blob: ca7143fe25b56d683d14d48aa3968753da5904cb [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// 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.
5 *
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.
8 *
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
11 */
12
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>
Olivier Deprez0e641232021-09-23 10:07:05 +020018#include <linux/swab.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000019#include <linux/bitops.h>
20#include <linux/slab.h>
21#include "slab.h"
22#include <linux/proc_fs.h>
23#include <linux/seq_file.h>
24#include <linux/kasan.h>
25#include <linux/cpu.h>
26#include <linux/cpuset.h>
27#include <linux/mempolicy.h>
28#include <linux/ctype.h>
29#include <linux/debugobjects.h>
30#include <linux/kallsyms.h>
31#include <linux/memory.h>
32#include <linux/math64.h>
33#include <linux/fault-inject.h>
34#include <linux/stacktrace.h>
35#include <linux/prefetch.h>
36#include <linux/memcontrol.h>
37#include <linux/random.h>
38
39#include <trace/events/kmem.h>
40
41#include "internal.h"
42
43/*
44 * Lock order:
45 * 1. slab_mutex (Global Mutex)
46 * 2. node->list_lock
47 * 3. slab_lock(page) (Only on some arches and for debugging)
48 *
49 * slab_mutex
50 *
51 * The role of the slab_mutex is to protect the list of all the slabs
52 * and to synchronize major metadata changes to slab cache structures.
53 *
54 * The slab_lock is only used for debugging and on arches that do not
55 * have the ability to do a cmpxchg_double. It only protects:
56 * A. page->freelist -> List of object free in a page
57 * B. page->inuse -> Number of objects in use
58 * C. page->objects -> Number of objects in page
59 * D. page->frozen -> frozen state
60 *
61 * If a slab is frozen then it is exempt from list management. It is not
David Brazdil0f672f62019-12-10 10:32:29 +000062 * on any list except per cpu partial list. The processor that froze the
63 * slab is the one who can perform list operations on the page. Other
64 * processors may put objects onto the freelist but the processor that
65 * froze the slab is the only one that can retrieve the objects from the
66 * page's freelist.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000067 *
68 * The list_lock protects the partial and full list on each node and
69 * the partial slab counter. If taken then no new slabs may be added or
70 * removed from the lists nor make the number of partial slabs be modified.
71 * (Note that the total number of slabs is an atomic value that may be
72 * modified without taking the list lock).
73 *
74 * The list_lock is a centralized lock and thus we avoid taking it as
75 * much as possible. As long as SLUB does not have to handle partial
76 * slabs, operations can continue without any centralized lock. F.e.
77 * allocating a long series of objects that fill up slabs does not require
78 * the list lock.
79 * Interrupts are disabled during allocation and deallocation in order to
80 * make the slab allocator safe to use in the context of an irq. In addition
81 * interrupts are disabled to ensure that the processor does not change
82 * while handling per_cpu slabs, due to kernel preemption.
83 *
84 * SLUB assigns one slab for allocation to each processor.
85 * Allocations only occur from these slabs called cpu slabs.
86 *
87 * Slabs with free elements are kept on a partial list and during regular
88 * operations no list for full slabs is used. If an object in a full slab is
89 * freed then the slab will show up again on the partial lists.
90 * We track full slabs for debugging purposes though because otherwise we
91 * cannot scan all objects.
92 *
93 * Slabs are freed when they become empty. Teardown and setup is
94 * minimal so we rely on the page allocators per cpu caches for
95 * fast frees and allocs.
96 *
97 * Overloading of page flags that are otherwise used for LRU management.
98 *
99 * PageActive The slab is frozen and exempt from list processing.
100 * This means that the slab is dedicated to a purpose
101 * such as satisfying allocations for a specific
102 * processor. Objects may be freed in the slab while
103 * it is frozen but slab_free will then skip the usual
104 * list operations. It is up to the processor holding
105 * the slab to integrate the slab into the slab lists
106 * when the slab is no longer needed.
107 *
108 * One use of this flag is to mark slabs that are
109 * used for allocations. Then such a slab becomes a cpu
110 * slab. The cpu slab may be equipped with an additional
111 * freelist that allows lockless access to
112 * free objects in addition to the regular freelist
113 * that requires the slab lock.
114 *
115 * PageError Slab requires special handling due to debug
116 * options set. This moves slab handling out of
117 * the fast path and disables lockless freelists.
118 */
119
120static inline int kmem_cache_debug(struct kmem_cache *s)
121{
122#ifdef CONFIG_SLUB_DEBUG
123 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
124#else
125 return 0;
126#endif
127}
128
129void *fixup_red_left(struct kmem_cache *s, void *p)
130{
131 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE)
132 p += s->red_left_pad;
133
134 return p;
135}
136
137static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
138{
139#ifdef CONFIG_SLUB_CPU_PARTIAL
140 return !kmem_cache_debug(s);
141#else
142 return false;
143#endif
144}
145
146/*
147 * Issues still to be resolved:
148 *
149 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
150 *
151 * - Variable sizing of the per node arrays
152 */
153
154/* Enable to test recovery from slab corruption on boot */
155#undef SLUB_RESILIENCY_TEST
156
157/* Enable to log cmpxchg failures */
158#undef SLUB_DEBUG_CMPXCHG
159
160/*
161 * Mininum number of partial slabs. These will be left on the partial
162 * lists even if they are empty. kmem_cache_shrink may reclaim them.
163 */
164#define MIN_PARTIAL 5
165
166/*
167 * Maximum number of desirable partial slabs.
168 * The existence of more partial slabs makes kmem_cache_shrink
169 * sort the partial list by the number of objects in use.
170 */
171#define MAX_PARTIAL 10
172
173#define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
174 SLAB_POISON | SLAB_STORE_USER)
175
176/*
177 * These debug flags cannot use CMPXCHG because there might be consistency
178 * issues when checking or reading debug information
179 */
180#define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
181 SLAB_TRACE)
182
183
184/*
185 * Debugging flags that require metadata to be stored in the slab. These get
186 * disabled when slub_debug=O is used and a cache's min order increases with
187 * metadata.
188 */
189#define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
190
191#define OO_SHIFT 16
192#define OO_MASK ((1 << OO_SHIFT) - 1)
193#define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
194
195/* Internal SLUB flags */
196/* Poison object */
197#define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
198/* Use cmpxchg_double */
199#define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
200
201/*
202 * Tracking user of a slab.
203 */
204#define TRACK_ADDRS_COUNT 16
205struct track {
206 unsigned long addr; /* Called from address */
207#ifdef CONFIG_STACKTRACE
208 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
209#endif
210 int cpu; /* Was running on cpu */
211 int pid; /* Pid context */
212 unsigned long when; /* When did the operation occur */
213};
214
215enum track_item { TRACK_ALLOC, TRACK_FREE };
216
217#ifdef CONFIG_SYSFS
218static int sysfs_slab_add(struct kmem_cache *);
219static int sysfs_slab_alias(struct kmem_cache *, const char *);
220static void memcg_propagate_slab_attrs(struct kmem_cache *s);
221static void sysfs_slab_remove(struct kmem_cache *s);
222#else
223static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
224static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
225 { return 0; }
226static inline void memcg_propagate_slab_attrs(struct kmem_cache *s) { }
227static inline void sysfs_slab_remove(struct kmem_cache *s) { }
228#endif
229
230static inline void stat(const struct kmem_cache *s, enum stat_item si)
231{
232#ifdef CONFIG_SLUB_STATS
233 /*
234 * The rmw is racy on a preemptible kernel but this is acceptable, so
235 * avoid this_cpu_add()'s irq-disable overhead.
236 */
237 raw_cpu_inc(s->cpu_slab->stat[si]);
238#endif
239}
240
241/********************************************************************
242 * Core slab cache functions
243 *******************************************************************/
244
245/*
246 * Returns freelist pointer (ptr). With hardening, this is obfuscated
247 * with an XOR of the address where the pointer is held and a per-cache
248 * random number.
249 */
250static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
251 unsigned long ptr_addr)
252{
253#ifdef CONFIG_SLAB_FREELIST_HARDENED
David Brazdil0f672f62019-12-10 10:32:29 +0000254 /*
255 * When CONFIG_KASAN_SW_TAGS is enabled, ptr_addr might be tagged.
256 * Normally, this doesn't cause any issues, as both set_freepointer()
257 * and get_freepointer() are called with a pointer with the same tag.
258 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
259 * example, when __free_slub() iterates over objects in a cache, it
260 * passes untagged pointers to check_object(). check_object() in turns
261 * calls get_freepointer() with an untagged pointer, which causes the
262 * freepointer to be restored incorrectly.
263 */
264 return (void *)((unsigned long)ptr ^ s->random ^
Olivier Deprez0e641232021-09-23 10:07:05 +0200265 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000266#else
267 return ptr;
268#endif
269}
270
271/* Returns the freelist pointer recorded at location ptr_addr. */
272static inline void *freelist_dereference(const struct kmem_cache *s,
273 void *ptr_addr)
274{
275 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
276 (unsigned long)ptr_addr);
277}
278
279static inline void *get_freepointer(struct kmem_cache *s, void *object)
280{
281 return freelist_dereference(s, object + s->offset);
282}
283
284static void prefetch_freepointer(const struct kmem_cache *s, void *object)
285{
286 prefetch(object + s->offset);
287}
288
289static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
290{
291 unsigned long freepointer_addr;
292 void *p;
293
Olivier Deprez0e641232021-09-23 10:07:05 +0200294 if (!debug_pagealloc_enabled_static())
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000295 return get_freepointer(s, object);
296
297 freepointer_addr = (unsigned long)object + s->offset;
298 probe_kernel_read(&p, (void **)freepointer_addr, sizeof(p));
299 return freelist_ptr(s, p, freepointer_addr);
300}
301
302static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
303{
304 unsigned long freeptr_addr = (unsigned long)object + s->offset;
305
306#ifdef CONFIG_SLAB_FREELIST_HARDENED
307 BUG_ON(object == fp); /* naive detection of double free or corruption */
308#endif
309
310 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
311}
312
313/* Loop over all objects in a slab */
314#define for_each_object(__p, __s, __addr, __objects) \
315 for (__p = fixup_red_left(__s, __addr); \
316 __p < (__addr) + (__objects) * (__s)->size; \
317 __p += (__s)->size)
318
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000319/* Determine object index from a given position */
320static inline unsigned int slab_index(void *p, struct kmem_cache *s, void *addr)
321{
David Brazdil0f672f62019-12-10 10:32:29 +0000322 return (kasan_reset_tag(p) - addr) / s->size;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000323}
324
325static inline unsigned int order_objects(unsigned int order, unsigned int size)
326{
327 return ((unsigned int)PAGE_SIZE << order) / size;
328}
329
330static inline struct kmem_cache_order_objects oo_make(unsigned int order,
331 unsigned int size)
332{
333 struct kmem_cache_order_objects x = {
334 (order << OO_SHIFT) + order_objects(order, size)
335 };
336
337 return x;
338}
339
340static inline unsigned int oo_order(struct kmem_cache_order_objects x)
341{
342 return x.x >> OO_SHIFT;
343}
344
345static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
346{
347 return x.x & OO_MASK;
348}
349
350/*
351 * Per slab locking using the pagelock
352 */
353static __always_inline void slab_lock(struct page *page)
354{
355 VM_BUG_ON_PAGE(PageTail(page), page);
356 bit_spin_lock(PG_locked, &page->flags);
357}
358
359static __always_inline void slab_unlock(struct page *page)
360{
361 VM_BUG_ON_PAGE(PageTail(page), page);
362 __bit_spin_unlock(PG_locked, &page->flags);
363}
364
365/* Interrupts must be disabled (for the fallback code to work right) */
366static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
367 void *freelist_old, unsigned long counters_old,
368 void *freelist_new, unsigned long counters_new,
369 const char *n)
370{
371 VM_BUG_ON(!irqs_disabled());
372#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
373 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
374 if (s->flags & __CMPXCHG_DOUBLE) {
375 if (cmpxchg_double(&page->freelist, &page->counters,
376 freelist_old, counters_old,
377 freelist_new, counters_new))
378 return true;
379 } else
380#endif
381 {
382 slab_lock(page);
383 if (page->freelist == freelist_old &&
384 page->counters == counters_old) {
385 page->freelist = freelist_new;
386 page->counters = counters_new;
387 slab_unlock(page);
388 return true;
389 }
390 slab_unlock(page);
391 }
392
393 cpu_relax();
394 stat(s, CMPXCHG_DOUBLE_FAIL);
395
396#ifdef SLUB_DEBUG_CMPXCHG
397 pr_info("%s %s: cmpxchg double redo ", n, s->name);
398#endif
399
400 return false;
401}
402
403static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
404 void *freelist_old, unsigned long counters_old,
405 void *freelist_new, unsigned long counters_new,
406 const char *n)
407{
408#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
409 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
410 if (s->flags & __CMPXCHG_DOUBLE) {
411 if (cmpxchg_double(&page->freelist, &page->counters,
412 freelist_old, counters_old,
413 freelist_new, counters_new))
414 return true;
415 } else
416#endif
417 {
418 unsigned long flags;
419
420 local_irq_save(flags);
421 slab_lock(page);
422 if (page->freelist == freelist_old &&
423 page->counters == counters_old) {
424 page->freelist = freelist_new;
425 page->counters = counters_new;
426 slab_unlock(page);
427 local_irq_restore(flags);
428 return true;
429 }
430 slab_unlock(page);
431 local_irq_restore(flags);
432 }
433
434 cpu_relax();
435 stat(s, CMPXCHG_DOUBLE_FAIL);
436
437#ifdef SLUB_DEBUG_CMPXCHG
438 pr_info("%s %s: cmpxchg double redo ", n, s->name);
439#endif
440
441 return false;
442}
443
444#ifdef CONFIG_SLUB_DEBUG
445/*
446 * Determine a map of object in use on a page.
447 *
448 * Node listlock must be held to guarantee that the page does
449 * not vanish from under us.
450 */
451static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
452{
453 void *p;
454 void *addr = page_address(page);
455
456 for (p = page->freelist; p; p = get_freepointer(s, p))
457 set_bit(slab_index(p, s, addr), map);
458}
459
460static inline unsigned int size_from_object(struct kmem_cache *s)
461{
462 if (s->flags & SLAB_RED_ZONE)
463 return s->size - s->red_left_pad;
464
465 return s->size;
466}
467
468static inline void *restore_red_left(struct kmem_cache *s, void *p)
469{
470 if (s->flags & SLAB_RED_ZONE)
471 p -= s->red_left_pad;
472
473 return p;
474}
475
476/*
477 * Debug settings:
478 */
479#if defined(CONFIG_SLUB_DEBUG_ON)
480static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
481#else
482static slab_flags_t slub_debug;
483#endif
484
485static char *slub_debug_slabs;
486static int disable_higher_order_debug;
487
488/*
489 * slub is about to manipulate internal object metadata. This memory lies
490 * outside the range of the allocated object, so accessing it would normally
491 * be reported by kasan as a bounds error. metadata_access_enable() is used
492 * to tell kasan that these accesses are OK.
493 */
494static inline void metadata_access_enable(void)
495{
496 kasan_disable_current();
497}
498
499static inline void metadata_access_disable(void)
500{
501 kasan_enable_current();
502}
503
504/*
505 * Object debugging
506 */
507
508/* Verify that a pointer has an address that is valid within a slab page */
509static inline int check_valid_pointer(struct kmem_cache *s,
510 struct page *page, void *object)
511{
512 void *base;
513
514 if (!object)
515 return 1;
516
517 base = page_address(page);
David Brazdil0f672f62019-12-10 10:32:29 +0000518 object = kasan_reset_tag(object);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000519 object = restore_red_left(s, object);
520 if (object < base || object >= base + page->objects * s->size ||
521 (object - base) % s->size) {
522 return 0;
523 }
524
525 return 1;
526}
527
528static void print_section(char *level, char *text, u8 *addr,
529 unsigned int length)
530{
531 metadata_access_enable();
532 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
533 length, 1);
534 metadata_access_disable();
535}
536
Olivier Deprez0e641232021-09-23 10:07:05 +0200537/*
538 * See comment in calculate_sizes().
539 */
540static inline bool freeptr_outside_object(struct kmem_cache *s)
541{
542 return s->offset >= s->inuse;
543}
544
545/*
546 * Return offset of the end of info block which is inuse + free pointer if
547 * not overlapping with object.
548 */
549static inline unsigned int get_info_end(struct kmem_cache *s)
550{
551 if (freeptr_outside_object(s))
552 return s->inuse + sizeof(void *);
553 else
554 return s->inuse;
555}
556
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000557static struct track *get_track(struct kmem_cache *s, void *object,
558 enum track_item alloc)
559{
560 struct track *p;
561
Olivier Deprez0e641232021-09-23 10:07:05 +0200562 p = object + get_info_end(s);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000563
564 return p + alloc;
565}
566
567static void set_track(struct kmem_cache *s, void *object,
568 enum track_item alloc, unsigned long addr)
569{
570 struct track *p = get_track(s, object, alloc);
571
572 if (addr) {
573#ifdef CONFIG_STACKTRACE
David Brazdil0f672f62019-12-10 10:32:29 +0000574 unsigned int nr_entries;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000575
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000576 metadata_access_enable();
David Brazdil0f672f62019-12-10 10:32:29 +0000577 nr_entries = stack_trace_save(p->addrs, TRACK_ADDRS_COUNT, 3);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000578 metadata_access_disable();
579
David Brazdil0f672f62019-12-10 10:32:29 +0000580 if (nr_entries < TRACK_ADDRS_COUNT)
581 p->addrs[nr_entries] = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000582#endif
583 p->addr = addr;
584 p->cpu = smp_processor_id();
585 p->pid = current->pid;
586 p->when = jiffies;
David Brazdil0f672f62019-12-10 10:32:29 +0000587 } else {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000588 memset(p, 0, sizeof(struct track));
David Brazdil0f672f62019-12-10 10:32:29 +0000589 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000590}
591
592static void init_tracking(struct kmem_cache *s, void *object)
593{
594 if (!(s->flags & SLAB_STORE_USER))
595 return;
596
597 set_track(s, object, TRACK_FREE, 0UL);
598 set_track(s, object, TRACK_ALLOC, 0UL);
599}
600
601static void print_track(const char *s, struct track *t, unsigned long pr_time)
602{
603 if (!t->addr)
604 return;
605
606 pr_err("INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
607 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
608#ifdef CONFIG_STACKTRACE
609 {
610 int i;
611 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
612 if (t->addrs[i])
613 pr_err("\t%pS\n", (void *)t->addrs[i]);
614 else
615 break;
616 }
617#endif
618}
619
620static void print_tracking(struct kmem_cache *s, void *object)
621{
622 unsigned long pr_time = jiffies;
623 if (!(s->flags & SLAB_STORE_USER))
624 return;
625
626 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
627 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
628}
629
630static void print_page_info(struct page *page)
631{
632 pr_err("INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
633 page, page->objects, page->inuse, page->freelist, page->flags);
634
635}
636
637static void slab_bug(struct kmem_cache *s, char *fmt, ...)
638{
639 struct va_format vaf;
640 va_list args;
641
642 va_start(args, fmt);
643 vaf.fmt = fmt;
644 vaf.va = &args;
645 pr_err("=============================================================================\n");
646 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
647 pr_err("-----------------------------------------------------------------------------\n\n");
648
649 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
650 va_end(args);
651}
652
653static void slab_fix(struct kmem_cache *s, char *fmt, ...)
654{
655 struct va_format vaf;
656 va_list args;
657
658 va_start(args, fmt);
659 vaf.fmt = fmt;
660 vaf.va = &args;
661 pr_err("FIX %s: %pV\n", s->name, &vaf);
662 va_end(args);
663}
664
Olivier Deprez0e641232021-09-23 10:07:05 +0200665static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
666 void **freelist, void *nextfree)
667{
668 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
669 !check_valid_pointer(s, page, nextfree) && freelist) {
670 object_err(s, page, *freelist, "Freechain corrupt");
671 *freelist = NULL;
672 slab_fix(s, "Isolate corrupted freechain");
673 return true;
674 }
675
676 return false;
677}
678
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000679static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
680{
681 unsigned int off; /* Offset of last byte */
682 u8 *addr = page_address(page);
683
684 print_tracking(s, p);
685
686 print_page_info(page);
687
688 pr_err("INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
689 p, p - addr, get_freepointer(s, p));
690
691 if (s->flags & SLAB_RED_ZONE)
Olivier Deprez0e641232021-09-23 10:07:05 +0200692 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000693 s->red_left_pad);
694 else if (p > addr + 16)
695 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
696
Olivier Deprez0e641232021-09-23 10:07:05 +0200697 print_section(KERN_ERR, "Object ", p,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000698 min_t(unsigned int, s->object_size, PAGE_SIZE));
699 if (s->flags & SLAB_RED_ZONE)
Olivier Deprez0e641232021-09-23 10:07:05 +0200700 print_section(KERN_ERR, "Redzone ", p + s->object_size,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000701 s->inuse - s->object_size);
702
Olivier Deprez0e641232021-09-23 10:07:05 +0200703 off = get_info_end(s);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000704
705 if (s->flags & SLAB_STORE_USER)
706 off += 2 * sizeof(struct track);
707
708 off += kasan_metadata_size(s);
709
710 if (off != size_from_object(s))
711 /* Beginning of the filler is the free pointer */
Olivier Deprez0e641232021-09-23 10:07:05 +0200712 print_section(KERN_ERR, "Padding ", p + off,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000713 size_from_object(s) - off);
714
715 dump_stack();
716}
717
718void object_err(struct kmem_cache *s, struct page *page,
719 u8 *object, char *reason)
720{
721 slab_bug(s, "%s", reason);
722 print_trailer(s, page, object);
723}
724
725static __printf(3, 4) void slab_err(struct kmem_cache *s, struct page *page,
726 const char *fmt, ...)
727{
728 va_list args;
729 char buf[100];
730
731 va_start(args, fmt);
732 vsnprintf(buf, sizeof(buf), fmt, args);
733 va_end(args);
734 slab_bug(s, "%s", buf);
735 print_page_info(page);
736 dump_stack();
737}
738
739static void init_object(struct kmem_cache *s, void *object, u8 val)
740{
741 u8 *p = object;
742
743 if (s->flags & SLAB_RED_ZONE)
744 memset(p - s->red_left_pad, val, s->red_left_pad);
745
746 if (s->flags & __OBJECT_POISON) {
747 memset(p, POISON_FREE, s->object_size - 1);
748 p[s->object_size - 1] = POISON_END;
749 }
750
751 if (s->flags & SLAB_RED_ZONE)
752 memset(p + s->object_size, val, s->inuse - s->object_size);
753}
754
755static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
756 void *from, void *to)
757{
758 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
759 memset(from, data, to - from);
760}
761
762static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
763 u8 *object, char *what,
764 u8 *start, unsigned int value, unsigned int bytes)
765{
766 u8 *fault;
767 u8 *end;
768
769 metadata_access_enable();
770 fault = memchr_inv(start, value, bytes);
771 metadata_access_disable();
772 if (!fault)
773 return 1;
774
775 end = start + bytes;
776 while (end > fault && end[-1] == value)
777 end--;
778
779 slab_bug(s, "%s overwritten", what);
780 pr_err("INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
781 fault, end - 1, fault[0], value);
782 print_trailer(s, page, object);
783
784 restore_bytes(s, what, value, fault, end);
785 return 0;
786}
787
788/*
789 * Object layout:
790 *
791 * object address
792 * Bytes of the object to be managed.
793 * If the freepointer may overlay the object then the free
Olivier Deprez0e641232021-09-23 10:07:05 +0200794 * pointer is at the middle of the object.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000795 *
796 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
797 * 0xa5 (POISON_END)
798 *
799 * object + s->object_size
800 * Padding to reach word boundary. This is also used for Redzoning.
801 * Padding is extended by another word if Redzoning is enabled and
802 * object_size == inuse.
803 *
804 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
805 * 0xcc (RED_ACTIVE) for objects in use.
806 *
807 * object + s->inuse
808 * Meta data starts here.
809 *
810 * A. Free pointer (if we cannot overwrite object on free)
811 * B. Tracking data for SLAB_STORE_USER
812 * C. Padding to reach required alignment boundary or at mininum
813 * one word if debugging is on to be able to detect writes
814 * before the word boundary.
815 *
816 * Padding is done using 0x5a (POISON_INUSE)
817 *
818 * object + s->size
819 * Nothing is used beyond s->size.
820 *
821 * If slabcaches are merged then the object_size and inuse boundaries are mostly
822 * ignored. And therefore no slab options that rely on these boundaries
823 * may be used with merged slabcaches.
824 */
825
826static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
827{
Olivier Deprez0e641232021-09-23 10:07:05 +0200828 unsigned long off = get_info_end(s); /* The end of info */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000829
830 if (s->flags & SLAB_STORE_USER)
831 /* We also have user information there */
832 off += 2 * sizeof(struct track);
833
834 off += kasan_metadata_size(s);
835
836 if (size_from_object(s) == off)
837 return 1;
838
839 return check_bytes_and_report(s, page, p, "Object padding",
840 p + off, POISON_INUSE, size_from_object(s) - off);
841}
842
843/* Check the pad bytes at the end of a slab page */
844static int slab_pad_check(struct kmem_cache *s, struct page *page)
845{
846 u8 *start;
847 u8 *fault;
848 u8 *end;
849 u8 *pad;
850 int length;
851 int remainder;
852
853 if (!(s->flags & SLAB_POISON))
854 return 1;
855
856 start = page_address(page);
David Brazdil0f672f62019-12-10 10:32:29 +0000857 length = page_size(page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000858 end = start + length;
859 remainder = length % s->size;
860 if (!remainder)
861 return 1;
862
863 pad = end - remainder;
864 metadata_access_enable();
865 fault = memchr_inv(pad, POISON_INUSE, remainder);
866 metadata_access_disable();
867 if (!fault)
868 return 1;
869 while (end > fault && end[-1] == POISON_INUSE)
870 end--;
871
872 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
873 print_section(KERN_ERR, "Padding ", pad, remainder);
874
875 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
876 return 0;
877}
878
879static int check_object(struct kmem_cache *s, struct page *page,
880 void *object, u8 val)
881{
882 u8 *p = object;
883 u8 *endobject = object + s->object_size;
884
885 if (s->flags & SLAB_RED_ZONE) {
Olivier Deprez0e641232021-09-23 10:07:05 +0200886 if (!check_bytes_and_report(s, page, object, "Left Redzone",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000887 object - s->red_left_pad, val, s->red_left_pad))
888 return 0;
889
Olivier Deprez0e641232021-09-23 10:07:05 +0200890 if (!check_bytes_and_report(s, page, object, "Right Redzone",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000891 endobject, val, s->inuse - s->object_size))
892 return 0;
893 } else {
894 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
895 check_bytes_and_report(s, page, p, "Alignment padding",
896 endobject, POISON_INUSE,
897 s->inuse - s->object_size);
898 }
899 }
900
901 if (s->flags & SLAB_POISON) {
902 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
903 (!check_bytes_and_report(s, page, p, "Poison", p,
904 POISON_FREE, s->object_size - 1) ||
Olivier Deprez0e641232021-09-23 10:07:05 +0200905 !check_bytes_and_report(s, page, p, "End Poison",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000906 p + s->object_size - 1, POISON_END, 1)))
907 return 0;
908 /*
909 * check_pad_bytes cleans up on its own.
910 */
911 check_pad_bytes(s, page, p);
912 }
913
Olivier Deprez0e641232021-09-23 10:07:05 +0200914 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +0000915 /*
916 * Object and freepointer overlap. Cannot check
917 * freepointer while object is allocated.
918 */
919 return 1;
920
921 /* Check free pointer validity */
922 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
923 object_err(s, page, p, "Freepointer corrupt");
924 /*
925 * No choice but to zap it and thus lose the remainder
926 * of the free objects in this slab. May cause
927 * another error because the object count is now wrong.
928 */
929 set_freepointer(s, p, NULL);
930 return 0;
931 }
932 return 1;
933}
934
935static int check_slab(struct kmem_cache *s, struct page *page)
936{
937 int maxobj;
938
939 VM_BUG_ON(!irqs_disabled());
940
941 if (!PageSlab(page)) {
942 slab_err(s, page, "Not a valid slab page");
943 return 0;
944 }
945
946 maxobj = order_objects(compound_order(page), s->size);
947 if (page->objects > maxobj) {
948 slab_err(s, page, "objects %u > max %u",
949 page->objects, maxobj);
950 return 0;
951 }
952 if (page->inuse > page->objects) {
953 slab_err(s, page, "inuse %u > max %u",
954 page->inuse, page->objects);
955 return 0;
956 }
957 /* Slab_pad_check fixes things up after itself */
958 slab_pad_check(s, page);
959 return 1;
960}
961
962/*
963 * Determine if a certain object on a page is on the freelist. Must hold the
964 * slab lock to guarantee that the chains are in a consistent state.
965 */
966static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
967{
968 int nr = 0;
969 void *fp;
970 void *object = NULL;
971 int max_objects;
972
973 fp = page->freelist;
974 while (fp && nr <= page->objects) {
975 if (fp == search)
976 return 1;
977 if (!check_valid_pointer(s, page, fp)) {
978 if (object) {
979 object_err(s, page, object,
980 "Freechain corrupt");
981 set_freepointer(s, object, NULL);
982 } else {
983 slab_err(s, page, "Freepointer corrupt");
984 page->freelist = NULL;
985 page->inuse = page->objects;
986 slab_fix(s, "Freelist cleared");
987 return 0;
988 }
989 break;
990 }
991 object = fp;
992 fp = get_freepointer(s, object);
993 nr++;
994 }
995
996 max_objects = order_objects(compound_order(page), s->size);
997 if (max_objects > MAX_OBJS_PER_PAGE)
998 max_objects = MAX_OBJS_PER_PAGE;
999
1000 if (page->objects != max_objects) {
1001 slab_err(s, page, "Wrong number of objects. Found %d but should be %d",
1002 page->objects, max_objects);
1003 page->objects = max_objects;
1004 slab_fix(s, "Number of objects adjusted.");
1005 }
1006 if (page->inuse != page->objects - nr) {
1007 slab_err(s, page, "Wrong object count. Counter is %d but counted were %d",
1008 page->inuse, page->objects - nr);
1009 page->inuse = page->objects - nr;
1010 slab_fix(s, "Object count adjusted.");
1011 }
1012 return search == NULL;
1013}
1014
1015static void trace(struct kmem_cache *s, struct page *page, void *object,
1016 int alloc)
1017{
1018 if (s->flags & SLAB_TRACE) {
1019 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1020 s->name,
1021 alloc ? "alloc" : "free",
1022 object, page->inuse,
1023 page->freelist);
1024
1025 if (!alloc)
1026 print_section(KERN_INFO, "Object ", (void *)object,
1027 s->object_size);
1028
1029 dump_stack();
1030 }
1031}
1032
1033/*
1034 * Tracking of fully allocated slabs for debugging purposes.
1035 */
1036static void add_full(struct kmem_cache *s,
1037 struct kmem_cache_node *n, struct page *page)
1038{
1039 if (!(s->flags & SLAB_STORE_USER))
1040 return;
1041
1042 lockdep_assert_held(&n->list_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001043 list_add(&page->slab_list, &n->full);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001044}
1045
1046static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct page *page)
1047{
1048 if (!(s->flags & SLAB_STORE_USER))
1049 return;
1050
1051 lockdep_assert_held(&n->list_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001052 list_del(&page->slab_list);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001053}
1054
1055/* Tracking of the number of slabs for debugging purposes */
1056static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1057{
1058 struct kmem_cache_node *n = get_node(s, node);
1059
1060 return atomic_long_read(&n->nr_slabs);
1061}
1062
1063static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1064{
1065 return atomic_long_read(&n->nr_slabs);
1066}
1067
1068static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1069{
1070 struct kmem_cache_node *n = get_node(s, node);
1071
1072 /*
1073 * May be called early in order to allocate a slab for the
1074 * kmem_cache_node structure. Solve the chicken-egg
1075 * dilemma by deferring the increment of the count during
1076 * bootstrap (see early_kmem_cache_node_alloc).
1077 */
1078 if (likely(n)) {
1079 atomic_long_inc(&n->nr_slabs);
1080 atomic_long_add(objects, &n->total_objects);
1081 }
1082}
1083static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1084{
1085 struct kmem_cache_node *n = get_node(s, node);
1086
1087 atomic_long_dec(&n->nr_slabs);
1088 atomic_long_sub(objects, &n->total_objects);
1089}
1090
1091/* Object debug checks for alloc/free paths */
1092static void setup_object_debug(struct kmem_cache *s, struct page *page,
1093 void *object)
1094{
1095 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1096 return;
1097
1098 init_object(s, object, SLUB_RED_INACTIVE);
1099 init_tracking(s, object);
1100}
1101
David Brazdil0f672f62019-12-10 10:32:29 +00001102static
1103void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr)
1104{
1105 if (!(s->flags & SLAB_POISON))
1106 return;
1107
1108 metadata_access_enable();
1109 memset(addr, POISON_INUSE, page_size(page));
1110 metadata_access_disable();
1111}
1112
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001113static inline int alloc_consistency_checks(struct kmem_cache *s,
David Brazdil0f672f62019-12-10 10:32:29 +00001114 struct page *page, void *object)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001115{
1116 if (!check_slab(s, page))
1117 return 0;
1118
1119 if (!check_valid_pointer(s, page, object)) {
1120 object_err(s, page, object, "Freelist Pointer check fails");
1121 return 0;
1122 }
1123
1124 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1125 return 0;
1126
1127 return 1;
1128}
1129
1130static noinline int alloc_debug_processing(struct kmem_cache *s,
1131 struct page *page,
1132 void *object, unsigned long addr)
1133{
1134 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
David Brazdil0f672f62019-12-10 10:32:29 +00001135 if (!alloc_consistency_checks(s, page, object))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001136 goto bad;
1137 }
1138
1139 /* Success perform special debug activities for allocs */
1140 if (s->flags & SLAB_STORE_USER)
1141 set_track(s, object, TRACK_ALLOC, addr);
1142 trace(s, page, object, 1);
1143 init_object(s, object, SLUB_RED_ACTIVE);
1144 return 1;
1145
1146bad:
1147 if (PageSlab(page)) {
1148 /*
1149 * If this is a slab page then lets do the best we can
1150 * to avoid issues in the future. Marking all objects
1151 * as used avoids touching the remaining objects.
1152 */
1153 slab_fix(s, "Marking all objects used");
1154 page->inuse = page->objects;
1155 page->freelist = NULL;
1156 }
1157 return 0;
1158}
1159
1160static inline int free_consistency_checks(struct kmem_cache *s,
1161 struct page *page, void *object, unsigned long addr)
1162{
1163 if (!check_valid_pointer(s, page, object)) {
1164 slab_err(s, page, "Invalid object pointer 0x%p", object);
1165 return 0;
1166 }
1167
1168 if (on_freelist(s, page, object)) {
1169 object_err(s, page, object, "Object already free");
1170 return 0;
1171 }
1172
1173 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1174 return 0;
1175
1176 if (unlikely(s != page->slab_cache)) {
1177 if (!PageSlab(page)) {
1178 slab_err(s, page, "Attempt to free object(0x%p) outside of slab",
1179 object);
1180 } else if (!page->slab_cache) {
1181 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1182 object);
1183 dump_stack();
1184 } else
1185 object_err(s, page, object,
1186 "page slab pointer corrupt.");
1187 return 0;
1188 }
1189 return 1;
1190}
1191
1192/* Supports checking bulk free of a constructed freelist */
1193static noinline int free_debug_processing(
1194 struct kmem_cache *s, struct page *page,
1195 void *head, void *tail, int bulk_cnt,
1196 unsigned long addr)
1197{
1198 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1199 void *object = head;
1200 int cnt = 0;
1201 unsigned long uninitialized_var(flags);
1202 int ret = 0;
1203
1204 spin_lock_irqsave(&n->list_lock, flags);
1205 slab_lock(page);
1206
1207 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1208 if (!check_slab(s, page))
1209 goto out;
1210 }
1211
1212next_object:
1213 cnt++;
1214
1215 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1216 if (!free_consistency_checks(s, page, object, addr))
1217 goto out;
1218 }
1219
1220 if (s->flags & SLAB_STORE_USER)
1221 set_track(s, object, TRACK_FREE, addr);
1222 trace(s, page, object, 0);
1223 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
1224 init_object(s, object, SLUB_RED_INACTIVE);
1225
1226 /* Reached end of constructed freelist yet? */
1227 if (object != tail) {
1228 object = get_freepointer(s, object);
1229 goto next_object;
1230 }
1231 ret = 1;
1232
1233out:
1234 if (cnt != bulk_cnt)
1235 slab_err(s, page, "Bulk freelist count(%d) invalid(%d)\n",
1236 bulk_cnt, cnt);
1237
1238 slab_unlock(page);
1239 spin_unlock_irqrestore(&n->list_lock, flags);
1240 if (!ret)
1241 slab_fix(s, "Object at 0x%p not freed", object);
1242 return ret;
1243}
1244
1245static int __init setup_slub_debug(char *str)
1246{
1247 slub_debug = DEBUG_DEFAULT_FLAGS;
1248 if (*str++ != '=' || !*str)
1249 /*
1250 * No options specified. Switch on full debugging.
1251 */
1252 goto out;
1253
1254 if (*str == ',')
1255 /*
1256 * No options but restriction on slabs. This means full
1257 * debugging for slabs matching a pattern.
1258 */
1259 goto check_slabs;
1260
1261 slub_debug = 0;
1262 if (*str == '-')
1263 /*
1264 * Switch off all debugging measures.
1265 */
1266 goto out;
1267
1268 /*
1269 * Determine which debug features should be switched on
1270 */
1271 for (; *str && *str != ','; str++) {
1272 switch (tolower(*str)) {
1273 case 'f':
1274 slub_debug |= SLAB_CONSISTENCY_CHECKS;
1275 break;
1276 case 'z':
1277 slub_debug |= SLAB_RED_ZONE;
1278 break;
1279 case 'p':
1280 slub_debug |= SLAB_POISON;
1281 break;
1282 case 'u':
1283 slub_debug |= SLAB_STORE_USER;
1284 break;
1285 case 't':
1286 slub_debug |= SLAB_TRACE;
1287 break;
1288 case 'a':
1289 slub_debug |= SLAB_FAILSLAB;
1290 break;
1291 case 'o':
1292 /*
1293 * Avoid enabling debugging on caches if its minimum
1294 * order would increase as a result.
1295 */
1296 disable_higher_order_debug = 1;
1297 break;
1298 default:
1299 pr_err("slub_debug option '%c' unknown. skipped\n",
1300 *str);
1301 }
1302 }
1303
1304check_slabs:
1305 if (*str == ',')
1306 slub_debug_slabs = str + 1;
1307out:
David Brazdil0f672f62019-12-10 10:32:29 +00001308 if ((static_branch_unlikely(&init_on_alloc) ||
1309 static_branch_unlikely(&init_on_free)) &&
1310 (slub_debug & SLAB_POISON))
1311 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001312 return 1;
1313}
1314
1315__setup("slub_debug", setup_slub_debug);
1316
David Brazdil0f672f62019-12-10 10:32:29 +00001317/*
1318 * kmem_cache_flags - apply debugging options to the cache
1319 * @object_size: the size of an object without meta data
1320 * @flags: flags to set
1321 * @name: name of the cache
1322 * @ctor: constructor function
1323 *
1324 * Debug option(s) are applied to @flags. In addition to the debug
1325 * option(s), if a slab name (or multiple) is specified i.e.
1326 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1327 * then only the select slabs will receive the debug option(s).
1328 */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001329slab_flags_t kmem_cache_flags(unsigned int object_size,
1330 slab_flags_t flags, const char *name,
1331 void (*ctor)(void *))
1332{
David Brazdil0f672f62019-12-10 10:32:29 +00001333 char *iter;
1334 size_t len;
1335
1336 /* If slub_debug = 0, it folds into the if conditional. */
1337 if (!slub_debug_slabs)
1338 return flags | slub_debug;
1339
1340 len = strlen(name);
1341 iter = slub_debug_slabs;
1342 while (*iter) {
1343 char *end, *glob;
1344 size_t cmplen;
1345
1346 end = strchrnul(iter, ',');
1347
1348 glob = strnchr(iter, end - iter, '*');
1349 if (glob)
1350 cmplen = glob - iter;
1351 else
1352 cmplen = max_t(size_t, len, (end - iter));
1353
1354 if (!strncmp(name, iter, cmplen)) {
1355 flags |= slub_debug;
1356 break;
1357 }
1358
1359 if (!*end)
1360 break;
1361 iter = end + 1;
1362 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001363
1364 return flags;
1365}
1366#else /* !CONFIG_SLUB_DEBUG */
1367static inline void setup_object_debug(struct kmem_cache *s,
1368 struct page *page, void *object) {}
David Brazdil0f672f62019-12-10 10:32:29 +00001369static inline
1370void setup_page_debug(struct kmem_cache *s, struct page *page, void *addr) {}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001371
1372static inline int alloc_debug_processing(struct kmem_cache *s,
1373 struct page *page, void *object, unsigned long addr) { return 0; }
1374
1375static inline int free_debug_processing(
1376 struct kmem_cache *s, struct page *page,
1377 void *head, void *tail, int bulk_cnt,
1378 unsigned long addr) { return 0; }
1379
1380static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1381 { return 1; }
1382static inline int check_object(struct kmem_cache *s, struct page *page,
1383 void *object, u8 val) { return 1; }
1384static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1385 struct page *page) {}
1386static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1387 struct page *page) {}
1388slab_flags_t kmem_cache_flags(unsigned int object_size,
1389 slab_flags_t flags, const char *name,
1390 void (*ctor)(void *))
1391{
1392 return flags;
1393}
1394#define slub_debug 0
1395
1396#define disable_higher_order_debug 0
1397
1398static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1399 { return 0; }
1400static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1401 { return 0; }
1402static inline void inc_slabs_node(struct kmem_cache *s, int node,
1403 int objects) {}
1404static inline void dec_slabs_node(struct kmem_cache *s, int node,
1405 int objects) {}
1406
Olivier Deprez0e641232021-09-23 10:07:05 +02001407static bool freelist_corrupted(struct kmem_cache *s, struct page *page,
1408 void **freelist, void *nextfree)
1409{
1410 return false;
1411}
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001412#endif /* CONFIG_SLUB_DEBUG */
1413
1414/*
1415 * Hooks for other subsystems that check memory allocations. In a typical
1416 * production configuration these hooks all should produce no code at all.
1417 */
David Brazdil0f672f62019-12-10 10:32:29 +00001418static inline void *kmalloc_large_node_hook(void *ptr, size_t size, gfp_t flags)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001419{
David Brazdil0f672f62019-12-10 10:32:29 +00001420 ptr = kasan_kmalloc_large(ptr, size, flags);
1421 /* As ptr might get tagged, call kmemleak hook after KASAN. */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001422 kmemleak_alloc(ptr, size, 1, flags);
David Brazdil0f672f62019-12-10 10:32:29 +00001423 return ptr;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001424}
1425
1426static __always_inline void kfree_hook(void *x)
1427{
1428 kmemleak_free(x);
1429 kasan_kfree_large(x, _RET_IP_);
1430}
1431
1432static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x)
1433{
1434 kmemleak_free_recursive(x, s->flags);
1435
1436 /*
1437 * Trouble is that we may no longer disable interrupts in the fast path
1438 * So in order to make the debug calls that expect irqs to be
1439 * disabled we need to disable interrupts temporarily.
1440 */
1441#ifdef CONFIG_LOCKDEP
1442 {
1443 unsigned long flags;
1444
1445 local_irq_save(flags);
1446 debug_check_no_locks_freed(x, s->object_size);
1447 local_irq_restore(flags);
1448 }
1449#endif
1450 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1451 debug_check_no_obj_freed(x, s->object_size);
1452
1453 /* KASAN might put x into memory quarantine, delaying its reuse */
1454 return kasan_slab_free(s, x, _RET_IP_);
1455}
1456
1457static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1458 void **head, void **tail)
1459{
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001460
1461 void *object;
1462 void *next = *head;
1463 void *old_tail = *tail ? *tail : *head;
David Brazdil0f672f62019-12-10 10:32:29 +00001464 int rsize;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001465
1466 /* Head and tail of the reconstructed freelist */
1467 *head = NULL;
1468 *tail = NULL;
1469
1470 do {
1471 object = next;
1472 next = get_freepointer(s, object);
David Brazdil0f672f62019-12-10 10:32:29 +00001473
1474 if (slab_want_init_on_free(s)) {
1475 /*
1476 * Clear the object and the metadata, but don't touch
1477 * the redzone.
1478 */
1479 memset(object, 0, s->object_size);
1480 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad
1481 : 0;
1482 memset((char *)object + s->inuse, 0,
1483 s->size - s->inuse - rsize);
1484
1485 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001486 /* If object's reuse doesn't have to be delayed */
1487 if (!slab_free_hook(s, object)) {
1488 /* Move object to the new freelist */
1489 set_freepointer(s, object, *head);
1490 *head = object;
1491 if (!*tail)
1492 *tail = object;
1493 }
1494 } while (object != old_tail);
1495
1496 if (*head == *tail)
1497 *tail = NULL;
1498
1499 return *head != NULL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001500}
1501
David Brazdil0f672f62019-12-10 10:32:29 +00001502static void *setup_object(struct kmem_cache *s, struct page *page,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001503 void *object)
1504{
1505 setup_object_debug(s, page, object);
David Brazdil0f672f62019-12-10 10:32:29 +00001506 object = kasan_init_slab_obj(s, object);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001507 if (unlikely(s->ctor)) {
1508 kasan_unpoison_object_data(s, object);
1509 s->ctor(object);
1510 kasan_poison_object_data(s, object);
1511 }
David Brazdil0f672f62019-12-10 10:32:29 +00001512 return object;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001513}
1514
1515/*
1516 * Slab allocation and freeing
1517 */
1518static inline struct page *alloc_slab_page(struct kmem_cache *s,
1519 gfp_t flags, int node, struct kmem_cache_order_objects oo)
1520{
1521 struct page *page;
1522 unsigned int order = oo_order(oo);
1523
1524 if (node == NUMA_NO_NODE)
1525 page = alloc_pages(flags, order);
1526 else
1527 page = __alloc_pages_node(node, flags, order);
1528
David Brazdil0f672f62019-12-10 10:32:29 +00001529 if (page && charge_slab_page(page, flags, order, s)) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001530 __free_pages(page, order);
1531 page = NULL;
1532 }
1533
1534 return page;
1535}
1536
1537#ifdef CONFIG_SLAB_FREELIST_RANDOM
1538/* Pre-initialize the random sequence cache */
1539static int init_cache_random_seq(struct kmem_cache *s)
1540{
1541 unsigned int count = oo_objects(s->oo);
1542 int err;
1543
1544 /* Bailout if already initialised */
1545 if (s->random_seq)
1546 return 0;
1547
1548 err = cache_random_seq_create(s, count, GFP_KERNEL);
1549 if (err) {
1550 pr_err("SLUB: Unable to initialize free list for %s\n",
1551 s->name);
1552 return err;
1553 }
1554
1555 /* Transform to an offset on the set of pages */
1556 if (s->random_seq) {
1557 unsigned int i;
1558
1559 for (i = 0; i < count; i++)
1560 s->random_seq[i] *= s->size;
1561 }
1562 return 0;
1563}
1564
1565/* Initialize each random sequence freelist per cache */
1566static void __init init_freelist_randomization(void)
1567{
1568 struct kmem_cache *s;
1569
1570 mutex_lock(&slab_mutex);
1571
1572 list_for_each_entry(s, &slab_caches, list)
1573 init_cache_random_seq(s);
1574
1575 mutex_unlock(&slab_mutex);
1576}
1577
1578/* Get the next entry on the pre-computed freelist randomized */
1579static void *next_freelist_entry(struct kmem_cache *s, struct page *page,
1580 unsigned long *pos, void *start,
1581 unsigned long page_limit,
1582 unsigned long freelist_count)
1583{
1584 unsigned int idx;
1585
1586 /*
1587 * If the target page allocation failed, the number of objects on the
1588 * page might be smaller than the usual size defined by the cache.
1589 */
1590 do {
1591 idx = s->random_seq[*pos];
1592 *pos += 1;
1593 if (*pos >= freelist_count)
1594 *pos = 0;
1595 } while (unlikely(idx >= page_limit));
1596
1597 return (char *)start + idx;
1598}
1599
1600/* Shuffle the single linked freelist based on a random pre-computed sequence */
1601static bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1602{
1603 void *start;
1604 void *cur;
1605 void *next;
1606 unsigned long idx, pos, page_limit, freelist_count;
1607
1608 if (page->objects < 2 || !s->random_seq)
1609 return false;
1610
1611 freelist_count = oo_objects(s->oo);
1612 pos = get_random_int() % freelist_count;
1613
1614 page_limit = page->objects * s->size;
1615 start = fixup_red_left(s, page_address(page));
1616
1617 /* First entry is used as the base of the freelist */
1618 cur = next_freelist_entry(s, page, &pos, start, page_limit,
1619 freelist_count);
David Brazdil0f672f62019-12-10 10:32:29 +00001620 cur = setup_object(s, page, cur);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001621 page->freelist = cur;
1622
1623 for (idx = 1; idx < page->objects; idx++) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001624 next = next_freelist_entry(s, page, &pos, start, page_limit,
1625 freelist_count);
David Brazdil0f672f62019-12-10 10:32:29 +00001626 next = setup_object(s, page, next);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001627 set_freepointer(s, cur, next);
1628 cur = next;
1629 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001630 set_freepointer(s, cur, NULL);
1631
1632 return true;
1633}
1634#else
1635static inline int init_cache_random_seq(struct kmem_cache *s)
1636{
1637 return 0;
1638}
1639static inline void init_freelist_randomization(void) { }
1640static inline bool shuffle_freelist(struct kmem_cache *s, struct page *page)
1641{
1642 return false;
1643}
1644#endif /* CONFIG_SLAB_FREELIST_RANDOM */
1645
1646static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1647{
1648 struct page *page;
1649 struct kmem_cache_order_objects oo = s->oo;
1650 gfp_t alloc_gfp;
David Brazdil0f672f62019-12-10 10:32:29 +00001651 void *start, *p, *next;
1652 int idx;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001653 bool shuffle;
1654
1655 flags &= gfp_allowed_mask;
1656
1657 if (gfpflags_allow_blocking(flags))
1658 local_irq_enable();
1659
1660 flags |= s->allocflags;
1661
1662 /*
1663 * Let the initial higher-order allocation fail under memory pressure
1664 * so we fall-back to the minimum order allocation.
1665 */
1666 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1667 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
1668 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
1669
1670 page = alloc_slab_page(s, alloc_gfp, node, oo);
1671 if (unlikely(!page)) {
1672 oo = s->min;
1673 alloc_gfp = flags;
1674 /*
1675 * Allocation may have failed due to fragmentation.
1676 * Try a lower order alloc if possible
1677 */
1678 page = alloc_slab_page(s, alloc_gfp, node, oo);
1679 if (unlikely(!page))
1680 goto out;
1681 stat(s, ORDER_FALLBACK);
1682 }
1683
1684 page->objects = oo_objects(oo);
1685
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001686 page->slab_cache = s;
1687 __SetPageSlab(page);
1688 if (page_is_pfmemalloc(page))
1689 SetPageSlabPfmemalloc(page);
1690
David Brazdil0f672f62019-12-10 10:32:29 +00001691 kasan_poison_slab(page);
1692
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001693 start = page_address(page);
1694
David Brazdil0f672f62019-12-10 10:32:29 +00001695 setup_page_debug(s, page, start);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001696
1697 shuffle = shuffle_freelist(s, page);
1698
1699 if (!shuffle) {
David Brazdil0f672f62019-12-10 10:32:29 +00001700 start = fixup_red_left(s, start);
1701 start = setup_object(s, page, start);
1702 page->freelist = start;
1703 for (idx = 0, p = start; idx < page->objects - 1; idx++) {
1704 next = p + s->size;
1705 next = setup_object(s, page, next);
1706 set_freepointer(s, p, next);
1707 p = next;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001708 }
David Brazdil0f672f62019-12-10 10:32:29 +00001709 set_freepointer(s, p, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001710 }
1711
1712 page->inuse = page->objects;
1713 page->frozen = 1;
1714
1715out:
1716 if (gfpflags_allow_blocking(flags))
1717 local_irq_disable();
1718 if (!page)
1719 return NULL;
1720
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001721 inc_slabs_node(s, page_to_nid(page), page->objects);
1722
1723 return page;
1724}
1725
1726static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1727{
1728 if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
1729 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
1730 flags &= ~GFP_SLAB_BUG_MASK;
1731 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
1732 invalid_mask, &invalid_mask, flags, &flags);
1733 dump_stack();
1734 }
1735
1736 return allocate_slab(s,
1737 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1738}
1739
1740static void __free_slab(struct kmem_cache *s, struct page *page)
1741{
1742 int order = compound_order(page);
1743 int pages = 1 << order;
1744
1745 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1746 void *p;
1747
1748 slab_pad_check(s, page);
1749 for_each_object(p, s, page_address(page),
1750 page->objects)
1751 check_object(s, page, p, SLUB_RED_INACTIVE);
1752 }
1753
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001754 __ClearPageSlabPfmemalloc(page);
1755 __ClearPageSlab(page);
1756
1757 page->mapping = NULL;
1758 if (current->reclaim_state)
1759 current->reclaim_state->reclaimed_slab += pages;
David Brazdil0f672f62019-12-10 10:32:29 +00001760 uncharge_slab_page(page, order, s);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001761 __free_pages(page, order);
1762}
1763
1764static void rcu_free_slab(struct rcu_head *h)
1765{
1766 struct page *page = container_of(h, struct page, rcu_head);
1767
1768 __free_slab(page->slab_cache, page);
1769}
1770
1771static void free_slab(struct kmem_cache *s, struct page *page)
1772{
1773 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) {
1774 call_rcu(&page->rcu_head, rcu_free_slab);
1775 } else
1776 __free_slab(s, page);
1777}
1778
1779static void discard_slab(struct kmem_cache *s, struct page *page)
1780{
1781 dec_slabs_node(s, page_to_nid(page), page->objects);
1782 free_slab(s, page);
1783}
1784
1785/*
1786 * Management of partially allocated slabs.
1787 */
1788static inline void
1789__add_partial(struct kmem_cache_node *n, struct page *page, int tail)
1790{
1791 n->nr_partial++;
1792 if (tail == DEACTIVATE_TO_TAIL)
David Brazdil0f672f62019-12-10 10:32:29 +00001793 list_add_tail(&page->slab_list, &n->partial);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001794 else
David Brazdil0f672f62019-12-10 10:32:29 +00001795 list_add(&page->slab_list, &n->partial);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001796}
1797
1798static inline void add_partial(struct kmem_cache_node *n,
1799 struct page *page, int tail)
1800{
1801 lockdep_assert_held(&n->list_lock);
1802 __add_partial(n, page, tail);
1803}
1804
1805static inline void remove_partial(struct kmem_cache_node *n,
1806 struct page *page)
1807{
1808 lockdep_assert_held(&n->list_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001809 list_del(&page->slab_list);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001810 n->nr_partial--;
1811}
1812
1813/*
1814 * Remove slab from the partial list, freeze it and
1815 * return the pointer to the freelist.
1816 *
1817 * Returns a list of objects or NULL if it fails.
1818 */
1819static inline void *acquire_slab(struct kmem_cache *s,
1820 struct kmem_cache_node *n, struct page *page,
1821 int mode, int *objects)
1822{
1823 void *freelist;
1824 unsigned long counters;
1825 struct page new;
1826
1827 lockdep_assert_held(&n->list_lock);
1828
1829 /*
1830 * Zap the freelist and set the frozen bit.
1831 * The old freelist is the list of objects for the
1832 * per cpu allocation list.
1833 */
1834 freelist = page->freelist;
1835 counters = page->counters;
1836 new.counters = counters;
1837 *objects = new.objects - new.inuse;
1838 if (mode) {
1839 new.inuse = page->objects;
1840 new.freelist = NULL;
1841 } else {
1842 new.freelist = freelist;
1843 }
1844
1845 VM_BUG_ON(new.frozen);
1846 new.frozen = 1;
1847
1848 if (!__cmpxchg_double_slab(s, page,
1849 freelist, counters,
1850 new.freelist, new.counters,
1851 "acquire_slab"))
1852 return NULL;
1853
1854 remove_partial(n, page);
1855 WARN_ON(!freelist);
1856 return freelist;
1857}
1858
1859static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1860static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags);
1861
1862/*
1863 * Try to allocate a partial slab from a specific node.
1864 */
1865static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
1866 struct kmem_cache_cpu *c, gfp_t flags)
1867{
1868 struct page *page, *page2;
1869 void *object = NULL;
1870 unsigned int available = 0;
1871 int objects;
1872
1873 /*
1874 * Racy check. If we mistakenly see no partial slabs then we
1875 * just allocate an empty slab. If we mistakenly try to get a
1876 * partial slab and there is none available then get_partials()
1877 * will return NULL.
1878 */
1879 if (!n || !n->nr_partial)
1880 return NULL;
1881
1882 spin_lock(&n->list_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001883 list_for_each_entry_safe(page, page2, &n->partial, slab_list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001884 void *t;
1885
1886 if (!pfmemalloc_match(page, flags))
1887 continue;
1888
1889 t = acquire_slab(s, n, page, object == NULL, &objects);
1890 if (!t)
1891 break;
1892
1893 available += objects;
1894 if (!object) {
1895 c->page = page;
1896 stat(s, ALLOC_FROM_PARTIAL);
1897 object = t;
1898 } else {
1899 put_cpu_partial(s, page, 0);
1900 stat(s, CPU_PARTIAL_NODE);
1901 }
1902 if (!kmem_cache_has_cpu_partial(s)
1903 || available > slub_cpu_partial(s) / 2)
1904 break;
1905
1906 }
1907 spin_unlock(&n->list_lock);
1908 return object;
1909}
1910
1911/*
1912 * Get a page from somewhere. Search in increasing NUMA distances.
1913 */
1914static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1915 struct kmem_cache_cpu *c)
1916{
1917#ifdef CONFIG_NUMA
1918 struct zonelist *zonelist;
1919 struct zoneref *z;
1920 struct zone *zone;
1921 enum zone_type high_zoneidx = gfp_zone(flags);
1922 void *object;
1923 unsigned int cpuset_mems_cookie;
1924
1925 /*
1926 * The defrag ratio allows a configuration of the tradeoffs between
1927 * inter node defragmentation and node local allocations. A lower
1928 * defrag_ratio increases the tendency to do local allocations
1929 * instead of attempting to obtain partial slabs from other nodes.
1930 *
1931 * If the defrag_ratio is set to 0 then kmalloc() always
1932 * returns node local objects. If the ratio is higher then kmalloc()
1933 * may return off node objects because partial slabs are obtained
1934 * from other nodes and filled up.
1935 *
1936 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
1937 * (which makes defrag_ratio = 1000) then every (well almost)
1938 * allocation will first attempt to defrag slab caches on other nodes.
1939 * This means scanning over all nodes to look for partial slabs which
1940 * may be expensive if we do it every time we are trying to find a slab
1941 * with available objects.
1942 */
1943 if (!s->remote_node_defrag_ratio ||
1944 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1945 return NULL;
1946
1947 do {
1948 cpuset_mems_cookie = read_mems_allowed_begin();
1949 zonelist = node_zonelist(mempolicy_slab_node(), flags);
1950 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1951 struct kmem_cache_node *n;
1952
1953 n = get_node(s, zone_to_nid(zone));
1954
1955 if (n && cpuset_zone_allowed(zone, flags) &&
1956 n->nr_partial > s->min_partial) {
1957 object = get_partial_node(s, n, c, flags);
1958 if (object) {
1959 /*
1960 * Don't check read_mems_allowed_retry()
1961 * here - if mems_allowed was updated in
1962 * parallel, that was a harmless race
1963 * between allocation and the cpuset
1964 * update
1965 */
1966 return object;
1967 }
1968 }
1969 }
1970 } while (read_mems_allowed_retry(cpuset_mems_cookie));
David Brazdil0f672f62019-12-10 10:32:29 +00001971#endif /* CONFIG_NUMA */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001972 return NULL;
1973}
1974
1975/*
1976 * Get a partial page, lock it and return it.
1977 */
1978static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1979 struct kmem_cache_cpu *c)
1980{
1981 void *object;
1982 int searchnode = node;
1983
1984 if (node == NUMA_NO_NODE)
1985 searchnode = numa_mem_id();
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001986
1987 object = get_partial_node(s, get_node(s, searchnode), c, flags);
1988 if (object || node != NUMA_NO_NODE)
1989 return object;
1990
1991 return get_any_partial(s, flags, c);
1992}
1993
1994#ifdef CONFIG_PREEMPT
1995/*
1996 * Calculate the next globally unique transaction for disambiguiation
1997 * during cmpxchg. The transactions start with the cpu number and are then
1998 * incremented by CONFIG_NR_CPUS.
1999 */
2000#define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2001#else
2002/*
2003 * No preemption supported therefore also no need to check for
2004 * different cpus.
2005 */
2006#define TID_STEP 1
2007#endif
2008
2009static inline unsigned long next_tid(unsigned long tid)
2010{
2011 return tid + TID_STEP;
2012}
2013
David Brazdil0f672f62019-12-10 10:32:29 +00002014#ifdef SLUB_DEBUG_CMPXCHG
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002015static inline unsigned int tid_to_cpu(unsigned long tid)
2016{
2017 return tid % TID_STEP;
2018}
2019
2020static inline unsigned long tid_to_event(unsigned long tid)
2021{
2022 return tid / TID_STEP;
2023}
David Brazdil0f672f62019-12-10 10:32:29 +00002024#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002025
2026static inline unsigned int init_tid(int cpu)
2027{
2028 return cpu;
2029}
2030
2031static inline void note_cmpxchg_failure(const char *n,
2032 const struct kmem_cache *s, unsigned long tid)
2033{
2034#ifdef SLUB_DEBUG_CMPXCHG
2035 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2036
2037 pr_info("%s %s: cmpxchg redo ", n, s->name);
2038
2039#ifdef CONFIG_PREEMPT
2040 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2041 pr_warn("due to cpu change %d -> %d\n",
2042 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2043 else
2044#endif
2045 if (tid_to_event(tid) != tid_to_event(actual_tid))
2046 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2047 tid_to_event(tid), tid_to_event(actual_tid));
2048 else
2049 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2050 actual_tid, tid, next_tid(tid));
2051#endif
2052 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2053}
2054
2055static void init_kmem_cache_cpus(struct kmem_cache *s)
2056{
2057 int cpu;
2058
2059 for_each_possible_cpu(cpu)
2060 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
2061}
2062
2063/*
2064 * Remove the cpu slab
2065 */
2066static void deactivate_slab(struct kmem_cache *s, struct page *page,
2067 void *freelist, struct kmem_cache_cpu *c)
2068{
2069 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
2070 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
2071 int lock = 0;
2072 enum slab_modes l = M_NONE, m = M_NONE;
2073 void *nextfree;
2074 int tail = DEACTIVATE_TO_HEAD;
2075 struct page new;
2076 struct page old;
2077
2078 if (page->freelist) {
2079 stat(s, DEACTIVATE_REMOTE_FREES);
2080 tail = DEACTIVATE_TO_TAIL;
2081 }
2082
2083 /*
2084 * Stage one: Free all available per cpu objects back
2085 * to the page freelist while it is still frozen. Leave the
2086 * last one.
2087 *
2088 * There is no need to take the list->lock because the page
2089 * is still frozen.
2090 */
2091 while (freelist && (nextfree = get_freepointer(s, freelist))) {
2092 void *prior;
2093 unsigned long counters;
2094
Olivier Deprez0e641232021-09-23 10:07:05 +02002095 /*
2096 * If 'nextfree' is invalid, it is possible that the object at
2097 * 'freelist' is already corrupted. So isolate all objects
2098 * starting at 'freelist'.
2099 */
2100 if (freelist_corrupted(s, page, &freelist, nextfree))
2101 break;
2102
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002103 do {
2104 prior = page->freelist;
2105 counters = page->counters;
2106 set_freepointer(s, freelist, prior);
2107 new.counters = counters;
2108 new.inuse--;
2109 VM_BUG_ON(!new.frozen);
2110
2111 } while (!__cmpxchg_double_slab(s, page,
2112 prior, counters,
2113 freelist, new.counters,
2114 "drain percpu freelist"));
2115
2116 freelist = nextfree;
2117 }
2118
2119 /*
2120 * Stage two: Ensure that the page is unfrozen while the
2121 * list presence reflects the actual number of objects
2122 * during unfreeze.
2123 *
2124 * We setup the list membership and then perform a cmpxchg
2125 * with the count. If there is a mismatch then the page
2126 * is not unfrozen but the page is on the wrong list.
2127 *
2128 * Then we restart the process which may have to remove
2129 * the page from the list that we just put it on again
2130 * because the number of objects in the slab may have
2131 * changed.
2132 */
2133redo:
2134
2135 old.freelist = page->freelist;
2136 old.counters = page->counters;
2137 VM_BUG_ON(!old.frozen);
2138
2139 /* Determine target state of the slab */
2140 new.counters = old.counters;
2141 if (freelist) {
2142 new.inuse--;
2143 set_freepointer(s, freelist, old.freelist);
2144 new.freelist = freelist;
2145 } else
2146 new.freelist = old.freelist;
2147
2148 new.frozen = 0;
2149
2150 if (!new.inuse && n->nr_partial >= s->min_partial)
2151 m = M_FREE;
2152 else if (new.freelist) {
2153 m = M_PARTIAL;
2154 if (!lock) {
2155 lock = 1;
2156 /*
David Brazdil0f672f62019-12-10 10:32:29 +00002157 * Taking the spinlock removes the possibility
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002158 * that acquire_slab() will see a slab page that
2159 * is frozen
2160 */
2161 spin_lock(&n->list_lock);
2162 }
2163 } else {
2164 m = M_FULL;
2165 if (kmem_cache_debug(s) && !lock) {
2166 lock = 1;
2167 /*
2168 * This also ensures that the scanning of full
2169 * slabs from diagnostic functions will not see
2170 * any frozen slabs.
2171 */
2172 spin_lock(&n->list_lock);
2173 }
2174 }
2175
2176 if (l != m) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002177 if (l == M_PARTIAL)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002178 remove_partial(n, page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002179 else if (l == M_FULL)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002180 remove_full(s, n, page);
2181
David Brazdil0f672f62019-12-10 10:32:29 +00002182 if (m == M_PARTIAL)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002183 add_partial(n, page, tail);
David Brazdil0f672f62019-12-10 10:32:29 +00002184 else if (m == M_FULL)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002185 add_full(s, n, page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002186 }
2187
2188 l = m;
2189 if (!__cmpxchg_double_slab(s, page,
2190 old.freelist, old.counters,
2191 new.freelist, new.counters,
2192 "unfreezing slab"))
2193 goto redo;
2194
2195 if (lock)
2196 spin_unlock(&n->list_lock);
2197
David Brazdil0f672f62019-12-10 10:32:29 +00002198 if (m == M_PARTIAL)
2199 stat(s, tail);
2200 else if (m == M_FULL)
2201 stat(s, DEACTIVATE_FULL);
2202 else if (m == M_FREE) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002203 stat(s, DEACTIVATE_EMPTY);
2204 discard_slab(s, page);
2205 stat(s, FREE_SLAB);
2206 }
2207
2208 c->page = NULL;
2209 c->freelist = NULL;
2210}
2211
2212/*
2213 * Unfreeze all the cpu partial slabs.
2214 *
2215 * This function must be called with interrupts disabled
2216 * for the cpu using c (or some other guarantee must be there
2217 * to guarantee no concurrent accesses).
2218 */
2219static void unfreeze_partials(struct kmem_cache *s,
2220 struct kmem_cache_cpu *c)
2221{
2222#ifdef CONFIG_SLUB_CPU_PARTIAL
2223 struct kmem_cache_node *n = NULL, *n2 = NULL;
2224 struct page *page, *discard_page = NULL;
2225
2226 while ((page = c->partial)) {
2227 struct page new;
2228 struct page old;
2229
2230 c->partial = page->next;
2231
2232 n2 = get_node(s, page_to_nid(page));
2233 if (n != n2) {
2234 if (n)
2235 spin_unlock(&n->list_lock);
2236
2237 n = n2;
2238 spin_lock(&n->list_lock);
2239 }
2240
2241 do {
2242
2243 old.freelist = page->freelist;
2244 old.counters = page->counters;
2245 VM_BUG_ON(!old.frozen);
2246
2247 new.counters = old.counters;
2248 new.freelist = old.freelist;
2249
2250 new.frozen = 0;
2251
2252 } while (!__cmpxchg_double_slab(s, page,
2253 old.freelist, old.counters,
2254 new.freelist, new.counters,
2255 "unfreezing slab"));
2256
2257 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2258 page->next = discard_page;
2259 discard_page = page;
2260 } else {
2261 add_partial(n, page, DEACTIVATE_TO_TAIL);
2262 stat(s, FREE_ADD_PARTIAL);
2263 }
2264 }
2265
2266 if (n)
2267 spin_unlock(&n->list_lock);
2268
2269 while (discard_page) {
2270 page = discard_page;
2271 discard_page = discard_page->next;
2272
2273 stat(s, DEACTIVATE_EMPTY);
2274 discard_slab(s, page);
2275 stat(s, FREE_SLAB);
2276 }
David Brazdil0f672f62019-12-10 10:32:29 +00002277#endif /* CONFIG_SLUB_CPU_PARTIAL */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002278}
2279
2280/*
David Brazdil0f672f62019-12-10 10:32:29 +00002281 * Put a page that was just frozen (in __slab_free|get_partial_node) into a
2282 * partial page slot if available.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002283 *
2284 * If we did not find a slot then simply move all the partials to the
2285 * per node partial list.
2286 */
2287static void put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
2288{
2289#ifdef CONFIG_SLUB_CPU_PARTIAL
2290 struct page *oldpage;
2291 int pages;
2292 int pobjects;
2293
2294 preempt_disable();
2295 do {
2296 pages = 0;
2297 pobjects = 0;
2298 oldpage = this_cpu_read(s->cpu_slab->partial);
2299
2300 if (oldpage) {
2301 pobjects = oldpage->pobjects;
2302 pages = oldpage->pages;
2303 if (drain && pobjects > s->cpu_partial) {
2304 unsigned long flags;
2305 /*
2306 * partial array is full. Move the existing
2307 * set to the per node partial list.
2308 */
2309 local_irq_save(flags);
2310 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2311 local_irq_restore(flags);
2312 oldpage = NULL;
2313 pobjects = 0;
2314 pages = 0;
2315 stat(s, CPU_PARTIAL_DRAIN);
2316 }
2317 }
2318
2319 pages++;
2320 pobjects += page->objects - page->inuse;
2321
2322 page->pages = pages;
2323 page->pobjects = pobjects;
2324 page->next = oldpage;
2325
2326 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page)
2327 != oldpage);
2328 if (unlikely(!s->cpu_partial)) {
2329 unsigned long flags;
2330
2331 local_irq_save(flags);
2332 unfreeze_partials(s, this_cpu_ptr(s->cpu_slab));
2333 local_irq_restore(flags);
2334 }
2335 preempt_enable();
David Brazdil0f672f62019-12-10 10:32:29 +00002336#endif /* CONFIG_SLUB_CPU_PARTIAL */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002337}
2338
2339static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2340{
2341 stat(s, CPUSLAB_FLUSH);
2342 deactivate_slab(s, c->page, c->freelist, c);
2343
2344 c->tid = next_tid(c->tid);
2345}
2346
2347/*
2348 * Flush cpu slab.
2349 *
2350 * Called from IPI handler with interrupts disabled.
2351 */
2352static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2353{
2354 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2355
David Brazdil0f672f62019-12-10 10:32:29 +00002356 if (c->page)
2357 flush_slab(s, c);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002358
David Brazdil0f672f62019-12-10 10:32:29 +00002359 unfreeze_partials(s, c);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002360}
2361
2362static void flush_cpu_slab(void *d)
2363{
2364 struct kmem_cache *s = d;
2365
2366 __flush_cpu_slab(s, smp_processor_id());
2367}
2368
2369static bool has_cpu_slab(int cpu, void *info)
2370{
2371 struct kmem_cache *s = info;
2372 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2373
2374 return c->page || slub_percpu_partial(c);
2375}
2376
2377static void flush_all(struct kmem_cache *s)
2378{
2379 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC);
2380}
2381
2382/*
2383 * Use the cpu notifier to insure that the cpu slabs are flushed when
2384 * necessary.
2385 */
2386static int slub_cpu_dead(unsigned int cpu)
2387{
2388 struct kmem_cache *s;
2389 unsigned long flags;
2390
2391 mutex_lock(&slab_mutex);
2392 list_for_each_entry(s, &slab_caches, list) {
2393 local_irq_save(flags);
2394 __flush_cpu_slab(s, cpu);
2395 local_irq_restore(flags);
2396 }
2397 mutex_unlock(&slab_mutex);
2398 return 0;
2399}
2400
2401/*
2402 * Check if the objects in a per cpu structure fit numa
2403 * locality expectations.
2404 */
2405static inline int node_match(struct page *page, int node)
2406{
2407#ifdef CONFIG_NUMA
David Brazdil0f672f62019-12-10 10:32:29 +00002408 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002409 return 0;
2410#endif
2411 return 1;
2412}
2413
2414#ifdef CONFIG_SLUB_DEBUG
2415static int count_free(struct page *page)
2416{
2417 return page->objects - page->inuse;
2418}
2419
2420static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2421{
2422 return atomic_long_read(&n->total_objects);
2423}
2424#endif /* CONFIG_SLUB_DEBUG */
2425
2426#if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
2427static unsigned long count_partial(struct kmem_cache_node *n,
2428 int (*get_count)(struct page *))
2429{
2430 unsigned long flags;
2431 unsigned long x = 0;
2432 struct page *page;
2433
2434 spin_lock_irqsave(&n->list_lock, flags);
David Brazdil0f672f62019-12-10 10:32:29 +00002435 list_for_each_entry(page, &n->partial, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002436 x += get_count(page);
2437 spin_unlock_irqrestore(&n->list_lock, flags);
2438 return x;
2439}
2440#endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
2441
2442static noinline void
2443slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2444{
2445#ifdef CONFIG_SLUB_DEBUG
2446 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2447 DEFAULT_RATELIMIT_BURST);
2448 int node;
2449 struct kmem_cache_node *n;
2450
2451 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2452 return;
2453
2454 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2455 nid, gfpflags, &gfpflags);
2456 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
2457 s->name, s->object_size, s->size, oo_order(s->oo),
2458 oo_order(s->min));
2459
2460 if (oo_order(s->min) > get_order(s->object_size))
2461 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
2462 s->name);
2463
2464 for_each_kmem_cache_node(s, node, n) {
2465 unsigned long nr_slabs;
2466 unsigned long nr_objs;
2467 unsigned long nr_free;
2468
2469 nr_free = count_partial(n, count_free);
2470 nr_slabs = node_nr_slabs(n);
2471 nr_objs = node_nr_objs(n);
2472
2473 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
2474 node, nr_slabs, nr_objs, nr_free);
2475 }
2476#endif
2477}
2478
2479static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2480 int node, struct kmem_cache_cpu **pc)
2481{
2482 void *freelist;
2483 struct kmem_cache_cpu *c = *pc;
2484 struct page *page;
2485
2486 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2487
2488 freelist = get_partial(s, flags, node, c);
2489
2490 if (freelist)
2491 return freelist;
2492
2493 page = new_slab(s, flags, node);
2494 if (page) {
2495 c = raw_cpu_ptr(s->cpu_slab);
2496 if (c->page)
2497 flush_slab(s, c);
2498
2499 /*
2500 * No other reference to the page yet so we can
2501 * muck around with it freely without cmpxchg
2502 */
2503 freelist = page->freelist;
2504 page->freelist = NULL;
2505
2506 stat(s, ALLOC_SLAB);
2507 c->page = page;
2508 *pc = c;
David Brazdil0f672f62019-12-10 10:32:29 +00002509 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002510
2511 return freelist;
2512}
2513
2514static inline bool pfmemalloc_match(struct page *page, gfp_t gfpflags)
2515{
2516 if (unlikely(PageSlabPfmemalloc(page)))
2517 return gfp_pfmemalloc_allowed(gfpflags);
2518
2519 return true;
2520}
2521
2522/*
2523 * Check the page->freelist of a page and either transfer the freelist to the
2524 * per cpu freelist or deactivate the page.
2525 *
2526 * The page is still frozen if the return value is not NULL.
2527 *
2528 * If this function returns NULL then the page has been unfrozen.
2529 *
2530 * This function must be called with interrupt disabled.
2531 */
2532static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2533{
2534 struct page new;
2535 unsigned long counters;
2536 void *freelist;
2537
2538 do {
2539 freelist = page->freelist;
2540 counters = page->counters;
2541
2542 new.counters = counters;
2543 VM_BUG_ON(!new.frozen);
2544
2545 new.inuse = page->objects;
2546 new.frozen = freelist != NULL;
2547
2548 } while (!__cmpxchg_double_slab(s, page,
2549 freelist, counters,
2550 NULL, new.counters,
2551 "get_freelist"));
2552
2553 return freelist;
2554}
2555
2556/*
2557 * Slow path. The lockless freelist is empty or we need to perform
2558 * debugging duties.
2559 *
2560 * Processing is still very fast if new objects have been freed to the
2561 * regular freelist. In that case we simply take over the regular freelist
2562 * as the lockless freelist and zap the regular freelist.
2563 *
2564 * If that is not working then we fall back to the partial lists. We take the
2565 * first element of the freelist as the object to allocate now and move the
2566 * rest of the freelist to the lockless freelist.
2567 *
2568 * And if we were unable to get a new slab from the partial slab lists then
2569 * we need to allocate a new slab. This is the slowest path since it involves
2570 * a call to the page allocator and the setup of a new slab.
2571 *
2572 * Version of __slab_alloc to use when we know that interrupts are
2573 * already disabled (which is the case for bulk allocation).
2574 */
2575static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2576 unsigned long addr, struct kmem_cache_cpu *c)
2577{
2578 void *freelist;
2579 struct page *page;
2580
2581 page = c->page;
Olivier Deprez0e641232021-09-23 10:07:05 +02002582 if (!page) {
2583 /*
2584 * if the node is not online or has no normal memory, just
2585 * ignore the node constraint
2586 */
2587 if (unlikely(node != NUMA_NO_NODE &&
2588 !node_state(node, N_NORMAL_MEMORY)))
2589 node = NUMA_NO_NODE;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002590 goto new_slab;
Olivier Deprez0e641232021-09-23 10:07:05 +02002591 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002592redo:
2593
2594 if (unlikely(!node_match(page, node))) {
Olivier Deprez0e641232021-09-23 10:07:05 +02002595 /*
2596 * same as above but node_match() being false already
2597 * implies node != NUMA_NO_NODE
2598 */
2599 if (!node_state(node, N_NORMAL_MEMORY)) {
2600 node = NUMA_NO_NODE;
2601 goto redo;
2602 } else {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002603 stat(s, ALLOC_NODE_MISMATCH);
2604 deactivate_slab(s, page, c->freelist, c);
2605 goto new_slab;
2606 }
2607 }
2608
2609 /*
2610 * By rights, we should be searching for a slab page that was
2611 * PFMEMALLOC but right now, we are losing the pfmemalloc
2612 * information when the page leaves the per-cpu allocator
2613 */
2614 if (unlikely(!pfmemalloc_match(page, gfpflags))) {
2615 deactivate_slab(s, page, c->freelist, c);
2616 goto new_slab;
2617 }
2618
2619 /* must check again c->freelist in case of cpu migration or IRQ */
2620 freelist = c->freelist;
2621 if (freelist)
2622 goto load_freelist;
2623
2624 freelist = get_freelist(s, page);
2625
2626 if (!freelist) {
2627 c->page = NULL;
2628 stat(s, DEACTIVATE_BYPASS);
2629 goto new_slab;
2630 }
2631
2632 stat(s, ALLOC_REFILL);
2633
2634load_freelist:
2635 /*
2636 * freelist is pointing to the list of objects to be used.
2637 * page is pointing to the page from which the objects are obtained.
2638 * That page must be frozen for per cpu allocations to work.
2639 */
2640 VM_BUG_ON(!c->page->frozen);
2641 c->freelist = get_freepointer(s, freelist);
2642 c->tid = next_tid(c->tid);
2643 return freelist;
2644
2645new_slab:
2646
2647 if (slub_percpu_partial(c)) {
2648 page = c->page = slub_percpu_partial(c);
2649 slub_set_percpu_partial(c, page);
2650 stat(s, CPU_PARTIAL_ALLOC);
2651 goto redo;
2652 }
2653
2654 freelist = new_slab_objects(s, gfpflags, node, &c);
2655
2656 if (unlikely(!freelist)) {
2657 slab_out_of_memory(s, gfpflags, node);
2658 return NULL;
2659 }
2660
2661 page = c->page;
2662 if (likely(!kmem_cache_debug(s) && pfmemalloc_match(page, gfpflags)))
2663 goto load_freelist;
2664
2665 /* Only entered in the debug case */
2666 if (kmem_cache_debug(s) &&
2667 !alloc_debug_processing(s, page, freelist, addr))
2668 goto new_slab; /* Slab failed checks. Next slab needed */
2669
2670 deactivate_slab(s, page, get_freepointer(s, freelist), c);
2671 return freelist;
2672}
2673
2674/*
2675 * Another one that disabled interrupt and compensates for possible
2676 * cpu changes by refetching the per cpu area pointer.
2677 */
2678static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2679 unsigned long addr, struct kmem_cache_cpu *c)
2680{
2681 void *p;
2682 unsigned long flags;
2683
2684 local_irq_save(flags);
2685#ifdef CONFIG_PREEMPT
2686 /*
2687 * We may have been preempted and rescheduled on a different
2688 * cpu before disabling interrupts. Need to reload cpu area
2689 * pointer.
2690 */
2691 c = this_cpu_ptr(s->cpu_slab);
2692#endif
2693
2694 p = ___slab_alloc(s, gfpflags, node, addr, c);
2695 local_irq_restore(flags);
2696 return p;
2697}
2698
2699/*
David Brazdil0f672f62019-12-10 10:32:29 +00002700 * If the object has been wiped upon free, make sure it's fully initialized by
2701 * zeroing out freelist pointer.
2702 */
2703static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
2704 void *obj)
2705{
2706 if (unlikely(slab_want_init_on_free(s)) && obj)
2707 memset((void *)((char *)obj + s->offset), 0, sizeof(void *));
2708}
2709
2710/*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002711 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2712 * have the fastpath folded into their functions. So no function call
2713 * overhead for requests that can be satisfied on the fastpath.
2714 *
2715 * The fastpath works by first checking if the lockless freelist can be used.
2716 * If not then __slab_alloc is called for slow processing.
2717 *
2718 * Otherwise we can simply pick the next object from the lockless free list.
2719 */
2720static __always_inline void *slab_alloc_node(struct kmem_cache *s,
2721 gfp_t gfpflags, int node, unsigned long addr)
2722{
2723 void *object;
2724 struct kmem_cache_cpu *c;
2725 struct page *page;
2726 unsigned long tid;
2727
2728 s = slab_pre_alloc_hook(s, gfpflags);
2729 if (!s)
2730 return NULL;
2731redo:
2732 /*
2733 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2734 * enabled. We may switch back and forth between cpus while
2735 * reading from one cpu area. That does not matter as long
2736 * as we end up on the original cpu again when doing the cmpxchg.
2737 *
2738 * We should guarantee that tid and kmem_cache are retrieved on
2739 * the same cpu. It could be different if CONFIG_PREEMPT so we need
2740 * to check if it is matched or not.
2741 */
2742 do {
2743 tid = this_cpu_read(s->cpu_slab->tid);
2744 c = raw_cpu_ptr(s->cpu_slab);
2745 } while (IS_ENABLED(CONFIG_PREEMPT) &&
2746 unlikely(tid != READ_ONCE(c->tid)));
2747
2748 /*
2749 * Irqless object alloc/free algorithm used here depends on sequence
2750 * of fetching cpu_slab's data. tid should be fetched before anything
2751 * on c to guarantee that object and page associated with previous tid
2752 * won't be used with current tid. If we fetch tid first, object and
2753 * page could be one associated with next tid and our alloc/free
2754 * request will be failed. In this case, we will retry. So, no problem.
2755 */
2756 barrier();
2757
2758 /*
2759 * The transaction ids are globally unique per cpu and per operation on
2760 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2761 * occurs on the right processor and that there was no operation on the
2762 * linked list in between.
2763 */
2764
2765 object = c->freelist;
2766 page = c->page;
Olivier Deprez0e641232021-09-23 10:07:05 +02002767 if (unlikely(!object || !page || !node_match(page, node))) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002768 object = __slab_alloc(s, gfpflags, node, addr, c);
2769 stat(s, ALLOC_SLOWPATH);
2770 } else {
2771 void *next_object = get_freepointer_safe(s, object);
2772
2773 /*
2774 * The cmpxchg will only match if there was no additional
2775 * operation and if we are on the right processor.
2776 *
2777 * The cmpxchg does the following atomically (without lock
2778 * semantics!)
2779 * 1. Relocate first pointer to the current per cpu area.
2780 * 2. Verify that tid and freelist have not been changed
2781 * 3. If they were not changed replace tid and freelist
2782 *
2783 * Since this is without lock semantics the protection is only
2784 * against code executing on this cpu *not* from access by
2785 * other cpus.
2786 */
2787 if (unlikely(!this_cpu_cmpxchg_double(
2788 s->cpu_slab->freelist, s->cpu_slab->tid,
2789 object, tid,
2790 next_object, next_tid(tid)))) {
2791
2792 note_cmpxchg_failure("slab_alloc", s, tid);
2793 goto redo;
2794 }
2795 prefetch_freepointer(s, next_object);
2796 stat(s, ALLOC_FASTPATH);
2797 }
2798
David Brazdil0f672f62019-12-10 10:32:29 +00002799 maybe_wipe_obj_freeptr(s, object);
2800
2801 if (unlikely(slab_want_init_on_alloc(gfpflags, s)) && object)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002802 memset(object, 0, s->object_size);
2803
2804 slab_post_alloc_hook(s, gfpflags, 1, &object);
2805
2806 return object;
2807}
2808
2809static __always_inline void *slab_alloc(struct kmem_cache *s,
2810 gfp_t gfpflags, unsigned long addr)
2811{
2812 return slab_alloc_node(s, gfpflags, NUMA_NO_NODE, addr);
2813}
2814
2815void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2816{
2817 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2818
2819 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size,
2820 s->size, gfpflags);
2821
2822 return ret;
2823}
2824EXPORT_SYMBOL(kmem_cache_alloc);
2825
2826#ifdef CONFIG_TRACING
2827void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2828{
2829 void *ret = slab_alloc(s, gfpflags, _RET_IP_);
2830 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
David Brazdil0f672f62019-12-10 10:32:29 +00002831 ret = kasan_kmalloc(s, ret, size, gfpflags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002832 return ret;
2833}
2834EXPORT_SYMBOL(kmem_cache_alloc_trace);
2835#endif
2836
2837#ifdef CONFIG_NUMA
2838void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2839{
2840 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2841
2842 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2843 s->object_size, s->size, gfpflags, node);
2844
2845 return ret;
2846}
2847EXPORT_SYMBOL(kmem_cache_alloc_node);
2848
2849#ifdef CONFIG_TRACING
2850void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2851 gfp_t gfpflags,
2852 int node, size_t size)
2853{
2854 void *ret = slab_alloc_node(s, gfpflags, node, _RET_IP_);
2855
2856 trace_kmalloc_node(_RET_IP_, ret,
2857 size, s->size, gfpflags, node);
2858
David Brazdil0f672f62019-12-10 10:32:29 +00002859 ret = kasan_kmalloc(s, ret, size, gfpflags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002860 return ret;
2861}
2862EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2863#endif
David Brazdil0f672f62019-12-10 10:32:29 +00002864#endif /* CONFIG_NUMA */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002865
2866/*
2867 * Slow path handling. This may still be called frequently since objects
2868 * have a longer lifetime than the cpu slabs in most processing loads.
2869 *
2870 * So we still attempt to reduce cache line usage. Just take the slab
2871 * lock and free the item. If there is no additional partial page
2872 * handling required then we can return immediately.
2873 */
2874static void __slab_free(struct kmem_cache *s, struct page *page,
2875 void *head, void *tail, int cnt,
2876 unsigned long addr)
2877
2878{
2879 void *prior;
2880 int was_frozen;
2881 struct page new;
2882 unsigned long counters;
2883 struct kmem_cache_node *n = NULL;
2884 unsigned long uninitialized_var(flags);
2885
2886 stat(s, FREE_SLOWPATH);
2887
2888 if (kmem_cache_debug(s) &&
2889 !free_debug_processing(s, page, head, tail, cnt, addr))
2890 return;
2891
2892 do {
2893 if (unlikely(n)) {
2894 spin_unlock_irqrestore(&n->list_lock, flags);
2895 n = NULL;
2896 }
2897 prior = page->freelist;
2898 counters = page->counters;
2899 set_freepointer(s, tail, prior);
2900 new.counters = counters;
2901 was_frozen = new.frozen;
2902 new.inuse -= cnt;
2903 if ((!new.inuse || !prior) && !was_frozen) {
2904
2905 if (kmem_cache_has_cpu_partial(s) && !prior) {
2906
2907 /*
2908 * Slab was on no list before and will be
2909 * partially empty
2910 * We can defer the list move and instead
2911 * freeze it.
2912 */
2913 new.frozen = 1;
2914
2915 } else { /* Needs to be taken off a list */
2916
2917 n = get_node(s, page_to_nid(page));
2918 /*
2919 * Speculatively acquire the list_lock.
2920 * If the cmpxchg does not succeed then we may
2921 * drop the list_lock without any processing.
2922 *
2923 * Otherwise the list_lock will synchronize with
2924 * other processors updating the list of slabs.
2925 */
2926 spin_lock_irqsave(&n->list_lock, flags);
2927
2928 }
2929 }
2930
2931 } while (!cmpxchg_double_slab(s, page,
2932 prior, counters,
2933 head, new.counters,
2934 "__slab_free"));
2935
2936 if (likely(!n)) {
2937
2938 /*
2939 * If we just froze the page then put it onto the
2940 * per cpu partial list.
2941 */
2942 if (new.frozen && !was_frozen) {
2943 put_cpu_partial(s, page, 1);
2944 stat(s, CPU_PARTIAL_FREE);
2945 }
2946 /*
2947 * The list lock was not taken therefore no list
2948 * activity can be necessary.
2949 */
2950 if (was_frozen)
2951 stat(s, FREE_FROZEN);
2952 return;
2953 }
2954
2955 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
2956 goto slab_empty;
2957
2958 /*
2959 * Objects left in the slab. If it was not on the partial list before
2960 * then add it.
2961 */
2962 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
David Brazdil0f672f62019-12-10 10:32:29 +00002963 remove_full(s, n, page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00002964 add_partial(n, page, DEACTIVATE_TO_TAIL);
2965 stat(s, FREE_ADD_PARTIAL);
2966 }
2967 spin_unlock_irqrestore(&n->list_lock, flags);
2968 return;
2969
2970slab_empty:
2971 if (prior) {
2972 /*
2973 * Slab on the partial list.
2974 */
2975 remove_partial(n, page);
2976 stat(s, FREE_REMOVE_PARTIAL);
2977 } else {
2978 /* Slab must be on the full list */
2979 remove_full(s, n, page);
2980 }
2981
2982 spin_unlock_irqrestore(&n->list_lock, flags);
2983 stat(s, FREE_SLAB);
2984 discard_slab(s, page);
2985}
2986
2987/*
2988 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2989 * can perform fastpath freeing without additional function calls.
2990 *
2991 * The fastpath is only possible if we are freeing to the current cpu slab
2992 * of this processor. This typically the case if we have just allocated
2993 * the item before.
2994 *
2995 * If fastpath is not possible then fall back to __slab_free where we deal
2996 * with all sorts of special processing.
2997 *
2998 * Bulk free of a freelist with several objects (all pointing to the
2999 * same page) possible by specifying head and tail ptr, plus objects
3000 * count (cnt). Bulk free indicated by tail pointer being set.
3001 */
3002static __always_inline void do_slab_free(struct kmem_cache *s,
3003 struct page *page, void *head, void *tail,
3004 int cnt, unsigned long addr)
3005{
3006 void *tail_obj = tail ? : head;
3007 struct kmem_cache_cpu *c;
3008 unsigned long tid;
3009redo:
3010 /*
3011 * Determine the currently cpus per cpu slab.
3012 * The cpu may change afterward. However that does not matter since
3013 * data is retrieved via this pointer. If we are on the same cpu
3014 * during the cmpxchg then the free will succeed.
3015 */
3016 do {
3017 tid = this_cpu_read(s->cpu_slab->tid);
3018 c = raw_cpu_ptr(s->cpu_slab);
3019 } while (IS_ENABLED(CONFIG_PREEMPT) &&
3020 unlikely(tid != READ_ONCE(c->tid)));
3021
3022 /* Same with comment on barrier() in slab_alloc_node() */
3023 barrier();
3024
3025 if (likely(page == c->page)) {
Olivier Deprez0e641232021-09-23 10:07:05 +02003026 void **freelist = READ_ONCE(c->freelist);
3027
3028 set_freepointer(s, tail_obj, freelist);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003029
3030 if (unlikely(!this_cpu_cmpxchg_double(
3031 s->cpu_slab->freelist, s->cpu_slab->tid,
Olivier Deprez0e641232021-09-23 10:07:05 +02003032 freelist, tid,
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003033 head, next_tid(tid)))) {
3034
3035 note_cmpxchg_failure("slab_free", s, tid);
3036 goto redo;
3037 }
3038 stat(s, FREE_FASTPATH);
3039 } else
3040 __slab_free(s, page, head, tail_obj, cnt, addr);
3041
3042}
3043
3044static __always_inline void slab_free(struct kmem_cache *s, struct page *page,
3045 void *head, void *tail, int cnt,
3046 unsigned long addr)
3047{
3048 /*
3049 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3050 * to remove objects, whose reuse must be delayed.
3051 */
3052 if (slab_free_freelist_hook(s, &head, &tail))
3053 do_slab_free(s, page, head, tail, cnt, addr);
3054}
3055
David Brazdil0f672f62019-12-10 10:32:29 +00003056#ifdef CONFIG_KASAN_GENERIC
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003057void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3058{
3059 do_slab_free(cache, virt_to_head_page(x), x, NULL, 1, addr);
3060}
3061#endif
3062
3063void kmem_cache_free(struct kmem_cache *s, void *x)
3064{
3065 s = cache_from_obj(s, x);
3066 if (!s)
3067 return;
3068 slab_free(s, virt_to_head_page(x), x, NULL, 1, _RET_IP_);
3069 trace_kmem_cache_free(_RET_IP_, x);
3070}
3071EXPORT_SYMBOL(kmem_cache_free);
3072
3073struct detached_freelist {
3074 struct page *page;
3075 void *tail;
3076 void *freelist;
3077 int cnt;
3078 struct kmem_cache *s;
3079};
3080
3081/*
3082 * This function progressively scans the array with free objects (with
3083 * a limited look ahead) and extract objects belonging to the same
3084 * page. It builds a detached freelist directly within the given
3085 * page/objects. This can happen without any need for
3086 * synchronization, because the objects are owned by running process.
3087 * The freelist is build up as a single linked list in the objects.
3088 * The idea is, that this detached freelist can then be bulk
3089 * transferred to the real freelist(s), but only requiring a single
3090 * synchronization primitive. Look ahead in the array is limited due
3091 * to performance reasons.
3092 */
3093static inline
3094int build_detached_freelist(struct kmem_cache *s, size_t size,
3095 void **p, struct detached_freelist *df)
3096{
3097 size_t first_skipped_index = 0;
3098 int lookahead = 3;
3099 void *object;
3100 struct page *page;
3101
3102 /* Always re-init detached_freelist */
3103 df->page = NULL;
3104
3105 do {
3106 object = p[--size];
3107 /* Do we need !ZERO_OR_NULL_PTR(object) here? (for kfree) */
3108 } while (!object && size);
3109
3110 if (!object)
3111 return 0;
3112
3113 page = virt_to_head_page(object);
3114 if (!s) {
3115 /* Handle kalloc'ed objects */
3116 if (unlikely(!PageSlab(page))) {
3117 BUG_ON(!PageCompound(page));
3118 kfree_hook(object);
3119 __free_pages(page, compound_order(page));
3120 p[size] = NULL; /* mark object processed */
3121 return size;
3122 }
3123 /* Derive kmem_cache from object */
3124 df->s = page->slab_cache;
3125 } else {
3126 df->s = cache_from_obj(s, object); /* Support for memcg */
3127 }
3128
3129 /* Start new detached freelist */
3130 df->page = page;
3131 set_freepointer(df->s, object, NULL);
3132 df->tail = object;
3133 df->freelist = object;
3134 p[size] = NULL; /* mark object processed */
3135 df->cnt = 1;
3136
3137 while (size) {
3138 object = p[--size];
3139 if (!object)
3140 continue; /* Skip processed objects */
3141
3142 /* df->page is always set at this point */
3143 if (df->page == virt_to_head_page(object)) {
3144 /* Opportunity build freelist */
3145 set_freepointer(df->s, object, df->freelist);
3146 df->freelist = object;
3147 df->cnt++;
3148 p[size] = NULL; /* mark object processed */
3149
3150 continue;
3151 }
3152
3153 /* Limit look ahead search */
3154 if (!--lookahead)
3155 break;
3156
3157 if (!first_skipped_index)
3158 first_skipped_index = size + 1;
3159 }
3160
3161 return first_skipped_index;
3162}
3163
3164/* Note that interrupts must be enabled when calling this function. */
3165void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3166{
3167 if (WARN_ON(!size))
3168 return;
3169
3170 do {
3171 struct detached_freelist df;
3172
3173 size = build_detached_freelist(s, size, p, &df);
3174 if (!df.page)
3175 continue;
3176
3177 slab_free(df.s, df.page, df.freelist, df.tail, df.cnt,_RET_IP_);
3178 } while (likely(size));
3179}
3180EXPORT_SYMBOL(kmem_cache_free_bulk);
3181
3182/* Note that interrupts must be enabled when calling this function. */
3183int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3184 void **p)
3185{
3186 struct kmem_cache_cpu *c;
3187 int i;
3188
3189 /* memcg and kmem_cache debug support */
3190 s = slab_pre_alloc_hook(s, flags);
3191 if (unlikely(!s))
3192 return false;
3193 /*
3194 * Drain objects in the per cpu slab, while disabling local
3195 * IRQs, which protects against PREEMPT and interrupts
3196 * handlers invoking normal fastpath.
3197 */
3198 local_irq_disable();
3199 c = this_cpu_ptr(s->cpu_slab);
3200
3201 for (i = 0; i < size; i++) {
3202 void *object = c->freelist;
3203
3204 if (unlikely(!object)) {
3205 /*
Olivier Deprez0e641232021-09-23 10:07:05 +02003206 * We may have removed an object from c->freelist using
3207 * the fastpath in the previous iteration; in that case,
3208 * c->tid has not been bumped yet.
3209 * Since ___slab_alloc() may reenable interrupts while
3210 * allocating memory, we should bump c->tid now.
3211 */
3212 c->tid = next_tid(c->tid);
3213
3214 /*
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003215 * Invoking slow path likely have side-effect
3216 * of re-populating per CPU c->freelist
3217 */
3218 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3219 _RET_IP_, c);
3220 if (unlikely(!p[i]))
3221 goto error;
3222
3223 c = this_cpu_ptr(s->cpu_slab);
David Brazdil0f672f62019-12-10 10:32:29 +00003224 maybe_wipe_obj_freeptr(s, p[i]);
3225
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003226 continue; /* goto for-loop */
3227 }
3228 c->freelist = get_freepointer(s, object);
3229 p[i] = object;
David Brazdil0f672f62019-12-10 10:32:29 +00003230 maybe_wipe_obj_freeptr(s, p[i]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003231 }
3232 c->tid = next_tid(c->tid);
3233 local_irq_enable();
3234
3235 /* Clear memory outside IRQ disabled fastpath loop */
David Brazdil0f672f62019-12-10 10:32:29 +00003236 if (unlikely(slab_want_init_on_alloc(flags, s))) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003237 int j;
3238
3239 for (j = 0; j < i; j++)
3240 memset(p[j], 0, s->object_size);
3241 }
3242
3243 /* memcg and kmem_cache debug support */
3244 slab_post_alloc_hook(s, flags, size, p);
3245 return i;
3246error:
3247 local_irq_enable();
3248 slab_post_alloc_hook(s, flags, i, p);
3249 __kmem_cache_free_bulk(s, i, p);
3250 return 0;
3251}
3252EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3253
3254
3255/*
3256 * Object placement in a slab is made very easy because we always start at
3257 * offset 0. If we tune the size of the object to the alignment then we can
3258 * get the required alignment by putting one properly sized object after
3259 * another.
3260 *
3261 * Notice that the allocation order determines the sizes of the per cpu
3262 * caches. Each processor has always one slab available for allocations.
3263 * Increasing the allocation order reduces the number of times that slabs
3264 * must be moved on and off the partial lists and is therefore a factor in
3265 * locking overhead.
3266 */
3267
3268/*
3269 * Mininum / Maximum order of slab pages. This influences locking overhead
3270 * and slab fragmentation. A higher order reduces the number of partial slabs
3271 * and increases the number of allocations possible without having to
3272 * take the list_lock.
3273 */
3274static unsigned int slub_min_order;
3275static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3276static unsigned int slub_min_objects;
3277
3278/*
3279 * Calculate the order of allocation given an slab object size.
3280 *
3281 * The order of allocation has significant impact on performance and other
3282 * system components. Generally order 0 allocations should be preferred since
3283 * order 0 does not cause fragmentation in the page allocator. Larger objects
3284 * be problematic to put into order 0 slabs because there may be too much
3285 * unused space left. We go to a higher order if more than 1/16th of the slab
3286 * would be wasted.
3287 *
3288 * In order to reach satisfactory performance we must ensure that a minimum
3289 * number of objects is in one slab. Otherwise we may generate too much
3290 * activity on the partial lists which requires taking the list_lock. This is
3291 * less a concern for large slabs though which are rarely used.
3292 *
3293 * slub_max_order specifies the order where we begin to stop considering the
3294 * number of objects in a slab as critical. If we reach slub_max_order then
3295 * we try to keep the page order as low as possible. So we accept more waste
3296 * of space in favor of a small page order.
3297 *
3298 * Higher order allocations also allow the placement of more objects in a
3299 * slab and thereby reduce object handling overhead. If the user has
3300 * requested a higher mininum order then we start with that one instead of
3301 * the smallest order which will fit the object.
3302 */
3303static inline unsigned int slab_order(unsigned int size,
3304 unsigned int min_objects, unsigned int max_order,
3305 unsigned int fract_leftover)
3306{
3307 unsigned int min_order = slub_min_order;
3308 unsigned int order;
3309
3310 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
3311 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
3312
3313 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
3314 order <= max_order; order++) {
3315
3316 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3317 unsigned int rem;
3318
3319 rem = slab_size % size;
3320
3321 if (rem <= slab_size / fract_leftover)
3322 break;
3323 }
3324
3325 return order;
3326}
3327
3328static inline int calculate_order(unsigned int size)
3329{
3330 unsigned int order;
3331 unsigned int min_objects;
3332 unsigned int max_objects;
3333
3334 /*
3335 * Attempt to find best configuration for a slab. This
3336 * works by first attempting to generate a layout with
3337 * the best configuration and backing off gradually.
3338 *
3339 * First we increase the acceptable waste in a slab. Then
3340 * we reduce the minimum objects required in a slab.
3341 */
3342 min_objects = slub_min_objects;
3343 if (!min_objects)
3344 min_objects = 4 * (fls(nr_cpu_ids) + 1);
3345 max_objects = order_objects(slub_max_order, size);
3346 min_objects = min(min_objects, max_objects);
3347
3348 while (min_objects > 1) {
3349 unsigned int fraction;
3350
3351 fraction = 16;
3352 while (fraction >= 4) {
3353 order = slab_order(size, min_objects,
3354 slub_max_order, fraction);
3355 if (order <= slub_max_order)
3356 return order;
3357 fraction /= 2;
3358 }
3359 min_objects--;
3360 }
3361
3362 /*
3363 * We were unable to place multiple objects in a slab. Now
3364 * lets see if we can place a single object there.
3365 */
3366 order = slab_order(size, 1, slub_max_order, 1);
3367 if (order <= slub_max_order)
3368 return order;
3369
3370 /*
3371 * Doh this slab cannot be placed using slub_max_order.
3372 */
3373 order = slab_order(size, 1, MAX_ORDER, 1);
3374 if (order < MAX_ORDER)
3375 return order;
3376 return -ENOSYS;
3377}
3378
3379static void
3380init_kmem_cache_node(struct kmem_cache_node *n)
3381{
3382 n->nr_partial = 0;
3383 spin_lock_init(&n->list_lock);
3384 INIT_LIST_HEAD(&n->partial);
3385#ifdef CONFIG_SLUB_DEBUG
3386 atomic_long_set(&n->nr_slabs, 0);
3387 atomic_long_set(&n->total_objects, 0);
3388 INIT_LIST_HEAD(&n->full);
3389#endif
3390}
3391
3392static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
3393{
3394 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
3395 KMALLOC_SHIFT_HIGH * sizeof(struct kmem_cache_cpu));
3396
3397 /*
3398 * Must align to double word boundary for the double cmpxchg
3399 * instructions to work; see __pcpu_double_call_return_bool().
3400 */
3401 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
3402 2 * sizeof(void *));
3403
3404 if (!s->cpu_slab)
3405 return 0;
3406
3407 init_kmem_cache_cpus(s);
3408
3409 return 1;
3410}
3411
3412static struct kmem_cache *kmem_cache_node;
3413
3414/*
3415 * No kmalloc_node yet so do it by hand. We know that this is the first
3416 * slab on the node for this slabcache. There are no concurrent accesses
3417 * possible.
3418 *
3419 * Note that this function only works on the kmem_cache_node
3420 * when allocating for the kmem_cache_node. This is used for bootstrapping
3421 * memory on a fresh node that has no slab structures yet.
3422 */
3423static void early_kmem_cache_node_alloc(int node)
3424{
3425 struct page *page;
3426 struct kmem_cache_node *n;
3427
3428 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
3429
3430 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
3431
3432 BUG_ON(!page);
3433 if (page_to_nid(page) != node) {
3434 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
3435 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
3436 }
3437
3438 n = page->freelist;
3439 BUG_ON(!n);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003440#ifdef CONFIG_SLUB_DEBUG
3441 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
3442 init_tracking(kmem_cache_node, n);
3443#endif
David Brazdil0f672f62019-12-10 10:32:29 +00003444 n = kasan_kmalloc(kmem_cache_node, n, sizeof(struct kmem_cache_node),
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003445 GFP_KERNEL);
David Brazdil0f672f62019-12-10 10:32:29 +00003446 page->freelist = get_freepointer(kmem_cache_node, n);
3447 page->inuse = 1;
3448 page->frozen = 0;
3449 kmem_cache_node->node[node] = n;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003450 init_kmem_cache_node(n);
3451 inc_slabs_node(kmem_cache_node, node, page->objects);
3452
3453 /*
3454 * No locks need to be taken here as it has just been
3455 * initialized and there is no concurrent access.
3456 */
3457 __add_partial(n, page, DEACTIVATE_TO_HEAD);
3458}
3459
3460static void free_kmem_cache_nodes(struct kmem_cache *s)
3461{
3462 int node;
3463 struct kmem_cache_node *n;
3464
3465 for_each_kmem_cache_node(s, node, n) {
3466 s->node[node] = NULL;
3467 kmem_cache_free(kmem_cache_node, n);
3468 }
3469}
3470
3471void __kmem_cache_release(struct kmem_cache *s)
3472{
3473 cache_random_seq_destroy(s);
3474 free_percpu(s->cpu_slab);
3475 free_kmem_cache_nodes(s);
3476}
3477
3478static int init_kmem_cache_nodes(struct kmem_cache *s)
3479{
3480 int node;
3481
3482 for_each_node_state(node, N_NORMAL_MEMORY) {
3483 struct kmem_cache_node *n;
3484
3485 if (slab_state == DOWN) {
3486 early_kmem_cache_node_alloc(node);
3487 continue;
3488 }
3489 n = kmem_cache_alloc_node(kmem_cache_node,
3490 GFP_KERNEL, node);
3491
3492 if (!n) {
3493 free_kmem_cache_nodes(s);
3494 return 0;
3495 }
3496
3497 init_kmem_cache_node(n);
3498 s->node[node] = n;
3499 }
3500 return 1;
3501}
3502
3503static void set_min_partial(struct kmem_cache *s, unsigned long min)
3504{
3505 if (min < MIN_PARTIAL)
3506 min = MIN_PARTIAL;
3507 else if (min > MAX_PARTIAL)
3508 min = MAX_PARTIAL;
3509 s->min_partial = min;
3510}
3511
3512static void set_cpu_partial(struct kmem_cache *s)
3513{
3514#ifdef CONFIG_SLUB_CPU_PARTIAL
3515 /*
3516 * cpu_partial determined the maximum number of objects kept in the
3517 * per cpu partial lists of a processor.
3518 *
3519 * Per cpu partial lists mainly contain slabs that just have one
3520 * object freed. If they are used for allocation then they can be
3521 * filled up again with minimal effort. The slab will never hit the
3522 * per node partial lists and therefore no locking will be required.
3523 *
3524 * This setting also determines
3525 *
3526 * A) The number of objects from per cpu partial slabs dumped to the
3527 * per node list when we reach the limit.
3528 * B) The number of objects in cpu partial slabs to extract from the
3529 * per node list when we run out of per cpu objects. We only fetch
3530 * 50% to keep some capacity around for frees.
3531 */
3532 if (!kmem_cache_has_cpu_partial(s))
3533 s->cpu_partial = 0;
3534 else if (s->size >= PAGE_SIZE)
3535 s->cpu_partial = 2;
3536 else if (s->size >= 1024)
3537 s->cpu_partial = 6;
3538 else if (s->size >= 256)
3539 s->cpu_partial = 13;
3540 else
3541 s->cpu_partial = 30;
3542#endif
3543}
3544
3545/*
3546 * calculate_sizes() determines the order and the distribution of data within
3547 * a slab object.
3548 */
3549static int calculate_sizes(struct kmem_cache *s, int forced_order)
3550{
3551 slab_flags_t flags = s->flags;
3552 unsigned int size = s->object_size;
3553 unsigned int order;
3554
3555 /*
3556 * Round up object size to the next word boundary. We can only
3557 * place the free pointer at word boundaries and this determines
3558 * the possible location of the free pointer.
3559 */
3560 size = ALIGN(size, sizeof(void *));
3561
3562#ifdef CONFIG_SLUB_DEBUG
3563 /*
3564 * Determine if we can poison the object itself. If the user of
3565 * the slab may touch the object after free or before allocation
3566 * then we should never poison the object itself.
3567 */
3568 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
3569 !s->ctor)
3570 s->flags |= __OBJECT_POISON;
3571 else
3572 s->flags &= ~__OBJECT_POISON;
3573
3574
3575 /*
3576 * If we are Redzoning then check if there is some space between the
3577 * end of the object and the free pointer. If not then add an
3578 * additional word to have some bytes to store Redzone information.
3579 */
3580 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
3581 size += sizeof(void *);
3582#endif
3583
3584 /*
3585 * With that we have determined the number of bytes in actual use
3586 * by the object. This is the potential offset to the free pointer.
3587 */
3588 s->inuse = size;
3589
Olivier Deprez0e641232021-09-23 10:07:05 +02003590 if ((flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
3591 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
3592 s->ctor) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003593 /*
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.
3597 *
3598 * This is the case if we do RCU, have a constructor or
Olivier Deprez0e641232021-09-23 10:07:05 +02003599 * destructor, are poisoning the objects, or are
3600 * redzoning an object smaller than sizeof(void *).
3601 *
3602 * The assumption that s->offset >= s->inuse means free
3603 * pointer is outside of the object is used in the
3604 * freeptr_outside_object() function. If that is no
3605 * longer true, the function needs to be modified.
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003606 */
3607 s->offset = size;
3608 size += sizeof(void *);
3609 }
3610
3611#ifdef CONFIG_SLUB_DEBUG
3612 if (flags & SLAB_STORE_USER)
3613 /*
3614 * Need to store information about allocs and frees after
3615 * the object.
3616 */
3617 size += 2 * sizeof(struct track);
3618#endif
3619
3620 kasan_cache_create(s, &size, &s->flags);
3621#ifdef CONFIG_SLUB_DEBUG
3622 if (flags & SLAB_RED_ZONE) {
3623 /*
3624 * Add some empty padding so that we can catch
3625 * overwrites from earlier objects rather than let
3626 * tracking information or the free pointer be
3627 * corrupted if a user writes before the start
3628 * of the object.
3629 */
3630 size += sizeof(void *);
3631
3632 s->red_left_pad = sizeof(void *);
3633 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
3634 size += s->red_left_pad;
3635 }
3636#endif
3637
3638 /*
3639 * SLUB stores one object immediately after another beginning from
3640 * offset 0. In order to align the objects we have to simply size
3641 * each object to conform to the alignment.
3642 */
3643 size = ALIGN(size, s->align);
3644 s->size = size;
3645 if (forced_order >= 0)
3646 order = forced_order;
3647 else
3648 order = calculate_order(size);
3649
3650 if ((int)order < 0)
3651 return 0;
3652
3653 s->allocflags = 0;
3654 if (order)
3655 s->allocflags |= __GFP_COMP;
3656
3657 if (s->flags & SLAB_CACHE_DMA)
3658 s->allocflags |= GFP_DMA;
3659
David Brazdil0f672f62019-12-10 10:32:29 +00003660 if (s->flags & SLAB_CACHE_DMA32)
3661 s->allocflags |= GFP_DMA32;
3662
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003663 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3664 s->allocflags |= __GFP_RECLAIMABLE;
3665
3666 /*
3667 * Determine the number of objects per slab
3668 */
3669 s->oo = oo_make(order, size);
3670 s->min = oo_make(get_order(size), size);
3671 if (oo_objects(s->oo) > oo_objects(s->max))
3672 s->max = s->oo;
3673
3674 return !!oo_objects(s->oo);
3675}
3676
3677static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
3678{
3679 s->flags = kmem_cache_flags(s->size, flags, s->name, s->ctor);
3680#ifdef CONFIG_SLAB_FREELIST_HARDENED
3681 s->random = get_random_long();
3682#endif
3683
3684 if (!calculate_sizes(s, -1))
3685 goto error;
3686 if (disable_higher_order_debug) {
3687 /*
3688 * Disable debugging flags that store metadata if the min slab
3689 * order increased.
3690 */
3691 if (get_order(s->size) > get_order(s->object_size)) {
3692 s->flags &= ~DEBUG_METADATA_FLAGS;
3693 s->offset = 0;
3694 if (!calculate_sizes(s, -1))
3695 goto error;
3696 }
3697 }
3698
3699#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3700 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3701 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
3702 /* Enable fast mode */
3703 s->flags |= __CMPXCHG_DOUBLE;
3704#endif
3705
3706 /*
3707 * The larger the object size is, the more pages we want on the partial
3708 * list to avoid pounding the page allocator excessively.
3709 */
3710 set_min_partial(s, ilog2(s->size) / 2);
3711
3712 set_cpu_partial(s);
3713
3714#ifdef CONFIG_NUMA
3715 s->remote_node_defrag_ratio = 1000;
3716#endif
3717
3718 /* Initialize the pre-computed randomized freelist if slab is up */
3719 if (slab_state >= UP) {
3720 if (init_cache_random_seq(s))
3721 goto error;
3722 }
3723
3724 if (!init_kmem_cache_nodes(s))
3725 goto error;
3726
3727 if (alloc_kmem_cache_cpus(s))
3728 return 0;
3729
3730 free_kmem_cache_nodes(s);
3731error:
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003732 return -EINVAL;
3733}
3734
3735static void list_slab_objects(struct kmem_cache *s, struct page *page,
3736 const char *text)
3737{
3738#ifdef CONFIG_SLUB_DEBUG
3739 void *addr = page_address(page);
3740 void *p;
David Brazdil0f672f62019-12-10 10:32:29 +00003741 unsigned long *map = bitmap_zalloc(page->objects, GFP_ATOMIC);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003742 if (!map)
3743 return;
3744 slab_err(s, page, text, s->name);
3745 slab_lock(page);
3746
3747 get_map(s, page, map);
3748 for_each_object(p, s, addr, page->objects) {
3749
3750 if (!test_bit(slab_index(p, s, addr), map)) {
3751 pr_err("INFO: Object 0x%p @offset=%tu\n", p, p - addr);
3752 print_tracking(s, p);
3753 }
3754 }
3755 slab_unlock(page);
David Brazdil0f672f62019-12-10 10:32:29 +00003756 bitmap_free(map);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003757#endif
3758}
3759
3760/*
3761 * Attempt to free all partial slabs on a node.
3762 * This is called from __kmem_cache_shutdown(). We must take list_lock
3763 * because sysfs file might still access partial list after the shutdowning.
3764 */
3765static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3766{
3767 LIST_HEAD(discard);
3768 struct page *page, *h;
3769
3770 BUG_ON(irqs_disabled());
3771 spin_lock_irq(&n->list_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00003772 list_for_each_entry_safe(page, h, &n->partial, slab_list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003773 if (!page->inuse) {
3774 remove_partial(n, page);
David Brazdil0f672f62019-12-10 10:32:29 +00003775 list_add(&page->slab_list, &discard);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003776 } else {
3777 list_slab_objects(s, page,
3778 "Objects remaining in %s on __kmem_cache_shutdown()");
3779 }
3780 }
3781 spin_unlock_irq(&n->list_lock);
3782
David Brazdil0f672f62019-12-10 10:32:29 +00003783 list_for_each_entry_safe(page, h, &discard, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003784 discard_slab(s, page);
3785}
3786
3787bool __kmem_cache_empty(struct kmem_cache *s)
3788{
3789 int node;
3790 struct kmem_cache_node *n;
3791
3792 for_each_kmem_cache_node(s, node, n)
3793 if (n->nr_partial || slabs_node(s, node))
3794 return false;
3795 return true;
3796}
3797
3798/*
3799 * Release all resources used by a slab cache.
3800 */
3801int __kmem_cache_shutdown(struct kmem_cache *s)
3802{
3803 int node;
3804 struct kmem_cache_node *n;
3805
3806 flush_all(s);
3807 /* Attempt to free all objects */
3808 for_each_kmem_cache_node(s, node, n) {
3809 free_partial(s, n);
3810 if (n->nr_partial || slabs_node(s, node))
3811 return 1;
3812 }
3813 sysfs_slab_remove(s);
3814 return 0;
3815}
3816
3817/********************************************************************
3818 * Kmalloc subsystem
3819 *******************************************************************/
3820
3821static int __init setup_slub_min_order(char *str)
3822{
3823 get_option(&str, (int *)&slub_min_order);
3824
3825 return 1;
3826}
3827
3828__setup("slub_min_order=", setup_slub_min_order);
3829
3830static int __init setup_slub_max_order(char *str)
3831{
3832 get_option(&str, (int *)&slub_max_order);
3833 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
3834
3835 return 1;
3836}
3837
3838__setup("slub_max_order=", setup_slub_max_order);
3839
3840static int __init setup_slub_min_objects(char *str)
3841{
3842 get_option(&str, (int *)&slub_min_objects);
3843
3844 return 1;
3845}
3846
3847__setup("slub_min_objects=", setup_slub_min_objects);
3848
3849void *__kmalloc(size_t size, gfp_t flags)
3850{
3851 struct kmem_cache *s;
3852 void *ret;
3853
3854 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
3855 return kmalloc_large(size, flags);
3856
3857 s = kmalloc_slab(size, flags);
3858
3859 if (unlikely(ZERO_OR_NULL_PTR(s)))
3860 return s;
3861
3862 ret = slab_alloc(s, flags, _RET_IP_);
3863
3864 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3865
David Brazdil0f672f62019-12-10 10:32:29 +00003866 ret = kasan_kmalloc(s, ret, size, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003867
3868 return ret;
3869}
3870EXPORT_SYMBOL(__kmalloc);
3871
3872#ifdef CONFIG_NUMA
3873static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3874{
3875 struct page *page;
3876 void *ptr = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00003877 unsigned int order = get_order(size);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003878
3879 flags |= __GFP_COMP;
David Brazdil0f672f62019-12-10 10:32:29 +00003880 page = alloc_pages_node(node, flags, order);
3881 if (page) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003882 ptr = page_address(page);
David Brazdil0f672f62019-12-10 10:32:29 +00003883 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
3884 1 << order);
3885 }
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003886
David Brazdil0f672f62019-12-10 10:32:29 +00003887 return kmalloc_large_node_hook(ptr, size, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003888}
3889
3890void *__kmalloc_node(size_t size, gfp_t flags, int node)
3891{
3892 struct kmem_cache *s;
3893 void *ret;
3894
3895 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
3896 ret = kmalloc_large_node(size, flags, node);
3897
3898 trace_kmalloc_node(_RET_IP_, ret,
3899 size, PAGE_SIZE << get_order(size),
3900 flags, node);
3901
3902 return ret;
3903 }
3904
3905 s = kmalloc_slab(size, flags);
3906
3907 if (unlikely(ZERO_OR_NULL_PTR(s)))
3908 return s;
3909
3910 ret = slab_alloc_node(s, flags, node, _RET_IP_);
3911
3912 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3913
David Brazdil0f672f62019-12-10 10:32:29 +00003914 ret = kasan_kmalloc(s, ret, size, flags);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003915
3916 return ret;
3917}
3918EXPORT_SYMBOL(__kmalloc_node);
David Brazdil0f672f62019-12-10 10:32:29 +00003919#endif /* CONFIG_NUMA */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003920
3921#ifdef CONFIG_HARDENED_USERCOPY
3922/*
3923 * Rejects incorrectly sized objects and objects that are to be copied
3924 * to/from userspace but do not fall entirely within the containing slab
3925 * cache's usercopy region.
3926 *
3927 * Returns NULL if check passes, otherwise const char * to name of cache
3928 * to indicate an error.
3929 */
3930void __check_heap_object(const void *ptr, unsigned long n, struct page *page,
3931 bool to_user)
3932{
3933 struct kmem_cache *s;
3934 unsigned int offset;
3935 size_t object_size;
3936
David Brazdil0f672f62019-12-10 10:32:29 +00003937 ptr = kasan_reset_tag(ptr);
3938
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003939 /* Find object and usable object size. */
3940 s = page->slab_cache;
3941
3942 /* Reject impossible pointers. */
3943 if (ptr < page_address(page))
3944 usercopy_abort("SLUB object not in SLUB page?!", NULL,
3945 to_user, 0, n);
3946
3947 /* Find offset within object. */
3948 offset = (ptr - page_address(page)) % s->size;
3949
3950 /* Adjust for redzone and reject if within the redzone. */
3951 if (kmem_cache_debug(s) && s->flags & SLAB_RED_ZONE) {
3952 if (offset < s->red_left_pad)
3953 usercopy_abort("SLUB object in left red zone",
3954 s->name, to_user, offset, n);
3955 offset -= s->red_left_pad;
3956 }
3957
3958 /* Allow address range falling entirely within usercopy region. */
3959 if (offset >= s->useroffset &&
3960 offset - s->useroffset <= s->usersize &&
3961 n <= s->useroffset - offset + s->usersize)
3962 return;
3963
3964 /*
3965 * If the copy is still within the allocated object, produce
3966 * a warning instead of rejecting the copy. This is intended
3967 * to be a temporary method to find any missing usercopy
3968 * whitelists.
3969 */
3970 object_size = slab_ksize(s);
3971 if (usercopy_fallback &&
3972 offset <= object_size && n <= object_size - offset) {
3973 usercopy_warn("SLUB object", s->name, to_user, offset, n);
3974 return;
3975 }
3976
3977 usercopy_abort("SLUB object", s->name, to_user, offset, n);
3978}
3979#endif /* CONFIG_HARDENED_USERCOPY */
3980
David Brazdil0f672f62019-12-10 10:32:29 +00003981size_t __ksize(const void *object)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003982{
3983 struct page *page;
3984
3985 if (unlikely(object == ZERO_SIZE_PTR))
3986 return 0;
3987
3988 page = virt_to_head_page(object);
3989
3990 if (unlikely(!PageSlab(page))) {
3991 WARN_ON(!PageCompound(page));
David Brazdil0f672f62019-12-10 10:32:29 +00003992 return page_size(page);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003993 }
3994
3995 return slab_ksize(page->slab_cache);
3996}
David Brazdil0f672f62019-12-10 10:32:29 +00003997EXPORT_SYMBOL(__ksize);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00003998
3999void kfree(const void *x)
4000{
4001 struct page *page;
4002 void *object = (void *)x;
4003
4004 trace_kfree(_RET_IP_, x);
4005
4006 if (unlikely(ZERO_OR_NULL_PTR(x)))
4007 return;
4008
4009 page = virt_to_head_page(x);
4010 if (unlikely(!PageSlab(page))) {
David Brazdil0f672f62019-12-10 10:32:29 +00004011 unsigned int order = compound_order(page);
4012
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004013 BUG_ON(!PageCompound(page));
4014 kfree_hook(object);
David Brazdil0f672f62019-12-10 10:32:29 +00004015 mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE,
4016 -(1 << order));
4017 __free_pages(page, order);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004018 return;
4019 }
4020 slab_free(page->slab_cache, page, object, NULL, 1, _RET_IP_);
4021}
4022EXPORT_SYMBOL(kfree);
4023
4024#define SHRINK_PROMOTE_MAX 32
4025
4026/*
4027 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4028 * up most to the head of the partial lists. New allocations will then
4029 * fill those up and thus they can be removed from the partial lists.
4030 *
4031 * The slabs with the least items are placed last. This results in them
4032 * being allocated from last increasing the chance that the last objects
4033 * are freed in them.
4034 */
4035int __kmem_cache_shrink(struct kmem_cache *s)
4036{
4037 int node;
4038 int i;
4039 struct kmem_cache_node *n;
4040 struct page *page;
4041 struct page *t;
4042 struct list_head discard;
4043 struct list_head promote[SHRINK_PROMOTE_MAX];
4044 unsigned long flags;
4045 int ret = 0;
4046
4047 flush_all(s);
4048 for_each_kmem_cache_node(s, node, n) {
4049 INIT_LIST_HEAD(&discard);
4050 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4051 INIT_LIST_HEAD(promote + i);
4052
4053 spin_lock_irqsave(&n->list_lock, flags);
4054
4055 /*
4056 * Build lists of slabs to discard or promote.
4057 *
4058 * Note that concurrent frees may occur while we hold the
4059 * list_lock. page->inuse here is the upper limit.
4060 */
David Brazdil0f672f62019-12-10 10:32:29 +00004061 list_for_each_entry_safe(page, t, &n->partial, slab_list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004062 int free = page->objects - page->inuse;
4063
4064 /* Do not reread page->inuse */
4065 barrier();
4066
4067 /* We do not keep full slabs on the list */
4068 BUG_ON(free <= 0);
4069
4070 if (free == page->objects) {
David Brazdil0f672f62019-12-10 10:32:29 +00004071 list_move(&page->slab_list, &discard);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004072 n->nr_partial--;
4073 } else if (free <= SHRINK_PROMOTE_MAX)
David Brazdil0f672f62019-12-10 10:32:29 +00004074 list_move(&page->slab_list, promote + free - 1);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004075 }
4076
4077 /*
4078 * Promote the slabs filled up most to the head of the
4079 * partial list.
4080 */
4081 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4082 list_splice(promote + i, &n->partial);
4083
4084 spin_unlock_irqrestore(&n->list_lock, flags);
4085
4086 /* Release empty slabs */
David Brazdil0f672f62019-12-10 10:32:29 +00004087 list_for_each_entry_safe(page, t, &discard, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004088 discard_slab(s, page);
4089
4090 if (slabs_node(s, node))
4091 ret = 1;
4092 }
4093
4094 return ret;
4095}
4096
4097#ifdef CONFIG_MEMCG
David Brazdil0f672f62019-12-10 10:32:29 +00004098void __kmemcg_cache_deactivate_after_rcu(struct kmem_cache *s)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004099{
4100 /*
4101 * Called with all the locks held after a sched RCU grace period.
4102 * Even if @s becomes empty after shrinking, we can't know that @s
4103 * doesn't have allocations already in-flight and thus can't
4104 * destroy @s until the associated memcg is released.
4105 *
4106 * However, let's remove the sysfs files for empty caches here.
4107 * Each cache has a lot of interface files which aren't
4108 * particularly useful for empty draining caches; otherwise, we can
4109 * easily end up with millions of unnecessary sysfs files on
4110 * systems which have a lot of memory and transient cgroups.
4111 */
4112 if (!__kmem_cache_shrink(s))
4113 sysfs_slab_remove(s);
4114}
4115
4116void __kmemcg_cache_deactivate(struct kmem_cache *s)
4117{
4118 /*
4119 * Disable empty slabs caching. Used to avoid pinning offline
4120 * memory cgroups by kmem pages that can be freed.
4121 */
4122 slub_set_cpu_partial(s, 0);
4123 s->min_partial = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004124}
David Brazdil0f672f62019-12-10 10:32:29 +00004125#endif /* CONFIG_MEMCG */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004126
4127static int slab_mem_going_offline_callback(void *arg)
4128{
4129 struct kmem_cache *s;
4130
4131 mutex_lock(&slab_mutex);
4132 list_for_each_entry(s, &slab_caches, list)
4133 __kmem_cache_shrink(s);
4134 mutex_unlock(&slab_mutex);
4135
4136 return 0;
4137}
4138
4139static void slab_mem_offline_callback(void *arg)
4140{
4141 struct kmem_cache_node *n;
4142 struct kmem_cache *s;
4143 struct memory_notify *marg = arg;
4144 int offline_node;
4145
4146 offline_node = marg->status_change_nid_normal;
4147
4148 /*
4149 * If the node still has available memory. we need kmem_cache_node
4150 * for it yet.
4151 */
4152 if (offline_node < 0)
4153 return;
4154
4155 mutex_lock(&slab_mutex);
4156 list_for_each_entry(s, &slab_caches, list) {
4157 n = get_node(s, offline_node);
4158 if (n) {
4159 /*
4160 * if n->nr_slabs > 0, slabs still exist on the node
4161 * that is going down. We were unable to free them,
4162 * and offline_pages() function shouldn't call this
4163 * callback. So, we must fail.
4164 */
4165 BUG_ON(slabs_node(s, offline_node));
4166
4167 s->node[offline_node] = NULL;
4168 kmem_cache_free(kmem_cache_node, n);
4169 }
4170 }
4171 mutex_unlock(&slab_mutex);
4172}
4173
4174static int slab_mem_going_online_callback(void *arg)
4175{
4176 struct kmem_cache_node *n;
4177 struct kmem_cache *s;
4178 struct memory_notify *marg = arg;
4179 int nid = marg->status_change_nid_normal;
4180 int ret = 0;
4181
4182 /*
4183 * If the node's memory is already available, then kmem_cache_node is
4184 * already created. Nothing to do.
4185 */
4186 if (nid < 0)
4187 return 0;
4188
4189 /*
4190 * We are bringing a node online. No memory is available yet. We must
4191 * allocate a kmem_cache_node structure in order to bring the node
4192 * online.
4193 */
4194 mutex_lock(&slab_mutex);
4195 list_for_each_entry(s, &slab_caches, list) {
4196 /*
4197 * XXX: kmem_cache_alloc_node will fallback to other nodes
4198 * since memory is not yet available from the node that
4199 * is brought up.
4200 */
4201 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4202 if (!n) {
4203 ret = -ENOMEM;
4204 goto out;
4205 }
4206 init_kmem_cache_node(n);
4207 s->node[nid] = n;
4208 }
4209out:
4210 mutex_unlock(&slab_mutex);
4211 return ret;
4212}
4213
4214static int slab_memory_callback(struct notifier_block *self,
4215 unsigned long action, void *arg)
4216{
4217 int ret = 0;
4218
4219 switch (action) {
4220 case MEM_GOING_ONLINE:
4221 ret = slab_mem_going_online_callback(arg);
4222 break;
4223 case MEM_GOING_OFFLINE:
4224 ret = slab_mem_going_offline_callback(arg);
4225 break;
4226 case MEM_OFFLINE:
4227 case MEM_CANCEL_ONLINE:
4228 slab_mem_offline_callback(arg);
4229 break;
4230 case MEM_ONLINE:
4231 case MEM_CANCEL_OFFLINE:
4232 break;
4233 }
4234 if (ret)
4235 ret = notifier_from_errno(ret);
4236 else
4237 ret = NOTIFY_OK;
4238 return ret;
4239}
4240
4241static struct notifier_block slab_memory_callback_nb = {
4242 .notifier_call = slab_memory_callback,
4243 .priority = SLAB_CALLBACK_PRI,
4244};
4245
4246/********************************************************************
4247 * Basic setup of slabs
4248 *******************************************************************/
4249
4250/*
4251 * Used for early kmem_cache structures that were allocated using
4252 * the page allocator. Allocate them properly then fix up the pointers
4253 * that may be pointing to the wrong kmem_cache structure.
4254 */
4255
4256static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
4257{
4258 int node;
4259 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
4260 struct kmem_cache_node *n;
4261
4262 memcpy(s, static_cache, kmem_cache->object_size);
4263
4264 /*
4265 * This runs very early, and only the boot processor is supposed to be
4266 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4267 * IPIs around.
4268 */
4269 __flush_cpu_slab(s, smp_processor_id());
4270 for_each_kmem_cache_node(s, node, n) {
4271 struct page *p;
4272
David Brazdil0f672f62019-12-10 10:32:29 +00004273 list_for_each_entry(p, &n->partial, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004274 p->slab_cache = s;
4275
4276#ifdef CONFIG_SLUB_DEBUG
David Brazdil0f672f62019-12-10 10:32:29 +00004277 list_for_each_entry(p, &n->full, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004278 p->slab_cache = s;
4279#endif
4280 }
4281 slab_init_memcg_params(s);
4282 list_add(&s->list, &slab_caches);
David Brazdil0f672f62019-12-10 10:32:29 +00004283 memcg_link_cache(s, NULL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004284 return s;
4285}
4286
4287void __init kmem_cache_init(void)
4288{
4289 static __initdata struct kmem_cache boot_kmem_cache,
4290 boot_kmem_cache_node;
4291
4292 if (debug_guardpage_minorder())
4293 slub_max_order = 0;
4294
4295 kmem_cache_node = &boot_kmem_cache_node;
4296 kmem_cache = &boot_kmem_cache;
4297
4298 create_boot_cache(kmem_cache_node, "kmem_cache_node",
4299 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
4300
4301 register_hotmemory_notifier(&slab_memory_callback_nb);
4302
4303 /* Able to allocate the per node structures */
4304 slab_state = PARTIAL;
4305
4306 create_boot_cache(kmem_cache, "kmem_cache",
4307 offsetof(struct kmem_cache, node) +
4308 nr_node_ids * sizeof(struct kmem_cache_node *),
4309 SLAB_HWCACHE_ALIGN, 0, 0);
4310
4311 kmem_cache = bootstrap(&boot_kmem_cache);
4312 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
4313
4314 /* Now we can use the kmem_cache to allocate kmalloc slabs */
4315 setup_kmalloc_cache_index_table();
4316 create_kmalloc_caches(0);
4317
4318 /* Setup random freelists for each cache */
4319 init_freelist_randomization();
4320
4321 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4322 slub_cpu_dead);
4323
David Brazdil0f672f62019-12-10 10:32:29 +00004324 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004325 cache_line_size(),
4326 slub_min_order, slub_max_order, slub_min_objects,
4327 nr_cpu_ids, nr_node_ids);
4328}
4329
4330void __init kmem_cache_init_late(void)
4331{
4332}
4333
4334struct kmem_cache *
4335__kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
4336 slab_flags_t flags, void (*ctor)(void *))
4337{
4338 struct kmem_cache *s, *c;
4339
4340 s = find_mergeable(size, align, flags, name, ctor);
4341 if (s) {
4342 s->refcount++;
4343
4344 /*
4345 * Adjust the object sizes so that we clear
4346 * the complete object on kzalloc.
4347 */
4348 s->object_size = max(s->object_size, size);
4349 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
4350
4351 for_each_memcg_cache(c, s) {
4352 c->object_size = s->object_size;
4353 c->inuse = max(c->inuse, ALIGN(size, sizeof(void *)));
4354 }
4355
4356 if (sysfs_slab_alias(s, name)) {
4357 s->refcount--;
4358 s = NULL;
4359 }
4360 }
4361
4362 return s;
4363}
4364
4365int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
4366{
4367 int err;
4368
4369 err = kmem_cache_open(s, flags);
4370 if (err)
4371 return err;
4372
4373 /* Mutex is not taken during early boot */
4374 if (slab_state <= UP)
4375 return 0;
4376
4377 memcg_propagate_slab_attrs(s);
4378 err = sysfs_slab_add(s);
4379 if (err)
4380 __kmem_cache_release(s);
4381
4382 return err;
4383}
4384
4385void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
4386{
4387 struct kmem_cache *s;
4388 void *ret;
4389
4390 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
4391 return kmalloc_large(size, gfpflags);
4392
4393 s = kmalloc_slab(size, gfpflags);
4394
4395 if (unlikely(ZERO_OR_NULL_PTR(s)))
4396 return s;
4397
4398 ret = slab_alloc(s, gfpflags, caller);
4399
4400 /* Honor the call site pointer we received. */
4401 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4402
4403 return ret;
4404}
4405
4406#ifdef CONFIG_NUMA
4407void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4408 int node, unsigned long caller)
4409{
4410 struct kmem_cache *s;
4411 void *ret;
4412
4413 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4414 ret = kmalloc_large_node(size, gfpflags, node);
4415
4416 trace_kmalloc_node(caller, ret,
4417 size, PAGE_SIZE << get_order(size),
4418 gfpflags, node);
4419
4420 return ret;
4421 }
4422
4423 s = kmalloc_slab(size, gfpflags);
4424
4425 if (unlikely(ZERO_OR_NULL_PTR(s)))
4426 return s;
4427
4428 ret = slab_alloc_node(s, gfpflags, node, caller);
4429
4430 /* Honor the call site pointer we received. */
4431 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4432
4433 return ret;
4434}
4435#endif
4436
4437#ifdef CONFIG_SYSFS
4438static int count_inuse(struct page *page)
4439{
4440 return page->inuse;
4441}
4442
4443static int count_total(struct page *page)
4444{
4445 return page->objects;
4446}
4447#endif
4448
4449#ifdef CONFIG_SLUB_DEBUG
4450static int validate_slab(struct kmem_cache *s, struct page *page,
4451 unsigned long *map)
4452{
4453 void *p;
4454 void *addr = page_address(page);
4455
4456 if (!check_slab(s, page) ||
4457 !on_freelist(s, page, NULL))
4458 return 0;
4459
4460 /* Now we know that a valid freelist exists */
4461 bitmap_zero(map, page->objects);
4462
4463 get_map(s, page, map);
4464 for_each_object(p, s, addr, page->objects) {
4465 if (test_bit(slab_index(p, s, addr), map))
4466 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4467 return 0;
4468 }
4469
4470 for_each_object(p, s, addr, page->objects)
4471 if (!test_bit(slab_index(p, s, addr), map))
4472 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4473 return 0;
4474 return 1;
4475}
4476
4477static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4478 unsigned long *map)
4479{
4480 slab_lock(page);
4481 validate_slab(s, page, map);
4482 slab_unlock(page);
4483}
4484
4485static int validate_slab_node(struct kmem_cache *s,
4486 struct kmem_cache_node *n, unsigned long *map)
4487{
4488 unsigned long count = 0;
4489 struct page *page;
4490 unsigned long flags;
4491
4492 spin_lock_irqsave(&n->list_lock, flags);
4493
David Brazdil0f672f62019-12-10 10:32:29 +00004494 list_for_each_entry(page, &n->partial, slab_list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004495 validate_slab_slab(s, page, map);
4496 count++;
4497 }
4498 if (count != n->nr_partial)
4499 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
4500 s->name, count, n->nr_partial);
4501
4502 if (!(s->flags & SLAB_STORE_USER))
4503 goto out;
4504
David Brazdil0f672f62019-12-10 10:32:29 +00004505 list_for_each_entry(page, &n->full, slab_list) {
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004506 validate_slab_slab(s, page, map);
4507 count++;
4508 }
4509 if (count != atomic_long_read(&n->nr_slabs))
4510 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
4511 s->name, count, atomic_long_read(&n->nr_slabs));
4512
4513out:
4514 spin_unlock_irqrestore(&n->list_lock, flags);
4515 return count;
4516}
4517
4518static long validate_slab_cache(struct kmem_cache *s)
4519{
4520 int node;
4521 unsigned long count = 0;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004522 struct kmem_cache_node *n;
David Brazdil0f672f62019-12-10 10:32:29 +00004523 unsigned long *map = bitmap_alloc(oo_objects(s->max), GFP_KERNEL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004524
4525 if (!map)
4526 return -ENOMEM;
4527
4528 flush_all(s);
4529 for_each_kmem_cache_node(s, node, n)
4530 count += validate_slab_node(s, n, map);
David Brazdil0f672f62019-12-10 10:32:29 +00004531 bitmap_free(map);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004532 return count;
4533}
4534/*
4535 * Generate lists of code addresses where slabcache objects are allocated
4536 * and freed.
4537 */
4538
4539struct location {
4540 unsigned long count;
4541 unsigned long addr;
4542 long long sum_time;
4543 long min_time;
4544 long max_time;
4545 long min_pid;
4546 long max_pid;
4547 DECLARE_BITMAP(cpus, NR_CPUS);
4548 nodemask_t nodes;
4549};
4550
4551struct loc_track {
4552 unsigned long max;
4553 unsigned long count;
4554 struct location *loc;
4555};
4556
4557static void free_loc_track(struct loc_track *t)
4558{
4559 if (t->max)
4560 free_pages((unsigned long)t->loc,
4561 get_order(sizeof(struct location) * t->max));
4562}
4563
4564static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4565{
4566 struct location *l;
4567 int order;
4568
4569 order = get_order(sizeof(struct location) * max);
4570
4571 l = (void *)__get_free_pages(flags, order);
4572 if (!l)
4573 return 0;
4574
4575 if (t->count) {
4576 memcpy(l, t->loc, sizeof(struct location) * t->count);
4577 free_loc_track(t);
4578 }
4579 t->max = max;
4580 t->loc = l;
4581 return 1;
4582}
4583
4584static int add_location(struct loc_track *t, struct kmem_cache *s,
4585 const struct track *track)
4586{
4587 long start, end, pos;
4588 struct location *l;
4589 unsigned long caddr;
4590 unsigned long age = jiffies - track->when;
4591
4592 start = -1;
4593 end = t->count;
4594
4595 for ( ; ; ) {
4596 pos = start + (end - start + 1) / 2;
4597
4598 /*
4599 * There is nothing at "end". If we end up there
4600 * we need to add something to before end.
4601 */
4602 if (pos == end)
4603 break;
4604
4605 caddr = t->loc[pos].addr;
4606 if (track->addr == caddr) {
4607
4608 l = &t->loc[pos];
4609 l->count++;
4610 if (track->when) {
4611 l->sum_time += age;
4612 if (age < l->min_time)
4613 l->min_time = age;
4614 if (age > l->max_time)
4615 l->max_time = age;
4616
4617 if (track->pid < l->min_pid)
4618 l->min_pid = track->pid;
4619 if (track->pid > l->max_pid)
4620 l->max_pid = track->pid;
4621
4622 cpumask_set_cpu(track->cpu,
4623 to_cpumask(l->cpus));
4624 }
4625 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4626 return 1;
4627 }
4628
4629 if (track->addr < caddr)
4630 end = pos;
4631 else
4632 start = pos;
4633 }
4634
4635 /*
4636 * Not found. Insert new tracking element.
4637 */
4638 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4639 return 0;
4640
4641 l = t->loc + pos;
4642 if (pos < t->count)
4643 memmove(l + 1, l,
4644 (t->count - pos) * sizeof(struct location));
4645 t->count++;
4646 l->count = 1;
4647 l->addr = track->addr;
4648 l->sum_time = age;
4649 l->min_time = age;
4650 l->max_time = age;
4651 l->min_pid = track->pid;
4652 l->max_pid = track->pid;
4653 cpumask_clear(to_cpumask(l->cpus));
4654 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4655 nodes_clear(l->nodes);
4656 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4657 return 1;
4658}
4659
4660static void process_slab(struct loc_track *t, struct kmem_cache *s,
4661 struct page *page, enum track_item alloc,
4662 unsigned long *map)
4663{
4664 void *addr = page_address(page);
4665 void *p;
4666
4667 bitmap_zero(map, page->objects);
4668 get_map(s, page, map);
4669
4670 for_each_object(p, s, addr, page->objects)
4671 if (!test_bit(slab_index(p, s, addr), map))
4672 add_location(t, s, get_track(s, p, alloc));
4673}
4674
4675static int list_locations(struct kmem_cache *s, char *buf,
4676 enum track_item alloc)
4677{
4678 int len = 0;
4679 unsigned long i;
4680 struct loc_track t = { 0, 0, NULL };
4681 int node;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004682 struct kmem_cache_node *n;
David Brazdil0f672f62019-12-10 10:32:29 +00004683 unsigned long *map = bitmap_alloc(oo_objects(s->max), GFP_KERNEL);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004684
4685 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4686 GFP_KERNEL)) {
David Brazdil0f672f62019-12-10 10:32:29 +00004687 bitmap_free(map);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004688 return sprintf(buf, "Out of memory\n");
4689 }
4690 /* Push back cpu slabs */
4691 flush_all(s);
4692
4693 for_each_kmem_cache_node(s, node, n) {
4694 unsigned long flags;
4695 struct page *page;
4696
4697 if (!atomic_long_read(&n->nr_slabs))
4698 continue;
4699
4700 spin_lock_irqsave(&n->list_lock, flags);
David Brazdil0f672f62019-12-10 10:32:29 +00004701 list_for_each_entry(page, &n->partial, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004702 process_slab(&t, s, page, alloc, map);
David Brazdil0f672f62019-12-10 10:32:29 +00004703 list_for_each_entry(page, &n->full, slab_list)
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004704 process_slab(&t, s, page, alloc, map);
4705 spin_unlock_irqrestore(&n->list_lock, flags);
4706 }
4707
4708 for (i = 0; i < t.count; i++) {
4709 struct location *l = &t.loc[i];
4710
4711 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4712 break;
4713 len += sprintf(buf + len, "%7ld ", l->count);
4714
4715 if (l->addr)
4716 len += sprintf(buf + len, "%pS", (void *)l->addr);
4717 else
4718 len += sprintf(buf + len, "<not-available>");
4719
4720 if (l->sum_time != l->min_time) {
4721 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4722 l->min_time,
4723 (long)div_u64(l->sum_time, l->count),
4724 l->max_time);
4725 } else
4726 len += sprintf(buf + len, " age=%ld",
4727 l->min_time);
4728
4729 if (l->min_pid != l->max_pid)
4730 len += sprintf(buf + len, " pid=%ld-%ld",
4731 l->min_pid, l->max_pid);
4732 else
4733 len += sprintf(buf + len, " pid=%ld",
4734 l->min_pid);
4735
4736 if (num_online_cpus() > 1 &&
4737 !cpumask_empty(to_cpumask(l->cpus)) &&
4738 len < PAGE_SIZE - 60)
4739 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4740 " cpus=%*pbl",
4741 cpumask_pr_args(to_cpumask(l->cpus)));
4742
4743 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4744 len < PAGE_SIZE - 60)
4745 len += scnprintf(buf + len, PAGE_SIZE - len - 50,
4746 " nodes=%*pbl",
4747 nodemask_pr_args(&l->nodes));
4748
4749 len += sprintf(buf + len, "\n");
4750 }
4751
4752 free_loc_track(&t);
David Brazdil0f672f62019-12-10 10:32:29 +00004753 bitmap_free(map);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004754 if (!t.count)
4755 len += sprintf(buf, "No data\n");
4756 return len;
4757}
David Brazdil0f672f62019-12-10 10:32:29 +00004758#endif /* CONFIG_SLUB_DEBUG */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004759
4760#ifdef SLUB_RESILIENCY_TEST
4761static void __init resiliency_test(void)
4762{
4763 u8 *p;
David Brazdil0f672f62019-12-10 10:32:29 +00004764 int type = KMALLOC_NORMAL;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004765
4766 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || KMALLOC_SHIFT_HIGH < 10);
4767
4768 pr_err("SLUB resiliency testing\n");
4769 pr_err("-----------------------\n");
4770 pr_err("A. Corruption after allocation\n");
4771
4772 p = kzalloc(16, GFP_KERNEL);
4773 p[16] = 0x12;
4774 pr_err("\n1. kmalloc-16: Clobber Redzone/next pointer 0x12->0x%p\n\n",
4775 p + 16);
4776
David Brazdil0f672f62019-12-10 10:32:29 +00004777 validate_slab_cache(kmalloc_caches[type][4]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004778
4779 /* Hmmm... The next two are dangerous */
4780 p = kzalloc(32, GFP_KERNEL);
4781 p[32 + sizeof(void *)] = 0x34;
4782 pr_err("\n2. kmalloc-32: Clobber next pointer/next slab 0x34 -> -0x%p\n",
4783 p);
4784 pr_err("If allocated object is overwritten then not detectable\n\n");
4785
David Brazdil0f672f62019-12-10 10:32:29 +00004786 validate_slab_cache(kmalloc_caches[type][5]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004787 p = kzalloc(64, GFP_KERNEL);
4788 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4789 *p = 0x56;
4790 pr_err("\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4791 p);
4792 pr_err("If allocated object is overwritten then not detectable\n\n");
David Brazdil0f672f62019-12-10 10:32:29 +00004793 validate_slab_cache(kmalloc_caches[type][6]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004794
4795 pr_err("\nB. Corruption after free\n");
4796 p = kzalloc(128, GFP_KERNEL);
4797 kfree(p);
4798 *p = 0x78;
4799 pr_err("1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
David Brazdil0f672f62019-12-10 10:32:29 +00004800 validate_slab_cache(kmalloc_caches[type][7]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004801
4802 p = kzalloc(256, GFP_KERNEL);
4803 kfree(p);
4804 p[50] = 0x9a;
4805 pr_err("\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
David Brazdil0f672f62019-12-10 10:32:29 +00004806 validate_slab_cache(kmalloc_caches[type][8]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004807
4808 p = kzalloc(512, GFP_KERNEL);
4809 kfree(p);
4810 p[512] = 0xab;
4811 pr_err("\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
David Brazdil0f672f62019-12-10 10:32:29 +00004812 validate_slab_cache(kmalloc_caches[type][9]);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004813}
4814#else
4815#ifdef CONFIG_SYSFS
4816static void resiliency_test(void) {};
4817#endif
David Brazdil0f672f62019-12-10 10:32:29 +00004818#endif /* SLUB_RESILIENCY_TEST */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004819
4820#ifdef CONFIG_SYSFS
4821enum slab_stat_type {
4822 SL_ALL, /* All slabs */
4823 SL_PARTIAL, /* Only partially allocated slabs */
4824 SL_CPU, /* Only slabs used for cpu caches */
4825 SL_OBJECTS, /* Determine allocated objects not slabs */
4826 SL_TOTAL /* Determine object capacity not slabs */
4827};
4828
4829#define SO_ALL (1 << SL_ALL)
4830#define SO_PARTIAL (1 << SL_PARTIAL)
4831#define SO_CPU (1 << SL_CPU)
4832#define SO_OBJECTS (1 << SL_OBJECTS)
4833#define SO_TOTAL (1 << SL_TOTAL)
4834
4835#ifdef CONFIG_MEMCG
4836static bool memcg_sysfs_enabled = IS_ENABLED(CONFIG_SLUB_MEMCG_SYSFS_ON);
4837
4838static int __init setup_slub_memcg_sysfs(char *str)
4839{
4840 int v;
4841
4842 if (get_option(&str, &v) > 0)
4843 memcg_sysfs_enabled = v;
4844
4845 return 1;
4846}
4847
4848__setup("slub_memcg_sysfs=", setup_slub_memcg_sysfs);
4849#endif
4850
4851static ssize_t show_slab_objects(struct kmem_cache *s,
4852 char *buf, unsigned long flags)
4853{
4854 unsigned long total = 0;
4855 int node;
4856 int x;
4857 unsigned long *nodes;
4858
4859 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
4860 if (!nodes)
4861 return -ENOMEM;
4862
4863 if (flags & SO_CPU) {
4864 int cpu;
4865
4866 for_each_possible_cpu(cpu) {
4867 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
4868 cpu);
4869 int node;
4870 struct page *page;
4871
4872 page = READ_ONCE(c->page);
4873 if (!page)
4874 continue;
4875
4876 node = page_to_nid(page);
4877 if (flags & SO_TOTAL)
4878 x = page->objects;
4879 else if (flags & SO_OBJECTS)
4880 x = page->inuse;
4881 else
4882 x = 1;
4883
4884 total += x;
4885 nodes[node] += x;
4886
4887 page = slub_percpu_partial_read_once(c);
4888 if (page) {
4889 node = page_to_nid(page);
4890 if (flags & SO_TOTAL)
4891 WARN_ON_ONCE(1);
4892 else if (flags & SO_OBJECTS)
4893 WARN_ON_ONCE(1);
4894 else
4895 x = page->pages;
4896 total += x;
4897 nodes[node] += x;
4898 }
4899 }
4900 }
4901
David Brazdil0f672f62019-12-10 10:32:29 +00004902 /*
4903 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
4904 * already held which will conflict with an existing lock order:
4905 *
4906 * mem_hotplug_lock->slab_mutex->kernfs_mutex
4907 *
4908 * We don't really need mem_hotplug_lock (to hold off
4909 * slab_mem_going_offline_callback) here because slab's memory hot
4910 * unplug code doesn't destroy the kmem_cache->node[] data.
4911 */
4912
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004913#ifdef CONFIG_SLUB_DEBUG
4914 if (flags & SO_ALL) {
4915 struct kmem_cache_node *n;
4916
4917 for_each_kmem_cache_node(s, node, n) {
4918
4919 if (flags & SO_TOTAL)
4920 x = atomic_long_read(&n->total_objects);
4921 else if (flags & SO_OBJECTS)
4922 x = atomic_long_read(&n->total_objects) -
4923 count_partial(n, count_free);
4924 else
4925 x = atomic_long_read(&n->nr_slabs);
4926 total += x;
4927 nodes[node] += x;
4928 }
4929
4930 } else
4931#endif
4932 if (flags & SO_PARTIAL) {
4933 struct kmem_cache_node *n;
4934
4935 for_each_kmem_cache_node(s, node, n) {
4936 if (flags & SO_TOTAL)
4937 x = count_partial(n, count_total);
4938 else if (flags & SO_OBJECTS)
4939 x = count_partial(n, count_inuse);
4940 else
4941 x = n->nr_partial;
4942 total += x;
4943 nodes[node] += x;
4944 }
4945 }
4946 x = sprintf(buf, "%lu", total);
4947#ifdef CONFIG_NUMA
4948 for (node = 0; node < nr_node_ids; node++)
4949 if (nodes[node])
4950 x += sprintf(buf + x, " N%d=%lu",
4951 node, nodes[node]);
4952#endif
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00004953 kfree(nodes);
4954 return x + sprintf(buf + x, "\n");
4955}
4956
4957#ifdef CONFIG_SLUB_DEBUG
4958static int any_slab_objects(struct kmem_cache *s)
4959{
4960 int node;
4961 struct kmem_cache_node *n;
4962
4963 for_each_kmem_cache_node(s, node, n)
4964 if (atomic_long_read(&n->total_objects))
4965 return 1;
4966
4967 return 0;
4968}
4969#endif
4970
4971#define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4972#define to_slab(n) container_of(n, struct kmem_cache, kobj)
4973
4974struct slab_attribute {
4975 struct attribute attr;
4976 ssize_t (*show)(struct kmem_cache *s, char *buf);
4977 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4978};
4979
4980#define SLAB_ATTR_RO(_name) \
4981 static struct slab_attribute _name##_attr = \
4982 __ATTR(_name, 0400, _name##_show, NULL)
4983
4984#define SLAB_ATTR(_name) \
4985 static struct slab_attribute _name##_attr = \
4986 __ATTR(_name, 0600, _name##_show, _name##_store)
4987
4988static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4989{
4990 return sprintf(buf, "%u\n", s->size);
4991}
4992SLAB_ATTR_RO(slab_size);
4993
4994static ssize_t align_show(struct kmem_cache *s, char *buf)
4995{
4996 return sprintf(buf, "%u\n", s->align);
4997}
4998SLAB_ATTR_RO(align);
4999
5000static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5001{
5002 return sprintf(buf, "%u\n", s->object_size);
5003}
5004SLAB_ATTR_RO(object_size);
5005
5006static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5007{
5008 return sprintf(buf, "%u\n", oo_objects(s->oo));
5009}
5010SLAB_ATTR_RO(objs_per_slab);
5011
5012static ssize_t order_store(struct kmem_cache *s,
5013 const char *buf, size_t length)
5014{
5015 unsigned int order;
5016 int err;
5017
5018 err = kstrtouint(buf, 10, &order);
5019 if (err)
5020 return err;
5021
5022 if (order > slub_max_order || order < slub_min_order)
5023 return -EINVAL;
5024
5025 calculate_sizes(s, order);
5026 return length;
5027}
5028
5029static ssize_t order_show(struct kmem_cache *s, char *buf)
5030{
5031 return sprintf(buf, "%u\n", oo_order(s->oo));
5032}
5033SLAB_ATTR(order);
5034
5035static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5036{
5037 return sprintf(buf, "%lu\n", s->min_partial);
5038}
5039
5040static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5041 size_t length)
5042{
5043 unsigned long min;
5044 int err;
5045
5046 err = kstrtoul(buf, 10, &min);
5047 if (err)
5048 return err;
5049
5050 set_min_partial(s, min);
5051 return length;
5052}
5053SLAB_ATTR(min_partial);
5054
5055static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5056{
5057 return sprintf(buf, "%u\n", slub_cpu_partial(s));
5058}
5059
5060static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5061 size_t length)
5062{
5063 unsigned int objects;
5064 int err;
5065
5066 err = kstrtouint(buf, 10, &objects);
5067 if (err)
5068 return err;
5069 if (objects && !kmem_cache_has_cpu_partial(s))
5070 return -EINVAL;
5071
5072 slub_set_cpu_partial(s, objects);
5073 flush_all(s);
5074 return length;
5075}
5076SLAB_ATTR(cpu_partial);
5077
5078static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5079{
5080 if (!s->ctor)
5081 return 0;
5082 return sprintf(buf, "%pS\n", s->ctor);
5083}
5084SLAB_ATTR_RO(ctor);
5085
5086static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5087{
5088 return sprintf(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5089}
5090SLAB_ATTR_RO(aliases);
5091
5092static ssize_t partial_show(struct kmem_cache *s, char *buf)
5093{
5094 return show_slab_objects(s, buf, SO_PARTIAL);
5095}
5096SLAB_ATTR_RO(partial);
5097
5098static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5099{
5100 return show_slab_objects(s, buf, SO_CPU);
5101}
5102SLAB_ATTR_RO(cpu_slabs);
5103
5104static ssize_t objects_show(struct kmem_cache *s, char *buf)
5105{
5106 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5107}
5108SLAB_ATTR_RO(objects);
5109
5110static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5111{
5112 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5113}
5114SLAB_ATTR_RO(objects_partial);
5115
5116static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5117{
5118 int objects = 0;
5119 int pages = 0;
5120 int cpu;
5121 int len;
5122
5123 for_each_online_cpu(cpu) {
5124 struct page *page;
5125
5126 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5127
5128 if (page) {
5129 pages += page->pages;
5130 objects += page->pobjects;
5131 }
5132 }
5133
5134 len = sprintf(buf, "%d(%d)", objects, pages);
5135
5136#ifdef CONFIG_SMP
5137 for_each_online_cpu(cpu) {
5138 struct page *page;
5139
5140 page = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5141
5142 if (page && len < PAGE_SIZE - 20)
5143 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
5144 page->pobjects, page->pages);
5145 }
5146#endif
5147 return len + sprintf(buf + len, "\n");
5148}
5149SLAB_ATTR_RO(slabs_cpu_partial);
5150
5151static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5152{
5153 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5154}
5155
5156static ssize_t reclaim_account_store(struct kmem_cache *s,
5157 const char *buf, size_t length)
5158{
5159 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
5160 if (buf[0] == '1')
5161 s->flags |= SLAB_RECLAIM_ACCOUNT;
5162 return length;
5163}
5164SLAB_ATTR(reclaim_account);
5165
5166static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5167{
5168 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5169}
5170SLAB_ATTR_RO(hwcache_align);
5171
5172#ifdef CONFIG_ZONE_DMA
5173static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5174{
5175 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5176}
5177SLAB_ATTR_RO(cache_dma);
5178#endif
5179
5180static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5181{
5182 return sprintf(buf, "%u\n", s->usersize);
5183}
5184SLAB_ATTR_RO(usersize);
5185
5186static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5187{
5188 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5189}
5190SLAB_ATTR_RO(destroy_by_rcu);
5191
5192#ifdef CONFIG_SLUB_DEBUG
5193static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5194{
5195 return show_slab_objects(s, buf, SO_ALL);
5196}
5197SLAB_ATTR_RO(slabs);
5198
5199static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5200{
5201 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5202}
5203SLAB_ATTR_RO(total_objects);
5204
5205static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5206{
5207 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5208}
5209
5210static ssize_t sanity_checks_store(struct kmem_cache *s,
5211 const char *buf, size_t length)
5212{
5213 s->flags &= ~SLAB_CONSISTENCY_CHECKS;
5214 if (buf[0] == '1') {
5215 s->flags &= ~__CMPXCHG_DOUBLE;
5216 s->flags |= SLAB_CONSISTENCY_CHECKS;
5217 }
5218 return length;
5219}
5220SLAB_ATTR(sanity_checks);
5221
5222static ssize_t trace_show(struct kmem_cache *s, char *buf)
5223{
5224 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5225}
5226
5227static ssize_t trace_store(struct kmem_cache *s, const char *buf,
5228 size_t length)
5229{
5230 /*
5231 * Tracing a merged cache is going to give confusing results
5232 * as well as cause other issues like converting a mergeable
5233 * cache into an umergeable one.
5234 */
5235 if (s->refcount > 1)
5236 return -EINVAL;
5237
5238 s->flags &= ~SLAB_TRACE;
5239 if (buf[0] == '1') {
5240 s->flags &= ~__CMPXCHG_DOUBLE;
5241 s->flags |= SLAB_TRACE;
5242 }
5243 return length;
5244}
5245SLAB_ATTR(trace);
5246
5247static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5248{
5249 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5250}
5251
5252static ssize_t red_zone_store(struct kmem_cache *s,
5253 const char *buf, size_t length)
5254{
5255 if (any_slab_objects(s))
5256 return -EBUSY;
5257
5258 s->flags &= ~SLAB_RED_ZONE;
5259 if (buf[0] == '1') {
5260 s->flags |= SLAB_RED_ZONE;
5261 }
5262 calculate_sizes(s, -1);
5263 return length;
5264}
5265SLAB_ATTR(red_zone);
5266
5267static ssize_t poison_show(struct kmem_cache *s, char *buf)
5268{
5269 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
5270}
5271
5272static ssize_t poison_store(struct kmem_cache *s,
5273 const char *buf, size_t length)
5274{
5275 if (any_slab_objects(s))
5276 return -EBUSY;
5277
5278 s->flags &= ~SLAB_POISON;
5279 if (buf[0] == '1') {
5280 s->flags |= SLAB_POISON;
5281 }
5282 calculate_sizes(s, -1);
5283 return length;
5284}
5285SLAB_ATTR(poison);
5286
5287static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5288{
5289 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5290}
5291
5292static ssize_t store_user_store(struct kmem_cache *s,
5293 const char *buf, size_t length)
5294{
5295 if (any_slab_objects(s))
5296 return -EBUSY;
5297
5298 s->flags &= ~SLAB_STORE_USER;
5299 if (buf[0] == '1') {
5300 s->flags &= ~__CMPXCHG_DOUBLE;
5301 s->flags |= SLAB_STORE_USER;
5302 }
5303 calculate_sizes(s, -1);
5304 return length;
5305}
5306SLAB_ATTR(store_user);
5307
5308static ssize_t validate_show(struct kmem_cache *s, char *buf)
5309{
5310 return 0;
5311}
5312
5313static ssize_t validate_store(struct kmem_cache *s,
5314 const char *buf, size_t length)
5315{
5316 int ret = -EINVAL;
5317
5318 if (buf[0] == '1') {
5319 ret = validate_slab_cache(s);
5320 if (ret >= 0)
5321 ret = length;
5322 }
5323 return ret;
5324}
5325SLAB_ATTR(validate);
5326
5327static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
5328{
5329 if (!(s->flags & SLAB_STORE_USER))
5330 return -ENOSYS;
5331 return list_locations(s, buf, TRACK_ALLOC);
5332}
5333SLAB_ATTR_RO(alloc_calls);
5334
5335static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
5336{
5337 if (!(s->flags & SLAB_STORE_USER))
5338 return -ENOSYS;
5339 return list_locations(s, buf, TRACK_FREE);
5340}
5341SLAB_ATTR_RO(free_calls);
5342#endif /* CONFIG_SLUB_DEBUG */
5343
5344#ifdef CONFIG_FAILSLAB
5345static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5346{
5347 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5348}
5349
5350static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5351 size_t length)
5352{
5353 if (s->refcount > 1)
5354 return -EINVAL;
5355
5356 s->flags &= ~SLAB_FAILSLAB;
5357 if (buf[0] == '1')
5358 s->flags |= SLAB_FAILSLAB;
5359 return length;
5360}
5361SLAB_ATTR(failslab);
5362#endif
5363
5364static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5365{
5366 return 0;
5367}
5368
5369static ssize_t shrink_store(struct kmem_cache *s,
5370 const char *buf, size_t length)
5371{
5372 if (buf[0] == '1')
David Brazdil0f672f62019-12-10 10:32:29 +00005373 kmem_cache_shrink_all(s);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005374 else
5375 return -EINVAL;
5376 return length;
5377}
5378SLAB_ATTR(shrink);
5379
5380#ifdef CONFIG_NUMA
5381static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5382{
5383 return sprintf(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5384}
5385
5386static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5387 const char *buf, size_t length)
5388{
5389 unsigned int ratio;
5390 int err;
5391
5392 err = kstrtouint(buf, 10, &ratio);
5393 if (err)
5394 return err;
5395 if (ratio > 100)
5396 return -ERANGE;
5397
5398 s->remote_node_defrag_ratio = ratio * 10;
5399
5400 return length;
5401}
5402SLAB_ATTR(remote_node_defrag_ratio);
5403#endif
5404
5405#ifdef CONFIG_SLUB_STATS
5406static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5407{
5408 unsigned long sum = 0;
5409 int cpu;
5410 int len;
5411 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5412
5413 if (!data)
5414 return -ENOMEM;
5415
5416 for_each_online_cpu(cpu) {
5417 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5418
5419 data[cpu] = x;
5420 sum += x;
5421 }
5422
5423 len = sprintf(buf, "%lu", sum);
5424
5425#ifdef CONFIG_SMP
5426 for_each_online_cpu(cpu) {
5427 if (data[cpu] && len < PAGE_SIZE - 20)
5428 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5429 }
5430#endif
5431 kfree(data);
5432 return len + sprintf(buf + len, "\n");
5433}
5434
5435static void clear_stat(struct kmem_cache *s, enum stat_item si)
5436{
5437 int cpu;
5438
5439 for_each_online_cpu(cpu)
5440 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5441}
5442
5443#define STAT_ATTR(si, text) \
5444static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5445{ \
5446 return show_stat(s, buf, si); \
5447} \
5448static ssize_t text##_store(struct kmem_cache *s, \
5449 const char *buf, size_t length) \
5450{ \
5451 if (buf[0] != '0') \
5452 return -EINVAL; \
5453 clear_stat(s, si); \
5454 return length; \
5455} \
5456SLAB_ATTR(text); \
5457
5458STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5459STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5460STAT_ATTR(FREE_FASTPATH, free_fastpath);
5461STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5462STAT_ATTR(FREE_FROZEN, free_frozen);
5463STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5464STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5465STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5466STAT_ATTR(ALLOC_SLAB, alloc_slab);
5467STAT_ATTR(ALLOC_REFILL, alloc_refill);
5468STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5469STAT_ATTR(FREE_SLAB, free_slab);
5470STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5471STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5472STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5473STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5474STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5475STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5476STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5477STAT_ATTR(ORDER_FALLBACK, order_fallback);
5478STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5479STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5480STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5481STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5482STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5483STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
David Brazdil0f672f62019-12-10 10:32:29 +00005484#endif /* CONFIG_SLUB_STATS */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005485
5486static struct attribute *slab_attrs[] = {
5487 &slab_size_attr.attr,
5488 &object_size_attr.attr,
5489 &objs_per_slab_attr.attr,
5490 &order_attr.attr,
5491 &min_partial_attr.attr,
5492 &cpu_partial_attr.attr,
5493 &objects_attr.attr,
5494 &objects_partial_attr.attr,
5495 &partial_attr.attr,
5496 &cpu_slabs_attr.attr,
5497 &ctor_attr.attr,
5498 &aliases_attr.attr,
5499 &align_attr.attr,
5500 &hwcache_align_attr.attr,
5501 &reclaim_account_attr.attr,
5502 &destroy_by_rcu_attr.attr,
5503 &shrink_attr.attr,
5504 &slabs_cpu_partial_attr.attr,
5505#ifdef CONFIG_SLUB_DEBUG
5506 &total_objects_attr.attr,
5507 &slabs_attr.attr,
5508 &sanity_checks_attr.attr,
5509 &trace_attr.attr,
5510 &red_zone_attr.attr,
5511 &poison_attr.attr,
5512 &store_user_attr.attr,
5513 &validate_attr.attr,
5514 &alloc_calls_attr.attr,
5515 &free_calls_attr.attr,
5516#endif
5517#ifdef CONFIG_ZONE_DMA
5518 &cache_dma_attr.attr,
5519#endif
5520#ifdef CONFIG_NUMA
5521 &remote_node_defrag_ratio_attr.attr,
5522#endif
5523#ifdef CONFIG_SLUB_STATS
5524 &alloc_fastpath_attr.attr,
5525 &alloc_slowpath_attr.attr,
5526 &free_fastpath_attr.attr,
5527 &free_slowpath_attr.attr,
5528 &free_frozen_attr.attr,
5529 &free_add_partial_attr.attr,
5530 &free_remove_partial_attr.attr,
5531 &alloc_from_partial_attr.attr,
5532 &alloc_slab_attr.attr,
5533 &alloc_refill_attr.attr,
5534 &alloc_node_mismatch_attr.attr,
5535 &free_slab_attr.attr,
5536 &cpuslab_flush_attr.attr,
5537 &deactivate_full_attr.attr,
5538 &deactivate_empty_attr.attr,
5539 &deactivate_to_head_attr.attr,
5540 &deactivate_to_tail_attr.attr,
5541 &deactivate_remote_frees_attr.attr,
5542 &deactivate_bypass_attr.attr,
5543 &order_fallback_attr.attr,
5544 &cmpxchg_double_fail_attr.attr,
5545 &cmpxchg_double_cpu_fail_attr.attr,
5546 &cpu_partial_alloc_attr.attr,
5547 &cpu_partial_free_attr.attr,
5548 &cpu_partial_node_attr.attr,
5549 &cpu_partial_drain_attr.attr,
5550#endif
5551#ifdef CONFIG_FAILSLAB
5552 &failslab_attr.attr,
5553#endif
5554 &usersize_attr.attr,
5555
5556 NULL
5557};
5558
5559static const struct attribute_group slab_attr_group = {
5560 .attrs = slab_attrs,
5561};
5562
5563static ssize_t slab_attr_show(struct kobject *kobj,
5564 struct attribute *attr,
5565 char *buf)
5566{
5567 struct slab_attribute *attribute;
5568 struct kmem_cache *s;
5569 int err;
5570
5571 attribute = to_slab_attr(attr);
5572 s = to_slab(kobj);
5573
5574 if (!attribute->show)
5575 return -EIO;
5576
5577 err = attribute->show(s, buf);
5578
5579 return err;
5580}
5581
5582static ssize_t slab_attr_store(struct kobject *kobj,
5583 struct attribute *attr,
5584 const char *buf, size_t len)
5585{
5586 struct slab_attribute *attribute;
5587 struct kmem_cache *s;
5588 int err;
5589
5590 attribute = to_slab_attr(attr);
5591 s = to_slab(kobj);
5592
5593 if (!attribute->store)
5594 return -EIO;
5595
5596 err = attribute->store(s, buf, len);
5597#ifdef CONFIG_MEMCG
5598 if (slab_state >= FULL && err >= 0 && is_root_cache(s)) {
5599 struct kmem_cache *c;
5600
5601 mutex_lock(&slab_mutex);
5602 if (s->max_attr_size < len)
5603 s->max_attr_size = len;
5604
5605 /*
5606 * This is a best effort propagation, so this function's return
5607 * value will be determined by the parent cache only. This is
5608 * basically because not all attributes will have a well
5609 * defined semantics for rollbacks - most of the actions will
5610 * have permanent effects.
5611 *
5612 * Returning the error value of any of the children that fail
5613 * is not 100 % defined, in the sense that users seeing the
5614 * error code won't be able to know anything about the state of
5615 * the cache.
5616 *
5617 * Only returning the error code for the parent cache at least
5618 * has well defined semantics. The cache being written to
5619 * directly either failed or succeeded, in which case we loop
5620 * through the descendants with best-effort propagation.
5621 */
5622 for_each_memcg_cache(c, s)
5623 attribute->store(c, buf, len);
5624 mutex_unlock(&slab_mutex);
5625 }
5626#endif
5627 return err;
5628}
5629
5630static void memcg_propagate_slab_attrs(struct kmem_cache *s)
5631{
5632#ifdef CONFIG_MEMCG
5633 int i;
5634 char *buffer = NULL;
5635 struct kmem_cache *root_cache;
5636
5637 if (is_root_cache(s))
5638 return;
5639
5640 root_cache = s->memcg_params.root_cache;
5641
5642 /*
5643 * This mean this cache had no attribute written. Therefore, no point
5644 * in copying default values around
5645 */
5646 if (!root_cache->max_attr_size)
5647 return;
5648
5649 for (i = 0; i < ARRAY_SIZE(slab_attrs); i++) {
5650 char mbuf[64];
5651 char *buf;
5652 struct slab_attribute *attr = to_slab_attr(slab_attrs[i]);
5653 ssize_t len;
5654
5655 if (!attr || !attr->store || !attr->show)
5656 continue;
5657
5658 /*
5659 * It is really bad that we have to allocate here, so we will
5660 * do it only as a fallback. If we actually allocate, though,
5661 * we can just use the allocated buffer until the end.
5662 *
5663 * Most of the slub attributes will tend to be very small in
5664 * size, but sysfs allows buffers up to a page, so they can
5665 * theoretically happen.
5666 */
5667 if (buffer)
5668 buf = buffer;
Olivier Deprez0e641232021-09-23 10:07:05 +02005669 else if (root_cache->max_attr_size < ARRAY_SIZE(mbuf) &&
5670 !IS_ENABLED(CONFIG_SLUB_STATS))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005671 buf = mbuf;
5672 else {
5673 buffer = (char *) get_zeroed_page(GFP_KERNEL);
5674 if (WARN_ON(!buffer))
5675 continue;
5676 buf = buffer;
5677 }
5678
5679 len = attr->show(root_cache, buf);
5680 if (len > 0)
5681 attr->store(s, buf, len);
5682 }
5683
5684 if (buffer)
5685 free_page((unsigned long)buffer);
David Brazdil0f672f62019-12-10 10:32:29 +00005686#endif /* CONFIG_MEMCG */
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005687}
5688
5689static void kmem_cache_release(struct kobject *k)
5690{
5691 slab_kmem_cache_release(to_slab(k));
5692}
5693
5694static const struct sysfs_ops slab_sysfs_ops = {
5695 .show = slab_attr_show,
5696 .store = slab_attr_store,
5697};
5698
5699static struct kobj_type slab_ktype = {
5700 .sysfs_ops = &slab_sysfs_ops,
5701 .release = kmem_cache_release,
5702};
5703
5704static int uevent_filter(struct kset *kset, struct kobject *kobj)
5705{
5706 struct kobj_type *ktype = get_ktype(kobj);
5707
5708 if (ktype == &slab_ktype)
5709 return 1;
5710 return 0;
5711}
5712
5713static const struct kset_uevent_ops slab_uevent_ops = {
5714 .filter = uevent_filter,
5715};
5716
5717static struct kset *slab_kset;
5718
5719static inline struct kset *cache_kset(struct kmem_cache *s)
5720{
5721#ifdef CONFIG_MEMCG
5722 if (!is_root_cache(s))
5723 return s->memcg_params.root_cache->memcg_kset;
5724#endif
5725 return slab_kset;
5726}
5727
5728#define ID_STR_LENGTH 64
5729
5730/* Create a unique string id for a slab cache:
5731 *
5732 * Format :[flags-]size
5733 */
5734static char *create_unique_id(struct kmem_cache *s)
5735{
5736 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5737 char *p = name;
5738
5739 BUG_ON(!name);
5740
5741 *p++ = ':';
5742 /*
5743 * First flags affecting slabcache operations. We will only
5744 * get here for aliasable slabs so we do not need to support
5745 * too many flags. The flags here must cover all flags that
5746 * are matched during merging to guarantee that the id is
5747 * unique.
5748 */
5749 if (s->flags & SLAB_CACHE_DMA)
5750 *p++ = 'd';
David Brazdil0f672f62019-12-10 10:32:29 +00005751 if (s->flags & SLAB_CACHE_DMA32)
5752 *p++ = 'D';
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00005753 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5754 *p++ = 'a';
5755 if (s->flags & SLAB_CONSISTENCY_CHECKS)
5756 *p++ = 'F';
5757 if (s->flags & SLAB_ACCOUNT)
5758 *p++ = 'A';
5759 if (p != name + 1)
5760 *p++ = '-';
5761 p += sprintf(p, "%07u", s->size);
5762
5763 BUG_ON(p > name + ID_STR_LENGTH - 1);
5764 return name;
5765}
5766
5767static void sysfs_slab_remove_workfn(struct work_struct *work)
5768{
5769 struct kmem_cache *s =
5770 container_of(work, struct kmem_cache, kobj_remove_work);
5771
5772 if (!s->kobj.state_in_sysfs)
5773 /*
5774 * For a memcg cache, this may be called during
5775 * deactivation and again on shutdown. Remove only once.
5776 * A cache is never shut down before deactivation is
5777 * complete, so no need to worry about synchronization.
5778 */
5779 goto out;
5780
5781#ifdef CONFIG_MEMCG
5782 kset_unregister(s->memcg_kset);
5783#endif
5784 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5785out:
5786 kobject_put(&s->kobj);
5787}
5788
5789static int sysfs_slab_add(struct kmem_cache *s)
5790{
5791 int err;
5792 const char *name;
5793 struct kset *kset = cache_kset(s);
5794 int unmergeable = slab_unmergeable(s);
5795
5796 INIT_WORK(&s->kobj_remove_work, sysfs_slab_remove_workfn);
5797
5798 if (!kset) {
5799 kobject_init(&s->kobj, &slab_ktype);
5800 return 0;
5801 }
5802
5803 if (!unmergeable && disable_higher_order_debug &&
5804 (slub_debug & DEBUG_METADATA_FLAGS))
5805 unmergeable = 1;
5806
5807 if (unmergeable) {
5808 /*
5809 * Slabcache can never be merged so we can use the name proper.
5810 * This is typically the case for debug situations. In that
5811 * case we can catch duplicate names easily.
5812 */
5813 sysfs_remove_link(&slab_kset->kobj, s->name);
5814 name = s->name;
5815 } else {
5816 /*
5817 * Create a unique name for the slab as a target
5818 * for the symlinks.
5819 */
5820 name = create_unique_id(s);
5821 }
5822
5823 s->kobj.kset = kset;
5824 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
5825 if (err)
5826 goto out;
5827
5828 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5829 if (err)
5830 goto out_del_kobj;
5831
5832#ifdef CONFIG_MEMCG
5833 if (is_root_cache(s) && memcg_sysfs_enabled) {
5834 s->memcg_kset = kset_create_and_add("cgroup", NULL, &s->kobj);
5835 if (!s->memcg_kset) {
5836 err = -ENOMEM;
5837 goto out_del_kobj;
5838 }
5839 }
5840#endif
5841
5842 kobject_uevent(&s->kobj, KOBJ_ADD);
5843 if (!unmergeable) {
5844 /* Setup first alias */
5845 sysfs_slab_alias(s, s->name);
5846 }
5847out:
5848 if (!unmergeable)
5849 kfree(name);
5850 return err;
5851out_del_kobj:
5852 kobject_del(&s->kobj);
5853 goto out;
5854}
5855
5856static void sysfs_slab_remove(struct kmem_cache *s)
5857{
5858 if (slab_state < FULL)
5859 /*
5860 * Sysfs has not been setup yet so no need to remove the
5861 * cache from sysfs.
5862 */
5863 return;
5864
5865 kobject_get(&s->kobj);
5866 schedule_work(&s->kobj_remove_work);
5867}
5868
5869void sysfs_slab_unlink(struct kmem_cache *s)
5870{
5871 if (slab_state >= FULL)
5872 kobject_del(&s->kobj);
5873}
5874
5875void sysfs_slab_release(struct kmem_cache *s)
5876{
5877 if (slab_state >= FULL)
5878 kobject_put(&s->kobj);
5879}
5880
5881/*
5882 * Need to buffer aliases during bootup until sysfs becomes
5883 * available lest we lose that information.
5884 */
5885struct saved_alias {
5886 struct kmem_cache *s;
5887 const char *name;
5888 struct saved_alias *next;
5889};
5890
5891static struct saved_alias *alias_list;
5892
5893static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5894{
5895 struct saved_alias *al;
5896
5897 if (slab_state == FULL) {
5898 /*
5899 * If we have a leftover link then remove it.
5900 */
5901 sysfs_remove_link(&slab_kset->kobj, name);
5902 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5903 }
5904
5905 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5906 if (!al)
5907 return -ENOMEM;
5908
5909 al->s = s;
5910 al->name = name;
5911 al->next = alias_list;
5912 alias_list = al;
5913 return 0;
5914}
5915
5916static int __init slab_sysfs_init(void)
5917{
5918 struct kmem_cache *s;
5919 int err;
5920
5921 mutex_lock(&slab_mutex);
5922
5923 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5924 if (!slab_kset) {
5925 mutex_unlock(&slab_mutex);
5926 pr_err("Cannot register slab subsystem.\n");
5927 return -ENOSYS;
5928 }
5929
5930 slab_state = FULL;
5931
5932 list_for_each_entry(s, &slab_caches, list) {
5933 err = sysfs_slab_add(s);
5934 if (err)
5935 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
5936 s->name);
5937 }
5938
5939 while (alias_list) {
5940 struct saved_alias *al = alias_list;
5941
5942 alias_list = alias_list->next;
5943 err = sysfs_slab_alias(al->s, al->name);
5944 if (err)
5945 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
5946 al->name);
5947 kfree(al);
5948 }
5949
5950 mutex_unlock(&slab_mutex);
5951 resiliency_test();
5952 return 0;
5953}
5954
5955__initcall(slab_sysfs_init);
5956#endif /* CONFIG_SYSFS */
5957
5958/*
5959 * The /proc/slabinfo ABI
5960 */
5961#ifdef CONFIG_SLUB_DEBUG
5962void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
5963{
5964 unsigned long nr_slabs = 0;
5965 unsigned long nr_objs = 0;
5966 unsigned long nr_free = 0;
5967 int node;
5968 struct kmem_cache_node *n;
5969
5970 for_each_kmem_cache_node(s, node, n) {
5971 nr_slabs += node_nr_slabs(n);
5972 nr_objs += node_nr_objs(n);
5973 nr_free += count_partial(n, count_free);
5974 }
5975
5976 sinfo->active_objs = nr_objs - nr_free;
5977 sinfo->num_objs = nr_objs;
5978 sinfo->active_slabs = nr_slabs;
5979 sinfo->num_slabs = nr_slabs;
5980 sinfo->objects_per_slab = oo_objects(s->oo);
5981 sinfo->cache_order = oo_order(s->oo);
5982}
5983
5984void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
5985{
5986}
5987
5988ssize_t slabinfo_write(struct file *file, const char __user *buffer,
5989 size_t count, loff_t *ppos)
5990{
5991 return -EIO;
5992}
5993#endif /* CONFIG_SLUB_DEBUG */