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 operations
7 * and only uses a centralized lock to manage a pool of partial slabs.
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
14 #include <linux/swap.h> /* struct reclaim_state */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
22 #include <linux/proc_fs.h>
23 #include <linux/seq_file.h>
24 #include <linux/kasan.h>
25 #include <linux/cpu.h>
26 #include <linux/cpuset.h>
27 #include <linux/mempolicy.h>
28 #include <linux/ctype.h>
29 #include <linux/debugobjects.h>
30 #include <linux/kallsyms.h>
31 #include <linux/kfence.h>
32 #include <linux/memory.h>
33 #include <linux/math64.h>
34 #include <linux/fault-inject.h>
35 #include <linux/stacktrace.h>
36 #include <linux/prefetch.h>
37 #include <linux/memcontrol.h>
38 #include <linux/random.h>
39 #include <kunit/test.h>
41 #include <linux/debugfs.h>
42 #include <trace/events/kmem.h>
48 * 1. slab_mutex (Global Mutex)
50 * 3. slab_lock(page) (Only on some arches and for debugging)
54 * The role of the slab_mutex is to protect the list of all the slabs
55 * and to synchronize major metadata changes to slab cache structures.
57 * The slab_lock is only used for debugging and on arches that do not
58 * have the ability to do a cmpxchg_double. It only protects:
59 * A. page->freelist -> List of object free in a page
60 * B. page->inuse -> Number of objects in use
61 * C. page->objects -> Number of objects in page
62 * D. page->frozen -> frozen state
64 * If a slab is frozen then it is exempt from list management. It is not
65 * on any list except per cpu partial list. The processor that froze the
66 * slab is the one who can perform list operations on the page. Other
67 * processors may put objects onto the freelist but the processor that
68 * froze the slab is the only one that can retrieve the objects from the
71 * The list_lock protects the partial and full list on each node and
72 * the partial slab counter. If taken then no new slabs may be added or
73 * removed from the lists nor make the number of partial slabs be modified.
74 * (Note that the total number of slabs is an atomic value that may be
75 * modified without taking the list lock).
77 * The list_lock is a centralized lock and thus we avoid taking it as
78 * much as possible. As long as SLUB does not have to handle partial
79 * slabs, operations can continue without any centralized lock. F.e.
80 * allocating a long series of objects that fill up slabs does not require
82 * Interrupts are disabled during allocation and deallocation in order to
83 * make the slab allocator safe to use in the context of an irq. In addition
84 * interrupts are disabled to ensure that the processor does not change
85 * while handling per_cpu slabs, due to kernel preemption.
87 * SLUB assigns one slab for allocation to each processor.
88 * Allocations only occur from these slabs called cpu slabs.
90 * Slabs with free elements are kept on a partial list and during regular
91 * operations no list for full slabs is used. If an object in a full slab is
92 * freed then the slab will show up again on the partial lists.
93 * We track full slabs for debugging purposes though because otherwise we
94 * cannot scan all objects.
96 * Slabs are freed when they become empty. Teardown and setup is
97 * minimal so we rely on the page allocators per cpu caches for
98 * fast frees and allocs.
100 * page->frozen The slab is frozen and exempt from list processing.
101 * This means that the slab is dedicated to a purpose
102 * such as satisfying allocations for a specific
103 * processor. Objects may be freed in the slab while
104 * it is frozen but slab_free will then skip the usual
105 * list operations. It is up to the processor holding
106 * the slab to integrate the slab into the slab lists
107 * when the slab is no longer needed.
109 * One use of this flag is to mark slabs that are
110 * used for allocations. Then such a slab becomes a cpu
111 * slab. The cpu slab may be equipped with an additional
112 * freelist that allows lockless access to
113 * free objects in addition to the regular freelist
114 * that requires the slab lock.
116 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
117 * options set. This moves slab handling out of
118 * the fast path and disables lockless freelists.
121 #ifdef CONFIG_SLUB_DEBUG
123 #ifdef CONFIG_SLUB_DEBUG_ON
124 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
126 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
129 static inline bool __slub_debug_enabled(void)
131 return static_branch_unlikely(&slub_debug_enabled);
134 #else /* CONFIG_SLUB_DEBUG */
136 static inline bool __slub_debug_enabled(void)
141 #endif /* CONFIG_SLUB_DEBUG */
143 static inline bool kmem_cache_debug(struct kmem_cache *s)
145 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
148 void *fixup_red_left(struct kmem_cache *s, void *p)
150 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
151 p += s->red_left_pad;
156 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
158 #ifdef CONFIG_SLUB_CPU_PARTIAL
159 return !kmem_cache_debug(s);
166 * Issues still to be resolved:
168 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
170 * - Variable sizing of the per node arrays
173 /* Enable to log cmpxchg failures */
174 #undef SLUB_DEBUG_CMPXCHG
177 * Minimum 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 *);
237 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
238 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
242 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
243 static void debugfs_slab_add(struct kmem_cache *);
245 static inline void debugfs_slab_add(struct kmem_cache *s) { }
248 static inline void stat(const struct kmem_cache *s, enum stat_item si)
250 #ifdef CONFIG_SLUB_STATS
252 * The rmw is racy on a preemptible kernel but this is acceptable, so
253 * avoid this_cpu_add()'s irq-disable overhead.
255 raw_cpu_inc(s->cpu_slab->stat[si]);
260 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
261 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
262 * differ during memory hotplug/hotremove operations.
263 * Protected by slab_mutex.
265 static nodemask_t slab_nodes;
267 /********************************************************************
268 * Core slab cache functions
269 *******************************************************************/
272 * Returns freelist pointer (ptr). With hardening, this is obfuscated
273 * with an XOR of the address where the pointer is held and a per-cache
276 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
277 unsigned long ptr_addr)
279 #ifdef CONFIG_SLAB_FREELIST_HARDENED
281 * When CONFIG_KASAN_SW/HW_TAGS is enabled, ptr_addr might be tagged.
282 * Normally, this doesn't cause any issues, as both set_freepointer()
283 * and get_freepointer() are called with a pointer with the same tag.
284 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
285 * example, when __free_slub() iterates over objects in a cache, it
286 * passes untagged pointers to check_object(). check_object() in turns
287 * calls get_freepointer() with an untagged pointer, which causes the
288 * freepointer to be restored incorrectly.
290 return (void *)((unsigned long)ptr ^ s->random ^
291 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
297 /* Returns the freelist pointer recorded at location ptr_addr. */
298 static inline void *freelist_dereference(const struct kmem_cache *s,
301 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
302 (unsigned long)ptr_addr);
305 static inline void *get_freepointer(struct kmem_cache *s, void *object)
307 object = kasan_reset_tag(object);
308 return freelist_dereference(s, object + s->offset);
311 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
313 prefetch(object + s->offset);
316 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
318 unsigned long freepointer_addr;
321 if (!debug_pagealloc_enabled_static())
322 return get_freepointer(s, object);
324 object = kasan_reset_tag(object);
325 freepointer_addr = (unsigned long)object + s->offset;
326 copy_from_kernel_nofault(&p, (void **)freepointer_addr, sizeof(p));
327 return freelist_ptr(s, p, freepointer_addr);
330 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
332 unsigned long freeptr_addr = (unsigned long)object + s->offset;
334 #ifdef CONFIG_SLAB_FREELIST_HARDENED
335 BUG_ON(object == fp); /* naive detection of double free or corruption */
338 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
339 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
342 /* Loop over all objects in a slab */
343 #define for_each_object(__p, __s, __addr, __objects) \
344 for (__p = fixup_red_left(__s, __addr); \
345 __p < (__addr) + (__objects) * (__s)->size; \
348 static inline unsigned int order_objects(unsigned int order, unsigned int size)
350 return ((unsigned int)PAGE_SIZE << order) / size;
353 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
356 struct kmem_cache_order_objects x = {
357 (order << OO_SHIFT) + order_objects(order, size)
363 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
365 return x.x >> OO_SHIFT;
368 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
370 return x.x & OO_MASK;
374 * Per slab locking using the pagelock
376 static __always_inline void slab_lock(struct page *page)
378 VM_BUG_ON_PAGE(PageTail(page), page);
379 bit_spin_lock(PG_locked, &page->flags);
382 static __always_inline void slab_unlock(struct page *page)
384 VM_BUG_ON_PAGE(PageTail(page), page);
385 __bit_spin_unlock(PG_locked, &page->flags);
388 /* Interrupts must be disabled (for the fallback code to work right) */
389 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
390 void *freelist_old, unsigned long counters_old,
391 void *freelist_new, unsigned long counters_new,
394 VM_BUG_ON(!irqs_disabled());
395 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
396 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
397 if (s->flags & __CMPXCHG_DOUBLE) {
398 if (cmpxchg_double(&page->freelist, &page->counters,
399 freelist_old, counters_old,
400 freelist_new, counters_new))
406 if (page->freelist == freelist_old &&
407 page->counters == counters_old) {
408 page->freelist = freelist_new;
409 page->counters = counters_new;
417 stat(s, CMPXCHG_DOUBLE_FAIL);
419 #ifdef SLUB_DEBUG_CMPXCHG
420 pr_info("%s %s: cmpxchg double redo ", n, s->name);
426 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
427 void *freelist_old, unsigned long counters_old,
428 void *freelist_new, unsigned long counters_new,
431 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
432 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
433 if (s->flags & __CMPXCHG_DOUBLE) {
434 if (cmpxchg_double(&page->freelist, &page->counters,
435 freelist_old, counters_old,
436 freelist_new, counters_new))
443 local_irq_save(flags);
445 if (page->freelist == freelist_old &&
446 page->counters == counters_old) {
447 page->freelist = freelist_new;
448 page->counters = counters_new;
450 local_irq_restore(flags);
454 local_irq_restore(flags);
458 stat(s, CMPXCHG_DOUBLE_FAIL);
460 #ifdef SLUB_DEBUG_CMPXCHG
461 pr_info("%s %s: cmpxchg double redo ", n, s->name);
467 #ifdef CONFIG_SLUB_DEBUG
468 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
469 static DEFINE_SPINLOCK(object_map_lock);
471 #if IS_ENABLED(CONFIG_KUNIT)
472 static bool slab_add_kunit_errors(void)
474 struct kunit_resource *resource;
476 if (likely(!current->kunit_test))
479 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
483 (*(int *)resource->data)++;
484 kunit_put_resource(resource);
488 static inline bool slab_add_kunit_errors(void) { return false; }
492 * Determine a map of object in use on a page.
494 * Node listlock must be held to guarantee that the page does
495 * not vanish from under us.
497 static unsigned long *get_map(struct kmem_cache *s, struct page *page)
498 __acquires(&object_map_lock)
501 void *addr = page_address(page);
503 VM_BUG_ON(!irqs_disabled());
505 spin_lock(&object_map_lock);
507 bitmap_zero(object_map, page->objects);
509 for (p = page->freelist; p; p = get_freepointer(s, p))
510 set_bit(__obj_to_index(s, addr, p), object_map);
515 static void put_map(unsigned long *map) __releases(&object_map_lock)
517 VM_BUG_ON(map != object_map);
518 spin_unlock(&object_map_lock);
521 static inline unsigned int size_from_object(struct kmem_cache *s)
523 if (s->flags & SLAB_RED_ZONE)
524 return s->size - s->red_left_pad;
529 static inline void *restore_red_left(struct kmem_cache *s, void *p)
531 if (s->flags & SLAB_RED_ZONE)
532 p -= s->red_left_pad;
540 #if defined(CONFIG_SLUB_DEBUG_ON)
541 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
543 static slab_flags_t slub_debug;
546 static char *slub_debug_string;
547 static int disable_higher_order_debug;
550 * slub is about to manipulate internal object metadata. This memory lies
551 * outside the range of the allocated object, so accessing it would normally
552 * be reported by kasan as a bounds error. metadata_access_enable() is used
553 * to tell kasan that these accesses are OK.
555 static inline void metadata_access_enable(void)
557 kasan_disable_current();
560 static inline void metadata_access_disable(void)
562 kasan_enable_current();
569 /* Verify that a pointer has an address that is valid within a slab page */
570 static inline int check_valid_pointer(struct kmem_cache *s,
571 struct page *page, void *object)
578 base = page_address(page);
579 object = kasan_reset_tag(object);
580 object = restore_red_left(s, object);
581 if (object < base || object >= base + page->objects * s->size ||
582 (object - base) % s->size) {
589 static void print_section(char *level, char *text, u8 *addr,
592 metadata_access_enable();
593 print_hex_dump(level, kasan_reset_tag(text), DUMP_PREFIX_ADDRESS,
594 16, 1, addr, length, 1);
595 metadata_access_disable();
599 * See comment in calculate_sizes().
601 static inline bool freeptr_outside_object(struct kmem_cache *s)
603 return s->offset >= s->inuse;
607 * Return offset of the end of info block which is inuse + free pointer if
608 * not overlapping with object.
610 static inline unsigned int get_info_end(struct kmem_cache *s)
612 if (freeptr_outside_object(s))
613 return s->inuse + sizeof(void *);
618 static struct track *get_track(struct kmem_cache *s, void *object,
619 enum track_item alloc)
623 p = object + get_info_end(s);
625 return kasan_reset_tag(p + alloc);
628 static void set_track(struct kmem_cache *s, void *object,
629 enum track_item alloc, unsigned long addr)
631 struct track *p = get_track(s, object, alloc);
634 #ifdef CONFIG_STACKTRACE
635 unsigned int nr_entries;
637 metadata_access_enable();
638 nr_entries = stack_trace_save(kasan_reset_tag(p->addrs),
639 TRACK_ADDRS_COUNT, 3);
640 metadata_access_disable();
642 if (nr_entries < TRACK_ADDRS_COUNT)
643 p->addrs[nr_entries] = 0;
646 p->cpu = smp_processor_id();
647 p->pid = current->pid;
650 memset(p, 0, sizeof(struct track));
654 static void init_tracking(struct kmem_cache *s, void *object)
656 if (!(s->flags & SLAB_STORE_USER))
659 set_track(s, object, TRACK_FREE, 0UL);
660 set_track(s, object, TRACK_ALLOC, 0UL);
663 static void print_track(const char *s, struct track *t, unsigned long pr_time)
668 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
669 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
670 #ifdef CONFIG_STACKTRACE
673 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
675 pr_err("\t%pS\n", (void *)t->addrs[i]);
682 void print_tracking(struct kmem_cache *s, void *object)
684 unsigned long pr_time = jiffies;
685 if (!(s->flags & SLAB_STORE_USER))
688 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
689 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
692 static void print_page_info(struct page *page)
694 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%#lx(%pGp)\n",
695 page, page->objects, page->inuse, page->freelist,
696 page->flags, &page->flags);
700 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
702 struct va_format vaf;
708 pr_err("=============================================================================\n");
709 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
710 pr_err("-----------------------------------------------------------------------------\n\n");
715 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
717 struct va_format vaf;
720 if (slab_add_kunit_errors())
726 pr_err("FIX %s: %pV\n", s->name, &vaf);
730 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
731 void **freelist, void *nextfree)
733 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
734 !check_valid_pointer(s, page, nextfree) && freelist) {
735 object_err(s, page, *freelist, "Freechain corrupt");
737 slab_fix(s, "Isolate corrupted freechain");
744 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
746 unsigned int off; /* Offset of last byte */
747 u8 *addr = page_address(page);
749 print_tracking(s, p);
751 print_page_info(page);
753 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
754 p, p - addr, get_freepointer(s, p));
756 if (s->flags & SLAB_RED_ZONE)
757 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
759 else if (p > addr + 16)
760 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
762 print_section(KERN_ERR, "Object ", p,
763 min_t(unsigned int, s->object_size, PAGE_SIZE));
764 if (s->flags & SLAB_RED_ZONE)
765 print_section(KERN_ERR, "Redzone ", p + s->object_size,
766 s->inuse - s->object_size);
768 off = get_info_end(s);
770 if (s->flags & SLAB_STORE_USER)
771 off += 2 * sizeof(struct track);
773 off += kasan_metadata_size(s);
775 if (off != size_from_object(s))
776 /* Beginning of the filler is the free pointer */
777 print_section(KERN_ERR, "Padding ", p + off,
778 size_from_object(s) - off);
783 void object_err(struct kmem_cache *s, struct page *page,
784 u8 *object, char *reason)
786 if (slab_add_kunit_errors())
789 slab_bug(s, "%s", reason);
790 print_trailer(s, page, object);
791 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
794 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
795 const char *fmt, ...)
800 if (slab_add_kunit_errors())
804 vsnprintf(buf, sizeof(buf), fmt, args);
806 slab_bug(s, "%s", buf);
807 print_page_info(page);
809 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
812 static void init_object(struct kmem_cache *s, void *object, u8 val)
814 u8 *p = kasan_reset_tag(object);
816 if (s->flags & SLAB_RED_ZONE)
817 memset(p - s->red_left_pad, val, s->red_left_pad);
819 if (s->flags & __OBJECT_POISON) {
820 memset(p, POISON_FREE, s->object_size - 1);
821 p[s->object_size - 1] = POISON_END;
824 if (s->flags & SLAB_RED_ZONE)
825 memset(p + s->object_size, val, s->inuse - s->object_size);
828 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
829 void *from, void *to)
831 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
832 memset(from, data, to - from);
835 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
836 u8 *object, char *what,
837 u8 *start, unsigned int value, unsigned int bytes)
841 u8 *addr = page_address(page);
843 metadata_access_enable();
844 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
845 metadata_access_disable();
850 while (end > fault && end[-1] == value)
853 if (slab_add_kunit_errors())
856 slab_bug(s, "%s overwritten", what);
857 pr_err("0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
858 fault, end - 1, fault - addr,
860 print_trailer(s, page, object);
861 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
864 restore_bytes(s, what, value, fault, end);
872 * Bytes of the object to be managed.
873 * If the freepointer may overlay the object then the free
874 * pointer is at the middle of the object.
876 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
879 * object + s->object_size
880 * Padding to reach word boundary. This is also used for Redzoning.
881 * Padding is extended by another word if Redzoning is enabled and
882 * object_size == inuse.
884 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
885 * 0xcc (RED_ACTIVE) for objects in use.
888 * Meta data starts here.
890 * A. Free pointer (if we cannot overwrite object on free)
891 * B. Tracking data for SLAB_STORE_USER
892 * C. Padding to reach required alignment boundary or at minimum
893 * one word if debugging is on to be able to detect writes
894 * before the word boundary.
896 * Padding is done using 0x5a (POISON_INUSE)
899 * Nothing is used beyond s->size.
901 * If slabcaches are merged then the object_size and inuse boundaries are mostly
902 * ignored. And therefore no slab options that rely on these boundaries
903 * may be used with merged slabcaches.
906 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
908 unsigned long off = get_info_end(s); /* The end of info */
910 if (s->flags & SLAB_STORE_USER)
911 /* We also have user information there */
912 off += 2 * sizeof(struct track);
914 off += kasan_metadata_size(s);
916 if (size_from_object(s) == off)
919 return check_bytes_and_report(s, page, p, "Object padding",
920 p + off, POISON_INUSE, size_from_object(s) - off);
923 /* Check the pad bytes at the end of a slab page */
924 static int slab_pad_check(struct kmem_cache *s, struct page *page)
933 if (!(s->flags & SLAB_POISON))
936 start = page_address(page);
937 length = page_size(page);
938 end = start + length;
939 remainder = length % s->size;
943 pad = end - remainder;
944 metadata_access_enable();
945 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
946 metadata_access_disable();
949 while (end > fault && end[-1] == POISON_INUSE)
952 slab_err(s, page, "Padding overwritten. 0x%p-0x%p @offset=%tu",
953 fault, end - 1, fault - start);
954 print_section(KERN_ERR, "Padding ", pad, remainder);
956 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
960 static int check_object(struct kmem_cache *s, struct page *page,
961 void *object, u8 val)
964 u8 *endobject = object + s->object_size;
966 if (s->flags & SLAB_RED_ZONE) {
967 if (!check_bytes_and_report(s, page, object, "Left Redzone",
968 object - s->red_left_pad, val, s->red_left_pad))
971 if (!check_bytes_and_report(s, page, object, "Right Redzone",
972 endobject, val, s->inuse - s->object_size))
975 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
976 check_bytes_and_report(s, page, p, "Alignment padding",
977 endobject, POISON_INUSE,
978 s->inuse - s->object_size);
982 if (s->flags & SLAB_POISON) {
983 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
984 (!check_bytes_and_report(s, page, p, "Poison", p,
985 POISON_FREE, s->object_size - 1) ||
986 !check_bytes_and_report(s, page, p, "End Poison",
987 p + s->object_size - 1, POISON_END, 1)))
990 * check_pad_bytes cleans up on its own.
992 check_pad_bytes(s, page, p);
995 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
997 * Object and freepointer overlap. Cannot check
998 * freepointer while object is allocated.
1002 /* Check free pointer validity */
1003 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
1004 object_err(s, page, p, "Freepointer corrupt");
1006 * No choice but to zap it and thus lose the remainder
1007 * of the free objects in this slab. May cause
1008 * another error because the object count is now wrong.
1010 set_freepointer(s, p, NULL);
1016 static int check_slab(struct kmem_cache *s, struct page *page)
1020 VM_BUG_ON(!irqs_disabled());
1022 if (!PageSlab(page)) {
1023 slab_err(s, page, "Not a valid slab page");
1027 maxobj = order_objects(compound_order(page), s->size);
1028 if (page->objects > maxobj) {
1029 slab_err(s, page, "objects %u > max %u",
1030 page->objects, maxobj);
1033 if (page->inuse > page->objects) {
1034 slab_err(s, page, "inuse %u > max %u",
1035 page->inuse, page->objects);
1038 /* Slab_pad_check fixes things up after itself */
1039 slab_pad_check(s, page);
1044 * Determine if a certain object on a page is on the freelist. Must hold the
1045 * slab lock to guarantee that the chains are in a consistent state.
1047 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
1051 void *object = NULL;
1054 fp = page->freelist;
1055 while (fp && nr <= page->objects) {
1058 if (!check_valid_pointer(s, page, fp)) {
1060 object_err(s, page, object,
1061 "Freechain corrupt");
1062 set_freepointer(s, object, NULL);
1064 slab_err(s, page, "Freepointer corrupt");
1065 page->freelist = NULL;
1066 page->inuse = page->objects;
1067 slab_fix(s, "Freelist cleared");
1073 fp = get_freepointer(s, object);
1077 max_objects = order_objects(compound_order(page), s->size);
1078 if (max_objects > MAX_OBJS_PER_PAGE)
1079 max_objects = MAX_OBJS_PER_PAGE;
1081 if (page->objects != max_objects) {
1082 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1083 page->objects, max_objects);
1084 page->objects = max_objects;
1085 slab_fix(s, "Number of objects adjusted");
1087 if (page->inuse != page->objects - nr) {
1088 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1089 page->inuse, page->objects - nr);
1090 page->inuse = page->objects - nr;
1091 slab_fix(s, "Object count adjusted");
1093 return search == NULL;
1096 static void trace(struct kmem_cache *s, struct page *page, void *object,
1099 if (s->flags & SLAB_TRACE) {
1100 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1102 alloc ? "alloc" : "free",
1103 object, page->inuse,
1107 print_section(KERN_INFO, "Object ", (void *)object,
1115 * Tracking of fully allocated slabs for debugging purposes.
1117 static void add_full(struct kmem_cache *s,
1118 struct kmem_cache_node *n, struct page *page)
1120 if (!(s->flags & SLAB_STORE_USER))
1123 lockdep_assert_held(&n->list_lock);
1124 list_add(&page->slab_list, &n->full);
1127 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1129 if (!(s->flags & SLAB_STORE_USER))
1132 lockdep_assert_held(&n->list_lock);
1133 list_del(&page->slab_list);
1136 /* Tracking of the number of slabs for debugging purposes */
1137 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1139 struct kmem_cache_node *n = get_node(s, node);
1141 return atomic_long_read(&n->nr_slabs);
1144 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1146 return atomic_long_read(&n->nr_slabs);
1149 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1151 struct kmem_cache_node *n = get_node(s, node);
1154 * May be called early in order to allocate a slab for the
1155 * kmem_cache_node structure. Solve the chicken-egg
1156 * dilemma by deferring the increment of the count during
1157 * bootstrap (see early_kmem_cache_node_alloc).
1160 atomic_long_inc(&n->nr_slabs);
1161 atomic_long_add(objects, &n->total_objects);
1164 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1166 struct kmem_cache_node *n = get_node(s, node);
1168 atomic_long_dec(&n->nr_slabs);
1169 atomic_long_sub(objects, &n->total_objects);
1172 /* Object debug checks for alloc/free paths */
1173 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1176 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1179 init_object(s, object, SLUB_RED_INACTIVE);
1180 init_tracking(s, object);
1184 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1186 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1189 metadata_access_enable();
1190 memset(kasan_reset_tag(addr), POISON_INUSE, page_size(page));
1191 metadata_access_disable();
1194 static inline int alloc_consistency_checks(struct kmem_cache *s,
1195 struct page *page, void *object)
1197 if (!check_slab(s, page))
1200 if (!check_valid_pointer(s, page, object)) {
1201 object_err(s, page, object, "Freelist Pointer check fails");
1205 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1211 static noinline int alloc_debug_processing(struct kmem_cache *s,
1213 void *object, unsigned long addr)
1215 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1216 if (!alloc_consistency_checks(s, page, object))
1220 /* Success perform special debug activities for allocs */
1221 if (s->flags & SLAB_STORE_USER)
1222 set_track(s, object, TRACK_ALLOC, addr);
1223 trace(s, page, object, 1);
1224 init_object(s, object, SLUB_RED_ACTIVE);
1228 if (PageSlab(page)) {
1230 * If this is a slab page then lets do the best we can
1231 * to avoid issues in the future. Marking all objects
1232 * as used avoids touching the remaining objects.
1234 slab_fix(s, "Marking all objects used");
1235 page->inuse = page->objects;
1236 page->freelist = NULL;
1241 static inline int free_consistency_checks(struct kmem_cache *s,
1242 struct page *page, void *object, unsigned long addr)
1244 if (!check_valid_pointer(s, page, object)) {
1245 slab_err(s, page, "Invalid object pointer 0x%p", object);
1249 if (on_freelist(s, page, object)) {
1250 object_err(s, page, object, "Object already free");
1254 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1257 if (unlikely(s != page->slab_cache)) {
1258 if (!PageSlab(page)) {
1259 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1261 } else if (!page->slab_cache) {
1262 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1266 object_err(s, page, object,
1267 "page slab pointer corrupt.");
1273 /* Supports checking bulk free of a constructed freelist */
1274 static noinline int free_debug_processing(
1275 struct kmem_cache *s, struct page *page,
1276 void *head, void *tail, int bulk_cnt,
1279 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1280 void *object = head;
1282 unsigned long flags;
1285 spin_lock_irqsave(&n->list_lock, flags);
1288 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1289 if (!check_slab(s, page))
1296 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1297 if (!free_consistency_checks(s, page, object, addr))
1301 if (s->flags & SLAB_STORE_USER)
1302 set_track(s, object, TRACK_FREE, addr);
1303 trace(s, page, object, 0);
1304 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1305 init_object(s, object, SLUB_RED_INACTIVE);
1307 /* Reached end of constructed freelist yet? */
1308 if (object != tail) {
1309 object = get_freepointer(s, object);
1315 if (cnt != bulk_cnt)
1316 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1320 spin_unlock_irqrestore(&n->list_lock, flags);
1322 slab_fix(s, "Object at 0x%p not freed", object);
1327 * Parse a block of slub_debug options. Blocks are delimited by ';'
1329 * @str: start of block
1330 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1331 * @slabs: return start of list of slabs, or NULL when there's no list
1332 * @init: assume this is initial parsing and not per-kmem-create parsing
1334 * returns the start of next block if there's any, or NULL
1337 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1339 bool higher_order_disable = false;
1341 /* Skip any completely empty blocks */
1342 while (*str && *str == ';')
1347 * No options but restriction on slabs. This means full
1348 * debugging for slabs matching a pattern.
1350 *flags = DEBUG_DEFAULT_FLAGS;
1355 /* Determine which debug features should be switched on */
1356 for (; *str && *str != ',' && *str != ';'; str++) {
1357 switch (tolower(*str)) {
1362 *flags |= SLAB_CONSISTENCY_CHECKS;
1365 *flags |= SLAB_RED_ZONE;
1368 *flags |= SLAB_POISON;
1371 *flags |= SLAB_STORE_USER;
1374 *flags |= SLAB_TRACE;
1377 *flags |= SLAB_FAILSLAB;
1381 * Avoid enabling debugging on caches if its minimum
1382 * order would increase as a result.
1384 higher_order_disable = true;
1388 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
1397 /* Skip over the slab list */
1398 while (*str && *str != ';')
1401 /* Skip any completely empty blocks */
1402 while (*str && *str == ';')
1405 if (init && higher_order_disable)
1406 disable_higher_order_debug = 1;
1414 static int __init setup_slub_debug(char *str)
1419 bool global_slub_debug_changed = false;
1420 bool slab_list_specified = false;
1422 slub_debug = DEBUG_DEFAULT_FLAGS;
1423 if (*str++ != '=' || !*str)
1425 * No options specified. Switch on full debugging.
1431 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1435 global_slub_debug_changed = true;
1437 slab_list_specified = true;
1442 * For backwards compatibility, a single list of flags with list of
1443 * slabs means debugging is only enabled for those slabs, so the global
1444 * slub_debug should be 0. We can extended that to multiple lists as
1445 * long as there is no option specifying flags without a slab list.
1447 if (slab_list_specified) {
1448 if (!global_slub_debug_changed)
1450 slub_debug_string = saved_str;
1453 if (slub_debug != 0 || slub_debug_string)
1454 static_branch_enable(&slub_debug_enabled);
1456 static_branch_disable(&slub_debug_enabled);
1457 if ((static_branch_unlikely(&init_on_alloc) ||
1458 static_branch_unlikely(&init_on_free)) &&
1459 (slub_debug & SLAB_POISON))
1460 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1464 __setup("slub_debug", setup_slub_debug);
1467 * kmem_cache_flags - apply debugging options to the cache
1468 * @object_size: the size of an object without meta data
1469 * @flags: flags to set
1470 * @name: name of the cache
1472 * Debug option(s) are applied to @flags. In addition to the debug
1473 * option(s), if a slab name (or multiple) is specified i.e.
1474 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1475 * then only the select slabs will receive the debug option(s).
1477 slab_flags_t kmem_cache_flags(unsigned int object_size,
1478 slab_flags_t flags, const char *name)
1483 slab_flags_t block_flags;
1484 slab_flags_t slub_debug_local = slub_debug;
1487 * If the slab cache is for debugging (e.g. kmemleak) then
1488 * don't store user (stack trace) information by default,
1489 * but let the user enable it via the command line below.
1491 if (flags & SLAB_NOLEAKTRACE)
1492 slub_debug_local &= ~SLAB_STORE_USER;
1495 next_block = slub_debug_string;
1496 /* Go through all blocks of debug options, see if any matches our slab's name */
1497 while (next_block) {
1498 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1501 /* Found a block that has a slab list, search it */
1506 end = strchrnul(iter, ',');
1507 if (next_block && next_block < end)
1508 end = next_block - 1;
1510 glob = strnchr(iter, end - iter, '*');
1512 cmplen = glob - iter;
1514 cmplen = max_t(size_t, len, (end - iter));
1516 if (!strncmp(name, iter, cmplen)) {
1517 flags |= block_flags;
1521 if (!*end || *end == ';')
1527 return flags | slub_debug_local;
1529 #else /* !CONFIG_SLUB_DEBUG */
1530 static inline void setup_object_debug(struct kmem_cache *s,
1531 struct page *page, void *object) {}
1533 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1535 static inline int alloc_debug_processing(struct kmem_cache *s,
1536 struct page *page, void *object, unsigned long addr) { return 0; }
1538 static inline int free_debug_processing(
1539 struct kmem_cache *s, struct page *page,
1540 void *head, void *tail, int bulk_cnt,
1541 unsigned long addr) { return 0; }
1543 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1545 static inline int check_object(struct kmem_cache *s, struct page *page,
1546 void *object, u8 val) { return 1; }
1547 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1548 struct page *page) {}
1549 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1550 struct page *page) {}
1551 slab_flags_t kmem_cache_flags(unsigned int object_size,
1552 slab_flags_t flags, const char *name)
1556 #define slub_debug 0
1558 #define disable_higher_order_debug 0
1560 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1562 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1564 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1566 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1569 static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1570 void **freelist, void *nextfree)
1574 #endif /* CONFIG_SLUB_DEBUG */
1577 * Hooks for other subsystems that check memory allocations. In a typical
1578 * production configuration these hooks all should produce no code at all.
1580 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1582 ptr = kasan_kmalloc_large(ptr, size, flags);
1583 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1584 kmemleak_alloc(ptr, size, 1, flags);
1588 static __always_inline void kfree_hook(void *x)
1591 kasan_kfree_large(x);
1594 static __always_inline bool slab_free_hook(struct kmem_cache *s,
1597 kmemleak_free_recursive(x, s->flags);
1600 * Trouble is that we may no longer disable interrupts in the fast path
1601 * So in order to make the debug calls that expect irqs to be
1602 * disabled we need to disable interrupts temporarily.
1604 #ifdef CONFIG_LOCKDEP
1606 unsigned long flags;
1608 local_irq_save(flags);
1609 debug_check_no_locks_freed(x, s->object_size);
1610 local_irq_restore(flags);
1613 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1614 debug_check_no_obj_freed(x, s->object_size);
1616 /* Use KCSAN to help debug racy use-after-free. */
1617 if (!(s->flags & SLAB_TYPESAFE_BY_RCU))
1618 __kcsan_check_access(x, s->object_size,
1619 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
1622 * As memory initialization might be integrated into KASAN,
1623 * kasan_slab_free and initialization memset's must be
1624 * kept together to avoid discrepancies in behavior.
1626 * The initialization memset's clear the object and the metadata,
1627 * but don't touch the SLAB redzone.
1632 if (!kasan_has_integrated_init())
1633 memset(kasan_reset_tag(x), 0, s->object_size);
1634 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
1635 memset((char *)kasan_reset_tag(x) + s->inuse, 0,
1636 s->size - s->inuse - rsize);
1638 /* KASAN might put x into memory quarantine, delaying its reuse. */
1639 return kasan_slab_free(s, x, init);
1642 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1643 void **head, void **tail)
1648 void *old_tail = *tail ? *tail : *head;
1650 if (is_kfence_address(next)) {
1651 slab_free_hook(s, next, false);
1655 /* Head and tail of the reconstructed freelist */
1661 next = get_freepointer(s, object);
1663 /* If object's reuse doesn't have to be delayed */
1664 if (!slab_free_hook(s, object, slab_want_init_on_free(s))) {
1665 /* Move object to the new freelist */
1666 set_freepointer(s, object, *head);
1671 } while (object != old_tail);
1676 return *head != NULL;
1679 static void *setup_object(struct kmem_cache *s, struct page *page,
1682 setup_object_debug(s, page, object);
1683 object = kasan_init_slab_obj(s, object);
1684 if (unlikely(s->ctor)) {
1685 kasan_unpoison_object_data(s, object);
1687 kasan_poison_object_data(s, object);
1693 * Slab allocation and freeing
1695 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1696 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1699 unsigned int order = oo_order(oo);
1701 if (node == NUMA_NO_NODE)
1702 page = alloc_pages(flags, order);
1704 page = __alloc_pages_node(node, flags, order);
1709 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1710 /* Pre-initialize the random sequence cache */
1711 static int init_cache_random_seq(struct kmem_cache *s)
1713 unsigned int count = oo_objects(s->oo);
1716 /* Bailout if already initialised */
1720 err = cache_random_seq_create(s, count, GFP_KERNEL);
1722 pr_err("SLUB: Unable to initialize free list for %s\n",
1727 /* Transform to an offset on the set of pages */
1728 if (s->random_seq) {
1731 for (i = 0; i < count; i++)
1732 s->random_seq[i] *= s->size;
1737 /* Initialize each random sequence freelist per cache */
1738 static void __init init_freelist_randomization(void)
1740 struct kmem_cache *s;
1742 mutex_lock(&slab_mutex);
1744 list_for_each_entry(s, &slab_caches, list)
1745 init_cache_random_seq(s);
1747 mutex_unlock(&slab_mutex);
1750 /* Get the next entry on the pre-computed freelist randomized */
1751 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1752 unsigned long *pos, void *start,
1753 unsigned long page_limit,
1754 unsigned long freelist_count)
1759 * If the target page allocation failed, the number of objects on the
1760 * page might be smaller than the usual size defined by the cache.
1763 idx = s->random_seq[*pos];
1765 if (*pos >= freelist_count)
1767 } while (unlikely(idx >= page_limit));
1769 return (char *)start + idx;
1772 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1773 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1778 unsigned long idx, pos, page_limit, freelist_count;
1780 if (page->objects < 2 || !s->random_seq)
1783 freelist_count = oo_objects(s->oo);
1784 pos = get_random_int() % freelist_count;
1786 page_limit = page->objects * s->size;
1787 start = fixup_red_left(s, page_address(page));
1789 /* First entry is used as the base of the freelist */
1790 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1792 cur = setup_object(s, page, cur);
1793 page->freelist = cur;
1795 for (idx = 1; idx < page->objects; idx++) {
1796 next = next_freelist_entry(s, page, &pos, start, page_limit,
1798 next = setup_object(s, page, next);
1799 set_freepointer(s, cur, next);
1802 set_freepointer(s, cur, NULL);
1807 static inline int init_cache_random_seq(struct kmem_cache *s)
1811 static inline void init_freelist_randomization(void) { }
1812 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1816 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1818 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1821 struct kmem_cache_order_objects oo = s->oo;
1823 void *start, *p, *next;
1827 flags &= gfp_allowed_mask;
1829 if (gfpflags_allow_blocking(flags))
1832 flags |= s->allocflags;
1835 * Let the initial higher-order allocation fail under memory pressure
1836 * so we fall-back to the minimum order allocation.
1838 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1839 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1840 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1842 page = alloc_slab_page(s, alloc_gfp, node, oo);
1843 if (unlikely(!page)) {
1847 * Allocation may have failed due to fragmentation.
1848 * Try a lower order alloc if possible
1850 page = alloc_slab_page(s, alloc_gfp, node, oo);
1851 if (unlikely(!page))
1853 stat(s, ORDER_FALLBACK);
1856 page->objects = oo_objects(oo);
1858 account_slab_page(page, oo_order(oo), s, flags);
1860 page->slab_cache = s;
1861 __SetPageSlab(page);
1862 if (page_is_pfmemalloc(page))
1863 SetPageSlabPfmemalloc(page);
1865 kasan_poison_slab(page);
1867 start = page_address(page);
1869 setup_page_debug(s, page, start);
1871 shuffle = shuffle_freelist(s, page);
1874 start = fixup_red_left(s, start);
1875 start = setup_object(s, page, start);
1876 page->freelist = start;
1877 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1879 next = setup_object(s, page, next);
1880 set_freepointer(s, p, next);
1883 set_freepointer(s, p, NULL);
1886 page->inuse = page->objects;
1890 if (gfpflags_allow_blocking(flags))
1891 local_irq_disable();
1895 inc_slabs_node(s, page_to_nid(page), page->objects);
1900 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1902 if (unlikely(flags & GFP_SLAB_BUG_MASK))
1903 flags = kmalloc_fix_flags(flags);
1905 return allocate_slab(s,
1906 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1909 static void __free_slab(struct kmem_cache *s, struct page *page)
1911 int order = compound_order(page);
1912 int pages = 1 << order;
1914 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
1917 slab_pad_check(s, page);
1918 for_each_object(p, s, page_address(page),
1920 check_object(s, page, p, SLUB_RED_INACTIVE);
1923 __ClearPageSlabPfmemalloc(page);
1924 __ClearPageSlab(page);
1925 /* In union with page->mapping where page allocator expects NULL */
1926 page->slab_cache = NULL;
1927 if (current->reclaim_state)
1928 current->reclaim_state->reclaimed_slab += pages;
1929 unaccount_slab_page(page, order, s);
1930 __free_pages(page, order);
1933 static void rcu_free_slab(struct rcu_head *h)
1935 struct page *page = container_of(h, struct page, rcu_head);
1937 __free_slab(page->slab_cache, page);
1940 static void free_slab(struct kmem_cache *s, struct page *page)
1942 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1943 call_rcu(&page->rcu_head, rcu_free_slab);
1945 __free_slab(s, page);
1948 static void discard_slab(struct kmem_cache *s, struct page *page)
1950 dec_slabs_node(s, page_to_nid(page), page->objects);
1955 * Management of partially allocated slabs.
1958 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1961 if (tail == DEACTIVATE_TO_TAIL)
1962 list_add_tail(&page->slab_list, &n->partial);
1964 list_add(&page->slab_list, &n->partial);
1967 static inline void add_partial(struct kmem_cache_node *n,
1968 struct page *page, int tail)
1970 lockdep_assert_held(&n->list_lock);
1971 __add_partial(n, page, tail);
1974 static inline void remove_partial(struct kmem_cache_node *n,
1977 lockdep_assert_held(&n->list_lock);
1978 list_del(&page->slab_list);
1983 * Remove slab from the partial list, freeze it and
1984 * return the pointer to the freelist.
1986 * Returns a list of objects or NULL if it fails.
1988 static inline void *acquire_slab(struct kmem_cache *s,
1989 struct kmem_cache_node *n, struct page *page,
1990 int mode, int *objects)
1993 unsigned long counters;
1996 lockdep_assert_held(&n->list_lock);
1999 * Zap the freelist and set the frozen bit.
2000 * The old freelist is the list of objects for the
2001 * per cpu allocation list.
2003 freelist = page->freelist;
2004 counters = page->counters;
2005 new.counters = counters;
2006 *objects = new.objects - new.inuse;
2008 new.inuse = page->objects;
2009 new.freelist = NULL;
2011 new.freelist = freelist;
2014 VM_BUG_ON(new.frozen);
2017 if (!__cmpxchg_double_slab(s, page,
2019 new.freelist, new.counters,
2023 remove_partial(n, page);
2028 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
2029 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
2032 * Try to allocate a partial slab from a specific node.
2034 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
2035 struct kmem_cache_cpu *c, gfp_t flags)
2037 struct page *page, *page2;
2038 void *object = NULL;
2039 unsigned int available = 0;
2043 * Racy check. If we mistakenly see no partial slabs then we
2044 * just allocate an empty slab. If we mistakenly try to get a
2045 * partial slab and there is none available then get_partial()
2048 if (!n || !n->nr_partial)
2051 spin_lock(&n->list_lock);
2052 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
2055 if (!pfmemalloc_match(page, flags))
2058 t = acquire_slab(s, n, page, object == NULL, &objects);
2062 available += objects;
2065 stat(s, ALLOC_FROM_PARTIAL);
2068 put_cpu_partial(s, page, 0);
2069 stat(s, CPU_PARTIAL_NODE);
2071 if (!kmem_cache_has_cpu_partial(s)
2072 || available > slub_cpu_partial(s) / 2)
2076 spin_unlock(&n->list_lock);
2081 * Get a page from somewhere. Search in increasing NUMA distances.
2083 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
2084 struct kmem_cache_cpu *c)
2087 struct zonelist *zonelist;
2090 enum zone_type highest_zoneidx = gfp_zone(flags);
2092 unsigned int cpuset_mems_cookie;
2095 * The defrag ratio allows a configuration of the tradeoffs between
2096 * inter node defragmentation and node local allocations. A lower
2097 * defrag_ratio increases the tendency to do local allocations
2098 * instead of attempting to obtain partial slabs from other nodes.
2100 * If the defrag_ratio is set to 0 then kmalloc() always
2101 * returns node local objects. If the ratio is higher then kmalloc()
2102 * may return off node objects because partial slabs are obtained
2103 * from other nodes and filled up.
2105 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2106 * (which makes defrag_ratio = 1000) then every (well almost)
2107 * allocation will first attempt to defrag slab caches on other nodes.
2108 * This means scanning over all nodes to look for partial slabs which
2109 * may be expensive if we do it every time we are trying to find a slab
2110 * with available objects.
2112 if (!s->remote_node_defrag_ratio ||
2113 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2117 cpuset_mems_cookie = read_mems_allowed_begin();
2118 zonelist = node_zonelist(mempolicy_slab_node(), flags);
2119 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2120 struct kmem_cache_node *n;
2122 n = get_node(s, zone_to_nid(zone));
2124 if (n && cpuset_zone_allowed(zone, flags) &&
2125 n->nr_partial > s->min_partial) {
2126 object = get_partial_node(s, n, c, flags);
2129 * Don't check read_mems_allowed_retry()
2130 * here - if mems_allowed was updated in
2131 * parallel, that was a harmless race
2132 * between allocation and the cpuset
2139 } while (read_mems_allowed_retry(cpuset_mems_cookie));
2140 #endif /* CONFIG_NUMA */
2145 * Get a partial page, lock it and return it.
2147 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
2148 struct kmem_cache_cpu *c)
2151 int searchnode = node;
2153 if (node == NUMA_NO_NODE)
2154 searchnode = numa_mem_id();
2156 object = get_partial_node(s, get_node(s, searchnode), c, flags);
2157 if (object || node != NUMA_NO_NODE)
2160 return get_any_partial(s, flags, c);
2163 #ifdef CONFIG_PREEMPTION
2165 * Calculate the next globally unique transaction for disambiguation
2166 * during cmpxchg. The transactions start with the cpu number and are then
2167 * incremented by CONFIG_NR_CPUS.
2169 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2172 * No preemption supported therefore also no need to check for
2178 static inline unsigned long next_tid(unsigned long tid)
2180 return tid + TID_STEP;
2183 #ifdef SLUB_DEBUG_CMPXCHG
2184 static inline unsigned int tid_to_cpu(unsigned long tid)
2186 return tid % TID_STEP;
2189 static inline unsigned long tid_to_event(unsigned long tid)
2191 return tid / TID_STEP;
2195 static inline unsigned int init_tid(int cpu)
2200 static inline void note_cmpxchg_failure(const char *n,
2201 const struct kmem_cache *s, unsigned long tid)
2203 #ifdef SLUB_DEBUG_CMPXCHG
2204 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2206 pr_info("%s %s: cmpxchg redo ", n, s->name);
2208 #ifdef CONFIG_PREEMPTION
2209 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2210 pr_warn("due to cpu change %d -> %d\n",
2211 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2214 if (tid_to_event(tid) != tid_to_event(actual_tid))
2215 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2216 tid_to_event(tid), tid_to_event(actual_tid));
2218 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2219 actual_tid, tid, next_tid(tid));
2221 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2224 static void init_kmem_cache_cpus(struct kmem_cache *s)
2228 for_each_possible_cpu(cpu)
2229 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2233 * Remove the cpu slab
2235 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2236 void *freelist, struct kmem_cache_cpu *c)
2238 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2239 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2240 int lock = 0, free_delta = 0;
2241 enum slab_modes l = M_NONE, m = M_NONE;
2242 void *nextfree, *freelist_iter, *freelist_tail;
2243 int tail = DEACTIVATE_TO_HEAD;
2247 if (page->freelist) {
2248 stat(s, DEACTIVATE_REMOTE_FREES);
2249 tail = DEACTIVATE_TO_TAIL;
2253 * Stage one: Count the objects on cpu's freelist as free_delta and
2254 * remember the last object in freelist_tail for later splicing.
2256 freelist_tail = NULL;
2257 freelist_iter = freelist;
2258 while (freelist_iter) {
2259 nextfree = get_freepointer(s, freelist_iter);
2262 * If 'nextfree' is invalid, it is possible that the object at
2263 * 'freelist_iter' is already corrupted. So isolate all objects
2264 * starting at 'freelist_iter' by skipping them.
2266 if (freelist_corrupted(s, page, &freelist_iter, nextfree))
2269 freelist_tail = freelist_iter;
2272 freelist_iter = nextfree;
2276 * Stage two: Unfreeze the page while splicing the per-cpu
2277 * freelist to the head of page's freelist.
2279 * Ensure that the page is unfrozen while the list presence
2280 * reflects the actual number of objects during unfreeze.
2282 * We setup the list membership and then perform a cmpxchg
2283 * with the count. If there is a mismatch then the page
2284 * is not unfrozen but the page is on the wrong list.
2286 * Then we restart the process which may have to remove
2287 * the page from the list that we just put it on again
2288 * because the number of objects in the slab may have
2293 old.freelist = READ_ONCE(page->freelist);
2294 old.counters = READ_ONCE(page->counters);
2295 VM_BUG_ON(!old.frozen);
2297 /* Determine target state of the slab */
2298 new.counters = old.counters;
2299 if (freelist_tail) {
2300 new.inuse -= free_delta;
2301 set_freepointer(s, freelist_tail, old.freelist);
2302 new.freelist = freelist;
2304 new.freelist = old.freelist;
2308 if (!new.inuse && n->nr_partial >= s->min_partial)
2310 else if (new.freelist) {
2315 * Taking the spinlock removes the possibility
2316 * that acquire_slab() will see a slab page that
2319 spin_lock(&n->list_lock);
2323 if (kmem_cache_debug_flags(s, SLAB_STORE_USER) && !lock) {
2326 * This also ensures that the scanning of full
2327 * slabs from diagnostic functions will not see
2330 spin_lock(&n->list_lock);
2336 remove_partial(n, page);
2337 else if (l == M_FULL)
2338 remove_full(s, n, page);
2341 add_partial(n, page, tail);
2342 else if (m == M_FULL)
2343 add_full(s, n, page);
2347 if (!__cmpxchg_double_slab(s, page,
2348 old.freelist, old.counters,
2349 new.freelist, new.counters,
2354 spin_unlock(&n->list_lock);
2358 else if (m == M_FULL)
2359 stat(s, DEACTIVATE_FULL);
2360 else if (m == M_FREE) {
2361 stat(s, DEACTIVATE_EMPTY);
2362 discard_slab(s, page);
2371 * Unfreeze all the cpu partial slabs.
2373 * This function must be called with interrupts disabled
2374 * for the cpu using c (or some other guarantee must be there
2375 * to guarantee no concurrent accesses).
2377 static void unfreeze_partials(struct kmem_cache *s,
2378 struct kmem_cache_cpu *c)
2380 #ifdef CONFIG_SLUB_CPU_PARTIAL
2381 struct kmem_cache_node *n = NULL, *n2 = NULL;
2382 struct page *page, *discard_page = NULL;
2384 while ((page = slub_percpu_partial(c))) {
2388 slub_set_percpu_partial(c, page);
2390 n2 = get_node(s, page_to_nid(page));
2393 spin_unlock(&n->list_lock);
2396 spin_lock(&n->list_lock);
2401 old.freelist = page->freelist;
2402 old.counters = page->counters;
2403 VM_BUG_ON(!old.frozen);
2405 new.counters = old.counters;
2406 new.freelist = old.freelist;
2410 } while (!__cmpxchg_double_slab(s, page,
2411 old.freelist, old.counters,
2412 new.freelist, new.counters,
2413 "unfreezing slab"));
2415 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2416 page->next = discard_page;
2417 discard_page = page;
2419 add_partial(n, page, DEACTIVATE_TO_TAIL);
2420 stat(s, FREE_ADD_PARTIAL);
2425 spin_unlock(&n->list_lock);
2427 while (discard_page) {
2428 page = discard_page;
2429 discard_page = discard_page->next;
2431 stat(s, DEACTIVATE_EMPTY);
2432 discard_slab(s, page);
2435 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2439 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2440 * partial page slot if available.
2442 * If we did not find a slot then simply move all the partials to the
2443 * per node partial list.
2445 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2447 #ifdef CONFIG_SLUB_CPU_PARTIAL
2448 struct page *oldpage;
2456 oldpage = this_cpu_read(s->cpu_slab->partial);
2459 pobjects = oldpage->pobjects;
2460 pages = oldpage->pages;
2461 if (drain && pobjects > slub_cpu_partial(s)) {
2462 unsigned long flags;
2464 * partial array is full. Move the existing
2465 * set to the per node partial list.
2467 local_irq_save(flags);
2468 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2469 local_irq_restore(flags);
2473 stat(s, CPU_PARTIAL_DRAIN);
2478 pobjects += page->objects - page->inuse;
2480 page->pages = pages;
2481 page->pobjects = pobjects;
2482 page->next = oldpage;
2484 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2486 if (unlikely(!slub_cpu_partial(s))) {
2487 unsigned long flags;
2489 local_irq_save(flags);
2490 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2491 local_irq_restore(flags);
2494 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2497 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2499 stat(s, CPUSLAB_FLUSH);
2500 deactivate_slab(s, c->page, c->freelist, c);
2502 c->tid = next_tid(c->tid);
2508 * Called from IPI handler with interrupts disabled.
2510 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2512 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2517 unfreeze_partials(s, c);
2520 static void flush_cpu_slab(void *d)
2522 struct kmem_cache *s = d;
2524 __flush_cpu_slab(s, smp_processor_id());
2527 static bool has_cpu_slab(int cpu, void *info)
2529 struct kmem_cache *s = info;
2530 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2532 return c->page || slub_percpu_partial(c);
2535 static void flush_all(struct kmem_cache *s)
2537 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1);
2541 * Use the cpu notifier to insure that the cpu slabs are flushed when
2544 static int slub_cpu_dead(unsigned int cpu)
2546 struct kmem_cache *s;
2547 unsigned long flags;
2549 mutex_lock(&slab_mutex);
2550 list_for_each_entry(s, &slab_caches, list) {
2551 local_irq_save(flags);
2552 __flush_cpu_slab(s, cpu);
2553 local_irq_restore(flags);
2555 mutex_unlock(&slab_mutex);
2560 * Check if the objects in a per cpu structure fit numa
2561 * locality expectations.
2563 static inline int node_match(struct page *page, int node)
2566 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2572 #ifdef CONFIG_SLUB_DEBUG
2573 static int count_free(struct page *page)
2575 return page->objects - page->inuse;
2578 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2580 return atomic_long_read(&n->total_objects);
2582 #endif /* CONFIG_SLUB_DEBUG */
2584 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2585 static unsigned long count_partial(struct kmem_cache_node *n,
2586 int (*get_count)(struct page *))
2588 unsigned long flags;
2589 unsigned long x = 0;
2592 spin_lock_irqsave(&n->list_lock, flags);
2593 list_for_each_entry(page, &n->partial, slab_list)
2594 x += get_count(page);
2595 spin_unlock_irqrestore(&n->list_lock, flags);
2598 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2600 static noinline void
2601 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2603 #ifdef CONFIG_SLUB_DEBUG
2604 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2605 DEFAULT_RATELIMIT_BURST);
2607 struct kmem_cache_node *n;
2609 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2612 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2613 nid, gfpflags, &gfpflags);
2614 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2615 s->name, s->object_size, s->size, oo_order(s->oo),
2618 if (oo_order(s->min) > get_order(s->object_size))
2619 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2622 for_each_kmem_cache_node(s, node, n) {
2623 unsigned long nr_slabs;
2624 unsigned long nr_objs;
2625 unsigned long nr_free;
2627 nr_free = count_partial(n, count_free);
2628 nr_slabs = node_nr_slabs(n);
2629 nr_objs = node_nr_objs(n);
2631 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2632 node, nr_slabs, nr_objs, nr_free);
2637 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2638 int node, struct kmem_cache_cpu **pc)
2641 struct kmem_cache_cpu *c = *pc;
2644 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2646 freelist = get_partial(s, flags, node, c);
2651 page = new_slab(s, flags, node);
2653 c = raw_cpu_ptr(s->cpu_slab);
2658 * No other reference to the page yet so we can
2659 * muck around with it freely without cmpxchg
2661 freelist = page->freelist;
2662 page->freelist = NULL;
2664 stat(s, ALLOC_SLAB);
2672 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2674 if (unlikely(PageSlabPfmemalloc(page)))
2675 return gfp_pfmemalloc_allowed(gfpflags);
2681 * Check the page->freelist of a page and either transfer the freelist to the
2682 * per cpu freelist or deactivate the page.
2684 * The page is still frozen if the return value is not NULL.
2686 * If this function returns NULL then the page has been unfrozen.
2688 * This function must be called with interrupt disabled.
2690 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2693 unsigned long counters;
2697 freelist = page->freelist;
2698 counters = page->counters;
2700 new.counters = counters;
2701 VM_BUG_ON(!new.frozen);
2703 new.inuse = page->objects;
2704 new.frozen = freelist != NULL;
2706 } while (!__cmpxchg_double_slab(s, page,
2715 * Slow path. The lockless freelist is empty or we need to perform
2718 * Processing is still very fast if new objects have been freed to the
2719 * regular freelist. In that case we simply take over the regular freelist
2720 * as the lockless freelist and zap the regular freelist.
2722 * If that is not working then we fall back to the partial lists. We take the
2723 * first element of the freelist as the object to allocate now and move the
2724 * rest of the freelist to the lockless freelist.
2726 * And if we were unable to get a new slab from the partial slab lists then
2727 * we need to allocate a new slab. This is the slowest path since it involves
2728 * a call to the page allocator and the setup of a new slab.
2730 * Version of __slab_alloc to use when we know that interrupts are
2731 * already disabled (which is the case for bulk allocation).
2733 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2734 unsigned long addr, struct kmem_cache_cpu *c)
2739 stat(s, ALLOC_SLOWPATH);
2744 * if the node is not online or has no normal memory, just
2745 * ignore the node constraint
2747 if (unlikely(node != NUMA_NO_NODE &&
2748 !node_isset(node, slab_nodes)))
2749 node = NUMA_NO_NODE;
2754 if (unlikely(!node_match(page, node))) {
2756 * same as above but node_match() being false already
2757 * implies node != NUMA_NO_NODE
2759 if (!node_isset(node, slab_nodes)) {
2760 node = NUMA_NO_NODE;
2763 stat(s, ALLOC_NODE_MISMATCH);
2764 deactivate_slab(s, page, c->freelist, c);
2770 * By rights, we should be searching for a slab page that was
2771 * PFMEMALLOC but right now, we are losing the pfmemalloc
2772 * information when the page leaves the per-cpu allocator
2774 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2775 deactivate_slab(s, page, c->freelist, c);
2779 /* must check again c->freelist in case of cpu migration or IRQ */
2780 freelist = c->freelist;
2784 freelist = get_freelist(s, page);
2788 stat(s, DEACTIVATE_BYPASS);
2792 stat(s, ALLOC_REFILL);
2796 * freelist is pointing to the list of objects to be used.
2797 * page is pointing to the page from which the objects are obtained.
2798 * That page must be frozen for per cpu allocations to work.
2800 VM_BUG_ON(!c->page->frozen);
2801 c->freelist = get_freepointer(s, freelist);
2802 c->tid = next_tid(c->tid);
2807 if (slub_percpu_partial(c)) {
2808 page = c->page = slub_percpu_partial(c);
2809 slub_set_percpu_partial(c, page);
2810 stat(s, CPU_PARTIAL_ALLOC);
2814 freelist = new_slab_objects(s, gfpflags, node, &c);
2816 if (unlikely(!freelist)) {
2817 slab_out_of_memory(s, gfpflags, node);
2822 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2825 /* Only entered in the debug case */
2826 if (kmem_cache_debug(s) &&
2827 !alloc_debug_processing(s, page, freelist, addr))
2828 goto new_slab; /* Slab failed checks. Next slab needed */
2830 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2835 * Another one that disabled interrupt and compensates for possible
2836 * cpu changes by refetching the per cpu area pointer.
2838 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2839 unsigned long addr, struct kmem_cache_cpu *c)
2842 unsigned long flags;
2844 local_irq_save(flags);
2845 #ifdef CONFIG_PREEMPTION
2847 * We may have been preempted and rescheduled on a different
2848 * cpu before disabling interrupts. Need to reload cpu area
2851 c = this_cpu_ptr(s->cpu_slab);
2854 p = ___slab_alloc(s, gfpflags, node, addr, c);
2855 local_irq_restore(flags);
2860 * If the object has been wiped upon free, make sure it's fully initialized by
2861 * zeroing out freelist pointer.
2863 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2866 if (unlikely(slab_want_init_on_free(s)) && obj)
2867 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
2872 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2873 * have the fastpath folded into their functions. So no function call
2874 * overhead for requests that can be satisfied on the fastpath.
2876 * The fastpath works by first checking if the lockless freelist can be used.
2877 * If not then __slab_alloc is called for slow processing.
2879 * Otherwise we can simply pick the next object from the lockless free list.
2881 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2882 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
2885 struct kmem_cache_cpu *c;
2888 struct obj_cgroup *objcg = NULL;
2891 s = slab_pre_alloc_hook(s, &objcg, 1, gfpflags);
2895 object = kfence_alloc(s, orig_size, gfpflags);
2896 if (unlikely(object))
2901 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2902 * enabled. We may switch back and forth between cpus while
2903 * reading from one cpu area. That does not matter as long
2904 * as we end up on the original cpu again when doing the cmpxchg.
2906 * We should guarantee that tid and kmem_cache are retrieved on
2907 * the same cpu. It could be different if CONFIG_PREEMPTION so we need
2908 * to check if it is matched or not.
2911 tid = this_cpu_read(s->cpu_slab->tid);
2912 c = raw_cpu_ptr(s->cpu_slab);
2913 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
2914 unlikely(tid != READ_ONCE(c->tid)));
2917 * Irqless object alloc/free algorithm used here depends on sequence
2918 * of fetching cpu_slab's data. tid should be fetched before anything
2919 * on c to guarantee that object and page associated with previous tid
2920 * won't be used with current tid. If we fetch tid first, object and
2921 * page could be one associated with next tid and our alloc/free
2922 * request will be failed. In this case, we will retry. So, no problem.
2927 * The transaction ids are globally unique per cpu and per operation on
2928 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2929 * occurs on the right processor and that there was no operation on the
2930 * linked list in between.
2933 object = c->freelist;
2935 if (unlikely(!object || !page || !node_match(page, node))) {
2936 object = __slab_alloc(s, gfpflags, node, addr, c);
2938 void *next_object = get_freepointer_safe(s, object);
2941 * The cmpxchg will only match if there was no additional
2942 * operation and if we are on the right processor.
2944 * The cmpxchg does the following atomically (without lock
2946 * 1. Relocate first pointer to the current per cpu area.
2947 * 2. Verify that tid and freelist have not been changed
2948 * 3. If they were not changed replace tid and freelist
2950 * Since this is without lock semantics the protection is only
2951 * against code executing on this cpu *not* from access by
2954 if (unlikely(!this_cpu_cmpxchg_double(
2955 s->cpu_slab->freelist, s->cpu_slab->tid,
2957 next_object, next_tid(tid)))) {
2959 note_cmpxchg_failure("slab_alloc", s, tid);
2962 prefetch_freepointer(s, next_object);
2963 stat(s, ALLOC_FASTPATH);
2966 maybe_wipe_obj_freeptr(s, object);
2967 init = slab_want_init_on_alloc(gfpflags, s);
2970 slab_post_alloc_hook(s, objcg, gfpflags, 1, &object, init);
2975 static __always_inline void *slab_alloc(struct kmem_cache *s,
2976 gfp_t gfpflags, unsigned long addr, size_t orig_size)
2978 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr, orig_size);
2981 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2983 void *ret = slab_alloc(s, gfpflags, _RET_IP_, s->object_size);
2985 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2990 EXPORT_SYMBOL(kmem_cache_alloc);
2992 #ifdef CONFIG_TRACING
2993 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2995 void *ret = slab_alloc(s, gfpflags, _RET_IP_, size);
2996 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2997 ret = kasan_kmalloc(s, ret, size, gfpflags);
3000 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3004 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
3006 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, s->object_size);
3008 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3009 s->object_size, s->size, gfpflags, node);
3013 EXPORT_SYMBOL(kmem_cache_alloc_node);
3015 #ifdef CONFIG_TRACING
3016 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
3018 int node, size_t size)
3020 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_, size);
3022 trace_kmalloc_node(_RET_IP_, ret,
3023 size, s->size, gfpflags, node);
3025 ret = kasan_kmalloc(s, ret, size, gfpflags);
3028 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3030 #endif /* CONFIG_NUMA */
3033 * Slow path handling. This may still be called frequently since objects
3034 * have a longer lifetime than the cpu slabs in most processing loads.
3036 * So we still attempt to reduce cache line usage. Just take the slab
3037 * lock and free the item. If there is no additional partial page
3038 * handling required then we can return immediately.
3040 static void __slab_free(struct kmem_cache *s, struct page *page,
3041 void *head, void *tail, int cnt,
3048 unsigned long counters;
3049 struct kmem_cache_node *n = NULL;
3050 unsigned long flags;
3052 stat(s, FREE_SLOWPATH);
3054 if (kfence_free(head))
3057 if (kmem_cache_debug(s) &&
3058 !free_debug_processing(s, page, head, tail, cnt, addr))
3063 spin_unlock_irqrestore(&n->list_lock, flags);
3066 prior = page->freelist;
3067 counters = page->counters;
3068 set_freepointer(s, tail, prior);
3069 new.counters = counters;
3070 was_frozen = new.frozen;
3072 if ((!new.inuse || !prior) && !was_frozen) {
3074 if (kmem_cache_has_cpu_partial(s) && !prior) {
3077 * Slab was on no list before and will be
3079 * We can defer the list move and instead
3084 } else { /* Needs to be taken off a list */
3086 n = get_node(s, page_to_nid(page));
3088 * Speculatively acquire the list_lock.
3089 * If the cmpxchg does not succeed then we may
3090 * drop the list_lock without any processing.
3092 * Otherwise the list_lock will synchronize with
3093 * other processors updating the list of slabs.
3095 spin_lock_irqsave(&n->list_lock, flags);
3100 } while (!cmpxchg_double_slab(s, page,
3107 if (likely(was_frozen)) {
3109 * The list lock was not taken therefore no list
3110 * activity can be necessary.
3112 stat(s, FREE_FROZEN);
3113 } else if (new.frozen) {
3115 * If we just froze the page then put it onto the
3116 * per cpu partial list.
3118 put_cpu_partial(s, page, 1);
3119 stat(s, CPU_PARTIAL_FREE);
3125 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
3129 * Objects left in the slab. If it was not on the partial list before
3132 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
3133 remove_full(s, n, page);
3134 add_partial(n, page, DEACTIVATE_TO_TAIL);
3135 stat(s, FREE_ADD_PARTIAL);
3137 spin_unlock_irqrestore(&n->list_lock, flags);
3143 * Slab on the partial list.
3145 remove_partial(n, page);
3146 stat(s, FREE_REMOVE_PARTIAL);
3148 /* Slab must be on the full list */
3149 remove_full(s, n, page);
3152 spin_unlock_irqrestore(&n->list_lock, flags);
3154 discard_slab(s, page);
3158 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3159 * can perform fastpath freeing without additional function calls.
3161 * The fastpath is only possible if we are freeing to the current cpu slab
3162 * of this processor. This typically the case if we have just allocated
3165 * If fastpath is not possible then fall back to __slab_free where we deal
3166 * with all sorts of special processing.
3168 * Bulk free of a freelist with several objects (all pointing to the
3169 * same page) possible by specifying head and tail ptr, plus objects
3170 * count (cnt). Bulk free indicated by tail pointer being set.
3172 static __always_inline void do_slab_free(struct kmem_cache *s,
3173 struct page *page, void *head, void *tail,
3174 int cnt, unsigned long addr)
3176 void *tail_obj = tail ? : head;
3177 struct kmem_cache_cpu *c;
3180 memcg_slab_free_hook(s, &head, 1);
3183 * Determine the currently cpus per cpu slab.
3184 * The cpu may change afterward. However that does not matter since
3185 * data is retrieved via this pointer. If we are on the same cpu
3186 * during the cmpxchg then the free will succeed.
3189 tid = this_cpu_read(s->cpu_slab->tid);
3190 c = raw_cpu_ptr(s->cpu_slab);
3191 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
3192 unlikely(tid != READ_ONCE(c->tid)));
3194 /* Same with comment on barrier() in slab_alloc_node() */
3197 if (likely(page == c->page)) {
3198 void **freelist = READ_ONCE(c->freelist);
3200 set_freepointer(s, tail_obj, freelist);
3202 if (unlikely(!this_cpu_cmpxchg_double(
3203 s->cpu_slab->freelist, s->cpu_slab->tid,
3205 head, next_tid(tid)))) {
3207 note_cmpxchg_failure("slab_free", s, tid);
3210 stat(s, FREE_FASTPATH);
3212 __slab_free(s, page, head, tail_obj, cnt, addr);
3216 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3217 void *head, void *tail, int cnt,
3221 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3222 * to remove objects, whose reuse must be delayed.
3224 if (slab_free_freelist_hook(s, &head, &tail))
3225 do_slab_free(s, page, head, tail, cnt, addr);
3228 #ifdef CONFIG_KASAN_GENERIC
3229 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3231 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3235 void kmem_cache_free(struct kmem_cache *s, void *x)
3237 s = cache_from_obj(s, x);
3240 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3241 trace_kmem_cache_free(_RET_IP_, x, s->name);
3243 EXPORT_SYMBOL(kmem_cache_free);
3245 struct detached_freelist {
3250 struct kmem_cache *s;
3254 * This function progressively scans the array with free objects (with
3255 * a limited look ahead) and extract objects belonging to the same
3256 * page. It builds a detached freelist directly within the given
3257 * page/objects. This can happen without any need for
3258 * synchronization, because the objects are owned by running process.
3259 * The freelist is build up as a single linked list in the objects.
3260 * The idea is, that this detached freelist can then be bulk
3261 * transferred to the real freelist(s), but only requiring a single
3262 * synchronization primitive. Look ahead in the array is limited due
3263 * to performance reasons.
3266 int build_detached_freelist(struct kmem_cache *s, size_t size,
3267 void **p, struct detached_freelist *df)
3269 size_t first_skipped_index = 0;
3274 /* Always re-init detached_freelist */
3279 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3280 } while (!object && size);
3285 page = virt_to_head_page(object);
3287 /* Handle kalloc'ed objects */
3288 if (unlikely(!PageSlab(page))) {
3289 BUG_ON(!PageCompound(page));
3291 __free_pages(page, compound_order(page));
3292 p[size] = NULL; /* mark object processed */
3295 /* Derive kmem_cache from object */
3296 df->s = page->slab_cache;
3298 df->s = cache_from_obj(s, object); /* Support for memcg */
3301 if (is_kfence_address(object)) {
3302 slab_free_hook(df->s, object, false);
3303 __kfence_free(object);
3304 p[size] = NULL; /* mark object processed */
3308 /* Start new detached freelist */
3310 set_freepointer(df->s, object, NULL);
3312 df->freelist = object;
3313 p[size] = NULL; /* mark object processed */
3319 continue; /* Skip processed objects */
3321 /* df->page is always set at this point */
3322 if (df->page == virt_to_head_page(object)) {
3323 /* Opportunity build freelist */
3324 set_freepointer(df->s, object, df->freelist);
3325 df->freelist = object;
3327 p[size] = NULL; /* mark object processed */
3332 /* Limit look ahead search */
3336 if (!first_skipped_index)
3337 first_skipped_index = size + 1;
3340 return first_skipped_index;
3343 /* Note that interrupts must be enabled when calling this function. */
3344 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3349 memcg_slab_free_hook(s, p, size);
3351 struct detached_freelist df;
3353 size = build_detached_freelist(s, size, p, &df);
3357 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt, _RET_IP_);
3358 } while (likely(size));
3360 EXPORT_SYMBOL(kmem_cache_free_bulk);
3362 /* Note that interrupts must be enabled when calling this function. */
3363 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3366 struct kmem_cache_cpu *c;
3368 struct obj_cgroup *objcg = NULL;
3370 /* memcg and kmem_cache debug support */
3371 s = slab_pre_alloc_hook(s, &objcg, size, flags);
3375 * Drain objects in the per cpu slab, while disabling local
3376 * IRQs, which protects against PREEMPT and interrupts
3377 * handlers invoking normal fastpath.
3379 local_irq_disable();
3380 c = this_cpu_ptr(s->cpu_slab);
3382 for (i = 0; i < size; i++) {
3383 void *object = kfence_alloc(s, s->object_size, flags);
3385 if (unlikely(object)) {
3390 object = c->freelist;
3391 if (unlikely(!object)) {
3393 * We may have removed an object from c->freelist using
3394 * the fastpath in the previous iteration; in that case,
3395 * c->tid has not been bumped yet.
3396 * Since ___slab_alloc() may reenable interrupts while
3397 * allocating memory, we should bump c->tid now.
3399 c->tid = next_tid(c->tid);
3402 * Invoking slow path likely have side-effect
3403 * of re-populating per CPU c->freelist
3405 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3407 if (unlikely(!p[i]))
3410 c = this_cpu_ptr(s->cpu_slab);
3411 maybe_wipe_obj_freeptr(s, p[i]);
3413 continue; /* goto for-loop */
3415 c->freelist = get_freepointer(s, object);
3417 maybe_wipe_obj_freeptr(s, p[i]);
3419 c->tid = next_tid(c->tid);
3423 * memcg and kmem_cache debug support and memory initialization.
3424 * Done outside of the IRQ disabled fastpath loop.
3426 slab_post_alloc_hook(s, objcg, flags, size, p,
3427 slab_want_init_on_alloc(flags, s));
3431 slab_post_alloc_hook(s, objcg, flags, i, p, false);
3432 __kmem_cache_free_bulk(s, i, p);
3435 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3439 * Object placement in a slab is made very easy because we always start at
3440 * offset 0. If we tune the size of the object to the alignment then we can
3441 * get the required alignment by putting one properly sized object after
3444 * Notice that the allocation order determines the sizes of the per cpu
3445 * caches. Each processor has always one slab available for allocations.
3446 * Increasing the allocation order reduces the number of times that slabs
3447 * must be moved on and off the partial lists and is therefore a factor in
3452 * Minimum / Maximum order of slab pages. This influences locking overhead
3453 * and slab fragmentation. A higher order reduces the number of partial slabs
3454 * and increases the number of allocations possible without having to
3455 * take the list_lock.
3457 static unsigned int slub_min_order;
3458 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3459 static unsigned int slub_min_objects;
3462 * Calculate the order of allocation given an slab object size.
3464 * The order of allocation has significant impact on performance and other
3465 * system components. Generally order 0 allocations should be preferred since
3466 * order 0 does not cause fragmentation in the page allocator. Larger objects
3467 * be problematic to put into order 0 slabs because there may be too much
3468 * unused space left. We go to a higher order if more than 1/16th of the slab
3471 * In order to reach satisfactory performance we must ensure that a minimum
3472 * number of objects is in one slab. Otherwise we may generate too much
3473 * activity on the partial lists which requires taking the list_lock. This is
3474 * less a concern for large slabs though which are rarely used.
3476 * slub_max_order specifies the order where we begin to stop considering the
3477 * number of objects in a slab as critical. If we reach slub_max_order then
3478 * we try to keep the page order as low as possible. So we accept more waste
3479 * of space in favor of a small page order.
3481 * Higher order allocations also allow the placement of more objects in a
3482 * slab and thereby reduce object handling overhead. If the user has
3483 * requested a higher minimum order then we start with that one instead of
3484 * the smallest order which will fit the object.
3486 static inline unsigned int slab_order(unsigned int size,
3487 unsigned int min_objects, unsigned int max_order,
3488 unsigned int fract_leftover)
3490 unsigned int min_order = slub_min_order;
3493 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3494 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3496 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3497 order <= max_order; order++) {
3499 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3502 rem = slab_size % size;
3504 if (rem <= slab_size / fract_leftover)
3511 static inline int calculate_order(unsigned int size)
3514 unsigned int min_objects;
3515 unsigned int max_objects;
3516 unsigned int nr_cpus;
3519 * Attempt to find best configuration for a slab. This
3520 * works by first attempting to generate a layout with
3521 * the best configuration and backing off gradually.
3523 * First we increase the acceptable waste in a slab. Then
3524 * we reduce the minimum objects required in a slab.
3526 min_objects = slub_min_objects;
3529 * Some architectures will only update present cpus when
3530 * onlining them, so don't trust the number if it's just 1. But
3531 * we also don't want to use nr_cpu_ids always, as on some other
3532 * architectures, there can be many possible cpus, but never
3533 * onlined. Here we compromise between trying to avoid too high
3534 * order on systems that appear larger than they are, and too
3535 * low order on systems that appear smaller than they are.
3537 nr_cpus = num_present_cpus();
3539 nr_cpus = nr_cpu_ids;
3540 min_objects = 4 * (fls(nr_cpus) + 1);
3542 max_objects = order_objects(slub_max_order, size);
3543 min_objects = min(min_objects, max_objects);
3545 while (min_objects > 1) {
3546 unsigned int fraction;
3549 while (fraction >= 4) {
3550 order = slab_order(size, min_objects,
3551 slub_max_order, fraction);
3552 if (order <= slub_max_order)
3560 * We were unable to place multiple objects in a slab. Now
3561 * lets see if we can place a single object there.
3563 order = slab_order(size, 1, slub_max_order, 1);
3564 if (order <= slub_max_order)
3568 * Doh this slab cannot be placed using slub_max_order.
3570 order = slab_order(size, 1, MAX_ORDER, 1);
3571 if (order < MAX_ORDER)
3577 init_kmem_cache_node(struct kmem_cache_node *n)
3580 spin_lock_init(&n->list_lock);
3581 INIT_LIST_HEAD(&n->partial);
3582 #ifdef CONFIG_SLUB_DEBUG
3583 atomic_long_set(&n->nr_slabs, 0);
3584 atomic_long_set(&n->total_objects, 0);
3585 INIT_LIST_HEAD(&n->full);
3589 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3591 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3592 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3595 * Must align to double word boundary for the double cmpxchg
3596 * instructions to work; see __pcpu_double_call_return_bool().
3598 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3599 2 * sizeof(void *));
3604 init_kmem_cache_cpus(s);
3609 static struct kmem_cache *kmem_cache_node;
3612 * No kmalloc_node yet so do it by hand. We know that this is the first
3613 * slab on the node for this slabcache. There are no concurrent accesses
3616 * Note that this function only works on the kmem_cache_node
3617 * when allocating for the kmem_cache_node. This is used for bootstrapping
3618 * memory on a fresh node that has no slab structures yet.
3620 static void early_kmem_cache_node_alloc(int node)
3623 struct kmem_cache_node *n;
3625 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3627 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3630 if (page_to_nid(page) != node) {
3631 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3632 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3637 #ifdef CONFIG_SLUB_DEBUG
3638 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3639 init_tracking(kmem_cache_node, n);
3641 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
3642 page->freelist = get_freepointer(kmem_cache_node, n);
3645 kmem_cache_node->node[node] = n;
3646 init_kmem_cache_node(n);
3647 inc_slabs_node(kmem_cache_node, node, page->objects);
3650 * No locks need to be taken here as it has just been
3651 * initialized and there is no concurrent access.
3653 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3656 static void free_kmem_cache_nodes(struct kmem_cache *s)
3659 struct kmem_cache_node *n;
3661 for_each_kmem_cache_node(s, node, n) {
3662 s->node[node] = NULL;
3663 kmem_cache_free(kmem_cache_node, n);
3667 void __kmem_cache_release(struct kmem_cache *s)
3669 cache_random_seq_destroy(s);
3670 free_percpu(s->cpu_slab);
3671 free_kmem_cache_nodes(s);
3674 static int init_kmem_cache_nodes(struct kmem_cache *s)
3678 for_each_node_mask(node, slab_nodes) {
3679 struct kmem_cache_node *n;
3681 if (slab_state == DOWN) {
3682 early_kmem_cache_node_alloc(node);
3685 n = kmem_cache_alloc_node(kmem_cache_node,
3689 free_kmem_cache_nodes(s);
3693 init_kmem_cache_node(n);
3699 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3701 if (min < MIN_PARTIAL)
3703 else if (min > MAX_PARTIAL)
3705 s->min_partial = min;
3708 static void set_cpu_partial(struct kmem_cache *s)
3710 #ifdef CONFIG_SLUB_CPU_PARTIAL
3712 * cpu_partial determined the maximum number of objects kept in the
3713 * per cpu partial lists of a processor.
3715 * Per cpu partial lists mainly contain slabs that just have one
3716 * object freed. If they are used for allocation then they can be
3717 * filled up again with minimal effort. The slab will never hit the
3718 * per node partial lists and therefore no locking will be required.
3720 * This setting also determines
3722 * A) The number of objects from per cpu partial slabs dumped to the
3723 * per node list when we reach the limit.
3724 * B) The number of objects in cpu partial slabs to extract from the
3725 * per node list when we run out of per cpu objects. We only fetch
3726 * 50% to keep some capacity around for frees.
3728 if (!kmem_cache_has_cpu_partial(s))
3729 slub_set_cpu_partial(s, 0);
3730 else if (s->size >= PAGE_SIZE)
3731 slub_set_cpu_partial(s, 2);
3732 else if (s->size >= 1024)
3733 slub_set_cpu_partial(s, 6);
3734 else if (s->size >= 256)
3735 slub_set_cpu_partial(s, 13);
3737 slub_set_cpu_partial(s, 30);
3742 * calculate_sizes() determines the order and the distribution of data within
3745 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3747 slab_flags_t flags = s->flags;
3748 unsigned int size = s->object_size;
3752 * Round up object size to the next word boundary. We can only
3753 * place the free pointer at word boundaries and this determines
3754 * the possible location of the free pointer.
3756 size = ALIGN(size, sizeof(void *));
3758 #ifdef CONFIG_SLUB_DEBUG
3760 * Determine if we can poison the object itself. If the user of
3761 * the slab may touch the object after free or before allocation
3762 * then we should never poison the object itself.
3764 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3766 s->flags |= __OBJECT_POISON;
3768 s->flags &= ~__OBJECT_POISON;
3772 * If we are Redzoning then check if there is some space between the
3773 * end of the object and the free pointer. If not then add an
3774 * additional word to have some bytes to store Redzone information.
3776 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3777 size += sizeof(void *);
3781 * With that we have determined the number of bytes in actual use
3782 * by the object and redzoning.
3786 if ((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3787 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
3790 * Relocate free pointer after the object if it is not
3791 * permitted to overwrite the first word of the object on
3794 * This is the case if we do RCU, have a constructor or
3795 * destructor, are poisoning the objects, or are
3796 * redzoning an object smaller than sizeof(void *).
3798 * The assumption that s->offset >= s->inuse means free
3799 * pointer is outside of the object is used in the
3800 * freeptr_outside_object() function. If that is no
3801 * longer true, the function needs to be modified.
3804 size += sizeof(void *);
3807 * Store freelist pointer near middle of object to keep
3808 * it away from the edges of the object to avoid small
3809 * sized over/underflows from neighboring allocations.
3811 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
3814 #ifdef CONFIG_SLUB_DEBUG
3815 if (flags & SLAB_STORE_USER)
3817 * Need to store information about allocs and frees after
3820 size += 2 * sizeof(struct track);
3823 kasan_cache_create(s, &size, &s->flags);
3824 #ifdef CONFIG_SLUB_DEBUG
3825 if (flags & SLAB_RED_ZONE) {
3827 * Add some empty padding so that we can catch
3828 * overwrites from earlier objects rather than let
3829 * tracking information or the free pointer be
3830 * corrupted if a user writes before the start
3833 size += sizeof(void *);
3835 s->red_left_pad = sizeof(void *);
3836 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3837 size += s->red_left_pad;
3842 * SLUB stores one object immediately after another beginning from
3843 * offset 0. In order to align the objects we have to simply size
3844 * each object to conform to the alignment.
3846 size = ALIGN(size, s->align);
3848 s->reciprocal_size = reciprocal_value(size);
3849 if (forced_order >= 0)
3850 order = forced_order;
3852 order = calculate_order(size);
3859 s->allocflags |= __GFP_COMP;
3861 if (s->flags & SLAB_CACHE_DMA)
3862 s->allocflags |= GFP_DMA;
3864 if (s->flags & SLAB_CACHE_DMA32)
3865 s->allocflags |= GFP_DMA32;
3867 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3868 s->allocflags |= __GFP_RECLAIMABLE;
3871 * Determine the number of objects per slab
3873 s->oo = oo_make(order, size);
3874 s->min = oo_make(get_order(size), size);
3875 if (oo_objects(s->oo) > oo_objects(s->max))
3878 return !!oo_objects(s->oo);
3881 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3883 s->flags = kmem_cache_flags(s->size, flags, s->name);
3884 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3885 s->random = get_random_long();
3888 if (!calculate_sizes(s, -1))
3890 if (disable_higher_order_debug) {
3892 * Disable debugging flags that store metadata if the min slab
3895 if (get_order(s->size) > get_order(s->object_size)) {
3896 s->flags &= ~DEBUG_METADATA_FLAGS;
3898 if (!calculate_sizes(s, -1))
3903 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3904 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3905 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3906 /* Enable fast mode */
3907 s->flags |= __CMPXCHG_DOUBLE;
3911 * The larger the object size is, the more pages we want on the partial
3912 * list to avoid pounding the page allocator excessively.
3914 set_min_partial(s, ilog2(s->size) / 2);
3919 s->remote_node_defrag_ratio = 1000;
3922 /* Initialize the pre-computed randomized freelist if slab is up */
3923 if (slab_state >= UP) {
3924 if (init_cache_random_seq(s))
3928 if (!init_kmem_cache_nodes(s))
3931 if (alloc_kmem_cache_cpus(s))
3934 free_kmem_cache_nodes(s);
3939 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3942 #ifdef CONFIG_SLUB_DEBUG
3943 void *addr = page_address(page);
3947 slab_err(s, page, text, s->name);
3950 map = get_map(s, page);
3951 for_each_object(p, s, addr, page->objects) {
3953 if (!test_bit(__obj_to_index(s, addr, p), map)) {
3954 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
3955 print_tracking(s, p);
3964 * Attempt to free all partial slabs on a node.
3965 * This is called from __kmem_cache_shutdown(). We must take list_lock
3966 * because sysfs file might still access partial list after the shutdowning.
3968 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3971 struct page *page, *h;
3973 BUG_ON(irqs_disabled());
3974 spin_lock_irq(&n->list_lock);
3975 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3977 remove_partial(n, page);
3978 list_add(&page->slab_list, &discard);
3980 list_slab_objects(s, page,
3981 "Objects remaining in %s on __kmem_cache_shutdown()");
3984 spin_unlock_irq(&n->list_lock);
3986 list_for_each_entry_safe(page, h, &discard, slab_list)
3987 discard_slab(s, page);
3990 bool __kmem_cache_empty(struct kmem_cache *s)
3993 struct kmem_cache_node *n;
3995 for_each_kmem_cache_node(s, node, n)
3996 if (n->nr_partial || slabs_node(s, node))
4002 * Release all resources used by a slab cache.
4004 int __kmem_cache_shutdown(struct kmem_cache *s)
4007 struct kmem_cache_node *n;
4010 /* Attempt to free all objects */
4011 for_each_kmem_cache_node(s, node, n) {
4013 if (n->nr_partial || slabs_node(s, node))
4019 #ifdef CONFIG_PRINTK
4020 void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct page *page)
4023 int __maybe_unused i;
4027 struct kmem_cache *s = page->slab_cache;
4028 struct track __maybe_unused *trackp;
4030 kpp->kp_ptr = object;
4031 kpp->kp_page = page;
4032 kpp->kp_slab_cache = s;
4033 base = page_address(page);
4034 objp0 = kasan_reset_tag(object);
4035 #ifdef CONFIG_SLUB_DEBUG
4036 objp = restore_red_left(s, objp0);
4040 objnr = obj_to_index(s, page, objp);
4041 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
4042 objp = base + s->size * objnr;
4043 kpp->kp_objp = objp;
4044 if (WARN_ON_ONCE(objp < base || objp >= base + page->objects * s->size || (objp - base) % s->size) ||
4045 !(s->flags & SLAB_STORE_USER))
4047 #ifdef CONFIG_SLUB_DEBUG
4048 objp = fixup_red_left(s, objp);
4049 trackp = get_track(s, objp, TRACK_ALLOC);
4050 kpp->kp_ret = (void *)trackp->addr;
4051 #ifdef CONFIG_STACKTRACE
4052 for (i = 0; i < KS_ADDRS_COUNT && i < TRACK_ADDRS_COUNT; i++) {
4053 kpp->kp_stack[i] = (void *)trackp->addrs[i];
4054 if (!kpp->kp_stack[i])
4058 trackp = get_track(s, objp, TRACK_FREE);
4059 for (i = 0; i < KS_ADDRS_COUNT && i < TRACK_ADDRS_COUNT; i++) {
4060 kpp->kp_free_stack[i] = (void *)trackp->addrs[i];
4061 if (!kpp->kp_free_stack[i])
4069 /********************************************************************
4071 *******************************************************************/
4073 static int __init setup_slub_min_order(char *str)
4075 get_option(&str, (int *)&slub_min_order);
4080 __setup("slub_min_order=", setup_slub_min_order);
4082 static int __init setup_slub_max_order(char *str)
4084 get_option(&str, (int *)&slub_max_order);
4085 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
4090 __setup("slub_max_order=", setup_slub_max_order);
4092 static int __init setup_slub_min_objects(char *str)
4094 get_option(&str, (int *)&slub_min_objects);
4099 __setup("slub_min_objects=", setup_slub_min_objects);
4101 void *__kmalloc(size_t size, gfp_t flags)
4103 struct kmem_cache *s;
4106 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4107 return kmalloc_large(size, flags);
4109 s = kmalloc_slab(size, flags);
4111 if (unlikely(ZERO_OR_NULL_PTR(s)))
4114 ret = slab_alloc(s, flags, _RET_IP_, size);
4116 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
4118 ret = kasan_kmalloc(s, ret, size, flags);
4122 EXPORT_SYMBOL(__kmalloc);
4125 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
4129 unsigned int order = get_order(size);
4131 flags |= __GFP_COMP;
4132 page = alloc_pages_node(node, flags, order);
4134 ptr = page_address(page);
4135 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4136 PAGE_SIZE << order);
4139 return kmalloc_large_node_hook(ptr, size, flags);
4142 void *__kmalloc_node(size_t size, gfp_t flags, int node)
4144 struct kmem_cache *s;
4147 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4148 ret = kmalloc_large_node(size, flags, node);
4150 trace_kmalloc_node(_RET_IP_, ret,
4151 size, PAGE_SIZE << get_order(size),
4157 s = kmalloc_slab(size, flags);
4159 if (unlikely(ZERO_OR_NULL_PTR(s)))
4162 ret = slab_alloc_node(s, flags, node, _RET_IP_, size);
4164 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
4166 ret = kasan_kmalloc(s, ret, size, flags);
4170 EXPORT_SYMBOL(__kmalloc_node);
4171 #endif /* CONFIG_NUMA */
4173 #ifdef CONFIG_HARDENED_USERCOPY
4175 * Rejects incorrectly sized objects and objects that are to be copied
4176 * to/from userspace but do not fall entirely within the containing slab
4177 * cache's usercopy region.
4179 * Returns NULL if check passes, otherwise const char * to name of cache
4180 * to indicate an error.
4182 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
4185 struct kmem_cache *s;
4186 unsigned int offset;
4188 bool is_kfence = is_kfence_address(ptr);
4190 ptr = kasan_reset_tag(ptr);
4192 /* Find object and usable object size. */
4193 s = page->slab_cache;
4195 /* Reject impossible pointers. */
4196 if (ptr < page_address(page))
4197 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4200 /* Find offset within object. */
4202 offset = ptr - kfence_object_start(ptr);
4204 offset = (ptr - page_address(page)) % s->size;
4206 /* Adjust for redzone and reject if within the redzone. */
4207 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
4208 if (offset < s->red_left_pad)
4209 usercopy_abort("SLUB object in left red zone",
4210 s->name, to_user, offset, n);
4211 offset -= s->red_left_pad;
4214 /* Allow address range falling entirely within usercopy region. */
4215 if (offset >= s->useroffset &&
4216 offset - s->useroffset <= s->usersize &&
4217 n <= s->useroffset - offset + s->usersize)
4221 * If the copy is still within the allocated object, produce
4222 * a warning instead of rejecting the copy. This is intended
4223 * to be a temporary method to find any missing usercopy
4226 object_size = slab_ksize(s);
4227 if (usercopy_fallback &&
4228 offset <= object_size && n <= object_size - offset) {
4229 usercopy_warn("SLUB object", s->name, to_user, offset, n);
4233 usercopy_abort("SLUB object", s->name, to_user, offset, n);
4235 #endif /* CONFIG_HARDENED_USERCOPY */
4237 size_t __ksize(const void *object)
4241 if (unlikely(object == ZERO_SIZE_PTR))
4244 page = virt_to_head_page(object);
4246 if (unlikely(!PageSlab(page))) {
4247 WARN_ON(!PageCompound(page));
4248 return page_size(page);
4251 return slab_ksize(page->slab_cache);
4253 EXPORT_SYMBOL(__ksize);
4255 void kfree(const void *x)
4258 void *object = (void *)x;
4260 trace_kfree(_RET_IP_, x);
4262 if (unlikely(ZERO_OR_NULL_PTR(x)))
4265 page = virt_to_head_page(x);
4266 if (unlikely(!PageSlab(page))) {
4267 unsigned int order = compound_order(page);
4269 BUG_ON(!PageCompound(page));
4271 mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
4272 -(PAGE_SIZE << order));
4273 __free_pages(page, order);
4276 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4278 EXPORT_SYMBOL(kfree);
4280 #define SHRINK_PROMOTE_MAX 32
4283 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4284 * up most to the head of the partial lists. New allocations will then
4285 * fill those up and thus they can be removed from the partial lists.
4287 * The slabs with the least items are placed last. This results in them
4288 * being allocated from last increasing the chance that the last objects
4289 * are freed in them.
4291 int __kmem_cache_shrink(struct kmem_cache *s)
4295 struct kmem_cache_node *n;
4298 struct list_head discard;
4299 struct list_head promote[SHRINK_PROMOTE_MAX];
4300 unsigned long flags;
4304 for_each_kmem_cache_node(s, node, n) {
4305 INIT_LIST_HEAD(&discard);
4306 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4307 INIT_LIST_HEAD(promote + i);
4309 spin_lock_irqsave(&n->list_lock, flags);
4312 * Build lists of slabs to discard or promote.
4314 * Note that concurrent frees may occur while we hold the
4315 * list_lock. page->inuse here is the upper limit.
4317 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4318 int free = page->objects - page->inuse;
4320 /* Do not reread page->inuse */
4323 /* We do not keep full slabs on the list */
4326 if (free == page->objects) {
4327 list_move(&page->slab_list, &discard);
4329 } else if (free <= SHRINK_PROMOTE_MAX)
4330 list_move(&page->slab_list, promote + free - 1);
4334 * Promote the slabs filled up most to the head of the
4337 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4338 list_splice(promote + i, &n->partial);
4340 spin_unlock_irqrestore(&n->list_lock, flags);
4342 /* Release empty slabs */
4343 list_for_each_entry_safe(page, t, &discard, slab_list)
4344 discard_slab(s, page);
4346 if (slabs_node(s, node))
4353 static int slab_mem_going_offline_callback(void *arg)
4355 struct kmem_cache *s;
4357 mutex_lock(&slab_mutex);
4358 list_for_each_entry(s, &slab_caches, list)
4359 __kmem_cache_shrink(s);
4360 mutex_unlock(&slab_mutex);
4365 static void slab_mem_offline_callback(void *arg)
4367 struct memory_notify *marg = arg;
4370 offline_node = marg->status_change_nid_normal;
4373 * If the node still has available memory. we need kmem_cache_node
4376 if (offline_node < 0)
4379 mutex_lock(&slab_mutex);
4380 node_clear(offline_node, slab_nodes);
4382 * We no longer free kmem_cache_node structures here, as it would be
4383 * racy with all get_node() users, and infeasible to protect them with
4386 mutex_unlock(&slab_mutex);
4389 static int slab_mem_going_online_callback(void *arg)
4391 struct kmem_cache_node *n;
4392 struct kmem_cache *s;
4393 struct memory_notify *marg = arg;
4394 int nid = marg->status_change_nid_normal;
4398 * If the node's memory is already available, then kmem_cache_node is
4399 * already created. Nothing to do.
4405 * We are bringing a node online. No memory is available yet. We must
4406 * allocate a kmem_cache_node structure in order to bring the node
4409 mutex_lock(&slab_mutex);
4410 list_for_each_entry(s, &slab_caches, list) {
4412 * The structure may already exist if the node was previously
4413 * onlined and offlined.
4415 if (get_node(s, nid))
4418 * XXX: kmem_cache_alloc_node will fallback to other nodes
4419 * since memory is not yet available from the node that
4422 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4427 init_kmem_cache_node(n);
4431 * Any cache created after this point will also have kmem_cache_node
4432 * initialized for the new node.
4434 node_set(nid, slab_nodes);
4436 mutex_unlock(&slab_mutex);
4440 static int slab_memory_callback(struct notifier_block *self,
4441 unsigned long action, void *arg)
4446 case MEM_GOING_ONLINE:
4447 ret = slab_mem_going_online_callback(arg);
4449 case MEM_GOING_OFFLINE:
4450 ret = slab_mem_going_offline_callback(arg);
4453 case MEM_CANCEL_ONLINE:
4454 slab_mem_offline_callback(arg);
4457 case MEM_CANCEL_OFFLINE:
4461 ret = notifier_from_errno(ret);
4467 static struct notifier_block slab_memory_callback_nb = {
4468 .notifier_call = slab_memory_callback,
4469 .priority = SLAB_CALLBACK_PRI,
4472 /********************************************************************
4473 * Basic setup of slabs
4474 *******************************************************************/
4477 * Used for early kmem_cache structures that were allocated using
4478 * the page allocator. Allocate them properly then fix up the pointers
4479 * that may be pointing to the wrong kmem_cache structure.
4482 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4485 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4486 struct kmem_cache_node *n;
4488 memcpy(s, static_cache, kmem_cache->object_size);
4491 * This runs very early, and only the boot processor is supposed to be
4492 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4495 __flush_cpu_slab(s, smp_processor_id());
4496 for_each_kmem_cache_node(s, node, n) {
4499 list_for_each_entry(p, &n->partial, slab_list)
4502 #ifdef CONFIG_SLUB_DEBUG
4503 list_for_each_entry(p, &n->full, slab_list)
4507 list_add(&s->list, &slab_caches);
4511 void __init kmem_cache_init(void)
4513 static __initdata struct kmem_cache boot_kmem_cache,
4514 boot_kmem_cache_node;
4517 if (debug_guardpage_minorder())
4520 /* Print slub debugging pointers without hashing */
4521 if (__slub_debug_enabled())
4522 no_hash_pointers_enable(NULL);
4524 kmem_cache_node = &boot_kmem_cache_node;
4525 kmem_cache = &boot_kmem_cache;
4528 * Initialize the nodemask for which we will allocate per node
4529 * structures. Here we don't need taking slab_mutex yet.
4531 for_each_node_state(node, N_NORMAL_MEMORY)
4532 node_set(node, slab_nodes);
4534 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4535 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4537 register_hotmemory_notifier(&slab_memory_callback_nb);
4539 /* Able to allocate the per node structures */
4540 slab_state = PARTIAL;
4542 create_boot_cache(kmem_cache, "kmem_cache",
4543 offsetof(struct kmem_cache, node) +
4544 nr_node_ids * sizeof(struct kmem_cache_node *),
4545 SLAB_HWCACHE_ALIGN, 0, 0);
4547 kmem_cache = bootstrap(&boot_kmem_cache);
4548 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4550 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4551 setup_kmalloc_cache_index_table();
4552 create_kmalloc_caches(0);
4554 /* Setup random freelists for each cache */
4555 init_freelist_randomization();
4557 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4560 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4562 slub_min_order, slub_max_order, slub_min_objects,
4563 nr_cpu_ids, nr_node_ids);
4566 void __init kmem_cache_init_late(void)
4571 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4572 slab_flags_t flags, void (*ctor)(void *))
4574 struct kmem_cache *s;
4576 s = find_mergeable(size, align, flags, name, ctor);
4581 * Adjust the object sizes so that we clear
4582 * the complete object on kzalloc.
4584 s->object_size = max(s->object_size, size);
4585 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4587 if (sysfs_slab_alias(s, name)) {
4596 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4600 err = kmem_cache_open(s, flags);
4604 /* Mutex is not taken during early boot */
4605 if (slab_state <= UP)
4608 err = sysfs_slab_add(s);
4610 __kmem_cache_release(s);
4612 if (s->flags & SLAB_STORE_USER)
4613 debugfs_slab_add(s);
4618 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4620 struct kmem_cache *s;
4623 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4624 return kmalloc_large(size, gfpflags);
4626 s = kmalloc_slab(size, gfpflags);
4628 if (unlikely(ZERO_OR_NULL_PTR(s)))
4631 ret = slab_alloc(s, gfpflags, caller, size);
4633 /* Honor the call site pointer we received. */
4634 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4638 EXPORT_SYMBOL(__kmalloc_track_caller);
4641 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4642 int node, unsigned long caller)
4644 struct kmem_cache *s;
4647 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4648 ret = kmalloc_large_node(size, gfpflags, node);
4650 trace_kmalloc_node(caller, ret,
4651 size, PAGE_SIZE << get_order(size),
4657 s = kmalloc_slab(size, gfpflags);
4659 if (unlikely(ZERO_OR_NULL_PTR(s)))
4662 ret = slab_alloc_node(s, gfpflags, node, caller, size);
4664 /* Honor the call site pointer we received. */
4665 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4669 EXPORT_SYMBOL(__kmalloc_node_track_caller);
4673 static int count_inuse(struct page *page)
4678 static int count_total(struct page *page)
4680 return page->objects;
4684 #ifdef CONFIG_SLUB_DEBUG
4685 static void validate_slab(struct kmem_cache *s, struct page *page)
4688 void *addr = page_address(page);
4693 if (!check_slab(s, page) || !on_freelist(s, page, NULL))
4696 /* Now we know that a valid freelist exists */
4697 map = get_map(s, page);
4698 for_each_object(p, s, addr, page->objects) {
4699 u8 val = test_bit(__obj_to_index(s, addr, p), map) ?
4700 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
4702 if (!check_object(s, page, p, val))
4710 static int validate_slab_node(struct kmem_cache *s,
4711 struct kmem_cache_node *n)
4713 unsigned long count = 0;
4715 unsigned long flags;
4717 spin_lock_irqsave(&n->list_lock, flags);
4719 list_for_each_entry(page, &n->partial, slab_list) {
4720 validate_slab(s, page);
4723 if (count != n->nr_partial) {
4724 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4725 s->name, count, n->nr_partial);
4726 slab_add_kunit_errors();
4729 if (!(s->flags & SLAB_STORE_USER))
4732 list_for_each_entry(page, &n->full, slab_list) {
4733 validate_slab(s, page);
4736 if (count != atomic_long_read(&n->nr_slabs)) {
4737 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4738 s->name, count, atomic_long_read(&n->nr_slabs));
4739 slab_add_kunit_errors();
4743 spin_unlock_irqrestore(&n->list_lock, flags);
4747 long validate_slab_cache(struct kmem_cache *s)
4750 unsigned long count = 0;
4751 struct kmem_cache_node *n;
4754 for_each_kmem_cache_node(s, node, n)
4755 count += validate_slab_node(s, n);
4759 EXPORT_SYMBOL(validate_slab_cache);
4761 #ifdef CONFIG_DEBUG_FS
4763 * Generate lists of code addresses where slabcache objects are allocated
4768 unsigned long count;
4775 DECLARE_BITMAP(cpus, NR_CPUS);
4781 unsigned long count;
4782 struct location *loc;
4785 static struct dentry *slab_debugfs_root;
4787 static void free_loc_track(struct loc_track *t)
4790 free_pages((unsigned long)t->loc,
4791 get_order(sizeof(struct location) * t->max));
4794 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4799 order = get_order(sizeof(struct location) * max);
4801 l = (void *)__get_free_pages(flags, order);
4806 memcpy(l, t->loc, sizeof(struct location) * t->count);
4814 static int add_location(struct loc_track *t, struct kmem_cache *s,
4815 const struct track *track)
4817 long start, end, pos;
4819 unsigned long caddr;
4820 unsigned long age = jiffies - track->when;
4826 pos = start + (end - start + 1) / 2;
4829 * There is nothing at "end". If we end up there
4830 * we need to add something to before end.
4835 caddr = t->loc[pos].addr;
4836 if (track->addr == caddr) {
4842 if (age < l->min_time)
4844 if (age > l->max_time)
4847 if (track->pid < l->min_pid)
4848 l->min_pid = track->pid;
4849 if (track->pid > l->max_pid)
4850 l->max_pid = track->pid;
4852 cpumask_set_cpu(track->cpu,
4853 to_cpumask(l->cpus));
4855 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4859 if (track->addr < caddr)
4866 * Not found. Insert new tracking element.
4868 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4874 (t->count - pos) * sizeof(struct location));
4877 l->addr = track->addr;
4881 l->min_pid = track->pid;
4882 l->max_pid = track->pid;
4883 cpumask_clear(to_cpumask(l->cpus));
4884 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4885 nodes_clear(l->nodes);
4886 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4890 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4891 struct page *page, enum track_item alloc)
4893 void *addr = page_address(page);
4897 map = get_map(s, page);
4898 for_each_object(p, s, addr, page->objects)
4899 if (!test_bit(__obj_to_index(s, addr, p), map))
4900 add_location(t, s, get_track(s, p, alloc));
4903 #endif /* CONFIG_DEBUG_FS */
4904 #endif /* CONFIG_SLUB_DEBUG */
4907 enum slab_stat_type {
4908 SL_ALL, /* All slabs */
4909 SL_PARTIAL, /* Only partially allocated slabs */
4910 SL_CPU, /* Only slabs used for cpu caches */
4911 SL_OBJECTS, /* Determine allocated objects not slabs */
4912 SL_TOTAL /* Determine object capacity not slabs */
4915 #define SO_ALL (1 << SL_ALL)
4916 #define SO_PARTIAL (1 << SL_PARTIAL)
4917 #define SO_CPU (1 << SL_CPU)
4918 #define SO_OBJECTS (1 << SL_OBJECTS)
4919 #define SO_TOTAL (1 << SL_TOTAL)
4921 static ssize_t show_slab_objects(struct kmem_cache *s,
4922 char *buf, unsigned long flags)
4924 unsigned long total = 0;
4927 unsigned long *nodes;
4930 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
4934 if (flags & SO_CPU) {
4937 for_each_possible_cpu(cpu) {
4938 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4943 page = READ_ONCE(c->page);
4947 node = page_to_nid(page);
4948 if (flags & SO_TOTAL)
4950 else if (flags & SO_OBJECTS)
4958 page = slub_percpu_partial_read_once(c);
4960 node = page_to_nid(page);
4961 if (flags & SO_TOTAL)
4963 else if (flags & SO_OBJECTS)
4974 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
4975 * already held which will conflict with an existing lock order:
4977 * mem_hotplug_lock->slab_mutex->kernfs_mutex
4979 * We don't really need mem_hotplug_lock (to hold off
4980 * slab_mem_going_offline_callback) here because slab's memory hot
4981 * unplug code doesn't destroy the kmem_cache->node[] data.
4984 #ifdef CONFIG_SLUB_DEBUG
4985 if (flags & SO_ALL) {
4986 struct kmem_cache_node *n;
4988 for_each_kmem_cache_node(s, node, n) {
4990 if (flags & SO_TOTAL)
4991 x = atomic_long_read(&n->total_objects);
4992 else if (flags & SO_OBJECTS)
4993 x = atomic_long_read(&n->total_objects) -
4994 count_partial(n, count_free);
4996 x = atomic_long_read(&n->nr_slabs);
5003 if (flags & SO_PARTIAL) {
5004 struct kmem_cache_node *n;
5006 for_each_kmem_cache_node(s, node, n) {
5007 if (flags & SO_TOTAL)
5008 x = count_partial(n, count_total);
5009 else if (flags & SO_OBJECTS)
5010 x = count_partial(n, count_inuse);
5018 len += sysfs_emit_at(buf, len, "%lu", total);
5020 for (node = 0; node < nr_node_ids; node++) {
5022 len += sysfs_emit_at(buf, len, " N%d=%lu",
5026 len += sysfs_emit_at(buf, len, "\n");
5032 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
5033 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
5035 struct slab_attribute {
5036 struct attribute attr;
5037 ssize_t (*show)(struct kmem_cache *s, char *buf);
5038 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5041 #define SLAB_ATTR_RO(_name) \
5042 static struct slab_attribute _name##_attr = \
5043 __ATTR(_name, 0400, _name##_show, NULL)
5045 #define SLAB_ATTR(_name) \
5046 static struct slab_attribute _name##_attr = \
5047 __ATTR(_name, 0600, _name##_show, _name##_store)
5049 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5051 return sysfs_emit(buf, "%u\n", s->size);
5053 SLAB_ATTR_RO(slab_size);
5055 static ssize_t align_show(struct kmem_cache *s, char *buf)
5057 return sysfs_emit(buf, "%u\n", s->align);
5059 SLAB_ATTR_RO(align);
5061 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5063 return sysfs_emit(buf, "%u\n", s->object_size);
5065 SLAB_ATTR_RO(object_size);
5067 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5069 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
5071 SLAB_ATTR_RO(objs_per_slab);
5073 static ssize_t order_show(struct kmem_cache *s, char *buf)
5075 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
5077 SLAB_ATTR_RO(order);
5079 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5081 return sysfs_emit(buf, "%lu\n", s->min_partial);
5084 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5090 err = kstrtoul(buf, 10, &min);
5094 set_min_partial(s, min);
5097 SLAB_ATTR(min_partial);
5099 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5101 return sysfs_emit(buf, "%u\n", slub_cpu_partial(s));
5104 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5107 unsigned int objects;
5110 err = kstrtouint(buf, 10, &objects);
5113 if (objects && !kmem_cache_has_cpu_partial(s))
5116 slub_set_cpu_partial(s, objects);
5120 SLAB_ATTR(cpu_partial);
5122 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5126 return sysfs_emit(buf, "%pS\n", s->ctor);
5130 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5132 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5134 SLAB_ATTR_RO(aliases);
5136 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5138 return show_slab_objects(s, buf, SO_PARTIAL);
5140 SLAB_ATTR_RO(partial);
5142 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5144 return show_slab_objects(s, buf, SO_CPU);
5146 SLAB_ATTR_RO(cpu_slabs);
5148 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5150 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5152 SLAB_ATTR_RO(objects);
5154 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5156 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5158 SLAB_ATTR_RO(objects_partial);
5160 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5167 for_each_online_cpu(cpu) {
5170 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5173 pages += page->pages;
5174 objects += page->pobjects;
5178 len += sysfs_emit_at(buf, len, "%d(%d)", objects, pages);
5181 for_each_online_cpu(cpu) {
5184 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5186 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
5187 cpu, page->pobjects, page->pages);
5190 len += sysfs_emit_at(buf, len, "\n");
5194 SLAB_ATTR_RO(slabs_cpu_partial);
5196 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5198 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5200 SLAB_ATTR_RO(reclaim_account);
5202 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5204 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5206 SLAB_ATTR_RO(hwcache_align);
5208 #ifdef CONFIG_ZONE_DMA
5209 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5211 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5213 SLAB_ATTR_RO(cache_dma);
5216 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5218 return sysfs_emit(buf, "%u\n", s->usersize);
5220 SLAB_ATTR_RO(usersize);
5222 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5224 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5226 SLAB_ATTR_RO(destroy_by_rcu);
5228 #ifdef CONFIG_SLUB_DEBUG
5229 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5231 return show_slab_objects(s, buf, SO_ALL);
5233 SLAB_ATTR_RO(slabs);
5235 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5237 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5239 SLAB_ATTR_RO(total_objects);
5241 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5243 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5245 SLAB_ATTR_RO(sanity_checks);
5247 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5249 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5251 SLAB_ATTR_RO(trace);
5253 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5255 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5258 SLAB_ATTR_RO(red_zone);
5260 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5262 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
5265 SLAB_ATTR_RO(poison);
5267 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5269 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5272 SLAB_ATTR_RO(store_user);
5274 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5279 static ssize_t validate_store(struct kmem_cache *s,
5280 const char *buf, size_t length)
5284 if (buf[0] == '1') {
5285 ret = validate_slab_cache(s);
5291 SLAB_ATTR(validate);
5293 #endif /* CONFIG_SLUB_DEBUG */
5295 #ifdef CONFIG_FAILSLAB
5296 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5298 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5300 SLAB_ATTR_RO(failslab);
5303 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5308 static ssize_t shrink_store(struct kmem_cache *s,
5309 const char *buf, size_t length)
5312 kmem_cache_shrink(s);
5320 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5322 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5325 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5326 const char *buf, size_t length)
5331 err = kstrtouint(buf, 10, &ratio);
5337 s->remote_node_defrag_ratio = ratio * 10;
5341 SLAB_ATTR(remote_node_defrag_ratio);
5344 #ifdef CONFIG_SLUB_STATS
5345 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5347 unsigned long sum = 0;
5350 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5355 for_each_online_cpu(cpu) {
5356 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5362 len += sysfs_emit_at(buf, len, "%lu", sum);
5365 for_each_online_cpu(cpu) {
5367 len += sysfs_emit_at(buf, len, " C%d=%u",
5372 len += sysfs_emit_at(buf, len, "\n");
5377 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5381 for_each_online_cpu(cpu)
5382 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5385 #define STAT_ATTR(si, text) \
5386 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5388 return show_stat(s, buf, si); \
5390 static ssize_t text##_store(struct kmem_cache *s, \
5391 const char *buf, size_t length) \
5393 if (buf[0] != '0') \
5395 clear_stat(s, si); \
5400 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5401 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5402 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5403 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5404 STAT_ATTR(FREE_FROZEN, free_frozen);
5405 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5406 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5407 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5408 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5409 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5410 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5411 STAT_ATTR(FREE_SLAB, free_slab);
5412 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5413 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5414 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5415 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5416 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5417 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5418 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5419 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5420 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5421 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5422 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5423 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5424 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5425 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5426 #endif /* CONFIG_SLUB_STATS */
5428 static struct attribute *slab_attrs[] = {
5429 &slab_size_attr.attr,
5430 &object_size_attr.attr,
5431 &objs_per_slab_attr.attr,
5433 &min_partial_attr.attr,
5434 &cpu_partial_attr.attr,
5436 &objects_partial_attr.attr,
5438 &cpu_slabs_attr.attr,
5442 &hwcache_align_attr.attr,
5443 &reclaim_account_attr.attr,
5444 &destroy_by_rcu_attr.attr,
5446 &slabs_cpu_partial_attr.attr,
5447 #ifdef CONFIG_SLUB_DEBUG
5448 &total_objects_attr.attr,
5450 &sanity_checks_attr.attr,
5452 &red_zone_attr.attr,
5454 &store_user_attr.attr,
5455 &validate_attr.attr,
5457 #ifdef CONFIG_ZONE_DMA
5458 &cache_dma_attr.attr,
5461 &remote_node_defrag_ratio_attr.attr,
5463 #ifdef CONFIG_SLUB_STATS
5464 &alloc_fastpath_attr.attr,
5465 &alloc_slowpath_attr.attr,
5466 &free_fastpath_attr.attr,
5467 &free_slowpath_attr.attr,
5468 &free_frozen_attr.attr,
5469 &free_add_partial_attr.attr,
5470 &free_remove_partial_attr.attr,
5471 &alloc_from_partial_attr.attr,
5472 &alloc_slab_attr.attr,
5473 &alloc_refill_attr.attr,
5474 &alloc_node_mismatch_attr.attr,
5475 &free_slab_attr.attr,
5476 &cpuslab_flush_attr.attr,
5477 &deactivate_full_attr.attr,
5478 &deactivate_empty_attr.attr,
5479 &deactivate_to_head_attr.attr,
5480 &deactivate_to_tail_attr.attr,
5481 &deactivate_remote_frees_attr.attr,
5482 &deactivate_bypass_attr.attr,
5483 &order_fallback_attr.attr,
5484 &cmpxchg_double_fail_attr.attr,
5485 &cmpxchg_double_cpu_fail_attr.attr,
5486 &cpu_partial_alloc_attr.attr,
5487 &cpu_partial_free_attr.attr,
5488 &cpu_partial_node_attr.attr,
5489 &cpu_partial_drain_attr.attr,
5491 #ifdef CONFIG_FAILSLAB
5492 &failslab_attr.attr,
5494 &usersize_attr.attr,
5499 static const struct attribute_group slab_attr_group = {
5500 .attrs = slab_attrs,
5503 static ssize_t slab_attr_show(struct kobject *kobj,
5504 struct attribute *attr,
5507 struct slab_attribute *attribute;
5508 struct kmem_cache *s;
5511 attribute = to_slab_attr(attr);
5514 if (!attribute->show)
5517 err = attribute->show(s, buf);
5522 static ssize_t slab_attr_store(struct kobject *kobj,
5523 struct attribute *attr,
5524 const char *buf, size_t len)
5526 struct slab_attribute *attribute;
5527 struct kmem_cache *s;
5530 attribute = to_slab_attr(attr);
5533 if (!attribute->store)
5536 err = attribute->store(s, buf, len);
5540 static void kmem_cache_release(struct kobject *k)
5542 slab_kmem_cache_release(to_slab(k));
5545 static const struct sysfs_ops slab_sysfs_ops = {
5546 .show = slab_attr_show,
5547 .store = slab_attr_store,
5550 static struct kobj_type slab_ktype = {
5551 .sysfs_ops = &slab_sysfs_ops,
5552 .release = kmem_cache_release,
5555 static struct kset *slab_kset;
5557 static inline struct kset *cache_kset(struct kmem_cache *s)
5562 #define ID_STR_LENGTH 64
5564 /* Create a unique string id for a slab cache:
5566 * Format :[flags-]size
5568 static char *create_unique_id(struct kmem_cache *s)
5570 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5577 * First flags affecting slabcache operations. We will only
5578 * get here for aliasable slabs so we do not need to support
5579 * too many flags. The flags here must cover all flags that
5580 * are matched during merging to guarantee that the id is
5583 if (s->flags & SLAB_CACHE_DMA)
5585 if (s->flags & SLAB_CACHE_DMA32)
5587 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5589 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5591 if (s->flags & SLAB_ACCOUNT)
5595 p += sprintf(p, "%07u", s->size);
5597 BUG_ON(p > name + ID_STR_LENGTH - 1);
5601 static int sysfs_slab_add(struct kmem_cache *s)
5605 struct kset *kset = cache_kset(s);
5606 int unmergeable = slab_unmergeable(s);
5609 kobject_init(&s->kobj, &slab_ktype);
5613 if (!unmergeable && disable_higher_order_debug &&
5614 (slub_debug & DEBUG_METADATA_FLAGS))
5619 * Slabcache can never be merged so we can use the name proper.
5620 * This is typically the case for debug situations. In that
5621 * case we can catch duplicate names easily.
5623 sysfs_remove_link(&slab_kset->kobj, s->name);
5627 * Create a unique name for the slab as a target
5630 name = create_unique_id(s);
5633 s->kobj.kset = kset;
5634 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5638 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5643 /* Setup first alias */
5644 sysfs_slab_alias(s, s->name);
5651 kobject_del(&s->kobj);
5655 void sysfs_slab_unlink(struct kmem_cache *s)
5657 if (slab_state >= FULL)
5658 kobject_del(&s->kobj);
5661 void sysfs_slab_release(struct kmem_cache *s)
5663 if (slab_state >= FULL)
5664 kobject_put(&s->kobj);
5668 * Need to buffer aliases during bootup until sysfs becomes
5669 * available lest we lose that information.
5671 struct saved_alias {
5672 struct kmem_cache *s;
5674 struct saved_alias *next;
5677 static struct saved_alias *alias_list;
5679 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5681 struct saved_alias *al;
5683 if (slab_state == FULL) {
5685 * If we have a leftover link then remove it.
5687 sysfs_remove_link(&slab_kset->kobj, name);
5688 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5691 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5697 al->next = alias_list;
5702 static int __init slab_sysfs_init(void)
5704 struct kmem_cache *s;
5707 mutex_lock(&slab_mutex);
5709 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
5711 mutex_unlock(&slab_mutex);
5712 pr_err("Cannot register slab subsystem.\n");
5718 list_for_each_entry(s, &slab_caches, list) {
5719 err = sysfs_slab_add(s);
5721 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5725 while (alias_list) {
5726 struct saved_alias *al = alias_list;
5728 alias_list = alias_list->next;
5729 err = sysfs_slab_alias(al->s, al->name);
5731 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5736 mutex_unlock(&slab_mutex);
5740 __initcall(slab_sysfs_init);
5741 #endif /* CONFIG_SYSFS */
5743 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
5744 static int slab_debugfs_show(struct seq_file *seq, void *v)
5748 unsigned int idx = *(unsigned int *)v;
5749 struct loc_track *t = seq->private;
5751 if (idx < t->count) {
5754 seq_printf(seq, "%7ld ", l->count);
5757 seq_printf(seq, "%pS", (void *)l->addr);
5759 seq_puts(seq, "<not-available>");
5761 if (l->sum_time != l->min_time) {
5762 seq_printf(seq, " age=%ld/%llu/%ld",
5763 l->min_time, div_u64(l->sum_time, l->count),
5766 seq_printf(seq, " age=%ld", l->min_time);
5768 if (l->min_pid != l->max_pid)
5769 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
5771 seq_printf(seq, " pid=%ld",
5774 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
5775 seq_printf(seq, " cpus=%*pbl",
5776 cpumask_pr_args(to_cpumask(l->cpus)));
5778 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
5779 seq_printf(seq, " nodes=%*pbl",
5780 nodemask_pr_args(&l->nodes));
5782 seq_puts(seq, "\n");
5785 if (!idx && !t->count)
5786 seq_puts(seq, "No data\n");
5791 static void slab_debugfs_stop(struct seq_file *seq, void *v)
5795 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
5797 struct loc_track *t = seq->private;
5801 if (*ppos <= t->count)
5807 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
5812 static const struct seq_operations slab_debugfs_sops = {
5813 .start = slab_debugfs_start,
5814 .next = slab_debugfs_next,
5815 .stop = slab_debugfs_stop,
5816 .show = slab_debugfs_show,
5819 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
5822 struct kmem_cache_node *n;
5823 enum track_item alloc;
5825 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
5826 sizeof(struct loc_track));
5827 struct kmem_cache *s = file_inode(filep)->i_private;
5829 if (strcmp(filep->f_path.dentry->d_name.name, "alloc_traces") == 0)
5830 alloc = TRACK_ALLOC;
5834 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL))
5837 /* Push back cpu slabs */
5840 for_each_kmem_cache_node(s, node, n) {
5841 unsigned long flags;
5844 if (!atomic_long_read(&n->nr_slabs))
5847 spin_lock_irqsave(&n->list_lock, flags);
5848 list_for_each_entry(page, &n->partial, slab_list)
5849 process_slab(t, s, page, alloc);
5850 list_for_each_entry(page, &n->full, slab_list)
5851 process_slab(t, s, page, alloc);
5852 spin_unlock_irqrestore(&n->list_lock, flags);
5858 static int slab_debug_trace_release(struct inode *inode, struct file *file)
5860 struct seq_file *seq = file->private_data;
5861 struct loc_track *t = seq->private;
5864 return seq_release_private(inode, file);
5867 static const struct file_operations slab_debugfs_fops = {
5868 .open = slab_debug_trace_open,
5870 .llseek = seq_lseek,
5871 .release = slab_debug_trace_release,
5874 static void debugfs_slab_add(struct kmem_cache *s)
5876 struct dentry *slab_cache_dir;
5878 if (unlikely(!slab_debugfs_root))
5881 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
5883 debugfs_create_file("alloc_traces", 0400,
5884 slab_cache_dir, s, &slab_debugfs_fops);
5886 debugfs_create_file("free_traces", 0400,
5887 slab_cache_dir, s, &slab_debugfs_fops);
5890 void debugfs_slab_release(struct kmem_cache *s)
5892 debugfs_remove_recursive(debugfs_lookup(s->name, slab_debugfs_root));
5895 static int __init slab_debugfs_init(void)
5897 struct kmem_cache *s;
5899 slab_debugfs_root = debugfs_create_dir("slab", NULL);
5901 list_for_each_entry(s, &slab_caches, list)
5902 if (s->flags & SLAB_STORE_USER)
5903 debugfs_slab_add(s);
5908 __initcall(slab_debugfs_init);
5911 * The /proc/slabinfo ABI
5913 #ifdef CONFIG_SLUB_DEBUG
5914 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5916 unsigned long nr_slabs = 0;
5917 unsigned long nr_objs = 0;
5918 unsigned long nr_free = 0;
5920 struct kmem_cache_node *n;
5922 for_each_kmem_cache_node(s, node, n) {
5923 nr_slabs += node_nr_slabs(n);
5924 nr_objs += node_nr_objs(n);
5925 nr_free += count_partial(n, count_free);
5928 sinfo->active_objs = nr_objs - nr_free;
5929 sinfo->num_objs = nr_objs;
5930 sinfo->active_slabs = nr_slabs;
5931 sinfo->num_slabs = nr_slabs;
5932 sinfo->objects_per_slab = oo_objects(s->oo);
5933 sinfo->cache_order = oo_order(s->oo);
5936 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5940 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5941 size_t count, loff_t *ppos)
5945 #endif /* CONFIG_SLUB_DEBUG */