xref: /linux-6.15/lib/stackdepot.c (revision 94b7d328)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Stack depot - a stack trace storage that avoids duplication.
4  *
5  * Internally, stack depot maintains a hash table of unique stacktraces. The
6  * stack traces themselves are stored contiguously one after another in a set
7  * of separate page allocations.
8  *
9  * Author: Alexander Potapenko <[email protected]>
10  * Copyright (C) 2016 Google, Inc.
11  *
12  * Based on the code by Dmitry Chernenkov.
13  */
14 
15 #define pr_fmt(fmt) "stackdepot: " fmt
16 
17 #include <linux/gfp.h>
18 #include <linux/jhash.h>
19 #include <linux/kernel.h>
20 #include <linux/kmsan.h>
21 #include <linux/mm.h>
22 #include <linux/mutex.h>
23 #include <linux/percpu.h>
24 #include <linux/printk.h>
25 #include <linux/slab.h>
26 #include <linux/stacktrace.h>
27 #include <linux/stackdepot.h>
28 #include <linux/string.h>
29 #include <linux/types.h>
30 #include <linux/memblock.h>
31 #include <linux/kasan-enabled.h>
32 
33 #define DEPOT_HANDLE_BITS (sizeof(depot_stack_handle_t) * 8)
34 
35 #define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages */
36 #define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT + DEPOT_POOL_ORDER))
37 #define DEPOT_STACK_ALIGN 4
38 #define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT - DEPOT_STACK_ALIGN)
39 #define DEPOT_POOL_INDEX_BITS (DEPOT_HANDLE_BITS - DEPOT_OFFSET_BITS - \
40 			       STACK_DEPOT_EXTRA_BITS)
41 #define DEPOT_POOLS_CAP 8192
42 #define DEPOT_MAX_POOLS \
43 	(((1LL << (DEPOT_POOL_INDEX_BITS)) < DEPOT_POOLS_CAP) ? \
44 	 (1LL << (DEPOT_POOL_INDEX_BITS)) : DEPOT_POOLS_CAP)
45 
46 /* Compact structure that stores a reference to a stack. */
47 union handle_parts {
48 	depot_stack_handle_t handle;
49 	struct {
50 		u32 pool_index	: DEPOT_POOL_INDEX_BITS;
51 		u32 offset	: DEPOT_OFFSET_BITS;
52 		u32 extra	: STACK_DEPOT_EXTRA_BITS;
53 	};
54 };
55 
56 struct stack_record {
57 	struct stack_record *next;	/* Link in the hash table */
58 	u32 hash;			/* Hash in the hash table */
59 	u32 size;			/* Number of stored frames */
60 	union handle_parts handle;
61 	unsigned long entries[CONFIG_STACKDEPOT_MAX_FRAMES];	/* Frames */
62 };
63 
64 #define DEPOT_STACK_RECORD_SIZE \
65 	ALIGN(sizeof(struct stack_record), 1 << DEPOT_STACK_ALIGN)
66 
67 static bool stack_depot_disabled;
68 static bool __stack_depot_early_init_requested __initdata = IS_ENABLED(CONFIG_STACKDEPOT_ALWAYS_INIT);
69 static bool __stack_depot_early_init_passed __initdata;
70 
71 /* Use one hash table bucket per 16 KB of memory. */
72 #define STACK_HASH_TABLE_SCALE 14
73 /* Limit the number of buckets between 4K and 1M. */
74 #define STACK_BUCKET_NUMBER_ORDER_MIN 12
75 #define STACK_BUCKET_NUMBER_ORDER_MAX 20
76 /* Initial seed for jhash2. */
77 #define STACK_HASH_SEED 0x9747b28c
78 
79 /* Hash table of pointers to stored stack traces. */
80 static struct stack_record **stack_table;
81 /* Fixed order of the number of table buckets. Used when KASAN is enabled. */
82 static unsigned int stack_bucket_number_order;
83 /* Hash mask for indexing the table. */
84 static unsigned int stack_hash_mask;
85 
86 /* Array of memory regions that store stack traces. */
87 static void *stack_pools[DEPOT_MAX_POOLS];
88 /* Currently used pool in stack_pools. */
89 static int pool_index;
90 /* Offset to the unused space in the currently used pool. */
91 static size_t pool_offset;
92 /* Lock that protects the variables above. */
93 static DEFINE_RAW_SPINLOCK(pool_lock);
94 /*
95  * Stack depot tries to keep an extra pool allocated even before it runs out
96  * of space in the currently used pool.
97  * This flag marks that this next extra pool needs to be allocated and
98  * initialized. It has the value 0 when either the next pool is not yet
99  * initialized or the limit on the number of pools is reached.
100  */
101 static int next_pool_required = 1;
102 
103 static int __init disable_stack_depot(char *str)
104 {
105 	return kstrtobool(str, &stack_depot_disabled);
106 }
107 early_param("stack_depot_disable", disable_stack_depot);
108 
109 void __init stack_depot_request_early_init(void)
110 {
111 	/* Too late to request early init now. */
112 	WARN_ON(__stack_depot_early_init_passed);
113 
114 	__stack_depot_early_init_requested = true;
115 }
116 
117 /* Allocates a hash table via memblock. Can only be used during early boot. */
118 int __init stack_depot_early_init(void)
119 {
120 	unsigned long entries = 0;
121 
122 	/* This function must be called only once, from mm_init(). */
123 	if (WARN_ON(__stack_depot_early_init_passed))
124 		return 0;
125 	__stack_depot_early_init_passed = true;
126 
127 	/*
128 	 * Print disabled message even if early init has not been requested:
129 	 * stack_depot_init() will not print one.
130 	 */
131 	if (stack_depot_disabled) {
132 		pr_info("disabled\n");
133 		return 0;
134 	}
135 
136 	/*
137 	 * If KASAN is enabled, use the maximum order: KASAN is frequently used
138 	 * in fuzzing scenarios, which leads to a large number of different
139 	 * stack traces being stored in stack depot.
140 	 */
141 	if (kasan_enabled() && !stack_bucket_number_order)
142 		stack_bucket_number_order = STACK_BUCKET_NUMBER_ORDER_MAX;
143 
144 	/*
145 	 * Check if early init has been requested after setting
146 	 * stack_bucket_number_order: stack_depot_init() uses its value.
147 	 */
148 	if (!__stack_depot_early_init_requested)
149 		return 0;
150 
151 	/*
152 	 * If stack_bucket_number_order is not set, leave entries as 0 to rely
153 	 * on the automatic calculations performed by alloc_large_system_hash.
154 	 */
155 	if (stack_bucket_number_order)
156 		entries = 1UL << stack_bucket_number_order;
157 	pr_info("allocating hash table via alloc_large_system_hash\n");
158 	stack_table = alloc_large_system_hash("stackdepot",
159 						sizeof(struct stack_record *),
160 						entries,
161 						STACK_HASH_TABLE_SCALE,
162 						HASH_EARLY | HASH_ZERO,
163 						NULL,
164 						&stack_hash_mask,
165 						1UL << STACK_BUCKET_NUMBER_ORDER_MIN,
166 						1UL << STACK_BUCKET_NUMBER_ORDER_MAX);
167 	if (!stack_table) {
168 		pr_err("hash table allocation failed, disabling\n");
169 		stack_depot_disabled = true;
170 		return -ENOMEM;
171 	}
172 
173 	return 0;
174 }
175 
176 /* Allocates a hash table via kvcalloc. Can be used after boot. */
177 int stack_depot_init(void)
178 {
179 	static DEFINE_MUTEX(stack_depot_init_mutex);
180 	unsigned long entries;
181 	int ret = 0;
182 
183 	mutex_lock(&stack_depot_init_mutex);
184 
185 	if (stack_depot_disabled || stack_table)
186 		goto out_unlock;
187 
188 	/*
189 	 * Similarly to stack_depot_early_init, use stack_bucket_number_order
190 	 * if assigned, and rely on automatic scaling otherwise.
191 	 */
192 	if (stack_bucket_number_order) {
193 		entries = 1UL << stack_bucket_number_order;
194 	} else {
195 		int scale = STACK_HASH_TABLE_SCALE;
196 
197 		entries = nr_free_buffer_pages();
198 		entries = roundup_pow_of_two(entries);
199 
200 		if (scale > PAGE_SHIFT)
201 			entries >>= (scale - PAGE_SHIFT);
202 		else
203 			entries <<= (PAGE_SHIFT - scale);
204 	}
205 
206 	if (entries < 1UL << STACK_BUCKET_NUMBER_ORDER_MIN)
207 		entries = 1UL << STACK_BUCKET_NUMBER_ORDER_MIN;
208 	if (entries > 1UL << STACK_BUCKET_NUMBER_ORDER_MAX)
209 		entries = 1UL << STACK_BUCKET_NUMBER_ORDER_MAX;
210 
211 	pr_info("allocating hash table of %lu entries via kvcalloc\n", entries);
212 	stack_table = kvcalloc(entries, sizeof(struct stack_record *), GFP_KERNEL);
213 	if (!stack_table) {
214 		pr_err("hash table allocation failed, disabling\n");
215 		stack_depot_disabled = true;
216 		ret = -ENOMEM;
217 		goto out_unlock;
218 	}
219 	stack_hash_mask = entries - 1;
220 
221 out_unlock:
222 	mutex_unlock(&stack_depot_init_mutex);
223 
224 	return ret;
225 }
226 EXPORT_SYMBOL_GPL(stack_depot_init);
227 
228 /* Keeps the preallocated memory to be used for the next stack depot pool. */
229 static void depot_keep_next_pool(void **prealloc)
230 {
231 	/*
232 	 * If the next pool is already saved or the maximum number of
233 	 * pools is reached, do not use the preallocated memory.
234 	 * Access next_pool_required non-atomically, as there are no concurrent
235 	 * write accesses to this variable.
236 	 */
237 	if (!next_pool_required)
238 		return;
239 
240 	/*
241 	 * Use the preallocated memory for the next pool
242 	 * as long as we do not exceed the maximum number of pools.
243 	 */
244 	if (pool_index + 1 < DEPOT_MAX_POOLS) {
245 		stack_pools[pool_index + 1] = *prealloc;
246 		*prealloc = NULL;
247 	}
248 
249 	/*
250 	 * At this point, either the next pool is kept or the maximum
251 	 * number of pools is reached. In either case, take note that
252 	 * keeping another pool is not required.
253 	 * smp_store_release() pairs with smp_load_acquire() in
254 	 * stack_depot_save().
255 	 */
256 	smp_store_release(&next_pool_required, 0);
257 }
258 
259 /* Updates references to the current and the next stack depot pools. */
260 static bool depot_update_pools(size_t required_size, void **prealloc)
261 {
262 	/* Check if there is not enough space in the current pool. */
263 	if (unlikely(pool_offset + required_size > DEPOT_POOL_SIZE)) {
264 		/* Bail out if we reached the pool limit. */
265 		if (unlikely(pool_index + 1 >= DEPOT_MAX_POOLS)) {
266 			WARN_ONCE(1, "Stack depot reached limit capacity");
267 			return false;
268 		}
269 
270 		/*
271 		 * Move on to the next pool.
272 		 * WRITE_ONCE() pairs with potential concurrent read in
273 		 * stack_depot_fetch().
274 		 */
275 		WRITE_ONCE(pool_index, pool_index + 1);
276 		pool_offset = 0;
277 
278 		/*
279 		 * If the maximum number of pools is not reached, take note
280 		 * that the next pool needs to be initialized.
281 		 * smp_store_release() pairs with smp_load_acquire() in
282 		 * stack_depot_save().
283 		 */
284 		if (pool_index + 1 < DEPOT_MAX_POOLS)
285 			smp_store_release(&next_pool_required, 1);
286 	}
287 
288 	/* Check if the current pool is not yet allocated. */
289 	if (*prealloc && stack_pools[pool_index] == NULL) {
290 		/* Use the preallocated memory for the current pool. */
291 		stack_pools[pool_index] = *prealloc;
292 		*prealloc = NULL;
293 		return true;
294 	}
295 
296 	/* Otherwise, try using the preallocated memory for the next pool. */
297 	if (*prealloc)
298 		depot_keep_next_pool(prealloc);
299 	return true;
300 }
301 
302 /* Allocates a new stack in a stack depot pool. */
303 static struct stack_record *
304 depot_alloc_stack(unsigned long *entries, int size, u32 hash, void **prealloc)
305 {
306 	struct stack_record *stack;
307 	size_t required_size = DEPOT_STACK_RECORD_SIZE;
308 
309 	/* Update current and next pools if required and possible. */
310 	if (!depot_update_pools(required_size, prealloc))
311 		return NULL;
312 
313 	/* Check if we have a pool to save the stack trace. */
314 	if (stack_pools[pool_index] == NULL)
315 		return NULL;
316 
317 	/* Limit number of saved frames to CONFIG_STACKDEPOT_MAX_FRAMES. */
318 	if (size > CONFIG_STACKDEPOT_MAX_FRAMES)
319 		size = CONFIG_STACKDEPOT_MAX_FRAMES;
320 
321 	/* Save the stack trace. */
322 	stack = stack_pools[pool_index] + pool_offset;
323 	stack->hash = hash;
324 	stack->size = size;
325 	stack->handle.pool_index = pool_index;
326 	stack->handle.offset = pool_offset >> DEPOT_STACK_ALIGN;
327 	stack->handle.extra = 0;
328 	memcpy(stack->entries, entries, flex_array_size(stack, entries, size));
329 	pool_offset += required_size;
330 
331 	/*
332 	 * Let KMSAN know the stored stack record is initialized. This shall
333 	 * prevent false positive reports if instrumented code accesses it.
334 	 */
335 	kmsan_unpoison_memory(stack, required_size);
336 
337 	return stack;
338 }
339 
340 static struct stack_record *depot_fetch_stack(depot_stack_handle_t handle)
341 {
342 	union handle_parts parts = { .handle = handle };
343 	/*
344 	 * READ_ONCE() pairs with potential concurrent write in
345 	 * depot_update_pools().
346 	 */
347 	int pool_index_cached = READ_ONCE(pool_index);
348 	void *pool;
349 	size_t offset = parts.offset << DEPOT_STACK_ALIGN;
350 	struct stack_record *stack;
351 
352 	if (parts.pool_index > pool_index_cached) {
353 		WARN(1, "pool index %d out of bounds (%d) for stack id %08x\n",
354 		     parts.pool_index, pool_index_cached, handle);
355 		return NULL;
356 	}
357 
358 	pool = stack_pools[parts.pool_index];
359 	if (!pool)
360 		return NULL;
361 
362 	stack = pool + offset;
363 	return stack;
364 }
365 
366 /* Calculates the hash for a stack. */
367 static inline u32 hash_stack(unsigned long *entries, unsigned int size)
368 {
369 	return jhash2((u32 *)entries,
370 		      array_size(size,  sizeof(*entries)) / sizeof(u32),
371 		      STACK_HASH_SEED);
372 }
373 
374 /*
375  * Non-instrumented version of memcmp().
376  * Does not check the lexicographical order, only the equality.
377  */
378 static inline
379 int stackdepot_memcmp(const unsigned long *u1, const unsigned long *u2,
380 			unsigned int n)
381 {
382 	for ( ; n-- ; u1++, u2++) {
383 		if (*u1 != *u2)
384 			return 1;
385 	}
386 	return 0;
387 }
388 
389 /* Finds a stack in a bucket of the hash table. */
390 static inline struct stack_record *find_stack(struct stack_record *bucket,
391 					     unsigned long *entries, int size,
392 					     u32 hash)
393 {
394 	struct stack_record *found;
395 
396 	for (found = bucket; found; found = found->next) {
397 		if (found->hash == hash &&
398 		    found->size == size &&
399 		    !stackdepot_memcmp(entries, found->entries, size))
400 			return found;
401 	}
402 	return NULL;
403 }
404 
405 depot_stack_handle_t __stack_depot_save(unsigned long *entries,
406 					unsigned int nr_entries,
407 					gfp_t alloc_flags, bool can_alloc)
408 {
409 	struct stack_record *found = NULL, **bucket;
410 	depot_stack_handle_t handle = 0;
411 	struct page *page = NULL;
412 	void *prealloc = NULL;
413 	unsigned long flags;
414 	u32 hash;
415 
416 	/*
417 	 * If this stack trace is from an interrupt, including anything before
418 	 * interrupt entry usually leads to unbounded stack depot growth.
419 	 *
420 	 * Since use of filter_irq_stacks() is a requirement to ensure stack
421 	 * depot can efficiently deduplicate interrupt stacks, always
422 	 * filter_irq_stacks() to simplify all callers' use of stack depot.
423 	 */
424 	nr_entries = filter_irq_stacks(entries, nr_entries);
425 
426 	if (unlikely(nr_entries == 0) || stack_depot_disabled)
427 		return 0;
428 
429 	hash = hash_stack(entries, nr_entries);
430 	bucket = &stack_table[hash & stack_hash_mask];
431 
432 	/*
433 	 * Fast path: look the stack trace up without locking.
434 	 * smp_load_acquire() pairs with smp_store_release() to |bucket| below.
435 	 */
436 	found = find_stack(smp_load_acquire(bucket), entries, nr_entries, hash);
437 	if (found)
438 		goto exit;
439 
440 	/*
441 	 * Check if another stack pool needs to be initialized. If so, allocate
442 	 * the memory now - we won't be able to do that under the lock.
443 	 *
444 	 * smp_load_acquire() pairs with smp_store_release() in
445 	 * depot_update_pools() and depot_keep_next_pool().
446 	 */
447 	if (unlikely(can_alloc && smp_load_acquire(&next_pool_required))) {
448 		/*
449 		 * Zero out zone modifiers, as we don't have specific zone
450 		 * requirements. Keep the flags related to allocation in atomic
451 		 * contexts and I/O.
452 		 */
453 		alloc_flags &= ~GFP_ZONEMASK;
454 		alloc_flags &= (GFP_ATOMIC | GFP_KERNEL);
455 		alloc_flags |= __GFP_NOWARN;
456 		page = alloc_pages(alloc_flags, DEPOT_POOL_ORDER);
457 		if (page)
458 			prealloc = page_address(page);
459 	}
460 
461 	raw_spin_lock_irqsave(&pool_lock, flags);
462 
463 	found = find_stack(*bucket, entries, nr_entries, hash);
464 	if (!found) {
465 		struct stack_record *new =
466 			depot_alloc_stack(entries, nr_entries, hash, &prealloc);
467 
468 		if (new) {
469 			new->next = *bucket;
470 			/*
471 			 * smp_store_release() pairs with smp_load_acquire()
472 			 * from |bucket| above.
473 			 */
474 			smp_store_release(bucket, new);
475 			found = new;
476 		}
477 	} else if (prealloc) {
478 		/*
479 		 * Stack depot already contains this stack trace, but let's
480 		 * keep the preallocated memory for the future.
481 		 */
482 		depot_keep_next_pool(&prealloc);
483 	}
484 
485 	raw_spin_unlock_irqrestore(&pool_lock, flags);
486 exit:
487 	if (prealloc) {
488 		/* Stack depot didn't use this memory, free it. */
489 		free_pages((unsigned long)prealloc, DEPOT_POOL_ORDER);
490 	}
491 	if (found)
492 		handle = found->handle.handle;
493 	return handle;
494 }
495 EXPORT_SYMBOL_GPL(__stack_depot_save);
496 
497 depot_stack_handle_t stack_depot_save(unsigned long *entries,
498 				      unsigned int nr_entries,
499 				      gfp_t alloc_flags)
500 {
501 	return __stack_depot_save(entries, nr_entries, alloc_flags, true);
502 }
503 EXPORT_SYMBOL_GPL(stack_depot_save);
504 
505 unsigned int stack_depot_fetch(depot_stack_handle_t handle,
506 			       unsigned long **entries)
507 {
508 	struct stack_record *stack;
509 
510 	*entries = NULL;
511 	/*
512 	 * Let KMSAN know *entries is initialized. This shall prevent false
513 	 * positive reports if instrumented code accesses it.
514 	 */
515 	kmsan_unpoison_memory(entries, sizeof(*entries));
516 
517 	if (!handle || stack_depot_disabled)
518 		return 0;
519 
520 	stack = depot_fetch_stack(handle);
521 
522 	*entries = stack->entries;
523 	return stack->size;
524 }
525 EXPORT_SYMBOL_GPL(stack_depot_fetch);
526 
527 void stack_depot_print(depot_stack_handle_t stack)
528 {
529 	unsigned long *entries;
530 	unsigned int nr_entries;
531 
532 	nr_entries = stack_depot_fetch(stack, &entries);
533 	if (nr_entries > 0)
534 		stack_trace_print(entries, nr_entries, 0);
535 }
536 EXPORT_SYMBOL_GPL(stack_depot_print);
537 
538 int stack_depot_snprint(depot_stack_handle_t handle, char *buf, size_t size,
539 		       int spaces)
540 {
541 	unsigned long *entries;
542 	unsigned int nr_entries;
543 
544 	nr_entries = stack_depot_fetch(handle, &entries);
545 	return nr_entries ? stack_trace_snprint(buf, size, entries, nr_entries,
546 						spaces) : 0;
547 }
548 EXPORT_SYMBOL_GPL(stack_depot_snprint);
549 
550 depot_stack_handle_t __must_check stack_depot_set_extra_bits(
551 			depot_stack_handle_t handle, unsigned int extra_bits)
552 {
553 	union handle_parts parts = { .handle = handle };
554 
555 	/* Don't set extra bits on empty handles. */
556 	if (!handle)
557 		return 0;
558 
559 	parts.extra = extra_bits;
560 	return parts.handle;
561 }
562 EXPORT_SYMBOL(stack_depot_set_extra_bits);
563 
564 unsigned int stack_depot_get_extra_bits(depot_stack_handle_t handle)
565 {
566 	union handle_parts parts = { .handle = handle };
567 
568 	return parts.extra;
569 }
570 EXPORT_SYMBOL(stack_depot_get_extra_bits);
571