Skip to contentSkip to conversation

lockdep: change 5 graph-db arrays to AofAs, fill from memblock pool

PATCH In review Jim Cromie 2 participants 13 messages Aug 27 Locking primitives

lore
Share & tools
lore

Jim Cromie

author
#0 lore raw

cover lockdep: change 5 graph-db arrays to AofAs, fill from memblock pool

Lockdep cannot rely upon any other subsystem that uses locks, so since inception, its graph-db has been stored in static arrays, pinning ~10 MB in .bss. This is a hardcoded compromise between embedded and enterprise hardware.

However, if it acts early, lockdep can pre-allocate a pool of slabs from memblock_alloc(), enough for its lifetime of anticipated workloads. Then it can allocate them as needed to provide new segments/slabs to the graph-db.

With that idea, we:

0. Add lockdep_early_init() hook in start_kernel() right before mm_core_init() to grab a private pool of 64 KB slabs from memblock.

1. Add DECLARE_CHUNKED_ARRAY() to build 2D chunk pointer tables. Indexing uses a compile-time hybrid:
- Power-of-2 tables (lock_chains @ 2,048/slab, chain_hlocks @ 32,768/slab) use single-cycle bit shifts (idx >> SHIFT) and masks (idx & MASK) for zero-overhead cache verification.
- Non-power-of-2 structs (lock_classes @ 409/slab, list_entries @ 1,365/slab) use Granlund-Montgomery reciprocal divide to achieve >99.8% slab packing density, avoiding 1.75 MB of internal dead padding.

2. Deploy chunked arrays across the 5 graph-db tables:
- lock_classes: struct lock_class (160 B) -> lock_class_chunk0 (409 / slab)

   - list_entries: struct lock_list  (48 B)  -> list_entries_chunk0 (1,365 / slab)
   - lock_chains:  struct lock_chain (32 B)  -> lock_chain_chunk0 (2,048 / slab)
   - chain_hlocks: u16               (2 B)   -> chain_hlock_chunk0 (32,768 / slab)
   - stack_trace:  unsigned long     (8 B)   -> stack_trace_chunk0 (8,192 / slab)

Each static name##_chunk0 in .bss (~320 kB total) provisions the graph-db with initial storage to cover early boot until memblock is up.

3. Embed struct lock_class.class_idx and struct lock_chain.chain_idx to replace flat pointer arithmetic (ptr - base) with O(1) index queries across disjoint 2D slabs.

4. Dole slabs out on demand to the 5 consumers via an index bump under graph_lock (zero allocator locks, zero recursion risk).

5. Auto-tune the pool size based on RAM and accept boot overrides via lockdep_slabs=N and lockdep_headroom=M%.

6. At late_initcall, satisfy both constraints (slabs >= N and headroom

Quoted 1 line

= M%), and return all unused excess slabs to the buddy allocator

via free_reserved_page().

7. Expose pool usage and remaining headroom via /proc/lockdep_stats and log lifetime usage via a reboot notifier.

8. On debug_locks_off() or OOM, immediately sacrifice all dynamically claimed slabs back to the buddy allocator.

Static .bss Memory Savings (vmlinux x86_64 defconfig):

    Kernel                 .bss Section Size       Notes
    ----------------------------------------------------------------------
    Upstream (Static)      12.46 MB (13061164 B)   Fixed max-sized arrays
    Patched (Memblock)      2.30 MB ( 2410988 B)   5 * 64 kB Chunk 0s in .bss
    ----------------------------------------------------------------------
    Net Savings            -10.16 MB (81.5% reduction in .bss)

Memblock-Pool Elasticity & Buddy Return:

  [ 0.850318] lockdep: boot complete : 9/64 slabs used, 41 kept (355% headroom), 23 returned to buddy (1472 kB freed)

That VM boot consumed 9 slabs (576 kB), keeps 41 slabs (2624 kB, 355% headroom) for runtime growth, and returns 23 slabs (1472 kB) to buddy at late_initcall:

The boot-args let user specify the reserved-slab-pool size:
lockdep_slabs=N # min ct of 64kb slabs kept
lockdep_headroom=N% # added % to boot-complete numbers, default is 100%

Workload Stress Performance & CPU Overheads (perf stat, 4 vCPUs):

    Benchmark     Metric          Upstream (Base)     Patched (Memblock)  Delta
    ---------------------------------------------------------------------------
    hackbench     Runtime             8.482 s             8.278 s        -2.40%
    hackbench     Cycles          52899510936         52033166458        -1.64%
    hackbench     Instructions    29008189069         31698626928        +9.27%
    netns         Runtime             9.704 s            13.321 s       +37.28%
    netns         Cycles           3941156282          5077381493       +28.83%
    netns         Instructions     2758079004          3008859260        +9.09%
    vfs           Runtime            10.544 s            10.608 s        +0.60%
    vfs           Cycles          48150692681         48840696114        +1.43%
    vfs           Instructions    32621052088         35448537908        +8.67%
    modstorm      Runtime             0.611 s             0.585 s        -4.17%
    modstorm      Cycles            512425082           514784953        +0.46%
    modstorm      Instructions      349890783           383054584        +9.48%

    Under heavy lock contention (hackbench), the power-of-2 fast-path on
    chain_hlocks and lock_chains brings total cycle consumption to parity
    with or slightly faster than upstream baseline (-1.64% cycles).

Workload specifics (virtme-ng, 4 vCPUs, 4 GB RAM):
- hackbench: hackbench -p -g 8 -l 1000

- netns:     40 netns add/del cycles with paired veth interfaces
- vfs:       8 parallel workers creating 200 dirs, files, symlinks + rm -rf
- modstorm:  10 sequential rounds of batch modprobe/rmmod (dummy loop null_blk brd tun)

What's Unchanged:
- All lockdep validation invariants, BFS graph algorithms, and deadlock detection logic are completely unmodified.
- RCU iteration semantics across lock classes and chains remain intact.
- /proc/lockdep and /proc/lockdep_stats formatting is fully preserved.

