Skip to contentSkip to conversation

Refcounted interrupt disable and SpinLockIrq for rust (Part 1)

PATCH Superseded Boqun Feng 3 participants 28 messages Jun 5

Subsystems (13)
x86 Kselftest Library code BPF +9 more subsystems

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Boqun Feng

author maintainer
#0 lore raw

v3 cover Refcounted interrupt disable and SpinLockIrq for rust (Part 1)

Hi Peter,

Please take a look at the v3 of refcounted interrupt disabling.

Changes since v2:

- Fix NMI_OFFSET underflow issue reported by sashiko. See patch #1 (__nmi_ext()) and #10 (__preempt_count_nmi_exit()) for details: we have to replace preempt_count_sub() with preempt_count_set().
- Add WARN_ON_ONCE(in_nmi()) in local_interrupt_disable() per Peter.
- Remove the use of should_resched() in local_interrupt_enable(), see patch #13.
- Remove my gmail in SoB.

v1: https://lore.kernel.org/rust-for-linux/[email protected]/
v2:

Boqun Feng (9):
preempt: Introduce HARDIRQ_DISABLE_BITS
preempt: Introduce __preempt_count_{sub, add}_return()
irq & spin_lock: Add counted interrupt disabling/enabling
locking: Switch to _irq_{disable,enable}() variants in cleanup guards
sched: Remove the unused preempt_offset parameter of __cant_sleep()
sched: Avoid signed comparison of preempt_count() in __cant_migrate()
preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS
arm64: sched/preempt: Enable HAS_SEPARATE_PREEMPT_RESCHED_BITS
irq: Optimize reschedule check in local_interrupt_enable()

Heiko Carstens (1):
s390/preempt: Enable HAS_SEPARATE_PREEMPT_RESCHED_BITS

Joel Fernandes (1):
preempt: Track NMI nesting to separate per-CPU counter

Lyude Paul (2):
openrisc: Include <linux/cpumask.h> in smp.h
irq: Add KUnit test for refcounted interrupt enable/disable

 arch/arm64/Kconfig                            |   1 +
 arch/arm64/include/asm/preempt.h              |  18 +++
 arch/openrisc/include/asm/smp.h               |   2 +
 arch/s390/Kconfig                             |   1 +
 arch/s390/include/asm/lowcore.h               |  13 ++-
 arch/s390/include/asm/preempt.h               |  49 ++++----
 arch/x86/Kconfig                              |   1 +
 arch/x86/include/asm/preempt.h                |  61 +++++++---
 arch/x86/kernel/cpu/common.c                  |   2 +-
 include/asm-generic/preempt.h                 |  14 +++
 include/linux/hardirq.h                       |  41 ++++++-
 include/linux/interrupt_rc.h                  |  76 ++++++++++++
 include/linux/kernel.h                        |   4 +-
 include/linux/preempt.h                       |  35 ++++--
 include/linux/spinlock.h                      |  49 +++++---
 include/linux/spinlock_api_smp.h              |  41 +++++++
 include/linux/spinlock_api_up.h               |  16 +++
 include/linux/spinlock_rt.h                   |  18 +++
 kernel/Kconfig.preempt                        |   4 +
 kernel/irq/Makefile                           |   1 +
 kernel/irq/refcount_interrupt_test.c          | 109 ++++++++++++++++++
 kernel/locking/spinlock.c                     |  29 +++++
 kernel/sched/core.c                           |  18 ++-
 kernel/softirq.c                              |  22 +++-
 lib/locking-selftest.c                        |   2 +-
 .../testing/selftests/bpf/bpf_experimental.h  |   7 +-
 26 files changed, 554 insertions(+), 80 deletions(-)
 create mode 100644 include/linux/interrupt_rc.h
 create mode 100644 kernel/irq/refcount_interrupt_test.c
Signature · 1 line
2.51.0
author maintainer
#1 lore raw

PATCH v3 1/13 preempt: Track NMI nesting to separate per-CPU counter

From: Joel Fernandes <[email protected]>

Move NMI nesting tracking from the preempt_count bits to a separate per-CPU counter (nmi_nesting). This is to free up the NMI bits in the preempt_count, allowing those bits to be repurposed for other uses.

Reduce NMI_BITS from 4 to 1, using it only to detect if we're in an NMI. The per-CPU counter currently caps nesting at 15.

[boqun: Solve Steven Rostedt's comment on the BUG_ON() condition] [boqun: Use preempt_count_set() in __nmi_exit() to avoid underflow]

---
 include/linux/hardirq.h                        | 17 +++++++++++++----
 include/linux/preempt.h                        |  9 +++++++--
 kernel/softirq.c                               |  2 ++
 tools/testing/selftests/bpf/bpf_experimental.h |  2 +-
 4 files changed, 23 insertions(+), 7 deletions(-)
include/linux/hardirq.h +13 -4
index d57cab4d4c06..8d4895531a45 100644
@@ -10,6 +10,8 @@
 #include <linux/vtime.h>
 #include <asm/hardirq.h>
 
+DECLARE_PER_CPU(unsigned int, nmi_nesting);
+
 extern void synchronize_irq(unsigned int irq);
 extern bool synchronize_hardirq(unsigned int irq);
 
@@ -102,14 +104,17 @@ void irq_exit_rcu(void);
  */
 
 /*
- * nmi_enter() can nest up to 15 times; see NMI_BITS.
+ * nmi_enter() can nest - nesting is tracked in a per-CPU counter.
  */
 #define __nmi_enter()						\
 	do {							\
 		lockdep_off();					\
 		arch_nmi_enter();				\
-		BUG_ON(in_nmi() == NMI_MASK);			\
-		__preempt_count_add(NMI_OFFSET + HARDIRQ_OFFSET);	\
+		/* Maximum NMI nesting is 15. */		\
+		BUG_ON(__this_cpu_read(nmi_nesting) >= 15);	\
+		__this_cpu_inc(nmi_nesting);			\
+		__preempt_count_add(HARDIRQ_OFFSET);		\
+		preempt_count_set(preempt_count() | NMI_MASK);	\
 	} while (0)
 
 #define nmi_enter()						\
@@ -124,8 +129,12 @@ void irq_exit_rcu(void);
 
 #define __nmi_exit()						\
 	do {							\
+		unsigned int nesting;				\
 		BUG_ON(!in_nmi());				\
-		__preempt_count_sub(NMI_OFFSET + HARDIRQ_OFFSET);	\
+		__preempt_count_sub(HARDIRQ_OFFSET);		\
+		nesting = __this_cpu_dec_return(nmi_nesting);	\
+		if (!nesting)					\
+			preempt_count_set(preempt_count() & ~NMI_MASK);	\
 		arch_nmi_exit();				\
 		lockdep_on();					\
 	} while (0)
include/linux/preempt.h +7 -2
index d964f965c8ff..586f96688325 100644
@@ -17,6 +17,8 @@
  *
  * - bits 0-7 are the preemption count (max preemption depth: 256)
  * - bits 8-15 are the softirq count (max # of softirqs: 256)
+ * - bits 16-19 are the hardirq count (max # of hardirqs: 16)
+ * - bit 20 is the NMI flag (no nesting count, tracked separately)
  *
  * The hardirq count could in theory be the same as the number of
  * interrupts in the system, but we run all interrupt handlers with
@@ -24,16 +26,19 @@
  * there are a few palaeontologic drivers which reenable interrupts in
  * the handler, so we need more than one bit here.
  *
+ * NMI nesting depth is tracked in a separate per-CPU variable
+ * (nmi_nesting) to save bits in preempt_count.
+ *
  *         PREEMPT_MASK:	0x000000ff
  *         SOFTIRQ_MASK:	0x0000ff00
  *         HARDIRQ_MASK:	0x000f0000
- *             NMI_MASK:	0x00f00000
+ *             NMI_MASK:	0x00100000
  * PREEMPT_NEED_RESCHED:	0x80000000
  */
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
 #define HARDIRQ_BITS	4
-#define NMI_BITS	4
+#define NMI_BITS	1
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
kernel/softirq.c +2 -0
index 4425d8dce44b..10af5ed859e7 100644
@@ -88,6 +88,8 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled);
 EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context);
 #endif
 
+DEFINE_PER_CPU(unsigned int, nmi_nesting);
+
 /*
  * SOFTIRQ_OFFSET usage:
  *
tools/testing/selftests/bpf/bpf_experimental.h +1 -1
index 2234bd6bc9d3..2d4256ff471f 100644
@@ -449,7 +449,7 @@ extern int bpf_cgroup_read_xattr(struct cgroup *cgroup, const char *name__str,
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
 #define HARDIRQ_BITS	4
-#define NMI_BITS	4
+#define NMI_BITS	1
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
Signature · 1 line
2.51.0
author maintainer
#3 lore raw

PATCH v3 2/13 preempt: Introduce HARDIRQ_DISABLE_BITS

In reply to Boqun Feng

From: Boqun Feng <[email protected]>

In order to support preempt_disable()-like interrupt disabling, that is, using part of preempt_count() to track interrupt disabling nested level, change the preempt_count() layout to contain 8-bit HARDIRQ_DISABLE count.

---
 include/linux/preempt.h                        | 16 +++++++++++-----
 tools/testing/selftests/bpf/bpf_experimental.h |  5 ++++-
 2 files changed, 15 insertions(+), 6 deletions(-)
include/linux/preempt.h +11 -5
index 586f96688325..e2d3079d3f5f 100644
@@ -17,8 +17,9 @@
  *
  * - bits 0-7 are the preemption count (max preemption depth: 256)
  * - bits 8-15 are the softirq count (max # of softirqs: 256)
- * - bits 16-19 are the hardirq count (max # of hardirqs: 16)
- * - bit 20 is the NMI flag (no nesting count, tracked separately)
+ * - bits 16-23 are the hardirq disable count (max # of hardirq disable: 256)
+ * - bits 24-27 are the hardirq count (max # of hardirqs: 16)
+ * - bit 28 is the NMI flag (no nesting count, tracked separately)
  *
  * The hardirq count could in theory be the same as the number of
  * interrupts in the system, but we run all interrupt handlers with
@@ -31,29 +32,34 @@
  *
  *         PREEMPT_MASK:	0x000000ff
  *         SOFTIRQ_MASK:	0x0000ff00
- *         HARDIRQ_MASK:	0x000f0000
- *             NMI_MASK:	0x00100000
+ * HARDIRQ_DISABLE_MASK:	0x00ff0000
+ *         HARDIRQ_MASK:	0x0f000000
+ *             NMI_MASK:	0x10000000
  * PREEMPT_NEED_RESCHED:	0x80000000
  */
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
+#define HARDIRQ_DISABLE_BITS	8
 #define HARDIRQ_BITS	4
 #define NMI_BITS	1
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
-#define HARDIRQ_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_DISABLE_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_SHIFT	(HARDIRQ_DISABLE_SHIFT + HARDIRQ_DISABLE_BITS)
 #define NMI_SHIFT	(HARDIRQ_SHIFT + HARDIRQ_BITS)
 
 #define __IRQ_MASK(x)	((1UL << (x))-1)
 
 #define PREEMPT_MASK	(__IRQ_MASK(PREEMPT_BITS) << PREEMPT_SHIFT)
 #define SOFTIRQ_MASK	(__IRQ_MASK(SOFTIRQ_BITS) << SOFTIRQ_SHIFT)
+#define HARDIRQ_DISABLE_MASK	(__IRQ_MASK(HARDIRQ_DISABLE_BITS) << HARDIRQ_DISABLE_SHIFT)
 #define HARDIRQ_MASK	(__IRQ_MASK(HARDIRQ_BITS) << HARDIRQ_SHIFT)
 #define NMI_MASK	(__IRQ_MASK(NMI_BITS)     << NMI_SHIFT)
 
 #define PREEMPT_OFFSET	(1UL << PREEMPT_SHIFT)
 #define SOFTIRQ_OFFSET	(1UL << SOFTIRQ_SHIFT)
+#define HARDIRQ_DISABLE_OFFSET	(1UL << HARDIRQ_DISABLE_SHIFT)
 #define HARDIRQ_OFFSET	(1UL << HARDIRQ_SHIFT)
 #define NMI_OFFSET	(1UL << NMI_SHIFT)
 
tools/testing/selftests/bpf/bpf_experimental.h +4 -1
index 2d4256ff471f..a811b080db02 100644
@@ -448,17 +448,20 @@ extern int bpf_cgroup_read_xattr(struct cgroup *cgroup, const char *name__str,
 
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
+#define HARDIRQ_DISABLE_BITS	8
 #define HARDIRQ_BITS	4
 #define NMI_BITS	1
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
-#define HARDIRQ_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_DISABLE_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_SHIFT	(HARDIRQ_DISABLE_SHIFT + HARDIRQ_DISABLE_BITS)
 #define NMI_SHIFT	(HARDIRQ_SHIFT + HARDIRQ_BITS)
 
 #define __IRQ_MASK(x)	((1UL << (x))-1)
 
 #define SOFTIRQ_MASK	(__IRQ_MASK(SOFTIRQ_BITS) << SOFTIRQ_SHIFT)
+#define HARDIRQ_DISABLE_MASK	(__IRQ_MASK(HARDIRQ_DISABLE_BITS) << HARDIRQ_DISABLE_SHIFT)
 #define HARDIRQ_MASK	(__IRQ_MASK(HARDIRQ_BITS) << HARDIRQ_SHIFT)
 #define NMI_MASK	(__IRQ_MASK(NMI_BITS)     << NMI_SHIFT)
 
Signature · 1 line
2.51.0
author maintainer
#5 lore raw

PATCH v3 3/13 preempt: Introduce __preempt_count_{sub, add}_return()

In reply to Boqun Feng

From: Boqun Feng <[email protected]>

In order to use preempt_count() to tracking the interrupt disable nesting level, __preempt_count_{add,sub}_return() are introduced, as their name suggest, these primitives return the new value of the preempt_count() after changing it. The following example shows the usage of it in local_interrupt_disable():

	// increase the HARDIRQ_DISABLE bit
	new_count = __preempt_count_add_return(HARDIRQ_DISABLE_OFFSET);

	// if it's the first-time increment, then disable the interrupt
	// at hardware level.
	if (new_count & HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET) {
		local_irq_save(flags);
		raw_cpu_write(local_interrupt_disable_state.flags, flags);
	}

Having these primitives will avoid a read of preempt_count() after changing preempt_count() on certain architectures.

---
 arch/arm64/include/asm/preempt.h | 18 ++++++++++++++++++
 arch/s390/include/asm/preempt.h  | 10 ++++++++++
 arch/x86/include/asm/preempt.h   | 10 ++++++++++
 include/asm-generic/preempt.h    | 14 ++++++++++++++
 4 files changed, 52 insertions(+)
arch/arm64/include/asm/preempt.h +18 -0
index 932ea4b62042..0dd8221d1bef 100644
@@ -55,6 +55,24 @@ static inline void __preempt_count_sub(int val)
 	WRITE_ONCE(current_thread_info()->preempt.count, pc);
 }
 
+static inline int __preempt_count_add_return(int val)
+{
+	u32 pc = READ_ONCE(current_thread_info()->preempt.count);
+	pc += val;
+	WRITE_ONCE(current_thread_info()->preempt.count, pc);
+
+	return pc;
+}
+
+static inline int __preempt_count_sub_return(int val)
+{
+	u32 pc = READ_ONCE(current_thread_info()->preempt.count);
+	pc -= val;
+	WRITE_ONCE(current_thread_info()->preempt.count, pc);
+
+	return pc;
+}
+
 static inline bool __preempt_count_dec_and_test(void)
 {
 	struct thread_info *ti = current_thread_info();
arch/s390/include/asm/preempt.h +10 -0
index 6e5821bb047e..0a25d4648b4c 100644
@@ -139,6 +139,16 @@ static __always_inline bool should_resched(int preempt_offset)
 	return unlikely(READ_ONCE(get_lowcore()->preempt_count) == preempt_offset);
 }
 
+static __always_inline int __preempt_count_add_return(int val)
+{
+	return val + __atomic_add(val, &get_lowcore()->preempt_count);
+}
+
+static __always_inline int __preempt_count_sub_return(int val)
+{
+	return __preempt_count_add_return(-val);
+}
+
 #define init_task_preempt_count(p)	do { } while (0)
 /* Deferred to CPU bringup time */
 #define init_idle_preempt_count(p, cpu)	do { } while (0)
arch/x86/include/asm/preempt.h +10 -0
index 578441db09f0..1220656f3370 100644
@@ -85,6 +85,16 @@ static __always_inline void __preempt_count_sub(int val)
 	raw_cpu_add_4(__preempt_count, -val);
 }
 
