Is it safe to call printk inside spin_lock_irqsave?

3.4k views Asked by At

I've written a code something like this:

It is in non-interrupt context:

spin_lock_irqsave(&lock, flags);
printk("some message blah...\n");
spin_unlock_irqrestore(&lock, flags);

I am running this code and "looks" safe because I don't see any crashes. But, I'm not sure this is really a safe code or not. Because that may trigger a system crash with 1/100000 probability.

Additionally, I would like to know if calling "sleep" function inside spin_lock_irqsave is safe (in not-interrupt context).

1

There are 1 answers

2
ctuffli On

Kernel code should not sleep while holding a spin lock. In Linux Device Drivers, Third Edition, the "Spinlocks and Atomic Context" section in Chapter 5 states:

Therefore, the core rule that applies to spinlocks is that any code must,
while holding a spinlock, be atomic. It cannot sleep; in fact, it cannot
relinquish the processor for any reason except to service interrupts (and
sometimes not even then).

As for printk, I believe it is safe to call within a critical section. The comments in the source code even mention:

This is printk(). It can be called from any context. We want it to work.