Program A periodically (20 times/s) over-writes the first (and only) line of a sysfs file (F). Program B periodically (20 times/s) opens the same sysfs file (F), reads the first line and closes it.

Since F is a shared resource and in the above scenario that does not have any synchronization between the two programs, there should be a possibility that B reads an incompletely written line in the file.

Is this true of sysfs files also or does the kernel serialize its access?


The sysfs code was partially split in version 3.14 (2014) into a kernfs common part that would make it suitable for other subsystems to have a virtual filesystem, so we have to look at sysfs and kernfs.

Though there is no apparent serialization in the sysfs code, the kernfs layer above is using a mutex in kernfs_file_direct_read and kernfs_fop_write to ensure only a single read or write can happen at a time for the same file. There's also some locking when mmap() is used.

So your scenario should be safe.

  • There's some automatic locking around kernfs file operations. Doesn't this cover all sysfs operations? – Gilles 'SO- stop being evil' Aug 8 '16 at 23:17
  • @Gilles Good catch. Thanks. I rewrote my answer. – meuh Aug 9 '16 at 9:32
  • And before kernfs there was locking in the sysfs code. And that had been the case at least as far back as 2.6.12. I don't know if it was already the case in the first patches that introduced sysfs. – Gilles 'SO- stop being evil' Aug 9 '16 at 9:50
  • Can you confirm that the kernel sysfs locking is per sysfs file? If for example a driver exposes multiple sysfs files (say F1 and F2) which access the same kernel resource R, and at least one of those sysfs files writes to the resource, then there is still the possibility of a race on resource R if multiple threads or processes are using F1 and F2 at the same time. – satur9nine Apr 8 '19 at 19:34
  • @satur9nine Yes it is per sysfs file. A driver might also have further locks around resources that could change at any time. – meuh Apr 8 '19 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.