+static __always_inline int __preempt_count_add_return(int val)
+{
+	return raw_cpu_add_return_4(__preempt_count, val);
+}
+
+static __always_inline int __preempt_count_sub_return(int val)
+{
+	return raw_cpu_add_return_4(__preempt_count, -val);
+}
+
 /*
  * Because we keep PREEMPT_NEED_RESCHED set when we do _not_ need to reschedule
  * a decrement which hits zero means we have no preempt_count and should
include/asm-generic/preempt.h +14 -0
index 51f8f3881523..c8683c046615 100644
@@ -59,6 +59,20 @@ static __always_inline void __preempt_count_sub(int val)
 	*preempt_count_ptr() -= val;
 }
 
+static __always_inline int __preempt_count_add_return(int val)
+{
+	*preempt_count_ptr() += val;
+
+	return *preempt_count_ptr();
+}
+
+static __always_inline int __preempt_count_sub_return(int val)
+{
+	*preempt_count_ptr() -= val;
+
+	return *preempt_count_ptr();
+}
+
 static __always_inline bool __preempt_count_dec_and_test(void)
 {
 	/*
Signature · 1 line
2.51.0
author maintainer
#9 lore raw

PATCH v3 4/13 openrisc: Include <linux/cpumask.h> in smp.h

In reply to Boqun Feng

From: Lyude Paul <[email protected]>

While OpenRISC currently doesn't fail to build upstream, it appears that include <asm/smp.h> in the right headers is enough to break that - primarily because OpenRISC's asm/smp.h header doesn't actually provide any definition for struct cpumask. Which means the only reason we aren't failing to build kernel is because we've been lucky enough that every spot including asm/smp.h already has definitions for struct cpumask pulled in.

This became evident when trying to work on a patch series for adding ref-counted interrupt enable/disables to the kernel, where introducing a new interrupt_rc.h header suddenly introduced a build error on OpenRISC:

In file included from include/linux/interrupt_rc.h:17,
from include/linux/spinlock.h:60,
from include/linux/mmzone.h:8,
from include/linux/gfp.h:7,
from include/linux/mm.h:7,
from arch/openrisc/include/asm/pgalloc.h:20,
from arch/openrisc/include/asm/io.h:18,
from include/linux/io.h:12,
from drivers/irqchip/irq-ompic.c:61:
arch/openrisc/include/asm/smp.h:21:59: warning: 'struct cpumask' declared inside parameter list will not be visible outside of this definition or declaration
21 | extern void arch_send_call_function_ipi_mask(const struct cpumask *mask);
| ^~~~~~~
arch/openrisc/include/asm/smp.h:23:54: warning: 'struct cpumask' declared inside parameter list will not be visible outside of this definition or declaration
23 | extern void set_smp_cross_call(void (*)(const struct cpumask *, unsigned int));
| ^~~~~~~
drivers/irqchip/irq-ompic.c: In function 'ompic_of_init':

Quoted 1 line
Quoted 1 line

drivers/irqchip/irq-ompic.c:191:28: error: passing argument 1 of

'set_smp_cross_call' from incompatible pointer type [-Werror=incompatible-pointer-types]
191 | set_smp_cross_call(ompic_raise_softirq);
| ^~~~~~~~~~~~~~~~~~~
| |
| void (*)(const struct cpumask *, unsigned int)
arch/openrisc/include/asm/smp.h:23:32: note: expected 'void (*)(const struct cpumask *, unsigned int)' but argument is of type 'void
(*)(const struct cpumask *, unsigned int)'
23 | extern void set_smp_cross_call(void (*)(const struct cpumask *, unsigned int));

To fix this, let's take an example from the smp.h headers of other architectures (x86, hexagon, arm64, probably more): just include linux/cpumask.h at the top.

---
 arch/openrisc/include/asm/smp.h | 2 ++
 1 file changed, 2 insertions(+)
arch/openrisc/include/asm/smp.h +2 -0
index 007296f160ef..84653aaffa96 100644
@@ -9,6 +9,8 @@
 #ifndef __ASM_OPENRISC_SMP_H
 #define __ASM_OPENRISC_SMP_H
 
+#include <linux/cpumask.h>
+
 #include <asm/spr.h>
 #include <asm/spr_defs.h>
 
Signature · 1 line
2.51.0
author maintainer
#10 lore raw

PATCH v3 5/13 irq & spin_lock: Add counted interrupt disabling/enabling

In reply to Boqun Feng

From: Boqun Feng <[email protected]>

Currently the nested interrupt disabling and enabling is present by _irqsave() and _irqrestore() APIs, which are relatively unsafe, for example:

	<interrupts are enabled as beginning>
	spin_lock_irqsave(l1, flag1);
	spin_lock_irqsave(l2, flag2);
	spin_unlock_irqrestore(l1, flags1);
	<l2 is still held but interrupts are enabled>
	// accesses to interrupt-disable protect data will cause races.

This is even easier to triggered with guard facilities:

	unsigned long flag2;

	scoped_guard(spin_lock_irqsave, l1) {
		spin_lock_irqsave(l2, flag2);
	}
	// l2 locked but interrupts are enabled.
	spin_unlock_irqrestore(l2, flag2);

(Hand-to-hand locking critical sections are not uncommon for a fine-grained lock design)

And because this unsafety, Rust cannot easily wrap the interrupt-disabling locks in a safe API, which complicates the design.

To resolve this, introduce a new set of interrupt disabling APIs:

* local_interrupt_disable();
* local_interrupt_enable();

They work like local_irq_save() and local_irq_restore() except that 1) the outermost local_interrupt_disable() call save the interrupt state into a percpu variable, so that the outermost local_interrupt_enable() can restore the state, and 2) a percpu counter is added to record the nest level of these calls, so that interrupts are not accidentally enabled inside the outermost critical section.

Also add the corresponding spin_lock primitives: spin_lock_irq_disable() and spin_unlock_irq_enable(), as a result, code as follow:

	spin_lock_irq_disable(l1);
	spin_lock_irq_disable(l2);
	spin_unlock_irq_enable(l1);
	// Interrupts are still disabled.
	spin_unlock_irq_enable(l2);

doesn't have the issue that interrupts are accidentally enabled.

This also makes the wrapper of interrupt-disabling locks on Rust easier to design.

---
 include/linux/interrupt_rc.h     | 67 ++++++++++++++++++++++++++++++++
 include/linux/preempt.h          |  4 ++
 include/linux/spinlock.h         | 23 +++++++++++
 include/linux/spinlock_api_smp.h | 41 +++++++++++++++++++
 include/linux/spinlock_api_up.h  | 16 ++++++++
 include/linux/spinlock_rt.h      | 18 +++++++++
 kernel/locking/spinlock.c        | 29 ++++++++++++++
 kernel/softirq.c                 | 14 ++++++-
 8 files changed, 211 insertions(+), 1 deletion(-)
 create mode 100644 include/linux/interrupt_rc.h
include/linux/interrupt_rc.h new file +67 -0
new file mode 100644
index 000000000000..dd4444c61330
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * include/linux/interrupt_rc.h - refcounted local processor interrupt
+ * management.
+ *
+ * Since the implementation of this API currently depends on
+ * local_irq_save()/local_irq_restore(), we split this into it's own header to
+ * make it easier to include without hitting circular header dependencies.
+ */
+
+#ifndef __LINUX_INTERRUPT_RC_H
+#define __LINUX_INTERRUPT_RC_H
+
+#include <linux/irqflags.h>
+#include <asm/processor.h>
+#ifdef CONFIG_SMP
+#include <asm/smp.h>
+#endif
+
+/* Per-cpu interrupt disabling state for local_interrupt_{disable,enable}() */
+struct interrupt_disable_state {
+	unsigned long flags;
+};
+
+DECLARE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+
+static inline void local_interrupt_disable(void)
+{
+	unsigned long flags;
+	int new_count;
+
+	WARN_ON_ONCE(in_nmi());
+
+	new_count = hardirq_disable_enter();
+
+	/* Interrupts can happen here, but it's OK, see __irq_exit_rcu(). */
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET) {
+		local_irq_save(flags);
+		raw_cpu_write(local_interrupt_disable_state.flags, flags);
+	}
+}
+
+static inline void local_interrupt_enable(void)
+{
+	int new_count;
+
+	new_count = hardirq_disable_exit();
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == 0) {
+		unsigned long flags;
+
+		flags = raw_cpu_read(local_interrupt_disable_state.flags);
+		local_irq_restore(flags);
+		/*
+		 * TODO: re-read preempt count can be avoided, but it needs
+		 * should_resched() taking another parameter as the current
+		 * preempt count
+		 */
+#ifdef CONFIG_PREEMPTION
+		if (should_resched(0))
+			__preempt_schedule();
+#endif
+	}
+}
+
+#endif /* !__LINUX_INTERRUPT_RC_H */
include/linux/preempt.h +4 -0
index e2d3079d3f5f..33fc4c814a9f 100644
@@ -151,6 +151,10 @@ static __always_inline unsigned char interrupt_context_level(void)
 #define in_softirq()		(softirq_count())
 #define in_interrupt()		(irq_count())
 
+#define hardirq_disable_count()	((preempt_count() & HARDIRQ_DISABLE_MASK) >> HARDIRQ_DISABLE_SHIFT)
+#define hardirq_disable_enter()	__preempt_count_add_return(HARDIRQ_DISABLE_OFFSET)
+#define hardirq_disable_exit()	__preempt_count_sub_return(HARDIRQ_DISABLE_OFFSET)
+
 /*
  * The preempt_count offset after preempt_disable();
  */
include/linux/spinlock.h +23 -0
index 241277cd34cf..3d405cc4c121 100644
@@ -57,6 +57,7 @@
 #include <linux/linkage.h>
 #include <linux/compiler.h>
 #include <linux/irqflags.h>
+#include <linux/interrupt_rc.h>
 #include <linux/thread_info.h>
 #include <linux/stringify.h>
 #include <linux/bottom_half.h>
@@ -273,9 +274,11 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock)
 #endif
 
 #define raw_spin_lock_irq(lock)		_raw_spin_lock_irq(lock)
