Skip to content
systemcoding.dev
Kernels

Why Kernel Code Must Never Sleep in an Interrupt Handler

Sleeping means the scheduler switches tasks, and an interrupt handler has no task to switch away from. See the reasons, the error message and the fixes.

6 min read
Summarize in AI
Flat illustration of a program timeline interrupted by an interrupt service routine, with the Linux, Rust and RISC-V logos.

Write msleep(10) inside an interrupt handler and the kernel does not politely wait. On a debug build it prints BUG: scheduling while atomic or sleeping function called from invalid context, and on a release build it may freeze with no message at all. Beginners often read the rule "no sleeping in interrupt handlers" as a style preference. It is a consequence of how scheduling works, and once you see the mechanism the list of forbidden calls becomes predictable. This post explains what sleeping is, why a handler cannot do it, and what to do instead, with Linux 6.12 as the reference.

What "sleep" means inside the kernel

When a process in the kernel needs to wait for something, such as a mutex, a disk read or a timer, it does not spin. It marks itself as not runnable, adds itself to a wait queue, and calls schedule(). The scheduler picks another task and switches to it. Later, when the event happens, someone wakes the first task, it becomes runnable, and the scheduler eventually runs it again right where it left off.

For that to work, there must be a task to put to sleep: a task_struct with its own kernel stack and saved registers that the scheduler can store and restore. Everything a blocking function does assumes it is running on behalf of such a task.

An interrupt handler has no task of its own

An interrupt handler runs on the stack of whatever was running when the interrupt arrived. It might be a user process, a kernel thread, or the idle loop. That task is current, and it is innocent: it did nothing to ask for the interrupt, and it is not in a state where the scheduler can safely park it.

If the handler called schedule(), the kernel would try to save the state of the interrupted task, but part of that state is a half-finished interrupt entry sequence, with the interrupted task's registers sitting on the stack, and interrupts masked in ways that are only unwound by returning through iret. Another task would then run with the interrupt not finished. The interrupted task would be put to sleep waiting for an event unrelated to its own work, and could wait forever. Worse, the stack the handler is using may be a dedicated per-CPU interrupt stack that has no task_struct attached to it, so there is nothing to switch away from.

So the kernel forbids it by tracking context. A counter in the thread info, preempt_count, records that this code is running in hard interrupt context (and in softirq context, and with preemption disabled). schedule() checks it:

c
/* kernel/sched/core.c, schedule_debug() */
if (unlikely(in_atomic_preempt_off())) {
	__schedule_bug(prev);
	preempt_count_set(PREEMPT_DISABLED);
}

__schedule_bug() prints the familiar message:

Text
BUG: scheduling while atomic: swapper/0/0/0x00010000

The three numbers are the task name, pid and the preempt_count value, where 0x00010000 shows the hard-interrupt bit set. The kernel then tries to continue, which is usually when things go wrong.

The second reason: locks

Even setting aside the scheduler, sleeping while holding a spinlock is a deadlock waiting to happen. A spinlock is held by a CPU that is not allowed to be preempted. If that CPU sleeps, another CPU may spin on the lock, waiting for a release that depends on the sleeping code being scheduled, and a single CPU system would spin forever because the only CPU is the one that must run the holder.

Interrupt handlers also often interrupt code that holds a lock. If the handler tried to take a mutex that the interrupted code holds, the handler would sleep waiting for the owner. But the owner is the very task the handler interrupted, and it cannot run until the handler returns. A deadlock follows with no other task involved at all.

Which calls can sleep

This is the practical list. A function may sleep if it can wait for memory, I/O, a lock or a timer. Common offenders:

CallWhy it sleeps
mutex_lock(), down()Waits if another task holds the lock
msleep(), usleep_range(), ssleep()Explicitly sleeps
kmalloc(..., GFP_KERNEL)May reclaim memory and wait for I/O
copy_to_user(), copy_from_user()May fault and wait for a page to be read in
wait_event(), wait_for_completion()Waits for a condition
i2c_transfer(), spi_sync()Waits for the bus transfer to complete
vmalloc(), vfree()May sleep during allocation
device_register() and most other registration callsAllocate and take mutexes

