Skip to contentSkip to conversation

Hazard pointer updates

PATCH Superseded Mathieu Desnoyers 7 participants 33 messages Sep 27 – Oct 6

Subsystems (7)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Mathieu Desnoyers

author reviewer
#0 lore raw

cover Hazard pointer updates

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
 Documentation/RCU/rcu_dereference.rst |  38 +++++++-
 include/linux/compiler.h              |  63 ++++++++++++
 include/linux/hazptr.h                |  47 +++++----
 kernel/hazptr.c                       | 135 +++++++++++++++-----------
 4 files changed, 203 insertions(+), 80 deletions(-)
Signature · 1 line
2.43.0
author reviewer
#1 lore raw

PATCH 1/4 hazptr: Fix two-phase hazptr_synchronize race with detach

Boqun Feng pointed out that a detach happening concurrently with hazptr_synchronize can miss a slot. Indeed, scanning the per-CPU slots needs to be done *before* scanning the overflow lists. Fix the implementation accordingly.

---
Changes since v0:
- Load the new overflow list phase word in "hazptr_chain_backup_slot".
- Rename the lock to hazptr_phase_lock to make it clear that it protects both the wildcard and the overflow list phases.

---
 kernel/hazptr.c | 50 +++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 40 insertions(+), 10 deletions(-)
kernel/hazptr.c +40 -10
index d3d1050d92cf..13faa5ba7677 100644
@@ -13,6 +13,8 @@
 #include <linux/list.h>
 #include <linux/export.h>
 
+static DEFINE_MUTEX(hazptr_phase_lock);	/* Protect the wildcard and list phase flip. */
+
 /*
  * The current hazard pointer wildcard. Flips between 1UL and 2UL to guarantee
  * hazptr_synchronize forward progress even with a steady stream of readers.
@@ -20,10 +22,12 @@
  * This also affects the overflow list selection: the current list used by
  * readers is array[(unsigned long) hazptr_wildcard - 1].
  */
-static DEFINE_MUTEX(hazptr_wildcard_lock);	/* Protect the wildcard flip. */
 void *hazptr_wildcard = (void *) 1UL;
 EXPORT_SYMBOL_GPL(hazptr_wildcard);
 
+/* The current overflow list phase. */
+static unsigned int hazptr_overflow_list_phase;
+
 struct hazptr_overflow_list {
 	raw_spinlock_t lock;		/* Lock protecting overflow list and list generation. */
 	struct hlist_head head;		/* Overflow list head. */
@@ -53,6 +57,12 @@ void *flip_wildcard(void *wildcard)
 	return ((unsigned long) wildcard == 1UL) ? (void *) 2UL : (void *) 1UL;
 }
 
+static
+unsigned int flip_list_phase(unsigned int phase)
+{
+	return 1 - phase;
+}
+
 static
 bool is_wildcard(void *addr)
 {
@@ -178,15 +188,12 @@ void hazptr_synchronize_cpu_slots(int cpu, void *addr, void *scan_wildcard)
 }
 
 static
-void hazptr_scan_period(void *addr, void *scan_wildcard)
+void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
 {
-	unsigned int scan_idx = (unsigned long) scan_wildcard - 1;
 	int cpu;
 
 	/* Scan all CPUs slots. */
 	for_each_possible_cpu(cpu) {
-		struct hazptr_overflow_list_flip *overflow_list_flip = per_cpu_ptr(&percpu_overflow_list_flip, cpu);
-
 		/*
 		 * Scan CPU slots.
 		 * Forward progress against recurring wildcards is guaranteed
@@ -199,6 +206,17 @@ void hazptr_scan_period(void *addr, void *scan_wildcard)
 		 * to acquire that same hazard pointer value.
 		 */
 		hazptr_synchronize_cpu_slots(cpu, addr, scan_wildcard);
+	}
+}
+
+static
+void hazptr_scan_overflow_list_period(void *addr, unsigned int scan_idx)
+{
+	int cpu;
+
+	/* Scan all CPUs overflow lists. */
+	for_each_possible_cpu(cpu) {
+		struct hazptr_overflow_list_flip *overflow_list_flip = per_cpu_ptr(&percpu_overflow_list_flip, cpu);
 
 		/*
 		 * Scan backup slots in percpu overflow lists.
@@ -218,6 +236,7 @@ void hazptr_scan_period(void *addr, void *scan_wildcard)
  */
 void hazptr_synchronize(void *addr)
 {
+	unsigned int scan_list_phase;
 	void *scan_wildcard;
 
 	/*
@@ -235,18 +254,29 @@ void hazptr_synchronize(void *addr)
 	/* Memory ordering: Store A before Load B. */
 	smp_mb();
 
-	guard(mutex)(&hazptr_wildcard_lock);
+	guard(mutex)(&hazptr_phase_lock);
+
+	/* Scan per-CPU slots. */
 	scan_wildcard = flip_wildcard(hazptr_wildcard);
-	hazptr_scan_period(addr, scan_wildcard);
-	WRITE_ONCE(hazptr_wildcard, scan_wildcard);	/* Flip the current wildcard. */
-	hazptr_scan_period(addr, flip_wildcard(scan_wildcard));
+	hazptr_scan_cpu_slots_period(addr, scan_wildcard);
+	WRITE_ONCE(hazptr_wildcard, scan_wildcard);			/* Flip the current wildcard. */
+	hazptr_scan_cpu_slots_period(addr, flip_wildcard(scan_wildcard));
+
+	/*
+	 * Scan overflow lists *after* scanning per-CPU slots. See
+	 * hazptr_promote_to_backup_slot() for scan ordering requirement.
+	 */
+	scan_list_phase = flip_list_phase(hazptr_overflow_list_phase);
+	hazptr_scan_overflow_list_period(addr, scan_list_phase);
+	WRITE_ONCE(hazptr_overflow_list_phase, scan_list_phase);	/* Flip the current list phase. */
+	hazptr_scan_overflow_list_period(addr, flip_list_phase(scan_list_phase));
 }
 EXPORT_SYMBOL_GPL(hazptr_synchronize);
 
 struct hazptr_slot *hazptr_chain_backup_slot(struct hazptr_ctx *ctx)
 {
 	struct hazptr_overflow_list_flip *overflow_list_flip = this_cpu_ptr(&percpu_overflow_list_flip);
-	unsigned int list_idx = (unsigned long) READ_ONCE(hazptr_wildcard) - 1;
+	unsigned int list_idx = READ_ONCE(hazptr_overflow_list_phase);
 	struct hazptr_overflow_list *overflow_list = &overflow_list_flip->array[list_idx];
 	struct hazptr_slot *slot = &ctx->backup_slot.slot;
 
Signature · 1 line
2.43.0
author reviewer
#2 lore raw

PATCH 2/4 compiler.h: Introduce ptr_eq() to preserve address dependency

In reply to Mathieu Desnoyers

Compiler CSE and SSA GVN optimizations can cause the address dependency of addresses returned by rcu_dereference to be lost when comparing those pointers with either constants or previously loaded pointers.

Introduce ptr_eq() to compare two addresses while preserving the address dependencies for later use of the address. It should be used when comparing an address returned by rcu_dereference().

This is needed to prevent the compiler CSE and SSA GVN optimizations from using @a (or @b) in places where the source refers to @b (or @a) based on the fact that after the comparison, the two are known to be equal, which does not preserve address dependencies and allows the following misordering speculations:

- If @b is a constant, the compiler can issue the loads which depend on @a before loading @a.
- If @b is a register populated by a prior load, weakly-ordered CPUs can speculate loads which depend on @a before loading @a.

The same logic applies with @a and @b swapped.

Cc Greg Kroah-Hartman <[email protected]>
Cc Sebastian Andrzej Siewior <[email protected]>
Cc "Paul E. McKenney" <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Alan Stern <[email protected]>
Cc John Stultz <[email protected]>
Cc Neeraj Upadhyay <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Frederic Weisbecker <[email protected]>
Cc Joel Fernandes <[email protected]>
Cc Josh Triplett <[email protected]>
Cc Uladzislau Rezki <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Lai Jiangshan <[email protected]>
Cc Zqiang <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Waiman Long <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Gary Guo <[email protected]>
Cc Jonas Oberhauser <[email protected]>
Cc Nikita Popov <[email protected]>

---
Changes since v0:
- Include feedback from Alan Stern.

---
 include/linux/compiler.h | 63 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 63 insertions(+)
include/linux/compiler.h +63 -0
index 70cb31d60538..0a8c8e53cdad 100644
@@ -166,6 +166,69 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,
 	__PASTE(name,						\
 	__PASTE(_, __COUNTER__)))
 
+/*
+ * Compare two addresses while preserving the address dependencies for
+ * later use of the address. It should be used when comparing an address
+ * returned by rcu_dereference().
+ *
+ * This is needed to prevent the compiler CSE and SSA GVN optimizations
+ * from using @a (or @b) in places where the source refers to @b (or @a)
+ * based on the fact that after the comparison, the two are known to be
+ * equal, which does not preserve address dependencies and allows the
+ * following misordering speculations:
+ *
+ * - If @b is a constant, the compiler can issue the loads which depend
+ *   on @a before loading @a.
+ * - If @b is a register populated by a prior load, weakly-ordered
+ *   CPUs can speculate loads which depend on @a before loading @a.
+ *
+ * The same logic applies with @a and @b swapped.
+ *
+ * Return value: true if pointers are equal, false otherwise.
+ *
+ * The compiler barrier() is ineffective at fixing this issue. It does
+ * not prevent the compiler CSE from losing the address dependency:
+ *
+ * int fct_2_volatile_barriers(void)
+ * {
+ *     int *a, *b;
+ *
+ *     do {
+ *         a = READ_ONCE(p);
+ *         asm volatile ("" : : : "memory");
+ *         b = READ_ONCE(p);
+ *     } while (a != b);
+ *     asm volatile ("" : : : "memory");  <-- barrier()
+ *     return *b;
+ * }
+ *
+ * With gcc 14.2 (arm64):
+ *
+ * fct_2_volatile_barriers:
+ *         adrp    x0, .LANCHOR0
+ *         add     x0, x0, :lo12:.LANCHOR0
+ * .L2:
+ *         ldr     x1, [x0]  <-- x1 populated by first load.
+ *         ldr     x2, [x0]
+ *         cmp     x1, x2
+ *         bne     .L2
+ *         ldr     w0, [x1]  <-- x1 is used for access which should depend on b.
+ *         ret
+ *
+ * On weakly-ordered architectures, this lets CPU speculation use the
+ * result from the first load to speculate "ldr w0, [x1]" before
+ * "ldr x2, [x0]".
+ * Based on the RCU documentation, the control dependency does not
+ * prevent the CPU from speculating loads.
+ */
+static __always_inline
+int ptr_eq(const volatile void *a, const volatile void *b)
+{
+	OPTIMIZER_HIDE_VAR(a);
+	OPTIMIZER_HIDE_VAR(b);
+	return a == b;
+}
+
 /**
  * data_race - mark an expression as containing intentional data races
  *
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH hazptr 2/4] compiler.h: Introduce ptr_eq() to preserve address dependency

include/linux/compiler.h void ftrace_likely_update(struct ftrace_likely_data *f, int val, · line 230

Quoted 8 lines · Mathieu Desnoyers
include/linux/compiler.h +7 -0
+static __always_inline
+int ptr_eq(const volatile void *a, const volatile void *b)
+{
+       OPTIMIZER_HIDE_VAR(a);
+       OPTIMIZER_HIDE_VAR(b);
+       return a == b;
+}

I had to think about why I hate this so much.

It's probably entirely senseless, but this just rubs me the wrong way. Those OPTIMIZER_HIDE_VAR() statements are hiding the wrong thing. They are telling the compiler to treat valid information (the pointers) as if they had changed, so then the compiler will have to just reload those pointers when they are used later (and "used later" is part of the whole *point* of this, after all).

But it was never the pointer values that needed hiding from the compiler. It's always just the comparison. And while the "optimal" thing would be to just do something like

static __always_inline bool ptr_eq(const volatile void *a, const
volatile void *b)

  {
        bool ret;
        asm("cmpq %0,%1":"=@ccz" (ret):"r" (a),"r"(b))
        return ret;

}

that is an architecture-specific thing - and then have that OPTIMIZER_HIDE_VAR() available as a fallback.

I don't know if it's really worth it, but I really do despise that "hide the wrong values" thing that generates two new values just to compare them and throw them away, and adds register pressure for no good reason.

Linus

author reviewer
#4 lore raw

Re: [PATCH hazptr 2/4] compiler.h: Introduce ptr_eq() to preserve address dependency

Quoted 32 lines · Linus Torvalds

include/linux/compiler.h void ftrace_likely_update(struct ftrace_likely_data *f, int val, · line 230

Quoted 8 lines · Mathieu Desnoyers
include/linux/compiler.h +7 -0
+static __always_inline
+int ptr_eq(const volatile void *a, const volatile void *b)
+{
+       OPTIMIZER_HIDE_VAR(a);
+       OPTIMIZER_HIDE_VAR(b);
+       return a == b;
+}

I had to think about why I hate this so much.

It's probably entirely senseless, but this just rubs me the wrong way. Those OPTIMIZER_HIDE_VAR() statements are hiding the wrong thing. They are telling the compiler to treat valid information (the pointers) as if they had changed, so then the compiler will have to just reload those pointers when they are used later (and "used later" is part of the whole *point* of this, after all).

But it was never the pointer values that needed hiding from the compiler. It's always just the comparison. And while the "optimal" thing would be to just do something like

static __always_inline bool ptr_eq(const volatile void *a, const
volatile void *b)

   {
         bool ret;
         asm("cmpq %0,%1":"=@ccz" (ret):"r" (a),"r"(b))
         return ret;

}

Quoted 7 lines

that is an architecture-specific thing - and then have that OPTIMIZER_HIDE_VAR() available as a fallback.

I don't know if it's really worth it, but I really do despise that "hide the wrong values" thing that generates two new values just to compare them and throw them away, and adds register pressure for no good reason.

I agree that doing it in asm would generate better code. Also, I've been told that clang now preserves the address dependency in this scenario, so perhaps we'd want to use preprocessor conditionals to select how to implement ptr_eq based on:

- architecture (allowing asm implementation overrides),
- compiler (e.g. if compiler is clang >= version X, just do a plain comparison). Likewise for gcc if it ever decides to fix this behavior.

I think this "hide var" hack is a fallback which can be used as a starting point, and then we can specialize based on architecture and compiler.

Or do you prefer this in a different order ?

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#5 lore raw

Re: [PATCH hazptr 2/4] compiler.h: Introduce ptr_eq() to preserve address dependency

Quoted 11 lines · Mathieu Desnoyers

I agree that doing it in asm would generate better code. Also, I've been told that clang now preserves the address dependency in this scenario, so perhaps we'd want to use preprocessor conditionals to select how to implement ptr_eq based on:

- architecture (allowing asm implementation overrides),
- compiler (e.g. if compiler is clang >= version X, just do a plain comparison). Likewise for gcc if it ever decides to fix this behavior.

Quoted 5 lines

I think this "hide var" hack is a fallback which can be used as a starting point, and then we can specialize based on architecture and compiler.

Or do you prefer this in a different order ?

Oh, if there's some sane way to tell that the compiler already honors address dependencies, then that should be done first and the whole thing should just become a simple

(a) == (b)

for that situation - allowing the compiler then the freedom to do whatever (which can involve not using a register at all, but a compare to memory, or whatever - the compiler might have reasons to avoid the 'cmp' and use another sequence entirely)

Then a "if we have an architecture fallback".

And then that OPTIMIZER_HIDE_VAR() thing as a last fallback.

Linus

author reviewer
#6 lore raw

Re: [PATCH hazptr 2/4] compiler.h: Introduce ptr_eq() to preserve address dependency

Quoted 23 lines · Linus Torvalds
Quoted 11 lines · Mathieu Desnoyers

I agree that doing it in asm would generate better code. Also, I've been told that clang now preserves the address dependency in this scenario, so perhaps we'd want to use preprocessor conditionals to select how to implement ptr_eq based on:

- architecture (allowing asm implementation overrides),
- compiler (e.g. if compiler is clang >= version X, just do a plain comparison). Likewise for gcc if it ever decides to fix this behavior.

Quoted 5 lines

I think this "hide var" hack is a fallback which can be used as a starting point, and then we can specialize based on architecture and compiler.

Or do you prefer this in a different order ?

Oh, if there's some sane way to tell that the compiler already honors address dependencies, then that should be done first and the whole thing should just become a simple

Quoted 6 lines

(a) == (b)

for that situation - allowing the compiler then the freedom to do whatever (which can involve not using a register at all, but a compare to memory, or whatever - the compiler might have reasons to avoid the 'cmp' and use another sequence entirely)

For the records, here is the relevant compiler discussion:

https://github.com/llvm/llvm-project/issues/34577

and it seems like they still have unfixed scenarios, which may or may not affect the hazptr use-case:

https://github.com/llvm/llvm-project/issues/220206

Considering this, I would not be inclined to jump to the conclusion that using the compiler compare for hazptr acquire load/test/reload is safe today without a careful analysis.

Quoted 4 lines

Then a "if we have an architecture fallback".

And then that OPTIMIZER_HIDE_VAR() thing as a last fallback.

OK,

Thanks!

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#7 lore raw

Re: [PATCH hazptr 2/4] compiler.h: Introduce ptr_eq() to preserve address dependency

Quoted 35 lines · Mathieu Desnoyers
Quoted 23 lines · Linus Torvalds
Quoted 11 lines · Mathieu Desnoyers

I agree that doing it in asm would generate better code. Also, I've been told that clang now preserves the address dependency in this scenario, so perhaps we'd want to use preprocessor conditionals to select how to implement ptr_eq based on:

- architecture (allowing asm implementation overrides),
- compiler (e.g. if compiler is clang >= version X, just do a plain comparison). Likewise for gcc if it ever decides to fix this behavior.

Quoted 5 lines

I think this "hide var" hack is a fallback which can be used as a starting point, and then we can specialize based on architecture and compiler.

Or do you prefer this in a different order ?

Oh, if there's some sane way to tell that the compiler already honors address dependencies, then that should be done first and the whole thing should just become a simple

Quoted 6 lines

(a) == (b)

for that situation - allowing the compiler then the freedom to do whatever (which can involve not using a register at all, but a compare to memory, or whatever - the compiler might have reasons to avoid the 'cmp' and use another sequence entirely)

For the records, here is the relevant compiler discussion:

https://github.com/llvm/llvm-project/issues/34577

Quoted 8 lines

and it seems like they still have unfixed scenarios, which may or may not affect the hazptr use-case:

https://github.com/llvm/llvm-project/issues/220206

Considering this, I would not be inclined to jump to the conclusion that using the compiler compare for hazptr acquire load/test/reload is safe today without a careful analysis.

Out of the existing cases I think the only problematic one for hazptr is the comparison against costant global. Which isn't going to be a problem for users that don't depend on a fixed adress.

But it might be a problem for the lockdep case.

If we use inline asm for ptr_eq I think there's very little optimization potentials left for compilers, so I think unconditionally using asm would be fine.

Best,
Gary

author reviewer
#8 lore raw

PATCH 3/4 Documentation: RCU: Refer to ptr_eq()

In reply to Mathieu Desnoyers

Refer to ptr_eq() in the rcu_dereference() documentation.

ptr_eq() is a mechanism that preserves address dependencies when comparing pointers, and should be favored when comparing a pointer obtained from rcu_dereference() against another pointer.

Cc Greg Kroah-Hartman <[email protected]>
Cc Sebastian Andrzej Siewior <[email protected]>
Cc "Paul E. McKenney" <[email protected]>
Cc Will Deacon <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Alan Stern <[email protected]>
Cc John Stultz <[email protected]>
Cc Neeraj Upadhyay <[email protected]>
Cc Linus Torvalds <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Frederic Weisbecker <[email protected]>
Cc Joel Fernandes <[email protected]>
Cc Josh Triplett <[email protected]>
Cc Uladzislau Rezki <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Lai Jiangshan <[email protected]>
Cc Zqiang <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Waiman Long <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Gary Guo <[email protected]>
Cc Jonas Oberhauser <[email protected]>
Cc Nikita Popov <[email protected]>

---
Changes since v1:
- Include feedback from Paul E. McKenney.

Changes since v0:
- Include feedback from Alan Stern.

---
 Documentation/RCU/rcu_dereference.rst | 38 +++++++++++++++++++++++----
 1 file changed, 33 insertions(+), 5 deletions(-)
Documentation/RCU/rcu_dereference.rst +33 -5
index 5bc3785ebfc2..85b5f79ebf14 100644
@@ -104,11 +104,12 @@ readers working properly:
 	after such branches, but can speculate loads, which can again
 	result in misordering bugs.
 
--	Be very careful about comparing pointers obtained from
-	rcu_dereference() against non-NULL values.  As Linus Torvalds
-	explained, if the two pointers are equal, the compiler could
-	substitute the pointer you are comparing against for the pointer
-	obtained from rcu_dereference().  For example::
+-	Use operations that preserve address dependencies (such as
+	"ptr_eq()") to compare pointers obtained from rcu_dereference()
+	against non-NULL pointers. As Linus Torvalds explained, if the
+	two pointers are equal, the compiler could substitute the
+	pointer you are comparing against for the pointer obtained from
+	rcu_dereference().  For example::
 
 		p = rcu_dereference(gp);
 		if (p == &default_struct)
@@ -125,6 +126,29 @@ readers working properly:
 	On ARM and Power hardware, the load from "default_struct.a"
 	can now be speculated, such that it might happen before the
 	rcu_dereference().  This could result in bugs due to misordering.
+	Performing the comparison with "ptr_eq()" ensures the compiler
+	does not perform such transformation.
+
+	If the comparison is against another pointer, the compiler is
+	allowed to use either pointer for the following accesses, which
+	loses the address dependency and allows weakly-ordered
+	architectures such as ARM and PowerPC to speculate the
+	address-dependent load before rcu_dereference().  For example::
+
+		p1 = READ_ONCE(gp);
+		p2 = rcu_dereference(gp);
+		if (p1 == p2)  /* BUGGY!!! */
+			do_default(p2->a);
+
+	The compiler can use p1->a rather than p2->a, destroying the
+	address dependency.  Performing the comparison with "ptr_eq()"
+	ensures the compiler preserves the address dependencies.
+	Corrected code::
+
+		p1 = READ_ONCE(gp);
+		p2 = rcu_dereference(gp);
+		if (ptr_eq(p1, p2))
+			do_default(p2->a);
 
 	However, comparisons are OK in the following cases:
 
@@ -204,6 +228,10 @@ readers working properly:
 		comparison will provide exactly the information that the
 		compiler needs to deduce the value of the pointer.
 
+	When in doubt, use operations that preserve address dependencies
+	(such as "ptr_eq()") to compare pointers obtained from
+	rcu_dereference() against non-NULL pointers.
+
 -	Disable any value-speculation optimizations that your compiler
 	might provide, especially if you are making use of feedback-based
 	optimizations that take data collected from prior runs.  Such
Signature · 1 line
2.43.0
author reviewer
#9 lore raw

PATCH 4/4 hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

---
 include/linux/hazptr.h |  47 +++++++++++--------
 kernel/hazptr.c        | 103 ++++++++++++++++++++---------------------
 2 files changed, 76 insertions(+), 74 deletions(-)
include/linux/hazptr.h +27 -20
index d1670121947a..fcf017ca2255 100644
@@ -29,9 +29,6 @@
 /* 4 slots (each sizeof(hazptr_slot_item)) fit in a single 64-byte cache line. */
 #define NR_HAZPTR_PERCPU_SLOTS	4
 
-/* The current hazard pointer wildcard. */
-extern void *hazptr_wildcard;
-
 /*
  * Hazard pointer slot.
  */
@@ -190,6 +187,31 @@ void hazptr_note_context_switch(void)
 	}
 }
 
