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.
317 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
318 slab_flags_t flags, const char *name, void (*ctor)(void *))
320 struct kmem_cache *s;
328 size = ALIGN(size, sizeof(void *));
329 align = calculate_alignment(flags, align, size);
330 size = ALIGN(size, align);
331 flags = kmem_cache_flags(size, flags, name, NULL);
333 if (flags & SLAB_NEVER_MERGE)
336 list_for_each_entry_reverse(s, &slab_root_caches, root_caches_node) {
337 if (slab_unmergeable(s))
343 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
346 * Check if alignment is compatible.
347 * Courtesy of Adrian Drzewiecki
349 if ((s->size & ~(align - 1)) != s->size)
352 if (s->size - size >= sizeof(void *))
355 if (IS_ENABLED(CONFIG_SLAB) && align &&
356 (align > s->align || s->align % align))
364 static struct kmem_cache *create_cache(const char *name,
365 unsigned int object_size, unsigned int align,
366 slab_flags_t flags, unsigned int useroffset,
367 unsigned int usersize, void (*ctor)(void *),
368 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
370 struct kmem_cache *s;
373 if (WARN_ON(useroffset + usersize > object_size))
374 useroffset = usersize = 0;
377 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
382 s->size = s->object_size = object_size;
385 s->useroffset = useroffset;
386 s->usersize = usersize;
388 err = init_memcg_params(s, memcg, root_cache);
392 err = __kmem_cache_create(s, flags);
397 list_add(&s->list, &slab_caches);
405 destroy_memcg_params(s);
406 kmem_cache_free(kmem_cache, s);
411 * kmem_cache_create_usercopy - Create a cache.
412 * @name: A string which is used in /proc/slabinfo to identify this cache.
413 * @size: The size of objects to be created in this cache.
414 * @align: The required alignment for the objects.
416 * @useroffset: Usercopy region offset
417 * @usersize: Usercopy region size
418 * @ctor: A constructor for the objects.
420 * Returns a ptr to the cache on success, NULL on failure.
421 * Cannot be called within a interrupt, but can be interrupted.
422 * The @ctor is run when new pages are allocated by the cache.
426 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
427 * to catch references to uninitialised memory.
429 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
430 * for buffer overruns.
432 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
433 * cacheline. This can be beneficial if you're counting cycles as closely
437 kmem_cache_create_usercopy(const char *name,
438 unsigned int size, unsigned int align,
440 unsigned int useroffset, unsigned int usersize,
441 void (*ctor)(void *))
443 struct kmem_cache *s = NULL;
444 const char *cache_name;
449 memcg_get_cache_ids();
451 mutex_lock(&slab_mutex);
453 err = kmem_cache_sanity_check(name, size);
458 /* Refuse requests with allocator specific flags */
459 if (flags & ~SLAB_FLAGS_PERMITTED) {
465 * Some allocators will constraint the set of valid flags to a subset
466 * of all flags. We expect them to define CACHE_CREATE_MASK in this
467 * case, and we'll just provide them with a sanitized version of the
470 flags &= CACHE_CREATE_MASK;
472 /* Fail closed on bad usersize of useroffset values. */
473 if (WARN_ON(!usersize && useroffset) ||
474 WARN_ON(size < usersize || size - usersize < useroffset))
475 usersize = useroffset = 0;
478 s = __kmem_cache_alias(name, size, align, flags, ctor);
482 cache_name = kstrdup_const(name, GFP_KERNEL);
488 s = create_cache(cache_name, size,
489 calculate_alignment(flags, align, size),
490 flags, useroffset, usersize, ctor, NULL, NULL);
493 kfree_const(cache_name);
497 mutex_unlock(&slab_mutex);
499 memcg_put_cache_ids();
504 if (flags & SLAB_PANIC)
505 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
508 pr_warn("kmem_cache_create(%s) failed with error %d\n",
516 EXPORT_SYMBOL(kmem_cache_create_usercopy);
519 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
520 slab_flags_t flags, void (*ctor)(void *))
522 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
525 EXPORT_SYMBOL(kmem_cache_create);
527 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
529 LIST_HEAD(to_destroy);
530 struct kmem_cache *s, *s2;
533 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
534 * @slab_caches_to_rcu_destroy list. The slab pages are freed
535 * through RCU and and the associated kmem_cache are dereferenced
536 * while freeing the pages, so the kmem_caches should be freed only
537 * after the pending RCU operations are finished. As rcu_barrier()
538 * is a pretty slow operation, we batch all pending destructions
541 mutex_lock(&slab_mutex);
542 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
543 mutex_unlock(&slab_mutex);
545 if (list_empty(&to_destroy))
550 list_for_each_entry_safe(s, s2, &to_destroy, list) {
551 #ifdef SLAB_SUPPORTS_SYSFS
552 sysfs_slab_release(s);
554 slab_kmem_cache_release(s);
559 static int shutdown_cache(struct kmem_cache *s)
561 /* free asan quarantined objects */
562 kasan_cache_shutdown(s);
564 if (__kmem_cache_shutdown(s) != 0)
567 memcg_unlink_cache(s);
570 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
571 #ifdef SLAB_SUPPORTS_SYSFS
572 sysfs_slab_unlink(s);
574 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
575 schedule_work(&slab_caches_to_rcu_destroy_work);
577 #ifdef SLAB_SUPPORTS_SYSFS
578 sysfs_slab_unlink(s);
579 sysfs_slab_release(s);
581 slab_kmem_cache_release(s);
588 #ifdef CONFIG_MEMCG_KMEM
590 * memcg_create_kmem_cache - Create a cache for a memory cgroup.
591 * @memcg: The memory cgroup the new cache is for.
592 * @root_cache: The parent of the new cache.
594 * This function attempts to create a kmem cache that will serve allocation
595 * requests going from @memcg to @root_cache. The new cache inherits properties
598 void memcg_create_kmem_cache(struct mem_cgroup *memcg,
599 struct kmem_cache *root_cache)
601 static char memcg_name_buf[NAME_MAX + 1]; /* protected by slab_mutex */
602 struct cgroup_subsys_state *css = &memcg->css;
603 struct memcg_cache_array *arr;
604 struct kmem_cache *s = NULL;
611 mutex_lock(&slab_mutex);
614 * The memory cgroup could have been offlined while the cache
615 * creation work was pending.
617 if (memcg->kmem_state != KMEM_ONLINE || root_cache->memcg_params.dying)
620 idx = memcg_cache_id(memcg);
621 arr = rcu_dereference_protected(root_cache->memcg_params.memcg_caches,
622 lockdep_is_held(&slab_mutex));
625 * Since per-memcg caches are created asynchronously on first
626 * allocation (see memcg_kmem_get_cache()), several threads can try to
627 * create the same cache, but only one of them may succeed.
629 if (arr->entries[idx])
632 cgroup_name(css->cgroup, memcg_name_buf, sizeof(memcg_name_buf));
633 cache_name = kasprintf(GFP_KERNEL, "%s(%llu:%s)", root_cache->name,
634 css->serial_nr, memcg_name_buf);
638 s = create_cache(cache_name, root_cache->object_size,
640 root_cache->flags & CACHE_CREATE_MASK,
641 root_cache->useroffset, root_cache->usersize,
642 root_cache->ctor, memcg, root_cache);
644 * If we could not create a memcg cache, do not complain, because
645 * that's not critical at all as we can always proceed with the root
654 * Since readers won't lock (see cache_from_memcg_idx()), we need a
655 * barrier here to ensure nobody will see the kmem_cache partially
659 arr->entries[idx] = s;
662 mutex_unlock(&slab_mutex);
668 static void kmemcg_deactivate_workfn(struct work_struct *work)
670 struct kmem_cache *s = container_of(work, struct kmem_cache,
671 memcg_params.deact_work);
676 mutex_lock(&slab_mutex);
678 s->memcg_params.deact_fn(s);
680 mutex_unlock(&slab_mutex);
685 /* done, put the ref from slab_deactivate_memcg_cache_rcu_sched() */
686 css_put(&s->memcg_params.memcg->css);
689 static void kmemcg_deactivate_rcufn(struct rcu_head *head)
691 struct kmem_cache *s = container_of(head, struct kmem_cache,
692 memcg_params.deact_rcu_head);
695 * We need to grab blocking locks. Bounce to ->deact_work. The
696 * work item shares the space with the RCU head and can't be
697 * initialized eariler.
699 INIT_WORK(&s->memcg_params.deact_work, kmemcg_deactivate_workfn);
700 queue_work(memcg_kmem_cache_wq, &s->memcg_params.deact_work);
704 * slab_deactivate_memcg_cache_rcu_sched - schedule deactivation after a
705 * sched RCU grace period
706 * @s: target kmem_cache
707 * @deact_fn: deactivation function to call
709 * Schedule @deact_fn to be invoked with online cpus, mems and slab_mutex
710 * held after a sched RCU grace period. The slab is guaranteed to stay
711 * alive until @deact_fn is finished. This is to be used from
712 * __kmemcg_cache_deactivate().
714 void slab_deactivate_memcg_cache_rcu_sched(struct kmem_cache *s,
715 void (*deact_fn)(struct kmem_cache *))
717 if (WARN_ON_ONCE(is_root_cache(s)) ||
718 WARN_ON_ONCE(s->memcg_params.deact_fn))
722 * memcg_kmem_wq_lock is used to synchronize memcg_params.dying
723 * flag and make sure that no new kmem_cache deactivation tasks
724 * are queued (see flush_memcg_workqueue() ).
726 spin_lock_irq(&memcg_kmem_wq_lock);
727 if (s->memcg_params.root_cache->memcg_params.dying)
730 /* pin memcg so that @s doesn't get destroyed in the middle */
731 css_get(&s->memcg_params.memcg->css);
733 s->memcg_params.deact_fn = deact_fn;
734 call_rcu_sched(&s->memcg_params.deact_rcu_head, kmemcg_deactivate_rcufn);
736 spin_unlock_irq(&memcg_kmem_wq_lock);
739 void memcg_deactivate_kmem_caches(struct mem_cgroup *memcg)
742 struct memcg_cache_array *arr;
743 struct kmem_cache *s, *c;
745 idx = memcg_cache_id(memcg);
750 mutex_lock(&slab_mutex);
751 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
752 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
753 lockdep_is_held(&slab_mutex));
754 c = arr->entries[idx];
758 __kmemcg_cache_deactivate(c);
759 arr->entries[idx] = NULL;
761 mutex_unlock(&slab_mutex);
767 void memcg_destroy_kmem_caches(struct mem_cgroup *memcg)
769 struct kmem_cache *s, *s2;
774 mutex_lock(&slab_mutex);
775 list_for_each_entry_safe(s, s2, &memcg->kmem_caches,
776 memcg_params.kmem_caches_node) {
778 * The cgroup is about to be freed and therefore has no charges
779 * left. Hence, all its caches must be empty by now.
781 BUG_ON(shutdown_cache(s));
783 mutex_unlock(&slab_mutex);
789 static int shutdown_memcg_caches(struct kmem_cache *s)
791 struct memcg_cache_array *arr;
792 struct kmem_cache *c, *c2;
796 BUG_ON(!is_root_cache(s));
799 * First, shutdown active caches, i.e. caches that belong to online
802 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
803 lockdep_is_held(&slab_mutex));
804 for_each_memcg_cache_index(i) {
808 if (shutdown_cache(c))
810 * The cache still has objects. Move it to a temporary
811 * list so as not to try to destroy it for a second
812 * time while iterating over inactive caches below.
814 list_move(&c->memcg_params.children_node, &busy);
817 * The cache is empty and will be destroyed soon. Clear
818 * the pointer to it in the memcg_caches array so that
819 * it will never be accessed even if the root cache
822 arr->entries[i] = NULL;
826 * Second, shutdown all caches left from memory cgroups that are now
829 list_for_each_entry_safe(c, c2, &s->memcg_params.children,
830 memcg_params.children_node)
833 list_splice(&busy, &s->memcg_params.children);
836 * A cache being destroyed must be empty. In particular, this means
837 * that all per memcg caches attached to it must be empty too.
839 if (!list_empty(&s->memcg_params.children))
844 static void memcg_set_kmem_cache_dying(struct kmem_cache *s)
846 spin_lock_irq(&memcg_kmem_wq_lock);
847 s->memcg_params.dying = true;
848 spin_unlock_irq(&memcg_kmem_wq_lock);
851 static void flush_memcg_workqueue(struct kmem_cache *s)
854 * SLUB deactivates the kmem_caches through call_rcu_sched. Make
855 * sure all registered rcu callbacks have been invoked.
857 if (IS_ENABLED(CONFIG_SLUB))
861 * SLAB and SLUB create memcg kmem_caches through workqueue and SLUB
862 * deactivates the memcg kmem_caches through workqueue. Make sure all
863 * previous workitems on workqueue are processed.
865 if (likely(memcg_kmem_cache_wq))
866 flush_workqueue(memcg_kmem_cache_wq);
869 static inline int shutdown_memcg_caches(struct kmem_cache *s)
873 #endif /* CONFIG_MEMCG_KMEM */
875 void slab_kmem_cache_release(struct kmem_cache *s)
877 __kmem_cache_release(s);
878 destroy_memcg_params(s);
879 kfree_const(s->name);
880 kmem_cache_free(kmem_cache, s);
883 void kmem_cache_destroy(struct kmem_cache *s)
893 mutex_lock(&slab_mutex);
899 #ifdef CONFIG_MEMCG_KMEM
900 memcg_set_kmem_cache_dying(s);
902 mutex_unlock(&slab_mutex);
907 flush_memcg_workqueue(s);
912 mutex_lock(&slab_mutex);
915 * Another thread referenced it again
917 if (READ_ONCE(s->refcount)) {
918 spin_lock_irq(&memcg_kmem_wq_lock);
919 s->memcg_params.dying = false;
920 spin_unlock_irq(&memcg_kmem_wq_lock);
925 err = shutdown_memcg_caches(s);
927 err = shutdown_cache(s);
930 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
935 mutex_unlock(&slab_mutex);
940 EXPORT_SYMBOL(kmem_cache_destroy);
943 * kmem_cache_shrink - Shrink a cache.
944 * @cachep: The cache to shrink.
946 * Releases as many slabs as possible for a cache.
947 * To help debugging, a zero exit status indicates all slabs were released.
949 int kmem_cache_shrink(struct kmem_cache *cachep)
955 kasan_cache_shrink(cachep);
956 ret = __kmem_cache_shrink(cachep);
961 EXPORT_SYMBOL(kmem_cache_shrink);
963 bool slab_is_available(void)
965 return slab_state >= UP;
969 /* Create a cache during boot when no slab services are available yet */
970 void __init create_boot_cache(struct kmem_cache *s, const char *name,
971 unsigned int size, slab_flags_t flags,
972 unsigned int useroffset, unsigned int usersize)
977 s->size = s->object_size = size;
978 s->align = calculate_alignment(flags, ARCH_KMALLOC_MINALIGN, size);
979 s->useroffset = useroffset;
980 s->usersize = usersize;
982 slab_init_memcg_params(s);
984 err = __kmem_cache_create(s, flags);
987 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
990 s->refcount = -1; /* Exempt from merging for now */
993 struct kmem_cache *__init create_kmalloc_cache(const char *name,
994 unsigned int size, slab_flags_t flags,
995 unsigned int useroffset, unsigned int usersize)
997 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
1000 panic("Out of memory when creating slab %s\n", name);
1002 create_boot_cache(s, name, size, flags, useroffset, usersize);
1003 list_add(&s->list, &slab_caches);
1004 memcg_link_cache(s);
1009 struct kmem_cache *kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
1010 EXPORT_SYMBOL(kmalloc_caches);
1012 #ifdef CONFIG_ZONE_DMA
1013 struct kmem_cache *kmalloc_dma_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
1014 EXPORT_SYMBOL(kmalloc_dma_caches);
1018 * Conversion table for small slabs sizes / 8 to the index in the
1019 * kmalloc array. This is necessary for slabs < 192 since we have non power
1020 * of two cache sizes there. The size of larger slabs can be determined using
1023 static u8 size_index[24] __ro_after_init = {
1050 static inline unsigned int size_index_elem(unsigned int bytes)
1052 return (bytes - 1) / 8;
1056 * Find the kmem_cache structure that serves a given size of
1059 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
1065 return ZERO_SIZE_PTR;
1067 index = size_index[size_index_elem(size)];
1069 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
1073 index = fls(size - 1);
1076 #ifdef CONFIG_ZONE_DMA
1077 if (unlikely((flags & GFP_DMA)))
1078 return kmalloc_dma_caches[index];
1081 return kmalloc_caches[index];
1085 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
1086 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
1089 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
1090 {NULL, 0}, {"kmalloc-96", 96},
1091 {"kmalloc-192", 192}, {"kmalloc-8", 8},
1092 {"kmalloc-16", 16}, {"kmalloc-32", 32},
1093 {"kmalloc-64", 64}, {"kmalloc-128", 128},
1094 {"kmalloc-256", 256}, {"kmalloc-512", 512},
1095 {"kmalloc-1024", 1024}, {"kmalloc-2048", 2048},
1096 {"kmalloc-4096", 4096}, {"kmalloc-8192", 8192},
1097 {"kmalloc-16384", 16384}, {"kmalloc-32768", 32768},
1098 {"kmalloc-65536", 65536}, {"kmalloc-131072", 131072},
1099 {"kmalloc-262144", 262144}, {"kmalloc-524288", 524288},
1100 {"kmalloc-1048576", 1048576}, {"kmalloc-2097152", 2097152},
1101 {"kmalloc-4194304", 4194304}, {"kmalloc-8388608", 8388608},
1102 {"kmalloc-16777216", 16777216}, {"kmalloc-33554432", 33554432},
1103 {"kmalloc-67108864", 67108864}
1107 * Patch up the size_index table if we have strange large alignment
1108 * requirements for the kmalloc array. This is only the case for
1109 * MIPS it seems. The standard arches will not generate any code here.
1111 * Largest permitted alignment is 256 bytes due to the way we
1112 * handle the index determination for the smaller caches.
1114 * Make sure that nothing crazy happens if someone starts tinkering
1115 * around with ARCH_KMALLOC_MINALIGN
1117 void __init setup_kmalloc_cache_index_table(void)
1121 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
1122 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
1124 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
1125 unsigned int elem = size_index_elem(i);
1127 if (elem >= ARRAY_SIZE(size_index))
1129 size_index[elem] = KMALLOC_SHIFT_LOW;
1132 if (KMALLOC_MIN_SIZE >= 64) {
1134 * The 96 byte size cache is not used if the alignment
1137 for (i = 64 + 8; i <= 96; i += 8)
1138 size_index[size_index_elem(i)] = 7;
1142 if (KMALLOC_MIN_SIZE >= 128) {
1144 * The 192 byte sized cache is not used if the alignment
1145 * is 128 byte. Redirect kmalloc to use the 256 byte cache
1148 for (i = 128 + 8; i <= 192; i += 8)
1149 size_index[size_index_elem(i)] = 8;
1153 static void __init new_kmalloc_cache(int idx, slab_flags_t flags)
1155 kmalloc_caches[idx] = create_kmalloc_cache(kmalloc_info[idx].name,
1156 kmalloc_info[idx].size, flags, 0,
1157 kmalloc_info[idx].size);
1161 * Create the kmalloc array. Some of the regular kmalloc arrays
1162 * may already have been created because they were needed to
1163 * enable allocations for slab creation.
1165 void __init create_kmalloc_caches(slab_flags_t flags)
1169 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
1170 if (!kmalloc_caches[i])
1171 new_kmalloc_cache(i, flags);
1174 * Caches that are not of the two-to-the-power-of size.
1175 * These have to be created immediately after the
1176 * earlier power of two caches
1178 if (KMALLOC_MIN_SIZE <= 32 && !kmalloc_caches[1] && i == 6)
1179 new_kmalloc_cache(1, flags);
1180 if (KMALLOC_MIN_SIZE <= 64 && !kmalloc_caches[2] && i == 7)
1181 new_kmalloc_cache(2, flags);
1184 /* Kmalloc array is now usable */
1187 #ifdef CONFIG_ZONE_DMA
1188 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
1189 struct kmem_cache *s = kmalloc_caches[i];
1192 unsigned int size = kmalloc_size(i);
1193 char *n = kasprintf(GFP_NOWAIT,
1194 "dma-kmalloc-%u", size);
1197 kmalloc_dma_caches[i] = create_kmalloc_cache(n,
1198 size, SLAB_CACHE_DMA | flags, 0, 0);
1203 #endif /* !CONFIG_SLOB */
1206 * To avoid unnecessary overhead, we pass through large allocation requests
1207 * directly to the page allocator. We use __GFP_COMP, because we will need to
1208 * know the allocation order to free the pages properly in kfree.
1210 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
1215 flags |= __GFP_COMP;
1216 page = alloc_pages(flags, order);
1217 ret = page ? page_address(page) : NULL;
1218 kmemleak_alloc(ret, size, 1, flags);
1219 kasan_kmalloc_large(ret, size, flags);
1222 EXPORT_SYMBOL(kmalloc_order);
1224 #ifdef CONFIG_TRACING
1225 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
1227 void *ret = kmalloc_order(size, flags, order);
1228 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
1231 EXPORT_SYMBOL(kmalloc_order_trace);
1234 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1235 /* Randomize a generic freelist */
1236 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
1242 for (i = 0; i < count; i++)
1245 /* Fisher-Yates shuffle */
1246 for (i = count - 1; i > 0; i--) {
1247 rand = prandom_u32_state(state);
1249 swap(list[i], list[rand]);
1253 /* Create a random sequence per cache */
1254 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1257 struct rnd_state state;
1259 if (count < 2 || cachep->random_seq)
1262 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1263 if (!cachep->random_seq)
1266 /* Get best entropy at this stage of boot */
1267 prandom_seed_state(&state, get_random_long());
1269 freelist_randomize(&state, cachep->random_seq, count);
1273 /* Destroy the per-cache random freelist sequence */
1274 void cache_random_seq_destroy(struct kmem_cache *cachep)
1276 kfree(cachep->random_seq);
1277 cachep->random_seq = NULL;
1279 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1281 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1283 #define SLABINFO_RIGHTS (0600)
1285 #define SLABINFO_RIGHTS (0400)
1288 static void print_slabinfo_header(struct seq_file *m)
1291 * Output format version, so at least we can change it
1292 * without _too_ many complaints.
1294 #ifdef CONFIG_DEBUG_SLAB
1295 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1297 seq_puts(m, "slabinfo - version: 2.1\n");
1299 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1300 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1301 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1302 #ifdef CONFIG_DEBUG_SLAB
1303 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1304 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1309 void *slab_start(struct seq_file *m, loff_t *pos)
1311 mutex_lock(&slab_mutex);
1312 return seq_list_start(&slab_root_caches, *pos);
1315 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1317 return seq_list_next(p, &slab_root_caches, pos);
1320 void slab_stop(struct seq_file *m, void *p)
1322 mutex_unlock(&slab_mutex);
1326 memcg_accumulate_slabinfo(struct kmem_cache *s, struct slabinfo *info)
1328 struct kmem_cache *c;
1329 struct slabinfo sinfo;
1331 if (!is_root_cache(s))
1334 for_each_memcg_cache(c, s) {
1335 memset(&sinfo, 0, sizeof(sinfo));
1336 get_slabinfo(c, &sinfo);
1338 info->active_slabs += sinfo.active_slabs;
1339 info->num_slabs += sinfo.num_slabs;
1340 info->shared_avail += sinfo.shared_avail;
1341 info->active_objs += sinfo.active_objs;
1342 info->num_objs += sinfo.num_objs;
1346 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1348 struct slabinfo sinfo;
1350 memset(&sinfo, 0, sizeof(sinfo));
1351 get_slabinfo(s, &sinfo);
1353 memcg_accumulate_slabinfo(s, &sinfo);
1355 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1356 cache_name(s), sinfo.active_objs, sinfo.num_objs, s->size,
1357 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1359 seq_printf(m, " : tunables %4u %4u %4u",
1360 sinfo.limit, sinfo.batchcount, sinfo.shared);
1361 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1362 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1363 slabinfo_show_stats(m, s);
1367 static int slab_show(struct seq_file *m, void *p)
1369 struct kmem_cache *s = list_entry(p, struct kmem_cache, root_caches_node);
1371 if (p == slab_root_caches.next)
1372 print_slabinfo_header(m);
1377 void dump_unreclaimable_slab(void)
1379 struct kmem_cache *s, *s2;
1380 struct slabinfo sinfo;
1383 * Here acquiring slab_mutex is risky since we don't prefer to get
1384 * sleep in oom path. But, without mutex hold, it may introduce a
1386 * Use mutex_trylock to protect the list traverse, dump nothing
1387 * without acquiring the mutex.
1389 if (!mutex_trylock(&slab_mutex)) {
1390 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1394 pr_info("Unreclaimable slab info:\n");
1395 pr_info("Name Used Total\n");
1397 list_for_each_entry_safe(s, s2, &slab_caches, list) {
1398 if (!is_root_cache(s) || (s->flags & SLAB_RECLAIM_ACCOUNT))
1401 get_slabinfo(s, &sinfo);
1403 if (sinfo.num_objs > 0)
1404 pr_info("%-17s %10luKB %10luKB\n", cache_name(s),
1405 (sinfo.active_objs * s->size) / 1024,
1406 (sinfo.num_objs * s->size) / 1024);
1408 mutex_unlock(&slab_mutex);
1411 #if defined(CONFIG_MEMCG)
1412 void *memcg_slab_start(struct seq_file *m, loff_t *pos)
1414 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1416 mutex_lock(&slab_mutex);
1417 return seq_list_start(&memcg->kmem_caches, *pos);
1420 void *memcg_slab_next(struct seq_file *m, void *p, loff_t *pos)
1422 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1424 return seq_list_next(p, &memcg->kmem_caches, pos);
1427 void memcg_slab_stop(struct seq_file *m, void *p)
1429 mutex_unlock(&slab_mutex);
1432 int memcg_slab_show(struct seq_file *m, void *p)
1434 struct kmem_cache *s = list_entry(p, struct kmem_cache,
1435 memcg_params.kmem_caches_node);
1436 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1438 if (p == memcg->kmem_caches.next)
1439 print_slabinfo_header(m);
1446 * slabinfo_op - iterator that generates /proc/slabinfo
1455 * num-pages-per-slab
1456 * + further values on SMP and with statistics enabled
1458 static const struct seq_operations slabinfo_op = {
1459 .start = slab_start,
1465 static int slabinfo_open(struct inode *inode, struct file *file)
1467 return seq_open(file, &slabinfo_op);
1470 static const struct file_operations proc_slabinfo_operations = {
1471 .open = slabinfo_open,
1473 .write = slabinfo_write,
1474 .llseek = seq_lseek,
1475 .release = seq_release,
1478 static int __init slab_proc_init(void)
1480 proc_create("slabinfo", SLABINFO_RIGHTS, NULL,
1481 &proc_slabinfo_operations);
1484 module_init(slab_proc_init);
1485 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1487 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1496 if (ks >= new_size) {
1497 kasan_krealloc((void *)p, new_size, flags);
1501 ret = kmalloc_track_caller(new_size, flags);
1509 * __krealloc - like krealloc() but don't free @p.
1510 * @p: object to reallocate memory for.
1511 * @new_size: how many bytes of memory are required.
1512 * @flags: the type of memory to allocate.
1514 * This function is like krealloc() except it never frees the originally
1515 * allocated buffer. Use this if you don't want to free the buffer immediately
1516 * like, for example, with RCU.
1518 void *__krealloc(const void *p, size_t new_size, gfp_t flags)
1520 if (unlikely(!new_size))
1521 return ZERO_SIZE_PTR;
1523 return __do_krealloc(p, new_size, flags);
1526 EXPORT_SYMBOL(__krealloc);
1529 * krealloc - reallocate memory. The contents will remain unchanged.
1530 * @p: object to reallocate memory for.
1531 * @new_size: how many bytes of memory are required.
1532 * @flags: the type of memory to allocate.
1534 * The contents of the object pointed to are preserved up to the
1535 * lesser of the new and old sizes. If @p is %NULL, krealloc()
1536 * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
1537 * %NULL pointer, the object pointed to is freed.
1539 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1543 if (unlikely(!new_size)) {
1545 return ZERO_SIZE_PTR;
1548 ret = __do_krealloc(p, new_size, flags);
1549 if (ret && p != ret)
1554 EXPORT_SYMBOL(krealloc);
1557 * kzfree - like kfree but zero memory
1558 * @p: object to free memory of
1560 * The memory of the object @p points to is zeroed before freed.
1561 * If @p is %NULL, kzfree() does nothing.
1563 * Note: this function zeroes the whole allocated buffer which can be a good
1564 * deal bigger than the requested buffer size passed to kmalloc(). So be
1565 * careful when using this function in performance sensitive code.
1567 void kzfree(const void *p)
1570 void *mem = (void *)p;
1572 if (unlikely(ZERO_OR_NULL_PTR(mem)))
1575 memzero_explicit(mem, ks);
1578 EXPORT_SYMBOL(kzfree);
1580 /* Tracepoints definitions. */
1581 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1582 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1583 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1584 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1585 EXPORT_TRACEPOINT_SYMBOL(kfree);
1586 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1588 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1590 if (__should_failslab(s, gfpflags))
1594 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);