powerpc/fadump: use static allocation for reserved memory ranges
[linux/fpc-iii.git] / mm / slub.c
blob63bd39c476431488bcba66c27e334292dc8b7a8a
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
6 * The allocator synchronizes using per slab locks or atomic operatios
7 * and only uses a centralized lock to manage a pool of partial slabs.
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
13 #include <linux/mm.h>
14 #include <linux/swap.h> /* struct reclaim_state */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/bitops.h>
19 #include <linux/slab.h>
20 #include "slab.h"
21 #include <linux/proc_fs.h>
22 #include <linux/seq_file.h>
23 #include <linux/kasan.h>
24 #include <linux/cpu.h>
25 #include <linux/cpuset.h>
26 #include <linux/mempolicy.h>
27 #include <linux/ctype.h>
28 #include <linux/debugobjects.h>
29 #include <linux/kallsyms.h>
30 #include <linux/memory.h>
31 #include <linux/math64.h>
32 #include <linux/fault-inject.h>
33 #include <linux/stacktrace.h>
34 #include <linux/prefetch.h>
35 #include <linux/memcontrol.h>
36 #include <linux/random.h>
38 #include <trace/events/kmem.h>
40 #include "internal.h"
43 * Lock order:
44 * 1. slab_mutex (Global Mutex)
45 * 2. node->list_lock
46 * 3. slab_lock(page) (Only on some arches and for debugging)
48 * slab_mutex
50 * The role of the slab_mutex is to protect the list of all the slabs
51 * and to synchronize major metadata changes to slab cache structures.
53 * The slab_lock is only used for debugging and on arches that do not
54 * have the ability to do a cmpxchg_double. It only protects:
55 * A. page->freelist -> List of object free in a page
56 * B. page->inuse -> Number of objects in use
57 * C. page->objects -> Number of objects in page
58 * D. page->frozen -> frozen state
60 * If a slab is frozen then it is exempt from list management. It is not
61 * on any list except per cpu partial list. The processor that froze the
62 * slab is the one who can perform list operations on the page. Other
63 * processors may put objects onto the freelist but the processor that
64 * froze the slab is the only one that can retrieve the objects from the
65 * page's freelist.
67 * The list_lock protects the partial and full list on each node and
68 * the partial slab counter. If taken then no new slabs may be added or
69 * removed from the lists nor make the number of partial slabs be modified.
70 * (Note that the total number of slabs is an atomic value that may be
71 * modified without taking the list lock).
73 * The list_lock is a centralized lock and thus we avoid taking it as
74 * much as possible. As long as SLUB does not have to handle partial
75 * slabs, operations can continue without any centralized lock. F.e.
76 * allocating a long series of objects that fill up slabs does not require
77 * the list lock.
78 * Interrupts are disabled during allocation and deallocation in order to
79 * make the slab allocator safe to use in the context of an irq. In addition
80 * interrupts are disabled to ensure that the processor does not change
81 * while handling per_cpu slabs, due to kernel preemption.
83 * SLUB assigns one slab for allocation to each processor.
84 * Allocations only occur from these slabs called cpu slabs.
86 * Slabs with free elements are kept on a partial list and during regular
87 * operations no list for full slabs is used. If an object in a full slab is
88 * freed then the slab will show up again on the partial lists.
89 * We track full slabs for debugging purposes though because otherwise we
90 * cannot scan all objects.
92 * Slabs are freed when they become empty. Teardown and setup is
93 * minimal so we rely on the page allocators per cpu caches for
94 * fast frees and allocs.
96 * page->frozen The slab is frozen and exempt from list processing.
97 * This means that the slab is dedicated to a purpose
98 * such as satisfying allocations for a specific
99 * processor. Objects may be freed in the slab while
100 * it is frozen but slab_free will then skip the usual
101 * list operations. It is up to the processor holding
102 * the slab to integrate the slab into the slab lists
103 * when the slab is no longer needed.
105 * One use of this flag is to mark slabs that are
106 * used for allocations. Then such a slab becomes a cpu
107 * slab. The cpu slab may be equipped with an additional
108 * freelist that allows lockless access to
109 * free objects in addition to the regular freelist
110 * that requires the slab lock.
112 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
113 * options set. This moves slab handling out of
114 * the fast path and disables lockless freelists.
117 static inline int kmem_cache_debug(struct kmem_cache *s)
119 #ifdef CONFIG_SLUB_DEBUG
120 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
121 #else
122 return 0;
123 #endif
126 void *fixup_red_left(struct kmem_cache *s, void *p)
128 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE)
129 p += s->red_left_pad;
131 return p;
134 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
136 #ifdef CONFIG_SLUB_CPU_PARTIAL
137 return !kmem_cache_debug(s);
138 #else
139 return false;
140 #endif
144 * Issues still to be resolved:
146 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
148 * - Variable sizing of the per node arrays
151 /* Enable to test recovery from slab corruption on boot */
152 #undef SLUB_RESILIENCY_TEST
154 /* Enable to log cmpxchg failures */
155 #undef SLUB_DEBUG_CMPXCHG
158 * Mininum number of partial slabs. These will be left on the partial
159 * lists even if they are empty. kmem_cache_shrink may reclaim them.
161 #define MIN_PARTIAL 5
164 * Maximum number of desirable partial slabs.
165 * The existence of more partial slabs makes kmem_cache_shrink
166 * sort the partial list by the number of objects in use.
168 #define MAX_PARTIAL 10
170 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
171 SLAB_POISON | SLAB_STORE_USER)
174 * These debug flags cannot use CMPXCHG because there might be consistency
175 * issues when checking or reading debug information
177 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
178 SLAB_TRACE)
182 * Debugging flags that require metadata to be stored in the slab. These get
183 * disabled when slub_debug=O is used and a cache's min order increases with
184 * metadata.
186 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
188 #define OO_SHIFT 16
189 #define OO_MASK ((1 << OO_SHIFT) - 1)
190 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
192 /* Internal SLUB flags */
193 /* Poison object */
194 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
195 /* Use cmpxchg_double */
196 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
199 * Tracking user of a slab.
201 #define TRACK_ADDRS_COUNT 16
202 struct track {
203 unsigned long addr; /* Called from address */
204 #ifdef CONFIG_STACKTRACE
205 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
206 #endif
207 int cpu; /* Was running on cpu */
208 int pid; /* Pid context */
209 unsigned long when; /* When did the operation occur */
212 enum track_item { TRACK_ALLOC, TRACK_FREE };
214 #ifdef CONFIG_SYSFS
215 static int sysfs_slab_add(struct kmem_cache *);
216 static int sysfs_slab_alias(struct kmem_cache *, const char *);
217 static void memcg_propagate_slab_attrs(struct kmem_cache *s);
218 static void sysfs_slab_remove(struct kmem_cache *s);
219 #else
220 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
221 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
222 { return 0; }
223 static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { }
224 static inline void sysfs_slab_remove(struct kmem_cache *s) { }
225 #endif
227 static inline void stat(const struct kmem_cache *s, enum stat_item si)
229 #ifdef CONFIG_SLUB_STATS
231 * The rmw is racy on a preemptible kernel but this is acceptable, so
232 * avoid this_cpu_add()'s irq-disable overhead.
234 raw_cpu_inc(s->cpu_slab->stat[si]);
235 #endif
238 /********************************************************************
239 * Core slab cache functions
240 *******************************************************************/
243 * Returns freelist pointer (ptr). With hardening, this is obfuscated
244 * with an XOR of the address where the pointer is held and a per-cache
245 * random number.
247 static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
248 unsigned long ptr_addr)
250 #ifdef CONFIG_SLAB_FREELIST_HARDENED
252 * When CONFIG_KASAN_SW_TAGS is enabled, ptr_addr might be tagged.
253 * Normally, this doesn't cause any issues, as both set_freepointer()
254 * and get_freepointer() are called with a pointer with the same tag.
255 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
256 * example, when __free_slub() iterates over objects in a cache, it
257 * passes untagged pointers to check_object(). check_object() in turns
258 * calls get_freepointer() with an untagged pointer, which causes the
259 * freepointer to be restored incorrectly.
261 return (void *)((unsigned long)ptr ^ s->random ^
262 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
263 #else
264 return ptr;
265 #endif
268 /* Returns the freelist pointer recorded at location ptr_addr. */
269 static inline void *freelist_dereference(const struct kmem_cache *s,
270 void *ptr_addr)
272 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
273 (unsigned long)ptr_addr);
276 static inline void *get_freepointer(struct kmem_cache *s, void *object)
278 return freelist_dereference(s, object + s->offset);
281 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
283 prefetch(object + s->offset);
286 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
288 unsigned long freepointer_addr;
289 void *p;
291 if (!debug_pagealloc_enabled_static())
292 return get_freepointer(s, object);
294 freepointer_addr = (unsigned long)object + s->offset;
295 probe_kernel_read(&p, (void **)freepointer_addr, sizeof(p));
296 return freelist_ptr(s, p, freepointer_addr);
299 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
301 unsigned long freeptr_addr = (unsigned long)object + s->offset;
303 #ifdef CONFIG_SLAB_FREELIST_HARDENED
304 BUG_ON(object == fp); /* naive detection of double free or corruption */
305 #endif
307 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
310 /* Loop over all objects in a slab */
311 #define for_each_object(__p, __s, __addr, __objects) \
312 for (__p = fixup_red_left(__s, __addr); \
313 __p < (__addr) + (__objects) * (__s)->size; \
314 __p += (__s)->size)
316 /* Determine object index from a given position */
317 static inline unsigned int slab_index(void *p, struct kmem_cache *s, void *addr)
319 return (kasan_reset_tag(p) - addr) / s->size;
322 static inline unsigned int order_objects(unsigned int order, unsigned int size)
324 return ((unsigned int)PAGE_SIZE << order) / size;
327 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
328 unsigned int size)
330 struct kmem_cache_order_objects x = {
331 (order << OO_SHIFT) + order_objects(order, size)
334 return x;
337 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
339 return x.x >> OO_SHIFT;
342 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
344 return x.x & OO_MASK;
348 * Per slab locking using the pagelock
350 static __always_inline void slab_lock(struct page *page)
352 VM_BUG_ON_PAGE(PageTail(page), page);
353 bit_spin_lock(PG_locked, &page->flags);
356 static __always_inline void slab_unlock(struct page *page)
358 VM_BUG_ON_PAGE(PageTail(page), page);
359 __bit_spin_unlock(PG_locked, &page->flags);
362 /* Interrupts must be disabled (for the fallback code to work right) */
363 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
364 void *freelist_old, unsigned long counters_old,
365 void *freelist_new, unsigned long counters_new,
366 const char *n)
368 VM_BUG_ON(!irqs_disabled());
369 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
370 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
371 if (s->flags & __CMPXCHG_DOUBLE) {
372 if (cmpxchg_double(&page->freelist, &page->counters,
373 freelist_old, counters_old,
374 freelist_new, counters_new))
375 return true;
376 } else
377 #endif
379 slab_lock(page);
380 if (page->freelist == freelist_old &&
381 page->counters == counters_old) {
382 page->freelist = freelist_new;
383 page->counters = counters_new;
384 slab_unlock(page);
385 return true;
387 slab_unlock(page);
390 cpu_relax();
391 stat(s, CMPXCHG_DOUBLE_FAIL);
393 #ifdef SLUB_DEBUG_CMPXCHG
394 pr_info("%s %s: cmpxchg double redo ", n, s->name);
395 #endif
397 return false;
400 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
401 void *freelist_old, unsigned long counters_old,
402 void *freelist_new, unsigned long counters_new,
403 const char *n)
405 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
406 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
407 if (s->flags & __CMPXCHG_DOUBLE) {
408 if (cmpxchg_double(&page->freelist, &page->counters,
409 freelist_old, counters_old,
410 freelist_new, counters_new))
411 return true;
412 } else
413 #endif
415 unsigned long flags;
417 local_irq_save(flags);
418 slab_lock(page);
419 if (page->freelist == freelist_old &&
420 page->counters == counters_old) {
421 page->freelist = freelist_new;
422 page->counters = counters_new;
423 slab_unlock(page);
424 local_irq_restore(flags);
425 return true;
427 slab_unlock(page);
428 local_irq_restore(flags);
431 cpu_relax();
432 stat(s, CMPXCHG_DOUBLE_FAIL);
434 #ifdef SLUB_DEBUG_CMPXCHG
435 pr_info("%s %s: cmpxchg double redo ", n, s->name);
436 #endif
438 return false;
441 #ifdef CONFIG_SLUB_DEBUG
442 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
443 static DEFINE_SPINLOCK(object_map_lock);
446 * Determine a map of object in use on a page.
448 * Node listlock must be held to guarantee that the page does
449 * not vanish from under us.
451 static unsigned long *get_map(struct kmem_cache *s, struct page *page)
452 __acquires(&object_map_lock)
454 void *p;
455 void *addr = page_address(page);
457 VM_BUG_ON(!irqs_disabled());
459 spin_lock(&object_map_lock);
461 bitmap_zero(object_map, page->objects);
463 for (p = page->freelist; p; p = get_freepointer(s, p))
464 set_bit(slab_index(p, s, addr), object_map);
466 return object_map;
469 static void put_map(unsigned long *map) __releases(&object_map_lock)
471 VM_BUG_ON(map != object_map);
472 lockdep_assert_held(&object_map_lock);
474 spin_unlock(&object_map_lock);
477 static inline unsigned int size_from_object(struct kmem_cache *s)
479 if (s->flags & SLAB_RED_ZONE)
480 return s->size - s->red_left_pad;
482 return s->size;
485 static inline void *restore_red_left(struct kmem_cache *s, void *p)
487 if (s->flags & SLAB_RED_ZONE)
488 p -= s->red_left_pad;
490 return p;
494 * Debug settings:
496 #if defined(CONFIG_SLUB_DEBUG_ON)
497 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
498 #else
499 static slab_flags_t slub_debug;
500 #endif
502 static char *slub_debug_slabs;
503 static int disable_higher_order_debug;
506 * slub is about to manipulate internal object metadata. This memory lies
507 * outside the range of the allocated object, so accessing it would normally
508 * be reported by kasan as a bounds error. metadata_access_enable() is used
509 * to tell kasan that these accesses are OK.
511 static inline void metadata_access_enable(void)
513 kasan_disable_current();
516 static inline void metadata_access_disable(void)
518 kasan_enable_current();
522 * Object debugging
525 /* Verify that a pointer has an address that is valid within a slab page */
526 static inline int check_valid_pointer(struct kmem_cache *s,
527 struct page *page, void *object)
529 void *base;
531 if (!object)
532 return 1;
534 base = page_address(page);
535 object = kasan_reset_tag(object);
536 object = restore_red_left(s, object);
537 if (object < base || object >= base + page->objects * s->size ||
538 (object - base) % s->size) {
539 return 0;
542 return 1;
545 static void print_section(char *level, char *text, u8 *addr,
546 unsigned int length)
548 metadata_access_enable();
549 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
550 length, 1);
551 metadata_access_disable();
555 * See comment in calculate_sizes().
557 static inline bool freeptr_outside_object(struct kmem_cache *s)
559 return s->offset >= s->inuse;
563 * Return offset of the end of info block which is inuse + free pointer if
564 * not overlapping with object.
566 static inline unsigned int get_info_end(struct kmem_cache *s)
568 if (freeptr_outside_object(s))
569 return s->inuse + sizeof(void *);
570 else
571 return s->inuse;
574 static struct track *get_track(struct kmem_cache *s, void *object,
575 enum track_item alloc)
577 struct track *p;
579 p = object + get_info_end(s);
581 return p + alloc;
584 static void set_track(struct kmem_cache *s, void *object,
585 enum track_item alloc, unsigned long addr)
587 struct track *p = get_track(s, object, alloc);
589 if (addr) {
590 #ifdef CONFIG_STACKTRACE
591 unsigned int nr_entries;
593 metadata_access_enable();
594 nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
595 metadata_access_disable();
597 if (nr_entries < TRACK_ADDRS_COUNT)
598 p->addrs[nr_entries] = 0;
599 #endif
600 p->addr = addr;
601 p->cpu = smp_processor_id();
602 p->pid = current->pid;
603 p->when = jiffies;
604 } else {
605 memset(p, 0, sizeof(struct track));
609 static void init_tracking(struct kmem_cache *s, void *object)
611 if (!(s->flags & SLAB_STORE_USER))
612 return;
614 set_track(s, object, TRACK_FREE, 0UL);
615 set_track(s, object, TRACK_ALLOC, 0UL);
618 static void print_track(const char *s, struct track *t, unsigned long pr_time)
620 if (!t->addr)
621 return;
623 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
624 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
625 #ifdef CONFIG_STACKTRACE
627 int i;
628 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
629 if (t->addrs[i])
630 pr_err("\t%pS\n", (void *)t->addrs[i]);
631 else
632 break;
634 #endif
637 static void print_tracking(struct kmem_cache *s, void *object)
639 unsigned long pr_time = jiffies;
640 if (!(s->flags & SLAB_STORE_USER))
641 return;
643 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
644 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
647 static void print_page_info(struct page *page)
649 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
650 page, page->objects, page->inuse, page->freelist, page->flags);
654 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
656 struct va_format vaf;
657 va_list args;
659 va_start(args, fmt);
660 vaf.fmt = fmt;
661 vaf.va = &args;
662 pr_err("=============================================================================\n");
663 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
664 pr_err("-----------------------------------------------------------------------------\n\n");
666 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
667 va_end(args);
670 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
672 struct va_format vaf;
673 va_list args;
675 va_start(args, fmt);
676 vaf.fmt = fmt;
677 vaf.va = &args;
678 pr_err("FIX %s: %pV\n", s->name, &vaf);
679 va_end(args);
682 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
684 unsigned int off; /* Offset of last byte */
685 u8 *addr = page_address(page);
687 print_tracking(s, p);
689 print_page_info(page);
691 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
692 p, p - addr, get_freepointer(s, p));
694 if (s->flags & SLAB_RED_ZONE)
695 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
696 s->red_left_pad);
697 else if (p > addr + 16)
698 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
700 print_section(KERN_ERR, "Object ", p,
701 min_t(unsigned int, s->object_size, PAGE_SIZE));
702 if (s->flags & SLAB_RED_ZONE)
703 print_section(KERN_ERR, "Redzone ", p + s->object_size,
704 s->inuse - s->object_size);
706 off = get_info_end(s);
708 if (s->flags & SLAB_STORE_USER)
709 off += 2 * sizeof(struct track);
711 off += kasan_metadata_size(s);
713 if (off != size_from_object(s))
714 /* Beginning of the filler is the free pointer */
715 print_section(KERN_ERR, "Padding ", p + off,
716 size_from_object(s) - off);
718 dump_stack();
721 void object_err(struct kmem_cache *s, struct page *page,
722 u8 *object, char *reason)
724 slab_bug(s, "%s", reason);
725 print_trailer(s, page, object);
728 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
729 const char *fmt, ...)
731 va_list args;
732 char buf[100];
734 va_start(args, fmt);
735 vsnprintf(buf, sizeof(buf), fmt, args);
736 va_end(args);
737 slab_bug(s, "%s", buf);
738 print_page_info(page);
739 dump_stack();
742 static void init_object(struct kmem_cache *s, void *object, u8 val)
744 u8 *p = object;
746 if (s->flags & SLAB_RED_ZONE)
747 memset(p - s->red_left_pad, val, s->red_left_pad);
749 if (s->flags & __OBJECT_POISON) {
750 memset(p, POISON_FREE, s->object_size - 1);
751 p[s->object_size - 1] = POISON_END;
754 if (s->flags & SLAB_RED_ZONE)
755 memset(p + s->object_size, val, s->inuse - s->object_size);
758 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
759 void *from, void *to)
761 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
762 memset(from, data, to - from);
765 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
766 u8 *object, char *what,
767 u8 *start, unsigned int value, unsigned int bytes)
769 u8 *fault;
770 u8 *end;
771 u8 *addr = page_address(page);
773 metadata_access_enable();
774 fault = memchr_inv(start, value, bytes);
775 metadata_access_disable();
776 if (!fault)
777 return 1;
779 end = start + bytes;
780 while (end > fault && end[-1] == value)
781 end--;
783 slab_bug(s, "%s overwritten", what);
784 pr_err("INFO: 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
785 fault, end - 1, fault - addr,
786 fault[0], value);
787 print_trailer(s, page, object);
789 restore_bytes(s, what, value, fault, end);
790 return 0;
794 * Object layout:
796 * object address
797 * Bytes of the object to be managed.
798 * If the freepointer may overlay the object then the free
799 * pointer is at the middle of the object.
801 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
802 * 0xa5 (POISON_END)
804 * object + s->object_size
805 * Padding to reach word boundary. This is also used for Redzoning.
806 * Padding is extended by another word if Redzoning is enabled and
807 * object_size == inuse.
809 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
810 * 0xcc (RED_ACTIVE) for objects in use.
812 * object + s->inuse
813 * Meta data starts here.
815 * A. Free pointer (if we cannot overwrite object on free)
816 * B. Tracking data for SLAB_STORE_USER
817 * C. Padding to reach required alignment boundary or at mininum
818 * one word if debugging is on to be able to detect writes
819 * before the word boundary.
821 * Padding is done using 0x5a (POISON_INUSE)
823 * object + s->size
824 * Nothing is used beyond s->size.
826 * If slabcaches are merged then the object_size and inuse boundaries are mostly
827 * ignored. And therefore no slab options that rely on these boundaries
828 * may be used with merged slabcaches.
831 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
833 unsigned long off = get_info_end(s); /* The end of info */
835 if (s->flags & SLAB_STORE_USER)
836 /* We also have user information there */
837 off += 2 * sizeof(struct track);
839 off += kasan_metadata_size(s);
841 if (size_from_object(s) == off)
842 return 1;
844 return check_bytes_and_report(s, page, p, "Object padding",
845 p + off, POISON_INUSE, size_from_object(s) - off);
848 /* Check the pad bytes at the end of a slab page */
849 static int slab_pad_check(struct kmem_cache *s, struct page *page)
851 u8 *start;
852 u8 *fault;
853 u8 *end;
854 u8 *pad;
855 int length;
856 int remainder;
858 if (!(s->flags & SLAB_POISON))
859 return 1;
861 start = page_address(page);
862 length = page_size(page);
863 end = start + length;
864 remainder = length % s->size;
865 if (!remainder)
866 return 1;
868 pad = end - remainder;
869 metadata_access_enable();
870 fault = memchr_inv(pad, POISON_INUSE, remainder);
871 metadata_access_disable();
872 if (!fault)
873 return 1;
874 while (end > fault && end[-1] == POISON_INUSE)
875 end--;
877 slab_err(s, page, "Padding overwritten. 0x%p-0x%p @offset=%tu",
878 fault, end - 1, fault - start);
879 print_section(KERN_ERR, "Padding ", pad, remainder);
881 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
882 return 0;
885 static int check_object(struct kmem_cache *s, struct page *page,
886 void *object, u8 val)
888 u8 *p = object;
889 u8 *endobject = object + s->object_size;
891 if (s->flags & SLAB_RED_ZONE) {
892 if (!check_bytes_and_report(s, page, object, "Redzone",
893 object - s->red_left_pad, val, s->red_left_pad))
894 return 0;
896 if (!check_bytes_and_report(s, page, object, "Redzone",
897 endobject, val, s->inuse - s->object_size))
898 return 0;
899 } else {
900 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
901 check_bytes_and_report(s, page, p, "Alignment padding",
902 endobject, POISON_INUSE,
903 s->inuse - s->object_size);
907 if (s->flags & SLAB_POISON) {
908 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
909 (!check_bytes_and_report(s, page, p, "Poison", p,
910 POISON_FREE, s->object_size - 1) ||
911 !check_bytes_and_report(s, page, p, "Poison",
912 p + s->object_size - 1, POISON_END, 1)))
913 return 0;
915 * check_pad_bytes cleans up on its own.
917 check_pad_bytes(s, page, p);
920 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
922 * Object and freepointer overlap. Cannot check
923 * freepointer while object is allocated.
925 return 1;
927 /* Check free pointer validity */
928 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
929 object_err(s, page, p, "Freepointer corrupt");
931 * No choice but to zap it and thus lose the remainder
932 * of the free objects in this slab. May cause
933 * another error because the object count is now wrong.
935 set_freepointer(s, p, NULL);
936 return 0;
938 return 1;
941 static int check_slab(struct kmem_cache *s, struct page *page)
943 int maxobj;
945 VM_BUG_ON(!irqs_disabled());
947 if (!PageSlab(page)) {
948 slab_err(s, page, "Not a valid slab page");
949 return 0;
952 maxobj = order_objects(compound_order(page), s->size);
953 if (page->objects > maxobj) {
954 slab_err(s, page, "objects %u > max %u",
955 page->objects, maxobj);
956 return 0;
958 if (page->inuse > page->objects) {
959 slab_err(s, page, "inuse %u > max %u",
960 page->inuse, page->objects);
961 return 0;
963 /* Slab_pad_check fixes things up after itself */
964 slab_pad_check(s, page);
965 return 1;
969 * Determine if a certain object on a page is on the freelist. Must hold the
970 * slab lock to guarantee that the chains are in a consistent state.
972 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
974 int nr = 0;
975 void *fp;
976 void *object = NULL;
977 int max_objects;
979 fp = page->freelist;
980 while (fp && nr <= page->objects) {
981 if (fp == search)
982 return 1;
983 if (!check_valid_pointer(s, page, fp)) {
984 if (object) {
985 object_err(s, page, object,
986 "Freechain corrupt");
987 set_freepointer(s, object, NULL);
988 } else {
989 slab_err(s, page, "Freepointer corrupt");
990 page->freelist = NULL;
991 page->inuse = page->objects;
992 slab_fix(s, "Freelist cleared");
993 return 0;
995 break;
997 object = fp;
998 fp = get_freepointer(s, object);
999 nr++;
1002 max_objects = order_objects(compound_order(page), s->size);
1003 if (max_objects > MAX_OBJS_PER_PAGE)
1004 max_objects = MAX_OBJS_PER_PAGE;
1006 if (page->objects != max_objects) {
1007 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1008 page->objects, max_objects);
1009 page->objects = max_objects;
1010 slab_fix(s, "Number of objects adjusted.");
1012 if (page->inuse != page->objects - nr) {
1013 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1014 page->inuse, page->objects - nr);
1015 page->inuse = page->objects - nr;
1016 slab_fix(s, "Object count adjusted.");
1018 return search == NULL;
1021 static void trace(struct kmem_cache *s, struct page *page, void *object,
1022 int alloc)
1024 if (s->flags & SLAB_TRACE) {
1025 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1026 s->name,
1027 alloc ? "alloc" : "free",
1028 object, page->inuse,
1029 page->freelist);
1031 if (!alloc)
1032 print_section(KERN_INFO, "Object ", (void *)object,
1033 s->object_size);
1035 dump_stack();
1040 * Tracking of fully allocated slabs for debugging purposes.
1042 static void add_full(struct kmem_cache *s,
1043 struct kmem_cache_node *n, struct page *page)
1045 if (!(s->flags & SLAB_STORE_USER))
1046 return;
1048 lockdep_assert_held(&n->list_lock);
1049 list_add(&page->slab_list, &n->full);
1052 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1054 if (!(s->flags & SLAB_STORE_USER))
1055 return;
1057 lockdep_assert_held(&n->list_lock);
1058 list_del(&page->slab_list);
1061 /* Tracking of the number of slabs for debugging purposes */
1062 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1064 struct kmem_cache_node *n = get_node(s, node);
1066 return atomic_long_read(&n->nr_slabs);
1069 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1071 return atomic_long_read(&n->nr_slabs);
1074 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1076 struct kmem_cache_node *n = get_node(s, node);
1079 * May be called early in order to allocate a slab for the
1080 * kmem_cache_node structure. Solve the chicken-egg
1081 * dilemma by deferring the increment of the count during
1082 * bootstrap (see early_kmem_cache_node_alloc).
1084 if (likely(n)) {
1085 atomic_long_inc(&n->nr_slabs);
1086 atomic_long_add(objects, &n->total_objects);
1089 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1091 struct kmem_cache_node *n = get_node(s, node);
1093 atomic_long_dec(&n->nr_slabs);
1094 atomic_long_sub(objects, &n->total_objects);
1097 /* Object debug checks for alloc/free paths */
1098 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1099 void *object)
1101 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1102 return;
1104 init_object(s, object, SLUB_RED_INACTIVE);
1105 init_tracking(s, object);
1108 static
1109 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1111 if (!(s->flags & SLAB_POISON))
1112 return;
1114 metadata_access_enable();
1115 memset(addr, POISON_INUSE, page_size(page));
1116 metadata_access_disable();
1119 static inline int alloc_consistency_checks(struct kmem_cache *s,
1120 struct page *page, void *object)
1122 if (!check_slab(s, page))
1123 return 0;
1125 if (!check_valid_pointer(s, page, object)) {
1126 object_err(s, page, object, "Freelist Pointer check fails");
1127 return 0;
1130 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1131 return 0;
1133 return 1;
1136 static noinline int alloc_debug_processing(struct kmem_cache *s,
1137 struct page *page,
1138 void *object, unsigned long addr)
1140 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1141 if (!alloc_consistency_checks(s, page, object))
1142 goto bad;
1145 /* Success perform special debug activities for allocs */
1146 if (s->flags & SLAB_STORE_USER)
1147 set_track(s, object, TRACK_ALLOC, addr);
1148 trace(s, page, object, 1);
1149 init_object(s, object, SLUB_RED_ACTIVE);
1150 return 1;
1152 bad:
1153 if (PageSlab(page)) {
1155 * If this is a slab page then lets do the best we can
1156 * to avoid issues in the future. Marking all objects
1157 * as used avoids touching the remaining objects.
1159 slab_fix(s, "Marking all objects used");
1160 page->inuse = page->objects;
1161 page->freelist = NULL;
1163 return 0;
1166 static inline int free_consistency_checks(struct kmem_cache *s,
1167 struct page *page, void *object, unsigned long addr)
1169 if (!check_valid_pointer(s, page, object)) {
1170 slab_err(s, page, "Invalid object pointer 0x%p", object);
1171 return 0;
1174 if (on_freelist(s, page, object)) {
1175 object_err(s, page, object, "Object already free");
1176 return 0;
1179 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1180 return 0;
1182 if (unlikely(s != page->slab_cache)) {
1183 if (!PageSlab(page)) {
1184 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1185 object);
1186 } else if (!page->slab_cache) {
1187 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1188 object);
1189 dump_stack();
1190 } else
1191 object_err(s, page, object,
1192 "page slab pointer corrupt.");
1193 return 0;
1195 return 1;
1198 /* Supports checking bulk free of a constructed freelist */
1199 static noinline int free_debug_processing(
1200 struct kmem_cache *s, struct page *page,
1201 void *head, void *tail, int bulk_cnt,
1202 unsigned long addr)
1204 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1205 void *object = head;
1206 int cnt = 0;
1207 unsigned long uninitialized_var(flags);
1208 int ret = 0;
1210 spin_lock_irqsave(&n->list_lock, flags);
1211 slab_lock(page);
1213 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1214 if (!check_slab(s, page))
1215 goto out;
1218 next_object:
1219 cnt++;
1221 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1222 if (!free_consistency_checks(s, page, object, addr))
1223 goto out;
1226 if (s->flags & SLAB_STORE_USER)
1227 set_track(s, object, TRACK_FREE, addr);
1228 trace(s, page, object, 0);
1229 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1230 init_object(s, object, SLUB_RED_INACTIVE);
1232 /* Reached end of constructed freelist yet? */
1233 if (object != tail) {
1234 object = get_freepointer(s, object);
1235 goto next_object;
1237 ret = 1;
1239 out:
1240 if (cnt != bulk_cnt)
1241 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1242 bulk_cnt, cnt);
1244 slab_unlock(page);
1245 spin_unlock_irqrestore(&n->list_lock, flags);
1246 if (!ret)
1247 slab_fix(s, "Object at 0x%p not freed", object);
1248 return ret;
1251 static int __init setup_slub_debug(char *str)
1253 slub_debug = DEBUG_DEFAULT_FLAGS;
1254 if (*str++ != '=' || !*str)
1256 * No options specified. Switch on full debugging.
1258 goto out;
1260 if (*str == ',')
1262 * No options but restriction on slabs. This means full
1263 * debugging for slabs matching a pattern.
1265 goto check_slabs;
1267 slub_debug = 0;
1268 if (*str == '-')
1270 * Switch off all debugging measures.
1272 goto out;
1275 * Determine which debug features should be switched on
1277 for (; *str && *str != ','; str++) {
1278 switch (tolower(*str)) {
1279 case 'f':
1280 slub_debug |= SLAB_CONSISTENCY_CHECKS;
1281 break;
1282 case 'z':
1283 slub_debug |= SLAB_RED_ZONE;
1284 break;
1285 case 'p':
1286 slub_debug |= SLAB_POISON;
1287 break;
1288 case 'u':
1289 slub_debug |= SLAB_STORE_USER;
1290 break;
1291 case 't':
1292 slub_debug |= SLAB_TRACE;
1293 break;
1294 case 'a':
1295 slub_debug |= SLAB_FAILSLAB;
1296 break;
1297 case 'o':
1299 * Avoid enabling debugging on caches if its minimum
1300 * order would increase as a result.
1302 disable_higher_order_debug = 1;
1303 break;
1304 default:
1305 pr_err("slub_debug option '%c' unknown. skipped\n",
1306 *str);
1310 check_slabs:
1311 if (*str == ',')
1312 slub_debug_slabs = str + 1;
1313 out:
1314 if ((static_branch_unlikely(&init_on_alloc) ||
1315 static_branch_unlikely(&init_on_free)) &&
1316 (slub_debug & SLAB_POISON))
1317 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1318 return 1;
1321 __setup("slub_debug", setup_slub_debug);
1324 * kmem_cache_flags - apply debugging options to the cache
1325 * @object_size: the size of an object without meta data
1326 * @flags: flags to set
1327 * @name: name of the cache
1328 * @ctor: constructor function
1330 * Debug option(s) are applied to @flags. In addition to the debug
1331 * option(s), if a slab name (or multiple) is specified i.e.
1332 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1333 * then only the select slabs will receive the debug option(s).
1335 slab_flags_t kmem_cache_flags(unsigned int object_size,
1336 slab_flags_t flags, const char *name,
1337 void (*ctor)(void *))
1339 char *iter;
1340 size_t len;
1342 /* If slub_debug = 0, it folds into the if conditional. */
1343 if (!slub_debug_slabs)
1344 return flags | slub_debug;
1346 len = strlen(name);
1347 iter = slub_debug_slabs;
1348 while (*iter) {
1349 char *end, *glob;
1350 size_t cmplen;
1352 end = strchrnul(iter, ',');
1354 glob = strnchr(iter, end - iter, '*');
1355 if (glob)
1356 cmplen = glob - iter;
1357 else
1358 cmplen = max_t(size_t, len, (end - iter));
1360 if (!strncmp(name, iter, cmplen)) {
1361 flags |= slub_debug;
1362 break;
1365 if (!*end)
1366 break;
1367 iter = end + 1;
1370 return flags;
1372 #else /* !CONFIG_SLUB_DEBUG */
1373 static inline void setup_object_debug(struct kmem_cache *s,
1374 struct page *page, void *object) {}
1375 static inline
1376 void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
1378 static inline int alloc_debug_processing(struct kmem_cache *s,
1379 struct page *page, void *object, unsigned long addr) { return 0; }
1381 static inline int free_debug_processing(
1382 struct kmem_cache *s, struct page *page,
1383 void *head, void *tail, int bulk_cnt,
1384 unsigned long addr) { return 0; }
1386 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1387 { return 1; }
1388 static inline int check_object(struct kmem_cache *s, struct page *page,
1389 void *object, u8 val) { return 1; }
1390 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1391 struct page *page) {}
1392 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1393 struct page *page) {}
1394 slab_flags_t kmem_cache_flags(unsigned int object_size,
1395 slab_flags_t flags, const char *name,
1396 void (*ctor)(void *))
1398 return flags;
1400 #define slub_debug 0
1402 #define disable_higher_order_debug 0
1404 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1405 { return 0; }
1406 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1407 { return 0; }
1408 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1409 int objects) {}
1410 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1411 int objects) {}
1413 #endif /* CONFIG_SLUB_DEBUG */
1416 * Hooks for other subsystems that check memory allocations. In a typical
1417 * production configuration these hooks all should produce no code at all.
1419 static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
1421 ptr = kasan_kmalloc_large(ptr, size, flags);
1422 /* As ptr might get tagged, call kmemleak hook after KASAN. */
1423 kmemleak_alloc(ptr, size, 1, flags);
1424 return ptr;
1427 static __always_inline void kfree_hook(void *x)
1429 kmemleak_free(x);
1430 kasan_kfree_large(x, _RET_IP_);
1433 static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x)
1435 kmemleak_free_recursive(x, s->flags);
1438 * Trouble is that we may no longer disable interrupts in the fast path
1439 * So in order to make the debug calls that expect irqs to be
1440 * disabled we need to disable interrupts temporarily.
1442 #ifdef CONFIG_LOCKDEP
1444 unsigned long flags;
1446 local_irq_save(flags);
1447 debug_check_no_locks_freed(x, s->object_size);
1448 local_irq_restore(flags);
1450 #endif
1451 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1452 debug_check_no_obj_freed(x, s->object_size);
1454 /* KASAN might put x into memory quarantine, delaying its reuse */
1455 return kasan_slab_free(s, x, _RET_IP_);
1458 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1459 void **head, void **tail)
1462 void *object;
1463 void *next = *head;
1464 void *old_tail = *tail ? *tail : *head;
1465 int rsize;
1467 /* Head and tail of the reconstructed freelist */
1468 *head = NULL;
1469 *tail = NULL;
1471 do {
1472 object = next;
1473 next = get_freepointer(s, object);
1475 if (slab_want_init_on_free(s)) {
1477 * Clear the object and the metadata, but don't touch
1478 * the redzone.
1480 memset(object, 0, s->object_size);
1481 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad
1482 : 0;
1483 memset((char *)object + s->inuse, 0,
1484 s->size - s->inuse - rsize);
1487 /* If object's reuse doesn't have to be delayed */
1488 if (!slab_free_hook(s, object)) {
1489 /* Move object to the new freelist */
1490 set_freepointer(s, object, *head);
1491 *head = object;
1492 if (!*tail)
1493 *tail = object;
1495 } while (object != old_tail);
1497 if (*head == *tail)
1498 *tail = NULL;
1500 return *head != NULL;
1503 static void *setup_object(struct kmem_cache *s, struct page *page,
1504 void *object)
1506 setup_object_debug(s, page, object);
1507 object = kasan_init_slab_obj(s, object);
1508 if (unlikely(s->ctor)) {
1509 kasan_unpoison_object_data(s, object);
1510 s->ctor(object);
1511 kasan_poison_object_data(s, object);
1513 return object;
1517 * Slab allocation and freeing
1519 static inline struct page *alloc_slab_page(struct kmem_cache *s,
1520 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1522 struct page *page;
1523 unsigned int order = oo_order(oo);
1525 if (node == NUMA_NO_NODE)
1526 page = alloc_pages(flags, order);
1527 else
1528 page = __alloc_pages_node(node, flags, order);
1530 if (page && charge_slab_page(page, flags, order, s)) {
1531 __free_pages(page, order);
1532 page = NULL;
1535 return page;
1538 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1539 /* Pre-initialize the random sequence cache */
1540 static int init_cache_random_seq(struct kmem_cache *s)
1542 unsigned int count = oo_objects(s->oo);
1543 int err;
1545 /* Bailout if already initialised */
1546 if (s->random_seq)
1547 return 0;
1549 err = cache_random_seq_create(s, count, GFP_KERNEL);
1550 if (err) {
1551 pr_err("SLUB: Unable to initialize free list for %s\n",
1552 s->name);
1553 return err;
1556 /* Transform to an offset on the set of pages */
1557 if (s->random_seq) {
1558 unsigned int i;
1560 for (i = 0; i < count; i++)
1561 s->random_seq[i] *= s->size;
1563 return 0;
1566 /* Initialize each random sequence freelist per cache */
1567 static void __init init_freelist_randomization(void)
1569 struct kmem_cache *s;
1571 mutex_lock(&slab_mutex);
1573 list_for_each_entry(s, &slab_caches, list)
1574 init_cache_random_seq(s);
1576 mutex_unlock(&slab_mutex);
1579 /* Get the next entry on the pre-computed freelist randomized */
1580 static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1581 unsigned long *pos, void *start,
1582 unsigned long page_limit,
1583 unsigned long freelist_count)
1585 unsigned int idx;
1588 * If the target page allocation failed, the number of objects on the
1589 * page might be smaller than the usual size defined by the cache.
1591 do {
1592 idx = s->random_seq[*pos];
1593 *pos += 1;
1594 if (*pos >= freelist_count)
1595 *pos = 0;
1596 } while (unlikely(idx >= page_limit));
1598 return (char *)start + idx;
1601 /* Shuffle the single linked freelist based on a random pre-computed sequence */
1602 static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1604 void *start;
1605 void *cur;
1606 void *next;
1607 unsigned long idx, pos, page_limit, freelist_count;
1609 if (page->objects < 2 || !s->random_seq)
1610 return false;
1612 freelist_count = oo_objects(s->oo);
1613 pos = get_random_int() % freelist_count;
1615 page_limit = page->objects * s->size;
1616 start = fixup_red_left(s, page_address(page));
1618 /* First entry is used as the base of the freelist */
1619 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1620 freelist_count);
1621 cur = setup_object(s, page, cur);
1622 page->freelist = cur;
1624 for (idx = 1; idx < page->objects; idx++) {
1625 next = next_freelist_entry(s, page, &pos, start, page_limit,
1626 freelist_count);
1627 next = setup_object(s, page, next);
1628 set_freepointer(s, cur, next);
1629 cur = next;
1631 set_freepointer(s, cur, NULL);
1633 return true;
1635 #else
1636 static inline int init_cache_random_seq(struct kmem_cache *s)
1638 return 0;
1640 static inline void init_freelist_randomization(void) { }
1641 static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1643 return false;
1645 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1647 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1649 struct page *page;
1650 struct kmem_cache_order_objects oo = s->oo;
1651 gfp_t alloc_gfp;
1652 void *start, *p, *next;
1653 int idx;
1654 bool shuffle;
1656 flags &= gfp_allowed_mask;
1658 if (gfpflags_allow_blocking(flags))
1659 local_irq_enable();
1661 flags |= s->allocflags;
1664 * Let the initial higher-order allocation fail under memory pressure
1665 * so we fall-back to the minimum order allocation.
1667 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1668 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1669 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1671 page = alloc_slab_page(s, alloc_gfp, node, oo);
1672 if (unlikely(!page)) {
1673 oo = s->min;
1674 alloc_gfp = flags;
1676 * Allocation may have failed due to fragmentation.
1677 * Try a lower order alloc if possible
1679 page = alloc_slab_page(s, alloc_gfp, node, oo);
1680 if (unlikely(!page))
1681 goto out;
1682 stat(s, ORDER_FALLBACK);
1685 page->objects = oo_objects(oo);
1687 page->slab_cache = s;
1688 __SetPageSlab(page);
1689 if (page_is_pfmemalloc(page))
1690 SetPageSlabPfmemalloc(page);
1692 kasan_poison_slab(page);
1694 start = page_address(page);
1696 setup_page_debug(s, page, start);
1698 shuffle = shuffle_freelist(s, page);
1700 if (!shuffle) {
1701 start = fixup_red_left(s, start);
1702 start = setup_object(s, page, start);
1703 page->freelist = start;
1704 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1705 next = p + s->size;
1706 next = setup_object(s, page, next);
1707 set_freepointer(s, p, next);
1708 p = next;
1710 set_freepointer(s, p, NULL);
1713 page->inuse = page->objects;
1714 page->frozen = 1;
1716 out:
1717 if (gfpflags_allow_blocking(flags))
1718 local_irq_disable();
1719 if (!page)
1720 return NULL;
1722 inc_slabs_node(s, page_to_nid(page), page->objects);
1724 return page;
1727 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1729 if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
1730 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
1731 flags &= ~GFP_SLAB_BUG_MASK;
1732 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
1733 invalid_mask, &invalid_mask, flags, &flags);
1734 dump_stack();
1737 return allocate_slab(s,
1738 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1741 static void __free_slab(struct kmem_cache *s, struct page *page)
1743 int order = compound_order(page);
1744 int pages = 1 << order;
1746 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1747 void *p;
1749 slab_pad_check(s, page);
1750 for_each_object(p, s, page_address(page),
1751 page->objects)
1752 check_object(s, page, p, SLUB_RED_INACTIVE);
1755 __ClearPageSlabPfmemalloc(page);
1756 __ClearPageSlab(page);
1758 page->mapping = NULL;
1759 if (current->reclaim_state)
1760 current->reclaim_state->reclaimed_slab += pages;
1761 uncharge_slab_page(page, order, s);
1762 __free_pages(page, order);
1765 static void rcu_free_slab(struct rcu_head *h)
1767 struct page *page = container_of(h, struct page, rcu_head);
1769 __free_slab(page->slab_cache, page);
1772 static void free_slab(struct kmem_cache *s, struct page *page)
1774 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1775 call_rcu(&page->rcu_head, rcu_free_slab);
1776 } else
1777 __free_slab(s, page);
1780 static void discard_slab(struct kmem_cache *s, struct page *page)
1782 dec_slabs_node(s, page_to_nid(page), page->objects);
1783 free_slab(s, page);
1787 * Management of partially allocated slabs.
1789 static inline void
1790 __add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1792 n->nr_partial++;
1793 if (tail == DEACTIVATE_TO_TAIL)
1794 list_add_tail(&page->slab_list, &n->partial);
1795 else
1796 list_add(&page->slab_list, &n->partial);
1799 static inline void add_partial(struct kmem_cache_node *n,
1800 struct page *page, int tail)
1802 lockdep_assert_held(&n->list_lock);
1803 __add_partial(n, page, tail);
1806 static inline void remove_partial(struct kmem_cache_node *n,
1807 struct page *page)
1809 lockdep_assert_held(&n->list_lock);
1810 list_del(&page->slab_list);
1811 n->nr_partial--;
1815 * Remove slab from the partial list, freeze it and
1816 * return the pointer to the freelist.
1818 * Returns a list of objects or NULL if it fails.
1820 static inline void *acquire_slab(struct kmem_cache *s,
1821 struct kmem_cache_node *n, struct page *page,
1822 int mode, int *objects)
1824 void *freelist;
1825 unsigned long counters;
1826 struct page new;
1828 lockdep_assert_held(&n->list_lock);
1831 * Zap the freelist and set the frozen bit.
1832 * The old freelist is the list of objects for the
1833 * per cpu allocation list.
1835 freelist = page->freelist;
1836 counters = page->counters;
1837 new.counters = counters;
1838 *objects = new.objects - new.inuse;
1839 if (mode) {
1840 new.inuse = page->objects;
1841 new.freelist = NULL;
1842 } else {
1843 new.freelist = freelist;
1846 VM_BUG_ON(new.frozen);
1847 new.frozen = 1;
1849 if (!__cmpxchg_double_slab(s, page,
1850 freelist, counters,
1851 new.freelist, new.counters,
1852 "acquire_slab"))
1853 return NULL;
1855 remove_partial(n, page);
1856 WARN_ON(!freelist);
1857 return freelist;
1860 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1861 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1864 * Try to allocate a partial slab from a specific node.
1866 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1867 struct kmem_cache_cpu *c, gfp_t flags)
1869 struct page *page, *page2;
1870 void *object = NULL;
1871 unsigned int available = 0;
1872 int objects;
1875 * Racy check. If we mistakenly see no partial slabs then we
1876 * just allocate an empty slab. If we mistakenly try to get a
1877 * partial slab and there is none available then get_partials()
1878 * will return NULL.
1880 if (!n || !n->nr_partial)
1881 return NULL;
1883 spin_lock(&n->list_lock);
1884 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
1885 void *t;
1887 if (!pfmemalloc_match(page, flags))
1888 continue;
1890 t = acquire_slab(s, n, page, object == NULL, &objects);
1891 if (!t)
1892 break;
1894 available += objects;
1895 if (!object) {
1896 c->page = page;
1897 stat(s, ALLOC_FROM_PARTIAL);
1898 object = t;
1899 } else {
1900 put_cpu_partial(s, page, 0);
1901 stat(s, CPU_PARTIAL_NODE);
1903 if (!kmem_cache_has_cpu_partial(s)
1904 || available > slub_cpu_partial(s) / 2)
1905 break;
1908 spin_unlock(&n->list_lock);
1909 return object;
1913 * Get a page from somewhere. Search in increasing NUMA distances.
1915 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1916 struct kmem_cache_cpu *c)
1918 #ifdef CONFIG_NUMA
1919 struct zonelist *zonelist;
1920 struct zoneref *z;
1921 struct zone *zone;
1922 enum zone_type high_zoneidx = gfp_zone(flags);
1923 void *object;
1924 unsigned int cpuset_mems_cookie;
1927 * The defrag ratio allows a configuration of the tradeoffs between
1928 * inter node defragmentation and node local allocations. A lower
1929 * defrag_ratio increases the tendency to do local allocations
1930 * instead of attempting to obtain partial slabs from other nodes.
1932 * If the defrag_ratio is set to 0 then kmalloc() always
1933 * returns node local objects. If the ratio is higher then kmalloc()
1934 * may return off node objects because partial slabs are obtained
1935 * from other nodes and filled up.
1937 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
1938 * (which makes defrag_ratio = 1000) then every (well almost)
1939 * allocation will first attempt to defrag slab caches on other nodes.
1940 * This means scanning over all nodes to look for partial slabs which
1941 * may be expensive if we do it every time we are trying to find a slab
1942 * with available objects.
1944 if (!s->remote_node_defrag_ratio ||
1945 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1946 return NULL;
1948 do {
1949 cpuset_mems_cookie = read_mems_allowed_begin();
1950 zonelist = node_zonelist(mempolicy_slab_node(), flags);
1951 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1952 struct kmem_cache_node *n;
1954 n = get_node(s, zone_to_nid(zone));
1956 if (n && cpuset_zone_allowed(zone, flags) &&
1957 n->nr_partial > s->min_partial) {
1958 object = get_partial_node(s, n, c, flags);
1959 if (object) {
1961 * Don't check read_mems_allowed_retry()
1962 * here - if mems_allowed was updated in
1963 * parallel, that was a harmless race
1964 * between allocation and the cpuset
1965 * update
1967 return object;
1971 } while (read_mems_allowed_retry(cpuset_mems_cookie));
1972 #endif /* CONFIG_NUMA */
1973 return NULL;
1977 * Get a partial page, lock it and return it.
1979 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1980 struct kmem_cache_cpu *c)
1982 void *object;
1983 int searchnode = node;
1985 if (node == NUMA_NO_NODE)
1986 searchnode = numa_mem_id();
1988 object = get_partial_node(s, get_node(s, searchnode), c, flags);
1989 if (object || node != NUMA_NO_NODE)
1990 return object;
1992 return get_any_partial(s, flags, c);
1995 #ifdef CONFIG_PREEMPTION
1997 * Calculate the next globally unique transaction for disambiguiation
1998 * during cmpxchg. The transactions start with the cpu number and are then
1999 * incremented by CONFIG_NR_CPUS.
2001 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2002 #else
2004 * No preemption supported therefore also no need to check for
2005 * different cpus.
2007 #define TID_STEP 1
2008 #endif
2010 static inline unsigned long next_tid(unsigned long tid)
2012 return tid + TID_STEP;
2015 #ifdef SLUB_DEBUG_CMPXCHG
2016 static inline unsigned int tid_to_cpu(unsigned long tid)
2018 return tid % TID_STEP;
2021 static inline unsigned long tid_to_event(unsigned long tid)
2023 return tid / TID_STEP;
2025 #endif
2027 static inline unsigned int init_tid(int cpu)
2029 return cpu;
2032 static inline void note_cmpxchg_failure(const char *n,
2033 const struct kmem_cache *s, unsigned long tid)
2035 #ifdef SLUB_DEBUG_CMPXCHG
2036 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2038 pr_info("%s %s: cmpxchg redo ", n, s->name);
2040 #ifdef CONFIG_PREEMPTION
2041 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2042 pr_warn("due to cpu change %d -> %d\n",
2043 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2044 else
2045 #endif
2046 if (tid_to_event(tid) != tid_to_event(actual_tid))
2047 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2048 tid_to_event(tid), tid_to_event(actual_tid));
2049 else
2050 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2051 actual_tid, tid, next_tid(tid));
2052 #endif
2053 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2056 static void init_kmem_cache_cpus(struct kmem_cache *s)
2058 int cpu;
2060 for_each_possible_cpu(cpu)
2061 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2065 * Remove the cpu slab
2067 static void deactivate_slab(struct kmem_cache *s, struct page *page,
2068 void *freelist, struct kmem_cache_cpu *c)
2070 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2071 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2072 int lock = 0;
2073 enum slab_modes l = M_NONE, m = M_NONE;
2074 void *nextfree;
2075 int tail = DEACTIVATE_TO_HEAD;
2076 struct page new;
2077 struct page old;
2079 if (page->freelist) {
2080 stat(s, DEACTIVATE_REMOTE_FREES);
2081 tail = DEACTIVATE_TO_TAIL;
2085 * Stage one: Free all available per cpu objects back
2086 * to the page freelist while it is still frozen. Leave the
2087 * last one.
2089 * There is no need to take the list->lock because the page
2090 * is still frozen.
2092 while (freelist && (nextfree = get_freepointer(s, freelist))) {
2093 void *prior;
2094 unsigned long counters;
2096 do {
2097 prior = page->freelist;
2098 counters = page->counters;
2099 set_freepointer(s, freelist, prior);
2100 new.counters = counters;
2101 new.inuse--;
2102 VM_BUG_ON(!new.frozen);
2104 } while (!__cmpxchg_double_slab(s, page,
2105 prior, counters,
2106 freelist, new.counters,
2107 "drain percpu freelist"));
2109 freelist = nextfree;
2113 * Stage two: Ensure that the page is unfrozen while the
2114 * list presence reflects the actual number of objects
2115 * during unfreeze.
2117 * We setup the list membership and then perform a cmpxchg
2118 * with the count. If there is a mismatch then the page
2119 * is not unfrozen but the page is on the wrong list.
2121 * Then we restart the process which may have to remove
2122 * the page from the list that we just put it on again
2123 * because the number of objects in the slab may have
2124 * changed.
2126 redo:
2128 old.freelist = page->freelist;
2129 old.counters = page->counters;
2130 VM_BUG_ON(!old.frozen);
2132 /* Determine target state of the slab */
2133 new.counters = old.counters;
2134 if (freelist) {
2135 new.inuse--;
2136 set_freepointer(s, freelist, old.freelist);
2137 new.freelist = freelist;
2138 } else
2139 new.freelist = old.freelist;
2141 new.frozen = 0;
2143 if (!new.inuse && n->nr_partial >= s->min_partial)
2144 m = M_FREE;
2145 else if (new.freelist) {
2146 m = M_PARTIAL;
2147 if (!lock) {
2148 lock = 1;
2150 * Taking the spinlock removes the possibility
2151 * that acquire_slab() will see a slab page that
2152 * is frozen
2154 spin_lock(&n->list_lock);
2156 } else {
2157 m = M_FULL;
2158 if (kmem_cache_debug(s) && !lock) {
2159 lock = 1;
2161 * This also ensures that the scanning of full
2162 * slabs from diagnostic functions will not see
2163 * any frozen slabs.
2165 spin_lock(&n->list_lock);
2169 if (l != m) {
2170 if (l == M_PARTIAL)
2171 remove_partial(n, page);
2172 else if (l == M_FULL)
2173 remove_full(s, n, page);
2175 if (m == M_PARTIAL)
2176 add_partial(n, page, tail);
2177 else if (m == M_FULL)
2178 add_full(s, n, page);
2181 l = m;
2182 if (!__cmpxchg_double_slab(s, page,
2183 old.freelist, old.counters,
2184 new.freelist, new.counters,
2185 "unfreezing slab"))
2186 goto redo;
2188 if (lock)
2189 spin_unlock(&n->list_lock);
2191 if (m == M_PARTIAL)
2192 stat(s, tail);
2193 else if (m == M_FULL)
2194 stat(s, DEACTIVATE_FULL);
2195 else if (m == M_FREE) {
2196 stat(s, DEACTIVATE_EMPTY);
2197 discard_slab(s, page);
2198 stat(s, FREE_SLAB);
2201 c->page = NULL;
2202 c->freelist = NULL;
2206 * Unfreeze all the cpu partial slabs.
2208 * This function must be called with interrupts disabled
2209 * for the cpu using c (or some other guarantee must be there
2210 * to guarantee no concurrent accesses).
2212 static void unfreeze_partials(struct kmem_cache *s,
2213 struct kmem_cache_cpu *c)
2215 #ifdef CONFIG_SLUB_CPU_PARTIAL
2216 struct kmem_cache_node *n = NULL, *n2 = NULL;
2217 struct page *page, *discard_page = NULL;
2219 while ((page = slub_percpu_partial(c))) {
2220 struct page new;
2221 struct page old;
2223 slub_set_percpu_partial(c, page);
2225 n2 = get_node(s, page_to_nid(page));
2226 if (n != n2) {
2227 if (n)
2228 spin_unlock(&n->list_lock);
2230 n = n2;
2231 spin_lock(&n->list_lock);
2234 do {
2236 old.freelist = page->freelist;
2237 old.counters = page->counters;
2238 VM_BUG_ON(!old.frozen);
2240 new.counters = old.counters;
2241 new.freelist = old.freelist;
2243 new.frozen = 0;
2245 } while (!__cmpxchg_double_slab(s, page,
2246 old.freelist, old.counters,
2247 new.freelist, new.counters,
2248 "unfreezing slab"));
2250 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2251 page->next = discard_page;
2252 discard_page = page;
2253 } else {
2254 add_partial(n, page, DEACTIVATE_TO_TAIL);
2255 stat(s, FREE_ADD_PARTIAL);
2259 if (n)
2260 spin_unlock(&n->list_lock);
2262 while (discard_page) {
2263 page = discard_page;
2264 discard_page = discard_page->next;
2266 stat(s, DEACTIVATE_EMPTY);
2267 discard_slab(s, page);
2268 stat(s, FREE_SLAB);
2270 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2274 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2275 * partial page slot if available.
2277 * If we did not find a slot then simply move all the partials to the
2278 * per node partial list.
2280 static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2282 #ifdef CONFIG_SLUB_CPU_PARTIAL
2283 struct page *oldpage;
2284 int pages;
2285 int pobjects;
2287 preempt_disable();
2288 do {
2289 pages = 0;
2290 pobjects = 0;
2291 oldpage = this_cpu_read(s->cpu_slab->partial);
2293 if (oldpage) {
2294 pobjects = oldpage->pobjects;
2295 pages = oldpage->pages;
2296 if (drain && pobjects > slub_cpu_partial(s)) {
2297 unsigned long flags;
2299 * partial array is full. Move the existing
2300 * set to the per node partial list.
2302 local_irq_save(flags);
2303 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2304 local_irq_restore(flags);
2305 oldpage = NULL;
2306 pobjects = 0;
2307 pages = 0;
2308 stat(s, CPU_PARTIAL_DRAIN);
2312 pages++;
2313 pobjects += page->objects - page->inuse;
2315 page->pages = pages;
2316 page->pobjects = pobjects;
2317 page->next = oldpage;
2319 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2320 != oldpage);
2321 if (unlikely(!slub_cpu_partial(s))) {
2322 unsigned long flags;
2324 local_irq_save(flags);
2325 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2326 local_irq_restore(flags);
2328 preempt_enable();
2329 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2332 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2334 stat(s, CPUSLAB_FLUSH);
2335 deactivate_slab(s, c->page, c->freelist, c);
2337 c->tid = next_tid(c->tid);
2341 * Flush cpu slab.
2343 * Called from IPI handler with interrupts disabled.
2345 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2347 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2349 if (c->page)
2350 flush_slab(s, c);
2352 unfreeze_partials(s, c);
2355 static void flush_cpu_slab(void *d)
2357 struct kmem_cache *s = d;
2359 __flush_cpu_slab(s, smp_processor_id());
2362 static bool has_cpu_slab(int cpu, void *info)
2364 struct kmem_cache *s = info;
2365 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2367 return c->page || slub_percpu_partial(c);
2370 static void flush_all(struct kmem_cache *s)
2372 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1);
2376 * Use the cpu notifier to insure that the cpu slabs are flushed when
2377 * necessary.
2379 static int slub_cpu_dead(unsigned int cpu)
2381 struct kmem_cache *s;
2382 unsigned long flags;
2384 mutex_lock(&slab_mutex);
2385 list_for_each_entry(s, &slab_caches, list) {
2386 local_irq_save(flags);
2387 __flush_cpu_slab(s, cpu);
2388 local_irq_restore(flags);
2390 mutex_unlock(&slab_mutex);
2391 return 0;
2395 * Check if the objects in a per cpu structure fit numa
2396 * locality expectations.
2398 static inline int node_match(struct page *page, int node)
2400 #ifdef CONFIG_NUMA
2401 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2402 return 0;
2403 #endif
2404 return 1;
2407 #ifdef CONFIG_SLUB_DEBUG
2408 static int count_free(struct page *page)
2410 return page->objects - page->inuse;
2413 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2415 return atomic_long_read(&n->total_objects);
2417 #endif /* CONFIG_SLUB_DEBUG */
2419 #if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2420 static unsigned long count_partial(struct kmem_cache_node *n,
2421 int (*get_count)(struct page *))
2423 unsigned long flags;
2424 unsigned long x = 0;
2425 struct page *page;
2427 spin_lock_irqsave(&n->list_lock, flags);
2428 list_for_each_entry(page, &n->partial, slab_list)
2429 x += get_count(page);
2430 spin_unlock_irqrestore(&n->list_lock, flags);
2431 return x;
2433 #endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2435 static noinline void
2436 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2438 #ifdef CONFIG_SLUB_DEBUG
2439 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2440 DEFAULT_RATELIMIT_BURST);
2441 int node;
2442 struct kmem_cache_node *n;
2444 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2445 return;
2447 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2448 nid, gfpflags, &gfpflags);
2449 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2450 s->name, s->object_size, s->size, oo_order(s->oo),
2451 oo_order(s->min));
2453 if (oo_order(s->min) > get_order(s->object_size))
2454 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2455 s->name);
2457 for_each_kmem_cache_node(s, node, n) {
2458 unsigned long nr_slabs;
2459 unsigned long nr_objs;
2460 unsigned long nr_free;
2462 nr_free = count_partial(n, count_free);
2463 nr_slabs = node_nr_slabs(n);
2464 nr_objs = node_nr_objs(n);
2466 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2467 node, nr_slabs, nr_objs, nr_free);
2469 #endif
2472 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2473 int node, struct kmem_cache_cpu **pc)
2475 void *freelist;
2476 struct kmem_cache_cpu *c = *pc;
2477 struct page *page;
2479 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2481 freelist = get_partial(s, flags, node, c);
2483 if (freelist)
2484 return freelist;
2486 page = new_slab(s, flags, node);
2487 if (page) {
2488 c = raw_cpu_ptr(s->cpu_slab);
2489 if (c->page)
2490 flush_slab(s, c);
2493 * No other reference to the page yet so we can
2494 * muck around with it freely without cmpxchg
2496 freelist = page->freelist;
2497 page->freelist = NULL;
2499 stat(s, ALLOC_SLAB);
2500 c->page = page;
2501 *pc = c;
2504 return freelist;
2507 static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2509 if (unlikely(PageSlabPfmemalloc(page)))
2510 return gfp_pfmemalloc_allowed(gfpflags);
2512 return true;
2516 * Check the page->freelist of a page and either transfer the freelist to the
2517 * per cpu freelist or deactivate the page.
2519 * The page is still frozen if the return value is not NULL.
2521 * If this function returns NULL then the page has been unfrozen.
2523 * This function must be called with interrupt disabled.
2525 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2527 struct page new;
2528 unsigned long counters;
2529 void *freelist;
2531 do {
2532 freelist = page->freelist;
2533 counters = page->counters;
2535 new.counters = counters;
2536 VM_BUG_ON(!new.frozen);
2538 new.inuse = page->objects;
2539 new.frozen = freelist != NULL;
2541 } while (!__cmpxchg_double_slab(s, page,
2542 freelist, counters,
2543 NULL, new.counters,
2544 "get_freelist"));
2546 return freelist;
2550 * Slow path. The lockless freelist is empty or we need to perform
2551 * debugging duties.
2553 * Processing is still very fast if new objects have been freed to the
2554 * regular freelist. In that case we simply take over the regular freelist
2555 * as the lockless freelist and zap the regular freelist.
2557 * If that is not working then we fall back to the partial lists. We take the
2558 * first element of the freelist as the object to allocate now and move the
2559 * rest of the freelist to the lockless freelist.
2561 * And if we were unable to get a new slab from the partial slab lists then
2562 * we need to allocate a new slab. This is the slowest path since it involves
2563 * a call to the page allocator and the setup of a new slab.
2565 * Version of __slab_alloc to use when we know that interrupts are
2566 * already disabled (which is the case for bulk allocation).
2568 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2569 unsigned long addr, struct kmem_cache_cpu *c)
2571 void *freelist;
2572 struct page *page;
2574 page = c->page;
2575 if (!page) {
2577 * if the node is not online or has no normal memory, just
2578 * ignore the node constraint
2580 if (unlikely(node != NUMA_NO_NODE &&
2581 !node_state(node, N_NORMAL_MEMORY)))
2582 node = NUMA_NO_NODE;
2583 goto new_slab;
2585 redo:
2587 if (unlikely(!node_match(page, node))) {
2589 * same as above but node_match() being false already
2590 * implies node != NUMA_NO_NODE
2592 if (!node_state(node, N_NORMAL_MEMORY)) {
2593 node = NUMA_NO_NODE;
2594 goto redo;
2595 } else {
2596 stat(s, ALLOC_NODE_MISMATCH);
2597 deactivate_slab(s, page, c->freelist, c);
2598 goto new_slab;
2603 * By rights, we should be searching for a slab page that was
2604 * PFMEMALLOC but right now, we are losing the pfmemalloc
2605 * information when the page leaves the per-cpu allocator
2607 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2608 deactivate_slab(s, page, c->freelist, c);
2609 goto new_slab;
2612 /* must check again c->freelist in case of cpu migration or IRQ */
2613 freelist = c->freelist;
2614 if (freelist)
2615 goto load_freelist;
2617 freelist = get_freelist(s, page);
2619 if (!freelist) {
2620 c->page = NULL;
2621 stat(s, DEACTIVATE_BYPASS);
2622 goto new_slab;
2625 stat(s, ALLOC_REFILL);
2627 load_freelist:
2629 * freelist is pointing to the list of objects to be used.
2630 * page is pointing to the page from which the objects are obtained.
2631 * That page must be frozen for per cpu allocations to work.
2633 VM_BUG_ON(!c->page->frozen);
2634 c->freelist = get_freepointer(s, freelist);
2635 c->tid = next_tid(c->tid);
2636 return freelist;
2638 new_slab:
2640 if (slub_percpu_partial(c)) {
2641 page = c->page = slub_percpu_partial(c);
2642 slub_set_percpu_partial(c, page);
2643 stat(s, CPU_PARTIAL_ALLOC);
2644 goto redo;
2647 freelist = new_slab_objects(s, gfpflags, node, &c);
2649 if (unlikely(!freelist)) {
2650 slab_out_of_memory(s, gfpflags, node);
2651 return NULL;
2654 page = c->page;
2655 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2656 goto load_freelist;
2658 /* Only entered in the debug case */
2659 if (kmem_cache_debug(s) &&
2660 !alloc_debug_processing(s, page, freelist, addr))
2661 goto new_slab; /* Slab failed checks. Next slab needed */
2663 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2664 return freelist;
2668 * Another one that disabled interrupt and compensates for possible
2669 * cpu changes by refetching the per cpu area pointer.
2671 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2672 unsigned long addr, struct kmem_cache_cpu *c)
2674 void *p;
2675 unsigned long flags;
2677 local_irq_save(flags);
2678 #ifdef CONFIG_PREEMPTION
2680 * We may have been preempted and rescheduled on a different
2681 * cpu before disabling interrupts. Need to reload cpu area
2682 * pointer.
2684 c = this_cpu_ptr(s->cpu_slab);
2685 #endif
2687 p = ___slab_alloc(s, gfpflags, node, addr, c);
2688 local_irq_restore(flags);
2689 return p;
2693 * If the object has been wiped upon free, make sure it's fully initialized by
2694 * zeroing out freelist pointer.
2696 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2697 void *obj)
2699 if (unlikely(slab_want_init_on_free(s)) && obj)
2700 memset((void *)((char *)obj + s->offset), 0, sizeof(void *));
2704 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2705 * have the fastpath folded into their functions. So no function call
2706 * overhead for requests that can be satisfied on the fastpath.
2708 * The fastpath works by first checking if the lockless freelist can be used.
2709 * If not then __slab_alloc is called for slow processing.
2711 * Otherwise we can simply pick the next object from the lockless free list.
2713 static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2714 gfp_t gfpflags, int node, unsigned long addr)
2716 void *object;
2717 struct kmem_cache_cpu *c;
2718 struct page *page;
2719 unsigned long tid;
2721 s = slab_pre_alloc_hook(s, gfpflags);
2722 if (!s)
2723 return NULL;
2724 redo:
2726 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2727 * enabled. We may switch back and forth between cpus while
2728 * reading from one cpu area. That does not matter as long
2729 * as we end up on the original cpu again when doing the cmpxchg.
2731 * We should guarantee that tid and kmem_cache are retrieved on
2732 * the same cpu. It could be different if CONFIG_PREEMPTION so we need
2733 * to check if it is matched or not.
2735 do {
2736 tid = this_cpu_read(s->cpu_slab->tid);
2737 c = raw_cpu_ptr(s->cpu_slab);
2738 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
2739 unlikely(tid != READ_ONCE(c->tid)));
2742 * Irqless object alloc/free algorithm used here depends on sequence
2743 * of fetching cpu_slab's data. tid should be fetched before anything
2744 * on c to guarantee that object and page associated with previous tid
2745 * won't be used with current tid. If we fetch tid first, object and
2746 * page could be one associated with next tid and our alloc/free
2747 * request will be failed. In this case, we will retry. So, no problem.
2749 barrier();
2752 * The transaction ids are globally unique per cpu and per operation on
2753 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2754 * occurs on the right processor and that there was no operation on the
2755 * linked list in between.
2758 object = c->freelist;
2759 page = c->page;
2760 if (unlikely(!object || !node_match(page, node))) {
2761 object = __slab_alloc(s, gfpflags, node, addr, c);
2762 stat(s, ALLOC_SLOWPATH);
2763 } else {
2764 void *next_object = get_freepointer_safe(s, object);
2767 * The cmpxchg will only match if there was no additional
2768 * operation and if we are on the right processor.
2770 * The cmpxchg does the following atomically (without lock
2771 * semantics!)
2772 * 1. Relocate first pointer to the current per cpu area.
2773 * 2. Verify that tid and freelist have not been changed
2774 * 3. If they were not changed replace tid and freelist
2776 * Since this is without lock semantics the protection is only
2777 * against code executing on this cpu *not* from access by
2778 * other cpus.
2780 if (unlikely(!this_cpu_cmpxchg_double(
2781 s->cpu_slab->freelist, s->cpu_slab->tid,
2782 object, tid,
2783 next_object, next_tid(tid)))) {
2785 note_cmpxchg_failure("slab_alloc", s, tid);
2786 goto redo;
2788 prefetch_freepointer(s, next_object);
2789 stat(s, ALLOC_FASTPATH);
2792 maybe_wipe_obj_freeptr(s, object);
2794 if (unlikely(slab_want_init_on_alloc(gfpflags, s)) && object)
2795 memset(object, 0, s->object_size);
2797 slab_post_alloc_hook(s, gfpflags, 1, &object);
2799 return object;
2802 static __always_inline void *slab_alloc(struct kmem_cache *s,
2803 gfp_t gfpflags, unsigned long addr)
2805 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2808 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2810 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2812 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2813 s->size, gfpflags);
2815 return ret;
2817 EXPORT_SYMBOL(kmem_cache_alloc);
2819 #ifdef CONFIG_TRACING
2820 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2822 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2823 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2824 ret = kasan_kmalloc(s, ret, size, gfpflags);
2825 return ret;
2827 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2828 #endif
2830 #ifdef CONFIG_NUMA
2831 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2833 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2835 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2836 s->object_size, s->size, gfpflags, node);
2838 return ret;
2840 EXPORT_SYMBOL(kmem_cache_alloc_node);
2842 #ifdef CONFIG_TRACING
2843 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2844 gfp_t gfpflags,
2845 int node, size_t size)
2847 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2849 trace_kmalloc_node(_RET_IP_, ret,
2850 size, s->size, gfpflags, node);
2852 ret = kasan_kmalloc(s, ret, size, gfpflags);
2853 return ret;
2855 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2856 #endif
2857 #endif /* CONFIG_NUMA */
2860 * Slow path handling. This may still be called frequently since objects
2861 * have a longer lifetime than the cpu slabs in most processing loads.
2863 * So we still attempt to reduce cache line usage. Just take the slab
2864 * lock and free the item. If there is no additional partial page
2865 * handling required then we can return immediately.
2867 static void __slab_free(struct kmem_cache *s, struct page *page,
2868 void *head, void *tail, int cnt,
2869 unsigned long addr)
2872 void *prior;
2873 int was_frozen;
2874 struct page new;
2875 unsigned long counters;
2876 struct kmem_cache_node *n = NULL;
2877 unsigned long uninitialized_var(flags);
2879 stat(s, FREE_SLOWPATH);
2881 if (kmem_cache_debug(s) &&
2882 !free_debug_processing(s, page, head, tail, cnt, addr))
2883 return;
2885 do {
2886 if (unlikely(n)) {
2887 spin_unlock_irqrestore(&n->list_lock, flags);
2888 n = NULL;
2890 prior = page->freelist;
2891 counters = page->counters;
2892 set_freepointer(s, tail, prior);
2893 new.counters = counters;
2894 was_frozen = new.frozen;
2895 new.inuse -= cnt;
2896 if ((!new.inuse || !prior) && !was_frozen) {
2898 if (kmem_cache_has_cpu_partial(s) && !prior) {
2901 * Slab was on no list before and will be
2902 * partially empty
2903 * We can defer the list move and instead
2904 * freeze it.
2906 new.frozen = 1;
2908 } else { /* Needs to be taken off a list */
2910 n = get_node(s, page_to_nid(page));
2912 * Speculatively acquire the list_lock.
2913 * If the cmpxchg does not succeed then we may
2914 * drop the list_lock without any processing.
2916 * Otherwise the list_lock will synchronize with
2917 * other processors updating the list of slabs.
2919 spin_lock_irqsave(&n->list_lock, flags);
2924 } while (!cmpxchg_double_slab(s, page,
2925 prior, counters,
2926 head, new.counters,
2927 "__slab_free"));
2929 if (likely(!n)) {
2932 * If we just froze the page then put it onto the
2933 * per cpu partial list.
2935 if (new.frozen && !was_frozen) {
2936 put_cpu_partial(s, page, 1);
2937 stat(s, CPU_PARTIAL_FREE);
2940 * The list lock was not taken therefore no list
2941 * activity can be necessary.
2943 if (was_frozen)
2944 stat(s, FREE_FROZEN);
2945 return;
2948 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
2949 goto slab_empty;
2952 * Objects left in the slab. If it was not on the partial list before
2953 * then add it.
2955 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
2956 remove_full(s, n, page);
2957 add_partial(n, page, DEACTIVATE_TO_TAIL);
2958 stat(s, FREE_ADD_PARTIAL);
2960 spin_unlock_irqrestore(&n->list_lock, flags);
2961 return;
2963 slab_empty:
2964 if (prior) {
2966 * Slab on the partial list.
2968 remove_partial(n, page);
2969 stat(s, FREE_REMOVE_PARTIAL);
2970 } else {
2971 /* Slab must be on the full list */
2972 remove_full(s, n, page);
2975 spin_unlock_irqrestore(&n->list_lock, flags);
2976 stat(s, FREE_SLAB);
2977 discard_slab(s, page);
2981 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2982 * can perform fastpath freeing without additional function calls.
2984 * The fastpath is only possible if we are freeing to the current cpu slab
2985 * of this processor. This typically the case if we have just allocated
2986 * the item before.
2988 * If fastpath is not possible then fall back to __slab_free where we deal
2989 * with all sorts of special processing.
2991 * Bulk free of a freelist with several objects (all pointing to the
2992 * same page) possible by specifying head and tail ptr, plus objects
2993 * count (cnt). Bulk free indicated by tail pointer being set.
2995 static __always_inline void do_slab_free(struct kmem_cache *s,
2996 struct page *page, void *head, void *tail,
2997 int cnt, unsigned long addr)
2999 void *tail_obj = tail ? : head;
3000 struct kmem_cache_cpu *c;
3001 unsigned long tid;
3002 redo:
3004 * Determine the currently cpus per cpu slab.
3005 * The cpu may change afterward. However that does not matter since
3006 * data is retrieved via this pointer. If we are on the same cpu
3007 * during the cmpxchg then the free will succeed.
3009 do {
3010 tid = this_cpu_read(s->cpu_slab->tid);
3011 c = raw_cpu_ptr(s->cpu_slab);
3012 } while (IS_ENABLED(CONFIG_PREEMPTION) &&
3013 unlikely(tid != READ_ONCE(c->tid)));
3015 /* Same with comment on barrier() in slab_alloc_node() */
3016 barrier();
3018 if (likely(page == c->page)) {
3019 void **freelist = READ_ONCE(c->freelist);
3021 set_freepointer(s, tail_obj, freelist);
3023 if (unlikely(!this_cpu_cmpxchg_double(
3024 s->cpu_slab->freelist, s->cpu_slab->tid,
3025 freelist, tid,
3026 head, next_tid(tid)))) {
3028 note_cmpxchg_failure("slab_free", s, tid);
3029 goto redo;
3031 stat(s, FREE_FASTPATH);
3032 } else
3033 __slab_free(s, page, head, tail_obj, cnt, addr);
3037 static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3038 void *head, void *tail, int cnt,
3039 unsigned long addr)
3042 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3043 * to remove objects, whose reuse must be delayed.
3045 if (slab_free_freelist_hook(s, &head, &tail))
3046 do_slab_free(s, page, head, tail, cnt, addr);
3049 #ifdef CONFIG_KASAN_GENERIC
3050 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3052 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3054 #endif
3056 void kmem_cache_free(struct kmem_cache *s, void *x)
3058 s = cache_from_obj(s, x);
3059 if (!s)
3060 return;
3061 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3062 trace_kmem_cache_free(_RET_IP_, x);
3064 EXPORT_SYMBOL(kmem_cache_free);
3066 struct detached_freelist {
3067 struct page *page;
3068 void *tail;
3069 void *freelist;
3070 int cnt;
3071 struct kmem_cache *s;
3075 * This function progressively scans the array with free objects (with
3076 * a limited look ahead) and extract objects belonging to the same
3077 * page. It builds a detached freelist directly within the given
3078 * page/objects. This can happen without any need for
3079 * synchronization, because the objects are owned by running process.
3080 * The freelist is build up as a single linked list in the objects.
3081 * The idea is, that this detached freelist can then be bulk
3082 * transferred to the real freelist(s), but only requiring a single
3083 * synchronization primitive. Look ahead in the array is limited due
3084 * to performance reasons.
3086 static inline
3087 int build_detached_freelist(struct kmem_cache *s, size_t size,
3088 void **p, struct detached_freelist *df)
3090 size_t first_skipped_index = 0;
3091 int lookahead = 3;
3092 void *object;
3093 struct page *page;
3095 /* Always re-init detached_freelist */
3096 df->page = NULL;
3098 do {
3099 object = p[--size];
3100 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3101 } while (!object && size);
3103 if (!object)
3104 return 0;
3106 page = virt_to_head_page(object);
3107 if (!s) {
3108 /* Handle kalloc'ed objects */
3109 if (unlikely(!PageSlab(page))) {
3110 BUG_ON(!PageCompound(page));
3111 kfree_hook(object);
3112 __free_pages(page, compound_order(page));
3113 p[size] = NULL; /* mark object processed */
3114 return size;
3116 /* Derive kmem_cache from object */
3117 df->s = page->slab_cache;
3118 } else {
3119 df->s = cache_from_obj(s, object); /* Support for memcg */
3122 /* Start new detached freelist */
3123 df->page = page;
3124 set_freepointer(df->s, object, NULL);
3125 df->tail = object;
3126 df->freelist = object;
3127 p[size] = NULL; /* mark object processed */
3128 df->cnt = 1;
3130 while (size) {
3131 object = p[--size];
3132 if (!object)
3133 continue; /* Skip processed objects */
3135 /* df->page is always set at this point */
3136 if (df->page == virt_to_head_page(object)) {
3137 /* Opportunity build freelist */
3138 set_freepointer(df->s, object, df->freelist);
3139 df->freelist = object;
3140 df->cnt++;
3141 p[size] = NULL; /* mark object processed */
3143 continue;
3146 /* Limit look ahead search */
3147 if (!--lookahead)
3148 break;
3150 if (!first_skipped_index)
3151 first_skipped_index = size + 1;
3154 return first_skipped_index;
3157 /* Note that interrupts must be enabled when calling this function. */
3158 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3160 if (WARN_ON(!size))
3161 return;
3163 do {
3164 struct detached_freelist df;
3166 size = build_detached_freelist(s, size, p, &df);
3167 if (!df.page)
3168 continue;
3170 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
3171 } while (likely(size));
3173 EXPORT_SYMBOL(kmem_cache_free_bulk);
3175 /* Note that interrupts must be enabled when calling this function. */
3176 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3177 void **p)
3179 struct kmem_cache_cpu *c;
3180 int i;
3182 /* memcg and kmem_cache debug support */
3183 s = slab_pre_alloc_hook(s, flags);
3184 if (unlikely(!s))
3185 return false;
3187 * Drain objects in the per cpu slab, while disabling local
3188 * IRQs, which protects against PREEMPT and interrupts
3189 * handlers invoking normal fastpath.
3191 local_irq_disable();
3192 c = this_cpu_ptr(s->cpu_slab);
3194 for (i = 0; i < size; i++) {
3195 void *object = c->freelist;
3197 if (unlikely(!object)) {
3199 * We may have removed an object from c->freelist using
3200 * the fastpath in the previous iteration; in that case,
3201 * c->tid has not been bumped yet.
3202 * Since ___slab_alloc() may reenable interrupts while
3203 * allocating memory, we should bump c->tid now.
3205 c->tid = next_tid(c->tid);
3208 * Invoking slow path likely have side-effect
3209 * of re-populating per CPU c->freelist
3211 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3212 _RET_IP_, c);
3213 if (unlikely(!p[i]))
3214 goto error;
3216 c = this_cpu_ptr(s->cpu_slab);
3217 maybe_wipe_obj_freeptr(s, p[i]);
3219 continue; /* goto for-loop */
3221 c->freelist = get_freepointer(s, object);
3222 p[i] = object;
3223 maybe_wipe_obj_freeptr(s, p[i]);
3225 c->tid = next_tid(c->tid);
3226 local_irq_enable();
3228 /* Clear memory outside IRQ disabled fastpath loop */
3229 if (unlikely(slab_want_init_on_alloc(flags, s))) {
3230 int j;
3232 for (j = 0; j < i; j++)
3233 memset(p[j], 0, s->object_size);
3236 /* memcg and kmem_cache debug support */
3237 slab_post_alloc_hook(s, flags, size, p);
3238 return i;
3239 error:
3240 local_irq_enable();
3241 slab_post_alloc_hook(s, flags, i, p);
3242 __kmem_cache_free_bulk(s, i, p);
3243 return 0;
3245 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3249 * Object placement in a slab is made very easy because we always start at
3250 * offset 0. If we tune the size of the object to the alignment then we can
3251 * get the required alignment by putting one properly sized object after
3252 * another.
3254 * Notice that the allocation order determines the sizes of the per cpu
3255 * caches. Each processor has always one slab available for allocations.
3256 * Increasing the allocation order reduces the number of times that slabs
3257 * must be moved on and off the partial lists and is therefore a factor in
3258 * locking overhead.
3262 * Mininum / Maximum order of slab pages. This influences locking overhead
3263 * and slab fragmentation. A higher order reduces the number of partial slabs
3264 * and increases the number of allocations possible without having to
3265 * take the list_lock.
3267 static unsigned int slub_min_order;
3268 static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3269 static unsigned int slub_min_objects;
3272 * Calculate the order of allocation given an slab object size.
3274 * The order of allocation has significant impact on performance and other
3275 * system components. Generally order 0 allocations should be preferred since
3276 * order 0 does not cause fragmentation in the page allocator. Larger objects
3277 * be problematic to put into order 0 slabs because there may be too much
3278 * unused space left. We go to a higher order if more than 1/16th of the slab
3279 * would be wasted.
3281 * In order to reach satisfactory performance we must ensure that a minimum
3282 * number of objects is in one slab. Otherwise we may generate too much
3283 * activity on the partial lists which requires taking the list_lock. This is
3284 * less a concern for large slabs though which are rarely used.
3286 * slub_max_order specifies the order where we begin to stop considering the
3287 * number of objects in a slab as critical. If we reach slub_max_order then
3288 * we try to keep the page order as low as possible. So we accept more waste
3289 * of space in favor of a small page order.
3291 * Higher order allocations also allow the placement of more objects in a
3292 * slab and thereby reduce object handling overhead. If the user has
3293 * requested a higher mininum order then we start with that one instead of
3294 * the smallest order which will fit the object.
3296 static inline unsigned int slab_order(unsigned int size,
3297 unsigned int min_objects, unsigned int max_order,
3298 unsigned int fract_leftover)
3300 unsigned int min_order = slub_min_order;
3301 unsigned int order;
3303 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3304 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3306 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3307 order <= max_order; order++) {
3309 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3310 unsigned int rem;
3312 rem = slab_size % size;
3314 if (rem <= slab_size / fract_leftover)
3315 break;
3318 return order;
3321 static inline int calculate_order(unsigned int size)
3323 unsigned int order;
3324 unsigned int min_objects;
3325 unsigned int max_objects;
3328 * Attempt to find best configuration for a slab. This
3329 * works by first attempting to generate a layout with
3330 * the best configuration and backing off gradually.
3332 * First we increase the acceptable waste in a slab. Then
3333 * we reduce the minimum objects required in a slab.
3335 min_objects = slub_min_objects;
3336 if (!min_objects)
3337 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3338 max_objects = order_objects(slub_max_order, size);
3339 min_objects = min(min_objects, max_objects);
3341 while (min_objects > 1) {
3342 unsigned int fraction;
3344 fraction = 16;
3345 while (fraction >= 4) {
3346 order = slab_order(size, min_objects,
3347 slub_max_order, fraction);
3348 if (order <= slub_max_order)
3349 return order;
3350 fraction /= 2;
3352 min_objects--;
3356 * We were unable to place multiple objects in a slab. Now
3357 * lets see if we can place a single object there.
3359 order = slab_order(size, 1, slub_max_order, 1);
3360 if (order <= slub_max_order)
3361 return order;
3364 * Doh this slab cannot be placed using slub_max_order.
3366 order = slab_order(size, 1, MAX_ORDER, 1);
3367 if (order < MAX_ORDER)
3368 return order;
3369 return -ENOSYS;
3372 static void
3373 init_kmem_cache_node(struct kmem_cache_node *n)
3375 n->nr_partial = 0;
3376 spin_lock_init(&n->list_lock);
3377 INIT_LIST_HEAD(&n->partial);
3378 #ifdef CONFIG_SLUB_DEBUG
3379 atomic_long_set(&n->nr_slabs, 0);
3380 atomic_long_set(&n->total_objects, 0);
3381 INIT_LIST_HEAD(&n->full);
3382 #endif
3385 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3387 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3388 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3391 * Must align to double word boundary for the double cmpxchg
3392 * instructions to work; see __pcpu_double_call_return_bool().
3394 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3395 2 * sizeof(void *));
3397 if (!s->cpu_slab)
3398 return 0;
3400 init_kmem_cache_cpus(s);
3402 return 1;
3405 static struct kmem_cache *kmem_cache_node;
3408 * No kmalloc_node yet so do it by hand. We know that this is the first
3409 * slab on the node for this slabcache. There are no concurrent accesses
3410 * possible.
3412 * Note that this function only works on the kmem_cache_node
3413 * when allocating for the kmem_cache_node. This is used for bootstrapping
3414 * memory on a fresh node that has no slab structures yet.
3416 static void early_kmem_cache_node_alloc(int node)
3418 struct page *page;
3419 struct kmem_cache_node *n;
3421 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3423 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3425 BUG_ON(!page);
3426 if (page_to_nid(page) != node) {
3427 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3428 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3431 n = page->freelist;
3432 BUG_ON(!n);
3433 #ifdef CONFIG_SLUB_DEBUG
3434 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3435 init_tracking(kmem_cache_node, n);
3436 #endif
3437 n = kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
3438 GFP_KERNEL);
3439 page->freelist = get_freepointer(kmem_cache_node, n);
3440 page->inuse = 1;
3441 page->frozen = 0;
3442 kmem_cache_node->node[node] = n;
3443 init_kmem_cache_node(n);
3444 inc_slabs_node(kmem_cache_node, node, page->objects);
3447 * No locks need to be taken here as it has just been
3448 * initialized and there is no concurrent access.
3450 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3453 static void free_kmem_cache_nodes(struct kmem_cache *s)
3455 int node;
3456 struct kmem_cache_node *n;
3458 for_each_kmem_cache_node(s, node, n) {
3459 s->node[node] = NULL;
3460 kmem_cache_free(kmem_cache_node, n);
3464 void __kmem_cache_release(struct kmem_cache *s)
3466 cache_random_seq_destroy(s);
3467 free_percpu(s->cpu_slab);
3468 free_kmem_cache_nodes(s);
3471 static int init_kmem_cache_nodes(struct kmem_cache *s)
3473 int node;
3475 for_each_node_state(node, N_NORMAL_MEMORY) {
3476 struct kmem_cache_node *n;
3478 if (slab_state == DOWN) {
3479 early_kmem_cache_node_alloc(node);
3480 continue;
3482 n = kmem_cache_alloc_node(kmem_cache_node,
3483 GFP_KERNEL, node);
3485 if (!n) {
3486 free_kmem_cache_nodes(s);
3487 return 0;
3490 init_kmem_cache_node(n);
3491 s->node[node] = n;
3493 return 1;
3496 static void set_min_partial(struct kmem_cache *s, unsigned long min)
3498 if (min < MIN_PARTIAL)
3499 min = MIN_PARTIAL;
3500 else if (min > MAX_PARTIAL)
3501 min = MAX_PARTIAL;
3502 s->min_partial = min;
3505 static void set_cpu_partial(struct kmem_cache *s)
3507 #ifdef CONFIG_SLUB_CPU_PARTIAL
3509 * cpu_partial determined the maximum number of objects kept in the
3510 * per cpu partial lists of a processor.
3512 * Per cpu partial lists mainly contain slabs that just have one
3513 * object freed. If they are used for allocation then they can be
3514 * filled up again with minimal effort. The slab will never hit the
3515 * per node partial lists and therefore no locking will be required.
3517 * This setting also determines
3519 * A) The number of objects from per cpu partial slabs dumped to the
3520 * per node list when we reach the limit.
3521 * B) The number of objects in cpu partial slabs to extract from the
3522 * per node list when we run out of per cpu objects. We only fetch
3523 * 50% to keep some capacity around for frees.
3525 if (!kmem_cache_has_cpu_partial(s))
3526 slub_set_cpu_partial(s, 0);
3527 else if (s->size >= PAGE_SIZE)
3528 slub_set_cpu_partial(s, 2);
3529 else if (s->size >= 1024)
3530 slub_set_cpu_partial(s, 6);
3531 else if (s->size >= 256)
3532 slub_set_cpu_partial(s, 13);
3533 else
3534 slub_set_cpu_partial(s, 30);
3535 #endif
3539 * calculate_sizes() determines the order and the distribution of data within
3540 * a slab object.
3542 static int calculate_sizes(struct kmem_cache *s, int forced_order)
3544 slab_flags_t flags = s->flags;
3545 unsigned int size = s->object_size;
3546 unsigned int freepointer_area;
3547 unsigned int order;
3550 * Round up object size to the next word boundary. We can only
3551 * place the free pointer at word boundaries and this determines
3552 * the possible location of the free pointer.
3554 size = ALIGN(size, sizeof(void *));
3556 * This is the area of the object where a freepointer can be
3557 * safely written. If redzoning adds more to the inuse size, we
3558 * can't use that portion for writing the freepointer, so
3559 * s->offset must be limited within this for the general case.
3561 freepointer_area = size;
3563 #ifdef CONFIG_SLUB_DEBUG
3565 * Determine if we can poison the object itself. If the user of
3566 * the slab may touch the object after free or before allocation
3567 * then we should never poison the object itself.
3569 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3570 !s->ctor)
3571 s->flags |= __OBJECT_POISON;
3572 else
3573 s->flags &= ~__OBJECT_POISON;
3577 * If we are Redzoning then check if there is some space between the
3578 * end of the object and the free pointer. If not then add an
3579 * additional word to have some bytes to store Redzone information.
3581 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3582 size += sizeof(void *);
3583 #endif
3586 * With that we have determined the number of bytes in actual use
3587 * by the object. This is the potential offset to the free pointer.
3589 s->inuse = size;
3591 if (((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3592 s->ctor)) {
3594 * Relocate free pointer after the object if it is not
3595 * permitted to overwrite the first word of the object on
3596 * kmem_cache_free.
3598 * This is the case if we do RCU, have a constructor or
3599 * destructor or are poisoning the objects.
3601 * The assumption that s->offset >= s->inuse means free
3602 * pointer is outside of the object is used in the
3603 * freeptr_outside_object() function. If that is no
3604 * longer true, the function needs to be modified.
3606 s->offset = size;
3607 size += sizeof(void *);
3608 } else if (freepointer_area > sizeof(void *)) {
3610 * Store freelist pointer near middle of object to keep
3611 * it away from the edges of the object to avoid small
3612 * sized over/underflows from neighboring allocations.
3614 s->offset = ALIGN(freepointer_area / 2, sizeof(void *));
3617 #ifdef CONFIG_SLUB_DEBUG
3618 if (flags & SLAB_STORE_USER)
3620 * Need to store information about allocs and frees after
3621 * the object.
3623 size += 2 * sizeof(struct track);
3624 #endif
3626 kasan_cache_create(s, &size, &s->flags);
3627 #ifdef CONFIG_SLUB_DEBUG
3628 if (flags & SLAB_RED_ZONE) {
3630 * Add some empty padding so that we can catch
3631 * overwrites from earlier objects rather than let
3632 * tracking information or the free pointer be
3633 * corrupted if a user writes before the start
3634 * of the object.
3636 size += sizeof(void *);
3638 s->red_left_pad = sizeof(void *);
3639 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3640 size += s->red_left_pad;
3642 #endif
3645 * SLUB stores one object immediately after another beginning from
3646 * offset 0. In order to align the objects we have to simply size
3647 * each object to conform to the alignment.
3649 size = ALIGN(size, s->align);
3650 s->size = size;
3651 if (forced_order >= 0)
3652 order = forced_order;
3653 else
3654 order = calculate_order(size);
3656 if ((int)order < 0)
3657 return 0;
3659 s->allocflags = 0;
3660 if (order)
3661 s->allocflags |= __GFP_COMP;
3663 if (s->flags & SLAB_CACHE_DMA)
3664 s->allocflags |= GFP_DMA;
3666 if (s->flags & SLAB_CACHE_DMA32)
3667 s->allocflags |= GFP_DMA32;
3669 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3670 s->allocflags |= __GFP_RECLAIMABLE;
3673 * Determine the number of objects per slab
3675 s->oo = oo_make(order, size);
3676 s->min = oo_make(get_order(size), size);
3677 if (oo_objects(s->oo) > oo_objects(s->max))
3678 s->max = s->oo;
3680 return !!oo_objects(s->oo);
3683 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3685 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3686 #ifdef CONFIG_SLAB_FREELIST_HARDENED
3687 s->random = get_random_long();
3688 #endif
3690 if (!calculate_sizes(s, -1))
3691 goto error;
3692 if (disable_higher_order_debug) {
3694 * Disable debugging flags that store metadata if the min slab
3695 * order increased.
3697 if (get_order(s->size) > get_order(s->object_size)) {
3698 s->flags &= ~DEBUG_METADATA_FLAGS;
3699 s->offset = 0;
3700 if (!calculate_sizes(s, -1))
3701 goto error;
3705 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3706 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3707 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3708 /* Enable fast mode */
3709 s->flags |= __CMPXCHG_DOUBLE;
3710 #endif
3713 * The larger the object size is, the more pages we want on the partial
3714 * list to avoid pounding the page allocator excessively.
3716 set_min_partial(s, ilog2(s->size) / 2);
3718 set_cpu_partial(s);
3720 #ifdef CONFIG_NUMA
3721 s->remote_node_defrag_ratio = 1000;
3722 #endif
3724 /* Initialize the pre-computed randomized freelist if slab is up */
3725 if (slab_state >= UP) {
3726 if (init_cache_random_seq(s))
3727 goto error;
3730 if (!init_kmem_cache_nodes(s))
3731 goto error;
3733 if (alloc_kmem_cache_cpus(s))
3734 return 0;
3736 free_kmem_cache_nodes(s);
3737 error:
3738 return -EINVAL;
3741 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3742 const char *text)
3744 #ifdef CONFIG_SLUB_DEBUG
3745 void *addr = page_address(page);
3746 void *p;
3747 unsigned long *map;
3749 slab_err(s, page, text, s->name);
3750 slab_lock(page);
3752 map = get_map(s, page);
3753 for_each_object(p, s, addr, page->objects) {
3755 if (!test_bit(slab_index(p, s, addr), map)) {
3756 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3757 print_tracking(s, p);
3760 put_map(map);
3762 slab_unlock(page);
3763 #endif
3767 * Attempt to free all partial slabs on a node.
3768 * This is called from __kmem_cache_shutdown(). We must take list_lock
3769 * because sysfs file might still access partial list after the shutdowning.
3771 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3773 LIST_HEAD(discard);
3774 struct page *page, *h;
3776 BUG_ON(irqs_disabled());
3777 spin_lock_irq(&n->list_lock);
3778 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
3779 if (!page->inuse) {
3780 remove_partial(n, page);
3781 list_add(&page->slab_list, &discard);
3782 } else {
3783 list_slab_objects(s, page,
3784 "Objects remaining in %s on __kmem_cache_shutdown()");
3787 spin_unlock_irq(&n->list_lock);
3789 list_for_each_entry_safe(page, h, &discard, slab_list)
3790 discard_slab(s, page);
3793 bool __kmem_cache_empty(struct kmem_cache *s)
3795 int node;
3796 struct kmem_cache_node *n;
3798 for_each_kmem_cache_node(s, node, n)
3799 if (n->nr_partial || slabs_node(s, node))
3800 return false;
3801 return true;
3805 * Release all resources used by a slab cache.
3807 int __kmem_cache_shutdown(struct kmem_cache *s)
3809 int node;
3810 struct kmem_cache_node *n;
3812 flush_all(s);
3813 /* Attempt to free all objects */
3814 for_each_kmem_cache_node(s, node, n) {
3815 free_partial(s, n);
3816 if (n->nr_partial || slabs_node(s, node))
3817 return 1;
3819 sysfs_slab_remove(s);
3820 return 0;
3823 /********************************************************************
3824 * Kmalloc subsystem
3825 *******************************************************************/
3827 static int __init setup_slub_min_order(char *str)
3829 get_option(&str, (int *)&slub_min_order);
3831 return 1;
3834 __setup("slub_min_order=", setup_slub_min_order);
3836 static int __init setup_slub_max_order(char *str)
3838 get_option(&str, (int *)&slub_max_order);
3839 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
3841 return 1;
3844 __setup("slub_max_order=", setup_slub_max_order);
3846 static int __init setup_slub_min_objects(char *str)
3848 get_option(&str, (int *)&slub_min_objects);
3850 return 1;
3853 __setup("slub_min_objects=", setup_slub_min_objects);
3855 void *__kmalloc(size_t size, gfp_t flags)
3857 struct kmem_cache *s;
3858 void *ret;
3860 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3861 return kmalloc_large(size, flags);
3863 s = kmalloc_slab(size, flags);
3865 if (unlikely(ZERO_OR_NULL_PTR(s)))
3866 return s;
3868 ret = slab_alloc(s, flags, _RET_IP_);
3870 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3872 ret = kasan_kmalloc(s, ret, size, flags);
3874 return ret;
3876 EXPORT_SYMBOL(__kmalloc);
3878 #ifdef CONFIG_NUMA
3879 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3881 struct page *page;
3882 void *ptr = NULL;
3883 unsigned int order = get_order(size);
3885 flags |= __GFP_COMP;
3886 page = alloc_pages_node(node, flags, order);
3887 if (page) {
3888 ptr = page_address(page);
3889 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
3890 1 << order);
3893 return kmalloc_large_node_hook(ptr, size, flags);
3896 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3898 struct kmem_cache *s;
3899 void *ret;
3901 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
3902 ret = kmalloc_large_node(size, flags, node);
3904 trace_kmalloc_node(_RET_IP_, ret,
3905 size, PAGE_SIZE << get_order(size),
3906 flags, node);
3908 return ret;
3911 s = kmalloc_slab(size, flags);
3913 if (unlikely(ZERO_OR_NULL_PTR(s)))
3914 return s;
3916 ret = slab_alloc_node(s, flags, node, _RET_IP_);
3918 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3920 ret = kasan_kmalloc(s, ret, size, flags);
3922 return ret;
3924 EXPORT_SYMBOL(__kmalloc_node);
3925 #endif /* CONFIG_NUMA */
3927 #ifdef CONFIG_HARDENED_USERCOPY
3929 * Rejects incorrectly sized objects and objects that are to be copied
3930 * to/from userspace but do not fall entirely within the containing slab
3931 * cache's usercopy region.
3933 * Returns NULL if check passes, otherwise const char * to name of cache
3934 * to indicate an error.
3936 void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
3937 bool to_user)
3939 struct kmem_cache *s;
3940 unsigned int offset;
3941 size_t object_size;
3943 ptr = kasan_reset_tag(ptr);
3945 /* Find object and usable object size. */
3946 s = page->slab_cache;
3948 /* Reject impossible pointers. */
3949 if (ptr < page_address(page))
3950 usercopy_abort("SLUB object not in SLUB page?!", NULL,
3951 to_user, 0, n);
3953 /* Find offset within object. */
3954 offset = (ptr - page_address(page)) % s->size;
3956 /* Adjust for redzone and reject if within the redzone. */
3957 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) {
3958 if (offset < s->red_left_pad)
3959 usercopy_abort("SLUB object in left red zone",
3960 s->name, to_user, offset, n);
3961 offset -= s->red_left_pad;
3964 /* Allow address range falling entirely within usercopy region. */
3965 if (offset >= s->useroffset &&
3966 offset - s->useroffset <= s->usersize &&
3967 n <= s->useroffset - offset + s->usersize)
3968 return;
3971 * If the copy is still within the allocated object, produce
3972 * a warning instead of rejecting the copy. This is intended
3973 * to be a temporary method to find any missing usercopy
3974 * whitelists.
3976 object_size = slab_ksize(s);
3977 if (usercopy_fallback &&
3978 offset <= object_size && n <= object_size - offset) {
3979 usercopy_warn("SLUB object", s->name, to_user, offset, n);
3980 return;
3983 usercopy_abort("SLUB object", s->name, to_user, offset, n);
3985 #endif /* CONFIG_HARDENED_USERCOPY */
3987 size_t __ksize(const void *object)
3989 struct page *page;
3991 if (unlikely(object == ZERO_SIZE_PTR))
3992 return 0;
3994 page = virt_to_head_page(object);
3996 if (unlikely(!PageSlab(page))) {
3997 WARN_ON(!PageCompound(page));
3998 return page_size(page);
4001 return slab_ksize(page->slab_cache);
4003 EXPORT_SYMBOL(__ksize);
4005 void kfree(const void *x)
4007 struct page *page;
4008 void *object = (void *)x;
4010 trace_kfree(_RET_IP_, x);
4012 if (unlikely(ZERO_OR_NULL_PTR(x)))
4013 return;
4015 page = virt_to_head_page(x);
4016 if (unlikely(!PageSlab(page))) {
4017 unsigned int order = compound_order(page);
4019 BUG_ON(!PageCompound(page));
4020 kfree_hook(object);
4021 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
4022 -(1 << order));
4023 __free_pages(page, order);
4024 return;
4026 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4028 EXPORT_SYMBOL(kfree);
4030 #define SHRINK_PROMOTE_MAX 32
4033 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4034 * up most to the head of the partial lists. New allocations will then
4035 * fill those up and thus they can be removed from the partial lists.
4037 * The slabs with the least items are placed last. This results in them
4038 * being allocated from last increasing the chance that the last objects
4039 * are freed in them.
4041 int __kmem_cache_shrink(struct kmem_cache *s)
4043 int node;
4044 int i;
4045 struct kmem_cache_node *n;
4046 struct page *page;
4047 struct page *t;
4048 struct list_head discard;
4049 struct list_head promote[SHRINK_PROMOTE_MAX];
4050 unsigned long flags;
4051 int ret = 0;
4053 flush_all(s);
4054 for_each_kmem_cache_node(s, node, n) {
4055 INIT_LIST_HEAD(&discard);
4056 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4057 INIT_LIST_HEAD(promote + i);
4059 spin_lock_irqsave(&n->list_lock, flags);
4062 * Build lists of slabs to discard or promote.
4064 * Note that concurrent frees may occur while we hold the
4065 * list_lock. page->inuse here is the upper limit.
4067 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
4068 int free = page->objects - page->inuse;
4070 /* Do not reread page->inuse */
4071 barrier();
4073 /* We do not keep full slabs on the list */
4074 BUG_ON(free <= 0);
4076 if (free == page->objects) {
4077 list_move(&page->slab_list, &discard);
4078 n->nr_partial--;
4079 } else if (free <= SHRINK_PROMOTE_MAX)
4080 list_move(&page->slab_list, promote + free - 1);
4084 * Promote the slabs filled up most to the head of the
4085 * partial list.
4087 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4088 list_splice(promote + i, &n->partial);
4090 spin_unlock_irqrestore(&n->list_lock, flags);
4092 /* Release empty slabs */
4093 list_for_each_entry_safe(page, t, &discard, slab_list)
4094 discard_slab(s, page);
4096 if (slabs_node(s, node))
4097 ret = 1;
4100 return ret;
4103 #ifdef CONFIG_MEMCG
4104 void __kmemcg_cache_deactivate_after_rcu(struct kmem_cache *s)
4107 * Called with all the locks held after a sched RCU grace period.
4108 * Even if @s becomes empty after shrinking, we can't know that @s
4109 * doesn't have allocations already in-flight and thus can't
4110 * destroy @s until the associated memcg is released.
4112 * However, let's remove the sysfs files for empty caches here.
4113 * Each cache has a lot of interface files which aren't
4114 * particularly useful for empty draining caches; otherwise, we can
4115 * easily end up with millions of unnecessary sysfs files on
4116 * systems which have a lot of memory and transient cgroups.
4118 if (!__kmem_cache_shrink(s))
4119 sysfs_slab_remove(s);
4122 void __kmemcg_cache_deactivate(struct kmem_cache *s)
4125 * Disable empty slabs caching. Used to avoid pinning offline
4126 * memory cgroups by kmem pages that can be freed.
4128 slub_set_cpu_partial(s, 0);
4129 s->min_partial = 0;
4131 #endif /* CONFIG_MEMCG */
4133 static int slab_mem_going_offline_callback(void *arg)
4135 struct kmem_cache *s;
4137 mutex_lock(&slab_mutex);
4138 list_for_each_entry(s, &slab_caches, list)
4139 __kmem_cache_shrink(s);
4140 mutex_unlock(&slab_mutex);
4142 return 0;
4145 static void slab_mem_offline_callback(void *arg)
4147 struct kmem_cache_node *n;
4148 struct kmem_cache *s;
4149 struct memory_notify *marg = arg;
4150 int offline_node;
4152 offline_node = marg->status_change_nid_normal;
4155 * If the node still has available memory. we need kmem_cache_node
4156 * for it yet.
4158 if (offline_node < 0)
4159 return;
4161 mutex_lock(&slab_mutex);
4162 list_for_each_entry(s, &slab_caches, list) {
4163 n = get_node(s, offline_node);
4164 if (n) {
4166 * if n->nr_slabs > 0, slabs still exist on the node
4167 * that is going down. We were unable to free them,
4168 * and offline_pages() function shouldn't call this
4169 * callback. So, we must fail.
4171 BUG_ON(slabs_node(s, offline_node));
4173 s->node[offline_node] = NULL;
4174 kmem_cache_free(kmem_cache_node, n);
4177 mutex_unlock(&slab_mutex);
4180 static int slab_mem_going_online_callback(void *arg)
4182 struct kmem_cache_node *n;
4183 struct kmem_cache *s;
4184 struct memory_notify *marg = arg;
4185 int nid = marg->status_change_nid_normal;
4186 int ret = 0;
4189 * If the node's memory is already available, then kmem_cache_node is
4190 * already created. Nothing to do.
4192 if (nid < 0)
4193 return 0;
4196 * We are bringing a node online. No memory is available yet. We must
4197 * allocate a kmem_cache_node structure in order to bring the node
4198 * online.
4200 mutex_lock(&slab_mutex);
4201 list_for_each_entry(s, &slab_caches, list) {
4203 * XXX: kmem_cache_alloc_node will fallback to other nodes
4204 * since memory is not yet available from the node that
4205 * is brought up.
4207 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4208 if (!n) {
4209 ret = -ENOMEM;
4210 goto out;
4212 init_kmem_cache_node(n);
4213 s->node[nid] = n;
4215 out:
4216 mutex_unlock(&slab_mutex);
4217 return ret;
4220 static int slab_memory_callback(struct notifier_block *self,
4221 unsigned long action, void *arg)
4223 int ret = 0;
4225 switch (action) {
4226 case MEM_GOING_ONLINE:
4227 ret = slab_mem_going_online_callback(arg);
4228 break;
4229 case MEM_GOING_OFFLINE:
4230 ret = slab_mem_going_offline_callback(arg);
4231 break;
4232 case MEM_OFFLINE:
4233 case MEM_CANCEL_ONLINE:
4234 slab_mem_offline_callback(arg);
4235 break;
4236 case MEM_ONLINE:
4237 case MEM_CANCEL_OFFLINE:
4238 break;
4240 if (ret)
4241 ret = notifier_from_errno(ret);
4242 else
4243 ret = NOTIFY_OK;
4244 return ret;
4247 static struct notifier_block slab_memory_callback_nb = {
4248 .notifier_call = slab_memory_callback,
4249 .priority = SLAB_CALLBACK_PRI,
4252 /********************************************************************
4253 * Basic setup of slabs
4254 *******************************************************************/
4257 * Used for early kmem_cache structures that were allocated using
4258 * the page allocator. Allocate them properly then fix up the pointers
4259 * that may be pointing to the wrong kmem_cache structure.
4262 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4264 int node;
4265 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4266 struct kmem_cache_node *n;
4268 memcpy(s, static_cache, kmem_cache->object_size);
4271 * This runs very early, and only the boot processor is supposed to be
4272 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4273 * IPIs around.
4275 __flush_cpu_slab(s, smp_processor_id());
4276 for_each_kmem_cache_node(s, node, n) {
4277 struct page *p;
4279 list_for_each_entry(p, &n->partial, slab_list)
4280 p->slab_cache = s;
4282 #ifdef CONFIG_SLUB_DEBUG
4283 list_for_each_entry(p, &n->full, slab_list)
4284 p->slab_cache = s;
4285 #endif
4287 slab_init_memcg_params(s);
4288 list_add(&s->list, &slab_caches);
4289 memcg_link_cache(s, NULL);
4290 return s;
4293 void __init kmem_cache_init(void)
4295 static __initdata struct kmem_cache boot_kmem_cache,
4296 boot_kmem_cache_node;
4298 if (debug_guardpage_minorder())
4299 slub_max_order = 0;
4301 kmem_cache_node = &boot_kmem_cache_node;
4302 kmem_cache = &boot_kmem_cache;
4304 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4305 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4307 register_hotmemory_notifier(&slab_memory_callback_nb);
4309 /* Able to allocate the per node structures */
4310 slab_state = PARTIAL;
4312 create_boot_cache(kmem_cache, "kmem_cache",
4313 offsetof(struct kmem_cache, node) +
4314 nr_node_ids * sizeof(struct kmem_cache_node *),
4315 SLAB_HWCACHE_ALIGN, 0, 0);
4317 kmem_cache = bootstrap(&boot_kmem_cache);
4318 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4320 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4321 setup_kmalloc_cache_index_table();
4322 create_kmalloc_caches(0);
4324 /* Setup random freelists for each cache */
4325 init_freelist_randomization();
4327 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4328 slub_cpu_dead);
4330 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
4331 cache_line_size(),
4332 slub_min_order, slub_max_order, slub_min_objects,
4333 nr_cpu_ids, nr_node_ids);
4336 void __init kmem_cache_init_late(void)
4340 struct kmem_cache *
4341 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4342 slab_flags_t flags, void (*ctor)(void *))
4344 struct kmem_cache *s, *c;
4346 s = find_mergeable(size, align, flags, name, ctor);
4347 if (s) {
4348 s->refcount++;
4351 * Adjust the object sizes so that we clear
4352 * the complete object on kzalloc.
4354 s->object_size = max(s->object_size, size);
4355 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4357 for_each_memcg_cache(c, s) {
4358 c->object_size = s->object_size;
4359 c->inuse = max(c->inuse, ALIGN(size, sizeof(void *)));
4362 if (sysfs_slab_alias(s, name)) {
4363 s->refcount--;
4364 s = NULL;
4368 return s;
4371 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4373 int err;
4375 err = kmem_cache_open(s, flags);
4376 if (err)
4377 return err;
4379 /* Mutex is not taken during early boot */
4380 if (slab_state <= UP)
4381 return 0;
4383 memcg_propagate_slab_attrs(s);
4384 err = sysfs_slab_add(s);
4385 if (err)
4386 __kmem_cache_release(s);
4388 return err;
4391 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4393 struct kmem_cache *s;
4394 void *ret;
4396 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4397 return kmalloc_large(size, gfpflags);
4399 s = kmalloc_slab(size, gfpflags);
4401 if (unlikely(ZERO_OR_NULL_PTR(s)))
4402 return s;
4404 ret = slab_alloc(s, gfpflags, caller);
4406 /* Honor the call site pointer we received. */
4407 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4409 return ret;
4412 #ifdef CONFIG_NUMA
4413 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4414 int node, unsigned long caller)
4416 struct kmem_cache *s;
4417 void *ret;
4419 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4420 ret = kmalloc_large_node(size, gfpflags, node);
4422 trace_kmalloc_node(caller, ret,
4423 size, PAGE_SIZE << get_order(size),
4424 gfpflags, node);
4426 return ret;
4429 s = kmalloc_slab(size, gfpflags);
4431 if (unlikely(ZERO_OR_NULL_PTR(s)))
4432 return s;
4434 ret = slab_alloc_node(s, gfpflags, node, caller);
4436 /* Honor the call site pointer we received. */
4437 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4439 return ret;
4441 #endif
4443 #ifdef CONFIG_SYSFS
4444 static int count_inuse(struct page *page)
4446 return page->inuse;
4449 static int count_total(struct page *page)
4451 return page->objects;
4453 #endif
4455 #ifdef CONFIG_SLUB_DEBUG
4456 static void validate_slab(struct kmem_cache *s, struct page *page)
4458 void *p;
4459 void *addr = page_address(page);
4460 unsigned long *map;
4462 slab_lock(page);
4464 if (!check_slab(s, page) || !on_freelist(s, page, NULL))
4465 goto unlock;
4467 /* Now we know that a valid freelist exists */
4468 map = get_map(s, page);
4469 for_each_object(p, s, addr, page->objects) {
4470 u8 val = test_bit(slab_index(p, s, addr), map) ?
4471 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
4473 if (!check_object(s, page, p, val))
4474 break;
4476 put_map(map);
4477 unlock:
4478 slab_unlock(page);
4481 static int validate_slab_node(struct kmem_cache *s,
4482 struct kmem_cache_node *n)
4484 unsigned long count = 0;
4485 struct page *page;
4486 unsigned long flags;
4488 spin_lock_irqsave(&n->list_lock, flags);
4490 list_for_each_entry(page, &n->partial, slab_list) {
4491 validate_slab(s, page);
4492 count++;
4494 if (count != n->nr_partial)
4495 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4496 s->name, count, n->nr_partial);
4498 if (!(s->flags & SLAB_STORE_USER))
4499 goto out;
4501 list_for_each_entry(page, &n->full, slab_list) {
4502 validate_slab(s, page);
4503 count++;
4505 if (count != atomic_long_read(&n->nr_slabs))
4506 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4507 s->name, count, atomic_long_read(&n->nr_slabs));
4509 out:
4510 spin_unlock_irqrestore(&n->list_lock, flags);
4511 return count;
4514 static long validate_slab_cache(struct kmem_cache *s)
4516 int node;
4517 unsigned long count = 0;
4518 struct kmem_cache_node *n;
4520 flush_all(s);
4521 for_each_kmem_cache_node(s, node, n)
4522 count += validate_slab_node(s, n);
4524 return count;
4527 * Generate lists of code addresses where slabcache objects are allocated
4528 * and freed.
4531 struct location {
4532 unsigned long count;
4533 unsigned long addr;
4534 long long sum_time;
4535 long min_time;
4536 long max_time;
4537 long min_pid;
4538 long max_pid;
4539 DECLARE_BITMAP(cpus, NR_CPUS);
4540 nodemask_t nodes;
4543 struct loc_track {
4544 unsigned long max;
4545 unsigned long count;
4546 struct location *loc;
4549 static void free_loc_track(struct loc_track *t)
4551 if (t->max)
4552 free_pages((unsigned long)t->loc,
4553 get_order(sizeof(struct location) * t->max));
4556 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4558 struct location *l;
4559 int order;
4561 order = get_order(sizeof(struct location) * max);
4563 l = (void *)__get_free_pages(flags, order);
4564 if (!l)
4565 return 0;
4567 if (t->count) {
4568 memcpy(l, t->loc, sizeof(struct location) * t->count);
4569 free_loc_track(t);
4571 t->max = max;
4572 t->loc = l;
4573 return 1;
4576 static int add_location(struct loc_track *t, struct kmem_cache *s,
4577 const struct track *track)
4579 long start, end, pos;
4580 struct location *l;
4581 unsigned long caddr;
4582 unsigned long age = jiffies - track->when;
4584 start = -1;
4585 end = t->count;
4587 for ( ; ; ) {
4588 pos = start + (end - start + 1) / 2;
4591 * There is nothing at "end". If we end up there
4592 * we need to add something to before end.
4594 if (pos == end)
4595 break;
4597 caddr = t->loc[pos].addr;
4598 if (track->addr == caddr) {
4600 l = &t->loc[pos];
4601 l->count++;
4602 if (track->when) {
4603 l->sum_time += age;
4604 if (age < l->min_time)
4605 l->min_time = age;
4606 if (age > l->max_time)
4607 l->max_time = age;
4609 if (track->pid < l->min_pid)
4610 l->min_pid = track->pid;
4611 if (track->pid > l->max_pid)
4612 l->max_pid = track->pid;
4614 cpumask_set_cpu(track->cpu,
4615 to_cpumask(l->cpus));
4617 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4618 return 1;
4621 if (track->addr < caddr)
4622 end = pos;
4623 else
4624 start = pos;
4628 * Not found. Insert new tracking element.
4630 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4631 return 0;
4633 l = t->loc + pos;
4634 if (pos < t->count)
4635 memmove(l + 1, l,
4636 (t->count - pos) * sizeof(struct location));
4637 t->count++;
4638 l->count = 1;
4639 l->addr = track->addr;
4640 l->sum_time = age;
4641 l->min_time = age;
4642 l->max_time = age;
4643 l->min_pid = track->pid;
4644 l->max_pid = track->pid;
4645 cpumask_clear(to_cpumask(l->cpus));
4646 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4647 nodes_clear(l->nodes);
4648 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4649 return 1;
4652 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4653 struct page *page, enum track_item alloc)
4655 void *addr = page_address(page);
4656 void *p;
4657 unsigned long *map;
4659 map = get_map(s, page);
4660 for_each_object(p, s, addr, page->objects)
4661 if (!test_bit(slab_index(p, s, addr), map))
4662 add_location(t, s, get_track(s, p, alloc));
4663 put_map(map);
4666 static int list_locations(struct kmem_cache *s, char *buf,
4667 enum track_item alloc)
4669 int len = 0;
4670 unsigned long i;
4671 struct loc_track t = { 0, 0, NULL };
4672 int node;
4673 struct kmem_cache_node *n;
4675 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4676 GFP_KERNEL)) {
4677 return sprintf(buf, "Out of memory\n");
4679 /* Push back cpu slabs */
4680 flush_all(s);
4682 for_each_kmem_cache_node(s, node, n) {
4683 unsigned long flags;
4684 struct page *page;
4686 if (!atomic_long_read(&n->nr_slabs))
4687 continue;
4689 spin_lock_irqsave(&n->list_lock, flags);
4690 list_for_each_entry(page, &n->partial, slab_list)
4691 process_slab(&t, s, page, alloc);
4692 list_for_each_entry(page, &n->full, slab_list)
4693 process_slab(&t, s, page, alloc);
4694 spin_unlock_irqrestore(&n->list_lock, flags);
4697 for (i = 0; i < t.count; i++) {
4698 struct location *l = &t.loc[i];
4700 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4701 break;
4702 len += sprintf(buf + len, "%7ld ", l->count);
4704 if (l->addr)
4705 len += sprintf(buf + len, "%pS", (void *)l->addr);
4706 else
4707 len += sprintf(buf + len, "<not-available>");
4709 if (l->sum_time != l->min_time) {
4710 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4711 l->min_time,
4712 (long)div_u64(l->sum_time, l->count),
4713 l->max_time);
4714 } else
4715 len += sprintf(buf + len, " age=%ld",
4716 l->min_time);
4718 if (l->min_pid != l->max_pid)
4719 len += sprintf(buf + len, " pid=%ld-%ld",
4720 l->min_pid, l->max_pid);
4721 else
4722 len += sprintf(buf + len, " pid=%ld",
4723 l->min_pid);
4725 if (num_online_cpus() > 1 &&
4726 !cpumask_empty(to_cpumask(l->cpus)) &&
4727 len < PAGE_SIZE - 60)
4728 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4729 " cpus=%*pbl",
4730 cpumask_pr_args(to_cpumask(l->cpus)));
4732 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4733 len < PAGE_SIZE - 60)
4734 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4735 " nodes=%*pbl",
4736 nodemask_pr_args(&l->nodes));
4738 len += sprintf(buf + len, "\n");
4741 free_loc_track(&t);
4742 if (!t.count)
4743 len += sprintf(buf, "No data\n");
4744 return len;
4746 #endif /* CONFIG_SLUB_DEBUG */
4748 #ifdef SLUB_RESILIENCY_TEST
4749 static void __init resiliency_test(void)
4751 u8 *p;
4752 int type = KMALLOC_NORMAL;
4754 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4756 pr_err("SLUB resiliency testing\n");
4757 pr_err("-----------------------\n");
4758 pr_err("A. Corruption after allocation\n");
4760 p = kzalloc(16, GFP_KERNEL);
4761 p[16] = 0x12;
4762 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4763 p + 16);
4765 validate_slab_cache(kmalloc_caches[type][4]);
4767 /* Hmmm... The next two are dangerous */
4768 p = kzalloc(32, GFP_KERNEL);
4769 p[32 + sizeof(void *)] = 0x34;
4770 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4772 pr_err("If allocated object is overwritten then not detectable\n\n");
4774 validate_slab_cache(kmalloc_caches[type][5]);
4775 p = kzalloc(64, GFP_KERNEL);
4776 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4777 *p = 0x56;
4778 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4780 pr_err("If allocated object is overwritten then not detectable\n\n");
4781 validate_slab_cache(kmalloc_caches[type][6]);
4783 pr_err("\nB. Corruption after free\n");
4784 p = kzalloc(128, GFP_KERNEL);
4785 kfree(p);
4786 *p = 0x78;
4787 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4788 validate_slab_cache(kmalloc_caches[type][7]);
4790 p = kzalloc(256, GFP_KERNEL);
4791 kfree(p);
4792 p[50] = 0x9a;
4793 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
4794 validate_slab_cache(kmalloc_caches[type][8]);
4796 p = kzalloc(512, GFP_KERNEL);
4797 kfree(p);
4798 p[512] = 0xab;
4799 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4800 validate_slab_cache(kmalloc_caches[type][9]);
4802 #else
4803 #ifdef CONFIG_SYSFS
4804 static void resiliency_test(void) {};
4805 #endif
4806 #endif /* SLUB_RESILIENCY_TEST */
4808 #ifdef CONFIG_SYSFS
4809 enum slab_stat_type {
4810 SL_ALL, /* All slabs */
4811 SL_PARTIAL, /* Only partially allocated slabs */
4812 SL_CPU, /* Only slabs used for cpu caches */
4813 SL_OBJECTS, /* Determine allocated objects not slabs */
4814 SL_TOTAL /* Determine object capacity not slabs */
4817 #define SO_ALL (1 << SL_ALL)
4818 #define SO_PARTIAL (1 << SL_PARTIAL)
4819 #define SO_CPU (1 << SL_CPU)
4820 #define SO_OBJECTS (1 << SL_OBJECTS)
4821 #define SO_TOTAL (1 << SL_TOTAL)
4823 #ifdef CONFIG_MEMCG
4824 static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON);
4826 static int __init setup_slub_memcg_sysfs(char *str)
4828 int v;
4830 if (get_option(&str, &v) > 0)
4831 memcg_sysfs_enabled = v;
4833 return 1;
4836 __setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs);
4837 #endif
4839 static ssize_t show_slab_objects(struct kmem_cache *s,
4840 char *buf, unsigned long flags)
4842 unsigned long total = 0;
4843 int node;
4844 int x;
4845 unsigned long *nodes;
4847 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
4848 if (!nodes)
4849 return -ENOMEM;
4851 if (flags & SO_CPU) {
4852 int cpu;
4854 for_each_possible_cpu(cpu) {
4855 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4856 cpu);
4857 int node;
4858 struct page *page;
4860 page = READ_ONCE(c->page);
4861 if (!page)
4862 continue;
4864 node = page_to_nid(page);
4865 if (flags & SO_TOTAL)
4866 x = page->objects;
4867 else if (flags & SO_OBJECTS)
4868 x = page->inuse;
4869 else
4870 x = 1;
4872 total += x;
4873 nodes[node] += x;
4875 page = slub_percpu_partial_read_once(c);
4876 if (page) {
4877 node = page_to_nid(page);
4878 if (flags & SO_TOTAL)
4879 WARN_ON_ONCE(1);
4880 else if (flags & SO_OBJECTS)
4881 WARN_ON_ONCE(1);
4882 else
4883 x = page->pages;
4884 total += x;
4885 nodes[node] += x;
4891 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
4892 * already held which will conflict with an existing lock order:
4894 * mem_hotplug_lock->slab_mutex->kernfs_mutex
4896 * We don't really need mem_hotplug_lock (to hold off
4897 * slab_mem_going_offline_callback) here because slab's memory hot
4898 * unplug code doesn't destroy the kmem_cache->node[] data.
4901 #ifdef CONFIG_SLUB_DEBUG
4902 if (flags & SO_ALL) {
4903 struct kmem_cache_node *n;
4905 for_each_kmem_cache_node(s, node, n) {
4907 if (flags & SO_TOTAL)
4908 x = atomic_long_read(&n->total_objects);
4909 else if (flags & SO_OBJECTS)
4910 x = atomic_long_read(&n->total_objects) -
4911 count_partial(n, count_free);
4912 else
4913 x = atomic_long_read(&n->nr_slabs);
4914 total += x;
4915 nodes[node] += x;
4918 } else
4919 #endif
4920 if (flags & SO_PARTIAL) {
4921 struct kmem_cache_node *n;
4923 for_each_kmem_cache_node(s, node, n) {
4924 if (flags & SO_TOTAL)
4925 x = count_partial(n, count_total);
4926 else if (flags & SO_OBJECTS)
4927 x = count_partial(n, count_inuse);
4928 else
4929 x = n->nr_partial;
4930 total += x;
4931 nodes[node] += x;
4934 x = sprintf(buf, "%lu", total);
4935 #ifdef CONFIG_NUMA
4936 for (node = 0; node < nr_node_ids; node++)
4937 if (nodes[node])
4938 x += sprintf(buf + x, " N%d=%lu",
4939 node, nodes[node]);
4940 #endif
4941 kfree(nodes);
4942 return x + sprintf(buf + x, "\n");
4945 #ifdef CONFIG_SLUB_DEBUG
4946 static int any_slab_objects(struct kmem_cache *s)
4948 int node;
4949 struct kmem_cache_node *n;
4951 for_each_kmem_cache_node(s, node, n)
4952 if (atomic_long_read(&n->total_objects))
4953 return 1;
4955 return 0;
4957 #endif
4959 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4960 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4962 struct slab_attribute {
4963 struct attribute attr;
4964 ssize_t (*show)(struct kmem_cache *s, char *buf);
4965 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4968 #define SLAB_ATTR_RO(_name) \
4969 static struct slab_attribute _name##_attr = \
4970 __ATTR(_name, 0400, _name##_show, NULL)
4972 #define SLAB_ATTR(_name) \
4973 static struct slab_attribute _name##_attr = \
4974 __ATTR(_name, 0600, _name##_show, _name##_store)
4976 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4978 return sprintf(buf, "%u\n", s->size);
4980 SLAB_ATTR_RO(slab_size);
4982 static ssize_t align_show(struct kmem_cache *s, char *buf)
4984 return sprintf(buf, "%u\n", s->align);
4986 SLAB_ATTR_RO(align);
4988 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
4990 return sprintf(buf, "%u\n", s->object_size);
4992 SLAB_ATTR_RO(object_size);
4994 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
4996 return sprintf(buf, "%u\n", oo_objects(s->oo));
4998 SLAB_ATTR_RO(objs_per_slab);
5000 static ssize_t order_store(struct kmem_cache *s,
5001 const char *buf, size_t length)
5003 unsigned int order;
5004 int err;
5006 err = kstrtouint(buf, 10, &order);
5007 if (err)
5008 return err;
5010 if (order > slub_max_order || order < slub_min_order)
5011 return -EINVAL;
5013 calculate_sizes(s, order);
5014 return length;
5017 static ssize_t order_show(struct kmem_cache *s, char *buf)
5019 return sprintf(buf, "%u\n", oo_order(s->oo));
5021 SLAB_ATTR(order);
5023 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5025 return sprintf(buf, "%lu\n", s->min_partial);
5028 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5029 size_t length)
5031 unsigned long min;
5032 int err;
5034 err = kstrtoul(buf, 10, &min);
5035 if (err)
5036 return err;
5038 set_min_partial(s, min);
5039 return length;
5041 SLAB_ATTR(min_partial);
5043 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5045 return sprintf(buf, "%u\n", slub_cpu_partial(s));
5048 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5049 size_t length)
5051 unsigned int objects;
5052 int err;
5054 err = kstrtouint(buf, 10, &objects);
5055 if (err)
5056 return err;
5057 if (objects && !kmem_cache_has_cpu_partial(s))
5058 return -EINVAL;
5060 slub_set_cpu_partial(s, objects);
5061 flush_all(s);
5062 return length;
5064 SLAB_ATTR(cpu_partial);
5066 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5068 if (!s->ctor)
5069 return 0;
5070 return sprintf(buf, "%pS\n", s->ctor);
5072 SLAB_ATTR_RO(ctor);
5074 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5076 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5078 SLAB_ATTR_RO(aliases);
5080 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5082 return show_slab_objects(s, buf, SO_PARTIAL);
5084 SLAB_ATTR_RO(partial);
5086 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5088 return show_slab_objects(s, buf, SO_CPU);
5090 SLAB_ATTR_RO(cpu_slabs);
5092 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5094 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5096 SLAB_ATTR_RO(objects);
5098 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5100 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5102 SLAB_ATTR_RO(objects_partial);
5104 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5106 int objects = 0;
5107 int pages = 0;
5108 int cpu;
5109 int len;
5111 for_each_online_cpu(cpu) {
5112 struct page *page;
5114 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5116 if (page) {
5117 pages += page->pages;
5118 objects += page->pobjects;
5122 len = sprintf(buf, "%d(%d)", objects, pages);
5124 #ifdef CONFIG_SMP
5125 for_each_online_cpu(cpu) {
5126 struct page *page;
5128 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5130 if (page && len < PAGE_SIZE - 20)
5131 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
5132 page->pobjects, page->pages);
5134 #endif
5135 return len + sprintf(buf + len, "\n");
5137 SLAB_ATTR_RO(slabs_cpu_partial);
5139 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5141 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5144 static ssize_t reclaim_account_store(struct kmem_cache *s,
5145 const char *buf, size_t length)
5147 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
5148 if (buf[0] == '1')
5149 s->flags |= SLAB_RECLAIM_ACCOUNT;
5150 return length;
5152 SLAB_ATTR(reclaim_account);
5154 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5156 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5158 SLAB_ATTR_RO(hwcache_align);
5160 #ifdef CONFIG_ZONE_DMA
5161 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5163 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5165 SLAB_ATTR_RO(cache_dma);
5166 #endif
5168 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5170 return sprintf(buf, "%u\n", s->usersize);
5172 SLAB_ATTR_RO(usersize);
5174 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5176 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5178 SLAB_ATTR_RO(destroy_by_rcu);
5180 #ifdef CONFIG_SLUB_DEBUG
5181 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5183 return show_slab_objects(s, buf, SO_ALL);
5185 SLAB_ATTR_RO(slabs);
5187 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5189 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5191 SLAB_ATTR_RO(total_objects);
5193 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5195 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5198 static ssize_t sanity_checks_store(struct kmem_cache *s,
5199 const char *buf, size_t length)
5201 s->flags &= ~SLAB_CONSISTENCY_CHECKS;
5202 if (buf[0] == '1') {
5203 s->flags &= ~__CMPXCHG_DOUBLE;
5204 s->flags |= SLAB_CONSISTENCY_CHECKS;
5206 return length;
5208 SLAB_ATTR(sanity_checks);
5210 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5212 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5215 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
5216 size_t length)
5219 * Tracing a merged cache is going to give confusing results
5220 * as well as cause other issues like converting a mergeable
5221 * cache into an umergeable one.
5223 if (s->refcount > 1)
5224 return -EINVAL;
5226 s->flags &= ~SLAB_TRACE;
5227 if (buf[0] == '1') {
5228 s->flags &= ~__CMPXCHG_DOUBLE;
5229 s->flags |= SLAB_TRACE;
5231 return length;
5233 SLAB_ATTR(trace);
5235 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5237 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5240 static ssize_t red_zone_store(struct kmem_cache *s,
5241 const char *buf, size_t length)
5243 if (any_slab_objects(s))
5244 return -EBUSY;
5246 s->flags &= ~SLAB_RED_ZONE;
5247 if (buf[0] == '1') {
5248 s->flags |= SLAB_RED_ZONE;
5250 calculate_sizes(s, -1);
5251 return length;
5253 SLAB_ATTR(red_zone);
5255 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5257 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5260 static ssize_t poison_store(struct kmem_cache *s,
5261 const char *buf, size_t length)
5263 if (any_slab_objects(s))
5264 return -EBUSY;
5266 s->flags &= ~SLAB_POISON;
5267 if (buf[0] == '1') {
5268 s->flags |= SLAB_POISON;
5270 calculate_sizes(s, -1);
5271 return length;
5273 SLAB_ATTR(poison);
5275 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5277 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5280 static ssize_t store_user_store(struct kmem_cache *s,
5281 const char *buf, size_t length)
5283 if (any_slab_objects(s))
5284 return -EBUSY;
5286 s->flags &= ~SLAB_STORE_USER;
5287 if (buf[0] == '1') {
5288 s->flags &= ~__CMPXCHG_DOUBLE;
5289 s->flags |= SLAB_STORE_USER;
5291 calculate_sizes(s, -1);
5292 return length;
5294 SLAB_ATTR(store_user);
5296 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5298 return 0;
5301 static ssize_t validate_store(struct kmem_cache *s,
5302 const char *buf, size_t length)
5304 int ret = -EINVAL;
5306 if (buf[0] == '1') {
5307 ret = validate_slab_cache(s);
5308 if (ret >= 0)
5309 ret = length;
5311 return ret;
5313 SLAB_ATTR(validate);
5315 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5317 if (!(s->flags & SLAB_STORE_USER))
5318 return -ENOSYS;
5319 return list_locations(s, buf, TRACK_ALLOC);
5321 SLAB_ATTR_RO(alloc_calls);
5323 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5325 if (!(s->flags & SLAB_STORE_USER))
5326 return -ENOSYS;
5327 return list_locations(s, buf, TRACK_FREE);
5329 SLAB_ATTR_RO(free_calls);
5330 #endif /* CONFIG_SLUB_DEBUG */
5332 #ifdef CONFIG_FAILSLAB
5333 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5335 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5338 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5339 size_t length)
5341 if (s->refcount > 1)
5342 return -EINVAL;
5344 s->flags &= ~SLAB_FAILSLAB;
5345 if (buf[0] == '1')
5346 s->flags |= SLAB_FAILSLAB;
5347 return length;
5349 SLAB_ATTR(failslab);
5350 #endif
5352 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5354 return 0;
5357 static ssize_t shrink_store(struct kmem_cache *s,
5358 const char *buf, size_t length)
5360 if (buf[0] == '1')
5361 kmem_cache_shrink_all(s);
5362 else
5363 return -EINVAL;
5364 return length;
5366 SLAB_ATTR(shrink);
5368 #ifdef CONFIG_NUMA
5369 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5371 return sprintf(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5374 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5375 const char *buf, size_t length)
5377 unsigned int ratio;
5378 int err;
5380 err = kstrtouint(buf, 10, &ratio);
5381 if (err)
5382 return err;
5383 if (ratio > 100)
5384 return -ERANGE;
5386 s->remote_node_defrag_ratio = ratio * 10;
5388 return length;
5390 SLAB_ATTR(remote_node_defrag_ratio);
5391 #endif
5393 #ifdef CONFIG_SLUB_STATS
5394 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5396 unsigned long sum = 0;
5397 int cpu;
5398 int len;
5399 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5401 if (!data)
5402 return -ENOMEM;
5404 for_each_online_cpu(cpu) {
5405 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5407 data[cpu] = x;
5408 sum += x;
5411 len = sprintf(buf, "%lu", sum);
5413 #ifdef CONFIG_SMP
5414 for_each_online_cpu(cpu) {
5415 if (data[cpu] && len < PAGE_SIZE - 20)
5416 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5418 #endif
5419 kfree(data);
5420 return len + sprintf(buf + len, "\n");
5423 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5425 int cpu;
5427 for_each_online_cpu(cpu)
5428 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5431 #define STAT_ATTR(si, text) \
5432 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5434 return show_stat(s, buf, si); \
5436 static ssize_t text##_store(struct kmem_cache *s, \
5437 const char *buf, size_t length) \
5439 if (buf[0] != '0') \
5440 return -EINVAL; \
5441 clear_stat(s, si); \
5442 return length; \
5444 SLAB_ATTR(text); \
5446 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5447 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5448 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5449 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5450 STAT_ATTR(FREE_FROZEN, free_frozen);
5451 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5452 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5453 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5454 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5455 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5456 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5457 STAT_ATTR(FREE_SLAB, free_slab);
5458 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5459 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5460 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5461 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5462 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5463 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5464 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5465 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5466 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5467 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5468 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5469 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5470 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5471 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5472 #endif /* CONFIG_SLUB_STATS */
5474 static struct attribute *slab_attrs[] = {
5475 &slab_size_attr.attr,
5476 &object_size_attr.attr,
5477 &objs_per_slab_attr.attr,
5478 &order_attr.attr,
5479 &min_partial_attr.attr,
5480 &cpu_partial_attr.attr,
5481 &objects_attr.attr,
5482 &objects_partial_attr.attr,
5483 &partial_attr.attr,
5484 &cpu_slabs_attr.attr,
5485 &ctor_attr.attr,
5486 &aliases_attr.attr,
5487 &align_attr.attr,
5488 &hwcache_align_attr.attr,
5489 &reclaim_account_attr.attr,
5490 &destroy_by_rcu_attr.attr,
5491 &shrink_attr.attr,
5492 &slabs_cpu_partial_attr.attr,
5493 #ifdef CONFIG_SLUB_DEBUG
5494 &total_objects_attr.attr,
5495 &slabs_attr.attr,
5496 &sanity_checks_attr.attr,
5497 &trace_attr.attr,
5498 &red_zone_attr.attr,
5499 &poison_attr.attr,
5500 &store_user_attr.attr,
5501 &validate_attr.attr,
5502 &alloc_calls_attr.attr,
5503 &free_calls_attr.attr,
5504 #endif
5505 #ifdef CONFIG_ZONE_DMA
5506 &cache_dma_attr.attr,
5507 #endif
5508 #ifdef CONFIG_NUMA
5509 &remote_node_defrag_ratio_attr.attr,
5510 #endif
5511 #ifdef CONFIG_SLUB_STATS
5512 &alloc_fastpath_attr.attr,
5513 &alloc_slowpath_attr.attr,
5514 &free_fastpath_attr.attr,
5515 &free_slowpath_attr.attr,
5516 &free_frozen_attr.attr,
5517 &free_add_partial_attr.attr,
5518 &free_remove_partial_attr.attr,
5519 &alloc_from_partial_attr.attr,
5520 &alloc_slab_attr.attr,
5521 &alloc_refill_attr.attr,
5522 &alloc_node_mismatch_attr.attr,
5523 &free_slab_attr.attr,
5524 &cpuslab_flush_attr.attr,
5525 &deactivate_full_attr.attr,
5526 &deactivate_empty_attr.attr,
5527 &deactivate_to_head_attr.attr,
5528 &deactivate_to_tail_attr.attr,
5529 &deactivate_remote_frees_attr.attr,
5530 &deactivate_bypass_attr.attr,
5531 &order_fallback_attr.attr,
5532 &cmpxchg_double_fail_attr.attr,
5533 &cmpxchg_double_cpu_fail_attr.attr,
5534 &cpu_partial_alloc_attr.attr,
5535 &cpu_partial_free_attr.attr,
5536 &cpu_partial_node_attr.attr,
5537 &cpu_partial_drain_attr.attr,
5538 #endif
5539 #ifdef CONFIG_FAILSLAB
5540 &failslab_attr.attr,
5541 #endif
5542 &usersize_attr.attr,
5544 NULL
5547 static const struct attribute_group slab_attr_group = {
5548 .attrs = slab_attrs,
5551 static ssize_t slab_attr_show(struct kobject *kobj,
5552 struct attribute *attr,
5553 char *buf)
5555 struct slab_attribute *attribute;
5556 struct kmem_cache *s;
5557 int err;
5559 attribute = to_slab_attr(attr);
5560 s = to_slab(kobj);
5562 if (!attribute->show)
5563 return -EIO;
5565 err = attribute->show(s, buf);
5567 return err;
5570 static ssize_t slab_attr_store(struct kobject *kobj,
5571 struct attribute *attr,
5572 const char *buf, size_t len)
5574 struct slab_attribute *attribute;
5575 struct kmem_cache *s;
5576 int err;
5578 attribute = to_slab_attr(attr);
5579 s = to_slab(kobj);
5581 if (!attribute->store)
5582 return -EIO;
5584 err = attribute->store(s, buf, len);
5585 #ifdef CONFIG_MEMCG
5586 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5587 struct kmem_cache *c;
5589 mutex_lock(&slab_mutex);
5590 if (s->max_attr_size < len)
5591 s->max_attr_size = len;
5594 * This is a best effort propagation, so this function's return
5595 * value will be determined by the parent cache only. This is
5596 * basically because not all attributes will have a well
5597 * defined semantics for rollbacks - most of the actions will
5598 * have permanent effects.
5600 * Returning the error value of any of the children that fail
5601 * is not 100 % defined, in the sense that users seeing the
5602 * error code won't be able to know anything about the state of
5603 * the cache.
5605 * Only returning the error code for the parent cache at least
5606 * has well defined semantics. The cache being written to
5607 * directly either failed or succeeded, in which case we loop
5608 * through the descendants with best-effort propagation.
5610 for_each_memcg_cache(c, s)
5611 attribute->store(c, buf, len);
5612 mutex_unlock(&slab_mutex);
5614 #endif
5615 return err;
5618 static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5620 #ifdef CONFIG_MEMCG
5621 int i;
5622 char *buffer = NULL;
5623 struct kmem_cache *root_cache;
5625 if (is_root_cache(s))
5626 return;
5628 root_cache = s->memcg_params.root_cache;
5631 * This mean this cache had no attribute written. Therefore, no point
5632 * in copying default values around
5634 if (!root_cache->max_attr_size)
5635 return;
5637 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5638 char mbuf[64];
5639 char *buf;
5640 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5641 ssize_t len;
5643 if (!attr || !attr->store || !attr->show)
5644 continue;
5647 * It is really bad that we have to allocate here, so we will
5648 * do it only as a fallback. If we actually allocate, though,
5649 * we can just use the allocated buffer until the end.
5651 * Most of the slub attributes will tend to be very small in
5652 * size, but sysfs allows buffers up to a page, so they can
5653 * theoretically happen.
5655 if (buffer)
5656 buf = buffer;
5657 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf))
5658 buf = mbuf;
5659 else {
5660 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5661 if (WARN_ON(!buffer))
5662 continue;
5663 buf = buffer;
5666 len = attr->show(root_cache, buf);
5667 if (len > 0)
5668 attr->store(s, buf, len);
5671 if (buffer)
5672 free_page((unsigned long)buffer);
5673 #endif /* CONFIG_MEMCG */
5676 static void kmem_cache_release(struct kobject *k)
5678 slab_kmem_cache_release(to_slab(k));
5681 static const struct sysfs_ops slab_sysfs_ops = {
5682 .show = slab_attr_show,
5683 .store = slab_attr_store,
5686 static struct kobj_type slab_ktype = {
5687 .sysfs_ops = &slab_sysfs_ops,
5688 .release = kmem_cache_release,
5691 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5693 struct kobj_type *ktype = get_ktype(kobj);
5695 if (ktype == &slab_ktype)
5696 return 1;
5697 return 0;
5700 static const struct kset_uevent_ops slab_uevent_ops = {
5701 .filter = uevent_filter,
5704 static struct kset *slab_kset;
5706 static inline struct kset *cache_kset(struct kmem_cache *s)
5708 #ifdef CONFIG_MEMCG
5709 if (!is_root_cache(s))
5710 return s->memcg_params.root_cache->memcg_kset;
5711 #endif
5712 return slab_kset;
5715 #define ID_STR_LENGTH 64
5717 /* Create a unique string id for a slab cache:
5719 * Format :[flags-]size
5721 static char *create_unique_id(struct kmem_cache *s)
5723 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5724 char *p = name;
5726 BUG_ON(!name);
5728 *p++ = ':';
5730 * First flags affecting slabcache operations. We will only
5731 * get here for aliasable slabs so we do not need to support
5732 * too many flags. The flags here must cover all flags that
5733 * are matched during merging to guarantee that the id is
5734 * unique.
5736 if (s->flags & SLAB_CACHE_DMA)
5737 *p++ = 'd';
5738 if (s->flags & SLAB_CACHE_DMA32)
5739 *p++ = 'D';
5740 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5741 *p++ = 'a';
5742 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5743 *p++ = 'F';
5744 if (s->flags & SLAB_ACCOUNT)
5745 *p++ = 'A';
5746 if (p != name + 1)
5747 *p++ = '-';
5748 p += sprintf(p, "%07u", s->size);
5750 BUG_ON(p > name + ID_STR_LENGTH - 1);
5751 return name;
5754 static void sysfs_slab_remove_workfn(struct work_struct *work)
5756 struct kmem_cache *s =
5757 container_of(work, struct kmem_cache, kobj_remove_work);
5759 if (!s->kobj.state_in_sysfs)
5761 * For a memcg cache, this may be called during
5762 * deactivation and again on shutdown. Remove only once.
5763 * A cache is never shut down before deactivation is
5764 * complete, so no need to worry about synchronization.
5766 goto out;
5768 #ifdef CONFIG_MEMCG
5769 kset_unregister(s->memcg_kset);
5770 #endif
5771 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5772 out:
5773 kobject_put(&s->kobj);
5776 static int sysfs_slab_add(struct kmem_cache *s)
5778 int err;
5779 const char *name;
5780 struct kset *kset = cache_kset(s);
5781 int unmergeable = slab_unmergeable(s);
5783 INIT_WORK(&s->kobj_remove_work, sysfs_slab_remove_workfn);
5785 if (!kset) {
5786 kobject_init(&s->kobj, &slab_ktype);
5787 return 0;
5790 if (!unmergeable && disable_higher_order_debug &&
5791 (slub_debug & DEBUG_METADATA_FLAGS))
5792 unmergeable = 1;
5794 if (unmergeable) {
5796 * Slabcache can never be merged so we can use the name proper.
5797 * This is typically the case for debug situations. In that
5798 * case we can catch duplicate names easily.
5800 sysfs_remove_link(&slab_kset->kobj, s->name);
5801 name = s->name;
5802 } else {
5804 * Create a unique name for the slab as a target
5805 * for the symlinks.
5807 name = create_unique_id(s);
5810 s->kobj.kset = kset;
5811 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5812 if (err) {
5813 kobject_put(&s->kobj);
5814 goto out;
5817 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5818 if (err)
5819 goto out_del_kobj;
5821 #ifdef CONFIG_MEMCG
5822 if (is_root_cache(s) && memcg_sysfs_enabled) {
5823 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5824 if (!s->memcg_kset) {
5825 err = -ENOMEM;
5826 goto out_del_kobj;
5829 #endif
5831 kobject_uevent(&s->kobj, KOBJ_ADD);
5832 if (!unmergeable) {
5833 /* Setup first alias */
5834 sysfs_slab_alias(s, s->name);
5836 out:
5837 if (!unmergeable)
5838 kfree(name);
5839 return err;
5840 out_del_kobj:
5841 kobject_del(&s->kobj);
5842 goto out;
5845 static void sysfs_slab_remove(struct kmem_cache *s)
5847 if (slab_state < FULL)
5849 * Sysfs has not been setup yet so no need to remove the
5850 * cache from sysfs.
5852 return;
5854 kobject_get(&s->kobj);
5855 schedule_work(&s->kobj_remove_work);
5858 void sysfs_slab_unlink(struct kmem_cache *s)
5860 if (slab_state >= FULL)
5861 kobject_del(&s->kobj);
5864 void sysfs_slab_release(struct kmem_cache *s)
5866 if (slab_state >= FULL)
5867 kobject_put(&s->kobj);
5871 * Need to buffer aliases during bootup until sysfs becomes
5872 * available lest we lose that information.
5874 struct saved_alias {
5875 struct kmem_cache *s;
5876 const char *name;
5877 struct saved_alias *next;
5880 static struct saved_alias *alias_list;
5882 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5884 struct saved_alias *al;
5886 if (slab_state == FULL) {
5888 * If we have a leftover link then remove it.
5890 sysfs_remove_link(&slab_kset->kobj, name);
5891 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5894 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5895 if (!al)
5896 return -ENOMEM;
5898 al->s = s;
5899 al->name = name;
5900 al->next = alias_list;
5901 alias_list = al;
5902 return 0;
5905 static int __init slab_sysfs_init(void)
5907 struct kmem_cache *s;
5908 int err;
5910 mutex_lock(&slab_mutex);
5912 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5913 if (!slab_kset) {
5914 mutex_unlock(&slab_mutex);
5915 pr_err("Cannot register slab subsystem.\n");
5916 return -ENOSYS;
5919 slab_state = FULL;
5921 list_for_each_entry(s, &slab_caches, list) {
5922 err = sysfs_slab_add(s);
5923 if (err)
5924 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5925 s->name);
5928 while (alias_list) {
5929 struct saved_alias *al = alias_list;
5931 alias_list = alias_list->next;
5932 err = sysfs_slab_alias(al->s, al->name);
5933 if (err)
5934 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5935 al->name);
5936 kfree(al);
5939 mutex_unlock(&slab_mutex);
5940 resiliency_test();
5941 return 0;
5944 __initcall(slab_sysfs_init);
5945 #endif /* CONFIG_SYSFS */
5948 * The /proc/slabinfo ABI
5950 #ifdef CONFIG_SLUB_DEBUG
5951 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5953 unsigned long nr_slabs = 0;
5954 unsigned long nr_objs = 0;
5955 unsigned long nr_free = 0;
5956 int node;
5957 struct kmem_cache_node *n;
5959 for_each_kmem_cache_node(s, node, n) {
5960 nr_slabs += node_nr_slabs(n);
5961 nr_objs += node_nr_objs(n);
5962 nr_free += count_partial(n, count_free);
5965 sinfo->active_objs = nr_objs - nr_free;
5966 sinfo->num_objs = nr_objs;
5967 sinfo->active_slabs = nr_slabs;
5968 sinfo->num_slabs = nr_slabs;
5969 sinfo->objects_per_slab = oo_objects(s->oo);
5970 sinfo->cache_order = oo_order(s->oo);
5973 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5977 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5978 size_t count, loff_t *ppos)
5980 return -EIO;
5982 #endif /* CONFIG_SLUB_DEBUG */