What is atomic context and what can't you do in it?
Short answer: Code is in atomic context when it must not sleep or be scheduled out: hard IRQ handlers, softirqs and tasklets, sections holding a spinlock, and sections with pre-emption or interrupts disabled (also rcu_read_lock() sections on non-RT kernels). In atomic context you must not call anything that may sleep: mutex_lock, msleep, kmalloc(GFP_KERNEL), copy_to_user/copy_from_user, I2C/SPI transfers, wait_event, vmalloc, request_firmware, and most regulator/clk_prepare calls.
What to use instead
| Instead of | Use in atomic context |
|---|---|
kmalloc(GFP_KERNEL) |
kmalloc(GFP_ATOMIC) (may fail; preallocate where possible) |
msleep, usleep_range |
udelay/ndelay for a few microseconds, or defer |
mutex_lock |
spinlock |
| I2C/SPI transfer | defer to a threaded IRQ or workqueue |
copy_to_user |
copy to a kernel buffer, then copy out later in process context |
Why sleeping is forbidden: with a spinlock held or pre-emption disabled, sleeping would let another task run on this CPU that might spin on the same lock forever (deadlock); in interrupt context there is no task to put to sleep at all.
Detecting bugs: CONFIG_DEBUG_ATOMIC_SLEEP makes might_sleep() calls (present in all sleeping functions) print "BUG: sleeping function called from invalid context" with a backtrace. Lockdep also reports locking problems. Check with in_atomic(), in_interrupt(), in_task() only for debugging, not to change behaviour.