When is to preempt safe?

Michael Blizek michi1 at michaelblizek.twilightparadox.com
Sun Oct 9 02:29:36 EDT 2011


Hi!

On 00:24 Sun 09 Oct     , Parmenides wrote:
> 2011/10/8 Michael Blizek <michi1 at michaelblizek.twilightparadox.com>:
> > Hi!
> >
> > There are 2 different kind of locks: Those which can be preempted (mutex and
> > semaphores) and those which cannot (spinlocks). Spinlocks do busy waiting
> > until the lock is released. On single cpu systems, the are optimised into
> > enable/disable preemption. Spinlocks have to be used if the data it protects
> > is partly accessed in code paths which have preemption disables for other
> > reasons (e.g. being interrupt handler). This is because otherwise you have a
> > problem if you cannot preempt, but need to aquire a lock which is held by a
> > "thread" which has been preempted.
> >
> 
> Except for interrupt handler, is there any other code path which
> cannot be preempted but need to obtain a lock.

AFAIK not, but I am not really sure.

> If not, I think a
> thread holding a spinlock can disable interrupt when it is in critical
> section to resolve this problem, rather than disable preemption.

Disabling interrupts actually disables preemption as well. Preemption is
triggered by a timer interrupt, which cannot arrive in this case. Spinlocks
can be aquired both by disabling interrupts (spin_lock_irqsave) or by
disabling preemption (spin_lock_bh). However, you cannot use spin_lock_bh if
the same spin_lock is aquired in an interrupt handler. spin_lock_bh allows
interrupt handlers to be invoked while you are still in the critical section.
If the interrupt handler is processed on the same CPU as the critical section,
you are stuck in a deadlock.

There is a "real time" patchset which reduces spin_lock usage a lot. It
replaces many interrupt handlers with code that schedules the real interrupt
as a thread. They can then be interrupted and use a normal mutex for
synchronisation. However, this increases latency and overhead for interrupts.
It depends on the situation whether this is faster or slower.

	-Michi
-- 
programing a layer 3+4 network protocol for mesh networks
see http://michaelblizek.twilightparadox.com




More information about the Kernelnewbies mailing list