In the linux kernel, why can't you sleep while holding a spinlock?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
- Null-terminated string, opening file for reading
Apart from what willtate has mentioned, assume that a process sleeps while holding a spilock. If the new process that is scheduled tries to acquire the same spinlock, it starts spinning for the lock to be available. Since the new process keeps spinning, it is not possible to schedule the first process and thus the lock is never released making the second process to spin for ever and we have a deadlock.
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
Another likely explanation is that, in a spinlock context pre-emption is disabled.
total agree with Nan Wang. I guess most important concept is "preemption" & "scheduling" and how happen when spinlock is acquired. when spinlock is acquired, preemption is disabled(true or not, I don't know, but assume it is correct), it means timer interrupt can't preempt current spinlock holder, but current spinlock hold still call sleepable kernel functions & actively invoke scheduler & run "another task". if "another task" happened to want to acquire the same spinlock as the first spinlock holder, here is problem come: since preemption is already disabled by first spinlock holder, "another task" which is invoked by actively call of scheduler by first spinlock holder, can't be preempted out, so its spinning always take the cpu, this is why deadlock happen.
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:
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.
http://www.kernel.org/pub/linux/kernel/people/rusty/kernel-locking/index.html
I think this mail has a clarity answer: