When is to preempt safe?

Dave Hylands dhylands at gmail.com
Sun Oct 9 02:53:46 EDT 2011


Hi Michi,

On Sat, Oct 8, 2011 at 11:29 PM, Michael Blizek
<michi1 at michaelblizek.twilightparadox.com> wrote:
> 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.

Disabling interrupts DOES NOT disable preemption on an SMP machine. It
only disables preemption on the core that interrupts are disabled on.

> 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.

People often associate real-time with "fast", when in fact real-time
really means "deterministic".

-- 
Dave Hylands
Shuswap, BC, Canada
http://www.davehylands.com



More information about the Kernelnewbies mailing list