1 // SPDX-License-Identifier: GPL-2.0
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
6 * The allocator synchronizes using per slab locks or atomic operations
7 * and only uses a centralized lock to manage a pool of partial slabs.
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
14 #include <linux/swap.h> /* struct reclaim_state */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
22 #include <linux/proc_fs.h>
23 #include <linux/seq_file.h>
24 #include <linux/kasan.h>
25 #include <linux/cpu.h>
26 #include <linux/cpuset.h>
27 #include <linux/mempolicy.h>
28 #include <linux/ctype.h>
29 #include <linux/debugobjects.h>
30 #include <linux/kallsyms.h>
31 #include <linux/kfence.h>
32 #include <linux/memory.h>
33 #include <linux/math64.h>
34 #include <linux/fault-inject.h>
35 #include <linux/stacktrace.h>
36 #include <linux/prefetch.h>
37 #include <linux/memcontrol.h>
38 #include <linux/random.h>
39 #include <kunit/test.h>
41 #include <trace/events/kmem.h>
47 * 1. slab_mutex (Global Mutex)
49 * 3. slab_lock(page) (Only on some arches and for debugging)
53 * The role of the slab_mutex is to protect the list of all the slabs
54 * and to synchronize major metadata changes to slab cache structures.
56 * The slab_lock is only used for debugging and on arches that do not
57 * have the ability to do a cmpxchg_double. It only protects:
58 * A. page->freelist -> List of object free in a page
59 * B. page->inuse -> Number of objects in use
60 * C. page->objects -> Number of objects in page
61 * D. page->frozen -> frozen state
63 * If a slab is frozen then it is exempt from list management. It is not
64 * on any list except per cpu partial list. The processor that froze the
65 * slab is the one who can perform list operations on the page. Other
66 * processors may put objects onto the freelist but the processor that
67 * froze the slab is the only one that can retrieve the objects from the
70 * The list_lock protects the partial and full list on each node and
71 * the partial slab counter. If taken then no new slabs may be added or
72 * removed from the lists nor make the number of partial slabs be modified.
73 * (Note that the total number of slabs is an atomic value that may be
74 * modified without taking the list lock).
76 * The list_lock is a centralized lock and thus we avoid taking it as
77 * much as possible. As long as SLUB does not have to handle partial
78 * slabs, operations can continue without any centralized lock. F.e.
79 * allocating a long series of objects that fill up slabs does not require
81 * Interrupts are disabled during allocation and deallocation in order to
82 * make the slab allocator safe to use in the context of an irq. In addition
83 * interrupts are disabled to ensure that the processor does not change
84 * while handling per_cpu slabs, due to kernel preemption.
86 * SLUB assigns one slab for allocation to each processor.
87 * Allocations only occur from these slabs called cpu slabs.
89 * Slabs with free elements are kept on a partial list and during regular
90 * operations no list for full slabs is used. If an object in a full slab is
91 * freed then the slab will show up again on the partial lists.
92 * We track full slabs for debugging purposes though because otherwise we
93 * cannot scan all objects.
95 * Slabs are freed when they become empty. Teardown and setup is
96 * minimal so we rely on the page allocators per cpu caches for
97 * fast frees and allocs.
99 * page->frozen The slab is frozen and exempt from list processing.
100 * This means that the slab is dedicated to a purpose
101 * such as satisfying allocations for a specific
102 * processor. Objects may be freed in the slab while
103 * it is frozen but slab_free will then skip the usual
104 * list operations. It is up to the processor holding
105 * the slab to integrate the slab into the slab lists
106 * when the slab is no longer needed.
108 * One use of this flag is to mark slabs that are
109 * used for allocations. Then such a slab becomes a cpu
110 * slab. The cpu slab may be equipped with an additional
111 * freelist that allows lockless access to
112 * free objects in addition to the regular freelist
113 * that requires the slab lock.
115 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
116 * options set. This moves slab handling out of
117 * the fast path and disables lockless freelists.
120 #ifdef CONFIG_SLUB_DEBUG
121 #ifdef CONFIG_SLUB_DEBUG_ON
122 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
124 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
128 static inline bool kmem_cache_debug(struct kmem_cache *s)
130 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
133 void *fixup_red_left(struct kmem_cache *s, void *p)
135 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
136 p += s->red_left_pad;
141 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
143 #ifdef CONFIG_SLUB_CPU_PARTIAL
144 return !kmem_cache_debug(s);
151 * Issues still to be resolved:
153 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
155 * - Variable sizing of the per node arrays
158 /* Enable to test recovery from slab corruption on boot */
159 #undef SLUB_RESILIENCY_TEST
161 /* Enable to log cmpxchg failures */
162 #undef SLUB_DEBUG_CMPXCHG
165 * Minimum number of partial slabs. These will be left on the partial
166 * lists even if they are empty. kmem_cache_shrink may reclaim them.
168 #define MIN_PARTIAL 5
171 * Maximum number of desirable partial slabs.
172 * The existence of more partial slabs makes kmem_cache_shrink
173 * sort the partial list by the number of objects in use.
175 #define MAX_PARTIAL 10
177 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
178 SLAB_POISON | SLAB_STORE_USER)
181 * These debug flags cannot use CMPXCHG because there might be consistency
182 * issues when checking or reading debug information
184 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
189 * Debugging flags that require metadata to be stored in the slab. These get
190 * disabled when slub_debug=O is used and a cache's min order increases with
193 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
196 #define OO_MASK ((1 << OO_SHIFT) - 1)
197 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
199 /* Internal SLUB flags */
201 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
202 /* Use cmpxchg_double */
203 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
206 * Tracking user of a slab.
208 #define TRACK_ADDRS_COUNT 16
210 unsigned long addr; /* Called from address */
211 #ifdef CONFIG_STACKTRACE
212 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
214 int cpu; /* Was running on cpu */
215 int pid; /* Pid context */
216 unsigned long when; /* When did the operation occur */
219 enum track_item { TRACK_ALLOC, TRACK_FREE };
222 static int sysfs_slab_add(struct kmem_cache *);
223 static int sysfs_slab_alias(struct kmem_cache *, const char *);
225 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
226 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
230 static inline void stat(const struct kmem_cache *s, enum stat_item si)
232 #ifdef CONFIG_SLUB_STATS
234 * The rmw is racy on a preemptible kernel but this is acceptable, so
235 * avoid this_cpu_add()'s irq-disable overhead.
237 raw_cpu_inc(s->cpu_slab->stat[si]);
242 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
243 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
244 * differ during memory hotplug/hotremove operations.
245 * Protected by slab_mutex.
247 static nodemask_t slab_nodes;
249 /********************************************************************
250 * Core slab cache functions
251 *******************************************************************/
254 * Returns freelist pointer (ptr). With hardening, this is obfuscated
255 * with an XOR of the address where the pointer is held and a per-cache
258 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
259 unsigned long ptr_addr)
261 #ifdef CONFIG_SLAB_FREELIST_HARDENED
263 * When CONFIG_KASAN_SW/HW_TAGS is enabled, ptr_addr might be tagged.
264 * Normally, this doesn't cause any issues, as both set_freepointer()
265 * and get_freepointer() are called with a pointer with the same tag.
266 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
267 * example, when __free_slub() iterates over objects in a cache, it
268 * passes untagged pointers to check_object(). check_object() in turns
269 * calls get_freepointer() with an untagged pointer, which causes the
270 * freepointer to be restored incorrectly.
272 return (void *)((unsigned long)ptr ^ s->random ^
273 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
279 /* Returns the freelist pointer recorded at location ptr_addr. */
280 static inline void *freelist_dereference(const struct kmem_cache *s,
283 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
284 (unsigned long)ptr_addr);
287 static inline void *get_freepointer(struct kmem_cache *s, void *object)
289 object = kasan_reset_tag(object);
290 return freelist_dereference(s, object + s->offset);
293 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
295 prefetch(object + s->offset);
298 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
300 unsigned long freepointer_addr;
303 if (!debug_pagealloc_enabled_static())
304 return get_freepointer(s, object);
306 object = kasan_reset_tag(object);
307 freepointer_addr = (unsigned long)object + s->offset;
308 copy_from_kernel_nofault(&p, (void **)freepointer_addr, sizeof(p));
309 return freelist_ptr(s, p, freepointer_addr);
312 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
314 unsigned long freeptr_addr = (unsigned long)object + s->offset;
316 #ifdef CONFIG_SLAB_FREELIST_HARDENED
317 BUG_ON(object == fp); /* naive detection of double free or corruption */
320 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
321 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
324 /* Loop over all objects in a slab */
325 #define for_each_object(__p, __s, __addr, __objects) \
326 for (__p = fixup_red_left(__s, __addr); \
327 __p < (__addr) + (__objects) * (__s)->size; \
330 static inline unsigned int order_objects(unsigned int order, unsigned int size)
332 return ((unsigned int)PAGE_SIZE << order) / size;
335 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
338 struct kmem_cache_order_objects x = {
339 (order << OO_SHIFT) + order_objects(order, size)
345 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
347 return x.x >> OO_SHIFT;
350 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
352 return x.x & OO_MASK;
356 * Per slab locking using the pagelock
358 static __always_inline void slab_lock(struct page *page)
360 VM_BUG_ON_PAGE(PageTail(page), page);
361 bit_spin_lock(PG_locked, &page->flags);
364 static __always_inline void slab_unlock(struct page *page)
366 VM_BUG_ON_PAGE(PageTail(page), page);
367 __bit_spin_unlock(PG_locked, &page->flags);
370 /* Interrupts must be disabled (for the fallback code to work right) */
371 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
372 void *freelist_old, unsigned long counters_old,
373 void *freelist_new, unsigned long counters_new,
376 VM_BUG_ON(!irqs_disabled());
377 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
378 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
379 if (s->flags & __CMPXCHG_DOUBLE) {
380 if (cmpxchg_double(&page->freelist, &page->counters,
381 freelist_old, counters_old,
382 freelist_new, counters_new))
388 if (page->freelist == freelist_old &&
389 page->counters == counters_old) {
390 page->freelist = freelist_new;
391 page->counters = counters_new;
399 stat(s, CMPXCHG_DOUBLE_FAIL);
401 #ifdef SLUB_DEBUG_CMPXCHG
402 pr_info("%s %s: cmpxchg double redo ", n, s->name);
408 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
409 void *freelist_old, unsigned long counters_old,
410 void *freelist_new, unsigned long counters_new,
413 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
414 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
415 if (s->flags & __CMPXCHG_DOUBLE) {
416 if (cmpxchg_double(&page->freelist, &page->counters,
417 freelist_old, counters_old,
418 freelist_new, counters_new))
425 local_irq_save(flags);
427 if (page->freelist == freelist_old &&
428 page->counters == counters_old) {
429 page->freelist = freelist_new;
430 page->counters = counters_new;
432 local_irq_restore(flags);
436 local_irq_restore(flags);
440 stat(s, CMPXCHG_DOUBLE_FAIL);
442 #ifdef SLUB_DEBUG_CMPXCHG
443 pr_info("%s %s: cmpxchg double redo ", n, s->name);
449 #ifdef CONFIG_SLUB_DEBUG
450 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
451 static DEFINE_SPINLOCK(object_map_lock);
453 #if IS_ENABLED(CONFIG_KUNIT)
454 static bool slab_add_kunit_errors(void)
456 struct kunit_resource *resource;
458 if (likely(!current->kunit_test))
461 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
465 (*(int *)resource->data)++;
466 kunit_put_resource(resource);
470 static inline bool slab_add_kunit_errors(void) { return false; }
474 * Determine a map of object in use on a page.
476 * Node listlock must be held to guarantee that the page does
477 * not vanish from under us.
479 static unsigned long *get_map(struct kmem_cache *s, struct page *page)
480 __acquires(&object_map_lock)
483 void *addr = page_address(page);
485 VM_BUG_ON(!irqs_disabled());
487 spin_lock(&object_map_lock);
489 bitmap_zero(object_map, page->objects);
491 for (p = page->freelist; p; p = get_freepointer(s, p))
492 set_bit(__obj_to_index(s, addr, p), object_map);
497 static void put_map(unsigned long *map) __releases(&object_map_lock)
499 VM_BUG_ON(map != object_map);
500 spin_unlock(&object_map_lock);
503 static inline unsigned int size_from_object(struct kmem_cache *s)
505 if (s->flags & SLAB_RED_ZONE)
506 return s->size - s->red_left_pad;
511 static inline void *restore_red_left(struct kmem_cache *s, void *p)
513 if (s->flags & SLAB_RED_ZONE)
514 p -= s->red_left_pad;
522 #if defined(CONFIG_SLUB_DEBUG_ON)
523 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
525 static slab_flags_t slub_debug;
528 static char *slub_debug_string;
529 static int disable_higher_order_debug;
532 * slub is about to manipulate internal object metadata. This memory lies
533 * outside the range of the allocated object, so accessing it would normally
534 * be reported by kasan as a bounds error. metadata_access_enable() is used
535 * to tell kasan that these accesses are OK.
537 static inline void metadata_access_enable(void)
539 kasan_disable_current();
542 static inline void metadata_access_disable(void)
544 kasan_enable_current();
551 /* Verify that a pointer has an address that is valid within a slab page */
552 static inline int check_valid_pointer(struct kmem_cache *s,
553 struct page *page, void *object)
560 base = page_address(page);
561 object = kasan_reset_tag(object);
562 object = restore_red_left(s, object);
563 if (object < base || object >= base + page->objects * s->size ||
564 (object - base) % s->size) {
571 static void print_section(char *level, char *text, u8 *addr,
574 metadata_access_enable();
575 print_hex_dump(level, kasan_reset_tag(text), DUMP_PREFIX_ADDRESS,
576 16, 1, addr, length, 1);
577 metadata_access_disable();
581 * See comment in calculate_sizes().
583 static inline bool freeptr_outside_object(struct kmem_cache *s)
585 return s->offset >= s->inuse;
589 * Return offset of the end of info block which is inuse + free pointer if
590 * not overlapping with object.
592 static inline unsigned int get_info_end(struct kmem_cache *s)
594 if (freeptr_outside_object(s))
595 return s->inuse + sizeof(void *);
600 static struct track *get_track(struct kmem_cache *s, void *object,
601 enum track_item alloc)
605 p = object + get_info_end(s);
607 return kasan_reset_tag(p + alloc);
610 static void set_track(struct kmem_cache *s, void *object,
611 enum track_item alloc, unsigned long addr)
613 struct track *p = get_track(s, object, alloc);
616 #ifdef CONFIG_STACKTRACE
617 unsigned int nr_entries;
619 metadata_access_enable();
620 nr_entries = stack_trace_save(kasan_reset_tag(p->addrs),
621 TRACK_ADDRS_COUNT, 3);
622 metadata_access_disable();
624 if (nr_entries < TRACK_ADDRS_COUNT)
625 p->addrs[nr_entries] = 0;
628 p->cpu = smp_processor_id();
629 p->pid = current->pid;
632 memset(p, 0, sizeof(struct track));
636 static void init_tracking(struct kmem_cache *s, void *object)
638 if (!(s->flags & SLAB_STORE_USER))
641 set_track(s, object, TRACK_FREE, 0UL);
642 set_track(s, object, TRACK_ALLOC, 0UL);
645 static void print_track(const char *s, struct track *t, unsigned long pr_time)
650 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
651 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
652 #ifdef CONFIG_STACKTRACE
655 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
657 pr_err("\t%pS\n", (void *)t->addrs[i]);
664 void print_tracking(struct kmem_cache *s, void *object)
666 unsigned long pr_time = jiffies;
667 if (!(s->flags & SLAB_STORE_USER))
670 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
671 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
674 static void print_page_info(struct page *page)
676 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%#lx(%pGp)\n",
677 page, page->objects, page->inuse, page->freelist,
678 page->flags, &page->flags);
682 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
684 struct va_format vaf;
690 pr_err("=============================================================================\n");
691 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
692 pr_err("-----------------------------------------------------------------------------\n\n");
694 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
698 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
700 struct va_format vaf;
703 if (slab_add_kunit_errors())
709 pr_err("FIX %s: %pV\n", s->name, &vaf);
713 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
714 void **freelist, void *nextfree)
716 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
717 !check_valid_pointer(s, page, nextfree) && freelist) {
718 object_err(s, page, *freelist, "Freechain corrupt");
720 slab_fix(s, "Isolate corrupted freechain");
727 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
729 unsigned int off; /* Offset of last byte */
730 u8 *addr = page_address(page);
732 print_tracking(s, p);
734 print_page_info(page);
736 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
737 p, p - addr, get_freepointer(s, p));
739 if (s->flags & SLAB_RED_ZONE)
740 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
742 else if (p > addr + 16)
743 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
745 print_section(KERN_ERR, "Object ", p,
746 min_t(unsigned int, s->object_size, PAGE_SIZE));
747 if (s->flags & SLAB_RED_ZONE)
748 print_section(KERN_ERR, "Redzone ", p + s->object_size,
749 s->inuse - s->object_size);
751 off = get_info_end(s);
753 if (s->flags & SLAB_STORE_USER)
754 off += 2 * sizeof(struct track);
756 off += kasan_metadata_size(s);
758 if (off != size_from_object(s))
759 /* Beginning of the filler is the free pointer */
760 print_section(KERN_ERR, "Padding ", p + off,
761 size_from_object(s) - off);
766 void object_err(struct kmem_cache *s, struct page *page,
767 u8 *object, char *reason)
769 if (slab_add_kunit_errors())
772 slab_bug(s, "%s", reason);
773 print_trailer(s, page, object);
776 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
777 const char *fmt, ...)
782 if (slab_add_kunit_errors())
786 vsnprintf(buf, sizeof(buf), fmt, args);
788 slab_bug(s, "%s", buf);
789 print_page_info(page);
793 static void init_object(struct kmem_cache *s, void *object, u8 val)
795 u8 *p = kasan_reset_tag(object);
797 if (s->flags & SLAB_RED_ZONE)
798 memset(p - s->red_left_pad, val, s->red_left_pad);
800 if (s->flags & __OBJECT_POISON) {
801 memset(p, POISON_FREE, s->object_size - 1);
802 p[s->object_size - 1] = POISON_END;
805 if (s->flags & SLAB_RED_ZONE)
806 memset(p + s->object_size, val, s->inuse - s->object_size);
809 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
810 void *from, void *to)
812 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
813 memset(from, data, to - from);
816 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
817 u8 *object, char *what,
818 u8 *start, unsigned int value, unsigned int bytes)
822 u8 *addr = page_address(page);
824 metadata_access_enable();
825 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
826 metadata_access_disable();
831 while (end > fault && end[-1] == value)
834 if (slab_add_kunit_errors())
837 slab_bug(s, "%s overwritten", what);
838 pr_err("0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
839 fault, end - 1, fault - addr,
841 print_trailer(s, page, object);
844 restore_bytes(s, what, value, fault, end);
852 * Bytes of the object to be managed.
853 * If the freepointer may overlay the object then the free
854 * pointer is at the middle of the object.
856 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
859 * object + s->object_size
860 * Padding to reach word boundary. This is also used for Redzoning.
861 * Padding is extended by another word if Redzoning is enabled and
862 * object_size == inuse.
864 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
865 * 0xcc (RED_ACTIVE) for objects in use.
868 * Meta data starts here.
870 * A. Free pointer (if we cannot overwrite object on free)
871 * B. Tracking data for SLAB_STORE_USER
872 * C. Padding to reach required alignment boundary or at minimum
873 * one word if debugging is on to be able to detect writes
874 * before the word boundary.
876 * Padding is done using 0x5a (POISON_INUSE)
879 * Nothing is used beyond s->size.
881 * If slabcaches are merged then the object_size and inuse boundaries are mostly
882 * ignored. And therefore no slab options that rely on these boundaries
883 * may be used with merged slabcaches.
886 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
888 unsigned long off = get_info_end(s); /* The end of info */
890 if (s->flags & SLAB_STORE_USER)
891 /* We also have user information there */
892 off += 2 * sizeof(struct track);
894 off += kasan_metadata_size(s);
896 if (size_from_object(s) == off)
899 return check_bytes_and_report(s, page, p, "Object padding",
900 p + off, POISON_INUSE, size_from_object(s) - off);
903 /* Check the pad bytes at the end of a slab page */
904 static int slab_pad_check(struct kmem_cache *s, struct page *page)
913 if (!(s->flags & SLAB_POISON))
916 start = page_address(page);
917 length = page_size(page);
918 end = start + length;
919 remainder = length % s->size;
923 pad = end - remainder;
924 metadata_access_enable();
925 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
926 metadata_access_disable();
929 while (end > fault && end[-1] == POISON_INUSE)
932 slab_err(s, page, "Padding overwritten. 0x%p-0x%p @offset=%tu",
933 fault, end - 1, fault - start);
934 print_section(KERN_ERR, "Padding ", pad, remainder);
936 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
940 static int check_object(struct kmem_cache *s, struct page *page,
941 void *object, u8 val)
944 u8 *endobject = object + s->object_size;
946 if (s->flags & SLAB_RED_ZONE) {
947 if (!check_bytes_and_report(s, page, object, "Left Redzone",
948 object - s->red_left_pad, val, s->red_left_pad))
951 if (!check_bytes_and_report(s, page, object, "Right Redzone",
952 endobject, val, s->inuse - s->object_size))
955 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
956 check_bytes_and_report(s, page, p, "Alignment padding",
957 endobject, POISON_INUSE,
958 s->inuse - s->object_size);
962 if (s->flags & SLAB_POISON) {
963 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
964 (!check_bytes_and_report(s, page, p, "Poison", p,
965 POISON_FREE, s->object_size - 1) ||
966 !check_bytes_and_report(s, page, p, "End Poison",
967 p + s->object_size - 1, POISON_END, 1)))
970 * check_pad_bytes cleans up on its own.
972 check_pad_bytes(s, page, p);
975 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
977 * Object and freepointer overlap. Cannot check
978 * freepointer while object is allocated.
982 /* Check free pointer validity */
983 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
984 object_err(s, page, p, "Freepointer corrupt");
986 * No choice but to zap it and thus lose the remainder
987 * of the free objects in this slab. May cause
988 * another error because the object count is now wrong.
990 set_freepointer(s, p, NULL);
996 static int check_slab(struct kmem_cache *s, struct page *page)
1000 VM_BUG_ON(!irqs_disabled());
1002 if (!PageSlab(page)) {
1003 slab_err(s, page, "Not a valid slab page");
1007 maxobj = order_objects(compound_order(page), s->size);
1008 if (page->objects > maxobj) {
1009 slab_err(s, page, "objects %u > max %u",
1010 page->objects, maxobj);
1013 if (page->inuse > page->objects) {
1014 slab_err(s, page, "inuse %u > max %u",
1015 page->inuse, page->objects);
1018 /* Slab_pad_check fixes things up after itself */
1019 slab_pad_check(s, page);
1024 * Determine if a certain object on a page is on the freelist. Must hold the
1025 * slab lock to guarantee that the chains are in a consistent state.
1027 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
1031 void *object = NULL;
1034 fp = page->freelist;
1035 while (fp && nr <= page->objects) {
1038 if (!check_valid_pointer(s, page, fp)) {
1040 object_err(s, page, object,
1041 "Freechain corrupt");
1042 set_freepointer(s, object, NULL);
1044 slab_err(s, page, "Freepointer corrupt");
1045 page->freelist = NULL;
1046 page->inuse = page->objects;
1047 slab_fix(s, "Freelist cleared");
1053 fp = get_freepointer(s, object);
1057 max_objects = order_objects(compound_order(page), s->size);
1058 if (max_objects > MAX_OBJS_PER_PAGE)
1059 max_objects = MAX_OBJS_PER_PAGE;
1061 if (page->objects != max_objects) {
1062 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1063 page->objects, max_objects);
1064 page->objects = max_objects;
1065 slab_fix(s, "Number of objects adjusted.");
1067 if (page->inuse != page->objects - nr) {
1068 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1069 page->inuse, page->objects - nr);
1070 page->inuse = page->objects - nr;
1071 slab_fix(s, "Object count adjusted.");
1073 return search == NULL;
1076 static void trace(struct kmem_cache *s, struct page *page, void *object,
1079 if (s->flags & SLAB_TRACE) {
1080 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1082 alloc ? "alloc" : "free",
1083 object, page->inuse,
1087 print_section(KERN_INFO, "Object ", (void *)object,
1095 * Tracking of fully allocated slabs for debugging purposes.
1097 static void add_full(struct kmem_cache *s,
1098 struct kmem_cache_node *n, struct page *page)
1100 if (!(s->flags & SLAB_STORE_USER))
1103 lockdep_assert_held(&n->list_lock);
1104 list_add(&page->slab_list, &n->full);
1107 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1109 if (!(s->flags & SLAB_STORE_USER))
1112 lockdep_assert_held(&n->list_lock);
1113 list_del(&page->slab_list);
1116 /* Tracking of the number of slabs for debugging purposes */
1117 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1119 struct kmem_cache_node *n = get_node(s, node);
1121 return atomic_long_read(&n->nr_slabs);
1124 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1126 return atomic_long_read(&n->nr_slabs);
1129 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1131 struct kmem_cache_node *n = get_node(s, node);
1134 * May be called early in order to allocate a slab for the
1135 * kmem_cache_node structure. Solve the chicken-egg
1136 * dilemma by deferring the increment of the count during
1137 * bootstrap (see early_kmem_cache_node_alloc).
1140 atomic_long_inc(&n->nr_slabs);
1141 atomic_long_add(objects, &n->total_objects);
1144 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1146 struct kmem_cache_node *n = get_node(s, node);
1148 atomic_long_dec(&n->nr_slabs);
1149 atomic_long_sub(objects, &n->total_objects);
1152 /* Object debug checks for alloc/free paths */
1153 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1156 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1159 init_object(s, object, SLUB_RED_INACTIVE);
1160 init_tracking(s, object);
1164 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1166 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1169 metadata_access_enable();
1170 memset(kasan_reset_tag(addr), POISON_INUSE, page_size(page));
1171 metadata_access_disable();
1174 static inline int alloc_consistency_checks(struct kmem_cache *s,
1175 struct page *page, void *object)
1177 if (!check_slab(s, page))
1180 if (!check_valid_pointer(s, page, object)) {
1181 object_err(s, page, object, "Freelist Pointer check fails");
1185 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1191 static noinline int alloc_debug_processing(struct kmem_cache *s,
1193 void *object, unsigned long addr)
1195 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1196 if (!alloc_consistency_checks(s, page, object))
1200 /* Success perform special debug activities for allocs */
1201 if (s->flags & SLAB_STORE_USER)
1202 set_track(s, object, TRACK_ALLOC, addr);
1203 trace(s, page, object, 1);
1204 init_object(s, object, SLUB_RED_ACTIVE);
1208 if (PageSlab(page)) {
1210 * If this is a slab page then lets do the best we can
1211 * to avoid issues in the future. Marking all objects
1212 * as used avoids touching the remaining objects.
1214 slab_fix(s, "Marking all objects used");
1215 page->inuse = page->objects;
1216 page->freelist = NULL;
1221 static inline int free_consistency_checks(struct kmem_cache *s,
1222 struct page *page, void *object, unsigned long addr)
1224 if (!check_valid_pointer(s, page, object)) {
1225 slab_err(s, page, "Invalid object pointer 0x%p", object);
1229 if (on_freelist(s, page, object)) {
1230 object_err(s, page, object, "Object already free");
1234 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1237 if (unlikely(s != page->slab_cache)) {
1238 if (!PageSlab(page)) {
1239 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1241 } else if (!page->slab_cache) {
1242 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1246 object_err(s, page, object,
1247 "page slab pointer corrupt.");
1253 /* Supports checking bulk free of a constructed freelist */
1254 static noinline int free_debug_processing(
1255 struct kmem_cache *s, struct page *page,
1256 void *head, void *tail, int bulk_cnt,
1259 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1260 void *object = head;
1262 unsigned long flags;
1265 spin_lock_irqsave(&n->list_lock, flags);
1268 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1269 if (!check_slab(s, page))
1276 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1277 if (!free_consistency_checks(s, page, object, addr))
1281 if (s->flags & SLAB_STORE_USER)
1282 set_track(s, object, TRACK_FREE, addr);
1283 trace(s, page, object, 0);
1284 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1285 init_object(s, object, SLUB_RED_INACTIVE);
1287 /* Reached end of constructed freelist yet? */
1288 if (object != tail) {
1289 object = get_freepointer(s, object);
1295 if (cnt != bulk_cnt)
1296 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1300 spin_unlock_irqrestore(&n->list_lock, flags);
1302 slab_fix(s, "Object at 0x%p not freed", object);
1307 * Parse a block of slub_debug options. Blocks are delimited by ';'
1309 * @str: start of block
1310 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1311 * @slabs: return start of list of slabs, or NULL when there's no list
1312 * @init: assume this is initial parsing and not per-kmem-create parsing
1314 * returns the start of next block if there's any, or NULL
1317 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1319 bool higher_order_disable = false;
1321 /* Skip any completely empty blocks */
1322 while (*str && *str == ';')
1327 * No options but restriction on slabs. This means full
1328 * debugging for slabs matching a pattern.
1330 *flags = DEBUG_DEFAULT_FLAGS;
1335 /* Determine which debug features should be switched on */
1336 for (; *str && *str != ',' && *str != ';'; str++) {
1337 switch (tolower(*str)) {
1342 *flags |= SLAB_CONSISTENCY_CHECKS;
1345 *flags |= SLAB_RED_ZONE;
1348 *flags |= SLAB_POISON;
1351 *flags |= SLAB_STORE_USER;
1354 *flags |= SLAB_TRACE;
1357 *flags |= SLAB_FAILSLAB;
1361 * Avoid enabling debugging on caches if its minimum
1362 * order would increase as a result.
1364 higher_order_disable = true;
1368 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
1377 /* Skip over the slab list */
1378 while (*str && *str != ';')
1381 /* Skip any completely empty blocks */
1382 while (*str && *str == ';')
1385 if (init && higher_order_disable)
1386 disable_higher_order_debug = 1;
1394 static int __init setup_slub_debug(char *str)
1399 bool global_slub_debug_changed = false;
1400 bool slab_list_specified = false;
1402 slub_debug = DEBUG_DEFAULT_FLAGS;
1403 if (*str++ != '=' || !*str)
1405 * No options specified. Switch on full debugging.
1411 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1415 global_slub_debug_changed = true;
1417 slab_list_specified = true;
1422 * For backwards compatibility, a single list of flags with list of
1423 * slabs means debugging is only enabled for those slabs, so the global
1424 * slub_debug should be 0. We can extended that to multiple lists as
1425 * long as there is no option specifying flags without a slab list.
1427 if (slab_list_specified) {
1428 if (!global_slub_debug_changed)
1430 slub_debug_string = saved_str;
1433 if (slub_debug != 0 || slub_debug_string)
1434 static_branch_enable(&slub_debug_enabled);
1435 if ((static_branch_unlikely(&init_on_alloc) ||
1436 static_branch_unlikely(&init_on_free)) &&
1437 (slub_debug & SLAB_POISON))
1438 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1442 __setup("slub_debug", setup_slub_debug);
1445 * kmem_cache_flags - apply debugging options to the cache
1446 * @object_size: the size of an object without meta data
1447 * @flags: flags to set
1448 * @name: name of the cache
1450 * Debug option(s) are applied to @flags. In addition to the debug
1451 * option(s), if a slab name (or multiple) is specified i.e.
1452 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1453 * then only the select slabs will receive the debug option(s).
1455 slab_flags_t kmem_cache_flags(unsigned int object_size,
1456 slab_flags_t flags, const char *name)
1461 slab_flags_t block_flags;
1462 slab_flags_t slub_debug_local = slub_debug;
1465 * If the slab cache is for debugging (e.g. kmemleak) then
1466 * don't store user (stack trace) information by default,
1467 * but let the user enable it via the command line below.
1469 if (flags & SLAB_NOLEAKTRACE)
1470 slub_debug_local &= ~SLAB_STORE_USER;
1473 next_block = slub_debug_string;
1474 /* Go through all blocks of debug options, see if any matches our slab's name */
1475 while (next_block) {
1476 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1479 /* Found a block that has a slab list, search it */
1484 end = strchrnul(iter, ',');
1485 if (next_block && next_block < end)
1486 end = next_block - 1;
1488 glob = strnchr(iter, end - iter, '*');
1490 cmplen = glob - iter;
1492 cmplen = max_t(size_t, len, (end - iter));
1494 if (!strncmp(name, iter, cmplen)) {
1495 flags |= block_flags;
1499 if (!*end || *end == ';')
1505 return flags | slub_debug_local;
1507 #else /* !CONFIG_SLUB_DEBUG */
1508 static inline void setup_object_debug(struct kmem_cache *s,
1509 struct page *page, void *object) {}
1511 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1513 static inline int alloc_debug_processing(struct kmem_cache *s,
1514 struct page *page, void *object, unsigned long addr) { return 0; }
1516 static inline int free_debug_processing(
1517 struct kmem_cache *s, struct page *page,
1518 void *head, void *tail, int bulk_cnt,
1519 unsigned long addr) { return 0; }
1521 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1523 static inline int check_object(struct kmem_cache *s, struct page *page,
1524 void *object, u8 val) { return 1; }
1525 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1526 struct page *page) {}
1527 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1528 struct page *page) {}
1529 slab_flags_t kmem_cache_flags(unsigned int object_size,
1530 slab_flags_t flags, const char *name)
1534 #define slub_debug 0
1536 #define disable_higher_order_debug 0
1538 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1540 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1542 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1544 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1547 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1548 void **freelist, void *nextfree)
1552 #endif /* CONFIG_SLUB_DEBUG */
1555 * Hooks for other subsystems that check memory allocations. In a typical
1556 * production configuration these hooks all should produce no code at all.
1558 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1560 ptr = kasan_kmalloc_large(ptr, size, flags);
1561 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1562 kmemleak_alloc(ptr, size, 1, flags);
1566 static __always_inline void kfree_hook(void *x)
1569 kasan_kfree_large(x);
1572 static __always_inline bool slab_free_hook(struct kmem_cache *s,
1575 kmemleak_free_recursive(x, s->flags);
1578 * Trouble is that we may no longer disable interrupts in the fast path
1579 * So in order to make the debug calls that expect irqs to be
1580 * disabled we need to disable interrupts temporarily.
1582 #ifdef CONFIG_LOCKDEP
1584 unsigned long flags;
1586 local_irq_save(flags);
1587 debug_check_no_locks_freed(x, s->object_size);
1588 local_irq_restore(flags);
1591 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1592 debug_check_no_obj_freed(x, s->object_size);
1594 /* Use KCSAN to help debug racy use-after-free. */
1595 if (!(s->flags & SLAB_TYPESAFE_BY_RCU))
1596 __kcsan_check_access(x, s->object_size,
1597 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
1600 * As memory initialization might be integrated into KASAN,
1601 * kasan_slab_free and initialization memset's must be
1602 * kept together to avoid discrepancies in behavior.
1604 * The initialization memset's clear the object and the metadata,
1605 * but don't touch the SLAB redzone.
1610 if (!kasan_has_integrated_init())
1611 memset(kasan_reset_tag(x), 0, s->object_size);
1612 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
1613 memset((char *)kasan_reset_tag(x) + s->inuse, 0,
1614 s->size - s->inuse - rsize);
1616 /* KASAN might put x into memory quarantine, delaying its reuse. */
1617 return kasan_slab_free(s, x, init);
1620 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1621 void **head, void **tail)
1626 void *old_tail = *tail ? *tail : *head;
1628 if (is_kfence_address(next)) {
1629 slab_free_hook(s, next, false);
1633 /* Head and tail of the reconstructed freelist */
1639 next = get_freepointer(s, object);
1641 /* If object's reuse doesn't have to be delayed */
1642 if (!slab_free_hook(s, object, slab_want_init_on_free(s))) {
1643 /* Move object to the new freelist */
1644 set_freepointer(s, object, *head);
1649 } while (object != old_tail);
1654 return *head != NULL;
1657 static void *setup_object(struct kmem_cache *s, struct page *page,
1660 setup_object_debug(s, page, object);
1661 object = kasan_init_slab_obj(s, object);
1662 if (unlikely(s->ctor)) {
1663 kasan_unpoison_object_data(s, object);
1665 kasan_poison_object_data(s, object);
1671 * Slab allocation and freeing
1673 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1674 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1677 unsigned int order = oo_order(oo);
1679 if (node == NUMA_NO_NODE)
1680 page = alloc_pages(flags, order);
1682 page = __alloc_pages_node(node, flags, order);
1687 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1688 /* Pre-initialize the random sequence cache */
1689 static int init_cache_random_seq(struct kmem_cache *s)
1691 unsigned int count = oo_objects(s->oo);
1694 /* Bailout if already initialised */
1698 err = cache_random_seq_create(s, count, GFP_KERNEL);
1700 pr_err("SLUB: Unable to initialize free list for %s\n",
1705 /* Transform to an offset on the set of pages */
1706 if (s->random_seq) {
1709 for (i = 0; i < count; i++)
1710 s->random_seq[i] *= s->size;
1715 /* Initialize each random sequence freelist per cache */
1716 static void __init init_freelist_randomization(void)
1718 struct kmem_cache *s;
1720 mutex_lock(&slab_mutex);
1722 list_for_each_entry(s, &slab_caches, list)
1723 init_cache_random_seq(s);
1725 mutex_unlock(&slab_mutex);
1728 /* Get the next entry on the pre-computed freelist randomized */
1729 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1730 unsigned long *pos, void *start,
1731 unsigned long page_limit,
1732 unsigned long freelist_count)
1737 * If the target page allocation failed, the number of objects on the
1738 * page might be smaller than the usual size defined by the cache.
1741 idx = s->random_seq[*pos];
1743 if (*pos >= freelist_count)
1745 } while (unlikely(idx >= page_limit));
1747 return (char *)start + idx;
1750 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1751 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1756 unsigned long idx, pos, page_limit, freelist_count;
1758 if (page->objects < 2 || !s->random_seq)
1761 freelist_count = oo_objects(s->oo);
1762 pos = get_random_int() % freelist_count;
1764 page_limit = page->objects * s->size;
1765 start = fixup_red_left(s, page_address(page));
1767 /* First entry is used as the base of the freelist */
1768 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1770 cur = setup_object(s, page, cur);
1771 page->freelist = cur;
1773 for (idx = 1; idx < page->objects; idx++) {
1774 next = next_freelist_entry(s, page, &pos, start, page_limit,
1776 next = setup_object(s, page, next);
1777 set_freepointer(s, cur, next);
1780 set_freepointer(s, cur, NULL);
1785 static inline int init_cache_random_seq(struct kmem_cache *s)
1789 static inline void init_freelist_randomization(void) { }
1790 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1794 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1796 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1799 struct kmem_cache_order_objects oo = s->oo;
1801 void *start, *p, *next;
1805 flags &= gfp_allowed_mask;
1807 if (gfpflags_allow_blocking(flags))
1810 flags |= s->allocflags;
1813 * Let the initial higher-order allocation fail under memory pressure
1814 * so we fall-back to the minimum order allocation.
1816 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1817 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1818 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1820 page = alloc_slab_page(s, alloc_gfp, node, oo);
1821 if (unlikely(!page)) {
1825 * Allocation may have failed due to fragmentation.
1826 * Try a lower order alloc if possible
1828 page = alloc_slab_page(s, alloc_gfp, node, oo);
1829 if (unlikely(!page))
1831 stat(s, ORDER_FALLBACK);
1834 page->objects = oo_objects(oo);
1836 account_slab_page(page, oo_order(oo), s, flags);
1838 page->slab_cache = s;
1839 __SetPageSlab(page);
1840 if (page_is_pfmemalloc(page))
1841 SetPageSlabPfmemalloc(page);
1843 kasan_poison_slab(page);
1845 start = page_address(page);
1847 setup_page_debug(s, page, start);
1849 shuffle = shuffle_freelist(s, page);
1852 start = fixup_red_left(s, start);
1853 start = setup_object(s, page, start);
1854 page->freelist = start;
1855 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1857 next = setup_object(s, page, next);
1858 set_freepointer(s, p, next);
1861 set_freepointer(s, p, NULL);
1864 page->inuse = page->objects;
1868 if (gfpflags_allow_blocking(flags))
1869 local_irq_disable();
1873 inc_slabs_node(s, page_to_nid(page), page->objects);
1878 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1880 if (unlikely(flags & GFP_SLAB_BUG_MASK))
1881 flags = kmalloc_fix_flags(flags);
1883 return allocate_slab(s,
1884 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1887 static void __free_slab(struct kmem_cache *s, struct page *page)
1889 int order = compound_order(page);
1890 int pages = 1 << order;
1892 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
1895 slab_pad_check(s, page);
1896 for_each_object(p, s, page_address(page),
1898 check_object(s, page, p, SLUB_RED_INACTIVE);
1901 __ClearPageSlabPfmemalloc(page);
1902 __ClearPageSlab(page);
1903 /* In union with page->mapping where page allocator expects NULL */
1904 page->slab_cache = NULL;
1905 if (current->reclaim_state)
1906 current->reclaim_state->reclaimed_slab += pages;
1907 unaccount_slab_page(page, order, s);
1908 __free_pages(page, order);
1911 static void rcu_free_slab(struct rcu_head *h)
1913 struct page *page = container_of(h, struct page, rcu_head);
1915 __free_slab(page->slab_cache, page);
1918 static void free_slab(struct kmem_cache *s, struct page *page)
1920 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1921 call_rcu(&page->rcu_head, rcu_free_slab);
1923 __free_slab(s, page);
1926 static void discard_slab(struct kmem_cache *s, struct page *page)
1928 dec_slabs_node(s, page_to_nid(page), page->objects);
1933 * Management of partially allocated slabs.
1936 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1939 if (tail == DEACTIVATE_TO_TAIL)
1940 list_add_tail(&page->slab_list, &n->partial);
1942 list_add(&page->slab_list, &n->partial);
1945 static inline void add_partial(struct kmem_cache_node *n,
1946 struct page *page, int tail)
1948 lockdep_assert_held(&n->list_lock);
1949 __add_partial(n, page, tail);
1952 static inline void remove_partial(struct kmem_cache_node *n,
1955 lockdep_assert_held(&n->list_lock);
1956 list_del(&page->slab_list);
1961 * Remove slab from the partial list, freeze it and
1962 * return the pointer to the freelist.
1964 * Returns a list of objects or NULL if it fails.
1966 static inline void *acquire_slab(struct kmem_cache *s,
1967 struct kmem_cache_node *n, struct page *page,
1968 int mode, int *objects)
1971 unsigned long counters;
1974 lockdep_assert_held(&n->list_lock);
1977 * Zap the freelist and set the frozen bit.
1978 * The old freelist is the list of objects for the
1979 * per cpu allocation list.
1981 freelist = page->freelist;
1982 counters = page->counters;
1983 new.counters = counters;
1984 *objects = new.objects - new.inuse;
1986 new.inuse = page->objects;
1987 new.freelist = NULL;
1989 new.freelist = freelist;
1992 VM_BUG_ON(new.frozen);
1995 if (!__cmpxchg_double_slab(s, page,
1997 new.freelist, new.counters,
2001 remove_partial(n, page);
2006 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
2007 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
2010 * Try to allocate a partial slab from a specific node.
2012 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
2013 struct kmem_cache_cpu *c, gfp_t flags)
2015 struct page *page, *page2;
2016 void *object = NULL;
2017 unsigned int available = 0;
2021 * Racy check. If we mistakenly see no partial slabs then we
2022 * just allocate an empty slab. If we mistakenly try to get a
2023 * partial slab and there is none available then get_partial()
2026 if (!n || !n->nr_partial)
2029 spin_lock(&n->list_lock);
2030 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
2033 if (!pfmemalloc_match(page, flags))
2036 t = acquire_slab(s, n, page, object == NULL, &objects);
2040 available += objects;
2043 stat(s, ALLOC_FROM_PARTIAL);
2046 put_cpu_partial(s, page, 0);
2047 stat(s, CPU_PARTIAL_NODE);
2049 if (!kmem_cache_has_cpu_partial(s)
2050 || available > slub_cpu_partial(s) / 2)
2054 spin_unlock(&n->list_lock);
2059 * Get a page from somewhere. Search in increasing NUMA distances.
2061 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
2062 struct kmem_cache_cpu *c)
2065 struct zonelist *zonelist;
2068 enum zone_type highest_zoneidx = gfp_zone(flags);
2070 unsigned int cpuset_mems_cookie;
2073 * The defrag ratio allows a configuration of the tradeoffs between
2074 * inter node defragmentation and node local allocations. A lower
2075 * defrag_ratio increases the tendency to do local allocations
2076 * instead of attempting to obtain partial slabs from other nodes.
2078 * If the defrag_ratio is set to 0 then kmalloc() always
2079 * returns node local objects. If the ratio is higher then kmalloc()
2080 * may return off node objects because partial slabs are obtained
2081 * from other nodes and filled up.
2083 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2084 * (which makes defrag_ratio = 1000) then every (well almost)
2085 * allocation will first attempt to defrag slab caches on other nodes.
2086 * This means scanning over all nodes to look for partial slabs which
2087 * may be expensive if we do it every time we are trying to find a slab
2088 * with available objects.
2090 if (!s->remote_node_defrag_ratio ||
2091 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2095 cpuset_mems_cookie = read_mems_allowed_begin();
2096 zonelist = node_zonelist(mempolicy_slab_node(), flags);
2097 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2098 struct kmem_cache_node *n;
2100 n = get_node(s, zone_to_nid(zone));
2102 if (n && cpuset_zone_allowed(zone, flags) &&
2103 n->nr_partial > s->min_partial) {
2104 object = get_partial_node(s, n, c, flags);
2107 * Don't check read_mems_allowed_retry()
2108 * here - if mems_allowed was updated in
2109 * parallel, that was a harmless race
2110 * between allocation and the cpuset
2117 } while (read_mems_allowed_retry(cpuset_mems_cookie));
2118 #endif /* CONFIG_NUMA */
2123 * Get a partial page, lock it and return it.
2125 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
2126 struct kmem_cache_cpu *c)
2129 int searchnode = node;
2131 if (node == NUMA_NO_NODE)
2132 searchnode = numa_mem_id();
2134 object = get_partial_node(s, get_node(s, searchnode), c, flags);
2135 if (object || node != NUMA_NO_NODE)
2138 return get_any_partial(s, flags, c);
2141 #ifdef CONFIG_PREEMPTION
2143 * Calculate the next globally unique transaction for disambiguation
2144 * during cmpxchg. The transactions start with the cpu number and are then
2145 * incremented by CONFIG_NR_CPUS.
2147 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2150 * No preemption supported therefore also no need to check for
2156 static inline unsigned long next_tid(unsigned long tid)
2158 return tid + TID_STEP;
2161 #ifdef SLUB_DEBUG_CMPXCHG
2162 static inline unsigned int tid_to_cpu(unsigned long tid)
2164 return tid % TID_STEP;
2167 static inline unsigned long tid_to_event(unsigned long tid)
2169 return tid / TID_STEP;
2173 static inline unsigned int init_tid(int cpu)
2178 static inline void note_cmpxchg_failure(const char *n,
2179 const struct kmem_cache *s, unsigned long tid)
2181 #ifdef SLUB_DEBUG_CMPXCHG
2182 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2184 pr_info("%s %s: cmpxchg redo ", n, s->name);
2186 #ifdef CONFIG_PREEMPTION
2187 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2188 pr_warn("due to cpu change %d -> %d\n",
2189 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2192 if (tid_to_event(tid) != tid_to_event(actual_tid))
2193 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2194 tid_to_event(tid), tid_to_event(actual_tid));
2196 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2197 actual_tid, tid, next_tid(tid));
2199 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2202 static void init_kmem_cache_cpus(struct kmem_cache *s)
2206 for_each_possible_cpu(cpu)
2207 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2211 * Remove the cpu slab
2213 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2214 void *freelist, struct kmem_cache_cpu *c)
2216 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2217 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2218 int lock = 0, free_delta = 0;
2219 enum slab_modes l = M_NONE, m = M_NONE;
2220 void *nextfree, *freelist_iter, *freelist_tail;
2221 int tail = DEACTIVATE_TO_HEAD;
2225 if (page->freelist) {
2226 stat(s, DEACTIVATE_REMOTE_FREES);
2227 tail = DEACTIVATE_TO_TAIL;
2231 * Stage one: Count the objects on cpu's freelist as free_delta and
2232 * remember the last object in freelist_tail for later splicing.
2234 freelist_tail = NULL;
2235 freelist_iter = freelist;
2236 while (freelist_iter) {
2237 nextfree = get_freepointer(s, freelist_iter);
2240 * If 'nextfree' is invalid, it is possible that the object at
2241 * 'freelist_iter' is already corrupted. So isolate all objects
2242 * starting at 'freelist_iter' by skipping them.
2244 if (freelist_corrupted(s, page, &freelist_iter, nextfree))
2247 freelist_tail = freelist_iter;
2250 freelist_iter = nextfree;
2254 * Stage two: Unfreeze the page while splicing the per-cpu
2255 * freelist to the head of page's freelist.
2257 * Ensure that the page is unfrozen while the list presence
2258 * reflects the actual number of objects during unfreeze.
2260 * We setup the list membership and then perform a cmpxchg
2261 * with the count. If there is a mismatch then the page
2262 * is not unfrozen but the page is on the wrong list.
2264 * Then we restart the process which may have to remove
2265 * the page from the list that we just put it on again
2266 * because the number of objects in the slab may have
2271 old.freelist = READ_ONCE(page->freelist);
2272 old.counters = READ_ONCE(page->counters);
2273 VM_BUG_ON(!old.frozen);
2275 /* Determine target state of the slab */
2276 new.counters = old.counters;
2277 if (freelist_tail) {
2278 new.inuse -= free_delta;
2279 set_freepointer(s, freelist_tail, old.freelist);
2280 new.freelist = freelist;
2282 new.freelist = old.freelist;
2286 if (!new.inuse && n->nr_partial >= s->min_partial)
2288 else if (new.freelist) {
2293 * Taking the spinlock removes the possibility
2294 * that acquire_slab() will see a slab page that
2297 spin_lock(&n->list_lock);
2301 if (kmem_cache_debug_flags(s, SLAB_STORE_USER) && !lock) {
2304 * This also ensures that the scanning of full
2305 * slabs from diagnostic functions will not see
2308 spin_lock(&n->list_lock);
2314 remove_partial(n, page);
2315 else if (l == M_FULL)
2316 remove_full(s, n, page);
2319 add_partial(n, page, tail);
2320 else if (m == M_FULL)
2321 add_full(s, n, page);
2325 if (!__cmpxchg_double_slab(s, page,
2326 old.freelist, old.counters,
2327 new.freelist, new.counters,
2332 spin_unlock(&n->list_lock);
2336 else if (m == M_FULL)
2337 stat(s, DEACTIVATE_FULL);
2338 else if (m == M_FREE) {
2339 stat(s, DEACTIVATE_EMPTY);
2340 discard_slab(s, page);
2349 * Unfreeze all the cpu partial slabs.
2351 * This function must be called with interrupts disabled
2352 * for the cpu using c (or some other guarantee must be there
2353 * to guarantee no concurrent accesses).
2355 static void unfreeze_partials(struct kmem_cache *s,
2356 struct kmem_cache_cpu *c)
2358 #ifdef CONFIG_SLUB_CPU_PARTIAL
2359 struct kmem_cache_node *n = NULL, *n2 = NULL;
2360 struct page *page, *discard_page = NULL;
2362 while ((page = slub_percpu_partial(c))) {
2366 slub_set_percpu_partial(c, page);
2368 n2 = get_node(s, page_to_nid(page));
2371 spin_unlock(&n->list_lock);
2374 spin_lock(&n->list_lock);
2379 old.freelist = page->freelist;
2380 old.counters = page->counters;
2381 VM_BUG_ON(!old.frozen);
2383 new.counters = old.counters;
2384 new.freelist = old.freelist;
2388 } while (!__cmpxchg_double_slab(s, page,
2389 old.freelist, old.counters,
2390 new.freelist, new.counters,
2391 "unfreezing slab"));
2393 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2394 page->next = discard_page;
2395 discard_page = page;
2397 add_partial(n, page, DEACTIVATE_TO_TAIL);
2398 stat(s, FREE_ADD_PARTIAL);
2403 spin_unlock(&n->list_lock);
2405 while (discard_page) {
2406 page = discard_page;
2407 discard_page = discard_page->next;
2409 stat(s, DEACTIVATE_EMPTY);
2410 discard_slab(s, page);
2413 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2417 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2418 * partial page slot if available.
2420 * If we did not find a slot then simply move all the partials to the
2421 * per node partial list.
2423 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2425 #ifdef CONFIG_SLUB_CPU_PARTIAL
2426 struct page *oldpage;
2434 oldpage = this_cpu_read(s->cpu_slab->partial);
2437 pobjects = oldpage->pobjects;
2438 pages = oldpage->pages;
2439 if (drain && pobjects > slub_cpu_partial(s)) {
2440 unsigned long flags;
2442 * partial array is full. Move the existing
2443 * set to the per node partial list.
2445 local_irq_save(flags);
2446 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2447 local_irq_restore(flags);
2451 stat(s, CPU_PARTIAL_DRAIN);
2456 pobjects += page->objects - page->inuse;
2458 page->pages = pages;
2459 page->pobjects = pobjects;
2460 page->next = oldpage;
2462 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2464 if (unlikely(!slub_cpu_partial(s))) {
2465 unsigned long flags;
2467 local_irq_save(flags);
2468 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2469 local_irq_restore(flags);
2472 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2475 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2477 stat(s, CPUSLAB_FLUSH);
2478 deactivate_slab(s, c->page, c->freelist, c);
2480 c->tid = next_tid(c->tid);
2486 * Called from IPI handler with interrupts disabled.
2488 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2490 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2495 unfreeze_partials(s, c);
2498 static void flush_cpu_slab(void *d)
2500 struct kmem_cache *s = d;
2502 __flush_cpu_slab(s, smp_processor_id());
2505 static bool has_cpu_slab(int cpu, void *info)
2507 struct kmem_cache *s = info;
2508 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2510 return c->page || slub_percpu_partial(c);
2513 static void flush_all(struct kmem_cache *s)
2515 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1);
2519 * Use the cpu notifier to insure that the cpu slabs are flushed when
2522 static int slub_cpu_dead(unsigned int cpu)
2524 struct kmem_cache *s;
2525 unsigned long flags;
2527 mutex_lock(&slab_mutex);
2528 list_for_each_entry(s, &slab_caches, list) {
2529 local_irq_save(flags);
2530 __flush_cpu_slab(s, cpu);
2531 local_irq_restore(flags);
2533 mutex_unlock(&slab_mutex);
2538 * Check if the objects in a per cpu structure fit numa
2539 * locality expectations.
2541 static inline int node_match(struct page *page, int node)
2544 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2550 #ifdef CONFIG_SLUB_DEBUG
2551 static int count_free(struct page *page)
2553 return page->objects - page->inuse;
2556 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2558 return atomic_long_read(&n->total_objects);
2560 #endif /* CONFIG_SLUB_DEBUG */
2562 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2563 static unsigned long count_partial(struct kmem_cache_node *n,
2564 int (*get_count)(struct page *))
2566 unsigned long flags;
2567 unsigned long x = 0;
2570 spin_lock_irqsave(&n->list_lock, flags);
2571 list_for_each_entry(page, &n->partial, slab_list)
2572 x += get_count(page);
2573 spin_unlock_irqrestore(&n->list_lock, flags);
2576 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2578 static noinline void
2579 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2581 #ifdef CONFIG_SLUB_DEBUG
2582 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2583 DEFAULT_RATELIMIT_BURST);
2585 struct kmem_cache_node *n;
2587 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2590 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2591 nid, gfpflags, &gfpflags);
2592 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2593 s->name, s->object_size, s->size, oo_order(s->oo),
2596 if (oo_order(s->min) > get_order(s->object_size))
2597 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2600 for_each_kmem_cache_node(s, node, n) {
2601 unsigned long nr_slabs;
2602 unsigned long nr_objs;
2603 unsigned long nr_free;
2605 nr_free = count_partial(n, count_free);
2606 nr_slabs = node_nr_slabs(n);
2607 nr_objs = node_nr_objs(n);
2609 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2610 node, nr_slabs, nr_objs, nr_free);
2615 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2616 int node, struct kmem_cache_cpu **pc)
2619 struct kmem_cache_cpu *c = *pc;
2622 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2624 freelist = get_partial(s, flags, node, c);
2629 page = new_slab(s, flags, node);
2631 c = raw_cpu_ptr(s->cpu_slab);
2636 * No other reference to the page yet so we can
2637 * muck around with it freely without cmpxchg
2639 freelist = page->freelist;
2640 page->freelist = NULL;
2642 stat(s, ALLOC_SLAB);
2650 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2652 if (unlikely(PageSlabPfmemalloc(page)))
2653 return gfp_pfmemalloc_allowed(gfpflags);
2659 * Check the page->freelist of a page and either transfer the freelist to the
2660 * per cpu freelist or deactivate the page.
2662 * The page is still frozen if the return value is not NULL.
2664 * If this function returns NULL then the page has been unfrozen.
2666 * This function must be called with interrupt disabled.
2668 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2671 unsigned long counters;
2675 freelist = page->freelist;
2676 counters = page->counters;
2678 new.counters = counters;
2679 VM_BUG_ON(!new.frozen);
2681 new.inuse = page->objects;
2682 new.frozen = freelist != NULL;
2684 } while (!__cmpxchg_double_slab(s, page,
2693 * Slow path. The lockless freelist is empty or we need to perform
2696 * Processing is still very fast if new objects have been freed to the
2697 * regular freelist. In that case we simply take over the regular freelist
2698 * as the lockless freelist and zap the regular freelist.
2700 * If that is not working then we fall back to the partial lists. We take the
2701 * first element of the freelist as the object to allocate now and move the
2702 * rest of the freelist to the lockless freelist.
2704 * And if we were unable to get a new slab from the partial slab lists then
2705 * we need to allocate a new slab. This is the slowest path since it involves
2706 * a call to the page allocator and the setup of a new slab.
2708 * Version of __slab_alloc to use when we know that interrupts are
2709 * already disabled (which is the case for bulk allocation).
2711 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2712 unsigned long addr, struct kmem_cache_cpu *c)
2717 stat(s, ALLOC_SLOWPATH);
2722 * if the node is not online or has no normal memory, just
2723 * ignore the node constraint
2725 if (unlikely(node != NUMA_NO_NODE &&
2726 !node_isset(node, slab_nodes)))
2727 node = NUMA_NO_NODE;
2732 if (unlikely(!node_match(page, node))) {
2734 * same as above but node_match() being false already
2735 * implies node != NUMA_NO_NODE
2737 if (!node_isset(node, slab_nodes)) {
2738 node = NUMA_NO_NODE;
2741 stat(s, ALLOC_NODE_MISMATCH);
2742 deactivate_slab(s, page, c->freelist, c);
2748 * By rights, we should be searching for a slab page that was
2749 * PFMEMALLOC but right now, we are losing the pfmemalloc
2750 * information when the page leaves the per-cpu allocator
2752 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2753 deactivate_slab(s, page, c->freelist, c);
2757 /* must check again c->freelist in case of cpu migration or IRQ */
2758 freelist = c->freelist;
2762 freelist = get_freelist(s, page);
2766 stat(s, DEACTIVATE_BYPASS);
2770 stat(s, ALLOC_REFILL);
2774 * freelist is pointing to the list of objects to be used.
2775 * page is pointing to the page from which the objects are obtained.
2776 * That page must be frozen for per cpu allocations to work.
2778 VM_BUG_ON(!c->page->frozen);
2779 c->freelist = get_freepointer(s, freelist);
2780 c->tid = next_tid(c->tid);
2785 if (slub_percpu_partial(c)) {
2786 page = c->page = slub_percpu_partial(c);
2787 slub_set_percpu_partial(c, page);
2788 stat(s, CPU_PARTIAL_ALLOC);
2792 freelist = new_slab_objects(s, gfpflags, node, &c);
2794 if (unlikely(!freelist)) {
2795 slab_out_of_memory(s, gfpflags, node);
2800 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2803 /* Only entered in the debug case */
2804 if (kmem_cache_debug(s) &&
2805 !alloc_debug_processing(s, page, freelist, addr))
2806 goto new_slab; /* Slab failed checks. Next slab needed */
2808 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2813 * Another one that disabled interrupt and compensates for possible
2814 * cpu changes by refetching the per cpu area pointer.
2816 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2817 unsigned long addr, struct kmem_cache_cpu *c)
2820 unsigned long flags;
2822 local_irq_save(flags);
2823 #ifdef CONFIG_PREEMPTION
2825 * We may have been preempted and rescheduled on a different
2826 * cpu before disabling interrupts. Need to reload cpu area
2829 c = this_cpu_ptr(s->cpu_slab);
2832 p = ___slab_alloc(s, gfpflags, node, addr, c);
2833 local_irq_restore(flags);
2838 * If the object has been wiped upon free, make sure it's fully initialized by
2839 * zeroing out freelist pointer.
2841 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2844 if (unlikely(slab_want_init_on_free(s)) && obj)
2845 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
2850 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2851 * have the fastpath folded into their functions. So no function call
2852 * overhead for requests that can be satisfied on the fastpath.
2854 * The fastpath works by first checking if the lockless freelist can be used.
2855 * If not then __slab_alloc is called for slow processing.
2857 * Otherwise we can simply pick the next object from the lockless free list.
2859 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2860 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
2863 struct kmem_cache_cpu *c;
2866 struct obj_cgroup *objcg = NULL;
2869 s = slab_pre_alloc_hook(s, &objcg, 1, gfpflags);
2873 object = kfence_alloc(s, orig_size, gfpflags);
2874 if (unlikely(object))
2879 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2880 * enabled. We may switch back and forth between cpus while
2881 * reading from one cpu area. That does not matter as long
2882 * as we end up on the original cpu again when doing the cmpxchg.
2884 * We should guarantee that tid and kmem_cache are retrieved on
2885 * the same cpu. It could be different if CONFIG_PREEMPTION so we need
2886 * to check if it is matched or not.
2889 tid = this_cpu_read(s->cpu_slab->tid);
2890 c = raw_cpu_ptr(s->cpu_slab);
2891 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
2892 unlikely(tid != READ_ONCE(c->tid)));
2895 * Irqless object alloc/free algorithm used here depends on sequence
2896 * of fetching cpu_slab's data. tid should be fetched before anything
2897 * on c to guarantee that object and page associated with previous tid
2898 * won't be used with current tid. If we fetch tid first, object and
2899 * page could be one associated with next tid and our alloc/free
2900 * request will be failed. In this case, we will retry. So, no problem.
2905 * The transaction ids are globally unique per cpu and per operation on
2906 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2907 * occurs on the right processor and that there was no operation on the
2908 * linked list in between.
2911 object = c->freelist;
2913 if (unlikely(!object || !page || !node_match(page, node))) {
2914 object = __slab_alloc(s, gfpflags, node, addr, c);
2916 void *next_object = get_freepointer_safe(s, object);
2919 * The cmpxchg will only match if there was no additional
2920 * operation and if we are on the right processor.
2922 * The cmpxchg does the following atomically (without lock
2924 * 1. Relocate first pointer to the current per cpu area.
2925 * 2. Verify that tid and freelist have not been changed
2926 * 3. If they were not changed replace tid and freelist
2928 * Since this is without lock semantics the protection is only
2929 * against code executing on this cpu *not* from access by
2932 if (unlikely(!this_cpu_cmpxchg_double(
2933 s->cpu_slab->freelist, s->cpu_slab->tid,
2935 next_object, next_tid(tid)))) {
2937 note_cmpxchg_failure("slab_alloc", s, tid);
2940 prefetch_freepointer(s, next_object);
2941 stat(s, ALLOC_FASTPATH);
2944 maybe_wipe_obj_freeptr(s, object);
2945 init = slab_want_init_on_alloc(gfpflags, s);
2948 slab_post_alloc_hook(s, objcg, gfpflags, 1, &object, init);
2953 static __always_inline void *slab_alloc(struct kmem_cache *s,
2954 gfp_t gfpflags, unsigned long addr, size_t orig_size)
2956 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr, orig_size);
2959 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2961 void *ret = slab_alloc(s, gfpflags, _RET_IP_, s->object_size);
2963 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2968 EXPORT_SYMBOL(kmem_cache_alloc);
2970 #ifdef CONFIG_TRACING
2971 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2973 void *ret = slab_alloc(s, gfpflags, _RET_IP_, size);
2974 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2975 ret = kasan_kmalloc(s, ret, size, gfpflags);
2978 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2982 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2984 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, s->object_size);
2986 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2987 s->object_size, s->size, gfpflags, node);
2991 EXPORT_SYMBOL(kmem_cache_alloc_node);
2993 #ifdef CONFIG_TRACING
2994 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2996 int node, size_t size)
2998 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, size);
3000 trace_kmalloc_node(_RET_IP_, ret,
3001 size, s->size, gfpflags, node);
3003 ret = kasan_kmalloc(s, ret, size, gfpflags);
3006 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3008 #endif /* CONFIG_NUMA */
3011 * Slow path handling. This may still be called frequently since objects
3012 * have a longer lifetime than the cpu slabs in most processing loads.
3014 * So we still attempt to reduce cache line usage. Just take the slab
3015 * lock and free the item. If there is no additional partial page
3016 * handling required then we can return immediately.
3018 static void __slab_free(struct kmem_cache *s, struct page *page,
3019 void *head, void *tail, int cnt,
3026 unsigned long counters;
3027 struct kmem_cache_node *n = NULL;
3028 unsigned long flags;
3030 stat(s, FREE_SLOWPATH);
3032 if (kfence_free(head))
3035 if (kmem_cache_debug(s) &&
3036 !free_debug_processing(s, page, head, tail, cnt, addr))
3041 spin_unlock_irqrestore(&n->list_lock, flags);
3044 prior = page->freelist;
3045 counters = page->counters;
3046 set_freepointer(s, tail, prior);
3047 new.counters = counters;
3048 was_frozen = new.frozen;
3050 if ((!new.inuse || !prior) && !was_frozen) {
3052 if (kmem_cache_has_cpu_partial(s) && !prior) {
3055 * Slab was on no list before and will be
3057 * We can defer the list move and instead
3062 } else { /* Needs to be taken off a list */
3064 n = get_node(s, page_to_nid(page));
3066 * Speculatively acquire the list_lock.
3067 * If the cmpxchg does not succeed then we may
3068 * drop the list_lock without any processing.
3070 * Otherwise the list_lock will synchronize with
3071 * other processors updating the list of slabs.
3073 spin_lock_irqsave(&n->list_lock, flags);
3078 } while (!cmpxchg_double_slab(s, page,
3085 if (likely(was_frozen)) {
3087 * The list lock was not taken therefore no list
3088 * activity can be necessary.
3090 stat(s, FREE_FROZEN);
3091 } else if (new.frozen) {
3093 * If we just froze the page then put it onto the
3094 * per cpu partial list.
3096 put_cpu_partial(s, page, 1);
3097 stat(s, CPU_PARTIAL_FREE);
3103 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
3107 * Objects left in the slab. If it was not on the partial list before
3110 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
3111 remove_full(s, n, page);
3112 add_partial(n, page, DEACTIVATE_TO_TAIL);
3113 stat(s, FREE_ADD_PARTIAL);
3115 spin_unlock_irqrestore(&n->list_lock, flags);
3121 * Slab on the partial list.
3123 remove_partial(n, page);
3124 stat(s, FREE_REMOVE_PARTIAL);
3126 /* Slab must be on the full list */
3127 remove_full(s, n, page);
3130 spin_unlock_irqrestore(&n->list_lock, flags);
3132 discard_slab(s, page);
3136 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3137 * can perform fastpath freeing without additional function calls.
3139 * The fastpath is only possible if we are freeing to the current cpu slab
3140 * of this processor. This typically the case if we have just allocated
3143 * If fastpath is not possible then fall back to __slab_free where we deal
3144 * with all sorts of special processing.
3146 * Bulk free of a freelist with several objects (all pointing to the
3147 * same page) possible by specifying head and tail ptr, plus objects
3148 * count (cnt). Bulk free indicated by tail pointer being set.
3150 static __always_inline void do_slab_free(struct kmem_cache *s,
3151 struct page *page, void *head, void *tail,
3152 int cnt, unsigned long addr)
3154 void *tail_obj = tail ? : head;
3155 struct kmem_cache_cpu *c;
3158 memcg_slab_free_hook(s, &head, 1);
3161 * Determine the currently cpus per cpu slab.
3162 * The cpu may change afterward. However that does not matter since
3163 * data is retrieved via this pointer. If we are on the same cpu
3164 * during the cmpxchg then the free will succeed.
3167 tid = this_cpu_read(s->cpu_slab->tid);
3168 c = raw_cpu_ptr(s->cpu_slab);
3169 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
3170 unlikely(tid != READ_ONCE(c->tid)));
3172 /* Same with comment on barrier() in slab_alloc_node() */
3175 if (likely(page == c->page)) {
3176 void **freelist = READ_ONCE(c->freelist);
3178 set_freepointer(s, tail_obj, freelist);
3180 if (unlikely(!this_cpu_cmpxchg_double(
3181 s->cpu_slab->freelist, s->cpu_slab->tid,
3183 head, next_tid(tid)))) {
3185 note_cmpxchg_failure("slab_free", s, tid);
3188 stat(s, FREE_FASTPATH);
3190 __slab_free(s, page, head, tail_obj, cnt, addr);
3194 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3195 void *head, void *tail, int cnt,
3199 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3200 * to remove objects, whose reuse must be delayed.
3202 if (slab_free_freelist_hook(s, &head, &tail))
3203 do_slab_free(s, page, head, tail, cnt, addr);
3206 #ifdef CONFIG_KASAN_GENERIC
3207 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3209 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3213 void kmem_cache_free(struct kmem_cache *s, void *x)
3215 s = cache_from_obj(s, x);
3218 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3219 trace_kmem_cache_free(_RET_IP_, x, s->name);
3221 EXPORT_SYMBOL(kmem_cache_free);
3223 struct detached_freelist {
3228 struct kmem_cache *s;
3232 * This function progressively scans the array with free objects (with
3233 * a limited look ahead) and extract objects belonging to the same
3234 * page. It builds a detached freelist directly within the given
3235 * page/objects. This can happen without any need for
3236 * synchronization, because the objects are owned by running process.
3237 * The freelist is build up as a single linked list in the objects.
3238 * The idea is, that this detached freelist can then be bulk
3239 * transferred to the real freelist(s), but only requiring a single
3240 * synchronization primitive. Look ahead in the array is limited due
3241 * to performance reasons.
3244 int build_detached_freelist(struct kmem_cache *s, size_t size,
3245 void **p, struct detached_freelist *df)
3247 size_t first_skipped_index = 0;
3252 /* Always re-init detached_freelist */
3257 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3258 } while (!object && size);
3263 page = virt_to_head_page(object);
3265 /* Handle kalloc'ed objects */
3266 if (unlikely(!PageSlab(page))) {
3267 BUG_ON(!PageCompound(page));
3269 __free_pages(page, compound_order(page));
3270 p[size] = NULL; /* mark object processed */
3273 /* Derive kmem_cache from object */
3274 df->s = page->slab_cache;
3276 df->s = cache_from_obj(s, object); /* Support for memcg */
3279 if (is_kfence_address(object)) {
3280 slab_free_hook(df->s, object, false);
3281 __kfence_free(object);
3282 p[size] = NULL; /* mark object processed */
3286 /* Start new detached freelist */
3288 set_freepointer(df->s, object, NULL);
3290 df->freelist = object;
3291 p[size] = NULL; /* mark object processed */
3297 continue; /* Skip processed objects */
3299 /* df->page is always set at this point */
3300 if (df->page == virt_to_head_page(object)) {
3301 /* Opportunity build freelist */
3302 set_freepointer(df->s, object, df->freelist);
3303 df->freelist = object;
3305 p[size] = NULL; /* mark object processed */
3310 /* Limit look ahead search */
3314 if (!first_skipped_index)
3315 first_skipped_index = size + 1;
3318 return first_skipped_index;
3321 /* Note that interrupts must be enabled when calling this function. */
3322 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3327 memcg_slab_free_hook(s, p, size);
3329 struct detached_freelist df;
3331 size = build_detached_freelist(s, size, p, &df);
3335 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt, _RET_IP_);
3336 } while (likely(size));
3338 EXPORT_SYMBOL(kmem_cache_free_bulk);
3340 /* Note that interrupts must be enabled when calling this function. */
3341 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3344 struct kmem_cache_cpu *c;
3346 struct obj_cgroup *objcg = NULL;
3348 /* memcg and kmem_cache debug support */
3349 s = slab_pre_alloc_hook(s, &objcg, size, flags);
3353 * Drain objects in the per cpu slab, while disabling local
3354 * IRQs, which protects against PREEMPT and interrupts
3355 * handlers invoking normal fastpath.
3357 local_irq_disable();
3358 c = this_cpu_ptr(s->cpu_slab);
3360 for (i = 0; i < size; i++) {
3361 void *object = kfence_alloc(s, s->object_size, flags);
3363 if (unlikely(object)) {
3368 object = c->freelist;
3369 if (unlikely(!object)) {
3371 * We may have removed an object from c->freelist using
3372 * the fastpath in the previous iteration; in that case,
3373 * c->tid has not been bumped yet.
3374 * Since ___slab_alloc() may reenable interrupts while
3375 * allocating memory, we should bump c->tid now.
3377 c->tid = next_tid(c->tid);
3380 * Invoking slow path likely have side-effect
3381 * of re-populating per CPU c->freelist
3383 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3385 if (unlikely(!p[i]))
3388 c = this_cpu_ptr(s->cpu_slab);
3389 maybe_wipe_obj_freeptr(s, p[i]);
3391 continue; /* goto for-loop */
3393 c->freelist = get_freepointer(s, object);
3395 maybe_wipe_obj_freeptr(s, p[i]);
3397 c->tid = next_tid(c->tid);
3401 * memcg and kmem_cache debug support and memory initialization.
3402 * Done outside of the IRQ disabled fastpath loop.
3404 slab_post_alloc_hook(s, objcg, flags, size, p,
3405 slab_want_init_on_alloc(flags, s));
3409 slab_post_alloc_hook(s, objcg, flags, i, p, false);
3410 __kmem_cache_free_bulk(s, i, p);
3413 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3417 * Object placement in a slab is made very easy because we always start at
3418 * offset 0. If we tune the size of the object to the alignment then we can
3419 * get the required alignment by putting one properly sized object after
3422 * Notice that the allocation order determines the sizes of the per cpu
3423 * caches. Each processor has always one slab available for allocations.
3424 * Increasing the allocation order reduces the number of times that slabs
3425 * must be moved on and off the partial lists and is therefore a factor in
3430 * Minimum / Maximum order of slab pages. This influences locking overhead
3431 * and slab fragmentation. A higher order reduces the number of partial slabs
3432 * and increases the number of allocations possible without having to
3433 * take the list_lock.
3435 static unsigned int slub_min_order;
3436 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3437 static unsigned int slub_min_objects;
3440 * Calculate the order of allocation given an slab object size.
3442 * The order of allocation has significant impact on performance and other
3443 * system components. Generally order 0 allocations should be preferred since
3444 * order 0 does not cause fragmentation in the page allocator. Larger objects
3445 * be problematic to put into order 0 slabs because there may be too much
3446 * unused space left. We go to a higher order if more than 1/16th of the slab
3449 * In order to reach satisfactory performance we must ensure that a minimum
3450 * number of objects is in one slab. Otherwise we may generate too much
3451 * activity on the partial lists which requires taking the list_lock. This is
3452 * less a concern for large slabs though which are rarely used.
3454 * slub_max_order specifies the order where we begin to stop considering the
3455 * number of objects in a slab as critical. If we reach slub_max_order then
3456 * we try to keep the page order as low as possible. So we accept more waste
3457 * of space in favor of a small page order.
3459 * Higher order allocations also allow the placement of more objects in a
3460 * slab and thereby reduce object handling overhead. If the user has
3461 * requested a higher minimum order then we start with that one instead of
3462 * the smallest order which will fit the object.
3464 static inline unsigned int slab_order(unsigned int size,
3465 unsigned int min_objects, unsigned int max_order,
3466 unsigned int fract_leftover)
3468 unsigned int min_order = slub_min_order;
3471 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3472 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3474 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3475 order <= max_order; order++) {
3477 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3480 rem = slab_size % size;
3482 if (rem <= slab_size / fract_leftover)
3489 static inline int calculate_order(unsigned int size)
3492 unsigned int min_objects;
3493 unsigned int max_objects;
3494 unsigned int nr_cpus;
3497 * Attempt to find best configuration for a slab. This
3498 * works by first attempting to generate a layout with
3499 * the best configuration and backing off gradually.
3501 * First we increase the acceptable waste in a slab. Then
3502 * we reduce the minimum objects required in a slab.
3504 min_objects = slub_min_objects;
3507 * Some architectures will only update present cpus when
3508 * onlining them, so don't trust the number if it's just 1. But
3509 * we also don't want to use nr_cpu_ids always, as on some other
3510 * architectures, there can be many possible cpus, but never
3511 * onlined. Here we compromise between trying to avoid too high
3512 * order on systems that appear larger than they are, and too
3513 * low order on systems that appear smaller than they are.
3515 nr_cpus = num_present_cpus();
3517 nr_cpus = nr_cpu_ids;
3518 min_objects = 4 * (fls(nr_cpus) + 1);
3520 max_objects = order_objects(slub_max_order, size);
3521 min_objects = min(min_objects, max_objects);
3523 while (min_objects > 1) {
3524 unsigned int fraction;
3527 while (fraction >= 4) {
3528 order = slab_order(size, min_objects,
3529 slub_max_order, fraction);
3530 if (order <= slub_max_order)
3538 * We were unable to place multiple objects in a slab. Now
3539 * lets see if we can place a single object there.
3541 order = slab_order(size, 1, slub_max_order, 1);
3542 if (order <= slub_max_order)
3546 * Doh this slab cannot be placed using slub_max_order.
3548 order = slab_order(size, 1, MAX_ORDER, 1);
3549 if (order < MAX_ORDER)
3555 init_kmem_cache_node(struct kmem_cache_node *n)
3558 spin_lock_init(&n->list_lock);
3559 INIT_LIST_HEAD(&n->partial);
3560 #ifdef CONFIG_SLUB_DEBUG
3561 atomic_long_set(&n->nr_slabs, 0);
3562 atomic_long_set(&n->total_objects, 0);
3563 INIT_LIST_HEAD(&n->full);
3567 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3569 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3570 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3573 * Must align to double word boundary for the double cmpxchg
3574 * instructions to work; see __pcpu_double_call_return_bool().
3576 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3577 2 * sizeof(void *));
3582 init_kmem_cache_cpus(s);
3587 static struct kmem_cache *kmem_cache_node;
3590 * No kmalloc_node yet so do it by hand. We know that this is the first
3591 * slab on the node for this slabcache. There are no concurrent accesses
3594 * Note that this function only works on the kmem_cache_node
3595 * when allocating for the kmem_cache_node. This is used for bootstrapping
3596 * memory on a fresh node that has no slab structures yet.
3598 static void early_kmem_cache_node_alloc(int node)
3601 struct kmem_cache_node *n;
3603 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3605 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3608 if (page_to_nid(page) != node) {
3609 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3610 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3615 #ifdef CONFIG_SLUB_DEBUG
3616 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3617 init_tracking(kmem_cache_node, n);
3619 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
3620 page->freelist = get_freepointer(kmem_cache_node, n);
3623 kmem_cache_node->node[node] = n;
3624 init_kmem_cache_node(n);
3625 inc_slabs_node(kmem_cache_node, node, page->objects);
3628 * No locks need to be taken here as it has just been
3629 * initialized and there is no concurrent access.
3631 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3634 static void free_kmem_cache_nodes(struct kmem_cache *s)
3637 struct kmem_cache_node *n;
3639 for_each_kmem_cache_node(s, node, n) {
3640 s->node[node] = NULL;
3641 kmem_cache_free(kmem_cache_node, n);
3645 void __kmem_cache_release(struct kmem_cache *s)
3647 cache_random_seq_destroy(s);
3648 free_percpu(s->cpu_slab);
3649 free_kmem_cache_nodes(s);
3652 static int init_kmem_cache_nodes(struct kmem_cache *s)
3656 for_each_node_mask(node, slab_nodes) {
3657 struct kmem_cache_node *n;
3659 if (slab_state == DOWN) {
3660 early_kmem_cache_node_alloc(node);
3663 n = kmem_cache_alloc_node(kmem_cache_node,
3667 free_kmem_cache_nodes(s);
3671 init_kmem_cache_node(n);
3677 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3679 if (min < MIN_PARTIAL)
3681 else if (min > MAX_PARTIAL)
3683 s->min_partial = min;
3686 static void set_cpu_partial(struct kmem_cache *s)
3688 #ifdef CONFIG_SLUB_CPU_PARTIAL
3690 * cpu_partial determined the maximum number of objects kept in the
3691 * per cpu partial lists of a processor.
3693 * Per cpu partial lists mainly contain slabs that just have one
3694 * object freed. If they are used for allocation then they can be
3695 * filled up again with minimal effort. The slab will never hit the
3696 * per node partial lists and therefore no locking will be required.
3698 * This setting also determines
3700 * A) The number of objects from per cpu partial slabs dumped to the
3701 * per node list when we reach the limit.
3702 * B) The number of objects in cpu partial slabs to extract from the
3703 * per node list when we run out of per cpu objects. We only fetch
3704 * 50% to keep some capacity around for frees.
3706 if (!kmem_cache_has_cpu_partial(s))
3707 slub_set_cpu_partial(s, 0);
3708 else if (s->size >= PAGE_SIZE)
3709 slub_set_cpu_partial(s, 2);
3710 else if (s->size >= 1024)
3711 slub_set_cpu_partial(s, 6);
3712 else if (s->size >= 256)
3713 slub_set_cpu_partial(s, 13);
3715 slub_set_cpu_partial(s, 30);
3720 * calculate_sizes() determines the order and the distribution of data within
3723 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3725 slab_flags_t flags = s->flags;
3726 unsigned int size = s->object_size;
3730 * Round up object size to the next word boundary. We can only
3731 * place the free pointer at word boundaries and this determines
3732 * the possible location of the free pointer.
3734 size = ALIGN(size, sizeof(void *));
3736 #ifdef CONFIG_SLUB_DEBUG
3738 * Determine if we can poison the object itself. If the user of
3739 * the slab may touch the object after free or before allocation
3740 * then we should never poison the object itself.
3742 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3744 s->flags |= __OBJECT_POISON;
3746 s->flags &= ~__OBJECT_POISON;
3750 * If we are Redzoning then check if there is some space between the
3751 * end of the object and the free pointer. If not then add an
3752 * additional word to have some bytes to store Redzone information.
3754 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3755 size += sizeof(void *);
3759 * With that we have determined the number of bytes in actual use
3760 * by the object and redzoning.
3764 if ((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3765 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
3768 * Relocate free pointer after the object if it is not
3769 * permitted to overwrite the first word of the object on
3772 * This is the case if we do RCU, have a constructor or
3773 * destructor, are poisoning the objects, or are
3774 * redzoning an object smaller than sizeof(void *).
3776 * The assumption that s->offset >= s->inuse means free
3777 * pointer is outside of the object is used in the
3778 * freeptr_outside_object() function. If that is no
3779 * longer true, the function needs to be modified.
3782 size += sizeof(void *);
3785 * Store freelist pointer near middle of object to keep
3786 * it away from the edges of the object to avoid small
3787 * sized over/underflows from neighboring allocations.
3789 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
3792 #ifdef CONFIG_SLUB_DEBUG
3793 if (flags & SLAB_STORE_USER)
3795 * Need to store information about allocs and frees after
3798 size += 2 * sizeof(struct track);
3801 kasan_cache_create(s, &size, &s->flags);
3802 #ifdef CONFIG_SLUB_DEBUG
3803 if (flags & SLAB_RED_ZONE) {
3805 * Add some empty padding so that we can catch
3806 * overwrites from earlier objects rather than let
3807 * tracking information or the free pointer be
3808 * corrupted if a user writes before the start
3811 size += sizeof(void *);
3813 s->red_left_pad = sizeof(void *);
3814 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3815 size += s->red_left_pad;
3820 * SLUB stores one object immediately after another beginning from
3821 * offset 0. In order to align the objects we have to simply size
3822 * each object to conform to the alignment.
3824 size = ALIGN(size, s->align);
3826 s->reciprocal_size = reciprocal_value(size);
3827 if (forced_order >= 0)
3828 order = forced_order;
3830 order = calculate_order(size);
3837 s->allocflags |= __GFP_COMP;
3839 if (s->flags & SLAB_CACHE_DMA)
3840 s->allocflags |= GFP_DMA;
3842 if (s->flags & SLAB_CACHE_DMA32)
3843 s->allocflags |= GFP_DMA32;
3845 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3846 s->allocflags |= __GFP_RECLAIMABLE;
3849 * Determine the number of objects per slab
3851 s->oo = oo_make(order, size);
3852 s->min = oo_make(get_order(size), size);
3853 if (oo_objects(s->oo) > oo_objects(s->max))
3856 return !!oo_objects(s->oo);
3859 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3861 s->flags = kmem_cache_flags(s->size, flags, s->name);
3862 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3863 s->random = get_random_long();
3866 if (!calculate_sizes(s, -1))
3868 if (disable_higher_order_debug) {
3870 * Disable debugging flags that store metadata if the min slab
3873 if (get_order(s->size) > get_order(s->object_size)) {
3874 s->flags &= ~DEBUG_METADATA_FLAGS;
3876 if (!calculate_sizes(s, -1))
3881 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3882 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3883 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3884 /* Enable fast mode */
3885 s->flags |= __CMPXCHG_DOUBLE;
3889 * The larger the object size is, the more pages we want on the partial
3890 * list to avoid pounding the page allocator excessively.
3892 set_min_partial(s, ilog2(s->size) / 2);
3897 s->remote_node_defrag_ratio = 1000;
3900 /* Initialize the pre-computed randomized freelist if slab is up */
3901 if (slab_state >= UP) {
3902 if (init_cache_random_seq(s))
3906 if (!init_kmem_cache_nodes(s))
3909 if (alloc_kmem_cache_cpus(s))
3912 free_kmem_cache_nodes(s);
3917 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3920 #ifdef CONFIG_SLUB_DEBUG
3921 void *addr = page_address(page);
3925 slab_err(s, page, text, s->name);
3928 map = get_map(s, page);
3929 for_each_object(p, s, addr, page->objects) {
3931 if (!test_bit(__obj_to_index(s, addr, p), map)) {
3932 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
3933 print_tracking(s, p);
3942 * Attempt to free all partial slabs on a node.
3943 * This is called from __kmem_cache_shutdown(). We must take list_lock
3944 * because sysfs file might still access partial list after the shutdowning.
3946 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3949 struct page *page, *h;
3951 BUG_ON(irqs_disabled());
3952 spin_lock_irq(&n->list_lock);
3953 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3955 remove_partial(n, page);
3956 list_add(&page->slab_list, &discard);
3958 list_slab_objects(s, page,
3959 "Objects remaining in %s on __kmem_cache_shutdown()");
3962 spin_unlock_irq(&n->list_lock);
3964 list_for_each_entry_safe(page, h, &discard, slab_list)
3965 discard_slab(s, page);
3968 bool __kmem_cache_empty(struct kmem_cache *s)
3971 struct kmem_cache_node *n;
3973 for_each_kmem_cache_node(s, node, n)
3974 if (n->nr_partial || slabs_node(s, node))
3980 * Release all resources used by a slab cache.
3982 int __kmem_cache_shutdown(struct kmem_cache *s)
3985 struct kmem_cache_node *n;
3988 /* Attempt to free all objects */
3989 for_each_kmem_cache_node(s, node, n) {
3991 if (n->nr_partial || slabs_node(s, node))
3997 #ifdef CONFIG_PRINTK
3998 void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct page *page)
4001 int __maybe_unused i;
4005 struct kmem_cache *s = page->slab_cache;
4006 struct track __maybe_unused *trackp;
4008 kpp->kp_ptr = object;
4009 kpp->kp_page = page;
4010 kpp->kp_slab_cache = s;
4011 base = page_address(page);
4012 objp0 = kasan_reset_tag(object);
4013 #ifdef CONFIG_SLUB_DEBUG
4014 objp = restore_red_left(s, objp0);
4018 objnr = obj_to_index(s, page, objp);
4019 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
4020 objp = base + s->size * objnr;
4021 kpp->kp_objp = objp;
4022 if (WARN_ON_ONCE(objp < base || objp >= base + page->objects * s->size || (objp - base) % s->size) ||
4023 !(s->flags & SLAB_STORE_USER))
4025 #ifdef CONFIG_SLUB_DEBUG
4026 trackp = get_track(s, objp, TRACK_ALLOC);
4027 kpp->kp_ret = (void *)trackp->addr;
4028 #ifdef CONFIG_STACKTRACE
4029 for (i = 0; i < KS_ADDRS_COUNT && i < TRACK_ADDRS_COUNT; i++) {
4030 kpp->kp_stack[i] = (void *)trackp->addrs[i];
4031 if (!kpp->kp_stack[i])
4039 /********************************************************************
4041 *******************************************************************/
4043 static int __init setup_slub_min_order(char *str)
4045 get_option(&str, (int *)&slub_min_order);
4050 __setup("slub_min_order=", setup_slub_min_order);
4052 static int __init setup_slub_max_order(char *str)
4054 get_option(&str, (int *)&slub_max_order);
4055 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
4060 __setup("slub_max_order=", setup_slub_max_order);
4062 static int __init setup_slub_min_objects(char *str)
4064 get_option(&str, (int *)&slub_min_objects);
4069 __setup("slub_min_objects=", setup_slub_min_objects);
4071 void *__kmalloc(size_t size, gfp_t flags)
4073 struct kmem_cache *s;
4076 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4077 return kmalloc_large(size, flags);
4079 s = kmalloc_slab(size, flags);
4081 if (unlikely(ZERO_OR_NULL_PTR(s)))
4084 ret = slab_alloc(s, flags, _RET_IP_, size);
4086 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
4088 ret = kasan_kmalloc(s, ret, size, flags);
4092 EXPORT_SYMBOL(__kmalloc);
4095 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
4099 unsigned int order = get_order(size);
4101 flags |= __GFP_COMP;
4102 page = alloc_pages_node(node, flags, order);
4104 ptr = page_address(page);
4105 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4106 PAGE_SIZE << order);
4109 return kmalloc_large_node_hook(ptr, size, flags);
4112 void *__kmalloc_node(size_t size, gfp_t flags, int node)
4114 struct kmem_cache *s;
4117 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4118 ret = kmalloc_large_node(size, flags, node);
4120 trace_kmalloc_node(_RET_IP_, ret,
4121 size, PAGE_SIZE << get_order(size),
4127 s = kmalloc_slab(size, flags);
4129 if (unlikely(ZERO_OR_NULL_PTR(s)))
4132 ret = slab_alloc_node(s, flags, node, _RET_IP_, size);
4134 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
4136 ret = kasan_kmalloc(s, ret, size, flags);
4140 EXPORT_SYMBOL(__kmalloc_node);
4141 #endif /* CONFIG_NUMA */
4143 #ifdef CONFIG_HARDENED_USERCOPY
4145 * Rejects incorrectly sized objects and objects that are to be copied
4146 * to/from userspace but do not fall entirely within the containing slab
4147 * cache's usercopy region.
4149 * Returns NULL if check passes, otherwise const char * to name of cache
4150 * to indicate an error.
4152 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
4155 struct kmem_cache *s;
4156 unsigned int offset;
4158 bool is_kfence = is_kfence_address(ptr);
4160 ptr = kasan_reset_tag(ptr);
4162 /* Find object and usable object size. */
4163 s = page->slab_cache;
4165 /* Reject impossible pointers. */
4166 if (ptr < page_address(page))
4167 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4170 /* Find offset within object. */
4172 offset = ptr - kfence_object_start(ptr);
4174 offset = (ptr - page_address(page)) % s->size;
4176 /* Adjust for redzone and reject if within the redzone. */
4177 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
4178 if (offset < s->red_left_pad)
4179 usercopy_abort("SLUB object in left red zone",
4180 s->name, to_user, offset, n);
4181 offset -= s->red_left_pad;
4184 /* Allow address range falling entirely within usercopy region. */
4185 if (offset >= s->useroffset &&
4186 offset - s->useroffset <= s->usersize &&
4187 n <= s->useroffset - offset + s->usersize)
4191 * If the copy is still within the allocated object, produce
4192 * a warning instead of rejecting the copy. This is intended
4193 * to be a temporary method to find any missing usercopy
4196 object_size = slab_ksize(s);
4197 if (usercopy_fallback &&
4198 offset <= object_size && n <= object_size - offset) {
4199 usercopy_warn("SLUB object", s->name, to_user, offset, n);
4203 usercopy_abort("SLUB object", s->name, to_user, offset, n);
4205 #endif /* CONFIG_HARDENED_USERCOPY */
4207 size_t __ksize(const void *object)
4211 if (unlikely(object == ZERO_SIZE_PTR))
4214 page = virt_to_head_page(object);
4216 if (unlikely(!PageSlab(page))) {
4217 WARN_ON(!PageCompound(page));
4218 return page_size(page);
4221 return slab_ksize(page->slab_cache);
4223 EXPORT_SYMBOL(__ksize);
4225 void kfree(const void *x)
4228 void *object = (void *)x;
4230 trace_kfree(_RET_IP_, x);
4232 if (unlikely(ZERO_OR_NULL_PTR(x)))
4235 page = virt_to_head_page(x);
4236 if (unlikely(!PageSlab(page))) {
4237 unsigned int order = compound_order(page);
4239 BUG_ON(!PageCompound(page));
4241 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4242 -(PAGE_SIZE << order));
4243 __free_pages(page, order);
4246 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4248 EXPORT_SYMBOL(kfree);
4250 #define SHRINK_PROMOTE_MAX 32
4253 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4254 * up most to the head of the partial lists. New allocations will then
4255 * fill those up and thus they can be removed from the partial lists.
4257 * The slabs with the least items are placed last. This results in them
4258 * being allocated from last increasing the chance that the last objects
4259 * are freed in them.
4261 int __kmem_cache_shrink(struct kmem_cache *s)
4265 struct kmem_cache_node *n;
4268 struct list_head discard;
4269 struct list_head promote[SHRINK_PROMOTE_MAX];
4270 unsigned long flags;
4274 for_each_kmem_cache_node(s, node, n) {
4275 INIT_LIST_HEAD(&discard);
4276 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4277 INIT_LIST_HEAD(promote + i);
4279 spin_lock_irqsave(&n->list_lock, flags);
4282 * Build lists of slabs to discard or promote.
4284 * Note that concurrent frees may occur while we hold the
4285 * list_lock. page->inuse here is the upper limit.
4287 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4288 int free = page->objects - page->inuse;
4290 /* Do not reread page->inuse */
4293 /* We do not keep full slabs on the list */
4296 if (free == page->objects) {
4297 list_move(&page->slab_list, &discard);
4299 } else if (free <= SHRINK_PROMOTE_MAX)
4300 list_move(&page->slab_list, promote + free - 1);
4304 * Promote the slabs filled up most to the head of the
4307 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4308 list_splice(promote + i, &n->partial);
4310 spin_unlock_irqrestore(&n->list_lock, flags);
4312 /* Release empty slabs */
4313 list_for_each_entry_safe(page, t, &discard, slab_list)
4314 discard_slab(s, page);
4316 if (slabs_node(s, node))
4323 static int slab_mem_going_offline_callback(void *arg)
4325 struct kmem_cache *s;
4327 mutex_lock(&slab_mutex);
4328 list_for_each_entry(s, &slab_caches, list)
4329 __kmem_cache_shrink(s);
4330 mutex_unlock(&slab_mutex);
4335 static void slab_mem_offline_callback(void *arg)
4337 struct memory_notify *marg = arg;
4340 offline_node = marg->status_change_nid_normal;
4343 * If the node still has available memory. we need kmem_cache_node
4346 if (offline_node < 0)
4349 mutex_lock(&slab_mutex);
4350 node_clear(offline_node, slab_nodes);
4352 * We no longer free kmem_cache_node structures here, as it would be
4353 * racy with all get_node() users, and infeasible to protect them with
4356 mutex_unlock(&slab_mutex);
4359 static int slab_mem_going_online_callback(void *arg)
4361 struct kmem_cache_node *n;
4362 struct kmem_cache *s;
4363 struct memory_notify *marg = arg;
4364 int nid = marg->status_change_nid_normal;
4368 * If the node's memory is already available, then kmem_cache_node is
4369 * already created. Nothing to do.
4375 * We are bringing a node online. No memory is available yet. We must
4376 * allocate a kmem_cache_node structure in order to bring the node
4379 mutex_lock(&slab_mutex);
4380 list_for_each_entry(s, &slab_caches, list) {
4382 * The structure may already exist if the node was previously
4383 * onlined and offlined.
4385 if (get_node(s, nid))
4388 * XXX: kmem_cache_alloc_node will fallback to other nodes
4389 * since memory is not yet available from the node that
4392 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4397 init_kmem_cache_node(n);
4401 * Any cache created after this point will also have kmem_cache_node
4402 * initialized for the new node.
4404 node_set(nid, slab_nodes);
4406 mutex_unlock(&slab_mutex);
4410 static int slab_memory_callback(struct notifier_block *self,
4411 unsigned long action, void *arg)
4416 case MEM_GOING_ONLINE:
4417 ret = slab_mem_going_online_callback(arg);
4419 case MEM_GOING_OFFLINE:
4420 ret = slab_mem_going_offline_callback(arg);
4423 case MEM_CANCEL_ONLINE:
4424 slab_mem_offline_callback(arg);
4427 case MEM_CANCEL_OFFLINE:
4431 ret = notifier_from_errno(ret);
4437 static struct notifier_block slab_memory_callback_nb = {
4438 .notifier_call = slab_memory_callback,
4439 .priority = SLAB_CALLBACK_PRI,
4442 /********************************************************************
4443 * Basic setup of slabs
4444 *******************************************************************/
4447 * Used for early kmem_cache structures that were allocated using
4448 * the page allocator. Allocate them properly then fix up the pointers
4449 * that may be pointing to the wrong kmem_cache structure.
4452 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4455 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4456 struct kmem_cache_node *n;
4458 memcpy(s, static_cache, kmem_cache->object_size);
4461 * This runs very early, and only the boot processor is supposed to be
4462 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4465 __flush_cpu_slab(s, smp_processor_id());
4466 for_each_kmem_cache_node(s, node, n) {
4469 list_for_each_entry(p, &n->partial, slab_list)
4472 #ifdef CONFIG_SLUB_DEBUG
4473 list_for_each_entry(p, &n->full, slab_list)
4477 list_add(&s->list, &slab_caches);
4481 void __init kmem_cache_init(void)
4483 static __initdata struct kmem_cache boot_kmem_cache,
4484 boot_kmem_cache_node;
4487 if (debug_guardpage_minorder())
4490 kmem_cache_node = &boot_kmem_cache_node;
4491 kmem_cache = &boot_kmem_cache;
4494 * Initialize the nodemask for which we will allocate per node
4495 * structures. Here we don't need taking slab_mutex yet.
4497 for_each_node_state(node, N_NORMAL_MEMORY)
4498 node_set(node, slab_nodes);
4500 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4501 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4503 register_hotmemory_notifier(&slab_memory_callback_nb);
4505 /* Able to allocate the per node structures */
4506 slab_state = PARTIAL;
4508 create_boot_cache(kmem_cache, "kmem_cache",
4509 offsetof(struct kmem_cache, node) +
4510 nr_node_ids * sizeof(struct kmem_cache_node *),
4511 SLAB_HWCACHE_ALIGN, 0, 0);
4513 kmem_cache = bootstrap(&boot_kmem_cache);
4514 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4516 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4517 setup_kmalloc_cache_index_table();
4518 create_kmalloc_caches(0);
4520 /* Setup random freelists for each cache */
4521 init_freelist_randomization();
4523 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4526 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4528 slub_min_order, slub_max_order, slub_min_objects,
4529 nr_cpu_ids, nr_node_ids);
4532 void __init kmem_cache_init_late(void)
4537 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4538 slab_flags_t flags, void (*ctor)(void *))
4540 struct kmem_cache *s;
4542 s = find_mergeable(size, align, flags, name, ctor);
4547 * Adjust the object sizes so that we clear
4548 * the complete object on kzalloc.
4550 s->object_size = max(s->object_size, size);
4551 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4553 if (sysfs_slab_alias(s, name)) {
4562 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4566 err = kmem_cache_open(s, flags);
4570 /* Mutex is not taken during early boot */
4571 if (slab_state <= UP)
4574 err = sysfs_slab_add(s);
4576 __kmem_cache_release(s);
4581 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4583 struct kmem_cache *s;
4586 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4587 return kmalloc_large(size, gfpflags);
4589 s = kmalloc_slab(size, gfpflags);
4591 if (unlikely(ZERO_OR_NULL_PTR(s)))
4594 ret = slab_alloc(s, gfpflags, caller, size);
4596 /* Honor the call site pointer we received. */
4597 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4601 EXPORT_SYMBOL(__kmalloc_track_caller);
4604 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4605 int node, unsigned long caller)
4607 struct kmem_cache *s;
4610 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4611 ret = kmalloc_large_node(size, gfpflags, node);
4613 trace_kmalloc_node(caller, ret,
4614 size, PAGE_SIZE << get_order(size),
4620 s = kmalloc_slab(size, gfpflags);
4622 if (unlikely(ZERO_OR_NULL_PTR(s)))
4625 ret = slab_alloc_node(s, gfpflags, node, caller, size);
4627 /* Honor the call site pointer we received. */
4628 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4632 EXPORT_SYMBOL(__kmalloc_node_track_caller);
4636 static int count_inuse(struct page *page)
4641 static int count_total(struct page *page)
4643 return page->objects;
4647 #ifdef CONFIG_SLUB_DEBUG
4648 static void validate_slab(struct kmem_cache *s, struct page *page)
4651 void *addr = page_address(page);
4656 if (!check_slab(s, page) || !on_freelist(s, page, NULL))
4659 /* Now we know that a valid freelist exists */
4660 map = get_map(s, page);
4661 for_each_object(p, s, addr, page->objects) {
4662 u8 val = test_bit(__obj_to_index(s, addr, p), map) ?
4663 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
4665 if (!check_object(s, page, p, val))
4673 static int validate_slab_node(struct kmem_cache *s,
4674 struct kmem_cache_node *n)
4676 unsigned long count = 0;
4678 unsigned long flags;
4680 spin_lock_irqsave(&n->list_lock, flags);
4682 list_for_each_entry(page, &n->partial, slab_list) {
4683 validate_slab(s, page);
4686 if (count != n->nr_partial) {
4687 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4688 s->name, count, n->nr_partial);
4689 slab_add_kunit_errors();
4692 if (!(s->flags & SLAB_STORE_USER))
4695 list_for_each_entry(page, &n->full, slab_list) {
4696 validate_slab(s, page);
4699 if (count != atomic_long_read(&n->nr_slabs)) {
4700 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4701 s->name, count, atomic_long_read(&n->nr_slabs));
4702 slab_add_kunit_errors();
4706 spin_unlock_irqrestore(&n->list_lock, flags);
4710 long validate_slab_cache(struct kmem_cache *s)
4713 unsigned long count = 0;
4714 struct kmem_cache_node *n;
4717 for_each_kmem_cache_node(s, node, n)
4718 count += validate_slab_node(s, n);
4722 EXPORT_SYMBOL(validate_slab_cache);
4725 * Generate lists of code addresses where slabcache objects are allocated
4730 unsigned long count;
4737 DECLARE_BITMAP(cpus, NR_CPUS);
4743 unsigned long count;
4744 struct location *loc;
4747 static void free_loc_track(struct loc_track *t)
4750 free_pages((unsigned long)t->loc,
4751 get_order(sizeof(struct location) * t->max));
4754 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4759 order = get_order(sizeof(struct location) * max);
4761 l = (void *)__get_free_pages(flags, order);
4766 memcpy(l, t->loc, sizeof(struct location) * t->count);
4774 static int add_location(struct loc_track *t, struct kmem_cache *s,
4775 const struct track *track)
4777 long start, end, pos;
4779 unsigned long caddr;
4780 unsigned long age = jiffies - track->when;
4786 pos = start + (end - start + 1) / 2;
4789 * There is nothing at "end". If we end up there
4790 * we need to add something to before end.
4795 caddr = t->loc[pos].addr;
4796 if (track->addr == caddr) {
4802 if (age < l->min_time)
4804 if (age > l->max_time)
4807 if (track->pid < l->min_pid)
4808 l->min_pid = track->pid;
4809 if (track->pid > l->max_pid)
4810 l->max_pid = track->pid;
4812 cpumask_set_cpu(track->cpu,
4813 to_cpumask(l->cpus));
4815 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4819 if (track->addr < caddr)
4826 * Not found. Insert new tracking element.
4828 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4834 (t->count - pos) * sizeof(struct location));
4837 l->addr = track->addr;
4841 l->min_pid = track->pid;
4842 l->max_pid = track->pid;
4843 cpumask_clear(to_cpumask(l->cpus));
4844 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4845 nodes_clear(l->nodes);
4846 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4850 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4851 struct page *page, enum track_item alloc)
4853 void *addr = page_address(page);
4857 map = get_map(s, page);
4858 for_each_object(p, s, addr, page->objects)
4859 if (!test_bit(__obj_to_index(s, addr, p), map))
4860 add_location(t, s, get_track(s, p, alloc));
4864 static int list_locations(struct kmem_cache *s, char *buf,
4865 enum track_item alloc)
4869 struct loc_track t = { 0, 0, NULL };
4871 struct kmem_cache_node *n;
4873 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4875 return sysfs_emit(buf, "Out of memory\n");
4877 /* Push back cpu slabs */
4880 for_each_kmem_cache_node(s, node, n) {
4881 unsigned long flags;
4884 if (!atomic_long_read(&n->nr_slabs))
4887 spin_lock_irqsave(&n->list_lock, flags);
4888 list_for_each_entry(page, &n->partial, slab_list)
4889 process_slab(&t, s, page, alloc);
4890 list_for_each_entry(page, &n->full, slab_list)
4891 process_slab(&t, s, page, alloc);
4892 spin_unlock_irqrestore(&n->list_lock, flags);
4895 for (i = 0; i < t.count; i++) {
4896 struct location *l = &t.loc[i];
4898 len += sysfs_emit_at(buf, len, "%7ld ", l->count);
4901 len += sysfs_emit_at(buf, len, "%pS", (void *)l->addr);
4903 len += sysfs_emit_at(buf, len, "<not-available>");
4905 if (l->sum_time != l->min_time)
4906 len += sysfs_emit_at(buf, len, " age=%ld/%ld/%ld",
4908 (long)div_u64(l->sum_time,
4912 len += sysfs_emit_at(buf, len, " age=%ld", l->min_time);
4914 if (l->min_pid != l->max_pid)
4915 len += sysfs_emit_at(buf, len, " pid=%ld-%ld",
4916 l->min_pid, l->max_pid);
4918 len += sysfs_emit_at(buf, len, " pid=%ld",
4921 if (num_online_cpus() > 1 &&
4922 !cpumask_empty(to_cpumask(l->cpus)))
4923 len += sysfs_emit_at(buf, len, " cpus=%*pbl",
4924 cpumask_pr_args(to_cpumask(l->cpus)));
4926 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
4927 len += sysfs_emit_at(buf, len, " nodes=%*pbl",
4928 nodemask_pr_args(&l->nodes));
4930 len += sysfs_emit_at(buf, len, "\n");
4935 len += sysfs_emit_at(buf, len, "No data\n");
4939 #endif /* CONFIG_SLUB_DEBUG */
4941 #ifdef SLUB_RESILIENCY_TEST
4942 static void __init resiliency_test(void)
4945 int type = KMALLOC_NORMAL;
4947 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4949 pr_err("SLUB resiliency testing\n");
4950 pr_err("-----------------------\n");
4951 pr_err("A. Corruption after allocation\n");
4953 p = kzalloc(16, GFP_KERNEL);
4955 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4958 validate_slab_cache(kmalloc_caches[type][4]);
4960 /* Hmmm... The next two are dangerous */
4961 p = kzalloc(32, GFP_KERNEL);
4962 p[32 + sizeof(void *)] = 0x34;
4963 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4965 pr_err("If allocated object is overwritten then not detectable\n\n");
4967 validate_slab_cache(kmalloc_caches[type][5]);
4968 p = kzalloc(64, GFP_KERNEL);
4969 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4971 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4973 pr_err("If allocated object is overwritten then not detectable\n\n");
4974 validate_slab_cache(kmalloc_caches[type][6]);
4976 pr_err("\nB. Corruption after free\n");
4977 p = kzalloc(128, GFP_KERNEL);
4980 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4981 validate_slab_cache(kmalloc_caches[type][7]);
4983 p = kzalloc(256, GFP_KERNEL);
4986 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4987 validate_slab_cache(kmalloc_caches[type][8]);
4989 p = kzalloc(512, GFP_KERNEL);
4992 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4993 validate_slab_cache(kmalloc_caches[type][9]);
4997 static void resiliency_test(void) {};
4999 #endif /* SLUB_RESILIENCY_TEST */
5002 enum slab_stat_type {
5003 SL_ALL, /* All slabs */
5004 SL_PARTIAL, /* Only partially allocated slabs */
5005 SL_CPU, /* Only slabs used for cpu caches */
5006 SL_OBJECTS, /* Determine allocated objects not slabs */
5007 SL_TOTAL /* Determine object capacity not slabs */
5010 #define SO_ALL (1 << SL_ALL)
5011 #define SO_PARTIAL (1 << SL_PARTIAL)
5012 #define SO_CPU (1 << SL_CPU)
5013 #define SO_OBJECTS (1 << SL_OBJECTS)
5014 #define SO_TOTAL (1 << SL_TOTAL)
5016 static ssize_t show_slab_objects(struct kmem_cache *s,
5017 char *buf, unsigned long flags)
5019 unsigned long total = 0;
5022 unsigned long *nodes;
5025 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
5029 if (flags & SO_CPU) {
5032 for_each_possible_cpu(cpu) {
5033 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
5038 page = READ_ONCE(c->page);
5042 node = page_to_nid(page);
5043 if (flags & SO_TOTAL)
5045 else if (flags & SO_OBJECTS)
5053 page = slub_percpu_partial_read_once(c);
5055 node = page_to_nid(page);
5056 if (flags & SO_TOTAL)
5058 else if (flags & SO_OBJECTS)
5069 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
5070 * already held which will conflict with an existing lock order:
5072 * mem_hotplug_lock->slab_mutex->kernfs_mutex
5074 * We don't really need mem_hotplug_lock (to hold off
5075 * slab_mem_going_offline_callback) here because slab's memory hot
5076 * unplug code doesn't destroy the kmem_cache->node[] data.
5079 #ifdef CONFIG_SLUB_DEBUG
5080 if (flags & SO_ALL) {
5081 struct kmem_cache_node *n;
5083 for_each_kmem_cache_node(s, node, n) {
5085 if (flags & SO_TOTAL)
5086 x = atomic_long_read(&n->total_objects);
5087 else if (flags & SO_OBJECTS)
5088 x = atomic_long_read(&n->total_objects) -
5089 count_partial(n, count_free);
5091 x = atomic_long_read(&n->nr_slabs);
5098 if (flags & SO_PARTIAL) {
5099 struct kmem_cache_node *n;
5101 for_each_kmem_cache_node(s, node, n) {
5102 if (flags & SO_TOTAL)
5103 x = count_partial(n, count_total);
5104 else if (flags & SO_OBJECTS)
5105 x = count_partial(n, count_inuse);
5113 len += sysfs_emit_at(buf, len, "%lu", total);
5115 for (node = 0; node < nr_node_ids; node++) {
5117 len += sysfs_emit_at(buf, len, " N%d=%lu",
5121 len += sysfs_emit_at(buf, len, "\n");
5127 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
5128 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
5130 struct slab_attribute {
5131 struct attribute attr;
5132 ssize_t (*show)(struct kmem_cache *s, char *buf);
5133 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5136 #define SLAB_ATTR_RO(_name) \
5137 static struct slab_attribute _name##_attr = \
5138 __ATTR(_name, 0400, _name##_show, NULL)
5140 #define SLAB_ATTR(_name) \
5141 static struct slab_attribute _name##_attr = \
5142 __ATTR(_name, 0600, _name##_show, _name##_store)
5144 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5146 return sysfs_emit(buf, "%u\n", s->size);
5148 SLAB_ATTR_RO(slab_size);
5150 static ssize_t align_show(struct kmem_cache *s, char *buf)
5152 return sysfs_emit(buf, "%u\n", s->align);
5154 SLAB_ATTR_RO(align);
5156 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5158 return sysfs_emit(buf, "%u\n", s->object_size);
5160 SLAB_ATTR_RO(object_size);
5162 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5164 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
5166 SLAB_ATTR_RO(objs_per_slab);
5168 static ssize_t order_show(struct kmem_cache *s, char *buf)
5170 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
5172 SLAB_ATTR_RO(order);
5174 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5176 return sysfs_emit(buf, "%lu\n", s->min_partial);
5179 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5185 err = kstrtoul(buf, 10, &min);
5189 set_min_partial(s, min);
5192 SLAB_ATTR(min_partial);
5194 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5196 return sysfs_emit(buf, "%u\n", slub_cpu_partial(s));
5199 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5202 unsigned int objects;
5205 err = kstrtouint(buf, 10, &objects);
5208 if (objects && !kmem_cache_has_cpu_partial(s))
5211 slub_set_cpu_partial(s, objects);
5215 SLAB_ATTR(cpu_partial);
5217 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5221 return sysfs_emit(buf, "%pS\n", s->ctor);
5225 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5227 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5229 SLAB_ATTR_RO(aliases);
5231 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5233 return show_slab_objects(s, buf, SO_PARTIAL);
5235 SLAB_ATTR_RO(partial);
5237 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5239 return show_slab_objects(s, buf, SO_CPU);
5241 SLAB_ATTR_RO(cpu_slabs);
5243 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5245 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5247 SLAB_ATTR_RO(objects);
5249 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5251 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5253 SLAB_ATTR_RO(objects_partial);
5255 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5262 for_each_online_cpu(cpu) {
5265 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5268 pages += page->pages;
5269 objects += page->pobjects;
5273 len += sysfs_emit_at(buf, len, "%d(%d)", objects, pages);
5276 for_each_online_cpu(cpu) {
5279 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5281 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
5282 cpu, page->pobjects, page->pages);
5285 len += sysfs_emit_at(buf, len, "\n");
5289 SLAB_ATTR_RO(slabs_cpu_partial);
5291 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5293 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5295 SLAB_ATTR_RO(reclaim_account);
5297 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5299 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5301 SLAB_ATTR_RO(hwcache_align);
5303 #ifdef CONFIG_ZONE_DMA
5304 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5306 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5308 SLAB_ATTR_RO(cache_dma);
5311 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5313 return sysfs_emit(buf, "%u\n", s->usersize);
5315 SLAB_ATTR_RO(usersize);
5317 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5319 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5321 SLAB_ATTR_RO(destroy_by_rcu);
5323 #ifdef CONFIG_SLUB_DEBUG
5324 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5326 return show_slab_objects(s, buf, SO_ALL);
5328 SLAB_ATTR_RO(slabs);
5330 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5332 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5334 SLAB_ATTR_RO(total_objects);
5336 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5338 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5340 SLAB_ATTR_RO(sanity_checks);
5342 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5344 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5346 SLAB_ATTR_RO(trace);
5348 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5350 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5353 SLAB_ATTR_RO(red_zone);
5355 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5357 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
5360 SLAB_ATTR_RO(poison);
5362 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5364 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5367 SLAB_ATTR_RO(store_user);
5369 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5374 static ssize_t validate_store(struct kmem_cache *s,
5375 const char *buf, size_t length)
5379 if (buf[0] == '1') {
5380 ret = validate_slab_cache(s);
5386 SLAB_ATTR(validate);
5388 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5390 if (!(s->flags & SLAB_STORE_USER))
5392 return list_locations(s, buf, TRACK_ALLOC);
5394 SLAB_ATTR_RO(alloc_calls);
5396 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5398 if (!(s->flags & SLAB_STORE_USER))
5400 return list_locations(s, buf, TRACK_FREE);
5402 SLAB_ATTR_RO(free_calls);
5403 #endif /* CONFIG_SLUB_DEBUG */
5405 #ifdef CONFIG_FAILSLAB
5406 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5408 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5410 SLAB_ATTR_RO(failslab);
5413 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5418 static ssize_t shrink_store(struct kmem_cache *s,
5419 const char *buf, size_t length)
5422 kmem_cache_shrink(s);
5430 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5432 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5435 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5436 const char *buf, size_t length)
5441 err = kstrtouint(buf, 10, &ratio);
5447 s->remote_node_defrag_ratio = ratio * 10;
5451 SLAB_ATTR(remote_node_defrag_ratio);
5454 #ifdef CONFIG_SLUB_STATS
5455 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5457 unsigned long sum = 0;
5460 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5465 for_each_online_cpu(cpu) {
5466 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5472 len += sysfs_emit_at(buf, len, "%lu", sum);
5475 for_each_online_cpu(cpu) {
5477 len += sysfs_emit_at(buf, len, " C%d=%u",
5482 len += sysfs_emit_at(buf, len, "\n");
5487 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5491 for_each_online_cpu(cpu)
5492 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5495 #define STAT_ATTR(si, text) \
5496 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5498 return show_stat(s, buf, si); \
5500 static ssize_t text##_store(struct kmem_cache *s, \
5501 const char *buf, size_t length) \
5503 if (buf[0] != '0') \
5505 clear_stat(s, si); \
5510 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5511 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5512 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5513 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5514 STAT_ATTR(FREE_FROZEN, free_frozen);
5515 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5516 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5517 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5518 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5519 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5520 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5521 STAT_ATTR(FREE_SLAB, free_slab);
5522 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5523 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5524 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5525 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5526 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5527 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5528 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5529 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5530 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5531 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5532 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5533 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5534 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5535 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5536 #endif /* CONFIG_SLUB_STATS */
5538 static struct attribute *slab_attrs[] = {
5539 &slab_size_attr.attr,
5540 &object_size_attr.attr,
5541 &objs_per_slab_attr.attr,
5543 &min_partial_attr.attr,
5544 &cpu_partial_attr.attr,
5546 &objects_partial_attr.attr,
5548 &cpu_slabs_attr.attr,
5552 &hwcache_align_attr.attr,
5553 &reclaim_account_attr.attr,
5554 &destroy_by_rcu_attr.attr,
5556 &slabs_cpu_partial_attr.attr,
5557 #ifdef CONFIG_SLUB_DEBUG
5558 &total_objects_attr.attr,
5560 &sanity_checks_attr.attr,
5562 &red_zone_attr.attr,
5564 &store_user_attr.attr,
5565 &validate_attr.attr,
5566 &alloc_calls_attr.attr,
5567 &free_calls_attr.attr,
5569 #ifdef CONFIG_ZONE_DMA
5570 &cache_dma_attr.attr,
5573 &remote_node_defrag_ratio_attr.attr,
5575 #ifdef CONFIG_SLUB_STATS
5576 &alloc_fastpath_attr.attr,
5577 &alloc_slowpath_attr.attr,
5578 &free_fastpath_attr.attr,
5579 &free_slowpath_attr.attr,
5580 &free_frozen_attr.attr,
5581 &free_add_partial_attr.attr,
5582 &free_remove_partial_attr.attr,
5583 &alloc_from_partial_attr.attr,
5584 &alloc_slab_attr.attr,
5585 &alloc_refill_attr.attr,
5586 &alloc_node_mismatch_attr.attr,
5587 &free_slab_attr.attr,
5588 &cpuslab_flush_attr.attr,
5589 &deactivate_full_attr.attr,
5590 &deactivate_empty_attr.attr,
5591 &deactivate_to_head_attr.attr,
5592 &deactivate_to_tail_attr.attr,
5593 &deactivate_remote_frees_attr.attr,
5594 &deactivate_bypass_attr.attr,
5595 &order_fallback_attr.attr,
5596 &cmpxchg_double_fail_attr.attr,
5597 &cmpxchg_double_cpu_fail_attr.attr,
5598 &cpu_partial_alloc_attr.attr,
5599 &cpu_partial_free_attr.attr,
5600 &cpu_partial_node_attr.attr,
5601 &cpu_partial_drain_attr.attr,
5603 #ifdef CONFIG_FAILSLAB
5604 &failslab_attr.attr,
5606 &usersize_attr.attr,
5611 static const struct attribute_group slab_attr_group = {
5612 .attrs = slab_attrs,
5615 static ssize_t slab_attr_show(struct kobject *kobj,
5616 struct attribute *attr,
5619 struct slab_attribute *attribute;
5620 struct kmem_cache *s;
5623 attribute = to_slab_attr(attr);
5626 if (!attribute->show)
5629 err = attribute->show(s, buf);
5634 static ssize_t slab_attr_store(struct kobject *kobj,
5635 struct attribute *attr,
5636 const char *buf, size_t len)
5638 struct slab_attribute *attribute;
5639 struct kmem_cache *s;
5642 attribute = to_slab_attr(attr);
5645 if (!attribute->store)
5648 err = attribute->store(s, buf, len);
5652 static void kmem_cache_release(struct kobject *k)
5654 slab_kmem_cache_release(to_slab(k));
5657 static const struct sysfs_ops slab_sysfs_ops = {
5658 .show = slab_attr_show,
5659 .store = slab_attr_store,
5662 static struct kobj_type slab_ktype = {
5663 .sysfs_ops = &slab_sysfs_ops,
5664 .release = kmem_cache_release,
5667 static struct kset *slab_kset;
5669 static inline struct kset *cache_kset(struct kmem_cache *s)
5674 #define ID_STR_LENGTH 64
5676 /* Create a unique string id for a slab cache:
5678 * Format :[flags-]size
5680 static char *create_unique_id(struct kmem_cache *s)
5682 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5689 * First flags affecting slabcache operations. We will only
5690 * get here for aliasable slabs so we do not need to support
5691 * too many flags. The flags here must cover all flags that
5692 * are matched during merging to guarantee that the id is
5695 if (s->flags & SLAB_CACHE_DMA)
5697 if (s->flags & SLAB_CACHE_DMA32)
5699 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5701 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5703 if (s->flags & SLAB_ACCOUNT)
5707 p += sprintf(p, "%07u", s->size);
5709 BUG_ON(p > name + ID_STR_LENGTH - 1);
5713 static int sysfs_slab_add(struct kmem_cache *s)
5717 struct kset *kset = cache_kset(s);
5718 int unmergeable = slab_unmergeable(s);
5721 kobject_init(&s->kobj, &slab_ktype);
5725 if (!unmergeable && disable_higher_order_debug &&
5726 (slub_debug & DEBUG_METADATA_FLAGS))
5731 * Slabcache can never be merged so we can use the name proper.
5732 * This is typically the case for debug situations. In that
5733 * case we can catch duplicate names easily.
5735 sysfs_remove_link(&slab_kset->kobj, s->name);
5739 * Create a unique name for the slab as a target
5742 name = create_unique_id(s);
5745 s->kobj.kset = kset;
5746 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5750 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5755 /* Setup first alias */
5756 sysfs_slab_alias(s, s->name);
5763 kobject_del(&s->kobj);
5767 void sysfs_slab_unlink(struct kmem_cache *s)
5769 if (slab_state >= FULL)
5770 kobject_del(&s->kobj);
5773 void sysfs_slab_release(struct kmem_cache *s)
5775 if (slab_state >= FULL)
5776 kobject_put(&s->kobj);
5780 * Need to buffer aliases during bootup until sysfs becomes
5781 * available lest we lose that information.
5783 struct saved_alias {
5784 struct kmem_cache *s;
5786 struct saved_alias *next;
5789 static struct saved_alias *alias_list;
5791 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5793 struct saved_alias *al;
5795 if (slab_state == FULL) {
5797 * If we have a leftover link then remove it.
5799 sysfs_remove_link(&slab_kset->kobj, name);
5800 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5803 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5809 al->next = alias_list;
5814 static int __init slab_sysfs_init(void)
5816 struct kmem_cache *s;
5819 mutex_lock(&slab_mutex);
5821 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
5823 mutex_unlock(&slab_mutex);
5824 pr_err("Cannot register slab subsystem.\n");
5830 list_for_each_entry(s, &slab_caches, list) {
5831 err = sysfs_slab_add(s);
5833 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5837 while (alias_list) {
5838 struct saved_alias *al = alias_list;
5840 alias_list = alias_list->next;
5841 err = sysfs_slab_alias(al->s, al->name);
5843 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5848 mutex_unlock(&slab_mutex);
5853 __initcall(slab_sysfs_init);
5854 #endif /* CONFIG_SYSFS */
5857 * The /proc/slabinfo ABI
5859 #ifdef CONFIG_SLUB_DEBUG
5860 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5862 unsigned long nr_slabs = 0;
5863 unsigned long nr_objs = 0;
5864 unsigned long nr_free = 0;
5866 struct kmem_cache_node *n;
5868 for_each_kmem_cache_node(s, node, n) {
5869 nr_slabs += node_nr_slabs(n);
5870 nr_objs += node_nr_objs(n);
5871 nr_free += count_partial(n, count_free);
5874 sinfo->active_objs = nr_objs - nr_free;
5875 sinfo->num_objs = nr_objs;
5876 sinfo->active_slabs = nr_slabs;
5877 sinfo->num_slabs = nr_slabs;
5878 sinfo->objects_per_slab = oo_objects(s->oo);
5879 sinfo->cache_order = oo_order(s->oo);
5882 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5886 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5887 size_t count, loff_t *ppos)
5891 #endif /* CONFIG_SLUB_DEBUG */