Re: when spin_lock_irq (as opposed to spin_lock_irqsave) is appropriate?

From: Arnd Bergmann
Date: Sun Oct 12 2008 - 18:21:55 EST


On Sunday 12 October 2008, Andrey Borzenkov wrote:
> This leaves me with a question - how can I know whether interrupts may
> (not) be disabled at particular point? In particular, is it safe to
> assume that any place marked at "code may sleep" has interrupts enabled?

Yes, that is safe. The only times you know that interrupts are disabled
are:

1. If you have disabled interrupts yourself using local_irq_{disable,save}
or spin_lock_irq{,save}.

2. If you get called from an interface that is documented to have interrupts
disabled. The only common example of this is the interrupt handler function
you register with request_irq().

In all other cases, interrupts are disabled, though in some places you may
not sleep, e.g. because of spin_lock(), preempt_disable() or softirq
context (timer, tasklet, ...). The question of whether you may sleep
or not is irrelevant to whether or not you can use spin_lock_irq.

The rules are:

* If you know that interrupts are disabled, use spin_lock().
* If you know that interrupts are enabled and you might race against
an interrupt handler, use spin_lock_irq().
* If you cannot race against a hard interrupt handler, but can race
against a softirq, use spin_lock_bh().
* If you cannot race against either hardirq or softirq context but cannot
sleep, use spin_lock().
* If you can sleep in all places that take the spinlock, replace the
spinlock with a mutex.
* If you cannot tell whether interrupts are enabled or disabled, but
you can race against a hardirq, use spin_lock_irqsave.

Some people interpret the last rule as "If I can't be bothered to find
out who is calling me, use spin_lock_irqsave", but I much prefer to
be explicit (besides efficient) to give the reader a better indication
of what the lock actually does.

Arnd <><
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/