+#define raw_spin_lock_irq_disable(lock)	_raw_spin_lock_irq_disable(lock)
 #define raw_spin_lock_bh(lock)		_raw_spin_lock_bh(lock)
 #define raw_spin_unlock(lock)		_raw_spin_unlock(lock)
 #define raw_spin_unlock_irq(lock)	_raw_spin_unlock_irq(lock)
+#define raw_spin_unlock_irq_enable(lock)	_raw_spin_unlock_irq_enable(lock)
 
 #define raw_spin_unlock_irqrestore(lock, flags)		\
 	do {							\
@@ -290,6 +293,8 @@ static inline void do_raw_spin_unlock(raw_spinlock_t *lock) __releases(lock)
 
 #define raw_spin_trylock_irqsave(lock, flags) _raw_spin_trylock_irqsave(lock, &(flags))
 
+#define raw_spin_trylock_irq_disable(lock)	_raw_spin_trylock_irq_disable(lock)
+
 #ifndef CONFIG_PREEMPT_RT
 /* Include rwlock functions for !RT */
 #include <linux/rwlock.h>
@@ -372,6 +377,12 @@ static __always_inline void spin_lock_irq(spinlock_t *lock)
 	raw_spin_lock_irq(&lock->rlock);
 }
 
+static __always_inline void spin_lock_irq_disable(spinlock_t *lock)
+	__acquires(lock) __no_context_analysis
+{
+	raw_spin_lock_irq_disable(&lock->rlock);
+}
+
 #define spin_lock_irqsave(lock, flags)				\
 do {								\
 	raw_spin_lock_irqsave(spinlock_check(lock), flags);	\
@@ -402,6 +413,12 @@ static __always_inline void spin_unlock_irq(spinlock_t *lock)
 	raw_spin_unlock_irq(&lock->rlock);
 }
 
+static __always_inline void spin_unlock_irq_enable(spinlock_t *lock)
+	__releases(lock) __no_context_analysis
+{
+	raw_spin_unlock_irq_enable(&lock->rlock);
+}
+
 static __always_inline void spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags)
 	__releases(lock) __no_context_analysis
 {
@@ -427,6 +444,12 @@ static __always_inline bool _spin_trylock_irqsave(spinlock_t *lock, unsigned lon
 }
 #define spin_trylock_irqsave(lock, flags) _spin_trylock_irqsave(lock, &(flags))
 
+static __always_inline int spin_trylock_irq_disable(spinlock_t *lock)
+	__cond_acquires(true, lock) __no_context_analysis
+{
+	return raw_spin_trylock_irq_disable(&lock->rlock);
+}
+
 /**
  * spin_is_locked() - Check whether a spinlock is locked.
  * @lock: Pointer to the spinlock.
include/linux/spinlock_api_smp.h +41 -0

83 lines not on this page · raw message

include/linux/spinlock_api_up.h +16 -0
index a9d5c7c66e03..e4de8bb26a15 100644
@@ -42,6 +42,9 @@
 #define __LOCK_IRQSAVE(lock, flags, ...) \
   do { local_irq_save(flags); __LOCK(lock, ##__VA_ARGS__); } while (0)
 
+#define __LOCK_IRQ_DISABLE(lock, ...) \
+  do { local_interrupt_disable(); __LOCK(lock, ##__VA_ARGS__); } while (0)
+
 #define ___UNLOCK_(lock) \
   do { __release(lock); (void)(lock); } while (0)
 
@@ -61,6 +64,10 @@
 #define __UNLOCK_IRQRESTORE(lock, flags, ...) \
   do { local_irq_restore(flags); __UNLOCK(lock, ##__VA_ARGS__); } while (0)
 
+#define __UNLOCK_IRQ_ENABLE(lock, ...) \
+  do { __UNLOCK(lock, ##__VA_ARGS__); local_interrupt_enable(); } while (0)
+
+
 #define _raw_spin_lock(lock)			__LOCK(lock)
 #define _raw_spin_lock_nested(lock, subclass)	__LOCK(lock)
 #define _raw_read_lock(lock)			__LOCK(lock, shared)
@@ -70,6 +77,7 @@
 #define _raw_read_lock_bh(lock)			__LOCK_BH(lock, shared)
 #define _raw_write_lock_bh(lock)		__LOCK_BH(lock)
 #define _raw_spin_lock_irq(lock)		__LOCK_IRQ(lock)
+#define _raw_spin_lock_irq_disable(lock)	__LOCK_IRQ_DISABLE(lock)
 #define _raw_read_lock_irq(lock)		__LOCK_IRQ(lock, shared)
 #define _raw_write_lock_irq(lock)		__LOCK_IRQ(lock)
 #define _raw_spin_lock_irqsave(lock, flags)	__LOCK_IRQSAVE(lock, flags)
@@ -97,6 +105,13 @@ static __always_inline int _raw_spin_trylock_irq(raw_spinlock_t *lock)
 	return 1;
 }
 
+static __always_inline int _raw_spin_trylock_irq_disable(raw_spinlock_t *lock)
+	__cond_acquires(true, lock)
+{
+	__LOCK_IRQ_DISABLE(lock);
+	return 1;
+}
+
 static __always_inline int _raw_spin_trylock_irqsave(raw_spinlock_t *lock, unsigned long *flags)
 	__cond_acquires(true, lock)
 {
@@ -132,6 +147,7 @@ static __always_inline int _raw_write_trylock_irqsave(rwlock_t *lock, unsigned l
 #define _raw_write_unlock_bh(lock)		__UNLOCK_BH(lock)
 #define _raw_read_unlock_bh(lock)		__UNLOCK_BH(lock, shared)
 #define _raw_spin_unlock_irq(lock)		__UNLOCK_IRQ(lock)
+#define _raw_spin_unlock_irq_enable(lock)	__UNLOCK_IRQ_ENABLE(lock)
 #define _raw_read_unlock_irq(lock)		__UNLOCK_IRQ(lock, shared)
 #define _raw_write_unlock_irq(lock)		__UNLOCK_IRQ(lock)
 #define _raw_spin_unlock_irqrestore(lock, flags) \
include/linux/spinlock_rt.h +18 -0
index 373618a4243c..560d06384e0c 100644
@@ -96,6 +96,12 @@ static __always_inline void spin_lock_irq(spinlock_t *lock)
 	rt_spin_lock(lock);
 }
 
+static __always_inline void spin_lock_irq_disable(spinlock_t *lock)
+	__acquires(lock)
+{
+	rt_spin_lock(lock);
+}
+
 #define spin_lock_irqsave(lock, flags)			 \
 	do {						 \
 		typecheck(unsigned long, flags);	 \
@@ -122,6 +128,12 @@ static __always_inline void spin_unlock_irq(spinlock_t *lock)
 	rt_spin_unlock(lock);
 }
 
+static __always_inline void spin_unlock_irq_enable(spinlock_t *lock)
+	__releases(lock)
+{
+	rt_spin_unlock(lock);
+}
+
 static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,
 						   unsigned long flags)
 	__releases(lock)
@@ -131,6 +143,12 @@ static __always_inline void spin_unlock_irqrestore(spinlock_t *lock,
 
 #define spin_trylock(lock)	rt_spin_trylock(lock)
 
+static __always_inline int spin_trylock_irq_disable(spinlock_t *lock)
+	__cond_acquires(true, lock)
+{
+	return rt_spin_trylock(lock);
+}
+
 #define spin_trylock_bh(lock)	rt_spin_trylock_bh(lock)
 
 #define spin_trylock_irq(lock)	rt_spin_trylock(lock)
kernel/locking/spinlock.c +29 -0
index b42d293da38b..764641f6ec57 100644
@@ -129,6 +129,19 @@ static void __lockfunc __raw_##op##_lock_bh(locktype##_t *lock)		\
  */
 BUILD_LOCK_OPS(spin, raw_spinlock, __acquires);
 
+/* No rwlock_t variants for now, so just build this function by hand */
+static void __lockfunc __raw_spin_lock_irq_disable(raw_spinlock_t *lock)
+{
+	for (;;) {
+		local_interrupt_disable();
+		if (likely(do_raw_spin_trylock(lock)))
+			break;
+		local_interrupt_enable();
+
+		arch_spin_relax(&lock->raw_lock);
+	}
+}
+
 #ifndef CONFIG_PREEMPT_RT
 BUILD_LOCK_OPS(read, rwlock, __acquires_shared);
 BUILD_LOCK_OPS(write, rwlock, __acquires);
@@ -176,6 +189,14 @@ noinline void __lockfunc _raw_spin_lock_irq(raw_spinlock_t *lock)
 EXPORT_SYMBOL(_raw_spin_lock_irq);
 #endif
 
+#ifndef CONFIG_INLINE_SPIN_LOCK_IRQ
+noinline void __lockfunc _raw_spin_lock_irq_disable(raw_spinlock_t *lock)
+{
+	__raw_spin_lock_irq_disable(lock);
+}
+EXPORT_SYMBOL_GPL(_raw_spin_lock_irq_disable);
+#endif
+
 #ifndef CONFIG_INLINE_SPIN_LOCK_BH
 noinline void __lockfunc _raw_spin_lock_bh(raw_spinlock_t *lock)
 {
@@ -208,6 +229,14 @@ noinline void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock)
 EXPORT_SYMBOL(_raw_spin_unlock_irq);
 #endif
 
+#ifndef CONFIG_INLINE_SPIN_UNLOCK_IRQ
+noinline void __lockfunc _raw_spin_unlock_irq_enable(raw_spinlock_t *lock)
+{
+	__raw_spin_unlock_irq_enable(lock);
+}
+EXPORT_SYMBOL_GPL(_raw_spin_unlock_irq_enable);
+#endif
+
 #ifndef CONFIG_INLINE_SPIN_UNLOCK_BH
 noinline void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock)
 {
kernel/softirq.c +13 -1
index 10af5ed859e7..d1ab1799794c 100644
@@ -88,6 +88,9 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled);
 EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context);
 #endif
 
