I heard that a mutex and spinlock can be acquired together to create a critical section as :-
mutex_lock--->spinlock-----critical section-----spinunlock--->mutex_unlock
Is this understanding correct? Where is this used in Kernel? Can anyone explain the real scenario in a device driver?
Also What happens if spinlock is acquired first and then the mutex?
spinlock--->mutex_lock -----critical section ....mutex_unlock---->spinunlock
Is this allowed? If not then how does the kernel behaves in such a case.
Both of these mechanisms are used for mutual exclusion (i.e. to protect "critical sections"). Hence you don't typically need to use both for the same critical section. However, the two mechanisms are commonly used in different situations.
A spinlock is used for very short term access to shared data. For example, if you need to add an item to a linked list that some other thread might also be adding to (or deleting from), you might use a spinlock to ensure that list pointers don't get corrupted.
Mutexes are typically used for longer-duration critical sections, especially if something you use might sleep (e.g. access user-space memory which might cause a page fault). Also a thread attempting to acquire a mutex might get put to sleep if some other thread already owns the lock. Since you must never do anything that might sleep while you hold a spinlock, you cannot acquire a mutex while holding a spinlock. (But note that a linux mutex actually contains a spinlock which it uses to synchronize access to the mutex data structure.)
OTOH, it's perfectly okay to acquire a spinlock while holding a mutex lock. (You might use this for example to ensure that even an interrupt handler running on another CPU cannot access a linked list while you're modifying it.)
See also this link for discussion about why preemption is disabled when you hold a spinlock and why often you also disable interrupts while you hold it. http://www.makelinux.net/ldd3/chp-5-sect-5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With