1 // SPDX-License-Identifier: GPL-2.0
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
6 * The allocator synchronizes using per slab locks or atomic operatios
7 * and only uses a centralized lock to manage a pool of partial slabs.
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
14 #include <linux/swap.h> /* struct reclaim_state */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/bitops.h>
19 #include <linux/slab.h>
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/kasan.h>
24 #include <linux/cpu.h>
25 #include <linux/cpuset.h>
26 #include <linux/mempolicy.h>
27 #include <linux/ctype.h>
28 #include <linux/debugobjects.h>
29 #include <linux/kallsyms.h>
30 #include <linux/memory.h>
31 #include <linux/math64.h>
32 #include <linux/fault-inject.h>
33 #include <linux/stacktrace.h>
34 #include <linux/prefetch.h>
35 #include <linux/memcontrol.h>
36 #include <linux/random.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:
55 * A. page->freelist -> List of object free in a page
56 * B. page->inuse -> Number of objects in use
57 * C. page->objects -> Number of objects in page
58 * D. page->frozen -> frozen state
60 * If a slab is frozen then it is exempt from list management. It is not
61 * on any list except per cpu partial list. The processor that froze the
62 * slab is the one who can perform list operations on the page. Other
63 * processors may put objects onto the freelist but the processor that
64 * froze the slab is the only one that can retrieve the objects from the
67 * The list_lock protects the partial and full list on each node and
68 * the partial slab counter. If taken then no new slabs may be added or
69 * removed from the lists nor make the number of partial slabs be modified.
70 * (Note that the total number of slabs is an atomic value that may be
71 * modified without taking the list lock).
73 * The list_lock is a centralized lock and thus we avoid taking it as
74 * much as possible. As long as SLUB does not have to handle partial
75 * slabs, operations can continue without any centralized lock. F.e.
76 * allocating a long series of objects that fill up slabs does not require
78 * Interrupts are disabled during allocation and deallocation in order to
79 * make the slab allocator safe to use in the context of an irq. In addition
80 * interrupts are disabled to ensure that the processor does not change
81 * while handling per_cpu slabs, due to kernel preemption.
83 * SLUB assigns one slab for allocation to each processor.
84 * Allocations only occur from these slabs called cpu slabs.
86 * Slabs with free elements are kept on a partial list and during regular
87 * operations no list for full slabs is used. If an object in a full slab is
88 * freed then the slab will show up again on the partial lists.
89 * We track full slabs for debugging purposes though because otherwise we
90 * cannot scan all objects.
92 * Slabs are freed when they become empty. Teardown and setup is
93 * minimal so we rely on the page allocators per cpu caches for
94 * fast frees and allocs.
96 * page->frozen The slab is frozen and exempt from list processing.
97 * This means that the slab is dedicated to a purpose
98 * such as satisfying allocations for a specific
99 * processor. Objects may be freed in the slab while
100 * it is frozen but slab_free will then skip the usual
101 * list operations. It is up to the processor holding
102 * the slab to integrate the slab into the slab lists
103 * when the slab is no longer needed.
105 * One use of this flag is to mark slabs that are
106 * used for allocations. Then such a slab becomes a cpu
107 * slab. The cpu slab may be equipped with an additional
108 * freelist that allows lockless access to
109 * free objects in addition to the regular freelist
110 * that requires the slab lock.
112 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
113 * options set. This moves slab handling out of
114 * the fast path and disables lockless freelists.
117 #ifdef CONFIG_SLUB_DEBUG
118 #ifdef CONFIG_SLUB_DEBUG_ON
119 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
121 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
126 * Returns true if any of the specified slub_debug flags is enabled for the
127 * cache. Use only for flags parsed by setup_slub_debug() as it also enables
130 static inline bool kmem_cache_debug_flags(struct kmem_cache *s, slab_flags_t flags)
132 VM_WARN_ON_ONCE(!(flags & SLAB_DEBUG_FLAGS));
133 #ifdef CONFIG_SLUB_DEBUG
134 if (static_branch_unlikely(&slub_debug_enabled))
135 return s->flags & flags;
140 static inline bool kmem_cache_debug(struct kmem_cache *s)
142 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
145 void *fixup_red_left(struct kmem_cache *s, void *p)
147 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
148 p += s->red_left_pad;
153 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
155 #ifdef CONFIG_SLUB_CPU_PARTIAL
156 return !kmem_cache_debug(s);
163 * Issues still to be resolved:
165 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
167 * - Variable sizing of the per node arrays
170 /* Enable to test recovery from slab corruption on boot */
171 #undef SLUB_RESILIENCY_TEST
173 /* Enable to log cmpxchg failures */
174 #undef SLUB_DEBUG_CMPXCHG
177 * Mininum number of partial slabs. These will be left on the partial
178 * lists even if they are empty. kmem_cache_shrink may reclaim them.
180 #define MIN_PARTIAL 5
183 * Maximum number of desirable partial slabs.
184 * The existence of more partial slabs makes kmem_cache_shrink
185 * sort the partial list by the number of objects in use.
187 #define MAX_PARTIAL 10
189 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
190 SLAB_POISON | SLAB_STORE_USER)
193 * These debug flags cannot use CMPXCHG because there might be consistency
194 * issues when checking or reading debug information
196 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
201 * Debugging flags that require metadata to be stored in the slab. These get
202 * disabled when slub_debug=O is used and a cache's min order increases with
205 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
208 #define OO_MASK ((1 << OO_SHIFT) - 1)
209 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
211 /* Internal SLUB flags */
213 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
214 /* Use cmpxchg_double */
215 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
218 * Tracking user of a slab.
220 #define TRACK_ADDRS_COUNT 16
222 unsigned long addr; /* Called from address */
223 #ifdef CONFIG_STACKTRACE
224 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
226 int cpu; /* Was running on cpu */
227 int pid; /* Pid context */
228 unsigned long when; /* When did the operation occur */
231 enum track_item { TRACK_ALLOC, TRACK_FREE };
234 static int sysfs_slab_add(struct kmem_cache *);
235 static int sysfs_slab_alias(struct kmem_cache *, const char *);
236 static void memcg_propagate_slab_attrs(struct kmem_cache *s);
237 static void sysfs_slab_remove(struct kmem_cache *s);
239 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
240 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
242 static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { }
243 static inline void sysfs_slab_remove(struct kmem_cache *s) { }
246 static inline void stat(const struct kmem_cache *s, enum stat_item si)
248 #ifdef CONFIG_SLUB_STATS
250 * The rmw is racy on a preemptible kernel but this is acceptable, so
251 * avoid this_cpu_add()'s irq-disable overhead.
253 raw_cpu_inc(s->cpu_slab->stat[si]);
257 /********************************************************************
258 * Core slab cache functions
259 *******************************************************************/
262 * Returns freelist pointer (ptr). With hardening, this is obfuscated
263 * with an XOR of the address where the pointer is held and a per-cache
266 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
267 unsigned long ptr_addr)
269 #ifdef CONFIG_SLAB_FREELIST_HARDENED
271 * When CONFIG_KASAN_SW_TAGS is enabled, ptr_addr might be tagged.
272 * Normally, this doesn't cause any issues, as both set_freepointer()
273 * and get_freepointer() are called with a pointer with the same tag.
274 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
275 * example, when __free_slub() iterates over objects in a cache, it
276 * passes untagged pointers to check_object(). check_object() in turns
277 * calls get_freepointer() with an untagged pointer, which causes the
278 * freepointer to be restored incorrectly.
280 return (void *)((unsigned long)ptr ^ s->random ^
281 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
287 /* Returns the freelist pointer recorded at location ptr_addr. */
288 static inline void *freelist_dereference(const struct kmem_cache *s,
291 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
292 (unsigned long)ptr_addr);
295 static inline void *get_freepointer(struct kmem_cache *s, void *object)
297 return freelist_dereference(s, object + s->offset);
300 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
302 prefetch(object + s->offset);
305 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
307 unsigned long freepointer_addr;
310 if (!debug_pagealloc_enabled_static())
311 return get_freepointer(s, object);
313 freepointer_addr = (unsigned long)object + s->offset;
314 copy_from_kernel_nofault(&p, (void **)freepointer_addr, sizeof(p));
315 return freelist_ptr(s, p, freepointer_addr);
318 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
320 unsigned long freeptr_addr = (unsigned long)object + s->offset;
322 #ifdef CONFIG_SLAB_FREELIST_HARDENED
323 BUG_ON(object == fp); /* naive detection of double free or corruption */
326 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
329 /* Loop over all objects in a slab */
330 #define for_each_object(__p, __s, __addr, __objects) \
331 for (__p = fixup_red_left(__s, __addr); \
332 __p < (__addr) + (__objects) * (__s)->size; \
335 /* Determine object index from a given position */
336 static inline unsigned int slab_index(void *p, struct kmem_cache *s, void *addr)
338 return (kasan_reset_tag(p) - addr) / s->size;
341 static inline unsigned int order_objects(unsigned int order, unsigned int size)
343 return ((unsigned int)PAGE_SIZE << order) / size;
346 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
349 struct kmem_cache_order_objects x = {
350 (order << OO_SHIFT) + order_objects(order, size)
356 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
358 return x.x >> OO_SHIFT;
361 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
363 return x.x & OO_MASK;
367 * Per slab locking using the pagelock
369 static __always_inline void slab_lock(struct page *page)
371 VM_BUG_ON_PAGE(PageTail(page), page);
372 bit_spin_lock(PG_locked, &page->flags);
375 static __always_inline void slab_unlock(struct page *page)
377 VM_BUG_ON_PAGE(PageTail(page), page);
378 __bit_spin_unlock(PG_locked, &page->flags);
381 /* Interrupts must be disabled (for the fallback code to work right) */
382 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
383 void *freelist_old, unsigned long counters_old,
384 void *freelist_new, unsigned long counters_new,
387 VM_BUG_ON(!irqs_disabled());
388 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
389 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
390 if (s->flags & __CMPXCHG_DOUBLE) {
391 if (cmpxchg_double(&page->freelist, &page->counters,
392 freelist_old, counters_old,
393 freelist_new, counters_new))
399 if (page->freelist == freelist_old &&
400 page->counters == counters_old) {
401 page->freelist = freelist_new;
402 page->counters = counters_new;
410 stat(s, CMPXCHG_DOUBLE_FAIL);
412 #ifdef SLUB_DEBUG_CMPXCHG
413 pr_info("%s %s: cmpxchg double redo ", n, s->name);
419 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
420 void *freelist_old, unsigned long counters_old,
421 void *freelist_new, unsigned long counters_new,
424 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
425 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
426 if (s->flags & __CMPXCHG_DOUBLE) {
427 if (cmpxchg_double(&page->freelist, &page->counters,
428 freelist_old, counters_old,
429 freelist_new, counters_new))
436 local_irq_save(flags);
438 if (page->freelist == freelist_old &&
439 page->counters == counters_old) {
440 page->freelist = freelist_new;
441 page->counters = counters_new;
443 local_irq_restore(flags);
447 local_irq_restore(flags);
451 stat(s, CMPXCHG_DOUBLE_FAIL);
453 #ifdef SLUB_DEBUG_CMPXCHG
454 pr_info("%s %s: cmpxchg double redo ", n, s->name);
460 #ifdef CONFIG_SLUB_DEBUG
461 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
462 static DEFINE_SPINLOCK(object_map_lock);
465 * Determine a map of object in use on a page.
467 * Node listlock must be held to guarantee that the page does
468 * not vanish from under us.
470 static unsigned long *get_map(struct kmem_cache *s, struct page *page)
471 __acquires(&object_map_lock)
474 void *addr = page_address(page);
476 VM_BUG_ON(!irqs_disabled());
478 spin_lock(&object_map_lock);
480 bitmap_zero(object_map, page->objects);
482 for (p = page->freelist; p; p = get_freepointer(s, p))
483 set_bit(slab_index(p, s, addr), object_map);
488 static void put_map(unsigned long *map) __releases(&object_map_lock)
490 VM_BUG_ON(map != object_map);
491 lockdep_assert_held(&object_map_lock);
493 spin_unlock(&object_map_lock);
496 static inline unsigned int size_from_object(struct kmem_cache *s)
498 if (s->flags & SLAB_RED_ZONE)
499 return s->size - s->red_left_pad;
504 static inline void *restore_red_left(struct kmem_cache *s, void *p)
506 if (s->flags & SLAB_RED_ZONE)
507 p -= s->red_left_pad;
515 #if defined(CONFIG_SLUB_DEBUG_ON)
516 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
518 static slab_flags_t slub_debug;
521 static char *slub_debug_string;
522 static int disable_higher_order_debug;
525 * slub is about to manipulate internal object metadata. This memory lies
526 * outside the range of the allocated object, so accessing it would normally
527 * be reported by kasan as a bounds error. metadata_access_enable() is used
528 * to tell kasan that these accesses are OK.
530 static inline void metadata_access_enable(void)
532 kasan_disable_current();
535 static inline void metadata_access_disable(void)
537 kasan_enable_current();
544 /* Verify that a pointer has an address that is valid within a slab page */
545 static inline int check_valid_pointer(struct kmem_cache *s,
546 struct page *page, void *object)
553 base = page_address(page);
554 object = kasan_reset_tag(object);
555 object = restore_red_left(s, object);
556 if (object < base || object >= base + page->objects * s->size ||
557 (object - base) % s->size) {
564 static void print_section(char *level, char *text, u8 *addr,
567 metadata_access_enable();
568 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
570 metadata_access_disable();
574 * See comment in calculate_sizes().
576 static inline bool freeptr_outside_object(struct kmem_cache *s)
578 return s->offset >= s->inuse;
582 * Return offset of the end of info block which is inuse + free pointer if
583 * not overlapping with object.
585 static inline unsigned int get_info_end(struct kmem_cache *s)
587 if (freeptr_outside_object(s))
588 return s->inuse + sizeof(void *);
593 static struct track *get_track(struct kmem_cache *s, void *object,
594 enum track_item alloc)
598 p = object + get_info_end(s);
603 static void set_track(struct kmem_cache *s, void *object,
604 enum track_item alloc, unsigned long addr)
606 struct track *p = get_track(s, object, alloc);
609 #ifdef CONFIG_STACKTRACE
610 unsigned int nr_entries;
612 metadata_access_enable();
613 nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
614 metadata_access_disable();
616 if (nr_entries < TRACK_ADDRS_COUNT)
617 p->addrs[nr_entries] = 0;
620 p->cpu = smp_processor_id();
621 p->pid = current->pid;
624 memset(p, 0, sizeof(struct track));
628 static void init_tracking(struct kmem_cache *s, void *object)
630 if (!(s->flags & SLAB_STORE_USER))
633 set_track(s, object, TRACK_FREE, 0UL);
634 set_track(s, object, TRACK_ALLOC, 0UL);
637 static void print_track(const char *s, struct track *t, unsigned long pr_time)
642 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
643 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
644 #ifdef CONFIG_STACKTRACE
647 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
649 pr_err("\t%pS\n", (void *)t->addrs[i]);
656 static void print_tracking(struct kmem_cache *s, void *object)
658 unsigned long pr_time = jiffies;
659 if (!(s->flags & SLAB_STORE_USER))
662 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
663 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
666 static void print_page_info(struct page *page)
668 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
669 page, page->objects, page->inuse, page->freelist, page->flags);
673 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
675 struct va_format vaf;
681 pr_err("=============================================================================\n");
682 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
683 pr_err("-----------------------------------------------------------------------------\n\n");
685 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
689 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
691 struct va_format vaf;
697 pr_err("FIX %s: %pV\n", s->name, &vaf);
701 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
702 void *freelist, void *nextfree)
704 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
705 !check_valid_pointer(s, page, nextfree)) {
706 object_err(s, page, freelist, "Freechain corrupt");
708 slab_fix(s, "Isolate corrupted freechain");
715 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
717 unsigned int off; /* Offset of last byte */
718 u8 *addr = page_address(page);
720 print_tracking(s, p);
722 print_page_info(page);
724 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
725 p, p - addr, get_freepointer(s, p));
727 if (s->flags & SLAB_RED_ZONE)
728 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
730 else if (p > addr + 16)
731 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
733 print_section(KERN_ERR, "Object ", p,
734 min_t(unsigned int, s->object_size, PAGE_SIZE));
735 if (s->flags & SLAB_RED_ZONE)
736 print_section(KERN_ERR, "Redzone ", p + s->object_size,
737 s->inuse - s->object_size);
739 off = get_info_end(s);
741 if (s->flags & SLAB_STORE_USER)
742 off += 2 * sizeof(struct track);
744 off += kasan_metadata_size(s);
746 if (off != size_from_object(s))
747 /* Beginning of the filler is the free pointer */
748 print_section(KERN_ERR, "Padding ", p + off,
749 size_from_object(s) - off);
754 void object_err(struct kmem_cache *s, struct page *page,
755 u8 *object, char *reason)
757 slab_bug(s, "%s", reason);
758 print_trailer(s, page, object);
761 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
762 const char *fmt, ...)
768 vsnprintf(buf, sizeof(buf), fmt, args);
770 slab_bug(s, "%s", buf);
771 print_page_info(page);
775 static void init_object(struct kmem_cache *s, void *object, u8 val)
779 if (s->flags & SLAB_RED_ZONE)
780 memset(p - s->red_left_pad, val, s->red_left_pad);
782 if (s->flags & __OBJECT_POISON) {
783 memset(p, POISON_FREE, s->object_size - 1);
784 p[s->object_size - 1] = POISON_END;
787 if (s->flags & SLAB_RED_ZONE)
788 memset(p + s->object_size, val, s->inuse - s->object_size);
791 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
792 void *from, void *to)
794 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
795 memset(from, data, to - from);
798 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
799 u8 *object, char *what,
800 u8 *start, unsigned int value, unsigned int bytes)
804 u8 *addr = page_address(page);
806 metadata_access_enable();
807 fault = memchr_inv(start, value, bytes);
808 metadata_access_disable();
813 while (end > fault && end[-1] == value)
816 slab_bug(s, "%s overwritten", what);
817 pr_err("INFO: 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
818 fault, end - 1, fault - addr,
820 print_trailer(s, page, object);
822 restore_bytes(s, what, value, fault, end);
830 * Bytes of the object to be managed.
831 * If the freepointer may overlay the object then the free
832 * pointer is at the middle of the object.
834 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
837 * object + s->object_size
838 * Padding to reach word boundary. This is also used for Redzoning.
839 * Padding is extended by another word if Redzoning is enabled and
840 * object_size == inuse.
842 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
843 * 0xcc (RED_ACTIVE) for objects in use.
846 * Meta data starts here.
848 * A. Free pointer (if we cannot overwrite object on free)
849 * B. Tracking data for SLAB_STORE_USER
850 * C. Padding to reach required alignment boundary or at mininum
851 * one word if debugging is on to be able to detect writes
852 * before the word boundary.
854 * Padding is done using 0x5a (POISON_INUSE)
857 * Nothing is used beyond s->size.
859 * If slabcaches are merged then the object_size and inuse boundaries are mostly
860 * ignored. And therefore no slab options that rely on these boundaries
861 * may be used with merged slabcaches.
864 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
866 unsigned long off = get_info_end(s); /* The end of info */
868 if (s->flags & SLAB_STORE_USER)
869 /* We also have user information there */
870 off += 2 * sizeof(struct track);
872 off += kasan_metadata_size(s);
874 if (size_from_object(s) == off)
877 return check_bytes_and_report(s, page, p, "Object padding",
878 p + off, POISON_INUSE, size_from_object(s) - off);
881 /* Check the pad bytes at the end of a slab page */
882 static int slab_pad_check(struct kmem_cache *s, struct page *page)
891 if (!(s->flags & SLAB_POISON))
894 start = page_address(page);
895 length = page_size(page);
896 end = start + length;
897 remainder = length % s->size;
901 pad = end - remainder;
902 metadata_access_enable();
903 fault = memchr_inv(pad, POISON_INUSE, remainder);
904 metadata_access_disable();
907 while (end > fault && end[-1] == POISON_INUSE)
910 slab_err(s, page, "Padding overwritten. 0x%p-0x%p @offset=%tu",
911 fault, end - 1, fault - start);
912 print_section(KERN_ERR, "Padding ", pad, remainder);
914 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
918 static int check_object(struct kmem_cache *s, struct page *page,
919 void *object, u8 val)
922 u8 *endobject = object + s->object_size;
924 if (s->flags & SLAB_RED_ZONE) {
925 if (!check_bytes_and_report(s, page, object, "Redzone",
926 object - s->red_left_pad, val, s->red_left_pad))
929 if (!check_bytes_and_report(s, page, object, "Redzone",
930 endobject, val, s->inuse - s->object_size))
933 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
934 check_bytes_and_report(s, page, p, "Alignment padding",
935 endobject, POISON_INUSE,
936 s->inuse - s->object_size);
940 if (s->flags & SLAB_POISON) {
941 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
942 (!check_bytes_and_report(s, page, p, "Poison", p,
943 POISON_FREE, s->object_size - 1) ||
944 !check_bytes_and_report(s, page, p, "Poison",
945 p + s->object_size - 1, POISON_END, 1)))
948 * check_pad_bytes cleans up on its own.
950 check_pad_bytes(s, page, p);
953 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
955 * Object and freepointer overlap. Cannot check
956 * freepointer while object is allocated.
960 /* Check free pointer validity */
961 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
962 object_err(s, page, p, "Freepointer corrupt");
964 * No choice but to zap it and thus lose the remainder
965 * of the free objects in this slab. May cause
966 * another error because the object count is now wrong.
968 set_freepointer(s, p, NULL);
974 static int check_slab(struct kmem_cache *s, struct page *page)
978 VM_BUG_ON(!irqs_disabled());
980 if (!PageSlab(page)) {
981 slab_err(s, page, "Not a valid slab page");
985 maxobj = order_objects(compound_order(page), s->size);
986 if (page->objects > maxobj) {
987 slab_err(s, page, "objects %u > max %u",
988 page->objects, maxobj);
991 if (page->inuse > page->objects) {
992 slab_err(s, page, "inuse %u > max %u",
993 page->inuse, page->objects);
996 /* Slab_pad_check fixes things up after itself */
997 slab_pad_check(s, page);
1002 * Determine if a certain object on a page is on the freelist. Must hold the
1003 * slab lock to guarantee that the chains are in a consistent state.
1005 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
1009 void *object = NULL;
1012 fp = page->freelist;
1013 while (fp && nr <= page->objects) {
1016 if (!check_valid_pointer(s, page, fp)) {
1018 object_err(s, page, object,
1019 "Freechain corrupt");
1020 set_freepointer(s, object, NULL);
1022 slab_err(s, page, "Freepointer corrupt");
1023 page->freelist = NULL;
1024 page->inuse = page->objects;
1025 slab_fix(s, "Freelist cleared");
1031 fp = get_freepointer(s, object);
1035 max_objects = order_objects(compound_order(page), s->size);
1036 if (max_objects > MAX_OBJS_PER_PAGE)
1037 max_objects = MAX_OBJS_PER_PAGE;
1039 if (page->objects != max_objects) {
1040 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1041 page->objects, max_objects);
1042 page->objects = max_objects;
1043 slab_fix(s, "Number of objects adjusted.");
1045 if (page->inuse != page->objects - nr) {
1046 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1047 page->inuse, page->objects - nr);
1048 page->inuse = page->objects - nr;
1049 slab_fix(s, "Object count adjusted.");
1051 return search == NULL;
1054 static void trace(struct kmem_cache *s, struct page *page, void *object,
1057 if (s->flags & SLAB_TRACE) {
1058 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1060 alloc ? "alloc" : "free",
1061 object, page->inuse,
1065 print_section(KERN_INFO, "Object ", (void *)object,
1073 * Tracking of fully allocated slabs for debugging purposes.
1075 static void add_full(struct kmem_cache *s,
1076 struct kmem_cache_node *n, struct page *page)
1078 if (!(s->flags & SLAB_STORE_USER))
1081 lockdep_assert_held(&n->list_lock);
1082 list_add(&page->slab_list, &n->full);
1085 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1087 if (!(s->flags & SLAB_STORE_USER))
1090 lockdep_assert_held(&n->list_lock);
1091 list_del(&page->slab_list);
1094 /* Tracking of the number of slabs for debugging purposes */
1095 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1097 struct kmem_cache_node *n = get_node(s, node);
1099 return atomic_long_read(&n->nr_slabs);
1102 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1104 return atomic_long_read(&n->nr_slabs);
1107 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1109 struct kmem_cache_node *n = get_node(s, node);
1112 * May be called early in order to allocate a slab for the
1113 * kmem_cache_node structure. Solve the chicken-egg
1114 * dilemma by deferring the increment of the count during
1115 * bootstrap (see early_kmem_cache_node_alloc).
1118 atomic_long_inc(&n->nr_slabs);
1119 atomic_long_add(objects, &n->total_objects);
1122 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1124 struct kmem_cache_node *n = get_node(s, node);
1126 atomic_long_dec(&n->nr_slabs);
1127 atomic_long_sub(objects, &n->total_objects);
1130 /* Object debug checks for alloc/free paths */
1131 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1134 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1137 init_object(s, object, SLUB_RED_INACTIVE);
1138 init_tracking(s, object);
1142 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1144 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1147 metadata_access_enable();
1148 memset(addr, POISON_INUSE, page_size(page));
1149 metadata_access_disable();
1152 static inline int alloc_consistency_checks(struct kmem_cache *s,
1153 struct page *page, void *object)
1155 if (!check_slab(s, page))
1158 if (!check_valid_pointer(s, page, object)) {
1159 object_err(s, page, object, "Freelist Pointer check fails");
1163 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1169 static noinline int alloc_debug_processing(struct kmem_cache *s,
1171 void *object, unsigned long addr)
1173 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1174 if (!alloc_consistency_checks(s, page, object))
1178 /* Success perform special debug activities for allocs */
1179 if (s->flags & SLAB_STORE_USER)
1180 set_track(s, object, TRACK_ALLOC, addr);
1181 trace(s, page, object, 1);
1182 init_object(s, object, SLUB_RED_ACTIVE);
1186 if (PageSlab(page)) {
1188 * If this is a slab page then lets do the best we can
1189 * to avoid issues in the future. Marking all objects
1190 * as used avoids touching the remaining objects.
1192 slab_fix(s, "Marking all objects used");
1193 page->inuse = page->objects;
1194 page->freelist = NULL;
1199 static inline int free_consistency_checks(struct kmem_cache *s,
1200 struct page *page, void *object, unsigned long addr)
1202 if (!check_valid_pointer(s, page, object)) {
1203 slab_err(s, page, "Invalid object pointer 0x%p", object);
1207 if (on_freelist(s, page, object)) {
1208 object_err(s, page, object, "Object already free");
1212 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1215 if (unlikely(s != page->slab_cache)) {
1216 if (!PageSlab(page)) {
1217 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1219 } else if (!page->slab_cache) {
1220 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1224 object_err(s, page, object,
1225 "page slab pointer corrupt.");
1231 /* Supports checking bulk free of a constructed freelist */
1232 static noinline int free_debug_processing(
1233 struct kmem_cache *s, struct page *page,
1234 void *head, void *tail, int bulk_cnt,
1237 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1238 void *object = head;
1240 unsigned long flags;
1243 spin_lock_irqsave(&n->list_lock, flags);
1246 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1247 if (!check_slab(s, page))
1254 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1255 if (!free_consistency_checks(s, page, object, addr))
1259 if (s->flags & SLAB_STORE_USER)
1260 set_track(s, object, TRACK_FREE, addr);
1261 trace(s, page, object, 0);
1262 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1263 init_object(s, object, SLUB_RED_INACTIVE);
1265 /* Reached end of constructed freelist yet? */
1266 if (object != tail) {
1267 object = get_freepointer(s, object);
1273 if (cnt != bulk_cnt)
1274 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1278 spin_unlock_irqrestore(&n->list_lock, flags);
1280 slab_fix(s, "Object at 0x%p not freed", object);
1285 * Parse a block of slub_debug options. Blocks are delimited by ';'
1287 * @str: start of block
1288 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1289 * @slabs: return start of list of slabs, or NULL when there's no list
1290 * @init: assume this is initial parsing and not per-kmem-create parsing
1292 * returns the start of next block if there's any, or NULL
1295 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1297 bool higher_order_disable = false;
1299 /* Skip any completely empty blocks */
1300 while (*str && *str == ';')
1305 * No options but restriction on slabs. This means full
1306 * debugging for slabs matching a pattern.
1308 *flags = DEBUG_DEFAULT_FLAGS;
1313 /* Determine which debug features should be switched on */
1314 for (; *str && *str != ',' && *str != ';'; str++) {
1315 switch (tolower(*str)) {
1320 *flags |= SLAB_CONSISTENCY_CHECKS;
1323 *flags |= SLAB_RED_ZONE;
1326 *flags |= SLAB_POISON;
1329 *flags |= SLAB_STORE_USER;
1332 *flags |= SLAB_TRACE;
1335 *flags |= SLAB_FAILSLAB;
1339 * Avoid enabling debugging on caches if its minimum
1340 * order would increase as a result.
1342 higher_order_disable = true;
1346 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
1355 /* Skip over the slab list */
1356 while (*str && *str != ';')
1359 /* Skip any completely empty blocks */
1360 while (*str && *str == ';')
1363 if (init && higher_order_disable)
1364 disable_higher_order_debug = 1;
1372 static int __init setup_slub_debug(char *str)
1377 bool global_slub_debug_changed = false;
1378 bool slab_list_specified = false;
1380 slub_debug = DEBUG_DEFAULT_FLAGS;
1381 if (*str++ != '=' || !*str)
1383 * No options specified. Switch on full debugging.
1389 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1393 global_slub_debug_changed = true;
1395 slab_list_specified = true;
1400 * For backwards compatibility, a single list of flags with list of
1401 * slabs means debugging is only enabled for those slabs, so the global
1402 * slub_debug should be 0. We can extended that to multiple lists as
1403 * long as there is no option specifying flags without a slab list.
1405 if (slab_list_specified) {
1406 if (!global_slub_debug_changed)
1408 slub_debug_string = saved_str;
1411 if (slub_debug != 0 || slub_debug_string)
1412 static_branch_enable(&slub_debug_enabled);
1413 if ((static_branch_unlikely(&init_on_alloc) ||
1414 static_branch_unlikely(&init_on_free)) &&
1415 (slub_debug & SLAB_POISON))
1416 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1420 __setup("slub_debug", setup_slub_debug);
1423 * kmem_cache_flags - apply debugging options to the cache
1424 * @object_size: the size of an object without meta data
1425 * @flags: flags to set
1426 * @name: name of the cache
1427 * @ctor: constructor function
1429 * Debug option(s) are applied to @flags. In addition to the debug
1430 * option(s), if a slab name (or multiple) is specified i.e.
1431 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1432 * then only the select slabs will receive the debug option(s).
1434 slab_flags_t kmem_cache_flags(unsigned int object_size,
1435 slab_flags_t flags, const char *name,
1436 void (*ctor)(void *))
1441 slab_flags_t block_flags;
1443 /* If slub_debug = 0, it folds into the if conditional. */
1444 if (!slub_debug_string)
1445 return flags | slub_debug;
1448 next_block = slub_debug_string;
1449 /* Go through all blocks of debug options, see if any matches our slab's name */
1450 while (next_block) {
1451 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1454 /* Found a block that has a slab list, search it */
1459 end = strchrnul(iter, ',');
1460 if (next_block && next_block < end)
1461 end = next_block - 1;
1463 glob = strnchr(iter, end - iter, '*');
1465 cmplen = glob - iter;
1467 cmplen = max_t(size_t, len, (end - iter));
1469 if (!strncmp(name, iter, cmplen)) {
1470 flags |= block_flags;
1474 if (!*end || *end == ';')
1482 #else /* !CONFIG_SLUB_DEBUG */
1483 static inline void setup_object_debug(struct kmem_cache *s,
1484 struct page *page, void *object) {}
1486 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1488 static inline int alloc_debug_processing(struct kmem_cache *s,
1489 struct page *page, void *object, unsigned long addr) { return 0; }
1491 static inline int free_debug_processing(
1492 struct kmem_cache *s, struct page *page,
1493 void *head, void *tail, int bulk_cnt,
1494 unsigned long addr) { return 0; }
1496 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1498 static inline int check_object(struct kmem_cache *s, struct page *page,
1499 void *object, u8 val) { return 1; }
1500 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1501 struct page *page) {}
1502 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1503 struct page *page) {}
1504 slab_flags_t kmem_cache_flags(unsigned int object_size,
1505 slab_flags_t flags, const char *name,
1506 void (*ctor)(void *))
1510 #define slub_debug 0
1512 #define disable_higher_order_debug 0
1514 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1516 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1518 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1520 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1523 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1524 void *freelist, void *nextfree)
1529 static void print_tracking(struct kmem_cache *s, void *object)
1532 #endif /* CONFIG_SLUB_DEBUG */
1535 * Hooks for other subsystems that check memory allocations. In a typical
1536 * production configuration these hooks all should produce no code at all.
1538 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1540 ptr = kasan_kmalloc_large(ptr, size, flags);
1541 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1542 kmemleak_alloc(ptr, size, 1, flags);
1546 static __always_inline void kfree_hook(void *x)
1549 kasan_kfree_large(x, _RET_IP_);
1552 static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x)
1554 kmemleak_free_recursive(x, s->flags);
1557 * Trouble is that we may no longer disable interrupts in the fast path
1558 * So in order to make the debug calls that expect irqs to be
1559 * disabled we need to disable interrupts temporarily.
1561 #ifdef CONFIG_LOCKDEP
1563 unsigned long flags;
1565 local_irq_save(flags);
1566 debug_check_no_locks_freed(x, s->object_size);
1567 local_irq_restore(flags);
1570 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1571 debug_check_no_obj_freed(x, s->object_size);
1573 /* KASAN might put x into memory quarantine, delaying its reuse */
1574 return kasan_slab_free(s, x, _RET_IP_);
1577 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1578 void **head, void **tail)
1583 void *old_tail = *tail ? *tail : *head;
1586 /* Head and tail of the reconstructed freelist */
1592 next = get_freepointer(s, object);
1594 if (slab_want_init_on_free(s)) {
1596 * Clear the object and the metadata, but don't touch
1599 memset(object, 0, s->object_size);
1600 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad
1602 memset((char *)object + s->inuse, 0,
1603 s->size - s->inuse - rsize);
1606 /* If object's reuse doesn't have to be delayed */
1607 if (!slab_free_hook(s, object)) {
1608 /* Move object to the new freelist */
1609 set_freepointer(s, object, *head);
1614 } while (object != old_tail);
1619 return *head != NULL;
1622 static void *setup_object(struct kmem_cache *s, struct page *page,
1625 setup_object_debug(s, page, object);
1626 object = kasan_init_slab_obj(s, object);
1627 if (unlikely(s->ctor)) {
1628 kasan_unpoison_object_data(s, object);
1630 kasan_poison_object_data(s, object);
1636 * Slab allocation and freeing
1638 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1639 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1642 unsigned int order = oo_order(oo);
1644 if (node == NUMA_NO_NODE)
1645 page = alloc_pages(flags, order);
1647 page = __alloc_pages_node(node, flags, order);
1649 if (page && charge_slab_page(page, flags, order, s)) {
1650 __free_pages(page, order);
1657 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1658 /* Pre-initialize the random sequence cache */
1659 static int init_cache_random_seq(struct kmem_cache *s)
1661 unsigned int count = oo_objects(s->oo);
1664 /* Bailout if already initialised */
1668 err = cache_random_seq_create(s, count, GFP_KERNEL);
1670 pr_err("SLUB: Unable to initialize free list for %s\n",
1675 /* Transform to an offset on the set of pages */
1676 if (s->random_seq) {
1679 for (i = 0; i < count; i++)
1680 s->random_seq[i] *= s->size;
1685 /* Initialize each random sequence freelist per cache */
1686 static void __init init_freelist_randomization(void)
1688 struct kmem_cache *s;
1690 mutex_lock(&slab_mutex);
1692 list_for_each_entry(s, &slab_caches, list)
1693 init_cache_random_seq(s);
1695 mutex_unlock(&slab_mutex);
1698 /* Get the next entry on the pre-computed freelist randomized */
1699 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1700 unsigned long *pos, void *start,
1701 unsigned long page_limit,
1702 unsigned long freelist_count)
1707 * If the target page allocation failed, the number of objects on the
1708 * page might be smaller than the usual size defined by the cache.
1711 idx = s->random_seq[*pos];
1713 if (*pos >= freelist_count)
1715 } while (unlikely(idx >= page_limit));
1717 return (char *)start + idx;
1720 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1721 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1726 unsigned long idx, pos, page_limit, freelist_count;
1728 if (page->objects < 2 || !s->random_seq)
1731 freelist_count = oo_objects(s->oo);
1732 pos = get_random_int() % freelist_count;
1734 page_limit = page->objects * s->size;
1735 start = fixup_red_left(s, page_address(page));
1737 /* First entry is used as the base of the freelist */
1738 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1740 cur = setup_object(s, page, cur);
1741 page->freelist = cur;
1743 for (idx = 1; idx < page->objects; idx++) {
1744 next = next_freelist_entry(s, page, &pos, start, page_limit,
1746 next = setup_object(s, page, next);
1747 set_freepointer(s, cur, next);
1750 set_freepointer(s, cur, NULL);
1755 static inline int init_cache_random_seq(struct kmem_cache *s)
1759 static inline void init_freelist_randomization(void) { }
1760 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1764 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1766 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1769 struct kmem_cache_order_objects oo = s->oo;
1771 void *start, *p, *next;
1775 flags &= gfp_allowed_mask;
1777 if (gfpflags_allow_blocking(flags))
1780 flags |= s->allocflags;
1783 * Let the initial higher-order allocation fail under memory pressure
1784 * so we fall-back to the minimum order allocation.
1786 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1787 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1788 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1790 page = alloc_slab_page(s, alloc_gfp, node, oo);
1791 if (unlikely(!page)) {
1795 * Allocation may have failed due to fragmentation.
1796 * Try a lower order alloc if possible
1798 page = alloc_slab_page(s, alloc_gfp, node, oo);
1799 if (unlikely(!page))
1801 stat(s, ORDER_FALLBACK);
1804 page->objects = oo_objects(oo);
1806 page->slab_cache = s;
1807 __SetPageSlab(page);
1808 if (page_is_pfmemalloc(page))
1809 SetPageSlabPfmemalloc(page);
1811 kasan_poison_slab(page);
1813 start = page_address(page);
1815 setup_page_debug(s, page, start);
1817 shuffle = shuffle_freelist(s, page);
1820 start = fixup_red_left(s, start);
1821 start = setup_object(s, page, start);
1822 page->freelist = start;
1823 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1825 next = setup_object(s, page, next);
1826 set_freepointer(s, p, next);
1829 set_freepointer(s, p, NULL);
1832 page->inuse = page->objects;
1836 if (gfpflags_allow_blocking(flags))
1837 local_irq_disable();
1841 inc_slabs_node(s, page_to_nid(page), page->objects);
1846 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1848 if (unlikely(flags & GFP_SLAB_BUG_MASK))
1849 flags = kmalloc_fix_flags(flags);
1851 return allocate_slab(s,
1852 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1855 static void __free_slab(struct kmem_cache *s, struct page *page)
1857 int order = compound_order(page);
1858 int pages = 1 << order;
1860 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
1863 slab_pad_check(s, page);
1864 for_each_object(p, s, page_address(page),
1866 check_object(s, page, p, SLUB_RED_INACTIVE);
1869 __ClearPageSlabPfmemalloc(page);
1870 __ClearPageSlab(page);
1872 page->mapping = NULL;
1873 if (current->reclaim_state)
1874 current->reclaim_state->reclaimed_slab += pages;
1875 uncharge_slab_page(page, order, s);
1876 __free_pages(page, order);
1879 static void rcu_free_slab(struct rcu_head *h)
1881 struct page *page = container_of(h, struct page, rcu_head);
1883 __free_slab(page->slab_cache, page);
1886 static void free_slab(struct kmem_cache *s, struct page *page)
1888 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1889 call_rcu(&page->rcu_head, rcu_free_slab);
1891 __free_slab(s, page);
1894 static void discard_slab(struct kmem_cache *s, struct page *page)
1896 dec_slabs_node(s, page_to_nid(page), page->objects);
1901 * Management of partially allocated slabs.
1904 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1907 if (tail == DEACTIVATE_TO_TAIL)
1908 list_add_tail(&page->slab_list, &n->partial);
1910 list_add(&page->slab_list, &n->partial);
1913 static inline void add_partial(struct kmem_cache_node *n,
1914 struct page *page, int tail)
1916 lockdep_assert_held(&n->list_lock);
1917 __add_partial(n, page, tail);
1920 static inline void remove_partial(struct kmem_cache_node *n,
1923 lockdep_assert_held(&n->list_lock);
1924 list_del(&page->slab_list);
1929 * Remove slab from the partial list, freeze it and
1930 * return the pointer to the freelist.
1932 * Returns a list of objects or NULL if it fails.
1934 static inline void *acquire_slab(struct kmem_cache *s,
1935 struct kmem_cache_node *n, struct page *page,
1936 int mode, int *objects)
1939 unsigned long counters;
1942 lockdep_assert_held(&n->list_lock);
1945 * Zap the freelist and set the frozen bit.
1946 * The old freelist is the list of objects for the
1947 * per cpu allocation list.
1949 freelist = page->freelist;
1950 counters = page->counters;
1951 new.counters = counters;
1952 *objects = new.objects - new.inuse;
1954 new.inuse = page->objects;
1955 new.freelist = NULL;
1957 new.freelist = freelist;
1960 VM_BUG_ON(new.frozen);
1963 if (!__cmpxchg_double_slab(s, page,
1965 new.freelist, new.counters,
1969 remove_partial(n, page);
1974 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1975 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1978 * Try to allocate a partial slab from a specific node.
1980 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1981 struct kmem_cache_cpu *c, gfp_t flags)
1983 struct page *page, *page2;
1984 void *object = NULL;
1985 unsigned int available = 0;
1989 * Racy check. If we mistakenly see no partial slabs then we
1990 * just allocate an empty slab. If we mistakenly try to get a
1991 * partial slab and there is none available then get_partials()
1994 if (!n || !n->nr_partial)
1997 spin_lock(&n->list_lock);
1998 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
2001 if (!pfmemalloc_match(page, flags))
2004 t = acquire_slab(s, n, page, object == NULL, &objects);
2008 available += objects;
2011 stat(s, ALLOC_FROM_PARTIAL);
2014 put_cpu_partial(s, page, 0);
2015 stat(s, CPU_PARTIAL_NODE);
2017 if (!kmem_cache_has_cpu_partial(s)
2018 || available > slub_cpu_partial(s) / 2)
2022 spin_unlock(&n->list_lock);
2027 * Get a page from somewhere. Search in increasing NUMA distances.
2029 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
2030 struct kmem_cache_cpu *c)
2033 struct zonelist *zonelist;
2036 enum zone_type highest_zoneidx = gfp_zone(flags);
2038 unsigned int cpuset_mems_cookie;
2041 * The defrag ratio allows a configuration of the tradeoffs between
2042 * inter node defragmentation and node local allocations. A lower
2043 * defrag_ratio increases the tendency to do local allocations
2044 * instead of attempting to obtain partial slabs from other nodes.
2046 * If the defrag_ratio is set to 0 then kmalloc() always
2047 * returns node local objects. If the ratio is higher then kmalloc()
2048 * may return off node objects because partial slabs are obtained
2049 * from other nodes and filled up.
2051 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2052 * (which makes defrag_ratio = 1000) then every (well almost)
2053 * allocation will first attempt to defrag slab caches on other nodes.
2054 * This means scanning over all nodes to look for partial slabs which
2055 * may be expensive if we do it every time we are trying to find a slab
2056 * with available objects.
2058 if (!s->remote_node_defrag_ratio ||
2059 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2063 cpuset_mems_cookie = read_mems_allowed_begin();
2064 zonelist = node_zonelist(mempolicy_slab_node(), flags);
2065 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2066 struct kmem_cache_node *n;
2068 n = get_node(s, zone_to_nid(zone));
2070 if (n && cpuset_zone_allowed(zone, flags) &&
2071 n->nr_partial > s->min_partial) {
2072 object = get_partial_node(s, n, c, flags);
2075 * Don't check read_mems_allowed_retry()
2076 * here - if mems_allowed was updated in
2077 * parallel, that was a harmless race
2078 * between allocation and the cpuset
2085 } while (read_mems_allowed_retry(cpuset_mems_cookie));
2086 #endif /* CONFIG_NUMA */
2091 * Get a partial page, lock it and return it.
2093 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
2094 struct kmem_cache_cpu *c)
2097 int searchnode = node;
2099 if (node == NUMA_NO_NODE)
2100 searchnode = numa_mem_id();
2102 object = get_partial_node(s, get_node(s, searchnode), c, flags);
2103 if (object || node != NUMA_NO_NODE)
2106 return get_any_partial(s, flags, c);
2109 #ifdef CONFIG_PREEMPTION
2111 * Calculate the next globally unique transaction for disambiguation
2112 * during cmpxchg. The transactions start with the cpu number and are then
2113 * incremented by CONFIG_NR_CPUS.
2115 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2118 * No preemption supported therefore also no need to check for
2124 static inline unsigned long next_tid(unsigned long tid)
2126 return tid + TID_STEP;
2129 #ifdef SLUB_DEBUG_CMPXCHG
2130 static inline unsigned int tid_to_cpu(unsigned long tid)
2132 return tid % TID_STEP;
2135 static inline unsigned long tid_to_event(unsigned long tid)
2137 return tid / TID_STEP;
2141 static inline unsigned int init_tid(int cpu)
2146 static inline void note_cmpxchg_failure(const char *n,
2147 const struct kmem_cache *s, unsigned long tid)
2149 #ifdef SLUB_DEBUG_CMPXCHG
2150 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2152 pr_info("%s %s: cmpxchg redo ", n, s->name);
2154 #ifdef CONFIG_PREEMPTION
2155 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2156 pr_warn("due to cpu change %d -> %d\n",
2157 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2160 if (tid_to_event(tid) != tid_to_event(actual_tid))
2161 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2162 tid_to_event(tid), tid_to_event(actual_tid));
2164 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2165 actual_tid, tid, next_tid(tid));
2167 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2170 static void init_kmem_cache_cpus(struct kmem_cache *s)
2174 for_each_possible_cpu(cpu)
2175 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2179 * Remove the cpu slab
2181 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2182 void *freelist, struct kmem_cache_cpu *c)
2184 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2185 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2187 enum slab_modes l = M_NONE, m = M_NONE;
2189 int tail = DEACTIVATE_TO_HEAD;
2193 if (page->freelist) {
2194 stat(s, DEACTIVATE_REMOTE_FREES);
2195 tail = DEACTIVATE_TO_TAIL;
2199 * Stage one: Free all available per cpu objects back
2200 * to the page freelist while it is still frozen. Leave the
2203 * There is no need to take the list->lock because the page
2206 while (freelist && (nextfree = get_freepointer(s, freelist))) {
2208 unsigned long counters;
2211 * If 'nextfree' is invalid, it is possible that the object at
2212 * 'freelist' is already corrupted. So isolate all objects
2213 * starting at 'freelist'.
2215 if (freelist_corrupted(s, page, freelist, nextfree))
2219 prior = page->freelist;
2220 counters = page->counters;
2221 set_freepointer(s, freelist, prior);
2222 new.counters = counters;
2224 VM_BUG_ON(!new.frozen);
2226 } while (!__cmpxchg_double_slab(s, page,
2228 freelist, new.counters,
2229 "drain percpu freelist"));
2231 freelist = nextfree;
2235 * Stage two: Ensure that the page is unfrozen while the
2236 * list presence reflects the actual number of objects
2239 * We setup the list membership and then perform a cmpxchg
2240 * with the count. If there is a mismatch then the page
2241 * is not unfrozen but the page is on the wrong list.
2243 * Then we restart the process which may have to remove
2244 * the page from the list that we just put it on again
2245 * because the number of objects in the slab may have
2250 old.freelist = page->freelist;
2251 old.counters = page->counters;
2252 VM_BUG_ON(!old.frozen);
2254 /* Determine target state of the slab */
2255 new.counters = old.counters;
2258 set_freepointer(s, freelist, old.freelist);
2259 new.freelist = freelist;
2261 new.freelist = old.freelist;
2265 if (!new.inuse && n->nr_partial >= s->min_partial)
2267 else if (new.freelist) {
2272 * Taking the spinlock removes the possibility
2273 * that acquire_slab() will see a slab page that
2276 spin_lock(&n->list_lock);
2280 if (kmem_cache_debug(s) && !lock) {
2283 * This also ensures that the scanning of full
2284 * slabs from diagnostic functions will not see
2287 spin_lock(&n->list_lock);
2293 remove_partial(n, page);
2294 else if (l == M_FULL)
2295 remove_full(s, n, page);
2298 add_partial(n, page, tail);
2299 else if (m == M_FULL)
2300 add_full(s, n, page);
2304 if (!__cmpxchg_double_slab(s, page,
2305 old.freelist, old.counters,
2306 new.freelist, new.counters,
2311 spin_unlock(&n->list_lock);
2315 else if (m == M_FULL)
2316 stat(s, DEACTIVATE_FULL);
2317 else if (m == M_FREE) {
2318 stat(s, DEACTIVATE_EMPTY);
2319 discard_slab(s, page);
2328 * Unfreeze all the cpu partial slabs.
2330 * This function must be called with interrupts disabled
2331 * for the cpu using c (or some other guarantee must be there
2332 * to guarantee no concurrent accesses).
2334 static void unfreeze_partials(struct kmem_cache *s,
2335 struct kmem_cache_cpu *c)
2337 #ifdef CONFIG_SLUB_CPU_PARTIAL
2338 struct kmem_cache_node *n = NULL, *n2 = NULL;
2339 struct page *page, *discard_page = NULL;
2341 while ((page = slub_percpu_partial(c))) {
2345 slub_set_percpu_partial(c, page);
2347 n2 = get_node(s, page_to_nid(page));
2350 spin_unlock(&n->list_lock);
2353 spin_lock(&n->list_lock);
2358 old.freelist = page->freelist;
2359 old.counters = page->counters;
2360 VM_BUG_ON(!old.frozen);
2362 new.counters = old.counters;
2363 new.freelist = old.freelist;
2367 } while (!__cmpxchg_double_slab(s, page,
2368 old.freelist, old.counters,
2369 new.freelist, new.counters,
2370 "unfreezing slab"));
2372 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2373 page->next = discard_page;
2374 discard_page = page;
2376 add_partial(n, page, DEACTIVATE_TO_TAIL);
2377 stat(s, FREE_ADD_PARTIAL);
2382 spin_unlock(&n->list_lock);
2384 while (discard_page) {
2385 page = discard_page;
2386 discard_page = discard_page->next;
2388 stat(s, DEACTIVATE_EMPTY);
2389 discard_slab(s, page);
2392 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2396 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2397 * partial page slot if available.
2399 * If we did not find a slot then simply move all the partials to the
2400 * per node partial list.
2402 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2404 #ifdef CONFIG_SLUB_CPU_PARTIAL
2405 struct page *oldpage;
2413 oldpage = this_cpu_read(s->cpu_slab->partial);
2416 pobjects = oldpage->pobjects;
2417 pages = oldpage->pages;
2418 if (drain && pobjects > slub_cpu_partial(s)) {
2419 unsigned long flags;
2421 * partial array is full. Move the existing
2422 * set to the per node partial list.
2424 local_irq_save(flags);
2425 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2426 local_irq_restore(flags);
2430 stat(s, CPU_PARTIAL_DRAIN);
2435 pobjects += page->objects - page->inuse;
2437 page->pages = pages;
2438 page->pobjects = pobjects;
2439 page->next = oldpage;
2441 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2443 if (unlikely(!slub_cpu_partial(s))) {
2444 unsigned long flags;
2446 local_irq_save(flags);
2447 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2448 local_irq_restore(flags);
2451 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2454 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2456 stat(s, CPUSLAB_FLUSH);
2457 deactivate_slab(s, c->page, c->freelist, c);
2459 c->tid = next_tid(c->tid);
2465 * Called from IPI handler with interrupts disabled.
2467 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2469 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2474 unfreeze_partials(s, c);
2477 static void flush_cpu_slab(void *d)
2479 struct kmem_cache *s = d;
2481 __flush_cpu_slab(s, smp_processor_id());
2484 static bool has_cpu_slab(int cpu, void *info)
2486 struct kmem_cache *s = info;
2487 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2489 return c->page || slub_percpu_partial(c);
2492 static void flush_all(struct kmem_cache *s)
2494 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1);
2498 * Use the cpu notifier to insure that the cpu slabs are flushed when
2501 static int slub_cpu_dead(unsigned int cpu)
2503 struct kmem_cache *s;
2504 unsigned long flags;
2506 mutex_lock(&slab_mutex);
2507 list_for_each_entry(s, &slab_caches, list) {
2508 local_irq_save(flags);
2509 __flush_cpu_slab(s, cpu);
2510 local_irq_restore(flags);
2512 mutex_unlock(&slab_mutex);
2517 * Check if the objects in a per cpu structure fit numa
2518 * locality expectations.
2520 static inline int node_match(struct page *page, int node)
2523 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2529 #ifdef CONFIG_SLUB_DEBUG
2530 static int count_free(struct page *page)
2532 return page->objects - page->inuse;
2535 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2537 return atomic_long_read(&n->total_objects);
2539 #endif /* CONFIG_SLUB_DEBUG */
2541 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2542 static unsigned long count_partial(struct kmem_cache_node *n,
2543 int (*get_count)(struct page *))
2545 unsigned long flags;
2546 unsigned long x = 0;
2549 spin_lock_irqsave(&n->list_lock, flags);
2550 list_for_each_entry(page, &n->partial, slab_list)
2551 x += get_count(page);
2552 spin_unlock_irqrestore(&n->list_lock, flags);
2555 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2557 static noinline void
2558 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2560 #ifdef CONFIG_SLUB_DEBUG
2561 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2562 DEFAULT_RATELIMIT_BURST);
2564 struct kmem_cache_node *n;
2566 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2569 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2570 nid, gfpflags, &gfpflags);
2571 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2572 s->name, s->object_size, s->size, oo_order(s->oo),
2575 if (oo_order(s->min) > get_order(s->object_size))
2576 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2579 for_each_kmem_cache_node(s, node, n) {
2580 unsigned long nr_slabs;
2581 unsigned long nr_objs;
2582 unsigned long nr_free;
2584 nr_free = count_partial(n, count_free);
2585 nr_slabs = node_nr_slabs(n);
2586 nr_objs = node_nr_objs(n);
2588 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2589 node, nr_slabs, nr_objs, nr_free);
2594 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2595 int node, struct kmem_cache_cpu **pc)
2598 struct kmem_cache_cpu *c = *pc;
2601 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2603 freelist = get_partial(s, flags, node, c);
2608 page = new_slab(s, flags, node);
2610 c = raw_cpu_ptr(s->cpu_slab);
2615 * No other reference to the page yet so we can
2616 * muck around with it freely without cmpxchg
2618 freelist = page->freelist;
2619 page->freelist = NULL;
2621 stat(s, ALLOC_SLAB);
2629 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2631 if (unlikely(PageSlabPfmemalloc(page)))
2632 return gfp_pfmemalloc_allowed(gfpflags);
2638 * Check the page->freelist of a page and either transfer the freelist to the
2639 * per cpu freelist or deactivate the page.
2641 * The page is still frozen if the return value is not NULL.
2643 * If this function returns NULL then the page has been unfrozen.
2645 * This function must be called with interrupt disabled.
2647 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2650 unsigned long counters;
2654 freelist = page->freelist;
2655 counters = page->counters;
2657 new.counters = counters;
2658 VM_BUG_ON(!new.frozen);
2660 new.inuse = page->objects;
2661 new.frozen = freelist != NULL;
2663 } while (!__cmpxchg_double_slab(s, page,
2672 * Slow path. The lockless freelist is empty or we need to perform
2675 * Processing is still very fast if new objects have been freed to the
2676 * regular freelist. In that case we simply take over the regular freelist
2677 * as the lockless freelist and zap the regular freelist.
2679 * If that is not working then we fall back to the partial lists. We take the
2680 * first element of the freelist as the object to allocate now and move the
2681 * rest of the freelist to the lockless freelist.
2683 * And if we were unable to get a new slab from the partial slab lists then
2684 * we need to allocate a new slab. This is the slowest path since it involves
2685 * a call to the page allocator and the setup of a new slab.
2687 * Version of __slab_alloc to use when we know that interrupts are
2688 * already disabled (which is the case for bulk allocation).
2690 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2691 unsigned long addr, struct kmem_cache_cpu *c)
2699 * if the node is not online or has no normal memory, just
2700 * ignore the node constraint
2702 if (unlikely(node != NUMA_NO_NODE &&
2703 !node_state(node, N_NORMAL_MEMORY)))
2704 node = NUMA_NO_NODE;
2709 if (unlikely(!node_match(page, node))) {
2711 * same as above but node_match() being false already
2712 * implies node != NUMA_NO_NODE
2714 if (!node_state(node, N_NORMAL_MEMORY)) {
2715 node = NUMA_NO_NODE;
2718 stat(s, ALLOC_NODE_MISMATCH);
2719 deactivate_slab(s, page, c->freelist, c);
2725 * By rights, we should be searching for a slab page that was
2726 * PFMEMALLOC but right now, we are losing the pfmemalloc
2727 * information when the page leaves the per-cpu allocator
2729 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2730 deactivate_slab(s, page, c->freelist, c);
2734 /* must check again c->freelist in case of cpu migration or IRQ */
2735 freelist = c->freelist;
2739 freelist = get_freelist(s, page);
2743 stat(s, DEACTIVATE_BYPASS);
2747 stat(s, ALLOC_REFILL);
2751 * freelist is pointing to the list of objects to be used.
2752 * page is pointing to the page from which the objects are obtained.
2753 * That page must be frozen for per cpu allocations to work.
2755 VM_BUG_ON(!c->page->frozen);
2756 c->freelist = get_freepointer(s, freelist);
2757 c->tid = next_tid(c->tid);
2762 if (slub_percpu_partial(c)) {
2763 page = c->page = slub_percpu_partial(c);
2764 slub_set_percpu_partial(c, page);
2765 stat(s, CPU_PARTIAL_ALLOC);
2769 freelist = new_slab_objects(s, gfpflags, node, &c);
2771 if (unlikely(!freelist)) {
2772 slab_out_of_memory(s, gfpflags, node);
2777 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2780 /* Only entered in the debug case */
2781 if (kmem_cache_debug(s) &&
2782 !alloc_debug_processing(s, page, freelist, addr))
2783 goto new_slab; /* Slab failed checks. Next slab needed */
2785 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2790 * Another one that disabled interrupt and compensates for possible
2791 * cpu changes by refetching the per cpu area pointer.
2793 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2794 unsigned long addr, struct kmem_cache_cpu *c)
2797 unsigned long flags;
2799 local_irq_save(flags);
2800 #ifdef CONFIG_PREEMPTION
2802 * We may have been preempted and rescheduled on a different
2803 * cpu before disabling interrupts. Need to reload cpu area
2806 c = this_cpu_ptr(s->cpu_slab);
2809 p = ___slab_alloc(s, gfpflags, node, addr, c);
2810 local_irq_restore(flags);
2815 * If the object has been wiped upon free, make sure it's fully initialized by
2816 * zeroing out freelist pointer.
2818 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2821 if (unlikely(slab_want_init_on_free(s)) && obj)
2822 memset((void *)((char *)obj + s->offset), 0, sizeof(void *));
2826 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2827 * have the fastpath folded into their functions. So no function call
2828 * overhead for requests that can be satisfied on the fastpath.
2830 * The fastpath works by first checking if the lockless freelist can be used.
2831 * If not then __slab_alloc is called for slow processing.
2833 * Otherwise we can simply pick the next object from the lockless free list.
2835 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2836 gfp_t gfpflags, int node, unsigned long addr)
2839 struct kmem_cache_cpu *c;
2843 s = slab_pre_alloc_hook(s, gfpflags);
2848 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2849 * enabled. We may switch back and forth between cpus while
2850 * reading from one cpu area. That does not matter as long
2851 * as we end up on the original cpu again when doing the cmpxchg.
2853 * We should guarantee that tid and kmem_cache are retrieved on
2854 * the same cpu. It could be different if CONFIG_PREEMPTION so we need
2855 * to check if it is matched or not.
2858 tid = this_cpu_read(s->cpu_slab->tid);
2859 c = raw_cpu_ptr(s->cpu_slab);
2860 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
2861 unlikely(tid != READ_ONCE(c->tid)));
2864 * Irqless object alloc/free algorithm used here depends on sequence
2865 * of fetching cpu_slab's data. tid should be fetched before anything
2866 * on c to guarantee that object and page associated with previous tid
2867 * won't be used with current tid. If we fetch tid first, object and
2868 * page could be one associated with next tid and our alloc/free
2869 * request will be failed. In this case, we will retry. So, no problem.
2874 * The transaction ids are globally unique per cpu and per operation on
2875 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2876 * occurs on the right processor and that there was no operation on the
2877 * linked list in between.
2880 object = c->freelist;
2882 if (unlikely(!object || !node_match(page, node))) {
2883 object = __slab_alloc(s, gfpflags, node, addr, c);
2884 stat(s, ALLOC_SLOWPATH);
2886 void *next_object = get_freepointer_safe(s, object);
2889 * The cmpxchg will only match if there was no additional
2890 * operation and if we are on the right processor.
2892 * The cmpxchg does the following atomically (without lock
2894 * 1. Relocate first pointer to the current per cpu area.
2895 * 2. Verify that tid and freelist have not been changed
2896 * 3. If they were not changed replace tid and freelist
2898 * Since this is without lock semantics the protection is only
2899 * against code executing on this cpu *not* from access by
2902 if (unlikely(!this_cpu_cmpxchg_double(
2903 s->cpu_slab->freelist, s->cpu_slab->tid,
2905 next_object, next_tid(tid)))) {
2907 note_cmpxchg_failure("slab_alloc", s, tid);
2910 prefetch_freepointer(s, next_object);
2911 stat(s, ALLOC_FASTPATH);
2914 maybe_wipe_obj_freeptr(s, object);
2916 if (unlikely(slab_want_init_on_alloc(gfpflags, s)) && object)
2917 memset(object, 0, s->object_size);
2919 slab_post_alloc_hook(s, gfpflags, 1, &object);
2924 static __always_inline void *slab_alloc(struct kmem_cache *s,
2925 gfp_t gfpflags, unsigned long addr)
2927 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2930 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2932 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2934 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2939 EXPORT_SYMBOL(kmem_cache_alloc);
2941 #ifdef CONFIG_TRACING
2942 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2944 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2945 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2946 ret = kasan_kmalloc(s, ret, size, gfpflags);
2949 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2953 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2955 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2957 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2958 s->object_size, s->size, gfpflags, node);
2962 EXPORT_SYMBOL(kmem_cache_alloc_node);
2964 #ifdef CONFIG_TRACING
2965 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2967 int node, size_t size)
2969 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2971 trace_kmalloc_node(_RET_IP_, ret,
2972 size, s->size, gfpflags, node);
2974 ret = kasan_kmalloc(s, ret, size, gfpflags);
2977 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2979 #endif /* CONFIG_NUMA */
2982 * Slow path handling. This may still be called frequently since objects
2983 * have a longer lifetime than the cpu slabs in most processing loads.
2985 * So we still attempt to reduce cache line usage. Just take the slab
2986 * lock and free the item. If there is no additional partial page
2987 * handling required then we can return immediately.
2989 static void __slab_free(struct kmem_cache *s, struct page *page,
2990 void *head, void *tail, int cnt,
2997 unsigned long counters;
2998 struct kmem_cache_node *n = NULL;
2999 unsigned long flags;
3001 stat(s, FREE_SLOWPATH);
3003 if (kmem_cache_debug(s) &&
3004 !free_debug_processing(s, page, head, tail, cnt, addr))
3009 spin_unlock_irqrestore(&n->list_lock, flags);
3012 prior = page->freelist;
3013 counters = page->counters;
3014 set_freepointer(s, tail, prior);
3015 new.counters = counters;
3016 was_frozen = new.frozen;
3018 if ((!new.inuse || !prior) && !was_frozen) {
3020 if (kmem_cache_has_cpu_partial(s) && !prior) {
3023 * Slab was on no list before and will be
3025 * We can defer the list move and instead
3030 } else { /* Needs to be taken off a list */
3032 n = get_node(s, page_to_nid(page));
3034 * Speculatively acquire the list_lock.
3035 * If the cmpxchg does not succeed then we may
3036 * drop the list_lock without any processing.
3038 * Otherwise the list_lock will synchronize with
3039 * other processors updating the list of slabs.
3041 spin_lock_irqsave(&n->list_lock, flags);
3046 } while (!cmpxchg_double_slab(s, page,
3054 * If we just froze the page then put it onto the
3055 * per cpu partial list.
3057 if (new.frozen && !was_frozen) {
3058 put_cpu_partial(s, page, 1);
3059 stat(s, CPU_PARTIAL_FREE);
3062 * The list lock was not taken therefore no list
3063 * activity can be necessary.
3066 stat(s, FREE_FROZEN);
3070 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
3074 * Objects left in the slab. If it was not on the partial list before
3077 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
3078 remove_full(s, n, page);
3079 add_partial(n, page, DEACTIVATE_TO_TAIL);
3080 stat(s, FREE_ADD_PARTIAL);
3082 spin_unlock_irqrestore(&n->list_lock, flags);
3088 * Slab on the partial list.
3090 remove_partial(n, page);
3091 stat(s, FREE_REMOVE_PARTIAL);
3093 /* Slab must be on the full list */
3094 remove_full(s, n, page);
3097 spin_unlock_irqrestore(&n->list_lock, flags);
3099 discard_slab(s, page);
3103 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3104 * can perform fastpath freeing without additional function calls.
3106 * The fastpath is only possible if we are freeing to the current cpu slab
3107 * of this processor. This typically the case if we have just allocated
3110 * If fastpath is not possible then fall back to __slab_free where we deal
3111 * with all sorts of special processing.
3113 * Bulk free of a freelist with several objects (all pointing to the
3114 * same page) possible by specifying head and tail ptr, plus objects
3115 * count (cnt). Bulk free indicated by tail pointer being set.
3117 static __always_inline void do_slab_free(struct kmem_cache *s,
3118 struct page *page, void *head, void *tail,
3119 int cnt, unsigned long addr)
3121 void *tail_obj = tail ? : head;
3122 struct kmem_cache_cpu *c;
3126 * Determine the currently cpus per cpu slab.
3127 * The cpu may change afterward. However that does not matter since
3128 * data is retrieved via this pointer. If we are on the same cpu
3129 * during the cmpxchg then the free will succeed.
3132 tid = this_cpu_read(s->cpu_slab->tid);
3133 c = raw_cpu_ptr(s->cpu_slab);
3134 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
3135 unlikely(tid != READ_ONCE(c->tid)));
3137 /* Same with comment on barrier() in slab_alloc_node() */
3140 if (likely(page == c->page)) {
3141 void **freelist = READ_ONCE(c->freelist);
3143 set_freepointer(s, tail_obj, freelist);
3145 if (unlikely(!this_cpu_cmpxchg_double(
3146 s->cpu_slab->freelist, s->cpu_slab->tid,
3148 head, next_tid(tid)))) {
3150 note_cmpxchg_failure("slab_free", s, tid);
3153 stat(s, FREE_FASTPATH);
3155 __slab_free(s, page, head, tail_obj, cnt, addr);
3159 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3160 void *head, void *tail, int cnt,
3164 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3165 * to remove objects, whose reuse must be delayed.
3167 if (slab_free_freelist_hook(s, &head, &tail))
3168 do_slab_free(s, page, head, tail, cnt, addr);
3171 #ifdef CONFIG_KASAN_GENERIC
3172 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3174 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3178 static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x)
3180 struct kmem_cache *cachep;
3182 if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
3183 !memcg_kmem_enabled() &&
3184 !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS))
3187 cachep = virt_to_cache(x);
3188 if (WARN(cachep && !slab_equal_or_root(cachep, s),
3189 "%s: Wrong slab cache. %s but object is from %s\n",
3190 __func__, s->name, cachep->name))
3191 print_tracking(cachep, x);
3195 void kmem_cache_free(struct kmem_cache *s, void *x)
3197 s = cache_from_obj(s, x);
3200 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3201 trace_kmem_cache_free(_RET_IP_, x);
3203 EXPORT_SYMBOL(kmem_cache_free);
3205 struct detached_freelist {
3210 struct kmem_cache *s;
3214 * This function progressively scans the array with free objects (with
3215 * a limited look ahead) and extract objects belonging to the same
3216 * page. It builds a detached freelist directly within the given
3217 * page/objects. This can happen without any need for
3218 * synchronization, because the objects are owned by running process.
3219 * The freelist is build up as a single linked list in the objects.
3220 * The idea is, that this detached freelist can then be bulk
3221 * transferred to the real freelist(s), but only requiring a single
3222 * synchronization primitive. Look ahead in the array is limited due
3223 * to performance reasons.
3226 int build_detached_freelist(struct kmem_cache *s, size_t size,
3227 void **p, struct detached_freelist *df)
3229 size_t first_skipped_index = 0;
3234 /* Always re-init detached_freelist */
3239 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3240 } while (!object && size);
3245 page = virt_to_head_page(object);
3247 /* Handle kalloc'ed objects */
3248 if (unlikely(!PageSlab(page))) {
3249 BUG_ON(!PageCompound(page));
3251 __free_pages(page, compound_order(page));
3252 p[size] = NULL; /* mark object processed */
3255 /* Derive kmem_cache from object */
3256 df->s = page->slab_cache;
3258 df->s = cache_from_obj(s, object); /* Support for memcg */
3261 /* Start new detached freelist */
3263 set_freepointer(df->s, object, NULL);
3265 df->freelist = object;
3266 p[size] = NULL; /* mark object processed */
3272 continue; /* Skip processed objects */
3274 /* df->page is always set at this point */
3275 if (df->page == virt_to_head_page(object)) {
3276 /* Opportunity build freelist */
3277 set_freepointer(df->s, object, df->freelist);
3278 df->freelist = object;
3280 p[size] = NULL; /* mark object processed */
3285 /* Limit look ahead search */
3289 if (!first_skipped_index)
3290 first_skipped_index = size + 1;
3293 return first_skipped_index;
3296 /* Note that interrupts must be enabled when calling this function. */
3297 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3303 struct detached_freelist df;
3305 size = build_detached_freelist(s, size, p, &df);
3309 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
3310 } while (likely(size));
3312 EXPORT_SYMBOL(kmem_cache_free_bulk);
3314 /* Note that interrupts must be enabled when calling this function. */
3315 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3318 struct kmem_cache_cpu *c;
3321 /* memcg and kmem_cache debug support */
3322 s = slab_pre_alloc_hook(s, flags);
3326 * Drain objects in the per cpu slab, while disabling local
3327 * IRQs, which protects against PREEMPT and interrupts
3328 * handlers invoking normal fastpath.
3330 local_irq_disable();
3331 c = this_cpu_ptr(s->cpu_slab);
3333 for (i = 0; i < size; i++) {
3334 void *object = c->freelist;
3336 if (unlikely(!object)) {
3338 * We may have removed an object from c->freelist using
3339 * the fastpath in the previous iteration; in that case,
3340 * c->tid has not been bumped yet.
3341 * Since ___slab_alloc() may reenable interrupts while
3342 * allocating memory, we should bump c->tid now.
3344 c->tid = next_tid(c->tid);
3347 * Invoking slow path likely have side-effect
3348 * of re-populating per CPU c->freelist
3350 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3352 if (unlikely(!p[i]))
3355 c = this_cpu_ptr(s->cpu_slab);
3356 maybe_wipe_obj_freeptr(s, p[i]);
3358 continue; /* goto for-loop */
3360 c->freelist = get_freepointer(s, object);
3362 maybe_wipe_obj_freeptr(s, p[i]);
3364 c->tid = next_tid(c->tid);
3367 /* Clear memory outside IRQ disabled fastpath loop */
3368 if (unlikely(slab_want_init_on_alloc(flags, s))) {
3371 for (j = 0; j < i; j++)
3372 memset(p[j], 0, s->object_size);
3375 /* memcg and kmem_cache debug support */
3376 slab_post_alloc_hook(s, flags, size, p);
3380 slab_post_alloc_hook(s, flags, i, p);
3381 __kmem_cache_free_bulk(s, i, p);
3384 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3388 * Object placement in a slab is made very easy because we always start at
3389 * offset 0. If we tune the size of the object to the alignment then we can
3390 * get the required alignment by putting one properly sized object after
3393 * Notice that the allocation order determines the sizes of the per cpu
3394 * caches. Each processor has always one slab available for allocations.
3395 * Increasing the allocation order reduces the number of times that slabs
3396 * must be moved on and off the partial lists and is therefore a factor in
3401 * Mininum / Maximum order of slab pages. This influences locking overhead
3402 * and slab fragmentation. A higher order reduces the number of partial slabs
3403 * and increases the number of allocations possible without having to
3404 * take the list_lock.
3406 static unsigned int slub_min_order;
3407 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3408 static unsigned int slub_min_objects;
3411 * Calculate the order of allocation given an slab object size.
3413 * The order of allocation has significant impact on performance and other
3414 * system components. Generally order 0 allocations should be preferred since
3415 * order 0 does not cause fragmentation in the page allocator. Larger objects
3416 * be problematic to put into order 0 slabs because there may be too much
3417 * unused space left. We go to a higher order if more than 1/16th of the slab
3420 * In order to reach satisfactory performance we must ensure that a minimum
3421 * number of objects is in one slab. Otherwise we may generate too much
3422 * activity on the partial lists which requires taking the list_lock. This is
3423 * less a concern for large slabs though which are rarely used.
3425 * slub_max_order specifies the order where we begin to stop considering the
3426 * number of objects in a slab as critical. If we reach slub_max_order then
3427 * we try to keep the page order as low as possible. So we accept more waste
3428 * of space in favor of a small page order.
3430 * Higher order allocations also allow the placement of more objects in a
3431 * slab and thereby reduce object handling overhead. If the user has
3432 * requested a higher mininum order then we start with that one instead of
3433 * the smallest order which will fit the object.
3435 static inline unsigned int slab_order(unsigned int size,
3436 unsigned int min_objects, unsigned int max_order,
3437 unsigned int fract_leftover)
3439 unsigned int min_order = slub_min_order;
3442 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3443 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3445 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3446 order <= max_order; order++) {
3448 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3451 rem = slab_size % size;
3453 if (rem <= slab_size / fract_leftover)
3460 static inline int calculate_order(unsigned int size)
3463 unsigned int min_objects;
3464 unsigned int max_objects;
3467 * Attempt to find best configuration for a slab. This
3468 * works by first attempting to generate a layout with
3469 * the best configuration and backing off gradually.
3471 * First we increase the acceptable waste in a slab. Then
3472 * we reduce the minimum objects required in a slab.
3474 min_objects = slub_min_objects;
3476 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3477 max_objects = order_objects(slub_max_order, size);
3478 min_objects = min(min_objects, max_objects);
3480 while (min_objects > 1) {
3481 unsigned int fraction;
3484 while (fraction >= 4) {
3485 order = slab_order(size, min_objects,
3486 slub_max_order, fraction);
3487 if (order <= slub_max_order)
3495 * We were unable to place multiple objects in a slab. Now
3496 * lets see if we can place a single object there.
3498 order = slab_order(size, 1, slub_max_order, 1);
3499 if (order <= slub_max_order)
3503 * Doh this slab cannot be placed using slub_max_order.
3505 order = slab_order(size, 1, MAX_ORDER, 1);
3506 if (order < MAX_ORDER)
3512 init_kmem_cache_node(struct kmem_cache_node *n)
3515 spin_lock_init(&n->list_lock);
3516 INIT_LIST_HEAD(&n->partial);
3517 #ifdef CONFIG_SLUB_DEBUG
3518 atomic_long_set(&n->nr_slabs, 0);
3519 atomic_long_set(&n->total_objects, 0);
3520 INIT_LIST_HEAD(&n->full);
3524 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3526 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3527 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3530 * Must align to double word boundary for the double cmpxchg
3531 * instructions to work; see __pcpu_double_call_return_bool().
3533 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3534 2 * sizeof(void *));
3539 init_kmem_cache_cpus(s);
3544 static struct kmem_cache *kmem_cache_node;
3547 * No kmalloc_node yet so do it by hand. We know that this is the first
3548 * slab on the node for this slabcache. There are no concurrent accesses
3551 * Note that this function only works on the kmem_cache_node
3552 * when allocating for the kmem_cache_node. This is used for bootstrapping
3553 * memory on a fresh node that has no slab structures yet.
3555 static void early_kmem_cache_node_alloc(int node)
3558 struct kmem_cache_node *n;
3560 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3562 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3565 if (page_to_nid(page) != node) {
3566 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3567 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3572 #ifdef CONFIG_SLUB_DEBUG
3573 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3574 init_tracking(kmem_cache_node, n);
3576 n = kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
3578 page->freelist = get_freepointer(kmem_cache_node, n);
3581 kmem_cache_node->node[node] = n;
3582 init_kmem_cache_node(n);
3583 inc_slabs_node(kmem_cache_node, node, page->objects);
3586 * No locks need to be taken here as it has just been
3587 * initialized and there is no concurrent access.
3589 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3592 static void free_kmem_cache_nodes(struct kmem_cache *s)
3595 struct kmem_cache_node *n;
3597 for_each_kmem_cache_node(s, node, n) {
3598 s->node[node] = NULL;
3599 kmem_cache_free(kmem_cache_node, n);
3603 void __kmem_cache_release(struct kmem_cache *s)
3605 cache_random_seq_destroy(s);
3606 free_percpu(s->cpu_slab);
3607 free_kmem_cache_nodes(s);
3610 static int init_kmem_cache_nodes(struct kmem_cache *s)
3614 for_each_node_state(node, N_NORMAL_MEMORY) {
3615 struct kmem_cache_node *n;
3617 if (slab_state == DOWN) {
3618 early_kmem_cache_node_alloc(node);
3621 n = kmem_cache_alloc_node(kmem_cache_node,
3625 free_kmem_cache_nodes(s);
3629 init_kmem_cache_node(n);
3635 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3637 if (min < MIN_PARTIAL)
3639 else if (min > MAX_PARTIAL)
3641 s->min_partial = min;
3644 static void set_cpu_partial(struct kmem_cache *s)
3646 #ifdef CONFIG_SLUB_CPU_PARTIAL
3648 * cpu_partial determined the maximum number of objects kept in the
3649 * per cpu partial lists of a processor.
3651 * Per cpu partial lists mainly contain slabs that just have one
3652 * object freed. If they are used for allocation then they can be
3653 * filled up again with minimal effort. The slab will never hit the
3654 * per node partial lists and therefore no locking will be required.
3656 * This setting also determines
3658 * A) The number of objects from per cpu partial slabs dumped to the
3659 * per node list when we reach the limit.
3660 * B) The number of objects in cpu partial slabs to extract from the
3661 * per node list when we run out of per cpu objects. We only fetch
3662 * 50% to keep some capacity around for frees.
3664 if (!kmem_cache_has_cpu_partial(s))
3665 slub_set_cpu_partial(s, 0);
3666 else if (s->size >= PAGE_SIZE)
3667 slub_set_cpu_partial(s, 2);
3668 else if (s->size >= 1024)
3669 slub_set_cpu_partial(s, 6);
3670 else if (s->size >= 256)
3671 slub_set_cpu_partial(s, 13);
3673 slub_set_cpu_partial(s, 30);
3678 * calculate_sizes() determines the order and the distribution of data within
3681 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3683 slab_flags_t flags = s->flags;
3684 unsigned int size = s->object_size;
3685 unsigned int freepointer_area;
3689 * Round up object size to the next word boundary. We can only
3690 * place the free pointer at word boundaries and this determines
3691 * the possible location of the free pointer.
3693 size = ALIGN(size, sizeof(void *));
3695 * This is the area of the object where a freepointer can be
3696 * safely written. If redzoning adds more to the inuse size, we
3697 * can't use that portion for writing the freepointer, so
3698 * s->offset must be limited within this for the general case.
3700 freepointer_area = size;
3702 #ifdef CONFIG_SLUB_DEBUG
3704 * Determine if we can poison the object itself. If the user of
3705 * the slab may touch the object after free or before allocation
3706 * then we should never poison the object itself.
3708 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3710 s->flags |= __OBJECT_POISON;
3712 s->flags &= ~__OBJECT_POISON;
3716 * If we are Redzoning then check if there is some space between the
3717 * end of the object and the free pointer. If not then add an
3718 * additional word to have some bytes to store Redzone information.
3720 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3721 size += sizeof(void *);
3725 * With that we have determined the number of bytes in actual use
3726 * by the object. This is the potential offset to the free pointer.
3730 if (((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3733 * Relocate free pointer after the object if it is not
3734 * permitted to overwrite the first word of the object on
3737 * This is the case if we do RCU, have a constructor or
3738 * destructor or are poisoning the objects.
3740 * The assumption that s->offset >= s->inuse means free
3741 * pointer is outside of the object is used in the
3742 * freeptr_outside_object() function. If that is no
3743 * longer true, the function needs to be modified.
3746 size += sizeof(void *);
3747 } else if (freepointer_area > sizeof(void *)) {
3749 * Store freelist pointer near middle of object to keep
3750 * it away from the edges of the object to avoid small
3751 * sized over/underflows from neighboring allocations.
3753 s->offset = ALIGN(freepointer_area / 2, sizeof(void *));
3756 #ifdef CONFIG_SLUB_DEBUG
3757 if (flags & SLAB_STORE_USER)
3759 * Need to store information about allocs and frees after
3762 size += 2 * sizeof(struct track);
3765 kasan_cache_create(s, &size, &s->flags);
3766 #ifdef CONFIG_SLUB_DEBUG
3767 if (flags & SLAB_RED_ZONE) {
3769 * Add some empty padding so that we can catch
3770 * overwrites from earlier objects rather than let
3771 * tracking information or the free pointer be
3772 * corrupted if a user writes before the start
3775 size += sizeof(void *);
3777 s->red_left_pad = sizeof(void *);
3778 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3779 size += s->red_left_pad;
3784 * SLUB stores one object immediately after another beginning from
3785 * offset 0. In order to align the objects we have to simply size
3786 * each object to conform to the alignment.
3788 size = ALIGN(size, s->align);
3790 if (forced_order >= 0)
3791 order = forced_order;
3793 order = calculate_order(size);
3800 s->allocflags |= __GFP_COMP;
3802 if (s->flags & SLAB_CACHE_DMA)
3803 s->allocflags |= GFP_DMA;
3805 if (s->flags & SLAB_CACHE_DMA32)
3806 s->allocflags |= GFP_DMA32;
3808 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3809 s->allocflags |= __GFP_RECLAIMABLE;
3812 * Determine the number of objects per slab
3814 s->oo = oo_make(order, size);
3815 s->min = oo_make(get_order(size), size);
3816 if (oo_objects(s->oo) > oo_objects(s->max))
3819 return !!oo_objects(s->oo);
3822 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3824 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3825 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3826 s->random = get_random_long();
3829 if (!calculate_sizes(s, -1))
3831 if (disable_higher_order_debug) {
3833 * Disable debugging flags that store metadata if the min slab
3836 if (get_order(s->size) > get_order(s->object_size)) {
3837 s->flags &= ~DEBUG_METADATA_FLAGS;
3839 if (!calculate_sizes(s, -1))
3844 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3845 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3846 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3847 /* Enable fast mode */
3848 s->flags |= __CMPXCHG_DOUBLE;
3852 * The larger the object size is, the more pages we want on the partial
3853 * list to avoid pounding the page allocator excessively.
3855 set_min_partial(s, ilog2(s->size) / 2);
3860 s->remote_node_defrag_ratio = 1000;
3863 /* Initialize the pre-computed randomized freelist if slab is up */
3864 if (slab_state >= UP) {
3865 if (init_cache_random_seq(s))
3869 if (!init_kmem_cache_nodes(s))
3872 if (alloc_kmem_cache_cpus(s))
3875 free_kmem_cache_nodes(s);
3880 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3883 #ifdef CONFIG_SLUB_DEBUG
3884 void *addr = page_address(page);
3888 slab_err(s, page, text, s->name);
3891 map = get_map(s, page);
3892 for_each_object(p, s, addr, page->objects) {
3894 if (!test_bit(slab_index(p, s, addr), map)) {
3895 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3896 print_tracking(s, p);
3905 * Attempt to free all partial slabs on a node.
3906 * This is called from __kmem_cache_shutdown(). We must take list_lock
3907 * because sysfs file might still access partial list after the shutdowning.
3909 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3912 struct page *page, *h;
3914 BUG_ON(irqs_disabled());
3915 spin_lock_irq(&n->list_lock);
3916 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3918 remove_partial(n, page);
3919 list_add(&page->slab_list, &discard);
3921 list_slab_objects(s, page,
3922 "Objects remaining in %s on __kmem_cache_shutdown()");
3925 spin_unlock_irq(&n->list_lock);
3927 list_for_each_entry_safe(page, h, &discard, slab_list)
3928 discard_slab(s, page);
3931 bool __kmem_cache_empty(struct kmem_cache *s)
3934 struct kmem_cache_node *n;
3936 for_each_kmem_cache_node(s, node, n)
3937 if (n->nr_partial || slabs_node(s, node))
3943 * Release all resources used by a slab cache.
3945 int __kmem_cache_shutdown(struct kmem_cache *s)
3948 struct kmem_cache_node *n;
3951 /* Attempt to free all objects */
3952 for_each_kmem_cache_node(s, node, n) {
3954 if (n->nr_partial || slabs_node(s, node))
3957 sysfs_slab_remove(s);
3961 /********************************************************************
3963 *******************************************************************/
3965 static int __init setup_slub_min_order(char *str)
3967 get_option(&str, (int *)&slub_min_order);
3972 __setup("slub_min_order=", setup_slub_min_order);
3974 static int __init setup_slub_max_order(char *str)
3976 get_option(&str, (int *)&slub_max_order);
3977 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
3982 __setup("slub_max_order=", setup_slub_max_order);
3984 static int __init setup_slub_min_objects(char *str)
3986 get_option(&str, (int *)&slub_min_objects);
3991 __setup("slub_min_objects=", setup_slub_min_objects);
3993 void *__kmalloc(size_t size, gfp_t flags)
3995 struct kmem_cache *s;
3998 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3999 return kmalloc_large(size, flags);
4001 s = kmalloc_slab(size, flags);
4003 if (unlikely(ZERO_OR_NULL_PTR(s)))
4006 ret = slab_alloc(s, flags, _RET_IP_);
4008 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
4010 ret = kasan_kmalloc(s, ret, size, flags);
4014 EXPORT_SYMBOL(__kmalloc);
4017 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
4021 unsigned int order = get_order(size);
4023 flags |= __GFP_COMP;
4024 page = alloc_pages_node(node, flags, order);
4026 ptr = page_address(page);
4027 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
4031 return kmalloc_large_node_hook(ptr, size, flags);
4034 void *__kmalloc_node(size_t size, gfp_t flags, int node)
4036 struct kmem_cache *s;
4039 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4040 ret = kmalloc_large_node(size, flags, node);
4042 trace_kmalloc_node(_RET_IP_, ret,
4043 size, PAGE_SIZE << get_order(size),
4049 s = kmalloc_slab(size, flags);
4051 if (unlikely(ZERO_OR_NULL_PTR(s)))
4054 ret = slab_alloc_node(s, flags, node, _RET_IP_);
4056 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
4058 ret = kasan_kmalloc(s, ret, size, flags);
4062 EXPORT_SYMBOL(__kmalloc_node);
4063 #endif /* CONFIG_NUMA */
4065 #ifdef CONFIG_HARDENED_USERCOPY
4067 * Rejects incorrectly sized objects and objects that are to be copied
4068 * to/from userspace but do not fall entirely within the containing slab
4069 * cache's usercopy region.
4071 * Returns NULL if check passes, otherwise const char * to name of cache
4072 * to indicate an error.
4074 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
4077 struct kmem_cache *s;
4078 unsigned int offset;
4081 ptr = kasan_reset_tag(ptr);
4083 /* Find object and usable object size. */
4084 s = page->slab_cache;
4086 /* Reject impossible pointers. */
4087 if (ptr < page_address(page))
4088 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4091 /* Find offset within object. */
4092 offset = (ptr - page_address(page)) % s->size;
4094 /* Adjust for redzone and reject if within the redzone. */
4095 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
4096 if (offset < s->red_left_pad)
4097 usercopy_abort("SLUB object in left red zone",
4098 s->name, to_user, offset, n);
4099 offset -= s->red_left_pad;
4102 /* Allow address range falling entirely within usercopy region. */
4103 if (offset >= s->useroffset &&
4104 offset - s->useroffset <= s->usersize &&
4105 n <= s->useroffset - offset + s->usersize)
4109 * If the copy is still within the allocated object, produce
4110 * a warning instead of rejecting the copy. This is intended
4111 * to be a temporary method to find any missing usercopy
4114 object_size = slab_ksize(s);
4115 if (usercopy_fallback &&
4116 offset <= object_size && n <= object_size - offset) {
4117 usercopy_warn("SLUB object", s->name, to_user, offset, n);
4121 usercopy_abort("SLUB object", s->name, to_user, offset, n);
4123 #endif /* CONFIG_HARDENED_USERCOPY */
4125 size_t __ksize(const void *object)
4129 if (unlikely(object == ZERO_SIZE_PTR))
4132 page = virt_to_head_page(object);
4134 if (unlikely(!PageSlab(page))) {
4135 WARN_ON(!PageCompound(page));
4136 return page_size(page);
4139 return slab_ksize(page->slab_cache);
4141 EXPORT_SYMBOL(__ksize);
4143 void kfree(const void *x)
4146 void *object = (void *)x;
4148 trace_kfree(_RET_IP_, x);
4150 if (unlikely(ZERO_OR_NULL_PTR(x)))
4153 page = virt_to_head_page(x);
4154 if (unlikely(!PageSlab(page))) {
4155 unsigned int order = compound_order(page);
4157 BUG_ON(!PageCompound(page));
4159 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
4161 __free_pages(page, order);
4164 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4166 EXPORT_SYMBOL(kfree);
4168 #define SHRINK_PROMOTE_MAX 32
4171 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4172 * up most to the head of the partial lists. New allocations will then
4173 * fill those up and thus they can be removed from the partial lists.
4175 * The slabs with the least items are placed last. This results in them
4176 * being allocated from last increasing the chance that the last objects
4177 * are freed in them.
4179 int __kmem_cache_shrink(struct kmem_cache *s)
4183 struct kmem_cache_node *n;
4186 struct list_head discard;
4187 struct list_head promote[SHRINK_PROMOTE_MAX];
4188 unsigned long flags;
4192 for_each_kmem_cache_node(s, node, n) {
4193 INIT_LIST_HEAD(&discard);
4194 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4195 INIT_LIST_HEAD(promote + i);
4197 spin_lock_irqsave(&n->list_lock, flags);
4200 * Build lists of slabs to discard or promote.
4202 * Note that concurrent frees may occur while we hold the
4203 * list_lock. page->inuse here is the upper limit.
4205 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4206 int free = page->objects - page->inuse;
4208 /* Do not reread page->inuse */
4211 /* We do not keep full slabs on the list */
4214 if (free == page->objects) {
4215 list_move(&page->slab_list, &discard);
4217 } else if (free <= SHRINK_PROMOTE_MAX)
4218 list_move(&page->slab_list, promote + free - 1);
4222 * Promote the slabs filled up most to the head of the
4225 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4226 list_splice(promote + i, &n->partial);
4228 spin_unlock_irqrestore(&n->list_lock, flags);
4230 /* Release empty slabs */
4231 list_for_each_entry_safe(page, t, &discard, slab_list)
4232 discard_slab(s, page);
4234 if (slabs_node(s, node))
4242 void __kmemcg_cache_deactivate_after_rcu(struct kmem_cache *s)
4245 * Called with all the locks held after a sched RCU grace period.
4246 * Even if @s becomes empty after shrinking, we can't know that @s
4247 * doesn't have allocations already in-flight and thus can't
4248 * destroy @s until the associated memcg is released.
4250 * However, let's remove the sysfs files for empty caches here.
4251 * Each cache has a lot of interface files which aren't
4252 * particularly useful for empty draining caches; otherwise, we can
4253 * easily end up with millions of unnecessary sysfs files on
4254 * systems which have a lot of memory and transient cgroups.
4256 if (!__kmem_cache_shrink(s))
4257 sysfs_slab_remove(s);
4260 void __kmemcg_cache_deactivate(struct kmem_cache *s)
4263 * Disable empty slabs caching. Used to avoid pinning offline
4264 * memory cgroups by kmem pages that can be freed.
4266 slub_set_cpu_partial(s, 0);
4269 #endif /* CONFIG_MEMCG */
4271 static int slab_mem_going_offline_callback(void *arg)
4273 struct kmem_cache *s;
4275 mutex_lock(&slab_mutex);
4276 list_for_each_entry(s, &slab_caches, list)
4277 __kmem_cache_shrink(s);
4278 mutex_unlock(&slab_mutex);
4283 static void slab_mem_offline_callback(void *arg)
4285 struct kmem_cache_node *n;
4286 struct kmem_cache *s;
4287 struct memory_notify *marg = arg;
4290 offline_node = marg->status_change_nid_normal;
4293 * If the node still has available memory. we need kmem_cache_node
4296 if (offline_node < 0)
4299 mutex_lock(&slab_mutex);
4300 list_for_each_entry(s, &slab_caches, list) {
4301 n = get_node(s, offline_node);
4304 * if n->nr_slabs > 0, slabs still exist on the node
4305 * that is going down. We were unable to free them,
4306 * and offline_pages() function shouldn't call this
4307 * callback. So, we must fail.
4309 BUG_ON(slabs_node(s, offline_node));
4311 s->node[offline_node] = NULL;
4312 kmem_cache_free(kmem_cache_node, n);
4315 mutex_unlock(&slab_mutex);
4318 static int slab_mem_going_online_callback(void *arg)
4320 struct kmem_cache_node *n;
4321 struct kmem_cache *s;
4322 struct memory_notify *marg = arg;
4323 int nid = marg->status_change_nid_normal;
4327 * If the node's memory is already available, then kmem_cache_node is
4328 * already created. Nothing to do.
4334 * We are bringing a node online. No memory is available yet. We must
4335 * allocate a kmem_cache_node structure in order to bring the node
4338 mutex_lock(&slab_mutex);
4339 list_for_each_entry(s, &slab_caches, list) {
4341 * XXX: kmem_cache_alloc_node will fallback to other nodes
4342 * since memory is not yet available from the node that
4345 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4350 init_kmem_cache_node(n);
4354 mutex_unlock(&slab_mutex);
4358 static int slab_memory_callback(struct notifier_block *self,
4359 unsigned long action, void *arg)
4364 case MEM_GOING_ONLINE:
4365 ret = slab_mem_going_online_callback(arg);
4367 case MEM_GOING_OFFLINE:
4368 ret = slab_mem_going_offline_callback(arg);
4371 case MEM_CANCEL_ONLINE:
4372 slab_mem_offline_callback(arg);
4375 case MEM_CANCEL_OFFLINE:
4379 ret = notifier_from_errno(ret);
4385 static struct notifier_block slab_memory_callback_nb = {
4386 .notifier_call = slab_memory_callback,
4387 .priority = SLAB_CALLBACK_PRI,
4390 /********************************************************************
4391 * Basic setup of slabs
4392 *******************************************************************/
4395 * Used for early kmem_cache structures that were allocated using
4396 * the page allocator. Allocate them properly then fix up the pointers
4397 * that may be pointing to the wrong kmem_cache structure.
4400 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4403 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4404 struct kmem_cache_node *n;
4406 memcpy(s, static_cache, kmem_cache->object_size);
4409 * This runs very early, and only the boot processor is supposed to be
4410 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4413 __flush_cpu_slab(s, smp_processor_id());
4414 for_each_kmem_cache_node(s, node, n) {
4417 list_for_each_entry(p, &n->partial, slab_list)
4420 #ifdef CONFIG_SLUB_DEBUG
4421 list_for_each_entry(p, &n->full, slab_list)
4425 slab_init_memcg_params(s);
4426 list_add(&s->list, &slab_caches);
4427 memcg_link_cache(s, NULL);
4431 void __init kmem_cache_init(void)
4433 static __initdata struct kmem_cache boot_kmem_cache,
4434 boot_kmem_cache_node;
4436 if (debug_guardpage_minorder())
4439 kmem_cache_node = &boot_kmem_cache_node;
4440 kmem_cache = &boot_kmem_cache;
4442 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4443 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4445 register_hotmemory_notifier(&slab_memory_callback_nb);
4447 /* Able to allocate the per node structures */
4448 slab_state = PARTIAL;
4450 create_boot_cache(kmem_cache, "kmem_cache",
4451 offsetof(struct kmem_cache, node) +
4452 nr_node_ids * sizeof(struct kmem_cache_node *),
4453 SLAB_HWCACHE_ALIGN, 0, 0);
4455 kmem_cache = bootstrap(&boot_kmem_cache);
4456 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4458 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4459 setup_kmalloc_cache_index_table();
4460 create_kmalloc_caches(0);
4462 /* Setup random freelists for each cache */
4463 init_freelist_randomization();
4465 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4468 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4470 slub_min_order, slub_max_order, slub_min_objects,
4471 nr_cpu_ids, nr_node_ids);
4474 void __init kmem_cache_init_late(void)
4479 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4480 slab_flags_t flags, void (*ctor)(void *))
4482 struct kmem_cache *s, *c;
4484 s = find_mergeable(size, align, flags, name, ctor);
4489 * Adjust the object sizes so that we clear
4490 * the complete object on kzalloc.
4492 s->object_size = max(s->object_size, size);
4493 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4495 for_each_memcg_cache(c, s) {
4496 c->object_size = s->object_size;
4497 c->inuse = max(c->inuse, ALIGN(size, sizeof(void *)));
4500 if (sysfs_slab_alias(s, name)) {
4509 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4513 err = kmem_cache_open(s, flags);
4517 /* Mutex is not taken during early boot */
4518 if (slab_state <= UP)
4521 memcg_propagate_slab_attrs(s);
4522 err = sysfs_slab_add(s);
4524 __kmem_cache_release(s);
4529 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4531 struct kmem_cache *s;
4534 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4535 return kmalloc_large(size, gfpflags);
4537 s = kmalloc_slab(size, gfpflags);
4539 if (unlikely(ZERO_OR_NULL_PTR(s)))
4542 ret = slab_alloc(s, gfpflags, caller);
4544 /* Honor the call site pointer we received. */
4545 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4549 EXPORT_SYMBOL(__kmalloc_track_caller);
4552 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4553 int node, unsigned long caller)
4555 struct kmem_cache *s;
4558 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4559 ret = kmalloc_large_node(size, gfpflags, node);
4561 trace_kmalloc_node(caller, ret,
4562 size, PAGE_SIZE << get_order(size),
4568 s = kmalloc_slab(size, gfpflags);
4570 if (unlikely(ZERO_OR_NULL_PTR(s)))
4573 ret = slab_alloc_node(s, gfpflags, node, caller);
4575 /* Honor the call site pointer we received. */
4576 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4580 EXPORT_SYMBOL(__kmalloc_node_track_caller);
4584 static int count_inuse(struct page *page)
4589 static int count_total(struct page *page)
4591 return page->objects;
4595 #ifdef CONFIG_SLUB_DEBUG
4596 static void validate_slab(struct kmem_cache *s, struct page *page)
4599 void *addr = page_address(page);
4604 if (!check_slab(s, page) || !on_freelist(s, page, NULL))
4607 /* Now we know that a valid freelist exists */
4608 map = get_map(s, page);
4609 for_each_object(p, s, addr, page->objects) {
4610 u8 val = test_bit(slab_index(p, s, addr), map) ?
4611 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
4613 if (!check_object(s, page, p, val))
4621 static int validate_slab_node(struct kmem_cache *s,
4622 struct kmem_cache_node *n)
4624 unsigned long count = 0;
4626 unsigned long flags;
4628 spin_lock_irqsave(&n->list_lock, flags);
4630 list_for_each_entry(page, &n->partial, slab_list) {
4631 validate_slab(s, page);
4634 if (count != n->nr_partial)
4635 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4636 s->name, count, n->nr_partial);
4638 if (!(s->flags & SLAB_STORE_USER))
4641 list_for_each_entry(page, &n->full, slab_list) {
4642 validate_slab(s, page);
4645 if (count != atomic_long_read(&n->nr_slabs))
4646 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4647 s->name, count, atomic_long_read(&n->nr_slabs));
4650 spin_unlock_irqrestore(&n->list_lock, flags);
4654 static long validate_slab_cache(struct kmem_cache *s)
4657 unsigned long count = 0;
4658 struct kmem_cache_node *n;
4661 for_each_kmem_cache_node(s, node, n)
4662 count += validate_slab_node(s, n);
4667 * Generate lists of code addresses where slabcache objects are allocated
4672 unsigned long count;
4679 DECLARE_BITMAP(cpus, NR_CPUS);
4685 unsigned long count;
4686 struct location *loc;
4689 static void free_loc_track(struct loc_track *t)
4692 free_pages((unsigned long)t->loc,
4693 get_order(sizeof(struct location) * t->max));
4696 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4701 order = get_order(sizeof(struct location) * max);
4703 l = (void *)__get_free_pages(flags, order);
4708 memcpy(l, t->loc, sizeof(struct location) * t->count);
4716 static int add_location(struct loc_track *t, struct kmem_cache *s,
4717 const struct track *track)
4719 long start, end, pos;
4721 unsigned long caddr;
4722 unsigned long age = jiffies - track->when;
4728 pos = start + (end - start + 1) / 2;
4731 * There is nothing at "end". If we end up there
4732 * we need to add something to before end.
4737 caddr = t->loc[pos].addr;
4738 if (track->addr == caddr) {
4744 if (age < l->min_time)
4746 if (age > l->max_time)
4749 if (track->pid < l->min_pid)
4750 l->min_pid = track->pid;
4751 if (track->pid > l->max_pid)
4752 l->max_pid = track->pid;
4754 cpumask_set_cpu(track->cpu,
4755 to_cpumask(l->cpus));
4757 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4761 if (track->addr < caddr)
4768 * Not found. Insert new tracking element.
4770 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4776 (t->count - pos) * sizeof(struct location));
4779 l->addr = track->addr;
4783 l->min_pid = track->pid;
4784 l->max_pid = track->pid;
4785 cpumask_clear(to_cpumask(l->cpus));
4786 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4787 nodes_clear(l->nodes);
4788 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4792 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4793 struct page *page, enum track_item alloc)
4795 void *addr = page_address(page);
4799 map = get_map(s, page);
4800 for_each_object(p, s, addr, page->objects)
4801 if (!test_bit(slab_index(p, s, addr), map))
4802 add_location(t, s, get_track(s, p, alloc));
4806 static int list_locations(struct kmem_cache *s, char *buf,
4807 enum track_item alloc)
4811 struct loc_track t = { 0, 0, NULL };
4813 struct kmem_cache_node *n;
4815 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4817 return sprintf(buf, "Out of memory\n");
4819 /* Push back cpu slabs */
4822 for_each_kmem_cache_node(s, node, n) {
4823 unsigned long flags;
4826 if (!atomic_long_read(&n->nr_slabs))
4829 spin_lock_irqsave(&n->list_lock, flags);
4830 list_for_each_entry(page, &n->partial, slab_list)
4831 process_slab(&t, s, page, alloc);
4832 list_for_each_entry(page, &n->full, slab_list)
4833 process_slab(&t, s, page, alloc);
4834 spin_unlock_irqrestore(&n->list_lock, flags);
4837 for (i = 0; i < t.count; i++) {
4838 struct location *l = &t.loc[i];
4840 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4842 len += sprintf(buf + len, "%7ld ", l->count);
4845 len += sprintf(buf + len, "%pS", (void *)l->addr);
4847 len += sprintf(buf + len, "<not-available>");
4849 if (l->sum_time != l->min_time) {
4850 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4852 (long)div_u64(l->sum_time, l->count),
4855 len += sprintf(buf + len, " age=%ld",
4858 if (l->min_pid != l->max_pid)
4859 len += sprintf(buf + len, " pid=%ld-%ld",
4860 l->min_pid, l->max_pid);
4862 len += sprintf(buf + len, " pid=%ld",
4865 if (num_online_cpus() > 1 &&
4866 !cpumask_empty(to_cpumask(l->cpus)) &&
4867 len < PAGE_SIZE - 60)
4868 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4870 cpumask_pr_args(to_cpumask(l->cpus)));
4872 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4873 len < PAGE_SIZE - 60)
4874 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4876 nodemask_pr_args(&l->nodes));
4878 len += sprintf(buf + len, "\n");
4883 len += sprintf(buf, "No data\n");
4886 #endif /* CONFIG_SLUB_DEBUG */
4888 #ifdef SLUB_RESILIENCY_TEST
4889 static void __init resiliency_test(void)
4892 int type = KMALLOC_NORMAL;
4894 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4896 pr_err("SLUB resiliency testing\n");
4897 pr_err("-----------------------\n");
4898 pr_err("A. Corruption after allocation\n");
4900 p = kzalloc(16, GFP_KERNEL);
4902 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4905 validate_slab_cache(kmalloc_caches[type][4]);
4907 /* Hmmm... The next two are dangerous */
4908 p = kzalloc(32, GFP_KERNEL);
4909 p[32 + sizeof(void *)] = 0x34;
4910 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4912 pr_err("If allocated object is overwritten then not detectable\n\n");
4914 validate_slab_cache(kmalloc_caches[type][5]);
4915 p = kzalloc(64, GFP_KERNEL);
4916 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4918 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4920 pr_err("If allocated object is overwritten then not detectable\n\n");
4921 validate_slab_cache(kmalloc_caches[type][6]);
4923 pr_err("\nB. Corruption after free\n");
4924 p = kzalloc(128, GFP_KERNEL);
4927 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4928 validate_slab_cache(kmalloc_caches[type][7]);
4930 p = kzalloc(256, GFP_KERNEL);
4933 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4934 validate_slab_cache(kmalloc_caches[type][8]);
4936 p = kzalloc(512, GFP_KERNEL);
4939 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4940 validate_slab_cache(kmalloc_caches[type][9]);
4944 static void resiliency_test(void) {};
4946 #endif /* SLUB_RESILIENCY_TEST */
4949 enum slab_stat_type {
4950 SL_ALL, /* All slabs */
4951 SL_PARTIAL, /* Only partially allocated slabs */
4952 SL_CPU, /* Only slabs used for cpu caches */
4953 SL_OBJECTS, /* Determine allocated objects not slabs */
4954 SL_TOTAL /* Determine object capacity not slabs */
4957 #define SO_ALL (1 << SL_ALL)
4958 #define SO_PARTIAL (1 << SL_PARTIAL)
4959 #define SO_CPU (1 << SL_CPU)
4960 #define SO_OBJECTS (1 << SL_OBJECTS)
4961 #define SO_TOTAL (1 << SL_TOTAL)
4964 static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON);
4966 static int __init setup_slub_memcg_sysfs(char *str)
4970 if (get_option(&str, &v) > 0)
4971 memcg_sysfs_enabled = v;
4976 __setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs);
4979 static ssize_t show_slab_objects(struct kmem_cache *s,
4980 char *buf, unsigned long flags)
4982 unsigned long total = 0;
4985 unsigned long *nodes;
4987 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
4991 if (flags & SO_CPU) {
4994 for_each_possible_cpu(cpu) {
4995 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
5000 page = READ_ONCE(c->page);
5004 node = page_to_nid(page);
5005 if (flags & SO_TOTAL)
5007 else if (flags & SO_OBJECTS)
5015 page = slub_percpu_partial_read_once(c);
5017 node = page_to_nid(page);
5018 if (flags & SO_TOTAL)
5020 else if (flags & SO_OBJECTS)
5031 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
5032 * already held which will conflict with an existing lock order:
5034 * mem_hotplug_lock->slab_mutex->kernfs_mutex
5036 * We don't really need mem_hotplug_lock (to hold off
5037 * slab_mem_going_offline_callback) here because slab's memory hot
5038 * unplug code doesn't destroy the kmem_cache->node[] data.
5041 #ifdef CONFIG_SLUB_DEBUG
5042 if (flags & SO_ALL) {
5043 struct kmem_cache_node *n;
5045 for_each_kmem_cache_node(s, node, n) {
5047 if (flags & SO_TOTAL)
5048 x = atomic_long_read(&n->total_objects);
5049 else if (flags & SO_OBJECTS)
5050 x = atomic_long_read(&n->total_objects) -
5051 count_partial(n, count_free);
5053 x = atomic_long_read(&n->nr_slabs);
5060 if (flags & SO_PARTIAL) {
5061 struct kmem_cache_node *n;
5063 for_each_kmem_cache_node(s, node, n) {
5064 if (flags & SO_TOTAL)
5065 x = count_partial(n, count_total);
5066 else if (flags & SO_OBJECTS)
5067 x = count_partial(n, count_inuse);
5074 x = sprintf(buf, "%lu", total);
5076 for (node = 0; node < nr_node_ids; node++)
5078 x += sprintf(buf + x, " N%d=%lu",
5082 return x + sprintf(buf + x, "\n");
5085 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
5086 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
5088 struct slab_attribute {
5089 struct attribute attr;
5090 ssize_t (*show)(struct kmem_cache *s, char *buf);
5091 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5094 #define SLAB_ATTR_RO(_name) \
5095 static struct slab_attribute _name##_attr = \
5096 __ATTR(_name, 0400, _name##_show, NULL)
5098 #define SLAB_ATTR(_name) \
5099 static struct slab_attribute _name##_attr = \
5100 __ATTR(_name, 0600, _name##_show, _name##_store)
5102 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5104 return sprintf(buf, "%u\n", s->size);
5106 SLAB_ATTR_RO(slab_size);
5108 static ssize_t align_show(struct kmem_cache *s, char *buf)
5110 return sprintf(buf, "%u\n", s->align);
5112 SLAB_ATTR_RO(align);
5114 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5116 return sprintf(buf, "%u\n", s->object_size);
5118 SLAB_ATTR_RO(object_size);
5120 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5122 return sprintf(buf, "%u\n", oo_objects(s->oo));
5124 SLAB_ATTR_RO(objs_per_slab);
5126 static ssize_t order_show(struct kmem_cache *s, char *buf)
5128 return sprintf(buf, "%u\n", oo_order(s->oo));
5130 SLAB_ATTR_RO(order);
5132 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5134 return sprintf(buf, "%lu\n", s->min_partial);
5137 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5143 err = kstrtoul(buf, 10, &min);
5147 set_min_partial(s, min);
5150 SLAB_ATTR(min_partial);
5152 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5154 return sprintf(buf, "%u\n", slub_cpu_partial(s));
5157 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5160 unsigned int objects;
5163 err = kstrtouint(buf, 10, &objects);
5166 if (objects && !kmem_cache_has_cpu_partial(s))
5169 slub_set_cpu_partial(s, objects);
5173 SLAB_ATTR(cpu_partial);
5175 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5179 return sprintf(buf, "%pS\n", s->ctor);
5183 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5185 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5187 SLAB_ATTR_RO(aliases);
5189 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5191 return show_slab_objects(s, buf, SO_PARTIAL);
5193 SLAB_ATTR_RO(partial);
5195 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5197 return show_slab_objects(s, buf, SO_CPU);
5199 SLAB_ATTR_RO(cpu_slabs);
5201 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5203 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5205 SLAB_ATTR_RO(objects);
5207 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5209 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5211 SLAB_ATTR_RO(objects_partial);
5213 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5220 for_each_online_cpu(cpu) {
5223 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5226 pages += page->pages;
5227 objects += page->pobjects;
5231 len = sprintf(buf, "%d(%d)", objects, pages);
5234 for_each_online_cpu(cpu) {
5237 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5239 if (page && len < PAGE_SIZE - 20)
5240 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
5241 page->pobjects, page->pages);
5244 return len + sprintf(buf + len, "\n");
5246 SLAB_ATTR_RO(slabs_cpu_partial);
5248 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5250 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5252 SLAB_ATTR_RO(reclaim_account);
5254 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5256 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5258 SLAB_ATTR_RO(hwcache_align);
5260 #ifdef CONFIG_ZONE_DMA
5261 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5263 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5265 SLAB_ATTR_RO(cache_dma);
5268 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5270 return sprintf(buf, "%u\n", s->usersize);
5272 SLAB_ATTR_RO(usersize);
5274 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5276 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5278 SLAB_ATTR_RO(destroy_by_rcu);
5280 #ifdef CONFIG_SLUB_DEBUG
5281 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5283 return show_slab_objects(s, buf, SO_ALL);
5285 SLAB_ATTR_RO(slabs);
5287 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5289 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5291 SLAB_ATTR_RO(total_objects);
5293 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5295 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5297 SLAB_ATTR_RO(sanity_checks);
5299 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5301 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5303 SLAB_ATTR_RO(trace);
5305 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5307 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5310 SLAB_ATTR_RO(red_zone);
5312 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5314 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5317 SLAB_ATTR_RO(poison);
5319 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5321 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5324 SLAB_ATTR_RO(store_user);
5326 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5331 static ssize_t validate_store(struct kmem_cache *s,
5332 const char *buf, size_t length)
5336 if (buf[0] == '1') {
5337 ret = validate_slab_cache(s);
5343 SLAB_ATTR(validate);
5345 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5347 if (!(s->flags & SLAB_STORE_USER))
5349 return list_locations(s, buf, TRACK_ALLOC);
5351 SLAB_ATTR_RO(alloc_calls);
5353 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5355 if (!(s->flags & SLAB_STORE_USER))
5357 return list_locations(s, buf, TRACK_FREE);
5359 SLAB_ATTR_RO(free_calls);
5360 #endif /* CONFIG_SLUB_DEBUG */
5362 #ifdef CONFIG_FAILSLAB
5363 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5365 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5367 SLAB_ATTR_RO(failslab);
5370 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5375 static ssize_t shrink_store(struct kmem_cache *s,
5376 const char *buf, size_t length)
5379 kmem_cache_shrink_all(s);
5387 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5389 return sprintf(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5392 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5393 const char *buf, size_t length)
5398 err = kstrtouint(buf, 10, &ratio);
5404 s->remote_node_defrag_ratio = ratio * 10;
5408 SLAB_ATTR(remote_node_defrag_ratio);
5411 #ifdef CONFIG_SLUB_STATS
5412 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5414 unsigned long sum = 0;
5417 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5422 for_each_online_cpu(cpu) {
5423 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5429 len = sprintf(buf, "%lu", sum);
5432 for_each_online_cpu(cpu) {
5433 if (data[cpu] && len < PAGE_SIZE - 20)
5434 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5438 return len + sprintf(buf + len, "\n");
5441 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5445 for_each_online_cpu(cpu)
5446 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5449 #define STAT_ATTR(si, text) \
5450 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5452 return show_stat(s, buf, si); \
5454 static ssize_t text##_store(struct kmem_cache *s, \
5455 const char *buf, size_t length) \
5457 if (buf[0] != '0') \
5459 clear_stat(s, si); \
5464 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5465 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5466 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5467 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5468 STAT_ATTR(FREE_FROZEN, free_frozen);
5469 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5470 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5471 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5472 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5473 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5474 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5475 STAT_ATTR(FREE_SLAB, free_slab);
5476 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5477 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5478 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5479 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5480 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5481 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5482 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5483 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5484 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5485 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5486 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5487 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5488 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5489 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5490 #endif /* CONFIG_SLUB_STATS */
5492 static struct attribute *slab_attrs[] = {
5493 &slab_size_attr.attr,
5494 &object_size_attr.attr,
5495 &objs_per_slab_attr.attr,
5497 &min_partial_attr.attr,
5498 &cpu_partial_attr.attr,
5500 &objects_partial_attr.attr,
5502 &cpu_slabs_attr.attr,
5506 &hwcache_align_attr.attr,
5507 &reclaim_account_attr.attr,
5508 &destroy_by_rcu_attr.attr,
5510 &slabs_cpu_partial_attr.attr,
5511 #ifdef CONFIG_SLUB_DEBUG
5512 &total_objects_attr.attr,
5514 &sanity_checks_attr.attr,
5516 &red_zone_attr.attr,
5518 &store_user_attr.attr,
5519 &validate_attr.attr,
5520 &alloc_calls_attr.attr,
5521 &free_calls_attr.attr,
5523 #ifdef CONFIG_ZONE_DMA
5524 &cache_dma_attr.attr,
5527 &remote_node_defrag_ratio_attr.attr,
5529 #ifdef CONFIG_SLUB_STATS
5530 &alloc_fastpath_attr.attr,
5531 &alloc_slowpath_attr.attr,
5532 &free_fastpath_attr.attr,
5533 &free_slowpath_attr.attr,
5534 &free_frozen_attr.attr,
5535 &free_add_partial_attr.attr,
5536 &free_remove_partial_attr.attr,
5537 &alloc_from_partial_attr.attr,
5538 &alloc_slab_attr.attr,
5539 &alloc_refill_attr.attr,
5540 &alloc_node_mismatch_attr.attr,
5541 &free_slab_attr.attr,
5542 &cpuslab_flush_attr.attr,
5543 &deactivate_full_attr.attr,
5544 &deactivate_empty_attr.attr,
5545 &deactivate_to_head_attr.attr,
5546 &deactivate_to_tail_attr.attr,
5547 &deactivate_remote_frees_attr.attr,
5548 &deactivate_bypass_attr.attr,
5549 &order_fallback_attr.attr,
5550 &cmpxchg_double_fail_attr.attr,
5551 &cmpxchg_double_cpu_fail_attr.attr,
5552 &cpu_partial_alloc_attr.attr,
5553 &cpu_partial_free_attr.attr,
5554 &cpu_partial_node_attr.attr,
5555 &cpu_partial_drain_attr.attr,
5557 #ifdef CONFIG_FAILSLAB
5558 &failslab_attr.attr,
5560 &usersize_attr.attr,
5565 static const struct attribute_group slab_attr_group = {
5566 .attrs = slab_attrs,
5569 static ssize_t slab_attr_show(struct kobject *kobj,
5570 struct attribute *attr,
5573 struct slab_attribute *attribute;
5574 struct kmem_cache *s;
5577 attribute = to_slab_attr(attr);
5580 if (!attribute->show)
5583 err = attribute->show(s, buf);
5588 static ssize_t slab_attr_store(struct kobject *kobj,
5589 struct attribute *attr,
5590 const char *buf, size_t len)
5592 struct slab_attribute *attribute;
5593 struct kmem_cache *s;
5596 attribute = to_slab_attr(attr);
5599 if (!attribute->store)
5602 err = attribute->store(s, buf, len);
5604 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5605 struct kmem_cache *c;
5607 mutex_lock(&slab_mutex);
5608 if (s->max_attr_size < len)
5609 s->max_attr_size = len;
5612 * This is a best effort propagation, so this function's return
5613 * value will be determined by the parent cache only. This is
5614 * basically because not all attributes will have a well
5615 * defined semantics for rollbacks - most of the actions will
5616 * have permanent effects.
5618 * Returning the error value of any of the children that fail
5619 * is not 100 % defined, in the sense that users seeing the
5620 * error code won't be able to know anything about the state of
5623 * Only returning the error code for the parent cache at least
5624 * has well defined semantics. The cache being written to
5625 * directly either failed or succeeded, in which case we loop
5626 * through the descendants with best-effort propagation.
5628 for_each_memcg_cache(c, s)
5629 attribute->store(c, buf, len);
5630 mutex_unlock(&slab_mutex);
5636 static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5640 char *buffer = NULL;
5641 struct kmem_cache *root_cache;
5643 if (is_root_cache(s))
5646 root_cache = s->memcg_params.root_cache;
5649 * This mean this cache had no attribute written. Therefore, no point
5650 * in copying default values around
5652 if (!root_cache->max_attr_size)
5655 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5658 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5661 if (!attr || !attr->store || !attr->show)
5665 * It is really bad that we have to allocate here, so we will
5666 * do it only as a fallback. If we actually allocate, though,
5667 * we can just use the allocated buffer until the end.
5669 * Most of the slub attributes will tend to be very small in
5670 * size, but sysfs allows buffers up to a page, so they can
5671 * theoretically happen.
5675 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf) &&
5676 !IS_ENABLED(CONFIG_SLUB_STATS))
5679 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5680 if (WARN_ON(!buffer))
5685 len = attr->show(root_cache, buf);
5687 attr->store(s, buf, len);
5691 free_page((unsigned long)buffer);
5692 #endif /* CONFIG_MEMCG */
5695 static void kmem_cache_release(struct kobject *k)
5697 slab_kmem_cache_release(to_slab(k));
5700 static const struct sysfs_ops slab_sysfs_ops = {
5701 .show = slab_attr_show,
5702 .store = slab_attr_store,
5705 static struct kobj_type slab_ktype = {
5706 .sysfs_ops = &slab_sysfs_ops,
5707 .release = kmem_cache_release,
5710 static struct kset *slab_kset;
5712 static inline struct kset *cache_kset(struct kmem_cache *s)
5715 if (!is_root_cache(s))
5716 return s->memcg_params.root_cache->memcg_kset;
5721 #define ID_STR_LENGTH 64
5723 /* Create a unique string id for a slab cache:
5725 * Format :[flags-]size
5727 static char *create_unique_id(struct kmem_cache *s)
5729 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5736 * First flags affecting slabcache operations. We will only
5737 * get here for aliasable slabs so we do not need to support
5738 * too many flags. The flags here must cover all flags that
5739 * are matched during merging to guarantee that the id is
5742 if (s->flags & SLAB_CACHE_DMA)
5744 if (s->flags & SLAB_CACHE_DMA32)
5746 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5748 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5750 if (s->flags & SLAB_ACCOUNT)
5754 p += sprintf(p, "%07u", s->size);
5756 BUG_ON(p > name + ID_STR_LENGTH - 1);
5760 static void sysfs_slab_remove_workfn(struct work_struct *work)
5762 struct kmem_cache *s =
5763 container_of(work, struct kmem_cache, kobj_remove_work);
5765 if (!s->kobj.state_in_sysfs)
5767 * For a memcg cache, this may be called during
5768 * deactivation and again on shutdown. Remove only once.
5769 * A cache is never shut down before deactivation is
5770 * complete, so no need to worry about synchronization.
5775 kset_unregister(s->memcg_kset);
5778 kobject_put(&s->kobj);
5781 static int sysfs_slab_add(struct kmem_cache *s)
5785 struct kset *kset = cache_kset(s);
5786 int unmergeable = slab_unmergeable(s);
5788 INIT_WORK(&s->kobj_remove_work, sysfs_slab_remove_workfn);
5791 kobject_init(&s->kobj, &slab_ktype);
5795 if (!unmergeable && disable_higher_order_debug &&
5796 (slub_debug & DEBUG_METADATA_FLAGS))
5801 * Slabcache can never be merged so we can use the name proper.
5802 * This is typically the case for debug situations. In that
5803 * case we can catch duplicate names easily.
5805 sysfs_remove_link(&slab_kset->kobj, s->name);
5809 * Create a unique name for the slab as a target
5812 name = create_unique_id(s);
5815 s->kobj.kset = kset;
5816 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5818 kobject_put(&s->kobj);
5822 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5827 if (is_root_cache(s) && memcg_sysfs_enabled) {
5828 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5829 if (!s->memcg_kset) {
5837 /* Setup first alias */
5838 sysfs_slab_alias(s, s->name);
5845 kobject_del(&s->kobj);
5849 static void sysfs_slab_remove(struct kmem_cache *s)
5851 if (slab_state < FULL)
5853 * Sysfs has not been setup yet so no need to remove the
5858 kobject_get(&s->kobj);
5859 schedule_work(&s->kobj_remove_work);
5862 void sysfs_slab_unlink(struct kmem_cache *s)
5864 if (slab_state >= FULL)
5865 kobject_del(&s->kobj);
5868 void sysfs_slab_release(struct kmem_cache *s)
5870 if (slab_state >= FULL)
5871 kobject_put(&s->kobj);
5875 * Need to buffer aliases during bootup until sysfs becomes
5876 * available lest we lose that information.
5878 struct saved_alias {
5879 struct kmem_cache *s;
5881 struct saved_alias *next;
5884 static struct saved_alias *alias_list;
5886 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5888 struct saved_alias *al;
5890 if (slab_state == FULL) {
5892 * If we have a leftover link then remove it.
5894 sysfs_remove_link(&slab_kset->kobj, name);
5895 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5898 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5904 al->next = alias_list;
5909 static int __init slab_sysfs_init(void)
5911 struct kmem_cache *s;
5914 mutex_lock(&slab_mutex);
5916 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
5918 mutex_unlock(&slab_mutex);
5919 pr_err("Cannot register slab subsystem.\n");
5925 list_for_each_entry(s, &slab_caches, list) {
5926 err = sysfs_slab_add(s);
5928 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5932 while (alias_list) {
5933 struct saved_alias *al = alias_list;
5935 alias_list = alias_list->next;
5936 err = sysfs_slab_alias(al->s, al->name);
5938 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5943 mutex_unlock(&slab_mutex);
5948 __initcall(slab_sysfs_init);
5949 #endif /* CONFIG_SYSFS */
5952 * The /proc/slabinfo ABI
5954 #ifdef CONFIG_SLUB_DEBUG
5955 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5957 unsigned long nr_slabs = 0;
5958 unsigned long nr_objs = 0;
5959 unsigned long nr_free = 0;
5961 struct kmem_cache_node *n;
5963 for_each_kmem_cache_node(s, node, n) {
5964 nr_slabs += node_nr_slabs(n);
5965 nr_objs += node_nr_objs(n);
5966 nr_free += count_partial(n, count_free);
5969 sinfo->active_objs = nr_objs - nr_free;
5970 sinfo->num_objs = nr_objs;
5971 sinfo->active_slabs = nr_slabs;
5972 sinfo->num_slabs = nr_slabs;
5973 sinfo->objects_per_slab = oo_objects(s->oo);
5974 sinfo->cache_order = oo_order(s->oo);
5977 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5981 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5982 size_t count, loff_t *ppos)
5986 #endif /* CONFIG_SLUB_DEBUG */