1 // SPDX-License-Identifier: GPL-2.0
3 * Slab allocator functions that are independent of the allocator strategy
5 * (C) 2012 Christoph Lameter <cl@linux.com>
7 #include <linux/slab.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>
26 #include <linux/memcontrol.h>
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/kmem.h>
35 enum slab_state slab_state;
36 LIST_HEAD(slab_caches);
37 DEFINE_MUTEX(slab_mutex);
38 struct kmem_cache *kmem_cache;
40 #ifdef CONFIG_HARDENED_USERCOPY
41 bool usercopy_fallback __ro_after_init =
42 IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
43 module_param(usercopy_fallback, bool, 0400);
44 MODULE_PARM_DESC(usercopy_fallback,
45 "WARN instead of reject usercopy whitelist violations");
48 static LIST_HEAD(slab_caches_to_rcu_destroy);
49 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
50 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
51 slab_caches_to_rcu_destroy_workfn);
54 * Set of flags that will prevent slab merging
56 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
57 SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
58 SLAB_FAILSLAB | kasan_never_merge())
60 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
61 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
64 * Merge control. If this is set then no merging of slab caches will occur.
66 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
68 static int __init setup_slab_nomerge(char *str)
74 static int __init setup_slab_merge(char *str)
81 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
82 __setup_param("slub_merge", slub_merge, setup_slab_merge, 0);
85 __setup("slab_nomerge", setup_slab_nomerge);
86 __setup("slab_merge", setup_slab_merge);
89 * Determine the size of a slab object
91 unsigned int kmem_cache_size(struct kmem_cache *s)
93 return s->object_size;
95 EXPORT_SYMBOL(kmem_cache_size);
97 #ifdef CONFIG_DEBUG_VM
98 static int kmem_cache_sanity_check(const char *name, unsigned int size)
100 if (!name || in_interrupt() || size < sizeof(void *) ||
101 size > KMALLOC_MAX_SIZE) {
102 pr_err("kmem_cache_create(%s) integrity check failed\n", name);
106 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
110 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
116 void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
120 for (i = 0; i < nr; i++) {
122 kmem_cache_free(s, p[i]);
128 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
133 for (i = 0; i < nr; i++) {
134 void *x = p[i] = kmem_cache_alloc(s, flags);
136 __kmem_cache_free_bulk(s, i, p);
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.
147 static unsigned int calculate_alignment(slab_flags_t flags,
148 unsigned int align, unsigned int size)
151 * If the user wants hardware cache aligned objects then follow that
152 * suggestion if the object is sufficiently large.
154 * The hardware cache alignment cannot override the specified
155 * alignment though. If that is greater then use it.
157 if (flags & SLAB_HWCACHE_ALIGN) {
160 ralign = cache_line_size();
161 while (size <= ralign / 2)
163 align = max(align, ralign);
166 if (align < ARCH_SLAB_MINALIGN)
167 align = ARCH_SLAB_MINALIGN;
169 return ALIGN(align, sizeof(void *));
173 * Find a mergeable slab cache
175 int slab_unmergeable(struct kmem_cache *s)
177 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
187 * We may have set a slab to be unmergeable during bootstrap.
195 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
196 slab_flags_t flags, const char *name, void (*ctor)(void *))
198 struct kmem_cache *s;
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);
211 if (flags & SLAB_NEVER_MERGE)
214 list_for_each_entry_reverse(s, &slab_caches, list) {
215 if (slab_unmergeable(s))
221 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
224 * Check if alignment is compatible.
225 * Courtesy of Adrian Drzewiecki
227 if ((s->size & ~(align - 1)) != s->size)
230 if (s->size - size >= sizeof(void *))
233 if (IS_ENABLED(CONFIG_SLAB) && align &&
234 (align > s->align || s->align % align))
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)
248 struct kmem_cache *s;
251 if (WARN_ON(useroffset + usersize > object_size))
252 useroffset = usersize = 0;
255 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
260 s->size = s->object_size = object_size;
263 s->useroffset = useroffset;
264 s->usersize = usersize;
266 err = __kmem_cache_create(s, flags);
271 list_add(&s->list, &slab_caches);
278 kmem_cache_free(kmem_cache, s);
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.
289 * @useroffset: Usercopy region offset
290 * @usersize: Usercopy region size
291 * @ctor: A constructor for the objects.
293 * Cannot be called within a interrupt, but can be interrupted.
294 * The @ctor is run when new pages are allocated by the cache.
298 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
299 * to catch references to uninitialised memory.
301 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
302 * for buffer overruns.
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
308 * Return: a pointer to the cache on success, NULL on failure.
311 kmem_cache_create_usercopy(const char *name,
312 unsigned int size, unsigned int align,
314 unsigned int useroffset, unsigned int usersize,
315 void (*ctor)(void *))
317 struct kmem_cache *s = NULL;
318 const char *cache_name;
321 mutex_lock(&slab_mutex);
323 err = kmem_cache_sanity_check(name, size);
328 /* Refuse requests with allocator specific flags */
329 if (flags & ~SLAB_FLAGS_PERMITTED) {
335 * Some allocators will constraint the set of valid flags to a subset
336 * of all flags. We expect them to define CACHE_CREATE_MASK in this
337 * case, and we'll just provide them with a sanitized version of the
340 flags &= CACHE_CREATE_MASK;
342 /* Fail closed on bad usersize of useroffset values. */
343 if (WARN_ON(!usersize && useroffset) ||
344 WARN_ON(size < usersize || size - usersize < useroffset))
345 usersize = useroffset = 0;
348 s = __kmem_cache_alias(name, size, align, flags, ctor);
352 cache_name = kstrdup_const(name, GFP_KERNEL);
358 s = create_cache(cache_name, size,
359 calculate_alignment(flags, align, size),
360 flags, useroffset, usersize, ctor, NULL);
363 kfree_const(cache_name);
367 mutex_unlock(&slab_mutex);
370 if (flags & SLAB_PANIC)
371 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
374 pr_warn("kmem_cache_create(%s) failed with error %d\n",
382 EXPORT_SYMBOL(kmem_cache_create_usercopy);
385 * kmem_cache_create - Create a cache.
386 * @name: A string which is used in /proc/slabinfo to identify this cache.
387 * @size: The size of objects to be created in this cache.
388 * @align: The required alignment for the objects.
390 * @ctor: A constructor for the objects.
392 * Cannot be called within a interrupt, but can be interrupted.
393 * The @ctor is run when new pages are allocated by the cache.
397 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
398 * to catch references to uninitialised memory.
400 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
401 * for buffer overruns.
403 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
404 * cacheline. This can be beneficial if you're counting cycles as closely
407 * Return: a pointer to the cache on success, NULL on failure.
410 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
411 slab_flags_t flags, void (*ctor)(void *))
413 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
416 EXPORT_SYMBOL(kmem_cache_create);
418 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
420 LIST_HEAD(to_destroy);
421 struct kmem_cache *s, *s2;
424 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
425 * @slab_caches_to_rcu_destroy list. The slab pages are freed
426 * through RCU and the associated kmem_cache are dereferenced
427 * while freeing the pages, so the kmem_caches should be freed only
428 * after the pending RCU operations are finished. As rcu_barrier()
429 * is a pretty slow operation, we batch all pending destructions
432 mutex_lock(&slab_mutex);
433 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
434 mutex_unlock(&slab_mutex);
436 if (list_empty(&to_destroy))
441 list_for_each_entry_safe(s, s2, &to_destroy, list) {
442 kfence_shutdown_cache(s);
443 #ifdef SLAB_SUPPORTS_SYSFS
444 sysfs_slab_release(s);
446 slab_kmem_cache_release(s);
451 static int shutdown_cache(struct kmem_cache *s)
453 /* free asan quarantined objects */
454 kasan_cache_shutdown(s);
456 if (__kmem_cache_shutdown(s) != 0)
461 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
462 #ifdef SLAB_SUPPORTS_SYSFS
463 sysfs_slab_unlink(s);
465 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
466 schedule_work(&slab_caches_to_rcu_destroy_work);
468 kfence_shutdown_cache(s);
469 #ifdef SLAB_SUPPORTS_SYSFS
470 sysfs_slab_unlink(s);
471 sysfs_slab_release(s);
473 slab_kmem_cache_release(s);
480 void slab_kmem_cache_release(struct kmem_cache *s)
482 __kmem_cache_release(s);
483 kfree_const(s->name);
484 kmem_cache_free(kmem_cache, s);
487 void kmem_cache_destroy(struct kmem_cache *s)
494 mutex_lock(&slab_mutex);
500 err = shutdown_cache(s);
502 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
507 mutex_unlock(&slab_mutex);
509 EXPORT_SYMBOL(kmem_cache_destroy);
512 * kmem_cache_shrink - Shrink a cache.
513 * @cachep: The cache to shrink.
515 * Releases as many slabs as possible for a cache.
516 * To help debugging, a zero exit status indicates all slabs were released.
518 * Return: %0 if all slabs were released, non-zero otherwise
520 int kmem_cache_shrink(struct kmem_cache *cachep)
525 kasan_cache_shrink(cachep);
526 ret = __kmem_cache_shrink(cachep);
530 EXPORT_SYMBOL(kmem_cache_shrink);
532 bool slab_is_available(void)
534 return slab_state >= UP;
539 * kmem_valid_obj - does the pointer reference a valid slab object?
540 * @object: pointer to query.
542 * Return: %true if the pointer is to a not-yet-freed object from
543 * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer
544 * is to an already-freed object, and %false otherwise.
546 bool kmem_valid_obj(void *object)
550 /* Some arches consider ZERO_SIZE_PTR to be a valid address. */
551 if (object < (void *)PAGE_SIZE || !virt_addr_valid(object))
553 page = virt_to_head_page(object);
554 return PageSlab(page);
556 EXPORT_SYMBOL_GPL(kmem_valid_obj);
559 * kmem_dump_obj - Print available slab provenance information
560 * @object: slab object for which to find provenance information.
562 * This function uses pr_cont(), so that the caller is expected to have
563 * printed out whatever preamble is appropriate. The provenance information
564 * depends on the type of object and on how much debugging is enabled.
565 * For a slab-cache object, the fact that it is a slab object is printed,
566 * and, if available, the slab name, return address, and stack trace from
567 * the allocation of that object.
569 * This function will splat if passed a pointer to a non-slab object.
570 * If you are not sure what type of object you have, you should instead
571 * use mem_dump_obj().
573 void kmem_dump_obj(void *object)
575 char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc";
578 unsigned long ptroffset;
579 struct kmem_obj_info kp = { };
581 if (WARN_ON_ONCE(!virt_addr_valid(object)))
583 page = virt_to_head_page(object);
584 if (WARN_ON_ONCE(!PageSlab(page))) {
585 pr_cont(" non-slab memory.\n");
588 kmem_obj_info(&kp, object, page);
589 if (kp.kp_slab_cache)
590 pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name);
592 pr_cont(" slab%s", cp);
594 pr_cont(" start %px", kp.kp_objp);
595 if (kp.kp_data_offset)
596 pr_cont(" data offset %lu", kp.kp_data_offset);
598 ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset;
599 pr_cont(" pointer offset %lu", ptroffset);
601 if (kp.kp_slab_cache && kp.kp_slab_cache->usersize)
602 pr_cont(" size %u", kp.kp_slab_cache->usersize);
604 pr_cont(" allocated at %pS\n", kp.kp_ret);
607 for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) {
610 pr_info(" %pS\n", kp.kp_stack[i]);
613 EXPORT_SYMBOL_GPL(kmem_dump_obj);
617 /* Create a cache during boot when no slab services are available yet */
618 void __init create_boot_cache(struct kmem_cache *s, const char *name,
619 unsigned int size, slab_flags_t flags,
620 unsigned int useroffset, unsigned int usersize)
623 unsigned int align = ARCH_KMALLOC_MINALIGN;
626 s->size = s->object_size = size;
629 * For power of two sizes, guarantee natural alignment for kmalloc
630 * caches, regardless of SL*B debugging options.
632 if (is_power_of_2(size))
633 align = max(align, size);
634 s->align = calculate_alignment(flags, align, size);
636 s->useroffset = useroffset;
637 s->usersize = usersize;
639 err = __kmem_cache_create(s, flags);
642 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
645 s->refcount = -1; /* Exempt from merging for now */
648 struct kmem_cache *__init create_kmalloc_cache(const char *name,
649 unsigned int size, slab_flags_t flags,
650 unsigned int useroffset, unsigned int usersize)
652 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
655 panic("Out of memory when creating slab %s\n", name);
657 create_boot_cache(s, name, size, flags, useroffset, usersize);
658 kasan_cache_create_kmalloc(s);
659 list_add(&s->list, &slab_caches);
665 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
666 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
667 EXPORT_SYMBOL(kmalloc_caches);
670 * Conversion table for small slabs sizes / 8 to the index in the
671 * kmalloc array. This is necessary for slabs < 192 since we have non power
672 * of two cache sizes there. The size of larger slabs can be determined using
675 static u8 size_index[24] __ro_after_init = {
702 static inline unsigned int size_index_elem(unsigned int bytes)
704 return (bytes - 1) / 8;
708 * Find the kmem_cache structure that serves a given size of
711 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
717 return ZERO_SIZE_PTR;
719 index = size_index[size_index_elem(size)];
721 if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
723 index = fls(size - 1);
726 return kmalloc_caches[kmalloc_type(flags)][index];
729 #ifdef CONFIG_ZONE_DMA
730 #define INIT_KMALLOC_INFO(__size, __short_size) \
732 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
733 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
734 .name[KMALLOC_DMA] = "dma-kmalloc-" #__short_size, \
738 #define INIT_KMALLOC_INFO(__size, __short_size) \
740 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
741 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
747 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
748 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
751 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
752 INIT_KMALLOC_INFO(0, 0),
753 INIT_KMALLOC_INFO(96, 96),
754 INIT_KMALLOC_INFO(192, 192),
755 INIT_KMALLOC_INFO(8, 8),
756 INIT_KMALLOC_INFO(16, 16),
757 INIT_KMALLOC_INFO(32, 32),
758 INIT_KMALLOC_INFO(64, 64),
759 INIT_KMALLOC_INFO(128, 128),
760 INIT_KMALLOC_INFO(256, 256),
761 INIT_KMALLOC_INFO(512, 512),
762 INIT_KMALLOC_INFO(1024, 1k),
763 INIT_KMALLOC_INFO(2048, 2k),
764 INIT_KMALLOC_INFO(4096, 4k),
765 INIT_KMALLOC_INFO(8192, 8k),
766 INIT_KMALLOC_INFO(16384, 16k),
767 INIT_KMALLOC_INFO(32768, 32k),
768 INIT_KMALLOC_INFO(65536, 64k),
769 INIT_KMALLOC_INFO(131072, 128k),
770 INIT_KMALLOC_INFO(262144, 256k),
771 INIT_KMALLOC_INFO(524288, 512k),
772 INIT_KMALLOC_INFO(1048576, 1M),
773 INIT_KMALLOC_INFO(2097152, 2M),
774 INIT_KMALLOC_INFO(4194304, 4M),
775 INIT_KMALLOC_INFO(8388608, 8M),
776 INIT_KMALLOC_INFO(16777216, 16M),
777 INIT_KMALLOC_INFO(33554432, 32M),
778 INIT_KMALLOC_INFO(67108864, 64M)
782 * Patch up the size_index table if we have strange large alignment
783 * requirements for the kmalloc array. This is only the case for
784 * MIPS it seems. The standard arches will not generate any code here.
786 * Largest permitted alignment is 256 bytes due to the way we
787 * handle the index determination for the smaller caches.
789 * Make sure that nothing crazy happens if someone starts tinkering
790 * around with ARCH_KMALLOC_MINALIGN
792 void __init setup_kmalloc_cache_index_table(void)
796 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
797 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
799 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
800 unsigned int elem = size_index_elem(i);
802 if (elem >= ARRAY_SIZE(size_index))
804 size_index[elem] = KMALLOC_SHIFT_LOW;
807 if (KMALLOC_MIN_SIZE >= 64) {
809 * The 96 byte size cache is not used if the alignment
812 for (i = 64 + 8; i <= 96; i += 8)
813 size_index[size_index_elem(i)] = 7;
817 if (KMALLOC_MIN_SIZE >= 128) {
819 * The 192 byte sized cache is not used if the alignment
820 * is 128 byte. Redirect kmalloc to use the 256 byte cache
823 for (i = 128 + 8; i <= 192; i += 8)
824 size_index[size_index_elem(i)] = 8;
829 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
831 if (type == KMALLOC_RECLAIM)
832 flags |= SLAB_RECLAIM_ACCOUNT;
834 kmalloc_caches[type][idx] = create_kmalloc_cache(
835 kmalloc_info[idx].name[type],
836 kmalloc_info[idx].size, flags, 0,
837 kmalloc_info[idx].size);
841 * Create the kmalloc array. Some of the regular kmalloc arrays
842 * may already have been created because they were needed to
843 * enable allocations for slab creation.
845 void __init create_kmalloc_caches(slab_flags_t flags)
848 enum kmalloc_cache_type type;
850 for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
851 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
852 if (!kmalloc_caches[type][i])
853 new_kmalloc_cache(i, type, flags);
856 * Caches that are not of the two-to-the-power-of size.
857 * These have to be created immediately after the
858 * earlier power of two caches
860 if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
861 !kmalloc_caches[type][1])
862 new_kmalloc_cache(1, type, flags);
863 if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
864 !kmalloc_caches[type][2])
865 new_kmalloc_cache(2, type, flags);
869 /* Kmalloc array is now usable */
872 #ifdef CONFIG_ZONE_DMA
873 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
874 struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
877 kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
878 kmalloc_info[i].name[KMALLOC_DMA],
879 kmalloc_info[i].size,
880 SLAB_CACHE_DMA | flags, 0,
881 kmalloc_info[i].size);
886 #endif /* !CONFIG_SLOB */
888 gfp_t kmalloc_fix_flags(gfp_t flags)
890 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
892 flags &= ~GFP_SLAB_BUG_MASK;
893 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
894 invalid_mask, &invalid_mask, flags, &flags);
901 * To avoid unnecessary overhead, we pass through large allocation requests
902 * directly to the page allocator. We use __GFP_COMP, because we will need to
903 * know the allocation order to free the pages properly in kfree.
905 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
910 if (unlikely(flags & GFP_SLAB_BUG_MASK))
911 flags = kmalloc_fix_flags(flags);
914 page = alloc_pages(flags, order);
916 ret = page_address(page);
917 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
920 ret = kasan_kmalloc_large(ret, size, flags);
921 /* As ret might get tagged, call kmemleak hook after KASAN. */
922 kmemleak_alloc(ret, size, 1, flags);
925 EXPORT_SYMBOL(kmalloc_order);
927 #ifdef CONFIG_TRACING
928 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
930 void *ret = kmalloc_order(size, flags, order);
931 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
934 EXPORT_SYMBOL(kmalloc_order_trace);
937 #ifdef CONFIG_SLAB_FREELIST_RANDOM
938 /* Randomize a generic freelist */
939 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
945 for (i = 0; i < count; i++)
948 /* Fisher-Yates shuffle */
949 for (i = count - 1; i > 0; i--) {
950 rand = prandom_u32_state(state);
952 swap(list[i], list[rand]);
956 /* Create a random sequence per cache */
957 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
960 struct rnd_state state;
962 if (count < 2 || cachep->random_seq)
965 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
966 if (!cachep->random_seq)
969 /* Get best entropy at this stage of boot */
970 prandom_seed_state(&state, get_random_long());
972 freelist_randomize(&state, cachep->random_seq, count);
976 /* Destroy the per-cache random freelist sequence */
977 void cache_random_seq_destroy(struct kmem_cache *cachep)
979 kfree(cachep->random_seq);
980 cachep->random_seq = NULL;
982 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
984 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
986 #define SLABINFO_RIGHTS (0600)
988 #define SLABINFO_RIGHTS (0400)
991 static void print_slabinfo_header(struct seq_file *m)
994 * Output format version, so at least we can change it
995 * without _too_ many complaints.
997 #ifdef CONFIG_DEBUG_SLAB
998 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1000 seq_puts(m, "slabinfo - version: 2.1\n");
1002 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1003 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1004 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1005 #ifdef CONFIG_DEBUG_SLAB
1006 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1007 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1012 void *slab_start(struct seq_file *m, loff_t *pos)
1014 mutex_lock(&slab_mutex);
1015 return seq_list_start(&slab_caches, *pos);
1018 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1020 return seq_list_next(p, &slab_caches, pos);
1023 void slab_stop(struct seq_file *m, void *p)
1025 mutex_unlock(&slab_mutex);
1028 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1030 struct slabinfo sinfo;
1032 memset(&sinfo, 0, sizeof(sinfo));
1033 get_slabinfo(s, &sinfo);
1035 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1036 s->name, sinfo.active_objs, sinfo.num_objs, s->size,
1037 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1039 seq_printf(m, " : tunables %4u %4u %4u",
1040 sinfo.limit, sinfo.batchcount, sinfo.shared);
1041 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1042 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1043 slabinfo_show_stats(m, s);
1047 static int slab_show(struct seq_file *m, void *p)
1049 struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1051 if (p == slab_caches.next)
1052 print_slabinfo_header(m);
1057 void dump_unreclaimable_slab(void)
1059 struct kmem_cache *s;
1060 struct slabinfo sinfo;
1063 * Here acquiring slab_mutex is risky since we don't prefer to get
1064 * sleep in oom path. But, without mutex hold, it may introduce a
1066 * Use mutex_trylock to protect the list traverse, dump nothing
1067 * without acquiring the mutex.
1069 if (!mutex_trylock(&slab_mutex)) {
1070 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1074 pr_info("Unreclaimable slab info:\n");
1075 pr_info("Name Used Total\n");
1077 list_for_each_entry(s, &slab_caches, list) {
1078 if (s->flags & SLAB_RECLAIM_ACCOUNT)
1081 get_slabinfo(s, &sinfo);
1083 if (sinfo.num_objs > 0)
1084 pr_info("%-17s %10luKB %10luKB\n", s->name,
1085 (sinfo.active_objs * s->size) / 1024,
1086 (sinfo.num_objs * s->size) / 1024);
1088 mutex_unlock(&slab_mutex);
1091 #if defined(CONFIG_MEMCG_KMEM)
1092 int memcg_slab_show(struct seq_file *m, void *p)
1096 * Please, take a look at tools/cgroup/slabinfo.py .
1103 * slabinfo_op - iterator that generates /proc/slabinfo
1112 * num-pages-per-slab
1113 * + further values on SMP and with statistics enabled
1115 static const struct seq_operations slabinfo_op = {
1116 .start = slab_start,
1122 static int slabinfo_open(struct inode *inode, struct file *file)
1124 return seq_open(file, &slabinfo_op);
1127 static const struct proc_ops slabinfo_proc_ops = {
1128 .proc_flags = PROC_ENTRY_PERMANENT,
1129 .proc_open = slabinfo_open,
1130 .proc_read = seq_read,
1131 .proc_write = slabinfo_write,
1132 .proc_lseek = seq_lseek,
1133 .proc_release = seq_release,
1136 static int __init slab_proc_init(void)
1138 proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1141 module_init(slab_proc_init);
1143 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1145 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1151 /* Don't use instrumented ksize to allow precise KASAN poisoning. */
1152 if (likely(!ZERO_OR_NULL_PTR(p))) {
1153 if (!kasan_check_byte(p))
1155 ks = kfence_ksize(p) ?: __ksize(p);
1159 /* If the object still fits, repoison it precisely. */
1160 if (ks >= new_size) {
1161 p = kasan_krealloc((void *)p, new_size, flags);
1165 ret = kmalloc_track_caller(new_size, flags);
1167 /* Disable KASAN checks as the object's redzone is accessed. */
1168 kasan_disable_current();
1169 memcpy(ret, kasan_reset_tag(p), ks);
1170 kasan_enable_current();
1177 * krealloc - reallocate memory. The contents will remain unchanged.
1178 * @p: object to reallocate memory for.
1179 * @new_size: how many bytes of memory are required.
1180 * @flags: the type of memory to allocate.
1182 * The contents of the object pointed to are preserved up to the
1183 * lesser of the new and old sizes (__GFP_ZERO flag is effectively ignored).
1184 * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size
1185 * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
1187 * Return: pointer to the allocated memory or %NULL in case of error
1189 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1193 if (unlikely(!new_size)) {
1195 return ZERO_SIZE_PTR;
1198 ret = __do_krealloc(p, new_size, flags);
1199 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1204 EXPORT_SYMBOL(krealloc);
1207 * kfree_sensitive - Clear sensitive information in memory before freeing
1208 * @p: object to free memory of
1210 * The memory of the object @p points to is zeroed before freed.
1211 * If @p is %NULL, kfree_sensitive() does nothing.
1213 * Note: this function zeroes the whole allocated buffer which can be a good
1214 * deal bigger than the requested buffer size passed to kmalloc(). So be
1215 * careful when using this function in performance sensitive code.
1217 void kfree_sensitive(const void *p)
1220 void *mem = (void *)p;
1224 memzero_explicit(mem, ks);
1227 EXPORT_SYMBOL(kfree_sensitive);
1230 * ksize - get the actual amount of memory allocated for a given object
1231 * @objp: Pointer to the object
1233 * kmalloc may internally round up allocations and return more memory
1234 * than requested. ksize() can be used to determine the actual amount of
1235 * memory allocated. The caller may use this additional memory, even though
1236 * a smaller amount of memory was initially specified with the kmalloc call.
1237 * The caller must guarantee that objp points to a valid object previously
1238 * allocated with either kmalloc() or kmem_cache_alloc(). The object
1239 * must not be freed during the duration of the call.
1241 * Return: size of the actual memory used by @objp in bytes
1243 size_t ksize(const void *objp)
1248 * We need to first check that the pointer to the object is valid, and
1249 * only then unpoison the memory. The report printed from ksize() is
1250 * more useful, then when it's printed later when the behaviour could
1251 * be undefined due to a potential use-after-free or double-free.
1253 * We use kasan_check_byte(), which is supported for the hardware
1254 * tag-based KASAN mode, unlike kasan_check_read/write().
1256 * If the pointed to memory is invalid, we return 0 to avoid users of
1257 * ksize() writing to and potentially corrupting the memory region.
1259 * We want to perform the check before __ksize(), to avoid potentially
1260 * crashing in __ksize() due to accessing invalid metadata.
1262 if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
1265 size = kfence_ksize(objp) ?: __ksize(objp);
1267 * We assume that ksize callers could use whole allocated area,
1268 * so we need to unpoison this area.
1270 kasan_unpoison_range(objp, size);
1273 EXPORT_SYMBOL(ksize);
1275 /* Tracepoints definitions. */
1276 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1277 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1278 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1279 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1280 EXPORT_TRACEPOINT_SYMBOL(kfree);
1281 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1283 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1285 if (__should_failslab(s, gfpflags))
1289 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);