Reading and Writing File Contents

Recall that sysfs_file_operations specifies the methods used by the VFS to access the content of files in sysfs. After having introduced all necessary data structures for reading and writing data, it is now time to discuss these operations.


Reading data is delegated to sysfs_read_file; the associated code flow diagram can be found in Figure 10-14.

Figure 10-14: Code flow diagram for sysfs_read_file.

Figure 10-14: Code flow diagram for sysfs_read_file.

The implementation is comparatively simple: If the data buffer is not yet filled in because it is accessed for the first time or has been modified by a write operation (both indicated by buffer->needs_read_fill), fill_read_buffer needs to be called to fill the buffer first. This function is responsible for two things:

1. Allocate a (zero-filled) page frame to hold the data.

2. Call the show method of the struct sysfs_ops instance to provide the buffer contents, that is, fill in data to the page frame allocated above.

Once the buffer is filled with data, the remaining work is delegated to simple_read_from_buffer. As you might have guessed from the name, the task is simple and requires only some bounds checking and a memory copy operation from kernel to userspace.


To allow the reverse process, namely, writing data from user to kernel space, sysfs_write_file is provided. Like for the read companion, the implementation is quite simple as the code flow diagram in Figure 10-15 shows.

First, fill_write_buffer allocates a page frame into which the data given from userspace are copied. This sets buffer->needs_refill because the content of the buffer needs to be refreshed if a read request takes place after the write. The remaining work is delegated to flush_write_buffer; its main job is to call the store method provided by the sysfs_ops instance specific to the file.

Figure 10-15: Code flow diagram for sysfs_write_file.

Figure 10-15: Code flow diagram for sysfs_write_file.

Continue reading here: Directory Traversal

Was this article helpful?

0 0