+/* Try hazard pointer protection. */
+static inline
+void *__hazptr_try_acquire(struct hazptr_ctx *ctx, void * const *addr_p, struct hazptr_slot *slot)
+{
+	void *early_addr, *addr;
+
+	if (unlikely(slot->addr))
+		return NULL;
+	early_addr = READ_ONCE(*addr_p);	/* Early load. */
+	WRITE_ONCE(slot->addr, early_addr);	/* Store B */
+	/* Memory ordering: Store B before Load A. */
+	smp_mb();
+	addr = READ_ONCE(*addr_p);		/* Load A */
+	/*
+	 * Validate that address did not change between Early load and Load A.
+	 * Use ptr_eq() to make sure that result from Load A is returned to the
+	 * caller to preserve address dependency.
+	 */
+	if (unlikely(!ptr_eq(addr, early_addr))) {
+		WRITE_ONCE(slot->addr, NULL);
+		return NULL;
+	}
+	return addr;
+}
+
 /**
  * hazptr_acquire - Load pointer at address and protect with hazard pointer.
  *
@@ -245,24 +267,9 @@ void *hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 	ctx->acquire_cpu = smp_processor_id();
 	ctx->acquire_caller = _THIS_IP_;
 #endif
-	if (unlikely(slot->addr))
+	addr = __hazptr_try_acquire(ctx, addr_p, slot);
+	if (unlikely(!addr))
 		return __hazptr_acquire(ctx, addr_p);
-	WRITE_ONCE(slot->addr, READ_ONCE(hazptr_wildcard));	/* Store B */
-
-	/* Memory ordering: Store B before Load A. */
-	smp_mb();
-
-	/*
-	 * Load @addr_p after storing wildcard to the hazard pointer slot.
-	 */
-	addr = READ_ONCE(*addr_p);	/* Load A */
-
-	/*
-	 * We don't care about ordering of Store C. It will simply
-	 * replace the wildcard by a more specific address. If addr is
-	 * NULL, we simply store NULL into the slot.
-	 */
-	WRITE_ONCE(slot->addr, addr);	/* Store C */
 	slot_item->ctx.ctx = ctx;
 	ctx->slot = slot;
 	return addr;
kernel/hazptr.c +49 -54

206 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#10 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 16 lines · Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

Quoted 9 lines

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Ok, I was missing something, but I think it's better to call it out. Wildcards can only exist in the overflow lists when the context is not preemptible. In other words, there won't be a preempted readers blocking the synchronize_hazptr() with a wilcard in the overflow list.

So no more design trade-off question from me :)

Regards,
Boqun

Quoted 263 lines
---
 include/linux/hazptr.h |  47 +++++++++++--------
 kernel/hazptr.c        | 103 ++++++++++++++++++++---------------------
 2 files changed, 76 insertions(+), 74 deletions(-)
include/linux/hazptr.h +27 -20
index d1670121947a..fcf017ca2255 100644
@@ -29,9 +29,6 @@
 /* 4 slots (each sizeof(hazptr_slot_item)) fit in a single 64-byte cache line. */
 #define NR_HAZPTR_PERCPU_SLOTS	4
 
-/* The current hazard pointer wildcard. */
-extern void *hazptr_wildcard;
-
 /*
  * Hazard pointer slot.
  */
@@ -190,6 +187,31 @@ void hazptr_note_context_switch(void)
 	}
 }
 
+/* Try hazard pointer protection. */
+static inline
+void *__hazptr_try_acquire(struct hazptr_ctx *ctx, void * const *addr_p, struct hazptr_slot *slot)
+{
+	void *early_addr, *addr;
+
+	if (unlikely(slot->addr))
+		return NULL;
+	early_addr = READ_ONCE(*addr_p);	/* Early load. */
+	WRITE_ONCE(slot->addr, early_addr);	/* Store B */
+	/* Memory ordering: Store B before Load A. */
+	smp_mb();
+	addr = READ_ONCE(*addr_p);		/* Load A */
+	/*
+	 * Validate that address did not change between Early load and Load A.
+	 * Use ptr_eq() to make sure that result from Load A is returned to the
+	 * caller to preserve address dependency.
+	 */
+	if (unlikely(!ptr_eq(addr, early_addr))) {
+		WRITE_ONCE(slot->addr, NULL);
+		return NULL;
+	}
+	return addr;
+}
+
 /**
  * hazptr_acquire - Load pointer at address and protect with hazard pointer.
  *
@@ -245,24 +267,9 @@ void *hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 	ctx->acquire_cpu = smp_processor_id();
 	ctx->acquire_caller = _THIS_IP_;
 #endif
-	if (unlikely(slot->addr))
+	addr = __hazptr_try_acquire(ctx, addr_p, slot);
+	if (unlikely(!addr))
 		return __hazptr_acquire(ctx, addr_p);
-	WRITE_ONCE(slot->addr, READ_ONCE(hazptr_wildcard));	/* Store B */
-
-	/* Memory ordering: Store B before Load A. */
-	smp_mb();
-
-	/*
-	 * Load @addr_p after storing wildcard to the hazard pointer slot.
-	 */
-	addr = READ_ONCE(*addr_p);	/* Load A */
-
-	/*
-	 * We don't care about ordering of Store C. It will simply
-	 * replace the wildcard by a more specific address. If addr is
-	 * NULL, we simply store NULL into the slot.
-	 */
-	WRITE_ONCE(slot->addr, addr);	/* Store C */
 	slot_item->ctx.ctx = ctx;
 	ctx->slot = slot;
 	return addr;
