linuxlinux-kernellinux-device-driversysfs

using sysfs show() and store() functions


I have 2 questions regarding using these functions. I don't completely understand the documentation written here:

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.

First, when I read/write to the sysfs attribute file with read/write, am I guaranteed that the buffer I read to / the buffer in the store function will have all of the bytes I wanted to read in that function, and not call it in several chunks?

Also, how is the null character added? That is, suppose I wrote n bytes, will the amount of written bytes be n in the function parameter, and the null char will be placed at n+1?

thanks


Solution

  • The answer to first questions yes - partial writes are not supported and the buffer is always filled in one call of show method.

    The answer to 2nd question is also yes. See implementation kernfs_fop_write() which is used by sysfs - it will allocate up to PAGE_SIZE+1 bytes so that there is enough space to fit \0.