【问题标题】:Is it safe to call printk inside spin_lock_irqsave?在 spin_lock_irqsave 中调用 printk 是否安全?
【发布时间】:2014-12-22 23:43:04
【问题描述】:

我写过这样的代码:

它处于非中断上下文中:

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

我正在运行此代码并且“看起来”很安全,因为我没有看到任何崩溃。 但是,我不确定这是否真的是一个安全的代码。因为这可能会以 1/100000 的概率触发系统崩溃。

另外,我想知道在 spin_lock_irqsave 中调用“sleep”函数是否安全(在非中断上下文中)。

【问题讨论】:

  • 还有什么能获取lock吗?
  • 是的,可以。而且,我想在 spin_lock_irq 之间放置事件等待例程...

标签: linux kernel sleep irq printk


【解决方案1】:

内核代码在持有自旋锁时不应休眠。在Linux Device Drivers, Third Edition 中,第 5 章的“自旋锁和原子上下文”部分指出:

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).

至于printk,我相信在临界区调用是安全的。 source code 中的 cmets 甚至提到:

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

【讨论】:

  • 其实不是驱动代码。上下文是内核线程,而不是中断上下文。但是,出于某种原因,我想通过持有自旋锁来禁用中断。
  • 驱动程序和“普通”内核线程都遵循大致相同的规则,但我更新了答案以澄清。
猜你喜欢
  • 2011-08-19
  • 2020-12-07
  • 2013-01-01
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
相关资源
最近更新 更多