kernel/hazptr.c +46 -45
index 13faa5ba7677..3ca73b56a5c2 100644
@@ -13,17 +13,9 @@
 #include <linux/list.h>
 #include <linux/export.h>
 
-static DEFINE_MUTEX(hazptr_phase_lock);	/* Protect the wildcard and list phase flip. */
+#define HAZPTR_WILDCARD	((void *) 1UL)
 
-/*
- * The current hazard pointer wildcard. Flips between 1UL and 2UL to guarantee
- * hazptr_synchronize forward progress even with a steady stream of readers.
- * This wildcard value is used by acquire to temporarily tag the per-CPU slots.
- * This also affects the overflow list selection: the current list used by
- * readers is array[(unsigned long) hazptr_wildcard - 1].
- */
-void *hazptr_wildcard = (void *) 1UL;
-EXPORT_SYMBOL_GPL(hazptr_wildcard);
+static DEFINE_MUTEX(hazptr_phase_lock);	/* Protect the list phase flip. */
 
 /* The current overflow list phase. */
 static unsigned int hazptr_overflow_list_phase;
@@ -41,6 +33,10 @@ struct hazptr_overflow_list {
  * successively iterates on both lists. Therefore, only list removals
  * can cause the iteration to retry, and the number of removals is
  * limited to the number of list elements.
+ *
+ * Due to the overflow list raw spin lock, the hazard pointer readers are
+ * blocking, starvation-free with bounded waiting, assuming bounded critical
+ * sections and no NMI or virtualization-induced holder preemption.
  */
 struct hazptr_overflow_list_flip {
 	struct hazptr_overflow_list array[2];
@@ -51,26 +47,12 @@ static DEFINE_PER_CPU(struct hazptr_overflow_list_flip, percpu_overflow_list_fli
 DEFINE_PER_CPU(struct hazptr_percpu_slots, hazptr_percpu_slots);
 EXPORT_PER_CPU_SYMBOL_GPL(hazptr_percpu_slots);
 
-static
-void *flip_wildcard(void *wildcard)
-{
-	return ((unsigned long) wildcard == 1UL) ? (void *) 2UL : (void *) 1UL;
-}
-
 static
 unsigned int flip_list_phase(unsigned int phase)
 {
 	return 1 - phase;
 }
 
-static
-bool is_wildcard(void *addr)
-{
-	if ((unsigned long) addr == 1UL || (unsigned long) addr == 2UL)
-		return true;
-	return false;
-}
-
 static
 struct hazptr_slot *hazptr_get_free_percpu_slot(struct hazptr_ctx *ctx)
 {
@@ -96,16 +78,36 @@ struct hazptr_slot *hazptr_get_free_percpu_slot(struct hazptr_ctx *ctx)
  */
 void *__hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 {
-	struct hazptr_slot *slot = hazptr_get_free_percpu_slot(ctx);
+	struct hazptr_slot *slot;
 	void *addr;
 
 	/*
-	 * If all the per-CPU slots are already in use, fallback
-	 * to the backup slot.
+	 * In case we are called due to nested use of hazard pointers,
+	 * try a slot protection with per-CPU slots.
 	 */
-	if (unlikely(!slot))
-		slot = hazptr_chain_backup_slot(ctx);
-	WRITE_ONCE(slot->addr, READ_ONCE(hazptr_wildcard));	/* Store B */
+	slot = hazptr_get_free_percpu_slot(ctx);
+	if (likely(slot)) {
+		addr = __hazptr_try_acquire(ctx, addr_p, slot);
+		if (addr) {
+			ctx->slot = slot;
+			return addr;
+		}
+	}
+
+	/*
+	 * The backup slot overflow list guarantees forward progress of both
+	 * hazard pointer readers and synchronize:
+	 *
+	 * - Readers set the wildcard, and then proceed to set the more
+	 *   specific address to replace the wildcard.
+	 *
+	 * - One synchronize alternates between two overflow list periods,
+	 *   scanning each one while readers are added to the other period,
+	 *   thus preventing a steady flow of readers from preventing
+	 *   synchronize forward progress.
+	 */
+	slot = hazptr_chain_backup_slot(ctx);
+	WRITE_ONCE(slot->addr, HAZPTR_WILDCARD);	/* Store B */
 
 	/* Memory ordering: Store B before Load A. */
 	smp_mb();
@@ -121,20 +123,21 @@ void *__hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 	 * NULL, we simply store NULL into the slot.
 	 */
 	WRITE_ONCE(slot->addr, addr);	/* Store C */
+
 	ctx->slot = slot;
-	if (!addr && hazptr_slot_is_backup(ctx, slot))
+	if (!addr)
 		hazptr_unchain_backup_slot(ctx);
 	return addr;
 }
 EXPORT_SYMBOL_GPL(__hazptr_acquire);
 
 /*
- * Perform piecewise iteration on overflow list waiting until "addr" is
- * not present. Raw spinlock is released and taken between each list
- * item and busy loop iteration. The overflow list generation is checked
- * each time the lock is taken to validate that the list has not changed
- * before resuming iteration or busy wait. If the generation has
- * changed, retry the entire list traversal.
+ * Perform piecewise iteration on overflow list waiting until "addr" and
+ * wildcard are not present. Raw spinlock is released and taken between each
+ * list item and busy loop iteration. The overflow list generation is checked
+ * each time the lock is taken to validate that the list has not changed before
+ * resuming iteration or busy wait. If the generation has changed, retry the
+ * entire list traversal.
  */
 static
 void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list, void *addr)
@@ -147,13 +150,11 @@ void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list
 retry:
 	snapshot_gen = overflow_list->gen;
 	hlist_for_each_entry(backup_slot, &overflow_list->head, overflow_node) {
-		/* Busy-wait if node is found. */
+		/* Busy-wait if addr or wildcard are found. */
 		for (;;) {
 			void *load_addr = smp_load_acquire(&backup_slot->slot.addr);	/* Load B */
 
-			/* We don't expect wildcards in overflow list. */
-			WARN_ON_ONCE(is_wildcard(load_addr));
-			if (load_addr != addr)
+			if (load_addr != addr && load_addr != HAZPTR_WILDCARD)
 				break;
 			raw_spin_unlock_irqrestore(&overflow_list->lock, flags);
 			cpu_relax();
@@ -174,7 +175,7 @@ void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list
 }
 
 static
-void hazptr_synchronize_cpu_slots(int cpu, void *addr, void *scan_wildcard)
+void hazptr_synchronize_cpu_slots(int cpu, void *addr)
 {
 	struct hazptr_percpu_slots *percpu_slots = per_cpu_ptr(&hazptr_percpu_slots, cpu);
 	unsigned int idx;
@@ -182,13 +183,13 @@ void hazptr_synchronize_cpu_slots(int cpu, void *addr, void *scan_wildcard)
 	for (idx = 0; idx < NR_HAZPTR_PERCPU_SLOTS; idx++) {
 		struct hazptr_slot_item *item = &percpu_slots->items[idx];
 
-		/* Busy-wait if node is found. */
-		smp_cond_load_acquire(&item->slot.addr, VAL != addr && VAL != scan_wildcard); /* Load B */
+		/* Busy-wait if addr is found. */
+		smp_cond_load_acquire(&item->slot.addr, VAL != addr); /* Load B */
 	}
 }
 
 static
-void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
+void hazptr_scan_cpu_slots(void *addr)
 {
 	int cpu;
 
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
 	for_each_possible_cpu(cpu) {

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 10 lines
kernel/hazptr.c +0 -3
 		/*
 		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
 		 * Forward progress against recurring single hazard pointer
 		 * values is guaranteed by the fact that a hazard pointer
 		 * is not reclaimed nor reused until the scan for that hazard
 		 * pointer completes, which prevents a steady flow of readers
 		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

The rest looks good to me.

Regards,
Boqun

Quoted 36 lines
kernel/hazptr.c +3 -6
 		 */
-		hazptr_synchronize_cpu_slots(cpu, addr, scan_wildcard);
+		hazptr_synchronize_cpu_slots(cpu, addr);
 	}
 }
 
@@ -237,7 +235,6 @@ void hazptr_scan_overflow_list_period(void *addr, unsigned int scan_idx)
 void hazptr_synchronize(void *addr)
 {
 	unsigned int scan_list_phase;
-	void *scan_wildcard;
 
 	/*
 	 * Busy-wait should only be done from preemptible context.
@@ -251,16 +248,14 @@ void hazptr_synchronize(void *addr)
 	 */
 	if (!addr)
 		return;
+
 	/* Memory ordering: Store A before Load B. */
 	smp_mb();
 
 	guard(mutex)(&hazptr_phase_lock);
 
 	/* Scan per-CPU slots. */
-	scan_wildcard = flip_wildcard(hazptr_wildcard);
-	hazptr_scan_cpu_slots_period(addr, scan_wildcard);
-	WRITE_ONCE(hazptr_wildcard, scan_wildcard);			/* Flip the current wildcard. */
-	hazptr_scan_cpu_slots_period(addr, flip_wildcard(scan_wildcard));
+	hazptr_scan_cpu_slots(addr);
 
 	/*
 	 * Scan overflow lists *after* scanning per-CPU slots. See
Signature · 1 line
2.43.0
author reviewer
#11 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 27 lines · Boqun Feng
Quoted 16 lines · Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

Quoted 9 lines

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Quoted 4 lines

Ok, I was missing something, but I think it's better to call it out. Wildcards can only exist in the overflow lists when the context is not preemptible. In other words, there won't be a preempted readers blocking the synchronize_hazptr() with a wilcard in the overflow list.

Exactly ! Wildcard slots only exist during the short time-frame of the preempt-off read-side code region (few instructions). And with this patch, this does not even happen very often, because the fast path don't rely on the wildcards.

Quoted 3 lines

So no more design trade-off question from me :)

Are you sure ? Scrolling down....

Quoted 22 lines

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 12 lines
kernel/hazptr.c +0 -3
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
  	for_each_possible_cpu(cpu) {
  		/*
  		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
  		 * Forward progress against recurring single hazard pointer
  		 * values is guaranteed by the fact that a hazard pointer
  		 * is not reclaimed nor reused until the scan for that hazard
  		 * pointer completes, which prevents a steady flow of readers
  		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the
address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than
protecting the specific nodes being retired, the whole hash chain is
protected. This means that, as you point out, many readers retiring
nodes from a given bucket (except the first node) could end up holding a
continuous stream of hazptr for a given hazptr value, preventing
progress of hazptr synchronize.

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Thoughts ?

Thanks,

Mathieu

Quoted 6 lines

The rest looks good to me.

Regards,
Boqun

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#12 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

On Sun, Sep 27, 2026 at 01:15:39PM -0400, Mathieu Desnoyers wrote:
[...]

Quoted 36 lines
Quoted 22 lines

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 12 lines
kernel/hazptr.c +0 -3
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
  	for_each_possible_cpu(cpu) {
  		/*
  		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
  		 * Forward progress against recurring single hazard pointer
  		 * values is guaranteed by the fact that a hazard pointer
  		 * is not reclaimed nor reused until the scan for that hazard
  		 * pointer completes, which prevents a steady flow of readers
  		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

Quoted 4 lines

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

No, you got it right, but as I said, we can use it in lockdep since the readers are relatively rare, so not an issue here.

Quoted 2 lines

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of

I honestly don't know. But in my opinion, we'd better focus on finding more typical usage of hazptr (i.e. protecting actual object). So ...

Quoted 7 lines

hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Thoughts ?

... I will say let's add it only if we have more users of this pattern.

Regards,
Boqun

Quoted 16 lines

Thanks,

Mathieu

Quoted 6 lines

The rest looks good to me.

Regards,
Boqun

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
author reviewer
#13 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 57 lines · Boqun Feng

On Sun, Sep 27, 2026 at 01:15:39PM -0400, Mathieu Desnoyers wrote:
[...]

Quoted 36 lines
Quoted 22 lines

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 12 lines
kernel/hazptr.c +0 -3
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
   	for_each_possible_cpu(cpu) {
   		/*
   		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
   		 * Forward progress against recurring single hazard pointer
   		 * values is guaranteed by the fact that a hazard pointer
   		 * is not reclaimed nor reused until the scan for that hazard
   		 * pointer completes, which prevents a steady flow of readers
   		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

Quoted 4 lines

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

No, you got it right, but as I said, we can use it in lockdep since the readers are relatively rare, so not an issue here.

Quoted 2 lines

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of

I honestly don't know. But in my opinion, we'd better focus on finding more typical usage of hazptr (i.e. protecting actual object). So ...

Quoted 5 lines

hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Quoted 5 lines
Quoted 2 lines

Thoughts ?

... I will say let's add it only if we have more users of this pattern.

I am concerned about this because many uses of RCU in the Linux kernel protects linked list traversals. Turning a RCU-protected list traversal into a hazptr protected traversal is not as simple as acquiring each hazptr hand in hand.

Your own use-case for lockdep is indeed a linked list traversal, and you need to use a work-around: protect the address of the hash bucket head.

I'm just wondering if this work-around will end up being the "blessed" way for protecting linked list traversals with hazptr, or whether we should consider alternatives ?

This ties into finding additional usage for hazptr, because linked lists are so prevalent in the kernel.

Thanks,

Mathieu

Quoted 19 lines

Regards,
Boqun

Quoted 16 lines

Thanks,

Mathieu

Quoted 6 lines

The rest looks good to me.

Regards,
Boqun

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#14 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 61 lines · Mathieu Desnoyers
Quoted 60 lines · Boqun Feng

On Sun, Sep 27, 2026 at 01:15:39PM -0400, Mathieu Desnoyers wrote:
[...]

Quoted 36 lines
Quoted 22 lines

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 12 lines
kernel/hazptr.c +0 -3
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
   	for_each_possible_cpu(cpu) {
   		/*
   		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
   		 * Forward progress against recurring single hazard pointer
   		 * values is guaranteed by the fact that a hazard pointer
   		 * is not reclaimed nor reused until the scan for that hazard
   		 * pointer completes, which prevents a steady flow of readers
   		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

Quoted 4 lines

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

No, you got it right, but as I said, we can use it in lockdep since the readers are relatively rare, so not an issue here.

Quoted 2 lines

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of

I honestly don't know. But in my opinion, we'd better focus on finding more typical usage of hazptr (i.e. protecting actual object). So ...

Quoted 7 lines

hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Thoughts ?

Quoted 8 lines
Quoted 2 lines

... I will say let's add it only if we have more users of this pattern.

I am concerned about this because many uses of RCU in the Linux kernel protects linked list traversals. Turning a RCU-protected list traversal into a hazptr protected traversal is not as simple as acquiring each hazptr hand in hand.

I actually don't think converting RCU usage into hazptr would be a good starting point for finding good hazptr usage. RCU readers are faster, and a lot of existing RCU users do want the reader side to be as fast as possible. So even though this is a problem, but I don't think that's an urgent problem to resolve. Of course, if one can find a faster hazptr reader implemenation, then it may be a different story.

Quoted 4 lines

Your own use-case for lockdep is indeed a linked list traversal, and you need to use a work-around: protect the address of the hash bucket head.

So the lockdep usage is IMO a very special case, but it does show the advantages of hazptr.

Quoted 4 lines

I'm just wondering if this work-around will end up being the "blessed" way for protecting linked list traversals with hazptr, or whether we should consider alternatives ?

It depends on how many uses of the linked list traversals really care about the reader side performance. I'm not sure we can easily find another one like lockdep. Hence I think we should only add the optimization when we find more of such a usage. Make sense?

Personally, I also want to see a refcount-like usage for hazptr, that'll be very exciting for me :D

Regards,
Boqun

Quoted 32 lines

This ties into finding additional usage for hazptr, because linked lists are so prevalent in the kernel.

Thanks,

Mathieu

Quoted 19 lines

Regards,
Boqun

Quoted 16 lines

Thanks,

Mathieu

Quoted 6 lines

The rest looks good to me.

Regards,
Boqun

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#15 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 40 lines · Boqun Feng
Quoted 39 lines · Mathieu Desnoyers
Quoted 38 lines · Boqun Feng

On Sun, Sep 27, 2026 at 01:15:39PM -0400, Mathieu Desnoyers wrote:
[...]

Quoted 36 lines
Quoted 22 lines

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 12 lines
kernel/hazptr.c +0 -3
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
   	for_each_possible_cpu(cpu) {
   		/*
   		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
   		 * Forward progress against recurring single hazard pointer
   		 * values is guaranteed by the fact that a hazard pointer
   		 * is not reclaimed nor reused until the scan for that hazard
   		 * pointer completes, which prevents a steady flow of readers
   		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

No, you got it right, but as I said, we can use it in lockdep since the readers are relatively rare, so not an issue here.

This sort of tradeoff is made in hazard-pointer use cases in other projects, with use of explicit counts of the incoming links to a given node being one such trick. The explicit count counts the links, and hazard pointers counts the readers. This approach usually ends up also restricting the order in which nodes can be removed.

Just like SRCU partitions the readers coming from the RCU end. ;-)

Quoted 22 lines
Quoted 14 lines
Quoted 14 lines
Quoted 2 lines

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of

I honestly don't know. But in my opinion, we'd better focus on finding more typical usage of hazptr (i.e. protecting actual object). So ...

Quoted 7 lines

hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Thoughts ?

Quoted 7 lines
Quoted 2 lines

... I will say let's add it only if we have more users of this pattern.

I am concerned about this because many uses of RCU in the Linux kernel protects linked list traversals. Turning a RCU-protected list traversal into a hazptr protected traversal is not as simple as acquiring each hazptr hand in hand.

Quoted 6 lines

I actually don't think converting RCU usage into hazptr would be a good starting point for finding good hazptr usage. RCU readers are faster, and a lot of existing RCU users do want the reader side to be as fast as possible. So even though this is a problem, but I don't think that's an urgent problem to resolve. Of course, if one can find a faster hazptr reader implemenation, then it may be a different story.

The usual hazard-pointers linked-list traversal includes a retry check at each node. So yes, we should first be looking for hazard-pointer use cases where RCU doesn't have such a great advantage. ;-)

Quoted 11 lines
Quoted 3 lines

Your own use-case for lockdep is indeed a linked list traversal, and you need to use a work-around: protect the address of the hash bucket head.

So the lockdep usage is IMO a very special case, but it does show the advantages of hazptr.

Quoted 3 lines

I'm just wondering if this work-around will end up being the "blessed" way for protecting linked list traversals with hazptr, or whether we should consider alternatives ?

Quoted 7 lines

It depends on how many uses of the linked list traversals really care about the reader side performance. I'm not sure we can easily find another one like lockdep. Hence I think we should only add the optimization when we find more of such a usage. Make sense?

Personally, I also want to see a refcount-like usage for hazptr, that'll be very exciting for me :D

Me too! The easiest cases will be those having a try-acquire rather than an unconditional acquisition.

Thanx, Paul

Quoted 35 lines

Regards,
Boqun

Quoted 32 lines

This ties into finding additional usage for hazptr, because linked lists are so prevalent in the kernel.

Thanks,

Mathieu

Quoted 19 lines

Regards,
Boqun

Quoted 16 lines

Thanks,

Mathieu

Quoted 6 lines

The rest looks good to me.

Regards,
Boqun

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#16 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Mathieu Desnoyers

On Sun, Sep 27, 2026 at 01:15:39PM -0400, Mathieu Desnoyers wrote:
[...]

Quoted 16 lines
Quoted 9 lines
Quoted 4 lines

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Ok, I was missing something, but I think it's better to call it out. Wildcards can only exist in the overflow lists when the context is not preemptible. In other words, there won't be a preempted readers blocking the synchronize_hazptr() with a wilcard in the overflow list.

Exactly ! Wildcard slots only exist during the short time-frame of the preempt-off read-side code region (few instructions). And with this patch, this does not even happen very often, because the fast path don't rely on the wildcards.

Quoted 1 line
Quoted 5 lines
Quoted 2 lines

So no more design trade-off question from me :)

Are you sure ? Scrolling down....

I do feel with scan thread support and call_hazptr() support, we will need to tweak the design and implementation some more, but right now it does look good to me :)

Regards,
Boqun

[...]

#17 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Mathieu Desnoyers
Quoted 25 lines · Mathieu Desnoyers
Quoted 10 lines · Boqun Feng

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

It's also coarser: per-bucket rather than per-node.

Quoted 8 lines

Am I missing something here ?

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Slightly off topic, but I have a use-case in mind (in case you're not already aware) where the address is fixed like the lockdep class, but it does not suffer the forward progress guarantee.

I have been wanting to use hazptr for revocable for quite a while (I think I chatted with Boqun about this last LPC). For the revocable use case, the protected pointer is fixed, however there is an additional boolean flag to determine if the resource been revoked or not.

Something like this:

    void *revocable_try_access(struct revocable *rev) {
        struct hazptr_ctx ctx = {};
        if (READ_ONCE(rev->revoked))
            return NULL;
        // note the & cancels out with the * in acquire, so the address is fixed.
        hazptr_acquire(&ctx, &rev);
        if (READ_ONCE(rev->revoked))
            return NULL;
        return rev->res;
    }

    void revocable_revoke(struct revocable *rev) {
        WRITE_ONCE(rev->revoked, true);
        hazptr_synchronize(&rev);
    }

So while the address is fixed, we have a different field to do the unpublishing part.

For some context, the current Rust revocable implementation uses RCU, but this is limiting the case where it can be used. The current C revocable series in
https://lore.kernel.org/all/[email protected]/ uses SRCU.

I think this use case is a good one for hazptr, in fact, I have encouraged Alvin Sun to try it out and you can see an implementation (Rust) in here:
https://lore.kernel.org/rust-for-linux/[email protected]/
Although, over the course of the year, we have been reducing the amount of revocable usage and shifting to represent things with lifetime..

Best,
Gary

maintainer
#18 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 69 lines · Gary Guo
Quoted 25 lines · Mathieu Desnoyers
Quoted 10 lines · Boqun Feng

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

It's also coarser: per-bucket rather than per-node.

Quoted 8 lines

Am I missing something here ?

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Slightly off topic, but I have a use-case in mind (in case you're not already aware) where the address is fixed like the lockdep class, but it does not suffer the forward progress guarantee.

I have been wanting to use hazptr for revocable for quite a while (I think I chatted with Boqun about this last LPC). For the revocable use case, the protected pointer is fixed, however there is an additional boolean flag to determine if the resource been revoked or not.

Something like this:

    void *revocable_try_access(struct revocable *rev) {
        struct hazptr_ctx ctx = {};
        if (READ_ONCE(rev->revoked))
            return NULL;
        // note the & cancels out with the * in acquire, so the address is fixed.
        hazptr_acquire(&ctx, &rev);
        if (READ_ONCE(rev->revoked))
            return NULL;
        return rev->res;
    }

    void revocable_revoke(struct revocable *rev) {
        WRITE_ONCE(rev->revoked, true);
        hazptr_synchronize(&rev);
    }

So while the address is fixed, we have a different field to do the unpublishing part.

For some context, the current Rust revocable implementation uses RCU, but this is limiting the case where it can be used. The current C revocable series in
https://lore.kernel.org/all/[email protected]/ uses SRCU.

Quoted 6 lines

I think this use case is a good one for hazptr, in fact, I have encouraged Alvin Sun to try it out and you can see an implementation (Rust) in here:
https://lore.kernel.org/rust-for-linux/[email protected]/
Although, over the course of the year, we have been reducing the amount of revocable usage and shifting to represent things with lifetime..

Paul asked me for the Rust usage a few days ago, and since we moved to a lifetime based approach [1], which is better IMO, I don't think switching to hazptr will should observable difference here, especially for a real workload improvement. It's still worth trying to see how hazptr in Rust would work for this, but it's less a sufficient condition to merge hazptr from my understanding. Of course I could be wrong.

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

Regards,
Boqun

Regards,
Boqun

Quoted 2 lines

Best,
Gary

#19 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 77 lines · Boqun Feng
Quoted 69 lines · Gary Guo
Quoted 25 lines · Mathieu Desnoyers
Quoted 10 lines · Boqun Feng

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address is invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up holding a continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

It's also coarser: per-bucket rather than per-node.

Quoted 8 lines

Am I missing something here ?

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of hazptr protection "period" flip (similar to some RCU implementations), where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a steady-flow of same-value readers from preventing synchronize forward progress.

Slightly off topic, but I have a use-case in mind (in case you're not already aware) where the address is fixed like the lockdep class, but it does not suffer the forward progress guarantee.

I have been wanting to use hazptr for revocable for quite a while (I think I chatted with Boqun about this last LPC). For the revocable use case, the protected pointer is fixed, however there is an additional boolean flag to determine if the resource been revoked or not.

Something like this:

    void *revocable_try_access(struct revocable *rev) {
        struct hazptr_ctx ctx = {};
        if (READ_ONCE(rev->revoked))
            return NULL;
        // note the & cancels out with the * in acquire, so the address is fixed.
        hazptr_acquire(&ctx, &rev);
        if (READ_ONCE(rev->revoked))
            return NULL;
        return rev->res;
    }

    void revocable_revoke(struct revocable *rev) {
        WRITE_ONCE(rev->revoked, true);
        hazptr_synchronize(&rev);
    }

So while the address is fixed, we have a different field to do the unpublishing part.

For some context, the current Rust revocable implementation uses RCU, but this is limiting the case where it can be used. The current C revocable series in
https://lore.kernel.org/all/[email protected]/ uses SRCU.

Quoted 6 lines

I think this use case is a good one for hazptr, in fact, I have encouraged Alvin Sun to try it out and you can see an implementation (Rust) in here:
https://lore.kernel.org/rust-for-linux/[email protected]/
Although, over the course of the year, we have been reducing the amount of revocable usage and shifting to represent things with lifetime..

Quoted 8 lines

Paul asked me for the Rust usage a few days ago, and since we moved to a lifetime based approach [1], which is better IMO, I don't think switching to hazptr will should observable difference here, especially for a real workload improvement. It's still worth trying to see how hazptr in Rust would work for this, but it's less a sufficient condition to merge hazptr from my understanding. Of course I could be wrong.

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

What we get rid of is to use Revocable (or DevRes) to protect resources where we _know_ that the resource is alive (for example, in device private data, because it's teared down by driver-core on unbind).

However, there are cases where we can still have the Revocable pattern, for example when a class device is exposed to userspace and the bus device is unbinding. This is a pretty recurring pattern too, and cannot be handled via lifetime alone. This is what motivates the C revocable series.

Best,
Gary

#20 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

Quoted 123 lines · Gary Guo
Quoted 5 lines · Boqun Feng
Quoted 4 lines · Gary Guo
Quoted 3 lines · Mathieu Desnoyers
Quoted 1 line · Boqun Feng

I want to point out this is not true for the lockdep use case,

because

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice

because

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class

to

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

register).

Maybe what we want to say here is that "if the users guarantee no

steady

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

flow of the same hazard pointer value, we guarantee forward

progress".

Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 1 line

Thoughts?

AFAIU, your approach to protect lockdep linked lists is to use the address of the hash bucket to protect the traversal. As this address

is

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

invariant (global array item address), that address should be fine to fulfill hazptr requirements, but it has downsides: rather than protecting the specific nodes being retired, the whole hash chain is protected. This means that, as you point out, many readers retiring nodes from a given bucket (except the first node) could end up

holding a

Quoted 10 lines
Quoted 10 lines
Quoted 10 lines

continuous stream of hazptr for a given hazptr value, preventing progress of hazptr synchronize.

It's also coarser: per-bucket rather than per-node.

Am I missing something here ?

One honest question: is this pattern something we expect to see often ? If so, then we may want to introduce a notion of hazptr protection "period" flip (similar to some RCU

implementations),

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

where we tag the low bit of the slot pointer (0 vs 1), and alternate between the two periods in synchronize. This would prevent a

steady-flow

Quoted 3 lines
Quoted 3 lines
Quoted 1 line

of same-value readers from preventing synchronize forward progress.

Slightly off topic, but I have a use-case in mind (in case you're not

already

Quoted 1 line
Quoted 1 line

aware) where the address is fixed like the lockdep class, but it does

not suffer

Quoted 3 lines
Quoted 3 lines

the forward progress guarantee.

I have been wanting to use hazptr for revocable for quite a while (I

think I

Quoted 1 line
Quoted 1 line

chatted with Boqun about this last LPC). For the revocable use case,

the

Quoted 1 line
Quoted 1 line

protected pointer is fixed, however there is an additional boolean flag

to

Quoted 9 lines
Quoted 9 lines

determine if the resource been revoked or not.

Something like this:

    void *revocable_try_access(struct revocable *rev) {
        struct hazptr_ctx ctx = {};
        if (READ_ONCE(rev->revoked))
            return NULL;
        // note the & cancels out with the * in acquire, so the address

is fixed.

Quoted 6 lines
Quoted 6 lines
        hazptr_acquire(&ctx, &rev);
        if (READ_ONCE(rev->revoked))
            return NULL;
        return rev->res;
    }
Quoted 6 lines
Quoted 6 lines
    void revocable_revoke(struct revocable *rev) {
        WRITE_ONCE(rev->revoked, true);
        hazptr_synchronize(&rev);
    }

So while the address is fixed, we have a different field to do the

unpublishing

Quoted 3 lines
Quoted 3 lines

part.

For some context, the current Rust revocable implementation uses RCU,

but this

Quoted 1 line
Quoted 1 line

is limiting the case where it can be used. The current C revocable

series in

Quoted 1 line
Quoted 1 line

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

uses SRCU.

Quoted 2 lines
Quoted 2 lines

I think this use case is a good one for hazptr, in fact, I have

encouraged Alvin

Quoted 2 lines
Quoted 2 lines

Sun to try it out and you can see an implementation (Rust) in here:

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

Quoted 1 line
Quoted 1 line

Although, over the course of the year, we have been reducing the amount

of

Quoted 11 lines
Quoted 2 lines

revocable usage and shifting to represent things with lifetime..

Paul asked me for the Rust usage a few days ago, and since we moved to a lifetime based approach [1], which is better IMO, I don't think switching to hazptr will should observable difference here, especially for a real workload improvement. It's still worth trying to see how hazptr in Rust would work for this, but it's less a sufficient condition to merge hazptr from my understanding. Of course I could be wrong.

[1]:

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

What we get rid of is to use Revocable (or DevRes) to protect resources
where we _know_ that the resource is alive (for example, in device private data,
because it's teared down by driver-core on unbind).

However, there are cases where we can still have the Revocable pattern, for
example when a class device is exposed to userspace and the bus device is unbinding. This is a pretty recurring pattern too, and cannot be handled via
lifetime alone. This is what motivates the C revocable series.

Quoted 3 lines

Best,
Gary

Would you like me to try and draft a hazptr rust file? I mean, I'm not a expert at it, but I'll throw my hat into the ring
--- Thanks!
"I'm not a very positive person" - Linus torvalds

maintainer
#21 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Gary Guo

On Mon, Sep 28, 2026 at 12:32:34PM +0100, Gary Guo wrote:
[...]

Quoted 20 lines
Quoted 11 lines
Quoted 10 lines

For some context, the current Rust revocable implementation uses RCU, but this is limiting the case where it can be used. The current C revocable series in
https://lore.kernel.org/all/[email protected]/ uses SRCU.

I think this use case is a good one for hazptr, in fact, I have encouraged Alvin Sun to try it out and you can see an implementation (Rust) in here:
https://lore.kernel.org/rust-for-linux/[email protected]/
Although, over the course of the year, we have been reducing the amount of revocable usage and shifting to represent things with lifetime..

Quoted 8 lines

Paul asked me for the Rust usage a few days ago, and since we moved to a lifetime based approach [1], which is better IMO, I don't think switching to hazptr will should observable difference here, especially for a real workload improvement. It's still worth trying to see how hazptr in Rust would work for this, but it's less a sufficient condition to merge hazptr from my understanding. Of course I could be wrong.

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

Quoted 9 lines

What we get rid of is to use Revocable (or DevRes) to protect resources where we _know_ that the resource is alive (for example, in device private data, because it's teared down by driver-core on unbind).

However, there are cases where we can still have the Revocable pattern, for example when a class device is exposed to userspace and the bus device is unbinding. This is a pretty recurring pattern too, and cannot be handled via lifetime alone. This is what motivates the C revocable series.

Not trying to discourage switching to hazptr in Revocable, but I think the only shortcoming of RCU there is "unable to sleep while referencing a Revocable", right? Certainly hazptr can help on that but so does SRCU. I'm unsure hazptr can show observable advantages against SRCU here. But I could be wrong.

Regards,
Boqun

Quoted 2 lines

Best,
Gary

maintainer
#22 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Mathieu Desnoyers
Quoted 33 lines · Mathieu Desnoyers
Quoted 27 lines · Boqun Feng
Quoted 16 lines · Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

Quoted 9 lines

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Quoted 4 lines

Ok, I was missing something, but I think it's better to call it out. Wildcards can only exist in the overflow lists when the context is not preemptible. In other words, there won't be a preempted readers blocking the synchronize_hazptr() with a wilcard in the overflow list.

Quoted 4 lines

Exactly ! Wildcard slots only exist during the short time-frame of the preempt-off read-side code region (few instructions). And with this patch, this does not even happen very often, because the fast path don't rely on the wildcards.

One advantage of getting rid of the wildcards completely is that it brings out hazard-pointers resistance to blocking. Even vCPU preemption would not do more than block reclamation of the nodes referenced by the preempted vCPU's current hazard pointers.

Thanx, Paul

#23 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Boqun Feng
Quoted 320 lines · On Sun, 27 Sep 2026 18:40:53 +0200 Boqun Feng <[email protected]> wrote:
Quoted 16 lines · Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

Quoted 9 lines

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Ok, I was missing something, but I think it's better to call it out. Wildcards can only exist in the overflow lists when the context is not preemptible. In other words, there won't be a preempted readers blocking the synchronize_hazptr() with a wilcard in the overflow list.

So no more design trade-off question from me :)

Regards,
Boqun

Quoted 263 lines
---
 include/linux/hazptr.h |  47 +++++++++++--------
 kernel/hazptr.c        | 103 ++++++++++++++++++++---------------------
 2 files changed, 76 insertions(+), 74 deletions(-)
include/linux/hazptr.h +27 -20
index d1670121947a..fcf017ca2255 100644
@@ -29,9 +29,6 @@
 /* 4 slots (each sizeof(hazptr_slot_item)) fit in a single 64-byte cache line. */
 #define NR_HAZPTR_PERCPU_SLOTS	4
 
-/* The current hazard pointer wildcard. */
-extern void *hazptr_wildcard;
-
 /*
  * Hazard pointer slot.
  */
@@ -190,6 +187,31 @@ void hazptr_note_context_switch(void)
 	}
 }
 
+/* Try hazard pointer protection. */
+static inline
+void *__hazptr_try_acquire(struct hazptr_ctx *ctx, void * const *addr_p, struct hazptr_slot *slot)
+{
+	void *early_addr, *addr;
+
+	if (unlikely(slot->addr))
+		return NULL;
+	early_addr = READ_ONCE(*addr_p);	/* Early load. */
+	WRITE_ONCE(slot->addr, early_addr);	/* Store B */
+	/* Memory ordering: Store B before Load A. */
+	smp_mb();
+	addr = READ_ONCE(*addr_p);		/* Load A */
+	/*
+	 * Validate that address did not change between Early load and Load A.
+	 * Use ptr_eq() to make sure that result from Load A is returned to the
+	 * caller to preserve address dependency.
+	 */
+	if (unlikely(!ptr_eq(addr, early_addr))) {
+		WRITE_ONCE(slot->addr, NULL);
+		return NULL;
+	}
+	return addr;
+}
+
 /**
  * hazptr_acquire - Load pointer at address and protect with hazard pointer.
  *
@@ -245,24 +267,9 @@ void *hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 	ctx->acquire_cpu = smp_processor_id();
 	ctx->acquire_caller = _THIS_IP_;
 #endif
-	if (unlikely(slot->addr))
+	addr = __hazptr_try_acquire(ctx, addr_p, slot);
+	if (unlikely(!addr))
 		return __hazptr_acquire(ctx, addr_p);
-	WRITE_ONCE(slot->addr, READ_ONCE(hazptr_wildcard));	/* Store B */
-
-	/* Memory ordering: Store B before Load A. */
-	smp_mb();
-
-	/*
-	 * Load @addr_p after storing wildcard to the hazard pointer slot.
-	 */
-	addr = READ_ONCE(*addr_p);	/* Load A */
-
-	/*
-	 * We don't care about ordering of Store C. It will simply
-	 * replace the wildcard by a more specific address. If addr is
-	 * NULL, we simply store NULL into the slot.
-	 */
-	WRITE_ONCE(slot->addr, addr);	/* Store C */
 	slot_item->ctx.ctx = ctx;
 	ctx->slot = slot;
 	return addr;
kernel/hazptr.c +46 -45
index 13faa5ba7677..3ca73b56a5c2 100644
@@ -13,17 +13,9 @@
 #include <linux/list.h>
 #include <linux/export.h>
 
-static DEFINE_MUTEX(hazptr_phase_lock);	/* Protect the wildcard and list phase flip. */
+#define HAZPTR_WILDCARD	((void *) 1UL)
 
-/*
- * The current hazard pointer wildcard. Flips between 1UL and 2UL to guarantee
- * hazptr_synchronize forward progress even with a steady stream of readers.
- * This wildcard value is used by acquire to temporarily tag the per-CPU slots.
- * This also affects the overflow list selection: the current list used by
- * readers is array[(unsigned long) hazptr_wildcard - 1].
- */
-void *hazptr_wildcard = (void *) 1UL;
-EXPORT_SYMBOL_GPL(hazptr_wildcard);
+static DEFINE_MUTEX(hazptr_phase_lock);	/* Protect the list phase flip. */
 
 /* The current overflow list phase. */
 static unsigned int hazptr_overflow_list_phase;
@@ -41,6 +33,10 @@ struct hazptr_overflow_list {
  * successively iterates on both lists. Therefore, only list removals
  * can cause the iteration to retry, and the number of removals is
  * limited to the number of list elements.
+ *
+ * Due to the overflow list raw spin lock, the hazard pointer readers are
+ * blocking, starvation-free with bounded waiting, assuming bounded critical
+ * sections and no NMI or virtualization-induced holder preemption.
  */
 struct hazptr_overflow_list_flip {
 	struct hazptr_overflow_list array[2];
@@ -51,26 +47,12 @@ static DEFINE_PER_CPU(struct hazptr_overflow_list_flip, percpu_overflow_list_fli
 DEFINE_PER_CPU(struct hazptr_percpu_slots, hazptr_percpu_slots);
 EXPORT_PER_CPU_SYMBOL_GPL(hazptr_percpu_slots);
 
-static
-void *flip_wildcard(void *wildcard)
-{
-	return ((unsigned long) wildcard == 1UL) ? (void *) 2UL : (void *) 1UL;
-}
-
 static
 unsigned int flip_list_phase(unsigned int phase)
 {
 	return 1 - phase;
 }
 
-static
-bool is_wildcard(void *addr)
-{
-	if ((unsigned long) addr == 1UL || (unsigned long) addr == 2UL)
-		return true;
-	return false;
-}
-
 static
 struct hazptr_slot *hazptr_get_free_percpu_slot(struct hazptr_ctx *ctx)
 {
@@ -96,16 +78,36 @@ struct hazptr_slot *hazptr_get_free_percpu_slot(struct hazptr_ctx *ctx)
  */
 void *__hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 {
-	struct hazptr_slot *slot = hazptr_get_free_percpu_slot(ctx);
+	struct hazptr_slot *slot;
 	void *addr;
 
 	/*
-	 * If all the per-CPU slots are already in use, fallback
-	 * to the backup slot.
+	 * In case we are called due to nested use of hazard pointers,
+	 * try a slot protection with per-CPU slots.
 	 */
-	if (unlikely(!slot))
-		slot = hazptr_chain_backup_slot(ctx);
-	WRITE_ONCE(slot->addr, READ_ONCE(hazptr_wildcard));	/* Store B */
+	slot = hazptr_get_free_percpu_slot(ctx);
+	if (likely(slot)) {
+		addr = __hazptr_try_acquire(ctx, addr_p, slot);
+		if (addr) {
+			ctx->slot = slot;
+			return addr;
+		}
+	}
+
+	/*
+	 * The backup slot overflow list guarantees forward progress of both
+	 * hazard pointer readers and synchronize:
+	 *
+	 * - Readers set the wildcard, and then proceed to set the more
+	 *   specific address to replace the wildcard.
+	 *
+	 * - One synchronize alternates between two overflow list periods,
+	 *   scanning each one while readers are added to the other period,
+	 *   thus preventing a steady flow of readers from preventing
+	 *   synchronize forward progress.
+	 */
+	slot = hazptr_chain_backup_slot(ctx);
+	WRITE_ONCE(slot->addr, HAZPTR_WILDCARD);	/* Store B */
 
 	/* Memory ordering: Store B before Load A. */
 	smp_mb();
@@ -121,20 +123,21 @@ void *__hazptr_acquire(struct hazptr_ctx *ctx, void * const *addr_p)
 	 * NULL, we simply store NULL into the slot.
 	 */
 	WRITE_ONCE(slot->addr, addr);	/* Store C */
+
 	ctx->slot = slot;
-	if (!addr && hazptr_slot_is_backup(ctx, slot))
+	if (!addr)
 		hazptr_unchain_backup_slot(ctx);
 	return addr;
 }
 EXPORT_SYMBOL_GPL(__hazptr_acquire);
 
 /*
- * Perform piecewise iteration on overflow list waiting until "addr" is
- * not present. Raw spinlock is released and taken between each list
- * item and busy loop iteration. The overflow list generation is checked
- * each time the lock is taken to validate that the list has not changed
- * before resuming iteration or busy wait. If the generation has
- * changed, retry the entire list traversal.
+ * Perform piecewise iteration on overflow list waiting until "addr" and
+ * wildcard are not present. Raw spinlock is released and taken between each
+ * list item and busy loop iteration. The overflow list generation is checked
+ * each time the lock is taken to validate that the list has not changed before
+ * resuming iteration or busy wait. If the generation has changed, retry the
+ * entire list traversal.
  */
 static
 void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list, void *addr)
@@ -147,13 +150,11 @@ void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list
 retry:
 	snapshot_gen = overflow_list->gen;
 	hlist_for_each_entry(backup_slot, &overflow_list->head, overflow_node) {
-		/* Busy-wait if node is found. */
+		/* Busy-wait if addr or wildcard are found. */
 		for (;;) {
 			void *load_addr = smp_load_acquire(&backup_slot->slot.addr);	/* Load B */
 
-			/* We don't expect wildcards in overflow list. */
-			WARN_ON_ONCE(is_wildcard(load_addr));
-			if (load_addr != addr)
+			if (load_addr != addr && load_addr != HAZPTR_WILDCARD)
 				break;
 			raw_spin_unlock_irqrestore(&overflow_list->lock, flags);
 			cpu_relax();
@@ -174,7 +175,7 @@ void hazptr_synchronize_overflow_list(struct hazptr_overflow_list *overflow_list
 }
 
 static
-void hazptr_synchronize_cpu_slots(int cpu, void *addr, void *scan_wildcard)
+void hazptr_synchronize_cpu_slots(int cpu, void *addr)
 {
 	struct hazptr_percpu_slots *percpu_slots = per_cpu_ptr(&hazptr_percpu_slots, cpu);
 	unsigned int idx;
@@ -182,13 +183,13 @@ void hazptr_synchronize_cpu_slots(int cpu, void *addr, void *scan_wildcard)
 	for (idx = 0; idx < NR_HAZPTR_PERCPU_SLOTS; idx++) {
 		struct hazptr_slot_item *item = &percpu_slots->items[idx];
 
-		/* Busy-wait if node is found. */
-		smp_cond_load_acquire(&item->slot.addr, VAL != addr && VAL != scan_wildcard); /* Load B */
+		/* Busy-wait if addr is found. */
+		smp_cond_load_acquire(&item->slot.addr, VAL != addr); /* Load B */
 	}
 }
 
 static
-void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
+void hazptr_scan_cpu_slots(void *addr)
 {
 	int cpu;
 
@@ -196,16 +197,13 @@ void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard)
 	for_each_possible_cpu(cpu) {

kernel/hazptr.c void hazptr_scan_cpu_slots_period(void *addr, void *scan_wildcard) · line 204

Quoted 10 lines
kernel/hazptr.c +0 -3
 		/*
 		 * Scan CPU slots.
-		 * Forward progress against recurring wildcards is guaranteed
-		 * by scanning for one wildcard while new elements use the
-		 * other wildcard value (1UL vs 2UL).
 		 * Forward progress against recurring single hazard pointer
 		 * values is guaranteed by the fact that a hazard pointer
 		 * is not reclaimed nor reused until the scan for that hazard
 		 * pointer completes, which prevents a steady flow of readers
 		 * to acquire that same hazard pointer value.

(Not a comment to this patch, but I think it's worth bringing up)

I want to point out this is not true for the lockdep use case, because the we need to protect a hash list deletion there, and we use the address of the hash bucket there. It's proven fine in practice because the readers are rare (we only call the reader is_dynamic_key() in register_lock_class(), that is every time you have a new lock class to register).

Quoted 3 lines

Maybe what we want to say here is that "if the users guarantee no steady flow of the same hazard pointer value, we guarantee forward progress". Thoughts?

Thanks Mathieu, and thanks Boqun for the review.

I hit the same ordering requirement in the shared-scan implementation I'm working on. hazptr_promote_to_backup_slot() links the backup slot into the overflow list before clearing the per-CPU slot, so the scan has to cover all per-CPU slots before the overflow lists. My series carries the same ordering fix in the scan-kthread path.

For the lockdep case, I've tested the conversion with the wq_churn/LOCKDEP torture scenario and PROVE_LOCKING enabled. The hazard pointer is the hash bucket address there, so I agree that the forward-progress guarantee should be stated conditional on there being no steady flow of the same hazard pointer value.

I'm also working on the scan-thread side, where concurrent hazptr_synchronize() callers share one scan cycle, based on
the scan-kthread approach from your shazptr series [1].
[1] https://lore.kernel.org/lkml/[email protected]/

The v2 series is testing, I'll include the rcuscale results in the cover letter.

Thanks,
Kunwu

Quoted 43 lines

The rest looks good to me.

Regards,
Boqun

Quoted 36 lines
kernel/hazptr.c +3 -6
 		 */
-		hazptr_synchronize_cpu_slots(cpu, addr, scan_wildcard);
+		hazptr_synchronize_cpu_slots(cpu, addr);
 	}
 }
 
@@ -237,7 +235,6 @@ void hazptr_scan_overflow_list_period(void *addr, unsigned int scan_idx)
 void hazptr_synchronize(void *addr)
 {
 	unsigned int scan_list_phase;
-	void *scan_wildcard;
 
 	/*
 	 * Busy-wait should only be done from preemptible context.
@@ -251,16 +248,14 @@ void hazptr_synchronize(void *addr)
 	 */
 	if (!addr)
 		return;
+
 	/* Memory ordering: Store A before Load B. */
 	smp_mb();
 
 	guard(mutex)(&hazptr_phase_lock);
 
 	/* Scan per-CPU slots. */
-	scan_wildcard = flip_wildcard(hazptr_wildcard);
-	hazptr_scan_cpu_slots_period(addr, scan_wildcard);
-	WRITE_ONCE(hazptr_wildcard, scan_wildcard);			/* Flip the current wildcard. */
-	hazptr_scan_cpu_slots_period(addr, flip_wildcard(scan_wildcard));
+	hazptr_scan_cpu_slots(addr);
 
 	/*
 	 * Scan overflow lists *after* scanning per-CPU slots. See
Signature · 1 line
2.43.0
Reviewed-by on v1 4/4
#24 lore raw

Re: [PATCH hazptr 4/4] hazptr: Introduce "try acquire" fast path, fallback to overflow list

In reply to Mathieu Desnoyers
Quoted 21 lines · Mathieu Desnoyers

Introduce a "try acquire" hazard pointer fast path, which performs an early load of the address to store it into the hazard pointer slot, and then re-loads that address after a barrier to check whether it has changed meanwhile.

On comparison failure, rather than re-try, guarantee forward progress by falling back to the __hazptr_acquire slow path on failure.

The acquire slow path attempts a try-acquire for any available per-CPU slot. If that fails, it chains the backup slot into the overflow list, therefore guaranteeing forward progress for both hazard pointer read-side and synchronize:

- Readers set the wildcard, and then proceed to set the more specific address to replace the wildcard.

- One synchronize alternates between two overflow list periods, scanning each one while readers are added to the other period, thus preventing a steady flow of readers from preventing synchronize forward progress.

Quoted 5 lines

With this change, the scan on per-CPU slots don't need to expect a wildcard anymore, because none can be produced by readers. Wildcards are only expected within overflow lists.

Quoted 10 lines
Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
---
 include/linux/hazptr.h |  47 +++++++++++--------
 kernel/hazptr.c        | 103 ++++++++++++++++++++---------------------
 2 files changed, 76 insertions(+), 74 deletions(-)
#25 lore raw
In reply to Mathieu Desnoyers
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 8 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Hi, here is a hazptr perf test on powerpc

REAL kill_fasync(), ns per call, best of 3, 100k calls:
(stock = rwlock walk, conv = hazptr walk, same v3 tree ± the conversion)

shape stock conv delta

  1 node,  1 walker     59      59     +0.0%   (singleton: identical)
  16 nodes, 1 walker   539     539     +0.0%   (uncontended: identical)
  16 nodes, 4 walkers  509     134    -73.7%   ← rwlock readers contend
  16 nodes, 8 walkers  313     113    -63.9%   ← same list, 8 cpus
  64 nodes, 1 walker  1979    2039     +3.0%   (pure walk: hazptr tax)
  64 nodes, 4 walkers 1914     509    -73.4%
  64 nodes, 8 walkers 1015     382    -62.4%

Its SLOWER than rcu, but beats rwlock

SIGIO delivery, plain mode, 8 ptys 1 listener each (identical harness):

BASELINE (rwlock) 472/s
CONVERTED v4 (hazptr) 452/s ← singleton fast path: gap 12% → 4%

With a few changes, it was 12% slower than rcu before.

Do you want those changes?

My idea is, we find something that would put use to hazptr, here is what I tried

fs/fcntl.c +47 -37
index c158f082f1da..bb04076ff6d9 100644
@@ -17,6 +17,7 @@
 #include <linux/slab.h>
 #include <linux/module.h>
 #include <linux/pipe_fs_i.h>
+#include <linux/hazptr.h>
 #include <linux/security.h>
 #include <linux/ptrace.h>
 #include <linux/signal.h>
@@ -1009,15 +1010,20 @@ int fasync_remove_entry(struct file *filp, struct fasync_struct **fapp)
 		if (fa->fa_file != filp)
 			continue;
 
-		write_lock_irq(&fa->fa_lock);
+		/*
+		 * Make the file invisible to the walk before unlinking,
+		 * then wait for any in-flight send_sigio() to be done with
+		 * the node before freeing it.  The walk holds a hazard
+		 * pointer to this node, so it cannot already be freed.
+		 */
 		fa->fa_file = NULL;
-		write_unlock_irq(&fa->fa_lock);
-
 		*fp = fa->fa_next;
-		kfree_rcu(fa, fa_rcu);
+		spin_unlock(&fasync_lock);
+		spin_unlock(&filp->f_lock);
+		hazptr_synchronize(fa);
+		fasync_free(fa);
 		filp->f_flags &= ~FASYNC;
-		result = 1;
-		break;
+		return 1;
 	}
 	spin_unlock(&fasync_lock);
 	spin_unlock(&filp->f_lock);
@@ -1056,13 +1062,10 @@ struct fasync_struct *fasync_insert_entry(int fd, struct file *filp, struct fasy
 		if (fa->fa_file != filp)
 			continue;
 
-		write_lock_irq(&fa->fa_lock);
-		fa->fa_fd = fd;
-		write_unlock_irq(&fa->fa_lock);
+		WRITE_ONCE(fa->fa_fd, fd);
 		goto out;
 	}
 
-	rwlock_init(&new->fa_lock);
 	new->magic = FASYNC_MAGIC;
 	new->fa_file = filp;
 	new->fa_fd = fd;
@@ -1121,44 +1124,51 @@ EXPORT_SYMBOL(fasync_helper);
 /*
  * rcu_read_lock() is held
  */
-static void kill_fasync_rcu(struct fasync_struct *fa, int sig, int band)
+void kill_fasync(struct fasync_struct **fp, int sig, int band)
 {
+	struct hazptr_ctx cur, nxt;
+	struct fasync_struct *fa;
+
+	/* First a quick test without locking: usually
+	 * the list is empty.
+	 */
+	fa = READ_ONCE(*fp);
+	if (!fa)
+		return;
+
+	/*
+	 * Hand-over-hand with two ping-ponged contexts: the next node
+	 * must be acquired before the current one is released, but a
+	 * hazptr_ctx may only front one live slot at a time.
+	 */
+	cur = (struct hazptr_ctx){ };
+	nxt = (struct hazptr_ctx){ };
+	fa = hazptr_acquire(&cur, (void * const *)fp);
 	while (fa) {
-		struct fown_struct *fown;
-		unsigned long flags;
+		struct fasync_struct *next;
 
 		if (fa->magic != FASYNC_MAGIC) {
 			printk(KERN_ERR "kill_fasync: bad magic number in "
 			       "fasync_struct!\n");
-			return;
+			break;
 		}
-		read_lock_irqsave(&fa->fa_lock, flags);
+
 		if (fa->fa_file) {
-			fown = file_f_owner(fa->fa_file);
-			if (!fown)
-				goto next;
-			/* Don't send SIGURG to processes which have not set a
-			   queued signum: SIGURG has its own default signalling
-			   mechanism. */
-			if (!(sig == SIGURG && fown->signum == 0))
+			struct fown_struct *fown = file_f_owner(fa->fa_file);
+
+			if (fown &&
+			    /* Don't send SIGURG to processes which have not set a
+			       queued signum: SIGURG has its own default signalling
+			       mechanism. */
+			    !(sig == SIGURG && fown->signum == 0))
 				send_sigio(fown, fa->fa_fd, band);
 		}
-next:
-		read_unlock_irqrestore(&fa->fa_lock, flags);
-		fa = rcu_dereference(fa->fa_next);
-	}
-}
-
-void kill_fasync(struct fasync_struct **fp, int sig, int band)
-{
-	/* First a quick test without locking: usually
-	 * the list is empty.
-	 */
-	if (*fp) {
-		rcu_read_lock();
-		kill_fasync_rcu(rcu_dereference(*fp), sig, band);
-		rcu_read_unlock();
+		next = hazptr_acquire(&nxt, (void * const *)&fa->fa_next);
+		hazptr_release(&cur, fa);
+		swap(cur, nxt);
+		fa = next;
 	}
+	hazptr_release(&cur, fa);
 }
 EXPORT_SYMBOL(kill_fasync);
 
include/linux/fs.h +0 -1
index f9d1e05e8ae6..852f1b8c00af 100644
@@ -1365,7 +1365,6 @@ static inline struct dentry *file_dentry(const struct file *file)
 }
 
 struct fasync_struct {
-	rwlock_t		fa_lock;
 	int			magic;
 	int			fa_fd;
 	struct fasync_struct	*fa_next; /* singly linked list */

Anything I did wrong? No?

Quoted 18 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
Quoted 7 lines
Documentation/RCU/rcu_dereference.rst |  38 +++++++-
include/linux/compiler.h              |  63 ++++++++++++
include/linux/hazptr.h                |  47 +++++----
kernel/hazptr.c                       | 135 +++++++++++++++-----------
4 files changed, 203 insertions(+), 80 deletions(-)

--- Thanks!
"I'm not a very positive person" - Linus torvalds

author reviewer
#26 lore raw
Quoted 33 lines · Bradley Morgan
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 8 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Hi, here is a hazptr perf test on powerpc

REAL kill_fasync(), ns per call, best of 3, 100k calls:
(stock = rwlock walk, conv = hazptr walk, same v3 tree ± the conversion)

   shape          stock    conv     delta
   1 node,  1 walker     59      59     +0.0%   (singleton: identical)
   16 nodes, 1 walker   539     539     +0.0%   (uncontended: identical)
   16 nodes, 4 walkers  509     134    -73.7%   ← rwlock readers contend
   16 nodes, 8 walkers  313     113    -63.9%   ← same list, 8 cpus
   64 nodes, 1 walker  1979    2039     +3.0%   (pure walk: hazptr tax)
   64 nodes, 4 walkers 1914     509    -73.4%
   64 nodes, 8 walkers 1015     382    -62.4%
Quoted 1 line

Its SLOWER than rcu, but beats rwlock

Two feedback points:

1) The comparison I think Boqun cares mostly about is with expedited RCU grace periods, this is where we suspect there is a significant benefit to using hazptr rather than RCU to eliminate those IPIs on synchronize.

It's good to know that it performs better than rwlock (albeit it's not surprising).

2) I'm concerned about what looks like a use of hazptr to protect linked lists elements in your benchmark (did I miss anything ?).

RCU read-side critical sections protect all elements of a linked list naturally, but hazptr requires more care. See this comment above hazptr_acquire:

* This protection is unconditional, and has limitations similar to
* that of unconditional reference-counter acquisition. In particular,
* although holding a hazard pointer prevents a hazard-pointer-protected
* object from being freed, it does not prevent that object from being
* removed from a linked data structure, and does not prevent other
* hazard-pointer-protected objects referenced by this object from being
* both removed and freed. At which point, invoking hazptr_acquire()
* on these dangling pointers would be a bug. On the other hand, use of
* hazptr_acquire() is safe for immortal pointers to objects that do not
* themselves contain pointers to hazard-pointer-protected objects.
* Other (more complex) use cases are also possible.

Does the pointer you protect qualify as an "immortal" pointer, or it's a linked list "next" pointer ?

Thanks,

Mathieu

Quoted 192 lines

SIGIO delivery, plain mode, 8 ptys 1 listener each (identical harness):

BASELINE (rwlock) 472/s
CONVERTED v4 (hazptr) 452/s ← singleton fast path: gap 12% → 4%

With a few changes, it was 12% slower than rcu before.

Do you want those changes?

My idea is, we find something that would put use to hazptr, here is what I tried

fs/fcntl.c +47 -37
index c158f082f1da..bb04076ff6d9 100644
@@ -17,6 +17,7 @@
  #include <linux/slab.h>
  #include <linux/module.h>
  #include <linux/pipe_fs_i.h>
+#include <linux/hazptr.h>
  #include <linux/security.h>
  #include <linux/ptrace.h>
  #include <linux/signal.h>
@@ -1009,15 +1010,20 @@ int fasync_remove_entry(struct file *filp, struct fasync_struct **fapp)
  		if (fa->fa_file != filp)
  			continue;
 
-		write_lock_irq(&fa->fa_lock);
+		/*
+		 * Make the file invisible to the walk before unlinking,
+		 * then wait for any in-flight send_sigio() to be done with
+		 * the node before freeing it.  The walk holds a hazard
+		 * pointer to this node, so it cannot already be freed.
+		 */
  		fa->fa_file = NULL;
-		write_unlock_irq(&fa->fa_lock);
-
  		*fp = fa->fa_next;
-		kfree_rcu(fa, fa_rcu);
+		spin_unlock(&fasync_lock);
+		spin_unlock(&filp->f_lock);
+		hazptr_synchronize(fa);
+		fasync_free(fa);
  		filp->f_flags &= ~FASYNC;
-		result = 1;
-		break;
+		return 1;
  	}
  	spin_unlock(&fasync_lock);
  	spin_unlock(&filp->f_lock);
@@ -1056,13 +1062,10 @@ struct fasync_struct *fasync_insert_entry(int fd, struct file *filp, struct fasy
  		if (fa->fa_file != filp)
  			continue;
 
-		write_lock_irq(&fa->fa_lock);
-		fa->fa_fd = fd;
-		write_unlock_irq(&fa->fa_lock);
+		WRITE_ONCE(fa->fa_fd, fd);
  		goto out;
  	}
 
-	rwlock_init(&new->fa_lock);
  	new->magic = FASYNC_MAGIC;
  	new->fa_file = filp;
  	new->fa_fd = fd;
@@ -1121,44 +1124,51 @@ EXPORT_SYMBOL(fasync_helper);
  /*
   * rcu_read_lock() is held
   */
-static void kill_fasync_rcu(struct fasync_struct *fa, int sig, int band)
+void kill_fasync(struct fasync_struct **fp, int sig, int band)
  {
+	struct hazptr_ctx cur, nxt;
+	struct fasync_struct *fa;
+
+	/* First a quick test without locking: usually
+	 * the list is empty.
+	 */
+	fa = READ_ONCE(*fp);
+	if (!fa)
+		return;
+
+	/*
+	 * Hand-over-hand with two ping-ponged contexts: the next node
+	 * must be acquired before the current one is released, but a
+	 * hazptr_ctx may only front one live slot at a time.
+	 */
+	cur = (struct hazptr_ctx){ };
+	nxt = (struct hazptr_ctx){ };
+	fa = hazptr_acquire(&cur, (void * const *)fp);
  	while (fa) {
-		struct fown_struct *fown;
-		unsigned long flags;
+		struct fasync_struct *next;
 
  		if (fa->magic != FASYNC_MAGIC) {
  			printk(KERN_ERR "kill_fasync: bad magic number in "
  			       "fasync_struct!\n");
-			return;
+			break;
  		}
-		read_lock_irqsave(&fa->fa_lock, flags);
+
  		if (fa->fa_file) {
-			fown = file_f_owner(fa->fa_file);
-			if (!fown)
-				goto next;
-			/* Don't send SIGURG to processes which have not set a
-			   queued signum: SIGURG has its own default signalling
-			   mechanism. */
-			if (!(sig == SIGURG && fown->signum == 0))
+			struct fown_struct *fown = file_f_owner(fa->fa_file);
+
+			if (fown &&
+			    /* Don't send SIGURG to processes which have not set a
+			       queued signum: SIGURG has its own default signalling
+			       mechanism. */
+			    !(sig == SIGURG && fown->signum == 0))
  				send_sigio(fown, fa->fa_fd, band);
  		}
-next:
-		read_unlock_irqrestore(&fa->fa_lock, flags);
-		fa = rcu_dereference(fa->fa_next);
-	}
-}
-
-void kill_fasync(struct fasync_struct **fp, int sig, int band)
-{
-	/* First a quick test without locking: usually
-	 * the list is empty.
-	 */
-	if (*fp) {
-		rcu_read_lock();
-		kill_fasync_rcu(rcu_dereference(*fp), sig, band);
-		rcu_read_unlock();
+		next = hazptr_acquire(&nxt, (void * const *)&fa->fa_next);
+		hazptr_release(&cur, fa);
+		swap(cur, nxt);
+		fa = next;
  	}
+	hazptr_release(&cur, fa);
  }
  EXPORT_SYMBOL(kill_fasync);
 
include/linux/fs.h +0 -1
index f9d1e05e8ae6..852f1b8c00af 100644
@@ -1365,7 +1365,6 @@ static inline struct dentry *file_dentry(const struct file *file)
  }
 
  struct fasync_struct {
-	rwlock_t		fa_lock;
  	int			magic;
  	int			fa_fd;
  	struct fasync_struct	*fa_next; /* singly linked list */

Anything I did wrong? No?

Quoted 18 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
Quoted 7 lines
Documentation/RCU/rcu_dereference.rst |  38 +++++++-
include/linux/compiler.h              |  63 ++++++++++++
include/linux/hazptr.h                |  47 +++++----
kernel/hazptr.c                       | 135 +++++++++++++++-----------
4 files changed, 203 insertions(+), 80 deletions(-)

--- Thanks!
"I'm not a very positive person" - Linus torvalds

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#27 lore raw
Quoted 65 lines · Mathieu Desnoyers
Quoted 33 lines · Bradley Morgan
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 8 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Hi, here is a hazptr perf test on powerpc

REAL kill_fasync(), ns per call, best of 3, 100k calls:
(stock = rwlock walk, conv = hazptr walk, same v3 tree ± the conversion)

   shape          stock    conv     delta
   1 node,  1 walker     59      59     +0.0%   (singleton: identical)
   16 nodes, 1 walker   539     539     +0.0%   (uncontended: identical)
   16 nodes, 4 walkers  509     134    -73.7%   ← rwlock readers contend
   16 nodes, 8 walkers  313     113    -63.9%   ← same list, 8 cpus
   64 nodes, 1 walker  1979    2039     +3.0%   (pure walk: hazptr tax)
   64 nodes, 4 walkers 1914     509    -73.4%
   64 nodes, 8 walkers 1015     382    -62.4%
Quoted 1 line

Its SLOWER than rcu, but beats rwlock

Two feedback points:

1) The comparison I think Boqun cares mostly about is with expedited RCU grace periods, this is where we suspect there is a significant benefit to using hazptr rather than RCU to eliminate those IPIs on synchronize.

It's good to know that it performs better than rwlock (albeit it's not surprising).

2) I'm concerned about what looks like a use of hazptr to protect linked lists elements in your benchmark (did I miss anything ?).

