Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you sleep while holding spinlock?

Tags:

linux

kernel

In the linux kernel, why can't you sleep while holding a spinlock?

like image 252
Bandicoot Avatar asked Jan 20 '11 20:01

Bandicoot


People also ask

Can a spinlock sleep?

Since spinlocks never sleep, they recover from contention as quickly as possible.

Why does the Linux kernel have a policy that a process Cannot hold a spinlock while attempting to acquire a semaphore?

This policy is in place because a spin lock cannot be hold while a semaphore is acquired. If this happens, it would take more than six to seven hours before semaphore is acquired and with spin lock in hold, one cannot do so. Linux is an operating system kernel, and it is like Unix; while semaphore is a variable.


2 Answers

Example: your driver is executing and has just taken out a lock that controls access to its device. While the lock is held, the device issues an interrupt, which causes your interrupt handler to run. The interrupt handler, before accessing the device, must also obtain the lock. Taking out a spinlock in an interrupt handler is a legitimate thing to do; that is one of the reasons that spinlock operations do not sleep. But what happens if the interrupt routine executes in the same processor as the code that took out the lock originally? While the interrupt handler is spinning, the noninterrupt code will not be able to run to release the lock. That processor will spin forever.

Source: http://www.makelinux.net/ldd3/chp-5-sect-5.shtml

like image 192
Will Tate Avatar answered Oct 02 '22 13:10

Will Tate


It's not that you can't sleep while holding a spin lock. It is a very very bad idea to do that. Quoting LDD:

Therefore, the core rule that applies to spinlocks is that any code must, while holding a spinlock, be atomic. It cannot sleep; in fact, it cannot relinquish the processor for any reason except to service interrupts (and sometimes not even then).

Any deadlock like mentioned above may result in an unrecoverable state. Another thing that could happen is that the spinlock gets locked on one CPU, and then when the thread sleeps, it wakes up on the other CPU, resulting in a kernel panic.

Answering Bandicoot's comment, in a spin lock context, pre-emption is disabled only in case of a uniprocessor pre-emptible kernel because disabling pre-emption effectively prevents races.

If the kernel is compiled without CONFIG_SMP, but CONFIG_PREEMPT is set, then spinlocks simply disable preemption, which is sufficient to prevent any races. For most purposes, we can think of preemption as equivalent to SMP, and not worry about it separately.

http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/index.html

like image 38
Omair Avatar answered Oct 02 '22 13:10

Omair