Skip to contentSkip to conversation

lockdep: Keep dynamic key hash nodes in lockdep-owned storage

RFC PATCH In review Vlad Poenaru 4 participants 6 messages Oct 21 – Oct 28

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

RFC PATCH 1/1 lockdep: Keep dynamic key hash nodes in lockdep-owned storage

lockdep_register_key() links the hlist_node embedded in the caller's lock_class_key into lock_keys_hash[], and is_dynamic_key() walks that list under rcu_read_lock(). So lockdep_unregister_key() must wait for an RCU grace period before the caller may free the key, and it does, with synchronize_rcu_expedited() since commit 7a3cedafccf8 ("lockdep:
Speed up lockdep_unregister_key() with expedited RCU synchronization"). Users that unregister many keys pay for one grace period each: replacing an mq root qdisc on a multi-queue NIC waits for one per TX queue, under RTNL.

Keep the hash nodes in a static array instead, like the other lockdep tables, with an in-use bitmap sized by CONFIG_LOCKDEP_DYNAMIC_KEYS_BITS. A node records the key's address; is_dynamic_key() compares addresses and never dereferences caller memory. Unregistering unhashes the node and hands it to the existing delayed_free machinery, so the slot is reused only after a grace period, and lockdep_unregister_key() no longer waits or sleeps. Running out of nodes turns lockdep off with "BUG: MAX_LOCKDEP_DYNAMIC_KEYS too low!", like the other tables.

This follows Eric Dumazet's suggestion (quoted in the first link) to keep the RCU-protected memory out of the caller's key, but keeps the key embedded and uses a static pool rather than a separate allocation freed with kfree_rcu().

With the node gone from struct lock_class_key, the key shrinks from 16 to 8 bytes on 64-bit.

Keys freed while still registered used to be caught by KASAN when a hash walk read their embedded node. To keep catching them, lockdep_register_key() and lockdep_unregister_key() run kasan_check_byte() on each key they pass under the graph lock, where every hashed node is a live registration.

On an x86_64 KASAN + PROVE_LOCKING kernel (64 vCPU KVM guest, mq on a 64-queue netdevsim device, 214K lock chains), three rebuilds of an mq root with an fq child per TX queue wait for 198 instead of 780 expedited grace periods, and a qdisc destroy drops from 24.2 ms to 16.7 ms. The guest's vCPUs are idle; on busy machines each of those grace periods also IPIs every non-idle CPU.

---
RFC: this is the alternative Boqun asked to explore in the discussion of the net-next series that added lockdep_unregister_key_nosync() for qdiscs [1]. If this approach is acceptable, that series is no longer
needed: no caller has to wait, and there is no new API to misuse.

Open questions:
- The cap. CONFIG_LOCKDEP_DYNAMIC_KEYS_BITS defaults to 14 (16K nodes, ~384KB; 1K with LOCKDEP_SMALL). The number of registered keys used to be unbounded, and now keys whose locks are never taken count too:
an unprivileged user with a network namespace can create more than 16K qdiscs and turn lockdep off. Lock classes already have the same exposure (8K, and every qdisc that carries traffic uses one, see a90f6dcefca6d), so this may be acceptable. If not, keys registered after the pool fills could fall back to the old embedded node and the old wait, at the cost of keeping the 16-byte key.
- is_dynamic_key() still returns true when debug_locks is off. That used to avoid a use-after-free; it is kept only to preserve the behaviour.

Notes:
- Keys freed while still registered are still caught under KASAN, by the register and unregister walks; the lockless is_dynamic_key() walk no longer checks, since a correctly unregistered key may already be freed there. Freeing a registered key and then registering 16K others gets a KASAN slab-use-after-free report from lockdep_register_key().
- The comment above blk_mq_hctx_set_fq_lock_class() in block/blk-flush.c says lockdep_unregister_key() waits for a grace period; that becomes stale. I left it out of the RFC and will update it in the non-RFC version.
- This conflicts textually with Nilay Shroff's pending "lockdep: Fix subclass resource leak in lockdep_unregister_key()" [3] (the same __lockdep_free_key_range() call); either needs a trivial rebase.