+DEFINE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+EXPORT_PER_CPU_SYMBOL_GPL(local_interrupt_disable_state);
+
 DEFINE_PER_CPU(unsigned int, nmi_nesting);
 
 /*
@@ -728,7 +731,16 @@ static inline void __irq_exit_rcu(void)
 #endif
 	account_hardirq_exit(current);
 	preempt_count_sub(HARDIRQ_OFFSET);
-	if (!in_interrupt() && local_softirq_pending()) {
+	/*
+	 * Interrupts may happen between hardirq_disable_enter() and
+	 * local_irq_save() in local_interrupt_disable(), if irq_exit() invokes
+	 * softirq here, we may have a softirq handler calling
+	 * local_interrupt_disable() but it won't disable the irq because
+	 * hardirq disabling count is already 1, hence we need to prevent
+	 * invoking softirq when a local_interrupt_disable() is ongoing.
+	 */
+	if (!in_interrupt() && !hardirq_disable_count() &&
+	    local_softirq_pending()) {
 		/*
 		 * If we left hrtimers unarmed, make sure to arm them now,
 		 * before enabling interrupts to run SoftIRQ.
Signature · 1 line
2.51.0
author maintainer
#15 lore raw

PATCH v3 6/13 irq: Add KUnit test for refcounted interrupt enable/disable

In reply to Boqun Feng

From: Lyude Paul <[email protected]>

While making changes to the refcounted interrupt patch series, at some point on my local branch I broke something and ended up writing some kunit tests for testing refcounted interrupts as a result. So, let's include these tests now that we have refcounted interrupts.

---
 kernel/irq/Makefile                  |   1 +
 kernel/irq/refcount_interrupt_test.c | 109 +++++++++++++++++++++++++++
 2 files changed, 110 insertions(+)
 create mode 100644 kernel/irq/refcount_interrupt_test.c
kernel/irq/Makefile +1 -0
index 86a2e5ae08f9..44c4d6fc502a 100644
@@ -16,3 +16,4 @@ obj-$(CONFIG_SMP) += affinity.o
 obj-$(CONFIG_GENERIC_IRQ_DEBUGFS) += debugfs.o
 obj-$(CONFIG_GENERIC_IRQ_MATRIX_ALLOCATOR) += matrix.o
 obj-$(CONFIG_IRQ_KUNIT_TEST) += irq_test.o
+obj-$(CONFIG_KUNIT) += refcount_interrupt_test.o
kernel/irq/refcount_interrupt_test.c new file +109 -0

109 lines not on this page · raw message

Signature · 1 line
2.51.0
author maintainer
#17 lore raw

PATCH v3 7/13 locking: Switch to _irq_{disable,enable}() variants in cleanup guards

In reply to Boqun Feng

From: Boqun Feng <[email protected]>

The semantics of various irq disabling guards match what *_irq_{disable,enable}() provide, i.e. the interrupt disabling is properly nested, therefore it's OK to switch to use *_irq_{disable,enable}() primitives.

---
 include/linux/spinlock.h | 26 ++++++++++++--------------
 1 file changed, 12 insertions(+), 14 deletions(-)
include/linux/spinlock.h +12 -14
index 3d405cc4c121..799a8f7d2741 100644
@@ -572,12 +572,12 @@ DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_nested, __acquires(_T), __releases(*(raw
 #define class_raw_spinlock_nested_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_nested, _T)
 
 DEFINE_LOCK_GUARD_1(raw_spinlock_irq, raw_spinlock_t,
-		    raw_spin_lock_irq(_T->lock),
-		    raw_spin_unlock_irq(_T->lock))
+		    raw_spin_lock_irq_disable(_T->lock),
+		    raw_spin_unlock_irq_enable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irq, __acquires(_T), __releases(*(raw_spinlock_t **)_T))
 #define class_raw_spinlock_irq_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_irq, _T)
 
-DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irq, _try, raw_spin_trylock_irq(_T->lock))
+DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irq, _try, raw_spin_trylock_irq_disable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irq_try, __acquires(_T), __releases(*(raw_spinlock_t **)_T))
 #define class_raw_spinlock_irq_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_irq_try, _T)
 
@@ -592,14 +592,13 @@ DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_bh_try, __acquires(_T), __releases(*(raw
 #define class_raw_spinlock_bh_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_bh_try, _T)
 
 DEFINE_LOCK_GUARD_1(raw_spinlock_irqsave, raw_spinlock_t,
-		    raw_spin_lock_irqsave(_T->lock, _T->flags),
-		    raw_spin_unlock_irqrestore(_T->lock, _T->flags),
-		    unsigned long flags)
+		    raw_spin_lock_irq_disable(_T->lock),
+		    raw_spin_unlock_irq_enable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave, __acquires(_T), __releases(*(raw_spinlock_t **)_T))
 #define class_raw_spinlock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave, _T)
 
 DEFINE_LOCK_GUARD_1_COND(raw_spinlock_irqsave, _try,
-			 raw_spin_trylock_irqsave(_T->lock, _T->flags))
+			 raw_spin_trylock_irq_disable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave_try, __acquires(_T), __releases(*(raw_spinlock_t **)_T))
 #define class_raw_spinlock_irqsave_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave_try, _T)
 
@@ -618,13 +617,13 @@ DECLARE_LOCK_GUARD_1_ATTRS(spinlock_try, __acquires(_T), __releases(*(spinlock_t
 #define class_spinlock_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_try, _T)
 
 DEFINE_LOCK_GUARD_1(spinlock_irq, spinlock_t,
-		    spin_lock_irq(_T->lock),
-		    spin_unlock_irq(_T->lock))
+		    spin_lock_irq_disable(_T->lock),
+		    spin_unlock_irq_enable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irq, __acquires(_T), __releases(*(spinlock_t **)_T))
 #define class_spinlock_irq_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_irq, _T)
 
 DEFINE_LOCK_GUARD_1_COND(spinlock_irq, _try,
-			 spin_trylock_irq(_T->lock))
+			 spin_trylock_irq_disable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irq_try, __acquires(_T), __releases(*(spinlock_t **)_T))
 #define class_spinlock_irq_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_irq_try, _T)
 
@@ -640,14 +639,13 @@ DECLARE_LOCK_GUARD_1_ATTRS(spinlock_bh_try, __acquires(_T), __releases(*(spinloc
 #define class_spinlock_bh_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_bh_try, _T)
 
 DEFINE_LOCK_GUARD_1(spinlock_irqsave, spinlock_t,
-		    spin_lock_irqsave(_T->lock, _T->flags),
-		    spin_unlock_irqrestore(_T->lock, _T->flags),
-		    unsigned long flags)
+		    spin_lock_irq_disable(_T->lock),
+		    spin_unlock_irq_enable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irqsave, __acquires(_T), __releases(*(spinlock_t **)_T))
 #define class_spinlock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_irqsave, _T)
 
 DEFINE_LOCK_GUARD_1_COND(spinlock_irqsave, _try,
-			 spin_trylock_irqsave(_T->lock, _T->flags))
+			 spin_trylock_irq_disable(_T->lock))
 DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irqsave_try, __acquires(_T), __releases(*(spinlock_t **)_T))
 #define class_spinlock_irqsave_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_irqsave_try, _T)
 
Signature · 1 line
2.51.0
author maintainer
#19 lore raw

PATCH v3 8/13 sched: Remove the unused preempt_offset parameter of __cant_sleep()

In reply to Boqun Feng

The preempt_offset is always 0 in all the callsites of __cant_sleep(), hence remove it. It also allows us to clear the code a bit by stopping using a "preempt_count() > .." comparison.

---
 include/linux/kernel.h | 4 ++--
 kernel/sched/core.c    | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
include/linux/kernel.h +2 -2
index e5570a16cbb1..24414c79e59a 100644
@@ -72,7 +72,7 @@ extern int dynamic_might_resched(void);
 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
 extern void __might_resched(const char *file, int line, unsigned int offsets);
 extern void __might_sleep(const char *file, int line);
-extern void __cant_sleep(const char *file, int line, int preempt_offset);
+extern void __cant_sleep(const char *file, int line);
 extern void __cant_migrate(const char *file, int line);
 
 /**
@@ -95,7 +95,7 @@ extern void __cant_migrate(const char *file, int line);
  * this macro will print a stack trace if it is executed with preemption enabled
  */
 # define cant_sleep() \
-	do { __cant_sleep(__FILE__, __LINE__, 0); } while (0)
+	do { __cant_sleep(__FILE__, __LINE__); } while (0)
 # define sched_annotate_sleep()	(current->task_state_change = 0)
 
 /**
kernel/sched/core.c +2 -2
index b8871449d3c6..75dba7cc09bd 100644
@@ -9165,7 +9165,7 @@ void __might_resched(const char *file, int line, unsigned int offsets)
 }
 EXPORT_SYMBOL(__might_resched);
 
-void __cant_sleep(const char *file, int line, int preempt_offset)
+void __cant_sleep(const char *file, int line)
 {
 	static unsigned long prev_jiffy;
 
@@ -9175,7 +9175,7 @@ void __cant_sleep(const char *file, int line, int preempt_offset)
 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
 		return;
 
-	if (preempt_count() > preempt_offset)
+	if (preempt_count())
 		return;
 
 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
Signature · 1 line
2.51.0
author maintainer
#20 lore raw

PATCH v3 9/13 sched: Avoid signed comparison of preempt_count() in __cant_migrate()

In reply to Boqun Feng

Currently preempt_count() is always a non-negative int on all archs (PREEMPT_NEED_RESCHED archs will mask out the MSB when return preempt_count()), hence the checking in __cant_migrate() is in fact just checking whether preempt_count() is 0 or not. In a future change, we are going to use all the 32 bits of preempt_count(), which would make negative int values possible from preempt_count(). Therefore convert the "> 0" comparison into a zero checking to prepare for the future change. No functional changes are intended.

---
 kernel/sched/core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/core.c +1 -1
index 75dba7cc09bd..636e6a15f104 100644
@@ -9207,7 +9207,7 @@ void __cant_migrate(const char *file, int line)
 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
 		return;
 
-	if (preempt_count() > 0)
+	if (preempt_count())
 		return;
 
 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
Signature · 1 line
2.51.0
author maintainer
#21 lore raw

PATCH v3 10/13 preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS

In reply to Boqun Feng

With the changes that enable preempt count to tracking irq disabling nesting, we don't have enough bits in 32bit preempt count implementation, as a result we move NMI nesting bits out of the 32bit preempt count. However on the architectures that can support 64bit preempt count implementation, we can keep the NMI nesting bits in the 32bit preempt count and avoid maintaining NMI nesting bits out of the same cache line.

Therefore HAS_SEPARATE_PREEMPT_RESCHED_BITS is introduced to allow architectures to select this. Note that under this kconfig, preempt count is maintained in a 64bit word however preempt_count() still remains as an int because all the effective bits still fit in (previously we mask out NEED_RESCHED bit in preempt_count()). This should make no functional changes for existing preempt_count() users.

Enable this for x86_64 along with the introduction of the Kconfig.

[boqun: Undo the __preempt_count_{add,sub}() optimization in 32bit preempt count since it may introduce {over,under}flow]

---
 arch/x86/Kconfig               |  1 +
 arch/x86/include/asm/preempt.h | 55 +++++++++++++++++++++++-----------
 arch/x86/kernel/cpu/common.c   |  2 +-
 include/linux/hardirq.h        | 48 +++++++++++++++++++++--------
 include/linux/preempt.h        | 20 +++++++------
 kernel/Kconfig.preempt         |  4 +++
 kernel/sched/core.c            | 12 ++++++--
 kernel/softirq.c               |  6 ++++
 lib/locking-selftest.c         |  2 +-
 9 files changed, 107 insertions(+), 43 deletions(-)
arch/x86/Kconfig +1 -0
index fdaef60b46d6..9a35c3a08757 100644
@@ -329,6 +329,7 @@ config X86
 	select USER_STACKTRACE_SUPPORT
 	select HAVE_ARCH_KCSAN			if X86_64
 	select PROC_PID_ARCH_STATUS		if PROC_FS
+	select HAS_SEPARATE_PREEMPT_RESCHED_BITS		if X86_64
 	select HAVE_ARCH_NODE_DEV_GROUP		if X86_SGX
 	select FUNCTION_ALIGNMENT_16B		if X86_64 || X86_ALIGNMENT_16
 	select FUNCTION_ALIGNMENT_4B
arch/x86/include/asm/preempt.h +38 -17

123 lines not on this page · raw message

arch/x86/kernel/cpu/common.c +1 -1
index a4268c47f2bc..182772b6ad6d 100644
@@ -2240,7 +2240,7 @@ DEFINE_PER_CPU_CACHE_HOT(struct task_struct *, current_task) = &init_task;
 EXPORT_PER_CPU_SYMBOL(current_task);
 EXPORT_PER_CPU_SYMBOL(const_current_task);
 
-DEFINE_PER_CPU_CACHE_HOT(int, __preempt_count) = INIT_PREEMPT_COUNT;
+DEFINE_PER_CPU_CACHE_HOT(unsigned long, __preempt_count) = INIT_PREEMPT_COUNT;
 EXPORT_PER_CPU_SYMBOL(__preempt_count);
 
 DEFINE_PER_CPU_CACHE_HOT(unsigned long, cpu_current_top_of_stack) = TOP_OF_INIT_STACK;
include/linux/hardirq.h +35 -13

79 lines not on this page · raw message

include/linux/preempt.h +11 -9
index 33fc4c814a9f..87d5367f986c 100644
@@ -30,18 +30,20 @@
  * NMI nesting depth is tracked in a separate per-CPU variable
  * (nmi_nesting) to save bits in preempt_count.
  *
- *         PREEMPT_MASK:	0x000000ff
- *         SOFTIRQ_MASK:	0x0000ff00
- * HARDIRQ_DISABLE_MASK:	0x00ff0000
- *         HARDIRQ_MASK:	0x0f000000
- *             NMI_MASK:	0x10000000
- * PREEMPT_NEED_RESCHED:	0x80000000
+ *				32bit		HAS_SEPARATE_PREEMPT_RESCHED_BITS
+ *
+ *         PREEMPT_MASK:	0x000000ff	0x00000000000000ff
+ *         SOFTIRQ_MASK:	0x0000ff00	0x000000000000ff00
+ * HARDIRQ_DISABLE_MASK:	0x00ff0000	0x0000000000ff0000
+ *         HARDIRQ_MASK:	0x0f000000	0x000000000f000000
+ *             NMI_MASK:	0x10000000	0x00000000f0000000
+ * PREEMPT_NEED_RESCHED:	0x80000000	0x8000000000000000
  */
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
 #define HARDIRQ_DISABLE_BITS	8
 #define HARDIRQ_BITS	4
-#define NMI_BITS	1
+#define NMI_BITS	(1 + 3*IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS))
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
@@ -116,8 +118,8 @@ static __always_inline unsigned char interrupt_context_level(void)
  * preempt_count() is commonly implemented with READ_ONCE().
  */
 
-#define nmi_count()	(preempt_count() & NMI_MASK)
-#define hardirq_count()	(preempt_count() & HARDIRQ_MASK)
+#define nmi_count()		(preempt_count() & NMI_MASK)
+#define hardirq_count()		(preempt_count() & HARDIRQ_MASK)
 #ifdef CONFIG_PREEMPT_RT
 # define softirq_count()	(current->softirq_disable_cnt & SOFTIRQ_MASK)
 # define irq_count()		((preempt_count() & (NMI_MASK | HARDIRQ_MASK)) | softirq_count())
kernel/Kconfig.preempt +4 -0
index 88c594c6d7fc..35f546a042b1 100644
@@ -122,6 +122,10 @@ config PREEMPT_RT_NEEDS_BH_LOCK
 config PREEMPT_COUNT
        bool
 
+config HAS_SEPARATE_PREEMPT_RESCHED_BITS
+	bool
+	depends on PREEMPT_COUNT && 64BIT
+
 config PREEMPTION
        bool
        select PREEMPT_COUNT
kernel/sched/core.c +10 -2
index 636e6a15f104..f4c944878516 100644
@@ -5847,8 +5847,13 @@ void preempt_count_add(int val)
 #ifdef CONFIG_DEBUG_PREEMPT
 	/*
 	 * Underflow?
+	 *
+	 * Cannot detect underflow based on the current preempt_count() value
+	 * if using HAS_SEPARATE_PREEMPT_RESCHED_BITS because preempt count takes all 32
+	 * bits.
 	 */
-	if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
+	if (!IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS) &&
+	    DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
 		return;
 #endif
 	__preempt_count_add(val);
@@ -5880,7 +5885,10 @@ void preempt_count_sub(int val)
 	/*
 	 * Underflow?
 	 */
-	if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
+	unsigned int uval = val;
+	unsigned int pc = preempt_count();
+
+	if (DEBUG_LOCKS_WARN_ON(pc - uval > pc))
 		return;
 	/*
 	 * Is the spinlock portion underflowing?
kernel/softirq.c +6 -0
index d1ab1799794c..491136a313db 100644
@@ -91,7 +91,13 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context);
 DEFINE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
 EXPORT_PER_CPU_SYMBOL_GPL(local_interrupt_disable_state);
 
+#ifndef CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS
+/*
+ * Any 32bit architecture that still cares about performance should
+ * probably ensure this is near preempt_count.
+ */
 DEFINE_PER_CPU(unsigned int, nmi_nesting);
+#endif
 
 /*
  * SOFTIRQ_OFFSET usage:
lib/locking-selftest.c +1 -1
index bfafe1204c7b..c3d976c801bb 100644
@@ -1429,7 +1429,7 @@ static int unexpected_testcase_failures;
 
 static void dotest(void (*testcase_fn)(void), int expected, int lockclass_mask)
 {
-	int saved_preempt_count = preempt_count();
+	long saved_preempt_count = preempt_count();
 #ifdef CONFIG_PREEMPT_RT
 	int saved_mgd_count = current->migration_disabled;
 	int saved_rcu_count = current->rcu_read_lock_nesting;
Signature · 1 line
2.51.0
author maintainer
#24 lore raw

PATCH v3 11/13 arm64: sched/preempt: Enable HAS_SEPARATE_PREEMPT_RESCHED_BITS

In reply to Boqun Feng

ARM64 already uses 64bit preempt count and the need reschedule bit is maintained in a separate 32bit than the preempt count. Therefore preempt count has enough bits to represent 16 level of NMI nesting, hence enable it for ARM64. This saves a per-CPU variable and additional instructions in the NMI path.

---
 arch/arm64/Kconfig | 1 +
 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +1 -0
index fe60738e5943..8178cb857115 100644
@@ -248,6 +248,7 @@ config ARM64
 	select PCI_SYSCALL if PCI
 	select POWER_RESET
 	select POWER_SUPPLY
+	select HAS_SEPARATE_PREEMPT_RESCHED_BITS
 	select SPARSE_IRQ
 	select SWIOTLB
 	select SYSCTL_EXCEPTION_TRACE
Signature · 1 line
2.51.0
author maintainer
#25 lore raw

PATCH v3 12/13 s390/preempt: Enable HAS_SEPARATE_PREEMPT_RESCHED_BITS

In reply to Boqun Feng

From: Heiko Carstens <[email protected]>

Convert s390's preempt_count to 64 bit, and change the preempt primitives accordingly.

---
 arch/s390/Kconfig               |  1 +
 arch/s390/include/asm/lowcore.h | 13 +++++++----
 arch/s390/include/asm/preempt.h | 41 +++++++++++++++------------------
 3 files changed, 29 insertions(+), 26 deletions(-)
arch/s390/Kconfig +1 -0
index ecbcbb781e40..cbbca82f8443 100644
@@ -276,6 +276,7 @@ config S390
 	select PCI_MSI			if PCI
 	select PCI_MSI_ARCH_FALLBACKS	if PCI_MSI
 	select PCI_QUIRKS		if PCI
+	select HAS_SEPARATE_PREEMPT_RESCHED_BITS
 	select SPARSE_IRQ
 	select SWIOTLB
 	select SYSCTL_EXCEPTION_TRACE
arch/s390/include/asm/lowcore.h +9 -4
index 50ffe75adeb4..0974ab278169 100644
@@ -160,10 +160,15 @@ struct lowcore {
 	/* SMP info area */
 	__u32	cpu_nr;				/* 0x03a0 */
 	__u32	softirq_pending;		/* 0x03a4 */
-	__s32	preempt_count;			/* 0x03a8 */
-	__u32	spinlock_lockval;		/* 0x03ac */
-	__u32	spinlock_index;			/* 0x03b0 */
-	__u8	pad_0x03b4[0x03b8-0x03b4];	/* 0x03b4 */
+	union {
+		struct {
+			__u32	need_resched;	/* 0x03a8 */
+			__u32	count;		/* 0x03ac */
+		} preempt;
+		__u64	preempt_count;		/* 0x03a8 */
+	};
+	__u32	spinlock_lockval;		/* 0x03b0 */
+	__u32	spinlock_index;			/* 0x03b4 */
 	__u64	percpu_offset;			/* 0x03b8 */
 	__u8	pad_0x03c0[0x0400-0x03c0];	/* 0x03c0 */
 
arch/s390/include/asm/preempt.h +19 -22

104 lines not on this page · raw message

Signature · 1 line
2.51.0
author maintainer
#26 lore raw

PATCH v3 13/13 irq: Optimize reschedule check in local_interrupt_enable()

In reply to Boqun Feng

In local_interrupt_enable(), we could avoid re-reading preempt count because of should_resched() by using the result from hardirq_disable_exit(), however this means __preempt_count_add_return() and __preempt_count_sub_return() need to return all the preempt count bits (including the PREEMPT_NEED_RESCHED bit), since the only user of __preempt_count_{add,sub}_return() is hardirq_disable_{enter,exit}(), hence make them return "unsigned long" to optimize this.

---
 arch/arm64/include/asm/preempt.h | 12 ++++++------
 arch/s390/include/asm/preempt.h  |  4 ++--
 arch/x86/include/asm/preempt.h   |  4 ++--
 include/asm-generic/preempt.h    |  4 ++--
 include/linux/interrupt_rc.h     | 31 ++++++++++++++++++++-----------
 5 files changed, 32 insertions(+), 23 deletions(-)
arch/arm64/include/asm/preempt.h +6 -6
index 0dd8221d1bef..e9f597d87413 100644
@@ -55,20 +55,20 @@ static inline void __preempt_count_sub(int val)
 	WRITE_ONCE(current_thread_info()->preempt.count, pc);
 }
 
