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/kfence.h>
32 #include <linux/memory.h>
33 #include <linux/math64.h>
34 #include <linux/fault-inject.h>
35 #include <linux/stacktrace.h>
36 #include <linux/prefetch.h>
37 #include <linux/memcontrol.h>
38 #include <linux/random.h>
40 #include <trace/events/kmem.h>
46 * 1. slab_mutex (Global Mutex)
48 * 3. slab_lock(page) (Only on some arches and for debugging)
52 * The role of the slab_mutex is to protect the list of all the slabs
53 * and to synchronize major metadata changes to slab cache structures.
55 * The slab_lock is only used for debugging and on arches that do not
56 * have the ability to do a cmpxchg_double. It only protects:
57 * A. page->freelist -> List of object free in a page
58 * B. page->inuse -> Number of objects in use
59 * C. page->objects -> Number of objects in page
60 * D. page->frozen -> frozen state
62 * If a slab is frozen then it is exempt from list management. It is not
63 * on any list except per cpu partial list. The processor that froze the
64 * slab is the one who can perform list operations on the page. Other
65 * processors may put objects onto the freelist but the processor that
66 * froze the slab is the only one that can retrieve the objects from the
69 * The list_lock protects the partial and full list on each node and
70 * the partial slab counter. If taken then no new slabs may be added or
71 * removed from the lists nor make the number of partial slabs be modified.
72 * (Note that the total number of slabs is an atomic value that may be
73 * modified without taking the list lock).
75 * The list_lock is a centralized lock and thus we avoid taking it as
76 * much as possible. As long as SLUB does not have to handle partial
77 * slabs, operations can continue without any centralized lock. F.e.
78 * allocating a long series of objects that fill up slabs does not require
80 * Interrupts are disabled during allocation and deallocation in order to
81 * make the slab allocator safe to use in the context of an irq. In addition
82 * interrupts are disabled to ensure that the processor does not change
83 * while handling per_cpu slabs, due to kernel preemption.
85 * SLUB assigns one slab for allocation to each processor.
86 * Allocations only occur from these slabs called cpu slabs.
88 * Slabs with free elements are kept on a partial list and during regular
89 * operations no list for full slabs is used. If an object in a full slab is
90 * freed then the slab will show up again on the partial lists.
91 * We track full slabs for debugging purposes though because otherwise we
92 * cannot scan all objects.
94 * Slabs are freed when they become empty. Teardown and setup is
95 * minimal so we rely on the page allocators per cpu caches for
96 * fast frees and allocs.
98 * page->frozen The slab is frozen and exempt from list processing.
99 * This means that the slab is dedicated to a purpose
100 * such as satisfying allocations for a specific
101 * processor. Objects may be freed in the slab while
102 * it is frozen but slab_free will then skip the usual
103 * list operations. It is up to the processor holding
104 * the slab to integrate the slab into the slab lists
105 * when the slab is no longer needed.
107 * One use of this flag is to mark slabs that are
108 * used for allocations. Then such a slab becomes a cpu
109 * slab. The cpu slab may be equipped with an additional
110 * freelist that allows lockless access to
111 * free objects in addition to the regular freelist
112 * that requires the slab lock.
114 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
115 * options set. This moves slab handling out of
116 * the fast path and disables lockless freelists.
119 #ifdef CONFIG_SLUB_DEBUG
120 #ifdef CONFIG_SLUB_DEBUG_ON
121 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
123 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
127 static inline bool kmem_cache_debug(struct kmem_cache *s)
129 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
132 void *fixup_red_left(struct kmem_cache *s, void *p)
134 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
135 p += s->red_left_pad;
140 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
142 #ifdef CONFIG_SLUB_CPU_PARTIAL
143 return !kmem_cache_debug(s);
150 * Issues still to be resolved:
152 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
154 * - Variable sizing of the per node arrays
157 /* Enable to test recovery from slab corruption on boot */
158 #undef SLUB_RESILIENCY_TEST
160 /* Enable to log cmpxchg failures */
161 #undef SLUB_DEBUG_CMPXCHG
164 * Mininum number of partial slabs. These will be left on the partial
165 * lists even if they are empty. kmem_cache_shrink may reclaim them.
167 #define MIN_PARTIAL 5
170 * Maximum number of desirable partial slabs.
171 * The existence of more partial slabs makes kmem_cache_shrink
172 * sort the partial list by the number of objects in use.
174 #define MAX_PARTIAL 10
176 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
177 SLAB_POISON | SLAB_STORE_USER)
180 * These debug flags cannot use CMPXCHG because there might be consistency
181 * issues when checking or reading debug information
183 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
188 * Debugging flags that require metadata to be stored in the slab. These get
189 * disabled when slub_debug=O is used and a cache's min order increases with
192 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
195 #define OO_MASK ((1 << OO_SHIFT) - 1)
196 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
198 /* Internal SLUB flags */
200 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
201 /* Use cmpxchg_double */
202 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
205 * Tracking user of a slab.
207 #define TRACK_ADDRS_COUNT 16
209 unsigned long addr; /* Called from address */
210 #ifdef CONFIG_STACKTRACE
211 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
213 int cpu; /* Was running on cpu */
214 int pid; /* Pid context */
215 unsigned long when; /* When did the operation occur */
218 enum track_item { TRACK_ALLOC, TRACK_FREE };
221 static int sysfs_slab_add(struct kmem_cache *);
222 static int sysfs_slab_alias(struct kmem_cache *, const char *);
224 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
225 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
229 static inline void stat(const struct kmem_cache *s, enum stat_item si)
231 #ifdef CONFIG_SLUB_STATS
233 * The rmw is racy on a preemptible kernel but this is acceptable, so
234 * avoid this_cpu_add()'s irq-disable overhead.
236 raw_cpu_inc(s->cpu_slab->stat[si]);
240 /********************************************************************
241 * Core slab cache functions
242 *******************************************************************/
245 * Returns freelist pointer (ptr). With hardening, this is obfuscated
246 * with an XOR of the address where the pointer is held and a per-cache
249 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
250 unsigned long ptr_addr)
252 #ifdef CONFIG_SLAB_FREELIST_HARDENED
254 * When CONFIG_KASAN_SW_TAGS is enabled, ptr_addr might be tagged.
255 * Normally, this doesn't cause any issues, as both set_freepointer()
256 * and get_freepointer() are called with a pointer with the same tag.
257 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
258 * example, when __free_slub() iterates over objects in a cache, it
259 * passes untagged pointers to check_object(). check_object() in turns
260 * calls get_freepointer() with an untagged pointer, which causes the
261 * freepointer to be restored incorrectly.
263 return (void *)((unsigned long)ptr ^ s->random ^
264 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
270 /* Returns the freelist pointer recorded at location ptr_addr. */
271 static inline void *freelist_dereference(const struct kmem_cache *s,
274 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
275 (unsigned long)ptr_addr);
278 static inline void *get_freepointer(struct kmem_cache *s, void *object)
280 return freelist_dereference(s, object + s->offset);
283 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
285 prefetch(object + s->offset);
288 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
290 unsigned long freepointer_addr;
293 if (!debug_pagealloc_enabled_static())
294 return get_freepointer(s, object);
296 freepointer_addr = (unsigned long)object + s->offset;
297 copy_from_kernel_nofault(&p, (void **)freepointer_addr, sizeof(p));
298 return freelist_ptr(s, p, freepointer_addr);
301 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
303 unsigned long freeptr_addr = (unsigned long)object + s->offset;
305 #ifdef CONFIG_SLAB_FREELIST_HARDENED
306 BUG_ON(object == fp); /* naive detection of double free or corruption */
309 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
312 /* Loop over all objects in a slab */
313 #define for_each_object(__p, __s, __addr, __objects) \
314 for (__p = fixup_red_left(__s, __addr); \
315 __p < (__addr) + (__objects) * (__s)->size; \
318 static inline unsigned int order_objects(unsigned int order, unsigned int size)
320 return ((unsigned int)PAGE_SIZE << order) / size;
323 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
326 struct kmem_cache_order_objects x = {
327 (order << OO_SHIFT) + order_objects(order, size)
333 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
335 return x.x >> OO_SHIFT;
338 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
340 return x.x & OO_MASK;
344 * Per slab locking using the pagelock
346 static __always_inline void slab_lock(struct page *page)
348 VM_BUG_ON_PAGE(PageTail(page), page);
349 bit_spin_lock(PG_locked, &page->flags);
352 static __always_inline void slab_unlock(struct page *page)
354 VM_BUG_ON_PAGE(PageTail(page), page);
355 __bit_spin_unlock(PG_locked, &page->flags);
358 /* Interrupts must be disabled (for the fallback code to work right) */
359 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
360 void *freelist_old, unsigned long counters_old,
361 void *freelist_new, unsigned long counters_new,
364 VM_BUG_ON(!irqs_disabled());
365 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
366 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
367 if (s->flags & __CMPXCHG_DOUBLE) {
368 if (cmpxchg_double(&page->freelist, &page->counters,
369 freelist_old, counters_old,
370 freelist_new, counters_new))
376 if (page->freelist == freelist_old &&
377 page->counters == counters_old) {
378 page->freelist = freelist_new;
379 page->counters = counters_new;
387 stat(s, CMPXCHG_DOUBLE_FAIL);
389 #ifdef SLUB_DEBUG_CMPXCHG
390 pr_info("%s %s: cmpxchg double redo ", n, s->name);
396 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
397 void *freelist_old, unsigned long counters_old,
398 void *freelist_new, unsigned long counters_new,
401 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
402 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
403 if (s->flags & __CMPXCHG_DOUBLE) {
404 if (cmpxchg_double(&page->freelist, &page->counters,
405 freelist_old, counters_old,
406 freelist_new, counters_new))
413 local_irq_save(flags);
415 if (page->freelist == freelist_old &&
416 page->counters == counters_old) {
417 page->freelist = freelist_new;
418 page->counters = counters_new;
420 local_irq_restore(flags);
424 local_irq_restore(flags);
428 stat(s, CMPXCHG_DOUBLE_FAIL);
430 #ifdef SLUB_DEBUG_CMPXCHG
431 pr_info("%s %s: cmpxchg double redo ", n, s->name);
437 #ifdef CONFIG_SLUB_DEBUG
438 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
439 static DEFINE_RAW_SPINLOCK(object_map_lock);
442 * Determine a map of object in use on a page.
444 * Node listlock must be held to guarantee that the page does
445 * not vanish from under us.
447 static unsigned long *get_map(struct kmem_cache *s, struct page *page)
448 __acquires(&object_map_lock)
451 void *addr = page_address(page);
453 VM_BUG_ON(!irqs_disabled());
455 raw_spin_lock(&object_map_lock);
457 bitmap_zero(object_map, page->objects);
459 for (p = page->freelist; p; p = get_freepointer(s, p))
460 set_bit(__obj_to_index(s, addr, p), object_map);
465 static void put_map(unsigned long *map) __releases(&object_map_lock)
467 VM_BUG_ON(map != object_map);
468 raw_spin_unlock(&object_map_lock);
471 static inline unsigned int size_from_object(struct kmem_cache *s)
473 if (s->flags & SLAB_RED_ZONE)
474 return s->size - s->red_left_pad;
479 static inline void *restore_red_left(struct kmem_cache *s, void *p)
481 if (s->flags & SLAB_RED_ZONE)
482 p -= s->red_left_pad;
490 #if defined(CONFIG_SLUB_DEBUG_ON)
491 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
493 static slab_flags_t slub_debug;
496 static char *slub_debug_string;
497 static int disable_higher_order_debug;
500 * slub is about to manipulate internal object metadata. This memory lies
501 * outside the range of the allocated object, so accessing it would normally
502 * be reported by kasan as a bounds error. metadata_access_enable() is used
503 * to tell kasan that these accesses are OK.
505 static inline void metadata_access_enable(void)
507 kasan_disable_current();
510 static inline void metadata_access_disable(void)
512 kasan_enable_current();
519 /* Verify that a pointer has an address that is valid within a slab page */
520 static inline int check_valid_pointer(struct kmem_cache *s,
521 struct page *page, void *object)
528 base = page_address(page);
529 object = kasan_reset_tag(object);
530 object = restore_red_left(s, object);
531 if (object < base || object >= base + page->objects * s->size ||
532 (object - base) % s->size) {
539 static void print_section(char *level, char *text, u8 *addr,
542 metadata_access_enable();
543 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
545 metadata_access_disable();
549 * See comment in calculate_sizes().
551 static inline bool freeptr_outside_object(struct kmem_cache *s)
553 return s->offset >= s->inuse;
557 * Return offset of the end of info block which is inuse + free pointer if
558 * not overlapping with object.
560 static inline unsigned int get_info_end(struct kmem_cache *s)
562 if (freeptr_outside_object(s))
563 return s->inuse + sizeof(void *);
568 static struct track *get_track(struct kmem_cache *s, void *object,
569 enum track_item alloc)
573 p = object + get_info_end(s);
578 static void set_track(struct kmem_cache *s, void *object,
579 enum track_item alloc, unsigned long addr)
581 struct track *p = get_track(s, object, alloc);
584 #ifdef CONFIG_STACKTRACE
585 unsigned int nr_entries;
587 metadata_access_enable();
588 nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
589 metadata_access_disable();
591 if (nr_entries < TRACK_ADDRS_COUNT)
592 p->addrs[nr_entries] = 0;
595 p->cpu = smp_processor_id();
596 p->pid = current->pid;
599 memset(p, 0, sizeof(struct track));
603 static void init_tracking(struct kmem_cache *s, void *object)
605 if (!(s->flags & SLAB_STORE_USER))
608 set_track(s, object, TRACK_FREE, 0UL);
609 set_track(s, object, TRACK_ALLOC, 0UL);
612 static void print_track(const char *s, struct track *t, unsigned long pr_time)
617 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
618 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
619 #ifdef CONFIG_STACKTRACE
622 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
624 pr_err("\t%pS\n", (void *)t->addrs[i]);
631 void print_tracking(struct kmem_cache *s, void *object)
633 unsigned long pr_time = jiffies;
634 if (!(s->flags & SLAB_STORE_USER))
637 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
638 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
641 static void print_page_info(struct page *page)
643 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
644 page, page->objects, page->inuse, page->freelist, page->flags);
648 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
650 struct va_format vaf;
656 pr_err("=============================================================================\n");
657 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
658 pr_err("-----------------------------------------------------------------------------\n\n");
660 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
664 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
666 struct va_format vaf;
672 pr_err("FIX %s: %pV\n", s->name, &vaf);
676 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
677 void **freelist, void *nextfree)
679 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
680 !check_valid_pointer(s, page, nextfree) && freelist) {
681 object_err(s, page, *freelist, "Freechain corrupt");
683 slab_fix(s, "Isolate corrupted freechain");
690 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
692 unsigned int off; /* Offset of last byte */
693 u8 *addr = page_address(page);
695 print_tracking(s, p);
697 print_page_info(page);
699 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
700 p, p - addr, get_freepointer(s, p));
702 if (s->flags & SLAB_RED_ZONE)
703 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
705 else if (p > addr + 16)
706 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
708 print_section(KERN_ERR, "Object ", p,
709 min_t(unsigned int, s->object_size, PAGE_SIZE));
710 if (s->flags & SLAB_RED_ZONE)
711 print_section(KERN_ERR, "Redzone ", p + s->object_size,
712 s->inuse - s->object_size);
714 off = get_info_end(s);
716 if (s->flags & SLAB_STORE_USER)
717 off += 2 * sizeof(struct track);
719 off += kasan_metadata_size(s);
721 if (off != size_from_object(s))
722 /* Beginning of the filler is the free pointer */
723 print_section(KERN_ERR, "Padding ", p + off,
724 size_from_object(s) - off);
729 void object_err(struct kmem_cache *s, struct page *page,
730 u8 *object, char *reason)
732 slab_bug(s, "%s", reason);
733 print_trailer(s, page, object);
736 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
737 const char *fmt, ...)
743 vsnprintf(buf, sizeof(buf), fmt, args);
745 slab_bug(s, "%s", buf);
746 print_page_info(page);
750 static void init_object(struct kmem_cache *s, void *object, u8 val)
754 if (s->flags & SLAB_RED_ZONE)
755 memset(p - s->red_left_pad, val, s->red_left_pad);
757 if (s->flags & __OBJECT_POISON) {
758 memset(p, POISON_FREE, s->object_size - 1);
759 p[s->object_size - 1] = POISON_END;
762 if (s->flags & SLAB_RED_ZONE)
763 memset(p + s->object_size, val, s->inuse - s->object_size);
766 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
767 void *from, void *to)
769 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
770 memset(from, data, to - from);
773 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
774 u8 *object, char *what,
775 u8 *start, unsigned int value, unsigned int bytes)
779 u8 *addr = page_address(page);
781 metadata_access_enable();
782 fault = memchr_inv(start, value, bytes);
783 metadata_access_disable();
788 while (end > fault && end[-1] == value)
791 slab_bug(s, "%s overwritten", what);
792 pr_err("INFO: 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
793 fault, end - 1, fault - addr,
795 print_trailer(s, page, object);
797 restore_bytes(s, what, value, fault, end);
805 * Bytes of the object to be managed.
806 * If the freepointer may overlay the object then the free
807 * pointer is at the middle of the object.
809 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
812 * object + s->object_size
813 * Padding to reach word boundary. This is also used for Redzoning.
814 * Padding is extended by another word if Redzoning is enabled and
815 * object_size == inuse.
817 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
818 * 0xcc (RED_ACTIVE) for objects in use.
821 * Meta data starts here.
823 * A. Free pointer (if we cannot overwrite object on free)
824 * B. Tracking data for SLAB_STORE_USER
825 * C. Padding to reach required alignment boundary or at mininum
826 * one word if debugging is on to be able to detect writes
827 * before the word boundary.
829 * Padding is done using 0x5a (POISON_INUSE)
832 * Nothing is used beyond s->size.
834 * If slabcaches are merged then the object_size and inuse boundaries are mostly
835 * ignored. And therefore no slab options that rely on these boundaries
836 * may be used with merged slabcaches.
839 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
841 unsigned long off = get_info_end(s); /* The end of info */
843 if (s->flags & SLAB_STORE_USER)
844 /* We also have user information there */
845 off += 2 * sizeof(struct track);
847 off += kasan_metadata_size(s);
849 if (size_from_object(s) == off)
852 return check_bytes_and_report(s, page, p, "Object padding",
853 p + off, POISON_INUSE, size_from_object(s) - off);
856 /* Check the pad bytes at the end of a slab page */
857 static int slab_pad_check(struct kmem_cache *s, struct page *page)
866 if (!(s->flags & SLAB_POISON))
869 start = page_address(page);
870 length = page_size(page);
871 end = start + length;
872 remainder = length % s->size;
876 pad = end - remainder;
877 metadata_access_enable();
878 fault = memchr_inv(pad, POISON_INUSE, remainder);
879 metadata_access_disable();
882 while (end > fault && end[-1] == POISON_INUSE)
885 slab_err(s, page, "Padding overwritten. 0x%p-0x%p @offset=%tu",
886 fault, end - 1, fault - start);
887 print_section(KERN_ERR, "Padding ", pad, remainder);
889 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
893 static int check_object(struct kmem_cache *s, struct page *page,
894 void *object, u8 val)
897 u8 *endobject = object + s->object_size;
899 if (s->flags & SLAB_RED_ZONE) {
900 if (!check_bytes_and_report(s, page, object, "Left Redzone",
901 object - s->red_left_pad, val, s->red_left_pad))
904 if (!check_bytes_and_report(s, page, object, "Right Redzone",
905 endobject, val, s->inuse - s->object_size))
908 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
909 check_bytes_and_report(s, page, p, "Alignment padding",
910 endobject, POISON_INUSE,
911 s->inuse - s->object_size);
915 if (s->flags & SLAB_POISON) {
916 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
917 (!check_bytes_and_report(s, page, p, "Poison", p,
918 POISON_FREE, s->object_size - 1) ||
919 !check_bytes_and_report(s, page, p, "End Poison",
920 p + s->object_size - 1, POISON_END, 1)))
923 * check_pad_bytes cleans up on its own.
925 check_pad_bytes(s, page, p);
928 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
930 * Object and freepointer overlap. Cannot check
931 * freepointer while object is allocated.
935 /* Check free pointer validity */
936 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
937 object_err(s, page, p, "Freepointer corrupt");
939 * No choice but to zap it and thus lose the remainder
940 * of the free objects in this slab. May cause
941 * another error because the object count is now wrong.
943 set_freepointer(s, p, NULL);
949 static int check_slab(struct kmem_cache *s, struct page *page)
953 VM_BUG_ON(!irqs_disabled());
955 if (!PageSlab(page)) {
956 slab_err(s, page, "Not a valid slab page");
960 maxobj = order_objects(compound_order(page), s->size);
961 if (page->objects > maxobj) {
962 slab_err(s, page, "objects %u > max %u",
963 page->objects, maxobj);
966 if (page->inuse > page->objects) {
967 slab_err(s, page, "inuse %u > max %u",
968 page->inuse, page->objects);
971 /* Slab_pad_check fixes things up after itself */
972 slab_pad_check(s, page);
977 * Determine if a certain object on a page is on the freelist. Must hold the
978 * slab lock to guarantee that the chains are in a consistent state.
980 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
988 while (fp && nr <= page->objects) {
991 if (!check_valid_pointer(s, page, fp)) {
993 object_err(s, page, object,
994 "Freechain corrupt");
995 set_freepointer(s, object, NULL);
997 slab_err(s, page, "Freepointer corrupt");
998 page->freelist = NULL;
999 page->inuse = page->objects;
1000 slab_fix(s, "Freelist cleared");
1006 fp = get_freepointer(s, object);
1010 max_objects = order_objects(compound_order(page), s->size);
1011 if (max_objects > MAX_OBJS_PER_PAGE)
1012 max_objects = MAX_OBJS_PER_PAGE;
1014 if (page->objects != max_objects) {
1015 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1016 page->objects, max_objects);
1017 page->objects = max_objects;
1018 slab_fix(s, "Number of objects adjusted.");
1020 if (page->inuse != page->objects - nr) {
1021 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1022 page->inuse, page->objects - nr);
1023 page->inuse = page->objects - nr;
1024 slab_fix(s, "Object count adjusted.");
1026 return search == NULL;
1029 static void trace(struct kmem_cache *s, struct page *page, void *object,
1032 if (s->flags & SLAB_TRACE) {
1033 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1035 alloc ? "alloc" : "free",
1036 object, page->inuse,
1040 print_section(KERN_INFO, "Object ", (void *)object,
1048 * Tracking of fully allocated slabs for debugging purposes.
1050 static void add_full(struct kmem_cache *s,
1051 struct kmem_cache_node *n, struct page *page)
1053 if (!(s->flags & SLAB_STORE_USER))
1056 lockdep_assert_held(&n->list_lock);
1057 list_add(&page->slab_list, &n->full);
1060 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1062 if (!(s->flags & SLAB_STORE_USER))
1065 lockdep_assert_held(&n->list_lock);
1066 list_del(&page->slab_list);
1069 /* Tracking of the number of slabs for debugging purposes */
1070 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1072 struct kmem_cache_node *n = get_node(s, node);
1074 return atomic_long_read(&n->nr_slabs);
1077 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1079 return atomic_long_read(&n->nr_slabs);
1082 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1084 struct kmem_cache_node *n = get_node(s, node);
1087 * May be called early in order to allocate a slab for the
1088 * kmem_cache_node structure. Solve the chicken-egg
1089 * dilemma by deferring the increment of the count during
1090 * bootstrap (see early_kmem_cache_node_alloc).
1093 atomic_long_inc(&n->nr_slabs);
1094 atomic_long_add(objects, &n->total_objects);
1097 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1099 struct kmem_cache_node *n = get_node(s, node);
1101 atomic_long_dec(&n->nr_slabs);
1102 atomic_long_sub(objects, &n->total_objects);
1105 /* Object debug checks for alloc/free paths */
1106 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1109 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1112 init_object(s, object, SLUB_RED_INACTIVE);
1113 init_tracking(s, object);
1117 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1119 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1122 metadata_access_enable();
1123 memset(addr, POISON_INUSE, page_size(page));
1124 metadata_access_disable();
1127 static inline int alloc_consistency_checks(struct kmem_cache *s,
1128 struct page *page, void *object)
1130 if (!check_slab(s, page))
1133 if (!check_valid_pointer(s, page, object)) {
1134 object_err(s, page, object, "Freelist Pointer check fails");
1138 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1144 static noinline int alloc_debug_processing(struct kmem_cache *s,
1146 void *object, unsigned long addr)
1148 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1149 if (!alloc_consistency_checks(s, page, object))
1153 /* Success perform special debug activities for allocs */
1154 if (s->flags & SLAB_STORE_USER)
1155 set_track(s, object, TRACK_ALLOC, addr);
1156 trace(s, page, object, 1);
1157 init_object(s, object, SLUB_RED_ACTIVE);
1161 if (PageSlab(page)) {
1163 * If this is a slab page then lets do the best we can
1164 * to avoid issues in the future. Marking all objects
1165 * as used avoids touching the remaining objects.
1167 slab_fix(s, "Marking all objects used");
1168 page->inuse = page->objects;
1169 page->freelist = NULL;
1174 static inline int free_consistency_checks(struct kmem_cache *s,
1175 struct page *page, void *object, unsigned long addr)
1177 if (!check_valid_pointer(s, page, object)) {
1178 slab_err(s, page, "Invalid object pointer 0x%p", object);
1182 if (on_freelist(s, page, object)) {
1183 object_err(s, page, object, "Object already free");
1187 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1190 if (unlikely(s != page->slab_cache)) {
1191 if (!PageSlab(page)) {
1192 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1194 } else if (!page->slab_cache) {
1195 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1199 object_err(s, page, object,
1200 "page slab pointer corrupt.");
1206 /* Supports checking bulk free of a constructed freelist */
1207 static noinline int free_debug_processing(
1208 struct kmem_cache *s, struct page *page,
1209 void *head, void *tail, int bulk_cnt,
1212 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1213 void *object = head;
1215 unsigned long flags;
1218 raw_spin_lock_irqsave(&n->list_lock, flags);
1221 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1222 if (!check_slab(s, page))
1229 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1230 if (!free_consistency_checks(s, page, object, addr))
1234 if (s->flags & SLAB_STORE_USER)
1235 set_track(s, object, TRACK_FREE, addr);
1236 trace(s, page, object, 0);
1237 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1238 init_object(s, object, SLUB_RED_INACTIVE);
1240 /* Reached end of constructed freelist yet? */
1241 if (object != tail) {
1242 object = get_freepointer(s, object);
1248 if (cnt != bulk_cnt)
1249 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1253 raw_spin_unlock_irqrestore(&n->list_lock, flags);
1255 slab_fix(s, "Object at 0x%p not freed", object);
1260 * Parse a block of slub_debug options. Blocks are delimited by ';'
1262 * @str: start of block
1263 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1264 * @slabs: return start of list of slabs, or NULL when there's no list
1265 * @init: assume this is initial parsing and not per-kmem-create parsing
1267 * returns the start of next block if there's any, or NULL
1270 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1272 bool higher_order_disable = false;
1274 /* Skip any completely empty blocks */
1275 while (*str && *str == ';')
1280 * No options but restriction on slabs. This means full
1281 * debugging for slabs matching a pattern.
1283 *flags = DEBUG_DEFAULT_FLAGS;
1288 /* Determine which debug features should be switched on */
1289 for (; *str && *str != ',' && *str != ';'; str++) {
1290 switch (tolower(*str)) {
1295 *flags |= SLAB_CONSISTENCY_CHECKS;
1298 *flags |= SLAB_RED_ZONE;
1301 *flags |= SLAB_POISON;
1304 *flags |= SLAB_STORE_USER;
1307 *flags |= SLAB_TRACE;
1310 *flags |= SLAB_FAILSLAB;
1314 * Avoid enabling debugging on caches if its minimum
1315 * order would increase as a result.
1317 higher_order_disable = true;
1321 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
1330 /* Skip over the slab list */
1331 while (*str && *str != ';')
1334 /* Skip any completely empty blocks */
1335 while (*str && *str == ';')
1338 if (init && higher_order_disable)
1339 disable_higher_order_debug = 1;
1347 static int __init setup_slub_debug(char *str)
1352 bool global_slub_debug_changed = false;
1353 bool slab_list_specified = false;
1355 slub_debug = DEBUG_DEFAULT_FLAGS;
1356 if (*str++ != '=' || !*str)
1358 * No options specified. Switch on full debugging.
1364 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1368 global_slub_debug_changed = true;
1370 slab_list_specified = true;
1375 * For backwards compatibility, a single list of flags with list of
1376 * slabs means debugging is only enabled for those slabs, so the global
1377 * slub_debug should be 0. We can extended that to multiple lists as
1378 * long as there is no option specifying flags without a slab list.
1380 if (slab_list_specified) {
1381 if (!global_slub_debug_changed)
1383 slub_debug_string = saved_str;
1386 if (slub_debug != 0 || slub_debug_string)
1387 static_branch_enable(&slub_debug_enabled);
1388 if ((static_branch_unlikely(&init_on_alloc) ||
1389 static_branch_unlikely(&init_on_free)) &&
1390 (slub_debug & SLAB_POISON))
1391 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1395 __setup("slub_debug", setup_slub_debug);
1398 * kmem_cache_flags - apply debugging options to the cache
1399 * @object_size: the size of an object without meta data
1400 * @flags: flags to set
1401 * @name: name of the cache
1403 * Debug option(s) are applied to @flags. In addition to the debug
1404 * option(s), if a slab name (or multiple) is specified i.e.
1405 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1406 * then only the select slabs will receive the debug option(s).
1408 slab_flags_t kmem_cache_flags(unsigned int object_size,
1409 slab_flags_t flags, const char *name)
1414 slab_flags_t block_flags;
1417 next_block = slub_debug_string;
1418 /* Go through all blocks of debug options, see if any matches our slab's name */
1419 while (next_block) {
1420 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1423 /* Found a block that has a slab list, search it */
1428 end = strchrnul(iter, ',');
1429 if (next_block && next_block < end)
1430 end = next_block - 1;
1432 glob = strnchr(iter, end - iter, '*');
1434 cmplen = glob - iter;
1436 cmplen = max_t(size_t, len, (end - iter));
1438 if (!strncmp(name, iter, cmplen)) {
1439 flags |= block_flags;
1443 if (!*end || *end == ';')
1449 return flags | slub_debug;
1451 #else /* !CONFIG_SLUB_DEBUG */
1452 static inline void setup_object_debug(struct kmem_cache *s,
1453 struct page *page, void *object) {}
1455 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1457 static inline int alloc_debug_processing(struct kmem_cache *s,
1458 struct page *page, void *object, unsigned long addr) { return 0; }
1460 static inline int free_debug_processing(
1461 struct kmem_cache *s, struct page *page,
1462 void *head, void *tail, int bulk_cnt,
1463 unsigned long addr) { return 0; }
1465 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1467 static inline int check_object(struct kmem_cache *s, struct page *page,
1468 void *object, u8 val) { return 1; }
1469 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1470 struct page *page) {}
1471 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1472 struct page *page) {}
1473 slab_flags_t kmem_cache_flags(unsigned int object_size,
1474 slab_flags_t flags, const char *name)
1478 #define slub_debug 0
1480 #define disable_higher_order_debug 0
1482 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1484 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1486 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1488 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1491 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1492 void **freelist, void *nextfree)
1496 #endif /* CONFIG_SLUB_DEBUG */
1498 struct slub_free_list {
1499 raw_spinlock_t lock;
1500 struct list_head list;
1502 static DEFINE_PER_CPU(struct slub_free_list, slub_free_list);
1505 * Hooks for other subsystems that check memory allocations. In a typical
1506 * production configuration these hooks all should produce no code at all.
1508 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1510 ptr = kasan_kmalloc_large(ptr, size, flags);
1511 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1512 kmemleak_alloc(ptr, size, 1, flags);
1516 static __always_inline void kfree_hook(void *x)
1519 kasan_kfree_large(x, _RET_IP_);
1522 static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x)
1524 kmemleak_free_recursive(x, s->flags);
1527 * Trouble is that we may no longer disable interrupts in the fast path
1528 * So in order to make the debug calls that expect irqs to be
1529 * disabled we need to disable interrupts temporarily.
1531 #ifdef CONFIG_LOCKDEP
1533 unsigned long flags;
1535 local_irq_save(flags);
1536 debug_check_no_locks_freed(x, s->object_size);
1537 local_irq_restore(flags);
1540 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1541 debug_check_no_obj_freed(x, s->object_size);
1543 /* Use KCSAN to help debug racy use-after-free. */
1544 if (!(s->flags & SLAB_TYPESAFE_BY_RCU))
1545 __kcsan_check_access(x, s->object_size,
1546 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
1548 /* KASAN might put x into memory quarantine, delaying its reuse */
1549 return kasan_slab_free(s, x, _RET_IP_);
1552 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1553 void **head, void **tail,
1559 void *old_tail = *tail ? *tail : *head;
1562 if (is_kfence_address(next)) {
1563 slab_free_hook(s, next);
1567 /* Head and tail of the reconstructed freelist */
1573 next = get_freepointer(s, object);
1575 if (slab_want_init_on_free(s)) {
1577 * Clear the object and the metadata, but don't touch
1580 memset(object, 0, s->object_size);
1581 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad
1583 memset((char *)object + s->inuse, 0,
1584 s->size - s->inuse - rsize);
1587 /* If object's reuse doesn't have to be delayed */
1588 if (!slab_free_hook(s, object)) {
1589 /* Move object to the new freelist */
1590 set_freepointer(s, object, *head);
1596 * Adjust the reconstructed freelist depth
1597 * accordingly if object's reuse is delayed.
1601 } while (object != old_tail);
1606 return *head != NULL;
1609 static void *setup_object(struct kmem_cache *s, struct page *page,
1612 setup_object_debug(s, page, object);
1613 object = kasan_init_slab_obj(s, object);
1614 if (unlikely(s->ctor)) {
1615 kasan_unpoison_object_data(s, object);
1617 kasan_poison_object_data(s, object);
1623 * Slab allocation and freeing
1625 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1626 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1629 unsigned int order = oo_order(oo);
1631 if (node == NUMA_NO_NODE)
1632 page = alloc_pages(flags, order);
1634 page = __alloc_pages_node(node, flags, order);
1637 account_slab_page(page, order, s);
1642 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1643 /* Pre-initialize the random sequence cache */
1644 static int init_cache_random_seq(struct kmem_cache *s)
1646 unsigned int count = oo_objects(s->oo);
1649 /* Bailout if already initialised */
1653 err = cache_random_seq_create(s, count, GFP_KERNEL);
1655 pr_err("SLUB: Unable to initialize free list for %s\n",
1660 /* Transform to an offset on the set of pages */
1661 if (s->random_seq) {
1664 for (i = 0; i < count; i++)
1665 s->random_seq[i] *= s->size;
1670 /* Initialize each random sequence freelist per cache */
1671 static void __init init_freelist_randomization(void)
1673 struct kmem_cache *s;
1675 mutex_lock(&slab_mutex);
1677 list_for_each_entry(s, &slab_caches, list)
1678 init_cache_random_seq(s);
1680 mutex_unlock(&slab_mutex);
1683 /* Get the next entry on the pre-computed freelist randomized */
1684 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1685 unsigned long *pos, void *start,
1686 unsigned long page_limit,
1687 unsigned long freelist_count)
1692 * If the target page allocation failed, the number of objects on the
1693 * page might be smaller than the usual size defined by the cache.
1696 idx = s->random_seq[*pos];
1698 if (*pos >= freelist_count)
1700 } while (unlikely(idx >= page_limit));
1702 return (char *)start + idx;
1705 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1706 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1711 unsigned long idx, pos, page_limit, freelist_count;
1713 if (page->objects < 2 || !s->random_seq)
1716 freelist_count = oo_objects(s->oo);
1717 pos = get_random_int() % freelist_count;
1719 page_limit = page->objects * s->size;
1720 start = fixup_red_left(s, page_address(page));
1722 /* First entry is used as the base of the freelist */
1723 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1725 cur = setup_object(s, page, cur);
1726 page->freelist = cur;
1728 for (idx = 1; idx < page->objects; idx++) {
1729 next = next_freelist_entry(s, page, &pos, start, page_limit,
1731 next = setup_object(s, page, next);
1732 set_freepointer(s, cur, next);
1735 set_freepointer(s, cur, NULL);
1740 static inline int init_cache_random_seq(struct kmem_cache *s)
1744 static inline void init_freelist_randomization(void) { }
1745 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1749 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1751 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1754 struct kmem_cache_order_objects oo = s->oo;
1756 void *start, *p, *next;
1759 bool enableirqs = false;
1761 flags &= gfp_allowed_mask;
1763 if (gfpflags_allow_blocking(flags))
1766 #ifdef CONFIG_PREEMPT_RT
1767 if (system_state > SYSTEM_BOOTING && system_state < SYSTEM_SUSPEND)
1773 flags |= s->allocflags;
1776 * Let the initial higher-order allocation fail under memory pressure
1777 * so we fall-back to the minimum order allocation.
1779 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1780 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1781 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1783 page = alloc_slab_page(s, alloc_gfp, node, oo);
1784 if (unlikely(!page)) {
1788 * Allocation may have failed due to fragmentation.
1789 * Try a lower order alloc if possible
1791 page = alloc_slab_page(s, alloc_gfp, node, oo);
1792 if (unlikely(!page))
1794 stat(s, ORDER_FALLBACK);
1797 page->objects = oo_objects(oo);
1799 page->slab_cache = s;
1800 __SetPageSlab(page);
1801 if (page_is_pfmemalloc(page))
1802 SetPageSlabPfmemalloc(page);
1804 kasan_poison_slab(page);
1806 start = page_address(page);
1808 setup_page_debug(s, page, start);
1810 shuffle = shuffle_freelist(s, page);
1813 start = fixup_red_left(s, start);
1814 start = setup_object(s, page, start);
1815 page->freelist = start;
1816 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1818 next = setup_object(s, page, next);
1819 set_freepointer(s, p, next);
1822 set_freepointer(s, p, NULL);
1825 page->inuse = page->objects;
1830 local_irq_disable();
1834 inc_slabs_node(s, page_to_nid(page), page->objects);
1839 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1841 if (unlikely(flags & GFP_SLAB_BUG_MASK))
1842 flags = kmalloc_fix_flags(flags);
1844 return allocate_slab(s,
1845 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1848 static void __free_slab(struct kmem_cache *s, struct page *page)
1850 int order = compound_order(page);
1851 int pages = 1 << order;
1853 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
1856 slab_pad_check(s, page);
1857 for_each_object(p, s, page_address(page),
1859 check_object(s, page, p, SLUB_RED_INACTIVE);
1862 __ClearPageSlabPfmemalloc(page);
1863 __ClearPageSlab(page);
1865 page->mapping = NULL;
1866 if (current->reclaim_state)
1867 current->reclaim_state->reclaimed_slab += pages;
1868 unaccount_slab_page(page, order, s);
1869 __free_pages(page, order);
1872 static void free_delayed(struct list_head *h)
1874 while (!list_empty(h)) {
1875 struct page *page = list_first_entry(h, struct page, lru);
1877 list_del(&page->lru);
1878 __free_slab(page->slab_cache, page);
1882 static void rcu_free_slab(struct rcu_head *h)
1884 struct page *page = container_of(h, struct page, rcu_head);
1886 __free_slab(page->slab_cache, page);
1889 static void free_slab(struct kmem_cache *s, struct page *page)
1891 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1892 call_rcu(&page->rcu_head, rcu_free_slab);
1893 } else if (irqs_disabled()) {
1894 struct slub_free_list *f = this_cpu_ptr(&slub_free_list);
1896 raw_spin_lock(&f->lock);
1897 list_add(&page->lru, &f->list);
1898 raw_spin_unlock(&f->lock);
1900 __free_slab(s, page);
1903 static void discard_slab(struct kmem_cache *s, struct page *page)
1905 dec_slabs_node(s, page_to_nid(page), page->objects);
1910 * Management of partially allocated slabs.
1913 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1916 if (tail == DEACTIVATE_TO_TAIL)
1917 list_add_tail(&page->slab_list, &n->partial);
1919 list_add(&page->slab_list, &n->partial);
1922 static inline void add_partial(struct kmem_cache_node *n,
1923 struct page *page, int tail)
1925 lockdep_assert_held(&n->list_lock);
1926 __add_partial(n, page, tail);
1929 static inline void remove_partial(struct kmem_cache_node *n,
1932 lockdep_assert_held(&n->list_lock);
1933 list_del(&page->slab_list);
1938 * Remove slab from the partial list, freeze it and
1939 * return the pointer to the freelist.
1941 * Returns a list of objects or NULL if it fails.
1943 static inline void *acquire_slab(struct kmem_cache *s,
1944 struct kmem_cache_node *n, struct page *page,
1945 int mode, int *objects)
1948 unsigned long counters;
1951 lockdep_assert_held(&n->list_lock);
1954 * Zap the freelist and set the frozen bit.
1955 * The old freelist is the list of objects for the
1956 * per cpu allocation list.
1958 freelist = page->freelist;
1959 counters = page->counters;
1960 new.counters = counters;
1961 *objects = new.objects - new.inuse;
1963 new.inuse = page->objects;
1964 new.freelist = NULL;
1966 new.freelist = freelist;
1969 VM_BUG_ON(new.frozen);
1972 if (!__cmpxchg_double_slab(s, page,
1974 new.freelist, new.counters,
1978 remove_partial(n, page);
1983 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1984 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1987 * Try to allocate a partial slab from a specific node.
1989 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1990 struct kmem_cache_cpu *c, gfp_t flags)
1992 struct page *page, *page2;
1993 void *object = NULL;
1994 unsigned int available = 0;
1998 * Racy check. If we mistakenly see no partial slabs then we
1999 * just allocate an empty slab. If we mistakenly try to get a
2000 * partial slab and there is none available then get_partial()
2003 if (!n || !n->nr_partial)
2006 raw_spin_lock(&n->list_lock);
2007 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
2010 if (!pfmemalloc_match(page, flags))
2013 t = acquire_slab(s, n, page, object == NULL, &objects);
2017 available += objects;
2020 stat(s, ALLOC_FROM_PARTIAL);
2023 put_cpu_partial(s, page, 0);
2024 stat(s, CPU_PARTIAL_NODE);
2026 if (!kmem_cache_has_cpu_partial(s)
2027 || available > slub_cpu_partial(s) / 2)
2031 raw_spin_unlock(&n->list_lock);
2036 * Get a page from somewhere. Search in increasing NUMA distances.
2038 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
2039 struct kmem_cache_cpu *c)
2042 struct zonelist *zonelist;
2045 enum zone_type highest_zoneidx = gfp_zone(flags);
2047 unsigned int cpuset_mems_cookie;
2050 * The defrag ratio allows a configuration of the tradeoffs between
2051 * inter node defragmentation and node local allocations. A lower
2052 * defrag_ratio increases the tendency to do local allocations
2053 * instead of attempting to obtain partial slabs from other nodes.
2055 * If the defrag_ratio is set to 0 then kmalloc() always
2056 * returns node local objects. If the ratio is higher then kmalloc()
2057 * may return off node objects because partial slabs are obtained
2058 * from other nodes and filled up.
2060 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2061 * (which makes defrag_ratio = 1000) then every (well almost)
2062 * allocation will first attempt to defrag slab caches on other nodes.
2063 * This means scanning over all nodes to look for partial slabs which
2064 * may be expensive if we do it every time we are trying to find a slab
2065 * with available objects.
2067 if (!s->remote_node_defrag_ratio ||
2068 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2072 cpuset_mems_cookie = read_mems_allowed_begin();
2073 zonelist = node_zonelist(mempolicy_slab_node(), flags);
2074 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2075 struct kmem_cache_node *n;
2077 n = get_node(s, zone_to_nid(zone));
2079 if (n && cpuset_zone_allowed(zone, flags) &&
2080 n->nr_partial > s->min_partial) {
2081 object = get_partial_node(s, n, c, flags);
2084 * Don't check read_mems_allowed_retry()
2085 * here - if mems_allowed was updated in
2086 * parallel, that was a harmless race
2087 * between allocation and the cpuset
2094 } while (read_mems_allowed_retry(cpuset_mems_cookie));
2095 #endif /* CONFIG_NUMA */
2100 * Get a partial page, lock it and return it.
2102 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
2103 struct kmem_cache_cpu *c)
2106 int searchnode = node;
2108 if (node == NUMA_NO_NODE)
2109 searchnode = numa_mem_id();
2111 object = get_partial_node(s, get_node(s, searchnode), c, flags);
2112 if (object || node != NUMA_NO_NODE)
2115 return get_any_partial(s, flags, c);
2118 #ifdef CONFIG_PREEMPTION
2120 * Calculate the next globally unique transaction for disambiguation
2121 * during cmpxchg. The transactions start with the cpu number and are then
2122 * incremented by CONFIG_NR_CPUS.
2124 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2127 * No preemption supported therefore also no need to check for
2133 static inline unsigned long next_tid(unsigned long tid)
2135 return tid + TID_STEP;
2138 #ifdef SLUB_DEBUG_CMPXCHG
2139 static inline unsigned int tid_to_cpu(unsigned long tid)
2141 return tid % TID_STEP;
2144 static inline unsigned long tid_to_event(unsigned long tid)
2146 return tid / TID_STEP;
2150 static inline unsigned int init_tid(int cpu)
2155 static inline void note_cmpxchg_failure(const char *n,
2156 const struct kmem_cache *s, unsigned long tid)
2158 #ifdef SLUB_DEBUG_CMPXCHG
2159 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2161 pr_info("%s %s: cmpxchg redo ", n, s->name);
2163 #ifdef CONFIG_PREEMPTION
2164 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2165 pr_warn("due to cpu change %d -> %d\n",
2166 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2169 if (tid_to_event(tid) != tid_to_event(actual_tid))
2170 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2171 tid_to_event(tid), tid_to_event(actual_tid));
2173 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2174 actual_tid, tid, next_tid(tid));
2176 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2179 static void init_kmem_cache_cpus(struct kmem_cache *s)
2183 for_each_possible_cpu(cpu)
2184 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2188 * Remove the cpu slab
2190 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2191 void *freelist, struct kmem_cache_cpu *c)
2193 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2194 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2196 enum slab_modes l = M_NONE, m = M_NONE;
2198 int tail = DEACTIVATE_TO_HEAD;
2202 if (page->freelist) {
2203 stat(s, DEACTIVATE_REMOTE_FREES);
2204 tail = DEACTIVATE_TO_TAIL;
2208 * Stage one: Free all available per cpu objects back
2209 * to the page freelist while it is still frozen. Leave the
2212 * There is no need to take the list->lock because the page
2215 while (freelist && (nextfree = get_freepointer(s, freelist))) {
2217 unsigned long counters;
2220 * If 'nextfree' is invalid, it is possible that the object at
2221 * 'freelist' is already corrupted. So isolate all objects
2222 * starting at 'freelist'.
2224 if (freelist_corrupted(s, page, &freelist, nextfree))
2228 prior = page->freelist;
2229 counters = page->counters;
2230 set_freepointer(s, freelist, prior);
2231 new.counters = counters;
2233 VM_BUG_ON(!new.frozen);
2235 } while (!__cmpxchg_double_slab(s, page,
2237 freelist, new.counters,
2238 "drain percpu freelist"));
2240 freelist = nextfree;
2244 * Stage two: Ensure that the page is unfrozen while the
2245 * list presence reflects the actual number of objects
2248 * We setup the list membership and then perform a cmpxchg
2249 * with the count. If there is a mismatch then the page
2250 * is not unfrozen but the page is on the wrong list.
2252 * Then we restart the process which may have to remove
2253 * the page from the list that we just put it on again
2254 * because the number of objects in the slab may have
2259 old.freelist = page->freelist;
2260 old.counters = page->counters;
2261 VM_BUG_ON(!old.frozen);
2263 /* Determine target state of the slab */
2264 new.counters = old.counters;
2267 set_freepointer(s, freelist, old.freelist);
2268 new.freelist = freelist;
2270 new.freelist = old.freelist;
2274 if (!new.inuse && n->nr_partial >= s->min_partial)
2276 else if (new.freelist) {
2281 * Taking the spinlock removes the possibility
2282 * that acquire_slab() will see a slab page that
2285 raw_spin_lock(&n->list_lock);
2289 #ifdef CONFIG_SLUB_DEBUG
2290 if ((s->flags & SLAB_STORE_USER) && !lock) {
2293 * This also ensures that the scanning of full
2294 * slabs from diagnostic functions will not see
2297 raw_spin_lock(&n->list_lock);
2304 remove_partial(n, page);
2305 else if (l == M_FULL)
2306 remove_full(s, n, page);
2309 add_partial(n, page, tail);
2310 else if (m == M_FULL)
2311 add_full(s, n, page);
2315 if (!__cmpxchg_double_slab(s, page,
2316 old.freelist, old.counters,
2317 new.freelist, new.counters,
2322 raw_spin_unlock(&n->list_lock);
2326 else if (m == M_FULL)
2327 stat(s, DEACTIVATE_FULL);
2328 else if (m == M_FREE) {
2329 stat(s, DEACTIVATE_EMPTY);
2330 discard_slab(s, page);
2339 * Unfreeze all the cpu partial slabs.
2341 * This function must be called with interrupts disabled
2342 * for the cpu using c (or some other guarantee must be there
2343 * to guarantee no concurrent accesses).
2345 static void unfreeze_partials(struct kmem_cache *s,
2346 struct kmem_cache_cpu *c)
2348 #ifdef CONFIG_SLUB_CPU_PARTIAL
2349 struct kmem_cache_node *n = NULL, *n2 = NULL;
2350 struct page *page, *discard_page = NULL;
2352 while ((page = slub_percpu_partial(c))) {
2356 slub_set_percpu_partial(c, page);
2358 n2 = get_node(s, page_to_nid(page));
2361 raw_spin_unlock(&n->list_lock);
2364 raw_spin_lock(&n->list_lock);
2369 old.freelist = page->freelist;
2370 old.counters = page->counters;
2371 VM_BUG_ON(!old.frozen);
2373 new.counters = old.counters;
2374 new.freelist = old.freelist;
2378 } while (!__cmpxchg_double_slab(s, page,
2379 old.freelist, old.counters,
2380 new.freelist, new.counters,
2381 "unfreezing slab"));
2383 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2384 page->next = discard_page;
2385 discard_page = page;
2387 add_partial(n, page, DEACTIVATE_TO_TAIL);
2388 stat(s, FREE_ADD_PARTIAL);
2393 raw_spin_unlock(&n->list_lock);
2395 while (discard_page) {
2396 page = discard_page;
2397 discard_page = discard_page->next;
2399 stat(s, DEACTIVATE_EMPTY);
2400 discard_slab(s, page);
2403 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2407 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2408 * partial page slot if available.
2410 * If we did not find a slot then simply move all the partials to the
2411 * per node partial list.
2413 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2415 #ifdef CONFIG_SLUB_CPU_PARTIAL
2416 struct page *oldpage;
2424 oldpage = this_cpu_read(s->cpu_slab->partial);
2427 pobjects = oldpage->pobjects;
2428 pages = oldpage->pages;
2429 if (drain && pobjects > slub_cpu_partial(s)) {
2430 struct slub_free_list *f;
2431 unsigned long flags;
2434 * partial array is full. Move the existing
2435 * set to the per node partial list.
2437 local_irq_save(flags);
2438 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2439 f = this_cpu_ptr(&slub_free_list);
2440 raw_spin_lock(&f->lock);
2441 list_splice_init(&f->list, &tofree);
2442 raw_spin_unlock(&f->lock);
2443 local_irq_restore(flags);
2444 free_delayed(&tofree);
2448 stat(s, CPU_PARTIAL_DRAIN);
2453 pobjects += page->objects - page->inuse;
2455 page->pages = pages;
2456 page->pobjects = pobjects;
2457 page->next = oldpage;
2459 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2461 if (unlikely(!slub_cpu_partial(s))) {
2462 unsigned long flags;
2464 local_irq_save(flags);
2465 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2466 local_irq_restore(flags);
2469 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2472 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2474 stat(s, CPUSLAB_FLUSH);
2475 deactivate_slab(s, c->page, c->freelist, c);
2477 c->tid = next_tid(c->tid);
2483 * Called from IPI handler with interrupts disabled.
2485 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2487 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2492 unfreeze_partials(s, c);
2495 static void flush_cpu_slab(void *d)
2497 struct kmem_cache *s = d;
2499 __flush_cpu_slab(s, smp_processor_id());
2502 static bool has_cpu_slab(int cpu, void *info)
2504 struct kmem_cache *s = info;
2505 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2507 return c->page || slub_percpu_partial(c);
2510 static void flush_all(struct kmem_cache *s)
2515 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1);
2516 for_each_online_cpu(cpu) {
2517 struct slub_free_list *f;
2519 f = &per_cpu(slub_free_list, cpu);
2520 raw_spin_lock_irq(&f->lock);
2521 list_splice_init(&f->list, &tofree);
2522 raw_spin_unlock_irq(&f->lock);
2523 free_delayed(&tofree);
2528 * Use the cpu notifier to insure that the cpu slabs are flushed when
2531 static int slub_cpu_dead(unsigned int cpu)
2533 struct kmem_cache *s;
2534 unsigned long flags;
2536 mutex_lock(&slab_mutex);
2537 list_for_each_entry(s, &slab_caches, list) {
2538 local_irq_save(flags);
2539 __flush_cpu_slab(s, cpu);
2540 local_irq_restore(flags);
2542 mutex_unlock(&slab_mutex);
2547 * Check if the objects in a per cpu structure fit numa
2548 * locality expectations.
2550 static inline int node_match(struct page *page, int node)
2553 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2559 #ifdef CONFIG_SLUB_DEBUG
2560 static int count_free(struct page *page)
2562 return page->objects - page->inuse;
2565 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2567 return atomic_long_read(&n->total_objects);
2569 #endif /* CONFIG_SLUB_DEBUG */
2571 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2572 static unsigned long count_partial(struct kmem_cache_node *n,
2573 int (*get_count)(struct page *))
2575 unsigned long flags;
2576 unsigned long x = 0;
2579 raw_spin_lock_irqsave(&n->list_lock, flags);
2580 list_for_each_entry(page, &n->partial, slab_list)
2581 x += get_count(page);
2582 raw_spin_unlock_irqrestore(&n->list_lock, flags);
2585 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2587 static noinline void
2588 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2590 #ifdef CONFIG_SLUB_DEBUG
2591 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2592 DEFAULT_RATELIMIT_BURST);
2594 struct kmem_cache_node *n;
2596 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2599 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2600 nid, gfpflags, &gfpflags);
2601 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2602 s->name, s->object_size, s->size, oo_order(s->oo),
2605 if (oo_order(s->min) > get_order(s->object_size))
2606 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2609 for_each_kmem_cache_node(s, node, n) {
2610 unsigned long nr_slabs;
2611 unsigned long nr_objs;
2612 unsigned long nr_free;
2614 nr_free = count_partial(n, count_free);
2615 nr_slabs = node_nr_slabs(n);
2616 nr_objs = node_nr_objs(n);
2618 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2619 node, nr_slabs, nr_objs, nr_free);
2624 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2625 int node, struct kmem_cache_cpu **pc)
2628 struct kmem_cache_cpu *c = *pc;
2631 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2633 freelist = get_partial(s, flags, node, c);
2638 page = new_slab(s, flags, node);
2640 c = raw_cpu_ptr(s->cpu_slab);
2645 * No other reference to the page yet so we can
2646 * muck around with it freely without cmpxchg
2648 freelist = page->freelist;
2649 page->freelist = NULL;
2651 stat(s, ALLOC_SLAB);
2659 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2661 if (unlikely(PageSlabPfmemalloc(page)))
2662 return gfp_pfmemalloc_allowed(gfpflags);
2668 * Check the page->freelist of a page and either transfer the freelist to the
2669 * per cpu freelist or deactivate the page.
2671 * The page is still frozen if the return value is not NULL.
2673 * If this function returns NULL then the page has been unfrozen.
2675 * This function must be called with interrupt disabled.
2677 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2680 unsigned long counters;
2684 freelist = page->freelist;
2685 counters = page->counters;
2687 new.counters = counters;
2688 VM_BUG_ON(!new.frozen);
2690 new.inuse = page->objects;
2691 new.frozen = freelist != NULL;
2693 } while (!__cmpxchg_double_slab(s, page,
2702 * Slow path. The lockless freelist is empty or we need to perform
2705 * Processing is still very fast if new objects have been freed to the
2706 * regular freelist. In that case we simply take over the regular freelist
2707 * as the lockless freelist and zap the regular freelist.
2709 * If that is not working then we fall back to the partial lists. We take the
2710 * first element of the freelist as the object to allocate now and move the
2711 * rest of the freelist to the lockless freelist.
2713 * And if we were unable to get a new slab from the partial slab lists then
2714 * we need to allocate a new slab. This is the slowest path since it involves
2715 * a call to the page allocator and the setup of a new slab.
2717 * Version of __slab_alloc to use when we know that interrupts are
2718 * already disabled (which is the case for bulk allocation).
2720 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2721 unsigned long addr, struct kmem_cache_cpu *c,
2722 struct list_head *to_free)
2724 struct slub_free_list *f;
2728 stat(s, ALLOC_SLOWPATH);
2733 * if the node is not online or has no normal memory, just
2734 * ignore the node constraint
2736 if (unlikely(node != NUMA_NO_NODE &&
2737 !node_state(node, N_NORMAL_MEMORY)))
2738 node = NUMA_NO_NODE;
2743 if (unlikely(!node_match(page, node))) {
2745 * same as above but node_match() being false already
2746 * implies node != NUMA_NO_NODE
2748 if (!node_state(node, N_NORMAL_MEMORY)) {
2749 node = NUMA_NO_NODE;
2752 stat(s, ALLOC_NODE_MISMATCH);
2753 deactivate_slab(s, page, c->freelist, c);
2759 * By rights, we should be searching for a slab page that was
2760 * PFMEMALLOC but right now, we are losing the pfmemalloc
2761 * information when the page leaves the per-cpu allocator
2763 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2764 deactivate_slab(s, page, c->freelist, c);
2768 /* must check again c->freelist in case of cpu migration or IRQ */
2769 freelist = c->freelist;
2773 freelist = get_freelist(s, page);
2777 stat(s, DEACTIVATE_BYPASS);
2781 stat(s, ALLOC_REFILL);
2785 * freelist is pointing to the list of objects to be used.
2786 * page is pointing to the page from which the objects are obtained.
2787 * That page must be frozen for per cpu allocations to work.
2789 VM_BUG_ON(!c->page->frozen);
2790 c->freelist = get_freepointer(s, freelist);
2791 c->tid = next_tid(c->tid);
2794 f = this_cpu_ptr(&slub_free_list);
2795 raw_spin_lock(&f->lock);
2796 list_splice_init(&f->list, to_free);
2797 raw_spin_unlock(&f->lock);
2803 if (slub_percpu_partial(c)) {
2804 page = c->page = slub_percpu_partial(c);
2805 slub_set_percpu_partial(c, page);
2806 stat(s, CPU_PARTIAL_ALLOC);
2810 freelist = new_slab_objects(s, gfpflags, node, &c);
2812 if (unlikely(!freelist)) {
2813 slab_out_of_memory(s, gfpflags, node);
2818 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2821 /* Only entered in the debug case */
2822 if (kmem_cache_debug(s) &&
2823 !alloc_debug_processing(s, page, freelist, addr))
2824 goto new_slab; /* Slab failed checks. Next slab needed */
2826 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2831 * Another one that disabled interrupt and compensates for possible
2832 * cpu changes by refetching the per cpu area pointer.
2834 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2835 unsigned long addr, struct kmem_cache_cpu *c)
2838 unsigned long flags;
2841 local_irq_save(flags);
2842 #ifdef CONFIG_PREEMPTION
2844 * We may have been preempted and rescheduled on a different
2845 * cpu before disabling interrupts. Need to reload cpu area
2848 c = this_cpu_ptr(s->cpu_slab);
2851 p = ___slab_alloc(s, gfpflags, node, addr, c, &tofree);
2852 local_irq_restore(flags);
2853 free_delayed(&tofree);
2858 * If the object has been wiped upon free, make sure it's fully initialized by
2859 * zeroing out freelist pointer.
2861 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2864 if (unlikely(slab_want_init_on_free(s)) && obj)
2865 memset((void *)((char *)obj + s->offset), 0, sizeof(void *));
2869 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2870 * have the fastpath folded into their functions. So no function call
2871 * overhead for requests that can be satisfied on the fastpath.
2873 * The fastpath works by first checking if the lockless freelist can be used.
2874 * If not then __slab_alloc is called for slow processing.
2876 * Otherwise we can simply pick the next object from the lockless free list.
2878 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2879 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
2882 struct kmem_cache_cpu *c;
2885 struct obj_cgroup *objcg = NULL;
2887 if (IS_ENABLED(CONFIG_PREEMPT_RT) && IS_ENABLED(CONFIG_DEBUG_ATOMIC_SLEEP))
2888 WARN_ON_ONCE(!preemptible() &&
2889 (system_state > SYSTEM_BOOTING && system_state < SYSTEM_SUSPEND));
2891 s = slab_pre_alloc_hook(s, &objcg, 1, gfpflags);
2895 object = kfence_alloc(s, orig_size, gfpflags);
2896 if (unlikely(object))
2901 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2902 * enabled. We may switch back and forth between cpus while
2903 * reading from one cpu area. That does not matter as long
2904 * as we end up on the original cpu again when doing the cmpxchg.
2906 * We should guarantee that tid and kmem_cache are retrieved on
2907 * the same cpu. It could be different if CONFIG_PREEMPTION so we need
2908 * to check if it is matched or not.
2911 tid = this_cpu_read(s->cpu_slab->tid);
2912 c = raw_cpu_ptr(s->cpu_slab);
2913 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
2914 unlikely(tid != READ_ONCE(c->tid)));
2917 * Irqless object alloc/free algorithm used here depends on sequence
2918 * of fetching cpu_slab's data. tid should be fetched before anything
2919 * on c to guarantee that object and page associated with previous tid
2920 * won't be used with current tid. If we fetch tid first, object and
2921 * page could be one associated with next tid and our alloc/free
2922 * request will be failed. In this case, we will retry. So, no problem.
2927 * The transaction ids are globally unique per cpu and per operation on
2928 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2929 * occurs on the right processor and that there was no operation on the
2930 * linked list in between.
2933 object = c->freelist;
2935 if (unlikely(!object || !page || !node_match(page, node))) {
2936 object = __slab_alloc(s, gfpflags, node, addr, c);
2938 void *next_object = get_freepointer_safe(s, object);
2941 * The cmpxchg will only match if there was no additional
2942 * operation and if we are on the right processor.
2944 * The cmpxchg does the following atomically (without lock
2946 * 1. Relocate first pointer to the current per cpu area.
2947 * 2. Verify that tid and freelist have not been changed
2948 * 3. If they were not changed replace tid and freelist
2950 * Since this is without lock semantics the protection is only
2951 * against code executing on this cpu *not* from access by
2954 if (unlikely(!this_cpu_cmpxchg_double(
2955 s->cpu_slab->freelist, s->cpu_slab->tid,
2957 next_object, next_tid(tid)))) {
2959 note_cmpxchg_failure("slab_alloc", s, tid);
2962 prefetch_freepointer(s, next_object);
2963 stat(s, ALLOC_FASTPATH);
2966 maybe_wipe_obj_freeptr(s, object);
2968 if (unlikely(slab_want_init_on_alloc(gfpflags, s)) && object)
2969 memset(object, 0, s->object_size);
2972 slab_post_alloc_hook(s, objcg, gfpflags, 1, &object);
2977 static __always_inline void *slab_alloc(struct kmem_cache *s,
2978 gfp_t gfpflags, unsigned long addr, size_t orig_size)
2980 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr, orig_size);
2983 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2985 void *ret = slab_alloc(s, gfpflags, _RET_IP_, s->object_size);
2987 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2992 EXPORT_SYMBOL(kmem_cache_alloc);
2994 #ifdef CONFIG_TRACING
2995 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2997 void *ret = slab_alloc(s, gfpflags, _RET_IP_, size);
2998 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2999 ret = kasan_kmalloc(s, ret, size, gfpflags);
3002 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3006 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
3008 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, s->object_size);
3010 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3011 s->object_size, s->size, gfpflags, node);
3015 EXPORT_SYMBOL(kmem_cache_alloc_node);
3017 #ifdef CONFIG_TRACING
3018 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
3020 int node, size_t size)
3022 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, size);
3024 trace_kmalloc_node(_RET_IP_, ret,
3025 size, s->size, gfpflags, node);
3027 ret = kasan_kmalloc(s, ret, size, gfpflags);
3030 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3032 #endif /* CONFIG_NUMA */
3035 * Slow path handling. This may still be called frequently since objects
3036 * have a longer lifetime than the cpu slabs in most processing loads.
3038 * So we still attempt to reduce cache line usage. Just take the slab
3039 * lock and free the item. If there is no additional partial page
3040 * handling required then we can return immediately.
3042 static void __slab_free(struct kmem_cache *s, struct page *page,
3043 void *head, void *tail, int cnt,
3050 unsigned long counters;
3051 struct kmem_cache_node *n = NULL;
3052 unsigned long flags;
3054 stat(s, FREE_SLOWPATH);
3056 if (kfence_free(head))
3059 if (kmem_cache_debug(s) &&
3060 !free_debug_processing(s, page, head, tail, cnt, addr))
3065 raw_spin_unlock_irqrestore(&n->list_lock, flags);
3068 prior = page->freelist;
3069 counters = page->counters;
3070 set_freepointer(s, tail, prior);
3071 new.counters = counters;
3072 was_frozen = new.frozen;
3074 if ((!new.inuse || !prior) && !was_frozen) {
3076 if (kmem_cache_has_cpu_partial(s) && !prior) {
3079 * Slab was on no list before and will be
3081 * We can defer the list move and instead
3086 } else { /* Needs to be taken off a list */
3088 n = get_node(s, page_to_nid(page));
3090 * Speculatively acquire the list_lock.
3091 * If the cmpxchg does not succeed then we may
3092 * drop the list_lock without any processing.
3094 * Otherwise the list_lock will synchronize with
3095 * other processors updating the list of slabs.
3097 raw_spin_lock_irqsave(&n->list_lock, flags);
3102 } while (!cmpxchg_double_slab(s, page,
3109 if (likely(was_frozen)) {
3111 * The list lock was not taken therefore no list
3112 * activity can be necessary.
3114 stat(s, FREE_FROZEN);
3115 } else if (new.frozen) {
3117 * If we just froze the page then put it onto the
3118 * per cpu partial list.
3120 put_cpu_partial(s, page, 1);
3121 stat(s, CPU_PARTIAL_FREE);
3127 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
3131 * Objects left in the slab. If it was not on the partial list before
3134 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
3135 remove_full(s, n, page);
3136 add_partial(n, page, DEACTIVATE_TO_TAIL);
3137 stat(s, FREE_ADD_PARTIAL);
3139 raw_spin_unlock_irqrestore(&n->list_lock, flags);
3145 * Slab on the partial list.
3147 remove_partial(n, page);
3148 stat(s, FREE_REMOVE_PARTIAL);
3150 /* Slab must be on the full list */
3151 remove_full(s, n, page);
3154 raw_spin_unlock_irqrestore(&n->list_lock, flags);
3156 discard_slab(s, page);
3160 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3161 * can perform fastpath freeing without additional function calls.
3163 * The fastpath is only possible if we are freeing to the current cpu slab
3164 * of this processor. This typically the case if we have just allocated
3167 * If fastpath is not possible then fall back to __slab_free where we deal
3168 * with all sorts of special processing.
3170 * Bulk free of a freelist with several objects (all pointing to the
3171 * same page) possible by specifying head and tail ptr, plus objects
3172 * count (cnt). Bulk free indicated by tail pointer being set.
3174 static __always_inline void do_slab_free(struct kmem_cache *s,
3175 struct page *page, void *head, void *tail,
3176 int cnt, unsigned long addr)
3178 void *tail_obj = tail ? : head;
3179 struct kmem_cache_cpu *c;
3182 /* memcg_slab_free_hook() is already called for bulk free. */
3184 memcg_slab_free_hook(s, &head, 1);
3187 * Determine the currently cpus per cpu slab.
3188 * The cpu may change afterward. However that does not matter since
3189 * data is retrieved via this pointer. If we are on the same cpu
3190 * during the cmpxchg then the free will succeed.
3193 tid = this_cpu_read(s->cpu_slab->tid);
3194 c = raw_cpu_ptr(s->cpu_slab);
3195 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
3196 unlikely(tid != READ_ONCE(c->tid)));
3198 /* Same with comment on barrier() in slab_alloc_node() */
3201 if (likely(page == c->page)) {
3202 void **freelist = READ_ONCE(c->freelist);
3204 set_freepointer(s, tail_obj, freelist);
3206 if (unlikely(!this_cpu_cmpxchg_double(
3207 s->cpu_slab->freelist, s->cpu_slab->tid,
3209 head, next_tid(tid)))) {
3211 note_cmpxchg_failure("slab_free", s, tid);
3214 stat(s, FREE_FASTPATH);
3216 __slab_free(s, page, head, tail_obj, cnt, addr);
3220 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3221 void *head, void *tail, int cnt,
3225 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3226 * to remove objects, whose reuse must be delayed.
3228 if (slab_free_freelist_hook(s, &head, &tail, &cnt))
3229 do_slab_free(s, page, head, tail, cnt, addr);
3232 #ifdef CONFIG_KASAN_GENERIC
3233 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3235 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3239 void kmem_cache_free(struct kmem_cache *s, void *x)
3241 s = cache_from_obj(s, x);
3244 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3245 trace_kmem_cache_free(_RET_IP_, x);
3247 EXPORT_SYMBOL(kmem_cache_free);
3249 struct detached_freelist {
3254 struct kmem_cache *s;
3258 * This function progressively scans the array with free objects (with
3259 * a limited look ahead) and extract objects belonging to the same
3260 * page. It builds a detached freelist directly within the given
3261 * page/objects. This can happen without any need for
3262 * synchronization, because the objects are owned by running process.
3263 * The freelist is build up as a single linked list in the objects.
3264 * The idea is, that this detached freelist can then be bulk
3265 * transferred to the real freelist(s), but only requiring a single
3266 * synchronization primitive. Look ahead in the array is limited due
3267 * to performance reasons.
3270 int build_detached_freelist(struct kmem_cache *s, size_t size,
3271 void **p, struct detached_freelist *df)
3273 size_t first_skipped_index = 0;
3278 /* Always re-init detached_freelist */
3283 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3284 } while (!object && size);
3289 page = virt_to_head_page(object);
3291 /* Handle kalloc'ed objects */
3292 if (unlikely(!PageSlab(page))) {
3293 BUG_ON(!PageCompound(page));
3295 __free_pages(page, compound_order(page));
3296 p[size] = NULL; /* mark object processed */
3299 /* Derive kmem_cache from object */
3300 df->s = page->slab_cache;
3302 df->s = cache_from_obj(s, object); /* Support for memcg */
3305 if (is_kfence_address(object)) {
3306 slab_free_hook(df->s, object);
3307 __kfence_free(object);
3308 p[size] = NULL; /* mark object processed */
3312 /* Start new detached freelist */
3314 set_freepointer(df->s, object, NULL);
3316 df->freelist = object;
3317 p[size] = NULL; /* mark object processed */
3323 continue; /* Skip processed objects */
3325 /* df->page is always set at this point */
3326 if (df->page == virt_to_head_page(object)) {
3327 /* Opportunity build freelist */
3328 set_freepointer(df->s, object, df->freelist);
3329 df->freelist = object;
3331 p[size] = NULL; /* mark object processed */
3336 /* Limit look ahead search */
3340 if (!first_skipped_index)
3341 first_skipped_index = size + 1;
3344 return first_skipped_index;
3347 /* Note that interrupts must be enabled when calling this function. */
3348 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3353 memcg_slab_free_hook(s, p, size);
3355 struct detached_freelist df;
3357 size = build_detached_freelist(s, size, p, &df);
3361 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
3362 } while (likely(size));
3364 EXPORT_SYMBOL(kmem_cache_free_bulk);
3366 /* Note that interrupts must be enabled when calling this function. */
3367 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3370 struct kmem_cache_cpu *c;
3373 struct obj_cgroup *objcg = NULL;
3375 if (IS_ENABLED(CONFIG_PREEMPT_RT) && IS_ENABLED(CONFIG_DEBUG_ATOMIC_SLEEP))
3376 WARN_ON_ONCE(!preemptible() &&
3377 (system_state > SYSTEM_BOOTING && system_state < SYSTEM_SUSPEND));
3379 /* memcg and kmem_cache debug support */
3380 s = slab_pre_alloc_hook(s, &objcg, size, flags);
3384 * Drain objects in the per cpu slab, while disabling local
3385 * IRQs, which protects against PREEMPT and interrupts
3386 * handlers invoking normal fastpath.
3388 local_irq_disable();
3389 c = this_cpu_ptr(s->cpu_slab);
3391 for (i = 0; i < size; i++) {
3392 void *object = kfence_alloc(s, s->object_size, flags);
3394 if (unlikely(object)) {
3399 object = c->freelist;
3400 if (unlikely(!object)) {
3402 * We may have removed an object from c->freelist using
3403 * the fastpath in the previous iteration; in that case,
3404 * c->tid has not been bumped yet.
3405 * Since ___slab_alloc() may reenable interrupts while
3406 * allocating memory, we should bump c->tid now.
3408 c->tid = next_tid(c->tid);
3411 * Invoking slow path likely have side-effect
3412 * of re-populating per CPU c->freelist
3414 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3415 _RET_IP_, c, &to_free);
3416 if (unlikely(!p[i]))
3419 c = this_cpu_ptr(s->cpu_slab);
3420 maybe_wipe_obj_freeptr(s, p[i]);
3422 continue; /* goto for-loop */
3424 c->freelist = get_freepointer(s, object);
3426 maybe_wipe_obj_freeptr(s, p[i]);
3428 c->tid = next_tid(c->tid);
3430 free_delayed(&to_free);
3432 /* Clear memory outside IRQ disabled fastpath loop */
3433 if (unlikely(slab_want_init_on_alloc(flags, s))) {
3436 for (j = 0; j < i; j++)
3437 memset(p[j], 0, s->object_size);
3440 /* memcg and kmem_cache debug support */
3441 slab_post_alloc_hook(s, objcg, flags, size, p);
3445 free_delayed(&to_free);
3446 slab_post_alloc_hook(s, objcg, flags, i, p);
3447 __kmem_cache_free_bulk(s, i, p);
3450 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3454 * Object placement in a slab is made very easy because we always start at
3455 * offset 0. If we tune the size of the object to the alignment then we can
3456 * get the required alignment by putting one properly sized object after
3459 * Notice that the allocation order determines the sizes of the per cpu
3460 * caches. Each processor has always one slab available for allocations.
3461 * Increasing the allocation order reduces the number of times that slabs
3462 * must be moved on and off the partial lists and is therefore a factor in
3467 * Mininum / Maximum order of slab pages. This influences locking overhead
3468 * and slab fragmentation. A higher order reduces the number of partial slabs
3469 * and increases the number of allocations possible without having to
3470 * take the list_lock.
3472 static unsigned int slub_min_order;
3473 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3474 static unsigned int slub_min_objects;
3477 * Calculate the order of allocation given an slab object size.
3479 * The order of allocation has significant impact on performance and other
3480 * system components. Generally order 0 allocations should be preferred since
3481 * order 0 does not cause fragmentation in the page allocator. Larger objects
3482 * be problematic to put into order 0 slabs because there may be too much
3483 * unused space left. We go to a higher order if more than 1/16th of the slab
3486 * In order to reach satisfactory performance we must ensure that a minimum
3487 * number of objects is in one slab. Otherwise we may generate too much
3488 * activity on the partial lists which requires taking the list_lock. This is
3489 * less a concern for large slabs though which are rarely used.
3491 * slub_max_order specifies the order where we begin to stop considering the
3492 * number of objects in a slab as critical. If we reach slub_max_order then
3493 * we try to keep the page order as low as possible. So we accept more waste
3494 * of space in favor of a small page order.
3496 * Higher order allocations also allow the placement of more objects in a
3497 * slab and thereby reduce object handling overhead. If the user has
3498 * requested a higher mininum order then we start with that one instead of
3499 * the smallest order which will fit the object.
3501 static inline unsigned int slab_order(unsigned int size,
3502 unsigned int min_objects, unsigned int max_order,
3503 unsigned int fract_leftover)
3505 unsigned int min_order = slub_min_order;
3508 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3509 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3511 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3512 order <= max_order; order++) {
3514 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3517 rem = slab_size % size;
3519 if (rem <= slab_size / fract_leftover)
3526 static inline int calculate_order(unsigned int size)
3529 unsigned int min_objects;
3530 unsigned int max_objects;
3533 * Attempt to find best configuration for a slab. This
3534 * works by first attempting to generate a layout with
3535 * the best configuration and backing off gradually.
3537 * First we increase the acceptable waste in a slab. Then
3538 * we reduce the minimum objects required in a slab.
3540 min_objects = slub_min_objects;
3542 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3543 max_objects = order_objects(slub_max_order, size);
3544 min_objects = min(min_objects, max_objects);
3546 while (min_objects > 1) {
3547 unsigned int fraction;
3550 while (fraction >= 4) {
3551 order = slab_order(size, min_objects,
3552 slub_max_order, fraction);
3553 if (order <= slub_max_order)
3561 * We were unable to place multiple objects in a slab. Now
3562 * lets see if we can place a single object there.
3564 order = slab_order(size, 1, slub_max_order, 1);
3565 if (order <= slub_max_order)
3569 * Doh this slab cannot be placed using slub_max_order.
3571 order = slab_order(size, 1, MAX_ORDER, 1);
3572 if (order < MAX_ORDER)
3578 init_kmem_cache_node(struct kmem_cache_node *n)
3581 raw_spin_lock_init(&n->list_lock);
3582 INIT_LIST_HEAD(&n->partial);
3583 #ifdef CONFIG_SLUB_DEBUG
3584 atomic_long_set(&n->nr_slabs, 0);
3585 atomic_long_set(&n->total_objects, 0);
3586 INIT_LIST_HEAD(&n->full);
3590 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3592 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3593 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3596 * Must align to double word boundary for the double cmpxchg
3597 * instructions to work; see __pcpu_double_call_return_bool().
3599 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3600 2 * sizeof(void *));
3605 init_kmem_cache_cpus(s);
3610 static struct kmem_cache *kmem_cache_node;
3613 * No kmalloc_node yet so do it by hand. We know that this is the first
3614 * slab on the node for this slabcache. There are no concurrent accesses
3617 * Note that this function only works on the kmem_cache_node
3618 * when allocating for the kmem_cache_node. This is used for bootstrapping
3619 * memory on a fresh node that has no slab structures yet.
3621 static void early_kmem_cache_node_alloc(int node)
3624 struct kmem_cache_node *n;
3626 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3628 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3631 if (page_to_nid(page) != node) {
3632 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3633 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3638 #ifdef CONFIG_SLUB_DEBUG
3639 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3640 init_tracking(kmem_cache_node, n);
3642 n = kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
3644 page->freelist = get_freepointer(kmem_cache_node, n);
3647 kmem_cache_node->node[node] = n;
3648 init_kmem_cache_node(n);
3649 inc_slabs_node(kmem_cache_node, node, page->objects);
3652 * No locks need to be taken here as it has just been
3653 * initialized and there is no concurrent access.
3655 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3658 static void free_kmem_cache_nodes(struct kmem_cache *s)
3661 struct kmem_cache_node *n;
3663 for_each_kmem_cache_node(s, node, n) {
3664 s->node[node] = NULL;
3665 kmem_cache_free(kmem_cache_node, n);
3669 void __kmem_cache_release(struct kmem_cache *s)
3671 cache_random_seq_destroy(s);
3672 free_percpu(s->cpu_slab);
3673 free_kmem_cache_nodes(s);
3676 static int init_kmem_cache_nodes(struct kmem_cache *s)
3680 for_each_node_state(node, N_NORMAL_MEMORY) {
3681 struct kmem_cache_node *n;
3683 if (slab_state == DOWN) {
3684 early_kmem_cache_node_alloc(node);
3687 n = kmem_cache_alloc_node(kmem_cache_node,
3691 free_kmem_cache_nodes(s);
3695 init_kmem_cache_node(n);
3701 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3703 if (min < MIN_PARTIAL)
3705 else if (min > MAX_PARTIAL)
3707 s->min_partial = min;
3710 static void set_cpu_partial(struct kmem_cache *s)
3712 #ifdef CONFIG_SLUB_CPU_PARTIAL
3714 * cpu_partial determined the maximum number of objects kept in the
3715 * per cpu partial lists of a processor.
3717 * Per cpu partial lists mainly contain slabs that just have one
3718 * object freed. If they are used for allocation then they can be
3719 * filled up again with minimal effort. The slab will never hit the
3720 * per node partial lists and therefore no locking will be required.
3722 * This setting also determines
3724 * A) The number of objects from per cpu partial slabs dumped to the
3725 * per node list when we reach the limit.
3726 * B) The number of objects in cpu partial slabs to extract from the
3727 * per node list when we run out of per cpu objects. We only fetch
3728 * 50% to keep some capacity around for frees.
3730 if (!kmem_cache_has_cpu_partial(s))
3731 slub_set_cpu_partial(s, 0);
3732 else if (s->size >= PAGE_SIZE)
3733 slub_set_cpu_partial(s, 2);
3734 else if (s->size >= 1024)
3735 slub_set_cpu_partial(s, 6);
3736 else if (s->size >= 256)
3737 slub_set_cpu_partial(s, 13);
3739 slub_set_cpu_partial(s, 30);
3744 * calculate_sizes() determines the order and the distribution of data within
3747 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3749 slab_flags_t flags = s->flags;
3750 unsigned int size = s->object_size;
3754 * Round up object size to the next word boundary. We can only
3755 * place the free pointer at word boundaries and this determines
3756 * the possible location of the free pointer.
3758 size = ALIGN(size, sizeof(void *));
3760 #ifdef CONFIG_SLUB_DEBUG
3762 * Determine if we can poison the object itself. If the user of
3763 * the slab may touch the object after free or before allocation
3764 * then we should never poison the object itself.
3766 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3768 s->flags |= __OBJECT_POISON;
3770 s->flags &= ~__OBJECT_POISON;
3774 * If we are Redzoning then check if there is some space between the
3775 * end of the object and the free pointer. If not then add an
3776 * additional word to have some bytes to store Redzone information.
3778 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3779 size += sizeof(void *);
3783 * With that we have determined the number of bytes in actual use
3784 * by the object and redzoning.
3788 if ((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3789 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
3792 * Relocate free pointer after the object if it is not
3793 * permitted to overwrite the first word of the object on
3796 * This is the case if we do RCU, have a constructor or
3797 * destructor, are poisoning the objects, or are
3798 * redzoning an object smaller than sizeof(void *).
3800 * The assumption that s->offset >= s->inuse means free
3801 * pointer is outside of the object is used in the
3802 * freeptr_outside_object() function. If that is no
3803 * longer true, the function needs to be modified.
3806 size += sizeof(void *);
3809 * Store freelist pointer near middle of object to keep
3810 * it away from the edges of the object to avoid small
3811 * sized over/underflows from neighboring allocations.
3813 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
3816 #ifdef CONFIG_SLUB_DEBUG
3817 if (flags & SLAB_STORE_USER)
3819 * Need to store information about allocs and frees after
3822 size += 2 * sizeof(struct track);
3825 kasan_cache_create(s, &size, &s->flags);
3826 #ifdef CONFIG_SLUB_DEBUG
3827 if (flags & SLAB_RED_ZONE) {
3829 * Add some empty padding so that we can catch
3830 * overwrites from earlier objects rather than let
3831 * tracking information or the free pointer be
3832 * corrupted if a user writes before the start
3835 size += sizeof(void *);
3837 s->red_left_pad = sizeof(void *);
3838 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3839 size += s->red_left_pad;
3844 * SLUB stores one object immediately after another beginning from
3845 * offset 0. In order to align the objects we have to simply size
3846 * each object to conform to the alignment.
3848 size = ALIGN(size, s->align);
3850 s->reciprocal_size = reciprocal_value(size);
3851 if (forced_order >= 0)
3852 order = forced_order;
3854 order = calculate_order(size);
3861 s->allocflags |= __GFP_COMP;
3863 if (s->flags & SLAB_CACHE_DMA)
3864 s->allocflags |= GFP_DMA;
3866 if (s->flags & SLAB_CACHE_DMA32)
3867 s->allocflags |= GFP_DMA32;
3869 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3870 s->allocflags |= __GFP_RECLAIMABLE;
3873 * Determine the number of objects per slab
3875 s->oo = oo_make(order, size);
3876 s->min = oo_make(get_order(size), size);
3877 if (oo_objects(s->oo) > oo_objects(s->max))
3880 return !!oo_objects(s->oo);
3883 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3885 s->flags = kmem_cache_flags(s->size, flags, s->name);
3886 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3887 s->random = get_random_long();
3890 if (!calculate_sizes(s, -1))
3892 if (disable_higher_order_debug) {
3894 * Disable debugging flags that store metadata if the min slab
3897 if (get_order(s->size) > get_order(s->object_size)) {
3898 s->flags &= ~DEBUG_METADATA_FLAGS;
3900 if (!calculate_sizes(s, -1))
3905 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3906 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3907 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3908 /* Enable fast mode */
3909 s->flags |= __CMPXCHG_DOUBLE;
3913 * The larger the object size is, the more pages we want on the partial
3914 * list to avoid pounding the page allocator excessively.
3916 set_min_partial(s, ilog2(s->size) / 2);
3921 s->remote_node_defrag_ratio = 1000;
3924 /* Initialize the pre-computed randomized freelist if slab is up */
3925 if (slab_state >= UP) {
3926 if (init_cache_random_seq(s))
3930 if (!init_kmem_cache_nodes(s))
3933 if (alloc_kmem_cache_cpus(s))
3937 __kmem_cache_release(s);
3941 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3944 #ifdef CONFIG_SLUB_DEBUG
3945 void *addr = page_address(page);
3949 slab_err(s, page, text, s->name);
3952 map = get_map(s, page);
3953 for_each_object(p, s, addr, page->objects) {
3955 if (!test_bit(__obj_to_index(s, addr, p), map)) {
3956 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3957 print_tracking(s, p);
3966 * Attempt to free all partial slabs on a node.
3967 * This is called from __kmem_cache_shutdown(). We must take list_lock
3968 * because sysfs file might still access partial list after the shutdowning.
3970 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3973 struct page *page, *h;
3975 BUG_ON(irqs_disabled());
3976 raw_spin_lock_irq(&n->list_lock);
3977 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3979 remove_partial(n, page);
3980 list_add(&page->slab_list, &discard);
3982 list_slab_objects(s, page,
3983 "Objects remaining in %s on __kmem_cache_shutdown()");
3986 raw_spin_unlock_irq(&n->list_lock);
3988 list_for_each_entry_safe(page, h, &discard, slab_list)
3989 discard_slab(s, page);
3992 bool __kmem_cache_empty(struct kmem_cache *s)
3995 struct kmem_cache_node *n;
3997 for_each_kmem_cache_node(s, node, n)
3998 if (n->nr_partial || slabs_node(s, node))
4004 * Release all resources used by a slab cache.
4006 int __kmem_cache_shutdown(struct kmem_cache *s)
4009 struct kmem_cache_node *n;
4012 /* Attempt to free all objects */
4013 for_each_kmem_cache_node(s, node, n) {
4015 if (n->nr_partial || slabs_node(s, node))
4021 /********************************************************************
4023 *******************************************************************/
4025 static int __init setup_slub_min_order(char *str)
4027 get_option(&str, (int *)&slub_min_order);
4032 __setup("slub_min_order=", setup_slub_min_order);
4034 static int __init setup_slub_max_order(char *str)
4036 get_option(&str, (int *)&slub_max_order);
4037 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
4042 __setup("slub_max_order=", setup_slub_max_order);
4044 static int __init setup_slub_min_objects(char *str)
4046 get_option(&str, (int *)&slub_min_objects);
4051 __setup("slub_min_objects=", setup_slub_min_objects);
4053 void *__kmalloc(size_t size, gfp_t flags)
4055 struct kmem_cache *s;
4058 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4059 return kmalloc_large(size, flags);
4061 s = kmalloc_slab(size, flags);
4063 if (unlikely(ZERO_OR_NULL_PTR(s)))
4066 ret = slab_alloc(s, flags, _RET_IP_, size);
4068 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
4070 ret = kasan_kmalloc(s, ret, size, flags);
4074 EXPORT_SYMBOL(__kmalloc);
4077 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
4081 unsigned int order = get_order(size);
4083 flags |= __GFP_COMP;
4084 page = alloc_pages_node(node, flags, order);
4086 ptr = page_address(page);
4087 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4088 PAGE_SIZE << order);
4091 return kmalloc_large_node_hook(ptr, size, flags);
4094 void *__kmalloc_node(size_t size, gfp_t flags, int node)
4096 struct kmem_cache *s;
4099 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4100 ret = kmalloc_large_node(size, flags, node);
4102 trace_kmalloc_node(_RET_IP_, ret,
4103 size, PAGE_SIZE << get_order(size),
4109 s = kmalloc_slab(size, flags);
4111 if (unlikely(ZERO_OR_NULL_PTR(s)))
4114 ret = slab_alloc_node(s, flags, node, _RET_IP_, size);
4116 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
4118 ret = kasan_kmalloc(s, ret, size, flags);
4122 EXPORT_SYMBOL(__kmalloc_node);
4123 #endif /* CONFIG_NUMA */
4125 #ifdef CONFIG_HARDENED_USERCOPY
4127 * Rejects incorrectly sized objects and objects that are to be copied
4128 * to/from userspace but do not fall entirely within the containing slab
4129 * cache's usercopy region.
4131 * Returns NULL if check passes, otherwise const char * to name of cache
4132 * to indicate an error.
4134 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
4137 struct kmem_cache *s;
4138 unsigned int offset;
4140 bool is_kfence = is_kfence_address(ptr);
4142 ptr = kasan_reset_tag(ptr);
4144 /* Find object and usable object size. */
4145 s = page->slab_cache;
4147 /* Reject impossible pointers. */
4148 if (ptr < page_address(page))
4149 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4152 /* Find offset within object. */
4154 offset = ptr - kfence_object_start(ptr);
4156 offset = (ptr - page_address(page)) % s->size;
4158 /* Adjust for redzone and reject if within the redzone. */
4159 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
4160 if (offset < s->red_left_pad)
4161 usercopy_abort("SLUB object in left red zone",
4162 s->name, to_user, offset, n);
4163 offset -= s->red_left_pad;
4166 /* Allow address range falling entirely within usercopy region. */
4167 if (offset >= s->useroffset &&
4168 offset - s->useroffset <= s->usersize &&
4169 n <= s->useroffset - offset + s->usersize)
4173 * If the copy is still within the allocated object, produce
4174 * a warning instead of rejecting the copy. This is intended
4175 * to be a temporary method to find any missing usercopy
4178 object_size = slab_ksize(s);
4179 if (usercopy_fallback &&
4180 offset <= object_size && n <= object_size - offset) {
4181 usercopy_warn("SLUB object", s->name, to_user, offset, n);
4185 usercopy_abort("SLUB object", s->name, to_user, offset, n);
4187 #endif /* CONFIG_HARDENED_USERCOPY */
4189 size_t __ksize(const void *object)
4193 if (unlikely(object == ZERO_SIZE_PTR))
4196 page = virt_to_head_page(object);
4198 if (unlikely(!PageSlab(page))) {
4199 WARN_ON(!PageCompound(page));
4200 return page_size(page);
4203 return slab_ksize(page->slab_cache);
4205 EXPORT_SYMBOL(__ksize);
4207 void kfree(const void *x)
4210 void *object = (void *)x;
4212 trace_kfree(_RET_IP_, x);
4214 if (unlikely(ZERO_OR_NULL_PTR(x)))
4217 page = virt_to_head_page(x);
4218 if (unlikely(!PageSlab(page))) {
4219 unsigned int order = compound_order(page);
4221 BUG_ON(!PageCompound(page));
4223 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4224 -(PAGE_SIZE << order));
4225 __free_pages(page, order);
4228 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4230 EXPORT_SYMBOL(kfree);
4232 #define SHRINK_PROMOTE_MAX 32
4235 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4236 * up most to the head of the partial lists. New allocations will then
4237 * fill those up and thus they can be removed from the partial lists.
4239 * The slabs with the least items are placed last. This results in them
4240 * being allocated from last increasing the chance that the last objects
4241 * are freed in them.
4243 int __kmem_cache_shrink(struct kmem_cache *s)
4247 struct kmem_cache_node *n;
4250 struct list_head discard;
4251 struct list_head promote[SHRINK_PROMOTE_MAX];
4252 unsigned long flags;
4256 for_each_kmem_cache_node(s, node, n) {
4257 INIT_LIST_HEAD(&discard);
4258 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4259 INIT_LIST_HEAD(promote + i);
4261 raw_spin_lock_irqsave(&n->list_lock, flags);
4264 * Build lists of slabs to discard or promote.
4266 * Note that concurrent frees may occur while we hold the
4267 * list_lock. page->inuse here is the upper limit.
4269 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4270 int free = page->objects - page->inuse;
4272 /* Do not reread page->inuse */
4275 /* We do not keep full slabs on the list */
4278 if (free == page->objects) {
4279 list_move(&page->slab_list, &discard);
4281 } else if (free <= SHRINK_PROMOTE_MAX)
4282 list_move(&page->slab_list, promote + free - 1);
4286 * Promote the slabs filled up most to the head of the
4289 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4290 list_splice(promote + i, &n->partial);
4292 raw_spin_unlock_irqrestore(&n->list_lock, flags);
4294 /* Release empty slabs */
4295 list_for_each_entry_safe(page, t, &discard, slab_list)
4296 discard_slab(s, page);
4298 if (slabs_node(s, node))
4305 static int slab_mem_going_offline_callback(void *arg)
4307 struct kmem_cache *s;
4309 mutex_lock(&slab_mutex);
4310 list_for_each_entry(s, &slab_caches, list)
4311 __kmem_cache_shrink(s);
4312 mutex_unlock(&slab_mutex);
4317 static void slab_mem_offline_callback(void *arg)
4319 struct kmem_cache_node *n;
4320 struct kmem_cache *s;
4321 struct memory_notify *marg = arg;
4324 offline_node = marg->status_change_nid_normal;
4327 * If the node still has available memory. we need kmem_cache_node
4330 if (offline_node < 0)
4333 mutex_lock(&slab_mutex);
4334 list_for_each_entry(s, &slab_caches, list) {
4335 n = get_node(s, offline_node);
4338 * if n->nr_slabs > 0, slabs still exist on the node
4339 * that is going down. We were unable to free them,
4340 * and offline_pages() function shouldn't call this
4341 * callback. So, we must fail.
4343 BUG_ON(slabs_node(s, offline_node));
4345 s->node[offline_node] = NULL;
4346 kmem_cache_free(kmem_cache_node, n);
4349 mutex_unlock(&slab_mutex);
4352 static int slab_mem_going_online_callback(void *arg)
4354 struct kmem_cache_node *n;
4355 struct kmem_cache *s;
4356 struct memory_notify *marg = arg;
4357 int nid = marg->status_change_nid_normal;
4361 * If the node's memory is already available, then kmem_cache_node is
4362 * already created. Nothing to do.
4368 * We are bringing a node online. No memory is available yet. We must
4369 * allocate a kmem_cache_node structure in order to bring the node
4372 mutex_lock(&slab_mutex);
4373 list_for_each_entry(s, &slab_caches, list) {
4375 * XXX: kmem_cache_alloc_node will fallback to other nodes
4376 * since memory is not yet available from the node that
4379 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4384 init_kmem_cache_node(n);
4388 mutex_unlock(&slab_mutex);
4392 static int slab_memory_callback(struct notifier_block *self,
4393 unsigned long action, void *arg)
4398 case MEM_GOING_ONLINE:
4399 ret = slab_mem_going_online_callback(arg);
4401 case MEM_GOING_OFFLINE:
4402 ret = slab_mem_going_offline_callback(arg);
4405 case MEM_CANCEL_ONLINE:
4406 slab_mem_offline_callback(arg);
4409 case MEM_CANCEL_OFFLINE:
4413 ret = notifier_from_errno(ret);
4419 static struct notifier_block slab_memory_callback_nb = {
4420 .notifier_call = slab_memory_callback,
4421 .priority = SLAB_CALLBACK_PRI,
4424 /********************************************************************
4425 * Basic setup of slabs
4426 *******************************************************************/
4429 * Used for early kmem_cache structures that were allocated using
4430 * the page allocator. Allocate them properly then fix up the pointers
4431 * that may be pointing to the wrong kmem_cache structure.
4434 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4437 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4438 struct kmem_cache_node *n;
4440 memcpy(s, static_cache, kmem_cache->object_size);
4443 * This runs very early, and only the boot processor is supposed to be
4444 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4447 __flush_cpu_slab(s, smp_processor_id());
4448 for_each_kmem_cache_node(s, node, n) {
4451 list_for_each_entry(p, &n->partial, slab_list)
4454 #ifdef CONFIG_SLUB_DEBUG
4455 list_for_each_entry(p, &n->full, slab_list)
4459 list_add(&s->list, &slab_caches);
4463 void __init kmem_cache_init(void)
4465 static __initdata struct kmem_cache boot_kmem_cache,
4466 boot_kmem_cache_node;
4469 for_each_possible_cpu(cpu) {
4470 raw_spin_lock_init(&per_cpu(slub_free_list, cpu).lock);
4471 INIT_LIST_HEAD(&per_cpu(slub_free_list, cpu).list);
4474 if (debug_guardpage_minorder())
4477 kmem_cache_node = &boot_kmem_cache_node;
4478 kmem_cache = &boot_kmem_cache;
4480 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4481 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4483 register_hotmemory_notifier(&slab_memory_callback_nb);
4485 /* Able to allocate the per node structures */
4486 slab_state = PARTIAL;
4488 create_boot_cache(kmem_cache, "kmem_cache",
4489 offsetof(struct kmem_cache, node) +
4490 nr_node_ids * sizeof(struct kmem_cache_node *),
4491 SLAB_HWCACHE_ALIGN, 0, 0);
4493 kmem_cache = bootstrap(&boot_kmem_cache);
4494 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4496 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4497 setup_kmalloc_cache_index_table();
4498 create_kmalloc_caches(0);
4500 /* Setup random freelists for each cache */
4501 init_freelist_randomization();
4503 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4506 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4508 slub_min_order, slub_max_order, slub_min_objects,
4509 nr_cpu_ids, nr_node_ids);
4512 void __init kmem_cache_init_late(void)
4517 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4518 slab_flags_t flags, void (*ctor)(void *))
4520 struct kmem_cache *s;
4522 s = find_mergeable(size, align, flags, name, ctor);
4527 * Adjust the object sizes so that we clear
4528 * the complete object on kzalloc.
4530 s->object_size = max(s->object_size, size);
4531 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4533 if (sysfs_slab_alias(s, name)) {
4542 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4546 err = kmem_cache_open(s, flags);
4550 /* Mutex is not taken during early boot */
4551 if (slab_state <= UP)
4554 err = sysfs_slab_add(s);
4556 __kmem_cache_release(s);
4561 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4563 struct kmem_cache *s;
4566 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4567 return kmalloc_large(size, gfpflags);
4569 s = kmalloc_slab(size, gfpflags);
4571 if (unlikely(ZERO_OR_NULL_PTR(s)))
4574 ret = slab_alloc(s, gfpflags, caller, size);
4576 /* Honor the call site pointer we received. */
4577 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4581 EXPORT_SYMBOL(__kmalloc_track_caller);
4584 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4585 int node, unsigned long caller)
4587 struct kmem_cache *s;
4590 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4591 ret = kmalloc_large_node(size, gfpflags, node);
4593 trace_kmalloc_node(caller, ret,
4594 size, PAGE_SIZE << get_order(size),
4600 s = kmalloc_slab(size, gfpflags);
4602 if (unlikely(ZERO_OR_NULL_PTR(s)))
4605 ret = slab_alloc_node(s, gfpflags, node, caller, size);
4607 /* Honor the call site pointer we received. */
4608 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4612 EXPORT_SYMBOL(__kmalloc_node_track_caller);
4616 static int count_inuse(struct page *page)
4621 static int count_total(struct page *page)
4623 return page->objects;
4627 #ifdef CONFIG_SLUB_DEBUG
4628 static void validate_slab(struct kmem_cache *s, struct page *page)
4631 void *addr = page_address(page);
4636 if (!check_slab(s, page) || !on_freelist(s, page, NULL))
4639 /* Now we know that a valid freelist exists */
4640 map = get_map(s, page);
4641 for_each_object(p, s, addr, page->objects) {
4642 u8 val = test_bit(__obj_to_index(s, addr, p), map) ?
4643 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
4645 if (!check_object(s, page, p, val))
4653 static int validate_slab_node(struct kmem_cache *s,
4654 struct kmem_cache_node *n)
4656 unsigned long count = 0;
4658 unsigned long flags;
4660 raw_spin_lock_irqsave(&n->list_lock, flags);
4662 list_for_each_entry(page, &n->partial, slab_list) {
4663 validate_slab(s, page);
4666 if (count != n->nr_partial)
4667 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4668 s->name, count, n->nr_partial);
4670 if (!(s->flags & SLAB_STORE_USER))
4673 list_for_each_entry(page, &n->full, slab_list) {
4674 validate_slab(s, page);
4677 if (count != atomic_long_read(&n->nr_slabs))
4678 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4679 s->name, count, atomic_long_read(&n->nr_slabs));
4682 raw_spin_unlock_irqrestore(&n->list_lock, flags);
4686 static long validate_slab_cache(struct kmem_cache *s)
4689 unsigned long count = 0;
4690 struct kmem_cache_node *n;
4693 for_each_kmem_cache_node(s, node, n)
4694 count += validate_slab_node(s, n);
4699 * Generate lists of code addresses where slabcache objects are allocated
4704 unsigned long count;
4711 DECLARE_BITMAP(cpus, NR_CPUS);
4717 unsigned long count;
4718 struct location *loc;
4721 static void free_loc_track(struct loc_track *t)
4724 free_pages((unsigned long)t->loc,
4725 get_order(sizeof(struct location) * t->max));
4728 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4733 if (IS_ENABLED(CONFIG_PREEMPT_RT) && flags == GFP_ATOMIC)
4736 order = get_order(sizeof(struct location) * max);
4738 l = (void *)__get_free_pages(flags, order);
4743 memcpy(l, t->loc, sizeof(struct location) * t->count);
4751 static int add_location(struct loc_track *t, struct kmem_cache *s,
4752 const struct track *track)
4754 long start, end, pos;
4756 unsigned long caddr;
4757 unsigned long age = jiffies - track->when;
4763 pos = start + (end - start + 1) / 2;
4766 * There is nothing at "end". If we end up there
4767 * we need to add something to before end.
4772 caddr = t->loc[pos].addr;
4773 if (track->addr == caddr) {
4779 if (age < l->min_time)
4781 if (age > l->max_time)
4784 if (track->pid < l->min_pid)
4785 l->min_pid = track->pid;
4786 if (track->pid > l->max_pid)
4787 l->max_pid = track->pid;
4789 cpumask_set_cpu(track->cpu,
4790 to_cpumask(l->cpus));
4792 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4796 if (track->addr < caddr)
4803 * Not found. Insert new tracking element.
4805 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4811 (t->count - pos) * sizeof(struct location));
4814 l->addr = track->addr;
4818 l->min_pid = track->pid;
4819 l->max_pid = track->pid;
4820 cpumask_clear(to_cpumask(l->cpus));
4821 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4822 nodes_clear(l->nodes);
4823 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4827 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4828 struct page *page, enum track_item alloc)
4830 void *addr = page_address(page);
4834 map = get_map(s, page);
4835 for_each_object(p, s, addr, page->objects)
4836 if (!test_bit(__obj_to_index(s, addr, p), map))
4837 add_location(t, s, get_track(s, p, alloc));
4841 static int list_locations(struct kmem_cache *s, char *buf,
4842 enum track_item alloc)
4846 struct loc_track t = { 0, 0, NULL };
4848 struct kmem_cache_node *n;
4850 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4852 return sprintf(buf, "Out of memory\n");
4854 /* Push back cpu slabs */
4857 for_each_kmem_cache_node(s, node, n) {
4858 unsigned long flags;
4861 if (!atomic_long_read(&n->nr_slabs))
4864 raw_spin_lock_irqsave(&n->list_lock, flags);
4865 list_for_each_entry(page, &n->partial, slab_list)
4866 process_slab(&t, s, page, alloc);
4867 list_for_each_entry(page, &n->full, slab_list)
4868 process_slab(&t, s, page, alloc);
4869 raw_spin_unlock_irqrestore(&n->list_lock, flags);
4872 for (i = 0; i < t.count; i++) {
4873 struct location *l = &t.loc[i];
4875 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4877 len += sprintf(buf + len, "%7ld ", l->count);
4880 len += sprintf(buf + len, "%pS", (void *)l->addr);
4882 len += sprintf(buf + len, "<not-available>");
4884 if (l->sum_time != l->min_time) {
4885 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4887 (long)div_u64(l->sum_time, l->count),
4890 len += sprintf(buf + len, " age=%ld",
4893 if (l->min_pid != l->max_pid)
4894 len += sprintf(buf + len, " pid=%ld-%ld",
4895 l->min_pid, l->max_pid);
4897 len += sprintf(buf + len, " pid=%ld",
4900 if (num_online_cpus() > 1 &&
4901 !cpumask_empty(to_cpumask(l->cpus)) &&
4902 len < PAGE_SIZE - 60)
4903 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4905 cpumask_pr_args(to_cpumask(l->cpus)));
4907 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4908 len < PAGE_SIZE - 60)
4909 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4911 nodemask_pr_args(&l->nodes));
4913 len += sprintf(buf + len, "\n");
4918 len += sprintf(buf, "No data\n");
4921 #endif /* CONFIG_SLUB_DEBUG */
4923 #ifdef SLUB_RESILIENCY_TEST
4924 static void __init resiliency_test(void)
4927 int type = KMALLOC_NORMAL;
4929 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4931 pr_err("SLUB resiliency testing\n");
4932 pr_err("-----------------------\n");
4933 pr_err("A. Corruption after allocation\n");
4935 p = kzalloc(16, GFP_KERNEL);
4937 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4940 validate_slab_cache(kmalloc_caches[type][4]);
4942 /* Hmmm... The next two are dangerous */
4943 p = kzalloc(32, GFP_KERNEL);
4944 p[32 + sizeof(void *)] = 0x34;
4945 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4947 pr_err("If allocated object is overwritten then not detectable\n\n");
4949 validate_slab_cache(kmalloc_caches[type][5]);
4950 p = kzalloc(64, GFP_KERNEL);
4951 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4953 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4955 pr_err("If allocated object is overwritten then not detectable\n\n");
4956 validate_slab_cache(kmalloc_caches[type][6]);
4958 pr_err("\nB. Corruption after free\n");
4959 p = kzalloc(128, GFP_KERNEL);
4962 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4963 validate_slab_cache(kmalloc_caches[type][7]);
4965 p = kzalloc(256, GFP_KERNEL);
4968 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4969 validate_slab_cache(kmalloc_caches[type][8]);
4971 p = kzalloc(512, GFP_KERNEL);
4974 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4975 validate_slab_cache(kmalloc_caches[type][9]);
4979 static void resiliency_test(void) {};
4981 #endif /* SLUB_RESILIENCY_TEST */
4984 enum slab_stat_type {
4985 SL_ALL, /* All slabs */
4986 SL_PARTIAL, /* Only partially allocated slabs */
4987 SL_CPU, /* Only slabs used for cpu caches */
4988 SL_OBJECTS, /* Determine allocated objects not slabs */
4989 SL_TOTAL /* Determine object capacity not slabs */
4992 #define SO_ALL (1 << SL_ALL)
4993 #define SO_PARTIAL (1 << SL_PARTIAL)
4994 #define SO_CPU (1 << SL_CPU)
4995 #define SO_OBJECTS (1 << SL_OBJECTS)
4996 #define SO_TOTAL (1 << SL_TOTAL)
4999 static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON);
5001 static int __init setup_slub_memcg_sysfs(char *str)
5005 if (get_option(&str, &v) > 0)
5006 memcg_sysfs_enabled = v;
5011 __setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs);
5014 static ssize_t show_slab_objects(struct kmem_cache *s,
5015 char *buf, unsigned long flags)
5017 unsigned long total = 0;
5020 unsigned long *nodes;
5022 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
5026 if (flags & SO_CPU) {
5029 for_each_possible_cpu(cpu) {
5030 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
5035 page = READ_ONCE(c->page);
5039 node = page_to_nid(page);
5040 if (flags & SO_TOTAL)
5042 else if (flags & SO_OBJECTS)
5050 page = slub_percpu_partial_read_once(c);
5052 node = page_to_nid(page);
5053 if (flags & SO_TOTAL)
5055 else if (flags & SO_OBJECTS)
5066 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
5067 * already held which will conflict with an existing lock order:
5069 * mem_hotplug_lock->slab_mutex->kernfs_mutex
5071 * We don't really need mem_hotplug_lock (to hold off
5072 * slab_mem_going_offline_callback) here because slab's memory hot
5073 * unplug code doesn't destroy the kmem_cache->node[] data.
5076 #ifdef CONFIG_SLUB_DEBUG
5077 if (flags & SO_ALL) {
5078 struct kmem_cache_node *n;
5080 for_each_kmem_cache_node(s, node, n) {
5082 if (flags & SO_TOTAL)
5083 x = atomic_long_read(&n->total_objects);
5084 else if (flags & SO_OBJECTS)
5085 x = atomic_long_read(&n->total_objects) -
5086 count_partial(n, count_free);
5088 x = atomic_long_read(&n->nr_slabs);
5095 if (flags & SO_PARTIAL) {
5096 struct kmem_cache_node *n;
5098 for_each_kmem_cache_node(s, node, n) {
5099 if (flags & SO_TOTAL)
5100 x = count_partial(n, count_total);
5101 else if (flags & SO_OBJECTS)
5102 x = count_partial(n, count_inuse);
5109 x = sprintf(buf, "%lu", total);
5111 for (node = 0; node < nr_node_ids; node++)
5113 x += sprintf(buf + x, " N%d=%lu",
5117 return x + sprintf(buf + x, "\n");
5120 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
5121 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
5123 struct slab_attribute {
5124 struct attribute attr;
5125 ssize_t (*show)(struct kmem_cache *s, char *buf);
5126 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5129 #define SLAB_ATTR_RO(_name) \
5130 static struct slab_attribute _name##_attr = \
5131 __ATTR(_name, 0400, _name##_show, NULL)
5133 #define SLAB_ATTR(_name) \
5134 static struct slab_attribute _name##_attr = \
5135 __ATTR(_name, 0600, _name##_show, _name##_store)
5137 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5139 return sprintf(buf, "%u\n", s->size);
5141 SLAB_ATTR_RO(slab_size);
5143 static ssize_t align_show(struct kmem_cache *s, char *buf)
5145 return sprintf(buf, "%u\n", s->align);
5147 SLAB_ATTR_RO(align);
5149 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5151 return sprintf(buf, "%u\n", s->object_size);
5153 SLAB_ATTR_RO(object_size);
5155 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5157 return sprintf(buf, "%u\n", oo_objects(s->oo));
5159 SLAB_ATTR_RO(objs_per_slab);
5161 static ssize_t order_show(struct kmem_cache *s, char *buf)
5163 return sprintf(buf, "%u\n", oo_order(s->oo));
5165 SLAB_ATTR_RO(order);
5167 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5169 return sprintf(buf, "%lu\n", s->min_partial);
5172 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5178 err = kstrtoul(buf, 10, &min);
5182 set_min_partial(s, min);
5185 SLAB_ATTR(min_partial);
5187 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5189 return sprintf(buf, "%u\n", slub_cpu_partial(s));
5192 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5195 unsigned int objects;
5198 err = kstrtouint(buf, 10, &objects);
5201 if (objects && !kmem_cache_has_cpu_partial(s))
5204 slub_set_cpu_partial(s, objects);
5208 SLAB_ATTR(cpu_partial);
5210 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5214 return sprintf(buf, "%pS\n", s->ctor);
5218 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5220 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5222 SLAB_ATTR_RO(aliases);
5224 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5226 return show_slab_objects(s, buf, SO_PARTIAL);
5228 SLAB_ATTR_RO(partial);
5230 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5232 return show_slab_objects(s, buf, SO_CPU);
5234 SLAB_ATTR_RO(cpu_slabs);
5236 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5238 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5240 SLAB_ATTR_RO(objects);
5242 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5244 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5246 SLAB_ATTR_RO(objects_partial);
5248 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5255 for_each_online_cpu(cpu) {
5258 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5261 pages += page->pages;
5262 objects += page->pobjects;
5266 len = sprintf(buf, "%d(%d)", objects, pages);
5269 for_each_online_cpu(cpu) {
5272 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5274 if (page && len < PAGE_SIZE - 20)
5275 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
5276 page->pobjects, page->pages);
5279 return len + sprintf(buf + len, "\n");
5281 SLAB_ATTR_RO(slabs_cpu_partial);
5283 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5285 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5287 SLAB_ATTR_RO(reclaim_account);
5289 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5291 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5293 SLAB_ATTR_RO(hwcache_align);
5295 #ifdef CONFIG_ZONE_DMA
5296 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5298 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5300 SLAB_ATTR_RO(cache_dma);
5303 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5305 return sprintf(buf, "%u\n", s->usersize);
5307 SLAB_ATTR_RO(usersize);
5309 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5311 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5313 SLAB_ATTR_RO(destroy_by_rcu);
5315 #ifdef CONFIG_SLUB_DEBUG
5316 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5318 return show_slab_objects(s, buf, SO_ALL);
5320 SLAB_ATTR_RO(slabs);
5322 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5324 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5326 SLAB_ATTR_RO(total_objects);
5328 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5330 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5332 SLAB_ATTR_RO(sanity_checks);
5334 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5336 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5338 SLAB_ATTR_RO(trace);
5340 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5342 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5345 SLAB_ATTR_RO(red_zone);
5347 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5349 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5352 SLAB_ATTR_RO(poison);
5354 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5356 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5359 SLAB_ATTR_RO(store_user);
5361 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5366 static ssize_t validate_store(struct kmem_cache *s,
5367 const char *buf, size_t length)
5371 if (buf[0] == '1') {
5372 ret = validate_slab_cache(s);
5378 SLAB_ATTR(validate);
5380 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5382 if (!(s->flags & SLAB_STORE_USER))
5384 return list_locations(s, buf, TRACK_ALLOC);
5386 SLAB_ATTR_RO(alloc_calls);
5388 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5390 if (!(s->flags & SLAB_STORE_USER))
5392 return list_locations(s, buf, TRACK_FREE);
5394 SLAB_ATTR_RO(free_calls);
5395 #endif /* CONFIG_SLUB_DEBUG */
5397 #ifdef CONFIG_FAILSLAB
5398 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5400 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5402 SLAB_ATTR_RO(failslab);
5405 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5410 static ssize_t shrink_store(struct kmem_cache *s,
5411 const char *buf, size_t length)
5414 kmem_cache_shrink(s);
5422 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5424 return sprintf(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5427 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5428 const char *buf, size_t length)
5433 err = kstrtouint(buf, 10, &ratio);
5439 s->remote_node_defrag_ratio = ratio * 10;
5443 SLAB_ATTR(remote_node_defrag_ratio);
5446 #ifdef CONFIG_SLUB_STATS
5447 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5449 unsigned long sum = 0;
5452 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5457 for_each_online_cpu(cpu) {
5458 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5464 len = sprintf(buf, "%lu", sum);
5467 for_each_online_cpu(cpu) {
5468 if (data[cpu] && len < PAGE_SIZE - 20)
5469 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5473 return len + sprintf(buf + len, "\n");
5476 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5480 for_each_online_cpu(cpu)
5481 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5484 #define STAT_ATTR(si, text) \
5485 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5487 return show_stat(s, buf, si); \
5489 static ssize_t text##_store(struct kmem_cache *s, \
5490 const char *buf, size_t length) \
5492 if (buf[0] != '0') \
5494 clear_stat(s, si); \
5499 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5500 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5501 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5502 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5503 STAT_ATTR(FREE_FROZEN, free_frozen);
5504 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5505 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5506 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5507 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5508 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5509 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5510 STAT_ATTR(FREE_SLAB, free_slab);
5511 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5512 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5513 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5514 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5515 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5516 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5517 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5518 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5519 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5520 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5521 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5522 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5523 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5524 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5525 #endif /* CONFIG_SLUB_STATS */
5527 static struct attribute *slab_attrs[] = {
5528 &slab_size_attr.attr,
5529 &object_size_attr.attr,
5530 &objs_per_slab_attr.attr,
5532 &min_partial_attr.attr,
5533 &cpu_partial_attr.attr,
5535 &objects_partial_attr.attr,
5537 &cpu_slabs_attr.attr,
5541 &hwcache_align_attr.attr,
5542 &reclaim_account_attr.attr,
5543 &destroy_by_rcu_attr.attr,
5545 &slabs_cpu_partial_attr.attr,
5546 #ifdef CONFIG_SLUB_DEBUG
5547 &total_objects_attr.attr,
5549 &sanity_checks_attr.attr,
5551 &red_zone_attr.attr,
5553 &store_user_attr.attr,
5554 &validate_attr.attr,
5555 &alloc_calls_attr.attr,
5556 &free_calls_attr.attr,
5558 #ifdef CONFIG_ZONE_DMA
5559 &cache_dma_attr.attr,
5562 &remote_node_defrag_ratio_attr.attr,
5564 #ifdef CONFIG_SLUB_STATS
5565 &alloc_fastpath_attr.attr,
5566 &alloc_slowpath_attr.attr,
5567 &free_fastpath_attr.attr,
5568 &free_slowpath_attr.attr,
5569 &free_frozen_attr.attr,
5570 &free_add_partial_attr.attr,
5571 &free_remove_partial_attr.attr,
5572 &alloc_from_partial_attr.attr,
5573 &alloc_slab_attr.attr,
5574 &alloc_refill_attr.attr,
5575 &alloc_node_mismatch_attr.attr,
5576 &free_slab_attr.attr,
5577 &cpuslab_flush_attr.attr,
5578 &deactivate_full_attr.attr,
5579 &deactivate_empty_attr.attr,
5580 &deactivate_to_head_attr.attr,
5581 &deactivate_to_tail_attr.attr,
5582 &deactivate_remote_frees_attr.attr,
5583 &deactivate_bypass_attr.attr,
5584 &order_fallback_attr.attr,
5585 &cmpxchg_double_fail_attr.attr,
5586 &cmpxchg_double_cpu_fail_attr.attr,
5587 &cpu_partial_alloc_attr.attr,
5588 &cpu_partial_free_attr.attr,
5589 &cpu_partial_node_attr.attr,
5590 &cpu_partial_drain_attr.attr,
5592 #ifdef CONFIG_FAILSLAB
5593 &failslab_attr.attr,
5595 &usersize_attr.attr,
5600 static const struct attribute_group slab_attr_group = {
5601 .attrs = slab_attrs,
5604 static ssize_t slab_attr_show(struct kobject *kobj,
5605 struct attribute *attr,
5608 struct slab_attribute *attribute;
5609 struct kmem_cache *s;
5612 attribute = to_slab_attr(attr);
5615 if (!attribute->show)
5618 err = attribute->show(s, buf);
5623 static ssize_t slab_attr_store(struct kobject *kobj,
5624 struct attribute *attr,
5625 const char *buf, size_t len)
5627 struct slab_attribute *attribute;
5628 struct kmem_cache *s;
5631 attribute = to_slab_attr(attr);
5634 if (!attribute->store)
5637 err = attribute->store(s, buf, len);
5641 static void kmem_cache_release(struct kobject *k)
5643 slab_kmem_cache_release(to_slab(k));
5646 static const struct sysfs_ops slab_sysfs_ops = {
5647 .show = slab_attr_show,
5648 .store = slab_attr_store,
5651 static struct kobj_type slab_ktype = {
5652 .sysfs_ops = &slab_sysfs_ops,
5653 .release = kmem_cache_release,
5656 static struct kset *slab_kset;
5658 static inline struct kset *cache_kset(struct kmem_cache *s)
5663 #define ID_STR_LENGTH 64
5665 /* Create a unique string id for a slab cache:
5667 * Format :[flags-]size
5669 static char *create_unique_id(struct kmem_cache *s)
5671 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5678 * First flags affecting slabcache operations. We will only
5679 * get here for aliasable slabs so we do not need to support
5680 * too many flags. The flags here must cover all flags that
5681 * are matched during merging to guarantee that the id is
5684 if (s->flags & SLAB_CACHE_DMA)
5686 if (s->flags & SLAB_CACHE_DMA32)
5688 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5690 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5692 if (s->flags & SLAB_ACCOUNT)
5696 p += sprintf(p, "%07u", s->size);
5698 BUG_ON(p > name + ID_STR_LENGTH - 1);
5702 static int sysfs_slab_add(struct kmem_cache *s)
5706 struct kset *kset = cache_kset(s);
5707 int unmergeable = slab_unmergeable(s);
5710 kobject_init(&s->kobj, &slab_ktype);
5714 if (!unmergeable && disable_higher_order_debug &&
5715 (slub_debug & DEBUG_METADATA_FLAGS))
5720 * Slabcache can never be merged so we can use the name proper.
5721 * This is typically the case for debug situations. In that
5722 * case we can catch duplicate names easily.
5724 sysfs_remove_link(&slab_kset->kobj, s->name);
5728 * Create a unique name for the slab as a target
5731 name = create_unique_id(s);
5734 s->kobj.kset = kset;
5735 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5739 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5744 /* Setup first alias */
5745 sysfs_slab_alias(s, s->name);
5752 kobject_del(&s->kobj);
5756 void sysfs_slab_unlink(struct kmem_cache *s)
5758 if (slab_state >= FULL)
5759 kobject_del(&s->kobj);
5762 void sysfs_slab_release(struct kmem_cache *s)
5764 if (slab_state >= FULL)
5765 kobject_put(&s->kobj);
5769 * Need to buffer aliases during bootup until sysfs becomes
5770 * available lest we lose that information.
5772 struct saved_alias {
5773 struct kmem_cache *s;
5775 struct saved_alias *next;
5778 static struct saved_alias *alias_list;
5780 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5782 struct saved_alias *al;
5784 if (slab_state == FULL) {
5786 * If we have a leftover link then remove it.
5788 sysfs_remove_link(&slab_kset->kobj, name);
5789 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5792 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5798 al->next = alias_list;
5803 static int __init slab_sysfs_init(void)
5805 struct kmem_cache *s;
5808 mutex_lock(&slab_mutex);
5810 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
5812 mutex_unlock(&slab_mutex);
5813 pr_err("Cannot register slab subsystem.\n");
5819 list_for_each_entry(s, &slab_caches, list) {
5820 err = sysfs_slab_add(s);
5822 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5826 while (alias_list) {
5827 struct saved_alias *al = alias_list;
5829 alias_list = alias_list->next;
5830 err = sysfs_slab_alias(al->s, al->name);
5832 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5837 mutex_unlock(&slab_mutex);
5842 __initcall(slab_sysfs_init);
5843 #endif /* CONFIG_SYSFS */
5846 * The /proc/slabinfo ABI
5848 #ifdef CONFIG_SLUB_DEBUG
5849 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5851 unsigned long nr_slabs = 0;
5852 unsigned long nr_objs = 0;
5853 unsigned long nr_free = 0;
5855 struct kmem_cache_node *n;
5857 for_each_kmem_cache_node(s, node, n) {
5858 nr_slabs += node_nr_slabs(n);
5859 nr_objs += node_nr_objs(n);
5860 nr_free += count_partial(n, count_free);
5863 sinfo->active_objs = nr_objs - nr_free;
5864 sinfo->num_objs = nr_objs;
5865 sinfo->active_slabs = nr_slabs;
5866 sinfo->num_slabs = nr_slabs;
5867 sinfo->objects_per_slab = oo_objects(s->oo);
5868 sinfo->cache_order = oo_order(s->oo);
5871 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5875 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5876 size_t count, loff_t *ppos)
5880 #endif /* CONFIG_SLUB_DEBUG */