Exploring /sys for System Settings: A Comprehensive Guide
Introduction
The /sys filesystem, also known as sysfs, is a virtual filesystem in Linux that provides a unified interface for accessing and modifying kernel objects, hardware information, and system settings. Unlike traditional filesystems that store data on physical storage devices, sysfs exists only in memory and serves as a bridge between user space and kernel space.
The sysfs filesystem was introduced in Linux kernel 2.6 as a replacement for parts of the /proc filesystem, providing a more structured and organized approach to exposing kernel information. It follows the principle of "one value per file," making it easier to parse and understand system information programmatically.
Understanding the /sys Filesystem Structure
The /sys directory is organized in a hierarchical structure that reflects the kernel's internal organization of devices, drivers, and subsystems. The main directories under /sys include:
| Directory | Purpose | Description |
|-----------|---------|-------------|
| /sys/block | Block devices | Contains information about block devices like hard drives, SSDs |
| /sys/bus | Bus types | Information about different bus types (PCI, USB, I2C, etc.) |
| /sys/class | Device classes | Groups devices by functionality (network, input, graphics, etc.) |
| /sys/dev | Device nodes | Maps device numbers to sysfs paths |
| /sys/devices | Device hierarchy | Physical device hierarchy as seen by the kernel |
| /sys/firmware | Firmware interfaces | BIOS/UEFI and other firmware information |
| /sys/fs | Filesystem information | Filesystem-specific parameters and statistics |
| /sys/kernel | Kernel parameters | Runtime kernel configuration and debugging |
| /sys/module | Loaded modules | Information about loaded kernel modules |
| /sys/power | Power management | System power management settings |
Key Directories and Their Functions
/sys/class Directory
The /sys/class directory organizes devices by their functionality rather than their physical connection. This makes it easier to find devices that perform similar functions regardless of how they are connected to the system.
Common subdirectories include:
`bash
List device classes
ls /sys/class/`| Class | Description | Example Files |
|-------|-------------|---------------|
| net | Network interfaces | eth0, wlan0, lo |
| input | Input devices | mouse0, event0, js0 |
| block | Block devices | sda, nvme0n1, loop0 |
| graphics | Graphics devices | fb0, card0 |
| sound | Audio devices | card0, controlC0 |
| thermal | Thermal zones | thermal_zone0 |
| power_supply | Power supplies | BAT0, ADP1 |
/sys/devices Directory
This directory contains the actual device hierarchy as discovered by the kernel. It represents the physical topology of devices in the system.
`bash
Explore the device hierarchy
find /sys/devices -maxdepth 3 -type d | head -20`/sys/kernel Directory
Contains kernel-specific information and tunable parameters:
`bash
View kernel parameters
ls /sys/kernel/`Important subdirectories:
- debug/ - Kernel debugging interfaces
- mm/ - Memory management parameters
- security/ - Security module parameters
Essential Commands for Exploring /sys
Basic Navigation Commands
`bash
List contents of /sys
ls -la /sys/Navigate to a specific subsystem
cd /sys/class/net/View file contents
cat /sys/class/net/eth0/addressFind specific files
find /sys -name "temperature" 2>/dev/nullSearch for files containing specific text
grep -r "processor" /sys/devices/system/cpu/ 2>/dev/null | head -5`Information Gathering Commands
`bash
Display all network interfaces
ls /sys/class/net/Show MAC address of network interface
cat /sys/class/net/eth0/addressCheck network interface status
cat /sys/class/net/eth0/operstateView CPU information
ls /sys/devices/system/cpu/Check CPU frequency
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freqView memory information
cat /sys/devices/system/memory/block_size_bytes`Hardware Information Access
CPU Information
The CPU information in sysfs provides detailed data about processor characteristics:
`bash
List all CPU cores
ls /sys/devices/system/cpu/cpu*/Check CPU frequency scaling information
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequenciesView CPU topology
cat /sys/devices/system/cpu/cpu0/topology/core_id cat /sys/devices/system/cpu/cpu0/topology/physical_package_id`| File | Description | Example Value |
|------|-------------|---------------|
| scaling_cur_freq | Current CPU frequency | 2400000 (2.4 GHz) |
| scaling_max_freq | Maximum CPU frequency | 3200000 (3.2 GHz) |
| scaling_min_freq | Minimum CPU frequency | 800000 (800 MHz) |
| scaling_governor | Current frequency governor | performance, powersave |
Memory Information
`bash
View memory block information
ls /sys/devices/system/memory/Check memory block size
cat /sys/devices/system/memory/block_size_bytesView memory state
cat /sys/devices/system/memory/memory0/state`Storage Device Information
`bash
List block devices
ls /sys/class/block/View disk information
cat /sys/class/block/sda/size cat /sys/class/block/sda/queue/schedulerCheck disk statistics
cat /sys/class/block/sda/stat`Network Interface Management
Network Interface Information
`bash
List network interfaces
ls /sys/class/net/View interface details
cat /sys/class/net/eth0/address # MAC address cat /sys/class/net/eth0/mtu # Maximum Transmission Unit cat /sys/class/net/eth0/operstate # Operational state cat /sys/class/net/eth0/speed # Link speed cat /sys/class/net/eth0/duplex # Duplex mode`Network Statistics
`bash
View network statistics
cat /sys/class/net/eth0/statistics/rx_bytes cat /sys/class/net/eth0/statistics/tx_bytes cat /sys/class/net/eth0/statistics/rx_packets cat /sys/class/net/eth0/statistics/tx_packets`| Statistics File | Description |
|------------------|-------------|
| rx_bytes | Bytes received |
| tx_bytes | Bytes transmitted |
| rx_packets | Packets received |
| tx_packets | Packets transmitted |
| rx_errors | Receive errors |
| tx_errors | Transmit errors |
Power Management
Power Supply Information
`bash
List power supplies
ls /sys/class/power_supply/Battery information
cat /sys/class/power_supply/BAT0/capacity cat /sys/class/power_supply/BAT0/status cat /sys/class/power_supply/BAT0/energy_now cat /sys/class/power_supply/BAT0/energy_full`Thermal Management
`bash
List thermal zones
ls /sys/class/thermal/Check temperature
cat /sys/class/thermal/thermal_zone0/tempView thermal trip points
cat /sys/class/thermal/thermal_zone0/trip_point_0_temp cat /sys/class/thermal/thermal_zone0/trip_point_0_type`Module and Driver Information
Loaded Modules
`bash
List loaded modules
ls /sys/module/View module parameters
ls /sys/module/e1000e/parameters/Check module information
cat /sys/module/e1000e/version`Driver Information
`bash
List drivers by bus type
ls /sys/bus/pci/drivers/View driver binding
ls /sys/bus/pci/drivers/e1000e/`Modifying System Settings
Many files in /sys are writable and can be used to modify system behavior. However, changes made through sysfs are typically temporary and will be lost after a reboot unless made persistent through configuration files.
CPU Frequency Scaling
`bash
Change CPU governor (requires root)
echo "performance" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governorSet maximum frequency
echo "2400000" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq`Network Interface Settings
`bash
Change MTU (requires root)
echo "1500" > /sys/class/net/eth0/mtuEnable/disable network interface
echo "1" > /sys/class/net/eth0/carrier`Block Device Settings
`bash
Change I/O scheduler
echo "deadline" > /sys/class/block/sda/queue/schedulerModify read-ahead setting
echo "256" > /sys/class/block/sda/queue/read_ahead_kb`Practical Examples and Use Cases
System Monitoring Script
`bash
#!/bin/bash
System monitoring using /sys filesystem
echo "=== CPU Information ===" echo "Current frequency: $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq) Hz" echo "Governor: $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)"
echo -e "\n=== Memory Information ===" echo "Block size: $(cat /sys/devices/system/memory/block_size_bytes) bytes"
echo -e "\n=== Network Statistics ===" for interface in /sys/class/net/*/; do iface=$(basename "$interface") if [ "$iface" != "lo" ]; then echo "Interface: $iface" echo " RX bytes: $(cat "$interface/statistics/rx_bytes")" echo " TX bytes: $(cat "$interface/statistics/tx_bytes")" fi done
echo -e "\n=== Thermal Information ==="
for thermal in /sys/class/thermal/thermal_zone*/; do
zone=$(basename "$thermal")
temp=$(cat "$thermal/temp")
echo "$zone: $((temp/1000))°C"
done
`
Hardware Inventory Script
`bash
#!/bin/bash
Hardware inventory using /sys
echo "=== Block Devices ===" for device in /sys/class/block/sd*; do dev=$(basename "$device") size=$(cat "$device/size") size_gb=$((size * 512 / 1024 / 1024 / 1024)) echo "$dev: ${size_gb}GB" done
echo -e "\n=== Network Interfaces ===" for interface in /sys/class/net/*/; do iface=$(basename "$interface") if [ -f "$interface/address" ]; then mac=$(cat "$interface/address") echo "$iface: $mac" fi done
echo -e "\n=== USB Devices ==="
for device in /sys/bus/usb/devices/*/; do
if [ -f "$device/product" ]; then
product=$(cat "$device/product" 2>/dev/null)
vendor=$(cat "$device/manufacturer" 2>/dev/null)
echo "$vendor $product"
fi
done
`
Security Considerations
When working with /sys, several security considerations should be kept in mind:
File Permissions
Most files in /sys are readable by all users, but only root can modify system settings:
`bash
Check file permissions
ls -la /sys/class/net/eth0/mtu ls -la /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`Sensitive Information
Some files may contain sensitive information:
`bash
Network statistics might reveal usage patterns
cat /sys/class/net/eth0/statistics/rx_bytesHardware information could be used for fingerprinting
cat /sys/class/dmi/id/product_name cat /sys/class/dmi/id/board_serial`Write Operations
Be cautious when writing to sysfs files, as incorrect values can cause system instability:
`bash
Always verify current values before changing
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governorsMake changes gradually and test thoroughly
echo "conservative" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`Troubleshooting Common Issues
Permission Denied Errors
`bash
Error: Permission denied when writing
echo "performance" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governorSolution: Use sudo or switch to root
sudo bash -c 'echo "performance" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor'`File Not Found Errors
`bash
Check if file exists before accessing
if [ -f "/sys/class/net/eth0/speed" ]; then cat /sys/class/net/eth0/speed else echo "Speed information not available" fi`Invalid Values
`bash
Check available values before setting
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors cat /sys/class/block/sda/queue/scheduler`Advanced Usage Patterns
Monitoring System Changes
`bash
Monitor file changes using inotify
inotifywait -m /sys/class/net/eth0/operstateWatch for thermal events
inotifywait -m /sys/class/thermal/thermal_zone0/temp`Batch Operations
`bash
Apply settings to all CPU cores
for cpu in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo "performance" > "$cpu" doneCollect information from all network interfaces
for interface in /sys/class/net/*/statistics/rx_bytes; do iface=$(echo "$interface" | cut -d'/' -f5) bytes=$(cat "$interface") echo "$iface: $bytes bytes received" done`Integration with System Services
systemd Integration
`bash
Create systemd service to apply sysfs settings
cat > /etc/systemd/system/sysfs-settings.service << EOF [Unit] Description=Apply sysfs settings After=multi-user.target[Service] Type=oneshot ExecStart=/usr/local/bin/apply-sysfs-settings.sh RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF
`
Udev Rules
`bash
Create udev rule to automatically apply settings
cat > /etc/udev/rules.d/99-sysfs-settings.rules << EOFSet network interface MTU
SUBSYSTEM=="net", ACTION=="add", KERNEL=="eth0", RUN+="/bin/sh -c 'echo 9000 > /sys/class/net/eth0/mtu'"Set CPU governor on boot
SUBSYSTEM=="cpu", ACTION=="add", RUN+="/bin/sh -c 'echo performance > /sys/devices/system/cpu/%k/cpufreq/scaling_governor'" EOF`Best Practices
Error Handling
Always implement proper error handling when working with sysfs:
`bash
Function to safely read sysfs files
read_sysfs() { local file="$1" if [ -r "$file" ]; then cat "$file" 2>/dev/null || echo "Error reading $file" else echo "File $file not accessible" fi }Function to safely write sysfs files
write_sysfs() { local file="$1" local value="$2" if [ -w "$file" ]; then echo "$value" > "$file" 2>/dev/null || echo "Error writing to $file" else echo "File $file not writable" fi }`Documentation and Logging
`bash
Log changes for troubleshooting
log_sysfs_change() { local file="$1" local old_value="$2" local new_value="$3" echo "$(date): Changed $file from '$old_value' to '$new_value'" >> /var/log/sysfs-changes.log }`The /sys filesystem provides a powerful and flexible interface for system administration and monitoring. Understanding its structure and capabilities enables administrators to effectively manage system resources, monitor hardware status, and troubleshoot issues. Regular exploration of sysfs can reveal valuable insights into system behavior and provide opportunities for optimization and automation.