RCU read-side critical sections protect all elements of a linked list naturally, but hazptr requires more care. See this comment above hazptr_acquire:

* This protection is unconditional, and has limitations similar to
* that of unconditional reference-counter acquisition. In particular,
* although holding a hazard pointer prevents a hazard-pointer-protected
* object from being freed, it does not prevent that object from being
* removed from a linked data structure, and does not prevent other
* hazard-pointer-protected objects referenced by this object from being
* both removed and freed. At which point, invoking hazptr_acquire()
* on these dangling pointers would be a bug. On the other hand, use of
* hazptr_acquire() is safe for immortal pointers to objects that do not
* themselves contain pointers to hazard-pointer-protected objects.
* Other (more complex) use cases are also possible.

Quoted 3 lines

Does the pointer you protect qualify as an "immortal" pointer, or it's a linked list "next" pointer ?

Hmm. Do you have a idea on what you could metaphorically convert, with a core subsystem?

I'll give anything you want me to do a try

Quoted 148 lines

Thanks,

Mathieu

Quoted 11 lines

SIGIO delivery, plain mode, 8 ptys 1 listener each (identical harness):

BASELINE (rwlock) 472/s
CONVERTED v4 (hazptr) 452/s ← singleton fast path: gap 12% → 4%

With a few changes, it was 12% slower than rcu before.