Series Structure:
- Patch 1: Optimize zap_class() to traverse adjacency lists directly rather than scanning the global bitmap.
- Patch 2: Add chunked array infrastructure and embedded indices.
- Patch 3: Pre-reserve early memblock slab pool for dynamic tables.
- Patch 4: Convert 5 graph arrays to chunked tables backed by slab pool.
- Patch 5: Fast-path power-of-2 tables with shift/mask indexing.
- Patch 6: Free unused reservation slabs to buddy allocator at late boot.
- Patch 7: Expose slab pool telemetry in /proc/lockdep_stats and initcalls.
- Patch 8: On debug_locks_off or OOM, recycle all slabs to buddy.

---
Jim Cromie (8):
lockdep: Traverse adjacency lists directly in zap_class()
lockdep: Add chunked array infrastructure and embedded indices
lockdep: Pre-reserve early memblock slab pool for dynamic tables
lockdep: Convert 5 graph arrays to chunked tables backed by slab pool
lockdep: Fast-path power-of-2 tables with shift/mask indexing
lockdep: Free unused reservation slabs to buddy allocator at late boot
lockdep: Expose slab pool telemetry in /proc/lockdep_stats and initcalls
lockdep: on debug_locks_off or OOM, recycle all slabs to buddy

 include/linux/lockdep.h            |   4 +-
 include/linux/lockdep_types.h      |   1 +
 init/main.c                        |   1 +
 kernel/locking/lockdep.c           | 951 ++++++++++++++++++++++++++++---------
 kernel/locking/lockdep_internals.h |  95 +++-
 kernel/locking/lockdep_proc.c      |  63 ++-
 6 files changed, 875 insertions(+), 240 deletions(-)

---
base-commit: 8d3ae59288f1e7d58d76558a6ee96d533bc5019f
change-id: 20260825-lockdep-memblock-v1-12c083225ef9

Best regards,

Signature · 1 line
Jim Cromie <[email protected]>
author
#1 lore raw

PATCH 1/8 lockdep: Traverse adjacency lists directly in zap_class()

Lockdep's canonical graph representation is its per-class adjacency lists (locks_after and locks_before). However, zap_class() operates on a flat storage-layer projection of the graph: it scans the global list_entries_in_use bitmap across the entire edge pool.

This global scan has a few defects:

0. Search Inefficiency:

On a typical booted laptop with ~2,000 lock classes and ~6,500 active dependency list entries, zapping a single class forces 6,500+ table inspections under graph_lock across 4 KB of bitmap. Zapping a batch of classes during module unload multiplies this into tens of thousands of global array iterations.

1. Projection maintenance: the bitmap must be kept up-to-date. given 0, its a net burden, but we still need the bitmap elsewhere.

2. Incompatible with Array Segmentation:

The loop relies on contiguous pointer arithmetic (list_entries + i) to map bitmap indices back to entries. This completely breaks once list_entries is segmented into dynamic 64 kB memblock slabs residing on disjoint memory pages.

So just implement the adjacency check literally, per graph-theory.

Real-world lock classes have very short adjacency lists: 3..5 entries on average for class->locks_after and class->locks_before, rarely exceeding 15.

Directly walking these lists visits only ~10..15 nodes per zapped class, replacing 6,500+ global table dereferences with a handful of cacheline-local pointer hops (>99.8% reduction in loop iterations).

Note: We continue clearing bits in list_entries_in_use for now, as alloc_list_entry() still queries the bitmap in this commit. The bitmap itself is eliminated soon

---
 kernel/locking/lockdep.c | 31 ++++++++++++++++++++++++-------
 1 file changed, 24 insertions(+), 7 deletions(-)