-static inline int __preempt_count_add_return(int val)
+static inline unsigned long __preempt_count_add_return(int val)
 {
-	u32 pc = READ_ONCE(current_thread_info()->preempt.count);
+	u64 pc = READ_ONCE(current_thread_info()->preempt_count);
 	pc += val;
-	WRITE_ONCE(current_thread_info()->preempt.count, pc);
+	WRITE_ONCE(current_thread_info()->preempt_count, pc);
 
 	return pc;
 }
 
-static inline int __preempt_count_sub_return(int val)
+static inline unsigned long __preempt_count_sub_return(int val)
 {
-	u32 pc = READ_ONCE(current_thread_info()->preempt.count);
+	u64 pc = READ_ONCE(current_thread_info()->preempt_count);
 	pc -= val;
-	WRITE_ONCE(current_thread_info()->preempt.count, pc);
+	WRITE_ONCE(current_thread_info()->preempt_count, pc);
 
 	return pc;
 }
arch/s390/include/asm/preempt.h +2 -2
index 1d5e4d7e9e1b..d0021b979a5d 100644
@@ -136,12 +136,12 @@ static __always_inline bool should_resched(int preempt_offset)
 	return unlikely(READ_ONCE(get_lowcore()->preempt_count) == preempt_offset);
 }
 
-static __always_inline int __preempt_count_add_return(int val)
+static __always_inline unsigned long __preempt_count_add_return(int val)
 {
 	return val + __atomic64_add(val, (long *)&get_lowcore()->preempt_count);
 }
 
-static __always_inline int __preempt_count_sub_return(int val)
+static __always_inline unsigned long __preempt_count_sub_return(int val)
 {
 	return __preempt_count_add_return(-val);
 }
arch/x86/include/asm/preempt.h +2 -2
index 12353eeebc52..fc1a2799990a 100644
@@ -103,12 +103,12 @@ static __always_inline void __preempt_count_sub(int val)
 	__pc_op(add, __preempt_count, -val);
 }
 
-static __always_inline int __preempt_count_add_return(int val)
+static __always_inline unsigned long __preempt_count_add_return(int val)
 {
 	return __pc_op(add_return, __preempt_count, val);
 }
 
-static __always_inline int __preempt_count_sub_return(int val)
+static __always_inline unsigned long __preempt_count_sub_return(int val)
 {
 	return __pc_op(add_return, __preempt_count, -val);
 }
include/asm-generic/preempt.h +2 -2
index c8683c046615..7629e23102d1 100644
@@ -59,14 +59,14 @@ static __always_inline void __preempt_count_sub(int val)
 	*preempt_count_ptr() -= val;
 }
 
-static __always_inline int __preempt_count_add_return(int val)
+static __always_inline unsigned long __preempt_count_add_return(int val)
 {
 	*preempt_count_ptr() += val;
 
 	return *preempt_count_ptr();
 }
 
-static __always_inline int __preempt_count_sub_return(int val)
+static __always_inline unsigned long __preempt_count_sub_return(int val)
 {
 	*preempt_count_ptr() -= val;
 
include/linux/interrupt_rc.h +20 -11
index dd4444c61330..c044dc395452 100644
@@ -27,7 +27,7 @@ DECLARE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
 static inline void local_interrupt_disable(void)
 {
 	unsigned long flags;
-	int new_count;
+	unsigned long new_count;
 
 	WARN_ON_ONCE(in_nmi());
 
@@ -41,9 +41,25 @@ static inline void local_interrupt_disable(void)
 	}
 }
 
+#ifdef CONFIG_PREEMPTION
+static inline void local_interrupt_enable_reched(unsigned long pc)
+{
+	if (pc)
+		return;
+	/* No PREEMPT_NEED_RESCHED bit? Check tif_need_resched() */
+#ifndef PREEMPT_NEED_RESCHED
+	if (!tif_need_resched())
+		return;
+#endif
+	__preempt_schedule();
+}
+#else
+static inline void local_interrupt_enable_reched(unsigned long pc) {}
+#endif
+
 static inline void local_interrupt_enable(void)
 {
-	int new_count;
+	unsigned long new_count;
 
 	new_count = hardirq_disable_exit();
 
@@ -52,15 +68,8 @@ static inline void local_interrupt_enable(void)
 
 		flags = raw_cpu_read(local_interrupt_disable_state.flags);
 		local_irq_restore(flags);
-		/*
-		 * TODO: re-read preempt count can be avoided, but it needs
-		 * should_resched() taking another parameter as the current
-		 * preempt count
-		 */
-#ifdef CONFIG_PREEMPTION
-		if (should_resched(0))
-			__preempt_schedule();
-#endif
+
+		local_interrupt_enable_reched(new_count);
 	}
 }
 
Signature · 1 line
2.51.0
#16 lore raw

Re: [PATCH v3 06/13] irq: Add KUnit test for refcounted interrupt enable/disable

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The refcount interrupt test is unconditionally compiled and executed whenever CONFIG_KUNIT is…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The refcount interrupt test is unconditionally compiled and executed whenever CONFIG_KUNIT is enabled, causing unnecessary kernel bloat. --

commit 0f70b0c848721241ef0e28b62356b6ec7b9daf4b
Author: Lyude Paul <[email protected]>

irq: Add KUnit test for refcounted interrupt enable/disable

This commit introduces a suite of KUnit tests to verify the behavior of the new refcounted interrupt enable and disable functionality.

kernel/irq/Makefile obj-$(CONFIG_SMP) += affinity.o · line 19

Quoted 9 lines
kernel/irq/Makefile +1 -0
index 86a2e5ae08f9a..44c4d6fc502ac 100644
@@ -16,3 +16,4 @@ obj-$(CONFIG_SMP) += affinity.o
 obj-$(CONFIG_GENERIC_IRQ_DEBUGFS) += debugfs.o
 obj-$(CONFIG_GENERIC_IRQ_MATRIX_ALLOCATOR) += matrix.o
 obj-$(CONFIG_IRQ_KUNIT_TEST) += irq_test.o
+obj-$(CONFIG_KUNIT) += refcount_interrupt_test.o

[Severity: Low]
Should this test be gated behind a dedicated Kconfig option instead of compiling unconditionally when KUnit is enabled?

Using CONFIG_KUNIT directly forces the test to compile and execute whenever the KUnit framework is enabled, even when a user is testing unrelated subsystems.

Could this reuse the existing CONFIG_IRQ_KUNIT_TEST (like irq_test.o on the line above it) or use a new, dedicated configuration option to allow granular test selection?

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#18 lore raw

Re: [PATCH v3 07/13] locking: Switch to _irq_{disable,enable}() variants in cleanup guards

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Switching `guard(raw_spinlock_irqsave)` and `guard(spinlock_irqsave)` to use `_irq_disable()`…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Switching guard(raw_spinlock_irqsave) and guard(spinlock_irqsave) to use _irq_disable() variants breaks NMI-safety and will trigger WARN splats and potential preempt_count corruption when used in NMI context. --

commit 545c01b2eb680702b0d892d04382c1e8bb27b35f
Author: Boqun Feng <[email protected]>

locking: Switch to _irq_{disable,enable}() variants in cleanup guards

This commit modifies various irq disabling guards to use the _irq_{disable,enable}() primitives instead of their previous variants.

Quoted 4 lines
include/linux/spinlock.h +0 -0
index 3d405cc4c1218..799a8f7d27418 100644

[ ... ]

