lib/stackdepot: rename handle and pool constants
[linux-block.git] / lib / stackdepot.c
CommitLineData
1802d0be 1// SPDX-License-Identifier: GPL-2.0-only
cd11016e
AP
2/*
3 * Generic stack depot for storing stack traces.
4 *
5 * Some debugging tools need to save stack traces of certain events which can
6 * be later presented to the user. For example, KASAN needs to safe alloc and
7 * free stacks for each object, but storing two stack traces per object
8 * requires too much memory (e.g. SLUB_DEBUG needs 256 bytes per object for
9 * that).
10 *
11 * Instead, stack depot maintains a hashtable of unique stacktraces. Since alloc
12 * and free stacks repeat a lot, we save about 100x space.
13 * Stacks are never removed from depot, so we store them contiguously one after
9dbbc3b9 14 * another in a contiguous memory allocation.
cd11016e
AP
15 *
16 * Author: Alexander Potapenko <glider@google.com>
17 * Copyright (C) 2016 Google, Inc.
18 *
19 * Based on code by Dmitry Chernenkov.
cd11016e
AP
20 */
21
4a6b5314
AK
22#define pr_fmt(fmt) "stackdepot: " fmt
23
cd11016e
AP
24#include <linux/gfp.h>
25#include <linux/jhash.h>
26#include <linux/kernel.h>
27#include <linux/mm.h>
2dba5eb1 28#include <linux/mutex.h>
cd11016e
AP
29#include <linux/percpu.h>
30#include <linux/printk.h>
31#include <linux/slab.h>
32#include <linux/stacktrace.h>
33#include <linux/stackdepot.h>
34#include <linux/string.h>
35#include <linux/types.h>
e1fdc403 36#include <linux/memblock.h>
f9987921 37#include <linux/kasan-enabled.h>
cd11016e 38
424cafee
AK
39#define DEPOT_HANDLE_BITS (sizeof(depot_stack_handle_t) * 8)
40
41#define DEPOT_VALID_BITS 1
42#define DEPOT_POOL_ORDER 2 /* Pool size order, 4 pages */
43#define DEPOT_POOL_SIZE (1LL << (PAGE_SHIFT + DEPOT_POOL_ORDER))
44#define DEPOT_STACK_ALIGN 4
45#define DEPOT_OFFSET_BITS (DEPOT_POOL_ORDER + PAGE_SHIFT - DEPOT_STACK_ALIGN)
46#define DEPOT_POOL_INDEX_BITS (DEPOT_HANDLE_BITS - DEPOT_VALID_BITS - \
47 DEPOT_OFFSET_BITS - STACK_DEPOT_EXTRA_BITS)
48#define DEPOT_POOLS_CAP 8192
49#define DEPOT_MAX_POOLS \
50 (((1LL << (DEPOT_POOL_INDEX_BITS)) < DEPOT_POOLS_CAP) ? \
51 (1LL << (DEPOT_POOL_INDEX_BITS)) : DEPOT_POOLS_CAP)
cd11016e
AP
52
53/* The compact structure to store the reference to stacks. */
54union handle_parts {
55 depot_stack_handle_t handle;
56 struct {
424cafee
AK
57 u32 pool_index : DEPOT_POOL_INDEX_BITS;
58 u32 offset : DEPOT_OFFSET_BITS;
59 u32 valid : DEPOT_VALID_BITS;
60 u32 extra : STACK_DEPOT_EXTRA_BITS;
cd11016e
AP
61 };
62};
63
64struct stack_record {
65 struct stack_record *next; /* Link in the hashtable */
66 u32 hash; /* Hash in the hastable */
67 u32 size; /* Number of frames in the stack */
68 union handle_parts handle;
3a2b67e6 69 unsigned long entries[]; /* Variable-sized array of entries. */
cd11016e
AP
70};
71
735df3c3 72static bool stack_depot_disabled;
1c0310ad 73static bool __stack_depot_early_init_requested __initdata = IS_ENABLED(CONFIG_STACKDEPOT_ALWAYS_INIT);
a5f1783b
VB
74static bool __stack_depot_early_init_passed __initdata;
75
0d249ac0 76/* Use one hash table bucket per 16 KB of memory. */
4c2e9a67 77#define STACK_HASH_TABLE_SCALE 14
0d249ac0 78/* Limit the number of buckets between 4K and 1M. */
4c2e9a67
AK
79#define STACK_BUCKET_NUMBER_ORDER_MIN 12
80#define STACK_BUCKET_NUMBER_ORDER_MAX 20
0d249ac0 81/* Initial seed for jhash2. */
cd11016e
AP
82#define STACK_HASH_SEED 0x9747b28c
83
0d249ac0
AK
84/* Hash table of pointers to stored stack traces. */
85static struct stack_record **stack_table;
86/* Fixed order of the number of table buckets. Used when KASAN is enabled. */
4c2e9a67 87static unsigned int stack_bucket_number_order;
0d249ac0 88/* Hash mask for indexing the table. */
f9987921
VB
89static unsigned int stack_hash_mask;
90
0d249ac0 91/* Array of memory regions that store stack traces. */
424cafee 92static void *stack_pools[DEPOT_MAX_POOLS];
961c949b
AK
93/* Currently used pool in stack_pools. */
94static int pool_index;
95/* Offset to the unused space in the currently used pool. */
96static size_t pool_offset;
0d249ac0 97/* Lock that protects the variables above. */
961c949b
AK
98static DEFINE_RAW_SPINLOCK(pool_lock);
99/* Whether the next pool is initialized. */
100static int next_pool_inited;
e1fdc403 101
735df3c3 102static int __init disable_stack_depot(char *str)
e1fdc403 103{
64427985
VJ
104 int ret;
105
735df3c3
AK
106 ret = kstrtobool(str, &stack_depot_disabled);
107 if (!ret && stack_depot_disabled) {
4a6b5314 108 pr_info("disabled\n");
e1fdc403
VJ
109 stack_table = NULL;
110 }
111 return 0;
112}
735df3c3 113early_param("stack_depot_disable", disable_stack_depot);
e1fdc403 114
1c0310ad 115void __init stack_depot_request_early_init(void)
a5f1783b 116{
1c0310ad 117 /* Too late to request early init now. */
a5f1783b
VB
118 WARN_ON(__stack_depot_early_init_passed);
119
1c0310ad 120 __stack_depot_early_init_requested = true;
a5f1783b
VB
121}
122
df225c87 123/* Allocates a hash table via memblock. Can only be used during early boot. */
a5f1783b
VB
124int __init stack_depot_early_init(void)
125{
f9987921 126 unsigned long entries = 0;
a5f1783b 127
df225c87 128 /* This function must be called only once, from mm_init(). */
a5f1783b
VB
129 if (WARN_ON(__stack_depot_early_init_passed))
130 return 0;
a5f1783b
VB
131 __stack_depot_early_init_passed = true;
132
df225c87
AK
133 /*
134 * If KASAN is enabled, use the maximum order: KASAN is frequently used
135 * in fuzzing scenarios, which leads to a large number of different
136 * stack traces being stored in stack depot.
137 */
4c2e9a67
AK
138 if (kasan_enabled() && !stack_bucket_number_order)
139 stack_bucket_number_order = STACK_BUCKET_NUMBER_ORDER_MAX;
f9987921 140
735df3c3 141 if (!__stack_depot_early_init_requested || stack_depot_disabled)
a5f1783b
VB
142 return 0;
143
df225c87 144 /*
4c2e9a67
AK
145 * If stack_bucket_number_order is not set, leave entries as 0 to rely
146 * on the automatic calculations performed by alloc_large_system_hash.
df225c87 147 */
4c2e9a67
AK
148 if (stack_bucket_number_order)
149 entries = 1UL << stack_bucket_number_order;
df225c87 150 pr_info("allocating hash table via alloc_large_system_hash\n");
f9987921
VB
151 stack_table = alloc_large_system_hash("stackdepot",
152 sizeof(struct stack_record *),
153 entries,
4c2e9a67 154 STACK_HASH_TABLE_SCALE,
f9987921
VB
155 HASH_EARLY | HASH_ZERO,
156 NULL,
157 &stack_hash_mask,
4c2e9a67
AK
158 1UL << STACK_BUCKET_NUMBER_ORDER_MIN,
159 1UL << STACK_BUCKET_NUMBER_ORDER_MAX);
a5f1783b 160 if (!stack_table) {
4a6b5314 161 pr_err("hash table allocation failed, disabling\n");
735df3c3 162 stack_depot_disabled = true;
a5f1783b
VB
163 return -ENOMEM;
164 }
165
166 return 0;
167}
168
df225c87 169/* Allocates a hash table via kvcalloc. Can be used after boot. */
a5f1783b 170int stack_depot_init(void)
e1fdc403 171{
2dba5eb1 172 static DEFINE_MUTEX(stack_depot_init_mutex);
c60324fb 173 unsigned long entries;
a5f1783b 174 int ret = 0;
2dba5eb1
VB
175
176 mutex_lock(&stack_depot_init_mutex);
f9987921 177
c60324fb
AK
178 if (stack_depot_disabled || stack_table)
179 goto out_unlock;
f9987921 180
c60324fb 181 /*
4c2e9a67 182 * Similarly to stack_depot_early_init, use stack_bucket_number_order
c60324fb
AK
183 * if assigned, and rely on automatic scaling otherwise.
184 */
4c2e9a67
AK
185 if (stack_bucket_number_order) {
186 entries = 1UL << stack_bucket_number_order;
c60324fb 187 } else {
4c2e9a67 188 int scale = STACK_HASH_TABLE_SCALE;
c60324fb
AK
189
190 entries = nr_free_buffer_pages();
191 entries = roundup_pow_of_two(entries);
192
193 if (scale > PAGE_SHIFT)
194 entries >>= (scale - PAGE_SHIFT);
195 else
196 entries <<= (PAGE_SHIFT - scale);
e1fdc403 197 }
c60324fb 198
4c2e9a67
AK
199 if (entries < 1UL << STACK_BUCKET_NUMBER_ORDER_MIN)
200 entries = 1UL << STACK_BUCKET_NUMBER_ORDER_MIN;
201 if (entries > 1UL << STACK_BUCKET_NUMBER_ORDER_MAX)
202 entries = 1UL << STACK_BUCKET_NUMBER_ORDER_MAX;
c60324fb
AK
203
204 pr_info("allocating hash table of %lu entries via kvcalloc\n", entries);
205 stack_table = kvcalloc(entries, sizeof(struct stack_record *), GFP_KERNEL);
206 if (!stack_table) {
207 pr_err("hash table allocation failed, disabling\n");
208 stack_depot_disabled = true;
209 ret = -ENOMEM;
210 goto out_unlock;
211 }
212 stack_hash_mask = entries - 1;
213
214out_unlock:
2dba5eb1 215 mutex_unlock(&stack_depot_init_mutex);
c60324fb 216
a5f1783b 217 return ret;
e1fdc403 218}
2dba5eb1 219EXPORT_SYMBOL_GPL(stack_depot_init);
cd11016e 220
961c949b 221static bool init_stack_pool(void **prealloc)
15ef6a98
AK
222{
223 if (!*prealloc)
224 return false;
225 /*
226 * This smp_load_acquire() pairs with smp_store_release() to
961c949b 227 * |next_pool_inited| below and in depot_alloc_stack().
15ef6a98 228 */
961c949b 229 if (smp_load_acquire(&next_pool_inited))
15ef6a98 230 return true;
961c949b
AK
231 if (stack_pools[pool_index] == NULL) {
232 stack_pools[pool_index] = *prealloc;
15ef6a98
AK
233 *prealloc = NULL;
234 } else {
961c949b 235 /* If this is the last depot pool, do not touch the next one. */
424cafee 236 if (pool_index + 1 < DEPOT_MAX_POOLS) {
961c949b 237 stack_pools[pool_index + 1] = *prealloc;
15ef6a98
AK
238 *prealloc = NULL;
239 }
240 /*
241 * This smp_store_release pairs with smp_load_acquire() from
961c949b 242 * |next_pool_inited| above and in stack_depot_save().
15ef6a98 243 */
961c949b 244 smp_store_release(&next_pool_inited, 1);
15ef6a98
AK
245 }
246 return true;
247}
248
249/* Allocation of a new stack in raw storage */
250static struct stack_record *
251depot_alloc_stack(unsigned long *entries, int size, u32 hash, void **prealloc)
252{
253 struct stack_record *stack;
254 size_t required_size = struct_size(stack, entries, size);
255
424cafee 256 required_size = ALIGN(required_size, 1 << DEPOT_STACK_ALIGN);
15ef6a98 257
424cafee
AK
258 if (unlikely(pool_offset + required_size > DEPOT_POOL_SIZE)) {
259 if (unlikely(pool_index + 1 >= DEPOT_MAX_POOLS)) {
15ef6a98
AK
260 WARN_ONCE(1, "Stack depot reached limit capacity");
261 return NULL;
262 }
961c949b
AK
263 pool_index++;
264 pool_offset = 0;
15ef6a98
AK
265 /*
266 * smp_store_release() here pairs with smp_load_acquire() from
961c949b
AK
267 * |next_pool_inited| in stack_depot_save() and
268 * init_stack_pool().
15ef6a98 269 */
424cafee 270 if (pool_index + 1 < DEPOT_MAX_POOLS)
961c949b 271 smp_store_release(&next_pool_inited, 0);
15ef6a98 272 }
961c949b
AK
273 init_stack_pool(prealloc);
274 if (stack_pools[pool_index] == NULL)
15ef6a98
AK
275 return NULL;
276
961c949b 277 stack = stack_pools[pool_index] + pool_offset;
15ef6a98
AK
278
279 stack->hash = hash;
280 stack->size = size;
961c949b 281 stack->handle.pool_index = pool_index;
424cafee 282 stack->handle.offset = pool_offset >> DEPOT_STACK_ALIGN;
15ef6a98
AK
283 stack->handle.valid = 1;
284 stack->handle.extra = 0;
285 memcpy(stack->entries, entries, flex_array_size(stack, entries, size));
961c949b 286 pool_offset += required_size;
15ef6a98
AK
287
288 return stack;
289}
290
cd11016e
AP
291/* Calculate hash for a stack */
292static inline u32 hash_stack(unsigned long *entries, unsigned int size)
293{
294 return jhash2((u32 *)entries,
180644f8
GS
295 array_size(size, sizeof(*entries)) / sizeof(u32),
296 STACK_HASH_SEED);
cd11016e
AP
297}
298
a571b272
AP
299/* Use our own, non-instrumented version of memcmp().
300 *
301 * We actually don't care about the order, just the equality.
302 */
303static inline
304int stackdepot_memcmp(const unsigned long *u1, const unsigned long *u2,
305 unsigned int n)
306{
307 for ( ; n-- ; u1++, u2++) {
308 if (*u1 != *u2)
309 return 1;
310 }
311 return 0;
312}
313
cd11016e
AP
314/* Find a stack that is equal to the one stored in entries in the hash */
315static inline struct stack_record *find_stack(struct stack_record *bucket,
316 unsigned long *entries, int size,
317 u32 hash)
318{
319 struct stack_record *found;
320
321 for (found = bucket; found; found = found->next) {
322 if (found->hash == hash &&
323 found->size == size &&
a571b272 324 !stackdepot_memcmp(entries, found->entries, size))
cd11016e 325 return found;
cd11016e
AP
326 }
327 return NULL;
328}
329
cd11016e 330/**
11ac25c6 331 * __stack_depot_save - Save a stack trace from an array
c0cfc337
TG
332 *
333 * @entries: Pointer to storage array
334 * @nr_entries: Size of the storage array
83a4f1ef 335 * @extra_bits: Flags to store in unused bits of depot_stack_handle_t
c0cfc337 336 * @alloc_flags: Allocation gfp flags
961c949b 337 * @can_alloc: Allocate stack pools (increased chance of failure if false)
11ac25c6
ME
338 *
339 * Saves a stack trace from @entries array of size @nr_entries. If @can_alloc is
961c949b 340 * %true, is allowed to replenish the stack pool in case no space is left
11ac25c6
ME
341 * (allocates using GFP flags of @alloc_flags). If @can_alloc is %false, avoids
342 * any allocations and will fail if no space is left to store the stack trace.
343 *
e9400660
ME
344 * If the stack trace in @entries is from an interrupt, only the portion up to
345 * interrupt entry is saved.
346 *
83a4f1ef
AP
347 * Additional opaque flags can be passed in @extra_bits, stored in the unused
348 * bits of the stack handle, and retrieved using stack_depot_get_extra_bits()
349 * without calling stack_depot_fetch().
350 *
11ac25c6
ME
351 * Context: Any context, but setting @can_alloc to %false is required if
352 * alloc_pages() cannot be used from the current context. Currently
353 * this is the case from contexts where neither %GFP_ATOMIC nor
354 * %GFP_NOWAIT can be used (NMI, raw_spin_lock).
cd11016e 355 *
11ac25c6 356 * Return: The handle of the stack struct stored in depot, 0 on failure.
cd11016e 357 */
11ac25c6
ME
358depot_stack_handle_t __stack_depot_save(unsigned long *entries,
359 unsigned int nr_entries,
83a4f1ef 360 unsigned int extra_bits,
11ac25c6 361 gfp_t alloc_flags, bool can_alloc)
cd11016e 362{
cd11016e 363 struct stack_record *found = NULL, **bucket;
83a4f1ef 364 union handle_parts retval = { .handle = 0 };
cd11016e
AP
365 struct page *page = NULL;
366 void *prealloc = NULL;
c0cfc337
TG
367 unsigned long flags;
368 u32 hash;
cd11016e 369
e9400660
ME
370 /*
371 * If this stack trace is from an interrupt, including anything before
372 * interrupt entry usually leads to unbounded stackdepot growth.
373 *
374 * Because use of filter_irq_stacks() is a requirement to ensure
375 * stackdepot can efficiently deduplicate interrupt stacks, always
376 * filter_irq_stacks() to simplify all callers' use of stackdepot.
377 */
378 nr_entries = filter_irq_stacks(entries, nr_entries);
379
735df3c3 380 if (unlikely(nr_entries == 0) || stack_depot_disabled)
cd11016e
AP
381 goto fast_exit;
382
c0cfc337 383 hash = hash_stack(entries, nr_entries);
f9987921 384 bucket = &stack_table[hash & stack_hash_mask];
cd11016e
AP
385
386 /*
387 * Fast path: look the stack trace up without locking.
388 * The smp_load_acquire() here pairs with smp_store_release() to
389 * |bucket| below.
390 */
c0cfc337
TG
391 found = find_stack(smp_load_acquire(bucket), entries,
392 nr_entries, hash);
cd11016e
AP
393 if (found)
394 goto exit;
395
396 /*
961c949b 397 * Check if the current or the next stack pool need to be initialized.
cd11016e
AP
398 * If so, allocate the memory - we won't be able to do that under the
399 * lock.
400 *
401 * The smp_load_acquire() here pairs with smp_store_release() to
961c949b 402 * |next_pool_inited| in depot_alloc_stack() and init_stack_pool().
cd11016e 403 */
961c949b 404 if (unlikely(can_alloc && !smp_load_acquire(&next_pool_inited))) {
cd11016e
AP
405 /*
406 * Zero out zone modifiers, as we don't have specific zone
407 * requirements. Keep the flags related to allocation in atomic
408 * contexts and I/O.
409 */
410 alloc_flags &= ~GFP_ZONEMASK;
411 alloc_flags &= (GFP_ATOMIC | GFP_KERNEL);
87cc271d 412 alloc_flags |= __GFP_NOWARN;
424cafee 413 page = alloc_pages(alloc_flags, DEPOT_POOL_ORDER);
cd11016e
AP
414 if (page)
415 prealloc = page_address(page);
416 }
417
961c949b 418 raw_spin_lock_irqsave(&pool_lock, flags);
cd11016e 419
c0cfc337 420 found = find_stack(*bucket, entries, nr_entries, hash);
cd11016e 421 if (!found) {
7f2b8818
ME
422 struct stack_record *new = depot_alloc_stack(entries, nr_entries, hash, &prealloc);
423
cd11016e
AP
424 if (new) {
425 new->next = *bucket;
426 /*
427 * This smp_store_release() pairs with
428 * smp_load_acquire() from |bucket| above.
429 */
430 smp_store_release(bucket, new);
431 found = new;
432 }
433 } else if (prealloc) {
434 /*
435 * We didn't need to store this stack trace, but let's keep
436 * the preallocated memory for the future.
437 */
961c949b 438 WARN_ON(!init_stack_pool(&prealloc));
cd11016e
AP
439 }
440
961c949b 441 raw_spin_unlock_irqrestore(&pool_lock, flags);
cd11016e
AP
442exit:
443 if (prealloc) {
444 /* Nobody used this memory, ok to free it. */
424cafee 445 free_pages((unsigned long)prealloc, DEPOT_POOL_ORDER);
cd11016e
AP
446 }
447 if (found)
83a4f1ef 448 retval.handle = found->handle.handle;
cd11016e 449fast_exit:
83a4f1ef
AP
450 retval.extra = extra_bits;
451
452 return retval.handle;
cd11016e 453}
11ac25c6
ME
454EXPORT_SYMBOL_GPL(__stack_depot_save);
455
456/**
457 * stack_depot_save - Save a stack trace from an array
458 *
459 * @entries: Pointer to storage array
460 * @nr_entries: Size of the storage array
461 * @alloc_flags: Allocation gfp flags
462 *
463 * Context: Contexts where allocations via alloc_pages() are allowed.
464 * See __stack_depot_save() for more details.
465 *
466 * Return: The handle of the stack struct stored in depot, 0 on failure.
467 */
468depot_stack_handle_t stack_depot_save(unsigned long *entries,
469 unsigned int nr_entries,
470 gfp_t alloc_flags)
471{
83a4f1ef 472 return __stack_depot_save(entries, nr_entries, 0, alloc_flags, true);
11ac25c6 473}
c0cfc337 474EXPORT_SYMBOL_GPL(stack_depot_save);
15ef6a98
AK
475
476/**
477 * stack_depot_fetch - Fetch stack entries from a depot
478 *
479 * @handle: Stack depot handle which was returned from
480 * stack_depot_save().
481 * @entries: Pointer to store the entries address
482 *
483 * Return: The number of trace entries for this depot.
484 */
485unsigned int stack_depot_fetch(depot_stack_handle_t handle,
486 unsigned long **entries)
487{
488 union handle_parts parts = { .handle = handle };
961c949b 489 void *pool;
424cafee 490 size_t offset = parts.offset << DEPOT_STACK_ALIGN;
15ef6a98
AK
491 struct stack_record *stack;
492
493 *entries = NULL;
494 if (!handle)
495 return 0;
496
961c949b
AK
497 if (parts.pool_index > pool_index) {
498 WARN(1, "pool index %d out of bounds (%d) for stack id %08x\n",
499 parts.pool_index, pool_index, handle);
15ef6a98
AK
500 return 0;
501 }
961c949b
AK
502 pool = stack_pools[parts.pool_index];
503 if (!pool)
15ef6a98 504 return 0;
961c949b 505 stack = pool + offset;
15ef6a98
AK
506
507 *entries = stack->entries;
508 return stack->size;
509}
510EXPORT_SYMBOL_GPL(stack_depot_fetch);
511
512/**
513 * stack_depot_print - print stack entries from a depot
514 *
515 * @stack: Stack depot handle which was returned from
516 * stack_depot_save().
517 *
518 */
519void stack_depot_print(depot_stack_handle_t stack)
520{
521 unsigned long *entries;
522 unsigned int nr_entries;
523
524 nr_entries = stack_depot_fetch(stack, &entries);
525 if (nr_entries > 0)
526 stack_trace_print(entries, nr_entries, 0);
527}
528EXPORT_SYMBOL_GPL(stack_depot_print);
529
530/**
531 * stack_depot_snprint - print stack entries from a depot into a buffer
532 *
533 * @handle: Stack depot handle which was returned from
534 * stack_depot_save().
535 * @buf: Pointer to the print buffer
536 *
537 * @size: Size of the print buffer
538 *
539 * @spaces: Number of leading spaces to print
540 *
541 * Return: Number of bytes printed.
542 */
543int stack_depot_snprint(depot_stack_handle_t handle, char *buf, size_t size,
544 int spaces)
545{
546 unsigned long *entries;
547 unsigned int nr_entries;
548
549 nr_entries = stack_depot_fetch(handle, &entries);
550 return nr_entries ? stack_trace_snprint(buf, size, entries, nr_entries,
551 spaces) : 0;
552}
553EXPORT_SYMBOL_GPL(stack_depot_snprint);
554
555unsigned int stack_depot_get_extra_bits(depot_stack_handle_t handle)
556{
557 union handle_parts parts = { .handle = handle };
558
559 return parts.extra;
560}
561EXPORT_SYMBOL(stack_depot_get_extra_bits);