Functions that are safe in a handler are a shorter list: spin_lock() and spin_unlock(), readl() and writel(), kmalloc(..., GFP_ATOMIC), complete(), wake_up(), schedule_work(), tasklet_schedule(), atomic_inc() and friends, and the printk family.

Documentation for a kernel function that can sleep begins with a line such as "Context: Process context. May sleep." in its kernel-doc comment, and the function starts with might_sleep(). Read the doc comment before calling anything from a handler.

What happens when you try

Here is a handler that sleeps, as a beginner might write it:

badirq.cc
#include <linux/delay.h>
#include <linux/interrupt.h>

static irqreturn_t bad_handler(int irq, void *dev_id)
{
	msleep(10);	/* wait for the device to settle: WRONG here */
	return IRQ_HANDLED;
}

On a kernel built with CONFIG_DEBUG_ATOMIC_SLEEP=y, the first interrupt prints:

Text
BUG: sleeping function called from invalid context at kernel/time/sleep_timeout.c:103
in_atomic(): 1, irqs_disabled(): 1, non_block: 0, pid: 0, name: swapper/0
preempt_count: 10000, expected: 0
CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 6.12.0 #1
Call Trace:
 <IRQ>
 dump_stack_lvl+0x5d/0x80
 __might_resched+0x14b/0x1d0
 msleep+0x1c/0x40
 bad_handler+0x9/0x20 [badirq]
 __handle_irq_event_percpu+0x4a/0x1c0
 handle_irq_event+0x34/0x80
 ...

Read it from the top. The message names the context violation. in_atomic(): 1 and irqs_disabled(): 1 say the code is in atomic context with interrupts off. The call trace has <IRQ> marking the interrupt stack, and shows msleep called from bad_handler. Line numbers and addresses vary. On a kernel without the debug option, the check is missing, and the call to schedule() happens with the consequences described above.

The fix: defer the sleeping work

Never wait in the handler. Do what must be done at interrupt time, which is little, and push the rest to a context that can sleep. Three standard tools:

  1. A workqueue. The handler calls schedule_work(). A kernel thread later runs your function in process context, where msleep(), mutex_lock() and I2C transfers are allowed.

  2. A threaded interrupt handler. Register with request_threaded_irq(). The first function runs at interrupt time and returns IRQ_WAKE_THREAD, and the second runs in a dedicated kernel thread.

  3. A timer, for "wait 10 ms". If the real need is a delay, arm a timer with mod_timer() for 10 ms and finish the work in its callback, which also may not sleep, or queue delayed work with queue_delayed_work(), which can.

The corrected version of the handler above, using a workqueue:

goodirq.cc
static void settle_work(struct work_struct *w)
{
	msleep(10);	/* fine here: process context */
	/* read the device, finish processing */
}

static DECLARE_WORK(settle, settle_work);

static irqreturn_t good_handler(int irq, void *dev_id)
{
	schedule_work(&settle);
	return IRQ_HANDLED;
}

If the delay is very short, under about ten microseconds, udelay() is allowed in a handler since it busy-waits instead of sleeping. It keeps interrupts handled on that CPU waiting, so use it for hardware settle times and nothing longer.

A rule of thumb

If you are not sure whether a function can sleep, assume it can. Look for might_sleep() in its source, or the "Context" line in its documentation, and test on a kernel with CONFIG_DEBUG_ATOMIC_SLEEP and CONFIG_PROVE_LOCKING. The same rule covers code holding a spinlock and code in a softirq or tasklet, and not only hard interrupt handlers. Everywhere the kernel cannot reschedule, you cannot sleep.

Also inHardware
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.