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;
290 if (s->flags & SLAB_KASAN)
291 return s->object_size;
294 * If we have the need to store the freelist pointer
295 * back there or track user information then we can
296 * only use the space before that information.
298 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
301 * Else we can use all the padding etc for the allocation
306 static inline int order_objects(int order, unsigned long size, int reserved)
308 return ((PAGE_SIZE << order) - reserved) / size;
311 static inline struct kmem_cache_order_objects oo_make(int order,
312 unsigned long size, int reserved)
314 struct kmem_cache_order_objects x = {
315 (order << OO_SHIFT) + order_objects(order, size, reserved)
321 static inline int oo_order(struct kmem_cache_order_objects x)
323 return x.x >> OO_SHIFT;
326 static inline int oo_objects(struct kmem_cache_order_objects x)
328 return x.x & OO_MASK;
332 * Per slab locking using the pagelock
334 static __always_inline void slab_lock(struct page *page)
336 VM_BUG_ON_PAGE(PageTail(page), page);
337 bit_spin_lock(PG_locked, &page->flags);
340 static __always_inline void slab_unlock(struct page *page)
342 VM_BUG_ON_PAGE(PageTail(page), page);
343 __bit_spin_unlock(PG_locked, &page->flags);
346 static inline void set_page_slub_counters(struct page *page, unsigned long counters_new)
349 tmp.counters = counters_new;
351 * page->counters can cover frozen/inuse/objects as well
352 * as page->_count. If we assign to ->counters directly
353 * we run the risk of losing updates to page->_count, so
354 * be careful and only assign to the fields we need.
356 page->frozen = tmp.frozen;
357 page->inuse = tmp.inuse;
358 page->objects = tmp.objects;
361 /* Interrupts must be disabled (for the fallback code to work right) */
362 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
363 void *freelist_old, unsigned long counters_old,
364 void *freelist_new, unsigned long counters_new,
367 VM_BUG_ON(!irqs_disabled());
368 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
369 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
370 if (s->flags & __CMPXCHG_DOUBLE) {
371 if (cmpxchg_double(&page->freelist, &page->counters,
372 freelist_old, counters_old,
373 freelist_new, counters_new))
379 if (page->freelist == freelist_old &&
380 page->counters == counters_old) {
381 page->freelist = freelist_new;
382 set_page_slub_counters(page, counters_new);
390 stat(s, CMPXCHG_DOUBLE_FAIL);
392 #ifdef SLUB_DEBUG_CMPXCHG
393 pr_info("%s %s: cmpxchg double redo ", n, s->name);
399 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
400 void *freelist_old, unsigned long counters_old,
401 void *freelist_new, unsigned long counters_new,
404 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
405 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
406 if (s->flags & __CMPXCHG_DOUBLE) {
407 if (cmpxchg_double(&page->freelist, &page->counters,
408 freelist_old, counters_old,
409 freelist_new, counters_new))
416 local_irq_save(flags);
418 if (page->freelist == freelist_old &&
419 page->counters == counters_old) {
420 page->freelist = freelist_new;
421 set_page_slub_counters(page, counters_new);
423 local_irq_restore(flags);
427 local_irq_restore(flags);
431 stat(s, CMPXCHG_DOUBLE_FAIL);
433 #ifdef SLUB_DEBUG_CMPXCHG
434 pr_info("%s %s: cmpxchg double redo ", n, s->name);
440 #ifdef CONFIG_SLUB_DEBUG
442 * Determine a map of object in use on a page.
444 * Node listlock must be held to guarantee that the page does
445 * not vanish from under us.
447 static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
450 void *addr = page_address(page);
452 for (p = page->freelist; p; p = get_freepointer(s, p))
453 set_bit(slab_index(p, s, addr), map);
456 static inline int size_from_object(struct kmem_cache *s)
458 if (s->flags & SLAB_RED_ZONE)
459 return s->size - s->red_left_pad;
464 static inline void *restore_red_left(struct kmem_cache *s, void *p)
466 if (s->flags & SLAB_RED_ZONE)
467 p -= s->red_left_pad;
475 #if defined(CONFIG_SLUB_DEBUG_ON)
476 static int slub_debug = DEBUG_DEFAULT_FLAGS;
478 static int slub_debug;
481 static char *slub_debug_slabs;
482 static int disable_higher_order_debug;
485 * slub is about to manipulate internal object metadata. This memory lies
486 * outside the range of the allocated object, so accessing it would normally
487 * be reported by kasan as a bounds error. metadata_access_enable() is used
488 * to tell kasan that these accesses are OK.
490 static inline void metadata_access_enable(void)
492 kasan_disable_current();
495 static inline void metadata_access_disable(void)
497 kasan_enable_current();
504 /* Verify that a pointer has an address that is valid within a slab page */
505 static inline int check_valid_pointer(struct kmem_cache *s,
506 struct page *page, void *object)
513 base = page_address(page);
514 object = restore_red_left(s, object);
515 if (object < base || object >= base + page->objects * s->size ||
516 (object - base) % s->size) {
523 static void print_section(char *text, u8 *addr, unsigned int length)
525 metadata_access_enable();
526 print_hex_dump(KERN_ERR, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
528 metadata_access_disable();
531 static struct track *get_track(struct kmem_cache *s, void *object,
532 enum track_item alloc)
537 p = object + s->offset + sizeof(void *);
539 p = object + s->inuse;
544 static void set_track(struct kmem_cache *s, void *object,
545 enum track_item alloc, unsigned long addr)
547 struct track *p = get_track(s, object, alloc);
550 #ifdef CONFIG_STACKTRACE
551 struct stack_trace trace;
554 trace.nr_entries = 0;
555 trace.max_entries = TRACK_ADDRS_COUNT;
556 trace.entries = p->addrs;
558 metadata_access_enable();
559 save_stack_trace(&trace);
560 metadata_access_disable();
562 /* See rant in lockdep.c */
563 if (trace.nr_entries != 0 &&
564 trace.entries[trace.nr_entries - 1] == ULONG_MAX)
567 for (i = trace.nr_entries; i < TRACK_ADDRS_COUNT; i++)
571 p->cpu = smp_processor_id();
572 p->pid = current->pid;
575 memset(p, 0, sizeof(struct track));
578 static void init_tracking(struct kmem_cache *s, void *object)
580 if (!(s->flags & SLAB_STORE_USER))
583 set_track(s, object, TRACK_FREE, 0UL);
584 set_track(s, object, TRACK_ALLOC, 0UL);
587 static void print_track(const char *s, struct track *t)
592 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
593 s, (void *)t->addr, jiffies - t->when, t->cpu, t->pid);
594 #ifdef CONFIG_STACKTRACE
597 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
599 pr_err("\t%pS\n", (void *)t->addrs[i]);
606 static void print_tracking(struct kmem_cache *s, void *object)
608 if (!(s->flags & SLAB_STORE_USER))
611 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
612 print_track("Freed", get_track(s, object, TRACK_FREE));
615 static void print_page_info(struct page *page)
617 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
618 page, page->objects, page->inuse, page->freelist, page->flags);
622 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
624 struct va_format vaf;
630 pr_err("=============================================================================\n");
631 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
632 pr_err("-----------------------------------------------------------------------------\n\n");
634 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
638 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
640 struct va_format vaf;
646 pr_err("FIX %s: %pV\n", s->name, &vaf);
650 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
652 unsigned int off; /* Offset of last byte */
653 u8 *addr = page_address(page);
655 print_tracking(s, p);
657 print_page_info(page);
659 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
660 p, p - addr, get_freepointer(s, p));
662 if (s->flags & SLAB_RED_ZONE)
663 print_section("Redzone ", p - s->red_left_pad, s->red_left_pad);
664 else if (p > addr + 16)
665 print_section("Bytes b4 ", p - 16, 16);
667 print_section("Object ", p, min_t(unsigned long, s->object_size,
669 if (s->flags & SLAB_RED_ZONE)
670 print_section("Redzone ", p + s->object_size,
671 s->inuse - s->object_size);
674 off = s->offset + sizeof(void *);
678 if (s->flags & SLAB_STORE_USER)
679 off += 2 * sizeof(struct track);
681 off += kasan_metadata_size(s);
683 if (off != size_from_object(s))
684 /* Beginning of the filler is the free pointer */
685 print_section("Padding ", p + off, size_from_object(s) - off);
690 #ifdef CONFIG_SLUB_DEBUG_PANIC_ON
691 static void slab_panic(const char *cause)
693 panic("%s\n", cause);
696 static inline void slab_panic(const char *cause) {}
699 void object_err(struct kmem_cache *s, struct page *page,
700 u8 *object, char *reason)
702 slab_bug(s, "%s", reason);
703 print_trailer(s, page, object);
707 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
708 const char *fmt, ...)
714 vsnprintf(buf, sizeof(buf), fmt, args);
716 slab_bug(s, "%s", buf);
717 print_page_info(page);
719 slab_panic("slab error");
722 static void init_object(struct kmem_cache *s, void *object, u8 val)
726 if (s->flags & SLAB_RED_ZONE)
727 memset(p - s->red_left_pad, val, s->red_left_pad);
729 if (s->flags & __OBJECT_POISON) {
730 memset(p, POISON_FREE, s->object_size - 1);
731 p[s->object_size - 1] = POISON_END;
734 if (s->flags & SLAB_RED_ZONE)
735 memset(p + s->object_size, val, s->inuse - s->object_size);
738 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
739 void *from, void *to)
741 slab_panic("object poison overwritten");
742 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
743 memset(from, data, to - from);
746 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
747 u8 *object, char *what,
748 u8 *start, unsigned int value, unsigned int bytes)
753 metadata_access_enable();
754 fault = memchr_inv(start, value, bytes);
755 metadata_access_disable();
760 while (end > fault && end[-1] == value)
763 slab_bug(s, "%s overwritten", what);
764 pr_err("INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
765 fault, end - 1, fault[0], value);
766 print_trailer(s, page, object);
768 restore_bytes(s, what, value, fault, end);
776 * Bytes of the object to be managed.
777 * If the freepointer may overlay the object then the free
778 * pointer is the first word of the object.
780 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
783 * object + s->object_size
784 * Padding to reach word boundary. This is also used for Redzoning.
785 * Padding is extended by another word if Redzoning is enabled and
786 * object_size == inuse.
788 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
789 * 0xcc (RED_ACTIVE) for objects in use.
792 * Meta data starts here.
794 * A. Free pointer (if we cannot overwrite object on free)
795 * B. Tracking data for SLAB_STORE_USER
796 * C. Padding to reach required alignment boundary or at mininum
797 * one word if debugging is on to be able to detect writes
798 * before the word boundary.
800 * Padding is done using 0x5a (POISON_INUSE)
803 * Nothing is used beyond s->size.
805 * If slabcaches are merged then the object_size and inuse boundaries are mostly
806 * ignored. And therefore no slab options that rely on these boundaries
807 * may be used with merged slabcaches.
810 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
812 unsigned long off = s->inuse; /* The end of info */
815 /* Freepointer is placed after the object. */
816 off += sizeof(void *);
818 if (s->flags & SLAB_STORE_USER)
819 /* We also have user information there */
820 off += 2 * sizeof(struct track);
822 off += kasan_metadata_size(s);
824 if (size_from_object(s) == off)
827 return check_bytes_and_report(s, page, p, "Object padding",
828 p + off, POISON_INUSE, size_from_object(s) - off);
831 /* Check the pad bytes at the end of a slab page */
832 static int slab_pad_check(struct kmem_cache *s, struct page *page)
840 if (!(s->flags & SLAB_POISON))
843 start = page_address(page);
844 length = (PAGE_SIZE << compound_order(page)) - s->reserved;
845 end = start + length;
846 remainder = length % s->size;
850 metadata_access_enable();
851 fault = memchr_inv(end - remainder, POISON_INUSE, remainder);
852 metadata_access_disable();
855 while (end > fault && end[-1] == POISON_INUSE)
858 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
859 print_section("Padding ", end - remainder, remainder);
861 restore_bytes(s, "slab padding", POISON_INUSE, end - remainder, end);
865 static int check_object(struct kmem_cache *s, struct page *page,
866 void *object, u8 val)
869 u8 *endobject = object + s->object_size;
871 if (s->flags & SLAB_RED_ZONE) {
872 if (!check_bytes_and_report(s, page, object, "Redzone",
873 object - s->red_left_pad, val, s->red_left_pad))
876 if (!check_bytes_and_report(s, page, object, "Redzone",
877 endobject, val, s->inuse - s->object_size))
880 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
881 check_bytes_and_report(s, page, p, "Alignment padding",
882 endobject, POISON_INUSE,
883 s->inuse - s->object_size);
887 if (s->flags & SLAB_POISON) {
888 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
889 (!check_bytes_and_report(s, page, p, "Poison", p,
890 POISON_FREE, s->object_size - 1) ||
891 !check_bytes_and_report(s, page, p, "Poison",
892 p + s->object_size - 1, POISON_END, 1)))
895 * check_pad_bytes cleans up on its own.
897 check_pad_bytes(s, page, p);
900 if (!s->offset && val == SLUB_RED_ACTIVE)
902 * Object and freepointer overlap. Cannot check
903 * freepointer while object is allocated.
907 /* Check free pointer validity */
908 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
909 object_err(s, page, p, "Freepointer corrupt");
911 * No choice but to zap it and thus lose the remainder
912 * of the free objects in this slab. May cause
913 * another error because the object count is now wrong.
915 set_freepointer(s, p, NULL);
921 static int check_slab(struct kmem_cache *s, struct page *page)
925 VM_BUG_ON(!irqs_disabled());
927 if (!PageSlab(page)) {
928 slab_err(s, page, "Not a valid slab page");
932 maxobj = order_objects(compound_order(page), s->size, s->reserved);
933 if (page->objects > maxobj) {
934 slab_err(s, page, "objects %u > max %u",
935 page->objects, maxobj);
938 if (page->inuse > page->objects) {
939 slab_err(s, page, "inuse %u > max %u",
940 page->inuse, page->objects);
943 /* Slab_pad_check fixes things up after itself */
944 slab_pad_check(s, page);
949 * Determine if a certain object on a page is on the freelist. Must hold the
950 * slab lock to guarantee that the chains are in a consistent state.
952 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
960 while (fp && nr <= page->objects) {
963 if (!check_valid_pointer(s, page, fp)) {
965 object_err(s, page, object,
966 "Freechain corrupt");
967 set_freepointer(s, object, NULL);
969 slab_err(s, page, "Freepointer corrupt");
970 page->freelist = NULL;
971 page->inuse = page->objects;
972 slab_fix(s, "Freelist cleared");
978 fp = get_freepointer(s, object);
982 max_objects = order_objects(compound_order(page), s->size, s->reserved);
983 if (max_objects > MAX_OBJS_PER_PAGE)
984 max_objects = MAX_OBJS_PER_PAGE;
986 if (page->objects != max_objects) {
987 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
988 page->objects, max_objects);
989 page->objects = max_objects;
990 slab_fix(s, "Number of objects adjusted.");
992 if (page->inuse != page->objects - nr) {
993 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
994 page->inuse, page->objects - nr);
995 page->inuse = page->objects - nr;
996 slab_fix(s, "Object count adjusted.");
998 return search == NULL;
1001 static void trace(struct kmem_cache *s, struct page *page, void *object,
1004 if (s->flags & SLAB_TRACE) {
1005 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1007 alloc ? "alloc" : "free",
1008 object, page->inuse,
1012 print_section("Object ", (void *)object,
1020 * Tracking of fully allocated slabs for debugging purposes.
1022 static void add_full(struct kmem_cache *s,
1023 struct kmem_cache_node *n, struct page *page)
1025 if (!(s->flags & SLAB_STORE_USER))
1028 lockdep_assert_held(&n->list_lock);
1029 list_add(&page->lru, &n->full);
1032 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1034 if (!(s->flags & SLAB_STORE_USER))
1037 lockdep_assert_held(&n->list_lock);
1038 list_del(&page->lru);
1041 /* Tracking of the number of slabs for debugging purposes */
1042 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1044 struct kmem_cache_node *n = get_node(s, node);
1046 return atomic_long_read(&n->nr_slabs);
1049 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1051 return atomic_long_read(&n->nr_slabs);
1054 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1056 struct kmem_cache_node *n = get_node(s, node);
1059 * May be called early in order to allocate a slab for the
1060 * kmem_cache_node structure. Solve the chicken-egg
1061 * dilemma by deferring the increment of the count during
1062 * bootstrap (see early_kmem_cache_node_alloc).
1065 atomic_long_inc(&n->nr_slabs);
1066 atomic_long_add(objects, &n->total_objects);
1069 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1071 struct kmem_cache_node *n = get_node(s, node);
1073 atomic_long_dec(&n->nr_slabs);
1074 atomic_long_sub(objects, &n->total_objects);
1077 /* Object debug checks for alloc/free paths */
1078 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1081 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1084 init_object(s, object, SLUB_RED_INACTIVE);
1085 init_tracking(s, object);
1088 static noinline int alloc_debug_processing(struct kmem_cache *s,
1090 void *object, unsigned long addr)
1092 if (!check_slab(s, page))
1095 if (!check_valid_pointer(s, page, object)) {
1096 object_err(s, page, object, "Freelist Pointer check fails");
1100 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1103 /* Success perform special debug activities for allocs */
1104 if (s->flags & SLAB_STORE_USER)
1105 set_track(s, object, TRACK_ALLOC, addr);
1106 trace(s, page, object, 1);
1107 init_object(s, object, SLUB_RED_ACTIVE);
1111 if (PageSlab(page)) {
1113 * If this is a slab page then lets do the best we can
1114 * to avoid issues in the future. Marking all objects
1115 * as used avoids touching the remaining objects.
1117 slab_fix(s, "Marking all objects used");
1118 page->inuse = page->objects;
1119 page->freelist = NULL;
1124 /* Supports checking bulk free of a constructed freelist */
1125 static noinline struct kmem_cache_node *free_debug_processing(
1126 struct kmem_cache *s, struct page *page,
1127 void *head, void *tail, int bulk_cnt,
1128 unsigned long addr, unsigned long *flags)
1130 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1131 void *object = head;
1134 spin_lock_irqsave(&n->list_lock, *flags);
1137 if (!check_slab(s, page))
1143 if (!check_valid_pointer(s, page, object)) {
1144 slab_err(s, page, "Invalid object pointer 0x%p", object);
1148 if (on_freelist(s, page, object)) {
1149 object_err(s, page, object, "Object already free");
1153 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1156 if (unlikely(s != page->slab_cache)) {
1157 if (!PageSlab(page)) {
1158 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1160 } else if (!page->slab_cache) {
1161 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1165 object_err(s, page, object,
1166 "page slab pointer corrupt.");
1170 if (s->flags & SLAB_STORE_USER)
1171 set_track(s, object, TRACK_FREE, addr);
1172 trace(s, page, object, 0);
1173 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1174 init_object(s, object, SLUB_RED_INACTIVE);
1176 /* Reached end of constructed freelist yet? */
1177 if (object != tail) {
1178 object = get_freepointer(s, object);
1182 if (cnt != bulk_cnt)
1183 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1188 * Keep node_lock to preserve integrity
1189 * until the object is actually freed
1195 spin_unlock_irqrestore(&n->list_lock, *flags);
1196 slab_fix(s, "Object at 0x%p not freed", object);
1200 static int __init setup_slub_debug(char *str)
1202 slub_debug = DEBUG_DEFAULT_FLAGS;
1203 if (*str++ != '=' || !*str)
1205 * No options specified. Switch on full debugging.
1211 * No options but restriction on slabs. This means full
1212 * debugging for slabs matching a pattern.
1219 * Switch off all debugging measures.
1224 * Determine which debug features should be switched on
1226 for (; *str && *str != ','; str++) {
1227 switch (tolower(*str)) {
1229 slub_debug |= SLAB_DEBUG_FREE;
1232 slub_debug |= SLAB_RED_ZONE;
1235 slub_debug |= SLAB_POISON;
1238 slub_debug |= SLAB_STORE_USER;
1241 slub_debug |= SLAB_TRACE;
1244 slub_debug |= SLAB_FAILSLAB;
1248 * Avoid enabling debugging on caches if its minimum
1249 * order would increase as a result.
1251 disable_higher_order_debug = 1;
1254 pr_err("slub_debug option '%c' unknown. skipped\n",
1261 slub_debug_slabs = str + 1;
1266 __setup("slub_debug", setup_slub_debug);
1268 unsigned long kmem_cache_flags(unsigned long object_size,
1269 unsigned long flags, const char *name,
1270 void (*ctor)(void *))
1273 * Enable debugging if selected on the kernel commandline.
1275 if (slub_debug && (!slub_debug_slabs || (name &&
1276 !strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs)))))
1277 flags |= slub_debug;
1281 #else /* !CONFIG_SLUB_DEBUG */
1282 static inline void setup_object_debug(struct kmem_cache *s,
1283 struct page *page, void *object) {}
1285 static inline int alloc_debug_processing(struct kmem_cache *s,
1286 struct page *page, void *object, unsigned long addr) { return 0; }
1288 static inline struct kmem_cache_node *free_debug_processing(
1289 struct kmem_cache *s, struct page *page,
1290 void *head, void *tail, int bulk_cnt,
1291 unsigned long addr, unsigned long *flags) { return NULL; }
1293 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1295 static inline int check_object(struct kmem_cache *s, struct page *page,
1296 void *object, u8 val) { return 1; }
1297 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1298 struct page *page) {}
1299 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1300 struct page *page) {}
1301 unsigned long kmem_cache_flags(unsigned long object_size,
1302 unsigned long flags, const char *name,
1303 void (*ctor)(void *))
1307 #define slub_debug 0
1309 #define disable_higher_order_debug 0
1311 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1313 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1315 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1317 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1320 #endif /* CONFIG_SLUB_DEBUG */
1323 * Hooks for other subsystems that check memory allocations. In a typical
1324 * production configuration these hooks all should produce no code at all.
1326 static inline void kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1328 kmemleak_alloc(ptr, size, 1, flags);
1329 kasan_kmalloc_large(ptr, size, flags);
1332 static inline void kfree_hook(const void *x)
1335 kasan_kfree_large(x);
1338 static inline struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s,
1341 flags &= gfp_allowed_mask;
1342 lockdep_trace_alloc(flags);
1343 might_sleep_if(gfpflags_allow_blocking(flags));
1345 if (should_failslab(s->object_size, flags, s->flags))
1348 return memcg_kmem_get_cache(s, flags);
1351 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags,
1352 size_t size, void **p)
1356 flags &= gfp_allowed_mask;
1357 for (i = 0; i < size; i++) {
1358 void *object = p[i];
1360 kmemcheck_slab_alloc(s, flags, object, slab_ksize(s));
1361 kmemleak_alloc_recursive(object, s->object_size, 1,
1363 kasan_slab_alloc(s, object, flags);
1365 memcg_kmem_put_cache(s);
1368 static inline void *slab_free_hook(struct kmem_cache *s, void *x)
1372 kmemleak_free_recursive(x, s->flags);
1375 * Trouble is that we may no longer disable interrupts in the fast path
1376 * So in order to make the debug calls that expect irqs to be
1377 * disabled we need to disable interrupts temporarily.
1379 #if defined(CONFIG_KMEMCHECK) || defined(CONFIG_LOCKDEP)
1381 unsigned long flags;
1383 local_irq_save(flags);
1384 kmemcheck_slab_free(s, x, s->object_size);
1385 debug_check_no_locks_freed(x, s->object_size);
1386 local_irq_restore(flags);
1389 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1390 debug_check_no_obj_freed(x, s->object_size);
1392 freeptr = get_freepointer(s, x);
1394 * kasan_slab_free() may put x into memory quarantine, delaying its
1395 * reuse. In this case the object's freelist pointer is changed.
1397 kasan_slab_free(s, x);
1401 static inline void slab_free_freelist_hook(struct kmem_cache *s,
1402 void *head, void *tail)
1405 * Compiler cannot detect this function can be removed if slab_free_hook()
1406 * evaluates to nothing. Thus, catch all relevant config debug options here.
1408 #if defined(CONFIG_KMEMCHECK) || \
1409 defined(CONFIG_LOCKDEP) || \
1410 defined(CONFIG_DEBUG_KMEMLEAK) || \
1411 defined(CONFIG_DEBUG_OBJECTS_FREE) || \
1412 defined(CONFIG_KASAN)
1414 void *object = head;
1415 void *tail_obj = tail ? : head;
1419 freeptr = slab_free_hook(s, object);
1420 } while ((object != tail_obj) && (object = freeptr));
1424 static void setup_object(struct kmem_cache *s, struct page *page,
1427 setup_object_debug(s, page, object);
1428 kasan_init_slab_obj(s, object);
1429 if (unlikely(s->ctor)) {
1430 kasan_unpoison_object_data(s, object);
1432 kasan_poison_object_data(s, object);
1437 * Slab allocation and freeing
1439 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1440 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1443 int order = oo_order(oo);
1445 flags |= __GFP_NOTRACK;
1447 if (node == NUMA_NO_NODE)
1448 page = alloc_pages(flags, order);
1450 page = __alloc_pages_node(node, flags, order);
1452 if (page && memcg_charge_slab(page, flags, order, s)) {
1453 __free_pages(page, order);
1460 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1463 struct kmem_cache_order_objects oo = s->oo;
1468 flags &= gfp_allowed_mask;
1470 if (gfpflags_allow_blocking(flags))
1473 flags |= s->allocflags;
1476 * Let the initial higher-order allocation fail under memory pressure
1477 * so we fall-back to the minimum order allocation.
1479 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1480 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1481 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_DIRECT_RECLAIM;
1483 page = alloc_slab_page(s, alloc_gfp, node, oo);
1484 if (unlikely(!page)) {
1488 * Allocation may have failed due to fragmentation.
1489 * Try a lower order alloc if possible
1491 page = alloc_slab_page(s, alloc_gfp, node, oo);
1492 if (unlikely(!page))
1494 stat(s, ORDER_FALLBACK);
1497 if (kmemcheck_enabled &&
1498 !(s->flags & (SLAB_NOTRACK | DEBUG_DEFAULT_FLAGS))) {
1499 int pages = 1 << oo_order(oo);
1501 kmemcheck_alloc_shadow(page, oo_order(oo), alloc_gfp, node);
1504 * Objects from caches that have a constructor don't get
1505 * cleared when they're allocated, so we need to do it here.
1508 kmemcheck_mark_uninitialized_pages(page, pages);
1510 kmemcheck_mark_unallocated_pages(page, pages);
1513 page->objects = oo_objects(oo);
1515 order = compound_order(page);
1516 page->slab_cache = s;
1517 __SetPageSlab(page);
1518 if (page_is_pfmemalloc(page))
1519 SetPageSlabPfmemalloc(page);
1521 start = page_address(page);
1523 if (unlikely(s->flags & SLAB_POISON))
1524 memset(start, POISON_INUSE, PAGE_SIZE << order);
1526 kasan_poison_slab(page);
1528 for_each_object_idx(p, idx, s, start, page->objects) {
1529 setup_object(s, page, p);
1530 if (likely(idx < page->objects))
1531 set_freepointer(s, p, p + s->size);
1533 set_freepointer(s, p, NULL);
1536 page->freelist = fixup_red_left(s, start);
1537 page->inuse = page->objects;
1541 if (gfpflags_allow_blocking(flags))
1542 local_irq_disable();
1546 mod_zone_page_state(page_zone(page),
1547 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1548 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1551 inc_slabs_node(s, page_to_nid(page), page->objects);
1556 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1558 if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
1559 pr_emerg("gfp: %u\n", flags & GFP_SLAB_BUG_MASK);
1563 return allocate_slab(s,
1564 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1567 static void __free_slab(struct kmem_cache *s, struct page *page)
1569 int order = compound_order(page);
1570 int pages = 1 << order;
1572 if (kmem_cache_debug(s)) {
1575 slab_pad_check(s, page);
1576 for_each_object(p, s, page_address(page),
1578 check_object(s, page, p, SLUB_RED_INACTIVE);
1581 kmemcheck_free_shadow(page, compound_order(page));
1583 mod_zone_page_state(page_zone(page),
1584 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1585 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1588 __ClearPageSlabPfmemalloc(page);
1589 __ClearPageSlab(page);
1591 page_mapcount_reset(page);
1592 if (current->reclaim_state)
1593 current->reclaim_state->reclaimed_slab += pages;
1594 kasan_alloc_pages(page, order);
1595 __free_kmem_pages(page, order);
1598 #define need_reserve_slab_rcu \
1599 (sizeof(((struct page *)NULL)->lru) < sizeof(struct rcu_head))
1601 static void rcu_free_slab(struct rcu_head *h)
1605 if (need_reserve_slab_rcu)
1606 page = virt_to_head_page(h);
1608 page = container_of((struct list_head *)h, struct page, lru);
1610 __free_slab(page->slab_cache, page);
1613 static void free_slab(struct kmem_cache *s, struct page *page)
1615 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1616 struct rcu_head *head;
1618 if (need_reserve_slab_rcu) {
1619 int order = compound_order(page);
1620 int offset = (PAGE_SIZE << order) - s->reserved;
1622 VM_BUG_ON(s->reserved != sizeof(*head));
1623 head = page_address(page) + offset;
1625 head = &page->rcu_head;
1628 call_rcu(head, rcu_free_slab);
1630 __free_slab(s, page);
1633 static void discard_slab(struct kmem_cache *s, struct page *page)
1635 dec_slabs_node(s, page_to_nid(page), page->objects);
1640 * Management of partially allocated slabs.
1643 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1646 if (tail == DEACTIVATE_TO_TAIL)
1647 list_add_tail(&page->lru, &n->partial);
1649 list_add(&page->lru, &n->partial);
1652 static inline void add_partial(struct kmem_cache_node *n,
1653 struct page *page, int tail)
1655 lockdep_assert_held(&n->list_lock);
1656 __add_partial(n, page, tail);
1660 __remove_partial(struct kmem_cache_node *n, struct page *page)
1662 list_del(&page->lru);
1666 static inline void remove_partial(struct kmem_cache_node *n,
1669 lockdep_assert_held(&n->list_lock);
1670 __remove_partial(n, page);
1674 * Remove slab from the partial list, freeze it and
1675 * return the pointer to the freelist.
1677 * Returns a list of objects or NULL if it fails.
1679 static inline void *acquire_slab(struct kmem_cache *s,
1680 struct kmem_cache_node *n, struct page *page,
1681 int mode, int *objects)
1684 unsigned long counters;
1687 lockdep_assert_held(&n->list_lock);
1690 * Zap the freelist and set the frozen bit.
1691 * The old freelist is the list of objects for the
1692 * per cpu allocation list.
1694 freelist = page->freelist;
1695 counters = page->counters;
1696 new.counters = counters;
1697 *objects = new.objects - new.inuse;
1699 new.inuse = page->objects;
1700 new.freelist = NULL;
1702 new.freelist = freelist;
1705 VM_BUG_ON(new.frozen);
1708 if (!__cmpxchg_double_slab(s, page,
1710 new.freelist, new.counters,
1714 remove_partial(n, page);
1719 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1720 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1723 * Try to allocate a partial slab from a specific node.
1725 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1726 struct kmem_cache_cpu *c, gfp_t flags)
1728 struct page *page, *page2;
1729 void *object = NULL;
1730 unsigned int available = 0;
1734 * Racy check. If we mistakenly see no partial slabs then we
1735 * just allocate an empty slab. If we mistakenly try to get a
1736 * partial slab and there is none available then get_partials()
1739 if (!n || !n->nr_partial)
1742 spin_lock(&n->list_lock);
1743 list_for_each_entry_safe(page, page2, &n->partial, lru) {
1746 if (!pfmemalloc_match(page, flags))
1749 t = acquire_slab(s, n, page, object == NULL, &objects);
1753 available += objects;
1756 stat(s, ALLOC_FROM_PARTIAL);
1759 put_cpu_partial(s, page, 0);
1760 stat(s, CPU_PARTIAL_NODE);
1762 if (!kmem_cache_has_cpu_partial(s)
1763 || available > s->cpu_partial / 2)
1767 spin_unlock(&n->list_lock);
1772 * Get a page from somewhere. Search in increasing NUMA distances.
1774 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1775 struct kmem_cache_cpu *c)
1778 struct zonelist *zonelist;
1781 enum zone_type high_zoneidx = gfp_zone(flags);
1783 unsigned int cpuset_mems_cookie;
1786 * The defrag ratio allows a configuration of the tradeoffs between
1787 * inter node defragmentation and node local allocations. A lower
1788 * defrag_ratio increases the tendency to do local allocations
1789 * instead of attempting to obtain partial slabs from other nodes.
1791 * If the defrag_ratio is set to 0 then kmalloc() always
1792 * returns node local objects. If the ratio is higher then kmalloc()
1793 * may return off node objects because partial slabs are obtained
1794 * from other nodes and filled up.
1796 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1797 * defrag_ratio = 1000) then every (well almost) allocation will
1798 * first attempt to defrag slab caches on other nodes. This means
1799 * scanning over all nodes to look for partial slabs which may be
1800 * expensive if we do it every time we are trying to find a slab
1801 * with available objects.
1803 if (!s->remote_node_defrag_ratio ||
1804 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1808 cpuset_mems_cookie = read_mems_allowed_begin();
1809 zonelist = node_zonelist(mempolicy_slab_node(), flags);
1810 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1811 struct kmem_cache_node *n;
1813 n = get_node(s, zone_to_nid(zone));
1815 if (n && cpuset_zone_allowed(zone, flags) &&
1816 n->nr_partial > s->min_partial) {
1817 object = get_partial_node(s, n, c, flags);
1820 * Don't check read_mems_allowed_retry()
1821 * here - if mems_allowed was updated in
1822 * parallel, that was a harmless race
1823 * between allocation and the cpuset
1830 } while (read_mems_allowed_retry(cpuset_mems_cookie));
1836 * Get a partial page, lock it and return it.
1838 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1839 struct kmem_cache_cpu *c)
1842 int searchnode = node;
1844 if (node == NUMA_NO_NODE)
1845 searchnode = numa_mem_id();
1846 else if (!node_present_pages(node))
1847 searchnode = node_to_mem_node(node);
1849 object = get_partial_node(s, get_node(s, searchnode), c, flags);
1850 if (object || node != NUMA_NO_NODE)
1853 return get_any_partial(s, flags, c);
1856 #ifdef CONFIG_PREEMPT
1858 * Calculate the next globally unique transaction for disambiguiation
1859 * during cmpxchg. The transactions start with the cpu number and are then
1860 * incremented by CONFIG_NR_CPUS.
1862 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
1865 * No preemption supported therefore also no need to check for
1871 static inline unsigned long next_tid(unsigned long tid)
1873 return tid + TID_STEP;
1876 static inline unsigned int tid_to_cpu(unsigned long tid)
1878 return tid % TID_STEP;
1881 static inline unsigned long tid_to_event(unsigned long tid)
1883 return tid / TID_STEP;
1886 static inline unsigned int init_tid(int cpu)
1891 static inline void note_cmpxchg_failure(const char *n,
1892 const struct kmem_cache *s, unsigned long tid)
1894 #ifdef SLUB_DEBUG_CMPXCHG
1895 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
1897 pr_info("%s %s: cmpxchg redo ", n, s->name);
1899 #ifdef CONFIG_PREEMPT
1900 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
1901 pr_warn("due to cpu change %d -> %d\n",
1902 tid_to_cpu(tid), tid_to_cpu(actual_tid));
1905 if (tid_to_event(tid) != tid_to_event(actual_tid))
1906 pr_warn("due to cpu running other code. Event %ld->%ld\n",
1907 tid_to_event(tid), tid_to_event(actual_tid));
1909 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
1910 actual_tid, tid, next_tid(tid));
1912 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
1915 static void init_kmem_cache_cpus(struct kmem_cache *s)
1919 for_each_possible_cpu(cpu)
1920 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
1924 * Remove the cpu slab
1926 static void deactivate_slab(struct kmem_cache *s, struct page *page,
1929 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
1930 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1932 enum slab_modes l = M_NONE, m = M_NONE;
1934 int tail = DEACTIVATE_TO_HEAD;
1938 if (page->freelist) {
1939 stat(s, DEACTIVATE_REMOTE_FREES);
1940 tail = DEACTIVATE_TO_TAIL;
1944 * Stage one: Free all available per cpu objects back
1945 * to the page freelist while it is still frozen. Leave the
1948 * There is no need to take the list->lock because the page
1951 while (freelist && (nextfree = get_freepointer(s, freelist))) {
1953 unsigned long counters;
1956 prior = page->freelist;
1957 counters = page->counters;
1958 set_freepointer(s, freelist, prior);
1959 new.counters = counters;
1961 VM_BUG_ON(!new.frozen);
1963 } while (!__cmpxchg_double_slab(s, page,
1965 freelist, new.counters,
1966 "drain percpu freelist"));
1968 freelist = nextfree;
1972 * Stage two: Ensure that the page is unfrozen while the
1973 * list presence reflects the actual number of objects
1976 * We setup the list membership and then perform a cmpxchg
1977 * with the count. If there is a mismatch then the page
1978 * is not unfrozen but the page is on the wrong list.
1980 * Then we restart the process which may have to remove
1981 * the page from the list that we just put it on again
1982 * because the number of objects in the slab may have
1987 old.freelist = page->freelist;
1988 old.counters = page->counters;
1989 VM_BUG_ON(!old.frozen);
1991 /* Determine target state of the slab */
1992 new.counters = old.counters;
1995 set_freepointer(s, freelist, old.freelist);
1996 new.freelist = freelist;
1998 new.freelist = old.freelist;
2002 if (!new.inuse && n->nr_partial >= s->min_partial)
2004 else if (new.freelist) {
2009 * Taking the spinlock removes the possiblity
2010 * that acquire_slab() will see a slab page that
2013 spin_lock(&n->list_lock);
2017 if (kmem_cache_debug(s) && !lock) {
2020 * This also ensures that the scanning of full
2021 * slabs from diagnostic functions will not see
2024 spin_lock(&n->list_lock);
2032 remove_partial(n, page);
2034 else if (l == M_FULL)
2036 remove_full(s, n, page);
2038 if (m == M_PARTIAL) {
2040 add_partial(n, page, tail);
2043 } else if (m == M_FULL) {
2045 stat(s, DEACTIVATE_FULL);
2046 add_full(s, n, page);
2052 if (!__cmpxchg_double_slab(s, page,
2053 old.freelist, old.counters,
2054 new.freelist, new.counters,
2059 spin_unlock(&n->list_lock);
2062 stat(s, DEACTIVATE_EMPTY);
2063 discard_slab(s, page);
2069 * Unfreeze all the cpu partial slabs.
2071 * This function must be called with interrupts disabled
2072 * for the cpu using c (or some other guarantee must be there
2073 * to guarantee no concurrent accesses).
2075 static void unfreeze_partials(struct kmem_cache *s,
2076 struct kmem_cache_cpu *c)
2078 #ifdef CONFIG_SLUB_CPU_PARTIAL
2079 struct kmem_cache_node *n = NULL, *n2 = NULL;
2080 struct page *page, *discard_page = NULL;
2082 while ((page = c->partial)) {
2086 c->partial = page->next;
2088 n2 = get_node(s, page_to_nid(page));
2091 spin_unlock(&n->list_lock);
2094 spin_lock(&n->list_lock);
2099 old.freelist = page->freelist;
2100 old.counters = page->counters;
2101 VM_BUG_ON(!old.frozen);
2103 new.counters = old.counters;
2104 new.freelist = old.freelist;
2108 } while (!__cmpxchg_double_slab(s, page,
2109 old.freelist, old.counters,
2110 new.freelist, new.counters,
2111 "unfreezing slab"));
2113 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2114 page->next = discard_page;
2115 discard_page = page;
2117 add_partial(n, page, DEACTIVATE_TO_TAIL);
2118 stat(s, FREE_ADD_PARTIAL);
2123 spin_unlock(&n->list_lock);
2125 while (discard_page) {
2126 page = discard_page;
2127 discard_page = discard_page->next;
2129 stat(s, DEACTIVATE_EMPTY);
2130 discard_slab(s, page);
2137 * Put a page that was just frozen (in __slab_free) into a partial page
2138 * slot if available. This is done without interrupts disabled and without
2139 * preemption disabled. The cmpxchg is racy and may put the partial page
2140 * onto a random cpus partial slot.
2142 * If we did not find a slot then simply move all the partials to the
2143 * per node partial list.
2145 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2147 #ifdef CONFIG_SLUB_CPU_PARTIAL
2148 struct page *oldpage;
2156 oldpage = this_cpu_read(s->cpu_slab->partial);
2159 pobjects = oldpage->pobjects;
2160 pages = oldpage->pages;
2161 if (drain && pobjects > s->cpu_partial) {
2162 unsigned long flags;
2164 * partial array is full. Move the existing
2165 * set to the per node partial list.
2167 local_irq_save(flags);
2168 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2169 local_irq_restore(flags);
2173 stat(s, CPU_PARTIAL_DRAIN);
2178 pobjects += page->objects - page->inuse;
2180 page->pages = pages;
2181 page->pobjects = pobjects;
2182 page->next = oldpage;
2184 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2186 if (unlikely(!s->cpu_partial)) {
2187 unsigned long flags;
2189 local_irq_save(flags);
2190 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2191 local_irq_restore(flags);
2197 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2199 stat(s, CPUSLAB_FLUSH);
2200 deactivate_slab(s, c->page, c->freelist);
2202 c->tid = next_tid(c->tid);
2210 * Called from IPI handler with interrupts disabled.
2212 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2214 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2220 unfreeze_partials(s, c);
2224 static void flush_cpu_slab(void *d)
2226 struct kmem_cache *s = d;
2228 __flush_cpu_slab(s, smp_processor_id());
2231 static bool has_cpu_slab(int cpu, void *info)
2233 struct kmem_cache *s = info;
2234 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2236 return c->page || c->partial;
2239 static void flush_all(struct kmem_cache *s)
2241 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC);
2245 * Check if the objects in a per cpu structure fit numa
2246 * locality expectations.
2248 static inline int node_match(struct page *page, int node)
2251 if (!page || (node != NUMA_NO_NODE && page_to_nid(page) != node))
2257 #ifdef CONFIG_SLUB_DEBUG
2258 static int count_free(struct page *page)
2260 return page->objects - page->inuse;
2263 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2265 return atomic_long_read(&n->total_objects);
2267 #endif /* CONFIG_SLUB_DEBUG */
2269 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2270 static unsigned long count_partial(struct kmem_cache_node *n,
2271 int (*get_count)(struct page *))
2273 unsigned long flags;
2274 unsigned long x = 0;
2277 spin_lock_irqsave(&n->list_lock, flags);
2278 list_for_each_entry(page, &n->partial, lru)
2279 x += get_count(page);
2280 spin_unlock_irqrestore(&n->list_lock, flags);
2283 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2285 static noinline void
2286 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2288 #ifdef CONFIG_SLUB_DEBUG
2289 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2290 DEFAULT_RATELIMIT_BURST);
2292 struct kmem_cache_node *n;
2294 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2297 pr_warn("SLUB: Unable to allocate memory on node %d (gfp=0x%x)\n",
2299 pr_warn(" cache: %s, object size: %d, buffer size: %d, default order: %d, min order: %d\n",
2300 s->name, s->object_size, s->size, oo_order(s->oo),
2303 if (oo_order(s->min) > get_order(s->object_size))
2304 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2307 for_each_kmem_cache_node(s, node, n) {
2308 unsigned long nr_slabs;
2309 unsigned long nr_objs;
2310 unsigned long nr_free;
2312 nr_free = count_partial(n, count_free);
2313 nr_slabs = node_nr_slabs(n);
2314 nr_objs = node_nr_objs(n);
2316 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2317 node, nr_slabs, nr_objs, nr_free);
2322 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2323 int node, struct kmem_cache_cpu **pc)
2326 struct kmem_cache_cpu *c = *pc;
2329 freelist = get_partial(s, flags, node, c);
2334 page = new_slab(s, flags, node);
2336 c = raw_cpu_ptr(s->cpu_slab);
2341 * No other reference to the page yet so we can
2342 * muck around with it freely without cmpxchg
2344 freelist = page->freelist;
2345 page->freelist = NULL;
2347 stat(s, ALLOC_SLAB);
2356 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2358 if (unlikely(PageSlabPfmemalloc(page)))
2359 return gfp_pfmemalloc_allowed(gfpflags);
2365 * Check the page->freelist of a page and either transfer the freelist to the
2366 * per cpu freelist or deactivate the page.
2368 * The page is still frozen if the return value is not NULL.
2370 * If this function returns NULL then the page has been unfrozen.
2372 * This function must be called with interrupt disabled.
2374 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2377 unsigned long counters;
2381 freelist = page->freelist;
2382 counters = page->counters;
2384 new.counters = counters;
2385 VM_BUG_ON(!new.frozen);
2387 new.inuse = page->objects;
2388 new.frozen = freelist != NULL;
2390 } while (!__cmpxchg_double_slab(s, page,
2399 * Slow path. The lockless freelist is empty or we need to perform
2402 * Processing is still very fast if new objects have been freed to the
2403 * regular freelist. In that case we simply take over the regular freelist
2404 * as the lockless freelist and zap the regular freelist.
2406 * If that is not working then we fall back to the partial lists. We take the
2407 * first element of the freelist as the object to allocate now and move the
2408 * rest of the freelist to the lockless freelist.
2410 * And if we were unable to get a new slab from the partial slab lists then
2411 * we need to allocate a new slab. This is the slowest path since it involves
2412 * a call to the page allocator and the setup of a new slab.
2414 * Version of __slab_alloc to use when we know that interrupts are
2415 * already disabled (which is the case for bulk allocation).
2417 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2418 unsigned long addr, struct kmem_cache_cpu *c)
2428 if (unlikely(!node_match(page, node))) {
2429 int searchnode = node;
2431 if (node != NUMA_NO_NODE && !node_present_pages(node))
2432 searchnode = node_to_mem_node(node);
2434 if (unlikely(!node_match(page, searchnode))) {
2435 stat(s, ALLOC_NODE_MISMATCH);
2436 deactivate_slab(s, page, c->freelist);
2444 * By rights, we should be searching for a slab page that was
2445 * PFMEMALLOC but right now, we are losing the pfmemalloc
2446 * information when the page leaves the per-cpu allocator
2448 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2449 deactivate_slab(s, page, c->freelist);
2455 /* must check again c->freelist in case of cpu migration or IRQ */
2456 freelist = c->freelist;
2460 freelist = get_freelist(s, page);
2464 stat(s, DEACTIVATE_BYPASS);
2468 stat(s, ALLOC_REFILL);
2472 * freelist is pointing to the list of objects to be used.
2473 * page is pointing to the page from which the objects are obtained.
2474 * That page must be frozen for per cpu allocations to work.
2476 VM_BUG_ON(!c->page->frozen);
2477 c->freelist = get_freepointer(s, freelist);
2478 c->tid = next_tid(c->tid);
2484 page = c->page = c->partial;
2485 c->partial = page->next;
2486 stat(s, CPU_PARTIAL_ALLOC);
2491 freelist = new_slab_objects(s, gfpflags, node, &c);
2493 if (unlikely(!freelist)) {
2494 slab_out_of_memory(s, gfpflags, node);
2499 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2502 /* Only entered in the debug case */
2503 if (kmem_cache_debug(s) &&
2504 !alloc_debug_processing(s, page, freelist, addr))
2505 goto new_slab; /* Slab failed checks. Next slab needed */
2507 deactivate_slab(s, page, get_freepointer(s, freelist));
2514 * Another one that disabled interrupt and compensates for possible
2515 * cpu changes by refetching the per cpu area pointer.
2517 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2518 unsigned long addr, struct kmem_cache_cpu *c)
2521 unsigned long flags;
2523 local_irq_save(flags);
2524 #ifdef CONFIG_PREEMPT
2526 * We may have been preempted and rescheduled on a different
2527 * cpu before disabling interrupts. Need to reload cpu area
2530 c = this_cpu_ptr(s->cpu_slab);
2533 p = ___slab_alloc(s, gfpflags, node, addr, c);
2534 local_irq_restore(flags);
2539 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2540 * have the fastpath folded into their functions. So no function call
2541 * overhead for requests that can be satisfied on the fastpath.
2543 * The fastpath works by first checking if the lockless freelist can be used.
2544 * If not then __slab_alloc is called for slow processing.
2546 * Otherwise we can simply pick the next object from the lockless free list.
2548 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2549 gfp_t gfpflags, int node, unsigned long addr)
2552 struct kmem_cache_cpu *c;
2556 s = slab_pre_alloc_hook(s, gfpflags);
2561 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2562 * enabled. We may switch back and forth between cpus while
2563 * reading from one cpu area. That does not matter as long
2564 * as we end up on the original cpu again when doing the cmpxchg.
2566 * We should guarantee that tid and kmem_cache are retrieved on
2567 * the same cpu. It could be different if CONFIG_PREEMPT so we need
2568 * to check if it is matched or not.
2571 tid = this_cpu_read(s->cpu_slab->tid);
2572 c = raw_cpu_ptr(s->cpu_slab);
2573 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2574 unlikely(tid != READ_ONCE(c->tid)));
2577 * Irqless object alloc/free algorithm used here depends on sequence
2578 * of fetching cpu_slab's data. tid should be fetched before anything
2579 * on c to guarantee that object and page associated with previous tid
2580 * won't be used with current tid. If we fetch tid first, object and
2581 * page could be one associated with next tid and our alloc/free
2582 * request will be failed. In this case, we will retry. So, no problem.
2587 * The transaction ids are globally unique per cpu and per operation on
2588 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2589 * occurs on the right processor and that there was no operation on the
2590 * linked list in between.
2593 object = c->freelist;
2595 if (unlikely(!object || !node_match(page, node))) {
2596 object = __slab_alloc(s, gfpflags, node, addr, c);
2597 stat(s, ALLOC_SLOWPATH);
2599 void *next_object = get_freepointer_safe(s, object);
2602 * The cmpxchg will only match if there was no additional
2603 * operation and if we are on the right processor.
2605 * The cmpxchg does the following atomically (without lock
2607 * 1. Relocate first pointer to the current per cpu area.
2608 * 2. Verify that tid and freelist have not been changed
2609 * 3. If they were not changed replace tid and freelist
2611 * Since this is without lock semantics the protection is only
2612 * against code executing on this cpu *not* from access by
2615 if (unlikely(!this_cpu_cmpxchg_double(
2616 s->cpu_slab->freelist, s->cpu_slab->tid,
2618 next_object, next_tid(tid)))) {
2620 note_cmpxchg_failure("slab_alloc", s, tid);
2623 prefetch_freepointer(s, next_object);
2624 stat(s, ALLOC_FASTPATH);
2627 if (unlikely(gfpflags & __GFP_ZERO) && object)
2628 memset(object, 0, s->object_size);
2630 slab_post_alloc_hook(s, gfpflags, 1, &object);
2635 static __always_inline void *slab_alloc(struct kmem_cache *s,
2636 gfp_t gfpflags, unsigned long addr)
2638 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2641 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2643 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2645 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2650 EXPORT_SYMBOL(kmem_cache_alloc);
2652 #ifdef CONFIG_TRACING
2653 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2655 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2656 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2657 kasan_kmalloc(s, ret, size, gfpflags);
2660 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2664 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2666 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2668 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2669 s->object_size, s->size, gfpflags, node);
2673 EXPORT_SYMBOL(kmem_cache_alloc_node);
2675 #ifdef CONFIG_TRACING
2676 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2678 int node, size_t size)
2680 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2682 trace_kmalloc_node(_RET_IP_, ret,
2683 size, s->size, gfpflags, node);
2685 kasan_kmalloc(s, ret, size, gfpflags);
2688 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2693 * Slow path handling. This may still be called frequently since objects
2694 * have a longer lifetime than the cpu slabs in most processing loads.
2696 * So we still attempt to reduce cache line usage. Just take the slab
2697 * lock and free the item. If there is no additional partial page
2698 * handling required then we can return immediately.
2700 static void __slab_free(struct kmem_cache *s, struct page *page,
2701 void *head, void *tail, int cnt,
2708 unsigned long counters;
2709 struct kmem_cache_node *n = NULL;
2710 unsigned long uninitialized_var(flags);
2712 stat(s, FREE_SLOWPATH);
2714 if (kmem_cache_debug(s) &&
2715 !(n = free_debug_processing(s, page, head, tail, cnt,
2721 spin_unlock_irqrestore(&n->list_lock, flags);
2724 prior = page->freelist;
2725 counters = page->counters;
2726 set_freepointer(s, tail, prior);
2727 new.counters = counters;
2728 was_frozen = new.frozen;
2730 if ((!new.inuse || !prior) && !was_frozen) {
2732 if (kmem_cache_has_cpu_partial(s) && !prior) {
2735 * Slab was on no list before and will be
2737 * We can defer the list move and instead
2742 } else { /* Needs to be taken off a list */
2744 n = get_node(s, page_to_nid(page));
2746 * Speculatively acquire the list_lock.
2747 * If the cmpxchg does not succeed then we may
2748 * drop the list_lock without any processing.
2750 * Otherwise the list_lock will synchronize with
2751 * other processors updating the list of slabs.
2753 spin_lock_irqsave(&n->list_lock, flags);
2758 } while (!cmpxchg_double_slab(s, page,
2766 * If we just froze the page then put it onto the
2767 * per cpu partial list.
2769 if (new.frozen && !was_frozen) {
2770 put_cpu_partial(s, page, 1);
2771 stat(s, CPU_PARTIAL_FREE);
2774 * The list lock was not taken therefore no list
2775 * activity can be necessary.
2778 stat(s, FREE_FROZEN);
2782 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
2786 * Objects left in the slab. If it was not on the partial list before
2789 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
2790 if (kmem_cache_debug(s))
2791 remove_full(s, n, page);
2792 add_partial(n, page, DEACTIVATE_TO_TAIL);
2793 stat(s, FREE_ADD_PARTIAL);
2795 spin_unlock_irqrestore(&n->list_lock, flags);
2801 * Slab on the partial list.
2803 remove_partial(n, page);
2804 stat(s, FREE_REMOVE_PARTIAL);
2806 /* Slab must be on the full list */
2807 remove_full(s, n, page);
2810 spin_unlock_irqrestore(&n->list_lock, flags);
2812 discard_slab(s, page);
2816 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2817 * can perform fastpath freeing without additional function calls.
2819 * The fastpath is only possible if we are freeing to the current cpu slab
2820 * of this processor. This typically the case if we have just allocated
2823 * If fastpath is not possible then fall back to __slab_free where we deal
2824 * with all sorts of special processing.
2826 * Bulk free of a freelist with several objects (all pointing to the
2827 * same page) possible by specifying head and tail ptr, plus objects
2828 * count (cnt). Bulk free indicated by tail pointer being set.
2830 static __always_inline void do_slab_free(struct kmem_cache *s,
2831 struct page *page, void *head, void *tail,
2832 int cnt, unsigned long addr)
2834 void *tail_obj = tail ? : head;
2835 struct kmem_cache_cpu *c;
2839 * Determine the currently cpus per cpu slab.
2840 * The cpu may change afterward. However that does not matter since
2841 * data is retrieved via this pointer. If we are on the same cpu
2842 * during the cmpxchg then the free will succeed.
2845 tid = this_cpu_read(s->cpu_slab->tid);
2846 c = raw_cpu_ptr(s->cpu_slab);
2847 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2848 unlikely(tid != READ_ONCE(c->tid)));
2850 /* Same with comment on barrier() in slab_alloc_node() */
2853 if (likely(page == c->page)) {
2854 set_freepointer(s, tail_obj, c->freelist);
2856 if (unlikely(!this_cpu_cmpxchg_double(
2857 s->cpu_slab->freelist, s->cpu_slab->tid,
2859 head, next_tid(tid)))) {
2861 note_cmpxchg_failure("slab_free", s, tid);
2864 stat(s, FREE_FASTPATH);
2866 __slab_free(s, page, head, tail_obj, cnt, addr);
2870 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
2871 void *head, void *tail, int cnt,
2874 slab_free_freelist_hook(s, head, tail);
2876 * slab_free_freelist_hook() could have put the items into quarantine.
2877 * If so, no need to free them.
2879 if (s->flags & SLAB_KASAN && !(s->flags & SLAB_DESTROY_BY_RCU))
2881 do_slab_free(s, page, head, tail, cnt, addr);
2885 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
2887 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
2891 void kmem_cache_free(struct kmem_cache *s, void *x)
2893 s = cache_from_obj(s, x);
2896 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
2897 trace_kmem_cache_free(_RET_IP_, x);
2899 EXPORT_SYMBOL(kmem_cache_free);
2901 struct detached_freelist {
2906 struct kmem_cache *s;
2910 * This function progressively scans the array with free objects (with
2911 * a limited look ahead) and extract objects belonging to the same
2912 * page. It builds a detached freelist directly within the given
2913 * page/objects. This can happen without any need for
2914 * synchronization, because the objects are owned by running process.
2915 * The freelist is build up as a single linked list in the objects.
2916 * The idea is, that this detached freelist can then be bulk
2917 * transferred to the real freelist(s), but only requiring a single
2918 * synchronization primitive. Look ahead in the array is limited due
2919 * to performance reasons.
2922 int build_detached_freelist(struct kmem_cache *s, size_t size,
2923 void **p, struct detached_freelist *df)
2925 size_t first_skipped_index = 0;
2929 /* Always re-init detached_freelist */
2934 } while (!object && size);
2939 /* Support for memcg, compiler can optimize this out */
2940 df->s = cache_from_obj(s, object);
2942 /* Start new detached freelist */
2943 set_freepointer(df->s, object, NULL);
2944 df->page = virt_to_head_page(object);
2946 df->freelist = object;
2947 p[size] = NULL; /* mark object processed */
2953 continue; /* Skip processed objects */
2955 /* df->page is always set at this point */
2956 if (df->page == virt_to_head_page(object)) {
2957 /* Opportunity build freelist */
2958 set_freepointer(df->s, object, df->freelist);
2959 df->freelist = object;
2961 p[size] = NULL; /* mark object processed */
2966 /* Limit look ahead search */
2970 if (!first_skipped_index)
2971 first_skipped_index = size + 1;
2974 return first_skipped_index;
2977 /* Note that interrupts must be enabled when calling this function. */
2978 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
2984 struct detached_freelist df;
2986 size = build_detached_freelist(s, size, p, &df);
2987 if (unlikely(!df.page))
2990 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
2991 } while (likely(size));
2993 EXPORT_SYMBOL(kmem_cache_free_bulk);
2995 /* Note that interrupts must be enabled when calling this function. */
2996 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
2999 struct kmem_cache_cpu *c;
3002 /* memcg and kmem_cache debug support */
3003 s = slab_pre_alloc_hook(s, flags);
3007 * Drain objects in the per cpu slab, while disabling local
3008 * IRQs, which protects against PREEMPT and interrupts
3009 * handlers invoking normal fastpath.
3011 local_irq_disable();
3012 c = this_cpu_ptr(s->cpu_slab);
3014 for (i = 0; i < size; i++) {
3015 void *object = c->freelist;
3017 if (unlikely(!object)) {
3019 * Invoking slow path likely have side-effect
3020 * of re-populating per CPU c->freelist
3022 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3024 if (unlikely(!p[i]))
3027 c = this_cpu_ptr(s->cpu_slab);
3028 continue; /* goto for-loop */
3030 c->freelist = get_freepointer(s, object);
3033 c->tid = next_tid(c->tid);
3036 /* Clear memory outside IRQ disabled fastpath loop */
3037 if (unlikely(flags & __GFP_ZERO)) {
3040 for (j = 0; j < i; j++)
3041 memset(p[j], 0, s->object_size);
3044 /* memcg and kmem_cache debug support */
3045 slab_post_alloc_hook(s, flags, size, p);
3049 slab_post_alloc_hook(s, flags, i, p);
3050 __kmem_cache_free_bulk(s, i, p);
3053 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3057 * Object placement in a slab is made very easy because we always start at
3058 * offset 0. If we tune the size of the object to the alignment then we can
3059 * get the required alignment by putting one properly sized object after
3062 * Notice that the allocation order determines the sizes of the per cpu
3063 * caches. Each processor has always one slab available for allocations.
3064 * Increasing the allocation order reduces the number of times that slabs
3065 * must be moved on and off the partial lists and is therefore a factor in
3070 * Mininum / Maximum order of slab pages. This influences locking overhead
3071 * and slab fragmentation. A higher order reduces the number of partial slabs
3072 * and increases the number of allocations possible without having to
3073 * take the list_lock.
3075 static int slub_min_order;
3076 static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3077 static int slub_min_objects;
3080 * Calculate the order of allocation given an slab object size.
3082 * The order of allocation has significant impact on performance and other
3083 * system components. Generally order 0 allocations should be preferred since
3084 * order 0 does not cause fragmentation in the page allocator. Larger objects
3085 * be problematic to put into order 0 slabs because there may be too much
3086 * unused space left. We go to a higher order if more than 1/16th of the slab
3089 * In order to reach satisfactory performance we must ensure that a minimum
3090 * number of objects is in one slab. Otherwise we may generate too much
3091 * activity on the partial lists which requires taking the list_lock. This is
3092 * less a concern for large slabs though which are rarely used.
3094 * slub_max_order specifies the order where we begin to stop considering the
3095 * number of objects in a slab as critical. If we reach slub_max_order then
3096 * we try to keep the page order as low as possible. So we accept more waste
3097 * of space in favor of a small page order.
3099 * Higher order allocations also allow the placement of more objects in a
3100 * slab and thereby reduce object handling overhead. If the user has
3101 * requested a higher mininum order then we start with that one instead of
3102 * the smallest order which will fit the object.
3104 static inline int slab_order(int size, int min_objects,
3105 int max_order, int fract_leftover, int reserved)
3109 int min_order = slub_min_order;
3111 if (order_objects(min_order, size, reserved) > MAX_OBJS_PER_PAGE)
3112 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3114 for (order = max(min_order, get_order(min_objects * size + reserved));
3115 order <= max_order; order++) {
3117 unsigned long slab_size = PAGE_SIZE << order;
3119 rem = (slab_size - reserved) % size;
3121 if (rem <= slab_size / fract_leftover)
3128 static inline int calculate_order(int size, int reserved)
3136 * Attempt to find best configuration for a slab. This
3137 * works by first attempting to generate a layout with
3138 * the best configuration and backing off gradually.
3140 * First we increase the acceptable waste in a slab. Then
3141 * we reduce the minimum objects required in a slab.
3143 min_objects = slub_min_objects;
3145 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3146 max_objects = order_objects(slub_max_order, size, reserved);
3147 min_objects = min(min_objects, max_objects);
3149 while (min_objects > 1) {
3151 while (fraction >= 4) {
3152 order = slab_order(size, min_objects,
3153 slub_max_order, fraction, reserved);
3154 if (order <= slub_max_order)
3162 * We were unable to place multiple objects in a slab. Now
3163 * lets see if we can place a single object there.
3165 order = slab_order(size, 1, slub_max_order, 1, reserved);
3166 if (order <= slub_max_order)
3170 * Doh this slab cannot be placed using slub_max_order.
3172 order = slab_order(size, 1, MAX_ORDER, 1, reserved);
3173 if (order < MAX_ORDER)
3179 init_kmem_cache_node(struct kmem_cache_node *n)
3182 spin_lock_init(&n->list_lock);
3183 INIT_LIST_HEAD(&n->partial);
3184 #ifdef CONFIG_SLUB_DEBUG
3185 atomic_long_set(&n->nr_slabs, 0);
3186 atomic_long_set(&n->total_objects, 0);
3187 INIT_LIST_HEAD(&n->full);
3191 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3193 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3194 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3197 * Must align to double word boundary for the double cmpxchg
3198 * instructions to work; see __pcpu_double_call_return_bool().
3200 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3201 2 * sizeof(void *));
3206 init_kmem_cache_cpus(s);
3211 static struct kmem_cache *kmem_cache_node;
3214 * No kmalloc_node yet so do it by hand. We know that this is the first
3215 * slab on the node for this slabcache. There are no concurrent accesses
3218 * Note that this function only works on the kmem_cache_node
3219 * when allocating for the kmem_cache_node. This is used for bootstrapping
3220 * memory on a fresh node that has no slab structures yet.
3222 static void early_kmem_cache_node_alloc(int node)
3225 struct kmem_cache_node *n;
3227 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3229 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3232 if (page_to_nid(page) != node) {
3233 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3234 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3239 page->freelist = get_freepointer(kmem_cache_node, n);
3242 kmem_cache_node->node[node] = n;
3243 #ifdef CONFIG_SLUB_DEBUG
3244 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3245 init_tracking(kmem_cache_node, n);
3247 kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
3249 init_kmem_cache_node(n);
3250 inc_slabs_node(kmem_cache_node, node, page->objects);
3253 * No locks need to be taken here as it has just been
3254 * initialized and there is no concurrent access.
3256 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3259 static void free_kmem_cache_nodes(struct kmem_cache *s)
3262 struct kmem_cache_node *n;
3264 for_each_kmem_cache_node(s, node, n) {
3265 kmem_cache_free(kmem_cache_node, n);
3266 s->node[node] = NULL;
3270 static int init_kmem_cache_nodes(struct kmem_cache *s)
3274 for_each_node_state(node, N_NORMAL_MEMORY) {
3275 struct kmem_cache_node *n;
3277 if (slab_state == DOWN) {
3278 early_kmem_cache_node_alloc(node);
3281 n = kmem_cache_alloc_node(kmem_cache_node,
3285 free_kmem_cache_nodes(s);
3290 init_kmem_cache_node(n);
3295 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3297 if (min < MIN_PARTIAL)
3299 else if (min > MAX_PARTIAL)
3301 s->min_partial = min;
3305 * calculate_sizes() determines the order and the distribution of data within
3308 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3310 unsigned long flags = s->flags;
3311 size_t size = s->object_size;
3315 * Round up object size to the next word boundary. We can only
3316 * place the free pointer at word boundaries and this determines
3317 * the possible location of the free pointer.
3319 size = ALIGN(size, sizeof(void *));
3321 #ifdef CONFIG_SLUB_DEBUG
3323 * Determine if we can poison the object itself. If the user of
3324 * the slab may touch the object after free or before allocation
3325 * then we should never poison the object itself.
3327 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
3329 s->flags |= __OBJECT_POISON;
3331 s->flags &= ~__OBJECT_POISON;
3335 * If we are Redzoning then check if there is some space between the
3336 * end of the object and the free pointer. If not then add an
3337 * additional word to have some bytes to store Redzone information.
3339 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3340 size += sizeof(void *);
3344 * With that we have determined the number of bytes in actual use
3345 * by the object. This is the potential offset to the free pointer.
3349 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
3352 * Relocate free pointer after the object if it is not
3353 * permitted to overwrite the first word of the object on
3356 * This is the case if we do RCU, have a constructor or
3357 * destructor or are poisoning the objects.
3360 size += sizeof(void *);
3363 #ifdef CONFIG_SLUB_DEBUG
3364 if (flags & SLAB_STORE_USER)
3366 * Need to store information about allocs and frees after
3369 size += 2 * sizeof(struct track);
3372 kasan_cache_create(s, &size, &s->flags);
3373 #ifdef CONFIG_SLUB_DEBUG
3374 if (flags & SLAB_RED_ZONE) {
3376 * Add some empty padding so that we can catch
3377 * overwrites from earlier objects rather than let
3378 * tracking information or the free pointer be
3379 * corrupted if a user writes before the start
3382 size += sizeof(void *);
3384 s->red_left_pad = sizeof(void *);
3385 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3386 size += s->red_left_pad;
3391 * SLUB stores one object immediately after another beginning from
3392 * offset 0. In order to align the objects we have to simply size
3393 * each object to conform to the alignment.
3395 size = ALIGN(size, s->align);
3397 if (forced_order >= 0)
3398 order = forced_order;
3400 order = calculate_order(size, s->reserved);
3407 s->allocflags |= __GFP_COMP;
3409 if (s->flags & SLAB_CACHE_DMA)
3410 s->allocflags |= GFP_DMA;
3412 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3413 s->allocflags |= __GFP_RECLAIMABLE;
3416 * Determine the number of objects per slab
3418 s->oo = oo_make(order, size, s->reserved);
3419 s->min = oo_make(get_order(size), size, s->reserved);
3420 if (oo_objects(s->oo) > oo_objects(s->max))
3423 return !!oo_objects(s->oo);
3426 static int kmem_cache_open(struct kmem_cache *s, unsigned long flags)
3428 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3431 if (need_reserve_slab_rcu && (s->flags & SLAB_DESTROY_BY_RCU))
3432 s->reserved = sizeof(struct rcu_head);
3434 if (!calculate_sizes(s, -1))
3436 if (disable_higher_order_debug) {
3438 * Disable debugging flags that store metadata if the min slab
3441 if (get_order(s->size) > get_order(s->object_size)) {
3442 s->flags &= ~DEBUG_METADATA_FLAGS;
3444 if (!calculate_sizes(s, -1))
3449 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3450 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3451 if (system_has_cmpxchg_double() && (s->flags & SLAB_DEBUG_FLAGS) == 0)
3452 /* Enable fast mode */
3453 s->flags |= __CMPXCHG_DOUBLE;
3457 * The larger the object size is, the more pages we want on the partial
3458 * list to avoid pounding the page allocator excessively.
3460 set_min_partial(s, ilog2(s->size) / 2);
3463 * cpu_partial determined the maximum number of objects kept in the
3464 * per cpu partial lists of a processor.
3466 * Per cpu partial lists mainly contain slabs that just have one
3467 * object freed. If they are used for allocation then they can be
3468 * filled up again with minimal effort. The slab will never hit the
3469 * per node partial lists and therefore no locking will be required.
3471 * This setting also determines
3473 * A) The number of objects from per cpu partial slabs dumped to the
3474 * per node list when we reach the limit.
3475 * B) The number of objects in cpu partial slabs to extract from the
3476 * per node list when we run out of per cpu objects. We only fetch
3477 * 50% to keep some capacity around for frees.
3479 if (!kmem_cache_has_cpu_partial(s))
3481 else if (s->size >= PAGE_SIZE)
3483 else if (s->size >= 1024)
3485 else if (s->size >= 256)
3486 s->cpu_partial = 13;
3488 s->cpu_partial = 30;
3491 s->remote_node_defrag_ratio = 1000;
3493 if (!init_kmem_cache_nodes(s))
3496 if (alloc_kmem_cache_cpus(s))
3499 free_kmem_cache_nodes(s);
3501 if (flags & SLAB_PANIC)
3502 panic("Cannot create slab %s size=%lu realsize=%u order=%u offset=%u flags=%lx\n",
3503 s->name, (unsigned long)s->size, s->size,
3504 oo_order(s->oo), s->offset, flags);
3508 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3511 #ifdef CONFIG_SLUB_DEBUG
3512 void *addr = page_address(page);
3514 unsigned long *map = kzalloc(BITS_TO_LONGS(page->objects) *
3515 sizeof(long), GFP_ATOMIC);
3518 slab_err(s, page, text, s->name);
3521 get_map(s, page, map);
3522 for_each_object(p, s, addr, page->objects) {
3524 if (!test_bit(slab_index(p, s, addr), map)) {
3525 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3526 print_tracking(s, p);
3535 * Attempt to free all partial slabs on a node.
3536 * This is called from kmem_cache_close(). We must be the last thread
3537 * using the cache and therefore we do not need to lock anymore.
3539 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3541 struct page *page, *h;
3543 list_for_each_entry_safe(page, h, &n->partial, lru) {
3545 __remove_partial(n, page);
3546 discard_slab(s, page);
3548 list_slab_objects(s, page,
3549 "Objects remaining in %s on kmem_cache_close()");
3555 * Release all resources used by a slab cache.
3557 static inline int kmem_cache_close(struct kmem_cache *s)
3560 struct kmem_cache_node *n;
3563 /* Attempt to free all objects */
3564 for_each_kmem_cache_node(s, node, n) {
3566 if (n->nr_partial || slabs_node(s, node))
3569 free_percpu(s->cpu_slab);
3570 free_kmem_cache_nodes(s);
3574 int __kmem_cache_shutdown(struct kmem_cache *s)
3576 return kmem_cache_close(s);
3579 /********************************************************************
3581 *******************************************************************/
3583 static int __init setup_slub_min_order(char *str)
3585 get_option(&str, &slub_min_order);
3590 __setup("slub_min_order=", setup_slub_min_order);
3592 static int __init setup_slub_max_order(char *str)
3594 get_option(&str, &slub_max_order);
3595 slub_max_order = min(slub_max_order, MAX_ORDER - 1);
3600 __setup("slub_max_order=", setup_slub_max_order);
3602 static int __init setup_slub_min_objects(char *str)
3604 get_option(&str, &slub_min_objects);
3609 __setup("slub_min_objects=", setup_slub_min_objects);
3611 void *__kmalloc(size_t size, gfp_t flags)
3613 struct kmem_cache *s;
3616 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3617 return kmalloc_large(size, flags);
3619 s = kmalloc_slab(size, flags);
3621 if (unlikely(ZERO_OR_NULL_PTR(s)))
3624 ret = slab_alloc(s, flags, _RET_IP_);
3626 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3628 kasan_kmalloc(s, ret, size, flags);
3632 EXPORT_SYMBOL(__kmalloc);
3635 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3640 flags |= __GFP_COMP | __GFP_NOTRACK;
3641 page = alloc_kmem_pages_node(node, flags, get_order(size));
3643 ptr = page_address(page);
3645 kmalloc_large_node_hook(ptr, size, flags);
3649 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3651 struct kmem_cache *s;
3654 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
3655 ret = kmalloc_large_node(size, flags, node);
3657 trace_kmalloc_node(_RET_IP_, ret,
3658 size, PAGE_SIZE << get_order(size),
3664 s = kmalloc_slab(size, flags);
3666 if (unlikely(ZERO_OR_NULL_PTR(s)))
3669 ret = slab_alloc_node(s, flags, node, _RET_IP_);
3671 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3673 kasan_kmalloc(s, ret, size, flags);
3677 EXPORT_SYMBOL(__kmalloc_node);
3680 #ifdef CONFIG_HARDENED_USERCOPY
3682 * Rejects objects that are incorrectly sized.
3684 * Returns NULL if check passes, otherwise const char * to name of cache
3685 * to indicate an error.
3687 const char *__check_heap_object(const void *ptr, unsigned long n,
3690 struct kmem_cache *s;
3691 unsigned long offset;
3694 /* Find object and usable object size. */
3695 s = page->slab_cache;
3696 object_size = slab_ksize(s);
3698 /* Reject impossible pointers. */
3699 if (ptr < page_address(page))
3702 /* Find offset within object. */
3703 offset = (ptr - page_address(page)) % s->size;
3705 /* Adjust for redzone and reject if within the redzone. */
3706 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) {
3707 if (offset < s->red_left_pad)
3709 offset -= s->red_left_pad;
3712 /* Allow address range falling entirely within object size. */
3713 if (offset <= object_size && n <= object_size - offset)
3718 #endif /* CONFIG_HARDENED_USERCOPY */
3720 static size_t __ksize(const void *object)
3724 if (unlikely(object == ZERO_SIZE_PTR))
3727 page = virt_to_head_page(object);
3729 if (unlikely(!PageSlab(page))) {
3730 WARN_ON(!PageCompound(page));
3731 return PAGE_SIZE << compound_order(page);
3734 return slab_ksize(page->slab_cache);
3737 size_t ksize(const void *object)
3739 size_t size = __ksize(object);
3740 /* We assume that ksize callers could use whole allocated area,
3741 so we need unpoison this area. */
3742 kasan_krealloc(object, size, GFP_NOWAIT);
3745 EXPORT_SYMBOL(ksize);
3747 void kfree(const void *x)
3750 void *object = (void *)x;
3752 trace_kfree(_RET_IP_, x);
3754 if (unlikely(ZERO_OR_NULL_PTR(x)))
3757 page = virt_to_head_page(x);
3758 if (unlikely(!PageSlab(page))) {
3759 BUG_ON(!PageCompound(page));
3761 kasan_alloc_pages(page, compound_order(page));
3762 __free_kmem_pages(page, compound_order(page));
3765 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
3767 EXPORT_SYMBOL(kfree);
3769 #define SHRINK_PROMOTE_MAX 32
3772 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
3773 * up most to the head of the partial lists. New allocations will then
3774 * fill those up and thus they can be removed from the partial lists.
3776 * The slabs with the least items are placed last. This results in them
3777 * being allocated from last increasing the chance that the last objects
3778 * are freed in them.
3780 int __kmem_cache_shrink(struct kmem_cache *s, bool deactivate)
3784 struct kmem_cache_node *n;
3787 struct list_head discard;
3788 struct list_head promote[SHRINK_PROMOTE_MAX];
3789 unsigned long flags;
3794 * Disable empty slabs caching. Used to avoid pinning offline
3795 * memory cgroups by kmem pages that can be freed.
3801 * s->cpu_partial is checked locklessly (see put_cpu_partial),
3802 * so we have to make sure the change is visible.
3804 kick_all_cpus_sync();
3808 for_each_kmem_cache_node(s, node, n) {
3809 INIT_LIST_HEAD(&discard);
3810 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
3811 INIT_LIST_HEAD(promote + i);
3813 spin_lock_irqsave(&n->list_lock, flags);
3816 * Build lists of slabs to discard or promote.
3818 * Note that concurrent frees may occur while we hold the
3819 * list_lock. page->inuse here is the upper limit.
3821 list_for_each_entry_safe(page, t, &n->partial, lru) {
3822 int free = page->objects - page->inuse;
3824 /* Do not reread page->inuse */
3827 /* We do not keep full slabs on the list */
3830 if (free == page->objects) {
3831 list_move(&page->lru, &discard);
3833 } else if (free <= SHRINK_PROMOTE_MAX)
3834 list_move(&page->lru, promote + free - 1);
3838 * Promote the slabs filled up most to the head of the
3841 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
3842 list_splice(promote + i, &n->partial);
3844 spin_unlock_irqrestore(&n->list_lock, flags);
3846 /* Release empty slabs */
3847 list_for_each_entry_safe(page, t, &discard, lru)
3848 discard_slab(s, page);
3850 if (slabs_node(s, node))
3857 static int slab_mem_going_offline_callback(void *arg)
3859 struct kmem_cache *s;
3861 mutex_lock(&slab_mutex);
3862 list_for_each_entry(s, &slab_caches, list)
3863 __kmem_cache_shrink(s, false);
3864 mutex_unlock(&slab_mutex);
3869 static void slab_mem_offline_callback(void *arg)
3871 struct kmem_cache_node *n;
3872 struct kmem_cache *s;
3873 struct memory_notify *marg = arg;
3876 offline_node = marg->status_change_nid_normal;
3879 * If the node still has available memory. we need kmem_cache_node
3882 if (offline_node < 0)
3885 mutex_lock(&slab_mutex);
3886 list_for_each_entry(s, &slab_caches, list) {
3887 n = get_node(s, offline_node);
3890 * if n->nr_slabs > 0, slabs still exist on the node
3891 * that is going down. We were unable to free them,
3892 * and offline_pages() function shouldn't call this
3893 * callback. So, we must fail.
3895 BUG_ON(slabs_node(s, offline_node));
3897 s->node[offline_node] = NULL;
3898 kmem_cache_free(kmem_cache_node, n);
3901 mutex_unlock(&slab_mutex);
3904 static int slab_mem_going_online_callback(void *arg)
3906 struct kmem_cache_node *n;
3907 struct kmem_cache *s;
3908 struct memory_notify *marg = arg;
3909 int nid = marg->status_change_nid_normal;
3913 * If the node's memory is already available, then kmem_cache_node is
3914 * already created. Nothing to do.
3920 * We are bringing a node online. No memory is available yet. We must
3921 * allocate a kmem_cache_node structure in order to bring the node
3924 mutex_lock(&slab_mutex);
3925 list_for_each_entry(s, &slab_caches, list) {
3927 * XXX: kmem_cache_alloc_node will fallback to other nodes
3928 * since memory is not yet available from the node that
3931 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
3936 init_kmem_cache_node(n);
3940 mutex_unlock(&slab_mutex);
3944 static int slab_memory_callback(struct notifier_block *self,
3945 unsigned long action, void *arg)
3950 case MEM_GOING_ONLINE:
3951 ret = slab_mem_going_online_callback(arg);
3953 case MEM_GOING_OFFLINE:
3954 ret = slab_mem_going_offline_callback(arg);
3957 case MEM_CANCEL_ONLINE:
3958 slab_mem_offline_callback(arg);
3961 case MEM_CANCEL_OFFLINE:
3965 ret = notifier_from_errno(ret);
3971 static struct notifier_block slab_memory_callback_nb = {
3972 .notifier_call = slab_memory_callback,
3973 .priority = SLAB_CALLBACK_PRI,
3976 /********************************************************************
3977 * Basic setup of slabs
3978 *******************************************************************/
3981 * Used for early kmem_cache structures that were allocated using
3982 * the page allocator. Allocate them properly then fix up the pointers
3983 * that may be pointing to the wrong kmem_cache structure.
3986 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
3989 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
3990 struct kmem_cache_node *n;
3992 memcpy(s, static_cache, kmem_cache->object_size);
3995 * This runs very early, and only the boot processor is supposed to be
3996 * up. Even if it weren't true, IRQs are not up so we couldn't fire
3999 __flush_cpu_slab(s, smp_processor_id());
4000 for_each_kmem_cache_node(s, node, n) {
4003 list_for_each_entry(p, &n->partial, lru)
4006 #ifdef CONFIG_SLUB_DEBUG
4007 list_for_each_entry(p, &n->full, lru)
4011 slab_init_memcg_params(s);
4012 list_add(&s->list, &slab_caches);
4016 void __init kmem_cache_init(void)
4018 static __initdata struct kmem_cache boot_kmem_cache,
4019 boot_kmem_cache_node;
4021 if (debug_guardpage_minorder())
4024 kmem_cache_node = &boot_kmem_cache_node;
4025 kmem_cache = &boot_kmem_cache;
4027 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4028 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN);
4030 register_hotmemory_notifier(&slab_memory_callback_nb);
4032 /* Able to allocate the per node structures */
4033 slab_state = PARTIAL;
4035 create_boot_cache(kmem_cache, "kmem_cache",
4036 offsetof(struct kmem_cache, node) +
4037 nr_node_ids * sizeof(struct kmem_cache_node *),
4038 SLAB_HWCACHE_ALIGN);
4040 kmem_cache = bootstrap(&boot_kmem_cache);
4043 * Allocate kmem_cache_node properly from the kmem_cache slab.
4044 * kmem_cache_node is separately allocated so no need to
4045 * update any list pointers.
4047 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4049 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4050 setup_kmalloc_cache_index_table();
4051 create_kmalloc_caches(0);
4054 register_cpu_notifier(&slab_notifier);
4057 pr_info("SLUB: HWalign=%d, Order=%d-%d, MinObjects=%d, CPUs=%d, Nodes=%d\n",
4059 slub_min_order, slub_max_order, slub_min_objects,
4060 nr_cpu_ids, nr_node_ids);
4063 void __init kmem_cache_init_late(void)
4068 __kmem_cache_alias(const char *name, size_t size, size_t align,
4069 unsigned long flags, void (*ctor)(void *))
4071 struct kmem_cache *s, *c;
4073 s = find_mergeable(size, align, flags, name, ctor);
4078 * Adjust the object sizes so that we clear
4079 * the complete object on kzalloc.
4081 s->object_size = max(s->object_size, (int)size);
4082 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
4084 for_each_memcg_cache(c, s) {
4085 c->object_size = s->object_size;
4086 c->inuse = max_t(int, c->inuse,
4087 ALIGN(size, sizeof(void *)));
4090 if (sysfs_slab_alias(s, name)) {
4099 int __kmem_cache_create(struct kmem_cache *s, unsigned long flags)
4103 err = kmem_cache_open(s, flags);
4107 /* Mutex is not taken during early boot */
4108 if (slab_state <= UP)
4111 memcg_propagate_slab_attrs(s);
4112 err = sysfs_slab_add(s);
4114 kmem_cache_close(s);
4121 * Use the cpu notifier to insure that the cpu slabs are flushed when
4124 static int slab_cpuup_callback(struct notifier_block *nfb,
4125 unsigned long action, void *hcpu)
4127 long cpu = (long)hcpu;
4128 struct kmem_cache *s;
4129 unsigned long flags;
4132 case CPU_UP_CANCELED:
4133 case CPU_UP_CANCELED_FROZEN:
4135 case CPU_DEAD_FROZEN:
4136 mutex_lock(&slab_mutex);
4137 list_for_each_entry(s, &slab_caches, list) {
4138 local_irq_save(flags);
4139 __flush_cpu_slab(s, cpu);
4140 local_irq_restore(flags);
4142 mutex_unlock(&slab_mutex);
4150 static struct notifier_block slab_notifier = {
4151 .notifier_call = slab_cpuup_callback
4156 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4158 struct kmem_cache *s;
4161 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4162 return kmalloc_large(size, gfpflags);
4164 s = kmalloc_slab(size, gfpflags);
4166 if (unlikely(ZERO_OR_NULL_PTR(s)))
4169 ret = slab_alloc(s, gfpflags, caller);
4171 /* Honor the call site pointer we received. */
4172 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4178 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4179 int node, unsigned long caller)
4181 struct kmem_cache *s;
4184 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4185 ret = kmalloc_large_node(size, gfpflags, node);
4187 trace_kmalloc_node(caller, ret,
4188 size, PAGE_SIZE << get_order(size),
4194 s = kmalloc_slab(size, gfpflags);
4196 if (unlikely(ZERO_OR_NULL_PTR(s)))
4199 ret = slab_alloc_node(s, gfpflags, node, caller);
4201 /* Honor the call site pointer we received. */
4202 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4209 static int count_inuse(struct page *page)
4214 static int count_total(struct page *page)
4216 return page->objects;
4220 #ifdef CONFIG_SLUB_DEBUG
4221 static int validate_slab(struct kmem_cache *s, struct page *page,
4225 void *addr = page_address(page);
4227 if (!check_slab(s, page) ||
4228 !on_freelist(s, page, NULL))
4231 /* Now we know that a valid freelist exists */
4232 bitmap_zero(map, page->objects);
4234 get_map(s, page, map);
4235 for_each_object(p, s, addr, page->objects) {
4236 if (test_bit(slab_index(p, s, addr), map))
4237 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4241 for_each_object(p, s, addr, page->objects)
4242 if (!test_bit(slab_index(p, s, addr), map))
4243 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4248 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4252 validate_slab(s, page, map);
4256 static int validate_slab_node(struct kmem_cache *s,
4257 struct kmem_cache_node *n, unsigned long *map)
4259 unsigned long count = 0;
4261 unsigned long flags;
4263 spin_lock_irqsave(&n->list_lock, flags);
4265 list_for_each_entry(page, &n->partial, lru) {
4266 validate_slab_slab(s, page, map);
4269 if (count != n->nr_partial)
4270 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4271 s->name, count, n->nr_partial);
4273 if (!(s->flags & SLAB_STORE_USER))
4276 list_for_each_entry(page, &n->full, lru) {
4277 validate_slab_slab(s, page, map);
4280 if (count != atomic_long_read(&n->nr_slabs))
4281 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4282 s->name, count, atomic_long_read(&n->nr_slabs));
4285 spin_unlock_irqrestore(&n->list_lock, flags);
4289 static long validate_slab_cache(struct kmem_cache *s)
4292 unsigned long count = 0;
4293 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4294 sizeof(unsigned long), GFP_KERNEL);
4295 struct kmem_cache_node *n;
4301 for_each_kmem_cache_node(s, node, n)
4302 count += validate_slab_node(s, n, map);
4307 * Generate lists of code addresses where slabcache objects are allocated
4312 unsigned long count;
4319 DECLARE_BITMAP(cpus, NR_CPUS);
4325 unsigned long count;
4326 struct location *loc;
4329 static void free_loc_track(struct loc_track *t)
4332 free_pages((unsigned long)t->loc,
4333 get_order(sizeof(struct location) * t->max));
4336 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4341 order = get_order(sizeof(struct location) * max);
4343 l = (void *)__get_free_pages(flags, order);
4348 memcpy(l, t->loc, sizeof(struct location) * t->count);
4356 static int add_location(struct loc_track *t, struct kmem_cache *s,
4357 const struct track *track)
4359 long start, end, pos;
4361 unsigned long caddr;
4362 unsigned long age = jiffies - track->when;
4368 pos = start + (end - start + 1) / 2;
4371 * There is nothing at "end". If we end up there
4372 * we need to add something to before end.
4377 caddr = t->loc[pos].addr;
4378 if (track->addr == caddr) {
4384 if (age < l->min_time)
4386 if (age > l->max_time)
4389 if (track->pid < l->min_pid)
4390 l->min_pid = track->pid;
4391 if (track->pid > l->max_pid)
4392 l->max_pid = track->pid;
4394 cpumask_set_cpu(track->cpu,
4395 to_cpumask(l->cpus));
4397 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4401 if (track->addr < caddr)
4408 * Not found. Insert new tracking element.
4410 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4416 (t->count - pos) * sizeof(struct location));
4419 l->addr = track->addr;
4423 l->min_pid = track->pid;
4424 l->max_pid = track->pid;
4425 cpumask_clear(to_cpumask(l->cpus));
4426 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4427 nodes_clear(l->nodes);
4428 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4432 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4433 struct page *page, enum track_item alloc,
4436 void *addr = page_address(page);
4439 bitmap_zero(map, page->objects);
4440 get_map(s, page, map);
4442 for_each_object(p, s, addr, page->objects)
4443 if (!test_bit(slab_index(p, s, addr), map))
4444 add_location(t, s, get_track(s, p, alloc));
4447 static int list_locations(struct kmem_cache *s, char *buf,
4448 enum track_item alloc)
4452 struct loc_track t = { 0, 0, NULL };
4454 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4455 sizeof(unsigned long), GFP_KERNEL);
4456 struct kmem_cache_node *n;
4458 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4461 return sprintf(buf, "Out of memory\n");
4463 /* Push back cpu slabs */
4466 for_each_kmem_cache_node(s, node, n) {
4467 unsigned long flags;
4470 if (!atomic_long_read(&n->nr_slabs))
4473 spin_lock_irqsave(&n->list_lock, flags);
4474 list_for_each_entry(page, &n->partial, lru)
4475 process_slab(&t, s, page, alloc, map);
4476 list_for_each_entry(page, &n->full, lru)
4477 process_slab(&t, s, page, alloc, map);
4478 spin_unlock_irqrestore(&n->list_lock, flags);
4481 for (i = 0; i < t.count; i++) {
4482 struct location *l = &t.loc[i];
4484 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4486 len += sprintf(buf + len, "%7ld ", l->count);
4489 len += sprintf(buf + len, "%pS", (void *)l->addr);
4491 len += sprintf(buf + len, "<not-available>");
4493 if (l->sum_time != l->min_time) {
4494 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4496 (long)div_u64(l->sum_time, l->count),
4499 len += sprintf(buf + len, " age=%ld",
4502 if (l->min_pid != l->max_pid)
4503 len += sprintf(buf + len, " pid=%ld-%ld",
4504 l->min_pid, l->max_pid);
4506 len += sprintf(buf + len, " pid=%ld",
4509 if (num_online_cpus() > 1 &&
4510 !cpumask_empty(to_cpumask(l->cpus)) &&
4511 len < PAGE_SIZE - 60)
4512 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4514 cpumask_pr_args(to_cpumask(l->cpus)));
4516 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4517 len < PAGE_SIZE - 60)
4518 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4520 nodemask_pr_args(&l->nodes));
4522 len += sprintf(buf + len, "\n");
4528 len += sprintf(buf, "No data\n");
4533 #ifdef SLUB_RESILIENCY_TEST
4534 static void __init resiliency_test(void)
4538 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4540 pr_err("SLUB resiliency testing\n");
4541 pr_err("-----------------------\n");
4542 pr_err("A. Corruption after allocation\n");
4544 p = kzalloc(16, GFP_KERNEL);
4546 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4549 validate_slab_cache(kmalloc_caches[4]);
4551 /* Hmmm... The next two are dangerous */
4552 p = kzalloc(32, GFP_KERNEL);
4553 p[32 + sizeof(void *)] = 0x34;
4554 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4556 pr_err("If allocated object is overwritten then not detectable\n\n");
4558 validate_slab_cache(kmalloc_caches[5]);
4559 p = kzalloc(64, GFP_KERNEL);
4560 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4562 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4564 pr_err("If allocated object is overwritten then not detectable\n\n");
4565 validate_slab_cache(kmalloc_caches[6]);
4567 pr_err("\nB. Corruption after free\n");
4568 p = kzalloc(128, GFP_KERNEL);
4571 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4572 validate_slab_cache(kmalloc_caches[7]);
4574 p = kzalloc(256, GFP_KERNEL);
4577 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4578 validate_slab_cache(kmalloc_caches[8]);
4580 p = kzalloc(512, GFP_KERNEL);
4583 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4584 validate_slab_cache(kmalloc_caches[9]);
4588 static void resiliency_test(void) {};
4593 enum slab_stat_type {
4594 SL_ALL, /* All slabs */
4595 SL_PARTIAL, /* Only partially allocated slabs */
4596 SL_CPU, /* Only slabs used for cpu caches */
4597 SL_OBJECTS, /* Determine allocated objects not slabs */
4598 SL_TOTAL /* Determine object capacity not slabs */
4601 #define SO_ALL (1 << SL_ALL)
4602 #define SO_PARTIAL (1 << SL_PARTIAL)
4603 #define SO_CPU (1 << SL_CPU)
4604 #define SO_OBJECTS (1 << SL_OBJECTS)
4605 #define SO_TOTAL (1 << SL_TOTAL)
4607 static ssize_t show_slab_objects(struct kmem_cache *s,
4608 char *buf, unsigned long flags)
4610 unsigned long total = 0;
4613 unsigned long *nodes;
4615 nodes = kzalloc(sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
4619 if (flags & SO_CPU) {
4622 for_each_possible_cpu(cpu) {
4623 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4628 page = READ_ONCE(c->page);
4632 node = page_to_nid(page);
4633 if (flags & SO_TOTAL)
4635 else if (flags & SO_OBJECTS)
4643 page = READ_ONCE(c->partial);
4645 node = page_to_nid(page);
4646 if (flags & SO_TOTAL)
4648 else if (flags & SO_OBJECTS)
4659 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
4660 * already held which will conflict with an existing lock order:
4662 * mem_hotplug_lock->slab_mutex->kernfs_mutex
4664 * We don't really need mem_hotplug_lock (to hold off
4665 * slab_mem_going_offline_callback) here because slab's memory hot
4666 * unplug code doesn't destroy the kmem_cache->node[] data.
4669 #ifdef CONFIG_SLUB_DEBUG
4670 if (flags & SO_ALL) {
4671 struct kmem_cache_node *n;
4673 for_each_kmem_cache_node(s, node, n) {
4675 if (flags & SO_TOTAL)
4676 x = atomic_long_read(&n->total_objects);
4677 else if (flags & SO_OBJECTS)
4678 x = atomic_long_read(&n->total_objects) -
4679 count_partial(n, count_free);
4681 x = atomic_long_read(&n->nr_slabs);
4688 if (flags & SO_PARTIAL) {
4689 struct kmem_cache_node *n;
4691 for_each_kmem_cache_node(s, node, n) {
4692 if (flags & SO_TOTAL)
4693 x = count_partial(n, count_total);
4694 else if (flags & SO_OBJECTS)
4695 x = count_partial(n, count_inuse);
4702 x = sprintf(buf, "%lu", total);
4704 for (node = 0; node < nr_node_ids; node++)
4706 x += sprintf(buf + x, " N%d=%lu",
4710 return x + sprintf(buf + x, "\n");
4713 #ifdef CONFIG_SLUB_DEBUG
4714 static int any_slab_objects(struct kmem_cache *s)
4717 struct kmem_cache_node *n;
4719 for_each_kmem_cache_node(s, node, n)
4720 if (atomic_long_read(&n->total_objects))
4727 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4728 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4730 struct slab_attribute {
4731 struct attribute attr;
4732 ssize_t (*show)(struct kmem_cache *s, char *buf);
4733 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4736 #define SLAB_ATTR_RO(_name) \
4737 static struct slab_attribute _name##_attr = \
4738 __ATTR(_name, 0400, _name##_show, NULL)
4740 #define SLAB_ATTR(_name) \
4741 static struct slab_attribute _name##_attr = \
4742 __ATTR(_name, 0600, _name##_show, _name##_store)
4744 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4746 return sprintf(buf, "%d\n", s->size);
4748 SLAB_ATTR_RO(slab_size);
4750 static ssize_t align_show(struct kmem_cache *s, char *buf)
4752 return sprintf(buf, "%d\n", s->align);
4754 SLAB_ATTR_RO(align);
4756 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
4758 return sprintf(buf, "%d\n", s->object_size);
4760 SLAB_ATTR_RO(object_size);
4762 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
4764 return sprintf(buf, "%d\n", oo_objects(s->oo));
4766 SLAB_ATTR_RO(objs_per_slab);
4768 static ssize_t order_store(struct kmem_cache *s,
4769 const char *buf, size_t length)
4771 unsigned long order;
4774 err = kstrtoul(buf, 10, &order);
4778 if (order > slub_max_order || order < slub_min_order)
4781 calculate_sizes(s, order);
4785 static ssize_t order_show(struct kmem_cache *s, char *buf)
4787 return sprintf(buf, "%d\n", oo_order(s->oo));
4791 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
4793 return sprintf(buf, "%lu\n", s->min_partial);
4796 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
4802 err = kstrtoul(buf, 10, &min);
4806 set_min_partial(s, min);
4809 SLAB_ATTR(min_partial);
4811 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
4813 return sprintf(buf, "%u\n", s->cpu_partial);
4816 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
4819 unsigned int objects;
4822 err = kstrtouint(buf, 10, &objects);
4825 if (objects && !kmem_cache_has_cpu_partial(s))
4828 s->cpu_partial = objects;
4832 SLAB_ATTR(cpu_partial);
4834 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
4838 return sprintf(buf, "%pS\n", s->ctor);
4842 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
4844 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
4846 SLAB_ATTR_RO(aliases);
4848 static ssize_t partial_show(struct kmem_cache *s, char *buf)
4850 return show_slab_objects(s, buf, SO_PARTIAL);
4852 SLAB_ATTR_RO(partial);
4854 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
4856 return show_slab_objects(s, buf, SO_CPU);
4858 SLAB_ATTR_RO(cpu_slabs);
4860 static ssize_t objects_show(struct kmem_cache *s, char *buf)
4862 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
4864 SLAB_ATTR_RO(objects);
4866 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
4868 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
4870 SLAB_ATTR_RO(objects_partial);
4872 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
4879 for_each_online_cpu(cpu) {
4880 struct page *page = per_cpu_ptr(s->cpu_slab, cpu)->partial;
4883 pages += page->pages;
4884 objects += page->pobjects;
4888 len = sprintf(buf, "%d(%d)", objects, pages);
4891 for_each_online_cpu(cpu) {
4892 struct page *page = per_cpu_ptr(s->cpu_slab, cpu) ->partial;
4894 if (page && len < PAGE_SIZE - 20)
4895 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
4896 page->pobjects, page->pages);
4899 return len + sprintf(buf + len, "\n");
4901 SLAB_ATTR_RO(slabs_cpu_partial);
4903 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
4905 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
4908 static ssize_t reclaim_account_store(struct kmem_cache *s,
4909 const char *buf, size_t length)
4911 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
4913 s->flags |= SLAB_RECLAIM_ACCOUNT;
4916 SLAB_ATTR(reclaim_account);
4918 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
4920 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
4922 SLAB_ATTR_RO(hwcache_align);
4924 #ifdef CONFIG_ZONE_DMA
4925 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
4927 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
4929 SLAB_ATTR_RO(cache_dma);
4932 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
4934 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
4936 SLAB_ATTR_RO(destroy_by_rcu);
4938 static ssize_t reserved_show(struct kmem_cache *s, char *buf)
4940 return sprintf(buf, "%d\n", s->reserved);
4942 SLAB_ATTR_RO(reserved);
4944 #ifdef CONFIG_SLUB_DEBUG
4945 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
4947 return show_slab_objects(s, buf, SO_ALL);
4949 SLAB_ATTR_RO(slabs);
4951 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
4953 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
4955 SLAB_ATTR_RO(total_objects);
4957 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
4959 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
4962 static ssize_t sanity_checks_store(struct kmem_cache *s,
4963 const char *buf, size_t length)
4965 s->flags &= ~SLAB_DEBUG_FREE;
4966 if (buf[0] == '1') {
4967 s->flags &= ~__CMPXCHG_DOUBLE;
4968 s->flags |= SLAB_DEBUG_FREE;
4972 SLAB_ATTR(sanity_checks);
4974 static ssize_t trace_show(struct kmem_cache *s, char *buf)
4976 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
4979 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
4983 * Tracing a merged cache is going to give confusing results
4984 * as well as cause other issues like converting a mergeable
4985 * cache into an umergeable one.
4987 if (s->refcount > 1)
4990 s->flags &= ~SLAB_TRACE;
4991 if (buf[0] == '1') {
4992 s->flags &= ~__CMPXCHG_DOUBLE;
4993 s->flags |= SLAB_TRACE;
4999 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5001 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5004 static ssize_t red_zone_store(struct kmem_cache *s,
5005 const char *buf, size_t length)
5007 if (any_slab_objects(s))
5010 s->flags &= ~SLAB_RED_ZONE;
5011 if (buf[0] == '1') {
5012 s->flags &= ~__CMPXCHG_DOUBLE;
5013 s->flags |= SLAB_RED_ZONE;
5015 calculate_sizes(s, -1);
5018 SLAB_ATTR(red_zone);
5020 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5022 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5025 static ssize_t poison_store(struct kmem_cache *s,
5026 const char *buf, size_t length)
5028 if (any_slab_objects(s))
5031 s->flags &= ~SLAB_POISON;
5032 if (buf[0] == '1') {
5033 s->flags &= ~__CMPXCHG_DOUBLE;
5034 s->flags |= SLAB_POISON;
5036 calculate_sizes(s, -1);
5041 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5043 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5046 static ssize_t store_user_store(struct kmem_cache *s,
5047 const char *buf, size_t length)
5049 if (any_slab_objects(s))
5052 s->flags &= ~SLAB_STORE_USER;
5053 if (buf[0] == '1') {
5054 s->flags &= ~__CMPXCHG_DOUBLE;
5055 s->flags |= SLAB_STORE_USER;
5057 calculate_sizes(s, -1);
5060 SLAB_ATTR(store_user);
5062 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5067 static ssize_t validate_store(struct kmem_cache *s,
5068 const char *buf, size_t length)
5072 if (buf[0] == '1') {
5073 ret = validate_slab_cache(s);
5079 SLAB_ATTR(validate);
5081 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5083 if (!(s->flags & SLAB_STORE_USER))
5085 return list_locations(s, buf, TRACK_ALLOC);
5087 SLAB_ATTR_RO(alloc_calls);
5089 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5091 if (!(s->flags & SLAB_STORE_USER))
5093 return list_locations(s, buf, TRACK_FREE);
5095 SLAB_ATTR_RO(free_calls);
5096 #endif /* CONFIG_SLUB_DEBUG */
5098 #ifdef CONFIG_FAILSLAB
5099 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5101 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5104 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5107 if (s->refcount > 1)
5110 s->flags &= ~SLAB_FAILSLAB;
5112 s->flags |= SLAB_FAILSLAB;
5115 SLAB_ATTR(failslab);
5118 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5123 static ssize_t shrink_store(struct kmem_cache *s,
5124 const char *buf, size_t length)
5127 kmem_cache_shrink(s);
5135 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5137 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
5140 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5141 const char *buf, size_t length)
5143 unsigned long ratio;
5146 err = kstrtoul(buf, 10, &ratio);
5151 s->remote_node_defrag_ratio = ratio * 10;
5155 SLAB_ATTR(remote_node_defrag_ratio);
5158 #ifdef CONFIG_SLUB_STATS
5159 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5161 unsigned long sum = 0;
5164 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
5169 for_each_online_cpu(cpu) {
5170 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5176 len = sprintf(buf, "%lu", sum);
5179 for_each_online_cpu(cpu) {
5180 if (data[cpu] && len < PAGE_SIZE - 20)
5181 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5185 return len + sprintf(buf + len, "\n");
5188 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5192 for_each_online_cpu(cpu)
5193 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5196 #define STAT_ATTR(si, text) \
5197 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5199 return show_stat(s, buf, si); \
5201 static ssize_t text##_store(struct kmem_cache *s, \
5202 const char *buf, size_t length) \
5204 if (buf[0] != '0') \
5206 clear_stat(s, si); \
5211 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5212 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5213 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5214 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5215 STAT_ATTR(FREE_FROZEN, free_frozen);
5216 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5217 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5218 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5219 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5220 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5221 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5222 STAT_ATTR(FREE_SLAB, free_slab);
5223 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5224 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5225 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5226 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5227 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5228 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5229 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5230 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5231 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5232 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5233 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5234 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5235 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5236 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5239 static struct attribute *slab_attrs[] = {
5240 &slab_size_attr.attr,
5241 &object_size_attr.attr,
5242 &objs_per_slab_attr.attr,
5244 &min_partial_attr.attr,
5245 &cpu_partial_attr.attr,
5247 &objects_partial_attr.attr,
5249 &cpu_slabs_attr.attr,
5253 &hwcache_align_attr.attr,
5254 &reclaim_account_attr.attr,
5255 &destroy_by_rcu_attr.attr,
5257 &reserved_attr.attr,
5258 &slabs_cpu_partial_attr.attr,
5259 #ifdef CONFIG_SLUB_DEBUG
5260 &total_objects_attr.attr,
5262 &sanity_checks_attr.attr,
5264 &red_zone_attr.attr,
5266 &store_user_attr.attr,
5267 &validate_attr.attr,
5268 &alloc_calls_attr.attr,
5269 &free_calls_attr.attr,
5271 #ifdef CONFIG_ZONE_DMA
5272 &cache_dma_attr.attr,
5275 &remote_node_defrag_ratio_attr.attr,
5277 #ifdef CONFIG_SLUB_STATS
5278 &alloc_fastpath_attr.attr,
5279 &alloc_slowpath_attr.attr,
5280 &free_fastpath_attr.attr,
5281 &free_slowpath_attr.attr,
5282 &free_frozen_attr.attr,
5283 &free_add_partial_attr.attr,
5284 &free_remove_partial_attr.attr,
5285 &alloc_from_partial_attr.attr,
5286 &alloc_slab_attr.attr,
5287 &alloc_refill_attr.attr,
5288 &alloc_node_mismatch_attr.attr,
5289 &free_slab_attr.attr,
5290 &cpuslab_flush_attr.attr,
5291 &deactivate_full_attr.attr,
5292 &deactivate_empty_attr.attr,
5293 &deactivate_to_head_attr.attr,
5294 &deactivate_to_tail_attr.attr,
5295 &deactivate_remote_frees_attr.attr,
5296 &deactivate_bypass_attr.attr,
5297 &order_fallback_attr.attr,
5298 &cmpxchg_double_fail_attr.attr,
5299 &cmpxchg_double_cpu_fail_attr.attr,
5300 &cpu_partial_alloc_attr.attr,
5301 &cpu_partial_free_attr.attr,
5302 &cpu_partial_node_attr.attr,
5303 &cpu_partial_drain_attr.attr,
5305 #ifdef CONFIG_FAILSLAB
5306 &failslab_attr.attr,
5312 static struct attribute_group slab_attr_group = {
5313 .attrs = slab_attrs,
5316 static ssize_t slab_attr_show(struct kobject *kobj,
5317 struct attribute *attr,
5320 struct slab_attribute *attribute;
5321 struct kmem_cache *s;
5324 attribute = to_slab_attr(attr);
5327 if (!attribute->show)
5330 err = attribute->show(s, buf);
5335 static ssize_t slab_attr_store(struct kobject *kobj,
5336 struct attribute *attr,
5337 const char *buf, size_t len)
5339 struct slab_attribute *attribute;
5340 struct kmem_cache *s;
5343 attribute = to_slab_attr(attr);
5346 if (!attribute->store)
5349 err = attribute->store(s, buf, len);
5350 #ifdef CONFIG_MEMCG_KMEM
5351 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5352 struct kmem_cache *c;
5354 mutex_lock(&slab_mutex);
5355 if (s->max_attr_size < len)
5356 s->max_attr_size = len;
5359 * This is a best effort propagation, so this function's return
5360 * value will be determined by the parent cache only. This is
5361 * basically because not all attributes will have a well
5362 * defined semantics for rollbacks - most of the actions will
5363 * have permanent effects.
5365 * Returning the error value of any of the children that fail
5366 * is not 100 % defined, in the sense that users seeing the
5367 * error code won't be able to know anything about the state of
5370 * Only returning the error code for the parent cache at least
5371 * has well defined semantics. The cache being written to
5372 * directly either failed or succeeded, in which case we loop
5373 * through the descendants with best-effort propagation.
5375 for_each_memcg_cache(c, s)
5376 attribute->store(c, buf, len);
5377 mutex_unlock(&slab_mutex);
5383 static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5385 #ifdef CONFIG_MEMCG_KMEM
5387 char *buffer = NULL;
5388 struct kmem_cache *root_cache;
5390 if (is_root_cache(s))
5393 root_cache = s->memcg_params.root_cache;
5396 * This mean this cache had no attribute written. Therefore, no point
5397 * in copying default values around
5399 if (!root_cache->max_attr_size)
5402 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5405 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5408 if (!attr || !attr->store || !attr->show)
5412 * It is really bad that we have to allocate here, so we will
5413 * do it only as a fallback. If we actually allocate, though,
5414 * we can just use the allocated buffer until the end.
5416 * Most of the slub attributes will tend to be very small in
5417 * size, but sysfs allows buffers up to a page, so they can
5418 * theoretically happen.
5422 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf))
5425 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5426 if (WARN_ON(!buffer))
5431 len = attr->show(root_cache, buf);
5433 attr->store(s, buf, len);
5437 free_page((unsigned long)buffer);
5441 static void kmem_cache_release(struct kobject *k)
5443 slab_kmem_cache_release(to_slab(k));
5446 static const struct sysfs_ops slab_sysfs_ops = {
5447 .show = slab_attr_show,
5448 .store = slab_attr_store,
5451 static struct kobj_type slab_ktype = {
5452 .sysfs_ops = &slab_sysfs_ops,
5453 .release = kmem_cache_release,
5456 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5458 struct kobj_type *ktype = get_ktype(kobj);
5460 if (ktype == &slab_ktype)
5465 static const struct kset_uevent_ops slab_uevent_ops = {
5466 .filter = uevent_filter,
5469 static struct kset *slab_kset;
5471 static inline struct kset *cache_kset(struct kmem_cache *s)
5473 #ifdef CONFIG_MEMCG_KMEM
5474 if (!is_root_cache(s))
5475 return s->memcg_params.root_cache->memcg_kset;
5480 #define ID_STR_LENGTH 64
5482 /* Create a unique string id for a slab cache:
5484 * Format :[flags-]size
5486 static char *create_unique_id(struct kmem_cache *s)
5488 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5495 * First flags affecting slabcache operations. We will only
5496 * get here for aliasable slabs so we do not need to support
5497 * too many flags. The flags here must cover all flags that
5498 * are matched during merging to guarantee that the id is
5501 if (s->flags & SLAB_CACHE_DMA)
5503 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5505 if (s->flags & SLAB_DEBUG_FREE)
5507 if (!(s->flags & SLAB_NOTRACK))
5511 p += sprintf(p, "%07d", s->size);
5513 BUG_ON(p > name + ID_STR_LENGTH - 1);
5517 static int sysfs_slab_add(struct kmem_cache *s)
5521 int unmergeable = slab_unmergeable(s);
5525 * Slabcache can never be merged so we can use the name proper.
5526 * This is typically the case for debug situations. In that
5527 * case we can catch duplicate names easily.
5529 sysfs_remove_link(&slab_kset->kobj, s->name);
5533 * Create a unique name for the slab as a target
5536 name = create_unique_id(s);
5539 s->kobj.kset = cache_kset(s);
5540 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5544 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5548 #ifdef CONFIG_MEMCG_KMEM
5549 if (is_root_cache(s)) {
5550 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5551 if (!s->memcg_kset) {
5558 kobject_uevent(&s->kobj, KOBJ_ADD);
5560 /* Setup first alias */
5561 sysfs_slab_alias(s, s->name);
5568 kobject_del(&s->kobj);
5572 void sysfs_slab_remove(struct kmem_cache *s)
5574 if (slab_state < FULL)
5576 * Sysfs has not been setup yet so no need to remove the
5581 #ifdef CONFIG_MEMCG_KMEM
5582 kset_unregister(s->memcg_kset);
5584 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5585 kobject_del(&s->kobj);
5586 kobject_put(&s->kobj);
5590 * Need to buffer aliases during bootup until sysfs becomes
5591 * available lest we lose that information.
5593 struct saved_alias {
5594 struct kmem_cache *s;
5596 struct saved_alias *next;
5599 static struct saved_alias *alias_list;
5601 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5603 struct saved_alias *al;
5605 if (slab_state == FULL) {
5607 * If we have a leftover link then remove it.
5609 sysfs_remove_link(&slab_kset->kobj, name);
5610 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5613 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5619 al->next = alias_list;
5624 static int __init slab_sysfs_init(void)
5626 struct kmem_cache *s;
5629 mutex_lock(&slab_mutex);
5631 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5633 mutex_unlock(&slab_mutex);
5634 pr_err("Cannot register slab subsystem.\n");
5640 list_for_each_entry(s, &slab_caches, list) {
5641 err = sysfs_slab_add(s);
5643 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5647 while (alias_list) {
5648 struct saved_alias *al = alias_list;
5650 alias_list = alias_list->next;
5651 err = sysfs_slab_alias(al->s, al->name);
5653 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5658 mutex_unlock(&slab_mutex);
5663 __initcall(slab_sysfs_init);
5664 #endif /* CONFIG_SYSFS */
5667 * The /proc/slabinfo ABI
5669 #ifdef CONFIG_SLABINFO
5670 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5672 unsigned long nr_slabs = 0;
5673 unsigned long nr_objs = 0;
5674 unsigned long nr_free = 0;
5676 struct kmem_cache_node *n;
5678 for_each_kmem_cache_node(s, node, n) {
5679 nr_slabs += node_nr_slabs(n);
5680 nr_objs += node_nr_objs(n);
5681 nr_free += count_partial(n, count_free);
5684 sinfo->active_objs = nr_objs - nr_free;
5685 sinfo->num_objs = nr_objs;
5686 sinfo->active_slabs = nr_slabs;
5687 sinfo->num_slabs = nr_slabs;
5688 sinfo->objects_per_slab = oo_objects(s->oo);
5689 sinfo->cache_order = oo_order(s->oo);
5692 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5696 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5697 size_t count, loff_t *ppos)
5701 #endif /* CONFIG_SLABINFO */