7
votes

I am reading Linux Kernel Development and get confused by the differences between mutex and semaphore.

The author says:

A mutex cannot be acquired by an interrupt handler or bottom half

I know a mutex may lead to sleep, and interrupt handler is not running in any specific process context so mutex or semaphore is not allowed. But bottom half can be implemented with work queues and it can sleep.

So, why a mutex can't be acquired in bottom half? Is simplicity and efficiency concerned here or something else?

2
Pray tell - what is the bottom half?Ed Heal

2 Answers

2
votes

The main motive for creating a mutex is simplicity and efficiency. As synchronization in bottom halves can be complicated, it is suggested that mutex be avoided in bottom halves. The design of bottom halves is not suitable for mutex. Eg. Mutex should be locked/unlocked in the same context - this would be hard to follow in case of bottom halves.

In theory you can decide to implement the whole interrupt handling different in which use of mutex in justified. Like the "threaded" interrupt handlers. http://lwn.net/Articles/380931/

4
votes

Mutex/semaphore locking can sleep, but BHs are designed not to sleep. Softirqs are asynchronously checked for execution in many places. For example they can execute every time you are restoring BH (like spin_unlock_bh). Causing such code to sleep on a mutex is a very bad idea. If you sleep while holding a BH spinlock you can cause other BH code to sleep and perhaps even deadlock the entire system.

From this point of view workqueues are not considered BH, they run in the context of kernel threads which are free to sleep. So a mutex is OK for workqueues but not for tasklets.

BH is a vague term, I find it helpful to think of the linux kernel as having three execution contexts: user (including kernel threads), softirq and hardirq. Preempting by each of these can be controlled with a set of bits in preempt_count.