kernel/locking/lockdep.c +24 -7
index 2d4c5bab5af8..6a4f21f3e9c8 100644
@@ -6243,8 +6243,7 @@ static void remove_class_from_lock_chains(struct pending_free *pf,
  */
 static void zap_class(struct pending_free *pf, struct lock_class *class)
 {
-	struct lock_list *entry;
-	int i;
+	struct lock_list *entry, *tmp, *other, *other_tmp;
 
 	WARN_ON_ONCE(!class->key);
 
@@ -6252,11 +6251,29 @@ static void zap_class(struct pending_free *pf, struct lock_class *class)
 	 * Remove all dependencies this lock is
 	 * involved in:
 	 */
-	for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) {
-		entry = list_entries + i;
-		if (entry->class != class && entry->links_to != class)
-			continue;
-		__clear_bit(i, list_entries_in_use);
+	list_for_each_entry_safe(entry, tmp, &class->locks_after, entry) {
+		list_for_each_entry_safe(other, other_tmp, &entry->links_to->locks_before, entry) {
+			if (other->links_to == class) {
+				__clear_bit(other - list_entries, list_entries_in_use);
+				nr_list_entries--;
+				list_del_rcu(&other->entry);
+				break;
+			}
+		}
+		__clear_bit(entry - list_entries, list_entries_in_use);
+		nr_list_entries--;
+		list_del_rcu(&entry->entry);
+	}
+	list_for_each_entry_safe(entry, tmp, &class->locks_before, entry) {
+		list_for_each_entry_safe(other, other_tmp, &entry->links_to->locks_after, entry) {
+			if (other->links_to == class) {
+				__clear_bit(other - list_entries, list_entries_in_use);
+				nr_list_entries--;
+				list_del_rcu(&other->entry);
+				break;
+			}
+		}
+		__clear_bit(entry - list_entries, list_entries_in_use);
 		nr_list_entries--;
 		list_del_rcu(&entry->entry);
 	}
Signature · 1 line
2.55.0
author
#2 lore raw

PATCH 2/8 lockdep: Add chunked array infrastructure and embedded indices

In reply to Jim Cromie

Lockdep's dependency graph has historically relied on flat static arrays in .bss. To transition these tables to dynamically allocated slabs without incurring division instructions, introduce the DECLARE_CHUNKED_ARRAY() and DEFINE_CHUNKED_ARRAY() macros.

These macros construct 2-tier chunked arrays (Array-of-Arrays) indexed via Granlund-Montgomery reciprocal divide (reciprocal_divide()), mapping indices to (chunk, offset) tuples in constant time (~3 cycles).

Also embed class_idx into struct lock_class and chain_idx into struct lock_chain to replace flat pointer arithmetic (ptr - base) with O(1) index lookups across disjoint slab chunks.

---
 include/linux/lockdep.h            |  3 ++-
 include/linux/lockdep_types.h      |  1 +
 kernel/locking/lockdep_internals.h | 48 ++++++++++++++++++++++++++++++++++++--
 3 files changed, 49 insertions(+), 3 deletions(-)
include/linux/lockdep.h +2 -1
index 621566345406..4c96959d8ad7 100644
@@ -77,7 +77,7 @@ struct lock_chain {
 	unsigned int			irq_context :  2,
 					depth       :  6,
 					base	    : 24;
-	/* 4 byte hole */
+	unsigned int			chain_idx;
 	struct hlist_node		entry;
 	u64				chain_key;
 };
@@ -85,6 +85,7 @@ struct lock_chain {
 /*
  * Initialization, self-test and debugging-output methods:
  */
+extern void lockdep_early_init(void);
 extern void lockdep_init(void);
 extern void lockdep_reset(void);
 extern void lockdep_reset_lock(struct lockdep_map *lock);
include/linux/lockdep_types.h +1 -0
index eae115a26488..8acac0b59f69 100644
@@ -121,6 +121,7 @@ struct lock_class {
 
 	unsigned int			subclass;
 	unsigned int			dep_gen_id;
+	unsigned int			class_idx;
 
 	/*
 	 * IRQ/softirq usage tracking bits:
kernel/locking/lockdep_internals.h +46 -2

55 lines not on this page · raw message

Signature · 1 line
2.55.0
author
#3 lore raw

PATCH 3/8 lockdep: Pre-reserve early memblock slab pool for dynamic tables

In reply to Jim Cromie

Lockdep cannot allocate memory dynamically during normal runtime because it cannot recurse into allocator locks. However, before mm_core_init() brings up the buddy allocator, lockdep can claim a contiguous pool of 64 KB slabs directly from early memblock.

Add lockdep_early_init() to start_kernel() right before mm_core_init() to reserve a private pool of 64 KB slabs. Auto-tune the pool based on physical RAM (2 MB on <512 MB systems, 4 MB default, 8 MB on >64 GB servers) and accept overrides via lockdep_slabs=N and lockdep_headroom=M%.

Provide lockdep_claim_slab() and lockdep_release_slab() to dole out and recycle slabs under graph_lock without invoking external locks.

---
 init/main.c                        |   1 +
 kernel/locking/lockdep.c           | 131 +++++++++++++++++++++++++++++++++++++
 kernel/locking/lockdep_internals.h |   3 +-
 3 files changed, 134 insertions(+), 1 deletion(-)
init/main.c +1 -0
index e363232b428b..12280dfe1d11 100644
@@ -1031,6 +1031,7 @@ void start_kernel(void)
 	vfs_caches_init_early();
 	sort_main_extable();
 	trap_init();
+	lockdep_early_init();
 	mm_core_init();
 	maple_tree_init();
 	poking_init();
kernel/locking/lockdep.c +131 -0

149 lines not on this page · raw message

kernel/locking/lockdep_internals.h +2 -1
index 3d8bce0dc9f9..3344361a1c3b 100644
@@ -125,7 +125,8 @@ enum {
 #include <linux/reciprocal_div.h>
 
 #define LOCKDEP_SLAB_SIZE	(64 * 1024)
-#define LOCKDEP_MAX_SLABS	64
+#define LOCKDEP_MAX_SLABS	512
+#define LOCKDEP_DEFAULT_SLABS	64
 
 /*
  * Chunked Array Tables:
Signature · 1 line
2.55.0
author
#4 lore raw

PATCH 4/8 lockdep: Convert 5 graph arrays to chunked tables backed by slab pool

In reply to Jim Cromie

Replace the monolithic static .bss tables for lock_classes, list_entries, lock_chains, chain_hlocks, and stack_trace with 2D chunked arrays (DECLARE_CHUNKED_ARRAY) backed by the early memblock slab pool.

Retain 1 static chunk (Chunk 0) in .bss per consumer (~320 kB total) to cover early bootstrap locking before memblock is initialized:
- lock_classes: 409 items in Chunk 0 (160 B each)
- list_entries: 1,365 items in Chunk 0 (48 B each)
- lock_chains: 2,048 items in Chunk 0 (32 B each)
- chain_hlocks: 32,768 items in Chunk 0 (2 B each)
- stack_trace: 8,192 items in Chunk 0 (8 B each)

Update allocators (alloc_lock_chain(), alloc_chain_hlocks(), alloc_list_entry(), save_trace()) to claim new 64 KB slabs dynamically from the memblock reservoir under graph_lock when chunk capacity is exhausted.

Replace flat array pointer arithmetic with embedded struct indices (class->class_idx and chain->chain_idx).

---
 include/linux/lockdep.h            |   1 +
 include/linux/lockdep_types.h      |   2 +-
 kernel/locking/lockdep.c           | 600 ++++++++++++++++++++++++-------------
 kernel/locking/lockdep_internals.h |  63 ++--
 4 files changed, 436 insertions(+), 230 deletions(-)
include/linux/lockdep.h +1 -0
index 4c96959d8ad7..0ebb9a3e1bea 100644
@@ -340,6 +340,7 @@ static inline void lockdep_set_selftest_task(struct task_struct *task)
 # define lock_set_class(l, n, key, s, i)	do { (void)(key); } while (0)
 # define lock_set_novalidate_class(l, n, i)	do { } while (0)
 # define lock_set_subclass(l, s, i)		do { } while (0)
+# define lockdep_early_init()			do { } while (0)
 # define lockdep_init()				do { } while (0)
 # define lockdep_init_map_type(lock, name, key, sub, inner, outer, type) \
 		do { (void)(name); (void)(key); } while (0)
include/linux/lockdep_types.h +1 -1
index 8acac0b59f69..fa0dcf3c3f70 100644
@@ -114,6 +114,7 @@ struct lock_class {
 	 * "backward" graph nodes.
 	 */
 	struct list_head		locks_after, locks_before;
+	unsigned int			class_idx;
 
 	const struct lockdep_subclass_key *key;
 	lock_cmp_fn			cmp_fn;
@@ -121,7 +122,6 @@ struct lock_class {
 
 	unsigned int			subclass;
 	unsigned int			dep_gen_id;
-	unsigned int			class_idx;
 
 	/*
 	 * IRQ/softirq usage tracking bits:
kernel/locking/lockdep.c +388 -212

1,019 lines not on this page · raw message

kernel/locking/lockdep_internals.h +46 -17

114 lines not on this page · raw message

Signature · 1 line
2.55.0
author
#5 lore raw

PATCH 5/8 lockdep: Fast-path power-of-2 tables with shift/mask indexing

In reply to Jim Cromie

The 2D chunked arrays (DECLARE_CHUNKED_ARRAY) use Granlund-Montgomery reciprocal division (reciprocal_divide()) to map indices to (chunk, offset) tuples across 64 KB slabs. This achieves >99.8% packing density for non-power-of-2 structs (lock_classes @ 160 B and list_entries @ 48 B).

However, the ultra-hot cache-verification tables (lock_chains @ 32 B and chain_hlocks @ 2 B) have exact power-of-2 chunk counts (2,048 and 32,768 elements per 64 KB slab).

Add a compile-time branch in DECLARE_CHUNKED_ARRAY() using __builtin_ctz():
for power-of-2 tables, GCC/Clang folds translation into single-cycle bit shifts (idx >> SHIFT) and masks (idx & MASK), eliminating reciprocal multiplication overhead entirely from the hot acquire validation path.

Workload Progression (hackbench -p -g 8 -l 1000, 4 vCPUs):

Metric Upstream (1D) Generic (P2) Fast-Path (P3) Delta
====================================================================

  Runtime             8.482 s    8.895 s (+4.8%)       8.278 s  -2.40%
  Cycles          52899510936   55428687460     52033166458     -1.64%
  Instructions    29008189069   31932214532     31698626928     +9.27%

By replacing G-M multiplication with single-cycle bit shifts on the hot cache verification tables, cycle overhead drops by ~6.4% relative to Patch 2, bringing total cycles to parity with or slightly faster than upstream baseline (-1.64% cycles).

---
 kernel/locking/lockdep.c           |  2 +-
 kernel/locking/lockdep_internals.h | 15 +++++++++++++--
 2 files changed, 14 insertions(+), 3 deletions(-)
kernel/locking/lockdep.c +1 -1
index 1c8db52af1ac..b2dc7619a5e3 100644
@@ -3953,7 +3953,7 @@ static struct lock_chain *alloc_lock_chain(void)
 	if (unlikely(idx >= MAX_LOCKDEP_CHAINS))
 		return NULL;
 
-	chunk_idx = reciprocal_divide(idx, lock_chain_rv);
+	chunk_idx = idx / lock_chain_PER_CHUNK;
 	if (chunk_idx >= LOCKDEP_MAX_SLABS)
 		return NULL;
 
kernel/locking/lockdep_internals.h +13 -2
index eaa23d9b4dd5..ccd7343af672 100644
@@ -154,14 +154,25 @@ enum {
 #define DECLARE_CHUNKED_ARRAY(name, type)					\
 	enum {									\
 		name##_PER_CHUNK = (LOCKDEP_SLAB_SIZE / sizeof(type)),		\
+		name##_IS_P2     = (!(name##_PER_CHUNK & (name##_PER_CHUNK - 1))), \
+		name##_SHIFT     = (__builtin_ctz(name##_PER_CHUNK)),		\
+		name##_MASK      = (name##_PER_CHUNK - 1),			\
 	};									\
 	extern type * name##_chunks[LOCKDEP_MAX_SLABS];				\
 	extern const struct reciprocal_value name##_rv;				\
 	static __always_inline type *idx_to_##name(unsigned int idx)		\
 	{									\
-		unsigned int chunk = reciprocal_divide(idx, name##_rv);		\
-		unsigned int offset = idx - (chunk * name##_PER_CHUNK);		\
+		unsigned int chunk, offset;					\
 		type *chunk_ptr;						\
+										\
+		if (name##_IS_P2) {						\
+			chunk = idx >> name##_SHIFT;				\
+			offset = idx & name##_MASK;				\
+		} else {							\
+			chunk = reciprocal_divide(idx, name##_rv);		\
+			offset = idx - (chunk * name##_PER_CHUNK);		\
+		}								\
+										\
 		if (unlikely(chunk >= LOCKDEP_MAX_SLABS))			\
 			return NULL;						\
 		/* Pairs with smp_store_release() when new chunk slabs are published */ \
Signature · 1 line
2.55.0
author
#6 lore raw

PATCH 6/8 lockdep: Free unused reservation slabs to buddy allocator at late boot

In reply to Jim Cromie

During early boot, lockdep reserves a generous slab pool (e.g. 64 slabs = 4 MB) from memblock to guarantee uninterrupted initialization. Once the kernel reaches late_initcall, the boot locking storm is complete, and lockdep's steady-state working set is known.

Add lockdep_post_init_trim() as a late_initcall_sync handler. Calculate required runtime headroom (default 100% headroom over boot usage, with a floor of 32 slabs, or custom lockdep_slabs=N / lockdep_headroom=M%), and return all excess slabs to the buddy page allocator via free_reserved_page().

Also register a reboot notifier to log total lifetime slab consumption and remaining headroom on clean system shutdown.

---
 kernel/locking/lockdep.c      | 71 +++++++++++++++++++++++++++++++++++++++++++
 kernel/locking/lockdep_proc.c | 23 +++++++-------
 2 files changed, 83 insertions(+), 11 deletions(-)
kernel/locking/lockdep.c +71 -0
index b2dc7619a5e3..3fb6c07cea36 100644
@@ -6992,6 +6992,77 @@ void __init lockdep_init(void)
 	       sizeof(((struct task_struct *)NULL)->held_locks));
 }
 
+static int lockdep_shutdown_notify(struct notifier_block *nb,
+				   unsigned long code, void *unused)
+{
+	unsigned int used = lockdep_slabs_used - lockdep_nr_free_slabs;
+	unsigned int total = lockdep_nr_slabs;
+	unsigned int free_slabs = total > used ? total - used : 0;
+	unsigned int headroom_pct = used ? (free_slabs * 100) / used : 0;
+
+	pr_info("lockdep: shutdown summary : %u/%u slabs (%u kB/%u kB, %u%% headroom left), %lu classes, %lu chains, %u hlocks\n",
+		used, total,
+		(used * LOCKDEP_SLAB_SIZE) / 1024,
+		(total * LOCKDEP_SLAB_SIZE) / 1024,
+		headroom_pct,
+		nr_lock_classes, lock_chain_count(), chain_hlocks_used());
+
+	return NOTIFY_OK;
+}
+
+static struct notifier_block lockdep_reboot_nb = {
+	.notifier_call = lockdep_shutdown_notify,
+};
+
+static int __init lockdep_post_init_trim(void)
+{
+	unsigned int used = lockdep_slabs_used - lockdep_nr_free_slabs;
+	unsigned int initial_slabs = lockdep_nr_slabs;
+	unsigned int target_slabs, kept_headroom_slabs;
+	unsigned int freed_slabs = 0;
+	unsigned int i;
+
+	if (!lockdep_nr_slabs)
+		return 0;
+
+	/* Compute headroom requirement (default 100% or custom percentage) with 32-slab floor */
+	kept_headroom_slabs = DIV_ROUND_UP(used * requested_lockdep_headroom_pct, 100);
+	if (kept_headroom_slabs < 32)
+		kept_headroom_slabs = 32;
+
+	target_slabs = used + kept_headroom_slabs;
+
+	/* Satisfy both: target_slabs >= requested_lockdep_slabs AND headroom >= M% */
+	if (requested_lockdep_slabs > target_slabs)
+		target_slabs = requested_lockdep_slabs;
+
+	target_slabs = clamp_t(unsigned int, target_slabs, used, lockdep_nr_slabs);
+
+	/* Release excess slabs to buddy allocator */
+	if (target_slabs < lockdep_nr_slabs) {
+		for (i = target_slabs; i < lockdep_nr_slabs; i++) {
+			struct page *page = virt_to_page(lockdep_slabs[i]);
+			unsigned long p;
+
+			for (p = 0; p < (LOCKDEP_SLAB_SIZE >> PAGE_SHIFT); p++)
+				free_reserved_page(page + p);
+
+			lockdep_slabs[i] = NULL;
+		}
+		freed_slabs = lockdep_nr_slabs - target_slabs;
+		lockdep_nr_slabs = target_slabs;
+	}
+
+	pr_info("lockdep: boot complete : %u/%u slabs used, %u kept (%u%% headroom), %u returned to buddy (%u kB freed)\n",
+		used, initial_slabs, lockdep_nr_slabs,
+		lockdep_nr_slabs > used ? ((lockdep_nr_slabs - used) * 100) / used : 0,
+		freed_slabs, (freed_slabs * LOCKDEP_SLAB_SIZE) / 1024);
+
+	register_reboot_notifier(&lockdep_reboot_nb);
+	return 0;
+}
+late_initcall_sync(lockdep_post_init_trim);
+
 static void
 print_freed_lock_bug(struct task_struct *curr, const void *mem_from,
 		     const void *mem_to, struct held_lock *hlock)
kernel/locking/lockdep_proc.c +12 -11
index 1916db9aa46b..95b76047918d 100644
@@ -32,16 +32,17 @@
  * bitmap and max_lock_class_idx.
  */
 #define iterate_lock_classes(idx, class)				\
-	for (idx = 0, class = lock_classes; idx <= max_lock_class_idx;	\
-	     idx++, class++)
+	for (idx = 0, class = idx_to_lock_class(0);			\
+	     idx <= max_lock_class_idx;					\
+	     idx++, class = idx_to_lock_class(idx))
 
 static void *l_next(struct seq_file *m, void *v, loff_t *pos)
 {
-	struct lock_class *class = v;
+	unsigned long idx = ++*pos;
 
-	++class;
-	*pos = class - lock_classes;
-	return (*pos > max_lock_class_idx) ? NULL : class;
+	if (idx > max_lock_class_idx)
+		return NULL;
+	return idx_to_lock_class(idx);
 }
 
 static void *l_start(struct seq_file *m, loff_t *pos)
@@ -50,7 +51,7 @@ static void *l_start(struct seq_file *m, loff_t *pos)
 
 	if (idx > max_lock_class_idx)
 		return NULL;
-	return lock_classes + idx;
+	return idx_to_lock_class(idx);
 }
 
 static void l_stop(struct seq_file *m, void *v)
@@ -59,7 +60,7 @@ static void l_stop(struct seq_file *m, void *v)
 
 static void print_name(struct seq_file *m, struct lock_class *class)
 {
-	char str[KSYM_NAME_LEN];
+	char str[128];
 	const char *name = class->name;
 
 	if (!name) {
@@ -79,9 +80,9 @@ static int l_show(struct seq_file *m, void *v)
 	struct lock_class *class = v;
 	struct lock_list *entry;
 	char usage[LOCK_USAGE_CHARS];
-	int idx = class - lock_classes;
+	int idx = class->class_idx;
 
-	if (v == lock_classes)
+	if (idx == 0)
 		seq_printf(m, "all lock classes:\n");
 
 	if (!test_bit(idx, lock_classes_in_use))
@@ -133,7 +134,7 @@ static void *lc_start(struct seq_file *m, loff_t *pos)
 	if (*pos == 0)
 		return SEQ_START_TOKEN;
 
-	return lock_chains + (*pos - 1);
+	return idx_to_lock_chain(*pos - 1);
 }
 
 static void *lc_next(struct seq_file *m, void *v, loff_t *pos)
Signature · 1 line
2.55.0
author
#7 lore raw

PATCH 7/8 lockdep: Expose slab pool telemetry in /proc/lockdep_stats and initcalls

In reply to Jim Cromie

Extend lockdep observability to track slab allocation dynamics:

0. In /proc/lockdep_stats, display total reserved slabs, used slabs, free slabs (headroom), and a per-consumer slab breakdown (lock_classes, direct deps, dependency chains, chain hlocks, stack traces).

1. In lockdep.c, add lockdep_report_stage() hooks registered across initcall milestones (core, postcore, arch, subsys, fs, device, late) to log slab consumption progress throughout kernel initialization.

---
 kernel/locking/lockdep.c           | 47 ++++++++++++++++++++++++++++++++++++++
 kernel/locking/lockdep_internals.h |  4 +++-
 kernel/locking/lockdep_proc.c      | 40 ++++++++++++++++++++++++--------
 3 files changed, 80 insertions(+), 11 deletions(-)
kernel/locking/lockdep.c +47 -0
index 3fb6c07cea36..b6048e7c8b56 100644
@@ -6992,6 +6992,53 @@ void __init lockdep_init(void)
 	       sizeof(((struct task_struct *)NULL)->held_locks));
 }
 
+static void lockdep_report_stage(const char *domain, const char *stage_name)
+{
+	unsigned int used = lockdep_slabs_used - lockdep_nr_free_slabs;
+	unsigned int class_per_chunk = lock_class_PER_CHUNK;
+	unsigned int entry_per_chunk = LOCKDEP_SLAB_SIZE / sizeof(struct lock_list);
+	unsigned int chain_per_chunk = lock_chain_PER_CHUNK;
+	unsigned int hlock_per_chunk = chain_hlock_PER_CHUNK;
+	unsigned int trace_per_chunk = LOCKDEP_SLAB_SIZE / sizeof(unsigned long);
+
+	unsigned int cl_w = nr_lock_classes / class_per_chunk;
+	unsigned int cl_f = ((nr_lock_classes % class_per_chunk) * 100) / class_per_chunk;
+
+	unsigned int en_w = nr_list_entries / entry_per_chunk;
+	unsigned int en_f = ((nr_list_entries % entry_per_chunk) * 100) / entry_per_chunk;
+
+	unsigned long chains = lock_chain_count();
+	unsigned int ch_w = chains / chain_per_chunk;
+	unsigned int ch_f = ((chains % chain_per_chunk) * 100) / chain_per_chunk;
+
+	unsigned int hlocks = chain_hlocks_used();
+	unsigned int hl_w = hlocks / hlock_per_chunk;
+	unsigned int hl_f = ((hlocks % hlock_per_chunk) * 100) / hlock_per_chunk;
+
+	unsigned int tr_w = nr_stack_trace_entries / trace_per_chunk;
+	unsigned int tr_f = ((nr_stack_trace_entries % trace_per_chunk) * 100) / trace_per_chunk;
+
+	pr_info("lockdep: %-8s [%-9s] : %u/%u slabs : classes=%u.%02u entries=%u.%02u chains=%u.%02u hlocks=%u.%02u trace=%u.%02u\n",
+		domain, stage_name, used, lockdep_nr_slabs,
+		cl_w, cl_f, en_w, en_f, ch_w, ch_f, hl_w, hl_f, tr_w, tr_f);
+}
+
+#define DEFINE_LOCKDEP_LEVEL_REPORT(lvl, name)			\
+	static int __init lockdep_report_##name(void)		\
+	{							\
+		lockdep_report_stage("initcall", #name);	\
+		return 0;					\
+	}							\
+	lvl(lockdep_report_##name)
+
+DEFINE_LOCKDEP_LEVEL_REPORT(core_initcall_sync, core);
+DEFINE_LOCKDEP_LEVEL_REPORT(postcore_initcall_sync, postcore);
+DEFINE_LOCKDEP_LEVEL_REPORT(arch_initcall_sync, arch);
+DEFINE_LOCKDEP_LEVEL_REPORT(subsys_initcall_sync, subsys);
+DEFINE_LOCKDEP_LEVEL_REPORT(fs_initcall_sync, fs);
+DEFINE_LOCKDEP_LEVEL_REPORT(device_initcall_sync, device);
+DEFINE_LOCKDEP_LEVEL_REPORT(late_initcall_sync, late);
+
 static int lockdep_shutdown_notify(struct notifier_block *nb,
 				   unsigned long code, void *unused)
 {
kernel/locking/lockdep_internals.h +3 -1
index ccd7343af672..6fb776618ac6 100644
@@ -223,7 +223,7 @@ extern unsigned int max_lockdep_depth;
 extern unsigned int max_bfs_queue_depth;
 extern unsigned long max_lock_class_idx;
 
-DECLARE_2D_RADIX(lock_class, struct lock_class);
+DECLARE_CHUNKED_ARRAY(lock_class, struct lock_class);
 extern unsigned long lock_classes_in_use[];
 
 struct lockdep_slab_usage {
@@ -240,6 +240,8 @@ struct lockdep_slab_stats {
 	struct lockdep_slab_usage usage;
 };
 
+void lockdep_get_slab_stats(struct lockdep_slab_stats *st);
+
 unsigned int chain_hlocks_used(void);
 unsigned long lock_chain_count(void);
 void lockdep_get_slab_stats(struct lockdep_slab_stats *st);
kernel/locking/lockdep_proc.c +30 -10
index 95b76047918d..76e32fca8c54 100644
@@ -380,17 +380,37 @@ static int lockdep_stats_show(struct seq_file *m, void *v)
 			debug_locks);
 
 	/*
-	 * Zapped classes and lockdep data buffers reuse statistics.
+	 * Shared Memblock Slab Reservoir Statistics
 	 */
-	seq_puts(m, "\n");
-	seq_printf(m, " zapped classes:                %11lu\n",
-			nr_zapped_classes);
-#ifdef CONFIG_PROVE_LOCKING
-	seq_printf(m, " zapped lock chains:            %11lu\n",
-			nr_zapped_lock_chains);
-	seq_printf(m, " large chain blocks:            %11u\n",
-			nr_large_chain_blocks);
-#endif
+	{
+		struct lockdep_slab_stats st;
+
+		lockdep_get_slab_stats(&st);
+		if (st.total_slabs) {
+			unsigned int free_slabs = st.total_slabs > st.used_slabs ?
+						  st.total_slabs - st.used_slabs : 0;
+			unsigned int headroom_pct = (free_slabs * 100) / st.total_slabs;
+
+			seq_puts(m, "\n lockdep memblock slab reservoir:\n");
+			seq_printf(m, "   total slabs:                 %11u (%zu kB)\n",
+				   st.total_slabs, (size_t)st.total_slabs * 64);
+			seq_printf(m, "   used slabs:                  %11u (%zu kB)\n",
+				   st.used_slabs, (size_t)st.used_slabs * 64);
+			seq_printf(m, "     - lock_classes slabs:      %11u (%zu kB)\n",
+				   st.usage.lock_classes, (size_t)st.usage.lock_classes * 64);
+			seq_printf(m, "     - direct deps slabs:       %11u (%zu kB)\n",
+				   st.usage.direct_deps, (size_t)st.usage.direct_deps * 64);
+			seq_printf(m, "     - dependency chains slabs: %11u (%zu kB)\n",
+				   st.usage.lock_chains, (size_t)st.usage.lock_chains * 64);
+			seq_printf(m, "     - chain hlocks slabs:      %11u (%zu kB)\n",
+				   st.usage.chain_hlocks, (size_t)st.usage.chain_hlocks * 64);
+			seq_printf(m, "     - stack_trace slabs:       %11u (%zu kB)\n",
+				   st.usage.stack_traces, (size_t)st.usage.stack_traces * 64);
+			seq_printf(m, "   free slabs (headroom):       %11u (%zu kB, %u%%)\n",
+				   free_slabs, (size_t)free_slabs * 64, headroom_pct);
+		}
+	}
+
 	return 0;
 }
 
Signature · 1 line
2.55.0
author
#8 lore raw

PATCH 8/8 lockdep: on debug_locks_off or OOM, recycle all slabs to buddy

In reply to Jim Cromie

If lockdep breaks, by assertion failure or for ENOMEM-ish reasons, we can no longer use the graph-db. Since most of the graph-db is now allocated from memblock_alloc() slabs, we can release them all back to buddy, and hope that freeing ~1.5MB will help. (v7.2 has ~10MB tied up in .bss).

0. Hook debug_locks_off() / print_lockdep_off() via an asynchronous work item (lockdep_sacrifice_work) to release all held slabs back to the buddy allocator via free_reserved_page() in process context.

1. Register an OOM notifier (lockdep_oom_nb) at late_initcall. If the system encounters an out-of-memory emergency, lockdep sacrifices its entire dynamic slab pool (1..8 MB of physical RAM), reporting freed pages to the OOM killer to avoid terminating user processes.

2. Clear lockdep_slabs[] pointers and zero lockdep_nr_slabs under graph_lock to seal off subsequent allocations.

---
 kernel/locking/lockdep.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 81 insertions(+)
kernel/locking/lockdep.c +81 -0
index b6048e7c8b56..9f28530b2f1d 100644
@@ -60,7 +60,9 @@
 #include <linux/kasan.h>
 #include <linux/mm.h>
 #include <linux/memblock.h>
+#include <linux/oom.h>
 #include <linux/reboot.h>
+#include <linux/workqueue.h>
 
 #include <asm/sections.h>
 
@@ -638,6 +640,82 @@ static int verbose(struct lock_class *class)
 	return 0;
 }
 
+/*
+ * Release all memblock slabs (used and unused) back to the buddy allocator
+ * when lockdep is disabled or during system OOM emergencies.
+ * Must run in process context (workqueue or OOM notifier).
+ */
+static unsigned int lockdep_release_slabs_to_buddy(void)
+{
+	unsigned int freed_slabs = 0;
+	unsigned int nr = lockdep_nr_slabs;
+	unsigned long flags;
+	unsigned int i;
+
+	if (!nr)
+		return 0;
+
+	/* Invalidate table bounds under graph_lock */
+	raw_local_irq_save(flags);
+	if (!graph_lock()) {
+		raw_local_irq_restore(flags);
+		return 0;
+	}
+	lockdep_nr_slabs = 0;
+	lockdep_slabs_used = 0;
+	graph_unlock();
+	raw_local_irq_restore(flags);
+
+	for (i = 0; i < nr; i++) {
+		struct page *page;
+		unsigned long p;
+
+		if (!lockdep_slabs[i])
+			continue;
+
+		page = virt_to_page(lockdep_slabs[i]);
+		for (p = 0; p < (LOCKDEP_SLAB_SIZE >> PAGE_SHIFT); p++)
+			free_reserved_page(page + p);
+
+		lockdep_slabs[i] = NULL;
+		freed_slabs++;
+	}
+
+	if (freed_slabs)
+		pr_info("lockdep: emergency sacrifice — released %u slabs (%u kB) to buddy allocator\n",
+			freed_slabs, (freed_slabs * LOCKDEP_SLAB_SIZE) / 1024);
+
+	return freed_slabs;
+}
+
+static void lockdep_sacrifice_work_fn(struct work_struct *work)
+{
+	lockdep_release_slabs_to_buddy();
+}
+static DECLARE_WORK(lockdep_sacrifice_work, lockdep_sacrifice_work_fn);
+
+static int lockdep_oom_notify(struct notifier_block *self,
+			      unsigned long dummy, void *parm)
+{
+	unsigned long *freed = parm;
+	unsigned int freed_slabs;
+
+	if (!lockdep_nr_slabs)
+		return NOTIFY_OK;
+
+	/* Turn off lockdep before sacrificing tables */
+	debug_locks_off();
+	freed_slabs = lockdep_release_slabs_to_buddy();
+	if (freed && freed_slabs)
+		*freed += (freed_slabs * (LOCKDEP_SLAB_SIZE >> PAGE_SHIFT));
+
+	return NOTIFY_OK;
+}
+
+static struct notifier_block lockdep_oom_nb = {
+	.notifier_call = lockdep_oom_notify,
+};
+
 static void print_lockdep_off(const char *bug_msg)
 {
 	printk(KERN_DEBUG "%s\n", bug_msg);
@@ -645,6 +723,8 @@ static void print_lockdep_off(const char *bug_msg)
 #ifdef CONFIG_LOCK_STAT
 	printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n");
 #endif
+	if (system_state >= SYSTEM_RUNNING)
+		schedule_work(&lockdep_sacrifice_work);
 }
 
 unsigned long nr_stack_trace_entries;
@@ -7105,6 +7185,7 @@ static int __init lockdep_post_init_trim(void)
 		lockdep_nr_slabs > used ? ((lockdep_nr_slabs - used) * 100) / used : 0,
 		freed_slabs, (freed_slabs * LOCKDEP_SLAB_SIZE) / 1024);
 
+	register_oom_notifier(&lockdep_oom_nb);
 	register_reboot_notifier(&lockdep_reboot_nb);
 	return 0;
 }
