Skip to contentSkip to conversation

x86,panic,nmi: use trylock when taking the nmi_desc lock from NMI context

PATCH New Rik van Riel 1 participant 1 message Aug 7, 2024 x86

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 x86,panic,nmi: use trylock when taking the nmi_desc lock from NMI context

When nmi_panic runs on a system with kdump enabled, the kernel ends up trying to take a spinlock from NMI context. This should normally succeed, since NMI handler registration is rare, and panic has its own locking mechanism to make sure only one drives the kernel panic.

However, this spinlock will still make lockdep unhappy, and may result in the lockdep splat hiding the actual source of the underlying panic.

[ 39675.176729] WARNING: inconsistent lock state
[ 39675.176734] inconsistent {INITIAL USE} -> {IN-NMI} usage.
...
[ 39675.176817]        CPU0
[ 39675.176818]        ----
[ 39675.176818]   lock(&nmi_desc[0].lock);
[ 39675.176821]   <Interrupt>
[ 39675.176822]     lock(&nmi_desc[0].lock);
...
[ 39675.176866]  <NMI>
[ 39675.176868]  dump_stack_lvl+0x3d/0xf0
[ 39675.176874]  lock_acquire+0x1ac/0x290
[ 39675.176879]  ? __register_nmi_handler+0x4f/0x140
[ 39675.176889]  _raw_spin_lock_irqsave+0x5a/0x90
[ 39675.176896]  ? __register_nmi_handler+0x4f/0x140
[ 39675.176901]  __register_nmi_handler+0x4f/0x140
[ 39675.176905]  ? kdump_nmi_shootdown_cpus+0x20/0x20
[ 39675.176915]  nmi_shootdown_cpus+0x6a/0xe0
[ 39675.176922]  kdump_nmi_shootdown_cpus+0x11/0x20
[ 39675.176928]  native_machine_crash_shutdown+0x46/0xc0
[ 39675.176936]  __crash_kexec+0xe4/0x120
[ 39675.176948]  ? dump_stack_lvl+0x3d/0xf0
[ 39675.176951]  ? __crash_kexec+0xce/0x120
[ 39675.176957]  ? panic+0x134/0x380
[ 39675.176967]  ? nmi_panic+0x27/0x40

Since taking this lock from NMI context should just succeed anyway, use a trylock to make lockdep happy.

---
 arch/x86/kernel/nmi.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
arch/x86/kernel/nmi.c +11 -1
index ed163c8c8604..b7f759bb28ee 100644
@@ -171,7 +171,17 @@ int __register_nmi_handler(unsigned int type, struct nmiaction *action)
 	if (WARN_ON_ONCE(!action->handler || !list_empty(&action->list)))
 		return -EINVAL;
 
-	raw_spin_lock_irqsave(&desc->lock, flags);
+	if (in_nmi()) {
+		/*
+		 * We cannot take a spinlock from NMI code. This can happen
+		 * from nmi_panic. Only one CPU can panic, so the trylock
+		 * should normally succeed.
+		 */
+		if (!raw_spin_trylock_irqsave(&desc->lock, flags))
+			return 1;
+	} else {
+		raw_spin_lock_irqsave(&desc->lock, flags);
+	}
 
 	/*
 	 * Indicate if there are multiple registrations on the
Signature · 1 line
2.45.2