Do you want those changes?

My idea is, we find something that would put use to hazptr, here is what

I

fs/fcntl.c int fasync_remove_entry(struct file *filp,

Quoted 16 lines

tried

fs/fcntl.c +1 -0
index c158f082f1da..bb04076ff6d9 100644
@@ -17,6 +17,7 @@
  #include <linux/slab.h>
  #include <linux/module.h>
  #include <linux/pipe_fs_i.h>
+#include <linux/hazptr.h>
  #include <linux/security.h>
  #include <linux/ptrace.h>
  #include <linux/signal.h>
@@ -1009,15 +1010,20 @@ int fasync_remove_entry(struct file *filp,

struct fasync_struct **fapp)

fs/fcntl.c struct fasync_struct *fasync_insert_entry(int

Quoted 26 lines
fs/fcntl.c +11 -5
  		if (fa->fa_file != filp)
  			continue;
  -		write_lock_irq(&fa->fa_lock);
+		/*
+		 * Make the file invisible to the walk before unlinking,
+		 * then wait for any in-flight send_sigio() to be done with
+		 * the node before freeing it.  The walk holds a hazard
+		 * pointer to this node, so it cannot already be freed.
+		 */
  		fa->fa_file = NULL;
-		write_unlock_irq(&fa->fa_lock);
-
  		*fp = fa->fa_next;
-		kfree_rcu(fa, fa_rcu);
+		spin_unlock(&fasync_lock);
+		spin_unlock(&filp->f_lock);
+		hazptr_synchronize(fa);
+		fasync_free(fa);
  		filp->f_flags &= ~FASYNC;
-		result = 1;
-		break;
+		return 1;
  	}
  	spin_unlock(&fasync_lock);
  	spin_unlock(&filp->f_lock);
@@ -1056,13 +1062,10 @@ struct fasync_struct *fasync_insert_entry(int

fd, struct file *filp, struct fasy

Quoted 13 lines
fs/fcntl.c +1 -2
  		if (fa->fa_file != filp)
  			continue;
  -		write_lock_irq(&fa->fa_lock);
-		fa->fa_fd = fd;
-		write_unlock_irq(&fa->fa_lock);
+		WRITE_ONCE(fa->fa_fd, fd);
  		goto out;
  	}
  -	rwlock_init(&new->fa_lock);
  	new->magic = FASYNC_MAGIC;
  	new->fa_file = filp;
  	new->fa_fd = fd;

fs/fcntl.c EXPORT_SYMBOL(fasync_helper); · line 1124

Quoted 4 lines
fs/fcntl.c +0 -1
@@ -1121,44 +1124,51 @@ EXPORT_SYMBOL(fasync_helper);
  /*
   * rcu_read_lock() is held
   */
-static void kill_fasync_rcu(struct fasync_struct *fa, int sig, int

band)

Quoted 70 lines
fs/fcntl.c +34 -26
+void kill_fasync(struct fasync_struct **fp, int sig, int band)
  {
+	struct hazptr_ctx cur, nxt;
+	struct fasync_struct *fa;
+
+	/* First a quick test without locking: usually
+	 * the list is empty.
+	 */
+	fa = READ_ONCE(*fp);
+	if (!fa)
+		return;
+
+	/*
+	 * Hand-over-hand with two ping-ponged contexts: the next node
+	 * must be acquired before the current one is released, but a
+	 * hazptr_ctx may only front one live slot at a time.
+	 */
+	cur = (struct hazptr_ctx){ };
+	nxt = (struct hazptr_ctx){ };
+	fa = hazptr_acquire(&cur, (void * const *)fp);
  	while (fa) {
-		struct fown_struct *fown;
-		unsigned long flags;
+		struct fasync_struct *next;
    		if (fa->magic != FASYNC_MAGIC) {
  			printk(KERN_ERR "kill_fasync: bad magic number in "
  			       "fasync_struct!\n");
-			return;
+			break;
  		}
-		read_lock_irqsave(&fa->fa_lock, flags);
+
  		if (fa->fa_file) {
-			fown = file_f_owner(fa->fa_file);
-			if (!fown)
-				goto next;
-			/* Don't send SIGURG to processes which have not set a
-			   queued signum: SIGURG has its own default signalling
-			   mechanism. */
-			if (!(sig == SIGURG && fown->signum == 0))
+			struct fown_struct *fown = file_f_owner(fa->fa_file);
+
+			if (fown &&
+			    /* Don't send SIGURG to processes which have not set a
+			       queued signum: SIGURG has its own default signalling
+			       mechanism. */
+			    !(sig == SIGURG && fown->signum == 0))
  				send_sigio(fown, fa->fa_fd, band);
  		}
-next:
-		read_unlock_irqrestore(&fa->fa_lock, flags);
-		fa = rcu_dereference(fa->fa_next);
-	}
-}
-
-void kill_fasync(struct fasync_struct **fp, int sig, int band)
-{
-	/* First a quick test without locking: usually
-	 * the list is empty.
-	 */
-	if (*fp) {
-		rcu_read_lock();
-		kill_fasync_rcu(rcu_dereference(*fp), sig, band);
-		rcu_read_unlock();
+		next = hazptr_acquire(&nxt, (void * const *)&fa->fa_next);
+		hazptr_release(&cur, fa);
+		swap(cur, nxt);
+		fa = next;
  	}
+	hazptr_release(&cur, fa);
Quoted 50 lines

include/linux/fs.h static inline struct dentry *file_dentry(const

Quoted 7 lines
fs/fcntl.c +0 -0
  }
  EXPORT_SYMBOL(kill_fasync);
  diff --git a/include/linux/fs.h b/include/linux/fs.h

index f9d1e05e8ae6..852f1b8c00af 100644

include/linux/fs.h +0 -0
@@ -1365,7 +1365,6 @@ static inline struct dentry *file_dentry(const

struct file *file)

Quoted 39 lines
include/linux/fs.h +0 -1
  }
    struct fasync_struct {
-	rwlock_t		fa_lock;
  	int			magic;
  	int			fa_fd;
  	struct fasync_struct	*fa_next; /* singly linked list */
 

Anything I did wrong? No?

Quoted 18 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
Quoted 7 lines
Documentation/RCU/rcu_dereference.rst |  38 +++++++-
include/linux/compiler.h              |  63 ++++++++++++
include/linux/hazptr.h                |  47 +++++----
kernel/hazptr.c                       | 135 +++++++++++++++-----------
4 files changed, 203 insertions(+), 80 deletions(-)

--- Thanks!
"I'm not a very positive person" - Linus torvalds

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

author reviewer
#28 lore raw
Quoted 67 lines · Bradley Morgan
Quoted 65 lines · Mathieu Desnoyers
Quoted 33 lines · Bradley Morgan
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 8 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Hi, here is a hazptr perf test on powerpc

REAL kill_fasync(), ns per call, best of 3, 100k calls:
(stock = rwlock walk, conv = hazptr walk, same v3 tree ± the conversion)

    shape          stock    conv     delta
    1 node,  1 walker     59      59     +0.0%   (singleton: identical)
    16 nodes, 1 walker   539     539     +0.0%   (uncontended: identical)
    16 nodes, 4 walkers  509     134    -73.7%   ← rwlock readers contend
    16 nodes, 8 walkers  313     113    -63.9%   ← same list, 8 cpus
    64 nodes, 1 walker  1979    2039     +3.0%   (pure walk: hazptr tax)
    64 nodes, 4 walkers 1914     509    -73.4%
    64 nodes, 8 walkers 1015     382    -62.4%
Quoted 1 line

Its SLOWER than rcu, but beats rwlock

Two feedback points:

1) The comparison I think Boqun cares mostly about is with expedited RCU grace periods, this is where we suspect there is a significant benefit to using hazptr rather than RCU to eliminate those IPIs on synchronize.

It's good to know that it performs better than rwlock (albeit it's not surprising).

