- GPIO Sysfs Interface for UserspaceВ¶
- The deprecated sysfs ABIВ¶
- Paths in SysfsВ¶
- Exporting from Kernel codeВ¶
- sysfs — _The_ filesystem for exporting kernel objectsВ¶
- What it is:В¶
- Using sysfsВ¶
- Directory CreationВ¶
- AttributesВ¶
- Subsystem-Specific CallbacksВ¶
- Reading/Writing Attribute DataВ¶
- Top Level Directory LayoutВ¶
- Current InterfacesВ¶
- Rules on how to access information in sysfsВ¶
GPIO Sysfs Interface for UserspaceВ¶
THIS ABI IS DEPRECATED, THE ABI DOCUMENTATION HAS BEEN MOVED TO Documentation/ABI/obsolete/sysfs-gpio AND NEW USERSPACE CONSUMERS ARE SUPPOSED TO USE THE CHARACTER DEVICE ABI. THIS OLD SYSFS ABI WILL NOT BE DEVELOPED (NO NEW FEATURES), IT WILL JUST BE MAINTAINED.
Refer to the examples in tools/gpio/* for an introduction to the new character device ABI. Also see the userspace header in include/uapi/linux/gpio.h
The deprecated sysfs ABIВ¶
Platforms which use the “gpiolib” implementors framework may choose to configure a sysfs user interface to GPIOs. This is different from the debugfs interface, since it provides control over GPIO direction and value instead of just showing a gpio state summary. Plus, it could be present on production systems without debugging support.
Given appropriate hardware documentation for the system, userspace could know for example that GPIO #23 controls the write protect line used to protect boot loader segments in flash memory. System upgrade procedures may need to temporarily remove that protection, first importing a GPIO, then changing its output state, then updating the code before re-enabling the write protection. In normal use, GPIO #23 would never be touched, and the kernel would have no need to know about it.
Again depending on appropriate hardware documentation, on some systems userspace GPIO can be used to determine system configuration data that standard kernels won’t know about. And for some tasks, simple userspace GPIO drivers could be all that the system really needs.
DO NOT ABUSE SYSFS TO CONTROL HARDWARE THAT HAS PROPER KERNEL DRIVERS. PLEASE READ THE DOCUMENT AT Subsystem drivers using GPIO TO AVOID REINVENTING KERNEL WHEELS IN USERSPACE. I MEAN IT. REALLY.
Paths in SysfsВ¶
There are three kinds of entries in /sys/class/gpio:
Control interfaces used to get userspace control over GPIOs;
GPIOs themselves; and
GPIO controllers (“gpio_chip” instances).
That’s in addition to standard files including the “device” symlink.
The control interfaces are write-only:
Userspace may ask the kernel to export control of a GPIO to userspace by writing its number to this file.
Example: “echo 19 > export” will create a “gpio19” node for GPIO #19, if that’s not requested by kernel code.
Reverses the effect of exporting to userspace.
Example: “echo 19 > unexport” will remove a “gpio19” node exported using the “export” file.
GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42) and have the following read/write attributes:
reads as either “in” or “out”. This value may normally be written. Writing as “out” defaults to initializing the value as low. To ensure glitch free operation, values “low” and “high” may be written to configure the GPIO as an output with that initial value.
Note that this attribute will not exist if the kernel doesn’t support changing the direction of a GPIO, or it was exported by kernel code that didn’t explicitly allow userspace to reconfigure this GPIO’s direction.
reads as either 0 (low) or 1 (high). If the GPIO is configured as an output, this value may be written; any nonzero value is treated as high.
If the pin can be configured as interrupt-generating interrupt and if it has been configured to generate interrupts (see the description of “edge”), you can poll(2) on that file and poll(2) will return whenever the interrupt was triggered. If you use poll(2), set the events POLLPRI and POLLERR. If you use select(2), set the file descriptor in exceptfds. After poll(2) returns, either lseek(2) to the beginning of the sysfs file and read the new value or close the file and re-open it to read the value.
reads as either “none”, “rising”, “falling”, or “both”. Write these strings to select the signal edge(s) that will make poll(2) on the “value” file return.
This file exists only if the pin can be configured as an interrupt generating input pin.
reads as either 0 (false) or 1 (true). Write any nonzero value to invert the value attribute both for reading and writing. Existing and subsequent poll(2) support configuration via the edge attribute for “rising” and “falling” edges will follow this setting.
GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the controller implementing GPIOs starting at #42) and have the following read-only attributes:
same as N, the first GPIO managed by this chip
provided for diagnostics (not always unique)
how many GPIOs this manages (N to N + ngpio — 1)
Board documentation should in most cases cover what GPIOs are used for what purposes. However, those numbers are not always stable; GPIOs on a daughtercard might be different depending on the base board being used, or other cards in the stack. In such cases, you may need to use the gpiochip nodes (possibly in conjunction with schematics) to determine the correct GPIO number to use for a given signal.
Exporting from Kernel codeВ¶
Kernel code can explicitly manage exports of GPIOs which have already been requested using gpio_request():
After a kernel driver requests a GPIO, it may only be made available in the sysfs interface by gpiod_export() . The driver can control whether the signal direction may change. This helps drivers prevent userspace code from accidentally clobbering important system state.
This explicit exporting can help with debugging (by making some kinds of experiments easier), or can provide an always-there interface that’s suitable for documenting as part of a board support package.
After the GPIO has been exported, gpiod_export_link() allows creating symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can use this to provide the interface under their own device in sysfs with a descriptive name.
© Copyright The kernel development community.
Источник
sysfs — _The_ filesystem for exporting kernel objectsВ¶
10 January 2003
What it is:В¶
sysfs is a ram-based filesystem initially based on ramfs. It provides a means to export kernel data structures, their attributes, and the linkages between them to userspace.
sysfs is tied inherently to the kobject infrastructure. Please read Everything you never wanted to know about kobjects, ksets, and ktypes for more information concerning the kobject interface.
Using sysfsВ¶
sysfs is always compiled in if CONFIG_SYSFS is defined. You can access it by doing:
Directory CreationВ¶
For every kobject that is registered with the system, a directory is created for it in sysfs. That directory is created as a subdirectory of the kobject’s parent, expressing internal object hierarchies to userspace. Top-level directories in sysfs represent the common ancestors of object hierarchies; i.e. the subsystems the objects belong to.
Sysfs internally stores a pointer to the kobject that implements a directory in the kernfs_node object associated with the directory. In the past this kobject pointer has been used by sysfs to do reference counting directly on the kobject whenever the file is opened or closed. With the current sysfs implementation the kobject reference count is only modified directly by the function sysfs_schedule_callback().
AttributesВ¶
Attributes can be exported for kobjects in the form of regular files in the filesystem. Sysfs forwards file I/O operations to methods defined for the attributes, providing a means to read and write kernel attributes.
Attributes should be ASCII text files, preferably with only one value per file. It is noted that it may not be efficient to contain only one value per file, so it is socially acceptable to express an array of values of the same type.
Mixing types, expressing multiple lines of data, and doing fancy formatting of data is heavily frowned upon. Doing these things may get you publicly humiliated and your code rewritten without notice.
An attribute definition is simply:
A bare attribute contains no means to read or write the value of the attribute. Subsystems are encouraged to define their own attribute structure and wrapper functions for adding and removing attributes for a specific object type.
For example, the driver model defines struct device_attribute like:
It also defines this helper for defining device attributes:
For example, declaring:
is equivalent to doing:
Note as stated in include/linux/kernel.h “OTHER_WRITABLE? Generally considered a bad idea.” so trying to set a sysfs file writable for everyone will fail reverting to RO mode for “Others”.
For the common cases sysfs.h provides convenience macros to make defining attributes easier as well as making code more concise and readable. The above case could be shortened to:
static struct device_attribute dev_attr_foo = __ATTR_RW(foo);
the list of helpers available to define your wrapper function is:
assumes default name_show and mode 0444
assumes a name_store only and is restricted to mode 0200 that is root write access only.
fore more restrictive RO access currently only use case is the EFI System Resource Table (see drivers/firmware/efi/esrt.c)
assumes default name_show, name_store and setting mode to 0644.
which sets the name to NULL and is used as end of list indicator (see: kernel/workqueue.c)
Subsystem-Specific CallbacksВ¶
When a subsystem defines a new attribute type, it must implement a set of sysfs operations for forwarding read and write calls to the show and store methods of the attribute owners:
[ Subsystems should have already defined a struct kobj_type as a descriptor for this type, which is where the sysfs_ops pointer is stored. See the kobject documentation for more information. ]
When a file is read or written, sysfs calls the appropriate method for the type. The method then translates the generic struct kobject and struct attribute pointers to the appropriate pointer types, and calls the associated methods.
Reading/Writing Attribute DataВ¶
To read or write attributes, show() or store() methods must be specified when declaring the attribute. The method types should be as simple as those defined for device attributes:
IOW, they should take only an object, an attribute, and a buffer as parameters.
sysfs allocates a buffer of size (PAGE_SIZE) and passes it to the method. Sysfs will call the method exactly once for each read or write. This forces the following behavior on the method implementations:
On read(2), the show() method should fill the entire buffer. Recall that an attribute should only be exporting one value, or an array of similar values, so this shouldn’t be that expensive.
This allows userspace to do partial reads and forward seeks arbitrarily over the entire file at will. If userspace seeks back to zero or does a pread(2) with an offset of вЂ0’ the show() method will be called again, rearmed, to fill the buffer.
On write(2), sysfs expects the entire buffer to be passed during the first write. Sysfs then passes the entire buffer to the store() method. A terminating null is added after the data on stores. This makes functions like sysfs_streq() safe to use.
When writing sysfs files, userspace processes should first read the entire file, modify the values it wishes to change, then write the entire buffer back.
Attribute method implementations should operate on an identical buffer when reading and writing values.
Writing causes the show() method to be rearmed regardless of current file position.
The buffer will always be PAGE_SIZE bytes in length. On i386, this is 4096.
show() methods should return the number of bytes printed into the buffer.
show() should only use sysfs_emit() or sysfs_emit_at() when formatting the value to be returned to user space.
store() should return the number of bytes used from the buffer. If the entire buffer has been used, just return the count argument.
show() or store() can always return errors. If a bad value comes through, be sure to return an error.
The object passed to the methods will be pinned in memory via sysfs referencing counting its embedded object. However, the physical entity (e.g. device) the object represents may not be present. Be sure to have a way to check this, if necessary.
A very simple (and naive) implementation of a device attribute is:
(Note that the real implementation doesn’t allow userspace to set the name for a device.)
Top Level Directory LayoutВ¶
The sysfs directory arrangement exposes the relationship of kernel data structures.
The top level sysfs directory looks like:
devices/ contains a filesystem representation of the device tree. It maps directly to the internal kernel device tree, which is a hierarchy of struct device .
bus/ contains flat directory layout of the various bus types in the kernel. Each bus’s directory contains two subdirectories:
devices/ contains symlinks for each device discovered in the system that point to the device’s directory under root/.
drivers/ contains a directory for each device driver that is loaded for devices on that particular bus (this assumes that drivers do not span multiple bus types).
fs/ contains a directory for some filesystems. Currently each filesystem wanting to export attributes must create its own hierarchy below fs/ (see ./fuse.txt for an example).
dev/ contains two directories char/ and block/. Inside these two directories there are symlinks named : . These symlinks point to the sysfs directory for the given device. /sys/dev provides a quick way to lookup the sysfs interface for a device from the result of a stat(2) operation.
More information can driver-model specific features can be found in Documentation/driver-api/driver-model/.
TODO: Finish this section.
Current InterfacesВ¶
The following interface layers currently exist in sysfs:
Источник
Rules on how to access information in sysfsВ¶
The kernel-exported sysfs exports internal kernel implementation details and depends on internal kernel structures and layout. It is agreed upon by the kernel developers that the Linux kernel does not provide a stable internal API. Therefore, there are aspects of the sysfs interface that may not be stable across kernel releases.
To minimize the risk of breaking users of sysfs, which are in most cases low-level userspace applications, with a new kernel release, the users of sysfs must follow some rules to use an as-abstract-as-possible way to access this filesystem. The current udev and HAL programs already implement this and users are encouraged to plug, if possible, into the abstractions these programs provide instead of accessing sysfs directly.
But if you really do want or need to access sysfs directly, please follow the following rules and then your programs should work with future versions of the sysfs interface.
- Do not use libsysfs
It makes assumptions about sysfs which are not true. Its API does not offer any abstraction, it exposes all the kernel driver-core implementation details in its own API. Therefore it is not better than reading directories and opening the files yourself. Also, it is not actively maintained, in the sense of reflecting the current kernel development. The goal of providing a stable interface to sysfs has failed; it causes more problems than it solves. It violates many of the rules in this document.
sysfs is always at /sys
Parsing /proc/mounts is a waste of time. Other mount points are a system configuration bug you should not try to solve. For test cases, possibly support a SYSFS_PATH environment variable to overwrite the application’s behavior, but never try to search for sysfs. Never try to mount it, if you are not an early boot script.
devices are only “devices”
There is no such thing like class-, bus-, physical devices, interfaces, and such that you can rely on in userspace. Everything is just simply a “device”. Class-, bus-, physical, . types are just kernel implementation details which should not be expected by applications that look for devices in sysfs.
The properties of a device are:
- devpath ( /devices/pci0000:00/0000:00:1d.1/usb2/2-2/2-2:1.0 )
- identical to the DEVPATH value in the event sent from the kernel at device creation and removal
- the unique key to the device at that point in time
- the kernel’s path to the device directory without the leading /sys , and always starting with a slash
- all elements of a devpath must be real directories. Symlinks pointing to /sys/devices must always be resolved to their real target and the target path must be used to access the device. That way the devpath to the device matches the devpath of the kernel used at event time.
- using or exposing symlink values as elements in a devpath string is a bug in the application
- kernel name ( sda , tty , 0000:00:1f.2 , . )
- a directory name, identical to the last element of the devpath
- applications need to handle spaces and characters like ! in the name
- subsystem ( block , tty , pci , . )
- simple string, never a path or a link
- retrieved by reading the “subsystem”-link and using only the last element of the target path
- driver ( tg3 , ata_piix , uhci_hcd )
- a simple string, which may contain spaces, never a path or a link
- it is retrieved by reading the “driver”-link and using only the last element of the target path
- devices which do not have “driver”-link just do not have a driver; copying the driver value in a child device context is a bug in the application
- attributes
- the files in the device directory or files below subdirectories of the same device directory
- accessing attributes reached by a symlink pointing to another device, like the “device”-link, is a bug in the application
Everything else is just a kernel driver-core implementation detail that should not be assumed to be stable across kernel releases.
Properties of parent devices never belong into a child device.
Always look at the parent devices themselves for determining device context properties. If the device eth0 or sda does not have a “driver”-link, then this device does not have a driver. Its value is empty. Never copy any property of the parent-device into a child-device. Parent device properties may change dynamically without any notice to the child device.
Hierarchy in a single device tree
There is only one valid place in sysfs where hierarchy can be examined and this is below: /sys/devices. It is planned that all device directories will end up in the tree below this directory.
Classification by subsystem
There are currently three places for classification of devices: /sys/block, /sys/class and /sys/bus. It is planned that these will not contain any device directories themselves, but only flat lists of symlinks pointing to the unified /sys/devices tree. All three places have completely different rules on how to access device information. It is planned to merge all three classification directories into one place at /sys/subsystem , following the layout of the bus directories. All buses and classes, including the converted block subsystem, will show up there. The devices belonging to a subsystem will create a symlink in the “devices” directory at /sys/subsystem/ /devices ,
If /sys/subsystem exists, /sys/bus , /sys/class and /sys/block can be ignored. If it does not exist, you always have to scan all three places, as the kernel is free to move a subsystem from one place to the other, as long as the devices are still reachable by the same subsystem name.
Assuming /sys/class/ and /sys/bus/ , or /sys/block and /sys/class/block are not interchangeable is a bug in the application.
The converted block subsystem at /sys/class/block or /sys/subsystem/block will contain the links for disks and partitions at the same level, never in a hierarchy. Assuming the block subsystem to contain only disks and not partition devices in the same flat list is a bug in the application.
“device”-link and : -links
Never depend on the “device”-link. The “device”-link is a workaround for the old layout, where class devices are not created in /sys/devices/ like the bus devices. If the link-resolving of a device directory does not end in /sys/devices/ , you can use the “device”-link to find the parent devices in /sys/devices/ , That is the single valid use of the “device”-link; it must never appear in any path as an element. Assuming the existence of the “device”-link for a device in /sys/devices/ is a bug in the application. Accessing /sys/class/net/eth0/device is a bug in the application.
Never depend on the class-specific links back to the /sys/class directory. These links are also a workaround for the design mistake that class devices are not created in /sys/devices. If a device directory does not contain directories for child devices, these links may be used to find the child devices in /sys/class. That is the single valid use of these links; they must never appear in any path as an element. Assuming the existence of these links for devices which are real child device directories in the /sys/devices tree is a bug in the application.
It is planned to remove all these links when all class device directories live in /sys/devices.
Position of devices along device chain can change.
Never depend on a specific parent device position in the devpath, or the chain of parent devices. The kernel is free to insert devices into the chain. You must always request the parent device you are looking for by its subsystem value. You need to walk up the chain until you find the device that matches the expected subsystem. Depending on a specific position of a parent device or exposing relative paths using ../ to access the chain of parents is a bug in the application.
When reading and writing sysfs device attribute files, avoid dependency
on specific error codes wherever possible. This minimizes coupling to the error handling implementation within the kernel.
In general, failures to read or write sysfs device attributes shall propagate errors wherever possible. Common errors include, but are not limited to:
-EIO : The read or store operation is not supported, typically returned by the sysfs system itself if the read or store pointer is NULL .
-ENXIO : The read or store operation failed
Error codes will not be changed without good reason, and should a change to error codes result in user-space breakage, it will be fixed, or the the offending change will be reverted.
Userspace applications can, however, expect the format and contents of the attribute files to remain consistent in the absence of a version attribute change in the context of a given attribute.
© Copyright The kernel development community.
Источник