include/linux/spinlock.h DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_bh_try, __acquires(_T), __releases(*(raw · line 596

Quoted 9 lines
include/linux/spinlock.h +2 -3
@@ -592,14 +592,13 @@ DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_bh_try, __acquires(_T), __releases(*(raw
 #define class_raw_spinlock_bh_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_bh_try, _T)
 
 DEFINE_LOCK_GUARD_1(raw_spinlock_irqsave, raw_spinlock_t,
-		    raw_spin_lock_irqsave(_T->lock, _T->flags),
-		    raw_spin_unlock_irqrestore(_T->lock, _T->flags),
-		    unsigned long flags)
+		    raw_spin_lock_irq_disable(_T->lock),
+		    raw_spin_unlock_irq_enable(_T->lock))

[Severity: High]
Does this change break NMI-safety for users of guard(raw_spinlock_irqsave)?

The raw_spin_lock_irqsave primitive relies exclusively on CPU-local hardware flag saving, which makes it safe for use in any context, including NMIs.

By switching to raw_spin_lock_irq_disable, this completely bypasses local flags saving and relies on local_interrupt_disable() under the hood.

Because local_interrupt_disable() manipulates the task's preempt_count via hardirq_disable_enter(), it isn't safe in NMI context and will trigger a WARN_ON_ONCE(in_nmi()) splat and potential preempt_count corruption.

Quoted 2 lines
include/linux/spinlock.h +0 -0
 DECLARE_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave, __acquires(_T), __releases(*(raw_spinlock_t **)_T))
 #define class_raw_spinlock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(raw_spinlock_irqsave, _T)

[ ... ]

include/linux/spinlock.h DECLARE_LOCK_GUARD_1_ATTRS(spinlock_bh_try, __acquires(_T), __releases(*(spinloc · line 643

Quoted 9 lines
include/linux/spinlock.h +2 -3
@@ -640,14 +639,13 @@ DECLARE_LOCK_GUARD_1_ATTRS(spinlock_bh_try, __acquires(_T), __releases(*(spinloc
 #define class_spinlock_bh_try_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_bh_try, _T)
 
 DEFINE_LOCK_GUARD_1(spinlock_irqsave, spinlock_t,
-		    spin_lock_irqsave(_T->lock, _T->flags),
-		    spin_unlock_irqrestore(_T->lock, _T->flags),
-		    unsigned long flags)
+		    spin_lock_irq_disable(_T->lock),
+		    spin_unlock_irq_enable(_T->lock))

[Severity: High]
Will this also cause preempt_count corruption and WARN splats in NMI context for guard(spinlock_irqsave)?

Similar to the raw_spinlock_irqsave change above, moving away from the true irqsave mechanism violates the contract that irqsave constructs are entirely context-agnostic.

Quoted 2 lines
include/linux/spinlock.h +0 -0
 DECLARE_LOCK_GUARD_1_ATTRS(spinlock_irqsave, __acquires(_T), __releases(*(spinlock_t **)_T))
 #define class_spinlock_irqsave_constructor(_T) WITH_LOCK_GUARD_1_ATTRS(spinlock_irqsave, _T)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#2 lore raw

Re: [PATCH v3 01/13] preempt: Track NMI nesting to separate per-CPU counter

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Arithmetic overflow of `HARDIRQ_COUNT` carrying into `NMI_MASK` permanently corrupts…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Arithmetic overflow of HARDIRQ_COUNT carrying into NMI_MASK permanently corrupts preempt_count and causes a fatal kernel panic on nested NMI exit. --

commit fea264f43839ad70d356b7c0bdb7708892c51c22
Author: Joel Fernandes <[email protected]>

preempt: Track NMI nesting to separate per-CPU counter

Move NMI nesting tracking from the preempt_count bits to a separate per-CPU counter (nmi_nesting). This frees up the NMI bits in the preempt_count, allowing those bits to be repurposed for other uses.

Quoted 22 lines
include/linux/hardirq.h +6 -3
@@ -102,14 +104,17 @@ void irq_exit_rcu(void);
  */
 
 /*
- * nmi_enter() can nest up to 15 times; see NMI_BITS.
+ * nmi_enter() can nest - nesting is tracked in a per-CPU counter.
  */
 #define __nmi_enter()						\
 	do {							\
 		lockdep_off();					\
 		arch_nmi_enter();				\
-		BUG_ON(in_nmi() == NMI_MASK);			\
-		__preempt_count_add(NMI_OFFSET + HARDIRQ_OFFSET);	\
+		/* Maximum NMI nesting is 15. */		\
+		BUG_ON(__this_cpu_read(nmi_nesting) >= 15);	\
+		__this_cpu_inc(nmi_nesting);			\
+		__preempt_count_add(HARDIRQ_OFFSET);		\
+		preempt_count_set(preempt_count() | NMI_MASK);	\
 	} while (0)

[ ... ]

Quoted 5 lines

#define nmi_enter() \

include/linux/hardirq.h +0 -0
@@ -124,8 +129,12 @@ void irq_exit_rcu(void);
 
 #define __nmi_exit()						\
 	do {							\

include/linux/hardirq.h void irq_exit_rcu(void); · line 140

Quoted 10 lines
include/linux/hardirq.h +5 -1
+		unsigned int nesting;				\
 		BUG_ON(!in_nmi());				\
-		__preempt_count_sub(NMI_OFFSET + HARDIRQ_OFFSET);	\
+		__preempt_count_sub(HARDIRQ_OFFSET);		\
+		nesting = __this_cpu_dec_return(nmi_nesting);	\
+		if (!nesting)					\
+			preempt_count_set(preempt_count() & ~NMI_MASK);	\
 		arch_nmi_exit();				\
 		lockdep_on();					\
 	} while (0)

[Severity: High]
Does this combination of __preempt_count_add() and bitwise OR in __nmi_enter() break arithmetic symmetry when NMIs nest deeply?

Because HARDIRQ_BITS is 4, it can hold a maximum value of 15. The patch explicitly allows NMI nesting up to 15 levels. If an NMI interrupts an active hardirq (where the hardirq count is already 1) and then nests 15 times, the total number of __preempt_count_add(HARDIRQ_OFFSET) operations reaches 16.

This overflows the 4-bit HARDIRQ field and carries a 1 into the NMI_MASK bit (bit 20). The overflow mathematically clears bit 20 and sets bit 21. By then forcing bit 20 back to 1 with a bitwise OR, the state is corrupted.

When the innermost NMI exits, __preempt_count_sub(HARDIRQ_OFFSET) subtracts from this corrupted state, borrowing from bit 20 and clearing it. Because the inner NMI does not explicitly restore NMI_MASK on exit (as nesting is 14), it returns to the outer NMI with bit 20 cleared.

When the outer NMI eventually exits, won't it fail the BUG_ON(!in_nmi()) in __nmi_exit() and trigger a kernel panic?

Also, doesn't this permanently leak a carry bit into the higher fields of preempt_count (e.g., bit 21), which can accumulate and corrupt other states like PREEMPT_NEED_RESCHED?

I note that a later patch in the series (commit "preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS") fixes this for 64-bit architectures by restoring the old algebraic logic, but 32-bit architectures without CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS appear to continue using this flawed bitwise-OR logic and remain vulnerable.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#6 lore raw

Re: [PATCH v3 03/13] preempt: Introduce __preempt_count_{sub, add}_return()

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Operator precedence bug in the commit message usage example. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Operator precedence bug in the commit message usage example.
--

commit 7f1eb356534806694deb9a4e04de28fe3e6692ab
Author: Boqun Feng <[email protected]>

preempt: Introduce __preempt_count_{sub, add}_return()

This commit introduces __preempt_count_add_return() and __preempt_count_sub_return() to track the interrupt disable nesting level while returning the new value of the preempt count. This helps avoid an additional read of preempt_count() on certain architectures.

Quoted 6 lines
    // if it's the first-time increment, then disable the interrupt
    // at hardware level.
    if (new_count & HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET) {
            local_irq_save(flags);
            raw_cpu_write(local_interrupt_disable_state.flags, flags);
    }

[Severity: Low]
Is there an operator precedence issue in this usage example?

In C, the equality operator == has higher precedence than the bitwise AND operator &. This means the expression evaluates as new_count & (HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET). Since the mask does not equal the offset, the equality evaluates to 0, making the entire condition always false.

Should this be written with explicit parentheses like (new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET to prevent readers from copying flawed logic into downstream implementations?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#22 lore raw

Re: [PATCH v3 10/13] preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Unconditional select of `HAS_SEPARATE_PREEMPT_RESCHED_BITS` violates Kconfig dependency on…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Unconditional select of HAS_SEPARATE_PREEMPT_RESCHED_BITS violates Kconfig dependency on PREEMPT_COUNT. --

commit 0d37eeeba0d2e4fb4b795207e44eb2cab20db648
Author: Boqun Feng <[email protected]>

preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS

This commit introduces HAS_SEPARATE_PREEMPT_RESCHED_BITS to allow 64-bit architectures to maintain NMI nesting bits in the 32-bit preempt count, avoiding the need to maintain them outside the same cache line. It also enables this feature for x86_64.

arch/x86/Kconfig config X86 · line 332

Quoted 9 lines
arch/x86/Kconfig +1 -0
index fdaef60b46d65..9a35c3a087573 100644
@@ -329,6 +329,7 @@ config X86
 	select USER_STACKTRACE_SUPPORT
 	select HAVE_ARCH_KCSAN			if X86_64
 	select PROC_PID_ARCH_STATUS		if PROC_FS
+	select HAS_SEPARATE_PREEMPT_RESCHED_BITS		if X86_64

[Severity: Medium]
Will selecting HAS_SEPARATE_PREEMPT_RESCHED_BITS unconditionally for X86_64 cause Kconfig unmet direct dependency warnings if PREEMPT_COUNT is disabled?

Looking at the definition in kernel/Kconfig.preempt, the config symbol HAS_SEPARATE_PREEMPT_RESCHED_BITS explicitly depends on PREEMPT_COUNT:

config HAS_SEPARATE_PREEMPT_RESCHED_BITS

    bool
    depends on PREEMPT_COUNT && 64BIT

Because select bypasses depends on, configuring a kernel where PREEMPT_COUNT is disabled (e.g., PREEMPT_NONE=y with no debug options) might force the target symbol to y. Should this select be conditional on PREEMPT_COUNT?

Quoted 3 lines
arch/x86/Kconfig +0 -0
 	select HAVE_ARCH_NODE_DEV_GROUP		if X86_SGX
 	select FUNCTION_ALIGNMENT_16B		if X86_64 || X86_ALIGNMENT_16
 	select FUNCTION_ALIGNMENT_4B

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#4 lore raw

Re: [PATCH v3 02/13] preempt: Introduce HARDIRQ_DISABLE_BITS

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] NMI nesting inside a hardirq causes HARDIRQ count to overflow into NMI bits, leading to permanent preempt_count corruption and a kernel panic. --

commit 81acab4bc4267e8b9061bcb43c1763c01ce614f2
Author: Boqun Feng <[email protected]>

preempt: Introduce HARDIRQ_DISABLE_BITS

This commit changes the preempt_count() layout to contain an 8-bit HARDIRQ_DISABLE count to track interrupt disabling nested levels. This supports preempt_disable()-like interrupt disabling.

Quoted 4 lines
include/linux/preempt.h +0 -0
index 586f966883255..e2d3079d3f5f1 100644

[ ... ]

Quoted 5 lines
include/linux/preempt.h +0 -1
@@ -31,29 +32,34 @@
  *
  *         PREEMPT_MASK:	0x000000ff
  *         SOFTIRQ_MASK:	0x0000ff00
- *         HARDIRQ_MASK:	0x000f0000

include/linux/preempt.h line 43

Quoted 10 lines
include/linux/preempt.h +4 -1
- *             NMI_MASK:	0x00100000
+ * HARDIRQ_DISABLE_MASK:	0x00ff0000
+ *         HARDIRQ_MASK:	0x0f000000
+ *             NMI_MASK:	0x10000000
  * PREEMPT_NEED_RESCHED:	0x80000000
  */
 #define PREEMPT_BITS	8
 #define SOFTIRQ_BITS	8
+#define HARDIRQ_DISABLE_BITS	8
 #define HARDIRQ_BITS	4

[Severity: High]
This is a pre-existing issue, but does keeping HARDIRQ_BITS at 4 risk a structural overflow into the NMI bits during deep NMI nesting?

Looking at __preempt_count_nmi_enter() in include/linux/hardirq.h, it adds HARDIRQ_OFFSET to preempt_count on every NMI, and explicitly permits up to 15 nested NMIs:

include/linux/hardirq.h:__preempt_count_nmi_enter() {
	__preempt_count_add(HARDIRQ_OFFSET);
	/* Maximum NMI nesting is 15. */
	BUG_ON(__this_cpu_read(nmi_nesting) >= 15);
	...
}

If 15 NMIs nest while the CPU is already inside a hardirq (where the HARDIRQ count is 1), the total count reaches 16.

Since HARDIRQ_BITS is 4, would a value of 16 overflow the 4-bit field into the adjacent NMI field? It appears this could corrupt preempt_count and eventually clear the NMI flags prematurely during exit, leading to a kernel panic.

Quoted 8 lines
include/linux/preempt.h +2 -1
 #define NMI_BITS	1
 
 #define PREEMPT_SHIFT	0
 #define SOFTIRQ_SHIFT	(PREEMPT_SHIFT + PREEMPT_BITS)
-#define HARDIRQ_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_DISABLE_SHIFT	(SOFTIRQ_SHIFT + SOFTIRQ_BITS)
+#define HARDIRQ_SHIFT	(HARDIRQ_DISABLE_SHIFT + HARDIRQ_DISABLE_BITS)
 #define NMI_SHIFT	(HARDIRQ_SHIFT + HARDIRQ_BITS)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#11 lore raw

Re: [PATCH v3 05/13] irq & spin_lock: Add counted interrupt disabling/enabling

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] local_interrupt_enable() fails to invoke deferred softirqs and re-arm hrtimers, leading to…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] local_interrupt_enable() fails to invoke deferred softirqs and re-arm hrtimers, leading to indefinite stalls. --

commit de449b5be29a59d42df6ee590a2de395da7bbacc
Author: Boqun Feng <[email protected]>

irq & spin_lock: Add counted interrupt disabling/enabling

This commit introduces a new set of interrupt disabling APIs:
local_interrupt_disable() and local_interrupt_enable(). These save the interrupt state to a per-cpu variable and use a per-cpu counter to track nesting levels, preventing accidental enablement.

Quoted 5 lines
include/linux/interrupt_rc.h new file +0 -0
new file mode 100644
index 0000000000000..dd4444c613307

[ ... ]

Quoted 12 lines
include/linux/interrupt_rc.h new file +12 -0
+static inline void local_interrupt_enable(void)
+{
+	int new_count;
+
+	new_count = hardirq_disable_exit();
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == 0) {
+		unsigned long flags;
+
+		flags = raw_cpu_read(local_interrupt_disable_state.flags);
+		local_irq_restore(flags);
+		/*

include/linux/interrupt_rc.h line 65

Quoted 10 lines
include/linux/interrupt_rc.h new file +10 -0
+		 * TODO: re-read preempt count can be avoided, but it needs
+		 * should_resched() taking another parameter as the current
+		 * preempt count
+		 */
+#ifdef CONFIG_PREEMPTION
+		if (should_resched(0))
+			__preempt_schedule();
+#endif
+	}
+}

[Severity: High]
When the hardirq disable count drops to 0 here, does this miss checking for deferred softirqs?

Because __irq_exit_rcu() is updated later in this patch to skip invoking softirqs and re-arming hrtimers if hardirq_disable_count() is non-zero, the responsibility appears to shift to this function. Without a check for local_softirq_pending() when the count reaches 0, could softirqs and hrtimers deferred during the vulnerable window be indefinitely stalled until the next hardware interrupt fires?

Quoted 4 lines
kernel/softirq.c +0 -0
index 10af5ed859e73..d1ab1799794ca 100644

[ ... ]

Quoted 22 lines
kernel/softirq.c +10 -1
@@ -728,7 +731,16 @@ static inline void __irq_exit_rcu(void)
 #endif
 	account_hardirq_exit(current);
 	preempt_count_sub(HARDIRQ_OFFSET);
-	if (!in_interrupt() && local_softirq_pending()) {
+	/*
+	 * Interrupts may happen between hardirq_disable_enter() and
+	 * local_irq_save() in local_interrupt_disable(), if irq_exit() invokes
+	 * softirq here, we may have a softirq handler calling
+	 * local_interrupt_disable() but it won't disable the irq because
+	 * hardirq disabling count is already 1, hence we need to prevent
+	 * invoking softirq when a local_interrupt_disable() is ongoing.
+	 */
+	if (!in_interrupt() && !hardirq_disable_count() &&
+	    local_softirq_pending()) {
 		/*
 		 * If we left hrtimers unarmed, make sure to arm them now,
 		 * before enabling interrupts to run SoftIRQ.
kernel/softirq.c +3 -0
 		 */
+		hrtimer_rearm_deferred();
+		invoke_softirq();
+	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#27 lore raw

Re: [PATCH v3 13/13] irq: Optimize reschedule check in local_interrupt_enable()

In reply to Boqun Feng
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] Data race in `__preempt_count_add_return` causes lost wakeups on ARM64 --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Data race in __preempt_count_add_return causes lost wakeups on ARM64 --

commit c3bbe9e483f96a8dad6049a0192dc87491aed263
Author: Boqun Feng <[email protected]>

irq: Optimize reschedule check in local_interrupt_enable()

This patch optimizes local_interrupt_enable() by avoiding a re-read of the preempt count. It modifies __preempt_count_{add,sub}_return() to return unsigned long, allowing it to capture and return the PREEMPT_NEED_RESCHED bit for reschedule checks.

Quoted 4 lines
arch/arm64/include/asm/preempt.h +0 -0
index 0dd8221d1bef7..e9f597d874134 100644

[ ... ]

arch/arm64/include/asm/preempt.h static inline void __preempt_count_sub(int val) · line 62

Quoted 11 lines
arch/arm64/include/asm/preempt.h +2 -3
@@ -55,20 +55,20 @@ static inline void __preempt_count_sub(int val)
 	WRITE_ONCE(current_thread_info()->preempt.count, pc);
 }
 
-static inline int __preempt_count_add_return(int val)
+static inline unsigned long __preempt_count_add_return(int val)
 {
-	u32 pc = READ_ONCE(current_thread_info()->preempt.count);
+	u64 pc = READ_ONCE(current_thread_info()->preempt_count);
 	pc += val;
-	WRITE_ONCE(current_thread_info()->preempt.count, pc);

[Severity: High]
Does this code introduce a regression where the need_resched flag can be clobbered, resulting in a lost wakeup?

On ARM64, the 64-bit preempt_count union contains both the 32-bit count and the 32-bit need_resched flag. Changing this to a non-atomic 64-bit read and write seems like it might race with hardware interrupts.

For instance, when local_interrupt_disable() runs, it calls into __preempt_count_add_return() via hardirq_disable_enter() before actually disabling hardware interrupts:

include/linux/interrupt_rc.h:local_interrupt_disable() {
    ...
    new_count = hardirq_disable_enter();
    if (!new_count) {
        ...
        raw_local_irq_save(flags);
}

Because hardware interrupts are still fully enabled during this operation, if an interrupt fires exactly between the 64-bit READ_ONCE() and WRITE_ONCE(), and the handler wakes up a task (updating need_resched), wouldn't this WRITE_ONCE() restore the stale need_resched value and lose the wakeup?

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author maintainer
#12 lore raw

Re: [PATCH v3 05/13] irq & spin_lock: Add counted interrupt disabling/enabling

In reply to [email protected]
Quoted 42 lines · On Fri, Jun 05, 2026 at 06:01:55AM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] local_interrupt_enable() fails to invoke deferred softirqs and re-arm hrtimers, leading to indefinite stalls. --

commit de449b5be29a59d42df6ee590a2de395da7bbacc
Author: Boqun Feng <[email protected]>

irq & spin_lock: Add counted interrupt disabling/enabling

This commit introduces a new set of interrupt disabling APIs:
local_interrupt_disable() and local_interrupt_enable(). These save the interrupt state to a per-cpu variable and use a per-cpu counter to track nesting levels, preventing accidental enablement.

Quoted 5 lines
include/linux/interrupt_rc.h new file +0 -0
new file mode 100644
index 0000000000000..dd4444c613307

[ ... ]

Quoted 18 lines
include/linux/interrupt_rc.h new file +18 -0
+static inline void local_interrupt_enable(void)
+{
+	int new_count;
+
+	new_count = hardirq_disable_exit();
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == 0) {
+		unsigned long flags;
+
+		flags = raw_cpu_read(local_interrupt_disable_state.flags);
+		local_irq_restore(flags);
+		/*
+		 * TODO: re-read preempt count can be avoided, but it needs
+		 * should_resched() taking another parameter as the current
+		 * preempt count
+		 */
+#ifdef CONFIG_PREEMPTION
+		if (should_resched(0))
Quoted 9 lines

include/linux/interrupt_rc.h line 65

Quoted 4 lines
include/linux/interrupt_rc.h new file +4 -0
+			__preempt_schedule();
+#endif
+	}
+}

[Severity: High]
When the hardirq disable count drops to 0 here, does this miss checking for deferred softirqs?

Yes, but it doesn't have any behavioral difference than a local_irq_enable(), which won't trigger deferred softirqs either.

Regards,
Boqun

Quoted 39 lines

Because __irq_exit_rcu() is updated later in this patch to skip invoking softirqs and re-arming hrtimers if hardirq_disable_count() is non-zero, the responsibility appears to shift to this function. Without a check for local_softirq_pending() when the count reaches 0, could softirqs and hrtimers deferred during the vulnerable window be indefinitely stalled until the next hardware interrupt fires?

Quoted 4 lines
kernel/softirq.c +0 -0
index 10af5ed859e73..d1ab1799794ca 100644

[ ... ]

Quoted 22 lines
kernel/softirq.c +10 -1
@@ -728,7 +731,16 @@ static inline void __irq_exit_rcu(void)
 #endif
 	account_hardirq_exit(current);
 	preempt_count_sub(HARDIRQ_OFFSET);
-	if (!in_interrupt() && local_softirq_pending()) {
+	/*
+	 * Interrupts may happen between hardirq_disable_enter() and
+	 * local_irq_save() in local_interrupt_disable(), if irq_exit() invokes
+	 * softirq here, we may have a softirq handler calling
+	 * local_interrupt_disable() but it won't disable the irq because
+	 * hardirq disabling count is already 1, hence we need to prevent
+	 * invoking softirq when a local_interrupt_disable() is ongoing.
+	 */
+	if (!in_interrupt() && !hardirq_disable_count() &&
+	    local_softirq_pending()) {
 		/*
 		 * If we left hrtimers unarmed, make sure to arm them now,
 		 * before enabling interrupts to run SoftIRQ.
kernel/softirq.c +3 -0
 		 */
+		hrtimer_rearm_deferred();
+		invoke_softirq();
+	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#7 lore raw

Re: [PATCH v3 03/13] preempt: Introduce __preempt_count_{sub, add}_return()

In reply to Boqun Feng
The operator precedence in this example appears incorrect. In C, the equality operator == has higher precedence than the bitwise AND operator &, so this evaluates as:
Quoted 8 lines

preempt: Introduce __preempt_count_{sub, add}_return()

In order to use preempt_count() to tracking the interrupt disable nesting level, __preempt_count_{add,sub}_return() are introduced, as their name suggest, these primitives return the new value of the preempt_count() after changing it. The following example shows the usage of it in local_interrupt_disable():

Quoted 6 lines

// increase the HARDIRQ_DISABLE bit
new_count = __preempt_count_add_return(HARDIRQ_DISABLE_OFFSET);

// if it's the first-time increment, then disable the interrupt // at hardware level.
if (new_count & HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET) {

                                                    ^^

The operator precedence in this example appears incorrect. In C, the equality operator == has higher precedence than the bitwise AND operator &, so this evaluates as:

    new_count & (HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET)

Since the mask does not equal the offset, the equality evaluates to 0, making the entire condition always false.

Should this be written with explicit parentheses to prevent readers from copying flawed logic into downstream implementations?

    if ((new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET) {

This was raised by [email protected] in v3 review:
https://lore.kernel.org/all/[email protected]/

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26998319662

#13 lore raw

Re: [PATCH v3 05/13] irq & spin_lock: Add counted interrupt disabling/enabling

In reply to Boqun Feng
Could this lead to indefinite softirq starvation? When __irq_exit_rcu() skips invoke_softirq() due to hardirq_disable_count() > 0, any scheduled softirqs (timers, RCU callbacks, networking) remain…
Quoted 50 lines
include/linux/interrupt_rc.h new file +44 -0
new file mode 100644
index 000000000000..dd4444c61330
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * include/linux/interrupt_rc.h - refcounted local processor interrupt
+ * management.
+ *
+ * Since the implementation of this API currently depends on
+ * local_irq_save()/local_irq_restore(), we split this into it's own header to
+ * make it easier to include without hitting circular header dependencies.
+ */
+
+#ifndef __LINUX_INTERRUPT_RC_H
+#define __LINUX_INTERRUPT_RC_H
+
+#include <linux/irqflags.h>
+#include <asm/processor.h>
+#ifdef CONFIG_SMP
+#include <asm/smp.h>
+#endif
+
+/* Per-cpu interrupt disabling state for local_interrupt_{disable,enable}() */
+struct interrupt_disable_state {
+	unsigned long flags;
+};
+
+DECLARE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+
+static inline void local_interrupt_disable(void)
+{
+	unsigned long flags;
+	int new_count;
+
+	WARN_ON_ONCE(in_nmi());
+
+	new_count = hardirq_disable_enter();
+
+	/* Interrupts can happen here, but it's OK, see __irq_exit_rcu(). */
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET) {
+		local_irq_save(flags);
+		raw_cpu_write(local_interrupt_disable_state.flags, flags);
+	}
+}
+
+static inline void local_interrupt_enable(void)

include/linux/interrupt_rc.h line 54

Quoted 10 lines
include/linux/interrupt_rc.h new file +10 -0
+{
+	int new_count;
+
+	new_count = hardirq_disable_exit();
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == 0) {
+		unsigned long flags;
+
+		flags = raw_cpu_read(local_interrupt_disable_state.flags);
+		local_irq_restore(flags);

Could this lead to indefinite softirq starvation? When __irq_exit_rcu() skips invoke_softirq() due to hardirq_disable_count() > 0, any scheduled softirqs (timers, RCU callbacks, networking) remain pending. When the outermost critical section ends and local_interrupt_enable() restores hardware interrupts, it doesn't check local_softirq_pending() to flush these deferred softirqs.

Will these pending softirqs stall until another unrelated hardware interrupt fires? In low-activity periods, this could potentially cause RCU stalls or network hangs. This concern was raised by the sashiko bot in both v2 and v3 but remains unaddressed:

https://lore.kernel.org/all/[email protected]/

include/linux/interrupt_rc.h line 62

Quoted 8 lines
include/linux/interrupt_rc.h new file +8 -0
+		/*
+		 * TODO: re-read preempt count can be avoided, but it needs
+		 * should_resched() taking another parameter as the current
+		 * preempt count
+		 */
+#ifdef CONFIG_PREEMPTION
+		if (should_resched(0))
+			__preempt_schedule();

Peter Zijlstra suggested in v2 replacing should_resched(0) with a direct check of new_count for preemption. His suggestion was "can't you simply
write: if (!new_count) __preempt_schedule();" The author acknowledged this in discussion but hasn't implemented it in v3:

https://lore.kernel.org/all/[email protected]/

Is there a reason to keep the more complex should_resched(0) approach, or would the direct check be more appropriate here?

Quoted 5 lines
include/linux/interrupt_rc.h new file +5 -0
+#endif
+	}
+}
+
+#endif /* !__LINUX_INTERRUPT_RC_H */

[ ... ]

Quoted 22 lines
kernel/softirq.c +6 -1
index 10af5ed859e7..d1ab1799794c 100644
@@ -88,6 +88,9 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled);
 EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context);
 #endif
 
+DEFINE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+EXPORT_PER_CPU_SYMBOL_GPL(local_interrupt_disable_state);
+
 DEFINE_PER_CPU(unsigned int, nmi_nesting);
 
 /*
@@ -728,7 +731,16 @@ static inline void __irq_exit_rcu(void)
 #endif
 	account_hardirq_exit(current);
 	preempt_count_sub(HARDIRQ_OFFSET);
-	if (!in_interrupt() && local_softirq_pending()) {
+	/*
+	 * Interrupts may happen between hardirq_disable_enter() and
+	 * local_irq_save() in local_interrupt_disable(), if irq_exit() invokes

kernel/softirq.c static inline void __irq_exit_rcu(void) · line 746

Quoted 10 lines
kernel/softirq.c +7 -0
+	 * softirq here, we may have a softirq handler calling
+	 * local_interrupt_disable() but it won't disable the irq because
+	 * hardirq disabling count is already 1, hence we need to prevent
+	 * invoking softirq when a local_interrupt_disable() is ongoing.
+	 */
+	if (!in_interrupt() && !hardirq_disable_count() &&
+	    local_softirq_pending()) {
 		/*
 		 * If we left hrtimers unarmed, make sure to arm them now,
 		 * before enabling interrupts to run SoftIRQ.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26998319662

#23 lore raw

Re: [PATCH v3 10/13] preempt: Introduce HAS_SEPARATE_PREEMPT_RESCHED_BITS

In reply to Boqun Feng
A subsystem pattern flags this as potentially concerning: selecting HAS_SEPARATE_PREEMPT_RESCHED_BITS with only the X86_64 condition may bypass the PREEMPT_COUNT dependency.

arch/x86/Kconfig config X86 · line 331

Quoted 10 lines
arch/x86/Kconfig +1 -0
index f3f7cb01d69d..bf8288b3d52b 100644
@@ -327,6 +327,7 @@ config X86
 	select USER_STACKTRACE_SUPPORT
 	select HAVE_ARCH_KCSAN			if X86_64
 	select PROC_PID_ARCH_STATUS		if PROC_FS
+	select HAS_SEPARATE_PREEMPT_RESCHED_BITS		if X86_64
 	select HAVE_ARCH_NODE_DEV_GROUP		if X86_SGX

A subsystem pattern flags this as potentially concerning: selecting HAS_SEPARATE_PREEMPT_RESCHED_BITS with only the X86_64 condition may bypass the PREEMPT_COUNT dependency.

Looking at the definition in kernel/Kconfig.preempt, the config symbol HAS_SEPARATE_PREEMPT_RESCHED_BITS explicitly depends on both PREEMPT_COUNT and 64BIT:

kernel/Kconfig.preempt:

    config HAS_SEPARATE_PREEMPT_RESCHED_BITS
        bool
        depends on PREEMPT_COUNT && 64BIT

PREEMPT_COUNT is not always enabled. It gets selected by PREEMPTION, and by a few debug configs (CONFIG_DEBUG_PREEMPT, DEBUG_ATOMIC_SLEEP, PREEMPT_TRACER, etc.), but a standard CONFIG_PREEMPT_NONE=y configuration without any of those debug options will have PREEMPT_COUNT=n.

In such a configuration, the select statement (gated only by X86_64) will force HAS_SEPARATE_PREEMPT_RESCHED_BITS=y while its depends on PREEMPT_COUNT is unmet. This will produce a Kconfig unmet-dependency
warning: "WARNING: unmet direct dependencies detected for HAS_SEPARATE_PREEMPT_RESCHED_BITS / Depends on [n]: PREEMPT_COUNT && 64BIT / Selected by [y]: - X86 [=y]".

Sashiko-bot raised this concern in both v2 and v3 of this patch (message IDs <[email protected]> and <[email protected]>), escalating it from Low to Medium severity:

https://lore.kernel.org/all/[email protected]/

Should this select be conditional on PREEMPT_COUNT? For example:

    select HAS_SEPARATE_PREEMPT_RESCHED_BITS  if X86_64 && PREEMPT_COUNT

[ ... ]

kernel/Kconfig.preempt config PREEMPT_RT_NEEDS_BH_LOCK · line 128

Quoted 12 lines
kernel/Kconfig.preempt +4 -0
index 88c594c6d7fc..35f546a042b1 100644
@@ -122,6 +122,10 @@ config PREEMPT_RT_NEEDS_BH_LOCK
 config PREEMPT_COUNT
        bool
 
+config HAS_SEPARATE_PREEMPT_RESCHED_BITS
+	bool
+	depends on PREEMPT_COUNT && 64BIT
+

This commit fixes a bug but lacks a Fixes: tag. The commit corrects underflow detection logic in preempt_count_sub() by changing from a signed comparison to unsigned wraparound detection. The bug was introduced when commit 7c346d37f86b expanded the preempt_count bit layout by adding 8-bit HARDIRQ_DISABLE_BITS, increasing total bit usage from 21 to 29 bits.

This expansion highlighted the flaw in the existing signed comparison underflow check (val > preempt_count()), which doesn't correctly detect unsigned underflow. The fix properly uses unsigned arithmetic (pc - uval > pc) to detect wraparound.

Should this include:

Fixes 7c346d37f86b ("preempt: Introduce HARDIRQ_DISABLE_BITS")

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26998319662

author maintainer
#14 lore raw

Re: [PATCH v3 05/13] irq & spin_lock: Add counted interrupt disabling/enabling

In reply to [email protected]
Quoted 54 lines · On Fri, Jun 05, 2026 at 06:30:16AM +0000, [email protected] wrote:
Quoted 54 lines
include/linux/interrupt_rc.h new file +48 -0
new file mode 100644
index 000000000000..dd4444c61330
@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * include/linux/interrupt_rc.h - refcounted local processor interrupt
+ * management.
+ *
+ * Since the implementation of this API currently depends on
+ * local_irq_save()/local_irq_restore(), we split this into it's own header to
+ * make it easier to include without hitting circular header dependencies.
+ */
+
+#ifndef __LINUX_INTERRUPT_RC_H
+#define __LINUX_INTERRUPT_RC_H
+
+#include <linux/irqflags.h>
+#include <asm/processor.h>
+#ifdef CONFIG_SMP
+#include <asm/smp.h>
+#endif
+
+/* Per-cpu interrupt disabling state for local_interrupt_{disable,enable}() */
+struct interrupt_disable_state {
+	unsigned long flags;
+};
+
+DECLARE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+
+static inline void local_interrupt_disable(void)
+{
+	unsigned long flags;
+	int new_count;
+
+	WARN_ON_ONCE(in_nmi());
+
+	new_count = hardirq_disable_enter();
+
+	/* Interrupts can happen here, but it's OK, see __irq_exit_rcu(). */
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET) {
+		local_irq_save(flags);
+		raw_cpu_write(local_interrupt_disable_state.flags, flags);
+	}
+}
+
+static inline void local_interrupt_enable(void)
+{
+	int new_count;
+
+	new_count = hardirq_disable_exit();
Quoted 8 lines

include/linux/interrupt_rc.h line 54

Quoted 6 lines
include/linux/interrupt_rc.h new file +6 -0
+
+	if ((new_count & HARDIRQ_DISABLE_MASK) == 0) {
+		unsigned long flags;
+
+		flags = raw_cpu_read(local_interrupt_disable_state.flags);
+		local_irq_restore(flags);

Could this lead to indefinite softirq starvation? When __irq_exit_rcu()

Yes and no. There is no behavioral difference between here and local_irq_enable(), neither will trigger softirqs.

Quoted 27 lines

skips invoke_softirq() due to hardirq_disable_count() > 0, any scheduled softirqs (timers, RCU callbacks, networking) remain pending. When the outermost critical section ends and local_interrupt_enable() restores hardware interrupts, it doesn't check local_softirq_pending() to flush these deferred softirqs.

Will these pending softirqs stall until another unrelated hardware interrupt fires? In low-activity periods, this could potentially cause RCU stalls or network hangs. This concern was raised by the sashiko bot in both v2 and v3 but remains unaddressed:

https://lore.kernel.org/all/[email protected]/

include/linux/interrupt_rc.h line 62

Quoted 8 lines
include/linux/interrupt_rc.h new file +8 -0
+		/*
+		 * TODO: re-read preempt count can be avoided, but it needs
+		 * should_resched() taking another parameter as the current
+		 * preempt count
+		 */
+#ifdef CONFIG_PREEMPTION
+		if (should_resched(0))
+			__preempt_schedule();

Peter Zijlstra suggested in v2 replacing should_resched(0) with a direct check of new_count for preemption. His suggestion was "can't you simply
write: if (!new_count) __preempt_schedule();" The author acknowledged this in discussion but hasn't implemented it in v3:

Quoted 5 lines

https://lore.kernel.org/all/[email protected]/

Is there a reason to keep the more complex should_resched(0) approach, or would the direct check be more appropriate here?

I have an optimization/cleanup patch in patch #13.

Regards,
Boqun

Quoted 47 lines
Quoted 5 lines
include/linux/interrupt_rc.h new file +5 -0
+#endif
+	}
+}
+
+#endif /* !__LINUX_INTERRUPT_RC_H */

[ ... ]

Quoted 22 lines
kernel/softirq.c +6 -1
index 10af5ed859e7..d1ab1799794c 100644
@@ -88,6 +88,9 @@ EXPORT_PER_CPU_SYMBOL_GPL(hardirqs_enabled);
 EXPORT_PER_CPU_SYMBOL_GPL(hardirq_context);
 #endif
 
+DEFINE_PER_CPU(struct interrupt_disable_state, local_interrupt_disable_state);
+EXPORT_PER_CPU_SYMBOL_GPL(local_interrupt_disable_state);
+
 DEFINE_PER_CPU(unsigned int, nmi_nesting);
 
 /*
@@ -728,7 +731,16 @@ static inline void __irq_exit_rcu(void)
 #endif
 	account_hardirq_exit(current);
 	preempt_count_sub(HARDIRQ_OFFSET);
-	if (!in_interrupt() && local_softirq_pending()) {
+	/*
+	 * Interrupts may happen between hardirq_disable_enter() and
+	 * local_irq_save() in local_interrupt_disable(), if irq_exit() invokes

kernel/softirq.c static inline void __irq_exit_rcu(void) · line 746

Quoted 10 lines
kernel/softirq.c +7 -0
+	 * softirq here, we may have a softirq handler calling
+	 * local_interrupt_disable() but it won't disable the irq because
+	 * hardirq disabling count is already 1, hence we need to prevent
+	 * invoking softirq when a local_interrupt_disable() is ongoing.
+	 */
+	if (!in_interrupt() && !hardirq_disable_count() &&
+	    local_softirq_pending()) {
 		/*
 		 * If we left hrtimers unarmed, make sure to arm them now,
 		 * before enabling interrupts to run SoftIRQ.

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26998319662

author maintainer
#8 lore raw

Re: [PATCH v3 03/13] preempt: Introduce __preempt_count_{sub, add}_return()

In reply to [email protected]
Quoted 20 lines · On Fri, Jun 05, 2026 at 06:30:14AM +0000, [email protected] wrote:
Quoted 8 lines

preempt: Introduce __preempt_count_{sub, add}_return()

In order to use preempt_count() to tracking the interrupt disable nesting level, __preempt_count_{add,sub}_return() are introduced, as their name suggest, these primitives return the new value of the preempt_count() after changing it. The following example shows the usage of it in local_interrupt_disable():

Quoted 6 lines

// increase the HARDIRQ_DISABLE bit
new_count = __preempt_count_add_return(HARDIRQ_DISABLE_OFFSET);

// if it's the first-time increment, then disable the interrupt // at hardware level.
if (new_count & HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET) {

                                                    ^^

The operator precedence in this example appears incorrect. In C, the equality operator == has higher precedence than the bitwise AND operator &, so this evaluates as:

Quoted 8 lines
    new_count & (HARDIRQ_DISABLE_MASK == HARDIRQ_DISABLE_OFFSET)

Since the mask does not equal the offset, the equality evaluates to 0, making the entire condition always false.

Should this be written with explicit parentheses to prevent readers from copying flawed logic into downstream implementations?

Will fix this but this code is in commit log rather than real code.

Regards,
Boqun

Quoted 11 lines
    if ((new_count & HARDIRQ_DISABLE_MASK) == HARDIRQ_DISABLE_OFFSET) {

This was raised by [email protected] in v3 review:
https://lore.kernel.org/all/[email protected]/

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/26998319662