1. What is sysfs?
sysfs is a virtual filesystem specially designed by the Linux kernel for the device model. It exposes objects in the kernel such as devices, buses, and drivers as files and directories in user space, usually mounted under the /sys directory.
Key understanding:
- sysfs does not store data but real-time reflects the structure and state of the kernel device model.
- sysfs = "Organize kernel devices and expose them to user space through a tree file structure!"
2. Role of sysfs
- Visibility: You can very intuitively see the relationships between kernel objects such as devices, drivers, and buses.
- Debuggability: Many driver and kernel parameters can be viewed or adjusted in real-time through sysfs (such as power management, driver parameters, etc.).
- Unified interface: Device/driver developers do not need to implement their own parameter debugging interfaces; they can directly read and write through sysfs files.
3. Relationship between sysfs and Device Model
- sysfs is automatically generated and maintained by the device model (when registering bus, device, driver and other objects, the kernel automatically creates corresponding files and directories under sysfs).
- User space can complete many operations of viewing, debugging, and controlling hardware through sysfs — for example:
- View all i2c devices and corresponding drivers
- Check attributes exposed under a certain device (such as power status, device information, etc.)
4. Basic Directory Structure of sysfs
/sys/bus/: All buses (bus), such as platform, pci, usb.
/sys/class/: Devices classified by function, such as net, block, input, tty, etc.
/sys/devices/: The tree structure of physical devices, reflecting the "topology" relationship of devices./sys/modules/: Loaded kernel modules.
/sys/kernel/: Kernel's own parameters and information.
5. Some sysfs Operation Examples
View from command line:
bash
ls /sys/class/net # View all network devices
ls /sys/bus/usb/devices # View all USB devices
cat /sys/class/net/end0/address # View the physical address of end0 network card1
2
3
2
3
Some attributes support writing configuration, for example controlling LED on/off on the board:
bash
# Turn off the light
echo 0 | sudo tee /sys/class/leds/work/brightness
# Turn on the light
echo 1 | sudo tee /sys/class/leds/work/brightness1
2
3
4
5
2
3
4
5
6. Summary
- sysfs is an important mechanism through which the Linux kernel device model exposes data and interfaces to user space
- Through sysfs, you can intuitively, uniformly, and dynamically observe and debug hardware devices