Signature · 1 line
2.55.0
maintainer
#9 lore raw
In reply to Jim Cromie
Quoted 10 lines · Jim Cromie

Lockdep cannot rely upon any other subsystem that uses locks, so since inception, its graph-db has been stored in static arrays, pinning ~10 MB in .bss. This is a hardcoded compromise between embedded and enterprise hardware.

However, if it acts early, lockdep can pre-allocate a pool of slabs from memblock_alloc(), enough for its lifetime of anticipated workloads. Then it can allocate them as needed to provide new segments/slabs to the graph-db.

Why? I really don't understand why. Who cares about this bss stuff.

#10 lore raw
Quoted 7 lines · Peter Zijlstra
Quoted 5 lines · Jim Cromie

Lockdep cannot rely upon any other subsystem that uses locks, so since inception, its graph-db has been stored in static arrays, pinning ~10 MB in .bss. This is a hardcoded compromise between embedded and enterprise hardware.

Quoted 7 lines
Quoted 5 lines

However, if it acts early, lockdep can pre-allocate a pool of slabs from memblock_alloc(), enough for its lifetime of anticipated workloads. Then it can allocate them as needed to provide new segments/slabs to the graph-db.

Why? I really don't understand why. Who cares about this bss stuff.

I thought embedded folk might value 10mb less bss ?
Or have they stopped using lockdep already, for size or other reasons.