Tested on tip/locking/core with KASAN + PROVE_LOCKING:
- lockdep selftests: 395/395;
- 60s stress: ~700K register/unregister/immediate-kfree() cycles against ~840M concurrent is_dynamic_key() walks, no KASAN report;
- exhaustion with CONFIG_LOCKDEP_DYNAMIC_KEYS_BITS=10: one "BUG: MAX_LOCKDEP_DYNAMIC_KEYS too low!", lockdep off, no crash;
- W=1 with gcc and clang, PROVE_LOCKING=y and LOCKDEP=y PROVE_LOCKING=n.

It is independent of "lockdep: Walk only in-use lock chains in zap_class()" [2], which makes the remaining zap_class() part cheaper.

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

 include/linux/lockdep_types.h      |  10 +--
 kernel/locking/lockdep.c           | 107 +++++++++++++++++++++--------
 kernel/locking/lockdep_internals.h |   3 +
 kernel/locking/lockdep_proc.c      |   4 +-
 lib/Kconfig.debug                  |  10 +++
 5 files changed, 98 insertions(+), 36 deletions(-)
include/linux/lockdep_types.h +5 -5
index 55c4b152fedf7..c3f318a4e48f5 100644
@@ -71,12 +71,12 @@ struct lockdep_subclass_key {
 	char __one_byte;
 } __attribute__ ((__packed__));
 
-/* hash_entry is used to keep track of dynamically allocated keys. */
+/*
+ * Only the address of a key matters; lockdep tracks dynamically allocated keys
+ * in its own hash table nodes.
+ */
 struct lock_class_key {
-	union {
-		struct hlist_node		hash_entry;
-		struct lockdep_subclass_key	subkeys[MAX_LOCKDEP_SUBCLASSES];
-	};
+	struct lockdep_subclass_key	subkeys[MAX_LOCKDEP_SUBCLASSES];
 };
 
 extern struct lock_class_key __lockdep_no_validate__;
kernel/locking/lockdep.c +78 -29

206 lines not on this page · raw message

