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 operatios
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/memory.h>
32 #include <linux/math64.h>
33 #include <linux/fault-inject.h>
34 #include <linux/stacktrace.h>
35 #include <linux/prefetch.h>
36 #include <linux/memcontrol.h>
37 #include <linux/random.h>
39 #include <trace/events/kmem.h>
45 * 1. slab_mutex (Global Mutex)
47 * 3. slab_lock(page) (Only on some arches and for debugging)
51 * The role of the slab_mutex is to protect the list of all the slabs
52 * and to synchronize major metadata changes to slab cache structures.
54 * The slab_lock is only used for debugging and on arches that do not
55 * have the ability to do a cmpxchg_double. It only protects:
56 * A. page->freelist -> List of object free in a page
57 * B. page->inuse -> Number of objects in use
58 * C. page->objects -> Number of objects in page
59 * D. page->frozen -> frozen state
61 * If a slab is frozen then it is exempt from list management. It is not
62 * on any list except per cpu partial list. The processor that froze the
63 * slab is the one who can perform list operations on the page. Other
64 * processors may put objects onto the freelist but the processor that
65 * froze the slab is the only one that can retrieve the objects from the
68 * The list_lock protects the partial and full list on each node and
69 * the partial slab counter. If taken then no new slabs may be added or
70 * removed from the lists nor make the number of partial slabs be modified.
71 * (Note that the total number of slabs is an atomic value that may be
72 * modified without taking the list lock).
74 * The list_lock is a centralized lock and thus we avoid taking it as
75 * much as possible. As long as SLUB does not have to handle partial
76 * slabs, operations can continue without any centralized lock. F.e.
77 * allocating a long series of objects that fill up slabs does not require
79 * Interrupts are disabled during allocation and deallocation in order to
80 * make the slab allocator safe to use in the context of an irq. In addition
81 * interrupts are disabled to ensure that the processor does not change
82 * while handling per_cpu slabs, due to kernel preemption.
84 * SLUB assigns one slab for allocation to each processor.
85 * Allocations only occur from these slabs called cpu slabs.
87 * Slabs with free elements are kept on a partial list and during regular
88 * operations no list for full slabs is used. If an object in a full slab is
89 * freed then the slab will show up again on the partial lists.
90 * We track full slabs for debugging purposes though because otherwise we
91 * cannot scan all objects.
93 * Slabs are freed when they become empty. Teardown and setup is
94 * minimal so we rely on the page allocators per cpu caches for
95 * fast frees and allocs.
97 * Overloading of page flags that are otherwise used for LRU management.
99 * PageActive 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 * PageError 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 static inline int kmem_cache_debug(struct kmem_cache *s)
122 #ifdef CONFIG_SLUB_DEBUG
123 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
129 void *fixup_red_left(struct kmem_cache *s, void *p)
131 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE)
132 p += s->red_left_pad;
137 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
139 #ifdef CONFIG_SLUB_CPU_PARTIAL
140 return !kmem_cache_debug(s);
147 * Issues still to be resolved:
149 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
151 * - Variable sizing of the per node arrays
154 /* Enable to test recovery from slab corruption on boot */
155 #undef SLUB_RESILIENCY_TEST
157 /* Enable to log cmpxchg failures */
158 #undef SLUB_DEBUG_CMPXCHG
161 * Mininum number of partial slabs. These will be left on the partial
162 * lists even if they are empty. kmem_cache_shrink may reclaim them.
164 #define MIN_PARTIAL 5
167 * Maximum number of desirable partial slabs.
168 * The existence of more partial slabs makes kmem_cache_shrink
169 * sort the partial list by the number of objects in use.
171 #define MAX_PARTIAL 10
173 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
174 SLAB_POISON | SLAB_STORE_USER)
177 * These debug flags cannot use CMPXCHG because there might be consistency
178 * issues when checking or reading debug information
180 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
185 * Debugging flags that require metadata to be stored in the slab. These get
186 * disabled when slub_debug=O is used and a cache's min order increases with
189 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
192 #define OO_MASK ((1 << OO_SHIFT) - 1)
193 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
195 /* Internal SLUB flags */
197 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
198 /* Use cmpxchg_double */
199 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
202 * Tracking user of a slab.
204 #define TRACK_ADDRS_COUNT 16
206 unsigned long addr; /* Called from address */
207 #ifdef CONFIG_STACKTRACE
208 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
210 int cpu; /* Was running on cpu */
211 int pid; /* Pid context */
212 unsigned long when; /* When did the operation occur */
215 enum track_item { TRACK_ALLOC, TRACK_FREE };
218 static int sysfs_slab_add(struct kmem_cache *);
219 static int sysfs_slab_alias(struct kmem_cache *, const char *);
220 static void memcg_propagate_slab_attrs(struct kmem_cache *s);
221 static void sysfs_slab_remove(struct kmem_cache *s);
223 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
224 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
226 static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { }
227 static inline void sysfs_slab_remove(struct kmem_cache *s) { }
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]);
241 /********************************************************************
242 * Core slab cache functions
243 *******************************************************************/
246 * Returns freelist pointer (ptr). With hardening, this is obfuscated
247 * with an XOR of the address where the pointer is held and a per-cache
250 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
251 unsigned long ptr_addr)
253 #ifdef CONFIG_SLAB_FREELIST_HARDENED
255 * When CONFIG_KASAN_SW_TAGS is enabled, ptr_addr might be tagged.
256 * Normally, this doesn't cause any issues, as both set_freepointer()
257 * and get_freepointer() are called with a pointer with the same tag.
258 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
259 * example, when __free_slub() iterates over objects in a cache, it
260 * passes untagged pointers to check_object(). check_object() in turns
261 * calls get_freepointer() with an untagged pointer, which causes the
262 * freepointer to be restored incorrectly.
264 return (void *)((unsigned long)ptr ^ s->random ^
265 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
271 /* Returns the freelist pointer recorded at location ptr_addr. */
272 static inline void *freelist_dereference(const struct kmem_cache *s,
275 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
276 (unsigned long)ptr_addr);
279 static inline void *get_freepointer(struct kmem_cache *s, void *object)
281 return freelist_dereference(s, object + s->offset);
284 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
286 prefetch(object + s->offset);
289 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
291 unsigned long freepointer_addr;
294 if (!debug_pagealloc_enabled_static())
295 return get_freepointer(s, object);
297 freepointer_addr = (unsigned long)object + s->offset;
298 probe_kernel_read(&p, (void **)freepointer_addr, sizeof(p));
299 return freelist_ptr(s, p, freepointer_addr);
302 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
304 unsigned long freeptr_addr = (unsigned long)object + s->offset;
306 #ifdef CONFIG_SLAB_FREELIST_HARDENED
307 BUG_ON(object == fp); /* naive detection of double free or corruption */
310 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
313 /* Loop over all objects in a slab */
314 #define for_each_object(__p, __s, __addr, __objects) \
315 for (__p = fixup_red_left(__s, __addr); \
316 __p < (__addr) + (__objects) * (__s)->size; \
319 /* Determine object index from a given position */
320 static inline unsigned int slab_index(void *p, struct kmem_cache *s, void *addr)
322 return (kasan_reset_tag(p) - addr) / s->size;
325 static inline unsigned int order_objects(unsigned int order, unsigned int size)
327 return ((unsigned int)PAGE_SIZE << order) / size;
330 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
333 struct kmem_cache_order_objects x = {
334 (order << OO_SHIFT) + order_objects(order, size)
340 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
342 return x.x >> OO_SHIFT;
345 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
347 return x.x & OO_MASK;
351 * Per slab locking using the pagelock
353 static __always_inline void slab_lock(struct page *page)
355 VM_BUG_ON_PAGE(PageTail(page), page);
356 bit_spin_lock(PG_locked, &page->flags);
359 static __always_inline void slab_unlock(struct page *page)
361 VM_BUG_ON_PAGE(PageTail(page), page);
362 __bit_spin_unlock(PG_locked, &page->flags);
365 /* Interrupts must be disabled (for the fallback code to work right) */
366 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
367 void *freelist_old, unsigned long counters_old,
368 void *freelist_new, unsigned long counters_new,
371 VM_BUG_ON(!irqs_disabled());
372 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
373 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
374 if (s->flags & __CMPXCHG_DOUBLE) {
375 if (cmpxchg_double(&page->freelist, &page->counters,
376 freelist_old, counters_old,
377 freelist_new, counters_new))
383 if (page->freelist == freelist_old &&
384 page->counters == counters_old) {
385 page->freelist = freelist_new;
386 page->counters = counters_new;
394 stat(s, CMPXCHG_DOUBLE_FAIL);
396 #ifdef SLUB_DEBUG_CMPXCHG
397 pr_info("%s %s: cmpxchg double redo ", n, s->name);
403 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
404 void *freelist_old, unsigned long counters_old,
405 void *freelist_new, unsigned long counters_new,
408 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
409 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
410 if (s->flags & __CMPXCHG_DOUBLE) {
411 if (cmpxchg_double(&page->freelist, &page->counters,
412 freelist_old, counters_old,
413 freelist_new, counters_new))
420 local_irq_save(flags);
422 if (page->freelist == freelist_old &&
423 page->counters == counters_old) {
424 page->freelist = freelist_new;
425 page->counters = counters_new;
427 local_irq_restore(flags);
431 local_irq_restore(flags);
435 stat(s, CMPXCHG_DOUBLE_FAIL);
437 #ifdef SLUB_DEBUG_CMPXCHG
438 pr_info("%s %s: cmpxchg double redo ", n, s->name);
444 #ifdef CONFIG_SLUB_DEBUG
446 * Determine a map of object in use on a page.
448 * Node listlock must be held to guarantee that the page does
449 * not vanish from under us.
451 static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
454 void *addr = page_address(page);
456 for (p = page->freelist; p; p = get_freepointer(s, p))
457 set_bit(slab_index(p, s, addr), map);
460 static inline unsigned int size_from_object(struct kmem_cache *s)
462 if (s->flags & SLAB_RED_ZONE)
463 return s->size - s->red_left_pad;
468 static inline void *restore_red_left(struct kmem_cache *s, void *p)
470 if (s->flags & SLAB_RED_ZONE)
471 p -= s->red_left_pad;
479 #if defined(CONFIG_SLUB_DEBUG_ON)
480 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
482 static slab_flags_t slub_debug;
485 static char *slub_debug_slabs;
486 static int disable_higher_order_debug;
489 * slub is about to manipulate internal object metadata. This memory lies
490 * outside the range of the allocated object, so accessing it would normally
491 * be reported by kasan as a bounds error. metadata_access_enable() is used
492 * to tell kasan that these accesses are OK.
494 static inline void metadata_access_enable(void)
496 kasan_disable_current();
499 static inline void metadata_access_disable(void)
501 kasan_enable_current();
508 /* Verify that a pointer has an address that is valid within a slab page */
509 static inline int check_valid_pointer(struct kmem_cache *s,
510 struct page *page, void *object)
517 base = page_address(page);
518 object = kasan_reset_tag(object);
519 object = restore_red_left(s, object);
520 if (object < base || object >= base + page->objects * s->size ||
521 (object - base) % s->size) {
528 static void print_section(char *level, char *text, u8 *addr,
531 metadata_access_enable();
532 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
534 metadata_access_disable();
538 * See comment in calculate_sizes().
540 static inline bool freeptr_outside_object(struct kmem_cache *s)
542 return s->offset >= s->inuse;
546 * Return offset of the end of info block which is inuse + free pointer if
547 * not overlapping with object.
549 static inline unsigned int get_info_end(struct kmem_cache *s)
551 if (freeptr_outside_object(s))
552 return s->inuse + sizeof(void *);
557 static struct track *get_track(struct kmem_cache *s, void *object,
558 enum track_item alloc)
562 p = object + get_info_end(s);
567 static void set_track(struct kmem_cache *s, void *object,
568 enum track_item alloc, unsigned long addr)
570 struct track *p = get_track(s, object, alloc);
573 #ifdef CONFIG_STACKTRACE
574 unsigned int nr_entries;
576 metadata_access_enable();
577 nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
578 metadata_access_disable();
580 if (nr_entries < TRACK_ADDRS_COUNT)
581 p->addrs[nr_entries] = 0;
584 p->cpu = smp_processor_id();
585 p->pid = current->pid;
588 memset(p, 0, sizeof(struct track));
592 static void init_tracking(struct kmem_cache *s, void *object)
594 if (!(s->flags & SLAB_STORE_USER))
597 set_track(s, object, TRACK_FREE, 0UL);
598 set_track(s, object, TRACK_ALLOC, 0UL);
601 static void print_track(const char *s, struct track *t, unsigned long pr_time)
606 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
607 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
608 #ifdef CONFIG_STACKTRACE
611 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
613 pr_err("\t%pS\n", (void *)t->addrs[i]);
620 static void print_tracking(struct kmem_cache *s, void *object)
622 unsigned long pr_time = jiffies;
623 if (!(s->flags & SLAB_STORE_USER))
626 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
627 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
630 static void print_page_info(struct page *page)
632 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
633 page, page->objects, page->inuse, page->freelist, page->flags);
637 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
639 struct va_format vaf;
645 pr_err("=============================================================================\n");
646 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
647 pr_err("-----------------------------------------------------------------------------\n\n");
649 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
653 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
655 struct va_format vaf;
661 pr_err("FIX %s: %pV\n", s->name, &vaf);
665 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
666 void **freelist, void *nextfree)
668 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
669 !check_valid_pointer(s, page, nextfree) && freelist) {
670 object_err(s, page, *freelist, "Freechain corrupt");
672 slab_fix(s, "Isolate corrupted freechain");
679 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
681 unsigned int off; /* Offset of last byte */
682 u8 *addr = page_address(page);
684 print_tracking(s, p);
686 print_page_info(page);
688 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
689 p, p - addr, get_freepointer(s, p));
691 if (s->flags & SLAB_RED_ZONE)
692 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
694 else if (p > addr + 16)
695 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
697 print_section(KERN_ERR, "Object ", p,
698 min_t(unsigned int, s->object_size, PAGE_SIZE));
699 if (s->flags & SLAB_RED_ZONE)
700 print_section(KERN_ERR, "Redzone ", p + s->object_size,
701 s->inuse - s->object_size);
703 off = get_info_end(s);
705 if (s->flags & SLAB_STORE_USER)
706 off += 2 * sizeof(struct track);
708 off += kasan_metadata_size(s);
710 if (off != size_from_object(s))
711 /* Beginning of the filler is the free pointer */
712 print_section(KERN_ERR, "Padding ", p + off,
713 size_from_object(s) - off);
718 void object_err(struct kmem_cache *s, struct page *page,
719 u8 *object, char *reason)
721 slab_bug(s, "%s", reason);
722 print_trailer(s, page, object);
725 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
726 const char *fmt, ...)
732 vsnprintf(buf, sizeof(buf), fmt, args);
734 slab_bug(s, "%s", buf);
735 print_page_info(page);
739 static void init_object(struct kmem_cache *s, void *object, u8 val)
743 if (s->flags & SLAB_RED_ZONE)
744 memset(p - s->red_left_pad, val, s->red_left_pad);
746 if (s->flags & __OBJECT_POISON) {
747 memset(p, POISON_FREE, s->object_size - 1);
748 p[s->object_size - 1] = POISON_END;
751 if (s->flags & SLAB_RED_ZONE)
752 memset(p + s->object_size, val, s->inuse - s->object_size);
755 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
756 void *from, void *to)
758 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
759 memset(from, data, to - from);
762 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
763 u8 *object, char *what,
764 u8 *start, unsigned int value, unsigned int bytes)
769 metadata_access_enable();
770 fault = memchr_inv(start, value, bytes);
771 metadata_access_disable();
776 while (end > fault && end[-1] == value)
779 slab_bug(s, "%s overwritten", what);
780 pr_err("INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
781 fault, end - 1, fault[0], value);
782 print_trailer(s, page, object);
784 restore_bytes(s, what, value, fault, end);
792 * Bytes of the object to be managed.
793 * If the freepointer may overlay the object then the free
794 * pointer is at the middle of the object.
796 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
799 * object + s->object_size
800 * Padding to reach word boundary. This is also used for Redzoning.
801 * Padding is extended by another word if Redzoning is enabled and
802 * object_size == inuse.
804 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
805 * 0xcc (RED_ACTIVE) for objects in use.
808 * Meta data starts here.
810 * A. Free pointer (if we cannot overwrite object on free)
811 * B. Tracking data for SLAB_STORE_USER
812 * C. Padding to reach required alignment boundary or at mininum
813 * one word if debugging is on to be able to detect writes
814 * before the word boundary.
816 * Padding is done using 0x5a (POISON_INUSE)
819 * Nothing is used beyond s->size.
821 * If slabcaches are merged then the object_size and inuse boundaries are mostly
822 * ignored. And therefore no slab options that rely on these boundaries
823 * may be used with merged slabcaches.
826 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
828 unsigned long off = get_info_end(s); /* The end of info */
830 if (s->flags & SLAB_STORE_USER)
831 /* We also have user information there */
832 off += 2 * sizeof(struct track);
834 off += kasan_metadata_size(s);
836 if (size_from_object(s) == off)
839 return check_bytes_and_report(s, page, p, "Object padding",
840 p + off, POISON_INUSE, size_from_object(s) - off);
843 /* Check the pad bytes at the end of a slab page */
844 static int slab_pad_check(struct kmem_cache *s, struct page *page)
853 if (!(s->flags & SLAB_POISON))
856 start = page_address(page);
857 length = page_size(page);
858 end = start + length;
859 remainder = length % s->size;
863 pad = end - remainder;
864 metadata_access_enable();
865 fault = memchr_inv(pad, POISON_INUSE, remainder);
866 metadata_access_disable();
869 while (end > fault && end[-1] == POISON_INUSE)
872 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
873 print_section(KERN_ERR, "Padding ", pad, remainder);
875 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
879 static int check_object(struct kmem_cache *s, struct page *page,
880 void *object, u8 val)
883 u8 *endobject = object + s->object_size;
885 if (s->flags & SLAB_RED_ZONE) {
886 if (!check_bytes_and_report(s, page, object, "Left Redzone",
887 object - s->red_left_pad, val, s->red_left_pad))
890 if (!check_bytes_and_report(s, page, object, "Right Redzone",
891 endobject, val, s->inuse - s->object_size))
894 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
895 check_bytes_and_report(s, page, p, "Alignment padding",
896 endobject, POISON_INUSE,
897 s->inuse - s->object_size);
901 if (s->flags & SLAB_POISON) {
902 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
903 (!check_bytes_and_report(s, page, p, "Poison", p,
904 POISON_FREE, s->object_size - 1) ||
905 !check_bytes_and_report(s, page, p, "End Poison",
906 p + s->object_size - 1, POISON_END, 1)))
909 * check_pad_bytes cleans up on its own.
911 check_pad_bytes(s, page, p);
914 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
916 * Object and freepointer overlap. Cannot check
917 * freepointer while object is allocated.
921 /* Check free pointer validity */
922 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
923 object_err(s, page, p, "Freepointer corrupt");
925 * No choice but to zap it and thus lose the remainder
926 * of the free objects in this slab. May cause
927 * another error because the object count is now wrong.
929 set_freepointer(s, p, NULL);
935 static int check_slab(struct kmem_cache *s, struct page *page)
939 VM_BUG_ON(!irqs_disabled());
941 if (!PageSlab(page)) {
942 slab_err(s, page, "Not a valid slab page");
946 maxobj = order_objects(compound_order(page), s->size);
947 if (page->objects > maxobj) {
948 slab_err(s, page, "objects %u > max %u",
949 page->objects, maxobj);
952 if (page->inuse > page->objects) {
953 slab_err(s, page, "inuse %u > max %u",
954 page->inuse, page->objects);
957 /* Slab_pad_check fixes things up after itself */
958 slab_pad_check(s, page);
963 * Determine if a certain object on a page is on the freelist. Must hold the
964 * slab lock to guarantee that the chains are in a consistent state.
966 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
974 while (fp && nr <= page->objects) {
977 if (!check_valid_pointer(s, page, fp)) {
979 object_err(s, page, object,
980 "Freechain corrupt");
981 set_freepointer(s, object, NULL);
983 slab_err(s, page, "Freepointer corrupt");
984 page->freelist = NULL;
985 page->inuse = page->objects;
986 slab_fix(s, "Freelist cleared");
992 fp = get_freepointer(s, object);
996 max_objects = order_objects(compound_order(page), s->size);
997 if (max_objects > MAX_OBJS_PER_PAGE)
998 max_objects = MAX_OBJS_PER_PAGE;
1000 if (page->objects != max_objects) {
1001 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1002 page->objects, max_objects);
1003 page->objects = max_objects;
1004 slab_fix(s, "Number of objects adjusted.");
1006 if (page->inuse != page->objects - nr) {
1007 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1008 page->inuse, page->objects - nr);
1009 page->inuse = page->objects - nr;
1010 slab_fix(s, "Object count adjusted.");
1012 return search == NULL;
1015 static void trace(struct kmem_cache *s, struct page *page, void *object,
1018 if (s->flags & SLAB_TRACE) {
1019 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1021 alloc ? "alloc" : "free",
1022 object, page->inuse,
1026 print_section(KERN_INFO, "Object ", (void *)object,
1034 * Tracking of fully allocated slabs for debugging purposes.
1036 static void add_full(struct kmem_cache *s,
1037 struct kmem_cache_node *n, struct page *page)
1039 if (!(s->flags & SLAB_STORE_USER))
1042 lockdep_assert_held(&n->list_lock);
1043 list_add(&page->slab_list, &n->full);
1046 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1048 if (!(s->flags & SLAB_STORE_USER))
1051 lockdep_assert_held(&n->list_lock);
1052 list_del(&page->slab_list);
1055 /* Tracking of the number of slabs for debugging purposes */
1056 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1058 struct kmem_cache_node *n = get_node(s, node);
1060 return atomic_long_read(&n->nr_slabs);
1063 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1065 return atomic_long_read(&n->nr_slabs);
1068 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1070 struct kmem_cache_node *n = get_node(s, node);
1073 * May be called early in order to allocate a slab for the
1074 * kmem_cache_node structure. Solve the chicken-egg
1075 * dilemma by deferring the increment of the count during
1076 * bootstrap (see early_kmem_cache_node_alloc).
1079 atomic_long_inc(&n->nr_slabs);
1080 atomic_long_add(objects, &n->total_objects);
1083 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1085 struct kmem_cache_node *n = get_node(s, node);
1087 atomic_long_dec(&n->nr_slabs);
1088 atomic_long_sub(objects, &n->total_objects);
1091 /* Object debug checks for alloc/free paths */
1092 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1095 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1098 init_object(s, object, SLUB_RED_INACTIVE);
1099 init_tracking(s, object);
1103 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1105 if (!(s->flags & SLAB_POISON))
1108 metadata_access_enable();
1109 memset(addr, POISON_INUSE, page_size(page));
1110 metadata_access_disable();
1113 static inline int alloc_consistency_checks(struct kmem_cache *s,
1114 struct page *page, void *object)
1116 if (!check_slab(s, page))
1119 if (!check_valid_pointer(s, page, object)) {
1120 object_err(s, page, object, "Freelist Pointer check fails");
1124 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1130 static noinline int alloc_debug_processing(struct kmem_cache *s,
1132 void *object, unsigned long addr)
1134 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1135 if (!alloc_consistency_checks(s, page, object))
1139 /* Success perform special debug activities for allocs */
1140 if (s->flags & SLAB_STORE_USER)
1141 set_track(s, object, TRACK_ALLOC, addr);
1142 trace(s, page, object, 1);
1143 init_object(s, object, SLUB_RED_ACTIVE);
1147 if (PageSlab(page)) {
1149 * If this is a slab page then lets do the best we can
1150 * to avoid issues in the future. Marking all objects
1151 * as used avoids touching the remaining objects.
1153 slab_fix(s, "Marking all objects used");
1154 page->inuse = page->objects;
1155 page->freelist = NULL;
1160 static inline int free_consistency_checks(struct kmem_cache *s,
1161 struct page *page, void *object, unsigned long addr)
1163 if (!check_valid_pointer(s, page, object)) {
1164 slab_err(s, page, "Invalid object pointer 0x%p", object);
1168 if (on_freelist(s, page, object)) {
1169 object_err(s, page, object, "Object already free");
1173 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1176 if (unlikely(s != page->slab_cache)) {
1177 if (!PageSlab(page)) {
1178 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1180 } else if (!page->slab_cache) {
1181 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1185 object_err(s, page, object,
1186 "page slab pointer corrupt.");
1192 /* Supports checking bulk free of a constructed freelist */
1193 static noinline int free_debug_processing(
1194 struct kmem_cache *s, struct page *page,
1195 void *head, void *tail, int bulk_cnt,
1198 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1199 void *object = head;
1201 unsigned long uninitialized_var(flags);
1204 spin_lock_irqsave(&n->list_lock, flags);
1207 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1208 if (!check_slab(s, page))
1215 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1216 if (!free_consistency_checks(s, page, object, addr))
1220 if (s->flags & SLAB_STORE_USER)
1221 set_track(s, object, TRACK_FREE, addr);
1222 trace(s, page, object, 0);
1223 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1224 init_object(s, object, SLUB_RED_INACTIVE);
1226 /* Reached end of constructed freelist yet? */
1227 if (object != tail) {
1228 object = get_freepointer(s, object);
1234 if (cnt != bulk_cnt)
1235 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1239 spin_unlock_irqrestore(&n->list_lock, flags);
1241 slab_fix(s, "Object at 0x%p not freed", object);
1245 static int __init setup_slub_debug(char *str)
1247 slub_debug = DEBUG_DEFAULT_FLAGS;
1248 if (*str++ != '=' || !*str)
1250 * No options specified. Switch on full debugging.
1256 * No options but restriction on slabs. This means full
1257 * debugging for slabs matching a pattern.
1264 * Switch off all debugging measures.
1269 * Determine which debug features should be switched on
1271 for (; *str && *str != ','; str++) {
1272 switch (tolower(*str)) {
1274 slub_debug |= SLAB_CONSISTENCY_CHECKS;
1277 slub_debug |= SLAB_RED_ZONE;
1280 slub_debug |= SLAB_POISON;
1283 slub_debug |= SLAB_STORE_USER;
1286 slub_debug |= SLAB_TRACE;
1289 slub_debug |= SLAB_FAILSLAB;
1293 * Avoid enabling debugging on caches if its minimum
1294 * order would increase as a result.
1296 disable_higher_order_debug = 1;
1299 pr_err("slub_debug option '%c' unknown. skipped\n",
1306 slub_debug_slabs = str + 1;
1308 if ((static_branch_unlikely(&init_on_alloc) ||
1309 static_branch_unlikely(&init_on_free)) &&
1310 (slub_debug & SLAB_POISON))
1311 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1315 __setup("slub_debug", setup_slub_debug);
1318 * kmem_cache_flags - apply debugging options to the cache
1319 * @object_size: the size of an object without meta data
1320 * @flags: flags to set
1321 * @name: name of the cache
1322 * @ctor: constructor function
1324 * Debug option(s) are applied to @flags. In addition to the debug
1325 * option(s), if a slab name (or multiple) is specified i.e.
1326 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1327 * then only the select slabs will receive the debug option(s).
1329 slab_flags_t kmem_cache_flags(unsigned int object_size,
1330 slab_flags_t flags, const char *name,
1331 void (*ctor)(void *))
1336 /* If slub_debug = 0, it folds into the if conditional. */
1337 if (!slub_debug_slabs)
1338 return flags | slub_debug;
1341 iter = slub_debug_slabs;
1346 end = strchrnul(iter, ',');
1348 glob = strnchr(iter, end - iter, '*');
1350 cmplen = glob - iter;
1352 cmplen = max_t(size_t, len, (end - iter));
1354 if (!strncmp(name, iter, cmplen)) {
1355 flags |= slub_debug;
1366 #else /* !CONFIG_SLUB_DEBUG */
1367 static inline void setup_object_debug(struct kmem_cache *s,
1368 struct page *page, void *object) {}
1370 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1372 static inline int alloc_debug_processing(struct kmem_cache *s,
1373 struct page *page, void *object, unsigned long addr) { return 0; }
1375 static inline int free_debug_processing(
1376 struct kmem_cache *s, struct page *page,
1377 void *head, void *tail, int bulk_cnt,
1378 unsigned long addr) { return 0; }
1380 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1382 static inline int check_object(struct kmem_cache *s, struct page *page,
1383 void *object, u8 val) { return 1; }
1384 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1385 struct page *page) {}
1386 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1387 struct page *page) {}
1388 slab_flags_t kmem_cache_flags(unsigned int object_size,
1389 slab_flags_t flags, const char *name,
1390 void (*ctor)(void *))
1394 #define slub_debug 0
1396 #define disable_higher_order_debug 0
1398 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1400 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1402 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1404 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1407 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1408 void **freelist, void *nextfree)
1412 #endif /* CONFIG_SLUB_DEBUG */
1415 * Hooks for other subsystems that check memory allocations. In a typical
1416 * production configuration these hooks all should produce no code at all.
1418 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1420 ptr = kasan_kmalloc_large(ptr, size, flags);
1421 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1422 kmemleak_alloc(ptr, size, 1, flags);
1426 static __always_inline void kfree_hook(void *x)
1429 kasan_kfree_large(x, _RET_IP_);
1432 static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x)
1434 kmemleak_free_recursive(x, s->flags);
1437 * Trouble is that we may no longer disable interrupts in the fast path
1438 * So in order to make the debug calls that expect irqs to be
1439 * disabled we need to disable interrupts temporarily.
1441 #ifdef CONFIG_LOCKDEP
1443 unsigned long flags;
1445 local_irq_save(flags);
1446 debug_check_no_locks_freed(x, s->object_size);
1447 local_irq_restore(flags);
1450 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1451 debug_check_no_obj_freed(x, s->object_size);
1453 /* KASAN might put x into memory quarantine, delaying its reuse */
1454 return kasan_slab_free(s, x, _RET_IP_);
1457 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1458 void **head, void **tail,
1464 void *old_tail = *tail ? *tail : *head;
1467 /* Head and tail of the reconstructed freelist */
1473 next = get_freepointer(s, object);
1475 if (slab_want_init_on_free(s)) {
1477 * Clear the object and the metadata, but don't touch
1480 memset(object, 0, s->object_size);
1481 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad
1483 memset((char *)object + s->inuse, 0,
1484 s->size - s->inuse - rsize);
1487 /* If object's reuse doesn't have to be delayed */
1488 if (!slab_free_hook(s, object)) {
1489 /* Move object to the new freelist */
1490 set_freepointer(s, object, *head);
1496 * Adjust the reconstructed freelist depth
1497 * accordingly if object's reuse is delayed.
1501 } while (object != old_tail);
1506 return *head != NULL;
1509 static void *setup_object(struct kmem_cache *s, struct page *page,
1512 setup_object_debug(s, page, object);
1513 object = kasan_init_slab_obj(s, object);
1514 if (unlikely(s->ctor)) {
1515 kasan_unpoison_object_data(s, object);
1517 kasan_poison_object_data(s, object);
1523 * Slab allocation and freeing
1525 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1526 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1529 unsigned int order = oo_order(oo);
1531 if (node == NUMA_NO_NODE)
1532 page = alloc_pages(flags, order);
1534 page = __alloc_pages_node(node, flags, order);
1536 if (page && charge_slab_page(page, flags, order, s)) {
1537 __free_pages(page, order);
1544 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1545 /* Pre-initialize the random sequence cache */
1546 static int init_cache_random_seq(struct kmem_cache *s)
1548 unsigned int count = oo_objects(s->oo);
1551 /* Bailout if already initialised */
1555 err = cache_random_seq_create(s, count, GFP_KERNEL);
1557 pr_err("SLUB: Unable to initialize free list for %s\n",
1562 /* Transform to an offset on the set of pages */
1563 if (s->random_seq) {
1566 for (i = 0; i < count; i++)
1567 s->random_seq[i] *= s->size;
1572 /* Initialize each random sequence freelist per cache */
1573 static void __init init_freelist_randomization(void)
1575 struct kmem_cache *s;
1577 mutex_lock(&slab_mutex);
1579 list_for_each_entry(s, &slab_caches, list)
1580 init_cache_random_seq(s);
1582 mutex_unlock(&slab_mutex);
1585 /* Get the next entry on the pre-computed freelist randomized */
1586 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1587 unsigned long *pos, void *start,
1588 unsigned long page_limit,
1589 unsigned long freelist_count)
1594 * If the target page allocation failed, the number of objects on the
1595 * page might be smaller than the usual size defined by the cache.
1598 idx = s->random_seq[*pos];
1600 if (*pos >= freelist_count)
1602 } while (unlikely(idx >= page_limit));
1604 return (char *)start + idx;
1607 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1608 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1613 unsigned long idx, pos, page_limit, freelist_count;
1615 if (page->objects < 2 || !s->random_seq)
1618 freelist_count = oo_objects(s->oo);
1619 pos = get_random_int() % freelist_count;
1621 page_limit = page->objects * s->size;
1622 start = fixup_red_left(s, page_address(page));
1624 /* First entry is used as the base of the freelist */
1625 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1627 cur = setup_object(s, page, cur);
1628 page->freelist = cur;
1630 for (idx = 1; idx < page->objects; idx++) {
1631 next = next_freelist_entry(s, page, &pos, start, page_limit,
1633 next = setup_object(s, page, next);
1634 set_freepointer(s, cur, next);
1637 set_freepointer(s, cur, NULL);
1642 static inline int init_cache_random_seq(struct kmem_cache *s)
1646 static inline void init_freelist_randomization(void) { }
1647 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1651 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1653 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1656 struct kmem_cache_order_objects oo = s->oo;
1658 void *start, *p, *next;
1662 flags &= gfp_allowed_mask;
1664 if (gfpflags_allow_blocking(flags))
1667 flags |= s->allocflags;
1670 * Let the initial higher-order allocation fail under memory pressure
1671 * so we fall-back to the minimum order allocation.
1673 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1674 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1675 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1677 page = alloc_slab_page(s, alloc_gfp, node, oo);
1678 if (unlikely(!page)) {
1682 * Allocation may have failed due to fragmentation.
1683 * Try a lower order alloc if possible
1685 page = alloc_slab_page(s, alloc_gfp, node, oo);
1686 if (unlikely(!page))
1688 stat(s, ORDER_FALLBACK);
1691 page->objects = oo_objects(oo);
1693 page->slab_cache = s;
1694 __SetPageSlab(page);
1695 if (page_is_pfmemalloc(page))
1696 SetPageSlabPfmemalloc(page);
1698 kasan_poison_slab(page);
1700 start = page_address(page);
1702 setup_page_debug(s, page, start);
1704 shuffle = shuffle_freelist(s, page);
1707 start = fixup_red_left(s, start);
1708 start = setup_object(s, page, start);
1709 page->freelist = start;
1710 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1712 next = setup_object(s, page, next);
1713 set_freepointer(s, p, next);
1716 set_freepointer(s, p, NULL);
1719 page->inuse = page->objects;
1723 if (gfpflags_allow_blocking(flags))
1724 local_irq_disable();
1728 inc_slabs_node(s, page_to_nid(page), page->objects);
1733 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1735 if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
1736 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
1737 flags &= ~GFP_SLAB_BUG_MASK;
1738 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
1739 invalid_mask, &invalid_mask, flags, &flags);
1743 return allocate_slab(s,
1744 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1747 static void __free_slab(struct kmem_cache *s, struct page *page)
1749 int order = compound_order(page);
1750 int pages = 1 << order;
1752 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1755 slab_pad_check(s, page);
1756 for_each_object(p, s, page_address(page),
1758 check_object(s, page, p, SLUB_RED_INACTIVE);
1761 __ClearPageSlabPfmemalloc(page);
1762 __ClearPageSlab(page);
1764 page->mapping = NULL;
1765 if (current->reclaim_state)
1766 current->reclaim_state->reclaimed_slab += pages;
1767 uncharge_slab_page(page, order, s);
1768 __free_pages(page, order);
1771 static void rcu_free_slab(struct rcu_head *h)
1773 struct page *page = container_of(h, struct page, rcu_head);
1775 __free_slab(page->slab_cache, page);
1778 static void free_slab(struct kmem_cache *s, struct page *page)
1780 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1781 call_rcu(&page->rcu_head, rcu_free_slab);
1783 __free_slab(s, page);
1786 static void discard_slab(struct kmem_cache *s, struct page *page)
1788 dec_slabs_node(s, page_to_nid(page), page->objects);
1793 * Management of partially allocated slabs.
1796 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1799 if (tail == DEACTIVATE_TO_TAIL)
1800 list_add_tail(&page->slab_list, &n->partial);
1802 list_add(&page->slab_list, &n->partial);
1805 static inline void add_partial(struct kmem_cache_node *n,
1806 struct page *page, int tail)
1808 lockdep_assert_held(&n->list_lock);
1809 __add_partial(n, page, tail);
1812 static inline void remove_partial(struct kmem_cache_node *n,
1815 lockdep_assert_held(&n->list_lock);
1816 list_del(&page->slab_list);
1821 * Remove slab from the partial list, freeze it and
1822 * return the pointer to the freelist.
1824 * Returns a list of objects or NULL if it fails.
1826 static inline void *acquire_slab(struct kmem_cache *s,
1827 struct kmem_cache_node *n, struct page *page,
1828 int mode, int *objects)
1831 unsigned long counters;
1834 lockdep_assert_held(&n->list_lock);
1837 * Zap the freelist and set the frozen bit.
1838 * The old freelist is the list of objects for the
1839 * per cpu allocation list.
1841 freelist = page->freelist;
1842 counters = page->counters;
1843 new.counters = counters;
1844 *objects = new.objects - new.inuse;
1846 new.inuse = page->objects;
1847 new.freelist = NULL;
1849 new.freelist = freelist;
1852 VM_BUG_ON(new.frozen);
1855 if (!__cmpxchg_double_slab(s, page,
1857 new.freelist, new.counters,
1861 remove_partial(n, page);
1866 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1867 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1870 * Try to allocate a partial slab from a specific node.
1872 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1873 struct kmem_cache_cpu *c, gfp_t flags)
1875 struct page *page, *page2;
1876 void *object = NULL;
1877 unsigned int available = 0;
1881 * Racy check. If we mistakenly see no partial slabs then we
1882 * just allocate an empty slab. If we mistakenly try to get a
1883 * partial slab and there is none available then get_partials()
1886 if (!n || !n->nr_partial)
1889 spin_lock(&n->list_lock);
1890 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
1893 if (!pfmemalloc_match(page, flags))
1896 t = acquire_slab(s, n, page, object == NULL, &objects);
1900 available += objects;
1903 stat(s, ALLOC_FROM_PARTIAL);
1906 put_cpu_partial(s, page, 0);
1907 stat(s, CPU_PARTIAL_NODE);
1909 if (!kmem_cache_has_cpu_partial(s)
1910 || available > slub_cpu_partial(s) / 2)
1914 spin_unlock(&n->list_lock);
1919 * Get a page from somewhere. Search in increasing NUMA distances.
1921 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1922 struct kmem_cache_cpu *c)
1925 struct zonelist *zonelist;
1928 enum zone_type high_zoneidx = gfp_zone(flags);
1930 unsigned int cpuset_mems_cookie;
1933 * The defrag ratio allows a configuration of the tradeoffs between
1934 * inter node defragmentation and node local allocations. A lower
1935 * defrag_ratio increases the tendency to do local allocations
1936 * instead of attempting to obtain partial slabs from other nodes.
1938 * If the defrag_ratio is set to 0 then kmalloc() always
1939 * returns node local objects. If the ratio is higher then kmalloc()
1940 * may return off node objects because partial slabs are obtained
1941 * from other nodes and filled up.
1943 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
1944 * (which makes defrag_ratio = 1000) then every (well almost)
1945 * allocation will first attempt to defrag slab caches on other nodes.
1946 * This means scanning over all nodes to look for partial slabs which
1947 * may be expensive if we do it every time we are trying to find a slab
1948 * with available objects.
1950 if (!s->remote_node_defrag_ratio ||
1951 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1955 cpuset_mems_cookie = read_mems_allowed_begin();
1956 zonelist = node_zonelist(mempolicy_slab_node(), flags);
1957 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1958 struct kmem_cache_node *n;
1960 n = get_node(s, zone_to_nid(zone));
1962 if (n && cpuset_zone_allowed(zone, flags) &&
1963 n->nr_partial > s->min_partial) {
1964 object = get_partial_node(s, n, c, flags);
1967 * Don't check read_mems_allowed_retry()
1968 * here - if mems_allowed was updated in
1969 * parallel, that was a harmless race
1970 * between allocation and the cpuset
1977 } while (read_mems_allowed_retry(cpuset_mems_cookie));
1978 #endif /* CONFIG_NUMA */
1983 * Get a partial page, lock it and return it.
1985 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1986 struct kmem_cache_cpu *c)
1989 int searchnode = node;
1991 if (node == NUMA_NO_NODE)
1992 searchnode = numa_mem_id();
1994 object = get_partial_node(s, get_node(s, searchnode), c, flags);
1995 if (object || node != NUMA_NO_NODE)
1998 return get_any_partial(s, flags, c);
2001 #ifdef CONFIG_PREEMPT
2003 * Calculate the next globally unique transaction for disambiguiation
2004 * during cmpxchg. The transactions start with the cpu number and are then
2005 * incremented by CONFIG_NR_CPUS.
2007 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2010 * No preemption supported therefore also no need to check for
2016 static inline unsigned long next_tid(unsigned long tid)
2018 return tid + TID_STEP;
2021 #ifdef SLUB_DEBUG_CMPXCHG
2022 static inline unsigned int tid_to_cpu(unsigned long tid)
2024 return tid % TID_STEP;
2027 static inline unsigned long tid_to_event(unsigned long tid)
2029 return tid / TID_STEP;
2033 static inline unsigned int init_tid(int cpu)
2038 static inline void note_cmpxchg_failure(const char *n,
2039 const struct kmem_cache *s, unsigned long tid)
2041 #ifdef SLUB_DEBUG_CMPXCHG
2042 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2044 pr_info("%s %s: cmpxchg redo ", n, s->name);
2046 #ifdef CONFIG_PREEMPT
2047 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2048 pr_warn("due to cpu change %d -> %d\n",
2049 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2052 if (tid_to_event(tid) != tid_to_event(actual_tid))
2053 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2054 tid_to_event(tid), tid_to_event(actual_tid));
2056 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2057 actual_tid, tid, next_tid(tid));
2059 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2062 static void init_kmem_cache_cpus(struct kmem_cache *s)
2066 for_each_possible_cpu(cpu)
2067 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2071 * Remove the cpu slab
2073 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2074 void *freelist, struct kmem_cache_cpu *c)
2076 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2077 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2079 enum slab_modes l = M_NONE, m = M_NONE;
2081 int tail = DEACTIVATE_TO_HEAD;
2085 if (page->freelist) {
2086 stat(s, DEACTIVATE_REMOTE_FREES);
2087 tail = DEACTIVATE_TO_TAIL;
2091 * Stage one: Free all available per cpu objects back
2092 * to the page freelist while it is still frozen. Leave the
2095 * There is no need to take the list->lock because the page
2098 while (freelist && (nextfree = get_freepointer(s, freelist))) {
2100 unsigned long counters;
2103 * If 'nextfree' is invalid, it is possible that the object at
2104 * 'freelist' is already corrupted. So isolate all objects
2105 * starting at 'freelist'.
2107 if (freelist_corrupted(s, page, &freelist, nextfree))
2111 prior = page->freelist;
2112 counters = page->counters;
2113 set_freepointer(s, freelist, prior);
2114 new.counters = counters;
2116 VM_BUG_ON(!new.frozen);
2118 } while (!__cmpxchg_double_slab(s, page,
2120 freelist, new.counters,
2121 "drain percpu freelist"));
2123 freelist = nextfree;
2127 * Stage two: Ensure that the page is unfrozen while the
2128 * list presence reflects the actual number of objects
2131 * We setup the list membership and then perform a cmpxchg
2132 * with the count. If there is a mismatch then the page
2133 * is not unfrozen but the page is on the wrong list.
2135 * Then we restart the process which may have to remove
2136 * the page from the list that we just put it on again
2137 * because the number of objects in the slab may have
2142 old.freelist = page->freelist;
2143 old.counters = page->counters;
2144 VM_BUG_ON(!old.frozen);
2146 /* Determine target state of the slab */
2147 new.counters = old.counters;
2150 set_freepointer(s, freelist, old.freelist);
2151 new.freelist = freelist;
2153 new.freelist = old.freelist;
2157 if (!new.inuse && n->nr_partial >= s->min_partial)
2159 else if (new.freelist) {
2164 * Taking the spinlock removes the possibility
2165 * that acquire_slab() will see a slab page that
2168 spin_lock(&n->list_lock);
2172 if (kmem_cache_debug(s) && !lock) {
2175 * This also ensures that the scanning of full
2176 * slabs from diagnostic functions will not see
2179 spin_lock(&n->list_lock);
2185 remove_partial(n, page);
2186 else if (l == M_FULL)
2187 remove_full(s, n, page);
2190 add_partial(n, page, tail);
2191 else if (m == M_FULL)
2192 add_full(s, n, page);
2196 if (!__cmpxchg_double_slab(s, page,
2197 old.freelist, old.counters,
2198 new.freelist, new.counters,
2203 spin_unlock(&n->list_lock);
2207 else if (m == M_FULL)
2208 stat(s, DEACTIVATE_FULL);
2209 else if (m == M_FREE) {
2210 stat(s, DEACTIVATE_EMPTY);
2211 discard_slab(s, page);
2220 * Unfreeze all the cpu partial slabs.
2222 * This function must be called with interrupts disabled
2223 * for the cpu using c (or some other guarantee must be there
2224 * to guarantee no concurrent accesses).
2226 static void unfreeze_partials(struct kmem_cache *s,
2227 struct kmem_cache_cpu *c)
2229 #ifdef CONFIG_SLUB_CPU_PARTIAL
2230 struct kmem_cache_node *n = NULL, *n2 = NULL;
2231 struct page *page, *discard_page = NULL;
2233 while ((page = c->partial)) {
2237 c->partial = page->next;
2239 n2 = get_node(s, page_to_nid(page));
2242 spin_unlock(&n->list_lock);
2245 spin_lock(&n->list_lock);
2250 old.freelist = page->freelist;
2251 old.counters = page->counters;
2252 VM_BUG_ON(!old.frozen);
2254 new.counters = old.counters;
2255 new.freelist = old.freelist;
2259 } while (!__cmpxchg_double_slab(s, page,
2260 old.freelist, old.counters,
2261 new.freelist, new.counters,
2262 "unfreezing slab"));
2264 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2265 page->next = discard_page;
2266 discard_page = page;
2268 add_partial(n, page, DEACTIVATE_TO_TAIL);
2269 stat(s, FREE_ADD_PARTIAL);
2274 spin_unlock(&n->list_lock);
2276 while (discard_page) {
2277 page = discard_page;
2278 discard_page = discard_page->next;
2280 stat(s, DEACTIVATE_EMPTY);
2281 discard_slab(s, page);
2284 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2288 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2289 * partial page slot if available.
2291 * If we did not find a slot then simply move all the partials to the
2292 * per node partial list.
2294 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2296 #ifdef CONFIG_SLUB_CPU_PARTIAL
2297 struct page *oldpage;
2305 oldpage = this_cpu_read(s->cpu_slab->partial);
2308 pobjects = oldpage->pobjects;
2309 pages = oldpage->pages;
2310 if (drain && pobjects > s->cpu_partial) {
2311 unsigned long flags;
2313 * partial array is full. Move the existing
2314 * set to the per node partial list.
2316 local_irq_save(flags);
2317 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2318 local_irq_restore(flags);
2322 stat(s, CPU_PARTIAL_DRAIN);
2327 pobjects += page->objects - page->inuse;
2329 page->pages = pages;
2330 page->pobjects = pobjects;
2331 page->next = oldpage;
2333 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2335 if (unlikely(!s->cpu_partial)) {
2336 unsigned long flags;
2338 local_irq_save(flags);
2339 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2340 local_irq_restore(flags);
2343 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2346 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2348 stat(s, CPUSLAB_FLUSH);
2349 deactivate_slab(s, c->page, c->freelist, c);
2351 c->tid = next_tid(c->tid);
2357 * Called from IPI handler with interrupts disabled.
2359 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2361 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2366 unfreeze_partials(s, c);
2369 static void flush_cpu_slab(void *d)
2371 struct kmem_cache *s = d;
2373 __flush_cpu_slab(s, smp_processor_id());
2376 static bool has_cpu_slab(int cpu, void *info)
2378 struct kmem_cache *s = info;
2379 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2381 return c->page || slub_percpu_partial(c);
2384 static void flush_all(struct kmem_cache *s)
2386 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC);
2390 * Use the cpu notifier to insure that the cpu slabs are flushed when
2393 static int slub_cpu_dead(unsigned int cpu)
2395 struct kmem_cache *s;
2396 unsigned long flags;
2398 mutex_lock(&slab_mutex);
2399 list_for_each_entry(s, &slab_caches, list) {
2400 local_irq_save(flags);
2401 __flush_cpu_slab(s, cpu);
2402 local_irq_restore(flags);
2404 mutex_unlock(&slab_mutex);
2409 * Check if the objects in a per cpu structure fit numa
2410 * locality expectations.
2412 static inline int node_match(struct page *page, int node)
2415 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2421 #ifdef CONFIG_SLUB_DEBUG
2422 static int count_free(struct page *page)
2424 return page->objects - page->inuse;
2427 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2429 return atomic_long_read(&n->total_objects);
2431 #endif /* CONFIG_SLUB_DEBUG */
2433 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2434 static unsigned long count_partial(struct kmem_cache_node *n,
2435 int (*get_count)(struct page *))
2437 unsigned long flags;
2438 unsigned long x = 0;
2441 spin_lock_irqsave(&n->list_lock, flags);
2442 list_for_each_entry(page, &n->partial, slab_list)
2443 x += get_count(page);
2444 spin_unlock_irqrestore(&n->list_lock, flags);
2447 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2449 static noinline void
2450 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2452 #ifdef CONFIG_SLUB_DEBUG
2453 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2454 DEFAULT_RATELIMIT_BURST);
2456 struct kmem_cache_node *n;
2458 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2461 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2462 nid, gfpflags, &gfpflags);
2463 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2464 s->name, s->object_size, s->size, oo_order(s->oo),
2467 if (oo_order(s->min) > get_order(s->object_size))
2468 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2471 for_each_kmem_cache_node(s, node, n) {
2472 unsigned long nr_slabs;
2473 unsigned long nr_objs;
2474 unsigned long nr_free;
2476 nr_free = count_partial(n, count_free);
2477 nr_slabs = node_nr_slabs(n);
2478 nr_objs = node_nr_objs(n);
2480 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2481 node, nr_slabs, nr_objs, nr_free);
2486 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2487 int node, struct kmem_cache_cpu **pc)
2490 struct kmem_cache_cpu *c = *pc;
2493 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2495 freelist = get_partial(s, flags, node, c);
2500 page = new_slab(s, flags, node);
2502 c = raw_cpu_ptr(s->cpu_slab);
2507 * No other reference to the page yet so we can
2508 * muck around with it freely without cmpxchg
2510 freelist = page->freelist;
2511 page->freelist = NULL;
2513 stat(s, ALLOC_SLAB);
2521 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2523 if (unlikely(PageSlabPfmemalloc(page)))
2524 return gfp_pfmemalloc_allowed(gfpflags);
2530 * Check the page->freelist of a page and either transfer the freelist to the
2531 * per cpu freelist or deactivate the page.
2533 * The page is still frozen if the return value is not NULL.
2535 * If this function returns NULL then the page has been unfrozen.
2537 * This function must be called with interrupt disabled.
2539 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2542 unsigned long counters;
2546 freelist = page->freelist;
2547 counters = page->counters;
2549 new.counters = counters;
2550 VM_BUG_ON(!new.frozen);
2552 new.inuse = page->objects;
2553 new.frozen = freelist != NULL;
2555 } while (!__cmpxchg_double_slab(s, page,
2564 * Slow path. The lockless freelist is empty or we need to perform
2567 * Processing is still very fast if new objects have been freed to the
2568 * regular freelist. In that case we simply take over the regular freelist
2569 * as the lockless freelist and zap the regular freelist.
2571 * If that is not working then we fall back to the partial lists. We take the
2572 * first element of the freelist as the object to allocate now and move the
2573 * rest of the freelist to the lockless freelist.
2575 * And if we were unable to get a new slab from the partial slab lists then
2576 * we need to allocate a new slab. This is the slowest path since it involves
2577 * a call to the page allocator and the setup of a new slab.
2579 * Version of __slab_alloc to use when we know that interrupts are
2580 * already disabled (which is the case for bulk allocation).
2582 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2583 unsigned long addr, struct kmem_cache_cpu *c)
2591 * if the node is not online or has no normal memory, just
2592 * ignore the node constraint
2594 if (unlikely(node != NUMA_NO_NODE &&
2595 !node_state(node, N_NORMAL_MEMORY)))
2596 node = NUMA_NO_NODE;
2601 if (unlikely(!node_match(page, node))) {
2603 * same as above but node_match() being false already
2604 * implies node != NUMA_NO_NODE
2606 if (!node_state(node, N_NORMAL_MEMORY)) {
2607 node = NUMA_NO_NODE;
2610 stat(s, ALLOC_NODE_MISMATCH);
2611 deactivate_slab(s, page, c->freelist, c);
2617 * By rights, we should be searching for a slab page that was
2618 * PFMEMALLOC but right now, we are losing the pfmemalloc
2619 * information when the page leaves the per-cpu allocator
2621 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2622 deactivate_slab(s, page, c->freelist, c);
2626 /* must check again c->freelist in case of cpu migration or IRQ */
2627 freelist = c->freelist;
2631 freelist = get_freelist(s, page);
2635 stat(s, DEACTIVATE_BYPASS);
2639 stat(s, ALLOC_REFILL);
2643 * freelist is pointing to the list of objects to be used.
2644 * page is pointing to the page from which the objects are obtained.
2645 * That page must be frozen for per cpu allocations to work.
2647 VM_BUG_ON(!c->page->frozen);
2648 c->freelist = get_freepointer(s, freelist);
2649 c->tid = next_tid(c->tid);
2654 if (slub_percpu_partial(c)) {
2655 page = c->page = slub_percpu_partial(c);
2656 slub_set_percpu_partial(c, page);
2657 stat(s, CPU_PARTIAL_ALLOC);
2661 freelist = new_slab_objects(s, gfpflags, node, &c);
2663 if (unlikely(!freelist)) {
2664 slab_out_of_memory(s, gfpflags, node);
2669 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2672 /* Only entered in the debug case */
2673 if (kmem_cache_debug(s) &&
2674 !alloc_debug_processing(s, page, freelist, addr))
2675 goto new_slab; /* Slab failed checks. Next slab needed */
2677 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2682 * Another one that disabled interrupt and compensates for possible
2683 * cpu changes by refetching the per cpu area pointer.
2685 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2686 unsigned long addr, struct kmem_cache_cpu *c)
2689 unsigned long flags;
2691 local_irq_save(flags);
2692 #ifdef CONFIG_PREEMPT
2694 * We may have been preempted and rescheduled on a different
2695 * cpu before disabling interrupts. Need to reload cpu area
2698 c = this_cpu_ptr(s->cpu_slab);
2701 p = ___slab_alloc(s, gfpflags, node, addr, c);
2702 local_irq_restore(flags);
2707 * If the object has been wiped upon free, make sure it's fully initialized by
2708 * zeroing out freelist pointer.
2710 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2713 if (unlikely(slab_want_init_on_free(s)) && obj)
2714 memset((void *)((char *)obj + s->offset), 0, sizeof(void *));
2718 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2719 * have the fastpath folded into their functions. So no function call
2720 * overhead for requests that can be satisfied on the fastpath.
2722 * The fastpath works by first checking if the lockless freelist can be used.
2723 * If not then __slab_alloc is called for slow processing.
2725 * Otherwise we can simply pick the next object from the lockless free list.
2727 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2728 gfp_t gfpflags, int node, unsigned long addr)
2731 struct kmem_cache_cpu *c;
2735 s = slab_pre_alloc_hook(s, gfpflags);
2740 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2741 * enabled. We may switch back and forth between cpus while
2742 * reading from one cpu area. That does not matter as long
2743 * as we end up on the original cpu again when doing the cmpxchg.
2745 * We should guarantee that tid and kmem_cache are retrieved on
2746 * the same cpu. It could be different if CONFIG_PREEMPT so we need
2747 * to check if it is matched or not.
2750 tid = this_cpu_read(s->cpu_slab->tid);
2751 c = raw_cpu_ptr(s->cpu_slab);
2752 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2753 unlikely(tid != READ_ONCE(c->tid)));
2756 * Irqless object alloc/free algorithm used here depends on sequence
2757 * of fetching cpu_slab's data. tid should be fetched before anything
2758 * on c to guarantee that object and page associated with previous tid
2759 * won't be used with current tid. If we fetch tid first, object and
2760 * page could be one associated with next tid and our alloc/free
2761 * request will be failed. In this case, we will retry. So, no problem.
2766 * The transaction ids are globally unique per cpu and per operation on
2767 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2768 * occurs on the right processor and that there was no operation on the
2769 * linked list in between.
2772 object = c->freelist;
2774 if (unlikely(!object || !page || !node_match(page, node))) {
2775 object = __slab_alloc(s, gfpflags, node, addr, c);
2776 stat(s, ALLOC_SLOWPATH);
2778 void *next_object = get_freepointer_safe(s, object);
2781 * The cmpxchg will only match if there was no additional
2782 * operation and if we are on the right processor.
2784 * The cmpxchg does the following atomically (without lock
2786 * 1. Relocate first pointer to the current per cpu area.
2787 * 2. Verify that tid and freelist have not been changed
2788 * 3. If they were not changed replace tid and freelist
2790 * Since this is without lock semantics the protection is only
2791 * against code executing on this cpu *not* from access by
2794 if (unlikely(!this_cpu_cmpxchg_double(
2795 s->cpu_slab->freelist, s->cpu_slab->tid,
2797 next_object, next_tid(tid)))) {
2799 note_cmpxchg_failure("slab_alloc", s, tid);
2802 prefetch_freepointer(s, next_object);
2803 stat(s, ALLOC_FASTPATH);
2806 maybe_wipe_obj_freeptr(s, object);
2808 if (unlikely(slab_want_init_on_alloc(gfpflags, s)) && object)
2809 memset(object, 0, s->object_size);
2811 slab_post_alloc_hook(s, gfpflags, 1, &object);
2816 static __always_inline void *slab_alloc(struct kmem_cache *s,
2817 gfp_t gfpflags, unsigned long addr)
2819 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2822 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2824 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2826 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2831 EXPORT_SYMBOL(kmem_cache_alloc);
2833 #ifdef CONFIG_TRACING
2834 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2836 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2837 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2838 ret = kasan_kmalloc(s, ret, size, gfpflags);
2841 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2845 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2847 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2849 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2850 s->object_size, s->size, gfpflags, node);
2854 EXPORT_SYMBOL(kmem_cache_alloc_node);
2856 #ifdef CONFIG_TRACING
2857 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2859 int node, size_t size)
2861 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2863 trace_kmalloc_node(_RET_IP_, ret,
2864 size, s->size, gfpflags, node);
2866 ret = kasan_kmalloc(s, ret, size, gfpflags);
2869 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2871 #endif /* CONFIG_NUMA */
2874 * Slow path handling. This may still be called frequently since objects
2875 * have a longer lifetime than the cpu slabs in most processing loads.
2877 * So we still attempt to reduce cache line usage. Just take the slab
2878 * lock and free the item. If there is no additional partial page
2879 * handling required then we can return immediately.
2881 static void __slab_free(struct kmem_cache *s, struct page *page,
2882 void *head, void *tail, int cnt,
2889 unsigned long counters;
2890 struct kmem_cache_node *n = NULL;
2891 unsigned long uninitialized_var(flags);
2893 stat(s, FREE_SLOWPATH);
2895 if (kmem_cache_debug(s) &&
2896 !free_debug_processing(s, page, head, tail, cnt, addr))
2901 spin_unlock_irqrestore(&n->list_lock, flags);
2904 prior = page->freelist;
2905 counters = page->counters;
2906 set_freepointer(s, tail, prior);
2907 new.counters = counters;
2908 was_frozen = new.frozen;
2910 if ((!new.inuse || !prior) && !was_frozen) {
2912 if (kmem_cache_has_cpu_partial(s) && !prior) {
2915 * Slab was on no list before and will be
2917 * We can defer the list move and instead
2922 } else { /* Needs to be taken off a list */
2924 n = get_node(s, page_to_nid(page));
2926 * Speculatively acquire the list_lock.
2927 * If the cmpxchg does not succeed then we may
2928 * drop the list_lock without any processing.
2930 * Otherwise the list_lock will synchronize with
2931 * other processors updating the list of slabs.
2933 spin_lock_irqsave(&n->list_lock, flags);
2938 } while (!cmpxchg_double_slab(s, page,
2946 * If we just froze the page then put it onto the
2947 * per cpu partial list.
2949 if (new.frozen && !was_frozen) {
2950 put_cpu_partial(s, page, 1);
2951 stat(s, CPU_PARTIAL_FREE);
2954 * The list lock was not taken therefore no list
2955 * activity can be necessary.
2958 stat(s, FREE_FROZEN);
2962 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
2966 * Objects left in the slab. If it was not on the partial list before
2969 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
2970 remove_full(s, n, page);
2971 add_partial(n, page, DEACTIVATE_TO_TAIL);
2972 stat(s, FREE_ADD_PARTIAL);
2974 spin_unlock_irqrestore(&n->list_lock, flags);
2980 * Slab on the partial list.
2982 remove_partial(n, page);
2983 stat(s, FREE_REMOVE_PARTIAL);
2985 /* Slab must be on the full list */
2986 remove_full(s, n, page);
2989 spin_unlock_irqrestore(&n->list_lock, flags);
2991 discard_slab(s, page);
2995 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2996 * can perform fastpath freeing without additional function calls.
2998 * The fastpath is only possible if we are freeing to the current cpu slab
2999 * of this processor. This typically the case if we have just allocated
3002 * If fastpath is not possible then fall back to __slab_free where we deal
3003 * with all sorts of special processing.
3005 * Bulk free of a freelist with several objects (all pointing to the
3006 * same page) possible by specifying head and tail ptr, plus objects
3007 * count (cnt). Bulk free indicated by tail pointer being set.
3009 static __always_inline void do_slab_free(struct kmem_cache *s,
3010 struct page *page, void *head, void *tail,
3011 int cnt, unsigned long addr)
3013 void *tail_obj = tail ? : head;
3014 struct kmem_cache_cpu *c;
3018 * Determine the currently cpus per cpu slab.
3019 * The cpu may change afterward. However that does not matter since
3020 * data is retrieved via this pointer. If we are on the same cpu
3021 * during the cmpxchg then the free will succeed.
3024 tid = this_cpu_read(s->cpu_slab->tid);
3025 c = raw_cpu_ptr(s->cpu_slab);
3026 } while (IS_ENABLED(CONFIG_PREEMPT) &&
3027 unlikely(tid != READ_ONCE(c->tid)));
3029 /* Same with comment on barrier() in slab_alloc_node() */
3032 if (likely(page == c->page)) {
3033 void **freelist = READ_ONCE(c->freelist);
3035 set_freepointer(s, tail_obj, freelist);
3037 if (unlikely(!this_cpu_cmpxchg_double(
3038 s->cpu_slab->freelist, s->cpu_slab->tid,
3040 head, next_tid(tid)))) {
3042 note_cmpxchg_failure("slab_free", s, tid);
3045 stat(s, FREE_FASTPATH);
3047 __slab_free(s, page, head, tail_obj, cnt, addr);
3051 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3052 void *head, void *tail, int cnt,
3056 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3057 * to remove objects, whose reuse must be delayed.
3059 if (slab_free_freelist_hook(s, &head, &tail, &cnt))
3060 do_slab_free(s, page, head, tail, cnt, addr);
3063 #ifdef CONFIG_KASAN_GENERIC
3064 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3066 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3070 void kmem_cache_free(struct kmem_cache *s, void *x)
3072 s = cache_from_obj(s, x);
3075 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3076 trace_kmem_cache_free(_RET_IP_, x);
3078 EXPORT_SYMBOL(kmem_cache_free);
3080 struct detached_freelist {
3085 struct kmem_cache *s;
3089 * This function progressively scans the array with free objects (with
3090 * a limited look ahead) and extract objects belonging to the same
3091 * page. It builds a detached freelist directly within the given
3092 * page/objects. This can happen without any need for
3093 * synchronization, because the objects are owned by running process.
3094 * The freelist is build up as a single linked list in the objects.
3095 * The idea is, that this detached freelist can then be bulk
3096 * transferred to the real freelist(s), but only requiring a single
3097 * synchronization primitive. Look ahead in the array is limited due
3098 * to performance reasons.
3101 int build_detached_freelist(struct kmem_cache *s, size_t size,
3102 void **p, struct detached_freelist *df)
3104 size_t first_skipped_index = 0;
3109 /* Always re-init detached_freelist */
3114 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3115 } while (!object && size);
3120 page = virt_to_head_page(object);
3122 /* Handle kalloc'ed objects */
3123 if (unlikely(!PageSlab(page))) {
3124 BUG_ON(!PageCompound(page));
3126 __free_pages(page, compound_order(page));
3127 p[size] = NULL; /* mark object processed */
3130 /* Derive kmem_cache from object */
3131 df->s = page->slab_cache;
3133 df->s = cache_from_obj(s, object); /* Support for memcg */
3136 /* Start new detached freelist */
3138 set_freepointer(df->s, object, NULL);
3140 df->freelist = object;
3141 p[size] = NULL; /* mark object processed */
3147 continue; /* Skip processed objects */
3149 /* df->page is always set at this point */
3150 if (df->page == virt_to_head_page(object)) {
3151 /* Opportunity build freelist */
3152 set_freepointer(df->s, object, df->freelist);
3153 df->freelist = object;
3155 p[size] = NULL; /* mark object processed */
3160 /* Limit look ahead search */
3164 if (!first_skipped_index)
3165 first_skipped_index = size + 1;
3168 return first_skipped_index;
3171 /* Note that interrupts must be enabled when calling this function. */
3172 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3178 struct detached_freelist df;
3180 size = build_detached_freelist(s, size, p, &df);
3184 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
3185 } while (likely(size));
3187 EXPORT_SYMBOL(kmem_cache_free_bulk);
3189 /* Note that interrupts must be enabled when calling this function. */
3190 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3193 struct kmem_cache_cpu *c;
3196 /* memcg and kmem_cache debug support */
3197 s = slab_pre_alloc_hook(s, flags);
3201 * Drain objects in the per cpu slab, while disabling local
3202 * IRQs, which protects against PREEMPT and interrupts
3203 * handlers invoking normal fastpath.
3205 local_irq_disable();
3206 c = this_cpu_ptr(s->cpu_slab);
3208 for (i = 0; i < size; i++) {
3209 void *object = c->freelist;
3211 if (unlikely(!object)) {
3213 * We may have removed an object from c->freelist using
3214 * the fastpath in the previous iteration; in that case,
3215 * c->tid has not been bumped yet.
3216 * Since ___slab_alloc() may reenable interrupts while
3217 * allocating memory, we should bump c->tid now.
3219 c->tid = next_tid(c->tid);
3222 * Invoking slow path likely have side-effect
3223 * of re-populating per CPU c->freelist
3225 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3227 if (unlikely(!p[i]))
3230 c = this_cpu_ptr(s->cpu_slab);
3231 maybe_wipe_obj_freeptr(s, p[i]);
3233 continue; /* goto for-loop */
3235 c->freelist = get_freepointer(s, object);
3237 maybe_wipe_obj_freeptr(s, p[i]);
3239 c->tid = next_tid(c->tid);
3242 /* Clear memory outside IRQ disabled fastpath loop */
3243 if (unlikely(slab_want_init_on_alloc(flags, s))) {
3246 for (j = 0; j < i; j++)
3247 memset(p[j], 0, s->object_size);
3250 /* memcg and kmem_cache debug support */
3251 slab_post_alloc_hook(s, flags, size, p);
3255 slab_post_alloc_hook(s, flags, i, p);
3256 __kmem_cache_free_bulk(s, i, p);
3259 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3263 * Object placement in a slab is made very easy because we always start at
3264 * offset 0. If we tune the size of the object to the alignment then we can
3265 * get the required alignment by putting one properly sized object after
3268 * Notice that the allocation order determines the sizes of the per cpu
3269 * caches. Each processor has always one slab available for allocations.
3270 * Increasing the allocation order reduces the number of times that slabs
3271 * must be moved on and off the partial lists and is therefore a factor in
3276 * Mininum / Maximum order of slab pages. This influences locking overhead
3277 * and slab fragmentation. A higher order reduces the number of partial slabs
3278 * and increases the number of allocations possible without having to
3279 * take the list_lock.
3281 static unsigned int slub_min_order;
3282 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3283 static unsigned int slub_min_objects;
3286 * Calculate the order of allocation given an slab object size.
3288 * The order of allocation has significant impact on performance and other
3289 * system components. Generally order 0 allocations should be preferred since
3290 * order 0 does not cause fragmentation in the page allocator. Larger objects
3291 * be problematic to put into order 0 slabs because there may be too much
3292 * unused space left. We go to a higher order if more than 1/16th of the slab
3295 * In order to reach satisfactory performance we must ensure that a minimum
3296 * number of objects is in one slab. Otherwise we may generate too much
3297 * activity on the partial lists which requires taking the list_lock. This is
3298 * less a concern for large slabs though which are rarely used.
3300 * slub_max_order specifies the order where we begin to stop considering the
3301 * number of objects in a slab as critical. If we reach slub_max_order then
3302 * we try to keep the page order as low as possible. So we accept more waste
3303 * of space in favor of a small page order.
3305 * Higher order allocations also allow the placement of more objects in a
3306 * slab and thereby reduce object handling overhead. If the user has
3307 * requested a higher mininum order then we start with that one instead of
3308 * the smallest order which will fit the object.
3310 static inline unsigned int slab_order(unsigned int size,
3311 unsigned int min_objects, unsigned int max_order,
3312 unsigned int fract_leftover)
3314 unsigned int min_order = slub_min_order;
3317 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3318 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3320 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3321 order <= max_order; order++) {
3323 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3326 rem = slab_size % size;
3328 if (rem <= slab_size / fract_leftover)
3335 static inline int calculate_order(unsigned int size)
3338 unsigned int min_objects;
3339 unsigned int max_objects;
3342 * Attempt to find best configuration for a slab. This
3343 * works by first attempting to generate a layout with
3344 * the best configuration and backing off gradually.
3346 * First we increase the acceptable waste in a slab. Then
3347 * we reduce the minimum objects required in a slab.
3349 min_objects = slub_min_objects;
3351 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3352 max_objects = order_objects(slub_max_order, size);
3353 min_objects = min(min_objects, max_objects);
3355 while (min_objects > 1) {
3356 unsigned int fraction;
3359 while (fraction >= 4) {
3360 order = slab_order(size, min_objects,
3361 slub_max_order, fraction);
3362 if (order <= slub_max_order)
3370 * We were unable to place multiple objects in a slab. Now
3371 * lets see if we can place a single object there.
3373 order = slab_order(size, 1, slub_max_order, 1);
3374 if (order <= slub_max_order)
3378 * Doh this slab cannot be placed using slub_max_order.
3380 order = slab_order(size, 1, MAX_ORDER, 1);
3381 if (order < MAX_ORDER)
3387 init_kmem_cache_node(struct kmem_cache_node *n)
3390 spin_lock_init(&n->list_lock);
3391 INIT_LIST_HEAD(&n->partial);
3392 #ifdef CONFIG_SLUB_DEBUG
3393 atomic_long_set(&n->nr_slabs, 0);
3394 atomic_long_set(&n->total_objects, 0);
3395 INIT_LIST_HEAD(&n->full);
3399 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3401 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3402 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3405 * Must align to double word boundary for the double cmpxchg
3406 * instructions to work; see __pcpu_double_call_return_bool().
3408 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3409 2 * sizeof(void *));
3414 init_kmem_cache_cpus(s);
3419 static struct kmem_cache *kmem_cache_node;
3422 * No kmalloc_node yet so do it by hand. We know that this is the first
3423 * slab on the node for this slabcache. There are no concurrent accesses
3426 * Note that this function only works on the kmem_cache_node
3427 * when allocating for the kmem_cache_node. This is used for bootstrapping
3428 * memory on a fresh node that has no slab structures yet.
3430 static void early_kmem_cache_node_alloc(int node)
3433 struct kmem_cache_node *n;
3435 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3437 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3440 if (page_to_nid(page) != node) {
3441 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3442 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3447 #ifdef CONFIG_SLUB_DEBUG
3448 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3449 init_tracking(kmem_cache_node, n);
3451 n = kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
3453 page->freelist = get_freepointer(kmem_cache_node, n);
3456 kmem_cache_node->node[node] = n;
3457 init_kmem_cache_node(n);
3458 inc_slabs_node(kmem_cache_node, node, page->objects);
3461 * No locks need to be taken here as it has just been
3462 * initialized and there is no concurrent access.
3464 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3467 static void free_kmem_cache_nodes(struct kmem_cache *s)
3470 struct kmem_cache_node *n;
3472 for_each_kmem_cache_node(s, node, n) {
3473 s->node[node] = NULL;
3474 kmem_cache_free(kmem_cache_node, n);
3478 void __kmem_cache_release(struct kmem_cache *s)
3480 cache_random_seq_destroy(s);
3481 free_percpu(s->cpu_slab);
3482 free_kmem_cache_nodes(s);
3485 static int init_kmem_cache_nodes(struct kmem_cache *s)
3489 for_each_node_state(node, N_NORMAL_MEMORY) {
3490 struct kmem_cache_node *n;
3492 if (slab_state == DOWN) {
3493 early_kmem_cache_node_alloc(node);
3496 n = kmem_cache_alloc_node(kmem_cache_node,
3500 free_kmem_cache_nodes(s);
3504 init_kmem_cache_node(n);
3510 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3512 if (min < MIN_PARTIAL)
3514 else if (min > MAX_PARTIAL)
3516 s->min_partial = min;
3519 static void set_cpu_partial(struct kmem_cache *s)
3521 #ifdef CONFIG_SLUB_CPU_PARTIAL
3523 * cpu_partial determined the maximum number of objects kept in the
3524 * per cpu partial lists of a processor.
3526 * Per cpu partial lists mainly contain slabs that just have one
3527 * object freed. If they are used for allocation then they can be
3528 * filled up again with minimal effort. The slab will never hit the
3529 * per node partial lists and therefore no locking will be required.
3531 * This setting also determines
3533 * A) The number of objects from per cpu partial slabs dumped to the
3534 * per node list when we reach the limit.
3535 * B) The number of objects in cpu partial slabs to extract from the
3536 * per node list when we run out of per cpu objects. We only fetch
3537 * 50% to keep some capacity around for frees.
3539 if (!kmem_cache_has_cpu_partial(s))
3541 else if (s->size >= PAGE_SIZE)
3543 else if (s->size >= 1024)
3545 else if (s->size >= 256)
3546 s->cpu_partial = 13;
3548 s->cpu_partial = 30;
3553 * calculate_sizes() determines the order and the distribution of data within
3556 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3558 slab_flags_t flags = s->flags;
3559 unsigned int size = s->object_size;
3563 * Round up object size to the next word boundary. We can only
3564 * place the free pointer at word boundaries and this determines
3565 * the possible location of the free pointer.
3567 size = ALIGN(size, sizeof(void *));
3569 #ifdef CONFIG_SLUB_DEBUG
3571 * Determine if we can poison the object itself. If the user of
3572 * the slab may touch the object after free or before allocation
3573 * then we should never poison the object itself.
3575 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3577 s->flags |= __OBJECT_POISON;
3579 s->flags &= ~__OBJECT_POISON;
3583 * If we are Redzoning then check if there is some space between the
3584 * end of the object and the free pointer. If not then add an
3585 * additional word to have some bytes to store Redzone information.
3587 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3588 size += sizeof(void *);
3592 * With that we have determined the number of bytes in actual use
3593 * by the object. This is the potential offset to the free pointer.
3597 if ((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3598 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
3601 * Relocate free pointer after the object if it is not
3602 * permitted to overwrite the first word of the object on
3605 * This is the case if we do RCU, have a constructor or
3606 * destructor, are poisoning the objects, or are
3607 * redzoning an object smaller than sizeof(void *).
3609 * The assumption that s->offset >= s->inuse means free
3610 * pointer is outside of the object is used in the
3611 * freeptr_outside_object() function. If that is no
3612 * longer true, the function needs to be modified.
3615 size += sizeof(void *);
3618 #ifdef CONFIG_SLUB_DEBUG
3619 if (flags & SLAB_STORE_USER)
3621 * Need to store information about allocs and frees after
3624 size += 2 * sizeof(struct track);
3627 kasan_cache_create(s, &size, &s->flags);
3628 #ifdef CONFIG_SLUB_DEBUG
3629 if (flags & SLAB_RED_ZONE) {
3631 * Add some empty padding so that we can catch
3632 * overwrites from earlier objects rather than let
3633 * tracking information or the free pointer be
3634 * corrupted if a user writes before the start
3637 size += sizeof(void *);
3639 s->red_left_pad = sizeof(void *);
3640 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3641 size += s->red_left_pad;
3646 * SLUB stores one object immediately after another beginning from
3647 * offset 0. In order to align the objects we have to simply size
3648 * each object to conform to the alignment.
3650 size = ALIGN(size, s->align);
3652 if (forced_order >= 0)
3653 order = forced_order;
3655 order = calculate_order(size);
3662 s->allocflags |= __GFP_COMP;
3664 if (s->flags & SLAB_CACHE_DMA)
3665 s->allocflags |= GFP_DMA;
3667 if (s->flags & SLAB_CACHE_DMA32)
3668 s->allocflags |= GFP_DMA32;
3670 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3671 s->allocflags |= __GFP_RECLAIMABLE;
3674 * Determine the number of objects per slab
3676 s->oo = oo_make(order, size);
3677 s->min = oo_make(get_order(size), size);
3678 if (oo_objects(s->oo) > oo_objects(s->max))
3681 return !!oo_objects(s->oo);
3684 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3686 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3687 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3688 s->random = get_random_long();
3691 if (!calculate_sizes(s, -1))
3693 if (disable_higher_order_debug) {
3695 * Disable debugging flags that store metadata if the min slab
3698 if (get_order(s->size) > get_order(s->object_size)) {
3699 s->flags &= ~DEBUG_METADATA_FLAGS;
3701 if (!calculate_sizes(s, -1))
3706 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3707 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3708 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3709 /* Enable fast mode */
3710 s->flags |= __CMPXCHG_DOUBLE;
3714 * The larger the object size is, the more pages we want on the partial
3715 * list to avoid pounding the page allocator excessively.
3717 set_min_partial(s, ilog2(s->size) / 2);
3722 s->remote_node_defrag_ratio = 1000;
3725 /* Initialize the pre-computed randomized freelist if slab is up */
3726 if (slab_state >= UP) {
3727 if (init_cache_random_seq(s))
3731 if (!init_kmem_cache_nodes(s))
3734 if (alloc_kmem_cache_cpus(s))
3738 __kmem_cache_release(s);
3742 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3745 #ifdef CONFIG_SLUB_DEBUG
3746 void *addr = page_address(page);
3748 unsigned long *map = bitmap_zalloc(page->objects, GFP_ATOMIC);
3751 slab_err(s, page, text, s->name);
3754 get_map(s, page, map);
3755 for_each_object(p, s, addr, page->objects) {
3757 if (!test_bit(slab_index(p, s, addr), map)) {
3758 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3759 print_tracking(s, p);
3768 * Attempt to free all partial slabs on a node.
3769 * This is called from __kmem_cache_shutdown(). We must take list_lock
3770 * because sysfs file might still access partial list after the shutdowning.
3772 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3775 struct page *page, *h;
3777 BUG_ON(irqs_disabled());
3778 spin_lock_irq(&n->list_lock);
3779 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3781 remove_partial(n, page);
3782 list_add(&page->slab_list, &discard);
3784 list_slab_objects(s, page,
3785 "Objects remaining in %s on __kmem_cache_shutdown()");
3788 spin_unlock_irq(&n->list_lock);
3790 list_for_each_entry_safe(page, h, &discard, slab_list)
3791 discard_slab(s, page);
3794 bool __kmem_cache_empty(struct kmem_cache *s)
3797 struct kmem_cache_node *n;
3799 for_each_kmem_cache_node(s, node, n)
3800 if (n->nr_partial || slabs_node(s, node))
3806 * Release all resources used by a slab cache.
3808 int __kmem_cache_shutdown(struct kmem_cache *s)
3811 struct kmem_cache_node *n;
3814 /* Attempt to free all objects */
3815 for_each_kmem_cache_node(s, node, n) {
3817 if (n->nr_partial || slabs_node(s, node))
3820 sysfs_slab_remove(s);
3824 /********************************************************************
3826 *******************************************************************/
3828 static int __init setup_slub_min_order(char *str)
3830 get_option(&str, (int *)&slub_min_order);
3835 __setup("slub_min_order=", setup_slub_min_order);
3837 static int __init setup_slub_max_order(char *str)
3839 get_option(&str, (int *)&slub_max_order);
3840 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
3845 __setup("slub_max_order=", setup_slub_max_order);
3847 static int __init setup_slub_min_objects(char *str)
3849 get_option(&str, (int *)&slub_min_objects);
3854 __setup("slub_min_objects=", setup_slub_min_objects);
3856 void *__kmalloc(size_t size, gfp_t flags)
3858 struct kmem_cache *s;
3861 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3862 return kmalloc_large(size, flags);
3864 s = kmalloc_slab(size, flags);
3866 if (unlikely(ZERO_OR_NULL_PTR(s)))
3869 ret = slab_alloc(s, flags, _RET_IP_);
3871 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3873 ret = kasan_kmalloc(s, ret, size, flags);
3877 EXPORT_SYMBOL(__kmalloc);
3880 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3884 unsigned int order = get_order(size);
3886 flags |= __GFP_COMP;
3887 page = alloc_pages_node(node, flags, order);
3889 ptr = page_address(page);
3890 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
3894 return kmalloc_large_node_hook(ptr, size, flags);
3897 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3899 struct kmem_cache *s;
3902 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
3903 ret = kmalloc_large_node(size, flags, node);
3905 trace_kmalloc_node(_RET_IP_, ret,
3906 size, PAGE_SIZE << get_order(size),
3912 s = kmalloc_slab(size, flags);
3914 if (unlikely(ZERO_OR_NULL_PTR(s)))
3917 ret = slab_alloc_node(s, flags, node, _RET_IP_);
3919 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3921 ret = kasan_kmalloc(s, ret, size, flags);
3925 EXPORT_SYMBOL(__kmalloc_node);
3926 #endif /* CONFIG_NUMA */
3928 #ifdef CONFIG_HARDENED_USERCOPY
3930 * Rejects incorrectly sized objects and objects that are to be copied
3931 * to/from userspace but do not fall entirely within the containing slab
3932 * cache's usercopy region.
3934 * Returns NULL if check passes, otherwise const char * to name of cache
3935 * to indicate an error.
3937 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
3940 struct kmem_cache *s;
3941 unsigned int offset;
3944 ptr = kasan_reset_tag(ptr);
3946 /* Find object and usable object size. */
3947 s = page->slab_cache;
3949 /* Reject impossible pointers. */
3950 if (ptr < page_address(page))
3951 usercopy_abort("SLUB object not in SLUB page?!", NULL,
3954 /* Find offset within object. */
3955 offset = (ptr - page_address(page)) % s->size;
3957 /* Adjust for redzone and reject if within the redzone. */
3958 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) {
3959 if (offset < s->red_left_pad)
3960 usercopy_abort("SLUB object in left red zone",
3961 s->name, to_user, offset, n);
3962 offset -= s->red_left_pad;
3965 /* Allow address range falling entirely within usercopy region. */
3966 if (offset >= s->useroffset &&
3967 offset - s->useroffset <= s->usersize &&
3968 n <= s->useroffset - offset + s->usersize)
3972 * If the copy is still within the allocated object, produce
3973 * a warning instead of rejecting the copy. This is intended
3974 * to be a temporary method to find any missing usercopy
3977 object_size = slab_ksize(s);
3978 if (usercopy_fallback &&
3979 offset <= object_size && n <= object_size - offset) {
3980 usercopy_warn("SLUB object", s->name, to_user, offset, n);
3984 usercopy_abort("SLUB object", s->name, to_user, offset, n);
3986 #endif /* CONFIG_HARDENED_USERCOPY */
3988 size_t __ksize(const void *object)
3992 if (unlikely(object == ZERO_SIZE_PTR))
3995 page = virt_to_head_page(object);
3997 if (unlikely(!PageSlab(page))) {
3998 WARN_ON(!PageCompound(page));
3999 return page_size(page);
4002 return slab_ksize(page->slab_cache);
4004 EXPORT_SYMBOL(__ksize);
4006 void kfree(const void *x)
4009 void *object = (void *)x;
4011 trace_kfree(_RET_IP_, x);
4013 if (unlikely(ZERO_OR_NULL_PTR(x)))
4016 page = virt_to_head_page(x);
4017 if (unlikely(!PageSlab(page))) {
4018 unsigned int order = compound_order(page);
4020 BUG_ON(!PageCompound(page));
4022 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
4024 __free_pages(page, order);
4027 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4029 EXPORT_SYMBOL(kfree);
4031 #define SHRINK_PROMOTE_MAX 32
4034 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4035 * up most to the head of the partial lists. New allocations will then
4036 * fill those up and thus they can be removed from the partial lists.
4038 * The slabs with the least items are placed last. This results in them
4039 * being allocated from last increasing the chance that the last objects
4040 * are freed in them.
4042 int __kmem_cache_shrink(struct kmem_cache *s)
4046 struct kmem_cache_node *n;
4049 struct list_head discard;
4050 struct list_head promote[SHRINK_PROMOTE_MAX];
4051 unsigned long flags;
4055 for_each_kmem_cache_node(s, node, n) {
4056 INIT_LIST_HEAD(&discard);
4057 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4058 INIT_LIST_HEAD(promote + i);
4060 spin_lock_irqsave(&n->list_lock, flags);
4063 * Build lists of slabs to discard or promote.
4065 * Note that concurrent frees may occur while we hold the
4066 * list_lock. page->inuse here is the upper limit.
4068 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4069 int free = page->objects - page->inuse;
4071 /* Do not reread page->inuse */
4074 /* We do not keep full slabs on the list */
4077 if (free == page->objects) {
4078 list_move(&page->slab_list, &discard);
4080 } else if (free <= SHRINK_PROMOTE_MAX)
4081 list_move(&page->slab_list, promote + free - 1);
4085 * Promote the slabs filled up most to the head of the
4088 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4089 list_splice(promote + i, &n->partial);
4091 spin_unlock_irqrestore(&n->list_lock, flags);
4093 /* Release empty slabs */
4094 list_for_each_entry_safe(page, t, &discard, slab_list)
4095 discard_slab(s, page);
4097 if (slabs_node(s, node))
4105 void __kmemcg_cache_deactivate_after_rcu(struct kmem_cache *s)
4108 * Called with all the locks held after a sched RCU grace period.
4109 * Even if @s becomes empty after shrinking, we can't know that @s
4110 * doesn't have allocations already in-flight and thus can't
4111 * destroy @s until the associated memcg is released.
4113 * However, let's remove the sysfs files for empty caches here.
4114 * Each cache has a lot of interface files which aren't
4115 * particularly useful for empty draining caches; otherwise, we can
4116 * easily end up with millions of unnecessary sysfs files on
4117 * systems which have a lot of memory and transient cgroups.
4119 if (!__kmem_cache_shrink(s))
4120 sysfs_slab_remove(s);
4123 void __kmemcg_cache_deactivate(struct kmem_cache *s)
4126 * Disable empty slabs caching. Used to avoid pinning offline
4127 * memory cgroups by kmem pages that can be freed.
4129 slub_set_cpu_partial(s, 0);
4132 #endif /* CONFIG_MEMCG */
4134 static int slab_mem_going_offline_callback(void *arg)
4136 struct kmem_cache *s;
4138 mutex_lock(&slab_mutex);
4139 list_for_each_entry(s, &slab_caches, list)
4140 __kmem_cache_shrink(s);
4141 mutex_unlock(&slab_mutex);
4146 static void slab_mem_offline_callback(void *arg)
4148 struct kmem_cache_node *n;
4149 struct kmem_cache *s;
4150 struct memory_notify *marg = arg;
4153 offline_node = marg->status_change_nid_normal;
4156 * If the node still has available memory. we need kmem_cache_node
4159 if (offline_node < 0)
4162 mutex_lock(&slab_mutex);
4163 list_for_each_entry(s, &slab_caches, list) {
4164 n = get_node(s, offline_node);
4167 * if n->nr_slabs > 0, slabs still exist on the node
4168 * that is going down. We were unable to free them,
4169 * and offline_pages() function shouldn't call this
4170 * callback. So, we must fail.
4172 BUG_ON(slabs_node(s, offline_node));
4174 s->node[offline_node] = NULL;
4175 kmem_cache_free(kmem_cache_node, n);
4178 mutex_unlock(&slab_mutex);
4181 static int slab_mem_going_online_callback(void *arg)
4183 struct kmem_cache_node *n;
4184 struct kmem_cache *s;
4185 struct memory_notify *marg = arg;
4186 int nid = marg->status_change_nid_normal;
4190 * If the node's memory is already available, then kmem_cache_node is
4191 * already created. Nothing to do.
4197 * We are bringing a node online. No memory is available yet. We must
4198 * allocate a kmem_cache_node structure in order to bring the node
4201 mutex_lock(&slab_mutex);
4202 list_for_each_entry(s, &slab_caches, list) {
4204 * XXX: kmem_cache_alloc_node will fallback to other nodes
4205 * since memory is not yet available from the node that
4208 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4213 init_kmem_cache_node(n);
4217 mutex_unlock(&slab_mutex);
4221 static int slab_memory_callback(struct notifier_block *self,
4222 unsigned long action, void *arg)
4227 case MEM_GOING_ONLINE:
4228 ret = slab_mem_going_online_callback(arg);
4230 case MEM_GOING_OFFLINE:
4231 ret = slab_mem_going_offline_callback(arg);
4234 case MEM_CANCEL_ONLINE:
4235 slab_mem_offline_callback(arg);
4238 case MEM_CANCEL_OFFLINE:
4242 ret = notifier_from_errno(ret);
4248 static struct notifier_block slab_memory_callback_nb = {
4249 .notifier_call = slab_memory_callback,
4250 .priority = SLAB_CALLBACK_PRI,
4253 /********************************************************************
4254 * Basic setup of slabs
4255 *******************************************************************/
4258 * Used for early kmem_cache structures that were allocated using
4259 * the page allocator. Allocate them properly then fix up the pointers
4260 * that may be pointing to the wrong kmem_cache structure.
4263 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4266 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4267 struct kmem_cache_node *n;
4269 memcpy(s, static_cache, kmem_cache->object_size);
4272 * This runs very early, and only the boot processor is supposed to be
4273 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4276 __flush_cpu_slab(s, smp_processor_id());
4277 for_each_kmem_cache_node(s, node, n) {
4280 list_for_each_entry(p, &n->partial, slab_list)
4283 #ifdef CONFIG_SLUB_DEBUG
4284 list_for_each_entry(p, &n->full, slab_list)
4288 slab_init_memcg_params(s);
4289 list_add(&s->list, &slab_caches);
4290 memcg_link_cache(s, NULL);
4294 void __init kmem_cache_init(void)
4296 static __initdata struct kmem_cache boot_kmem_cache,
4297 boot_kmem_cache_node;
4299 if (debug_guardpage_minorder())
4302 kmem_cache_node = &boot_kmem_cache_node;
4303 kmem_cache = &boot_kmem_cache;
4305 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4306 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4308 register_hotmemory_notifier(&slab_memory_callback_nb);
4310 /* Able to allocate the per node structures */
4311 slab_state = PARTIAL;
4313 create_boot_cache(kmem_cache, "kmem_cache",
4314 offsetof(struct kmem_cache, node) +
4315 nr_node_ids * sizeof(struct kmem_cache_node *),
4316 SLAB_HWCACHE_ALIGN, 0, 0);
4318 kmem_cache = bootstrap(&boot_kmem_cache);
4319 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4321 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4322 setup_kmalloc_cache_index_table();
4323 create_kmalloc_caches(0);
4325 /* Setup random freelists for each cache */
4326 init_freelist_randomization();
4328 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4331 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4333 slub_min_order, slub_max_order, slub_min_objects,
4334 nr_cpu_ids, nr_node_ids);
4337 void __init kmem_cache_init_late(void)
4342 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4343 slab_flags_t flags, void (*ctor)(void *))
4345 struct kmem_cache *s, *c;
4347 s = find_mergeable(size, align, flags, name, ctor);
4352 * Adjust the object sizes so that we clear
4353 * the complete object on kzalloc.
4355 s->object_size = max(s->object_size, size);
4356 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4358 for_each_memcg_cache(c, s) {
4359 c->object_size = s->object_size;
4360 c->inuse = max(c->inuse, ALIGN(size, sizeof(void *)));
4363 if (sysfs_slab_alias(s, name)) {
4372 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4376 err = kmem_cache_open(s, flags);
4380 /* Mutex is not taken during early boot */
4381 if (slab_state <= UP)
4384 memcg_propagate_slab_attrs(s);
4385 err = sysfs_slab_add(s);
4387 __kmem_cache_release(s);
4392 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4394 struct kmem_cache *s;
4397 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4398 return kmalloc_large(size, gfpflags);
4400 s = kmalloc_slab(size, gfpflags);
4402 if (unlikely(ZERO_OR_NULL_PTR(s)))
4405 ret = slab_alloc(s, gfpflags, caller);
4407 /* Honor the call site pointer we received. */
4408 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4414 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4415 int node, unsigned long caller)
4417 struct kmem_cache *s;
4420 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4421 ret = kmalloc_large_node(size, gfpflags, node);
4423 trace_kmalloc_node(caller, ret,
4424 size, PAGE_SIZE << get_order(size),
4430 s = kmalloc_slab(size, gfpflags);
4432 if (unlikely(ZERO_OR_NULL_PTR(s)))
4435 ret = slab_alloc_node(s, gfpflags, node, caller);
4437 /* Honor the call site pointer we received. */
4438 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4445 static int count_inuse(struct page *page)
4450 static int count_total(struct page *page)
4452 return page->objects;
4456 #ifdef CONFIG_SLUB_DEBUG
4457 static int validate_slab(struct kmem_cache *s, struct page *page,
4461 void *addr = page_address(page);
4463 if (!check_slab(s, page) ||
4464 !on_freelist(s, page, NULL))
4467 /* Now we know that a valid freelist exists */
4468 bitmap_zero(map, page->objects);
4470 get_map(s, page, map);
4471 for_each_object(p, s, addr, page->objects) {
4472 if (test_bit(slab_index(p, s, addr), map))
4473 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4477 for_each_object(p, s, addr, page->objects)
4478 if (!test_bit(slab_index(p, s, addr), map))
4479 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4484 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4488 validate_slab(s, page, map);
4492 static int validate_slab_node(struct kmem_cache *s,
4493 struct kmem_cache_node *n, unsigned long *map)
4495 unsigned long count = 0;
4497 unsigned long flags;
4499 spin_lock_irqsave(&n->list_lock, flags);
4501 list_for_each_entry(page, &n->partial, slab_list) {
4502 validate_slab_slab(s, page, map);
4505 if (count != n->nr_partial)
4506 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4507 s->name, count, n->nr_partial);
4509 if (!(s->flags & SLAB_STORE_USER))
4512 list_for_each_entry(page, &n->full, slab_list) {
4513 validate_slab_slab(s, page, map);
4516 if (count != atomic_long_read(&n->nr_slabs))
4517 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4518 s->name, count, atomic_long_read(&n->nr_slabs));
4521 spin_unlock_irqrestore(&n->list_lock, flags);
4525 static long validate_slab_cache(struct kmem_cache *s)
4528 unsigned long count = 0;
4529 struct kmem_cache_node *n;
4530 unsigned long *map = bitmap_alloc(oo_objects(s->max), GFP_KERNEL);
4536 for_each_kmem_cache_node(s, node, n)
4537 count += validate_slab_node(s, n, map);
4542 * Generate lists of code addresses where slabcache objects are allocated
4547 unsigned long count;
4554 DECLARE_BITMAP(cpus, NR_CPUS);
4560 unsigned long count;
4561 struct location *loc;
4564 static void free_loc_track(struct loc_track *t)
4567 free_pages((unsigned long)t->loc,
4568 get_order(sizeof(struct location) * t->max));
4571 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4576 order = get_order(sizeof(struct location) * max);
4578 l = (void *)__get_free_pages(flags, order);
4583 memcpy(l, t->loc, sizeof(struct location) * t->count);
4591 static int add_location(struct loc_track *t, struct kmem_cache *s,
4592 const struct track *track)
4594 long start, end, pos;
4596 unsigned long caddr;
4597 unsigned long age = jiffies - track->when;
4603 pos = start + (end - start + 1) / 2;
4606 * There is nothing at "end". If we end up there
4607 * we need to add something to before end.
4612 caddr = t->loc[pos].addr;
4613 if (track->addr == caddr) {
4619 if (age < l->min_time)
4621 if (age > l->max_time)
4624 if (track->pid < l->min_pid)
4625 l->min_pid = track->pid;
4626 if (track->pid > l->max_pid)
4627 l->max_pid = track->pid;
4629 cpumask_set_cpu(track->cpu,
4630 to_cpumask(l->cpus));
4632 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4636 if (track->addr < caddr)
4643 * Not found. Insert new tracking element.
4645 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4651 (t->count - pos) * sizeof(struct location));
4654 l->addr = track->addr;
4658 l->min_pid = track->pid;
4659 l->max_pid = track->pid;
4660 cpumask_clear(to_cpumask(l->cpus));
4661 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4662 nodes_clear(l->nodes);
4663 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4667 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4668 struct page *page, enum track_item alloc,
4671 void *addr = page_address(page);
4674 bitmap_zero(map, page->objects);
4675 get_map(s, page, map);
4677 for_each_object(p, s, addr, page->objects)
4678 if (!test_bit(slab_index(p, s, addr), map))
4679 add_location(t, s, get_track(s, p, alloc));
4682 static int list_locations(struct kmem_cache *s, char *buf,
4683 enum track_item alloc)
4687 struct loc_track t = { 0, 0, NULL };
4689 struct kmem_cache_node *n;
4690 unsigned long *map = bitmap_alloc(oo_objects(s->max), GFP_KERNEL);
4692 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4695 return sprintf(buf, "Out of memory\n");
4697 /* Push back cpu slabs */
4700 for_each_kmem_cache_node(s, node, n) {
4701 unsigned long flags;
4704 if (!atomic_long_read(&n->nr_slabs))
4707 spin_lock_irqsave(&n->list_lock, flags);
4708 list_for_each_entry(page, &n->partial, slab_list)
4709 process_slab(&t, s, page, alloc, map);
4710 list_for_each_entry(page, &n->full, slab_list)
4711 process_slab(&t, s, page, alloc, map);
4712 spin_unlock_irqrestore(&n->list_lock, flags);
4715 for (i = 0; i < t.count; i++) {
4716 struct location *l = &t.loc[i];
4718 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4720 len += sprintf(buf + len, "%7ld ", l->count);
4723 len += sprintf(buf + len, "%pS", (void *)l->addr);
4725 len += sprintf(buf + len, "<not-available>");
4727 if (l->sum_time != l->min_time) {
4728 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4730 (long)div_u64(l->sum_time, l->count),
4733 len += sprintf(buf + len, " age=%ld",
4736 if (l->min_pid != l->max_pid)
4737 len += sprintf(buf + len, " pid=%ld-%ld",
4738 l->min_pid, l->max_pid);
4740 len += sprintf(buf + len, " pid=%ld",
4743 if (num_online_cpus() > 1 &&
4744 !cpumask_empty(to_cpumask(l->cpus)) &&
4745 len < PAGE_SIZE - 60)
4746 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4748 cpumask_pr_args(to_cpumask(l->cpus)));
4750 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4751 len < PAGE_SIZE - 60)
4752 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4754 nodemask_pr_args(&l->nodes));
4756 len += sprintf(buf + len, "\n");
4762 len += sprintf(buf, "No data\n");
4765 #endif /* CONFIG_SLUB_DEBUG */
4767 #ifdef SLUB_RESILIENCY_TEST
4768 static void __init resiliency_test(void)
4771 int type = KMALLOC_NORMAL;
4773 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4775 pr_err("SLUB resiliency testing\n");
4776 pr_err("-----------------------\n");
4777 pr_err("A. Corruption after allocation\n");
4779 p = kzalloc(16, GFP_KERNEL);
4781 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4784 validate_slab_cache(kmalloc_caches[type][4]);
4786 /* Hmmm... The next two are dangerous */
4787 p = kzalloc(32, GFP_KERNEL);
4788 p[32 + sizeof(void *)] = 0x34;
4789 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4791 pr_err("If allocated object is overwritten then not detectable\n\n");
4793 validate_slab_cache(kmalloc_caches[type][5]);
4794 p = kzalloc(64, GFP_KERNEL);
4795 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4797 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4799 pr_err("If allocated object is overwritten then not detectable\n\n");
4800 validate_slab_cache(kmalloc_caches[type][6]);
4802 pr_err("\nB. Corruption after free\n");
4803 p = kzalloc(128, GFP_KERNEL);
4806 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4807 validate_slab_cache(kmalloc_caches[type][7]);
4809 p = kzalloc(256, GFP_KERNEL);
4812 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4813 validate_slab_cache(kmalloc_caches[type][8]);
4815 p = kzalloc(512, GFP_KERNEL);
4818 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4819 validate_slab_cache(kmalloc_caches[type][9]);
4823 static void resiliency_test(void) {};
4825 #endif /* SLUB_RESILIENCY_TEST */
4828 enum slab_stat_type {
4829 SL_ALL, /* All slabs */
4830 SL_PARTIAL, /* Only partially allocated slabs */
4831 SL_CPU, /* Only slabs used for cpu caches */
4832 SL_OBJECTS, /* Determine allocated objects not slabs */
4833 SL_TOTAL /* Determine object capacity not slabs */
4836 #define SO_ALL (1 << SL_ALL)
4837 #define SO_PARTIAL (1 << SL_PARTIAL)
4838 #define SO_CPU (1 << SL_CPU)
4839 #define SO_OBJECTS (1 << SL_OBJECTS)
4840 #define SO_TOTAL (1 << SL_TOTAL)
4843 static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON);
4845 static int __init setup_slub_memcg_sysfs(char *str)
4849 if (get_option(&str, &v) > 0)
4850 memcg_sysfs_enabled = v;
4855 __setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs);
4858 static ssize_t show_slab_objects(struct kmem_cache *s,
4859 char *buf, unsigned long flags)
4861 unsigned long total = 0;
4864 unsigned long *nodes;
4866 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
4870 if (flags & SO_CPU) {
4873 for_each_possible_cpu(cpu) {
4874 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4879 page = READ_ONCE(c->page);
4883 node = page_to_nid(page);
4884 if (flags & SO_TOTAL)
4886 else if (flags & SO_OBJECTS)
4894 page = slub_percpu_partial_read_once(c);
4896 node = page_to_nid(page);
4897 if (flags & SO_TOTAL)
4899 else if (flags & SO_OBJECTS)
4910 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
4911 * already held which will conflict with an existing lock order:
4913 * mem_hotplug_lock->slab_mutex->kernfs_mutex
4915 * We don't really need mem_hotplug_lock (to hold off
4916 * slab_mem_going_offline_callback) here because slab's memory hot
4917 * unplug code doesn't destroy the kmem_cache->node[] data.
4920 #ifdef CONFIG_SLUB_DEBUG
4921 if (flags & SO_ALL) {
4922 struct kmem_cache_node *n;
4924 for_each_kmem_cache_node(s, node, n) {
4926 if (flags & SO_TOTAL)
4927 x = atomic_long_read(&n->total_objects);
4928 else if (flags & SO_OBJECTS)
4929 x = atomic_long_read(&n->total_objects) -
4930 count_partial(n, count_free);
4932 x = atomic_long_read(&n->nr_slabs);
4939 if (flags & SO_PARTIAL) {
4940 struct kmem_cache_node *n;
4942 for_each_kmem_cache_node(s, node, n) {
4943 if (flags & SO_TOTAL)
4944 x = count_partial(n, count_total);
4945 else if (flags & SO_OBJECTS)
4946 x = count_partial(n, count_inuse);
4953 x = sprintf(buf, "%lu", total);
4955 for (node = 0; node < nr_node_ids; node++)
4957 x += sprintf(buf + x, " N%d=%lu",
4961 return x + sprintf(buf + x, "\n");
4964 #ifdef CONFIG_SLUB_DEBUG
4965 static int any_slab_objects(struct kmem_cache *s)
4968 struct kmem_cache_node *n;
4970 for_each_kmem_cache_node(s, node, n)
4971 if (atomic_long_read(&n->total_objects))
4978 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4979 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4981 struct slab_attribute {
4982 struct attribute attr;
4983 ssize_t (*show)(struct kmem_cache *s, char *buf);
4984 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4987 #define SLAB_ATTR_RO(_name) \
4988 static struct slab_attribute _name##_attr = \
4989 __ATTR(_name, 0400, _name##_show, NULL)
4991 #define SLAB_ATTR(_name) \
4992 static struct slab_attribute _name##_attr = \
4993 __ATTR(_name, 0600, _name##_show, _name##_store)
4995 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4997 return sprintf(buf, "%u\n", s->size);
4999 SLAB_ATTR_RO(slab_size);
5001 static ssize_t align_show(struct kmem_cache *s, char *buf)
5003 return sprintf(buf, "%u\n", s->align);
5005 SLAB_ATTR_RO(align);
5007 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5009 return sprintf(buf, "%u\n", s->object_size);
5011 SLAB_ATTR_RO(object_size);
5013 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5015 return sprintf(buf, "%u\n", oo_objects(s->oo));
5017 SLAB_ATTR_RO(objs_per_slab);
5019 static ssize_t order_store(struct kmem_cache *s,
5020 const char *buf, size_t length)
5025 err = kstrtouint(buf, 10, &order);
5029 if (order > slub_max_order || order < slub_min_order)
5032 calculate_sizes(s, order);
5036 static ssize_t order_show(struct kmem_cache *s, char *buf)
5038 return sprintf(buf, "%u\n", oo_order(s->oo));
5042 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5044 return sprintf(buf, "%lu\n", s->min_partial);
5047 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5053 err = kstrtoul(buf, 10, &min);
5057 set_min_partial(s, min);
5060 SLAB_ATTR(min_partial);
5062 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5064 return sprintf(buf, "%u\n", slub_cpu_partial(s));
5067 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5070 unsigned int objects;
5073 err = kstrtouint(buf, 10, &objects);
5076 if (objects && !kmem_cache_has_cpu_partial(s))
5079 slub_set_cpu_partial(s, objects);
5083 SLAB_ATTR(cpu_partial);
5085 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5089 return sprintf(buf, "%pS\n", s->ctor);
5093 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5095 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5097 SLAB_ATTR_RO(aliases);
5099 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5101 return show_slab_objects(s, buf, SO_PARTIAL);
5103 SLAB_ATTR_RO(partial);
5105 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5107 return show_slab_objects(s, buf, SO_CPU);
5109 SLAB_ATTR_RO(cpu_slabs);
5111 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5113 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5115 SLAB_ATTR_RO(objects);
5117 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5119 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5121 SLAB_ATTR_RO(objects_partial);
5123 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5130 for_each_online_cpu(cpu) {
5133 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5136 pages += page->pages;
5137 objects += page->pobjects;
5141 len = sprintf(buf, "%d(%d)", objects, pages);
5144 for_each_online_cpu(cpu) {
5147 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5149 if (page && len < PAGE_SIZE - 20)
5150 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
5151 page->pobjects, page->pages);
5154 return len + sprintf(buf + len, "\n");
5156 SLAB_ATTR_RO(slabs_cpu_partial);
5158 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5160 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5163 static ssize_t reclaim_account_store(struct kmem_cache *s,
5164 const char *buf, size_t length)
5166 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
5168 s->flags |= SLAB_RECLAIM_ACCOUNT;
5171 SLAB_ATTR(reclaim_account);
5173 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5175 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5177 SLAB_ATTR_RO(hwcache_align);
5179 #ifdef CONFIG_ZONE_DMA
5180 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5182 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5184 SLAB_ATTR_RO(cache_dma);
5187 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5189 return sprintf(buf, "%u\n", s->usersize);
5191 SLAB_ATTR_RO(usersize);
5193 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5195 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5197 SLAB_ATTR_RO(destroy_by_rcu);
5199 #ifdef CONFIG_SLUB_DEBUG
5200 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5202 return show_slab_objects(s, buf, SO_ALL);
5204 SLAB_ATTR_RO(slabs);
5206 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5208 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5210 SLAB_ATTR_RO(total_objects);
5212 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5214 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5217 static ssize_t sanity_checks_store(struct kmem_cache *s,
5218 const char *buf, size_t length)
5220 s->flags &= ~SLAB_CONSISTENCY_CHECKS;
5221 if (buf[0] == '1') {
5222 s->flags &= ~__CMPXCHG_DOUBLE;
5223 s->flags |= SLAB_CONSISTENCY_CHECKS;
5227 SLAB_ATTR(sanity_checks);
5229 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5231 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5234 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
5238 * Tracing a merged cache is going to give confusing results
5239 * as well as cause other issues like converting a mergeable
5240 * cache into an umergeable one.
5242 if (s->refcount > 1)
5245 s->flags &= ~SLAB_TRACE;
5246 if (buf[0] == '1') {
5247 s->flags &= ~__CMPXCHG_DOUBLE;
5248 s->flags |= SLAB_TRACE;
5254 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5256 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5259 static ssize_t red_zone_store(struct kmem_cache *s,
5260 const char *buf, size_t length)
5262 if (any_slab_objects(s))
5265 s->flags &= ~SLAB_RED_ZONE;
5266 if (buf[0] == '1') {
5267 s->flags |= SLAB_RED_ZONE;
5269 calculate_sizes(s, -1);
5272 SLAB_ATTR(red_zone);
5274 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5276 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5279 static ssize_t poison_store(struct kmem_cache *s,
5280 const char *buf, size_t length)
5282 if (any_slab_objects(s))
5285 s->flags &= ~SLAB_POISON;
5286 if (buf[0] == '1') {
5287 s->flags |= SLAB_POISON;
5289 calculate_sizes(s, -1);
5294 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5296 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5299 static ssize_t store_user_store(struct kmem_cache *s,
5300 const char *buf, size_t length)
5302 if (any_slab_objects(s))
5305 s->flags &= ~SLAB_STORE_USER;
5306 if (buf[0] == '1') {
5307 s->flags &= ~__CMPXCHG_DOUBLE;
5308 s->flags |= SLAB_STORE_USER;
5310 calculate_sizes(s, -1);
5313 SLAB_ATTR(store_user);
5315 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5320 static ssize_t validate_store(struct kmem_cache *s,
5321 const char *buf, size_t length)
5325 if (buf[0] == '1') {
5326 ret = validate_slab_cache(s);
5332 SLAB_ATTR(validate);
5334 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5336 if (!(s->flags & SLAB_STORE_USER))
5338 return list_locations(s, buf, TRACK_ALLOC);
5340 SLAB_ATTR_RO(alloc_calls);
5342 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5344 if (!(s->flags & SLAB_STORE_USER))
5346 return list_locations(s, buf, TRACK_FREE);
5348 SLAB_ATTR_RO(free_calls);
5349 #endif /* CONFIG_SLUB_DEBUG */
5351 #ifdef CONFIG_FAILSLAB
5352 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5354 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5357 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5360 if (s->refcount > 1)
5363 s->flags &= ~SLAB_FAILSLAB;
5365 s->flags |= SLAB_FAILSLAB;
5368 SLAB_ATTR(failslab);
5371 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5376 static ssize_t shrink_store(struct kmem_cache *s,
5377 const char *buf, size_t length)
5380 kmem_cache_shrink_all(s);
5388 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5390 return sprintf(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5393 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5394 const char *buf, size_t length)
5399 err = kstrtouint(buf, 10, &ratio);
5405 s->remote_node_defrag_ratio = ratio * 10;
5409 SLAB_ATTR(remote_node_defrag_ratio);
5412 #ifdef CONFIG_SLUB_STATS
5413 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5415 unsigned long sum = 0;
5418 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5423 for_each_online_cpu(cpu) {
5424 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5430 len = sprintf(buf, "%lu", sum);
5433 for_each_online_cpu(cpu) {
5434 if (data[cpu] && len < PAGE_SIZE - 20)
5435 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5439 return len + sprintf(buf + len, "\n");
5442 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5446 for_each_online_cpu(cpu)
5447 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5450 #define STAT_ATTR(si, text) \
5451 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5453 return show_stat(s, buf, si); \
5455 static ssize_t text##_store(struct kmem_cache *s, \
5456 const char *buf, size_t length) \
5458 if (buf[0] != '0') \
5460 clear_stat(s, si); \
5465 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5466 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5467 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5468 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5469 STAT_ATTR(FREE_FROZEN, free_frozen);
5470 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5471 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5472 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5473 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5474 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5475 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5476 STAT_ATTR(FREE_SLAB, free_slab);
5477 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5478 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5479 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5480 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5481 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5482 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5483 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5484 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5485 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5486 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5487 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5488 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5489 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5490 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5491 #endif /* CONFIG_SLUB_STATS */
5493 static struct attribute *slab_attrs[] = {
5494 &slab_size_attr.attr,
5495 &object_size_attr.attr,
5496 &objs_per_slab_attr.attr,
5498 &min_partial_attr.attr,
5499 &cpu_partial_attr.attr,
5501 &objects_partial_attr.attr,
5503 &cpu_slabs_attr.attr,
5507 &hwcache_align_attr.attr,
5508 &reclaim_account_attr.attr,
5509 &destroy_by_rcu_attr.attr,
5511 &slabs_cpu_partial_attr.attr,
5512 #ifdef CONFIG_SLUB_DEBUG
5513 &total_objects_attr.attr,
5515 &sanity_checks_attr.attr,
5517 &red_zone_attr.attr,
5519 &store_user_attr.attr,
5520 &validate_attr.attr,
5521 &alloc_calls_attr.attr,
5522 &free_calls_attr.attr,
5524 #ifdef CONFIG_ZONE_DMA
5525 &cache_dma_attr.attr,
5528 &remote_node_defrag_ratio_attr.attr,
5530 #ifdef CONFIG_SLUB_STATS
5531 &alloc_fastpath_attr.attr,
5532 &alloc_slowpath_attr.attr,
5533 &free_fastpath_attr.attr,
5534 &free_slowpath_attr.attr,
5535 &free_frozen_attr.attr,
5536 &free_add_partial_attr.attr,
5537 &free_remove_partial_attr.attr,
5538 &alloc_from_partial_attr.attr,
5539 &alloc_slab_attr.attr,
5540 &alloc_refill_attr.attr,
5541 &alloc_node_mismatch_attr.attr,
5542 &free_slab_attr.attr,
5543 &cpuslab_flush_attr.attr,
5544 &deactivate_full_attr.attr,
5545 &deactivate_empty_attr.attr,
5546 &deactivate_to_head_attr.attr,
5547 &deactivate_to_tail_attr.attr,
5548 &deactivate_remote_frees_attr.attr,
5549 &deactivate_bypass_attr.attr,
5550 &order_fallback_attr.attr,
5551 &cmpxchg_double_fail_attr.attr,
5552 &cmpxchg_double_cpu_fail_attr.attr,
5553 &cpu_partial_alloc_attr.attr,
5554 &cpu_partial_free_attr.attr,
5555 &cpu_partial_node_attr.attr,
5556 &cpu_partial_drain_attr.attr,
5558 #ifdef CONFIG_FAILSLAB
5559 &failslab_attr.attr,
5561 &usersize_attr.attr,
5566 static const struct attribute_group slab_attr_group = {
5567 .attrs = slab_attrs,
5570 static ssize_t slab_attr_show(struct kobject *kobj,
5571 struct attribute *attr,
5574 struct slab_attribute *attribute;
5575 struct kmem_cache *s;
5578 attribute = to_slab_attr(attr);
5581 if (!attribute->show)
5584 err = attribute->show(s, buf);
5589 static ssize_t slab_attr_store(struct kobject *kobj,
5590 struct attribute *attr,
5591 const char *buf, size_t len)
5593 struct slab_attribute *attribute;
5594 struct kmem_cache *s;
5597 attribute = to_slab_attr(attr);
5600 if (!attribute->store)
5603 err = attribute->store(s, buf, len);
5605 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5606 struct kmem_cache *c;
5608 mutex_lock(&slab_mutex);
5609 if (s->max_attr_size < len)
5610 s->max_attr_size = len;
5613 * This is a best effort propagation, so this function's return
5614 * value will be determined by the parent cache only. This is
5615 * basically because not all attributes will have a well
5616 * defined semantics for rollbacks - most of the actions will
5617 * have permanent effects.
5619 * Returning the error value of any of the children that fail
5620 * is not 100 % defined, in the sense that users seeing the
5621 * error code won't be able to know anything about the state of
5624 * Only returning the error code for the parent cache at least
5625 * has well defined semantics. The cache being written to
5626 * directly either failed or succeeded, in which case we loop
5627 * through the descendants with best-effort propagation.
5629 for_each_memcg_cache(c, s)
5630 attribute->store(c, buf, len);
5631 mutex_unlock(&slab_mutex);
5637 static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5641 char *buffer = NULL;
5642 struct kmem_cache *root_cache;
5644 if (is_root_cache(s))
5647 root_cache = s->memcg_params.root_cache;
5650 * This mean this cache had no attribute written. Therefore, no point
5651 * in copying default values around
5653 if (!root_cache->max_attr_size)
5656 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5659 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5662 if (!attr || !attr->store || !attr->show)
5666 * It is really bad that we have to allocate here, so we will
5667 * do it only as a fallback. If we actually allocate, though,
5668 * we can just use the allocated buffer until the end.
5670 * Most of the slub attributes will tend to be very small in
5671 * size, but sysfs allows buffers up to a page, so they can
5672 * theoretically happen.
5676 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf) &&
5677 !IS_ENABLED(CONFIG_SLUB_STATS))
5680 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5681 if (WARN_ON(!buffer))
5686 len = attr->show(root_cache, buf);
5688 attr->store(s, buf, len);
5692 free_page((unsigned long)buffer);
5693 #endif /* CONFIG_MEMCG */
5696 static void kmem_cache_release(struct kobject *k)
5698 slab_kmem_cache_release(to_slab(k));
5701 static const struct sysfs_ops slab_sysfs_ops = {
5702 .show = slab_attr_show,
5703 .store = slab_attr_store,
5706 static struct kobj_type slab_ktype = {
5707 .sysfs_ops = &slab_sysfs_ops,
5708 .release = kmem_cache_release,
5711 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5713 struct kobj_type *ktype = get_ktype(kobj);
5715 if (ktype == &slab_ktype)
5720 static const struct kset_uevent_ops slab_uevent_ops = {
5721 .filter = uevent_filter,
5724 static struct kset *slab_kset;
5726 static inline struct kset *cache_kset(struct kmem_cache *s)
5729 if (!is_root_cache(s))
5730 return s->memcg_params.root_cache->memcg_kset;
5735 #define ID_STR_LENGTH 64
5737 /* Create a unique string id for a slab cache:
5739 * Format :[flags-]size
5741 static char *create_unique_id(struct kmem_cache *s)
5743 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5750 * First flags affecting slabcache operations. We will only
5751 * get here for aliasable slabs so we do not need to support
5752 * too many flags. The flags here must cover all flags that
5753 * are matched during merging to guarantee that the id is
5756 if (s->flags & SLAB_CACHE_DMA)
5758 if (s->flags & SLAB_CACHE_DMA32)
5760 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5762 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5764 if (s->flags & SLAB_ACCOUNT)
5768 p += sprintf(p, "%07u", s->size);
5770 BUG_ON(p > name + ID_STR_LENGTH - 1);
5774 static void sysfs_slab_remove_workfn(struct work_struct *work)
5776 struct kmem_cache *s =
5777 container_of(work, struct kmem_cache, kobj_remove_work);
5779 if (!s->kobj.state_in_sysfs)
5781 * For a memcg cache, this may be called during
5782 * deactivation and again on shutdown. Remove only once.
5783 * A cache is never shut down before deactivation is
5784 * complete, so no need to worry about synchronization.
5789 kset_unregister(s->memcg_kset);
5791 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5793 kobject_put(&s->kobj);
5796 static int sysfs_slab_add(struct kmem_cache *s)
5800 struct kset *kset = cache_kset(s);
5801 int unmergeable = slab_unmergeable(s);
5803 INIT_WORK(&s->kobj_remove_work, sysfs_slab_remove_workfn);
5806 kobject_init(&s->kobj, &slab_ktype);
5810 if (!unmergeable && disable_higher_order_debug &&
5811 (slub_debug & DEBUG_METADATA_FLAGS))
5816 * Slabcache can never be merged so we can use the name proper.
5817 * This is typically the case for debug situations. In that
5818 * case we can catch duplicate names easily.
5820 sysfs_remove_link(&slab_kset->kobj, s->name);
5824 * Create a unique name for the slab as a target
5827 name = create_unique_id(s);
5830 s->kobj.kset = kset;
5831 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5835 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5840 if (is_root_cache(s) && memcg_sysfs_enabled) {
5841 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5842 if (!s->memcg_kset) {
5849 kobject_uevent(&s->kobj, KOBJ_ADD);
5851 /* Setup first alias */
5852 sysfs_slab_alias(s, s->name);
5859 kobject_del(&s->kobj);
5863 static void sysfs_slab_remove(struct kmem_cache *s)
5865 if (slab_state < FULL)
5867 * Sysfs has not been setup yet so no need to remove the
5872 kobject_get(&s->kobj);
5873 schedule_work(&s->kobj_remove_work);
5876 void sysfs_slab_unlink(struct kmem_cache *s)
5878 if (slab_state >= FULL)
5879 kobject_del(&s->kobj);
5882 void sysfs_slab_release(struct kmem_cache *s)
5884 if (slab_state >= FULL)
5885 kobject_put(&s->kobj);
5889 * Need to buffer aliases during bootup until sysfs becomes
5890 * available lest we lose that information.
5892 struct saved_alias {
5893 struct kmem_cache *s;
5895 struct saved_alias *next;
5898 static struct saved_alias *alias_list;
5900 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5902 struct saved_alias *al;
5904 if (slab_state == FULL) {
5906 * If we have a leftover link then remove it.
5908 sysfs_remove_link(&slab_kset->kobj, name);
5909 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5912 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5918 al->next = alias_list;
5923 static int __init slab_sysfs_init(void)
5925 struct kmem_cache *s;
5928 mutex_lock(&slab_mutex);
5930 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5932 mutex_unlock(&slab_mutex);
5933 pr_err("Cannot register slab subsystem.\n");
5939 list_for_each_entry(s, &slab_caches, list) {
5940 err = sysfs_slab_add(s);
5942 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5946 while (alias_list) {
5947 struct saved_alias *al = alias_list;
5949 alias_list = alias_list->next;
5950 err = sysfs_slab_alias(al->s, al->name);
5952 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5957 mutex_unlock(&slab_mutex);
5962 __initcall(slab_sysfs_init);
5963 #endif /* CONFIG_SYSFS */
5966 * The /proc/slabinfo ABI
5968 #ifdef CONFIG_SLUB_DEBUG
5969 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5971 unsigned long nr_slabs = 0;
5972 unsigned long nr_objs = 0;
5973 unsigned long nr_free = 0;
5975 struct kmem_cache_node *n;
5977 for_each_kmem_cache_node(s, node, n) {
5978 nr_slabs += node_nr_slabs(n);
5979 nr_objs += node_nr_objs(n);
5980 nr_free += count_partial(n, count_free);
5983 sinfo->active_objs = nr_objs - nr_free;
5984 sinfo->num_objs = nr_objs;
5985 sinfo->active_slabs = nr_slabs;
5986 sinfo->num_slabs = nr_slabs;
5987 sinfo->objects_per_slab = oo_objects(s->oo);
5988 sinfo->cache_order = oo_order(s->oo);
5991 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5995 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5996 size_t count, loff_t *ppos)
6000 #endif /* CONFIG_SLUB_DEBUG */