</>EmbeddedInterview

When should you use spin_lock_irqsave?

HardLinux Kernel & Device Drivers

Short answer: Use spin_lock_irqsave when the data protected by the lock is also accessed from a hard interrupt handler. If process-context code takes a plain spin_lock and the interrupt fires on the same CPU, the handler spins forever on a lock that its own CPU holds, and the CPU deadlocks. spin_lock_irqsave(&lock, flags) disables local interrupts and saves their previous state, so it is safe from any context.

/* process context (e.g. ioctl) */
unsigned long flags;
spin_lock_irqsave(&d->lock, flags);
d->config = new_config;
spin_unlock_irqrestore(&d->lock, flags);

/* hard IRQ handler on the same data */
static irqreturn_t mydev_irq(int irq, void *data)
{
    struct mydev *d = data;
    spin_lock(&d->lock);        /* interrupts are already disabled here: plain lock is enough */
    d->count++;
    spin_unlock(&d->lock);
    return IRQ_HANDLED;
}

Choosing the variant

Data shared with Process-context side uses
only other process context spin_lock (or a mutex if it may sleep)
softirq / tasklet / timer spin_lock_bh (disables bottom halves locally)
hard IRQ handler spin_lock_irqsave (or spin_lock_irq if interrupts are known to be enabled)
  • spin_lock_irq / spin_unlock_irq unconditionally re-enable interrupts, which is a bug if they were already disabled by the caller; irqsave/irqrestore restores the original state.
  • Interrupts are disabled only on the local CPU; another CPU can still run the handler and spin briefly on the lock, which is fine — that is what the spinlock is for.
  • Lockdep reports "inconsistent lock state" when a lock is taken both with and without IRQs disabled where an IRQ could interrupt the holder.
  • Keep these sections short: interrupt latency on that CPU grows while they are held.