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/module.h>
16 #include <linux/cpu.h>
17 #include <linux/uaccess.h>
18 #include <linux/seq_file.h>
19 #include <linux/proc_fs.h>
20 #include <linux/debugfs.h>
21 #include <asm/cacheflush.h>
22 #include <asm/tlbflush.h>
24 #include <linux/memcontrol.h>
26 #define CREATE_TRACE_POINTS
27 #include <trace/events/kmem.h>
33 enum slab_state slab_state;
34 LIST_HEAD(slab_caches);
35 DEFINE_MUTEX(slab_mutex);
36 struct kmem_cache *kmem_cache;
38 #ifdef CONFIG_HARDENED_USERCOPY
39 bool usercopy_fallback __ro_after_init =
40 IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
41 module_param(usercopy_fallback, bool, 0400);
42 MODULE_PARM_DESC(usercopy_fallback,
43 "WARN instead of reject usercopy whitelist violations");
46 static LIST_HEAD(slab_caches_to_rcu_destroy);
47 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
48 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
49 slab_caches_to_rcu_destroy_workfn);
52 * Set of flags that will prevent slab merging
54 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
55 SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
56 SLAB_FAILSLAB | SLAB_KASAN)
58 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
59 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
62 * Merge control. If this is set then no merging of slab caches will occur.
64 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
66 static int __init setup_slab_nomerge(char *str)
73 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
76 __setup("slab_nomerge", setup_slab_nomerge);
79 * Determine the size of a slab object
81 unsigned int kmem_cache_size(struct kmem_cache *s)
83 return s->object_size;
85 EXPORT_SYMBOL(kmem_cache_size);
87 #ifdef CONFIG_DEBUG_VM
88 static int kmem_cache_sanity_check(const char *name, unsigned int size)
90 if (!name || in_interrupt() || size < sizeof(void *) ||
91 size > KMALLOC_MAX_SIZE) {
92 pr_err("kmem_cache_create(%s) integrity check failed\n", name);
96 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
100 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
106 void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
110 for (i = 0; i < nr; i++) {
112 kmem_cache_free(s, p[i]);
118 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
123 for (i = 0; i < nr; i++) {
124 void *x = p[i] = kmem_cache_alloc(s, flags);
126 __kmem_cache_free_bulk(s, i, p);
133 #ifdef CONFIG_MEMCG_KMEM
134 static void memcg_kmem_cache_create_func(struct work_struct *work)
136 struct kmem_cache *cachep = container_of(work, struct kmem_cache,
138 memcg_create_kmem_cache(cachep);
141 void slab_init_memcg_params(struct kmem_cache *s)
143 s->memcg_params.root_cache = NULL;
144 s->memcg_params.memcg_cache = NULL;
145 INIT_WORK(&s->memcg_params.work, memcg_kmem_cache_create_func);
148 static void init_memcg_params(struct kmem_cache *s,
149 struct kmem_cache *root_cache)
152 s->memcg_params.root_cache = root_cache;
154 slab_init_memcg_params(s);
157 static inline void init_memcg_params(struct kmem_cache *s,
158 struct kmem_cache *root_cache)
161 #endif /* CONFIG_MEMCG_KMEM */
164 * Figure out what the alignment of the objects will be given a set of
165 * flags, a user specified alignment and the size of the objects.
167 static unsigned int calculate_alignment(slab_flags_t flags,
168 unsigned int align, unsigned int size)
171 * If the user wants hardware cache aligned objects then follow that
172 * suggestion if the object is sufficiently large.
174 * The hardware cache alignment cannot override the specified
175 * alignment though. If that is greater then use it.
177 if (flags & SLAB_HWCACHE_ALIGN) {
180 ralign = cache_line_size();
181 while (size <= ralign / 2)
183 align = max(align, ralign);
186 if (align < ARCH_SLAB_MINALIGN)
187 align = ARCH_SLAB_MINALIGN;
189 return ALIGN(align, sizeof(void *));
193 * Find a mergeable slab cache
195 int slab_unmergeable(struct kmem_cache *s)
197 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
200 if (!is_root_cache(s))
210 * We may have set a slab to be unmergeable during bootstrap.
218 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
219 slab_flags_t flags, const char *name, void (*ctor)(void *))
221 struct kmem_cache *s;
229 size = ALIGN(size, sizeof(void *));
230 align = calculate_alignment(flags, align, size);
231 size = ALIGN(size, align);
232 flags = kmem_cache_flags(size, flags, name, NULL);
234 if (flags & SLAB_NEVER_MERGE)
237 list_for_each_entry_reverse(s, &slab_caches, list) {
238 if (slab_unmergeable(s))
244 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
247 * Check if alignment is compatible.
248 * Courtesy of Adrian Drzewiecki
250 if ((s->size & ~(align - 1)) != s->size)
253 if (s->size - size >= sizeof(void *))
256 if (IS_ENABLED(CONFIG_SLAB) && align &&
257 (align > s->align || s->align % align))
265 static struct kmem_cache *create_cache(const char *name,
266 unsigned int object_size, unsigned int align,
267 slab_flags_t flags, unsigned int useroffset,
268 unsigned int usersize, void (*ctor)(void *),
269 struct kmem_cache *root_cache)
271 struct kmem_cache *s;
274 if (WARN_ON(useroffset + usersize > object_size))
275 useroffset = usersize = 0;
278 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
283 s->size = s->object_size = object_size;
286 s->useroffset = useroffset;
287 s->usersize = usersize;
289 init_memcg_params(s, root_cache);
290 err = __kmem_cache_create(s, flags);
295 list_add(&s->list, &slab_caches);
302 kmem_cache_free(kmem_cache, s);
307 * kmem_cache_create_usercopy - Create a cache with a region suitable
308 * for copying to userspace
309 * @name: A string which is used in /proc/slabinfo to identify this cache.
310 * @size: The size of objects to be created in this cache.
311 * @align: The required alignment for the objects.
313 * @useroffset: Usercopy region offset
314 * @usersize: Usercopy region size
315 * @ctor: A constructor for the objects.
317 * Cannot be called within a interrupt, but can be interrupted.
318 * The @ctor is run when new pages are allocated by the cache.
322 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
323 * to catch references to uninitialised memory.
325 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
326 * for buffer overruns.
328 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
329 * cacheline. This can be beneficial if you're counting cycles as closely
332 * Return: a pointer to the cache on success, NULL on failure.
335 kmem_cache_create_usercopy(const char *name,
336 unsigned int size, unsigned int align,
338 unsigned int useroffset, unsigned int usersize,
339 void (*ctor)(void *))
341 struct kmem_cache *s = NULL;
342 const char *cache_name;
347 memcg_get_cache_ids();
349 mutex_lock(&slab_mutex);
351 err = kmem_cache_sanity_check(name, size);
356 /* Refuse requests with allocator specific flags */
357 if (flags & ~SLAB_FLAGS_PERMITTED) {
363 * Some allocators will constraint the set of valid flags to a subset
364 * of all flags. We expect them to define CACHE_CREATE_MASK in this
365 * case, and we'll just provide them with a sanitized version of the
368 flags &= CACHE_CREATE_MASK;
370 /* Fail closed on bad usersize of useroffset values. */
371 if (WARN_ON(!usersize && useroffset) ||
372 WARN_ON(size < usersize || size - usersize < useroffset))
373 usersize = useroffset = 0;
376 s = __kmem_cache_alias(name, size, align, flags, ctor);
380 cache_name = kstrdup_const(name, GFP_KERNEL);
386 s = create_cache(cache_name, size,
387 calculate_alignment(flags, align, size),
388 flags, useroffset, usersize, ctor, NULL);
391 kfree_const(cache_name);
395 mutex_unlock(&slab_mutex);
397 memcg_put_cache_ids();
402 if (flags & SLAB_PANIC)
403 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
406 pr_warn("kmem_cache_create(%s) failed with error %d\n",
414 EXPORT_SYMBOL(kmem_cache_create_usercopy);
417 * kmem_cache_create - Create a cache.
418 * @name: A string which is used in /proc/slabinfo to identify this cache.
419 * @size: The size of objects to be created in this cache.
420 * @align: The required alignment for the objects.
422 * @ctor: A constructor for the objects.
424 * Cannot be called within a interrupt, but can be interrupted.
425 * The @ctor is run when new pages are allocated by the cache.
429 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
430 * to catch references to uninitialised memory.
432 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
433 * for buffer overruns.
435 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
436 * cacheline. This can be beneficial if you're counting cycles as closely
439 * Return: a pointer to the cache on success, NULL on failure.
442 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
443 slab_flags_t flags, void (*ctor)(void *))
445 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
448 EXPORT_SYMBOL(kmem_cache_create);
450 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
452 LIST_HEAD(to_destroy);
453 struct kmem_cache *s, *s2;
456 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
457 * @slab_caches_to_rcu_destroy list. The slab pages are freed
458 * through RCU and and the associated kmem_cache are dereferenced
459 * while freeing the pages, so the kmem_caches should be freed only
460 * after the pending RCU operations are finished. As rcu_barrier()
461 * is a pretty slow operation, we batch all pending destructions
464 mutex_lock(&slab_mutex);
465 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
466 mutex_unlock(&slab_mutex);
468 if (list_empty(&to_destroy))
473 list_for_each_entry_safe(s, s2, &to_destroy, list) {
474 #ifdef SLAB_SUPPORTS_SYSFS
475 sysfs_slab_release(s);
477 slab_kmem_cache_release(s);
482 static int shutdown_cache(struct kmem_cache *s)
484 /* free asan quarantined objects */
485 kasan_cache_shutdown(s);
487 if (__kmem_cache_shutdown(s) != 0)
492 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
493 #ifdef SLAB_SUPPORTS_SYSFS
494 sysfs_slab_unlink(s);
496 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
497 schedule_work(&slab_caches_to_rcu_destroy_work);
499 #ifdef SLAB_SUPPORTS_SYSFS
500 sysfs_slab_unlink(s);
501 sysfs_slab_release(s);
503 slab_kmem_cache_release(s);
510 #ifdef CONFIG_MEMCG_KMEM
512 * memcg_create_kmem_cache - Create a cache for non-root memory cgroups.
513 * @root_cache: The parent of the new cache.
515 * This function attempts to create a kmem cache that will serve allocation
516 * requests going all non-root memory cgroups to @root_cache. The new cache
517 * inherits properties from its parent.
519 void memcg_create_kmem_cache(struct kmem_cache *root_cache)
521 struct kmem_cache *s = NULL;
527 mutex_lock(&slab_mutex);
529 if (root_cache->memcg_params.memcg_cache)
532 cache_name = kasprintf(GFP_KERNEL, "%s-memcg", root_cache->name);
536 s = create_cache(cache_name, root_cache->object_size,
538 root_cache->flags & CACHE_CREATE_MASK,
539 root_cache->useroffset, root_cache->usersize,
540 root_cache->ctor, root_cache);
542 * If we could not create a memcg cache, do not complain, because
543 * that's not critical at all as we can always proceed with the root
552 * Since readers won't lock (see memcg_slab_pre_alloc_hook()), we need a
553 * barrier here to ensure nobody will see the kmem_cache partially
557 root_cache->memcg_params.memcg_cache = s;
560 mutex_unlock(&slab_mutex);
566 static int shutdown_memcg_caches(struct kmem_cache *s)
568 BUG_ON(!is_root_cache(s));
570 if (s->memcg_params.memcg_cache)
571 WARN_ON(shutdown_cache(s->memcg_params.memcg_cache));
576 static void cancel_memcg_cache_creation(struct kmem_cache *s)
578 cancel_work_sync(&s->memcg_params.work);
581 static inline int shutdown_memcg_caches(struct kmem_cache *s)
586 static inline void cancel_memcg_cache_creation(struct kmem_cache *s)
589 #endif /* CONFIG_MEMCG_KMEM */
591 void slab_kmem_cache_release(struct kmem_cache *s)
593 __kmem_cache_release(s);
594 kfree_const(s->name);
595 kmem_cache_free(kmem_cache, s);
598 void kmem_cache_destroy(struct kmem_cache *s)
605 cancel_memcg_cache_creation(s);
610 mutex_lock(&slab_mutex);
616 err = shutdown_memcg_caches(s);
618 err = shutdown_cache(s);
621 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
626 mutex_unlock(&slab_mutex);
631 EXPORT_SYMBOL(kmem_cache_destroy);
634 * kmem_cache_shrink - Shrink a cache.
635 * @cachep: The cache to shrink.
637 * Releases as many slabs as possible for a cache.
638 * To help debugging, a zero exit status indicates all slabs were released.
640 * Return: %0 if all slabs were released, non-zero otherwise
642 int kmem_cache_shrink(struct kmem_cache *cachep)
648 kasan_cache_shrink(cachep);
649 ret = __kmem_cache_shrink(cachep);
654 EXPORT_SYMBOL(kmem_cache_shrink);
657 * kmem_cache_shrink_all - shrink root and memcg caches
658 * @s: The cache pointer
660 void kmem_cache_shrink_all(struct kmem_cache *s)
662 struct kmem_cache *c;
664 if (!IS_ENABLED(CONFIG_MEMCG_KMEM) || !is_root_cache(s)) {
665 kmem_cache_shrink(s);
671 kasan_cache_shrink(s);
672 __kmem_cache_shrink(s);
676 kasan_cache_shrink(c);
677 __kmem_cache_shrink(c);
683 bool slab_is_available(void)
685 return slab_state >= UP;
689 /* Create a cache during boot when no slab services are available yet */
690 void __init create_boot_cache(struct kmem_cache *s, const char *name,
691 unsigned int size, slab_flags_t flags,
692 unsigned int useroffset, unsigned int usersize)
695 unsigned int align = ARCH_KMALLOC_MINALIGN;
698 s->size = s->object_size = size;
701 * For power of two sizes, guarantee natural alignment for kmalloc
702 * caches, regardless of SL*B debugging options.
704 if (is_power_of_2(size))
705 align = max(align, size);
706 s->align = calculate_alignment(flags, align, size);
708 s->useroffset = useroffset;
709 s->usersize = usersize;
711 slab_init_memcg_params(s);
713 err = __kmem_cache_create(s, flags);
716 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
719 s->refcount = -1; /* Exempt from merging for now */
722 struct kmem_cache *__init create_kmalloc_cache(const char *name,
723 unsigned int size, slab_flags_t flags,
724 unsigned int useroffset, unsigned int usersize)
726 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
729 panic("Out of memory when creating slab %s\n", name);
731 create_boot_cache(s, name, size, flags, useroffset, usersize);
732 list_add(&s->list, &slab_caches);
738 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
739 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
740 EXPORT_SYMBOL(kmalloc_caches);
743 * Conversion table for small slabs sizes / 8 to the index in the
744 * kmalloc array. This is necessary for slabs < 192 since we have non power
745 * of two cache sizes there. The size of larger slabs can be determined using
748 static u8 size_index[24] __ro_after_init = {
775 static inline unsigned int size_index_elem(unsigned int bytes)
777 return (bytes - 1) / 8;
781 * Find the kmem_cache structure that serves a given size of
784 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
790 return ZERO_SIZE_PTR;
792 index = size_index[size_index_elem(size)];
794 if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
796 index = fls(size - 1);
799 return kmalloc_caches[kmalloc_type(flags)][index];
802 #ifdef CONFIG_ZONE_DMA
803 #define INIT_KMALLOC_INFO(__size, __short_size) \
805 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
806 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
807 .name[KMALLOC_DMA] = "dma-kmalloc-" #__short_size, \
811 #define INIT_KMALLOC_INFO(__size, __short_size) \
813 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
814 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
820 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
821 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
824 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
825 INIT_KMALLOC_INFO(0, 0),
826 INIT_KMALLOC_INFO(96, 96),
827 INIT_KMALLOC_INFO(192, 192),
828 INIT_KMALLOC_INFO(8, 8),
829 INIT_KMALLOC_INFO(16, 16),
830 INIT_KMALLOC_INFO(32, 32),
831 INIT_KMALLOC_INFO(64, 64),
832 INIT_KMALLOC_INFO(128, 128),
833 INIT_KMALLOC_INFO(256, 256),
834 INIT_KMALLOC_INFO(512, 512),
835 INIT_KMALLOC_INFO(1024, 1k),
836 INIT_KMALLOC_INFO(2048, 2k),
837 INIT_KMALLOC_INFO(4096, 4k),
838 INIT_KMALLOC_INFO(8192, 8k),
839 INIT_KMALLOC_INFO(16384, 16k),
840 INIT_KMALLOC_INFO(32768, 32k),
841 INIT_KMALLOC_INFO(65536, 64k),
842 INIT_KMALLOC_INFO(131072, 128k),
843 INIT_KMALLOC_INFO(262144, 256k),
844 INIT_KMALLOC_INFO(524288, 512k),
845 INIT_KMALLOC_INFO(1048576, 1M),
846 INIT_KMALLOC_INFO(2097152, 2M),
847 INIT_KMALLOC_INFO(4194304, 4M),
848 INIT_KMALLOC_INFO(8388608, 8M),
849 INIT_KMALLOC_INFO(16777216, 16M),
850 INIT_KMALLOC_INFO(33554432, 32M),
851 INIT_KMALLOC_INFO(67108864, 64M)
855 * Patch up the size_index table if we have strange large alignment
856 * requirements for the kmalloc array. This is only the case for
857 * MIPS it seems. The standard arches will not generate any code here.
859 * Largest permitted alignment is 256 bytes due to the way we
860 * handle the index determination for the smaller caches.
862 * Make sure that nothing crazy happens if someone starts tinkering
863 * around with ARCH_KMALLOC_MINALIGN
865 void __init setup_kmalloc_cache_index_table(void)
869 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
870 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
872 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
873 unsigned int elem = size_index_elem(i);
875 if (elem >= ARRAY_SIZE(size_index))
877 size_index[elem] = KMALLOC_SHIFT_LOW;
880 if (KMALLOC_MIN_SIZE >= 64) {
882 * The 96 byte size cache is not used if the alignment
885 for (i = 64 + 8; i <= 96; i += 8)
886 size_index[size_index_elem(i)] = 7;
890 if (KMALLOC_MIN_SIZE >= 128) {
892 * The 192 byte sized cache is not used if the alignment
893 * is 128 byte. Redirect kmalloc to use the 256 byte cache
896 for (i = 128 + 8; i <= 192; i += 8)
897 size_index[size_index_elem(i)] = 8;
902 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
904 if (type == KMALLOC_RECLAIM)
905 flags |= SLAB_RECLAIM_ACCOUNT;
907 kmalloc_caches[type][idx] = create_kmalloc_cache(
908 kmalloc_info[idx].name[type],
909 kmalloc_info[idx].size, flags, 0,
910 kmalloc_info[idx].size);
914 * Create the kmalloc array. Some of the regular kmalloc arrays
915 * may already have been created because they were needed to
916 * enable allocations for slab creation.
918 void __init create_kmalloc_caches(slab_flags_t flags)
921 enum kmalloc_cache_type type;
923 for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
924 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
925 if (!kmalloc_caches[type][i])
926 new_kmalloc_cache(i, type, flags);
929 * Caches that are not of the two-to-the-power-of size.
930 * These have to be created immediately after the
931 * earlier power of two caches
933 if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
934 !kmalloc_caches[type][1])
935 new_kmalloc_cache(1, type, flags);
936 if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
937 !kmalloc_caches[type][2])
938 new_kmalloc_cache(2, type, flags);
942 /* Kmalloc array is now usable */
945 #ifdef CONFIG_ZONE_DMA
946 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
947 struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
950 kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
951 kmalloc_info[i].name[KMALLOC_DMA],
952 kmalloc_info[i].size,
953 SLAB_CACHE_DMA | flags, 0,
954 kmalloc_info[i].size);
959 #endif /* !CONFIG_SLOB */
961 gfp_t kmalloc_fix_flags(gfp_t flags)
963 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
965 flags &= ~GFP_SLAB_BUG_MASK;
966 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
967 invalid_mask, &invalid_mask, flags, &flags);
974 * To avoid unnecessary overhead, we pass through large allocation requests
975 * directly to the page allocator. We use __GFP_COMP, because we will need to
976 * know the allocation order to free the pages properly in kfree.
978 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
983 if (unlikely(flags & GFP_SLAB_BUG_MASK))
984 flags = kmalloc_fix_flags(flags);
987 page = alloc_pages(flags, order);
989 ret = page_address(page);
990 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE_B,
993 ret = kasan_kmalloc_large(ret, size, flags);
994 /* As ret might get tagged, call kmemleak hook after KASAN. */
995 kmemleak_alloc(ret, size, 1, flags);
998 EXPORT_SYMBOL(kmalloc_order);
1000 #ifdef CONFIG_TRACING
1001 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
1003 void *ret = kmalloc_order(size, flags, order);
1004 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
1007 EXPORT_SYMBOL(kmalloc_order_trace);
1010 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1011 /* Randomize a generic freelist */
1012 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
1018 for (i = 0; i < count; i++)
1021 /* Fisher-Yates shuffle */
1022 for (i = count - 1; i > 0; i--) {
1023 rand = prandom_u32_state(state);
1025 swap(list[i], list[rand]);
1029 /* Create a random sequence per cache */
1030 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1033 struct rnd_state state;
1035 if (count < 2 || cachep->random_seq)
1038 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1039 if (!cachep->random_seq)
1042 /* Get best entropy at this stage of boot */
1043 prandom_seed_state(&state, get_random_long());
1045 freelist_randomize(&state, cachep->random_seq, count);
1049 /* Destroy the per-cache random freelist sequence */
1050 void cache_random_seq_destroy(struct kmem_cache *cachep)
1052 kfree(cachep->random_seq);
1053 cachep->random_seq = NULL;
1055 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1057 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1059 #define SLABINFO_RIGHTS (0600)
1061 #define SLABINFO_RIGHTS (0400)
1064 static void print_slabinfo_header(struct seq_file *m)
1067 * Output format version, so at least we can change it
1068 * without _too_ many complaints.
1070 #ifdef CONFIG_DEBUG_SLAB
1071 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1073 seq_puts(m, "slabinfo - version: 2.1\n");
1075 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1076 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1077 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1078 #ifdef CONFIG_DEBUG_SLAB
1079 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1080 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1085 void *slab_start(struct seq_file *m, loff_t *pos)
1087 mutex_lock(&slab_mutex);
1088 return seq_list_start(&slab_caches, *pos);
1091 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1093 return seq_list_next(p, &slab_caches, pos);
1096 void slab_stop(struct seq_file *m, void *p)
1098 mutex_unlock(&slab_mutex);
1102 memcg_accumulate_slabinfo(struct kmem_cache *s, struct slabinfo *info)
1104 struct kmem_cache *c;
1105 struct slabinfo sinfo;
1107 if (!is_root_cache(s))
1112 memset(&sinfo, 0, sizeof(sinfo));
1113 get_slabinfo(c, &sinfo);
1115 info->active_slabs += sinfo.active_slabs;
1116 info->num_slabs += sinfo.num_slabs;
1117 info->shared_avail += sinfo.shared_avail;
1118 info->active_objs += sinfo.active_objs;
1119 info->num_objs += sinfo.num_objs;
1123 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1125 struct slabinfo sinfo;
1127 memset(&sinfo, 0, sizeof(sinfo));
1128 get_slabinfo(s, &sinfo);
1130 memcg_accumulate_slabinfo(s, &sinfo);
1132 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1133 cache_name(s), sinfo.active_objs, sinfo.num_objs, s->size,
1134 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1136 seq_printf(m, " : tunables %4u %4u %4u",
1137 sinfo.limit, sinfo.batchcount, sinfo.shared);
1138 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1139 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1140 slabinfo_show_stats(m, s);
1144 static int slab_show(struct seq_file *m, void *p)
1146 struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1148 if (p == slab_caches.next)
1149 print_slabinfo_header(m);
1150 if (is_root_cache(s))
1155 void dump_unreclaimable_slab(void)
1157 struct kmem_cache *s, *s2;
1158 struct slabinfo sinfo;
1161 * Here acquiring slab_mutex is risky since we don't prefer to get
1162 * sleep in oom path. But, without mutex hold, it may introduce a
1164 * Use mutex_trylock to protect the list traverse, dump nothing
1165 * without acquiring the mutex.
1167 if (!mutex_trylock(&slab_mutex)) {
1168 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1172 pr_info("Unreclaimable slab info:\n");
1173 pr_info("Name Used Total\n");
1175 list_for_each_entry_safe(s, s2, &slab_caches, list) {
1176 if (!is_root_cache(s) || (s->flags & SLAB_RECLAIM_ACCOUNT))
1179 get_slabinfo(s, &sinfo);
1181 if (sinfo.num_objs > 0)
1182 pr_info("%-17s %10luKB %10luKB\n", cache_name(s),
1183 (sinfo.active_objs * s->size) / 1024,
1184 (sinfo.num_objs * s->size) / 1024);
1186 mutex_unlock(&slab_mutex);
1189 #if defined(CONFIG_MEMCG_KMEM)
1190 int memcg_slab_show(struct seq_file *m, void *p)
1194 * Please, take a look at tools/cgroup/slabinfo.py .
1201 * slabinfo_op - iterator that generates /proc/slabinfo
1210 * num-pages-per-slab
1211 * + further values on SMP and with statistics enabled
1213 static const struct seq_operations slabinfo_op = {
1214 .start = slab_start,
1220 static int slabinfo_open(struct inode *inode, struct file *file)
1222 return seq_open(file, &slabinfo_op);
1225 static const struct proc_ops slabinfo_proc_ops = {
1226 .proc_flags = PROC_ENTRY_PERMANENT,
1227 .proc_open = slabinfo_open,
1228 .proc_read = seq_read,
1229 .proc_write = slabinfo_write,
1230 .proc_lseek = seq_lseek,
1231 .proc_release = seq_release,
1234 static int __init slab_proc_init(void)
1236 proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1239 module_init(slab_proc_init);
1241 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_MEMCG_KMEM)
1243 * Display information about kmem caches that have memcg cache.
1245 static int memcg_slabinfo_show(struct seq_file *m, void *unused)
1247 struct kmem_cache *s, *c;
1248 struct slabinfo sinfo;
1250 mutex_lock(&slab_mutex);
1251 seq_puts(m, "# <name> <css_id[:dead|deact]> <active_objs> <num_objs>");
1252 seq_puts(m, " <active_slabs> <num_slabs>\n");
1253 list_for_each_entry(s, &slab_caches, list) {
1255 * Skip kmem caches that don't have the memcg cache.
1257 if (!s->memcg_params.memcg_cache)
1260 memset(&sinfo, 0, sizeof(sinfo));
1261 get_slabinfo(s, &sinfo);
1262 seq_printf(m, "%-17s root %6lu %6lu %6lu %6lu\n",
1263 cache_name(s), sinfo.active_objs, sinfo.num_objs,
1264 sinfo.active_slabs, sinfo.num_slabs);
1266 c = s->memcg_params.memcg_cache;
1267 memset(&sinfo, 0, sizeof(sinfo));
1268 get_slabinfo(c, &sinfo);
1269 seq_printf(m, "%-17s %4d %6lu %6lu %6lu %6lu\n",
1270 cache_name(c), root_mem_cgroup->css.id,
1271 sinfo.active_objs, sinfo.num_objs,
1272 sinfo.active_slabs, sinfo.num_slabs);
1274 mutex_unlock(&slab_mutex);
1277 DEFINE_SHOW_ATTRIBUTE(memcg_slabinfo);
1279 static int __init memcg_slabinfo_init(void)
1281 debugfs_create_file("memcg_slabinfo", S_IFREG | S_IRUGO,
1282 NULL, NULL, &memcg_slabinfo_fops);
1286 late_initcall(memcg_slabinfo_init);
1287 #endif /* CONFIG_DEBUG_FS && CONFIG_MEMCG_KMEM */
1288 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1290 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1298 if (ks >= new_size) {
1299 p = kasan_krealloc((void *)p, new_size, flags);
1303 ret = kmalloc_track_caller(new_size, flags);
1311 * krealloc - reallocate memory. The contents will remain unchanged.
1312 * @p: object to reallocate memory for.
1313 * @new_size: how many bytes of memory are required.
1314 * @flags: the type of memory to allocate.
1316 * The contents of the object pointed to are preserved up to the
1317 * lesser of the new and old sizes. If @p is %NULL, krealloc()
1318 * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
1319 * %NULL pointer, the object pointed to is freed.
1321 * Return: pointer to the allocated memory or %NULL in case of error
1323 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1327 if (unlikely(!new_size)) {
1329 return ZERO_SIZE_PTR;
1332 ret = __do_krealloc(p, new_size, flags);
1333 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1338 EXPORT_SYMBOL(krealloc);
1341 * kfree_sensitive - Clear sensitive information in memory before freeing
1342 * @p: object to free memory of
1344 * The memory of the object @p points to is zeroed before freed.
1345 * If @p is %NULL, kfree_sensitive() does nothing.
1347 * Note: this function zeroes the whole allocated buffer which can be a good
1348 * deal bigger than the requested buffer size passed to kmalloc(). So be
1349 * careful when using this function in performance sensitive code.
1351 void kfree_sensitive(const void *p)
1354 void *mem = (void *)p;
1358 memzero_explicit(mem, ks);
1361 EXPORT_SYMBOL(kfree_sensitive);
1364 * ksize - get the actual amount of memory allocated for a given object
1365 * @objp: Pointer to the object
1367 * kmalloc may internally round up allocations and return more memory
1368 * than requested. ksize() can be used to determine the actual amount of
1369 * memory allocated. The caller may use this additional memory, even though
1370 * a smaller amount of memory was initially specified with the kmalloc call.
1371 * The caller must guarantee that objp points to a valid object previously
1372 * allocated with either kmalloc() or kmem_cache_alloc(). The object
1373 * must not be freed during the duration of the call.
1375 * Return: size of the actual memory used by @objp in bytes
1377 size_t ksize(const void *objp)
1382 * We need to check that the pointed to object is valid, and only then
1383 * unpoison the shadow memory below. We use __kasan_check_read(), to
1384 * generate a more useful report at the time ksize() is called (rather
1385 * than later where behaviour is undefined due to potential
1386 * use-after-free or double-free).
1388 * If the pointed to memory is invalid we return 0, to avoid users of
1389 * ksize() writing to and potentially corrupting the memory region.
1391 * We want to perform the check before __ksize(), to avoid potentially
1392 * crashing in __ksize() due to accessing invalid metadata.
1394 if (unlikely(ZERO_OR_NULL_PTR(objp)) || !__kasan_check_read(objp, 1))
1397 size = __ksize(objp);
1399 * We assume that ksize callers could use whole allocated area,
1400 * so we need to unpoison this area.
1402 kasan_unpoison_shadow(objp, size);
1405 EXPORT_SYMBOL(ksize);
1407 /* Tracepoints definitions. */
1408 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1409 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1410 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1411 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1412 EXPORT_TRACEPOINT_SYMBOL(kfree);
1413 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1415 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1417 if (__should_failslab(s, gfpflags))
1421 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);