1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Slab allocator functions that are independent of the allocator strategy
4 *
5 * (C) 2012 Christoph Lameter <cl@linux.com>
6 */
7 #include <linux/slab.h>
8
9 #include <linux/mm.h>
10 #include <linux/poison.h>
11 #include <linux/interrupt.h>
12 #include <linux/memory.h>
13 #include <linux/cache.h>
14 #include <linux/compiler.h>
15 #include <linux/kfence.h>
16 #include <linux/module.h>
17 #include <linux/cpu.h>
18 #include <linux/uaccess.h>
19 #include <linux/seq_file.h>
20 #include <linux/proc_fs.h>
21 #include <linux/debugfs.h>
22 #include <linux/kasan.h>
23 #include <asm/cacheflush.h>
24 #include <asm/tlbflush.h>
25 #include <asm/page.h>
26 #include <linux/memcontrol.h>
27
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/kmem.h>
30 #undef CREATE_TRACE_POINTS
31 #include <trace/hooks/mm.h>
32 #include "internal.h"
33
34 #include "slab.h"
35
36 enum slab_state slab_state;
37 LIST_HEAD(slab_caches);
38 DEFINE_MUTEX(slab_mutex);
39 struct kmem_cache *kmem_cache;
40
41 #ifdef CONFIG_HARDENED_USERCOPY
42 bool usercopy_fallback __ro_after_init =
43 IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
44 module_param(usercopy_fallback, bool, 0400);
45 MODULE_PARM_DESC(usercopy_fallback,
46 "WARN instead of reject usercopy whitelist violations");
47 #endif
48
49 static LIST_HEAD(slab_caches_to_rcu_destroy);
50 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
51 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
52 slab_caches_to_rcu_destroy_workfn);
53
54 /*
55 * Set of flags that will prevent slab merging
56 */
57 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
58 SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
59 SLAB_FAILSLAB | kasan_never_merge())
60
61 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
62 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
63
64 /*
65 * Merge control. If this is set then no merging of slab caches will occur.
66 */
67 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
68
setup_slab_nomerge(char * str)69 static int __init setup_slab_nomerge(char *str)
70 {
71 slab_nomerge = true;
72 return 1;
73 }
74
setup_slab_merge(char * str)75 static int __init setup_slab_merge(char *str)
76 {
77 slab_nomerge = false;
78 return 1;
79 }
80
81 #ifdef CONFIG_SLUB
82 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
83 __setup_param("slub_merge", slub_merge, setup_slab_merge, 0);
84 #endif
85
86 __setup("slab_nomerge", setup_slab_nomerge);
87 __setup("slab_merge", setup_slab_merge);
88
89 /*
90 * Determine the size of a slab object
91 */
kmem_cache_size(struct kmem_cache * s)92 unsigned int kmem_cache_size(struct kmem_cache *s)
93 {
94 return s->object_size;
95 }
96 EXPORT_SYMBOL(kmem_cache_size);
97
98 #ifdef CONFIG_DEBUG_VM
kmem_cache_sanity_check(const char * name,unsigned int size)99 static int kmem_cache_sanity_check(const char *name, unsigned int size)
100 {
101 if (!name || in_interrupt() || size > KMALLOC_MAX_SIZE) {
102 pr_err("kmem_cache_create(%s) integrity check failed\n", name);
103 return -EINVAL;
104 }
105
106 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
107 return 0;
108 }
109 #else
kmem_cache_sanity_check(const char * name,unsigned int size)110 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
111 {
112 return 0;
113 }
114 #endif
115
__kmem_cache_free_bulk(struct kmem_cache * s,size_t nr,void ** p)116 void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
117 {
118 size_t i;
119
120 for (i = 0; i < nr; i++) {
121 if (s)
122 kmem_cache_free(s, p[i]);
123 else
124 kfree(p[i]);
125 }
126 }
127
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t nr,void ** p)128 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
129 void **p)
130 {
131 size_t i;
132
133 for (i = 0; i < nr; i++) {
134 void *x = p[i] = kmem_cache_alloc(s, flags);
135 if (!x) {
136 __kmem_cache_free_bulk(s, i, p);
137 return 0;
138 }
139 }
140 return i;
141 }
142
143 /*
144 * Figure out what the alignment of the objects will be given a set of
145 * flags, a user specified alignment and the size of the objects.
146 */
calculate_alignment(slab_flags_t flags,unsigned int align,unsigned int size)147 static unsigned int calculate_alignment(slab_flags_t flags,
148 unsigned int align, unsigned int size)
149 {
150 /*
151 * If the user wants hardware cache aligned objects then follow that
152 * suggestion if the object is sufficiently large.
153 *
154 * The hardware cache alignment cannot override the specified
155 * alignment though. If that is greater then use it.
156 */
157 if (flags & SLAB_HWCACHE_ALIGN) {
158 unsigned int ralign;
159
160 ralign = cache_line_size();
161 while (size <= ralign / 2)
162 ralign /= 2;
163 align = max(align, ralign);
164 }
165
166 if (align < ARCH_SLAB_MINALIGN)
167 align = ARCH_SLAB_MINALIGN;
168
169 return ALIGN(align, sizeof(void *));
170 }
171
172 /*
173 * Find a mergeable slab cache
174 */
slab_unmergeable(struct kmem_cache * s)175 int slab_unmergeable(struct kmem_cache *s)
176 {
177 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
178 return 1;
179
180 if (s->ctor)
181 return 1;
182
183 if (s->usersize)
184 return 1;
185
186 /*
187 * We may have set a slab to be unmergeable during bootstrap.
188 */
189 if (s->refcount < 0)
190 return 1;
191
192 return 0;
193 }
194
find_mergeable(unsigned int size,unsigned int align,slab_flags_t flags,const char * name,void (* ctor)(void *))195 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
196 slab_flags_t flags, const char *name, void (*ctor)(void *))
197 {
198 struct kmem_cache *s;
199
200 if (slab_nomerge)
201 return NULL;
202
203 if (ctor)
204 return NULL;
205
206 size = ALIGN(size, sizeof(void *));
207 align = calculate_alignment(flags, align, size);
208 size = ALIGN(size, align);
209 flags = kmem_cache_flags(size, flags, name);
210
211 if (flags & SLAB_NEVER_MERGE)
212 return NULL;
213
214 list_for_each_entry_reverse(s, &slab_caches, list) {
215 if (slab_unmergeable(s))
216 continue;
217
218 if (size > s->size)
219 continue;
220
221 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
222 continue;
223 /*
224 * Check if alignment is compatible.
225 * Courtesy of Adrian Drzewiecki
226 */
227 if ((s->size & ~(align - 1)) != s->size)
228 continue;
229
230 if (s->size - size >= sizeof(void *))
231 continue;
232
233 if (IS_ENABLED(CONFIG_SLAB) && align &&
234 (align > s->align || s->align % align))
235 continue;
236
237 return s;
238 }
239 return NULL;
240 }
241
create_cache(const char * name,unsigned int object_size,unsigned int align,slab_flags_t flags,unsigned int useroffset,unsigned int usersize,void (* ctor)(void *),struct kmem_cache * root_cache)242 static struct kmem_cache *create_cache(const char *name,
243 unsigned int object_size, unsigned int align,
244 slab_flags_t flags, unsigned int useroffset,
245 unsigned int usersize, void (*ctor)(void *),
246 struct kmem_cache *root_cache)
247 {
248 struct kmem_cache *s;
249 int err;
250
251 if (WARN_ON(useroffset + usersize > object_size))
252 useroffset = usersize = 0;
253
254 err = -ENOMEM;
255 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
256 if (!s)
257 goto out;
258
259 s->name = name;
260 s->size = s->object_size = object_size;
261 s->align = align;
262 s->ctor = ctor;
263 s->useroffset = useroffset;
264 s->usersize = usersize;
265
266 err = __kmem_cache_create(s, flags);
267 if (err)
268 goto out_free_cache;
269
270 s->refcount = 1;
271 list_add(&s->list, &slab_caches);
272 out:
273 if (err)
274 return ERR_PTR(err);
275 return s;
276
277 out_free_cache:
278 kmem_cache_free(kmem_cache, s);
279 goto out;
280 }
281
282 /**
283 * kmem_cache_create_usercopy - Create a cache with a region suitable
284 * for copying to userspace
285 * @name: A string which is used in /proc/slabinfo to identify this cache.
286 * @size: The size of objects to be created in this cache.
287 * @align: The required alignment for the objects.
288 * @flags: SLAB flags
289 * @useroffset: Usercopy region offset
290 * @usersize: Usercopy region size
291 * @ctor: A constructor for the objects.
292 *
293 * Cannot be called within a interrupt, but can be interrupted.
294 * The @ctor is run when new pages are allocated by the cache.
295 *
296 * The flags are
297 *
298 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
299 * to catch references to uninitialised memory.
300 *
301 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
302 * for buffer overruns.
303 *
304 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
305 * cacheline. This can be beneficial if you're counting cycles as closely
306 * as davem.
307 *
308 * Return: a pointer to the cache on success, NULL on failure.
309 */
310 struct kmem_cache *
kmem_cache_create_usercopy(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,unsigned int useroffset,unsigned int usersize,void (* ctor)(void *))311 kmem_cache_create_usercopy(const char *name,
312 unsigned int size, unsigned int align,
313 slab_flags_t flags,
314 unsigned int useroffset, unsigned int usersize,
315 void (*ctor)(void *))
316 {
317 struct kmem_cache *s = NULL;
318 const char *cache_name;
319 int err;
320
321 #ifdef CONFIG_SLUB_DEBUG
322 /*
323 * If no slub_debug was enabled globally, the static key is not yet
324 * enabled by setup_slub_debug(). Enable it if the cache is being
325 * created with any of the debugging flags passed explicitly.
326 */
327 if (flags & SLAB_DEBUG_FLAGS)
328 static_branch_enable(&slub_debug_enabled);
329 #endif
330
331 mutex_lock(&slab_mutex);
332
333 err = kmem_cache_sanity_check(name, size);
334 if (err) {
335 goto out_unlock;
336 }
337
338 /* Refuse requests with allocator specific flags */
339 if (flags & ~SLAB_FLAGS_PERMITTED) {
340 err = -EINVAL;
341 goto out_unlock;
342 }
343
344 /*
345 * Some allocators will constraint the set of valid flags to a subset
346 * of all flags. We expect them to define CACHE_CREATE_MASK in this
347 * case, and we'll just provide them with a sanitized version of the
348 * passed flags.
349 */
350 flags &= CACHE_CREATE_MASK;
351
352 /* Fail closed on bad usersize of useroffset values. */
353 if (WARN_ON(!usersize && useroffset) ||
354 WARN_ON(size < usersize || size - usersize < useroffset))
355 usersize = useroffset = 0;
356
357 if (!usersize)
358 s = __kmem_cache_alias(name, size, align, flags, ctor);
359 if (s)
360 goto out_unlock;
361
362 cache_name = kstrdup_const(name, GFP_KERNEL);
363 if (!cache_name) {
364 err = -ENOMEM;
365 goto out_unlock;
366 }
367
368 s = create_cache(cache_name, size,
369 calculate_alignment(flags, align, size),
370 flags, useroffset, usersize, ctor, NULL);
371 if (IS_ERR(s)) {
372 err = PTR_ERR(s);
373 kfree_const(cache_name);
374 }
375
376 out_unlock:
377 mutex_unlock(&slab_mutex);
378
379 if (err) {
380 if (flags & SLAB_PANIC)
381 panic("%s: Failed to create slab '%s'. Error %d\n",
382 __func__, name, err);
383 else {
384 pr_warn("%s(%s) failed with error %d\n",
385 __func__, name, err);
386 dump_stack();
387 }
388 return NULL;
389 }
390 return s;
391 }
392 EXPORT_SYMBOL(kmem_cache_create_usercopy);
393
394 /**
395 * kmem_cache_create - Create a cache.
396 * @name: A string which is used in /proc/slabinfo to identify this cache.
397 * @size: The size of objects to be created in this cache.
398 * @align: The required alignment for the objects.
399 * @flags: SLAB flags
400 * @ctor: A constructor for the objects.
401 *
402 * Cannot be called within a interrupt, but can be interrupted.
403 * The @ctor is run when new pages are allocated by the cache.
404 *
405 * The flags are
406 *
407 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
408 * to catch references to uninitialised memory.
409 *
410 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
411 * for buffer overruns.
412 *
413 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
414 * cacheline. This can be beneficial if you're counting cycles as closely
415 * as davem.
416 *
417 * Return: a pointer to the cache on success, NULL on failure.
418 */
419 struct kmem_cache *
kmem_cache_create(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))420 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
421 slab_flags_t flags, void (*ctor)(void *))
422 {
423 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
424 ctor);
425 }
426 EXPORT_SYMBOL(kmem_cache_create);
427
slab_caches_to_rcu_destroy_workfn(struct work_struct * work)428 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
429 {
430 LIST_HEAD(to_destroy);
431 struct kmem_cache *s, *s2;
432
433 /*
434 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
435 * @slab_caches_to_rcu_destroy list. The slab pages are freed
436 * through RCU and the associated kmem_cache are dereferenced
437 * while freeing the pages, so the kmem_caches should be freed only
438 * after the pending RCU operations are finished. As rcu_barrier()
439 * is a pretty slow operation, we batch all pending destructions
440 * asynchronously.
441 */
442 mutex_lock(&slab_mutex);
443 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
444 mutex_unlock(&slab_mutex);
445
446 if (list_empty(&to_destroy))
447 return;
448
449 rcu_barrier();
450
451 list_for_each_entry_safe(s, s2, &to_destroy, list) {
452 debugfs_slab_release(s);
453 kfence_shutdown_cache(s);
454 #ifdef SLAB_SUPPORTS_SYSFS
455 sysfs_slab_release(s);
456 #else
457 slab_kmem_cache_release(s);
458 #endif
459 }
460 }
461
shutdown_cache(struct kmem_cache * s)462 static int shutdown_cache(struct kmem_cache *s)
463 {
464 /* free asan quarantined objects */
465 kasan_cache_shutdown(s);
466
467 if (__kmem_cache_shutdown(s) != 0)
468 return -EBUSY;
469
470 list_del(&s->list);
471
472 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
473 #ifdef SLAB_SUPPORTS_SYSFS
474 sysfs_slab_unlink(s);
475 #endif
476 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
477 schedule_work(&slab_caches_to_rcu_destroy_work);
478 } else {
479 kfence_shutdown_cache(s);
480 debugfs_slab_release(s);
481 #ifdef SLAB_SUPPORTS_SYSFS
482 sysfs_slab_unlink(s);
483 sysfs_slab_release(s);
484 #else
485 slab_kmem_cache_release(s);
486 #endif
487 }
488
489 return 0;
490 }
491
slab_kmem_cache_release(struct kmem_cache * s)492 void slab_kmem_cache_release(struct kmem_cache *s)
493 {
494 __kmem_cache_release(s);
495 kfree_const(s->name);
496 kmem_cache_free(kmem_cache, s);
497 }
498
kmem_cache_destroy(struct kmem_cache * s)499 void kmem_cache_destroy(struct kmem_cache *s)
500 {
501 int err;
502
503 if (unlikely(!s) || !kasan_check_byte(s))
504 return;
505
506 cpus_read_lock();
507 mutex_lock(&slab_mutex);
508
509 s->refcount--;
510 if (s->refcount)
511 goto out_unlock;
512
513 err = shutdown_cache(s);
514 if (err) {
515 pr_err("%s %s: Slab cache still has objects\n",
516 __func__, s->name);
517 dump_stack();
518 }
519 out_unlock:
520 mutex_unlock(&slab_mutex);
521 cpus_read_unlock();
522 }
523 EXPORT_SYMBOL(kmem_cache_destroy);
524
525 /**
526 * kmem_cache_shrink - Shrink a cache.
527 * @cachep: The cache to shrink.
528 *
529 * Releases as many slabs as possible for a cache.
530 * To help debugging, a zero exit status indicates all slabs were released.
531 *
532 * Return: %0 if all slabs were released, non-zero otherwise
533 */
kmem_cache_shrink(struct kmem_cache * cachep)534 int kmem_cache_shrink(struct kmem_cache *cachep)
535 {
536 int ret;
537
538
539 kasan_cache_shrink(cachep);
540 ret = __kmem_cache_shrink(cachep);
541
542 return ret;
543 }
544 EXPORT_SYMBOL(kmem_cache_shrink);
545
slab_is_available(void)546 bool slab_is_available(void)
547 {
548 return slab_state >= UP;
549 }
550
551 #ifdef CONFIG_PRINTK
552 /**
553 * kmem_valid_obj - does the pointer reference a valid slab object?
554 * @object: pointer to query.
555 *
556 * Return: %true if the pointer is to a not-yet-freed object from
557 * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer
558 * is to an already-freed object, and %false otherwise.
559 */
kmem_valid_obj(void * object)560 bool kmem_valid_obj(void *object)
561 {
562 struct page *page;
563
564 /* Some arches consider ZERO_SIZE_PTR to be a valid address. */
565 if (object < (void *)PAGE_SIZE || !virt_addr_valid(object))
566 return false;
567 page = virt_to_head_page(object);
568 return PageSlab(page);
569 }
570 EXPORT_SYMBOL_GPL(kmem_valid_obj);
571
kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct page * page)572 static void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct page *page)
573 {
574 if (__kfence_obj_info(kpp, object, page))
575 return;
576 __kmem_obj_info(kpp, object, page);
577 }
578
579 /**
580 * kmem_dump_obj - Print available slab provenance information
581 * @object: slab object for which to find provenance information.
582 *
583 * This function uses pr_cont(), so that the caller is expected to have
584 * printed out whatever preamble is appropriate. The provenance information
585 * depends on the type of object and on how much debugging is enabled.
586 * For a slab-cache object, the fact that it is a slab object is printed,
587 * and, if available, the slab name, return address, and stack trace from
588 * the allocation and last free path of that object.
589 *
590 * This function will splat if passed a pointer to a non-slab object.
591 * If you are not sure what type of object you have, you should instead
592 * use mem_dump_obj().
593 */
kmem_dump_obj(void * object)594 void kmem_dump_obj(void *object)
595 {
596 char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc";
597 int i;
598 struct page *page;
599 unsigned long ptroffset;
600 struct kmem_obj_info kp = { };
601
602 if (WARN_ON_ONCE(!virt_addr_valid(object)))
603 return;
604 page = virt_to_head_page(object);
605 if (WARN_ON_ONCE(!PageSlab(page))) {
606 pr_cont(" non-slab memory.\n");
607 return;
608 }
609 kmem_obj_info(&kp, object, page);
610 if (kp.kp_slab_cache)
611 pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name);
612 else
613 pr_cont(" slab%s", cp);
614 if (is_kfence_address(object))
615 pr_cont(" (kfence)");
616 if (kp.kp_objp)
617 pr_cont(" start %px", kp.kp_objp);
618 if (kp.kp_data_offset)
619 pr_cont(" data offset %lu", kp.kp_data_offset);
620 if (kp.kp_objp) {
621 ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset;
622 pr_cont(" pointer offset %lu", ptroffset);
623 }
624 if (kp.kp_slab_cache && kp.kp_slab_cache->usersize)
625 pr_cont(" size %u", kp.kp_slab_cache->usersize);
626 if (kp.kp_ret)
627 pr_cont(" allocated at %pS\n", kp.kp_ret);
628 else
629 pr_cont("\n");
630 for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) {
631 if (!kp.kp_stack[i])
632 break;
633 pr_info(" %pS\n", kp.kp_stack[i]);
634 }
635
636 if (kp.kp_free_stack[0])
637 pr_cont(" Free path:\n");
638
639 for (i = 0; i < ARRAY_SIZE(kp.kp_free_stack); i++) {
640 if (!kp.kp_free_stack[i])
641 break;
642 pr_info(" %pS\n", kp.kp_free_stack[i]);
643 }
644
645 }
646 EXPORT_SYMBOL_GPL(kmem_dump_obj);
647 #endif
648
649 #ifndef CONFIG_SLOB
650 /* Create a cache during boot when no slab services are available yet */
create_boot_cache(struct kmem_cache * s,const char * name,unsigned int size,slab_flags_t flags,unsigned int useroffset,unsigned int usersize)651 void __init create_boot_cache(struct kmem_cache *s, const char *name,
652 unsigned int size, slab_flags_t flags,
653 unsigned int useroffset, unsigned int usersize)
654 {
655 int err;
656 unsigned int align = ARCH_KMALLOC_MINALIGN;
657
658 s->name = name;
659 s->size = s->object_size = size;
660
661 /*
662 * For power of two sizes, guarantee natural alignment for kmalloc
663 * caches, regardless of SL*B debugging options.
664 */
665 if (is_power_of_2(size))
666 align = max(align, size);
667 s->align = calculate_alignment(flags, align, size);
668
669 s->useroffset = useroffset;
670 s->usersize = usersize;
671
672 err = __kmem_cache_create(s, flags);
673
674 if (err)
675 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
676 name, size, err);
677
678 s->refcount = -1; /* Exempt from merging for now */
679 }
680
create_kmalloc_cache(const char * name,unsigned int size,slab_flags_t flags,unsigned int useroffset,unsigned int usersize)681 struct kmem_cache *__init create_kmalloc_cache(const char *name,
682 unsigned int size, slab_flags_t flags,
683 unsigned int useroffset, unsigned int usersize)
684 {
685 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
686
687 if (!s)
688 panic("Out of memory when creating slab %s\n", name);
689
690 create_boot_cache(s, name, size, flags, useroffset, usersize);
691 kasan_cache_create_kmalloc(s);
692 list_add(&s->list, &slab_caches);
693 s->refcount = 1;
694 return s;
695 }
696
697 struct kmem_cache *
698 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
699 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
700 EXPORT_SYMBOL(kmalloc_caches);
701
702 /*
703 * Conversion table for small slabs sizes / 8 to the index in the
704 * kmalloc array. This is necessary for slabs < 192 since we have non power
705 * of two cache sizes there. The size of larger slabs can be determined using
706 * fls.
707 */
708 static u8 size_index[24] __ro_after_init = {
709 3, /* 8 */
710 4, /* 16 */
711 5, /* 24 */
712 5, /* 32 */
713 6, /* 40 */
714 6, /* 48 */
715 6, /* 56 */
716 6, /* 64 */
717 1, /* 72 */
718 1, /* 80 */
719 1, /* 88 */
720 1, /* 96 */
721 7, /* 104 */
722 7, /* 112 */
723 7, /* 120 */
724 7, /* 128 */
725 2, /* 136 */
726 2, /* 144 */
727 2, /* 152 */
728 2, /* 160 */
729 2, /* 168 */
730 2, /* 176 */
731 2, /* 184 */
732 2 /* 192 */
733 };
734
size_index_elem(unsigned int bytes)735 static inline unsigned int size_index_elem(unsigned int bytes)
736 {
737 return (bytes - 1) / 8;
738 }
739
740 /*
741 * Find the kmem_cache structure that serves a given size of
742 * allocation
743 */
kmalloc_slab(size_t size,gfp_t flags)744 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
745 {
746 unsigned int index;
747
748 if (size <= 192) {
749 if (!size)
750 return ZERO_SIZE_PTR;
751
752 index = size_index[size_index_elem(size)];
753 } else {
754 if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
755 return NULL;
756 index = fls(size - 1);
757 }
758
759 return kmalloc_caches[kmalloc_type(flags)][index];
760 }
761
762 #ifdef CONFIG_ZONE_DMA
763 #define KMALLOC_DMA_NAME(sz) .name[KMALLOC_DMA] = "dma-kmalloc-" #sz,
764 #else
765 #define KMALLOC_DMA_NAME(sz)
766 #endif
767
768 #ifdef CONFIG_MEMCG_KMEM
769 #define KMALLOC_CGROUP_NAME(sz) .name[KMALLOC_CGROUP] = "kmalloc-cg-" #sz,
770 #else
771 #define KMALLOC_CGROUP_NAME(sz)
772 #endif
773
774 #define INIT_KMALLOC_INFO(__size, __short_size) \
775 { \
776 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
777 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
778 KMALLOC_CGROUP_NAME(__short_size) \
779 KMALLOC_DMA_NAME(__short_size) \
780 .size = __size, \
781 }
782
783 /*
784 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
785 * kmalloc_index() supports up to 2^25=32MB, so the final entry of the table is
786 * kmalloc-32M.
787 */
788 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
789 INIT_KMALLOC_INFO(0, 0),
790 INIT_KMALLOC_INFO(96, 96),
791 INIT_KMALLOC_INFO(192, 192),
792 INIT_KMALLOC_INFO(8, 8),
793 INIT_KMALLOC_INFO(16, 16),
794 INIT_KMALLOC_INFO(32, 32),
795 INIT_KMALLOC_INFO(64, 64),
796 INIT_KMALLOC_INFO(128, 128),
797 INIT_KMALLOC_INFO(256, 256),
798 INIT_KMALLOC_INFO(512, 512),
799 INIT_KMALLOC_INFO(1024, 1k),
800 INIT_KMALLOC_INFO(2048, 2k),
801 INIT_KMALLOC_INFO(4096, 4k),
802 INIT_KMALLOC_INFO(8192, 8k),
803 INIT_KMALLOC_INFO(16384, 16k),
804 INIT_KMALLOC_INFO(32768, 32k),
805 INIT_KMALLOC_INFO(65536, 64k),
806 INIT_KMALLOC_INFO(131072, 128k),
807 INIT_KMALLOC_INFO(262144, 256k),
808 INIT_KMALLOC_INFO(524288, 512k),
809 INIT_KMALLOC_INFO(1048576, 1M),
810 INIT_KMALLOC_INFO(2097152, 2M),
811 INIT_KMALLOC_INFO(4194304, 4M),
812 INIT_KMALLOC_INFO(8388608, 8M),
813 INIT_KMALLOC_INFO(16777216, 16M),
814 INIT_KMALLOC_INFO(33554432, 32M)
815 };
816
817 /*
818 * Patch up the size_index table if we have strange large alignment
819 * requirements for the kmalloc array. This is only the case for
820 * MIPS it seems. The standard arches will not generate any code here.
821 *
822 * Largest permitted alignment is 256 bytes due to the way we
823 * handle the index determination for the smaller caches.
824 *
825 * Make sure that nothing crazy happens if someone starts tinkering
826 * around with ARCH_KMALLOC_MINALIGN
827 */
setup_kmalloc_cache_index_table(void)828 void __init setup_kmalloc_cache_index_table(void)
829 {
830 unsigned int i;
831
832 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
833 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
834
835 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
836 unsigned int elem = size_index_elem(i);
837
838 if (elem >= ARRAY_SIZE(size_index))
839 break;
840 size_index[elem] = KMALLOC_SHIFT_LOW;
841 }
842
843 if (KMALLOC_MIN_SIZE >= 64) {
844 /*
845 * The 96 byte size cache is not used if the alignment
846 * is 64 byte.
847 */
848 for (i = 64 + 8; i <= 96; i += 8)
849 size_index[size_index_elem(i)] = 7;
850
851 }
852
853 if (KMALLOC_MIN_SIZE >= 128) {
854 /*
855 * The 192 byte sized cache is not used if the alignment
856 * is 128 byte. Redirect kmalloc to use the 256 byte cache
857 * instead.
858 */
859 for (i = 128 + 8; i <= 192; i += 8)
860 size_index[size_index_elem(i)] = 8;
861 }
862 }
863
864 static void __init
new_kmalloc_cache(int idx,enum kmalloc_cache_type type,slab_flags_t flags)865 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
866 {
867 if (type == KMALLOC_RECLAIM) {
868 flags |= SLAB_RECLAIM_ACCOUNT;
869 } else if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_CGROUP)) {
870 if (cgroup_memory_nokmem) {
871 kmalloc_caches[type][idx] = kmalloc_caches[KMALLOC_NORMAL][idx];
872 return;
873 }
874 flags |= SLAB_ACCOUNT;
875 }
876
877 kmalloc_caches[type][idx] = create_kmalloc_cache(
878 kmalloc_info[idx].name[type],
879 kmalloc_info[idx].size, flags, 0,
880 kmalloc_info[idx].size);
881
882 /*
883 * If CONFIG_MEMCG_KMEM is enabled, disable cache merging for
884 * KMALLOC_NORMAL caches.
885 */
886 if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_NORMAL))
887 kmalloc_caches[type][idx]->refcount = -1;
888 }
889
890 /*
891 * Create the kmalloc array. Some of the regular kmalloc arrays
892 * may already have been created because they were needed to
893 * enable allocations for slab creation.
894 */
create_kmalloc_caches(slab_flags_t flags)895 void __init create_kmalloc_caches(slab_flags_t flags)
896 {
897 int i;
898 enum kmalloc_cache_type type;
899
900 /*
901 * Including KMALLOC_CGROUP if CONFIG_MEMCG_KMEM defined
902 */
903 for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
904 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
905 if (!kmalloc_caches[type][i])
906 new_kmalloc_cache(i, type, flags);
907
908 /*
909 * Caches that are not of the two-to-the-power-of size.
910 * These have to be created immediately after the
911 * earlier power of two caches
912 */
913 if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
914 !kmalloc_caches[type][1])
915 new_kmalloc_cache(1, type, flags);
916 if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
917 !kmalloc_caches[type][2])
918 new_kmalloc_cache(2, type, flags);
919 }
920 }
921
922 /* Kmalloc array is now usable */
923 slab_state = UP;
924
925 #ifdef CONFIG_ZONE_DMA
926 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
927 struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
928
929 if (s) {
930 kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
931 kmalloc_info[i].name[KMALLOC_DMA],
932 kmalloc_info[i].size,
933 SLAB_CACHE_DMA | flags, 0,
934 kmalloc_info[i].size);
935 }
936 }
937 #endif
938 }
939 #endif /* !CONFIG_SLOB */
940
kmalloc_fix_flags(gfp_t flags)941 gfp_t kmalloc_fix_flags(gfp_t flags)
942 {
943 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
944
945 flags &= ~GFP_SLAB_BUG_MASK;
946 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
947 invalid_mask, &invalid_mask, flags, &flags);
948 dump_stack();
949
950 return flags;
951 }
952
953 /*
954 * To avoid unnecessary overhead, we pass through large allocation requests
955 * directly to the page allocator. We use __GFP_COMP, because we will need to
956 * know the allocation order to free the pages properly in kfree.
957 */
kmalloc_order(size_t size,gfp_t flags,unsigned int order)958 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
959 {
960 void *ret = NULL;
961 struct page *page;
962
963 if (unlikely(flags & GFP_SLAB_BUG_MASK))
964 flags = kmalloc_fix_flags(flags);
965
966 flags |= __GFP_COMP;
967 page = alloc_pages(flags, order);
968 if (likely(page)) {
969 ret = page_address(page);
970 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
971 PAGE_SIZE << order);
972 }
973 ret = kasan_kmalloc_large(ret, size, flags);
974 /* As ret might get tagged, call kmemleak hook after KASAN. */
975 kmemleak_alloc(ret, size, 1, flags);
976 return ret;
977 }
978 EXPORT_SYMBOL(kmalloc_order);
979
980 #ifdef CONFIG_TRACING
kmalloc_order_trace(size_t size,gfp_t flags,unsigned int order)981 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
982 {
983 void *ret = kmalloc_order(size, flags, order);
984 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
985 return ret;
986 }
987 EXPORT_SYMBOL(kmalloc_order_trace);
988 #endif
989
990 #ifdef CONFIG_SLAB_FREELIST_RANDOM
991 /* Randomize a generic freelist */
freelist_randomize(struct rnd_state * state,unsigned int * list,unsigned int count)992 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
993 unsigned int count)
994 {
995 unsigned int rand;
996 unsigned int i;
997
998 for (i = 0; i < count; i++)
999 list[i] = i;
1000
1001 /* Fisher-Yates shuffle */
1002 for (i = count - 1; i > 0; i--) {
1003 rand = prandom_u32_state(state);
1004 rand %= (i + 1);
1005 swap(list[i], list[rand]);
1006 }
1007 }
1008
1009 /* Create a random sequence per cache */
cache_random_seq_create(struct kmem_cache * cachep,unsigned int count,gfp_t gfp)1010 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1011 gfp_t gfp)
1012 {
1013 struct rnd_state state;
1014
1015 if (count < 2 || cachep->random_seq)
1016 return 0;
1017
1018 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1019 if (!cachep->random_seq)
1020 return -ENOMEM;
1021
1022 /* Get best entropy at this stage of boot */
1023 prandom_seed_state(&state, get_random_long());
1024
1025 freelist_randomize(&state, cachep->random_seq, count);
1026 return 0;
1027 }
1028
1029 /* Destroy the per-cache random freelist sequence */
cache_random_seq_destroy(struct kmem_cache * cachep)1030 void cache_random_seq_destroy(struct kmem_cache *cachep)
1031 {
1032 kfree(cachep->random_seq);
1033 cachep->random_seq = NULL;
1034 }
1035 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1036
1037 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1038 #ifdef CONFIG_SLAB
1039 #define SLABINFO_RIGHTS (0600)
1040 #else
1041 #define SLABINFO_RIGHTS (0400)
1042 #endif
1043
print_slabinfo_header(struct seq_file * m)1044 static void print_slabinfo_header(struct seq_file *m)
1045 {
1046 /*
1047 * Output format version, so at least we can change it
1048 * without _too_ many complaints.
1049 */
1050 #ifdef CONFIG_DEBUG_SLAB
1051 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1052 #else
1053 seq_puts(m, "slabinfo - version: 2.1\n");
1054 #endif
1055 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1056 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1057 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1058 #ifdef CONFIG_DEBUG_SLAB
1059 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1060 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1061 #endif
1062 trace_android_vh_print_slabinfo_header(m);
1063 seq_putc(m, '\n');
1064 }
1065
slab_start(struct seq_file * m,loff_t * pos)1066 void *slab_start(struct seq_file *m, loff_t *pos)
1067 {
1068 mutex_lock(&slab_mutex);
1069 return seq_list_start(&slab_caches, *pos);
1070 }
1071
slab_next(struct seq_file * m,void * p,loff_t * pos)1072 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1073 {
1074 return seq_list_next(p, &slab_caches, pos);
1075 }
1076
slab_stop(struct seq_file * m,void * p)1077 void slab_stop(struct seq_file *m, void *p)
1078 {
1079 mutex_unlock(&slab_mutex);
1080 }
1081
cache_show(struct kmem_cache * s,struct seq_file * m)1082 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1083 {
1084 struct slabinfo sinfo;
1085
1086 memset(&sinfo, 0, sizeof(sinfo));
1087 get_slabinfo(s, &sinfo);
1088
1089 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1090 s->name, sinfo.active_objs, sinfo.num_objs, s->size,
1091 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1092
1093 seq_printf(m, " : tunables %4u %4u %4u",
1094 sinfo.limit, sinfo.batchcount, sinfo.shared);
1095 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1096 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1097 slabinfo_show_stats(m, s);
1098 trace_android_vh_cache_show(m, &sinfo, s);
1099 seq_putc(m, '\n');
1100 }
1101
slab_show(struct seq_file * m,void * p)1102 static int slab_show(struct seq_file *m, void *p)
1103 {
1104 struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1105
1106 if (p == slab_caches.next)
1107 print_slabinfo_header(m);
1108 cache_show(s, m);
1109 return 0;
1110 }
1111
dump_unreclaimable_slab(void)1112 void dump_unreclaimable_slab(void)
1113 {
1114 struct kmem_cache *s;
1115 struct slabinfo sinfo;
1116
1117 /*
1118 * Here acquiring slab_mutex is risky since we don't prefer to get
1119 * sleep in oom path. But, without mutex hold, it may introduce a
1120 * risk of crash.
1121 * Use mutex_trylock to protect the list traverse, dump nothing
1122 * without acquiring the mutex.
1123 */
1124 if (!mutex_trylock(&slab_mutex)) {
1125 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1126 return;
1127 }
1128
1129 pr_info("Unreclaimable slab info:\n");
1130 pr_info("Name Used Total\n");
1131
1132 list_for_each_entry(s, &slab_caches, list) {
1133 if (s->flags & SLAB_RECLAIM_ACCOUNT)
1134 continue;
1135
1136 get_slabinfo(s, &sinfo);
1137
1138 if (sinfo.num_objs > 0)
1139 pr_info("%-17s %10luKB %10luKB\n", s->name,
1140 (sinfo.active_objs * s->size) / 1024,
1141 (sinfo.num_objs * s->size) / 1024);
1142 }
1143 mutex_unlock(&slab_mutex);
1144 }
1145
1146 #if defined(CONFIG_MEMCG_KMEM)
memcg_slab_show(struct seq_file * m,void * p)1147 int memcg_slab_show(struct seq_file *m, void *p)
1148 {
1149 /*
1150 * Deprecated.
1151 * Please, take a look at tools/cgroup/slabinfo.py .
1152 */
1153 return 0;
1154 }
1155 #endif
1156
1157 /*
1158 * slabinfo_op - iterator that generates /proc/slabinfo
1159 *
1160 * Output layout:
1161 * cache-name
1162 * num-active-objs
1163 * total-objs
1164 * object size
1165 * num-active-slabs
1166 * total-slabs
1167 * num-pages-per-slab
1168 * + further values on SMP and with statistics enabled
1169 */
1170 static const struct seq_operations slabinfo_op = {
1171 .start = slab_start,
1172 .next = slab_next,
1173 .stop = slab_stop,
1174 .show = slab_show,
1175 };
1176
slabinfo_open(struct inode * inode,struct file * file)1177 static int slabinfo_open(struct inode *inode, struct file *file)
1178 {
1179 return seq_open(file, &slabinfo_op);
1180 }
1181
1182 static const struct proc_ops slabinfo_proc_ops = {
1183 .proc_flags = PROC_ENTRY_PERMANENT,
1184 .proc_open = slabinfo_open,
1185 .proc_read = seq_read,
1186 .proc_write = slabinfo_write,
1187 .proc_lseek = seq_lseek,
1188 .proc_release = seq_release,
1189 };
1190
slab_proc_init(void)1191 static int __init slab_proc_init(void)
1192 {
1193 proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1194 return 0;
1195 }
1196 module_init(slab_proc_init);
1197
1198 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1199
__do_krealloc(const void * p,size_t new_size,gfp_t flags)1200 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1201 gfp_t flags)
1202 {
1203 void *ret;
1204 size_t ks;
1205
1206 /* Don't use instrumented ksize to allow precise KASAN poisoning. */
1207 if (likely(!ZERO_OR_NULL_PTR(p))) {
1208 if (!kasan_check_byte(p))
1209 return NULL;
1210 ks = kfence_ksize(p) ?: __ksize(p);
1211 } else
1212 ks = 0;
1213
1214 /* If the object still fits, repoison it precisely. */
1215 if (ks >= new_size) {
1216 p = kasan_krealloc((void *)p, new_size, flags);
1217 return (void *)p;
1218 }
1219
1220 ret = kmalloc_track_caller(new_size, flags);
1221 if (ret && p) {
1222 /* Disable KASAN checks as the object's redzone is accessed. */
1223 kasan_disable_current();
1224 memcpy(ret, kasan_reset_tag(p), ks);
1225 kasan_enable_current();
1226 }
1227
1228 return ret;
1229 }
1230
1231 /**
1232 * krealloc - reallocate memory. The contents will remain unchanged.
1233 * @p: object to reallocate memory for.
1234 * @new_size: how many bytes of memory are required.
1235 * @flags: the type of memory to allocate.
1236 *
1237 * The contents of the object pointed to are preserved up to the
1238 * lesser of the new and old sizes (__GFP_ZERO flag is effectively ignored).
1239 * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size
1240 * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
1241 *
1242 * Return: pointer to the allocated memory or %NULL in case of error
1243 */
krealloc(const void * p,size_t new_size,gfp_t flags)1244 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1245 {
1246 void *ret;
1247
1248 if (unlikely(!new_size)) {
1249 kfree(p);
1250 return ZERO_SIZE_PTR;
1251 }
1252
1253 ret = __do_krealloc(p, new_size, flags);
1254 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1255 kfree(p);
1256
1257 return ret;
1258 }
1259 EXPORT_SYMBOL(krealloc);
1260
1261 /**
1262 * kfree_sensitive - Clear sensitive information in memory before freeing
1263 * @p: object to free memory of
1264 *
1265 * The memory of the object @p points to is zeroed before freed.
1266 * If @p is %NULL, kfree_sensitive() does nothing.
1267 *
1268 * Note: this function zeroes the whole allocated buffer which can be a good
1269 * deal bigger than the requested buffer size passed to kmalloc(). So be
1270 * careful when using this function in performance sensitive code.
1271 */
kfree_sensitive(const void * p)1272 void kfree_sensitive(const void *p)
1273 {
1274 size_t ks;
1275 void *mem = (void *)p;
1276
1277 ks = ksize(mem);
1278 if (ks)
1279 memzero_explicit(mem, ks);
1280 kfree(mem);
1281 }
1282 EXPORT_SYMBOL(kfree_sensitive);
1283
1284 /**
1285 * ksize - get the actual amount of memory allocated for a given object
1286 * @objp: Pointer to the object
1287 *
1288 * kmalloc may internally round up allocations and return more memory
1289 * than requested. ksize() can be used to determine the actual amount of
1290 * memory allocated. The caller may use this additional memory, even though
1291 * a smaller amount of memory was initially specified with the kmalloc call.
1292 * The caller must guarantee that objp points to a valid object previously
1293 * allocated with either kmalloc() or kmem_cache_alloc(). The object
1294 * must not be freed during the duration of the call.
1295 *
1296 * Return: size of the actual memory used by @objp in bytes
1297 */
ksize(const void * objp)1298 size_t ksize(const void *objp)
1299 {
1300 size_t size;
1301
1302 /*
1303 * We need to first check that the pointer to the object is valid, and
1304 * only then unpoison the memory. The report printed from ksize() is
1305 * more useful, then when it's printed later when the behaviour could
1306 * be undefined due to a potential use-after-free or double-free.
1307 *
1308 * We use kasan_check_byte(), which is supported for the hardware
1309 * tag-based KASAN mode, unlike kasan_check_read/write().
1310 *
1311 * If the pointed to memory is invalid, we return 0 to avoid users of
1312 * ksize() writing to and potentially corrupting the memory region.
1313 *
1314 * We want to perform the check before __ksize(), to avoid potentially
1315 * crashing in __ksize() due to accessing invalid metadata.
1316 */
1317 if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
1318 return 0;
1319
1320 size = kfence_ksize(objp) ?: __ksize(objp);
1321 /*
1322 * We assume that ksize callers could use whole allocated area,
1323 * so we need to unpoison this area.
1324 */
1325 kasan_unpoison_range(objp, size);
1326 return size;
1327 }
1328 EXPORT_SYMBOL(ksize);
1329
1330 /* Tracepoints definitions. */
1331 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1332 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1333 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1334 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1335 EXPORT_TRACEPOINT_SYMBOL(kfree);
1336 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1337
should_failslab(struct kmem_cache * s,gfp_t gfpflags)1338 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1339 {
1340 if (__should_failslab(s, gfpflags))
1341 return -ENOMEM;
1342 return 0;
1343 }
1344 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);
1345