kernel/locking/lockdep_internals.h +3 -0
index 0e5e6ffe91a3f..f214bbdd9dcfa 100644
@@ -98,6 +98,7 @@ enum {
  */
 #define MAX_LOCKDEP_ENTRIES	16384UL
 #define MAX_LOCKDEP_CHAINS_BITS	15
+#define MAX_LOCKDEP_DYNAMIC_KEYS	1024UL
 #define MAX_STACK_TRACE_ENTRIES	262144UL
 #define STACK_TRACE_HASH_SIZE	8192
 #else
@@ -105,6 +106,8 @@ enum {
 
 #define MAX_LOCKDEP_CHAINS_BITS	CONFIG_LOCKDEP_CHAINS_BITS
 
+#define MAX_LOCKDEP_DYNAMIC_KEYS	(1UL << CONFIG_LOCKDEP_DYNAMIC_KEYS_BITS)
+
 /*
  * Stack-trace: tightly packed array of stack backtrace
  * addresses. Protected by the hash_lock.
kernel/locking/lockdep_proc.c +2 -2
index 1916db9aa46b6..cab78d91a241a 100644
@@ -286,8 +286,8 @@ static int lockdep_stats_show(struct seq_file *m, void *v)
 #endif
 	seq_printf(m, " lock-classes:                  %11lu [max: %lu]\n",
 			nr_lock_classes, MAX_LOCKDEP_KEYS);
-	seq_printf(m, " dynamic-keys:                  %11lu\n",
-			nr_dynamic_keys);
+	seq_printf(m, " dynamic-keys:                  %11lu [max: %lu]\n",
+			nr_dynamic_keys, MAX_LOCKDEP_DYNAMIC_KEYS);
 	seq_printf(m, " direct dependencies:           %11lu [max: %lu]\n",
 			nr_list_entries, MAX_LOCKDEP_ENTRIES);
 	seq_printf(m, " indirect dependencies:         %11lu\n",
lib/Kconfig.debug +10 -0
index 134b15a44625e..993a9c24ffcc0 100644
@@ -1571,6 +1571,16 @@ config LOCKDEP_CHAINS_BITS
 	help
 	  Try increasing this value if you hit "BUG: MAX_LOCKDEP_CHAINS too low!" message.
 
+config LOCKDEP_DYNAMIC_KEYS_BITS
+	int "Size for MAX_LOCKDEP_DYNAMIC_KEYS (as Nth power of 2)"
+	depends on LOCKDEP && !LOCKDEP_SMALL
+	range 10 20
+	default 14
+	help
+	  Try increasing this value if you hit "BUG: MAX_LOCKDEP_DYNAMIC_KEYS too low!" message.
+	  The message can also mean that keys are freed without calling
+	  lockdep_unregister_key(), which leaks their slots.
+
 config LOCKDEP_STACK_TRACE_BITS
 	int "Size for MAX_STACK_TRACE_ENTRIES (as Nth power of 2)"
 	depends on LOCKDEP && !LOCKDEP_SMALL
Signature · 1 line
2.53.0-Meta
#1 lore raw
Quoted 5 lines · Vlad Poenaru

#define MAX_LOCKDEP_ENTRIES 16384UL
#define MAX_LOCKDEP_CHAINS_BITS 15
+#define MAX_LOCKDEP_DYNAMIC_KEYS 1024UL
#define MAX_STACK_TRACE_ENTRIES 262144UL
#define STACK_TRACE_HASH_SIZE 8192

This patch introduces a new hard upper limit on the number of dynamic lockdep keys. That's unfortunate but I assume it's not possible to eliminate this hard upper bound if the key storage is owned by lockdep?

Thanks,

Bart.

#2 lore raw
Quoted 4 lines · Bart Van Assche

This patch introduces a new hard upper limit on the number of dynamic lockdep keys. That's unfortunate but I assume it's not possible to eliminate this hard upper bound if the key storage is owned by lockdep?

It isn't inherent; it comes from preallocating the nodes the way lockdep does for its other tables. Two ways to lift it:

1. Fall back to the embedded node when the pool is full. Keys registered after that are linked through their own hash_entry, as today, and only those wait for a grace period when they are unregistered. The key stays at 16 bytes and there is a second lookup path, but running out becomes a slowdown instead of lockdep turning itself off.

2. Grow the pool in chunks allocated outside the graph lock in lockdep_register_key(). That removes the bound without a fallback, but it is the allocation Boqun preferred to avoid.

For what it's worth, keys whose locks are ever taken already count against MAX_LOCKDEP_KEYS (8K classes), and the default pool is 16K, so what the cap adds is a limit on keys that never get a class.

Boqun, would you prefer (1), so that the cap can never turn lockdep off?

Thanks,
Vlad

maintainer
#3 lore raw
Quoted 9 lines · Vlad Poenaru
Quoted 4 lines · Bart Van Assche

This patch introduces a new hard upper limit on the number of dynamic lockdep keys. That's unfortunate but I assume it's not possible to eliminate this hard upper bound if the key storage is owned by lockdep?

It isn't inherent; it comes from preallocating the nodes the way lockdep does for its other tables. Two ways to lift it:

Quoted 7 lines

1. Fall back to the embedded node when the pool is full. Keys registered after that are linked through their own hash_entry, as today, and only those wait for a grace period when they are unregistered. The key stays at 16 bytes and there is a second lookup path, but running out becomes a slowdown instead of lockdep turning itself off.

This gives me feeling that we did something for nothing, because in a system where there are a plenty of dynamic keys, we back to the current status after we introduce another hashlist.

Quoted 8 lines

2. Grow the pool in chunks allocated outside the graph lock in lockdep_register_key(). That removes the bound without a fallback, but it is the allocation Boqun preferred to avoid.

For what it's worth, keys whose locks are ever taken already count against MAX_LOCKDEP_KEYS (8K classes), and the default pool is 16K, so what the cap adds is a limit on keys that never get a class.

Yeah, I think if everyone call lockdep_init_map_type() right after lockdep_register_key(), MAX_LOCKDEP_KEYS will be reached to the limit before MAX_LOCKDEP_DYNAMIC_KEYS. So technically it's not a new limitation. Honestly you can just make MAX_LOCKDEP_DYNAMIC_KEYS = 2 * MAX_LOCKDEP_KEYS (i.e. without introducing a Kconfig), "2 *" is needed because a key can be in-between lockdep_register_key() and lockdep_init_map_type() and pending_free can be delayed, so "2 *" provides a buffer for when active key numbers > class numbers.

It might be worth checking whether a lockdep_register_key() is always followed by a some sort of lockdep_init_map_type() in the kernel code base.

Regards,
Boqun

Quoted 4 lines

Boqun, would you prefer (1), so that the cap can never turn lockdep off?

Thanks,
Vlad

#4 lore raw

On Mon, Oct 26, 2026 at 07:07:39AM -0700, Boqun Feng wrote: > Yeah, I think if everyone call lockdep_init_map_type() right after > lockdep_register_key(), MAX_LOCKDEP_KEYS will be reached to the limit > before MAX_LOCKDEP_DYNAMIC_KEYS. So technically it's not a new > limitation. Honestly you can just make MAX_LOCKDEP_DYNAMIC_KEYS = 2 * > MAX_LOCKDEP_KEYS (i.e. without introducing a Kconfig), "2 *" is needed > because a key can be in-between lockdep_register_key() and > lockdep_init_map_type() and pending_free can be delayed, so "2 *" > provides a buffer for when active key numbers > class numbers. > > It might be worth checking whether a lockdep_register_key() is always > followed by a some sort of lockdep_init_map_type() in the kernel code > base.

I went through all the callers (36 call sites). Mostly yes, with a few
exceptions: ath11k/ath12k register a key for every SRNG ring id (170-210 per device) but only initialize the rings they set up, hugetlb_cgroup initializes when the cgroup file is created, and omap_hwmod, ucsi and jbd2 skip the init on error paths. (omap_hwmod also frees a registered key without unregistering it on one allocation failure; I'll send a separate fix.)

The init itself doesn't take a class: every caller uses subclass 0, so the class only appears on the first acquire. That matters for qdiscs. mq creates a child for every TX queue, up to 4096 per device, each with its own key, and a child's q.lock isn't taken until the device is deactivated (or, for qdisc kinds that take it on transmit, until there is traffic). In a VM with this RFC, four dummy devices with numtxqueues 4096 and an mq root, left down, went from 214 to 16384 dynamic keys while the classes stayed under 900, and the pool ran out.

The class table is already exposed the same way, though. Deactivating a device takes the q.lock of every TX queue's qdisc in some_qdisc_is_busy(), so on current tip two such devices taken up and down went from 852 to 8192 classes and hit "BUG: MAX_LOCKDEP_KEYS too low!". (I ran both as root; from the code, the same commands should only need CAP_NET_ADMIN in a user namespace.) So the cap adds another way to reach a limit the same user can already reach. Agreed on dropping (1), and I'll go with your suggestion:
MAX_LOCKDEP_DYNAMIC_KEYS = 2 * MAX_LOCKDEP_KEYS, no Kconfig. That is 16K, the same as the RFC's current default. Should LOCKDEP_SMALL keep a smaller value? 16K nodes are ~384KB of bss on sparc64.

If the qdisc case should be narrowed anyway, net/sched could skip the key for pfifo_fast, the only qdisc with TCQ_F_NOLOCK in its static_flags, as it already does for ingress, clsact and noqueue. It takes q.lock only around its requeue lists (gso_skb, skb_bad_txq) and in control paths, never across a nested transmit, so I don't think that brings back the mirred false positive from af0cb3fa3f9e, but netdev would have to agree. It wouldn't bound the count either, since the user picks the qdisc kind.

Does that work for you?

Thanks,
Vlad

#5 lore raw
Quoted 5 lines · Vlad Poenaru

On Mon, Oct 26, 2026 at 07:07:39AM -0700, Boqun Feng wrote: > Yeah, I

If the qdisc case should be narrowed anyway, net/sched could skip the key for pfifo_fast, the only qdisc with TCQ_F_NOLOCK in its static_flags, as it already does for ingress, clsact and noqueue.

I was tempted to do ^^ this in the past, but then I gave up because TCQ_F_NOLOCK can theoretically flip [1]. So I was afraid there was one (remote, but still possible) situation where pfifo would use the qdisc lock with no lockdep annotation.

Quoted 4 lines

takes q.lock only around its requeue lists (gso_skb, skb_bad_txq) and in control paths, never across a nested transmit, so I don't think that brings back the mirred false positive from af0cb3fa3f9e, but netdev would have to agree.

maybe this doesn't happen for real, because only non-root pfifos would have TCQ_F_NOLOCK bit cleared. But I wasn't 100% sure, and also afraid of causing troubles on qdisc dismantle - so I decided to settle with a better though sub-optimal allocation of dynamic keys for pfifo. If we are sure that pfifos never use their qdisc root lock, I'm ok for a patch that avoids registering dynamic keys like it happens for clsact.

Signature · 3 lines
davide

[1] https://elixir.bootlin.com/linux/v7.3/source/net/sched/sch_api.c#L1198