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
135 LIST_HEAD(slab_root_caches);
137 static void memcg_kmem_cache_create_func(struct work_struct *work)
139 struct kmem_cache *cachep = container_of(work, struct kmem_cache,
141 memcg_create_kmem_cache(cachep);
144 void slab_init_memcg_params(struct kmem_cache *s)
146 s->memcg_params.root_cache = NULL;
147 s->memcg_params.memcg_cache = NULL;
148 INIT_WORK(&s->memcg_params.work, memcg_kmem_cache_create_func);
151 static void init_memcg_params(struct kmem_cache *s,
152 struct kmem_cache *root_cache)
155 s->memcg_params.root_cache = root_cache;
157 slab_init_memcg_params(s);
160 void memcg_link_cache(struct kmem_cache *s)
162 if (is_root_cache(s))
163 list_add(&s->root_caches_node, &slab_root_caches);
166 static void memcg_unlink_cache(struct kmem_cache *s)
168 if (is_root_cache(s))
169 list_del(&s->root_caches_node);
172 static inline void init_memcg_params(struct kmem_cache *s,
173 struct kmem_cache *root_cache)
177 static inline void memcg_unlink_cache(struct kmem_cache *s)
180 #endif /* CONFIG_MEMCG_KMEM */
183 * Figure out what the alignment of the objects will be given a set of
184 * flags, a user specified alignment and the size of the objects.
186 static unsigned int calculate_alignment(slab_flags_t flags,
187 unsigned int align, unsigned int size)
190 * If the user wants hardware cache aligned objects then follow that
191 * suggestion if the object is sufficiently large.
193 * The hardware cache alignment cannot override the specified
194 * alignment though. If that is greater then use it.
196 if (flags & SLAB_HWCACHE_ALIGN) {
199 ralign = cache_line_size();
200 while (size <= ralign / 2)
202 align = max(align, ralign);
205 if (align < ARCH_SLAB_MINALIGN)
206 align = ARCH_SLAB_MINALIGN;
208 return ALIGN(align, sizeof(void *));
212 * Find a mergeable slab cache
214 int slab_unmergeable(struct kmem_cache *s)
216 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
219 if (!is_root_cache(s))
229 * We may have set a slab to be unmergeable during bootstrap.
237 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
238 slab_flags_t flags, const char *name, void (*ctor)(void *))
240 struct kmem_cache *s;
248 size = ALIGN(size, sizeof(void *));
249 align = calculate_alignment(flags, align, size);
250 size = ALIGN(size, align);
251 flags = kmem_cache_flags(size, flags, name, NULL);
253 if (flags & SLAB_NEVER_MERGE)
256 list_for_each_entry_reverse(s, &slab_root_caches, root_caches_node) {
257 if (slab_unmergeable(s))
263 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
266 * Check if alignment is compatible.
267 * Courtesy of Adrian Drzewiecki
269 if ((s->size & ~(align - 1)) != s->size)
272 if (s->size - size >= sizeof(void *))
275 if (IS_ENABLED(CONFIG_SLAB) && align &&
276 (align > s->align || s->align % align))
284 static struct kmem_cache *create_cache(const char *name,
285 unsigned int object_size, unsigned int align,
286 slab_flags_t flags, unsigned int useroffset,
287 unsigned int usersize, void (*ctor)(void *),
288 struct kmem_cache *root_cache)
290 struct kmem_cache *s;
293 if (WARN_ON(useroffset + usersize > object_size))
294 useroffset = usersize = 0;
297 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
302 s->size = s->object_size = object_size;
305 s->useroffset = useroffset;
306 s->usersize = usersize;
308 init_memcg_params(s, root_cache);
309 err = __kmem_cache_create(s, flags);
314 list_add(&s->list, &slab_caches);
322 kmem_cache_free(kmem_cache, s);
327 * kmem_cache_create_usercopy - Create a cache with a region suitable
328 * for copying to userspace
329 * @name: A string which is used in /proc/slabinfo to identify this cache.
330 * @size: The size of objects to be created in this cache.
331 * @align: The required alignment for the objects.
333 * @useroffset: Usercopy region offset
334 * @usersize: Usercopy region size
335 * @ctor: A constructor for the objects.
337 * Cannot be called within a interrupt, but can be interrupted.
338 * The @ctor is run when new pages are allocated by the cache.
342 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
343 * to catch references to uninitialised memory.
345 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
346 * for buffer overruns.
348 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
349 * cacheline. This can be beneficial if you're counting cycles as closely
352 * Return: a pointer to the cache on success, NULL on failure.
355 kmem_cache_create_usercopy(const char *name,
356 unsigned int size, unsigned int align,
358 unsigned int useroffset, unsigned int usersize,
359 void (*ctor)(void *))
361 struct kmem_cache *s = NULL;
362 const char *cache_name;
367 memcg_get_cache_ids();
369 mutex_lock(&slab_mutex);
371 err = kmem_cache_sanity_check(name, size);
376 /* Refuse requests with allocator specific flags */
377 if (flags & ~SLAB_FLAGS_PERMITTED) {
383 * Some allocators will constraint the set of valid flags to a subset
384 * of all flags. We expect them to define CACHE_CREATE_MASK in this
385 * case, and we'll just provide them with a sanitized version of the
388 flags &= CACHE_CREATE_MASK;
390 /* Fail closed on bad usersize of useroffset values. */
391 if (WARN_ON(!usersize && useroffset) ||
392 WARN_ON(size < usersize || size - usersize < useroffset))
393 usersize = useroffset = 0;
396 s = __kmem_cache_alias(name, size, align, flags, ctor);
400 cache_name = kstrdup_const(name, GFP_KERNEL);
406 s = create_cache(cache_name, size,
407 calculate_alignment(flags, align, size),
408 flags, useroffset, usersize, ctor, NULL);
411 kfree_const(cache_name);
415 mutex_unlock(&slab_mutex);
417 memcg_put_cache_ids();
422 if (flags & SLAB_PANIC)
423 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
426 pr_warn("kmem_cache_create(%s) failed with error %d\n",
434 EXPORT_SYMBOL(kmem_cache_create_usercopy);
437 * kmem_cache_create - Create a cache.
438 * @name: A string which is used in /proc/slabinfo to identify this cache.
439 * @size: The size of objects to be created in this cache.
440 * @align: The required alignment for the objects.
442 * @ctor: A constructor for the objects.
444 * Cannot be called within a interrupt, but can be interrupted.
445 * The @ctor is run when new pages are allocated by the cache.
449 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
450 * to catch references to uninitialised memory.
452 * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
453 * for buffer overruns.
455 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
456 * cacheline. This can be beneficial if you're counting cycles as closely
459 * Return: a pointer to the cache on success, NULL on failure.
462 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
463 slab_flags_t flags, void (*ctor)(void *))
465 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
468 EXPORT_SYMBOL(kmem_cache_create);
470 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
472 LIST_HEAD(to_destroy);
473 struct kmem_cache *s, *s2;
476 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
477 * @slab_caches_to_rcu_destroy list. The slab pages are freed
478 * through RCU and and the associated kmem_cache are dereferenced
479 * while freeing the pages, so the kmem_caches should be freed only
480 * after the pending RCU operations are finished. As rcu_barrier()
481 * is a pretty slow operation, we batch all pending destructions
484 mutex_lock(&slab_mutex);
485 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
486 mutex_unlock(&slab_mutex);
488 if (list_empty(&to_destroy))
493 list_for_each_entry_safe(s, s2, &to_destroy, list) {
494 #ifdef SLAB_SUPPORTS_SYSFS
495 sysfs_slab_release(s);
497 slab_kmem_cache_release(s);
502 static int shutdown_cache(struct kmem_cache *s)
504 /* free asan quarantined objects */
505 kasan_cache_shutdown(s);
507 if (__kmem_cache_shutdown(s) != 0)
510 memcg_unlink_cache(s);
513 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
514 #ifdef SLAB_SUPPORTS_SYSFS
515 sysfs_slab_unlink(s);
517 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
518 schedule_work(&slab_caches_to_rcu_destroy_work);
520 #ifdef SLAB_SUPPORTS_SYSFS
521 sysfs_slab_unlink(s);
522 sysfs_slab_release(s);
524 slab_kmem_cache_release(s);
531 #ifdef CONFIG_MEMCG_KMEM
533 * memcg_create_kmem_cache - Create a cache for non-root memory cgroups.
534 * @root_cache: The parent of the new cache.
536 * This function attempts to create a kmem cache that will serve allocation
537 * requests going all non-root memory cgroups to @root_cache. The new cache
538 * inherits properties from its parent.
540 void memcg_create_kmem_cache(struct kmem_cache *root_cache)
542 struct kmem_cache *s = NULL;
548 mutex_lock(&slab_mutex);
550 if (root_cache->memcg_params.memcg_cache)
553 cache_name = kasprintf(GFP_KERNEL, "%s-memcg", root_cache->name);
557 s = create_cache(cache_name, root_cache->object_size,
559 root_cache->flags & CACHE_CREATE_MASK,
560 root_cache->useroffset, root_cache->usersize,
561 root_cache->ctor, root_cache);
563 * If we could not create a memcg cache, do not complain, because
564 * that's not critical at all as we can always proceed with the root
573 * Since readers won't lock (see memcg_slab_pre_alloc_hook()), we need a
574 * barrier here to ensure nobody will see the kmem_cache partially
578 root_cache->memcg_params.memcg_cache = s;
581 mutex_unlock(&slab_mutex);
587 static int shutdown_memcg_caches(struct kmem_cache *s)
589 BUG_ON(!is_root_cache(s));
591 if (s->memcg_params.memcg_cache)
592 WARN_ON(shutdown_cache(s->memcg_params.memcg_cache));
597 static void cancel_memcg_cache_creation(struct kmem_cache *s)
599 cancel_work_sync(&s->memcg_params.work);
602 static inline int shutdown_memcg_caches(struct kmem_cache *s)
607 static inline void cancel_memcg_cache_creation(struct kmem_cache *s)
610 #endif /* CONFIG_MEMCG_KMEM */
612 void slab_kmem_cache_release(struct kmem_cache *s)
614 __kmem_cache_release(s);
615 kfree_const(s->name);
616 kmem_cache_free(kmem_cache, s);
619 void kmem_cache_destroy(struct kmem_cache *s)
626 cancel_memcg_cache_creation(s);
631 mutex_lock(&slab_mutex);
637 err = shutdown_memcg_caches(s);
639 err = shutdown_cache(s);
642 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
647 mutex_unlock(&slab_mutex);
652 EXPORT_SYMBOL(kmem_cache_destroy);
655 * kmem_cache_shrink - Shrink a cache.
656 * @cachep: The cache to shrink.
658 * Releases as many slabs as possible for a cache.
659 * To help debugging, a zero exit status indicates all slabs were released.
661 * Return: %0 if all slabs were released, non-zero otherwise
663 int kmem_cache_shrink(struct kmem_cache *cachep)
669 kasan_cache_shrink(cachep);
670 ret = __kmem_cache_shrink(cachep);
675 EXPORT_SYMBOL(kmem_cache_shrink);
678 * kmem_cache_shrink_all - shrink root and memcg caches
679 * @s: The cache pointer
681 void kmem_cache_shrink_all(struct kmem_cache *s)
683 struct kmem_cache *c;
685 if (!IS_ENABLED(CONFIG_MEMCG_KMEM) || !is_root_cache(s)) {
686 kmem_cache_shrink(s);
692 kasan_cache_shrink(s);
693 __kmem_cache_shrink(s);
697 kasan_cache_shrink(c);
698 __kmem_cache_shrink(c);
704 bool slab_is_available(void)
706 return slab_state >= UP;
710 /* Create a cache during boot when no slab services are available yet */
711 void __init create_boot_cache(struct kmem_cache *s, const char *name,
712 unsigned int size, slab_flags_t flags,
713 unsigned int useroffset, unsigned int usersize)
716 unsigned int align = ARCH_KMALLOC_MINALIGN;
719 s->size = s->object_size = size;
722 * For power of two sizes, guarantee natural alignment for kmalloc
723 * caches, regardless of SL*B debugging options.
725 if (is_power_of_2(size))
726 align = max(align, size);
727 s->align = calculate_alignment(flags, align, size);
729 s->useroffset = useroffset;
730 s->usersize = usersize;
732 slab_init_memcg_params(s);
734 err = __kmem_cache_create(s, flags);
737 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
740 s->refcount = -1; /* Exempt from merging for now */
743 struct kmem_cache *__init create_kmalloc_cache(const char *name,
744 unsigned int size, slab_flags_t flags,
745 unsigned int useroffset, unsigned int usersize)
747 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
750 panic("Out of memory when creating slab %s\n", name);
752 create_boot_cache(s, name, size, flags, useroffset, usersize);
753 list_add(&s->list, &slab_caches);
760 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
761 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
762 EXPORT_SYMBOL(kmalloc_caches);
765 * Conversion table for small slabs sizes / 8 to the index in the
766 * kmalloc array. This is necessary for slabs < 192 since we have non power
767 * of two cache sizes there. The size of larger slabs can be determined using
770 static u8 size_index[24] __ro_after_init = {
797 static inline unsigned int size_index_elem(unsigned int bytes)
799 return (bytes - 1) / 8;
803 * Find the kmem_cache structure that serves a given size of
806 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
812 return ZERO_SIZE_PTR;
814 index = size_index[size_index_elem(size)];
816 if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
818 index = fls(size - 1);
821 return kmalloc_caches[kmalloc_type(flags)][index];
824 #ifdef CONFIG_ZONE_DMA
825 #define INIT_KMALLOC_INFO(__size, __short_size) \
827 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
828 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
829 .name[KMALLOC_DMA] = "dma-kmalloc-" #__short_size, \
833 #define INIT_KMALLOC_INFO(__size, __short_size) \
835 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
836 .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size, \
842 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
843 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
846 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
847 INIT_KMALLOC_INFO(0, 0),
848 INIT_KMALLOC_INFO(96, 96),
849 INIT_KMALLOC_INFO(192, 192),
850 INIT_KMALLOC_INFO(8, 8),
851 INIT_KMALLOC_INFO(16, 16),
852 INIT_KMALLOC_INFO(32, 32),
853 INIT_KMALLOC_INFO(64, 64),
854 INIT_KMALLOC_INFO(128, 128),
855 INIT_KMALLOC_INFO(256, 256),
856 INIT_KMALLOC_INFO(512, 512),
857 INIT_KMALLOC_INFO(1024, 1k),
858 INIT_KMALLOC_INFO(2048, 2k),
859 INIT_KMALLOC_INFO(4096, 4k),
860 INIT_KMALLOC_INFO(8192, 8k),
861 INIT_KMALLOC_INFO(16384, 16k),
862 INIT_KMALLOC_INFO(32768, 32k),
863 INIT_KMALLOC_INFO(65536, 64k),
864 INIT_KMALLOC_INFO(131072, 128k),
865 INIT_KMALLOC_INFO(262144, 256k),
866 INIT_KMALLOC_INFO(524288, 512k),
867 INIT_KMALLOC_INFO(1048576, 1M),
868 INIT_KMALLOC_INFO(2097152, 2M),
869 INIT_KMALLOC_INFO(4194304, 4M),
870 INIT_KMALLOC_INFO(8388608, 8M),
871 INIT_KMALLOC_INFO(16777216, 16M),
872 INIT_KMALLOC_INFO(33554432, 32M),
873 INIT_KMALLOC_INFO(67108864, 64M)
877 * Patch up the size_index table if we have strange large alignment
878 * requirements for the kmalloc array. This is only the case for
879 * MIPS it seems. The standard arches will not generate any code here.
881 * Largest permitted alignment is 256 bytes due to the way we
882 * handle the index determination for the smaller caches.
884 * Make sure that nothing crazy happens if someone starts tinkering
885 * around with ARCH_KMALLOC_MINALIGN
887 void __init setup_kmalloc_cache_index_table(void)
891 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
892 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
894 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
895 unsigned int elem = size_index_elem(i);
897 if (elem >= ARRAY_SIZE(size_index))
899 size_index[elem] = KMALLOC_SHIFT_LOW;
902 if (KMALLOC_MIN_SIZE >= 64) {
904 * The 96 byte size cache is not used if the alignment
907 for (i = 64 + 8; i <= 96; i += 8)
908 size_index[size_index_elem(i)] = 7;
912 if (KMALLOC_MIN_SIZE >= 128) {
914 * The 192 byte sized cache is not used if the alignment
915 * is 128 byte. Redirect kmalloc to use the 256 byte cache
918 for (i = 128 + 8; i <= 192; i += 8)
919 size_index[size_index_elem(i)] = 8;
924 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
926 if (type == KMALLOC_RECLAIM)
927 flags |= SLAB_RECLAIM_ACCOUNT;
929 kmalloc_caches[type][idx] = create_kmalloc_cache(
930 kmalloc_info[idx].name[type],
931 kmalloc_info[idx].size, flags, 0,
932 kmalloc_info[idx].size);
936 * Create the kmalloc array. Some of the regular kmalloc arrays
937 * may already have been created because they were needed to
938 * enable allocations for slab creation.
940 void __init create_kmalloc_caches(slab_flags_t flags)
943 enum kmalloc_cache_type type;
945 for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
946 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
947 if (!kmalloc_caches[type][i])
948 new_kmalloc_cache(i, type, flags);
951 * Caches that are not of the two-to-the-power-of size.
952 * These have to be created immediately after the
953 * earlier power of two caches
955 if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
956 !kmalloc_caches[type][1])
957 new_kmalloc_cache(1, type, flags);
958 if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
959 !kmalloc_caches[type][2])
960 new_kmalloc_cache(2, type, flags);
964 /* Kmalloc array is now usable */
967 #ifdef CONFIG_ZONE_DMA
968 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
969 struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
972 kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
973 kmalloc_info[i].name[KMALLOC_DMA],
974 kmalloc_info[i].size,
975 SLAB_CACHE_DMA | flags, 0,
976 kmalloc_info[i].size);
981 #endif /* !CONFIG_SLOB */
983 gfp_t kmalloc_fix_flags(gfp_t flags)
985 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
987 flags &= ~GFP_SLAB_BUG_MASK;
988 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
989 invalid_mask, &invalid_mask, flags, &flags);
996 * To avoid unnecessary overhead, we pass through large allocation requests
997 * directly to the page allocator. We use __GFP_COMP, because we will need to
998 * know the allocation order to free the pages properly in kfree.
1000 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
1005 if (unlikely(flags & GFP_SLAB_BUG_MASK))
1006 flags = kmalloc_fix_flags(flags);
1008 flags |= __GFP_COMP;
1009 page = alloc_pages(flags, order);
1011 ret = page_address(page);
1012 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE_B,
1013 PAGE_SIZE << order);
1015 ret = kasan_kmalloc_large(ret, size, flags);
1016 /* As ret might get tagged, call kmemleak hook after KASAN. */
1017 kmemleak_alloc(ret, size, 1, flags);
1020 EXPORT_SYMBOL(kmalloc_order);
1022 #ifdef CONFIG_TRACING
1023 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
1025 void *ret = kmalloc_order(size, flags, order);
1026 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
1029 EXPORT_SYMBOL(kmalloc_order_trace);
1032 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1033 /* Randomize a generic freelist */
1034 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
1040 for (i = 0; i < count; i++)
1043 /* Fisher-Yates shuffle */
1044 for (i = count - 1; i > 0; i--) {
1045 rand = prandom_u32_state(state);
1047 swap(list[i], list[rand]);
1051 /* Create a random sequence per cache */
1052 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1055 struct rnd_state state;
1057 if (count < 2 || cachep->random_seq)
1060 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1061 if (!cachep->random_seq)
1064 /* Get best entropy at this stage of boot */
1065 prandom_seed_state(&state, get_random_long());
1067 freelist_randomize(&state, cachep->random_seq, count);
1071 /* Destroy the per-cache random freelist sequence */
1072 void cache_random_seq_destroy(struct kmem_cache *cachep)
1074 kfree(cachep->random_seq);
1075 cachep->random_seq = NULL;
1077 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1079 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1081 #define SLABINFO_RIGHTS (0600)
1083 #define SLABINFO_RIGHTS (0400)
1086 static void print_slabinfo_header(struct seq_file *m)
1089 * Output format version, so at least we can change it
1090 * without _too_ many complaints.
1092 #ifdef CONFIG_DEBUG_SLAB
1093 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1095 seq_puts(m, "slabinfo - version: 2.1\n");
1097 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1098 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1099 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1100 #ifdef CONFIG_DEBUG_SLAB
1101 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1102 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1107 void *slab_start(struct seq_file *m, loff_t *pos)
1109 mutex_lock(&slab_mutex);
1110 return seq_list_start(&slab_root_caches, *pos);
1113 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1115 return seq_list_next(p, &slab_root_caches, pos);
1118 void slab_stop(struct seq_file *m, void *p)
1120 mutex_unlock(&slab_mutex);
1124 memcg_accumulate_slabinfo(struct kmem_cache *s, struct slabinfo *info)
1126 struct kmem_cache *c;
1127 struct slabinfo sinfo;
1129 if (!is_root_cache(s))
1134 memset(&sinfo, 0, sizeof(sinfo));
1135 get_slabinfo(c, &sinfo);
1137 info->active_slabs += sinfo.active_slabs;
1138 info->num_slabs += sinfo.num_slabs;
1139 info->shared_avail += sinfo.shared_avail;
1140 info->active_objs += sinfo.active_objs;
1141 info->num_objs += sinfo.num_objs;
1145 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1147 struct slabinfo sinfo;
1149 memset(&sinfo, 0, sizeof(sinfo));
1150 get_slabinfo(s, &sinfo);
1152 memcg_accumulate_slabinfo(s, &sinfo);
1154 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1155 cache_name(s), sinfo.active_objs, sinfo.num_objs, s->size,
1156 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1158 seq_printf(m, " : tunables %4u %4u %4u",
1159 sinfo.limit, sinfo.batchcount, sinfo.shared);
1160 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1161 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1162 slabinfo_show_stats(m, s);
1166 static int slab_show(struct seq_file *m, void *p)
1168 struct kmem_cache *s = list_entry(p, struct kmem_cache, root_caches_node);
1170 if (p == slab_root_caches.next)
1171 print_slabinfo_header(m);
1176 void dump_unreclaimable_slab(void)
1178 struct kmem_cache *s, *s2;
1179 struct slabinfo sinfo;
1182 * Here acquiring slab_mutex is risky since we don't prefer to get
1183 * sleep in oom path. But, without mutex hold, it may introduce a
1185 * Use mutex_trylock to protect the list traverse, dump nothing
1186 * without acquiring the mutex.
1188 if (!mutex_trylock(&slab_mutex)) {
1189 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1193 pr_info("Unreclaimable slab info:\n");
1194 pr_info("Name Used Total\n");
1196 list_for_each_entry_safe(s, s2, &slab_caches, list) {
1197 if (!is_root_cache(s) || (s->flags & SLAB_RECLAIM_ACCOUNT))
1200 get_slabinfo(s, &sinfo);
1202 if (sinfo.num_objs > 0)
1203 pr_info("%-17s %10luKB %10luKB\n", cache_name(s),
1204 (sinfo.active_objs * s->size) / 1024,
1205 (sinfo.num_objs * s->size) / 1024);
1207 mutex_unlock(&slab_mutex);
1210 #if defined(CONFIG_MEMCG_KMEM)
1211 int memcg_slab_show(struct seq_file *m, void *p)
1215 * Please, take a look at tools/cgroup/slabinfo.py .
1222 * slabinfo_op - iterator that generates /proc/slabinfo
1231 * num-pages-per-slab
1232 * + further values on SMP and with statistics enabled
1234 static const struct seq_operations slabinfo_op = {
1235 .start = slab_start,
1241 static int slabinfo_open(struct inode *inode, struct file *file)
1243 return seq_open(file, &slabinfo_op);
1246 static const struct proc_ops slabinfo_proc_ops = {
1247 .proc_flags = PROC_ENTRY_PERMANENT,
1248 .proc_open = slabinfo_open,
1249 .proc_read = seq_read,
1250 .proc_write = slabinfo_write,
1251 .proc_lseek = seq_lseek,
1252 .proc_release = seq_release,
1255 static int __init slab_proc_init(void)
1257 proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1260 module_init(slab_proc_init);
1262 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_MEMCG_KMEM)
1264 * Display information about kmem caches that have memcg cache.
1266 static int memcg_slabinfo_show(struct seq_file *m, void *unused)
1268 struct kmem_cache *s, *c;
1269 struct slabinfo sinfo;
1271 mutex_lock(&slab_mutex);
1272 seq_puts(m, "# <name> <css_id[:dead|deact]> <active_objs> <num_objs>");
1273 seq_puts(m, " <active_slabs> <num_slabs>\n");
1274 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
1276 * Skip kmem caches that don't have the memcg cache.
1278 if (!s->memcg_params.memcg_cache)
1281 memset(&sinfo, 0, sizeof(sinfo));
1282 get_slabinfo(s, &sinfo);
1283 seq_printf(m, "%-17s root %6lu %6lu %6lu %6lu\n",
1284 cache_name(s), sinfo.active_objs, sinfo.num_objs,
1285 sinfo.active_slabs, sinfo.num_slabs);
1287 c = s->memcg_params.memcg_cache;
1288 memset(&sinfo, 0, sizeof(sinfo));
1289 get_slabinfo(c, &sinfo);
1290 seq_printf(m, "%-17s %4d %6lu %6lu %6lu %6lu\n",
1291 cache_name(c), root_mem_cgroup->css.id,
1292 sinfo.active_objs, sinfo.num_objs,
1293 sinfo.active_slabs, sinfo.num_slabs);
1295 mutex_unlock(&slab_mutex);
1298 DEFINE_SHOW_ATTRIBUTE(memcg_slabinfo);
1300 static int __init memcg_slabinfo_init(void)
1302 debugfs_create_file("memcg_slabinfo", S_IFREG | S_IRUGO,
1303 NULL, NULL, &memcg_slabinfo_fops);
1307 late_initcall(memcg_slabinfo_init);
1308 #endif /* CONFIG_DEBUG_FS && CONFIG_MEMCG_KMEM */
1309 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1311 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1319 if (ks >= new_size) {
1320 p = kasan_krealloc((void *)p, new_size, flags);
1324 ret = kmalloc_track_caller(new_size, flags);
1332 * krealloc - reallocate memory. The contents will remain unchanged.
1333 * @p: object to reallocate memory for.
1334 * @new_size: how many bytes of memory are required.
1335 * @flags: the type of memory to allocate.
1337 * The contents of the object pointed to are preserved up to the
1338 * lesser of the new and old sizes. If @p is %NULL, krealloc()
1339 * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
1340 * %NULL pointer, the object pointed to is freed.
1342 * Return: pointer to the allocated memory or %NULL in case of error
1344 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1348 if (unlikely(!new_size)) {
1350 return ZERO_SIZE_PTR;
1353 ret = __do_krealloc(p, new_size, flags);
1354 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1359 EXPORT_SYMBOL(krealloc);
1362 * kfree_sensitive - Clear sensitive information in memory before freeing
1363 * @p: object to free memory of
1365 * The memory of the object @p points to is zeroed before freed.
1366 * If @p is %NULL, kfree_sensitive() does nothing.
1368 * Note: this function zeroes the whole allocated buffer which can be a good
1369 * deal bigger than the requested buffer size passed to kmalloc(). So be
1370 * careful when using this function in performance sensitive code.
1372 void kfree_sensitive(const void *p)
1375 void *mem = (void *)p;
1379 memzero_explicit(mem, ks);
1382 EXPORT_SYMBOL(kfree_sensitive);
1385 * ksize - get the actual amount of memory allocated for a given object
1386 * @objp: Pointer to the object
1388 * kmalloc may internally round up allocations and return more memory
1389 * than requested. ksize() can be used to determine the actual amount of
1390 * memory allocated. The caller may use this additional memory, even though
1391 * a smaller amount of memory was initially specified with the kmalloc call.
1392 * The caller must guarantee that objp points to a valid object previously
1393 * allocated with either kmalloc() or kmem_cache_alloc(). The object
1394 * must not be freed during the duration of the call.
1396 * Return: size of the actual memory used by @objp in bytes
1398 size_t ksize(const void *objp)
1403 * We need to check that the pointed to object is valid, and only then
1404 * unpoison the shadow memory below. We use __kasan_check_read(), to
1405 * generate a more useful report at the time ksize() is called (rather
1406 * than later where behaviour is undefined due to potential
1407 * use-after-free or double-free).
1409 * If the pointed to memory is invalid we return 0, to avoid users of
1410 * ksize() writing to and potentially corrupting the memory region.
1412 * We want to perform the check before __ksize(), to avoid potentially
1413 * crashing in __ksize() due to accessing invalid metadata.
1415 if (unlikely(ZERO_OR_NULL_PTR(objp)) || !__kasan_check_read(objp, 1))
1418 size = __ksize(objp);
1420 * We assume that ksize callers could use whole allocated area,
1421 * so we need to unpoison this area.
1423 kasan_unpoison_shadow(objp, size);
1426 EXPORT_SYMBOL(ksize);
1428 /* Tracepoints definitions. */
1429 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1430 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1431 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1432 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1433 EXPORT_TRACEPOINT_SYMBOL(kfree);
1434 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1436 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1438 if (__should_failslab(s, gfpflags))
1442 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);