2) I'm concerned about what looks like a use of hazptr to protect linked lists elements in your benchmark (did I miss anything ?).

RCU read-side critical sections protect all elements of a linked list naturally, but hazptr requires more care. See this comment above hazptr_acquire:

* This protection is unconditional, and has limitations similar to
* that of unconditional reference-counter acquisition. In particular,
* although holding a hazard pointer prevents a hazard-pointer-protected
* object from being freed, it does not prevent that object from being
* removed from a linked data structure, and does not prevent other
* hazard-pointer-protected objects referenced by this object from being
* both removed and freed. At which point, invoking hazptr_acquire()
* on these dangling pointers would be a bug. On the other hand, use of
* hazptr_acquire() is safe for immortal pointers to objects that do not
* themselves contain pointers to hazard-pointer-protected objects.
* Other (more complex) use cases are also possible.

Quoted 8 lines
Quoted 3 lines

Does the pointer you protect qualify as an "immortal" pointer, or it's a linked list "next" pointer ?

Hmm. Do you have a idea on what you could metaphorically convert, with a core subsystem?

I'll give anything you want me to do a try

At a high level, I suspect it would be good to start by digging into users of synchronize_rcu_expedited(), to see if a few of those may be good candidates.

I would also favor scenarios where RCU (or locking) are used to protect the existence of an object reachable from a global pointer, and use hazptr to protect that object. Note that initially this precludes a hazptr-protected list, because the next pointers would sit in prior objects which are themselves hazptr-protected, which is not sufficient to guarantee existence against a hand in hand traversal.