How about OOM, when kernel needs mem,
or lockdep debug-off, when the slabs tied up in the graph-db could be returned

do these not tip the scales ?

maintainer
#11 lore raw
Quoted 14 lines · On Thu, Aug 27, 2026 at 02:54:12AM -0600, [email protected] wrote:
Quoted 13 lines · Peter Zijlstra
Quoted 10 lines · Jim Cromie

Lockdep cannot rely upon any other subsystem that uses locks, so since inception, its graph-db has been stored in static arrays, pinning ~10 MB in .bss. This is a hardcoded compromise between embedded and enterprise hardware.

However, if it acts early, lockdep can pre-allocate a pool of slabs from memblock_alloc(), enough for its lifetime of anticipated workloads. Then it can allocate them as needed to provide new segments/slabs to the graph-db.

Quoted 4 lines
Quoted 1 line

Why? I really don't understand why. Who cares about this bss stuff.

I thought embedded folk might value 10mb less bss ?
Or have they stopped using lockdep already, for size or other reasons.

I've never heard complaints from embedded people that this is a problem. Very few Linux capable machines can't spare 10mb.

This is about kernel development, if you need to develop a driver (only case you might be tied to specific hardware) just get your developer a board that has a spare 10mb of memory? Your developer is probably served by having the most beefy board available anyway.

