Kernel locking mechanism
Locking is a mechanism that helps shares resources between different threads or processes. A shared resource is data or a device that can be accessed by at least two users, simultaneously or not. Locking mechanisms prevent abusive access, for example, a process writing data when another one is reading in the same place, or two processes accessing the same device (the same GPIO, for example). The kernel provides several locking mechanisms. The most important are:
- Mutex
- Semaphore
- Spinlock
We will only learn about mutexes and spinlocks, since they are widely used in device drivers.
Mutex
Mutual exclusion (mutex) is the de facto, most-used locking mechanism. To understand how it works, let's see what its structure looks like in include/linux/mutex.h
:
struct mutex { /* 1: unlocked, 0: locked, negative: locked, possible waiters */ atomic_t count; spinlock_t wait_lock; struct list_head wait_list; [...] };
As we have seen in the wait queue section, there...