However, if you have a pointer to an object "side-car" structure (e.g. optional extra metadata), and the object containing the pointer is guaranteed to exist by another mechanism (e.g. RCU, locking), then that pointer-to-side-car-object field would be a good candidate for hazptr (AFAIU).

I'm not saying the linked lists could not be done, but it would require more care.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
maintainer
#29 lore raw
Quoted 86 lines · Mathieu Desnoyers
Quoted 67 lines · Bradley Morgan
Quoted 65 lines · Mathieu Desnoyers
Quoted 33 lines · Bradley Morgan
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 8 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Hi, here is a hazptr perf test on powerpc

REAL kill_fasync(), ns per call, best of 3, 100k calls:
(stock = rwlock walk, conv = hazptr walk, same v3 tree ± the conversion)

    shape          stock    conv     delta
    1 node,  1 walker     59      59     +0.0%   (singleton: identical)
    16 nodes, 1 walker   539     539     +0.0%   (uncontended: identical)
    16 nodes, 4 walkers  509     134    -73.7%   ← rwlock readers contend
    16 nodes, 8 walkers  313     113    -63.9%   ← same list, 8 cpus
    64 nodes, 1 walker  1979    2039     +3.0%   (pure walk: hazptr tax)
    64 nodes, 4 walkers 1914     509    -73.4%
    64 nodes, 8 walkers 1015     382    -62.4%