There was a case on sparc where the bss was a problem because the kernel image had definite size constraints, but I don't think any 'modern' systems suffer that particular problem.

Quoted 2 lines

How about OOM, when kernel needs mem,
or lockdep debug-off, when the slabs tied up in the graph-db could be returned

If you're running into OOM while doing kernel dev you're doing it wrong?

#12 lore raw
Quoted 24 lines · Peter Zijlstra
Quoted 14 lines · On Thu, Aug 27, 2026 at 02:54:12AM -0600, [email protected] wrote:
Quoted 13 lines · Peter Zijlstra
Quoted 10 lines · Jim Cromie

Lockdep cannot rely upon any other subsystem that uses locks, so since inception, its graph-db has been stored in static arrays, pinning ~10 MB in .bss. This is a hardcoded compromise between embedded and enterprise hardware.

However, if it acts early, lockdep can pre-allocate a pool of slabs from memblock_alloc(), enough for its lifetime of anticipated workloads. Then it can allocate them as needed to provide new segments/slabs to the graph-db.

Quoted 4 lines
Quoted 1 line

Why? I really don't understand why. Who cares about this bss stuff.

I thought embedded folk might value 10mb less bss ?
Or have they stopped using lockdep already, for size or other reasons.

I've never heard complaints from embedded people that this is a problem. Very few Linux capable machines can't spare 10mb.

Quoted 9 lines

This is about kernel development, if you need to develop a driver (only case you might be tied to specific hardware) just get your developer a board that has a spare 10mb of memory? Your developer is probably served by having the most beefy board available anyway.

There was a case on sparc where the bss was a problem because the kernel image had definite size constraints, but I don't think any 'modern' systems suffer that particular problem.

Fair points on embedded.
So the value proposition is narrow:

folks hitting "BUG: MAX_LOCKDEP_* too low!"
who cannot build, deploy a kernel with tweaked MAX_LOCKDEP constants. They're running a distro-debug kernel.

this group might include:
Distro QA, enterprise testers, Syzbot/CI runners. For these users, lockdep sometimes turns off permanently, silently invalidating the rest of the test run.

if they had the lockdep_slabs=N knob, they might use it,
and throw more workload on the box without a possible hard-fail looming.

Quoted 4 lines
Quoted 2 lines

How about OOM, when kernel needs mem,
or lockdep debug-off, when the slabs tied up in the graph-db could be returned

If you're running into OOM while doing kernel dev you're doing it wrong?

heh - not me, that was the other guy.
it was a "feature", I thought it might help the sale. :-)

thanks