A new API for interrupt-aware spinlocks

Boqun Feng spoke at Kangrejos 2025 about adding a frequently needed API for Rust drivers that need to handle interrupts: interrupt-aware spinlocks. Most drivers will need to communicate information from interrupt handlers to main driver code, and this exchange is frequently synchronized with the use of spinlocks. While his first attempts ran into problems, Feng's ultimate solution could help prevent bugs in C code as well, by tracking the number of nested scopes that have disabled interrupts. The patch set, which contains work from Feng and Lyude Paul, is still under review.

冯博群在 2025 年的 Kangrejos 会议上介绍了一个 Rust 驱动程序经常需要的新 API:可感知中断的自旋锁(interrupt-aware spinlocks)。大多数驱动程序都需要在中断处理程序与主驱动代码之间交换信息,而这种交换通常需要通过自旋锁来同步。虽然他最初的尝试遇到了一些问题,但他最终的解决方案不仅能帮助 Rust 驱动,还能防止 C 代码中出现 bug——通过追踪禁用中断的嵌套层级数量。包含冯博群和 Lyude Paul 工作的补丁集目前仍在审查中。

Code that acquires a spinlock needs to disable preemption: otherwise, if it were preempted, everything else contending for the lock would just pointlessly burn CPU time. The same thing (almost) applies to using spinlocks in interrupts, Feng said. If kernel code acquires a spinlock in process context, and then an interrupt arrives, the handler for which tries to acquire the same lock, the system will deadlock. The simple rule in the kernel is that if a lock is ever used in both interrupt handler and process context, the lock must be "irq-safe" (meaning that the acquirer disables interrupts when appropriate). The kernel's lockdep tool will check that this rule is followed.

获取自旋锁的代码必须禁用抢占;否则,如果该代码在持锁期间被抢占,其他试图获得同一锁的线程将会白白浪费 CPU 时间。冯博群指出,在中断中使用自旋锁时几乎也是同样的道理。如果内核代码在进程上下文中获取了一个自旋锁,而此时发生中断且中断处理程序尝试获取同一个锁,那么系统将陷入死锁。内核中有一个简单的规则:如果某个锁既在中断上下文又在进程上下文中使用,那么该锁必须是“irq-safe”的,也就是说,在合适的时机禁用中断。内核的 lockdep 工具会检查此规则是否被遵守。

Every sufficiently complex driver will need an interrupt handler, Feng continued. In order to write drivers in Rust, kernel programmers will need an abstraction to deal with interrupts and irq-safe locks. The existing irq-safe spinlocks in C use either spin_lock_irq()/spin_unlock_irq() or spin_lock_irqsave()/spin_lock_irqrestore(), depending on whether the code is expected to run in an interrupt-enabled context or not. The former pair of functions leaves interrupts unconditionally enabled after the lock is released, while

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mounter625

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值