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 <asm/cacheflush.h>
21 #include <asm/tlbflush.h>
23 #include <linux/memcontrol.h>
25 #define CREATE_TRACE_POINTS
26 #include <trace/events/kmem.h>
30 enum slab_state slab_state;
31 LIST_HEAD(slab_caches);
32 DEFINE_MUTEX(slab_mutex);
33 struct kmem_cache *kmem_cache;
35 #ifdef CONFIG_HARDENED_USERCOPY
36 bool usercopy_fallback __ro_after_init =
37 IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
38 module_param(usercopy_fallback, bool, 0400);
39 MODULE_PARM_DESC(usercopy_fallback,
40 "WARN instead of reject usercopy whitelist violations");
43 static LIST_HEAD(slab_caches_to_rcu_destroy);
44 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
45 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
46 slab_caches_to_rcu_destroy_workfn);
49 * Set of flags that will prevent slab merging
51 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
52 SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
53 SLAB_FAILSLAB | SLAB_KASAN)
55 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
56 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
59 * Merge control. If this is set then no merging of slab caches will occur.
61 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
63 static int __init setup_slab_nomerge(char *str)
70 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
73 __setup("slab_nomerge", setup_slab_nomerge);
76 * Determine the size of a slab object
78 unsigned int kmem_cache_size(struct kmem_cache *s)
80 return s->object_size;
82 EXPORT_SYMBOL(kmem_cache_size);
84 #ifdef CONFIG_DEBUG_VM
85 static int kmem_cache_sanity_check(const char *name, unsigned int size)
87 if (!name || in_interrupt() || size < sizeof(void *) ||
88 size > KMALLOC_MAX_SIZE) {
89 pr_err("kmem_cache_create(%s) integrity check failed\n", name);
93 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
97 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
103 void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
107 for (i = 0; i < nr; i++) {
109 kmem_cache_free(s, p[i]);
115 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
120 for (i = 0; i < nr; i++) {
121 void *x = p[i] = kmem_cache_alloc(s, flags);
123 __kmem_cache_free_bulk(s, i, p);
130 #ifdef CONFIG_MEMCG_KMEM
132 LIST_HEAD(slab_root_caches);
133 static DEFINE_SPINLOCK(memcg_kmem_wq_lock);
135 void slab_init_memcg_params(struct kmem_cache *s)
137 s->memcg_params.root_cache = NULL;
138 RCU_INIT_POINTER(s->memcg_params.memcg_caches, NULL);
139 INIT_LIST_HEAD(&s->memcg_params.children);
140 s->memcg_params.dying = false;
143 static int init_memcg_params(struct kmem_cache *s,
144 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
146 struct memcg_cache_array *arr;
149 s->memcg_params.root_cache = root_cache;
150 s->memcg_params.memcg = memcg;
151 INIT_LIST_HEAD(&s->memcg_params.children_node);
152 INIT_LIST_HEAD(&s->memcg_params.kmem_caches_node);
156 slab_init_memcg_params(s);
158 if (!memcg_nr_cache_ids)
161 arr = kvzalloc(sizeof(struct memcg_cache_array) +
162 memcg_nr_cache_ids * sizeof(void *),
167 RCU_INIT_POINTER(s->memcg_params.memcg_caches, arr);
171 static void destroy_memcg_params(struct kmem_cache *s)
173 if (is_root_cache(s))
174 kvfree(rcu_access_pointer(s->memcg_params.memcg_caches));
177 static void free_memcg_params(struct rcu_head *rcu)
179 struct memcg_cache_array *old;
181 old = container_of(rcu, struct memcg_cache_array, rcu);
185 static int update_memcg_params(struct kmem_cache *s, int new_array_size)
187 struct memcg_cache_array *old, *new;
189 new = kvzalloc(sizeof(struct memcg_cache_array) +
190 new_array_size * sizeof(void *), GFP_KERNEL);
194 old = rcu_dereference_protected(s->memcg_params.memcg_caches,
195 lockdep_is_held(&slab_mutex));
197 memcpy(new->entries, old->entries,
198 memcg_nr_cache_ids * sizeof(void *));
200 rcu_assign_pointer(s->memcg_params.memcg_caches, new);
202 call_rcu(&old->rcu, free_memcg_params);
206 int memcg_update_all_caches(int num_memcgs)
208 struct kmem_cache *s;
211 mutex_lock(&slab_mutex);
212 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
213 ret = update_memcg_params(s, num_memcgs);
215 * Instead of freeing the memory, we'll just leave the caches
216 * up to this point in an updated state.
221 mutex_unlock(&slab_mutex);
225 void memcg_link_cache(struct kmem_cache *s)
227 if (is_root_cache(s)) {
228 list_add(&s->root_caches_node, &slab_root_caches);
230 list_add(&s->memcg_params.children_node,
231 &s->memcg_params.root_cache->memcg_params.children);
232 list_add(&s->memcg_params.kmem_caches_node,
233 &s->memcg_params.memcg->kmem_caches);
237 static void memcg_unlink_cache(struct kmem_cache *s)
239 if (is_root_cache(s)) {
240 list_del(&s->root_caches_node);
242 list_del(&s->memcg_params.children_node);
243 list_del(&s->memcg_params.kmem_caches_node);
247 static inline int init_memcg_params(struct kmem_cache *s,
248 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
253 static inline void destroy_memcg_params(struct kmem_cache *s)
257 static inline void memcg_unlink_cache(struct kmem_cache *s)
260 #endif /* CONFIG_MEMCG_KMEM */
263 * Figure out what the alignment of the objects will be given a set of
264 * flags, a user specified alignment and the size of the objects.
266 static unsigned int calculate_alignment(slab_flags_t flags,
267 unsigned int align, unsigned int size)
270 * If the user wants hardware cache aligned objects then follow that
271 * suggestion if the object is sufficiently large.
273 * The hardware cache alignment cannot override the specified
274 * alignment though. If that is greater then use it.
276 if (flags & SLAB_HWCACHE_ALIGN) {
279 ralign = cache_line_size();
280 while (size <= ralign / 2)
282 align = max(align, ralign);
285 if (align < ARCH_SLAB_MINALIGN)
286 align = ARCH_SLAB_MINALIGN;
288 return ALIGN(align, sizeof(void *));
292 * Find a mergeable slab cache
294 int slab_unmergeable(struct kmem_cache *s)
296 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
299 if (!is_root_cache(s))
309 * We may have set a slab to be unmergeable during bootstrap.
314 #ifdef CONFIG_MEMCG_KMEM
316 * Skip the dying kmem_cache.
318 if (s->memcg_params.dying)
325 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
326 slab_flags_t flags, const char *name, void (*ctor)(void *))
328 struct kmem_cache *s;
336 size = ALIGN(size, sizeof(void *));
337 align = calculate_alignment(flags, align, size);
338 size = ALIGN(size, align);
339 flags = kmem_cache_flags(size, flags, name, NULL);
341 if (flags & SLAB_NEVER_MERGE)
344 list_for_each_entry_reverse(s, &slab_root_caches, root_caches_node) {
345 if (slab_unmergeable(s))
351 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
354 * Check if alignment is compatible.
355 * Courtesy of Adrian Drzewiecki
357 if ((s->size & ~(align - 1)) != s->size)
360 if (s->size - size >= sizeof(void *))
363 if (IS_ENABLED(CONFIG_SLAB) && align &&
364 (align > s->align || s->align % align))
372 static struct kmem_cache *create_cache(const char *name,
373 unsigned int object_size, unsigned int align,
374 slab_flags_t flags, unsigned int useroffset,
375 unsigned int usersize, void (*ctor)(void *),
376 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
378 struct kmem_cache *s;
381 if (WARN_ON(useroffset + usersize > object_size))
382 useroffset = usersize = 0;
385 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
390 s->size = s->object_size = object_size;
393 s->useroffset = useroffset;
394 s->usersize = usersize;
396 err = init_memcg_params(s, memcg, root_cache);
400 err = __kmem_cache_create(s, flags);
405 list_add(&s->list, &slab_caches);
413 destroy_memcg_params(s);
414 kmem_cache_free(kmem_cache, s);
419 * kmem_cache_create_usercopy - Create a cache.
420 * @name: A string which is used in /proc/slabinfo to identify this cache.
421 * @size: The size of objects to be created in this cache.
422 * @align: The required alignment for the objects.
424 * @useroffset: Usercopy region offset
425 * @usersize: Usercopy region size
426 * @ctor: A constructor for the objects.
428 * Returns a ptr to the cache on success, NULL on failure.
429 * Cannot be called within a interrupt, but can be interrupted.
430 * The @ctor is run when new pages are allocated by the cache.
434 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
435 * to catch references to uninitialised memory.
437 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
438 * for buffer overruns.
440 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
441 * cacheline. This can be beneficial if you're counting cycles as closely
445 kmem_cache_create_usercopy(const char *name,
446 unsigned int size, unsigned int align,
448 unsigned int useroffset, unsigned int usersize,
449 void (*ctor)(void *))
451 struct kmem_cache *s = NULL;
452 const char *cache_name;
457 memcg_get_cache_ids();
459 mutex_lock(&slab_mutex);
461 err = kmem_cache_sanity_check(name, size);
466 /* Refuse requests with allocator specific flags */
467 if (flags & ~SLAB_FLAGS_PERMITTED) {
473 * Some allocators will constraint the set of valid flags to a subset
474 * of all flags. We expect them to define CACHE_CREATE_MASK in this
475 * case, and we'll just provide them with a sanitized version of the
478 flags &= CACHE_CREATE_MASK;
480 /* Fail closed on bad usersize of useroffset values. */
481 if (WARN_ON(!usersize && useroffset) ||
482 WARN_ON(size < usersize || size - usersize < useroffset))
483 usersize = useroffset = 0;
486 s = __kmem_cache_alias(name, size, align, flags, ctor);
490 cache_name = kstrdup_const(name, GFP_KERNEL);
496 s = create_cache(cache_name, size,
497 calculate_alignment(flags, align, size),
498 flags, useroffset, usersize, ctor, NULL, NULL);
501 kfree_const(cache_name);
505 mutex_unlock(&slab_mutex);
507 memcg_put_cache_ids();
512 if (flags & SLAB_PANIC)
513 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
516 pr_warn("kmem_cache_create(%s) failed with error %d\n",
524 EXPORT_SYMBOL(kmem_cache_create_usercopy);
527 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
528 slab_flags_t flags, void (*ctor)(void *))
530 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
533 EXPORT_SYMBOL(kmem_cache_create);
535 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
537 LIST_HEAD(to_destroy);
538 struct kmem_cache *s, *s2;
541 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
542 * @slab_caches_to_rcu_destroy list. The slab pages are freed
543 * through RCU and and the associated kmem_cache are dereferenced
544 * while freeing the pages, so the kmem_caches should be freed only
545 * after the pending RCU operations are finished. As rcu_barrier()
546 * is a pretty slow operation, we batch all pending destructions
549 mutex_lock(&slab_mutex);
550 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
551 mutex_unlock(&slab_mutex);
553 if (list_empty(&to_destroy))
558 list_for_each_entry_safe(s, s2, &to_destroy, list) {
559 #ifdef SLAB_SUPPORTS_SYSFS
560 sysfs_slab_release(s);
562 slab_kmem_cache_release(s);
567 static int shutdown_cache(struct kmem_cache *s)
569 /* free asan quarantined objects */
570 kasan_cache_shutdown(s);
572 if (__kmem_cache_shutdown(s) != 0)
575 memcg_unlink_cache(s);
578 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
579 #ifdef SLAB_SUPPORTS_SYSFS
580 sysfs_slab_unlink(s);
582 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
583 schedule_work(&slab_caches_to_rcu_destroy_work);
585 #ifdef SLAB_SUPPORTS_SYSFS
586 sysfs_slab_unlink(s);
587 sysfs_slab_release(s);
589 slab_kmem_cache_release(s);
596 #ifdef CONFIG_MEMCG_KMEM
598 * memcg_create_kmem_cache - Create a cache for a memory cgroup.
599 * @memcg: The memory cgroup the new cache is for.
600 * @root_cache: The parent of the new cache.
602 * This function attempts to create a kmem cache that will serve allocation
603 * requests going from @memcg to @root_cache. The new cache inherits properties
606 void memcg_create_kmem_cache(struct mem_cgroup *memcg,
607 struct kmem_cache *root_cache)
609 static char memcg_name_buf[NAME_MAX + 1]; /* protected by slab_mutex */
610 struct cgroup_subsys_state *css = &memcg->css;
611 struct memcg_cache_array *arr;
612 struct kmem_cache *s = NULL;
619 mutex_lock(&slab_mutex);
622 * The memory cgroup could have been offlined while the cache
623 * creation work was pending.
625 if (memcg->kmem_state != KMEM_ONLINE || root_cache->memcg_params.dying)
628 idx = memcg_cache_id(memcg);
629 arr = rcu_dereference_protected(root_cache->memcg_params.memcg_caches,
630 lockdep_is_held(&slab_mutex));
633 * Since per-memcg caches are created asynchronously on first
634 * allocation (see memcg_kmem_get_cache()), several threads can try to
635 * create the same cache, but only one of them may succeed.
637 if (arr->entries[idx])
640 cgroup_name(css->cgroup, memcg_name_buf, sizeof(memcg_name_buf));
641 cache_name = kasprintf(GFP_KERNEL, "%s(%llu:%s)", root_cache->name,
642 css->serial_nr, memcg_name_buf);
646 s = create_cache(cache_name, root_cache->object_size,
648 root_cache->flags & CACHE_CREATE_MASK,
649 root_cache->useroffset, root_cache->usersize,
650 root_cache->ctor, memcg, root_cache);
652 * If we could not create a memcg cache, do not complain, because
653 * that's not critical at all as we can always proceed with the root
662 * Since readers won't lock (see cache_from_memcg_idx()), we need a
663 * barrier here to ensure nobody will see the kmem_cache partially
667 arr->entries[idx] = s;
670 mutex_unlock(&slab_mutex);
676 static void kmemcg_deactivate_workfn(struct work_struct *work)
678 struct kmem_cache *s = container_of(work, struct kmem_cache,
679 memcg_params.deact_work);
684 mutex_lock(&slab_mutex);
686 s->memcg_params.deact_fn(s);
688 mutex_unlock(&slab_mutex);
693 /* done, put the ref from slab_deactivate_memcg_cache_rcu_sched() */
694 css_put(&s->memcg_params.memcg->css);
697 static void kmemcg_deactivate_rcufn(struct rcu_head *head)
699 struct kmem_cache *s = container_of(head, struct kmem_cache,
700 memcg_params.deact_rcu_head);
703 * We need to grab blocking locks. Bounce to ->deact_work. The
704 * work item shares the space with the RCU head and can't be
705 * initialized eariler.
707 INIT_WORK(&s->memcg_params.deact_work, kmemcg_deactivate_workfn);
708 queue_work(memcg_kmem_cache_wq, &s->memcg_params.deact_work);
712 * slab_deactivate_memcg_cache_rcu_sched - schedule deactivation after a
713 * sched RCU grace period
714 * @s: target kmem_cache
715 * @deact_fn: deactivation function to call
717 * Schedule @deact_fn to be invoked with online cpus, mems and slab_mutex
718 * held after a sched RCU grace period. The slab is guaranteed to stay
719 * alive until @deact_fn is finished. This is to be used from
720 * __kmemcg_cache_deactivate().
722 void slab_deactivate_memcg_cache_rcu_sched(struct kmem_cache *s,
723 void (*deact_fn)(struct kmem_cache *))
725 if (WARN_ON_ONCE(is_root_cache(s)) ||
726 WARN_ON_ONCE(s->memcg_params.deact_fn))
730 * memcg_kmem_wq_lock is used to synchronize memcg_params.dying
731 * flag and make sure that no new kmem_cache deactivation tasks
732 * are queued (see flush_memcg_workqueue() ).
734 spin_lock_irq(&memcg_kmem_wq_lock);
735 if (s->memcg_params.root_cache->memcg_params.dying)
738 /* pin memcg so that @s doesn't get destroyed in the middle */
739 css_get(&s->memcg_params.memcg->css);
741 s->memcg_params.deact_fn = deact_fn;
742 call_rcu_sched(&s->memcg_params.deact_rcu_head, kmemcg_deactivate_rcufn);
744 spin_unlock_irq(&memcg_kmem_wq_lock);
747 void memcg_deactivate_kmem_caches(struct mem_cgroup *memcg)
750 struct memcg_cache_array *arr;
751 struct kmem_cache *s, *c;
753 idx = memcg_cache_id(memcg);
758 mutex_lock(&slab_mutex);
759 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
760 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
761 lockdep_is_held(&slab_mutex));
762 c = arr->entries[idx];
766 __kmemcg_cache_deactivate(c);
767 arr->entries[idx] = NULL;
769 mutex_unlock(&slab_mutex);
775 void memcg_destroy_kmem_caches(struct mem_cgroup *memcg)
777 struct kmem_cache *s, *s2;
782 mutex_lock(&slab_mutex);
783 list_for_each_entry_safe(s, s2, &memcg->kmem_caches,
784 memcg_params.kmem_caches_node) {
786 * The cgroup is about to be freed and therefore has no charges
787 * left. Hence, all its caches must be empty by now.
789 BUG_ON(shutdown_cache(s));
791 mutex_unlock(&slab_mutex);
797 static int shutdown_memcg_caches(struct kmem_cache *s)
799 struct memcg_cache_array *arr;
800 struct kmem_cache *c, *c2;
804 BUG_ON(!is_root_cache(s));
807 * First, shutdown active caches, i.e. caches that belong to online
810 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
811 lockdep_is_held(&slab_mutex));
812 for_each_memcg_cache_index(i) {
816 if (shutdown_cache(c))
818 * The cache still has objects. Move it to a temporary
819 * list so as not to try to destroy it for a second
820 * time while iterating over inactive caches below.
822 list_move(&c->memcg_params.children_node, &busy);
825 * The cache is empty and will be destroyed soon. Clear
826 * the pointer to it in the memcg_caches array so that
827 * it will never be accessed even if the root cache
830 arr->entries[i] = NULL;
834 * Second, shutdown all caches left from memory cgroups that are now
837 list_for_each_entry_safe(c, c2, &s->memcg_params.children,
838 memcg_params.children_node)
841 list_splice(&busy, &s->memcg_params.children);
844 * A cache being destroyed must be empty. In particular, this means
845 * that all per memcg caches attached to it must be empty too.
847 if (!list_empty(&s->memcg_params.children))
852 static void memcg_set_kmem_cache_dying(struct kmem_cache *s)
854 spin_lock_irq(&memcg_kmem_wq_lock);
855 s->memcg_params.dying = true;
856 spin_unlock_irq(&memcg_kmem_wq_lock);
859 static void flush_memcg_workqueue(struct kmem_cache *s)
862 * SLUB deactivates the kmem_caches through call_rcu_sched. Make
863 * sure all registered rcu callbacks have been invoked.
865 if (IS_ENABLED(CONFIG_SLUB))
869 * SLAB and SLUB create memcg kmem_caches through workqueue and SLUB
870 * deactivates the memcg kmem_caches through workqueue. Make sure all
871 * previous workitems on workqueue are processed.
873 if (likely(memcg_kmem_cache_wq))
874 flush_workqueue(memcg_kmem_cache_wq);
877 static inline int shutdown_memcg_caches(struct kmem_cache *s)
881 #endif /* CONFIG_MEMCG_KMEM */
883 void slab_kmem_cache_release(struct kmem_cache *s)
885 __kmem_cache_release(s);
886 destroy_memcg_params(s);
887 kfree_const(s->name);
888 kmem_cache_free(kmem_cache, s);
891 void kmem_cache_destroy(struct kmem_cache *s)
901 mutex_lock(&slab_mutex);
907 #ifdef CONFIG_MEMCG_KMEM
908 memcg_set_kmem_cache_dying(s);
910 mutex_unlock(&slab_mutex);
915 flush_memcg_workqueue(s);
920 mutex_lock(&slab_mutex);
923 err = shutdown_memcg_caches(s);
925 err = shutdown_cache(s);
928 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
933 mutex_unlock(&slab_mutex);
938 EXPORT_SYMBOL(kmem_cache_destroy);
941 * kmem_cache_shrink - Shrink a cache.
942 * @cachep: The cache to shrink.
944 * Releases as many slabs as possible for a cache.
945 * To help debugging, a zero exit status indicates all slabs were released.
947 int kmem_cache_shrink(struct kmem_cache *cachep)
953 kasan_cache_shrink(cachep);
954 ret = __kmem_cache_shrink(cachep);
959 EXPORT_SYMBOL(kmem_cache_shrink);
961 bool slab_is_available(void)
963 return slab_state >= UP;
967 /* Create a cache during boot when no slab services are available yet */
968 void __init create_boot_cache(struct kmem_cache *s, const char *name,
969 unsigned int size, slab_flags_t flags,
970 unsigned int useroffset, unsigned int usersize)
975 s->size = s->object_size = size;
976 s->align = calculate_alignment(flags, ARCH_KMALLOC_MINALIGN, size);
977 s->useroffset = useroffset;
978 s->usersize = usersize;
980 slab_init_memcg_params(s);
982 err = __kmem_cache_create(s, flags);
985 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
988 s->refcount = -1; /* Exempt from merging for now */
991 struct kmem_cache *__init create_kmalloc_cache(const char *name,
992 unsigned int size, slab_flags_t flags,
993 unsigned int useroffset, unsigned int usersize)
995 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
998 panic("Out of memory when creating slab %s\n", name);
1000 create_boot_cache(s, name, size, flags, useroffset, usersize);
1001 list_add(&s->list, &slab_caches);
1002 memcg_link_cache(s);
1007 struct kmem_cache *kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
1008 EXPORT_SYMBOL(kmalloc_caches);
1010 #ifdef CONFIG_ZONE_DMA
1011 struct kmem_cache *kmalloc_dma_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
1012 EXPORT_SYMBOL(kmalloc_dma_caches);
1016 * Conversion table for small slabs sizes / 8 to the index in the
1017 * kmalloc array. This is necessary for slabs < 192 since we have non power
1018 * of two cache sizes there. The size of larger slabs can be determined using
1021 static u8 size_index[24] __ro_after_init = {
1048 static inline unsigned int size_index_elem(unsigned int bytes)
1050 return (bytes - 1) / 8;
1054 * Find the kmem_cache structure that serves a given size of
1057 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
1063 return ZERO_SIZE_PTR;
1065 index = size_index[size_index_elem(size)];
1067 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
1071 index = fls(size - 1);
1074 #ifdef CONFIG_ZONE_DMA
1075 if (unlikely((flags & GFP_DMA)))
1076 return kmalloc_dma_caches[index];
1079 return kmalloc_caches[index];
1083 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
1084 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
1087 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
1088 {NULL, 0}, {"kmalloc-96", 96},
1089 {"kmalloc-192", 192}, {"kmalloc-8", 8},
1090 {"kmalloc-16", 16}, {"kmalloc-32", 32},
1091 {"kmalloc-64", 64}, {"kmalloc-128", 128},
1092 {"kmalloc-256", 256}, {"kmalloc-512", 512},
1093 {"kmalloc-1024", 1024}, {"kmalloc-2048", 2048},
1094 {"kmalloc-4096", 4096}, {"kmalloc-8192", 8192},
1095 {"kmalloc-16384", 16384}, {"kmalloc-32768", 32768},
1096 {"kmalloc-65536", 65536}, {"kmalloc-131072", 131072},
1097 {"kmalloc-262144", 262144}, {"kmalloc-524288", 524288},
1098 {"kmalloc-1048576", 1048576}, {"kmalloc-2097152", 2097152},
1099 {"kmalloc-4194304", 4194304}, {"kmalloc-8388608", 8388608},
1100 {"kmalloc-16777216", 16777216}, {"kmalloc-33554432", 33554432},
1101 {"kmalloc-67108864", 67108864}
1105 * Patch up the size_index table if we have strange large alignment
1106 * requirements for the kmalloc array. This is only the case for
1107 * MIPS it seems. The standard arches will not generate any code here.
1109 * Largest permitted alignment is 256 bytes due to the way we
1110 * handle the index determination for the smaller caches.
1112 * Make sure that nothing crazy happens if someone starts tinkering
1113 * around with ARCH_KMALLOC_MINALIGN
1115 void __init setup_kmalloc_cache_index_table(void)
1119 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
1120 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
1122 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
1123 unsigned int elem = size_index_elem(i);
1125 if (elem >= ARRAY_SIZE(size_index))
1127 size_index[elem] = KMALLOC_SHIFT_LOW;
1130 if (KMALLOC_MIN_SIZE >= 64) {
1132 * The 96 byte size cache is not used if the alignment
1135 for (i = 64 + 8; i <= 96; i += 8)
1136 size_index[size_index_elem(i)] = 7;
1140 if (KMALLOC_MIN_SIZE >= 128) {
1142 * The 192 byte sized cache is not used if the alignment
1143 * is 128 byte. Redirect kmalloc to use the 256 byte cache
1146 for (i = 128 + 8; i <= 192; i += 8)
1147 size_index[size_index_elem(i)] = 8;
1151 static void __init new_kmalloc_cache(int idx, slab_flags_t flags)
1153 kmalloc_caches[idx] = create_kmalloc_cache(kmalloc_info[idx].name,
1154 kmalloc_info[idx].size, flags, 0,
1155 kmalloc_info[idx].size);
1159 * Create the kmalloc array. Some of the regular kmalloc arrays
1160 * may already have been created because they were needed to
1161 * enable allocations for slab creation.
1163 void __init create_kmalloc_caches(slab_flags_t flags)
1167 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
1168 if (!kmalloc_caches[i])
1169 new_kmalloc_cache(i, flags);
1172 * Caches that are not of the two-to-the-power-of size.
1173 * These have to be created immediately after the
1174 * earlier power of two caches
1176 if (KMALLOC_MIN_SIZE <= 32 && !kmalloc_caches[1] && i == 6)
1177 new_kmalloc_cache(1, flags);
1178 if (KMALLOC_MIN_SIZE <= 64 && !kmalloc_caches[2] && i == 7)
1179 new_kmalloc_cache(2, flags);
1182 /* Kmalloc array is now usable */
1185 #ifdef CONFIG_ZONE_DMA
1186 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
1187 struct kmem_cache *s = kmalloc_caches[i];
1190 unsigned int size = kmalloc_size(i);
1191 char *n = kasprintf(GFP_NOWAIT,
1192 "dma-kmalloc-%u", size);
1195 kmalloc_dma_caches[i] = create_kmalloc_cache(n,
1196 size, SLAB_CACHE_DMA | flags, 0, 0);
1201 #endif /* !CONFIG_SLOB */
1204 * To avoid unnecessary overhead, we pass through large allocation requests
1205 * directly to the page allocator. We use __GFP_COMP, because we will need to
1206 * know the allocation order to free the pages properly in kfree.
1208 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
1213 flags |= __GFP_COMP;
1214 page = alloc_pages(flags, order);
1215 ret = page ? page_address(page) : NULL;
1216 kmemleak_alloc(ret, size, 1, flags);
1217 kasan_kmalloc_large(ret, size, flags);
1220 EXPORT_SYMBOL(kmalloc_order);
1222 #ifdef CONFIG_TRACING
1223 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
1225 void *ret = kmalloc_order(size, flags, order);
1226 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
1229 EXPORT_SYMBOL(kmalloc_order_trace);
1232 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1233 /* Randomize a generic freelist */
1234 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
1240 for (i = 0; i < count; i++)
1243 /* Fisher-Yates shuffle */
1244 for (i = count - 1; i > 0; i--) {
1245 rand = prandom_u32_state(state);
1247 swap(list[i], list[rand]);
1251 /* Create a random sequence per cache */
1252 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1255 struct rnd_state state;
1257 if (count < 2 || cachep->random_seq)
1260 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1261 if (!cachep->random_seq)
1264 /* Get best entropy at this stage of boot */
1265 prandom_seed_state(&state, get_random_long());
1267 freelist_randomize(&state, cachep->random_seq, count);
1271 /* Destroy the per-cache random freelist sequence */
1272 void cache_random_seq_destroy(struct kmem_cache *cachep)
1274 kfree(cachep->random_seq);
1275 cachep->random_seq = NULL;
1277 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1279 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1281 #define SLABINFO_RIGHTS (0600)
1283 #define SLABINFO_RIGHTS (0400)
1286 static void print_slabinfo_header(struct seq_file *m)
1289 * Output format version, so at least we can change it
1290 * without _too_ many complaints.
1292 #ifdef CONFIG_DEBUG_SLAB
1293 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1295 seq_puts(m, "slabinfo - version: 2.1\n");
1297 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1298 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1299 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1300 #ifdef CONFIG_DEBUG_SLAB
1301 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1302 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1307 void *slab_start(struct seq_file *m, loff_t *pos)
1309 mutex_lock(&slab_mutex);
1310 return seq_list_start(&slab_root_caches, *pos);
1313 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1315 return seq_list_next(p, &slab_root_caches, pos);
1318 void slab_stop(struct seq_file *m, void *p)
1320 mutex_unlock(&slab_mutex);
1324 memcg_accumulate_slabinfo(struct kmem_cache *s, struct slabinfo *info)
1326 struct kmem_cache *c;
1327 struct slabinfo sinfo;
1329 if (!is_root_cache(s))
1332 for_each_memcg_cache(c, s) {
1333 memset(&sinfo, 0, sizeof(sinfo));
1334 get_slabinfo(c, &sinfo);
1336 info->active_slabs += sinfo.active_slabs;
1337 info->num_slabs += sinfo.num_slabs;
1338 info->shared_avail += sinfo.shared_avail;
1339 info->active_objs += sinfo.active_objs;
1340 info->num_objs += sinfo.num_objs;
1344 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1346 struct slabinfo sinfo;
1348 memset(&sinfo, 0, sizeof(sinfo));
1349 get_slabinfo(s, &sinfo);
1351 memcg_accumulate_slabinfo(s, &sinfo);
1353 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1354 cache_name(s), sinfo.active_objs, sinfo.num_objs, s->size,
1355 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1357 seq_printf(m, " : tunables %4u %4u %4u",
1358 sinfo.limit, sinfo.batchcount, sinfo.shared);
1359 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1360 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1361 slabinfo_show_stats(m, s);
1365 static int slab_show(struct seq_file *m, void *p)
1367 struct kmem_cache *s = list_entry(p, struct kmem_cache, root_caches_node);
1369 if (p == slab_root_caches.next)
1370 print_slabinfo_header(m);
1375 void dump_unreclaimable_slab(void)
1377 struct kmem_cache *s, *s2;
1378 struct slabinfo sinfo;
1381 * Here acquiring slab_mutex is risky since we don't prefer to get
1382 * sleep in oom path. But, without mutex hold, it may introduce a
1384 * Use mutex_trylock to protect the list traverse, dump nothing
1385 * without acquiring the mutex.
1387 if (!mutex_trylock(&slab_mutex)) {
1388 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1392 pr_info("Unreclaimable slab info:\n");
1393 pr_info("Name Used Total\n");
1395 list_for_each_entry_safe(s, s2, &slab_caches, list) {
1396 if (!is_root_cache(s) || (s->flags & SLAB_RECLAIM_ACCOUNT))
1399 get_slabinfo(s, &sinfo);
1401 if (sinfo.num_objs > 0)
1402 pr_info("%-17s %10luKB %10luKB\n", cache_name(s),
1403 (sinfo.active_objs * s->size) / 1024,
1404 (sinfo.num_objs * s->size) / 1024);
1406 mutex_unlock(&slab_mutex);
1409 #if defined(CONFIG_MEMCG)
1410 void *memcg_slab_start(struct seq_file *m, loff_t *pos)
1412 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1414 mutex_lock(&slab_mutex);
1415 return seq_list_start(&memcg->kmem_caches, *pos);
1418 void *memcg_slab_next(struct seq_file *m, void *p, loff_t *pos)
1420 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1422 return seq_list_next(p, &memcg->kmem_caches, pos);
1425 void memcg_slab_stop(struct seq_file *m, void *p)
1427 mutex_unlock(&slab_mutex);
1430 int memcg_slab_show(struct seq_file *m, void *p)
1432 struct kmem_cache *s = list_entry(p, struct kmem_cache,
1433 memcg_params.kmem_caches_node);
1434 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1436 if (p == memcg->kmem_caches.next)
1437 print_slabinfo_header(m);
1444 * slabinfo_op - iterator that generates /proc/slabinfo
1453 * num-pages-per-slab
1454 * + further values on SMP and with statistics enabled
1456 static const struct seq_operations slabinfo_op = {
1457 .start = slab_start,
1463 static int slabinfo_open(struct inode *inode, struct file *file)
1465 return seq_open(file, &slabinfo_op);
1468 static const struct file_operations proc_slabinfo_operations = {
1469 .open = slabinfo_open,
1471 .write = slabinfo_write,
1472 .llseek = seq_lseek,
1473 .release = seq_release,
1476 static int __init slab_proc_init(void)
1478 proc_create("slabinfo", SLABINFO_RIGHTS, NULL,
1479 &proc_slabinfo_operations);
1482 module_init(slab_proc_init);
1483 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1485 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1494 if (ks >= new_size) {
1495 kasan_krealloc((void *)p, new_size, flags);
1499 ret = kmalloc_track_caller(new_size, flags);
1507 * __krealloc - like krealloc() but don't free @p.
1508 * @p: object to reallocate memory for.
1509 * @new_size: how many bytes of memory are required.
1510 * @flags: the type of memory to allocate.
1512 * This function is like krealloc() except it never frees the originally
1513 * allocated buffer. Use this if you don't want to free the buffer immediately
1514 * like, for example, with RCU.
1516 void *__krealloc(const void *p, size_t new_size, gfp_t flags)
1518 if (unlikely(!new_size))
1519 return ZERO_SIZE_PTR;
1521 return __do_krealloc(p, new_size, flags);
1524 EXPORT_SYMBOL(__krealloc);
1527 * krealloc - reallocate memory. The contents will remain unchanged.
1528 * @p: object to reallocate memory for.
1529 * @new_size: how many bytes of memory are required.
1530 * @flags: the type of memory to allocate.
1532 * The contents of the object pointed to are preserved up to the
1533 * lesser of the new and old sizes. If @p is %NULL, krealloc()
1534 * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
1535 * %NULL pointer, the object pointed to is freed.
1537 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1541 if (unlikely(!new_size)) {
1543 return ZERO_SIZE_PTR;
1546 ret = __do_krealloc(p, new_size, flags);
1547 if (ret && p != ret)
1552 EXPORT_SYMBOL(krealloc);
1555 * kzfree - like kfree but zero memory
1556 * @p: object to free memory of
1558 * The memory of the object @p points to is zeroed before freed.
1559 * If @p is %NULL, kzfree() does nothing.
1561 * Note: this function zeroes the whole allocated buffer which can be a good
1562 * deal bigger than the requested buffer size passed to kmalloc(). So be
1563 * careful when using this function in performance sensitive code.
1565 void kzfree(const void *p)
1568 void *mem = (void *)p;
1570 if (unlikely(ZERO_OR_NULL_PTR(mem)))
1573 memzero_explicit(mem, ks);
1576 EXPORT_SYMBOL(kzfree);
1578 /* Tracepoints definitions. */
1579 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1580 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1581 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1582 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1583 EXPORT_TRACEPOINT_SYMBOL(kfree);
1584 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1586 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1588 if (__should_failslab(s, gfpflags))
1592 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);