lib/stackdepot: use pr_fmt to define message format
[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
AP
38
39#define DEPOT_STACK_BITS (sizeof(depot_stack_handle_t) * 8)
40
7c31190b 41#define STACK_ALLOC_NULL_PROTECTION_BITS 1
cd11016e
AP
42#define STACK_ALLOC_ORDER 2 /* 'Slab' size order for stack depot, 4 pages */
43#define STACK_ALLOC_SIZE (1LL << (PAGE_SHIFT + STACK_ALLOC_ORDER))
44#define STACK_ALLOC_ALIGN 4
45#define STACK_ALLOC_OFFSET_BITS (STACK_ALLOC_ORDER + PAGE_SHIFT - \
46 STACK_ALLOC_ALIGN)
7c31190b 47#define STACK_ALLOC_INDEX_BITS (DEPOT_STACK_BITS - \
83a4f1ef
AP
48 STACK_ALLOC_NULL_PROTECTION_BITS - \
49 STACK_ALLOC_OFFSET_BITS - STACK_DEPOT_EXTRA_BITS)
02754e0a 50#define STACK_ALLOC_SLABS_CAP 8192
cd11016e
AP
51#define STACK_ALLOC_MAX_SLABS \
52 (((1LL << (STACK_ALLOC_INDEX_BITS)) < STACK_ALLOC_SLABS_CAP) ? \
53 (1LL << (STACK_ALLOC_INDEX_BITS)) : STACK_ALLOC_SLABS_CAP)
54
55/* The compact structure to store the reference to stacks. */
56union handle_parts {
57 depot_stack_handle_t handle;
58 struct {
59 u32 slabindex : STACK_ALLOC_INDEX_BITS;
60 u32 offset : STACK_ALLOC_OFFSET_BITS;
7c31190b 61 u32 valid : STACK_ALLOC_NULL_PROTECTION_BITS;
83a4f1ef 62 u32 extra : STACK_DEPOT_EXTRA_BITS;
cd11016e
AP
63 };
64};
65
66struct stack_record {
67 struct stack_record *next; /* Link in the hashtable */
68 u32 hash; /* Hash in the hastable */
69 u32 size; /* Number of frames in the stack */
70 union handle_parts handle;
3a2b67e6 71 unsigned long entries[]; /* Variable-sized array of entries. */
cd11016e
AP
72};
73
a5f1783b
VB
74static bool __stack_depot_want_early_init __initdata = IS_ENABLED(CONFIG_STACKDEPOT_ALWAYS_INIT);
75static bool __stack_depot_early_init_passed __initdata;
76
cd11016e
AP
77static void *stack_slabs[STACK_ALLOC_MAX_SLABS];
78
79static int depot_index;
80static int next_slab_inited;
81static size_t depot_offset;
78564b94 82static DEFINE_RAW_SPINLOCK(depot_lock);
cd11016e 83
f9987921
VB
84/* one hash table bucket entry per 16kB of memory */
85#define STACK_HASH_SCALE 14
86/* limited between 4k and 1M buckets */
87#define STACK_HASH_ORDER_MIN 12
88#define STACK_HASH_ORDER_MAX 20
cd11016e
AP
89#define STACK_HASH_SEED 0x9747b28c
90
f9987921
VB
91static unsigned int stack_hash_order;
92static unsigned int stack_hash_mask;
93
e1fdc403
VJ
94static bool stack_depot_disable;
95static struct stack_record **stack_table;
96
97static int __init is_stack_depot_disabled(char *str)
98{
64427985
VJ
99 int ret;
100
101 ret = kstrtobool(str, &stack_depot_disable);
102 if (!ret && stack_depot_disable) {
4a6b5314 103 pr_info("disabled\n");
e1fdc403
VJ
104 stack_table = NULL;
105 }
106 return 0;
107}
108early_param("stack_depot_disable", is_stack_depot_disabled);
109
a5f1783b
VB
110void __init stack_depot_want_early_init(void)
111{
112 /* Too late to request early init now */
113 WARN_ON(__stack_depot_early_init_passed);
114
115 __stack_depot_want_early_init = true;
116}
117
118int __init stack_depot_early_init(void)
119{
f9987921 120 unsigned long entries = 0;
a5f1783b
VB
121
122 /* This is supposed to be called only once, from mm_init() */
123 if (WARN_ON(__stack_depot_early_init_passed))
124 return 0;
125
126 __stack_depot_early_init_passed = true;
127
f9987921
VB
128 if (kasan_enabled() && !stack_hash_order)
129 stack_hash_order = STACK_HASH_ORDER_MAX;
130
a5f1783b
VB
131 if (!__stack_depot_want_early_init || stack_depot_disable)
132 return 0;
133
f9987921
VB
134 if (stack_hash_order)
135 entries = 1UL << stack_hash_order;
136 stack_table = alloc_large_system_hash("stackdepot",
137 sizeof(struct stack_record *),
138 entries,
139 STACK_HASH_SCALE,
140 HASH_EARLY | HASH_ZERO,
141 NULL,
142 &stack_hash_mask,
143 1UL << STACK_HASH_ORDER_MIN,
144 1UL << STACK_HASH_ORDER_MAX);
a5f1783b
VB
145
146 if (!stack_table) {
4a6b5314 147 pr_err("hash table allocation failed, disabling\n");
a5f1783b
VB
148 stack_depot_disable = true;
149 return -ENOMEM;
150 }
151
152 return 0;
153}
154
155int stack_depot_init(void)
e1fdc403 156{
2dba5eb1 157 static DEFINE_MUTEX(stack_depot_init_mutex);
a5f1783b 158 int ret = 0;
2dba5eb1
VB
159
160 mutex_lock(&stack_depot_init_mutex);
161 if (!stack_depot_disable && !stack_table) {
f9987921
VB
162 unsigned long entries;
163 int scale = STACK_HASH_SCALE;
164
165 if (stack_hash_order) {
166 entries = 1UL << stack_hash_order;
167 } else {
168 entries = nr_free_buffer_pages();
169 entries = roundup_pow_of_two(entries);
170
171 if (scale > PAGE_SHIFT)
172 entries >>= (scale - PAGE_SHIFT);
173 else
174 entries <<= (PAGE_SHIFT - scale);
175 }
176
177 if (entries < 1UL << STACK_HASH_ORDER_MIN)
178 entries = 1UL << STACK_HASH_ORDER_MIN;
179 if (entries > 1UL << STACK_HASH_ORDER_MAX)
180 entries = 1UL << STACK_HASH_ORDER_MAX;
181
4a6b5314 182 pr_info("allocating hash table of %lu entries with kvcalloc\n",
f9987921
VB
183 entries);
184 stack_table = kvcalloc(entries, sizeof(struct stack_record *), GFP_KERNEL);
a5f1783b 185 if (!stack_table) {
4a6b5314 186 pr_err("hash table allocation failed, disabling\n");
2dba5eb1 187 stack_depot_disable = true;
a5f1783b 188 ret = -ENOMEM;
2dba5eb1 189 }
f9987921 190 stack_hash_mask = entries - 1;
e1fdc403 191 }
2dba5eb1 192 mutex_unlock(&stack_depot_init_mutex);
a5f1783b 193 return ret;
e1fdc403 194}
2dba5eb1 195EXPORT_SYMBOL_GPL(stack_depot_init);
cd11016e 196
15ef6a98
AK
197static bool init_stack_slab(void **prealloc)
198{
199 if (!*prealloc)
200 return false;
201 /*
202 * This smp_load_acquire() pairs with smp_store_release() to
203 * |next_slab_inited| below and in depot_alloc_stack().
204 */
205 if (smp_load_acquire(&next_slab_inited))
206 return true;
207 if (stack_slabs[depot_index] == NULL) {
208 stack_slabs[depot_index] = *prealloc;
209 *prealloc = NULL;
210 } else {
211 /* If this is the last depot slab, do not touch the next one. */
212 if (depot_index + 1 < STACK_ALLOC_MAX_SLABS) {
213 stack_slabs[depot_index + 1] = *prealloc;
214 *prealloc = NULL;
215 }
216 /*
217 * This smp_store_release pairs with smp_load_acquire() from
218 * |next_slab_inited| above and in stack_depot_save().
219 */
220 smp_store_release(&next_slab_inited, 1);
221 }
222 return true;
223}
224
225/* Allocation of a new stack in raw storage */
226static struct stack_record *
227depot_alloc_stack(unsigned long *entries, int size, u32 hash, void **prealloc)
228{
229 struct stack_record *stack;
230 size_t required_size = struct_size(stack, entries, size);
231
232 required_size = ALIGN(required_size, 1 << STACK_ALLOC_ALIGN);
233
234 if (unlikely(depot_offset + required_size > STACK_ALLOC_SIZE)) {
235 if (unlikely(depot_index + 1 >= STACK_ALLOC_MAX_SLABS)) {
236 WARN_ONCE(1, "Stack depot reached limit capacity");
237 return NULL;
238 }
239 depot_index++;
240 depot_offset = 0;
241 /*
242 * smp_store_release() here pairs with smp_load_acquire() from
243 * |next_slab_inited| in stack_depot_save() and
244 * init_stack_slab().
245 */
246 if (depot_index + 1 < STACK_ALLOC_MAX_SLABS)
247 smp_store_release(&next_slab_inited, 0);
248 }
249 init_stack_slab(prealloc);
250 if (stack_slabs[depot_index] == NULL)
251 return NULL;
252
253 stack = stack_slabs[depot_index] + depot_offset;
254
255 stack->hash = hash;
256 stack->size = size;
257 stack->handle.slabindex = depot_index;
258 stack->handle.offset = depot_offset >> STACK_ALLOC_ALIGN;
259 stack->handle.valid = 1;
260 stack->handle.extra = 0;
261 memcpy(stack->entries, entries, flex_array_size(stack, entries, size));
262 depot_offset += required_size;
263
264 return stack;
265}
266
cd11016e
AP
267/* Calculate hash for a stack */
268static inline u32 hash_stack(unsigned long *entries, unsigned int size)
269{
270 return jhash2((u32 *)entries,
180644f8
GS
271 array_size(size, sizeof(*entries)) / sizeof(u32),
272 STACK_HASH_SEED);
cd11016e
AP
273}
274
a571b272
AP
275/* Use our own, non-instrumented version of memcmp().
276 *
277 * We actually don't care about the order, just the equality.
278 */
279static inline
280int stackdepot_memcmp(const unsigned long *u1, const unsigned long *u2,
281 unsigned int n)
282{
283 for ( ; n-- ; u1++, u2++) {
284 if (*u1 != *u2)
285 return 1;
286 }
287 return 0;
288}
289
cd11016e
AP
290/* Find a stack that is equal to the one stored in entries in the hash */
291static inline struct stack_record *find_stack(struct stack_record *bucket,
292 unsigned long *entries, int size,
293 u32 hash)
294{
295 struct stack_record *found;
296
297 for (found = bucket; found; found = found->next) {
298 if (found->hash == hash &&
299 found->size == size &&
a571b272 300 !stackdepot_memcmp(entries, found->entries, size))
cd11016e 301 return found;
cd11016e
AP
302 }
303 return NULL;
304}
305
cd11016e 306/**
11ac25c6 307 * __stack_depot_save - Save a stack trace from an array
c0cfc337
TG
308 *
309 * @entries: Pointer to storage array
310 * @nr_entries: Size of the storage array
83a4f1ef 311 * @extra_bits: Flags to store in unused bits of depot_stack_handle_t
c0cfc337 312 * @alloc_flags: Allocation gfp flags
11ac25c6
ME
313 * @can_alloc: Allocate stack slabs (increased chance of failure if false)
314 *
315 * Saves a stack trace from @entries array of size @nr_entries. If @can_alloc is
316 * %true, is allowed to replenish the stack slab pool in case no space is left
317 * (allocates using GFP flags of @alloc_flags). If @can_alloc is %false, avoids
318 * any allocations and will fail if no space is left to store the stack trace.
319 *
e9400660
ME
320 * If the stack trace in @entries is from an interrupt, only the portion up to
321 * interrupt entry is saved.
322 *
83a4f1ef
AP
323 * Additional opaque flags can be passed in @extra_bits, stored in the unused
324 * bits of the stack handle, and retrieved using stack_depot_get_extra_bits()
325 * without calling stack_depot_fetch().
326 *
11ac25c6
ME
327 * Context: Any context, but setting @can_alloc to %false is required if
328 * alloc_pages() cannot be used from the current context. Currently
329 * this is the case from contexts where neither %GFP_ATOMIC nor
330 * %GFP_NOWAIT can be used (NMI, raw_spin_lock).
cd11016e 331 *
11ac25c6 332 * Return: The handle of the stack struct stored in depot, 0 on failure.
cd11016e 333 */
11ac25c6
ME
334depot_stack_handle_t __stack_depot_save(unsigned long *entries,
335 unsigned int nr_entries,
83a4f1ef 336 unsigned int extra_bits,
11ac25c6 337 gfp_t alloc_flags, bool can_alloc)
cd11016e 338{
cd11016e 339 struct stack_record *found = NULL, **bucket;
83a4f1ef 340 union handle_parts retval = { .handle = 0 };
cd11016e
AP
341 struct page *page = NULL;
342 void *prealloc = NULL;
c0cfc337
TG
343 unsigned long flags;
344 u32 hash;
cd11016e 345
e9400660
ME
346 /*
347 * If this stack trace is from an interrupt, including anything before
348 * interrupt entry usually leads to unbounded stackdepot growth.
349 *
350 * Because use of filter_irq_stacks() is a requirement to ensure
351 * stackdepot can efficiently deduplicate interrupt stacks, always
352 * filter_irq_stacks() to simplify all callers' use of stackdepot.
353 */
354 nr_entries = filter_irq_stacks(entries, nr_entries);
355
e1fdc403 356 if (unlikely(nr_entries == 0) || stack_depot_disable)
cd11016e
AP
357 goto fast_exit;
358
c0cfc337 359 hash = hash_stack(entries, nr_entries);
f9987921 360 bucket = &stack_table[hash & stack_hash_mask];
cd11016e
AP
361
362 /*
363 * Fast path: look the stack trace up without locking.
364 * The smp_load_acquire() here pairs with smp_store_release() to
365 * |bucket| below.
366 */
c0cfc337
TG
367 found = find_stack(smp_load_acquire(bucket), entries,
368 nr_entries, hash);
cd11016e
AP
369 if (found)
370 goto exit;
371
372 /*
373 * Check if the current or the next stack slab need to be initialized.
374 * If so, allocate the memory - we won't be able to do that under the
375 * lock.
376 *
377 * The smp_load_acquire() here pairs with smp_store_release() to
378 * |next_slab_inited| in depot_alloc_stack() and init_stack_slab().
379 */
11ac25c6 380 if (unlikely(can_alloc && !smp_load_acquire(&next_slab_inited))) {
cd11016e
AP
381 /*
382 * Zero out zone modifiers, as we don't have specific zone
383 * requirements. Keep the flags related to allocation in atomic
384 * contexts and I/O.
385 */
386 alloc_flags &= ~GFP_ZONEMASK;
387 alloc_flags &= (GFP_ATOMIC | GFP_KERNEL);
87cc271d 388 alloc_flags |= __GFP_NOWARN;
cd11016e
AP
389 page = alloc_pages(alloc_flags, STACK_ALLOC_ORDER);
390 if (page)
391 prealloc = page_address(page);
392 }
393
78564b94 394 raw_spin_lock_irqsave(&depot_lock, flags);
cd11016e 395
c0cfc337 396 found = find_stack(*bucket, entries, nr_entries, hash);
cd11016e 397 if (!found) {
7f2b8818
ME
398 struct stack_record *new = depot_alloc_stack(entries, nr_entries, hash, &prealloc);
399
cd11016e
AP
400 if (new) {
401 new->next = *bucket;
402 /*
403 * This smp_store_release() pairs with
404 * smp_load_acquire() from |bucket| above.
405 */
406 smp_store_release(bucket, new);
407 found = new;
408 }
409 } else if (prealloc) {
410 /*
411 * We didn't need to store this stack trace, but let's keep
412 * the preallocated memory for the future.
413 */
414 WARN_ON(!init_stack_slab(&prealloc));
415 }
416
78564b94 417 raw_spin_unlock_irqrestore(&depot_lock, flags);
cd11016e
AP
418exit:
419 if (prealloc) {
420 /* Nobody used this memory, ok to free it. */
421 free_pages((unsigned long)prealloc, STACK_ALLOC_ORDER);
422 }
423 if (found)
83a4f1ef 424 retval.handle = found->handle.handle;
cd11016e 425fast_exit:
83a4f1ef
AP
426 retval.extra = extra_bits;
427
428 return retval.handle;
cd11016e 429}
11ac25c6
ME
430EXPORT_SYMBOL_GPL(__stack_depot_save);
431
432/**
433 * stack_depot_save - Save a stack trace from an array
434 *
435 * @entries: Pointer to storage array
436 * @nr_entries: Size of the storage array
437 * @alloc_flags: Allocation gfp flags
438 *
439 * Context: Contexts where allocations via alloc_pages() are allowed.
440 * See __stack_depot_save() for more details.
441 *
442 * Return: The handle of the stack struct stored in depot, 0 on failure.
443 */
444depot_stack_handle_t stack_depot_save(unsigned long *entries,
445 unsigned int nr_entries,
446 gfp_t alloc_flags)
447{
83a4f1ef 448 return __stack_depot_save(entries, nr_entries, 0, alloc_flags, true);
11ac25c6 449}
c0cfc337 450EXPORT_SYMBOL_GPL(stack_depot_save);
15ef6a98
AK
451
452/**
453 * stack_depot_fetch - Fetch stack entries from a depot
454 *
455 * @handle: Stack depot handle which was returned from
456 * stack_depot_save().
457 * @entries: Pointer to store the entries address
458 *
459 * Return: The number of trace entries for this depot.
460 */
461unsigned int stack_depot_fetch(depot_stack_handle_t handle,
462 unsigned long **entries)
463{
464 union handle_parts parts = { .handle = handle };
465 void *slab;
466 size_t offset = parts.offset << STACK_ALLOC_ALIGN;
467 struct stack_record *stack;
468
469 *entries = NULL;
470 if (!handle)
471 return 0;
472
473 if (parts.slabindex > depot_index) {
474 WARN(1, "slab index %d out of bounds (%d) for stack id %08x\n",
475 parts.slabindex, depot_index, handle);
476 return 0;
477 }
478 slab = stack_slabs[parts.slabindex];
479 if (!slab)
480 return 0;
481 stack = slab + offset;
482
483 *entries = stack->entries;
484 return stack->size;
485}
486EXPORT_SYMBOL_GPL(stack_depot_fetch);
487
488/**
489 * stack_depot_print - print stack entries from a depot
490 *
491 * @stack: Stack depot handle which was returned from
492 * stack_depot_save().
493 *
494 */
495void stack_depot_print(depot_stack_handle_t stack)
496{
497 unsigned long *entries;
498 unsigned int nr_entries;
499
500 nr_entries = stack_depot_fetch(stack, &entries);
501 if (nr_entries > 0)
502 stack_trace_print(entries, nr_entries, 0);
503}
504EXPORT_SYMBOL_GPL(stack_depot_print);
505
506/**
507 * stack_depot_snprint - print stack entries from a depot into a buffer
508 *
509 * @handle: Stack depot handle which was returned from
510 * stack_depot_save().
511 * @buf: Pointer to the print buffer
512 *
513 * @size: Size of the print buffer
514 *
515 * @spaces: Number of leading spaces to print
516 *
517 * Return: Number of bytes printed.
518 */
519int stack_depot_snprint(depot_stack_handle_t handle, char *buf, size_t size,
520 int spaces)
521{
522 unsigned long *entries;
523 unsigned int nr_entries;
524
525 nr_entries = stack_depot_fetch(handle, &entries);
526 return nr_entries ? stack_trace_snprint(buf, size, entries, nr_entries,
527 spaces) : 0;
528}
529EXPORT_SYMBOL_GPL(stack_depot_snprint);
530
531unsigned int stack_depot_get_extra_bits(depot_stack_handle_t handle)
532{
533 union handle_parts parts = { .handle = handle };
534
535 return parts.extra;
536}
537EXPORT_SYMBOL(stack_depot_get_extra_bits);