Quoted 1 line

Its SLOWER than rcu, but beats rwlock

Two feedback points:

1) The comparison I think Boqun cares mostly about is with expedited RCU grace periods, this is where we suspect there is a significant benefit to using hazptr rather than RCU to eliminate those IPIs on synchronize.

It's good to know that it performs better than rwlock (albeit it's not surprising).

2) I'm concerned about what looks like a use of hazptr to protect linked lists elements in your benchmark (did I miss anything ?).

RCU read-side critical sections protect all elements of a linked list naturally, but hazptr requires more care. See this comment above hazptr_acquire:

* This protection is unconditional, and has limitations similar to
* that of unconditional reference-counter acquisition. In particular,
* although holding a hazard pointer prevents a hazard-pointer-protected
* object from being freed, it does not prevent that object from being
* removed from a linked data structure, and does not prevent other
* hazard-pointer-protected objects referenced by this object from being
* both removed and freed. At which point, invoking hazptr_acquire()
* on these dangling pointers would be a bug. On the other hand, use of
* hazptr_acquire() is safe for immortal pointers to objects that do not
* themselves contain pointers to hazard-pointer-protected objects.
* Other (more complex) use cases are also possible.

Quoted 7 lines
Quoted 2 lines

Does the pointer you protect qualify as an "immortal" pointer, or it's a linked list "next" pointer ?

Hmm. Do you have a idea on what you could metaphorically convert, with a core subsystem?

I'll give anything you want me to do a try

At a high level, I suspect it would be good to start by digging into users of synchronize_rcu_expedited(), to see if a few of those may be good candidates.

I would also favor scenarios where RCU (or locking) are used to protect the existence of an object reachable from a global pointer, and use hazptr to protect that object. Note that initially this precludes a hazptr-protected list, because the next pointers would sit in prior objects which are themselves hazptr-protected, which is not sufficient to guarantee existence against a hand in hand traversal.

Quoted 8 lines

However, if you have a pointer to an object "side-car" structure (e.g. optional extra metadata), and the object containing the pointer is guaranteed to exist by another mechanism (e.g. RCU, locking), then that pointer-to-side-car-object field would be a good candidate for hazptr (AFAIU).

I'm not saying the linked lists could not be done, but it would require more care.

Other candidates include users of per-CPU reference counters, along with any try-acquire reference counters that have seen memory contention.

Thanx, Paul

maintainer
#30 lore raw
In reply to Mathieu Desnoyers
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Thank you! That looks good from a quick look. I will give a deep look later on (I was traveling).

For the following versions/patches, could you also Cc Kuwu Chan and Liang Wang (Cced) ? They are helping on the scan thread and lockdep integration, so it'll be good to keep them in the loop. Thank you!

Quoted 9 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Nice! I want to point out that later on if the reader can handle the race with the updater (i.e. the readers don't need the progress guarantees from hazptr, then we can expose a hazptr_try_acquire() for exactly that). Although I do have some design trade-off questions for patch 4.

Regards,
Boqun

Quoted 26 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
 Documentation/RCU/rcu_dereference.rst |  38 +++++++-
 include/linux/compiler.h              |  63 ++++++++++++
 include/linux/hazptr.h                |  47 +++++----
 kernel/hazptr.c                       | 135 +++++++++++++++-----------
 4 files changed, 203 insertions(+), 80 deletions(-)
Signature · 1 line
2.43.0
author reviewer
#31 lore raw
Quoted 10 lines · Boqun Feng
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Quoted 6 lines

Thank you! That looks good from a quick look. I will give a deep look later on (I was traveling).

For the following versions/patches, could you also Cc Kuwu Chan and Liang Wang (Cced) ? They are helping on the scan thread and lockdep integration, so it'll be good to keep them in the loop. Thank you!

Noted, I've added them to my patch commit messages, so they should be there for the next round.

Quoted 11 lines
Quoted 10 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Quoted 5 lines

Nice! I want to point out that later on if the reader can handle the race with the updater (i.e. the readers don't need the progress guarantees from hazptr, then we can expose a hazptr_try_acquire() for exactly that). Although I do have some design trade-off questions for patch 4.

Sure, if you have a use-case in mind I'm interested to hear about it!

Thanks,

Mathieu

Quoted 30 lines

Regards,
Boqun

Quoted 26 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
  Documentation/RCU/rcu_dereference.rst |  38 +++++++-
  include/linux/compiler.h              |  63 ++++++++++++
  include/linux/hazptr.h                |  47 +++++----
  kernel/hazptr.c                       | 135 +++++++++++++++-----------
  4 files changed, 203 insertions(+), 80 deletions(-)
Signature · 1 line
2.43.0
Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#32 lore raw
Quoted 14 lines · Mathieu Desnoyers
Quoted 13 lines · Boqun Feng
Quoted 8 lines · Mathieu Desnoyers

Hi Paul,

This series applies on top of "hazptr: handle NULL address in hazptr_detach" you have in your rcu dev tree.

This first patch addresses a race identified by Boqun Feng in the two-phase wildcard scheme.

Thank you! That looks good from a quick look. I will give a deep look later on (I was traveling).

Quoted 7 lines
Quoted 3 lines

For the following versions/patches, could you also Cc Kuwu Chan and Liang Wang (Cced) ? They are helping on the scan thread and lockdep integration, so it'll be good to keep them in the loop. Thank you!

Noted, I've added them to my patch commit messages, so they should be there for the next round.

Maybe my tests could help you? Sorry to impede but the things I sent may need a but if discussi9n around it

Quoted 44 lines
Quoted 11 lines
Quoted 10 lines

Patches 2-3 are prerequisites for using ptr_eq() in the 4th patch. Those were discussed at length in a prior version of hazard pointer patches.

Patch 4 introduces a "try acquire" helper to allow the fast path to not rely on wildcards, while keeping the wildcard forward progress guarantees in the acquire slow path, used on fast path failure.

Quoted 5 lines

Nice! I want to point out that later on if the reader can handle the race with the updater (i.e. the readers don't need the progress guarantees from hazptr, then we can expose a hazptr_try_acquire() for exactly that). Although I do have some design trade-off questions for patch 4.

Sure, if you have a use-case in mind I'm interested to hear about it!

Thanks,

Mathieu

Quoted 21 lines

Regards,
Boqun

Quoted 17 lines

Thanks,

Mathieu

Mathieu Desnoyers (4):
hazptr: Fix two-phase hazptr_synchronize race with detach compiler.h: Introduce ptr_eq() to preserve address dependency
Documentation: RCU: Refer to ptr_eq()
hazptr: Introduce "try acquire" fast path, fallback to overflow list

Cc Paul E. McKenney <[email protected]>
Cc Boqun Feng <[email protected]>
Cc Bradley Morgan <[email protected]>
Cc Gary Guo <[email protected]>
Quoted 13 lines
Quoted 4 lines
Quoted 4 lines
  Documentation/RCU/rcu_dereference.rst |  38 +++++++-
  include/linux/compiler.h              |  63 ++++++++++++
  include/linux/hazptr.h                |  47 +++++----
  kernel/hazptr.c                       | 135

+++++++++++++++-----------

Quoted 5 lines
Quoted 5 lines
  4 files changed, 203 insertions(+), 80 deletions(-)
Signature · 1 line
2.43.0

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