2 * SLUB: A slab allocator that limits cache line use instead of queuing
3 * objects in per cpu and per node lists.
5 * The allocator synchronizes using per slab locks or atomic operatios
6 * and only uses a centralized lock to manage a pool of partial slabs.
8 * (C) 2007 SGI, Christoph Lameter
9 * (C) 2011 Linux Foundation, Christoph Lameter
13 #include <linux/swap.h> /* struct reclaim_state */
14 #include <linux/module.h>
15 #include <linux/bit_spinlock.h>
16 #include <linux/interrupt.h>
17 #include <linux/bitops.h>
18 #include <linux/slab.h>
20 #include <linux/proc_fs.h>
21 #include <linux/notifier.h>
22 #include <linux/seq_file.h>
23 #include <linux/kasan.h>
24 #include <linux/kmemcheck.h>
25 #include <linux/cpu.h>
26 #include <linux/cpuset.h>
27 #include <linux/mempolicy.h>
28 #include <linux/ctype.h>
29 #include <linux/debugobjects.h>
30 #include <linux/kallsyms.h>
31 #include <linux/memory.h>
32 #include <linux/math64.h>
33 #include <linux/fault-inject.h>
34 #include <linux/stacktrace.h>
35 #include <linux/prefetch.h>
36 #include <linux/memcontrol.h>
38 #include <trace/events/kmem.h>
44 * 1. slab_mutex (Global Mutex)
46 * 3. slab_lock(page) (Only on some arches and for debugging)
50 * The role of the slab_mutex is to protect the list of all the slabs
51 * and to synchronize major metadata changes to slab cache structures.
53 * The slab_lock is only used for debugging and on arches that do not
54 * have the ability to do a cmpxchg_double. It only protects the second
55 * double word in the page struct. Meaning
56 * A. page->freelist -> List of object free in a page
57 * B. page->counters -> Counters of objects
58 * C. page->frozen -> frozen state
60 * If a slab is frozen then it is exempt from list management. It is not
61 * on any list. The processor that froze the slab is the one who can
62 * perform list operations on the page. Other processors may put objects
63 * onto the freelist but the processor that froze the slab is the only
64 * one that can retrieve the objects from the page's freelist.
66 * The list_lock protects the partial and full list on each node and
67 * the partial slab counter. If taken then no new slabs may be added or
68 * removed from the lists nor make the number of partial slabs be modified.
69 * (Note that the total number of slabs is an atomic value that may be
70 * modified without taking the list lock).
72 * The list_lock is a centralized lock and thus we avoid taking it as
73 * much as possible. As long as SLUB does not have to handle partial
74 * slabs, operations can continue without any centralized lock. F.e.
75 * allocating a long series of objects that fill up slabs does not require
77 * Interrupts are disabled during allocation and deallocation in order to
78 * make the slab allocator safe to use in the context of an irq. In addition
79 * interrupts are disabled to ensure that the processor does not change
80 * while handling per_cpu slabs, due to kernel preemption.
82 * SLUB assigns one slab for allocation to each processor.
83 * Allocations only occur from these slabs called cpu slabs.
85 * Slabs with free elements are kept on a partial list and during regular
86 * operations no list for full slabs is used. If an object in a full slab is
87 * freed then the slab will show up again on the partial lists.
88 * We track full slabs for debugging purposes though because otherwise we
89 * cannot scan all objects.
91 * Slabs are freed when they become empty. Teardown and setup is
92 * minimal so we rely on the page allocators per cpu caches for
93 * fast frees and allocs.
95 * Overloading of page flags that are otherwise used for LRU management.
97 * PageActive The slab is frozen and exempt from list processing.
98 * This means that the slab is dedicated to a purpose
99 * such as satisfying allocations for a specific
100 * processor. Objects may be freed in the slab while
101 * it is frozen but slab_free will then skip the usual
102 * list operations. It is up to the processor holding
103 * the slab to integrate the slab into the slab lists
104 * when the slab is no longer needed.
106 * One use of this flag is to mark slabs that are
107 * used for allocations. Then such a slab becomes a cpu
108 * slab. The cpu slab may be equipped with an additional
109 * freelist that allows lockless access to
110 * free objects in addition to the regular freelist
111 * that requires the slab lock.
113 * PageError Slab requires special handling due to debug
114 * options set. This moves slab handling out of
115 * the fast path and disables lockless freelists.
118 static inline int kmem_cache_debug(struct kmem_cache *s)
120 #ifdef CONFIG_SLUB_DEBUG
121 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
127 static inline void *fixup_red_left(struct kmem_cache *s, void *p)
129 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE)
130 p += s->red_left_pad;
135 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
137 #ifdef CONFIG_SLUB_CPU_PARTIAL
138 return !kmem_cache_debug(s);
145 * Issues still to be resolved:
147 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
149 * - Variable sizing of the per node arrays
152 /* Enable to test recovery from slab corruption on boot */
153 #undef SLUB_RESILIENCY_TEST
155 /* Enable to log cmpxchg failures */
156 #undef SLUB_DEBUG_CMPXCHG
159 * Mininum number of partial slabs. These will be left on the partial
160 * lists even if they are empty. kmem_cache_shrink may reclaim them.
162 #define MIN_PARTIAL 5
165 * Maximum number of desirable partial slabs.
166 * The existence of more partial slabs makes kmem_cache_shrink
167 * sort the partial list by the number of objects in use.
169 #define MAX_PARTIAL 10
171 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
172 SLAB_POISON | SLAB_STORE_USER)
175 * Debugging flags that require metadata to be stored in the slab. These get
176 * disabled when slub_debug=O is used and a cache's min order increases with
179 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
182 #define OO_MASK ((1 << OO_SHIFT) - 1)
183 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
185 /* Internal SLUB flags */
186 #define __OBJECT_POISON 0x80000000UL /* Poison object */
187 #define __CMPXCHG_DOUBLE 0x40000000UL /* Use cmpxchg_double */
190 static struct notifier_block slab_notifier;
194 * Tracking user of a slab.
196 #define TRACK_ADDRS_COUNT 16
198 unsigned long addr; /* Called from address */
199 #ifdef CONFIG_STACKTRACE
200 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
202 int cpu; /* Was running on cpu */
203 int pid; /* Pid context */
204 unsigned long when; /* When did the operation occur */
207 enum track_item { TRACK_ALLOC, TRACK_FREE };
210 static int sysfs_slab_add(struct kmem_cache *);
211 static int sysfs_slab_alias(struct kmem_cache *, const char *);
212 static void memcg_propagate_slab_attrs(struct kmem_cache *s);
214 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
215 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
217 static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { }
220 static inline void stat(const struct kmem_cache *s, enum stat_item si)
222 #ifdef CONFIG_SLUB_STATS
224 * The rmw is racy on a preemptible kernel but this is acceptable, so
225 * avoid this_cpu_add()'s irq-disable overhead.
227 raw_cpu_inc(s->cpu_slab->stat[si]);
231 /********************************************************************
232 * Core slab cache functions
233 *******************************************************************/
235 static inline void *get_freepointer(struct kmem_cache *s, void *object)
237 return *(void **)(object + s->offset);
240 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
242 prefetch(object + s->offset);
245 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
249 #ifdef CONFIG_DEBUG_PAGEALLOC
250 probe_kernel_read(&p, (void **)(object + s->offset), sizeof(p));
252 p = get_freepointer(s, object);
257 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
259 *(void **)(object + s->offset) = fp;
262 /* Loop over all objects in a slab */
263 #define for_each_object(__p, __s, __addr, __objects) \
264 for (__p = fixup_red_left(__s, __addr); \
265 __p < (__addr) + (__objects) * (__s)->size; \
268 #define for_each_object_idx(__p, __idx, __s, __addr, __objects) \
269 for (__p = fixup_red_left(__s, __addr), __idx = 1; \
270 __idx <= __objects; \
271 __p += (__s)->size, __idx++)
273 /* Determine object index from a given position */
274 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
276 return (p - addr) / s->size;
279 static inline size_t slab_ksize(const struct kmem_cache *s)
281 #ifdef CONFIG_SLUB_DEBUG
283 * Debugging requires use of the padding between object
284 * and whatever may come after it.
286 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
287 return s->object_size;
291 * If we have the need to store the freelist pointer
292 * back there or track user information then we can
293 * only use the space before that information.
295 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
298 * Else we can use all the padding etc for the allocation
303 static inline int order_objects(int order, unsigned long size, int reserved)
305 return ((PAGE_SIZE << order) - reserved) / size;
308 static inline struct kmem_cache_order_objects oo_make(int order,
309 unsigned long size, int reserved)
311 struct kmem_cache_order_objects x = {
312 (order << OO_SHIFT) + order_objects(order, size, reserved)
318 static inline int oo_order(struct kmem_cache_order_objects x)
320 return x.x >> OO_SHIFT;
323 static inline int oo_objects(struct kmem_cache_order_objects x)
325 return x.x & OO_MASK;
329 * Per slab locking using the pagelock
331 static __always_inline void slab_lock(struct page *page)
333 bit_spin_lock(PG_locked, &page->flags);
336 static __always_inline void slab_unlock(struct page *page)
338 __bit_spin_unlock(PG_locked, &page->flags);
341 static inline void set_page_slub_counters(struct page *page, unsigned long counters_new)
344 tmp.counters = counters_new;
346 * page->counters can cover frozen/inuse/objects as well
347 * as page->_count. If we assign to ->counters directly
348 * we run the risk of losing updates to page->_count, so
349 * be careful and only assign to the fields we need.
351 page->frozen = tmp.frozen;
352 page->inuse = tmp.inuse;
353 page->objects = tmp.objects;
356 /* Interrupts must be disabled (for the fallback code to work right) */
357 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
358 void *freelist_old, unsigned long counters_old,
359 void *freelist_new, unsigned long counters_new,
362 VM_BUG_ON(!irqs_disabled());
363 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
364 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
365 if (s->flags & __CMPXCHG_DOUBLE) {
366 if (cmpxchg_double(&page->freelist, &page->counters,
367 freelist_old, counters_old,
368 freelist_new, counters_new))
374 if (page->freelist == freelist_old &&
375 page->counters == counters_old) {
376 page->freelist = freelist_new;
377 set_page_slub_counters(page, counters_new);
385 stat(s, CMPXCHG_DOUBLE_FAIL);
387 #ifdef SLUB_DEBUG_CMPXCHG
388 pr_info("%s %s: cmpxchg double redo ", n, s->name);
394 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
395 void *freelist_old, unsigned long counters_old,
396 void *freelist_new, unsigned long counters_new,
399 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
400 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
401 if (s->flags & __CMPXCHG_DOUBLE) {
402 if (cmpxchg_double(&page->freelist, &page->counters,
403 freelist_old, counters_old,
404 freelist_new, counters_new))
411 local_irq_save(flags);
413 if (page->freelist == freelist_old &&
414 page->counters == counters_old) {
415 page->freelist = freelist_new;
416 set_page_slub_counters(page, counters_new);
418 local_irq_restore(flags);
422 local_irq_restore(flags);
426 stat(s, CMPXCHG_DOUBLE_FAIL);
428 #ifdef SLUB_DEBUG_CMPXCHG
429 pr_info("%s %s: cmpxchg double redo ", n, s->name);
435 #ifdef CONFIG_SLUB_DEBUG
437 * Determine a map of object in use on a page.
439 * Node listlock must be held to guarantee that the page does
440 * not vanish from under us.
442 static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
445 void *addr = page_address(page);
447 for (p = page->freelist; p; p = get_freepointer(s, p))
448 set_bit(slab_index(p, s, addr), map);
451 static inline int size_from_object(struct kmem_cache *s)
453 if (s->flags & SLAB_RED_ZONE)
454 return s->size - s->red_left_pad;
459 static inline void *restore_red_left(struct kmem_cache *s, void *p)
461 if (s->flags & SLAB_RED_ZONE)
462 p -= s->red_left_pad;
470 #if defined(CONFIG_SLUB_DEBUG_ON)
471 static int slub_debug = DEBUG_DEFAULT_FLAGS;
472 #elif defined(CONFIG_KASAN)
473 static int slub_debug = SLAB_STORE_USER;
475 static int slub_debug;
478 static char *slub_debug_slabs;
479 static int disable_higher_order_debug;
482 * slub is about to manipulate internal object metadata. This memory lies
483 * outside the range of the allocated object, so accessing it would normally
484 * be reported by kasan as a bounds error. metadata_access_enable() is used
485 * to tell kasan that these accesses are OK.
487 static inline void metadata_access_enable(void)
489 kasan_disable_current();
492 static inline void metadata_access_disable(void)
494 kasan_enable_current();
501 /* Verify that a pointer has an address that is valid within a slab page */
502 static inline int check_valid_pointer(struct kmem_cache *s,
503 struct page *page, void *object)
510 base = page_address(page);
511 object = restore_red_left(s, object);
512 if (object < base || object >= base + page->objects * s->size ||
513 (object - base) % s->size) {
520 static void print_section(char *text, u8 *addr, unsigned int length)
522 metadata_access_enable();
523 print_hex_dump(KERN_ERR, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
525 metadata_access_disable();
528 static struct track *get_track(struct kmem_cache *s, void *object,
529 enum track_item alloc)
534 p = object + s->offset + sizeof(void *);
536 p = object + s->inuse;
541 static void set_track(struct kmem_cache *s, void *object,
542 enum track_item alloc, unsigned long addr)
544 struct track *p = get_track(s, object, alloc);
547 #ifdef CONFIG_STACKTRACE
548 struct stack_trace trace;
551 trace.nr_entries = 0;
552 trace.max_entries = TRACK_ADDRS_COUNT;
553 trace.entries = p->addrs;
555 metadata_access_enable();
556 save_stack_trace(&trace);
557 metadata_access_disable();
559 /* See rant in lockdep.c */
560 if (trace.nr_entries != 0 &&
561 trace.entries[trace.nr_entries - 1] == ULONG_MAX)
564 for (i = trace.nr_entries; i < TRACK_ADDRS_COUNT; i++)
568 p->cpu = smp_processor_id();
569 p->pid = current->pid;
572 memset(p, 0, sizeof(struct track));
575 static void init_tracking(struct kmem_cache *s, void *object)
577 if (!(s->flags & SLAB_STORE_USER))
580 set_track(s, object, TRACK_FREE, 0UL);
581 set_track(s, object, TRACK_ALLOC, 0UL);
584 static void print_track(const char *s, struct track *t)
589 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
590 s, (void *)t->addr, jiffies - t->when, t->cpu, t->pid);
591 #ifdef CONFIG_STACKTRACE
594 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
596 pr_err("\t%pS\n", (void *)t->addrs[i]);
603 static void print_tracking(struct kmem_cache *s, void *object)
605 if (!(s->flags & SLAB_STORE_USER))
608 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
609 print_track("Freed", get_track(s, object, TRACK_FREE));
612 static void print_page_info(struct page *page)
614 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
615 page, page->objects, page->inuse, page->freelist, page->flags);
619 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
621 struct va_format vaf;
627 pr_err("=============================================================================\n");
628 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
629 pr_err("-----------------------------------------------------------------------------\n\n");
631 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
635 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
637 struct va_format vaf;
643 pr_err("FIX %s: %pV\n", s->name, &vaf);
647 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
649 unsigned int off; /* Offset of last byte */
650 u8 *addr = page_address(page);
652 print_tracking(s, p);
654 print_page_info(page);
656 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
657 p, p - addr, get_freepointer(s, p));
659 if (s->flags & SLAB_RED_ZONE)
660 print_section("Redzone ", p - s->red_left_pad, s->red_left_pad);
661 else if (p > addr + 16)
662 print_section("Bytes b4 ", p - 16, 16);
664 print_section("Object ", p, min_t(unsigned long, s->object_size,
666 if (s->flags & SLAB_RED_ZONE)
667 print_section("Redzone ", p + s->object_size,
668 s->inuse - s->object_size);
671 off = s->offset + sizeof(void *);
675 if (s->flags & SLAB_STORE_USER)
676 off += 2 * sizeof(struct track);
678 if (off != size_from_object(s))
679 /* Beginning of the filler is the free pointer */
680 print_section("Padding ", p + off, size_from_object(s) - off);
685 void object_err(struct kmem_cache *s, struct page *page,
686 u8 *object, char *reason)
688 slab_bug(s, "%s", reason);
689 print_trailer(s, page, object);
692 static void slab_err(struct kmem_cache *s, struct page *page,
693 const char *fmt, ...)
699 vsnprintf(buf, sizeof(buf), fmt, args);
701 slab_bug(s, "%s", buf);
702 print_page_info(page);
706 static void init_object(struct kmem_cache *s, void *object, u8 val)
710 if (s->flags & SLAB_RED_ZONE)
711 memset(p - s->red_left_pad, val, s->red_left_pad);
713 if (s->flags & __OBJECT_POISON) {
714 memset(p, POISON_FREE, s->object_size - 1);
715 p[s->object_size - 1] = POISON_END;
718 if (s->flags & SLAB_RED_ZONE)
719 memset(p + s->object_size, val, s->inuse - s->object_size);
722 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
723 void *from, void *to)
725 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
726 memset(from, data, to - from);
729 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
730 u8 *object, char *what,
731 u8 *start, unsigned int value, unsigned int bytes)
736 metadata_access_enable();
737 fault = memchr_inv(start, value, bytes);
738 metadata_access_disable();
743 while (end > fault && end[-1] == value)
746 slab_bug(s, "%s overwritten", what);
747 pr_err("INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
748 fault, end - 1, fault[0], value);
749 print_trailer(s, page, object);
751 restore_bytes(s, what, value, fault, end);
759 * Bytes of the object to be managed.
760 * If the freepointer may overlay the object then the free
761 * pointer is the first word of the object.
763 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
766 * object + s->object_size
767 * Padding to reach word boundary. This is also used for Redzoning.
768 * Padding is extended by another word if Redzoning is enabled and
769 * object_size == inuse.
771 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
772 * 0xcc (RED_ACTIVE) for objects in use.
775 * Meta data starts here.
777 * A. Free pointer (if we cannot overwrite object on free)
778 * B. Tracking data for SLAB_STORE_USER
779 * C. Padding to reach required alignment boundary or at mininum
780 * one word if debugging is on to be able to detect writes
781 * before the word boundary.
783 * Padding is done using 0x5a (POISON_INUSE)
786 * Nothing is used beyond s->size.
788 * If slabcaches are merged then the object_size and inuse boundaries are mostly
789 * ignored. And therefore no slab options that rely on these boundaries
790 * may be used with merged slabcaches.
793 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
795 unsigned long off = s->inuse; /* The end of info */
798 /* Freepointer is placed after the object. */
799 off += sizeof(void *);
801 if (s->flags & SLAB_STORE_USER)
802 /* We also have user information there */
803 off += 2 * sizeof(struct track);
805 if (size_from_object(s) == off)
808 return check_bytes_and_report(s, page, p, "Object padding",
809 p + off, POISON_INUSE, size_from_object(s) - off);
812 /* Check the pad bytes at the end of a slab page */
813 static int slab_pad_check(struct kmem_cache *s, struct page *page)
821 if (!(s->flags & SLAB_POISON))
824 start = page_address(page);
825 length = (PAGE_SIZE << compound_order(page)) - s->reserved;
826 end = start + length;
827 remainder = length % s->size;
831 metadata_access_enable();
832 fault = memchr_inv(end - remainder, POISON_INUSE, remainder);
833 metadata_access_disable();
836 while (end > fault && end[-1] == POISON_INUSE)
839 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
840 print_section("Padding ", end - remainder, remainder);
842 restore_bytes(s, "slab padding", POISON_INUSE, end - remainder, end);
846 static int check_object(struct kmem_cache *s, struct page *page,
847 void *object, u8 val)
850 u8 *endobject = object + s->object_size;
852 if (s->flags & SLAB_RED_ZONE) {
853 if (!check_bytes_and_report(s, page, object, "Redzone",
854 object - s->red_left_pad, val, s->red_left_pad))
857 if (!check_bytes_and_report(s, page, object, "Redzone",
858 endobject, val, s->inuse - s->object_size))
861 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
862 check_bytes_and_report(s, page, p, "Alignment padding",
863 endobject, POISON_INUSE,
864 s->inuse - s->object_size);
868 if (s->flags & SLAB_POISON) {
869 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
870 (!check_bytes_and_report(s, page, p, "Poison", p,
871 POISON_FREE, s->object_size - 1) ||
872 !check_bytes_and_report(s, page, p, "Poison",
873 p + s->object_size - 1, POISON_END, 1)))
876 * check_pad_bytes cleans up on its own.
878 check_pad_bytes(s, page, p);
881 if (!s->offset && val == SLUB_RED_ACTIVE)
883 * Object and freepointer overlap. Cannot check
884 * freepointer while object is allocated.
888 /* Check free pointer validity */
889 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
890 object_err(s, page, p, "Freepointer corrupt");
892 * No choice but to zap it and thus lose the remainder
893 * of the free objects in this slab. May cause
894 * another error because the object count is now wrong.
896 set_freepointer(s, p, NULL);
902 static int check_slab(struct kmem_cache *s, struct page *page)
906 VM_BUG_ON(!irqs_disabled());
908 if (!PageSlab(page)) {
909 slab_err(s, page, "Not a valid slab page");
913 maxobj = order_objects(compound_order(page), s->size, s->reserved);
914 if (page->objects > maxobj) {
915 slab_err(s, page, "objects %u > max %u",
916 page->objects, maxobj);
919 if (page->inuse > page->objects) {
920 slab_err(s, page, "inuse %u > max %u",
921 page->inuse, page->objects);
924 /* Slab_pad_check fixes things up after itself */
925 slab_pad_check(s, page);
930 * Determine if a certain object on a page is on the freelist. Must hold the
931 * slab lock to guarantee that the chains are in a consistent state.
933 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
941 while (fp && nr <= page->objects) {
944 if (!check_valid_pointer(s, page, fp)) {
946 object_err(s, page, object,
947 "Freechain corrupt");
948 set_freepointer(s, object, NULL);
950 slab_err(s, page, "Freepointer corrupt");
951 page->freelist = NULL;
952 page->inuse = page->objects;
953 slab_fix(s, "Freelist cleared");
959 fp = get_freepointer(s, object);
963 max_objects = order_objects(compound_order(page), s->size, s->reserved);
964 if (max_objects > MAX_OBJS_PER_PAGE)
965 max_objects = MAX_OBJS_PER_PAGE;
967 if (page->objects != max_objects) {
968 slab_err(s, page, "Wrong number of objects. Found %d but "
969 "should be %d", page->objects, max_objects);
970 page->objects = max_objects;
971 slab_fix(s, "Number of objects adjusted.");
973 if (page->inuse != page->objects - nr) {
974 slab_err(s, page, "Wrong object count. Counter is %d but "
975 "counted were %d", page->inuse, page->objects - nr);
976 page->inuse = page->objects - nr;
977 slab_fix(s, "Object count adjusted.");
979 return search == NULL;
982 static void trace(struct kmem_cache *s, struct page *page, void *object,
985 if (s->flags & SLAB_TRACE) {
986 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
988 alloc ? "alloc" : "free",
993 print_section("Object ", (void *)object,
1001 * Tracking of fully allocated slabs for debugging purposes.
1003 static void add_full(struct kmem_cache *s,
1004 struct kmem_cache_node *n, struct page *page)
1006 if (!(s->flags & SLAB_STORE_USER))
1009 lockdep_assert_held(&n->list_lock);
1010 list_add(&page->lru, &n->full);
1013 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1015 if (!(s->flags & SLAB_STORE_USER))
1018 lockdep_assert_held(&n->list_lock);
1019 list_del(&page->lru);
1022 /* Tracking of the number of slabs for debugging purposes */
1023 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1025 struct kmem_cache_node *n = get_node(s, node);
1027 return atomic_long_read(&n->nr_slabs);
1030 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1032 return atomic_long_read(&n->nr_slabs);
1035 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1037 struct kmem_cache_node *n = get_node(s, node);
1040 * May be called early in order to allocate a slab for the
1041 * kmem_cache_node structure. Solve the chicken-egg
1042 * dilemma by deferring the increment of the count during
1043 * bootstrap (see early_kmem_cache_node_alloc).
1046 atomic_long_inc(&n->nr_slabs);
1047 atomic_long_add(objects, &n->total_objects);
1050 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1052 struct kmem_cache_node *n = get_node(s, node);
1054 atomic_long_dec(&n->nr_slabs);
1055 atomic_long_sub(objects, &n->total_objects);
1058 /* Object debug checks for alloc/free paths */
1059 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1062 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1065 init_object(s, object, SLUB_RED_INACTIVE);
1066 init_tracking(s, object);
1069 static noinline int alloc_debug_processing(struct kmem_cache *s,
1071 void *object, unsigned long addr)
1073 if (!check_slab(s, page))
1076 if (!check_valid_pointer(s, page, object)) {
1077 object_err(s, page, object, "Freelist Pointer check fails");
1081 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1084 /* Success perform special debug activities for allocs */
1085 if (s->flags & SLAB_STORE_USER)
1086 set_track(s, object, TRACK_ALLOC, addr);
1087 trace(s, page, object, 1);
1088 init_object(s, object, SLUB_RED_ACTIVE);
1092 if (PageSlab(page)) {
1094 * If this is a slab page then lets do the best we can
1095 * to avoid issues in the future. Marking all objects
1096 * as used avoids touching the remaining objects.
1098 slab_fix(s, "Marking all objects used");
1099 page->inuse = page->objects;
1100 page->freelist = NULL;
1105 /* Supports checking bulk free of a constructed freelist */
1106 static noinline struct kmem_cache_node *free_debug_processing(
1107 struct kmem_cache *s, struct page *page,
1108 void *head, void *tail, int bulk_cnt,
1109 unsigned long addr, unsigned long *flags)
1111 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1112 void *object = head;
1115 spin_lock_irqsave(&n->list_lock, *flags);
1118 if (!check_slab(s, page))
1124 if (!check_valid_pointer(s, page, object)) {
1125 slab_err(s, page, "Invalid object pointer 0x%p", object);
1129 if (on_freelist(s, page, object)) {
1130 object_err(s, page, object, "Object already free");
1134 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1137 if (unlikely(s != page->slab_cache)) {
1138 if (!PageSlab(page)) {
1139 slab_err(s, page, "Attempt to free object(0x%p) "
1140 "outside of slab", object);
1141 } else if (!page->slab_cache) {
1142 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1146 object_err(s, page, object,
1147 "page slab pointer corrupt.");
1151 if (s->flags & SLAB_STORE_USER)
1152 set_track(s, object, TRACK_FREE, addr);
1153 trace(s, page, object, 0);
1154 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1155 init_object(s, object, SLUB_RED_INACTIVE);
1157 /* Reached end of constructed freelist yet? */
1158 if (object != tail) {
1159 object = get_freepointer(s, object);
1163 if (cnt != bulk_cnt)
1164 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1169 * Keep node_lock to preserve integrity
1170 * until the object is actually freed
1176 spin_unlock_irqrestore(&n->list_lock, *flags);
1177 slab_fix(s, "Object at 0x%p not freed", object);
1181 static int __init setup_slub_debug(char *str)
1183 slub_debug = DEBUG_DEFAULT_FLAGS;
1184 if (*str++ != '=' || !*str)
1186 * No options specified. Switch on full debugging.
1192 * No options but restriction on slabs. This means full
1193 * debugging for slabs matching a pattern.
1200 * Switch off all debugging measures.
1205 * Determine which debug features should be switched on
1207 for (; *str && *str != ','; str++) {
1208 switch (tolower(*str)) {
1210 slub_debug |= SLAB_DEBUG_FREE;
1213 slub_debug |= SLAB_RED_ZONE;
1216 slub_debug |= SLAB_POISON;
1219 slub_debug |= SLAB_STORE_USER;
1222 slub_debug |= SLAB_TRACE;
1225 slub_debug |= SLAB_FAILSLAB;
1229 * Avoid enabling debugging on caches if its minimum
1230 * order would increase as a result.
1232 disable_higher_order_debug = 1;
1235 pr_err("slub_debug option '%c' unknown. skipped\n",
1242 slub_debug_slabs = str + 1;
1247 __setup("slub_debug", setup_slub_debug);
1249 unsigned long kmem_cache_flags(unsigned long object_size,
1250 unsigned long flags, const char *name,
1251 void (*ctor)(void *))
1254 * Enable debugging if selected on the kernel commandline.
1256 if (slub_debug && (!slub_debug_slabs || (name &&
1257 !strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs)))))
1258 flags |= slub_debug;
1262 #else /* !CONFIG_SLUB_DEBUG */
1263 static inline void setup_object_debug(struct kmem_cache *s,
1264 struct page *page, void *object) {}
1266 static inline int alloc_debug_processing(struct kmem_cache *s,
1267 struct page *page, void *object, unsigned long addr) { return 0; }
1269 static inline struct kmem_cache_node *free_debug_processing(
1270 struct kmem_cache *s, struct page *page,
1271 void *head, void *tail, int bulk_cnt,
1272 unsigned long addr, unsigned long *flags) { return NULL; }
1274 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1276 static inline int check_object(struct kmem_cache *s, struct page *page,
1277 void *object, u8 val) { return 1; }
1278 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1279 struct page *page) {}
1280 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1281 struct page *page) {}
1282 unsigned long kmem_cache_flags(unsigned long object_size,
1283 unsigned long flags, const char *name,
1284 void (*ctor)(void *))
1288 #define slub_debug 0
1290 #define disable_higher_order_debug 0
1292 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1294 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1296 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1298 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1301 #endif /* CONFIG_SLUB_DEBUG */
1304 * Hooks for other subsystems that check memory allocations. In a typical
1305 * production configuration these hooks all should produce no code at all.
1307 static inline void kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1309 kmemleak_alloc(ptr, size, 1, flags);
1310 kasan_kmalloc_large(ptr, size);
1313 static inline void kfree_hook(const void *x)
1316 kasan_kfree_large(x);
1319 static inline struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s,
1322 flags &= gfp_allowed_mask;
1323 lockdep_trace_alloc(flags);
1324 might_sleep_if(gfpflags_allow_blocking(flags));
1326 if (should_failslab(s->object_size, flags, s->flags))
1329 return memcg_kmem_get_cache(s, flags);
1332 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags,
1333 size_t size, void **p)
1337 flags &= gfp_allowed_mask;
1338 for (i = 0; i < size; i++) {
1339 void *object = p[i];
1341 kmemcheck_slab_alloc(s, flags, object, slab_ksize(s));
1342 kmemleak_alloc_recursive(object, s->object_size, 1,
1344 kasan_slab_alloc(s, object);
1346 memcg_kmem_put_cache(s);
1349 static inline void slab_free_hook(struct kmem_cache *s, void *x)
1351 kmemleak_free_recursive(x, s->flags);
1354 * Trouble is that we may no longer disable interrupts in the fast path
1355 * So in order to make the debug calls that expect irqs to be
1356 * disabled we need to disable interrupts temporarily.
1358 #if defined(CONFIG_KMEMCHECK) || defined(CONFIG_LOCKDEP)
1360 unsigned long flags;
1362 local_irq_save(flags);
1363 kmemcheck_slab_free(s, x, s->object_size);
1364 debug_check_no_locks_freed(x, s->object_size);
1365 local_irq_restore(flags);
1368 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1369 debug_check_no_obj_freed(x, s->object_size);
1371 kasan_slab_free(s, x);
1374 static inline void slab_free_freelist_hook(struct kmem_cache *s,
1375 void *head, void *tail)
1378 * Compiler cannot detect this function can be removed if slab_free_hook()
1379 * evaluates to nothing. Thus, catch all relevant config debug options here.
1381 #if defined(CONFIG_KMEMCHECK) || \
1382 defined(CONFIG_LOCKDEP) || \
1383 defined(CONFIG_DEBUG_KMEMLEAK) || \
1384 defined(CONFIG_DEBUG_OBJECTS_FREE) || \
1385 defined(CONFIG_KASAN)
1387 void *object = head;
1388 void *tail_obj = tail ? : head;
1391 slab_free_hook(s, object);
1392 } while ((object != tail_obj) &&
1393 (object = get_freepointer(s, object)));
1397 static void setup_object(struct kmem_cache *s, struct page *page,
1400 setup_object_debug(s, page, object);
1401 if (unlikely(s->ctor)) {
1402 kasan_unpoison_object_data(s, object);
1404 kasan_poison_object_data(s, object);
1409 * Slab allocation and freeing
1411 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1412 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1415 int order = oo_order(oo);
1417 flags |= __GFP_NOTRACK;
1419 if (node == NUMA_NO_NODE)
1420 page = alloc_pages(flags, order);
1422 page = __alloc_pages_node(node, flags, order);
1424 if (page && memcg_charge_slab(page, flags, order, s)) {
1425 __free_pages(page, order);
1432 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1435 struct kmem_cache_order_objects oo = s->oo;
1440 flags &= gfp_allowed_mask;
1442 if (gfpflags_allow_blocking(flags))
1445 flags |= s->allocflags;
1448 * Let the initial higher-order allocation fail under memory pressure
1449 * so we fall-back to the minimum order allocation.
1451 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1452 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1453 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_DIRECT_RECLAIM;
1455 page = alloc_slab_page(s, alloc_gfp, node, oo);
1456 if (unlikely(!page)) {
1460 * Allocation may have failed due to fragmentation.
1461 * Try a lower order alloc if possible
1463 page = alloc_slab_page(s, alloc_gfp, node, oo);
1464 if (unlikely(!page))
1466 stat(s, ORDER_FALLBACK);
1469 if (kmemcheck_enabled &&
1470 !(s->flags & (SLAB_NOTRACK | DEBUG_DEFAULT_FLAGS))) {
1471 int pages = 1 << oo_order(oo);
1473 kmemcheck_alloc_shadow(page, oo_order(oo), alloc_gfp, node);
1476 * Objects from caches that have a constructor don't get
1477 * cleared when they're allocated, so we need to do it here.
1480 kmemcheck_mark_uninitialized_pages(page, pages);
1482 kmemcheck_mark_unallocated_pages(page, pages);
1485 page->objects = oo_objects(oo);
1487 order = compound_order(page);
1488 page->slab_cache = s;
1489 __SetPageSlab(page);
1490 if (page_is_pfmemalloc(page))
1491 SetPageSlabPfmemalloc(page);
1493 start = page_address(page);
1495 if (unlikely(s->flags & SLAB_POISON))
1496 memset(start, POISON_INUSE, PAGE_SIZE << order);
1498 kasan_poison_slab(page);
1500 for_each_object_idx(p, idx, s, start, page->objects) {
1501 setup_object(s, page, p);
1502 if (likely(idx < page->objects))
1503 set_freepointer(s, p, p + s->size);
1505 set_freepointer(s, p, NULL);
1508 page->freelist = fixup_red_left(s, start);
1509 page->inuse = page->objects;
1513 if (gfpflags_allow_blocking(flags))
1514 local_irq_disable();
1518 mod_zone_page_state(page_zone(page),
1519 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1520 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1523 inc_slabs_node(s, page_to_nid(page), page->objects);
1528 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1530 if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
1531 pr_emerg("gfp: %u\n", flags & GFP_SLAB_BUG_MASK);
1535 return allocate_slab(s,
1536 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1539 static void __free_slab(struct kmem_cache *s, struct page *page)
1541 int order = compound_order(page);
1542 int pages = 1 << order;
1544 if (kmem_cache_debug(s)) {
1547 slab_pad_check(s, page);
1548 for_each_object(p, s, page_address(page),
1550 check_object(s, page, p, SLUB_RED_INACTIVE);
1553 kmemcheck_free_shadow(page, compound_order(page));
1555 mod_zone_page_state(page_zone(page),
1556 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1557 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1560 __ClearPageSlabPfmemalloc(page);
1561 __ClearPageSlab(page);
1563 page_mapcount_reset(page);
1564 if (current->reclaim_state)
1565 current->reclaim_state->reclaimed_slab += pages;
1566 __free_kmem_pages(page, order);
1569 #define need_reserve_slab_rcu \
1570 (sizeof(((struct page *)NULL)->lru) < sizeof(struct rcu_head))
1572 static void rcu_free_slab(struct rcu_head *h)
1576 if (need_reserve_slab_rcu)
1577 page = virt_to_head_page(h);
1579 page = container_of((struct list_head *)h, struct page, lru);
1581 __free_slab(page->slab_cache, page);
1584 static void free_slab(struct kmem_cache *s, struct page *page)
1586 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1587 struct rcu_head *head;
1589 if (need_reserve_slab_rcu) {
1590 int order = compound_order(page);
1591 int offset = (PAGE_SIZE << order) - s->reserved;
1593 VM_BUG_ON(s->reserved != sizeof(*head));
1594 head = page_address(page) + offset;
1596 head = &page->rcu_head;
1599 call_rcu(head, rcu_free_slab);
1601 __free_slab(s, page);
1604 static void discard_slab(struct kmem_cache *s, struct page *page)
1606 dec_slabs_node(s, page_to_nid(page), page->objects);
1611 * Management of partially allocated slabs.
1614 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1617 if (tail == DEACTIVATE_TO_TAIL)
1618 list_add_tail(&page->lru, &n->partial);
1620 list_add(&page->lru, &n->partial);
1623 static inline void add_partial(struct kmem_cache_node *n,
1624 struct page *page, int tail)
1626 lockdep_assert_held(&n->list_lock);
1627 __add_partial(n, page, tail);
1631 __remove_partial(struct kmem_cache_node *n, struct page *page)
1633 list_del(&page->lru);
1637 static inline void remove_partial(struct kmem_cache_node *n,
1640 lockdep_assert_held(&n->list_lock);
1641 __remove_partial(n, page);
1645 * Remove slab from the partial list, freeze it and
1646 * return the pointer to the freelist.
1648 * Returns a list of objects or NULL if it fails.
1650 static inline void *acquire_slab(struct kmem_cache *s,
1651 struct kmem_cache_node *n, struct page *page,
1652 int mode, int *objects)
1655 unsigned long counters;
1658 lockdep_assert_held(&n->list_lock);
1661 * Zap the freelist and set the frozen bit.
1662 * The old freelist is the list of objects for the
1663 * per cpu allocation list.
1665 freelist = page->freelist;
1666 counters = page->counters;
1667 new.counters = counters;
1668 *objects = new.objects - new.inuse;
1670 new.inuse = page->objects;
1671 new.freelist = NULL;
1673 new.freelist = freelist;
1676 VM_BUG_ON(new.frozen);
1679 if (!__cmpxchg_double_slab(s, page,
1681 new.freelist, new.counters,
1685 remove_partial(n, page);
1690 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1691 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1694 * Try to allocate a partial slab from a specific node.
1696 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1697 struct kmem_cache_cpu *c, gfp_t flags)
1699 struct page *page, *page2;
1700 void *object = NULL;
1705 * Racy check. If we mistakenly see no partial slabs then we
1706 * just allocate an empty slab. If we mistakenly try to get a
1707 * partial slab and there is none available then get_partials()
1710 if (!n || !n->nr_partial)
1713 spin_lock(&n->list_lock);
1714 list_for_each_entry_safe(page, page2, &n->partial, lru) {
1717 if (!pfmemalloc_match(page, flags))
1720 t = acquire_slab(s, n, page, object == NULL, &objects);
1724 available += objects;
1727 stat(s, ALLOC_FROM_PARTIAL);
1730 put_cpu_partial(s, page, 0);
1731 stat(s, CPU_PARTIAL_NODE);
1733 if (!kmem_cache_has_cpu_partial(s)
1734 || available > s->cpu_partial / 2)
1738 spin_unlock(&n->list_lock);
1743 * Get a page from somewhere. Search in increasing NUMA distances.
1745 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1746 struct kmem_cache_cpu *c)
1749 struct zonelist *zonelist;
1752 enum zone_type high_zoneidx = gfp_zone(flags);
1754 unsigned int cpuset_mems_cookie;
1757 * The defrag ratio allows a configuration of the tradeoffs between
1758 * inter node defragmentation and node local allocations. A lower
1759 * defrag_ratio increases the tendency to do local allocations
1760 * instead of attempting to obtain partial slabs from other nodes.
1762 * If the defrag_ratio is set to 0 then kmalloc() always
1763 * returns node local objects. If the ratio is higher then kmalloc()
1764 * may return off node objects because partial slabs are obtained
1765 * from other nodes and filled up.
1767 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1768 * defrag_ratio = 1000) then every (well almost) allocation will
1769 * first attempt to defrag slab caches on other nodes. This means
1770 * scanning over all nodes to look for partial slabs which may be
1771 * expensive if we do it every time we are trying to find a slab
1772 * with available objects.
1774 if (!s->remote_node_defrag_ratio ||
1775 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1779 cpuset_mems_cookie = read_mems_allowed_begin();
1780 zonelist = node_zonelist(mempolicy_slab_node(), flags);
1781 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1782 struct kmem_cache_node *n;
1784 n = get_node(s, zone_to_nid(zone));
1786 if (n && cpuset_zone_allowed(zone, flags) &&
1787 n->nr_partial > s->min_partial) {
1788 object = get_partial_node(s, n, c, flags);
1791 * Don't check read_mems_allowed_retry()
1792 * here - if mems_allowed was updated in
1793 * parallel, that was a harmless race
1794 * between allocation and the cpuset
1801 } while (read_mems_allowed_retry(cpuset_mems_cookie));
1807 * Get a partial page, lock it and return it.
1809 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1810 struct kmem_cache_cpu *c)
1813 int searchnode = node;
1815 if (node == NUMA_NO_NODE)
1816 searchnode = numa_mem_id();
1817 else if (!node_present_pages(node))
1818 searchnode = node_to_mem_node(node);
1820 object = get_partial_node(s, get_node(s, searchnode), c, flags);
1821 if (object || node != NUMA_NO_NODE)
1824 return get_any_partial(s, flags, c);
1827 #ifdef CONFIG_PREEMPT
1829 * Calculate the next globally unique transaction for disambiguiation
1830 * during cmpxchg. The transactions start with the cpu number and are then
1831 * incremented by CONFIG_NR_CPUS.
1833 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
1836 * No preemption supported therefore also no need to check for
1842 static inline unsigned long next_tid(unsigned long tid)
1844 return tid + TID_STEP;
1847 static inline unsigned int tid_to_cpu(unsigned long tid)
1849 return tid % TID_STEP;
1852 static inline unsigned long tid_to_event(unsigned long tid)
1854 return tid / TID_STEP;
1857 static inline unsigned int init_tid(int cpu)
1862 static inline void note_cmpxchg_failure(const char *n,
1863 const struct kmem_cache *s, unsigned long tid)
1865 #ifdef SLUB_DEBUG_CMPXCHG
1866 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
1868 pr_info("%s %s: cmpxchg redo ", n, s->name);
1870 #ifdef CONFIG_PREEMPT
1871 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
1872 pr_warn("due to cpu change %d -> %d\n",
1873 tid_to_cpu(tid), tid_to_cpu(actual_tid));
1876 if (tid_to_event(tid) != tid_to_event(actual_tid))
1877 pr_warn("due to cpu running other code. Event %ld->%ld\n",
1878 tid_to_event(tid), tid_to_event(actual_tid));
1880 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
1881 actual_tid, tid, next_tid(tid));
1883 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
1886 static void init_kmem_cache_cpus(struct kmem_cache *s)
1890 for_each_possible_cpu(cpu)
1891 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
1895 * Remove the cpu slab
1897 static void deactivate_slab(struct kmem_cache *s, struct page *page,
1900 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
1901 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1903 enum slab_modes l = M_NONE, m = M_NONE;
1905 int tail = DEACTIVATE_TO_HEAD;
1909 if (page->freelist) {
1910 stat(s, DEACTIVATE_REMOTE_FREES);
1911 tail = DEACTIVATE_TO_TAIL;
1915 * Stage one: Free all available per cpu objects back
1916 * to the page freelist while it is still frozen. Leave the
1919 * There is no need to take the list->lock because the page
1922 while (freelist && (nextfree = get_freepointer(s, freelist))) {
1924 unsigned long counters;
1927 prior = page->freelist;
1928 counters = page->counters;
1929 set_freepointer(s, freelist, prior);
1930 new.counters = counters;
1932 VM_BUG_ON(!new.frozen);
1934 } while (!__cmpxchg_double_slab(s, page,
1936 freelist, new.counters,
1937 "drain percpu freelist"));
1939 freelist = nextfree;
1943 * Stage two: Ensure that the page is unfrozen while the
1944 * list presence reflects the actual number of objects
1947 * We setup the list membership and then perform a cmpxchg
1948 * with the count. If there is a mismatch then the page
1949 * is not unfrozen but the page is on the wrong list.
1951 * Then we restart the process which may have to remove
1952 * the page from the list that we just put it on again
1953 * because the number of objects in the slab may have
1958 old.freelist = page->freelist;
1959 old.counters = page->counters;
1960 VM_BUG_ON(!old.frozen);
1962 /* Determine target state of the slab */
1963 new.counters = old.counters;
1966 set_freepointer(s, freelist, old.freelist);
1967 new.freelist = freelist;
1969 new.freelist = old.freelist;
1973 if (!new.inuse && n->nr_partial >= s->min_partial)
1975 else if (new.freelist) {
1980 * Taking the spinlock removes the possiblity
1981 * that acquire_slab() will see a slab page that
1984 spin_lock(&n->list_lock);
1988 if (kmem_cache_debug(s) && !lock) {
1991 * This also ensures that the scanning of full
1992 * slabs from diagnostic functions will not see
1995 spin_lock(&n->list_lock);
2003 remove_partial(n, page);
2005 else if (l == M_FULL)
2007 remove_full(s, n, page);
2009 if (m == M_PARTIAL) {
2011 add_partial(n, page, tail);
2014 } else if (m == M_FULL) {
2016 stat(s, DEACTIVATE_FULL);
2017 add_full(s, n, page);
2023 if (!__cmpxchg_double_slab(s, page,
2024 old.freelist, old.counters,
2025 new.freelist, new.counters,
2030 spin_unlock(&n->list_lock);
2033 stat(s, DEACTIVATE_EMPTY);
2034 discard_slab(s, page);
2040 * Unfreeze all the cpu partial slabs.
2042 * This function must be called with interrupts disabled
2043 * for the cpu using c (or some other guarantee must be there
2044 * to guarantee no concurrent accesses).
2046 static void unfreeze_partials(struct kmem_cache *s,
2047 struct kmem_cache_cpu *c)
2049 #ifdef CONFIG_SLUB_CPU_PARTIAL
2050 struct kmem_cache_node *n = NULL, *n2 = NULL;
2051 struct page *page, *discard_page = NULL;
2053 while ((page = c->partial)) {
2057 c->partial = page->next;
2059 n2 = get_node(s, page_to_nid(page));
2062 spin_unlock(&n->list_lock);
2065 spin_lock(&n->list_lock);
2070 old.freelist = page->freelist;
2071 old.counters = page->counters;
2072 VM_BUG_ON(!old.frozen);
2074 new.counters = old.counters;
2075 new.freelist = old.freelist;
2079 } while (!__cmpxchg_double_slab(s, page,
2080 old.freelist, old.counters,
2081 new.freelist, new.counters,
2082 "unfreezing slab"));
2084 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2085 page->next = discard_page;
2086 discard_page = page;
2088 add_partial(n, page, DEACTIVATE_TO_TAIL);
2089 stat(s, FREE_ADD_PARTIAL);
2094 spin_unlock(&n->list_lock);
2096 while (discard_page) {
2097 page = discard_page;
2098 discard_page = discard_page->next;
2100 stat(s, DEACTIVATE_EMPTY);
2101 discard_slab(s, page);
2108 * Put a page that was just frozen (in __slab_free) into a partial page
2109 * slot if available. This is done without interrupts disabled and without
2110 * preemption disabled. The cmpxchg is racy and may put the partial page
2111 * onto a random cpus partial slot.
2113 * If we did not find a slot then simply move all the partials to the
2114 * per node partial list.
2116 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2118 #ifdef CONFIG_SLUB_CPU_PARTIAL
2119 struct page *oldpage;
2127 oldpage = this_cpu_read(s->cpu_slab->partial);
2130 pobjects = oldpage->pobjects;
2131 pages = oldpage->pages;
2132 if (drain && pobjects > s->cpu_partial) {
2133 unsigned long flags;
2135 * partial array is full. Move the existing
2136 * set to the per node partial list.
2138 local_irq_save(flags);
2139 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2140 local_irq_restore(flags);
2144 stat(s, CPU_PARTIAL_DRAIN);
2149 pobjects += page->objects - page->inuse;
2151 page->pages = pages;
2152 page->pobjects = pobjects;
2153 page->next = oldpage;
2155 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2157 if (unlikely(!s->cpu_partial)) {
2158 unsigned long flags;
2160 local_irq_save(flags);
2161 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2162 local_irq_restore(flags);
2168 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2170 stat(s, CPUSLAB_FLUSH);
2171 deactivate_slab(s, c->page, c->freelist);
2173 c->tid = next_tid(c->tid);
2181 * Called from IPI handler with interrupts disabled.
2183 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2185 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2191 unfreeze_partials(s, c);
2195 static void flush_cpu_slab(void *d)
2197 struct kmem_cache *s = d;
2199 __flush_cpu_slab(s, smp_processor_id());
2202 static bool has_cpu_slab(int cpu, void *info)
2204 struct kmem_cache *s = info;
2205 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2207 return c->page || c->partial;
2210 static void flush_all(struct kmem_cache *s)
2212 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC);
2216 * Check if the objects in a per cpu structure fit numa
2217 * locality expectations.
2219 static inline int node_match(struct page *page, int node)
2222 if (!page || (node != NUMA_NO_NODE && page_to_nid(page) != node))
2228 #ifdef CONFIG_SLUB_DEBUG
2229 static int count_free(struct page *page)
2231 return page->objects - page->inuse;
2234 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2236 return atomic_long_read(&n->total_objects);
2238 #endif /* CONFIG_SLUB_DEBUG */
2240 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2241 static unsigned long count_partial(struct kmem_cache_node *n,
2242 int (*get_count)(struct page *))
2244 unsigned long flags;
2245 unsigned long x = 0;
2248 spin_lock_irqsave(&n->list_lock, flags);
2249 list_for_each_entry(page, &n->partial, lru)
2250 x += get_count(page);
2251 spin_unlock_irqrestore(&n->list_lock, flags);
2254 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2256 static noinline void
2257 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2259 #ifdef CONFIG_SLUB_DEBUG
2260 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2261 DEFAULT_RATELIMIT_BURST);
2263 struct kmem_cache_node *n;
2265 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2268 pr_warn("SLUB: Unable to allocate memory on node %d (gfp=0x%x)\n",
2270 pr_warn(" cache: %s, object size: %d, buffer size: %d, default order: %d, min order: %d\n",
2271 s->name, s->object_size, s->size, oo_order(s->oo),
2274 if (oo_order(s->min) > get_order(s->object_size))
2275 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2278 for_each_kmem_cache_node(s, node, n) {
2279 unsigned long nr_slabs;
2280 unsigned long nr_objs;
2281 unsigned long nr_free;
2283 nr_free = count_partial(n, count_free);
2284 nr_slabs = node_nr_slabs(n);
2285 nr_objs = node_nr_objs(n);
2287 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2288 node, nr_slabs, nr_objs, nr_free);
2293 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2294 int node, struct kmem_cache_cpu **pc)
2297 struct kmem_cache_cpu *c = *pc;
2300 freelist = get_partial(s, flags, node, c);
2305 page = new_slab(s, flags, node);
2307 c = raw_cpu_ptr(s->cpu_slab);
2312 * No other reference to the page yet so we can
2313 * muck around with it freely without cmpxchg
2315 freelist = page->freelist;
2316 page->freelist = NULL;
2318 stat(s, ALLOC_SLAB);
2327 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2329 if (unlikely(PageSlabPfmemalloc(page)))
2330 return gfp_pfmemalloc_allowed(gfpflags);
2336 * Check the page->freelist of a page and either transfer the freelist to the
2337 * per cpu freelist or deactivate the page.
2339 * The page is still frozen if the return value is not NULL.
2341 * If this function returns NULL then the page has been unfrozen.
2343 * This function must be called with interrupt disabled.
2345 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2348 unsigned long counters;
2352 freelist = page->freelist;
2353 counters = page->counters;
2355 new.counters = counters;
2356 VM_BUG_ON(!new.frozen);
2358 new.inuse = page->objects;
2359 new.frozen = freelist != NULL;
2361 } while (!__cmpxchg_double_slab(s, page,
2370 * Slow path. The lockless freelist is empty or we need to perform
2373 * Processing is still very fast if new objects have been freed to the
2374 * regular freelist. In that case we simply take over the regular freelist
2375 * as the lockless freelist and zap the regular freelist.
2377 * If that is not working then we fall back to the partial lists. We take the
2378 * first element of the freelist as the object to allocate now and move the
2379 * rest of the freelist to the lockless freelist.
2381 * And if we were unable to get a new slab from the partial slab lists then
2382 * we need to allocate a new slab. This is the slowest path since it involves
2383 * a call to the page allocator and the setup of a new slab.
2385 * Version of __slab_alloc to use when we know that interrupts are
2386 * already disabled (which is the case for bulk allocation).
2388 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2389 unsigned long addr, struct kmem_cache_cpu *c)
2399 if (unlikely(!node_match(page, node))) {
2400 int searchnode = node;
2402 if (node != NUMA_NO_NODE && !node_present_pages(node))
2403 searchnode = node_to_mem_node(node);
2405 if (unlikely(!node_match(page, searchnode))) {
2406 stat(s, ALLOC_NODE_MISMATCH);
2407 deactivate_slab(s, page, c->freelist);
2415 * By rights, we should be searching for a slab page that was
2416 * PFMEMALLOC but right now, we are losing the pfmemalloc
2417 * information when the page leaves the per-cpu allocator
2419 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2420 deactivate_slab(s, page, c->freelist);
2426 /* must check again c->freelist in case of cpu migration or IRQ */
2427 freelist = c->freelist;
2431 freelist = get_freelist(s, page);
2435 stat(s, DEACTIVATE_BYPASS);
2439 stat(s, ALLOC_REFILL);
2443 * freelist is pointing to the list of objects to be used.
2444 * page is pointing to the page from which the objects are obtained.
2445 * That page must be frozen for per cpu allocations to work.
2447 VM_BUG_ON(!c->page->frozen);
2448 c->freelist = get_freepointer(s, freelist);
2449 c->tid = next_tid(c->tid);
2455 page = c->page = c->partial;
2456 c->partial = page->next;
2457 stat(s, CPU_PARTIAL_ALLOC);
2462 freelist = new_slab_objects(s, gfpflags, node, &c);
2464 if (unlikely(!freelist)) {
2465 slab_out_of_memory(s, gfpflags, node);
2470 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2473 /* Only entered in the debug case */
2474 if (kmem_cache_debug(s) &&
2475 !alloc_debug_processing(s, page, freelist, addr))
2476 goto new_slab; /* Slab failed checks. Next slab needed */
2478 deactivate_slab(s, page, get_freepointer(s, freelist));
2485 * Another one that disabled interrupt and compensates for possible
2486 * cpu changes by refetching the per cpu area pointer.
2488 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2489 unsigned long addr, struct kmem_cache_cpu *c)
2492 unsigned long flags;
2494 local_irq_save(flags);
2495 #ifdef CONFIG_PREEMPT
2497 * We may have been preempted and rescheduled on a different
2498 * cpu before disabling interrupts. Need to reload cpu area
2501 c = this_cpu_ptr(s->cpu_slab);
2504 p = ___slab_alloc(s, gfpflags, node, addr, c);
2505 local_irq_restore(flags);
2510 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2511 * have the fastpath folded into their functions. So no function call
2512 * overhead for requests that can be satisfied on the fastpath.
2514 * The fastpath works by first checking if the lockless freelist can be used.
2515 * If not then __slab_alloc is called for slow processing.
2517 * Otherwise we can simply pick the next object from the lockless free list.
2519 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2520 gfp_t gfpflags, int node, unsigned long addr)
2523 struct kmem_cache_cpu *c;
2527 s = slab_pre_alloc_hook(s, gfpflags);
2532 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2533 * enabled. We may switch back and forth between cpus while
2534 * reading from one cpu area. That does not matter as long
2535 * as we end up on the original cpu again when doing the cmpxchg.
2537 * We should guarantee that tid and kmem_cache are retrieved on
2538 * the same cpu. It could be different if CONFIG_PREEMPT so we need
2539 * to check if it is matched or not.
2542 tid = this_cpu_read(s->cpu_slab->tid);
2543 c = raw_cpu_ptr(s->cpu_slab);
2544 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2545 unlikely(tid != READ_ONCE(c->tid)));
2548 * Irqless object alloc/free algorithm used here depends on sequence
2549 * of fetching cpu_slab's data. tid should be fetched before anything
2550 * on c to guarantee that object and page associated with previous tid
2551 * won't be used with current tid. If we fetch tid first, object and
2552 * page could be one associated with next tid and our alloc/free
2553 * request will be failed. In this case, we will retry. So, no problem.
2558 * The transaction ids are globally unique per cpu and per operation on
2559 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2560 * occurs on the right processor and that there was no operation on the
2561 * linked list in between.
2564 object = c->freelist;
2566 if (unlikely(!object || !node_match(page, node))) {
2567 object = __slab_alloc(s, gfpflags, node, addr, c);
2568 stat(s, ALLOC_SLOWPATH);
2570 void *next_object = get_freepointer_safe(s, object);
2573 * The cmpxchg will only match if there was no additional
2574 * operation and if we are on the right processor.
2576 * The cmpxchg does the following atomically (without lock
2578 * 1. Relocate first pointer to the current per cpu area.
2579 * 2. Verify that tid and freelist have not been changed
2580 * 3. If they were not changed replace tid and freelist
2582 * Since this is without lock semantics the protection is only
2583 * against code executing on this cpu *not* from access by
2586 if (unlikely(!this_cpu_cmpxchg_double(
2587 s->cpu_slab->freelist, s->cpu_slab->tid,
2589 next_object, next_tid(tid)))) {
2591 note_cmpxchg_failure("slab_alloc", s, tid);
2594 prefetch_freepointer(s, next_object);
2595 stat(s, ALLOC_FASTPATH);
2598 if (unlikely(gfpflags & __GFP_ZERO) && object)
2599 memset(object, 0, s->object_size);
2601 slab_post_alloc_hook(s, gfpflags, 1, &object);
2606 static __always_inline void *slab_alloc(struct kmem_cache *s,
2607 gfp_t gfpflags, unsigned long addr)
2609 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2612 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2614 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2616 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2621 EXPORT_SYMBOL(kmem_cache_alloc);
2623 #ifdef CONFIG_TRACING
2624 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2626 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2627 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2628 kasan_kmalloc(s, ret, size);
2631 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2635 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2637 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2639 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2640 s->object_size, s->size, gfpflags, node);
2644 EXPORT_SYMBOL(kmem_cache_alloc_node);
2646 #ifdef CONFIG_TRACING
2647 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2649 int node, size_t size)
2651 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2653 trace_kmalloc_node(_RET_IP_, ret,
2654 size, s->size, gfpflags, node);
2656 kasan_kmalloc(s, ret, size);
2659 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2664 * Slow path handling. This may still be called frequently since objects
2665 * have a longer lifetime than the cpu slabs in most processing loads.
2667 * So we still attempt to reduce cache line usage. Just take the slab
2668 * lock and free the item. If there is no additional partial page
2669 * handling required then we can return immediately.
2671 static void __slab_free(struct kmem_cache *s, struct page *page,
2672 void *head, void *tail, int cnt,
2679 unsigned long counters;
2680 struct kmem_cache_node *n = NULL;
2681 unsigned long uninitialized_var(flags);
2683 stat(s, FREE_SLOWPATH);
2685 if (kmem_cache_debug(s) &&
2686 !(n = free_debug_processing(s, page, head, tail, cnt,
2692 spin_unlock_irqrestore(&n->list_lock, flags);
2695 prior = page->freelist;
2696 counters = page->counters;
2697 set_freepointer(s, tail, prior);
2698 new.counters = counters;
2699 was_frozen = new.frozen;
2701 if ((!new.inuse || !prior) && !was_frozen) {
2703 if (kmem_cache_has_cpu_partial(s) && !prior) {
2706 * Slab was on no list before and will be
2708 * We can defer the list move and instead
2713 } else { /* Needs to be taken off a list */
2715 n = get_node(s, page_to_nid(page));
2717 * Speculatively acquire the list_lock.
2718 * If the cmpxchg does not succeed then we may
2719 * drop the list_lock without any processing.
2721 * Otherwise the list_lock will synchronize with
2722 * other processors updating the list of slabs.
2724 spin_lock_irqsave(&n->list_lock, flags);
2729 } while (!cmpxchg_double_slab(s, page,
2737 * If we just froze the page then put it onto the
2738 * per cpu partial list.
2740 if (new.frozen && !was_frozen) {
2741 put_cpu_partial(s, page, 1);
2742 stat(s, CPU_PARTIAL_FREE);
2745 * The list lock was not taken therefore no list
2746 * activity can be necessary.
2749 stat(s, FREE_FROZEN);
2753 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
2757 * Objects left in the slab. If it was not on the partial list before
2760 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
2761 if (kmem_cache_debug(s))
2762 remove_full(s, n, page);
2763 add_partial(n, page, DEACTIVATE_TO_TAIL);
2764 stat(s, FREE_ADD_PARTIAL);
2766 spin_unlock_irqrestore(&n->list_lock, flags);
2772 * Slab on the partial list.
2774 remove_partial(n, page);
2775 stat(s, FREE_REMOVE_PARTIAL);
2777 /* Slab must be on the full list */
2778 remove_full(s, n, page);
2781 spin_unlock_irqrestore(&n->list_lock, flags);
2783 discard_slab(s, page);
2787 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2788 * can perform fastpath freeing without additional function calls.
2790 * The fastpath is only possible if we are freeing to the current cpu slab
2791 * of this processor. This typically the case if we have just allocated
2794 * If fastpath is not possible then fall back to __slab_free where we deal
2795 * with all sorts of special processing.
2797 * Bulk free of a freelist with several objects (all pointing to the
2798 * same page) possible by specifying head and tail ptr, plus objects
2799 * count (cnt). Bulk free indicated by tail pointer being set.
2801 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
2802 void *head, void *tail, int cnt,
2805 void *tail_obj = tail ? : head;
2806 struct kmem_cache_cpu *c;
2809 slab_free_freelist_hook(s, head, tail);
2813 * Determine the currently cpus per cpu slab.
2814 * The cpu may change afterward. However that does not matter since
2815 * data is retrieved via this pointer. If we are on the same cpu
2816 * during the cmpxchg then the free will succeed.
2819 tid = this_cpu_read(s->cpu_slab->tid);
2820 c = raw_cpu_ptr(s->cpu_slab);
2821 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2822 unlikely(tid != READ_ONCE(c->tid)));
2824 /* Same with comment on barrier() in slab_alloc_node() */
2827 if (likely(page == c->page)) {
2828 set_freepointer(s, tail_obj, c->freelist);
2830 if (unlikely(!this_cpu_cmpxchg_double(
2831 s->cpu_slab->freelist, s->cpu_slab->tid,
2833 head, next_tid(tid)))) {
2835 note_cmpxchg_failure("slab_free", s, tid);
2838 stat(s, FREE_FASTPATH);
2840 __slab_free(s, page, head, tail_obj, cnt, addr);
2844 void kmem_cache_free(struct kmem_cache *s, void *x)
2846 s = cache_from_obj(s, x);
2849 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
2850 trace_kmem_cache_free(_RET_IP_, x);
2852 EXPORT_SYMBOL(kmem_cache_free);
2854 struct detached_freelist {
2859 struct kmem_cache *s;
2863 * This function progressively scans the array with free objects (with
2864 * a limited look ahead) and extract objects belonging to the same
2865 * page. It builds a detached freelist directly within the given
2866 * page/objects. This can happen without any need for
2867 * synchronization, because the objects are owned by running process.
2868 * The freelist is build up as a single linked list in the objects.
2869 * The idea is, that this detached freelist can then be bulk
2870 * transferred to the real freelist(s), but only requiring a single
2871 * synchronization primitive. Look ahead in the array is limited due
2872 * to performance reasons.
2875 int build_detached_freelist(struct kmem_cache *s, size_t size,
2876 void **p, struct detached_freelist *df)
2878 size_t first_skipped_index = 0;
2882 /* Always re-init detached_freelist */
2887 } while (!object && size);
2892 /* Support for memcg, compiler can optimize this out */
2893 df->s = cache_from_obj(s, object);
2895 /* Start new detached freelist */
2896 set_freepointer(df->s, object, NULL);
2897 df->page = virt_to_head_page(object);
2899 df->freelist = object;
2900 p[size] = NULL; /* mark object processed */
2906 continue; /* Skip processed objects */
2908 /* df->page is always set at this point */
2909 if (df->page == virt_to_head_page(object)) {
2910 /* Opportunity build freelist */
2911 set_freepointer(df->s, object, df->freelist);
2912 df->freelist = object;
2914 p[size] = NULL; /* mark object processed */
2919 /* Limit look ahead search */
2923 if (!first_skipped_index)
2924 first_skipped_index = size + 1;
2927 return first_skipped_index;
2930 /* Note that interrupts must be enabled when calling this function. */
2931 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
2937 struct detached_freelist df;
2939 size = build_detached_freelist(s, size, p, &df);
2940 if (unlikely(!df.page))
2943 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
2944 } while (likely(size));
2946 EXPORT_SYMBOL(kmem_cache_free_bulk);
2948 /* Note that interrupts must be enabled when calling this function. */
2949 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
2952 struct kmem_cache_cpu *c;
2955 /* memcg and kmem_cache debug support */
2956 s = slab_pre_alloc_hook(s, flags);
2960 * Drain objects in the per cpu slab, while disabling local
2961 * IRQs, which protects against PREEMPT and interrupts
2962 * handlers invoking normal fastpath.
2964 local_irq_disable();
2965 c = this_cpu_ptr(s->cpu_slab);
2967 for (i = 0; i < size; i++) {
2968 void *object = c->freelist;
2970 if (unlikely(!object)) {
2972 * Invoking slow path likely have side-effect
2973 * of re-populating per CPU c->freelist
2975 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
2977 if (unlikely(!p[i]))
2980 c = this_cpu_ptr(s->cpu_slab);
2981 continue; /* goto for-loop */
2983 c->freelist = get_freepointer(s, object);
2986 c->tid = next_tid(c->tid);
2989 /* Clear memory outside IRQ disabled fastpath loop */
2990 if (unlikely(flags & __GFP_ZERO)) {
2993 for (j = 0; j < i; j++)
2994 memset(p[j], 0, s->object_size);
2997 /* memcg and kmem_cache debug support */
2998 slab_post_alloc_hook(s, flags, size, p);
3002 slab_post_alloc_hook(s, flags, i, p);
3003 __kmem_cache_free_bulk(s, i, p);
3006 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3010 * Object placement in a slab is made very easy because we always start at
3011 * offset 0. If we tune the size of the object to the alignment then we can
3012 * get the required alignment by putting one properly sized object after
3015 * Notice that the allocation order determines the sizes of the per cpu
3016 * caches. Each processor has always one slab available for allocations.
3017 * Increasing the allocation order reduces the number of times that slabs
3018 * must be moved on and off the partial lists and is therefore a factor in
3023 * Mininum / Maximum order of slab pages. This influences locking overhead
3024 * and slab fragmentation. A higher order reduces the number of partial slabs
3025 * and increases the number of allocations possible without having to
3026 * take the list_lock.
3028 static int slub_min_order;
3029 static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3030 static int slub_min_objects;
3033 * Calculate the order of allocation given an slab object size.
3035 * The order of allocation has significant impact on performance and other
3036 * system components. Generally order 0 allocations should be preferred since
3037 * order 0 does not cause fragmentation in the page allocator. Larger objects
3038 * be problematic to put into order 0 slabs because there may be too much
3039 * unused space left. We go to a higher order if more than 1/16th of the slab
3042 * In order to reach satisfactory performance we must ensure that a minimum
3043 * number of objects is in one slab. Otherwise we may generate too much
3044 * activity on the partial lists which requires taking the list_lock. This is
3045 * less a concern for large slabs though which are rarely used.
3047 * slub_max_order specifies the order where we begin to stop considering the
3048 * number of objects in a slab as critical. If we reach slub_max_order then
3049 * we try to keep the page order as low as possible. So we accept more waste
3050 * of space in favor of a small page order.
3052 * Higher order allocations also allow the placement of more objects in a
3053 * slab and thereby reduce object handling overhead. If the user has
3054 * requested a higher mininum order then we start with that one instead of
3055 * the smallest order which will fit the object.
3057 static inline int slab_order(int size, int min_objects,
3058 int max_order, int fract_leftover, int reserved)
3062 int min_order = slub_min_order;
3064 if (order_objects(min_order, size, reserved) > MAX_OBJS_PER_PAGE)
3065 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3067 for (order = max(min_order, get_order(min_objects * size + reserved));
3068 order <= max_order; order++) {
3070 unsigned long slab_size = PAGE_SIZE << order;
3072 rem = (slab_size - reserved) % size;
3074 if (rem <= slab_size / fract_leftover)
3081 static inline int calculate_order(int size, int reserved)
3089 * Attempt to find best configuration for a slab. This
3090 * works by first attempting to generate a layout with
3091 * the best configuration and backing off gradually.
3093 * First we increase the acceptable waste in a slab. Then
3094 * we reduce the minimum objects required in a slab.
3096 min_objects = slub_min_objects;
3098 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3099 max_objects = order_objects(slub_max_order, size, reserved);
3100 min_objects = min(min_objects, max_objects);
3102 while (min_objects > 1) {
3104 while (fraction >= 4) {
3105 order = slab_order(size, min_objects,
3106 slub_max_order, fraction, reserved);
3107 if (order <= slub_max_order)
3115 * We were unable to place multiple objects in a slab. Now
3116 * lets see if we can place a single object there.
3118 order = slab_order(size, 1, slub_max_order, 1, reserved);
3119 if (order <= slub_max_order)
3123 * Doh this slab cannot be placed using slub_max_order.
3125 order = slab_order(size, 1, MAX_ORDER, 1, reserved);
3126 if (order < MAX_ORDER)
3132 init_kmem_cache_node(struct kmem_cache_node *n)
3135 spin_lock_init(&n->list_lock);
3136 INIT_LIST_HEAD(&n->partial);
3137 #ifdef CONFIG_SLUB_DEBUG
3138 atomic_long_set(&n->nr_slabs, 0);
3139 atomic_long_set(&n->total_objects, 0);
3140 INIT_LIST_HEAD(&n->full);
3144 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3146 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3147 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3150 * Must align to double word boundary for the double cmpxchg
3151 * instructions to work; see __pcpu_double_call_return_bool().
3153 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3154 2 * sizeof(void *));
3159 init_kmem_cache_cpus(s);
3164 static struct kmem_cache *kmem_cache_node;
3167 * No kmalloc_node yet so do it by hand. We know that this is the first
3168 * slab on the node for this slabcache. There are no concurrent accesses
3171 * Note that this function only works on the kmem_cache_node
3172 * when allocating for the kmem_cache_node. This is used for bootstrapping
3173 * memory on a fresh node that has no slab structures yet.
3175 static void early_kmem_cache_node_alloc(int node)
3178 struct kmem_cache_node *n;
3180 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3182 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3185 if (page_to_nid(page) != node) {
3186 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3187 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3192 page->freelist = get_freepointer(kmem_cache_node, n);
3195 kmem_cache_node->node[node] = n;
3196 #ifdef CONFIG_SLUB_DEBUG
3197 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3198 init_tracking(kmem_cache_node, n);
3200 kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node));
3201 init_kmem_cache_node(n);
3202 inc_slabs_node(kmem_cache_node, node, page->objects);
3205 * No locks need to be taken here as it has just been
3206 * initialized and there is no concurrent access.
3208 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3211 static void free_kmem_cache_nodes(struct kmem_cache *s)
3214 struct kmem_cache_node *n;
3216 for_each_kmem_cache_node(s, node, n) {
3217 kmem_cache_free(kmem_cache_node, n);
3218 s->node[node] = NULL;
3222 static int init_kmem_cache_nodes(struct kmem_cache *s)
3226 for_each_node_state(node, N_NORMAL_MEMORY) {
3227 struct kmem_cache_node *n;
3229 if (slab_state == DOWN) {
3230 early_kmem_cache_node_alloc(node);
3233 n = kmem_cache_alloc_node(kmem_cache_node,
3237 free_kmem_cache_nodes(s);
3242 init_kmem_cache_node(n);
3247 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3249 if (min < MIN_PARTIAL)
3251 else if (min > MAX_PARTIAL)
3253 s->min_partial = min;
3257 * calculate_sizes() determines the order and the distribution of data within
3260 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3262 unsigned long flags = s->flags;
3263 unsigned long size = s->object_size;
3267 * Round up object size to the next word boundary. We can only
3268 * place the free pointer at word boundaries and this determines
3269 * the possible location of the free pointer.
3271 size = ALIGN(size, sizeof(void *));
3273 #ifdef CONFIG_SLUB_DEBUG
3275 * Determine if we can poison the object itself. If the user of
3276 * the slab may touch the object after free or before allocation
3277 * then we should never poison the object itself.
3279 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
3281 s->flags |= __OBJECT_POISON;
3283 s->flags &= ~__OBJECT_POISON;
3287 * If we are Redzoning then check if there is some space between the
3288 * end of the object and the free pointer. If not then add an
3289 * additional word to have some bytes to store Redzone information.
3291 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3292 size += sizeof(void *);
3296 * With that we have determined the number of bytes in actual use
3297 * by the object. This is the potential offset to the free pointer.
3301 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
3304 * Relocate free pointer after the object if it is not
3305 * permitted to overwrite the first word of the object on
3308 * This is the case if we do RCU, have a constructor or
3309 * destructor or are poisoning the objects.
3312 size += sizeof(void *);
3315 #ifdef CONFIG_SLUB_DEBUG
3316 if (flags & SLAB_STORE_USER)
3318 * Need to store information about allocs and frees after
3321 size += 2 * sizeof(struct track);
3323 if (flags & SLAB_RED_ZONE) {
3325 * Add some empty padding so that we can catch
3326 * overwrites from earlier objects rather than let
3327 * tracking information or the free pointer be
3328 * corrupted if a user writes before the start
3331 size += sizeof(void *);
3333 s->red_left_pad = sizeof(void *);
3334 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3335 size += s->red_left_pad;
3340 * SLUB stores one object immediately after another beginning from
3341 * offset 0. In order to align the objects we have to simply size
3342 * each object to conform to the alignment.
3344 size = ALIGN(size, s->align);
3346 if (forced_order >= 0)
3347 order = forced_order;
3349 order = calculate_order(size, s->reserved);
3356 s->allocflags |= __GFP_COMP;
3358 if (s->flags & SLAB_CACHE_DMA)
3359 s->allocflags |= GFP_DMA;
3361 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3362 s->allocflags |= __GFP_RECLAIMABLE;
3365 * Determine the number of objects per slab
3367 s->oo = oo_make(order, size, s->reserved);
3368 s->min = oo_make(get_order(size), size, s->reserved);
3369 if (oo_objects(s->oo) > oo_objects(s->max))
3372 return !!oo_objects(s->oo);
3375 static int kmem_cache_open(struct kmem_cache *s, unsigned long flags)
3377 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3380 if (need_reserve_slab_rcu && (s->flags & SLAB_DESTROY_BY_RCU))
3381 s->reserved = sizeof(struct rcu_head);
3383 if (!calculate_sizes(s, -1))
3385 if (disable_higher_order_debug) {
3387 * Disable debugging flags that store metadata if the min slab
3390 if (get_order(s->size) > get_order(s->object_size)) {
3391 s->flags &= ~DEBUG_METADATA_FLAGS;
3393 if (!calculate_sizes(s, -1))
3398 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3399 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3400 if (system_has_cmpxchg_double() && (s->flags & SLAB_DEBUG_FLAGS) == 0)
3401 /* Enable fast mode */
3402 s->flags |= __CMPXCHG_DOUBLE;
3406 * The larger the object size is, the more pages we want on the partial
3407 * list to avoid pounding the page allocator excessively.
3409 set_min_partial(s, ilog2(s->size) / 2);
3412 * cpu_partial determined the maximum number of objects kept in the
3413 * per cpu partial lists of a processor.
3415 * Per cpu partial lists mainly contain slabs that just have one
3416 * object freed. If they are used for allocation then they can be
3417 * filled up again with minimal effort. The slab will never hit the
3418 * per node partial lists and therefore no locking will be required.
3420 * This setting also determines
3422 * A) The number of objects from per cpu partial slabs dumped to the
3423 * per node list when we reach the limit.
3424 * B) The number of objects in cpu partial slabs to extract from the
3425 * per node list when we run out of per cpu objects. We only fetch
3426 * 50% to keep some capacity around for frees.
3428 if (!kmem_cache_has_cpu_partial(s))
3430 else if (s->size >= PAGE_SIZE)
3432 else if (s->size >= 1024)
3434 else if (s->size >= 256)
3435 s->cpu_partial = 13;
3437 s->cpu_partial = 30;
3440 s->remote_node_defrag_ratio = 1000;
3442 if (!init_kmem_cache_nodes(s))
3445 if (alloc_kmem_cache_cpus(s))
3448 free_kmem_cache_nodes(s);
3450 if (flags & SLAB_PANIC)
3451 panic("Cannot create slab %s size=%lu realsize=%u "
3452 "order=%u offset=%u flags=%lx\n",
3453 s->name, (unsigned long)s->size, s->size,
3454 oo_order(s->oo), s->offset, flags);
3458 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3461 #ifdef CONFIG_SLUB_DEBUG
3462 void *addr = page_address(page);
3464 unsigned long *map = kzalloc(BITS_TO_LONGS(page->objects) *
3465 sizeof(long), GFP_ATOMIC);
3468 slab_err(s, page, text, s->name);
3471 get_map(s, page, map);
3472 for_each_object(p, s, addr, page->objects) {
3474 if (!test_bit(slab_index(p, s, addr), map)) {
3475 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3476 print_tracking(s, p);
3485 * Attempt to free all partial slabs on a node.
3486 * This is called from kmem_cache_close(). We must be the last thread
3487 * using the cache and therefore we do not need to lock anymore.
3489 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3491 struct page *page, *h;
3493 list_for_each_entry_safe(page, h, &n->partial, lru) {
3495 __remove_partial(n, page);
3496 discard_slab(s, page);
3498 list_slab_objects(s, page,
3499 "Objects remaining in %s on kmem_cache_close()");
3505 * Release all resources used by a slab cache.
3507 static inline int kmem_cache_close(struct kmem_cache *s)
3510 struct kmem_cache_node *n;
3513 /* Attempt to free all objects */
3514 for_each_kmem_cache_node(s, node, n) {
3516 if (n->nr_partial || slabs_node(s, node))
3519 free_percpu(s->cpu_slab);
3520 free_kmem_cache_nodes(s);
3524 int __kmem_cache_shutdown(struct kmem_cache *s)
3526 return kmem_cache_close(s);
3529 /********************************************************************
3531 *******************************************************************/
3533 static int __init setup_slub_min_order(char *str)
3535 get_option(&str, &slub_min_order);
3540 __setup("slub_min_order=", setup_slub_min_order);
3542 static int __init setup_slub_max_order(char *str)
3544 get_option(&str, &slub_max_order);
3545 slub_max_order = min(slub_max_order, MAX_ORDER - 1);
3550 __setup("slub_max_order=", setup_slub_max_order);
3552 static int __init setup_slub_min_objects(char *str)
3554 get_option(&str, &slub_min_objects);
3559 __setup("slub_min_objects=", setup_slub_min_objects);
3561 void *__kmalloc(size_t size, gfp_t flags)
3563 struct kmem_cache *s;
3566 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3567 return kmalloc_large(size, flags);
3569 s = kmalloc_slab(size, flags);
3571 if (unlikely(ZERO_OR_NULL_PTR(s)))
3574 ret = slab_alloc(s, flags, _RET_IP_);
3576 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3578 kasan_kmalloc(s, ret, size);
3582 EXPORT_SYMBOL(__kmalloc);
3585 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3590 flags |= __GFP_COMP | __GFP_NOTRACK;
3591 page = alloc_kmem_pages_node(node, flags, get_order(size));
3593 ptr = page_address(page);
3595 kmalloc_large_node_hook(ptr, size, flags);
3599 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3601 struct kmem_cache *s;
3604 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
3605 ret = kmalloc_large_node(size, flags, node);
3607 trace_kmalloc_node(_RET_IP_, ret,
3608 size, PAGE_SIZE << get_order(size),
3614 s = kmalloc_slab(size, flags);
3616 if (unlikely(ZERO_OR_NULL_PTR(s)))
3619 ret = slab_alloc_node(s, flags, node, _RET_IP_);
3621 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3623 kasan_kmalloc(s, ret, size);
3627 EXPORT_SYMBOL(__kmalloc_node);
3630 #ifdef CONFIG_HARDENED_USERCOPY
3632 * Rejects objects that are incorrectly sized.
3634 * Returns NULL if check passes, otherwise const char * to name of cache
3635 * to indicate an error.
3637 const char *__check_heap_object(const void *ptr, unsigned long n,
3640 struct kmem_cache *s;
3641 unsigned long offset;
3644 /* Find object and usable object size. */
3645 s = page->slab_cache;
3646 object_size = slab_ksize(s);
3648 /* Reject impossible pointers. */
3649 if (ptr < page_address(page))
3652 /* Find offset within object. */
3653 offset = (ptr - page_address(page)) % s->size;
3655 /* Adjust for redzone and reject if within the redzone. */
3656 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) {
3657 if (offset < s->red_left_pad)
3659 offset -= s->red_left_pad;
3662 /* Allow address range falling entirely within object size. */
3663 if (offset <= object_size && n <= object_size - offset)
3668 #endif /* CONFIG_HARDENED_USERCOPY */
3670 static size_t __ksize(const void *object)
3674 if (unlikely(object == ZERO_SIZE_PTR))
3677 page = virt_to_head_page(object);
3679 if (unlikely(!PageSlab(page))) {
3680 WARN_ON(!PageCompound(page));
3681 return PAGE_SIZE << compound_order(page);
3684 return slab_ksize(page->slab_cache);
3687 size_t ksize(const void *object)
3689 size_t size = __ksize(object);
3690 /* We assume that ksize callers could use whole allocated area,
3691 so we need unpoison this area. */
3692 kasan_krealloc(object, size);
3695 EXPORT_SYMBOL(ksize);
3697 void kfree(const void *x)
3700 void *object = (void *)x;
3702 trace_kfree(_RET_IP_, x);
3704 if (unlikely(ZERO_OR_NULL_PTR(x)))
3707 page = virt_to_head_page(x);
3708 if (unlikely(!PageSlab(page))) {
3709 BUG_ON(!PageCompound(page));
3711 __free_kmem_pages(page, compound_order(page));
3714 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
3716 EXPORT_SYMBOL(kfree);
3718 #define SHRINK_PROMOTE_MAX 32
3721 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
3722 * up most to the head of the partial lists. New allocations will then
3723 * fill those up and thus they can be removed from the partial lists.
3725 * The slabs with the least items are placed last. This results in them
3726 * being allocated from last increasing the chance that the last objects
3727 * are freed in them.
3729 int __kmem_cache_shrink(struct kmem_cache *s, bool deactivate)
3733 struct kmem_cache_node *n;
3736 struct list_head discard;
3737 struct list_head promote[SHRINK_PROMOTE_MAX];
3738 unsigned long flags;
3743 * Disable empty slabs caching. Used to avoid pinning offline
3744 * memory cgroups by kmem pages that can be freed.
3750 * s->cpu_partial is checked locklessly (see put_cpu_partial),
3751 * so we have to make sure the change is visible.
3753 kick_all_cpus_sync();
3757 for_each_kmem_cache_node(s, node, n) {
3758 INIT_LIST_HEAD(&discard);
3759 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
3760 INIT_LIST_HEAD(promote + i);
3762 spin_lock_irqsave(&n->list_lock, flags);
3765 * Build lists of slabs to discard or promote.
3767 * Note that concurrent frees may occur while we hold the
3768 * list_lock. page->inuse here is the upper limit.
3770 list_for_each_entry_safe(page, t, &n->partial, lru) {
3771 int free = page->objects - page->inuse;
3773 /* Do not reread page->inuse */
3776 /* We do not keep full slabs on the list */
3779 if (free == page->objects) {
3780 list_move(&page->lru, &discard);
3782 } else if (free <= SHRINK_PROMOTE_MAX)
3783 list_move(&page->lru, promote + free - 1);
3787 * Promote the slabs filled up most to the head of the
3790 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
3791 list_splice(promote + i, &n->partial);
3793 spin_unlock_irqrestore(&n->list_lock, flags);
3795 /* Release empty slabs */
3796 list_for_each_entry_safe(page, t, &discard, lru)
3797 discard_slab(s, page);
3799 if (slabs_node(s, node))
3806 static int slab_mem_going_offline_callback(void *arg)
3808 struct kmem_cache *s;
3810 mutex_lock(&slab_mutex);
3811 list_for_each_entry(s, &slab_caches, list)
3812 __kmem_cache_shrink(s, false);
3813 mutex_unlock(&slab_mutex);
3818 static void slab_mem_offline_callback(void *arg)
3820 struct kmem_cache_node *n;
3821 struct kmem_cache *s;
3822 struct memory_notify *marg = arg;
3825 offline_node = marg->status_change_nid_normal;
3828 * If the node still has available memory. we need kmem_cache_node
3831 if (offline_node < 0)
3834 mutex_lock(&slab_mutex);
3835 list_for_each_entry(s, &slab_caches, list) {
3836 n = get_node(s, offline_node);
3839 * if n->nr_slabs > 0, slabs still exist on the node
3840 * that is going down. We were unable to free them,
3841 * and offline_pages() function shouldn't call this
3842 * callback. So, we must fail.
3844 BUG_ON(slabs_node(s, offline_node));
3846 s->node[offline_node] = NULL;
3847 kmem_cache_free(kmem_cache_node, n);
3850 mutex_unlock(&slab_mutex);
3853 static int slab_mem_going_online_callback(void *arg)
3855 struct kmem_cache_node *n;
3856 struct kmem_cache *s;
3857 struct memory_notify *marg = arg;
3858 int nid = marg->status_change_nid_normal;
3862 * If the node's memory is already available, then kmem_cache_node is
3863 * already created. Nothing to do.
3869 * We are bringing a node online. No memory is available yet. We must
3870 * allocate a kmem_cache_node structure in order to bring the node
3873 mutex_lock(&slab_mutex);
3874 list_for_each_entry(s, &slab_caches, list) {
3876 * XXX: kmem_cache_alloc_node will fallback to other nodes
3877 * since memory is not yet available from the node that
3880 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
3885 init_kmem_cache_node(n);
3889 mutex_unlock(&slab_mutex);
3893 static int slab_memory_callback(struct notifier_block *self,
3894 unsigned long action, void *arg)
3899 case MEM_GOING_ONLINE:
3900 ret = slab_mem_going_online_callback(arg);
3902 case MEM_GOING_OFFLINE:
3903 ret = slab_mem_going_offline_callback(arg);
3906 case MEM_CANCEL_ONLINE:
3907 slab_mem_offline_callback(arg);
3910 case MEM_CANCEL_OFFLINE:
3914 ret = notifier_from_errno(ret);
3920 static struct notifier_block slab_memory_callback_nb = {
3921 .notifier_call = slab_memory_callback,
3922 .priority = SLAB_CALLBACK_PRI,
3925 /********************************************************************
3926 * Basic setup of slabs
3927 *******************************************************************/
3930 * Used for early kmem_cache structures that were allocated using
3931 * the page allocator. Allocate them properly then fix up the pointers
3932 * that may be pointing to the wrong kmem_cache structure.
3935 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
3938 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
3939 struct kmem_cache_node *n;
3941 memcpy(s, static_cache, kmem_cache->object_size);
3944 * This runs very early, and only the boot processor is supposed to be
3945 * up. Even if it weren't true, IRQs are not up so we couldn't fire
3948 __flush_cpu_slab(s, smp_processor_id());
3949 for_each_kmem_cache_node(s, node, n) {
3952 list_for_each_entry(p, &n->partial, lru)
3955 #ifdef CONFIG_SLUB_DEBUG
3956 list_for_each_entry(p, &n->full, lru)
3960 slab_init_memcg_params(s);
3961 list_add(&s->list, &slab_caches);
3965 void __init kmem_cache_init(void)
3967 static __initdata struct kmem_cache boot_kmem_cache,
3968 boot_kmem_cache_node;
3970 if (debug_guardpage_minorder())
3973 kmem_cache_node = &boot_kmem_cache_node;
3974 kmem_cache = &boot_kmem_cache;
3976 create_boot_cache(kmem_cache_node, "kmem_cache_node",
3977 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN);
3979 register_hotmemory_notifier(&slab_memory_callback_nb);
3981 /* Able to allocate the per node structures */
3982 slab_state = PARTIAL;
3984 create_boot_cache(kmem_cache, "kmem_cache",
3985 offsetof(struct kmem_cache, node) +
3986 nr_node_ids * sizeof(struct kmem_cache_node *),
3987 SLAB_HWCACHE_ALIGN);
3989 kmem_cache = bootstrap(&boot_kmem_cache);
3992 * Allocate kmem_cache_node properly from the kmem_cache slab.
3993 * kmem_cache_node is separately allocated so no need to
3994 * update any list pointers.
3996 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
3998 /* Now we can use the kmem_cache to allocate kmalloc slabs */
3999 setup_kmalloc_cache_index_table();
4000 create_kmalloc_caches(0);
4003 register_cpu_notifier(&slab_notifier);
4006 pr_info("SLUB: HWalign=%d, Order=%d-%d, MinObjects=%d, CPUs=%d, Nodes=%d\n",
4008 slub_min_order, slub_max_order, slub_min_objects,
4009 nr_cpu_ids, nr_node_ids);
4012 void __init kmem_cache_init_late(void)
4017 __kmem_cache_alias(const char *name, size_t size, size_t align,
4018 unsigned long flags, void (*ctor)(void *))
4020 struct kmem_cache *s, *c;
4022 s = find_mergeable(size, align, flags, name, ctor);
4027 * Adjust the object sizes so that we clear
4028 * the complete object on kzalloc.
4030 s->object_size = max(s->object_size, (int)size);
4031 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
4033 for_each_memcg_cache(c, s) {
4034 c->object_size = s->object_size;
4035 c->inuse = max_t(int, c->inuse,
4036 ALIGN(size, sizeof(void *)));
4039 if (sysfs_slab_alias(s, name)) {
4048 int __kmem_cache_create(struct kmem_cache *s, unsigned long flags)
4052 err = kmem_cache_open(s, flags);
4056 /* Mutex is not taken during early boot */
4057 if (slab_state <= UP)
4060 memcg_propagate_slab_attrs(s);
4061 err = sysfs_slab_add(s);
4063 kmem_cache_close(s);
4070 * Use the cpu notifier to insure that the cpu slabs are flushed when
4073 static int slab_cpuup_callback(struct notifier_block *nfb,
4074 unsigned long action, void *hcpu)
4076 long cpu = (long)hcpu;
4077 struct kmem_cache *s;
4078 unsigned long flags;
4081 case CPU_UP_CANCELED:
4082 case CPU_UP_CANCELED_FROZEN:
4084 case CPU_DEAD_FROZEN:
4085 mutex_lock(&slab_mutex);
4086 list_for_each_entry(s, &slab_caches, list) {
4087 local_irq_save(flags);
4088 __flush_cpu_slab(s, cpu);
4089 local_irq_restore(flags);
4091 mutex_unlock(&slab_mutex);
4099 static struct notifier_block slab_notifier = {
4100 .notifier_call = slab_cpuup_callback
4105 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4107 struct kmem_cache *s;
4110 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4111 return kmalloc_large(size, gfpflags);
4113 s = kmalloc_slab(size, gfpflags);
4115 if (unlikely(ZERO_OR_NULL_PTR(s)))
4118 ret = slab_alloc(s, gfpflags, caller);
4120 /* Honor the call site pointer we received. */
4121 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4127 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4128 int node, unsigned long caller)
4130 struct kmem_cache *s;
4133 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4134 ret = kmalloc_large_node(size, gfpflags, node);
4136 trace_kmalloc_node(caller, ret,
4137 size, PAGE_SIZE << get_order(size),
4143 s = kmalloc_slab(size, gfpflags);
4145 if (unlikely(ZERO_OR_NULL_PTR(s)))
4148 ret = slab_alloc_node(s, gfpflags, node, caller);
4150 /* Honor the call site pointer we received. */
4151 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4158 static int count_inuse(struct page *page)
4163 static int count_total(struct page *page)
4165 return page->objects;
4169 #ifdef CONFIG_SLUB_DEBUG
4170 static int validate_slab(struct kmem_cache *s, struct page *page,
4174 void *addr = page_address(page);
4176 if (!check_slab(s, page) ||
4177 !on_freelist(s, page, NULL))
4180 /* Now we know that a valid freelist exists */
4181 bitmap_zero(map, page->objects);
4183 get_map(s, page, map);
4184 for_each_object(p, s, addr, page->objects) {
4185 if (test_bit(slab_index(p, s, addr), map))
4186 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4190 for_each_object(p, s, addr, page->objects)
4191 if (!test_bit(slab_index(p, s, addr), map))
4192 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4197 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4201 validate_slab(s, page, map);
4205 static int validate_slab_node(struct kmem_cache *s,
4206 struct kmem_cache_node *n, unsigned long *map)
4208 unsigned long count = 0;
4210 unsigned long flags;
4212 spin_lock_irqsave(&n->list_lock, flags);
4214 list_for_each_entry(page, &n->partial, lru) {
4215 validate_slab_slab(s, page, map);
4218 if (count != n->nr_partial)
4219 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4220 s->name, count, n->nr_partial);
4222 if (!(s->flags & SLAB_STORE_USER))
4225 list_for_each_entry(page, &n->full, lru) {
4226 validate_slab_slab(s, page, map);
4229 if (count != atomic_long_read(&n->nr_slabs))
4230 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4231 s->name, count, atomic_long_read(&n->nr_slabs));
4234 spin_unlock_irqrestore(&n->list_lock, flags);
4238 static long validate_slab_cache(struct kmem_cache *s)
4241 unsigned long count = 0;
4242 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4243 sizeof(unsigned long), GFP_KERNEL);
4244 struct kmem_cache_node *n;
4250 for_each_kmem_cache_node(s, node, n)
4251 count += validate_slab_node(s, n, map);
4256 * Generate lists of code addresses where slabcache objects are allocated
4261 unsigned long count;
4268 DECLARE_BITMAP(cpus, NR_CPUS);
4274 unsigned long count;
4275 struct location *loc;
4278 static void free_loc_track(struct loc_track *t)
4281 free_pages((unsigned long)t->loc,
4282 get_order(sizeof(struct location) * t->max));
4285 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4290 order = get_order(sizeof(struct location) * max);
4292 l = (void *)__get_free_pages(flags, order);
4297 memcpy(l, t->loc, sizeof(struct location) * t->count);
4305 static int add_location(struct loc_track *t, struct kmem_cache *s,
4306 const struct track *track)
4308 long start, end, pos;
4310 unsigned long caddr;
4311 unsigned long age = jiffies - track->when;
4317 pos = start + (end - start + 1) / 2;
4320 * There is nothing at "end". If we end up there
4321 * we need to add something to before end.
4326 caddr = t->loc[pos].addr;
4327 if (track->addr == caddr) {
4333 if (age < l->min_time)
4335 if (age > l->max_time)
4338 if (track->pid < l->min_pid)
4339 l->min_pid = track->pid;
4340 if (track->pid > l->max_pid)
4341 l->max_pid = track->pid;
4343 cpumask_set_cpu(track->cpu,
4344 to_cpumask(l->cpus));
4346 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4350 if (track->addr < caddr)
4357 * Not found. Insert new tracking element.
4359 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4365 (t->count - pos) * sizeof(struct location));
4368 l->addr = track->addr;
4372 l->min_pid = track->pid;
4373 l->max_pid = track->pid;
4374 cpumask_clear(to_cpumask(l->cpus));
4375 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4376 nodes_clear(l->nodes);
4377 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4381 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4382 struct page *page, enum track_item alloc,
4385 void *addr = page_address(page);
4388 bitmap_zero(map, page->objects);
4389 get_map(s, page, map);
4391 for_each_object(p, s, addr, page->objects)
4392 if (!test_bit(slab_index(p, s, addr), map))
4393 add_location(t, s, get_track(s, p, alloc));
4396 static int list_locations(struct kmem_cache *s, char *buf,
4397 enum track_item alloc)
4401 struct loc_track t = { 0, 0, NULL };
4403 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4404 sizeof(unsigned long), GFP_KERNEL);
4405 struct kmem_cache_node *n;
4407 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4410 return sprintf(buf, "Out of memory\n");
4412 /* Push back cpu slabs */
4415 for_each_kmem_cache_node(s, node, n) {
4416 unsigned long flags;
4419 if (!atomic_long_read(&n->nr_slabs))
4422 spin_lock_irqsave(&n->list_lock, flags);
4423 list_for_each_entry(page, &n->partial, lru)
4424 process_slab(&t, s, page, alloc, map);
4425 list_for_each_entry(page, &n->full, lru)
4426 process_slab(&t, s, page, alloc, map);
4427 spin_unlock_irqrestore(&n->list_lock, flags);
4430 for (i = 0; i < t.count; i++) {
4431 struct location *l = &t.loc[i];
4433 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4435 len += sprintf(buf + len, "%7ld ", l->count);
4438 len += sprintf(buf + len, "%pS", (void *)l->addr);
4440 len += sprintf(buf + len, "<not-available>");
4442 if (l->sum_time != l->min_time) {
4443 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4445 (long)div_u64(l->sum_time, l->count),
4448 len += sprintf(buf + len, " age=%ld",
4451 if (l->min_pid != l->max_pid)
4452 len += sprintf(buf + len, " pid=%ld-%ld",
4453 l->min_pid, l->max_pid);
4455 len += sprintf(buf + len, " pid=%ld",
4458 if (num_online_cpus() > 1 &&
4459 !cpumask_empty(to_cpumask(l->cpus)) &&
4460 len < PAGE_SIZE - 60)
4461 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4463 cpumask_pr_args(to_cpumask(l->cpus)));
4465 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4466 len < PAGE_SIZE - 60)
4467 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4469 nodemask_pr_args(&l->nodes));
4471 len += sprintf(buf + len, "\n");
4477 len += sprintf(buf, "No data\n");
4482 #ifdef SLUB_RESILIENCY_TEST
4483 static void __init resiliency_test(void)
4487 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4489 pr_err("SLUB resiliency testing\n");
4490 pr_err("-----------------------\n");
4491 pr_err("A. Corruption after allocation\n");
4493 p = kzalloc(16, GFP_KERNEL);
4495 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4498 validate_slab_cache(kmalloc_caches[4]);
4500 /* Hmmm... The next two are dangerous */
4501 p = kzalloc(32, GFP_KERNEL);
4502 p[32 + sizeof(void *)] = 0x34;
4503 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4505 pr_err("If allocated object is overwritten then not detectable\n\n");
4507 validate_slab_cache(kmalloc_caches[5]);
4508 p = kzalloc(64, GFP_KERNEL);
4509 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4511 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4513 pr_err("If allocated object is overwritten then not detectable\n\n");
4514 validate_slab_cache(kmalloc_caches[6]);
4516 pr_err("\nB. Corruption after free\n");
4517 p = kzalloc(128, GFP_KERNEL);
4520 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4521 validate_slab_cache(kmalloc_caches[7]);
4523 p = kzalloc(256, GFP_KERNEL);
4526 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4527 validate_slab_cache(kmalloc_caches[8]);
4529 p = kzalloc(512, GFP_KERNEL);
4532 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4533 validate_slab_cache(kmalloc_caches[9]);
4537 static void resiliency_test(void) {};
4542 enum slab_stat_type {
4543 SL_ALL, /* All slabs */
4544 SL_PARTIAL, /* Only partially allocated slabs */
4545 SL_CPU, /* Only slabs used for cpu caches */
4546 SL_OBJECTS, /* Determine allocated objects not slabs */
4547 SL_TOTAL /* Determine object capacity not slabs */
4550 #define SO_ALL (1 << SL_ALL)
4551 #define SO_PARTIAL (1 << SL_PARTIAL)
4552 #define SO_CPU (1 << SL_CPU)
4553 #define SO_OBJECTS (1 << SL_OBJECTS)
4554 #define SO_TOTAL (1 << SL_TOTAL)
4556 static ssize_t show_slab_objects(struct kmem_cache *s,
4557 char *buf, unsigned long flags)
4559 unsigned long total = 0;
4562 unsigned long *nodes;
4564 nodes = kzalloc(sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
4568 if (flags & SO_CPU) {
4571 for_each_possible_cpu(cpu) {
4572 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4577 page = READ_ONCE(c->page);
4581 node = page_to_nid(page);
4582 if (flags & SO_TOTAL)
4584 else if (flags & SO_OBJECTS)
4592 page = READ_ONCE(c->partial);
4594 node = page_to_nid(page);
4595 if (flags & SO_TOTAL)
4597 else if (flags & SO_OBJECTS)
4608 #ifdef CONFIG_SLUB_DEBUG
4609 if (flags & SO_ALL) {
4610 struct kmem_cache_node *n;
4612 for_each_kmem_cache_node(s, node, n) {
4614 if (flags & SO_TOTAL)
4615 x = atomic_long_read(&n->total_objects);
4616 else if (flags & SO_OBJECTS)
4617 x = atomic_long_read(&n->total_objects) -
4618 count_partial(n, count_free);
4620 x = atomic_long_read(&n->nr_slabs);
4627 if (flags & SO_PARTIAL) {
4628 struct kmem_cache_node *n;
4630 for_each_kmem_cache_node(s, node, n) {
4631 if (flags & SO_TOTAL)
4632 x = count_partial(n, count_total);
4633 else if (flags & SO_OBJECTS)
4634 x = count_partial(n, count_inuse);
4641 x = sprintf(buf, "%lu", total);
4643 for (node = 0; node < nr_node_ids; node++)
4645 x += sprintf(buf + x, " N%d=%lu",
4650 return x + sprintf(buf + x, "\n");
4653 #ifdef CONFIG_SLUB_DEBUG
4654 static int any_slab_objects(struct kmem_cache *s)
4657 struct kmem_cache_node *n;
4659 for_each_kmem_cache_node(s, node, n)
4660 if (atomic_long_read(&n->total_objects))
4667 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4668 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4670 struct slab_attribute {
4671 struct attribute attr;
4672 ssize_t (*show)(struct kmem_cache *s, char *buf);
4673 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4676 #define SLAB_ATTR_RO(_name) \
4677 static struct slab_attribute _name##_attr = \
4678 __ATTR(_name, 0400, _name##_show, NULL)
4680 #define SLAB_ATTR(_name) \
4681 static struct slab_attribute _name##_attr = \
4682 __ATTR(_name, 0600, _name##_show, _name##_store)
4684 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4686 return sprintf(buf, "%d\n", s->size);
4688 SLAB_ATTR_RO(slab_size);
4690 static ssize_t align_show(struct kmem_cache *s, char *buf)
4692 return sprintf(buf, "%d\n", s->align);
4694 SLAB_ATTR_RO(align);
4696 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
4698 return sprintf(buf, "%d\n", s->object_size);
4700 SLAB_ATTR_RO(object_size);
4702 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
4704 return sprintf(buf, "%d\n", oo_objects(s->oo));
4706 SLAB_ATTR_RO(objs_per_slab);
4708 static ssize_t order_store(struct kmem_cache *s,
4709 const char *buf, size_t length)
4711 unsigned long order;
4714 err = kstrtoul(buf, 10, &order);
4718 if (order > slub_max_order || order < slub_min_order)
4721 calculate_sizes(s, order);
4725 static ssize_t order_show(struct kmem_cache *s, char *buf)
4727 return sprintf(buf, "%d\n", oo_order(s->oo));
4731 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
4733 return sprintf(buf, "%lu\n", s->min_partial);
4736 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
4742 err = kstrtoul(buf, 10, &min);
4746 set_min_partial(s, min);
4749 SLAB_ATTR(min_partial);
4751 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
4753 return sprintf(buf, "%u\n", s->cpu_partial);
4756 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
4759 unsigned long objects;
4762 err = kstrtoul(buf, 10, &objects);
4765 if (objects && !kmem_cache_has_cpu_partial(s))
4768 s->cpu_partial = objects;
4772 SLAB_ATTR(cpu_partial);
4774 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
4778 return sprintf(buf, "%pS\n", s->ctor);
4782 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
4784 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
4786 SLAB_ATTR_RO(aliases);
4788 static ssize_t partial_show(struct kmem_cache *s, char *buf)
4790 return show_slab_objects(s, buf, SO_PARTIAL);
4792 SLAB_ATTR_RO(partial);
4794 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
4796 return show_slab_objects(s, buf, SO_CPU);
4798 SLAB_ATTR_RO(cpu_slabs);
4800 static ssize_t objects_show(struct kmem_cache *s, char *buf)
4802 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
4804 SLAB_ATTR_RO(objects);
4806 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
4808 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
4810 SLAB_ATTR_RO(objects_partial);
4812 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
4819 for_each_online_cpu(cpu) {
4820 struct page *page = per_cpu_ptr(s->cpu_slab, cpu)->partial;
4823 pages += page->pages;
4824 objects += page->pobjects;
4828 len = sprintf(buf, "%d(%d)", objects, pages);
4831 for_each_online_cpu(cpu) {
4832 struct page *page = per_cpu_ptr(s->cpu_slab, cpu) ->partial;
4834 if (page && len < PAGE_SIZE - 20)
4835 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
4836 page->pobjects, page->pages);
4839 return len + sprintf(buf + len, "\n");
4841 SLAB_ATTR_RO(slabs_cpu_partial);
4843 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
4845 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
4848 static ssize_t reclaim_account_store(struct kmem_cache *s,
4849 const char *buf, size_t length)
4851 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
4853 s->flags |= SLAB_RECLAIM_ACCOUNT;
4856 SLAB_ATTR(reclaim_account);
4858 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
4860 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
4862 SLAB_ATTR_RO(hwcache_align);
4864 #ifdef CONFIG_ZONE_DMA
4865 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
4867 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
4869 SLAB_ATTR_RO(cache_dma);
4872 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
4874 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
4876 SLAB_ATTR_RO(destroy_by_rcu);
4878 static ssize_t reserved_show(struct kmem_cache *s, char *buf)
4880 return sprintf(buf, "%d\n", s->reserved);
4882 SLAB_ATTR_RO(reserved);
4884 #ifdef CONFIG_SLUB_DEBUG
4885 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
4887 return show_slab_objects(s, buf, SO_ALL);
4889 SLAB_ATTR_RO(slabs);
4891 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
4893 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
4895 SLAB_ATTR_RO(total_objects);
4897 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
4899 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
4902 static ssize_t sanity_checks_store(struct kmem_cache *s,
4903 const char *buf, size_t length)
4905 s->flags &= ~SLAB_DEBUG_FREE;
4906 if (buf[0] == '1') {
4907 s->flags &= ~__CMPXCHG_DOUBLE;
4908 s->flags |= SLAB_DEBUG_FREE;
4912 SLAB_ATTR(sanity_checks);
4914 static ssize_t trace_show(struct kmem_cache *s, char *buf)
4916 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
4919 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
4923 * Tracing a merged cache is going to give confusing results
4924 * as well as cause other issues like converting a mergeable
4925 * cache into an umergeable one.
4927 if (s->refcount > 1)
4930 s->flags &= ~SLAB_TRACE;
4931 if (buf[0] == '1') {
4932 s->flags &= ~__CMPXCHG_DOUBLE;
4933 s->flags |= SLAB_TRACE;
4939 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
4941 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
4944 static ssize_t red_zone_store(struct kmem_cache *s,
4945 const char *buf, size_t length)
4947 if (any_slab_objects(s))
4950 s->flags &= ~SLAB_RED_ZONE;
4951 if (buf[0] == '1') {
4952 s->flags &= ~__CMPXCHG_DOUBLE;
4953 s->flags |= SLAB_RED_ZONE;
4955 calculate_sizes(s, -1);
4958 SLAB_ATTR(red_zone);
4960 static ssize_t poison_show(struct kmem_cache *s, char *buf)
4962 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
4965 static ssize_t poison_store(struct kmem_cache *s,
4966 const char *buf, size_t length)
4968 if (any_slab_objects(s))
4971 s->flags &= ~SLAB_POISON;
4972 if (buf[0] == '1') {
4973 s->flags &= ~__CMPXCHG_DOUBLE;
4974 s->flags |= SLAB_POISON;
4976 calculate_sizes(s, -1);
4981 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
4983 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
4986 static ssize_t store_user_store(struct kmem_cache *s,
4987 const char *buf, size_t length)
4989 if (any_slab_objects(s))
4992 s->flags &= ~SLAB_STORE_USER;
4993 if (buf[0] == '1') {
4994 s->flags &= ~__CMPXCHG_DOUBLE;
4995 s->flags |= SLAB_STORE_USER;
4997 calculate_sizes(s, -1);
5000 SLAB_ATTR(store_user);
5002 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5007 static ssize_t validate_store(struct kmem_cache *s,
5008 const char *buf, size_t length)
5012 if (buf[0] == '1') {
5013 ret = validate_slab_cache(s);
5019 SLAB_ATTR(validate);
5021 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5023 if (!(s->flags & SLAB_STORE_USER))
5025 return list_locations(s, buf, TRACK_ALLOC);
5027 SLAB_ATTR_RO(alloc_calls);
5029 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5031 if (!(s->flags & SLAB_STORE_USER))
5033 return list_locations(s, buf, TRACK_FREE);
5035 SLAB_ATTR_RO(free_calls);
5036 #endif /* CONFIG_SLUB_DEBUG */
5038 #ifdef CONFIG_FAILSLAB
5039 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5041 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5044 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5047 if (s->refcount > 1)
5050 s->flags &= ~SLAB_FAILSLAB;
5052 s->flags |= SLAB_FAILSLAB;
5055 SLAB_ATTR(failslab);
5058 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5063 static ssize_t shrink_store(struct kmem_cache *s,
5064 const char *buf, size_t length)
5067 kmem_cache_shrink(s);
5075 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5077 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
5080 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5081 const char *buf, size_t length)
5083 unsigned long ratio;
5086 err = kstrtoul(buf, 10, &ratio);
5091 s->remote_node_defrag_ratio = ratio * 10;
5095 SLAB_ATTR(remote_node_defrag_ratio);
5098 #ifdef CONFIG_SLUB_STATS
5099 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5101 unsigned long sum = 0;
5104 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
5109 for_each_online_cpu(cpu) {
5110 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5116 len = sprintf(buf, "%lu", sum);
5119 for_each_online_cpu(cpu) {
5120 if (data[cpu] && len < PAGE_SIZE - 20)
5121 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5125 return len + sprintf(buf + len, "\n");
5128 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5132 for_each_online_cpu(cpu)
5133 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5136 #define STAT_ATTR(si, text) \
5137 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5139 return show_stat(s, buf, si); \
5141 static ssize_t text##_store(struct kmem_cache *s, \
5142 const char *buf, size_t length) \
5144 if (buf[0] != '0') \
5146 clear_stat(s, si); \
5151 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5152 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5153 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5154 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5155 STAT_ATTR(FREE_FROZEN, free_frozen);
5156 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5157 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5158 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5159 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5160 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5161 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5162 STAT_ATTR(FREE_SLAB, free_slab);
5163 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5164 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5165 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5166 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5167 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5168 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5169 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5170 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5171 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5172 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5173 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5174 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5175 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5176 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5179 static struct attribute *slab_attrs[] = {
5180 &slab_size_attr.attr,
5181 &object_size_attr.attr,
5182 &objs_per_slab_attr.attr,
5184 &min_partial_attr.attr,
5185 &cpu_partial_attr.attr,
5187 &objects_partial_attr.attr,
5189 &cpu_slabs_attr.attr,
5193 &hwcache_align_attr.attr,
5194 &reclaim_account_attr.attr,
5195 &destroy_by_rcu_attr.attr,
5197 &reserved_attr.attr,
5198 &slabs_cpu_partial_attr.attr,
5199 #ifdef CONFIG_SLUB_DEBUG
5200 &total_objects_attr.attr,
5202 &sanity_checks_attr.attr,
5204 &red_zone_attr.attr,
5206 &store_user_attr.attr,
5207 &validate_attr.attr,
5208 &alloc_calls_attr.attr,
5209 &free_calls_attr.attr,
5211 #ifdef CONFIG_ZONE_DMA
5212 &cache_dma_attr.attr,
5215 &remote_node_defrag_ratio_attr.attr,
5217 #ifdef CONFIG_SLUB_STATS
5218 &alloc_fastpath_attr.attr,
5219 &alloc_slowpath_attr.attr,
5220 &free_fastpath_attr.attr,
5221 &free_slowpath_attr.attr,
5222 &free_frozen_attr.attr,
5223 &free_add_partial_attr.attr,
5224 &free_remove_partial_attr.attr,
5225 &alloc_from_partial_attr.attr,
5226 &alloc_slab_attr.attr,
5227 &alloc_refill_attr.attr,
5228 &alloc_node_mismatch_attr.attr,
5229 &free_slab_attr.attr,
5230 &cpuslab_flush_attr.attr,
5231 &deactivate_full_attr.attr,
5232 &deactivate_empty_attr.attr,
5233 &deactivate_to_head_attr.attr,
5234 &deactivate_to_tail_attr.attr,
5235 &deactivate_remote_frees_attr.attr,
5236 &deactivate_bypass_attr.attr,
5237 &order_fallback_attr.attr,
5238 &cmpxchg_double_fail_attr.attr,
5239 &cmpxchg_double_cpu_fail_attr.attr,
5240 &cpu_partial_alloc_attr.attr,
5241 &cpu_partial_free_attr.attr,
5242 &cpu_partial_node_attr.attr,
5243 &cpu_partial_drain_attr.attr,
5245 #ifdef CONFIG_FAILSLAB
5246 &failslab_attr.attr,
5252 static struct attribute_group slab_attr_group = {
5253 .attrs = slab_attrs,
5256 static ssize_t slab_attr_show(struct kobject *kobj,
5257 struct attribute *attr,
5260 struct slab_attribute *attribute;
5261 struct kmem_cache *s;
5264 attribute = to_slab_attr(attr);
5267 if (!attribute->show)
5270 err = attribute->show(s, buf);
5275 static ssize_t slab_attr_store(struct kobject *kobj,
5276 struct attribute *attr,
5277 const char *buf, size_t len)
5279 struct slab_attribute *attribute;
5280 struct kmem_cache *s;
5283 attribute = to_slab_attr(attr);
5286 if (!attribute->store)
5289 err = attribute->store(s, buf, len);
5290 #ifdef CONFIG_MEMCG_KMEM
5291 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5292 struct kmem_cache *c;
5294 mutex_lock(&slab_mutex);
5295 if (s->max_attr_size < len)
5296 s->max_attr_size = len;
5299 * This is a best effort propagation, so this function's return
5300 * value will be determined by the parent cache only. This is
5301 * basically because not all attributes will have a well
5302 * defined semantics for rollbacks - most of the actions will
5303 * have permanent effects.
5305 * Returning the error value of any of the children that fail
5306 * is not 100 % defined, in the sense that users seeing the
5307 * error code won't be able to know anything about the state of
5310 * Only returning the error code for the parent cache at least
5311 * has well defined semantics. The cache being written to
5312 * directly either failed or succeeded, in which case we loop
5313 * through the descendants with best-effort propagation.
5315 for_each_memcg_cache(c, s)
5316 attribute->store(c, buf, len);
5317 mutex_unlock(&slab_mutex);
5323 static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5325 #ifdef CONFIG_MEMCG_KMEM
5327 char *buffer = NULL;
5328 struct kmem_cache *root_cache;
5330 if (is_root_cache(s))
5333 root_cache = s->memcg_params.root_cache;
5336 * This mean this cache had no attribute written. Therefore, no point
5337 * in copying default values around
5339 if (!root_cache->max_attr_size)
5342 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5345 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5347 if (!attr || !attr->store || !attr->show)
5351 * It is really bad that we have to allocate here, so we will
5352 * do it only as a fallback. If we actually allocate, though,
5353 * we can just use the allocated buffer until the end.
5355 * Most of the slub attributes will tend to be very small in
5356 * size, but sysfs allows buffers up to a page, so they can
5357 * theoretically happen.
5361 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf))
5364 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5365 if (WARN_ON(!buffer))
5370 attr->show(root_cache, buf);
5371 attr->store(s, buf, strlen(buf));
5375 free_page((unsigned long)buffer);
5379 static void kmem_cache_release(struct kobject *k)
5381 slab_kmem_cache_release(to_slab(k));
5384 static const struct sysfs_ops slab_sysfs_ops = {
5385 .show = slab_attr_show,
5386 .store = slab_attr_store,
5389 static struct kobj_type slab_ktype = {
5390 .sysfs_ops = &slab_sysfs_ops,
5391 .release = kmem_cache_release,
5394 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5396 struct kobj_type *ktype = get_ktype(kobj);
5398 if (ktype == &slab_ktype)
5403 static const struct kset_uevent_ops slab_uevent_ops = {
5404 .filter = uevent_filter,
5407 static struct kset *slab_kset;
5409 static inline struct kset *cache_kset(struct kmem_cache *s)
5411 #ifdef CONFIG_MEMCG_KMEM
5412 if (!is_root_cache(s))
5413 return s->memcg_params.root_cache->memcg_kset;
5418 #define ID_STR_LENGTH 64
5420 /* Create a unique string id for a slab cache:
5422 * Format :[flags-]size
5424 static char *create_unique_id(struct kmem_cache *s)
5426 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5433 * First flags affecting slabcache operations. We will only
5434 * get here for aliasable slabs so we do not need to support
5435 * too many flags. The flags here must cover all flags that
5436 * are matched during merging to guarantee that the id is
5439 if (s->flags & SLAB_CACHE_DMA)
5441 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5443 if (s->flags & SLAB_DEBUG_FREE)
5445 if (!(s->flags & SLAB_NOTRACK))
5449 p += sprintf(p, "%07d", s->size);
5451 BUG_ON(p > name + ID_STR_LENGTH - 1);
5455 static int sysfs_slab_add(struct kmem_cache *s)
5459 int unmergeable = slab_unmergeable(s);
5463 * Slabcache can never be merged so we can use the name proper.
5464 * This is typically the case for debug situations. In that
5465 * case we can catch duplicate names easily.
5467 sysfs_remove_link(&slab_kset->kobj, s->name);
5471 * Create a unique name for the slab as a target
5474 name = create_unique_id(s);
5477 s->kobj.kset = cache_kset(s);
5478 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5482 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5486 #ifdef CONFIG_MEMCG_KMEM
5487 if (is_root_cache(s)) {
5488 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5489 if (!s->memcg_kset) {
5496 kobject_uevent(&s->kobj, KOBJ_ADD);
5498 /* Setup first alias */
5499 sysfs_slab_alias(s, s->name);
5506 kobject_del(&s->kobj);
5510 void sysfs_slab_remove(struct kmem_cache *s)
5512 if (slab_state < FULL)
5514 * Sysfs has not been setup yet so no need to remove the
5519 #ifdef CONFIG_MEMCG_KMEM
5520 kset_unregister(s->memcg_kset);
5522 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5523 kobject_del(&s->kobj);
5524 kobject_put(&s->kobj);
5528 * Need to buffer aliases during bootup until sysfs becomes
5529 * available lest we lose that information.
5531 struct saved_alias {
5532 struct kmem_cache *s;
5534 struct saved_alias *next;
5537 static struct saved_alias *alias_list;
5539 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5541 struct saved_alias *al;
5543 if (slab_state == FULL) {
5545 * If we have a leftover link then remove it.
5547 sysfs_remove_link(&slab_kset->kobj, name);
5548 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5551 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5557 al->next = alias_list;
5562 static int __init slab_sysfs_init(void)
5564 struct kmem_cache *s;
5567 mutex_lock(&slab_mutex);
5569 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5571 mutex_unlock(&slab_mutex);
5572 pr_err("Cannot register slab subsystem.\n");
5578 list_for_each_entry(s, &slab_caches, list) {
5579 err = sysfs_slab_add(s);
5581 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5585 while (alias_list) {
5586 struct saved_alias *al = alias_list;
5588 alias_list = alias_list->next;
5589 err = sysfs_slab_alias(al->s, al->name);
5591 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5596 mutex_unlock(&slab_mutex);
5601 __initcall(slab_sysfs_init);
5602 #endif /* CONFIG_SYSFS */
5605 * The /proc/slabinfo ABI
5607 #ifdef CONFIG_SLABINFO
5608 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5610 unsigned long nr_slabs = 0;
5611 unsigned long nr_objs = 0;
5612 unsigned long nr_free = 0;
5614 struct kmem_cache_node *n;
5616 for_each_kmem_cache_node(s, node, n) {
5617 nr_slabs += node_nr_slabs(n);
5618 nr_objs += node_nr_objs(n);
5619 nr_free += count_partial(n, count_free);
5622 sinfo->active_objs = nr_objs - nr_free;
5623 sinfo->num_objs = nr_objs;
5624 sinfo->active_slabs = nr_slabs;
5625 sinfo->num_slabs = nr_slabs;
5626 sinfo->objects_per_slab = oo_objects(s->oo);
5627 sinfo->cache_order = oo_order(s->oo);
5630 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5634 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5635 size_t count, loff_t *ppos)
5639 #endif /* CONFIG_SLABINFO */