Listen to the sound of a race condition and understand the fix
Class files in sysfs
Mutexes in the kernel
Atomic types in the kernel
Triggering a race
Preventing the race
Use sysfs to expose a kernel interface
sysfs
Can be read-only, write-only, or read-write
More options exist beyond class files
->show() == read ->store() == write
class_create_file()
class_remove_file()
struct class_attribute
sysfs_emit()
offset_in_page()
kstrtou8()
*_from_user
kkey implements RW attributes for velocity and slowdown
kkey
velocity
slowdown
Initialization can be static or dynamic
Static: #define DEFINE_MUTEX()
#define DEFINE_MUTEX()
Dynamic: mutex_init()
mutex_init()
Destruction is a no-op on unless debugging:
Normal: mutex_destroy()
mutex_destroy()
Debug: mutex_destroy()
mutex_lock()
mutex_trylock()
mutex_lock_interruptible()
mutex_unlock()
Where are these locks forbidden?
Atomic context certain: spin_lock() and spin_unlock()
spin_lock()
spin_unlock()
Maybe atomic context: spin_lock_irqsave() and spin_unlock_irqrestore()
spin_lock_irqsave()
spin_unlock_irqrestore()
Initialize with atomic{,64}_t and ATOMIC_INIT()
atomic{,64}_t
ATOMIC_INIT()
Read with atomic_read() or atomic64_read()
atomic_read()
atomic64_read()
Set with atomic_set() or atomic64_set()
atomic_set()
atomic64_set()
Also: atomic_long_t and atomic_ptr_t
atomic_long_t
atomic_ptr_t
Two processes writing to kkey
Each note is pressed and released
Race condition: a release or press is missing
A press without release will linger
Ensure real multiprocessing
sysconf(3), _SC_NPROCESSORS_ONLN
sysconf(3)
_SC_NPROCESSORS_ONLN
CPU_SET, CPU_ZERO
sched_setaffinity(2)
D_GNU_SOURCE
Can you fix this race?
sysfs can provide a nice API to set/get values in the kernel
Race conditions in the kernel can be subtle and severe
Utilize the appropriate lock type for your use case
Never sleep or block in atomic context!