1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
5 *
6 * The allocator synchronizes using per slab locks or atomic operations
7 * and only uses a centralized lock to manage a pool of partial slabs.
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> /* mm_account_reclaimed_pages() */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
21 #include "slab.h"
22 #include <linux/proc_fs.h>
23 #include <linux/seq_file.h>
24 #include <linux/kasan.h>
25 #include <linux/kmsan.h>
26 #include <linux/cpu.h>
27 #include <linux/cpuset.h>
28 #include <linux/mempolicy.h>
29 #include <linux/ctype.h>
30 #include <linux/stackdepot.h>
31 #include <linux/debugobjects.h>
32 #include <linux/kallsyms.h>
33 #include <linux/kfence.h>
34 #include <linux/memory.h>
35 #include <linux/math64.h>
36 #include <linux/fault-inject.h>
37 #include <linux/stacktrace.h>
38 #include <linux/prefetch.h>
39 #include <linux/memcontrol.h>
40 #include <linux/random.h>
41 #include <kunit/test.h>
42 #include <kunit/test-bug.h>
43 #include <linux/sort.h>
44
45 #include <linux/debugfs.h>
46 #include <trace/events/kmem.h>
47
48 #include "internal.h"
49
50 /*
51 * Lock order:
52 * 1. slab_mutex (Global Mutex)
53 * 2. node->list_lock (Spinlock)
54 * 3. kmem_cache->cpu_slab->lock (Local lock)
55 * 4. slab_lock(slab) (Only on some arches)
56 * 5. object_map_lock (Only for debugging)
57 *
58 * slab_mutex
59 *
60 * The role of the slab_mutex is to protect the list of all the slabs
61 * and to synchronize major metadata changes to slab cache structures.
62 * Also synchronizes memory hotplug callbacks.
63 *
64 * slab_lock
65 *
66 * The slab_lock is a wrapper around the page lock, thus it is a bit
67 * spinlock.
68 *
69 * The slab_lock is only used on arches that do not have the ability
70 * to do a cmpxchg_double. It only protects:
71 *
72 * A. slab->freelist -> List of free objects in a slab
73 * B. slab->inuse -> Number of objects in use
74 * C. slab->objects -> Number of objects in slab
75 * D. slab->frozen -> frozen state
76 *
77 * Frozen slabs
78 *
79 * If a slab is frozen then it is exempt from list management. It is not
80 * on any list except per cpu partial list. The processor that froze the
81 * slab is the one who can perform list operations on the slab. Other
82 * processors may put objects onto the freelist but the processor that
83 * froze the slab is the only one that can retrieve the objects from the
84 * slab's freelist.
85 *
86 * list_lock
87 *
88 * The list_lock protects the partial and full list on each node and
89 * the partial slab counter. If taken then no new slabs may be added or
90 * removed from the lists nor make the number of partial slabs be modified.
91 * (Note that the total number of slabs is an atomic value that may be
92 * modified without taking the list lock).
93 *
94 * The list_lock is a centralized lock and thus we avoid taking it as
95 * much as possible. As long as SLUB does not have to handle partial
96 * slabs, operations can continue without any centralized lock. F.e.
97 * allocating a long series of objects that fill up slabs does not require
98 * the list lock.
99 *
100 * For debug caches, all allocations are forced to go through a list_lock
101 * protected region to serialize against concurrent validation.
102 *
103 * cpu_slab->lock local lock
104 *
105 * This locks protect slowpath manipulation of all kmem_cache_cpu fields
106 * except the stat counters. This is a percpu structure manipulated only by
107 * the local cpu, so the lock protects against being preempted or interrupted
108 * by an irq. Fast path operations rely on lockless operations instead.
109 *
110 * On PREEMPT_RT, the local lock neither disables interrupts nor preemption
111 * which means the lockless fastpath cannot be used as it might interfere with
112 * an in-progress slow path operations. In this case the local lock is always
113 * taken but it still utilizes the freelist for the common operations.
114 *
115 * lockless fastpaths
116 *
117 * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
118 * are fully lockless when satisfied from the percpu slab (and when
119 * cmpxchg_double is possible to use, otherwise slab_lock is taken).
120 * They also don't disable preemption or migration or irqs. They rely on
121 * the transaction id (tid) field to detect being preempted or moved to
122 * another cpu.
123 *
124 * irq, preemption, migration considerations
125 *
126 * Interrupts are disabled as part of list_lock or local_lock operations, or
127 * around the slab_lock operation, in order to make the slab allocator safe
128 * to use in the context of an irq.
129 *
130 * In addition, preemption (or migration on PREEMPT_RT) is disabled in the
131 * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
132 * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
133 * doesn't have to be revalidated in each section protected by the local lock.
134 *
135 * SLUB assigns one slab for allocation to each processor.
136 * Allocations only occur from these slabs called cpu slabs.
137 *
138 * Slabs with free elements are kept on a partial list and during regular
139 * operations no list for full slabs is used. If an object in a full slab is
140 * freed then the slab will show up again on the partial lists.
141 * We track full slabs for debugging purposes though because otherwise we
142 * cannot scan all objects.
143 *
144 * Slabs are freed when they become empty. Teardown and setup is
145 * minimal so we rely on the page allocators per cpu caches for
146 * fast frees and allocs.
147 *
148 * slab->frozen The slab is frozen and exempt from list processing.
149 * This means that the slab is dedicated to a purpose
150 * such as satisfying allocations for a specific
151 * processor. Objects may be freed in the slab while
152 * it is frozen but slab_free will then skip the usual
153 * list operations. It is up to the processor holding
154 * the slab to integrate the slab into the slab lists
155 * when the slab is no longer needed.
156 *
157 * One use of this flag is to mark slabs that are
158 * used for allocations. Then such a slab becomes a cpu
159 * slab. The cpu slab may be equipped with an additional
160 * freelist that allows lockless access to
161 * free objects in addition to the regular freelist
162 * that requires the slab lock.
163 *
164 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
165 * options set. This moves slab handling out of
166 * the fast path and disables lockless freelists.
167 */
168
169 /*
170 * We could simply use migrate_disable()/enable() but as long as it's a
171 * function call even on !PREEMPT_RT, use inline preempt_disable() there.
172 */
173 #ifndef CONFIG_PREEMPT_RT
174 #define slub_get_cpu_ptr(var) get_cpu_ptr(var)
175 #define slub_put_cpu_ptr(var) put_cpu_ptr(var)
176 #define USE_LOCKLESS_FAST_PATH() (true)
177 #else
178 #define slub_get_cpu_ptr(var) \
179 ({ \
180 migrate_disable(); \
181 this_cpu_ptr(var); \
182 })
183 #define slub_put_cpu_ptr(var) \
184 do { \
185 (void)(var); \
186 migrate_enable(); \
187 } while (0)
188 #define USE_LOCKLESS_FAST_PATH() (false)
189 #endif
190
191 #ifndef CONFIG_SLUB_TINY
192 #define __fastpath_inline __always_inline
193 #else
194 #define __fastpath_inline
195 #endif
196
197 #ifdef CONFIG_SLUB_DEBUG
198 #ifdef CONFIG_SLUB_DEBUG_ON
199 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
200 #else
201 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
202 #endif
203 #endif /* CONFIG_SLUB_DEBUG */
204
205 /* Structure holding parameters for get_partial() call chain */
206 struct partial_context {
207 struct slab **slab;
208 gfp_t flags;
209 unsigned int orig_size;
210 };
211
kmem_cache_debug(struct kmem_cache * s)212 static inline bool kmem_cache_debug(struct kmem_cache *s)
213 {
214 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
215 }
216
slub_debug_orig_size(struct kmem_cache * s)217 static inline bool slub_debug_orig_size(struct kmem_cache *s)
218 {
219 return (kmem_cache_debug_flags(s, SLAB_STORE_USER) &&
220 (s->flags & SLAB_KMALLOC));
221 }
222
fixup_red_left(struct kmem_cache * s,void * p)223 void *fixup_red_left(struct kmem_cache *s, void *p)
224 {
225 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
226 p += s->red_left_pad;
227
228 return p;
229 }
230
kmem_cache_has_cpu_partial(struct kmem_cache * s)231 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
232 {
233 #ifdef CONFIG_SLUB_CPU_PARTIAL
234 return !kmem_cache_debug(s);
235 #else
236 return false;
237 #endif
238 }
239
240 /*
241 * Issues still to be resolved:
242 *
243 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
244 *
245 * - Variable sizing of the per node arrays
246 */
247
248 /* Enable to log cmpxchg failures */
249 #undef SLUB_DEBUG_CMPXCHG
250
251 #ifndef CONFIG_SLUB_TINY
252 /*
253 * Minimum number of partial slabs. These will be left on the partial
254 * lists even if they are empty. kmem_cache_shrink may reclaim them.
255 */
256 #define MIN_PARTIAL 5
257
258 /*
259 * Maximum number of desirable partial slabs.
260 * The existence of more partial slabs makes kmem_cache_shrink
261 * sort the partial list by the number of objects in use.
262 */
263 #define MAX_PARTIAL 10
264 #else
265 #define MIN_PARTIAL 0
266 #define MAX_PARTIAL 0
267 #endif
268
269 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
270 SLAB_POISON | SLAB_STORE_USER)
271
272 /*
273 * These debug flags cannot use CMPXCHG because there might be consistency
274 * issues when checking or reading debug information
275 */
276 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
277 SLAB_TRACE)
278
279
280 /*
281 * Debugging flags that require metadata to be stored in the slab. These get
282 * disabled when slub_debug=O is used and a cache's min order increases with
283 * metadata.
284 */
285 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
286
287 #define OO_SHIFT 16
288 #define OO_MASK ((1 << OO_SHIFT) - 1)
289 #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
290
291 /* Internal SLUB flags */
292 /* Poison object */
293 #define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
294 /* Use cmpxchg_double */
295
296 #ifdef system_has_freelist_aba
297 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
298 #else
299 #define __CMPXCHG_DOUBLE ((slab_flags_t __force)0U)
300 #endif
301
302 /*
303 * Tracking user of a slab.
304 */
305 #define TRACK_ADDRS_COUNT 16
306 struct track {
307 unsigned long addr; /* Called from address */
308 #ifdef CONFIG_STACKDEPOT
309 depot_stack_handle_t handle;
310 #endif
311 int cpu; /* Was running on cpu */
312 int pid; /* Pid context */
313 unsigned long when; /* When did the operation occur */
314 };
315
316 enum track_item { TRACK_ALLOC, TRACK_FREE };
317
318 #ifdef SLAB_SUPPORTS_SYSFS
319 static int sysfs_slab_add(struct kmem_cache *);
320 static int sysfs_slab_alias(struct kmem_cache *, const char *);
321 #else
sysfs_slab_add(struct kmem_cache * s)322 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
sysfs_slab_alias(struct kmem_cache * s,const char * p)323 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
324 { return 0; }
325 #endif
326
327 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
328 static void debugfs_slab_add(struct kmem_cache *);
329 #else
debugfs_slab_add(struct kmem_cache * s)330 static inline void debugfs_slab_add(struct kmem_cache *s) { }
331 #endif
332
stat(const struct kmem_cache * s,enum stat_item si)333 static inline void stat(const struct kmem_cache *s, enum stat_item si)
334 {
335 #ifdef CONFIG_SLUB_STATS
336 /*
337 * The rmw is racy on a preemptible kernel but this is acceptable, so
338 * avoid this_cpu_add()'s irq-disable overhead.
339 */
340 raw_cpu_inc(s->cpu_slab->stat[si]);
341 #endif
342 }
343
344 /*
345 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
346 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
347 * differ during memory hotplug/hotremove operations.
348 * Protected by slab_mutex.
349 */
350 static nodemask_t slab_nodes;
351
352 #ifndef CONFIG_SLUB_TINY
353 /*
354 * Workqueue used for flush_cpu_slab().
355 */
356 static struct workqueue_struct *flushwq;
357 #endif
358
359 /********************************************************************
360 * Core slab cache functions
361 *******************************************************************/
362
363 /*
364 * freeptr_t represents a SLUB freelist pointer, which might be encoded
365 * and not dereferenceable if CONFIG_SLAB_FREELIST_HARDENED is enabled.
366 */
367 typedef struct { unsigned long v; } freeptr_t;
368
369 /*
370 * Returns freelist pointer (ptr). With hardening, this is obfuscated
371 * with an XOR of the address where the pointer is held and a per-cache
372 * random number.
373 */
freelist_ptr_encode(const struct kmem_cache * s,void * ptr,unsigned long ptr_addr)374 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
375 void *ptr, unsigned long ptr_addr)
376 {
377 unsigned long encoded;
378
379 #ifdef CONFIG_SLAB_FREELIST_HARDENED
380 encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
381 #else
382 encoded = (unsigned long)ptr;
383 #endif
384 return (freeptr_t){.v = encoded};
385 }
386
freelist_ptr_decode(const struct kmem_cache * s,freeptr_t ptr,unsigned long ptr_addr)387 static inline void *freelist_ptr_decode(const struct kmem_cache *s,
388 freeptr_t ptr, unsigned long ptr_addr)
389 {
390 void *decoded;
391
392 #ifdef CONFIG_SLAB_FREELIST_HARDENED
393 decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
394 #else
395 decoded = (void *)ptr.v;
396 #endif
397 return decoded;
398 }
399
get_freepointer(struct kmem_cache * s,void * object)400 static inline void *get_freepointer(struct kmem_cache *s, void *object)
401 {
402 unsigned long ptr_addr;
403 freeptr_t p;
404
405 object = kasan_reset_tag(object);
406 ptr_addr = (unsigned long)object + s->offset;
407 p = *(freeptr_t *)(ptr_addr);
408 return freelist_ptr_decode(s, p, ptr_addr);
409 }
410
411 #ifndef CONFIG_SLUB_TINY
prefetch_freepointer(const struct kmem_cache * s,void * object)412 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
413 {
414 prefetchw(object + s->offset);
415 }
416 #endif
417
418 /*
419 * When running under KMSAN, get_freepointer_safe() may return an uninitialized
420 * pointer value in the case the current thread loses the race for the next
421 * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
422 * slab_alloc_node() will fail, so the uninitialized value won't be used, but
423 * KMSAN will still check all arguments of cmpxchg because of imperfect
424 * handling of inline assembly.
425 * To work around this problem, we apply __no_kmsan_checks to ensure that
426 * get_freepointer_safe() returns initialized memory.
427 */
428 __no_kmsan_checks
get_freepointer_safe(struct kmem_cache * s,void * object)429 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
430 {
431 unsigned long freepointer_addr;
432 freeptr_t p;
433
434 if (!debug_pagealloc_enabled_static())
435 return get_freepointer(s, object);
436
437 object = kasan_reset_tag(object);
438 freepointer_addr = (unsigned long)object + s->offset;
439 copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p));
440 return freelist_ptr_decode(s, p, freepointer_addr);
441 }
442
set_freepointer(struct kmem_cache * s,void * object,void * fp)443 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
444 {
445 unsigned long freeptr_addr = (unsigned long)object + s->offset;
446
447 #ifdef CONFIG_SLAB_FREELIST_HARDENED
448 BUG_ON(object == fp); /* naive detection of double free or corruption */
449 #endif
450
451 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
452 *(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
453 }
454
455 /*
456 * See comment in calculate_sizes().
457 */
freeptr_outside_object(struct kmem_cache * s)458 static inline bool freeptr_outside_object(struct kmem_cache *s)
459 {
460 return s->offset >= s->inuse;
461 }
462
463 /*
464 * Return offset of the end of info block which is inuse + free pointer if
465 * not overlapping with object.
466 */
get_info_end(struct kmem_cache * s)467 static inline unsigned int get_info_end(struct kmem_cache *s)
468 {
469 if (freeptr_outside_object(s))
470 return s->inuse + sizeof(void *);
471 else
472 return s->inuse;
473 }
474
475 /* Loop over all objects in a slab */
476 #define for_each_object(__p, __s, __addr, __objects) \
477 for (__p = fixup_red_left(__s, __addr); \
478 __p < (__addr) + (__objects) * (__s)->size; \
479 __p += (__s)->size)
480
order_objects(unsigned int order,unsigned int size)481 static inline unsigned int order_objects(unsigned int order, unsigned int size)
482 {
483 return ((unsigned int)PAGE_SIZE << order) / size;
484 }
485
oo_make(unsigned int order,unsigned int size)486 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
487 unsigned int size)
488 {
489 struct kmem_cache_order_objects x = {
490 (order << OO_SHIFT) + order_objects(order, size)
491 };
492
493 return x;
494 }
495
oo_order(struct kmem_cache_order_objects x)496 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
497 {
498 return x.x >> OO_SHIFT;
499 }
500
oo_objects(struct kmem_cache_order_objects x)501 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
502 {
503 return x.x & OO_MASK;
504 }
505
506 #ifdef CONFIG_SLUB_CPU_PARTIAL
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)507 static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
508 {
509 unsigned int nr_slabs;
510
511 s->cpu_partial = nr_objects;
512
513 /*
514 * We take the number of objects but actually limit the number of
515 * slabs on the per cpu partial list, in order to limit excessive
516 * growth of the list. For simplicity we assume that the slabs will
517 * be half-full.
518 */
519 nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
520 s->cpu_partial_slabs = nr_slabs;
521 }
522 #else
523 static inline void
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)524 slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
525 {
526 }
527 #endif /* CONFIG_SLUB_CPU_PARTIAL */
528
529 /*
530 * Per slab locking using the pagelock
531 */
slab_lock(struct slab * slab)532 static __always_inline void slab_lock(struct slab *slab)
533 {
534 struct page *page = slab_page(slab);
535
536 VM_BUG_ON_PAGE(PageTail(page), page);
537 bit_spin_lock(PG_locked, &page->flags);
538 }
539
slab_unlock(struct slab * slab)540 static __always_inline void slab_unlock(struct slab *slab)
541 {
542 struct page *page = slab_page(slab);
543
544 VM_BUG_ON_PAGE(PageTail(page), page);
545 __bit_spin_unlock(PG_locked, &page->flags);
546 }
547
548 static inline bool
__update_freelist_fast(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)549 __update_freelist_fast(struct slab *slab,
550 void *freelist_old, unsigned long counters_old,
551 void *freelist_new, unsigned long counters_new)
552 {
553 #ifdef system_has_freelist_aba
554 freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old };
555 freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new };
556
557 return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full);
558 #else
559 return false;
560 #endif
561 }
562
563 static inline bool
__update_freelist_slow(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)564 __update_freelist_slow(struct slab *slab,
565 void *freelist_old, unsigned long counters_old,
566 void *freelist_new, unsigned long counters_new)
567 {
568 bool ret = false;
569
570 slab_lock(slab);
571 if (slab->freelist == freelist_old &&
572 slab->counters == counters_old) {
573 slab->freelist = freelist_new;
574 slab->counters = counters_new;
575 ret = true;
576 }
577 slab_unlock(slab);
578
579 return ret;
580 }
581
582 /*
583 * Interrupts must be disabled (for the fallback code to work right), typically
584 * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
585 * part of bit_spin_lock(), is sufficient because the policy is not to allow any
586 * allocation/ free operation in hardirq context. Therefore nothing can
587 * interrupt the operation.
588 */
__slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)589 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
590 void *freelist_old, unsigned long counters_old,
591 void *freelist_new, unsigned long counters_new,
592 const char *n)
593 {
594 bool ret;
595
596 if (USE_LOCKLESS_FAST_PATH())
597 lockdep_assert_irqs_disabled();
598
599 if (s->flags & __CMPXCHG_DOUBLE) {
600 ret = __update_freelist_fast(slab, freelist_old, counters_old,
601 freelist_new, counters_new);
602 } else {
603 ret = __update_freelist_slow(slab, freelist_old, counters_old,
604 freelist_new, counters_new);
605 }
606 if (likely(ret))
607 return true;
608
609 cpu_relax();
610 stat(s, CMPXCHG_DOUBLE_FAIL);
611
612 #ifdef SLUB_DEBUG_CMPXCHG
613 pr_info("%s %s: cmpxchg double redo ", n, s->name);
614 #endif
615
616 return false;
617 }
618
slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)619 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
620 void *freelist_old, unsigned long counters_old,
621 void *freelist_new, unsigned long counters_new,
622 const char *n)
623 {
624 bool ret;
625
626 if (s->flags & __CMPXCHG_DOUBLE) {
627 ret = __update_freelist_fast(slab, freelist_old, counters_old,
628 freelist_new, counters_new);
629 } else {
630 unsigned long flags;
631
632 local_irq_save(flags);
633 ret = __update_freelist_slow(slab, freelist_old, counters_old,
634 freelist_new, counters_new);
635 local_irq_restore(flags);
636 }
637 if (likely(ret))
638 return true;
639
640 cpu_relax();
641 stat(s, CMPXCHG_DOUBLE_FAIL);
642
643 #ifdef SLUB_DEBUG_CMPXCHG
644 pr_info("%s %s: cmpxchg double redo ", n, s->name);
645 #endif
646
647 return false;
648 }
649
650 /*
651 * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
652 * family will round up the real request size to these fixed ones, so
653 * there could be an extra area than what is requested. Save the original
654 * request size in the meta data area, for better debug and sanity check.
655 */
set_orig_size(struct kmem_cache * s,void * object,unsigned int orig_size)656 static inline void set_orig_size(struct kmem_cache *s,
657 void *object, unsigned int orig_size)
658 {
659 void *p = kasan_reset_tag(object);
660
661 if (!slub_debug_orig_size(s))
662 return;
663
664 #ifdef CONFIG_KASAN_GENERIC
665 /*
666 * KASAN can save its free meta data inside of the object at offset 0.
667 * If this meta data size is larger than 'orig_size', it will overlap
668 * the data redzone in [orig_size+1, object_size]. Thus, we adjust
669 * 'orig_size' to be as at least as big as KASAN's meta data.
670 */
671 if (kasan_metadata_size(s, true) > orig_size)
672 orig_size = kasan_meta_size;
673 #endif
674
675 p += get_info_end(s);
676 p += sizeof(struct track) * 2;
677
678 *(unsigned int *)p = orig_size;
679 }
680
get_orig_size(struct kmem_cache * s,void * object)681 static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
682 {
683 void *p = kasan_reset_tag(object);
684
685 if (!slub_debug_orig_size(s))
686 return s->object_size;
687
688 p += get_info_end(s);
689 p += sizeof(struct track) * 2;
690
691 return *(unsigned int *)p;
692 }
693
694 #ifdef CONFIG_SLUB_DEBUG
695 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
696 static DEFINE_SPINLOCK(object_map_lock);
697
__fill_map(unsigned long * obj_map,struct kmem_cache * s,struct slab * slab)698 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
699 struct slab *slab)
700 {
701 void *addr = slab_address(slab);
702 void *p;
703
704 bitmap_zero(obj_map, slab->objects);
705
706 for (p = slab->freelist; p; p = get_freepointer(s, p))
707 set_bit(__obj_to_index(s, addr, p), obj_map);
708 }
709
710 #if IS_ENABLED(CONFIG_KUNIT)
slab_add_kunit_errors(void)711 static bool slab_add_kunit_errors(void)
712 {
713 struct kunit_resource *resource;
714
715 if (!kunit_get_current_test())
716 return false;
717
718 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
719 if (!resource)
720 return false;
721
722 (*(int *)resource->data)++;
723 kunit_put_resource(resource);
724 return true;
725 }
726 #else
slab_add_kunit_errors(void)727 static inline bool slab_add_kunit_errors(void) { return false; }
728 #endif
729
size_from_object(struct kmem_cache * s)730 static inline unsigned int size_from_object(struct kmem_cache *s)
731 {
732 if (s->flags & SLAB_RED_ZONE)
733 return s->size - s->red_left_pad;
734
735 return s->size;
736 }
737
restore_red_left(struct kmem_cache * s,void * p)738 static inline void *restore_red_left(struct kmem_cache *s, void *p)
739 {
740 if (s->flags & SLAB_RED_ZONE)
741 p -= s->red_left_pad;
742
743 return p;
744 }
745
746 /*
747 * Debug settings:
748 */
749 #if defined(CONFIG_SLUB_DEBUG_ON)
750 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
751 #else
752 static slab_flags_t slub_debug;
753 #endif
754
755 static char *slub_debug_string;
756 static int disable_higher_order_debug;
757
758 /*
759 * slub is about to manipulate internal object metadata. This memory lies
760 * outside the range of the allocated object, so accessing it would normally
761 * be reported by kasan as a bounds error. metadata_access_enable() is used
762 * to tell kasan that these accesses are OK.
763 */
metadata_access_enable(void)764 static inline void metadata_access_enable(void)
765 {
766 kasan_disable_current();
767 }
768
metadata_access_disable(void)769 static inline void metadata_access_disable(void)
770 {
771 kasan_enable_current();
772 }
773
774 /*
775 * Object debugging
776 */
777
778 /* Verify that a pointer has an address that is valid within a slab page */
check_valid_pointer(struct kmem_cache * s,struct slab * slab,void * object)779 static inline int check_valid_pointer(struct kmem_cache *s,
780 struct slab *slab, void *object)
781 {
782 void *base;
783
784 if (!object)
785 return 1;
786
787 base = slab_address(slab);
788 object = kasan_reset_tag(object);
789 object = restore_red_left(s, object);
790 if (object < base || object >= base + slab->objects * s->size ||
791 (object - base) % s->size) {
792 return 0;
793 }
794
795 return 1;
796 }
797
print_section(char * level,char * text,u8 * addr,unsigned int length)798 static void print_section(char *level, char *text, u8 *addr,
799 unsigned int length)
800 {
801 metadata_access_enable();
802 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
803 16, 1, kasan_reset_tag((void *)addr), length, 1);
804 metadata_access_disable();
805 }
806
get_track(struct kmem_cache * s,void * object,enum track_item alloc)807 static struct track *get_track(struct kmem_cache *s, void *object,
808 enum track_item alloc)
809 {
810 struct track *p;
811
812 p = object + get_info_end(s);
813
814 return kasan_reset_tag(p + alloc);
815 }
816
817 #ifdef CONFIG_STACKDEPOT
set_track_prepare(void)818 static noinline depot_stack_handle_t set_track_prepare(void)
819 {
820 depot_stack_handle_t handle;
821 unsigned long entries[TRACK_ADDRS_COUNT];
822 unsigned int nr_entries;
823
824 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
825 handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT);
826
827 return handle;
828 }
829 #else
set_track_prepare(void)830 static inline depot_stack_handle_t set_track_prepare(void)
831 {
832 return 0;
833 }
834 #endif
835
set_track_update(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,depot_stack_handle_t handle)836 static void set_track_update(struct kmem_cache *s, void *object,
837 enum track_item alloc, unsigned long addr,
838 depot_stack_handle_t handle)
839 {
840 struct track *p = get_track(s, object, alloc);
841
842 #ifdef CONFIG_STACKDEPOT
843 p->handle = handle;
844 #endif
845 p->addr = addr;
846 p->cpu = smp_processor_id();
847 p->pid = current->pid;
848 p->when = jiffies;
849 }
850
set_track(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr)851 static __always_inline void set_track(struct kmem_cache *s, void *object,
852 enum track_item alloc, unsigned long addr)
853 {
854 depot_stack_handle_t handle = set_track_prepare();
855
856 set_track_update(s, object, alloc, addr, handle);
857 }
858
init_tracking(struct kmem_cache * s,void * object)859 static void init_tracking(struct kmem_cache *s, void *object)
860 {
861 struct track *p;
862
863 if (!(s->flags & SLAB_STORE_USER))
864 return;
865
866 p = get_track(s, object, TRACK_ALLOC);
867 memset(p, 0, 2*sizeof(struct track));
868 }
869
print_track(const char * s,struct track * t,unsigned long pr_time)870 static void print_track(const char *s, struct track *t, unsigned long pr_time)
871 {
872 depot_stack_handle_t handle __maybe_unused;
873
874 if (!t->addr)
875 return;
876
877 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
878 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
879 #ifdef CONFIG_STACKDEPOT
880 handle = READ_ONCE(t->handle);
881 if (handle)
882 stack_depot_print(handle);
883 else
884 pr_err("object allocation/free stack trace missing\n");
885 #endif
886 }
887
print_tracking(struct kmem_cache * s,void * object)888 void print_tracking(struct kmem_cache *s, void *object)
889 {
890 unsigned long pr_time = jiffies;
891 if (!(s->flags & SLAB_STORE_USER))
892 return;
893
894 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
895 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
896 }
897
print_slab_info(const struct slab * slab)898 static void print_slab_info(const struct slab *slab)
899 {
900 struct folio *folio = (struct folio *)slab_folio(slab);
901
902 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
903 slab, slab->objects, slab->inuse, slab->freelist,
904 folio_flags(folio, 0));
905 }
906
skip_orig_size_check(struct kmem_cache * s,const void * object)907 void skip_orig_size_check(struct kmem_cache *s, const void *object)
908 {
909 set_orig_size(s, (void *)object, s->object_size);
910 }
911
slab_bug(struct kmem_cache * s,char * fmt,...)912 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
913 {
914 struct va_format vaf;
915 va_list args;
916
917 va_start(args, fmt);
918 vaf.fmt = fmt;
919 vaf.va = &args;
920 pr_err("=============================================================================\n");
921 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
922 pr_err("-----------------------------------------------------------------------------\n\n");
923 va_end(args);
924 }
925
926 __printf(2, 3)
slab_fix(struct kmem_cache * s,char * fmt,...)927 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
928 {
929 struct va_format vaf;
930 va_list args;
931
932 if (slab_add_kunit_errors())
933 return;
934
935 va_start(args, fmt);
936 vaf.fmt = fmt;
937 vaf.va = &args;
938 pr_err("FIX %s: %pV\n", s->name, &vaf);
939 va_end(args);
940 }
941
print_trailer(struct kmem_cache * s,struct slab * slab,u8 * p)942 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
943 {
944 unsigned int off; /* Offset of last byte */
945 u8 *addr = slab_address(slab);
946
947 print_tracking(s, p);
948
949 print_slab_info(slab);
950
951 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
952 p, p - addr, get_freepointer(s, p));
953
954 if (s->flags & SLAB_RED_ZONE)
955 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
956 s->red_left_pad);
957 else if (p > addr + 16)
958 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
959
960 print_section(KERN_ERR, "Object ", p,
961 min_t(unsigned int, s->object_size, PAGE_SIZE));
962 if (s->flags & SLAB_RED_ZONE)
963 print_section(KERN_ERR, "Redzone ", p + s->object_size,
964 s->inuse - s->object_size);
965
966 off = get_info_end(s);
967
968 if (s->flags & SLAB_STORE_USER)
969 off += 2 * sizeof(struct track);
970
971 if (slub_debug_orig_size(s))
972 off += sizeof(unsigned int);
973
974 off += kasan_metadata_size(s, false);
975
976 if (off != size_from_object(s))
977 /* Beginning of the filler is the free pointer */
978 print_section(KERN_ERR, "Padding ", p + off,
979 size_from_object(s) - off);
980
981 dump_stack();
982 }
983
object_err(struct kmem_cache * s,struct slab * slab,u8 * object,char * reason)984 static void object_err(struct kmem_cache *s, struct slab *slab,
985 u8 *object, char *reason)
986 {
987 if (slab_add_kunit_errors())
988 return;
989
990 slab_bug(s, "%s", reason);
991 print_trailer(s, slab, object);
992 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
993 }
994
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)995 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
996 void **freelist, void *nextfree)
997 {
998 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
999 !check_valid_pointer(s, slab, nextfree) && freelist) {
1000 object_err(s, slab, *freelist, "Freechain corrupt");
1001 *freelist = NULL;
1002 slab_fix(s, "Isolate corrupted freechain");
1003 return true;
1004 }
1005
1006 return false;
1007 }
1008
slab_err(struct kmem_cache * s,struct slab * slab,const char * fmt,...)1009 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
1010 const char *fmt, ...)
1011 {
1012 va_list args;
1013 char buf[100];
1014
1015 if (slab_add_kunit_errors())
1016 return;
1017
1018 va_start(args, fmt);
1019 vsnprintf(buf, sizeof(buf), fmt, args);
1020 va_end(args);
1021 slab_bug(s, "%s", buf);
1022 print_slab_info(slab);
1023 dump_stack();
1024 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1025 }
1026
init_object(struct kmem_cache * s,void * object,u8 val)1027 static void init_object(struct kmem_cache *s, void *object, u8 val)
1028 {
1029 u8 *p = kasan_reset_tag(object);
1030 unsigned int poison_size = s->object_size;
1031
1032 if (s->flags & SLAB_RED_ZONE) {
1033 memset(p - s->red_left_pad, val, s->red_left_pad);
1034
1035 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1036 /*
1037 * Redzone the extra allocated space by kmalloc than
1038 * requested, and the poison size will be limited to
1039 * the original request size accordingly.
1040 */
1041 poison_size = get_orig_size(s, object);
1042 }
1043 }
1044
1045 if (s->flags & __OBJECT_POISON) {
1046 memset(p, POISON_FREE, poison_size - 1);
1047 p[poison_size - 1] = POISON_END;
1048 }
1049
1050 if (s->flags & SLAB_RED_ZONE)
1051 memset(p + poison_size, val, s->inuse - poison_size);
1052 }
1053
restore_bytes(struct kmem_cache * s,char * message,u8 data,void * from,void * to)1054 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
1055 void *from, void *to)
1056 {
1057 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
1058 memset(from, data, to - from);
1059 }
1060
check_bytes_and_report(struct kmem_cache * s,struct slab * slab,u8 * object,char * what,u8 * start,unsigned int value,unsigned int bytes)1061 static int check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
1062 u8 *object, char *what,
1063 u8 *start, unsigned int value, unsigned int bytes)
1064 {
1065 u8 *fault;
1066 u8 *end;
1067 u8 *addr = slab_address(slab);
1068
1069 metadata_access_enable();
1070 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
1071 metadata_access_disable();
1072 if (!fault)
1073 return 1;
1074
1075 end = start + bytes;
1076 while (end > fault && end[-1] == value)
1077 end--;
1078
1079 if (slab_add_kunit_errors())
1080 goto skip_bug_print;
1081
1082 slab_bug(s, "%s overwritten", what);
1083 pr_err("0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
1084 fault, end - 1, fault - addr,
1085 fault[0], value);
1086 print_trailer(s, slab, object);
1087 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1088
1089 skip_bug_print:
1090 restore_bytes(s, what, value, fault, end);
1091 return 0;
1092 }
1093
1094 /*
1095 * Object layout:
1096 *
1097 * object address
1098 * Bytes of the object to be managed.
1099 * If the freepointer may overlay the object then the free
1100 * pointer is at the middle of the object.
1101 *
1102 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
1103 * 0xa5 (POISON_END)
1104 *
1105 * object + s->object_size
1106 * Padding to reach word boundary. This is also used for Redzoning.
1107 * Padding is extended by another word if Redzoning is enabled and
1108 * object_size == inuse.
1109 *
1110 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
1111 * 0xcc (RED_ACTIVE) for objects in use.
1112 *
1113 * object + s->inuse
1114 * Meta data starts here.
1115 *
1116 * A. Free pointer (if we cannot overwrite object on free)
1117 * B. Tracking data for SLAB_STORE_USER
1118 * C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
1119 * D. Padding to reach required alignment boundary or at minimum
1120 * one word if debugging is on to be able to detect writes
1121 * before the word boundary.
1122 *
1123 * Padding is done using 0x5a (POISON_INUSE)
1124 *
1125 * object + s->size
1126 * Nothing is used beyond s->size.
1127 *
1128 * If slabcaches are merged then the object_size and inuse boundaries are mostly
1129 * ignored. And therefore no slab options that rely on these boundaries
1130 * may be used with merged slabcaches.
1131 */
1132
check_pad_bytes(struct kmem_cache * s,struct slab * slab,u8 * p)1133 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
1134 {
1135 unsigned long off = get_info_end(s); /* The end of info */
1136
1137 if (s->flags & SLAB_STORE_USER) {
1138 /* We also have user information there */
1139 off += 2 * sizeof(struct track);
1140
1141 if (s->flags & SLAB_KMALLOC)
1142 off += sizeof(unsigned int);
1143 }
1144
1145 off += kasan_metadata_size(s, false);
1146
1147 if (size_from_object(s) == off)
1148 return 1;
1149
1150 return check_bytes_and_report(s, slab, p, "Object padding",
1151 p + off, POISON_INUSE, size_from_object(s) - off);
1152 }
1153
1154 /* Check the pad bytes at the end of a slab page */
slab_pad_check(struct kmem_cache * s,struct slab * slab)1155 static void slab_pad_check(struct kmem_cache *s, struct slab *slab)
1156 {
1157 u8 *start;
1158 u8 *fault;
1159 u8 *end;
1160 u8 *pad;
1161 int length;
1162 int remainder;
1163
1164 if (!(s->flags & SLAB_POISON))
1165 return;
1166
1167 start = slab_address(slab);
1168 length = slab_size(slab);
1169 end = start + length;
1170 remainder = length % s->size;
1171 if (!remainder)
1172 return;
1173
1174 pad = end - remainder;
1175 metadata_access_enable();
1176 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
1177 metadata_access_disable();
1178 if (!fault)
1179 return;
1180 while (end > fault && end[-1] == POISON_INUSE)
1181 end--;
1182
1183 slab_err(s, slab, "Padding overwritten. 0x%p-0x%p @offset=%tu",
1184 fault, end - 1, fault - start);
1185 print_section(KERN_ERR, "Padding ", pad, remainder);
1186
1187 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
1188 }
1189
check_object(struct kmem_cache * s,struct slab * slab,void * object,u8 val)1190 static int check_object(struct kmem_cache *s, struct slab *slab,
1191 void *object, u8 val)
1192 {
1193 u8 *p = object;
1194 u8 *endobject = object + s->object_size;
1195 unsigned int orig_size;
1196
1197 if (s->flags & SLAB_RED_ZONE) {
1198 if (!check_bytes_and_report(s, slab, object, "Left Redzone",
1199 object - s->red_left_pad, val, s->red_left_pad))
1200 return 0;
1201
1202 if (!check_bytes_and_report(s, slab, object, "Right Redzone",
1203 endobject, val, s->inuse - s->object_size))
1204 return 0;
1205
1206 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1207 orig_size = get_orig_size(s, object);
1208
1209 if (s->object_size > orig_size &&
1210 !check_bytes_and_report(s, slab, object,
1211 "kmalloc Redzone", p + orig_size,
1212 val, s->object_size - orig_size)) {
1213 return 0;
1214 }
1215 }
1216 } else {
1217 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
1218 check_bytes_and_report(s, slab, p, "Alignment padding",
1219 endobject, POISON_INUSE,
1220 s->inuse - s->object_size);
1221 }
1222 }
1223
1224 if (s->flags & SLAB_POISON) {
1225 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
1226 (!check_bytes_and_report(s, slab, p, "Poison", p,
1227 POISON_FREE, s->object_size - 1) ||
1228 !check_bytes_and_report(s, slab, p, "End Poison",
1229 p + s->object_size - 1, POISON_END, 1)))
1230 return 0;
1231 /*
1232 * check_pad_bytes cleans up on its own.
1233 */
1234 check_pad_bytes(s, slab, p);
1235 }
1236
1237 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
1238 /*
1239 * Object and freepointer overlap. Cannot check
1240 * freepointer while object is allocated.
1241 */
1242 return 1;
1243
1244 /* Check free pointer validity */
1245 if (!check_valid_pointer(s, slab, get_freepointer(s, p))) {
1246 object_err(s, slab, p, "Freepointer corrupt");
1247 /*
1248 * No choice but to zap it and thus lose the remainder
1249 * of the free objects in this slab. May cause
1250 * another error because the object count is now wrong.
1251 */
1252 set_freepointer(s, p, NULL);
1253 return 0;
1254 }
1255 return 1;
1256 }
1257
check_slab(struct kmem_cache * s,struct slab * slab)1258 static int check_slab(struct kmem_cache *s, struct slab *slab)
1259 {
1260 int maxobj;
1261
1262 if (!folio_test_slab(slab_folio(slab))) {
1263 slab_err(s, slab, "Not a valid slab page");
1264 return 0;
1265 }
1266
1267 maxobj = order_objects(slab_order(slab), s->size);
1268 if (slab->objects > maxobj) {
1269 slab_err(s, slab, "objects %u > max %u",
1270 slab->objects, maxobj);
1271 return 0;
1272 }
1273 if (slab->inuse > slab->objects) {
1274 slab_err(s, slab, "inuse %u > max %u",
1275 slab->inuse, slab->objects);
1276 return 0;
1277 }
1278 if (slab->frozen) {
1279 slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
1280 return 0;
1281 }
1282
1283 /* Slab_pad_check fixes things up after itself */
1284 slab_pad_check(s, slab);
1285 return 1;
1286 }
1287
1288 /*
1289 * Determine if a certain object in a slab is on the freelist. Must hold the
1290 * slab lock to guarantee that the chains are in a consistent state.
1291 */
on_freelist(struct kmem_cache * s,struct slab * slab,void * search)1292 static int on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
1293 {
1294 int nr = 0;
1295 void *fp;
1296 void *object = NULL;
1297 int max_objects;
1298
1299 fp = slab->freelist;
1300 while (fp && nr <= slab->objects) {
1301 if (fp == search)
1302 return 1;
1303 if (!check_valid_pointer(s, slab, fp)) {
1304 if (object) {
1305 object_err(s, slab, object,
1306 "Freechain corrupt");
1307 set_freepointer(s, object, NULL);
1308 } else {
1309 slab_err(s, slab, "Freepointer corrupt");
1310 slab->freelist = NULL;
1311 slab->inuse = slab->objects;
1312 slab_fix(s, "Freelist cleared");
1313 return 0;
1314 }
1315 break;
1316 }
1317 object = fp;
1318 fp = get_freepointer(s, object);
1319 nr++;
1320 }
1321
1322 max_objects = order_objects(slab_order(slab), s->size);
1323 if (max_objects > MAX_OBJS_PER_PAGE)
1324 max_objects = MAX_OBJS_PER_PAGE;
1325
1326 if (slab->objects != max_objects) {
1327 slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1328 slab->objects, max_objects);
1329 slab->objects = max_objects;
1330 slab_fix(s, "Number of objects adjusted");
1331 }
1332 if (slab->inuse != slab->objects - nr) {
1333 slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1334 slab->inuse, slab->objects - nr);
1335 slab->inuse = slab->objects - nr;
1336 slab_fix(s, "Object count adjusted");
1337 }
1338 return search == NULL;
1339 }
1340
trace(struct kmem_cache * s,struct slab * slab,void * object,int alloc)1341 static void trace(struct kmem_cache *s, struct slab *slab, void *object,
1342 int alloc)
1343 {
1344 if (s->flags & SLAB_TRACE) {
1345 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1346 s->name,
1347 alloc ? "alloc" : "free",
1348 object, slab->inuse,
1349 slab->freelist);
1350
1351 if (!alloc)
1352 print_section(KERN_INFO, "Object ", (void *)object,
1353 s->object_size);
1354
1355 dump_stack();
1356 }
1357 }
1358
1359 /*
1360 * Tracking of fully allocated slabs for debugging purposes.
1361 */
add_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1362 static void add_full(struct kmem_cache *s,
1363 struct kmem_cache_node *n, struct slab *slab)
1364 {
1365 if (!(s->flags & SLAB_STORE_USER))
1366 return;
1367
1368 lockdep_assert_held(&n->list_lock);
1369 list_add(&slab->slab_list, &n->full);
1370 }
1371
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1372 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
1373 {
1374 if (!(s->flags & SLAB_STORE_USER))
1375 return;
1376
1377 lockdep_assert_held(&n->list_lock);
1378 list_del(&slab->slab_list);
1379 }
1380
node_nr_slabs(struct kmem_cache_node * n)1381 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1382 {
1383 return atomic_long_read(&n->nr_slabs);
1384 }
1385
inc_slabs_node(struct kmem_cache * s,int node,int objects)1386 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1387 {
1388 struct kmem_cache_node *n = get_node(s, node);
1389
1390 /*
1391 * May be called early in order to allocate a slab for the
1392 * kmem_cache_node structure. Solve the chicken-egg
1393 * dilemma by deferring the increment of the count during
1394 * bootstrap (see early_kmem_cache_node_alloc).
1395 */
1396 if (likely(n)) {
1397 atomic_long_inc(&n->nr_slabs);
1398 atomic_long_add(objects, &n->total_objects);
1399 }
1400 }
dec_slabs_node(struct kmem_cache * s,int node,int objects)1401 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1402 {
1403 struct kmem_cache_node *n = get_node(s, node);
1404
1405 atomic_long_dec(&n->nr_slabs);
1406 atomic_long_sub(objects, &n->total_objects);
1407 }
1408
1409 /* Object debug checks for alloc/free paths */
setup_object_debug(struct kmem_cache * s,void * object)1410 static void setup_object_debug(struct kmem_cache *s, void *object)
1411 {
1412 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1413 return;
1414
1415 init_object(s, object, SLUB_RED_INACTIVE);
1416 init_tracking(s, object);
1417 }
1418
1419 static
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1420 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
1421 {
1422 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1423 return;
1424
1425 metadata_access_enable();
1426 memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
1427 metadata_access_disable();
1428 }
1429
alloc_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object)1430 static inline int alloc_consistency_checks(struct kmem_cache *s,
1431 struct slab *slab, void *object)
1432 {
1433 if (!check_slab(s, slab))
1434 return 0;
1435
1436 if (!check_valid_pointer(s, slab, object)) {
1437 object_err(s, slab, object, "Freelist Pointer check fails");
1438 return 0;
1439 }
1440
1441 if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
1442 return 0;
1443
1444 return 1;
1445 }
1446
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1447 static noinline bool alloc_debug_processing(struct kmem_cache *s,
1448 struct slab *slab, void *object, int orig_size)
1449 {
1450 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1451 if (!alloc_consistency_checks(s, slab, object))
1452 goto bad;
1453 }
1454
1455 /* Success. Perform special debug activities for allocs */
1456 trace(s, slab, object, 1);
1457 set_orig_size(s, object, orig_size);
1458 init_object(s, object, SLUB_RED_ACTIVE);
1459 return true;
1460
1461 bad:
1462 if (folio_test_slab(slab_folio(slab))) {
1463 /*
1464 * If this is a slab page then lets do the best we can
1465 * to avoid issues in the future. Marking all objects
1466 * as used avoids touching the remaining objects.
1467 */
1468 slab_fix(s, "Marking all objects used");
1469 slab->inuse = slab->objects;
1470 slab->freelist = NULL;
1471 slab->frozen = 1; /* mark consistency-failed slab as frozen */
1472 }
1473 return false;
1474 }
1475
free_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object,unsigned long addr)1476 static inline int free_consistency_checks(struct kmem_cache *s,
1477 struct slab *slab, void *object, unsigned long addr)
1478 {
1479 if (!check_valid_pointer(s, slab, object)) {
1480 slab_err(s, slab, "Invalid object pointer 0x%p", object);
1481 return 0;
1482 }
1483
1484 if (on_freelist(s, slab, object)) {
1485 object_err(s, slab, object, "Object already free");
1486 return 0;
1487 }
1488
1489 if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
1490 return 0;
1491
1492 if (unlikely(s != slab->slab_cache)) {
1493 if (!folio_test_slab(slab_folio(slab))) {
1494 slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
1495 object);
1496 } else if (!slab->slab_cache) {
1497 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1498 object);
1499 dump_stack();
1500 } else
1501 object_err(s, slab, object,
1502 "page slab pointer corrupt.");
1503 return 0;
1504 }
1505 return 1;
1506 }
1507
1508 /*
1509 * Parse a block of slub_debug options. Blocks are delimited by ';'
1510 *
1511 * @str: start of block
1512 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1513 * @slabs: return start of list of slabs, or NULL when there's no list
1514 * @init: assume this is initial parsing and not per-kmem-create parsing
1515 *
1516 * returns the start of next block if there's any, or NULL
1517 */
1518 static char *
parse_slub_debug_flags(char * str,slab_flags_t * flags,char ** slabs,bool init)1519 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1520 {
1521 bool higher_order_disable = false;
1522
1523 /* Skip any completely empty blocks */
1524 while (*str && *str == ';')
1525 str++;
1526
1527 if (*str == ',') {
1528 /*
1529 * No options but restriction on slabs. This means full
1530 * debugging for slabs matching a pattern.
1531 */
1532 *flags = DEBUG_DEFAULT_FLAGS;
1533 goto check_slabs;
1534 }
1535 *flags = 0;
1536
1537 /* Determine which debug features should be switched on */
1538 for (; *str && *str != ',' && *str != ';'; str++) {
1539 switch (tolower(*str)) {
1540 case '-':
1541 *flags = 0;
1542 break;
1543 case 'f':
1544 *flags |= SLAB_CONSISTENCY_CHECKS;
1545 break;
1546 case 'z':
1547 *flags |= SLAB_RED_ZONE;
1548 break;
1549 case 'p':
1550 *flags |= SLAB_POISON;
1551 break;
1552 case 'u':
1553 *flags |= SLAB_STORE_USER;
1554 break;
1555 case 't':
1556 *flags |= SLAB_TRACE;
1557 break;
1558 case 'a':
1559 *flags |= SLAB_FAILSLAB;
1560 break;
1561 case 'o':
1562 /*
1563 * Avoid enabling debugging on caches if its minimum
1564 * order would increase as a result.
1565 */
1566 higher_order_disable = true;
1567 break;
1568 default:
1569 if (init)
1570 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
1571 }
1572 }
1573 check_slabs:
1574 if (*str == ',')
1575 *slabs = ++str;
1576 else
1577 *slabs = NULL;
1578
1579 /* Skip over the slab list */
1580 while (*str && *str != ';')
1581 str++;
1582
1583 /* Skip any completely empty blocks */
1584 while (*str && *str == ';')
1585 str++;
1586
1587 if (init && higher_order_disable)
1588 disable_higher_order_debug = 1;
1589
1590 if (*str)
1591 return str;
1592 else
1593 return NULL;
1594 }
1595
setup_slub_debug(char * str)1596 static int __init setup_slub_debug(char *str)
1597 {
1598 slab_flags_t flags;
1599 slab_flags_t global_flags;
1600 char *saved_str;
1601 char *slab_list;
1602 bool global_slub_debug_changed = false;
1603 bool slab_list_specified = false;
1604
1605 global_flags = DEBUG_DEFAULT_FLAGS;
1606 if (*str++ != '=' || !*str)
1607 /*
1608 * No options specified. Switch on full debugging.
1609 */
1610 goto out;
1611
1612 saved_str = str;
1613 while (str) {
1614 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1615
1616 if (!slab_list) {
1617 global_flags = flags;
1618 global_slub_debug_changed = true;
1619 } else {
1620 slab_list_specified = true;
1621 if (flags & SLAB_STORE_USER)
1622 stack_depot_request_early_init();
1623 }
1624 }
1625
1626 /*
1627 * For backwards compatibility, a single list of flags with list of
1628 * slabs means debugging is only changed for those slabs, so the global
1629 * slub_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1630 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
1631 * long as there is no option specifying flags without a slab list.
1632 */
1633 if (slab_list_specified) {
1634 if (!global_slub_debug_changed)
1635 global_flags = slub_debug;
1636 slub_debug_string = saved_str;
1637 }
1638 out:
1639 slub_debug = global_flags;
1640 if (slub_debug & SLAB_STORE_USER)
1641 stack_depot_request_early_init();
1642 if (slub_debug != 0 || slub_debug_string)
1643 static_branch_enable(&slub_debug_enabled);
1644 else
1645 static_branch_disable(&slub_debug_enabled);
1646 if ((static_branch_unlikely(&init_on_alloc) ||
1647 static_branch_unlikely(&init_on_free)) &&
1648 (slub_debug & SLAB_POISON))
1649 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1650 return 1;
1651 }
1652
1653 __setup("slub_debug", setup_slub_debug);
1654
1655 /*
1656 * kmem_cache_flags - apply debugging options to the cache
1657 * @object_size: the size of an object without meta data
1658 * @flags: flags to set
1659 * @name: name of the cache
1660 *
1661 * Debug option(s) are applied to @flags. In addition to the debug
1662 * option(s), if a slab name (or multiple) is specified i.e.
1663 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1664 * then only the select slabs will receive the debug option(s).
1665 */
kmem_cache_flags(unsigned int object_size,slab_flags_t flags,const char * name)1666 slab_flags_t kmem_cache_flags(unsigned int object_size,
1667 slab_flags_t flags, const char *name)
1668 {
1669 char *iter;
1670 size_t len;
1671 char *next_block;
1672 slab_flags_t block_flags;
1673 slab_flags_t slub_debug_local = slub_debug;
1674
1675 if (flags & SLAB_NO_USER_FLAGS)
1676 return flags;
1677
1678 /*
1679 * If the slab cache is for debugging (e.g. kmemleak) then
1680 * don't store user (stack trace) information by default,
1681 * but let the user enable it via the command line below.
1682 */
1683 if (flags & SLAB_NOLEAKTRACE)
1684 slub_debug_local &= ~SLAB_STORE_USER;
1685
1686 len = strlen(name);
1687 next_block = slub_debug_string;
1688 /* Go through all blocks of debug options, see if any matches our slab's name */
1689 while (next_block) {
1690 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1691 if (!iter)
1692 continue;
1693 /* Found a block that has a slab list, search it */
1694 while (*iter) {
1695 char *end, *glob;
1696 size_t cmplen;
1697
1698 end = strchrnul(iter, ',');
1699 if (next_block && next_block < end)
1700 end = next_block - 1;
1701
1702 glob = strnchr(iter, end - iter, '*');
1703 if (glob)
1704 cmplen = glob - iter;
1705 else
1706 cmplen = max_t(size_t, len, (end - iter));
1707
1708 if (!strncmp(name, iter, cmplen)) {
1709 flags |= block_flags;
1710 return flags;
1711 }
1712
1713 if (!*end || *end == ';')
1714 break;
1715 iter = end + 1;
1716 }
1717 }
1718
1719 return flags | slub_debug_local;
1720 }
1721 #else /* !CONFIG_SLUB_DEBUG */
setup_object_debug(struct kmem_cache * s,void * object)1722 static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
1723 static inline
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1724 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
1725
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1726 static inline bool alloc_debug_processing(struct kmem_cache *s,
1727 struct slab *slab, void *object, int orig_size) { return true; }
1728
free_debug_processing(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int * bulk_cnt,unsigned long addr,depot_stack_handle_t handle)1729 static inline bool free_debug_processing(struct kmem_cache *s,
1730 struct slab *slab, void *head, void *tail, int *bulk_cnt,
1731 unsigned long addr, depot_stack_handle_t handle) { return true; }
1732
slab_pad_check(struct kmem_cache * s,struct slab * slab)1733 static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
check_object(struct kmem_cache * s,struct slab * slab,void * object,u8 val)1734 static inline int check_object(struct kmem_cache *s, struct slab *slab,
1735 void *object, u8 val) { return 1; }
set_track_prepare(void)1736 static inline depot_stack_handle_t set_track_prepare(void) { return 0; }
set_track(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr)1737 static inline void set_track(struct kmem_cache *s, void *object,
1738 enum track_item alloc, unsigned long addr) {}
add_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1739 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1740 struct slab *slab) {}
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1741 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1742 struct slab *slab) {}
kmem_cache_flags(unsigned int object_size,slab_flags_t flags,const char * name)1743 slab_flags_t kmem_cache_flags(unsigned int object_size,
1744 slab_flags_t flags, const char *name)
1745 {
1746 return flags;
1747 }
1748 #define slub_debug 0
1749
1750 #define disable_higher_order_debug 0
1751
node_nr_slabs(struct kmem_cache_node * n)1752 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1753 { return 0; }
inc_slabs_node(struct kmem_cache * s,int node,int objects)1754 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1755 int objects) {}
dec_slabs_node(struct kmem_cache * s,int node,int objects)1756 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1757 int objects) {}
1758 #ifndef CONFIG_SLUB_TINY
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)1759 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1760 void **freelist, void *nextfree)
1761 {
1762 return false;
1763 }
1764 #endif
1765 #endif /* CONFIG_SLUB_DEBUG */
1766
1767 /*
1768 * Hooks for other subsystems that check memory allocations. In a typical
1769 * production configuration these hooks all should produce no code at all.
1770 */
slab_free_hook(struct kmem_cache * s,void * x,bool init)1771 static __always_inline bool slab_free_hook(struct kmem_cache *s,
1772 void *x, bool init)
1773 {
1774 kmemleak_free_recursive(x, s->flags);
1775 kmsan_slab_free(s, x);
1776
1777 debug_check_no_locks_freed(x, s->object_size);
1778
1779 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1780 debug_check_no_obj_freed(x, s->object_size);
1781
1782 /* Use KCSAN to help debug racy use-after-free. */
1783 if (!(s->flags & SLAB_TYPESAFE_BY_RCU))
1784 __kcsan_check_access(x, s->object_size,
1785 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
1786
1787 /*
1788 * As memory initialization might be integrated into KASAN,
1789 * kasan_slab_free and initialization memset's must be
1790 * kept together to avoid discrepancies in behavior.
1791 *
1792 * The initialization memset's clear the object and the metadata,
1793 * but don't touch the SLAB redzone.
1794 */
1795 if (init) {
1796 int rsize;
1797 unsigned int orig_size;
1798
1799 orig_size = get_orig_size(s, x);
1800 if (!kasan_has_integrated_init())
1801 memset(kasan_reset_tag(x), 0, orig_size);
1802 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
1803 memset((char *)kasan_reset_tag(x) + s->inuse, 0,
1804 s->size - s->inuse - rsize);
1805 /*
1806 * Restore orig_size, otherwize kmalloc redzone overwritten
1807 * would be reported
1808 */
1809 set_orig_size(s, x, orig_size);
1810 }
1811 /* KASAN might put x into memory quarantine, delaying its reuse. */
1812 return kasan_slab_free(s, x, init);
1813 }
1814
slab_free_freelist_hook(struct kmem_cache * s,void ** head,void ** tail,int * cnt)1815 static inline bool slab_free_freelist_hook(struct kmem_cache *s,
1816 void **head, void **tail,
1817 int *cnt)
1818 {
1819
1820 void *object;
1821 void *next = *head;
1822 void *old_tail = *tail ? *tail : *head;
1823
1824 if (is_kfence_address(next)) {
1825 slab_free_hook(s, next, false);
1826 return true;
1827 }
1828
1829 /* Head and tail of the reconstructed freelist */
1830 *head = NULL;
1831 *tail = NULL;
1832
1833 do {
1834 object = next;
1835 next = get_freepointer(s, object);
1836
1837 /* If object's reuse doesn't have to be delayed */
1838 if (!slab_free_hook(s, object, slab_want_init_on_free(s))) {
1839 /* Move object to the new freelist */
1840 set_freepointer(s, object, *head);
1841 *head = object;
1842 if (!*tail)
1843 *tail = object;
1844 } else {
1845 /*
1846 * Adjust the reconstructed freelist depth
1847 * accordingly if object's reuse is delayed.
1848 */
1849 --(*cnt);
1850 }
1851 } while (object != old_tail);
1852
1853 if (*head == *tail)
1854 *tail = NULL;
1855
1856 return *head != NULL;
1857 }
1858
setup_object(struct kmem_cache * s,void * object)1859 static void *setup_object(struct kmem_cache *s, void *object)
1860 {
1861 setup_object_debug(s, object);
1862 object = kasan_init_slab_obj(s, object);
1863 if (unlikely(s->ctor)) {
1864 kasan_unpoison_object_data(s, object);
1865 s->ctor(object);
1866 kasan_poison_object_data(s, object);
1867 }
1868 return object;
1869 }
1870
1871 /*
1872 * Slab allocation and freeing
1873 */
alloc_slab_page(gfp_t flags,int node,struct kmem_cache_order_objects oo)1874 static inline struct slab *alloc_slab_page(gfp_t flags, int node,
1875 struct kmem_cache_order_objects oo)
1876 {
1877 struct folio *folio;
1878 struct slab *slab;
1879 unsigned int order = oo_order(oo);
1880
1881 if (node == NUMA_NO_NODE)
1882 folio = (struct folio *)alloc_pages(flags, order);
1883 else
1884 folio = (struct folio *)__alloc_pages_node(node, flags, order);
1885
1886 if (!folio)
1887 return NULL;
1888
1889 slab = folio_slab(folio);
1890 __folio_set_slab(folio);
1891 /* Make the flag visible before any changes to folio->mapping */
1892 smp_wmb();
1893 if (folio_is_pfmemalloc(folio))
1894 slab_set_pfmemalloc(slab);
1895
1896 return slab;
1897 }
1898
1899 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1900 /* Pre-initialize the random sequence cache */
init_cache_random_seq(struct kmem_cache * s)1901 static int init_cache_random_seq(struct kmem_cache *s)
1902 {
1903 unsigned int count = oo_objects(s->oo);
1904 int err;
1905
1906 /* Bailout if already initialised */
1907 if (s->random_seq)
1908 return 0;
1909
1910 err = cache_random_seq_create(s, count, GFP_KERNEL);
1911 if (err) {
1912 pr_err("SLUB: Unable to initialize free list for %s\n",
1913 s->name);
1914 return err;
1915 }
1916
1917 /* Transform to an offset on the set of pages */
1918 if (s->random_seq) {
1919 unsigned int i;
1920
1921 for (i = 0; i < count; i++)
1922 s->random_seq[i] *= s->size;
1923 }
1924 return 0;
1925 }
1926
1927 /* Initialize each random sequence freelist per cache */
init_freelist_randomization(void)1928 static void __init init_freelist_randomization(void)
1929 {
1930 struct kmem_cache *s;
1931
1932 mutex_lock(&slab_mutex);
1933
1934 list_for_each_entry(s, &slab_caches, list)
1935 init_cache_random_seq(s);
1936
1937 mutex_unlock(&slab_mutex);
1938 }
1939
1940 /* Get the next entry on the pre-computed freelist randomized */
next_freelist_entry(struct kmem_cache * s,struct slab * slab,unsigned long * pos,void * start,unsigned long page_limit,unsigned long freelist_count)1941 static void *next_freelist_entry(struct kmem_cache *s, struct slab *slab,
1942 unsigned long *pos, void *start,
1943 unsigned long page_limit,
1944 unsigned long freelist_count)
1945 {
1946 unsigned int idx;
1947
1948 /*
1949 * If the target page allocation failed, the number of objects on the
1950 * page might be smaller than the usual size defined by the cache.
1951 */
1952 do {
1953 idx = s->random_seq[*pos];
1954 *pos += 1;
1955 if (*pos >= freelist_count)
1956 *pos = 0;
1957 } while (unlikely(idx >= page_limit));
1958
1959 return (char *)start + idx;
1960 }
1961
1962 /* Shuffle the single linked freelist based on a random pre-computed sequence */
shuffle_freelist(struct kmem_cache * s,struct slab * slab)1963 static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
1964 {
1965 void *start;
1966 void *cur;
1967 void *next;
1968 unsigned long idx, pos, page_limit, freelist_count;
1969
1970 if (slab->objects < 2 || !s->random_seq)
1971 return false;
1972
1973 freelist_count = oo_objects(s->oo);
1974 pos = get_random_u32_below(freelist_count);
1975
1976 page_limit = slab->objects * s->size;
1977 start = fixup_red_left(s, slab_address(slab));
1978
1979 /* First entry is used as the base of the freelist */
1980 cur = next_freelist_entry(s, slab, &pos, start, page_limit,
1981 freelist_count);
1982 cur = setup_object(s, cur);
1983 slab->freelist = cur;
1984
1985 for (idx = 1; idx < slab->objects; idx++) {
1986 next = next_freelist_entry(s, slab, &pos, start, page_limit,
1987 freelist_count);
1988 next = setup_object(s, next);
1989 set_freepointer(s, cur, next);
1990 cur = next;
1991 }
1992 set_freepointer(s, cur, NULL);
1993
1994 return true;
1995 }
1996 #else
init_cache_random_seq(struct kmem_cache * s)1997 static inline int init_cache_random_seq(struct kmem_cache *s)
1998 {
1999 return 0;
2000 }
init_freelist_randomization(void)2001 static inline void init_freelist_randomization(void) { }
shuffle_freelist(struct kmem_cache * s,struct slab * slab)2002 static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
2003 {
2004 return false;
2005 }
2006 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
2007
allocate_slab(struct kmem_cache * s,gfp_t flags,int node)2008 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
2009 {
2010 struct slab *slab;
2011 struct kmem_cache_order_objects oo = s->oo;
2012 gfp_t alloc_gfp;
2013 void *start, *p, *next;
2014 int idx;
2015 bool shuffle;
2016
2017 flags &= gfp_allowed_mask;
2018
2019 flags |= s->allocflags;
2020
2021 /*
2022 * Let the initial higher-order allocation fail under memory pressure
2023 * so we fall-back to the minimum order allocation.
2024 */
2025 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
2026 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
2027 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
2028
2029 slab = alloc_slab_page(alloc_gfp, node, oo);
2030 if (unlikely(!slab)) {
2031 oo = s->min;
2032 alloc_gfp = flags;
2033 /*
2034 * Allocation may have failed due to fragmentation.
2035 * Try a lower order alloc if possible
2036 */
2037 slab = alloc_slab_page(alloc_gfp, node, oo);
2038 if (unlikely(!slab))
2039 return NULL;
2040 stat(s, ORDER_FALLBACK);
2041 }
2042
2043 slab->objects = oo_objects(oo);
2044 slab->inuse = 0;
2045 slab->frozen = 0;
2046
2047 account_slab(slab, oo_order(oo), s, flags);
2048
2049 slab->slab_cache = s;
2050
2051 kasan_poison_slab(slab);
2052
2053 start = slab_address(slab);
2054
2055 setup_slab_debug(s, slab, start);
2056
2057 shuffle = shuffle_freelist(s, slab);
2058
2059 if (!shuffle) {
2060 start = fixup_red_left(s, start);
2061 start = setup_object(s, start);
2062 slab->freelist = start;
2063 for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
2064 next = p + s->size;
2065 next = setup_object(s, next);
2066 set_freepointer(s, p, next);
2067 p = next;
2068 }
2069 set_freepointer(s, p, NULL);
2070 }
2071
2072 return slab;
2073 }
2074
new_slab(struct kmem_cache * s,gfp_t flags,int node)2075 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
2076 {
2077 if (unlikely(flags & GFP_SLAB_BUG_MASK))
2078 flags = kmalloc_fix_flags(flags);
2079
2080 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2081
2082 return allocate_slab(s,
2083 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
2084 }
2085
__free_slab(struct kmem_cache * s,struct slab * slab)2086 static void __free_slab(struct kmem_cache *s, struct slab *slab)
2087 {
2088 struct folio *folio = slab_folio(slab);
2089 int order = folio_order(folio);
2090 int pages = 1 << order;
2091
2092 __slab_clear_pfmemalloc(slab);
2093 folio->mapping = NULL;
2094 /* Make the mapping reset visible before clearing the flag */
2095 smp_wmb();
2096 __folio_clear_slab(folio);
2097 mm_account_reclaimed_pages(pages);
2098 unaccount_slab(slab, order, s);
2099 __free_pages(&folio->page, order);
2100 }
2101
rcu_free_slab(struct rcu_head * h)2102 static void rcu_free_slab(struct rcu_head *h)
2103 {
2104 struct slab *slab = container_of(h, struct slab, rcu_head);
2105
2106 __free_slab(slab->slab_cache, slab);
2107 }
2108
free_slab(struct kmem_cache * s,struct slab * slab)2109 static void free_slab(struct kmem_cache *s, struct slab *slab)
2110 {
2111 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
2112 void *p;
2113
2114 slab_pad_check(s, slab);
2115 for_each_object(p, s, slab_address(slab), slab->objects)
2116 check_object(s, slab, p, SLUB_RED_INACTIVE);
2117 }
2118
2119 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
2120 call_rcu(&slab->rcu_head, rcu_free_slab);
2121 else
2122 __free_slab(s, slab);
2123 }
2124
discard_slab(struct kmem_cache * s,struct slab * slab)2125 static void discard_slab(struct kmem_cache *s, struct slab *slab)
2126 {
2127 dec_slabs_node(s, slab_nid(slab), slab->objects);
2128 free_slab(s, slab);
2129 }
2130
2131 /*
2132 * Management of partially allocated slabs.
2133 */
2134 static inline void
__add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)2135 __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
2136 {
2137 n->nr_partial++;
2138 if (tail == DEACTIVATE_TO_TAIL)
2139 list_add_tail(&slab->slab_list, &n->partial);
2140 else
2141 list_add(&slab->slab_list, &n->partial);
2142 }
2143
add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)2144 static inline void add_partial(struct kmem_cache_node *n,
2145 struct slab *slab, int tail)
2146 {
2147 lockdep_assert_held(&n->list_lock);
2148 __add_partial(n, slab, tail);
2149 }
2150
remove_partial(struct kmem_cache_node * n,struct slab * slab)2151 static inline void remove_partial(struct kmem_cache_node *n,
2152 struct slab *slab)
2153 {
2154 lockdep_assert_held(&n->list_lock);
2155 list_del(&slab->slab_list);
2156 n->nr_partial--;
2157 }
2158
2159 /*
2160 * Called only for kmem_cache_debug() caches instead of acquire_slab(), with a
2161 * slab from the n->partial list. Remove only a single object from the slab, do
2162 * the alloc_debug_processing() checks and leave the slab on the list, or move
2163 * it to full list if it was the last free object.
2164 */
alloc_single_from_partial(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab,int orig_size)2165 static void *alloc_single_from_partial(struct kmem_cache *s,
2166 struct kmem_cache_node *n, struct slab *slab, int orig_size)
2167 {
2168 void *object;
2169
2170 lockdep_assert_held(&n->list_lock);
2171
2172 object = slab->freelist;
2173 slab->freelist = get_freepointer(s, object);
2174 slab->inuse++;
2175
2176 if (!alloc_debug_processing(s, slab, object, orig_size)) {
2177 if (folio_test_slab(slab_folio(slab)))
2178 remove_partial(n, slab);
2179 return NULL;
2180 }
2181
2182 if (slab->inuse == slab->objects) {
2183 remove_partial(n, slab);
2184 add_full(s, n, slab);
2185 }
2186
2187 return object;
2188 }
2189
2190 /*
2191 * Called only for kmem_cache_debug() caches to allocate from a freshly
2192 * allocated slab. Allocate a single object instead of whole freelist
2193 * and put the slab to the partial (or full) list.
2194 */
alloc_single_from_new_slab(struct kmem_cache * s,struct slab * slab,int orig_size)2195 static void *alloc_single_from_new_slab(struct kmem_cache *s,
2196 struct slab *slab, int orig_size)
2197 {
2198 int nid = slab_nid(slab);
2199 struct kmem_cache_node *n = get_node(s, nid);
2200 unsigned long flags;
2201 void *object;
2202
2203
2204 object = slab->freelist;
2205 slab->freelist = get_freepointer(s, object);
2206 slab->inuse = 1;
2207
2208 if (!alloc_debug_processing(s, slab, object, orig_size))
2209 /*
2210 * It's not really expected that this would fail on a
2211 * freshly allocated slab, but a concurrent memory
2212 * corruption in theory could cause that.
2213 */
2214 return NULL;
2215
2216 spin_lock_irqsave(&n->list_lock, flags);
2217
2218 if (slab->inuse == slab->objects)
2219 add_full(s, n, slab);
2220 else
2221 add_partial(n, slab, DEACTIVATE_TO_HEAD);
2222
2223 inc_slabs_node(s, nid, slab->objects);
2224 spin_unlock_irqrestore(&n->list_lock, flags);
2225
2226 return object;
2227 }
2228
2229 /*
2230 * Remove slab from the partial list, freeze it and
2231 * return the pointer to the freelist.
2232 *
2233 * Returns a list of objects or NULL if it fails.
2234 */
acquire_slab(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab,int mode)2235 static inline void *acquire_slab(struct kmem_cache *s,
2236 struct kmem_cache_node *n, struct slab *slab,
2237 int mode)
2238 {
2239 void *freelist;
2240 unsigned long counters;
2241 struct slab new;
2242
2243 lockdep_assert_held(&n->list_lock);
2244
2245 /*
2246 * Zap the freelist and set the frozen bit.
2247 * The old freelist is the list of objects for the
2248 * per cpu allocation list.
2249 */
2250 freelist = slab->freelist;
2251 counters = slab->counters;
2252 new.counters = counters;
2253 if (mode) {
2254 new.inuse = slab->objects;
2255 new.freelist = NULL;
2256 } else {
2257 new.freelist = freelist;
2258 }
2259
2260 VM_BUG_ON(new.frozen);
2261 new.frozen = 1;
2262
2263 if (!__slab_update_freelist(s, slab,
2264 freelist, counters,
2265 new.freelist, new.counters,
2266 "acquire_slab"))
2267 return NULL;
2268
2269 remove_partial(n, slab);
2270 WARN_ON(!freelist);
2271 return freelist;
2272 }
2273
2274 #ifdef CONFIG_SLUB_CPU_PARTIAL
2275 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
2276 #else
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)2277 static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
2278 int drain) { }
2279 #endif
2280 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
2281
2282 /*
2283 * Try to allocate a partial slab from a specific node.
2284 */
get_partial_node(struct kmem_cache * s,struct kmem_cache_node * n,struct partial_context * pc)2285 static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
2286 struct partial_context *pc)
2287 {
2288 struct slab *slab, *slab2;
2289 void *object = NULL;
2290 unsigned long flags;
2291 unsigned int partial_slabs = 0;
2292
2293 /*
2294 * Racy check. If we mistakenly see no partial slabs then we
2295 * just allocate an empty slab. If we mistakenly try to get a
2296 * partial slab and there is none available then get_partial()
2297 * will return NULL.
2298 */
2299 if (!n || !n->nr_partial)
2300 return NULL;
2301
2302 spin_lock_irqsave(&n->list_lock, flags);
2303 list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
2304 void *t;
2305
2306 if (!pfmemalloc_match(slab, pc->flags))
2307 continue;
2308
2309 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
2310 object = alloc_single_from_partial(s, n, slab,
2311 pc->orig_size);
2312 if (object)
2313 break;
2314 continue;
2315 }
2316
2317 t = acquire_slab(s, n, slab, object == NULL);
2318 if (!t)
2319 break;
2320
2321 if (!object) {
2322 *pc->slab = slab;
2323 stat(s, ALLOC_FROM_PARTIAL);
2324 object = t;
2325 } else {
2326 put_cpu_partial(s, slab, 0);
2327 stat(s, CPU_PARTIAL_NODE);
2328 partial_slabs++;
2329 }
2330 #ifdef CONFIG_SLUB_CPU_PARTIAL
2331 if (!kmem_cache_has_cpu_partial(s)
2332 || partial_slabs > s->cpu_partial_slabs / 2)
2333 break;
2334 #else
2335 break;
2336 #endif
2337
2338 }
2339 spin_unlock_irqrestore(&n->list_lock, flags);
2340 return object;
2341 }
2342
2343 /*
2344 * Get a slab from somewhere. Search in increasing NUMA distances.
2345 */
get_any_partial(struct kmem_cache * s,struct partial_context * pc)2346 static void *get_any_partial(struct kmem_cache *s, struct partial_context *pc)
2347 {
2348 #ifdef CONFIG_NUMA
2349 struct zonelist *zonelist;
2350 struct zoneref *z;
2351 struct zone *zone;
2352 enum zone_type highest_zoneidx = gfp_zone(pc->flags);
2353 void *object;
2354 unsigned int cpuset_mems_cookie;
2355
2356 /*
2357 * The defrag ratio allows a configuration of the tradeoffs between
2358 * inter node defragmentation and node local allocations. A lower
2359 * defrag_ratio increases the tendency to do local allocations
2360 * instead of attempting to obtain partial slabs from other nodes.
2361 *
2362 * If the defrag_ratio is set to 0 then kmalloc() always
2363 * returns node local objects. If the ratio is higher then kmalloc()
2364 * may return off node objects because partial slabs are obtained
2365 * from other nodes and filled up.
2366 *
2367 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2368 * (which makes defrag_ratio = 1000) then every (well almost)
2369 * allocation will first attempt to defrag slab caches on other nodes.
2370 * This means scanning over all nodes to look for partial slabs which
2371 * may be expensive if we do it every time we are trying to find a slab
2372 * with available objects.
2373 */
2374 if (!s->remote_node_defrag_ratio ||
2375 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2376 return NULL;
2377
2378 do {
2379 cpuset_mems_cookie = read_mems_allowed_begin();
2380 zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
2381 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2382 struct kmem_cache_node *n;
2383
2384 n = get_node(s, zone_to_nid(zone));
2385
2386 if (n && cpuset_zone_allowed(zone, pc->flags) &&
2387 n->nr_partial > s->min_partial) {
2388 object = get_partial_node(s, n, pc);
2389 if (object) {
2390 /*
2391 * Don't check read_mems_allowed_retry()
2392 * here - if mems_allowed was updated in
2393 * parallel, that was a harmless race
2394 * between allocation and the cpuset
2395 * update
2396 */
2397 return object;
2398 }
2399 }
2400 }
2401 } while (read_mems_allowed_retry(cpuset_mems_cookie));
2402 #endif /* CONFIG_NUMA */
2403 return NULL;
2404 }
2405
2406 /*
2407 * Get a partial slab, lock it and return it.
2408 */
get_partial(struct kmem_cache * s,int node,struct partial_context * pc)2409 static void *get_partial(struct kmem_cache *s, int node, struct partial_context *pc)
2410 {
2411 void *object;
2412 int searchnode = node;
2413
2414 if (node == NUMA_NO_NODE)
2415 searchnode = numa_mem_id();
2416
2417 object = get_partial_node(s, get_node(s, searchnode), pc);
2418 if (object || node != NUMA_NO_NODE)
2419 return object;
2420
2421 return get_any_partial(s, pc);
2422 }
2423
2424 #ifndef CONFIG_SLUB_TINY
2425
2426 #ifdef CONFIG_PREEMPTION
2427 /*
2428 * Calculate the next globally unique transaction for disambiguation
2429 * during cmpxchg. The transactions start with the cpu number and are then
2430 * incremented by CONFIG_NR_CPUS.
2431 */
2432 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2433 #else
2434 /*
2435 * No preemption supported therefore also no need to check for
2436 * different cpus.
2437 */
2438 #define TID_STEP 1
2439 #endif /* CONFIG_PREEMPTION */
2440
next_tid(unsigned long tid)2441 static inline unsigned long next_tid(unsigned long tid)
2442 {
2443 return tid + TID_STEP;
2444 }
2445
2446 #ifdef SLUB_DEBUG_CMPXCHG
tid_to_cpu(unsigned long tid)2447 static inline unsigned int tid_to_cpu(unsigned long tid)
2448 {
2449 return tid % TID_STEP;
2450 }
2451
tid_to_event(unsigned long tid)2452 static inline unsigned long tid_to_event(unsigned long tid)
2453 {
2454 return tid / TID_STEP;
2455 }
2456 #endif
2457
init_tid(int cpu)2458 static inline unsigned int init_tid(int cpu)
2459 {
2460 return cpu;
2461 }
2462
note_cmpxchg_failure(const char * n,const struct kmem_cache * s,unsigned long tid)2463 static inline void note_cmpxchg_failure(const char *n,
2464 const struct kmem_cache *s, unsigned long tid)
2465 {
2466 #ifdef SLUB_DEBUG_CMPXCHG
2467 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2468
2469 pr_info("%s %s: cmpxchg redo ", n, s->name);
2470
2471 #ifdef CONFIG_PREEMPTION
2472 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
2473 pr_warn("due to cpu change %d -> %d\n",
2474 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2475 else
2476 #endif
2477 if (tid_to_event(tid) != tid_to_event(actual_tid))
2478 pr_warn("due to cpu running other code. Event %ld->%ld\n",
2479 tid_to_event(tid), tid_to_event(actual_tid));
2480 else
2481 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
2482 actual_tid, tid, next_tid(tid));
2483 #endif
2484 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
2485 }
2486
init_kmem_cache_cpus(struct kmem_cache * s)2487 static void init_kmem_cache_cpus(struct kmem_cache *s)
2488 {
2489 int cpu;
2490 struct kmem_cache_cpu *c;
2491
2492 for_each_possible_cpu(cpu) {
2493 c = per_cpu_ptr(s->cpu_slab, cpu);
2494 local_lock_init(&c->lock);
2495 c->tid = init_tid(cpu);
2496 }
2497 }
2498
2499 /*
2500 * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
2501 * unfreezes the slabs and puts it on the proper list.
2502 * Assumes the slab has been already safely taken away from kmem_cache_cpu
2503 * by the caller.
2504 */
deactivate_slab(struct kmem_cache * s,struct slab * slab,void * freelist)2505 static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
2506 void *freelist)
2507 {
2508 enum slab_modes { M_NONE, M_PARTIAL, M_FREE, M_FULL_NOLIST };
2509 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
2510 int free_delta = 0;
2511 enum slab_modes mode = M_NONE;
2512 void *nextfree, *freelist_iter, *freelist_tail;
2513 int tail = DEACTIVATE_TO_HEAD;
2514 unsigned long flags = 0;
2515 struct slab new;
2516 struct slab old;
2517
2518 if (slab->freelist) {
2519 stat(s, DEACTIVATE_REMOTE_FREES);
2520 tail = DEACTIVATE_TO_TAIL;
2521 }
2522
2523 /*
2524 * Stage one: Count the objects on cpu's freelist as free_delta and
2525 * remember the last object in freelist_tail for later splicing.
2526 */
2527 freelist_tail = NULL;
2528 freelist_iter = freelist;
2529 while (freelist_iter) {
2530 nextfree = get_freepointer(s, freelist_iter);
2531
2532 /*
2533 * If 'nextfree' is invalid, it is possible that the object at
2534 * 'freelist_iter' is already corrupted. So isolate all objects
2535 * starting at 'freelist_iter' by skipping them.
2536 */
2537 if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
2538 break;
2539
2540 freelist_tail = freelist_iter;
2541 free_delta++;
2542
2543 freelist_iter = nextfree;
2544 }
2545
2546 /*
2547 * Stage two: Unfreeze the slab while splicing the per-cpu
2548 * freelist to the head of slab's freelist.
2549 *
2550 * Ensure that the slab is unfrozen while the list presence
2551 * reflects the actual number of objects during unfreeze.
2552 *
2553 * We first perform cmpxchg holding lock and insert to list
2554 * when it succeed. If there is mismatch then the slab is not
2555 * unfrozen and number of objects in the slab may have changed.
2556 * Then release lock and retry cmpxchg again.
2557 */
2558 redo:
2559
2560 old.freelist = READ_ONCE(slab->freelist);
2561 old.counters = READ_ONCE(slab->counters);
2562 VM_BUG_ON(!old.frozen);
2563
2564 /* Determine target state of the slab */
2565 new.counters = old.counters;
2566 if (freelist_tail) {
2567 new.inuse -= free_delta;
2568 set_freepointer(s, freelist_tail, old.freelist);
2569 new.freelist = freelist;
2570 } else
2571 new.freelist = old.freelist;
2572
2573 new.frozen = 0;
2574
2575 if (!new.inuse && n->nr_partial >= s->min_partial) {
2576 mode = M_FREE;
2577 } else if (new.freelist) {
2578 mode = M_PARTIAL;
2579 /*
2580 * Taking the spinlock removes the possibility that
2581 * acquire_slab() will see a slab that is frozen
2582 */
2583 spin_lock_irqsave(&n->list_lock, flags);
2584 } else {
2585 mode = M_FULL_NOLIST;
2586 }
2587
2588
2589 if (!slab_update_freelist(s, slab,
2590 old.freelist, old.counters,
2591 new.freelist, new.counters,
2592 "unfreezing slab")) {
2593 if (mode == M_PARTIAL)
2594 spin_unlock_irqrestore(&n->list_lock, flags);
2595 goto redo;
2596 }
2597
2598
2599 if (mode == M_PARTIAL) {
2600 add_partial(n, slab, tail);
2601 spin_unlock_irqrestore(&n->list_lock, flags);
2602 stat(s, tail);
2603 } else if (mode == M_FREE) {
2604 stat(s, DEACTIVATE_EMPTY);
2605 discard_slab(s, slab);
2606 stat(s, FREE_SLAB);
2607 } else if (mode == M_FULL_NOLIST) {
2608 stat(s, DEACTIVATE_FULL);
2609 }
2610 }
2611
2612 #ifdef CONFIG_SLUB_CPU_PARTIAL
__unfreeze_partials(struct kmem_cache * s,struct slab * partial_slab)2613 static void __unfreeze_partials(struct kmem_cache *s, struct slab *partial_slab)
2614 {
2615 struct kmem_cache_node *n = NULL, *n2 = NULL;
2616 struct slab *slab, *slab_to_discard = NULL;
2617 unsigned long flags = 0;
2618
2619 while (partial_slab) {
2620 struct slab new;
2621 struct slab old;
2622
2623 slab = partial_slab;
2624 partial_slab = slab->next;
2625
2626 n2 = get_node(s, slab_nid(slab));
2627 if (n != n2) {
2628 if (n)
2629 spin_unlock_irqrestore(&n->list_lock, flags);
2630
2631 n = n2;
2632 spin_lock_irqsave(&n->list_lock, flags);
2633 }
2634
2635 do {
2636
2637 old.freelist = slab->freelist;
2638 old.counters = slab->counters;
2639 VM_BUG_ON(!old.frozen);
2640
2641 new.counters = old.counters;
2642 new.freelist = old.freelist;
2643
2644 new.frozen = 0;
2645
2646 } while (!__slab_update_freelist(s, slab,
2647 old.freelist, old.counters,
2648 new.freelist, new.counters,
2649 "unfreezing slab"));
2650
2651 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
2652 slab->next = slab_to_discard;
2653 slab_to_discard = slab;
2654 } else {
2655 add_partial(n, slab, DEACTIVATE_TO_TAIL);
2656 stat(s, FREE_ADD_PARTIAL);
2657 }
2658 }
2659
2660 if (n)
2661 spin_unlock_irqrestore(&n->list_lock, flags);
2662
2663 while (slab_to_discard) {
2664 slab = slab_to_discard;
2665 slab_to_discard = slab_to_discard->next;
2666
2667 stat(s, DEACTIVATE_EMPTY);
2668 discard_slab(s, slab);
2669 stat(s, FREE_SLAB);
2670 }
2671 }
2672
2673 /*
2674 * Unfreeze all the cpu partial slabs.
2675 */
unfreeze_partials(struct kmem_cache * s)2676 static void unfreeze_partials(struct kmem_cache *s)
2677 {
2678 struct slab *partial_slab;
2679 unsigned long flags;
2680
2681 local_lock_irqsave(&s->cpu_slab->lock, flags);
2682 partial_slab = this_cpu_read(s->cpu_slab->partial);
2683 this_cpu_write(s->cpu_slab->partial, NULL);
2684 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
2685
2686 if (partial_slab)
2687 __unfreeze_partials(s, partial_slab);
2688 }
2689
unfreeze_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)2690 static void unfreeze_partials_cpu(struct kmem_cache *s,
2691 struct kmem_cache_cpu *c)
2692 {
2693 struct slab *partial_slab;
2694
2695 partial_slab = slub_percpu_partial(c);
2696 c->partial = NULL;
2697
2698 if (partial_slab)
2699 __unfreeze_partials(s, partial_slab);
2700 }
2701
2702 /*
2703 * Put a slab that was just frozen (in __slab_free|get_partial_node) into a
2704 * partial slab slot if available.
2705 *
2706 * If we did not find a slot then simply move all the partials to the
2707 * per node partial list.
2708 */
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)2709 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
2710 {
2711 struct slab *oldslab;
2712 struct slab *slab_to_unfreeze = NULL;
2713 unsigned long flags;
2714 int slabs = 0;
2715
2716 local_lock_irqsave(&s->cpu_slab->lock, flags);
2717
2718 oldslab = this_cpu_read(s->cpu_slab->partial);
2719
2720 if (oldslab) {
2721 if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
2722 /*
2723 * Partial array is full. Move the existing set to the
2724 * per node partial list. Postpone the actual unfreezing
2725 * outside of the critical section.
2726 */
2727 slab_to_unfreeze = oldslab;
2728 oldslab = NULL;
2729 } else {
2730 slabs = oldslab->slabs;
2731 }
2732 }
2733
2734 slabs++;
2735
2736 slab->slabs = slabs;
2737 slab->next = oldslab;
2738
2739 this_cpu_write(s->cpu_slab->partial, slab);
2740
2741 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
2742
2743 if (slab_to_unfreeze) {
2744 __unfreeze_partials(s, slab_to_unfreeze);
2745 stat(s, CPU_PARTIAL_DRAIN);
2746 }
2747 }
2748
2749 #else /* CONFIG_SLUB_CPU_PARTIAL */
2750
unfreeze_partials(struct kmem_cache * s)2751 static inline void unfreeze_partials(struct kmem_cache *s) { }
unfreeze_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)2752 static inline void unfreeze_partials_cpu(struct kmem_cache *s,
2753 struct kmem_cache_cpu *c) { }
2754
2755 #endif /* CONFIG_SLUB_CPU_PARTIAL */
2756
flush_slab(struct kmem_cache * s,struct kmem_cache_cpu * c)2757 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2758 {
2759 unsigned long flags;
2760 struct slab *slab;
2761 void *freelist;
2762
2763 local_lock_irqsave(&s->cpu_slab->lock, flags);
2764
2765 slab = c->slab;
2766 freelist = c->freelist;
2767
2768 c->slab = NULL;
2769 c->freelist = NULL;
2770 c->tid = next_tid(c->tid);
2771
2772 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
2773
2774 if (slab) {
2775 deactivate_slab(s, slab, freelist);
2776 stat(s, CPUSLAB_FLUSH);
2777 }
2778 }
2779
__flush_cpu_slab(struct kmem_cache * s,int cpu)2780 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2781 {
2782 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2783 void *freelist = c->freelist;
2784 struct slab *slab = c->slab;
2785
2786 c->slab = NULL;
2787 c->freelist = NULL;
2788 c->tid = next_tid(c->tid);
2789
2790 if (slab) {
2791 deactivate_slab(s, slab, freelist);
2792 stat(s, CPUSLAB_FLUSH);
2793 }
2794
2795 unfreeze_partials_cpu(s, c);
2796 }
2797
2798 struct slub_flush_work {
2799 struct work_struct work;
2800 struct kmem_cache *s;
2801 bool skip;
2802 };
2803
2804 /*
2805 * Flush cpu slab.
2806 *
2807 * Called from CPU work handler with migration disabled.
2808 */
flush_cpu_slab(struct work_struct * w)2809 static void flush_cpu_slab(struct work_struct *w)
2810 {
2811 struct kmem_cache *s;
2812 struct kmem_cache_cpu *c;
2813 struct slub_flush_work *sfw;
2814
2815 sfw = container_of(w, struct slub_flush_work, work);
2816
2817 s = sfw->s;
2818 c = this_cpu_ptr(s->cpu_slab);
2819
2820 if (c->slab)
2821 flush_slab(s, c);
2822
2823 unfreeze_partials(s);
2824 }
2825
has_cpu_slab(int cpu,struct kmem_cache * s)2826 static bool has_cpu_slab(int cpu, struct kmem_cache *s)
2827 {
2828 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2829
2830 return c->slab || slub_percpu_partial(c);
2831 }
2832
2833 static DEFINE_MUTEX(flush_lock);
2834 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
2835
flush_all_cpus_locked(struct kmem_cache * s)2836 static void flush_all_cpus_locked(struct kmem_cache *s)
2837 {
2838 struct slub_flush_work *sfw;
2839 unsigned int cpu;
2840
2841 lockdep_assert_cpus_held();
2842 mutex_lock(&flush_lock);
2843
2844 for_each_online_cpu(cpu) {
2845 sfw = &per_cpu(slub_flush, cpu);
2846 if (!has_cpu_slab(cpu, s)) {
2847 sfw->skip = true;
2848 continue;
2849 }
2850 INIT_WORK(&sfw->work, flush_cpu_slab);
2851 sfw->skip = false;
2852 sfw->s = s;
2853 queue_work_on(cpu, flushwq, &sfw->work);
2854 }
2855
2856 for_each_online_cpu(cpu) {
2857 sfw = &per_cpu(slub_flush, cpu);
2858 if (sfw->skip)
2859 continue;
2860 flush_work(&sfw->work);
2861 }
2862
2863 mutex_unlock(&flush_lock);
2864 }
2865
flush_all(struct kmem_cache * s)2866 static void flush_all(struct kmem_cache *s)
2867 {
2868 cpus_read_lock();
2869 flush_all_cpus_locked(s);
2870 cpus_read_unlock();
2871 }
2872
2873 /*
2874 * Use the cpu notifier to insure that the cpu slabs are flushed when
2875 * necessary.
2876 */
slub_cpu_dead(unsigned int cpu)2877 static int slub_cpu_dead(unsigned int cpu)
2878 {
2879 struct kmem_cache *s;
2880
2881 mutex_lock(&slab_mutex);
2882 list_for_each_entry(s, &slab_caches, list)
2883 __flush_cpu_slab(s, cpu);
2884 mutex_unlock(&slab_mutex);
2885 return 0;
2886 }
2887
2888 #else /* CONFIG_SLUB_TINY */
flush_all_cpus_locked(struct kmem_cache * s)2889 static inline void flush_all_cpus_locked(struct kmem_cache *s) { }
flush_all(struct kmem_cache * s)2890 static inline void flush_all(struct kmem_cache *s) { }
__flush_cpu_slab(struct kmem_cache * s,int cpu)2891 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { }
slub_cpu_dead(unsigned int cpu)2892 static inline int slub_cpu_dead(unsigned int cpu) { return 0; }
2893 #endif /* CONFIG_SLUB_TINY */
2894
2895 /*
2896 * Check if the objects in a per cpu structure fit numa
2897 * locality expectations.
2898 */
node_match(struct slab * slab,int node)2899 static inline int node_match(struct slab *slab, int node)
2900 {
2901 #ifdef CONFIG_NUMA
2902 if (node != NUMA_NO_NODE && slab_nid(slab) != node)
2903 return 0;
2904 #endif
2905 return 1;
2906 }
2907
2908 #ifdef CONFIG_SLUB_DEBUG
count_free(struct slab * slab)2909 static int count_free(struct slab *slab)
2910 {
2911 return slab->objects - slab->inuse;
2912 }
2913
node_nr_objs(struct kmem_cache_node * n)2914 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2915 {
2916 return atomic_long_read(&n->total_objects);
2917 }
2918
2919 /* Supports checking bulk free of a constructed freelist */
free_debug_processing(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int * bulk_cnt,unsigned long addr,depot_stack_handle_t handle)2920 static inline bool free_debug_processing(struct kmem_cache *s,
2921 struct slab *slab, void *head, void *tail, int *bulk_cnt,
2922 unsigned long addr, depot_stack_handle_t handle)
2923 {
2924 bool checks_ok = false;
2925 void *object = head;
2926 int cnt = 0;
2927
2928 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
2929 if (!check_slab(s, slab))
2930 goto out;
2931 }
2932
2933 if (slab->inuse < *bulk_cnt) {
2934 slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
2935 slab->inuse, *bulk_cnt);
2936 goto out;
2937 }
2938
2939 next_object:
2940
2941 if (++cnt > *bulk_cnt)
2942 goto out_cnt;
2943
2944 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
2945 if (!free_consistency_checks(s, slab, object, addr))
2946 goto out;
2947 }
2948
2949 if (s->flags & SLAB_STORE_USER)
2950 set_track_update(s, object, TRACK_FREE, addr, handle);
2951 trace(s, slab, object, 0);
2952 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
2953 init_object(s, object, SLUB_RED_INACTIVE);
2954
2955 /* Reached end of constructed freelist yet? */
2956 if (object != tail) {
2957 object = get_freepointer(s, object);
2958 goto next_object;
2959 }
2960 checks_ok = true;
2961
2962 out_cnt:
2963 if (cnt != *bulk_cnt) {
2964 slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
2965 *bulk_cnt, cnt);
2966 *bulk_cnt = cnt;
2967 }
2968
2969 out:
2970
2971 if (!checks_ok)
2972 slab_fix(s, "Object at 0x%p not freed", object);
2973
2974 return checks_ok;
2975 }
2976 #endif /* CONFIG_SLUB_DEBUG */
2977
2978 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
count_partial(struct kmem_cache_node * n,int (* get_count)(struct slab *))2979 static unsigned long count_partial(struct kmem_cache_node *n,
2980 int (*get_count)(struct slab *))
2981 {
2982 unsigned long flags;
2983 unsigned long x = 0;
2984 struct slab *slab;
2985
2986 spin_lock_irqsave(&n->list_lock, flags);
2987 list_for_each_entry(slab, &n->partial, slab_list)
2988 x += get_count(slab);
2989 spin_unlock_irqrestore(&n->list_lock, flags);
2990 return x;
2991 }
2992 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
2993
2994 #ifdef CONFIG_SLUB_DEBUG
2995 static noinline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)2996 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2997 {
2998 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2999 DEFAULT_RATELIMIT_BURST);
3000 int node;
3001 struct kmem_cache_node *n;
3002
3003 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
3004 return;
3005
3006 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
3007 nid, gfpflags, &gfpflags);
3008 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
3009 s->name, s->object_size, s->size, oo_order(s->oo),
3010 oo_order(s->min));
3011
3012 if (oo_order(s->min) > get_order(s->object_size))
3013 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
3014 s->name);
3015
3016 for_each_kmem_cache_node(s, node, n) {
3017 unsigned long nr_slabs;
3018 unsigned long nr_objs;
3019 unsigned long nr_free;
3020
3021 nr_free = count_partial(n, count_free);
3022 nr_slabs = node_nr_slabs(n);
3023 nr_objs = node_nr_objs(n);
3024
3025 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
3026 node, nr_slabs, nr_objs, nr_free);
3027 }
3028 }
3029 #else /* CONFIG_SLUB_DEBUG */
3030 static inline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)3031 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
3032 #endif
3033
pfmemalloc_match(struct slab * slab,gfp_t gfpflags)3034 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
3035 {
3036 if (unlikely(slab_test_pfmemalloc(slab)))
3037 return gfp_pfmemalloc_allowed(gfpflags);
3038
3039 return true;
3040 }
3041
3042 #ifndef CONFIG_SLUB_TINY
3043 static inline bool
__update_cpu_freelist_fast(struct kmem_cache * s,void * freelist_old,void * freelist_new,unsigned long tid)3044 __update_cpu_freelist_fast(struct kmem_cache *s,
3045 void *freelist_old, void *freelist_new,
3046 unsigned long tid)
3047 {
3048 freelist_aba_t old = { .freelist = freelist_old, .counter = tid };
3049 freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) };
3050
3051 return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full,
3052 &old.full, new.full);
3053 }
3054
3055 /*
3056 * Check the slab->freelist and either transfer the freelist to the
3057 * per cpu freelist or deactivate the slab.
3058 *
3059 * The slab is still frozen if the return value is not NULL.
3060 *
3061 * If this function returns NULL then the slab has been unfrozen.
3062 */
get_freelist(struct kmem_cache * s,struct slab * slab)3063 static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
3064 {
3065 struct slab new;
3066 unsigned long counters;
3067 void *freelist;
3068
3069 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3070
3071 do {
3072 freelist = slab->freelist;
3073 counters = slab->counters;
3074
3075 new.counters = counters;
3076 VM_BUG_ON(!new.frozen);
3077
3078 new.inuse = slab->objects;
3079 new.frozen = freelist != NULL;
3080
3081 } while (!__slab_update_freelist(s, slab,
3082 freelist, counters,
3083 NULL, new.counters,
3084 "get_freelist"));
3085
3086 return freelist;
3087 }
3088
3089 /*
3090 * Slow path. The lockless freelist is empty or we need to perform
3091 * debugging duties.
3092 *
3093 * Processing is still very fast if new objects have been freed to the
3094 * regular freelist. In that case we simply take over the regular freelist
3095 * as the lockless freelist and zap the regular freelist.
3096 *
3097 * If that is not working then we fall back to the partial lists. We take the
3098 * first element of the freelist as the object to allocate now and move the
3099 * rest of the freelist to the lockless freelist.
3100 *
3101 * And if we were unable to get a new slab from the partial slab lists then
3102 * we need to allocate a new slab. This is the slowest path since it involves
3103 * a call to the page allocator and the setup of a new slab.
3104 *
3105 * Version of __slab_alloc to use when we know that preemption is
3106 * already disabled (which is the case for bulk allocation).
3107 */
___slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)3108 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3109 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3110 {
3111 void *freelist;
3112 struct slab *slab;
3113 unsigned long flags;
3114 struct partial_context pc;
3115
3116 stat(s, ALLOC_SLOWPATH);
3117
3118 reread_slab:
3119
3120 slab = READ_ONCE(c->slab);
3121 if (!slab) {
3122 /*
3123 * if the node is not online or has no normal memory, just
3124 * ignore the node constraint
3125 */
3126 if (unlikely(node != NUMA_NO_NODE &&
3127 !node_isset(node, slab_nodes)))
3128 node = NUMA_NO_NODE;
3129 goto new_slab;
3130 }
3131 redo:
3132
3133 if (unlikely(!node_match(slab, node))) {
3134 /*
3135 * same as above but node_match() being false already
3136 * implies node != NUMA_NO_NODE
3137 */
3138 if (!node_isset(node, slab_nodes)) {
3139 node = NUMA_NO_NODE;
3140 } else {
3141 stat(s, ALLOC_NODE_MISMATCH);
3142 goto deactivate_slab;
3143 }
3144 }
3145
3146 /*
3147 * By rights, we should be searching for a slab page that was
3148 * PFMEMALLOC but right now, we are losing the pfmemalloc
3149 * information when the page leaves the per-cpu allocator
3150 */
3151 if (unlikely(!pfmemalloc_match(slab, gfpflags)))
3152 goto deactivate_slab;
3153
3154 /* must check again c->slab in case we got preempted and it changed */
3155 local_lock_irqsave(&s->cpu_slab->lock, flags);
3156 if (unlikely(slab != c->slab)) {
3157 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3158 goto reread_slab;
3159 }
3160 freelist = c->freelist;
3161 if (freelist)
3162 goto load_freelist;
3163
3164 freelist = get_freelist(s, slab);
3165
3166 if (!freelist) {
3167 c->slab = NULL;
3168 c->tid = next_tid(c->tid);
3169 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3170 stat(s, DEACTIVATE_BYPASS);
3171 goto new_slab;
3172 }
3173
3174 stat(s, ALLOC_REFILL);
3175
3176 load_freelist:
3177
3178 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3179
3180 /*
3181 * freelist is pointing to the list of objects to be used.
3182 * slab is pointing to the slab from which the objects are obtained.
3183 * That slab must be frozen for per cpu allocations to work.
3184 */
3185 VM_BUG_ON(!c->slab->frozen);
3186 c->freelist = get_freepointer(s, freelist);
3187 c->tid = next_tid(c->tid);
3188 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3189 return freelist;
3190
3191 deactivate_slab:
3192
3193 local_lock_irqsave(&s->cpu_slab->lock, flags);
3194 if (slab != c->slab) {
3195 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3196 goto reread_slab;
3197 }
3198 freelist = c->freelist;
3199 c->slab = NULL;
3200 c->freelist = NULL;
3201 c->tid = next_tid(c->tid);
3202 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3203 deactivate_slab(s, slab, freelist);
3204
3205 new_slab:
3206
3207 if (slub_percpu_partial(c)) {
3208 local_lock_irqsave(&s->cpu_slab->lock, flags);
3209 if (unlikely(c->slab)) {
3210 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3211 goto reread_slab;
3212 }
3213 if (unlikely(!slub_percpu_partial(c))) {
3214 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3215 /* we were preempted and partial list got empty */
3216 goto new_objects;
3217 }
3218
3219 slab = c->slab = slub_percpu_partial(c);
3220 slub_set_percpu_partial(c, slab);
3221 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3222 stat(s, CPU_PARTIAL_ALLOC);
3223 goto redo;
3224 }
3225
3226 new_objects:
3227
3228 pc.flags = gfpflags;
3229 pc.slab = &slab;
3230 pc.orig_size = orig_size;
3231 freelist = get_partial(s, node, &pc);
3232 if (freelist)
3233 goto check_new_slab;
3234
3235 slub_put_cpu_ptr(s->cpu_slab);
3236 slab = new_slab(s, gfpflags, node);
3237 c = slub_get_cpu_ptr(s->cpu_slab);
3238
3239 if (unlikely(!slab)) {
3240 slab_out_of_memory(s, gfpflags, node);
3241 return NULL;
3242 }
3243
3244 stat(s, ALLOC_SLAB);
3245
3246 if (kmem_cache_debug(s)) {
3247 freelist = alloc_single_from_new_slab(s, slab, orig_size);
3248
3249 if (unlikely(!freelist))
3250 goto new_objects;
3251
3252 if (s->flags & SLAB_STORE_USER)
3253 set_track(s, freelist, TRACK_ALLOC, addr);
3254
3255 return freelist;
3256 }
3257
3258 /*
3259 * No other reference to the slab yet so we can
3260 * muck around with it freely without cmpxchg
3261 */
3262 freelist = slab->freelist;
3263 slab->freelist = NULL;
3264 slab->inuse = slab->objects;
3265 slab->frozen = 1;
3266
3267 inc_slabs_node(s, slab_nid(slab), slab->objects);
3268
3269 check_new_slab:
3270
3271 if (kmem_cache_debug(s)) {
3272 /*
3273 * For debug caches here we had to go through
3274 * alloc_single_from_partial() so just store the tracking info
3275 * and return the object
3276 */
3277 if (s->flags & SLAB_STORE_USER)
3278 set_track(s, freelist, TRACK_ALLOC, addr);
3279
3280 return freelist;
3281 }
3282
3283 if (unlikely(!pfmemalloc_match(slab, gfpflags))) {
3284 /*
3285 * For !pfmemalloc_match() case we don't load freelist so that
3286 * we don't make further mismatched allocations easier.
3287 */
3288 deactivate_slab(s, slab, get_freepointer(s, freelist));
3289 return freelist;
3290 }
3291
3292 retry_load_slab:
3293
3294 local_lock_irqsave(&s->cpu_slab->lock, flags);
3295 if (unlikely(c->slab)) {
3296 void *flush_freelist = c->freelist;
3297 struct slab *flush_slab = c->slab;
3298
3299 c->slab = NULL;
3300 c->freelist = NULL;
3301 c->tid = next_tid(c->tid);
3302
3303 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3304
3305 deactivate_slab(s, flush_slab, flush_freelist);
3306
3307 stat(s, CPUSLAB_FLUSH);
3308
3309 goto retry_load_slab;
3310 }
3311 c->slab = slab;
3312
3313 goto load_freelist;
3314 }
3315
3316 /*
3317 * A wrapper for ___slab_alloc() for contexts where preemption is not yet
3318 * disabled. Compensates for possible cpu changes by refetching the per cpu area
3319 * pointer.
3320 */
__slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)3321 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3322 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3323 {
3324 void *p;
3325
3326 #ifdef CONFIG_PREEMPT_COUNT
3327 /*
3328 * We may have been preempted and rescheduled on a different
3329 * cpu before disabling preemption. Need to reload cpu area
3330 * pointer.
3331 */
3332 c = slub_get_cpu_ptr(s->cpu_slab);
3333 #endif
3334
3335 p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
3336 #ifdef CONFIG_PREEMPT_COUNT
3337 slub_put_cpu_ptr(s->cpu_slab);
3338 #endif
3339 return p;
3340 }
3341
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)3342 static __always_inline void *__slab_alloc_node(struct kmem_cache *s,
3343 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
3344 {
3345 struct kmem_cache_cpu *c;
3346 struct slab *slab;
3347 unsigned long tid;
3348 void *object;
3349
3350 redo:
3351 /*
3352 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
3353 * enabled. We may switch back and forth between cpus while
3354 * reading from one cpu area. That does not matter as long
3355 * as we end up on the original cpu again when doing the cmpxchg.
3356 *
3357 * We must guarantee that tid and kmem_cache_cpu are retrieved on the
3358 * same cpu. We read first the kmem_cache_cpu pointer and use it to read
3359 * the tid. If we are preempted and switched to another cpu between the
3360 * two reads, it's OK as the two are still associated with the same cpu
3361 * and cmpxchg later will validate the cpu.
3362 */
3363 c = raw_cpu_ptr(s->cpu_slab);
3364 tid = READ_ONCE(c->tid);
3365
3366 /*
3367 * Irqless object alloc/free algorithm used here depends on sequence
3368 * of fetching cpu_slab's data. tid should be fetched before anything
3369 * on c to guarantee that object and slab associated with previous tid
3370 * won't be used with current tid. If we fetch tid first, object and
3371 * slab could be one associated with next tid and our alloc/free
3372 * request will be failed. In this case, we will retry. So, no problem.
3373 */
3374 barrier();
3375
3376 /*
3377 * The transaction ids are globally unique per cpu and per operation on
3378 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
3379 * occurs on the right processor and that there was no operation on the
3380 * linked list in between.
3381 */
3382
3383 object = c->freelist;
3384 slab = c->slab;
3385
3386 if (!USE_LOCKLESS_FAST_PATH() ||
3387 unlikely(!object || !slab || !node_match(slab, node))) {
3388 object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
3389 } else {
3390 void *next_object = get_freepointer_safe(s, object);
3391
3392 /*
3393 * The cmpxchg will only match if there was no additional
3394 * operation and if we are on the right processor.
3395 *
3396 * The cmpxchg does the following atomically (without lock
3397 * semantics!)
3398 * 1. Relocate first pointer to the current per cpu area.
3399 * 2. Verify that tid and freelist have not been changed
3400 * 3. If they were not changed replace tid and freelist
3401 *
3402 * Since this is without lock semantics the protection is only
3403 * against code executing on this cpu *not* from access by
3404 * other cpus.
3405 */
3406 if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
3407 note_cmpxchg_failure("slab_alloc", s, tid);
3408 goto redo;
3409 }
3410 prefetch_freepointer(s, next_object);
3411 stat(s, ALLOC_FASTPATH);
3412 }
3413
3414 return object;
3415 }
3416 #else /* CONFIG_SLUB_TINY */
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)3417 static void *__slab_alloc_node(struct kmem_cache *s,
3418 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
3419 {
3420 struct partial_context pc;
3421 struct slab *slab;
3422 void *object;
3423
3424 pc.flags = gfpflags;
3425 pc.slab = &slab;
3426 pc.orig_size = orig_size;
3427 object = get_partial(s, node, &pc);
3428
3429 if (object)
3430 return object;
3431
3432 slab = new_slab(s, gfpflags, node);
3433 if (unlikely(!slab)) {
3434 slab_out_of_memory(s, gfpflags, node);
3435 return NULL;
3436 }
3437
3438 object = alloc_single_from_new_slab(s, slab, orig_size);
3439
3440 return object;
3441 }
3442 #endif /* CONFIG_SLUB_TINY */
3443
3444 /*
3445 * If the object has been wiped upon free, make sure it's fully initialized by
3446 * zeroing out freelist pointer.
3447 */
maybe_wipe_obj_freeptr(struct kmem_cache * s,void * obj)3448 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
3449 void *obj)
3450 {
3451 if (unlikely(slab_want_init_on_free(s)) && obj)
3452 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
3453 0, sizeof(void *));
3454 }
3455
3456 /*
3457 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
3458 * have the fastpath folded into their functions. So no function call
3459 * overhead for requests that can be satisfied on the fastpath.
3460 *
3461 * The fastpath works by first checking if the lockless freelist can be used.
3462 * If not then __slab_alloc is called for slow processing.
3463 *
3464 * Otherwise we can simply pick the next object from the lockless free list.
3465 */
slab_alloc_node(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)3466 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
3467 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
3468 {
3469 void *object;
3470 struct obj_cgroup *objcg = NULL;
3471 bool init = false;
3472
3473 s = slab_pre_alloc_hook(s, lru, &objcg, 1, gfpflags);
3474 if (!s)
3475 return NULL;
3476
3477 object = kfence_alloc(s, orig_size, gfpflags);
3478 if (unlikely(object))
3479 goto out;
3480
3481 object = __slab_alloc_node(s, gfpflags, node, addr, orig_size);
3482
3483 maybe_wipe_obj_freeptr(s, object);
3484 init = slab_want_init_on_alloc(gfpflags, s);
3485
3486 out:
3487 /*
3488 * When init equals 'true', like for kzalloc() family, only
3489 * @orig_size bytes might be zeroed instead of s->object_size
3490 */
3491 slab_post_alloc_hook(s, objcg, gfpflags, 1, &object, init, orig_size);
3492
3493 return object;
3494 }
3495
slab_alloc(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags,unsigned long addr,size_t orig_size)3496 static __fastpath_inline void *slab_alloc(struct kmem_cache *s, struct list_lru *lru,
3497 gfp_t gfpflags, unsigned long addr, size_t orig_size)
3498 {
3499 return slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, addr, orig_size);
3500 }
3501
3502 static __fastpath_inline
__kmem_cache_alloc_lru(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags)3503 void *__kmem_cache_alloc_lru(struct kmem_cache *s, struct list_lru *lru,
3504 gfp_t gfpflags)
3505 {
3506 void *ret = slab_alloc(s, lru, gfpflags, _RET_IP_, s->object_size);
3507
3508 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
3509
3510 return ret;
3511 }
3512
kmem_cache_alloc(struct kmem_cache * s,gfp_t gfpflags)3513 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
3514 {
3515 return __kmem_cache_alloc_lru(s, NULL, gfpflags);
3516 }
3517 EXPORT_SYMBOL(kmem_cache_alloc);
3518
kmem_cache_alloc_lru(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags)3519 void *kmem_cache_alloc_lru(struct kmem_cache *s, struct list_lru *lru,
3520 gfp_t gfpflags)
3521 {
3522 return __kmem_cache_alloc_lru(s, lru, gfpflags);
3523 }
3524 EXPORT_SYMBOL(kmem_cache_alloc_lru);
3525
__kmem_cache_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,size_t orig_size,unsigned long caller)3526 void *__kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags,
3527 int node, size_t orig_size,
3528 unsigned long caller)
3529 {
3530 return slab_alloc_node(s, NULL, gfpflags, node,
3531 caller, orig_size);
3532 }
3533
kmem_cache_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node)3534 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
3535 {
3536 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
3537
3538 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
3539
3540 return ret;
3541 }
3542 EXPORT_SYMBOL(kmem_cache_alloc_node);
3543
free_to_partial_list(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int bulk_cnt,unsigned long addr)3544 static noinline void free_to_partial_list(
3545 struct kmem_cache *s, struct slab *slab,
3546 void *head, void *tail, int bulk_cnt,
3547 unsigned long addr)
3548 {
3549 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
3550 struct slab *slab_free = NULL;
3551 int cnt = bulk_cnt;
3552 unsigned long flags;
3553 depot_stack_handle_t handle = 0;
3554
3555 if (s->flags & SLAB_STORE_USER)
3556 handle = set_track_prepare();
3557
3558 spin_lock_irqsave(&n->list_lock, flags);
3559
3560 if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
3561 void *prior = slab->freelist;
3562
3563 /* Perform the actual freeing while we still hold the locks */
3564 slab->inuse -= cnt;
3565 set_freepointer(s, tail, prior);
3566 slab->freelist = head;
3567
3568 /*
3569 * If the slab is empty, and node's partial list is full,
3570 * it should be discarded anyway no matter it's on full or
3571 * partial list.
3572 */
3573 if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
3574 slab_free = slab;
3575
3576 if (!prior) {
3577 /* was on full list */
3578 remove_full(s, n, slab);
3579 if (!slab_free) {
3580 add_partial(n, slab, DEACTIVATE_TO_TAIL);
3581 stat(s, FREE_ADD_PARTIAL);
3582 }
3583 } else if (slab_free) {
3584 remove_partial(n, slab);
3585 stat(s, FREE_REMOVE_PARTIAL);
3586 }
3587 }
3588
3589 if (slab_free) {
3590 /*
3591 * Update the counters while still holding n->list_lock to
3592 * prevent spurious validation warnings
3593 */
3594 dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
3595 }
3596
3597 spin_unlock_irqrestore(&n->list_lock, flags);
3598
3599 if (slab_free) {
3600 stat(s, FREE_SLAB);
3601 free_slab(s, slab_free);
3602 }
3603 }
3604
3605 /*
3606 * Slow path handling. This may still be called frequently since objects
3607 * have a longer lifetime than the cpu slabs in most processing loads.
3608 *
3609 * So we still attempt to reduce cache line usage. Just take the slab
3610 * lock and free the item. If there is no additional partial slab
3611 * handling required then we can return immediately.
3612 */
__slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)3613 static void __slab_free(struct kmem_cache *s, struct slab *slab,
3614 void *head, void *tail, int cnt,
3615 unsigned long addr)
3616
3617 {
3618 void *prior;
3619 int was_frozen;
3620 struct slab new;
3621 unsigned long counters;
3622 struct kmem_cache_node *n = NULL;
3623 unsigned long flags;
3624
3625 stat(s, FREE_SLOWPATH);
3626
3627 if (kfence_free(head))
3628 return;
3629
3630 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
3631 free_to_partial_list(s, slab, head, tail, cnt, addr);
3632 return;
3633 }
3634
3635 do {
3636 if (unlikely(n)) {
3637 spin_unlock_irqrestore(&n->list_lock, flags);
3638 n = NULL;
3639 }
3640 prior = slab->freelist;
3641 counters = slab->counters;
3642 set_freepointer(s, tail, prior);
3643 new.counters = counters;
3644 was_frozen = new.frozen;
3645 new.inuse -= cnt;
3646 if ((!new.inuse || !prior) && !was_frozen) {
3647
3648 if (kmem_cache_has_cpu_partial(s) && !prior) {
3649
3650 /*
3651 * Slab was on no list before and will be
3652 * partially empty
3653 * We can defer the list move and instead
3654 * freeze it.
3655 */
3656 new.frozen = 1;
3657
3658 } else { /* Needs to be taken off a list */
3659
3660 n = get_node(s, slab_nid(slab));
3661 /*
3662 * Speculatively acquire the list_lock.
3663 * If the cmpxchg does not succeed then we may
3664 * drop the list_lock without any processing.
3665 *
3666 * Otherwise the list_lock will synchronize with
3667 * other processors updating the list of slabs.
3668 */
3669 spin_lock_irqsave(&n->list_lock, flags);
3670
3671 }
3672 }
3673
3674 } while (!slab_update_freelist(s, slab,
3675 prior, counters,
3676 head, new.counters,
3677 "__slab_free"));
3678
3679 if (likely(!n)) {
3680
3681 if (likely(was_frozen)) {
3682 /*
3683 * The list lock was not taken therefore no list
3684 * activity can be necessary.
3685 */
3686 stat(s, FREE_FROZEN);
3687 } else if (new.frozen) {
3688 /*
3689 * If we just froze the slab then put it onto the
3690 * per cpu partial list.
3691 */
3692 put_cpu_partial(s, slab, 1);
3693 stat(s, CPU_PARTIAL_FREE);
3694 }
3695
3696 return;
3697 }
3698
3699 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
3700 goto slab_empty;
3701
3702 /*
3703 * Objects left in the slab. If it was not on the partial list before
3704 * then add it.
3705 */
3706 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
3707 remove_full(s, n, slab);
3708 add_partial(n, slab, DEACTIVATE_TO_TAIL);
3709 stat(s, FREE_ADD_PARTIAL);
3710 }
3711 spin_unlock_irqrestore(&n->list_lock, flags);
3712 return;
3713
3714 slab_empty:
3715 if (prior) {
3716 /*
3717 * Slab on the partial list.
3718 */
3719 remove_partial(n, slab);
3720 stat(s, FREE_REMOVE_PARTIAL);
3721 } else {
3722 /* Slab must be on the full list */
3723 remove_full(s, n, slab);
3724 }
3725
3726 spin_unlock_irqrestore(&n->list_lock, flags);
3727 stat(s, FREE_SLAB);
3728 discard_slab(s, slab);
3729 }
3730
3731 #ifndef CONFIG_SLUB_TINY
3732 /*
3733 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3734 * can perform fastpath freeing without additional function calls.
3735 *
3736 * The fastpath is only possible if we are freeing to the current cpu slab
3737 * of this processor. This typically the case if we have just allocated
3738 * the item before.
3739 *
3740 * If fastpath is not possible then fall back to __slab_free where we deal
3741 * with all sorts of special processing.
3742 *
3743 * Bulk free of a freelist with several objects (all pointing to the
3744 * same slab) possible by specifying head and tail ptr, plus objects
3745 * count (cnt). Bulk free indicated by tail pointer being set.
3746 */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)3747 static __always_inline void do_slab_free(struct kmem_cache *s,
3748 struct slab *slab, void *head, void *tail,
3749 int cnt, unsigned long addr)
3750 {
3751 void *tail_obj = tail ? : head;
3752 struct kmem_cache_cpu *c;
3753 unsigned long tid;
3754 void **freelist;
3755
3756 redo:
3757 /*
3758 * Determine the currently cpus per cpu slab.
3759 * The cpu may change afterward. However that does not matter since
3760 * data is retrieved via this pointer. If we are on the same cpu
3761 * during the cmpxchg then the free will succeed.
3762 */
3763 c = raw_cpu_ptr(s->cpu_slab);
3764 tid = READ_ONCE(c->tid);
3765
3766 /* Same with comment on barrier() in slab_alloc_node() */
3767 barrier();
3768
3769 if (unlikely(slab != c->slab)) {
3770 __slab_free(s, slab, head, tail_obj, cnt, addr);
3771 return;
3772 }
3773
3774 if (USE_LOCKLESS_FAST_PATH()) {
3775 freelist = READ_ONCE(c->freelist);
3776
3777 set_freepointer(s, tail_obj, freelist);
3778
3779 if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
3780 note_cmpxchg_failure("slab_free", s, tid);
3781 goto redo;
3782 }
3783 } else {
3784 /* Update the free list under the local lock */
3785 local_lock(&s->cpu_slab->lock);
3786 c = this_cpu_ptr(s->cpu_slab);
3787 if (unlikely(slab != c->slab)) {
3788 local_unlock(&s->cpu_slab->lock);
3789 goto redo;
3790 }
3791 tid = c->tid;
3792 freelist = c->freelist;
3793
3794 set_freepointer(s, tail_obj, freelist);
3795 c->freelist = head;
3796 c->tid = next_tid(tid);
3797
3798 local_unlock(&s->cpu_slab->lock);
3799 }
3800 stat(s, FREE_FASTPATH);
3801 }
3802 #else /* CONFIG_SLUB_TINY */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)3803 static void do_slab_free(struct kmem_cache *s,
3804 struct slab *slab, void *head, void *tail,
3805 int cnt, unsigned long addr)
3806 {
3807 void *tail_obj = tail ? : head;
3808
3809 __slab_free(s, slab, head, tail_obj, cnt, addr);
3810 }
3811 #endif /* CONFIG_SLUB_TINY */
3812
slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,void ** p,int cnt,unsigned long addr)3813 static __fastpath_inline void slab_free(struct kmem_cache *s, struct slab *slab,
3814 void *head, void *tail, void **p, int cnt,
3815 unsigned long addr)
3816 {
3817 memcg_slab_free_hook(s, slab, p, cnt);
3818 /*
3819 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3820 * to remove objects, whose reuse must be delayed.
3821 */
3822 if (slab_free_freelist_hook(s, &head, &tail, &cnt))
3823 do_slab_free(s, slab, head, tail, cnt, addr);
3824 }
3825
3826 #ifdef CONFIG_KASAN_GENERIC
___cache_free(struct kmem_cache * cache,void * x,unsigned long addr)3827 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3828 {
3829 do_slab_free(cache, virt_to_slab(x), x, NULL, 1, addr);
3830 }
3831 #endif
3832
__kmem_cache_free(struct kmem_cache * s,void * x,unsigned long caller)3833 void __kmem_cache_free(struct kmem_cache *s, void *x, unsigned long caller)
3834 {
3835 slab_free(s, virt_to_slab(x), x, NULL, &x, 1, caller);
3836 }
3837
kmem_cache_free(struct kmem_cache * s,void * x)3838 void kmem_cache_free(struct kmem_cache *s, void *x)
3839 {
3840 s = cache_from_obj(s, x);
3841 if (!s)
3842 return;
3843 trace_kmem_cache_free(_RET_IP_, x, s);
3844 slab_free(s, virt_to_slab(x), x, NULL, &x, 1, _RET_IP_);
3845 }
3846 EXPORT_SYMBOL(kmem_cache_free);
3847
3848 struct detached_freelist {
3849 struct slab *slab;
3850 void *tail;
3851 void *freelist;
3852 int cnt;
3853 struct kmem_cache *s;
3854 };
3855
3856 /*
3857 * This function progressively scans the array with free objects (with
3858 * a limited look ahead) and extract objects belonging to the same
3859 * slab. It builds a detached freelist directly within the given
3860 * slab/objects. This can happen without any need for
3861 * synchronization, because the objects are owned by running process.
3862 * The freelist is build up as a single linked list in the objects.
3863 * The idea is, that this detached freelist can then be bulk
3864 * transferred to the real freelist(s), but only requiring a single
3865 * synchronization primitive. Look ahead in the array is limited due
3866 * to performance reasons.
3867 */
3868 static inline
build_detached_freelist(struct kmem_cache * s,size_t size,void ** p,struct detached_freelist * df)3869 int build_detached_freelist(struct kmem_cache *s, size_t size,
3870 void **p, struct detached_freelist *df)
3871 {
3872 int lookahead = 3;
3873 void *object;
3874 struct folio *folio;
3875 size_t same;
3876
3877 object = p[--size];
3878 folio = virt_to_folio(object);
3879 if (!s) {
3880 /* Handle kalloc'ed objects */
3881 if (unlikely(!folio_test_slab(folio))) {
3882 free_large_kmalloc(folio, object);
3883 df->slab = NULL;
3884 return size;
3885 }
3886 /* Derive kmem_cache from object */
3887 df->slab = folio_slab(folio);
3888 df->s = df->slab->slab_cache;
3889 } else {
3890 df->slab = folio_slab(folio);
3891 df->s = cache_from_obj(s, object); /* Support for memcg */
3892 }
3893
3894 /* Start new detached freelist */
3895 df->tail = object;
3896 df->freelist = object;
3897 df->cnt = 1;
3898
3899 if (is_kfence_address(object))
3900 return size;
3901
3902 set_freepointer(df->s, object, NULL);
3903
3904 same = size;
3905 while (size) {
3906 object = p[--size];
3907 /* df->slab is always set at this point */
3908 if (df->slab == virt_to_slab(object)) {
3909 /* Opportunity build freelist */
3910 set_freepointer(df->s, object, df->freelist);
3911 df->freelist = object;
3912 df->cnt++;
3913 same--;
3914 if (size != same)
3915 swap(p[size], p[same]);
3916 continue;
3917 }
3918
3919 /* Limit look ahead search */
3920 if (!--lookahead)
3921 break;
3922 }
3923
3924 return same;
3925 }
3926
3927 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_free_bulk(struct kmem_cache * s,size_t size,void ** p)3928 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3929 {
3930 if (!size)
3931 return;
3932
3933 do {
3934 struct detached_freelist df;
3935
3936 size = build_detached_freelist(s, size, p, &df);
3937 if (!df.slab)
3938 continue;
3939
3940 slab_free(df.s, df.slab, df.freelist, df.tail, &p[size], df.cnt,
3941 _RET_IP_);
3942 } while (likely(size));
3943 }
3944 EXPORT_SYMBOL(kmem_cache_free_bulk);
3945
3946 #ifndef CONFIG_SLUB_TINY
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p,struct obj_cgroup * objcg)3947 static inline int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
3948 size_t size, void **p, struct obj_cgroup *objcg)
3949 {
3950 struct kmem_cache_cpu *c;
3951 unsigned long irqflags;
3952 int i;
3953
3954 /*
3955 * Drain objects in the per cpu slab, while disabling local
3956 * IRQs, which protects against PREEMPT and interrupts
3957 * handlers invoking normal fastpath.
3958 */
3959 c = slub_get_cpu_ptr(s->cpu_slab);
3960 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
3961
3962 for (i = 0; i < size; i++) {
3963 void *object = kfence_alloc(s, s->object_size, flags);
3964
3965 if (unlikely(object)) {
3966 p[i] = object;
3967 continue;
3968 }
3969
3970 object = c->freelist;
3971 if (unlikely(!object)) {
3972 /*
3973 * We may have removed an object from c->freelist using
3974 * the fastpath in the previous iteration; in that case,
3975 * c->tid has not been bumped yet.
3976 * Since ___slab_alloc() may reenable interrupts while
3977 * allocating memory, we should bump c->tid now.
3978 */
3979 c->tid = next_tid(c->tid);
3980
3981 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
3982
3983 /*
3984 * Invoking slow path likely have side-effect
3985 * of re-populating per CPU c->freelist
3986 */
3987 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
3988 _RET_IP_, c, s->object_size);
3989 if (unlikely(!p[i]))
3990 goto error;
3991
3992 c = this_cpu_ptr(s->cpu_slab);
3993 maybe_wipe_obj_freeptr(s, p[i]);
3994
3995 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
3996
3997 continue; /* goto for-loop */
3998 }
3999 c->freelist = get_freepointer(s, object);
4000 p[i] = object;
4001 maybe_wipe_obj_freeptr(s, p[i]);
4002 }
4003 c->tid = next_tid(c->tid);
4004 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
4005 slub_put_cpu_ptr(s->cpu_slab);
4006
4007 return i;
4008
4009 error:
4010 slub_put_cpu_ptr(s->cpu_slab);
4011 slab_post_alloc_hook(s, objcg, flags, i, p, false, s->object_size);
4012 kmem_cache_free_bulk(s, i, p);
4013 return 0;
4014
4015 }
4016 #else /* CONFIG_SLUB_TINY */
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p,struct obj_cgroup * objcg)4017 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
4018 size_t size, void **p, struct obj_cgroup *objcg)
4019 {
4020 int i;
4021
4022 for (i = 0; i < size; i++) {
4023 void *object = kfence_alloc(s, s->object_size, flags);
4024
4025 if (unlikely(object)) {
4026 p[i] = object;
4027 continue;
4028 }
4029
4030 p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE,
4031 _RET_IP_, s->object_size);
4032 if (unlikely(!p[i]))
4033 goto error;
4034
4035 maybe_wipe_obj_freeptr(s, p[i]);
4036 }
4037
4038 return i;
4039
4040 error:
4041 slab_post_alloc_hook(s, objcg, flags, i, p, false, s->object_size);
4042 kmem_cache_free_bulk(s, i, p);
4043 return 0;
4044 }
4045 #endif /* CONFIG_SLUB_TINY */
4046
4047 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)4048 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
4049 void **p)
4050 {
4051 int i;
4052 struct obj_cgroup *objcg = NULL;
4053
4054 if (!size)
4055 return 0;
4056
4057 /* memcg and kmem_cache debug support */
4058 s = slab_pre_alloc_hook(s, NULL, &objcg, size, flags);
4059 if (unlikely(!s))
4060 return 0;
4061
4062 i = __kmem_cache_alloc_bulk(s, flags, size, p, objcg);
4063
4064 /*
4065 * memcg and kmem_cache debug support and memory initialization.
4066 * Done outside of the IRQ disabled fastpath loop.
4067 */
4068 if (i != 0)
4069 slab_post_alloc_hook(s, objcg, flags, size, p,
4070 slab_want_init_on_alloc(flags, s), s->object_size);
4071 return i;
4072 }
4073 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
4074
4075
4076 /*
4077 * Object placement in a slab is made very easy because we always start at
4078 * offset 0. If we tune the size of the object to the alignment then we can
4079 * get the required alignment by putting one properly sized object after
4080 * another.
4081 *
4082 * Notice that the allocation order determines the sizes of the per cpu
4083 * caches. Each processor has always one slab available for allocations.
4084 * Increasing the allocation order reduces the number of times that slabs
4085 * must be moved on and off the partial lists and is therefore a factor in
4086 * locking overhead.
4087 */
4088
4089 /*
4090 * Minimum / Maximum order of slab pages. This influences locking overhead
4091 * and slab fragmentation. A higher order reduces the number of partial slabs
4092 * and increases the number of allocations possible without having to
4093 * take the list_lock.
4094 */
4095 static unsigned int slub_min_order;
4096 static unsigned int slub_max_order =
4097 IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
4098 static unsigned int slub_min_objects;
4099
4100 /*
4101 * Calculate the order of allocation given an slab object size.
4102 *
4103 * The order of allocation has significant impact on performance and other
4104 * system components. Generally order 0 allocations should be preferred since
4105 * order 0 does not cause fragmentation in the page allocator. Larger objects
4106 * be problematic to put into order 0 slabs because there may be too much
4107 * unused space left. We go to a higher order if more than 1/16th of the slab
4108 * would be wasted.
4109 *
4110 * In order to reach satisfactory performance we must ensure that a minimum
4111 * number of objects is in one slab. Otherwise we may generate too much
4112 * activity on the partial lists which requires taking the list_lock. This is
4113 * less a concern for large slabs though which are rarely used.
4114 *
4115 * slub_max_order specifies the order where we begin to stop considering the
4116 * number of objects in a slab as critical. If we reach slub_max_order then
4117 * we try to keep the page order as low as possible. So we accept more waste
4118 * of space in favor of a small page order.
4119 *
4120 * Higher order allocations also allow the placement of more objects in a
4121 * slab and thereby reduce object handling overhead. If the user has
4122 * requested a higher minimum order then we start with that one instead of
4123 * the smallest order which will fit the object.
4124 */
calc_slab_order(unsigned int size,unsigned int min_objects,unsigned int max_order,unsigned int fract_leftover)4125 static inline unsigned int calc_slab_order(unsigned int size,
4126 unsigned int min_objects, unsigned int max_order,
4127 unsigned int fract_leftover)
4128 {
4129 unsigned int min_order = slub_min_order;
4130 unsigned int order;
4131
4132 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
4133 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
4134
4135 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
4136 order <= max_order; order++) {
4137
4138 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
4139 unsigned int rem;
4140
4141 rem = slab_size % size;
4142
4143 if (rem <= slab_size / fract_leftover)
4144 break;
4145 }
4146
4147 return order;
4148 }
4149
calculate_order(unsigned int size)4150 static inline int calculate_order(unsigned int size)
4151 {
4152 unsigned int order;
4153 unsigned int min_objects;
4154 unsigned int max_objects;
4155 unsigned int nr_cpus;
4156
4157 /*
4158 * Attempt to find best configuration for a slab. This
4159 * works by first attempting to generate a layout with
4160 * the best configuration and backing off gradually.
4161 *
4162 * First we increase the acceptable waste in a slab. Then
4163 * we reduce the minimum objects required in a slab.
4164 */
4165 min_objects = slub_min_objects;
4166 if (!min_objects) {
4167 /*
4168 * Some architectures will only update present cpus when
4169 * onlining them, so don't trust the number if it's just 1. But
4170 * we also don't want to use nr_cpu_ids always, as on some other
4171 * architectures, there can be many possible cpus, but never
4172 * onlined. Here we compromise between trying to avoid too high
4173 * order on systems that appear larger than they are, and too
4174 * low order on systems that appear smaller than they are.
4175 */
4176 nr_cpus = num_present_cpus();
4177 if (nr_cpus <= 1)
4178 nr_cpus = nr_cpu_ids;
4179 min_objects = 4 * (fls(nr_cpus) + 1);
4180 }
4181 max_objects = order_objects(slub_max_order, size);
4182 min_objects = min(min_objects, max_objects);
4183
4184 while (min_objects > 1) {
4185 unsigned int fraction;
4186
4187 fraction = 16;
4188 while (fraction >= 4) {
4189 order = calc_slab_order(size, min_objects,
4190 slub_max_order, fraction);
4191 if (order <= slub_max_order)
4192 return order;
4193 fraction /= 2;
4194 }
4195 min_objects--;
4196 }
4197
4198 /*
4199 * We were unable to place multiple objects in a slab. Now
4200 * lets see if we can place a single object there.
4201 */
4202 order = calc_slab_order(size, 1, slub_max_order, 1);
4203 if (order <= slub_max_order)
4204 return order;
4205
4206 /*
4207 * Doh this slab cannot be placed using slub_max_order.
4208 */
4209 order = calc_slab_order(size, 1, MAX_ORDER, 1);
4210 if (order <= MAX_ORDER)
4211 return order;
4212 return -ENOSYS;
4213 }
4214
4215 static void
init_kmem_cache_node(struct kmem_cache_node * n)4216 init_kmem_cache_node(struct kmem_cache_node *n)
4217 {
4218 n->nr_partial = 0;
4219 spin_lock_init(&n->list_lock);
4220 INIT_LIST_HEAD(&n->partial);
4221 #ifdef CONFIG_SLUB_DEBUG
4222 atomic_long_set(&n->nr_slabs, 0);
4223 atomic_long_set(&n->total_objects, 0);
4224 INIT_LIST_HEAD(&n->full);
4225 #endif
4226 }
4227
4228 #ifndef CONFIG_SLUB_TINY
alloc_kmem_cache_cpus(struct kmem_cache * s)4229 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
4230 {
4231 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
4232 NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
4233 sizeof(struct kmem_cache_cpu));
4234
4235 /*
4236 * Must align to double word boundary for the double cmpxchg
4237 * instructions to work; see __pcpu_double_call_return_bool().
4238 */
4239 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
4240 2 * sizeof(void *));
4241
4242 if (!s->cpu_slab)
4243 return 0;
4244
4245 init_kmem_cache_cpus(s);
4246
4247 return 1;
4248 }
4249 #else
alloc_kmem_cache_cpus(struct kmem_cache * s)4250 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
4251 {
4252 return 1;
4253 }
4254 #endif /* CONFIG_SLUB_TINY */
4255
4256 static struct kmem_cache *kmem_cache_node;
4257
4258 /*
4259 * No kmalloc_node yet so do it by hand. We know that this is the first
4260 * slab on the node for this slabcache. There are no concurrent accesses
4261 * possible.
4262 *
4263 * Note that this function only works on the kmem_cache_node
4264 * when allocating for the kmem_cache_node. This is used for bootstrapping
4265 * memory on a fresh node that has no slab structures yet.
4266 */
early_kmem_cache_node_alloc(int node)4267 static void early_kmem_cache_node_alloc(int node)
4268 {
4269 struct slab *slab;
4270 struct kmem_cache_node *n;
4271
4272 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
4273
4274 slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
4275
4276 BUG_ON(!slab);
4277 inc_slabs_node(kmem_cache_node, slab_nid(slab), slab->objects);
4278 if (slab_nid(slab) != node) {
4279 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
4280 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
4281 }
4282
4283 n = slab->freelist;
4284 BUG_ON(!n);
4285 #ifdef CONFIG_SLUB_DEBUG
4286 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
4287 init_tracking(kmem_cache_node, n);
4288 #endif
4289 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
4290 slab->freelist = get_freepointer(kmem_cache_node, n);
4291 slab->inuse = 1;
4292 kmem_cache_node->node[node] = n;
4293 init_kmem_cache_node(n);
4294 inc_slabs_node(kmem_cache_node, node, slab->objects);
4295
4296 /*
4297 * No locks need to be taken here as it has just been
4298 * initialized and there is no concurrent access.
4299 */
4300 __add_partial(n, slab, DEACTIVATE_TO_HEAD);
4301 }
4302
free_kmem_cache_nodes(struct kmem_cache * s)4303 static void free_kmem_cache_nodes(struct kmem_cache *s)
4304 {
4305 int node;
4306 struct kmem_cache_node *n;
4307
4308 for_each_kmem_cache_node(s, node, n) {
4309 s->node[node] = NULL;
4310 kmem_cache_free(kmem_cache_node, n);
4311 }
4312 }
4313
__kmem_cache_release(struct kmem_cache * s)4314 void __kmem_cache_release(struct kmem_cache *s)
4315 {
4316 cache_random_seq_destroy(s);
4317 #ifndef CONFIG_SLUB_TINY
4318 free_percpu(s->cpu_slab);
4319 #endif
4320 free_kmem_cache_nodes(s);
4321 }
4322
init_kmem_cache_nodes(struct kmem_cache * s)4323 static int init_kmem_cache_nodes(struct kmem_cache *s)
4324 {
4325 int node;
4326
4327 for_each_node_mask(node, slab_nodes) {
4328 struct kmem_cache_node *n;
4329
4330 if (slab_state == DOWN) {
4331 early_kmem_cache_node_alloc(node);
4332 continue;
4333 }
4334 n = kmem_cache_alloc_node(kmem_cache_node,
4335 GFP_KERNEL, node);
4336
4337 if (!n) {
4338 free_kmem_cache_nodes(s);
4339 return 0;
4340 }
4341
4342 init_kmem_cache_node(n);
4343 s->node[node] = n;
4344 }
4345 return 1;
4346 }
4347
set_cpu_partial(struct kmem_cache * s)4348 static void set_cpu_partial(struct kmem_cache *s)
4349 {
4350 #ifdef CONFIG_SLUB_CPU_PARTIAL
4351 unsigned int nr_objects;
4352
4353 /*
4354 * cpu_partial determined the maximum number of objects kept in the
4355 * per cpu partial lists of a processor.
4356 *
4357 * Per cpu partial lists mainly contain slabs that just have one
4358 * object freed. If they are used for allocation then they can be
4359 * filled up again with minimal effort. The slab will never hit the
4360 * per node partial lists and therefore no locking will be required.
4361 *
4362 * For backwards compatibility reasons, this is determined as number
4363 * of objects, even though we now limit maximum number of pages, see
4364 * slub_set_cpu_partial()
4365 */
4366 if (!kmem_cache_has_cpu_partial(s))
4367 nr_objects = 0;
4368 else if (s->size >= PAGE_SIZE)
4369 nr_objects = 6;
4370 else if (s->size >= 1024)
4371 nr_objects = 24;
4372 else if (s->size >= 256)
4373 nr_objects = 52;
4374 else
4375 nr_objects = 120;
4376
4377 slub_set_cpu_partial(s, nr_objects);
4378 #endif
4379 }
4380
4381 /*
4382 * calculate_sizes() determines the order and the distribution of data within
4383 * a slab object.
4384 */
calculate_sizes(struct kmem_cache * s)4385 static int calculate_sizes(struct kmem_cache *s)
4386 {
4387 slab_flags_t flags = s->flags;
4388 unsigned int size = s->object_size;
4389 unsigned int order;
4390
4391 /*
4392 * Round up object size to the next word boundary. We can only
4393 * place the free pointer at word boundaries and this determines
4394 * the possible location of the free pointer.
4395 */
4396 size = ALIGN(size, sizeof(void *));
4397
4398 #ifdef CONFIG_SLUB_DEBUG
4399 /*
4400 * Determine if we can poison the object itself. If the user of
4401 * the slab may touch the object after free or before allocation
4402 * then we should never poison the object itself.
4403 */
4404 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
4405 !s->ctor)
4406 s->flags |= __OBJECT_POISON;
4407 else
4408 s->flags &= ~__OBJECT_POISON;
4409
4410
4411 /*
4412 * If we are Redzoning then check if there is some space between the
4413 * end of the object and the free pointer. If not then add an
4414 * additional word to have some bytes to store Redzone information.
4415 */
4416 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
4417 size += sizeof(void *);
4418 #endif
4419
4420 /*
4421 * With that we have determined the number of bytes in actual use
4422 * by the object and redzoning.
4423 */
4424 s->inuse = size;
4425
4426 if (slub_debug_orig_size(s) ||
4427 (flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
4428 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
4429 s->ctor) {
4430 /*
4431 * Relocate free pointer after the object if it is not
4432 * permitted to overwrite the first word of the object on
4433 * kmem_cache_free.
4434 *
4435 * This is the case if we do RCU, have a constructor or
4436 * destructor, are poisoning the objects, or are
4437 * redzoning an object smaller than sizeof(void *).
4438 *
4439 * The assumption that s->offset >= s->inuse means free
4440 * pointer is outside of the object is used in the
4441 * freeptr_outside_object() function. If that is no
4442 * longer true, the function needs to be modified.
4443 */
4444 s->offset = size;
4445 size += sizeof(void *);
4446 } else {
4447 /*
4448 * Store freelist pointer near middle of object to keep
4449 * it away from the edges of the object to avoid small
4450 * sized over/underflows from neighboring allocations.
4451 */
4452 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
4453 }
4454
4455 #ifdef CONFIG_SLUB_DEBUG
4456 if (flags & SLAB_STORE_USER) {
4457 /*
4458 * Need to store information about allocs and frees after
4459 * the object.
4460 */
4461 size += 2 * sizeof(struct track);
4462
4463 /* Save the original kmalloc request size */
4464 if (flags & SLAB_KMALLOC)
4465 size += sizeof(unsigned int);
4466 }
4467 #endif
4468
4469 kasan_cache_create(s, &size, &s->flags);
4470 #ifdef CONFIG_SLUB_DEBUG
4471 if (flags & SLAB_RED_ZONE) {
4472 /*
4473 * Add some empty padding so that we can catch
4474 * overwrites from earlier objects rather than let
4475 * tracking information or the free pointer be
4476 * corrupted if a user writes before the start
4477 * of the object.
4478 */
4479 size += sizeof(void *);
4480
4481 s->red_left_pad = sizeof(void *);
4482 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
4483 size += s->red_left_pad;
4484 }
4485 #endif
4486
4487 /*
4488 * SLUB stores one object immediately after another beginning from
4489 * offset 0. In order to align the objects we have to simply size
4490 * each object to conform to the alignment.
4491 */
4492 size = ALIGN(size, s->align);
4493 s->size = size;
4494 s->reciprocal_size = reciprocal_value(size);
4495 order = calculate_order(size);
4496
4497 if ((int)order < 0)
4498 return 0;
4499
4500 s->allocflags = 0;
4501 if (order)
4502 s->allocflags |= __GFP_COMP;
4503
4504 if (s->flags & SLAB_CACHE_DMA)
4505 s->allocflags |= GFP_DMA;
4506
4507 if (s->flags & SLAB_CACHE_DMA32)
4508 s->allocflags |= GFP_DMA32;
4509
4510 if (s->flags & SLAB_RECLAIM_ACCOUNT)
4511 s->allocflags |= __GFP_RECLAIMABLE;
4512
4513 /*
4514 * Determine the number of objects per slab
4515 */
4516 s->oo = oo_make(order, size);
4517 s->min = oo_make(get_order(size), size);
4518
4519 return !!oo_objects(s->oo);
4520 }
4521
kmem_cache_open(struct kmem_cache * s,slab_flags_t flags)4522 static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
4523 {
4524 s->flags = kmem_cache_flags(s->size, flags, s->name);
4525 #ifdef CONFIG_SLAB_FREELIST_HARDENED
4526 s->random = get_random_long();
4527 #endif
4528
4529 if (!calculate_sizes(s))
4530 goto error;
4531 if (disable_higher_order_debug) {
4532 /*
4533 * Disable debugging flags that store metadata if the min slab
4534 * order increased.
4535 */
4536 if (get_order(s->size) > get_order(s->object_size)) {
4537 s->flags &= ~DEBUG_METADATA_FLAGS;
4538 s->offset = 0;
4539 if (!calculate_sizes(s))
4540 goto error;
4541 }
4542 }
4543
4544 #ifdef system_has_freelist_aba
4545 if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
4546 /* Enable fast mode */
4547 s->flags |= __CMPXCHG_DOUBLE;
4548 }
4549 #endif
4550
4551 /*
4552 * The larger the object size is, the more slabs we want on the partial
4553 * list to avoid pounding the page allocator excessively.
4554 */
4555 s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
4556 s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
4557
4558 set_cpu_partial(s);
4559
4560 #ifdef CONFIG_NUMA
4561 s->remote_node_defrag_ratio = 1000;
4562 #endif
4563
4564 /* Initialize the pre-computed randomized freelist if slab is up */
4565 if (slab_state >= UP) {
4566 if (init_cache_random_seq(s))
4567 goto error;
4568 }
4569
4570 if (!init_kmem_cache_nodes(s))
4571 goto error;
4572
4573 if (alloc_kmem_cache_cpus(s))
4574 return 0;
4575
4576 error:
4577 __kmem_cache_release(s);
4578 return -EINVAL;
4579 }
4580
list_slab_objects(struct kmem_cache * s,struct slab * slab,const char * text)4581 static void list_slab_objects(struct kmem_cache *s, struct slab *slab,
4582 const char *text)
4583 {
4584 #ifdef CONFIG_SLUB_DEBUG
4585 void *addr = slab_address(slab);
4586 void *p;
4587
4588 slab_err(s, slab, text, s->name);
4589
4590 spin_lock(&object_map_lock);
4591 __fill_map(object_map, s, slab);
4592
4593 for_each_object(p, s, addr, slab->objects) {
4594
4595 if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
4596 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
4597 print_tracking(s, p);
4598 }
4599 }
4600 spin_unlock(&object_map_lock);
4601 #endif
4602 }
4603
4604 /*
4605 * Attempt to free all partial slabs on a node.
4606 * This is called from __kmem_cache_shutdown(). We must take list_lock
4607 * because sysfs file might still access partial list after the shutdowning.
4608 */
free_partial(struct kmem_cache * s,struct kmem_cache_node * n)4609 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
4610 {
4611 LIST_HEAD(discard);
4612 struct slab *slab, *h;
4613
4614 BUG_ON(irqs_disabled());
4615 spin_lock_irq(&n->list_lock);
4616 list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
4617 if (!slab->inuse) {
4618 remove_partial(n, slab);
4619 list_add(&slab->slab_list, &discard);
4620 } else {
4621 list_slab_objects(s, slab,
4622 "Objects remaining in %s on __kmem_cache_shutdown()");
4623 }
4624 }
4625 spin_unlock_irq(&n->list_lock);
4626
4627 list_for_each_entry_safe(slab, h, &discard, slab_list)
4628 discard_slab(s, slab);
4629 }
4630
__kmem_cache_empty(struct kmem_cache * s)4631 bool __kmem_cache_empty(struct kmem_cache *s)
4632 {
4633 int node;
4634 struct kmem_cache_node *n;
4635
4636 for_each_kmem_cache_node(s, node, n)
4637 if (n->nr_partial || node_nr_slabs(n))
4638 return false;
4639 return true;
4640 }
4641
4642 /*
4643 * Release all resources used by a slab cache.
4644 */
__kmem_cache_shutdown(struct kmem_cache * s)4645 int __kmem_cache_shutdown(struct kmem_cache *s)
4646 {
4647 int node;
4648 struct kmem_cache_node *n;
4649
4650 flush_all_cpus_locked(s);
4651 /* Attempt to free all objects */
4652 for_each_kmem_cache_node(s, node, n) {
4653 free_partial(s, n);
4654 if (n->nr_partial || node_nr_slabs(n))
4655 return 1;
4656 }
4657 return 0;
4658 }
4659
4660 #ifdef CONFIG_PRINTK
__kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct slab * slab)4661 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
4662 {
4663 void *base;
4664 int __maybe_unused i;
4665 unsigned int objnr;
4666 void *objp;
4667 void *objp0;
4668 struct kmem_cache *s = slab->slab_cache;
4669 struct track __maybe_unused *trackp;
4670
4671 kpp->kp_ptr = object;
4672 kpp->kp_slab = slab;
4673 kpp->kp_slab_cache = s;
4674 base = slab_address(slab);
4675 objp0 = kasan_reset_tag(object);
4676 #ifdef CONFIG_SLUB_DEBUG
4677 objp = restore_red_left(s, objp0);
4678 #else
4679 objp = objp0;
4680 #endif
4681 objnr = obj_to_index(s, slab, objp);
4682 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
4683 objp = base + s->size * objnr;
4684 kpp->kp_objp = objp;
4685 if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
4686 || (objp - base) % s->size) ||
4687 !(s->flags & SLAB_STORE_USER))
4688 return;
4689 #ifdef CONFIG_SLUB_DEBUG
4690 objp = fixup_red_left(s, objp);
4691 trackp = get_track(s, objp, TRACK_ALLOC);
4692 kpp->kp_ret = (void *)trackp->addr;
4693 #ifdef CONFIG_STACKDEPOT
4694 {
4695 depot_stack_handle_t handle;
4696 unsigned long *entries;
4697 unsigned int nr_entries;
4698
4699 handle = READ_ONCE(trackp->handle);
4700 if (handle) {
4701 nr_entries = stack_depot_fetch(handle, &entries);
4702 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
4703 kpp->kp_stack[i] = (void *)entries[i];
4704 }
4705
4706 trackp = get_track(s, objp, TRACK_FREE);
4707 handle = READ_ONCE(trackp->handle);
4708 if (handle) {
4709 nr_entries = stack_depot_fetch(handle, &entries);
4710 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
4711 kpp->kp_free_stack[i] = (void *)entries[i];
4712 }
4713 }
4714 #endif
4715 #endif
4716 }
4717 #endif
4718
4719 /********************************************************************
4720 * Kmalloc subsystem
4721 *******************************************************************/
4722
setup_slub_min_order(char * str)4723 static int __init setup_slub_min_order(char *str)
4724 {
4725 get_option(&str, (int *)&slub_min_order);
4726
4727 return 1;
4728 }
4729
4730 __setup("slub_min_order=", setup_slub_min_order);
4731
setup_slub_max_order(char * str)4732 static int __init setup_slub_max_order(char *str)
4733 {
4734 get_option(&str, (int *)&slub_max_order);
4735 slub_max_order = min_t(unsigned int, slub_max_order, MAX_ORDER);
4736
4737 return 1;
4738 }
4739
4740 __setup("slub_max_order=", setup_slub_max_order);
4741
setup_slub_min_objects(char * str)4742 static int __init setup_slub_min_objects(char *str)
4743 {
4744 get_option(&str, (int *)&slub_min_objects);
4745
4746 return 1;
4747 }
4748
4749 __setup("slub_min_objects=", setup_slub_min_objects);
4750
4751 #ifdef CONFIG_HARDENED_USERCOPY
4752 /*
4753 * Rejects incorrectly sized objects and objects that are to be copied
4754 * to/from userspace but do not fall entirely within the containing slab
4755 * cache's usercopy region.
4756 *
4757 * Returns NULL if check passes, otherwise const char * to name of cache
4758 * to indicate an error.
4759 */
__check_heap_object(const void * ptr,unsigned long n,const struct slab * slab,bool to_user)4760 void __check_heap_object(const void *ptr, unsigned long n,
4761 const struct slab *slab, bool to_user)
4762 {
4763 struct kmem_cache *s;
4764 unsigned int offset;
4765 bool is_kfence = is_kfence_address(ptr);
4766
4767 ptr = kasan_reset_tag(ptr);
4768
4769 /* Find object and usable object size. */
4770 s = slab->slab_cache;
4771
4772 /* Reject impossible pointers. */
4773 if (ptr < slab_address(slab))
4774 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4775 to_user, 0, n);
4776
4777 /* Find offset within object. */
4778 if (is_kfence)
4779 offset = ptr - kfence_object_start(ptr);
4780 else
4781 offset = (ptr - slab_address(slab)) % s->size;
4782
4783 /* Adjust for redzone and reject if within the redzone. */
4784 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
4785 if (offset < s->red_left_pad)
4786 usercopy_abort("SLUB object in left red zone",
4787 s->name, to_user, offset, n);
4788 offset -= s->red_left_pad;
4789 }
4790
4791 /* Allow address range falling entirely within usercopy region. */
4792 if (offset >= s->useroffset &&
4793 offset - s->useroffset <= s->usersize &&
4794 n <= s->useroffset - offset + s->usersize)
4795 return;
4796
4797 usercopy_abort("SLUB object", s->name, to_user, offset, n);
4798 }
4799 #endif /* CONFIG_HARDENED_USERCOPY */
4800
4801 #define SHRINK_PROMOTE_MAX 32
4802
4803 /*
4804 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4805 * up most to the head of the partial lists. New allocations will then
4806 * fill those up and thus they can be removed from the partial lists.
4807 *
4808 * The slabs with the least items are placed last. This results in them
4809 * being allocated from last increasing the chance that the last objects
4810 * are freed in them.
4811 */
__kmem_cache_do_shrink(struct kmem_cache * s)4812 static int __kmem_cache_do_shrink(struct kmem_cache *s)
4813 {
4814 int node;
4815 int i;
4816 struct kmem_cache_node *n;
4817 struct slab *slab;
4818 struct slab *t;
4819 struct list_head discard;
4820 struct list_head promote[SHRINK_PROMOTE_MAX];
4821 unsigned long flags;
4822 int ret = 0;
4823
4824 for_each_kmem_cache_node(s, node, n) {
4825 INIT_LIST_HEAD(&discard);
4826 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4827 INIT_LIST_HEAD(promote + i);
4828
4829 spin_lock_irqsave(&n->list_lock, flags);
4830
4831 /*
4832 * Build lists of slabs to discard or promote.
4833 *
4834 * Note that concurrent frees may occur while we hold the
4835 * list_lock. slab->inuse here is the upper limit.
4836 */
4837 list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
4838 int free = slab->objects - slab->inuse;
4839
4840 /* Do not reread slab->inuse */
4841 barrier();
4842
4843 /* We do not keep full slabs on the list */
4844 BUG_ON(free <= 0);
4845
4846 if (free == slab->objects) {
4847 list_move(&slab->slab_list, &discard);
4848 n->nr_partial--;
4849 dec_slabs_node(s, node, slab->objects);
4850 } else if (free <= SHRINK_PROMOTE_MAX)
4851 list_move(&slab->slab_list, promote + free - 1);
4852 }
4853
4854 /*
4855 * Promote the slabs filled up most to the head of the
4856 * partial list.
4857 */
4858 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4859 list_splice(promote + i, &n->partial);
4860
4861 spin_unlock_irqrestore(&n->list_lock, flags);
4862
4863 /* Release empty slabs */
4864 list_for_each_entry_safe(slab, t, &discard, slab_list)
4865 free_slab(s, slab);
4866
4867 if (node_nr_slabs(n))
4868 ret = 1;
4869 }
4870
4871 return ret;
4872 }
4873
__kmem_cache_shrink(struct kmem_cache * s)4874 int __kmem_cache_shrink(struct kmem_cache *s)
4875 {
4876 flush_all(s);
4877 return __kmem_cache_do_shrink(s);
4878 }
4879
slab_mem_going_offline_callback(void * arg)4880 static int slab_mem_going_offline_callback(void *arg)
4881 {
4882 struct kmem_cache *s;
4883
4884 mutex_lock(&slab_mutex);
4885 list_for_each_entry(s, &slab_caches, list) {
4886 flush_all_cpus_locked(s);
4887 __kmem_cache_do_shrink(s);
4888 }
4889 mutex_unlock(&slab_mutex);
4890
4891 return 0;
4892 }
4893
slab_mem_offline_callback(void * arg)4894 static void slab_mem_offline_callback(void *arg)
4895 {
4896 struct memory_notify *marg = arg;
4897 int offline_node;
4898
4899 offline_node = marg->status_change_nid_normal;
4900
4901 /*
4902 * If the node still has available memory. we need kmem_cache_node
4903 * for it yet.
4904 */
4905 if (offline_node < 0)
4906 return;
4907
4908 mutex_lock(&slab_mutex);
4909 node_clear(offline_node, slab_nodes);
4910 /*
4911 * We no longer free kmem_cache_node structures here, as it would be
4912 * racy with all get_node() users, and infeasible to protect them with
4913 * slab_mutex.
4914 */
4915 mutex_unlock(&slab_mutex);
4916 }
4917
slab_mem_going_online_callback(void * arg)4918 static int slab_mem_going_online_callback(void *arg)
4919 {
4920 struct kmem_cache_node *n;
4921 struct kmem_cache *s;
4922 struct memory_notify *marg = arg;
4923 int nid = marg->status_change_nid_normal;
4924 int ret = 0;
4925
4926 /*
4927 * If the node's memory is already available, then kmem_cache_node is
4928 * already created. Nothing to do.
4929 */
4930 if (nid < 0)
4931 return 0;
4932
4933 /*
4934 * We are bringing a node online. No memory is available yet. We must
4935 * allocate a kmem_cache_node structure in order to bring the node
4936 * online.
4937 */
4938 mutex_lock(&slab_mutex);
4939 list_for_each_entry(s, &slab_caches, list) {
4940 /*
4941 * The structure may already exist if the node was previously
4942 * onlined and offlined.
4943 */
4944 if (get_node(s, nid))
4945 continue;
4946 /*
4947 * XXX: kmem_cache_alloc_node will fallback to other nodes
4948 * since memory is not yet available from the node that
4949 * is brought up.
4950 */
4951 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
4952 if (!n) {
4953 ret = -ENOMEM;
4954 goto out;
4955 }
4956 init_kmem_cache_node(n);
4957 s->node[nid] = n;
4958 }
4959 /*
4960 * Any cache created after this point will also have kmem_cache_node
4961 * initialized for the new node.
4962 */
4963 node_set(nid, slab_nodes);
4964 out:
4965 mutex_unlock(&slab_mutex);
4966 return ret;
4967 }
4968
slab_memory_callback(struct notifier_block * self,unsigned long action,void * arg)4969 static int slab_memory_callback(struct notifier_block *self,
4970 unsigned long action, void *arg)
4971 {
4972 int ret = 0;
4973
4974 switch (action) {
4975 case MEM_GOING_ONLINE:
4976 ret = slab_mem_going_online_callback(arg);
4977 break;
4978 case MEM_GOING_OFFLINE:
4979 ret = slab_mem_going_offline_callback(arg);
4980 break;
4981 case MEM_OFFLINE:
4982 case MEM_CANCEL_ONLINE:
4983 slab_mem_offline_callback(arg);
4984 break;
4985 case MEM_ONLINE:
4986 case MEM_CANCEL_OFFLINE:
4987 break;
4988 }
4989 if (ret)
4990 ret = notifier_from_errno(ret);
4991 else
4992 ret = NOTIFY_OK;
4993 return ret;
4994 }
4995
4996 /********************************************************************
4997 * Basic setup of slabs
4998 *******************************************************************/
4999
5000 /*
5001 * Used for early kmem_cache structures that were allocated using
5002 * the page allocator. Allocate them properly then fix up the pointers
5003 * that may be pointing to the wrong kmem_cache structure.
5004 */
5005
bootstrap(struct kmem_cache * static_cache)5006 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
5007 {
5008 int node;
5009 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
5010 struct kmem_cache_node *n;
5011
5012 memcpy(s, static_cache, kmem_cache->object_size);
5013
5014 /*
5015 * This runs very early, and only the boot processor is supposed to be
5016 * up. Even if it weren't true, IRQs are not up so we couldn't fire
5017 * IPIs around.
5018 */
5019 __flush_cpu_slab(s, smp_processor_id());
5020 for_each_kmem_cache_node(s, node, n) {
5021 struct slab *p;
5022
5023 list_for_each_entry(p, &n->partial, slab_list)
5024 p->slab_cache = s;
5025
5026 #ifdef CONFIG_SLUB_DEBUG
5027 list_for_each_entry(p, &n->full, slab_list)
5028 p->slab_cache = s;
5029 #endif
5030 }
5031 list_add(&s->list, &slab_caches);
5032 return s;
5033 }
5034
kmem_cache_init(void)5035 void __init kmem_cache_init(void)
5036 {
5037 static __initdata struct kmem_cache boot_kmem_cache,
5038 boot_kmem_cache_node;
5039 int node;
5040
5041 if (debug_guardpage_minorder())
5042 slub_max_order = 0;
5043
5044 /* Print slub debugging pointers without hashing */
5045 if (__slub_debug_enabled())
5046 no_hash_pointers_enable(NULL);
5047
5048 kmem_cache_node = &boot_kmem_cache_node;
5049 kmem_cache = &boot_kmem_cache;
5050
5051 /*
5052 * Initialize the nodemask for which we will allocate per node
5053 * structures. Here we don't need taking slab_mutex yet.
5054 */
5055 for_each_node_state(node, N_NORMAL_MEMORY)
5056 node_set(node, slab_nodes);
5057
5058 create_boot_cache(kmem_cache_node, "kmem_cache_node",
5059 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
5060
5061 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
5062
5063 /* Able to allocate the per node structures */
5064 slab_state = PARTIAL;
5065
5066 create_boot_cache(kmem_cache, "kmem_cache",
5067 offsetof(struct kmem_cache, node) +
5068 nr_node_ids * sizeof(struct kmem_cache_node *),
5069 SLAB_HWCACHE_ALIGN, 0, 0);
5070
5071 kmem_cache = bootstrap(&boot_kmem_cache);
5072 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
5073
5074 /* Now we can use the kmem_cache to allocate kmalloc slabs */
5075 setup_kmalloc_cache_index_table();
5076 create_kmalloc_caches(0);
5077
5078 /* Setup random freelists for each cache */
5079 init_freelist_randomization();
5080
5081 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
5082 slub_cpu_dead);
5083
5084 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
5085 cache_line_size(),
5086 slub_min_order, slub_max_order, slub_min_objects,
5087 nr_cpu_ids, nr_node_ids);
5088 }
5089
kmem_cache_init_late(void)5090 void __init kmem_cache_init_late(void)
5091 {
5092 #ifndef CONFIG_SLUB_TINY
5093 flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
5094 WARN_ON(!flushwq);
5095 #endif
5096 }
5097
5098 struct kmem_cache *
__kmem_cache_alias(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))5099 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
5100 slab_flags_t flags, void (*ctor)(void *))
5101 {
5102 struct kmem_cache *s;
5103
5104 s = find_mergeable(size, align, flags, name, ctor);
5105 if (s) {
5106 if (sysfs_slab_alias(s, name))
5107 return NULL;
5108
5109 s->refcount++;
5110
5111 /*
5112 * Adjust the object sizes so that we clear
5113 * the complete object on kzalloc.
5114 */
5115 s->object_size = max(s->object_size, size);
5116 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
5117 }
5118
5119 return s;
5120 }
5121
__kmem_cache_create(struct kmem_cache * s,slab_flags_t flags)5122 int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
5123 {
5124 int err;
5125
5126 err = kmem_cache_open(s, flags);
5127 if (err)
5128 return err;
5129
5130 /* Mutex is not taken during early boot */
5131 if (slab_state <= UP)
5132 return 0;
5133
5134 err = sysfs_slab_add(s);
5135 if (err) {
5136 __kmem_cache_release(s);
5137 return err;
5138 }
5139
5140 if (s->flags & SLAB_STORE_USER)
5141 debugfs_slab_add(s);
5142
5143 return 0;
5144 }
5145
5146 #ifdef SLAB_SUPPORTS_SYSFS
count_inuse(struct slab * slab)5147 static int count_inuse(struct slab *slab)
5148 {
5149 return slab->inuse;
5150 }
5151
count_total(struct slab * slab)5152 static int count_total(struct slab *slab)
5153 {
5154 return slab->objects;
5155 }
5156 #endif
5157
5158 #ifdef CONFIG_SLUB_DEBUG
validate_slab(struct kmem_cache * s,struct slab * slab,unsigned long * obj_map)5159 static void validate_slab(struct kmem_cache *s, struct slab *slab,
5160 unsigned long *obj_map)
5161 {
5162 void *p;
5163 void *addr = slab_address(slab);
5164
5165 if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
5166 return;
5167
5168 /* Now we know that a valid freelist exists */
5169 __fill_map(obj_map, s, slab);
5170 for_each_object(p, s, addr, slab->objects) {
5171 u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
5172 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
5173
5174 if (!check_object(s, slab, p, val))
5175 break;
5176 }
5177 }
5178
validate_slab_node(struct kmem_cache * s,struct kmem_cache_node * n,unsigned long * obj_map)5179 static int validate_slab_node(struct kmem_cache *s,
5180 struct kmem_cache_node *n, unsigned long *obj_map)
5181 {
5182 unsigned long count = 0;
5183 struct slab *slab;
5184 unsigned long flags;
5185
5186 spin_lock_irqsave(&n->list_lock, flags);
5187
5188 list_for_each_entry(slab, &n->partial, slab_list) {
5189 validate_slab(s, slab, obj_map);
5190 count++;
5191 }
5192 if (count != n->nr_partial) {
5193 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
5194 s->name, count, n->nr_partial);
5195 slab_add_kunit_errors();
5196 }
5197
5198 if (!(s->flags & SLAB_STORE_USER))
5199 goto out;
5200
5201 list_for_each_entry(slab, &n->full, slab_list) {
5202 validate_slab(s, slab, obj_map);
5203 count++;
5204 }
5205 if (count != node_nr_slabs(n)) {
5206 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
5207 s->name, count, node_nr_slabs(n));
5208 slab_add_kunit_errors();
5209 }
5210
5211 out:
5212 spin_unlock_irqrestore(&n->list_lock, flags);
5213 return count;
5214 }
5215
validate_slab_cache(struct kmem_cache * s)5216 long validate_slab_cache(struct kmem_cache *s)
5217 {
5218 int node;
5219 unsigned long count = 0;
5220 struct kmem_cache_node *n;
5221 unsigned long *obj_map;
5222
5223 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
5224 if (!obj_map)
5225 return -ENOMEM;
5226
5227 flush_all(s);
5228 for_each_kmem_cache_node(s, node, n)
5229 count += validate_slab_node(s, n, obj_map);
5230
5231 bitmap_free(obj_map);
5232
5233 return count;
5234 }
5235 EXPORT_SYMBOL(validate_slab_cache);
5236
5237 #ifdef CONFIG_DEBUG_FS
5238 /*
5239 * Generate lists of code addresses where slabcache objects are allocated
5240 * and freed.
5241 */
5242
5243 struct location {
5244 depot_stack_handle_t handle;
5245 unsigned long count;
5246 unsigned long addr;
5247 unsigned long waste;
5248 long long sum_time;
5249 long min_time;
5250 long max_time;
5251 long min_pid;
5252 long max_pid;
5253 DECLARE_BITMAP(cpus, NR_CPUS);
5254 nodemask_t nodes;
5255 };
5256
5257 struct loc_track {
5258 unsigned long max;
5259 unsigned long count;
5260 struct location *loc;
5261 loff_t idx;
5262 };
5263
5264 static struct dentry *slab_debugfs_root;
5265
free_loc_track(struct loc_track * t)5266 static void free_loc_track(struct loc_track *t)
5267 {
5268 if (t->max)
5269 free_pages((unsigned long)t->loc,
5270 get_order(sizeof(struct location) * t->max));
5271 }
5272
alloc_loc_track(struct loc_track * t,unsigned long max,gfp_t flags)5273 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
5274 {
5275 struct location *l;
5276 int order;
5277
5278 order = get_order(sizeof(struct location) * max);
5279
5280 l = (void *)__get_free_pages(flags, order);
5281 if (!l)
5282 return 0;
5283
5284 if (t->count) {
5285 memcpy(l, t->loc, sizeof(struct location) * t->count);
5286 free_loc_track(t);
5287 }
5288 t->max = max;
5289 t->loc = l;
5290 return 1;
5291 }
5292
add_location(struct loc_track * t,struct kmem_cache * s,const struct track * track,unsigned int orig_size)5293 static int add_location(struct loc_track *t, struct kmem_cache *s,
5294 const struct track *track,
5295 unsigned int orig_size)
5296 {
5297 long start, end, pos;
5298 struct location *l;
5299 unsigned long caddr, chandle, cwaste;
5300 unsigned long age = jiffies - track->when;
5301 depot_stack_handle_t handle = 0;
5302 unsigned int waste = s->object_size - orig_size;
5303
5304 #ifdef CONFIG_STACKDEPOT
5305 handle = READ_ONCE(track->handle);
5306 #endif
5307 start = -1;
5308 end = t->count;
5309
5310 for ( ; ; ) {
5311 pos = start + (end - start + 1) / 2;
5312
5313 /*
5314 * There is nothing at "end". If we end up there
5315 * we need to add something to before end.
5316 */
5317 if (pos == end)
5318 break;
5319
5320 l = &t->loc[pos];
5321 caddr = l->addr;
5322 chandle = l->handle;
5323 cwaste = l->waste;
5324 if ((track->addr == caddr) && (handle == chandle) &&
5325 (waste == cwaste)) {
5326
5327 l->count++;
5328 if (track->when) {
5329 l->sum_time += age;
5330 if (age < l->min_time)
5331 l->min_time = age;
5332 if (age > l->max_time)
5333 l->max_time = age;
5334
5335 if (track->pid < l->min_pid)
5336 l->min_pid = track->pid;
5337 if (track->pid > l->max_pid)
5338 l->max_pid = track->pid;
5339
5340 cpumask_set_cpu(track->cpu,
5341 to_cpumask(l->cpus));
5342 }
5343 node_set(page_to_nid(virt_to_page(track)), l->nodes);
5344 return 1;
5345 }
5346
5347 if (track->addr < caddr)
5348 end = pos;
5349 else if (track->addr == caddr && handle < chandle)
5350 end = pos;
5351 else if (track->addr == caddr && handle == chandle &&
5352 waste < cwaste)
5353 end = pos;
5354 else
5355 start = pos;
5356 }
5357
5358 /*
5359 * Not found. Insert new tracking element.
5360 */
5361 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
5362 return 0;
5363
5364 l = t->loc + pos;
5365 if (pos < t->count)
5366 memmove(l + 1, l,
5367 (t->count - pos) * sizeof(struct location));
5368 t->count++;
5369 l->count = 1;
5370 l->addr = track->addr;
5371 l->sum_time = age;
5372 l->min_time = age;
5373 l->max_time = age;
5374 l->min_pid = track->pid;
5375 l->max_pid = track->pid;
5376 l->handle = handle;
5377 l->waste = waste;
5378 cpumask_clear(to_cpumask(l->cpus));
5379 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
5380 nodes_clear(l->nodes);
5381 node_set(page_to_nid(virt_to_page(track)), l->nodes);
5382 return 1;
5383 }
5384
process_slab(struct loc_track * t,struct kmem_cache * s,struct slab * slab,enum track_item alloc,unsigned long * obj_map)5385 static void process_slab(struct loc_track *t, struct kmem_cache *s,
5386 struct slab *slab, enum track_item alloc,
5387 unsigned long *obj_map)
5388 {
5389 void *addr = slab_address(slab);
5390 bool is_alloc = (alloc == TRACK_ALLOC);
5391 void *p;
5392
5393 __fill_map(obj_map, s, slab);
5394
5395 for_each_object(p, s, addr, slab->objects)
5396 if (!test_bit(__obj_to_index(s, addr, p), obj_map))
5397 add_location(t, s, get_track(s, p, alloc),
5398 is_alloc ? get_orig_size(s, p) :
5399 s->object_size);
5400 }
5401 #endif /* CONFIG_DEBUG_FS */
5402 #endif /* CONFIG_SLUB_DEBUG */
5403
5404 #ifdef SLAB_SUPPORTS_SYSFS
5405 enum slab_stat_type {
5406 SL_ALL, /* All slabs */
5407 SL_PARTIAL, /* Only partially allocated slabs */
5408 SL_CPU, /* Only slabs used for cpu caches */
5409 SL_OBJECTS, /* Determine allocated objects not slabs */
5410 SL_TOTAL /* Determine object capacity not slabs */
5411 };
5412
5413 #define SO_ALL (1 << SL_ALL)
5414 #define SO_PARTIAL (1 << SL_PARTIAL)
5415 #define SO_CPU (1 << SL_CPU)
5416 #define SO_OBJECTS (1 << SL_OBJECTS)
5417 #define SO_TOTAL (1 << SL_TOTAL)
5418
show_slab_objects(struct kmem_cache * s,char * buf,unsigned long flags)5419 static ssize_t show_slab_objects(struct kmem_cache *s,
5420 char *buf, unsigned long flags)
5421 {
5422 unsigned long total = 0;
5423 int node;
5424 int x;
5425 unsigned long *nodes;
5426 int len = 0;
5427
5428 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
5429 if (!nodes)
5430 return -ENOMEM;
5431
5432 if (flags & SO_CPU) {
5433 int cpu;
5434
5435 for_each_possible_cpu(cpu) {
5436 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
5437 cpu);
5438 int node;
5439 struct slab *slab;
5440
5441 slab = READ_ONCE(c->slab);
5442 if (!slab)
5443 continue;
5444
5445 node = slab_nid(slab);
5446 if (flags & SO_TOTAL)
5447 x = slab->objects;
5448 else if (flags & SO_OBJECTS)
5449 x = slab->inuse;
5450 else
5451 x = 1;
5452
5453 total += x;
5454 nodes[node] += x;
5455
5456 #ifdef CONFIG_SLUB_CPU_PARTIAL
5457 slab = slub_percpu_partial_read_once(c);
5458 if (slab) {
5459 node = slab_nid(slab);
5460 if (flags & SO_TOTAL)
5461 WARN_ON_ONCE(1);
5462 else if (flags & SO_OBJECTS)
5463 WARN_ON_ONCE(1);
5464 else
5465 x = slab->slabs;
5466 total += x;
5467 nodes[node] += x;
5468 }
5469 #endif
5470 }
5471 }
5472
5473 /*
5474 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
5475 * already held which will conflict with an existing lock order:
5476 *
5477 * mem_hotplug_lock->slab_mutex->kernfs_mutex
5478 *
5479 * We don't really need mem_hotplug_lock (to hold off
5480 * slab_mem_going_offline_callback) here because slab's memory hot
5481 * unplug code doesn't destroy the kmem_cache->node[] data.
5482 */
5483
5484 #ifdef CONFIG_SLUB_DEBUG
5485 if (flags & SO_ALL) {
5486 struct kmem_cache_node *n;
5487
5488 for_each_kmem_cache_node(s, node, n) {
5489
5490 if (flags & SO_TOTAL)
5491 x = node_nr_objs(n);
5492 else if (flags & SO_OBJECTS)
5493 x = node_nr_objs(n) - count_partial(n, count_free);
5494 else
5495 x = node_nr_slabs(n);
5496 total += x;
5497 nodes[node] += x;
5498 }
5499
5500 } else
5501 #endif
5502 if (flags & SO_PARTIAL) {
5503 struct kmem_cache_node *n;
5504
5505 for_each_kmem_cache_node(s, node, n) {
5506 if (flags & SO_TOTAL)
5507 x = count_partial(n, count_total);
5508 else if (flags & SO_OBJECTS)
5509 x = count_partial(n, count_inuse);
5510 else
5511 x = n->nr_partial;
5512 total += x;
5513 nodes[node] += x;
5514 }
5515 }
5516
5517 len += sysfs_emit_at(buf, len, "%lu", total);
5518 #ifdef CONFIG_NUMA
5519 for (node = 0; node < nr_node_ids; node++) {
5520 if (nodes[node])
5521 len += sysfs_emit_at(buf, len, " N%d=%lu",
5522 node, nodes[node]);
5523 }
5524 #endif
5525 len += sysfs_emit_at(buf, len, "\n");
5526 kfree(nodes);
5527
5528 return len;
5529 }
5530
5531 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
5532 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
5533
5534 struct slab_attribute {
5535 struct attribute attr;
5536 ssize_t (*show)(struct kmem_cache *s, char *buf);
5537 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5538 };
5539
5540 #define SLAB_ATTR_RO(_name) \
5541 static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
5542
5543 #define SLAB_ATTR(_name) \
5544 static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
5545
slab_size_show(struct kmem_cache * s,char * buf)5546 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5547 {
5548 return sysfs_emit(buf, "%u\n", s->size);
5549 }
5550 SLAB_ATTR_RO(slab_size);
5551
align_show(struct kmem_cache * s,char * buf)5552 static ssize_t align_show(struct kmem_cache *s, char *buf)
5553 {
5554 return sysfs_emit(buf, "%u\n", s->align);
5555 }
5556 SLAB_ATTR_RO(align);
5557
object_size_show(struct kmem_cache * s,char * buf)5558 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5559 {
5560 return sysfs_emit(buf, "%u\n", s->object_size);
5561 }
5562 SLAB_ATTR_RO(object_size);
5563
objs_per_slab_show(struct kmem_cache * s,char * buf)5564 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5565 {
5566 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
5567 }
5568 SLAB_ATTR_RO(objs_per_slab);
5569
order_show(struct kmem_cache * s,char * buf)5570 static ssize_t order_show(struct kmem_cache *s, char *buf)
5571 {
5572 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
5573 }
5574 SLAB_ATTR_RO(order);
5575
min_partial_show(struct kmem_cache * s,char * buf)5576 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5577 {
5578 return sysfs_emit(buf, "%lu\n", s->min_partial);
5579 }
5580
min_partial_store(struct kmem_cache * s,const char * buf,size_t length)5581 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5582 size_t length)
5583 {
5584 unsigned long min;
5585 int err;
5586
5587 err = kstrtoul(buf, 10, &min);
5588 if (err)
5589 return err;
5590
5591 s->min_partial = min;
5592 return length;
5593 }
5594 SLAB_ATTR(min_partial);
5595
cpu_partial_show(struct kmem_cache * s,char * buf)5596 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5597 {
5598 unsigned int nr_partial = 0;
5599 #ifdef CONFIG_SLUB_CPU_PARTIAL
5600 nr_partial = s->cpu_partial;
5601 #endif
5602
5603 return sysfs_emit(buf, "%u\n", nr_partial);
5604 }
5605
cpu_partial_store(struct kmem_cache * s,const char * buf,size_t length)5606 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5607 size_t length)
5608 {
5609 unsigned int objects;
5610 int err;
5611
5612 err = kstrtouint(buf, 10, &objects);
5613 if (err)
5614 return err;
5615 if (objects && !kmem_cache_has_cpu_partial(s))
5616 return -EINVAL;
5617
5618 slub_set_cpu_partial(s, objects);
5619 flush_all(s);
5620 return length;
5621 }
5622 SLAB_ATTR(cpu_partial);
5623
ctor_show(struct kmem_cache * s,char * buf)5624 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5625 {
5626 if (!s->ctor)
5627 return 0;
5628 return sysfs_emit(buf, "%pS\n", s->ctor);
5629 }
5630 SLAB_ATTR_RO(ctor);
5631
aliases_show(struct kmem_cache * s,char * buf)5632 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5633 {
5634 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
5635 }
5636 SLAB_ATTR_RO(aliases);
5637
partial_show(struct kmem_cache * s,char * buf)5638 static ssize_t partial_show(struct kmem_cache *s, char *buf)
5639 {
5640 return show_slab_objects(s, buf, SO_PARTIAL);
5641 }
5642 SLAB_ATTR_RO(partial);
5643
cpu_slabs_show(struct kmem_cache * s,char * buf)5644 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5645 {
5646 return show_slab_objects(s, buf, SO_CPU);
5647 }
5648 SLAB_ATTR_RO(cpu_slabs);
5649
objects_partial_show(struct kmem_cache * s,char * buf)5650 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5651 {
5652 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5653 }
5654 SLAB_ATTR_RO(objects_partial);
5655
slabs_cpu_partial_show(struct kmem_cache * s,char * buf)5656 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5657 {
5658 int objects = 0;
5659 int slabs = 0;
5660 int cpu __maybe_unused;
5661 int len = 0;
5662
5663 #ifdef CONFIG_SLUB_CPU_PARTIAL
5664 for_each_online_cpu(cpu) {
5665 struct slab *slab;
5666
5667 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5668
5669 if (slab)
5670 slabs += slab->slabs;
5671 }
5672 #endif
5673
5674 /* Approximate half-full slabs, see slub_set_cpu_partial() */
5675 objects = (slabs * oo_objects(s->oo)) / 2;
5676 len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
5677
5678 #ifdef CONFIG_SLUB_CPU_PARTIAL
5679 for_each_online_cpu(cpu) {
5680 struct slab *slab;
5681
5682 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5683 if (slab) {
5684 slabs = READ_ONCE(slab->slabs);
5685 objects = (slabs * oo_objects(s->oo)) / 2;
5686 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
5687 cpu, objects, slabs);
5688 }
5689 }
5690 #endif
5691 len += sysfs_emit_at(buf, len, "\n");
5692
5693 return len;
5694 }
5695 SLAB_ATTR_RO(slabs_cpu_partial);
5696
reclaim_account_show(struct kmem_cache * s,char * buf)5697 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5698 {
5699 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
5700 }
5701 SLAB_ATTR_RO(reclaim_account);
5702
hwcache_align_show(struct kmem_cache * s,char * buf)5703 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5704 {
5705 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
5706 }
5707 SLAB_ATTR_RO(hwcache_align);
5708
5709 #ifdef CONFIG_ZONE_DMA
cache_dma_show(struct kmem_cache * s,char * buf)5710 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5711 {
5712 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
5713 }
5714 SLAB_ATTR_RO(cache_dma);
5715 #endif
5716
5717 #ifdef CONFIG_HARDENED_USERCOPY
usersize_show(struct kmem_cache * s,char * buf)5718 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5719 {
5720 return sysfs_emit(buf, "%u\n", s->usersize);
5721 }
5722 SLAB_ATTR_RO(usersize);
5723 #endif
5724
destroy_by_rcu_show(struct kmem_cache * s,char * buf)5725 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5726 {
5727 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
5728 }
5729 SLAB_ATTR_RO(destroy_by_rcu);
5730
5731 #ifdef CONFIG_SLUB_DEBUG
slabs_show(struct kmem_cache * s,char * buf)5732 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5733 {
5734 return show_slab_objects(s, buf, SO_ALL);
5735 }
5736 SLAB_ATTR_RO(slabs);
5737
total_objects_show(struct kmem_cache * s,char * buf)5738 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5739 {
5740 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5741 }
5742 SLAB_ATTR_RO(total_objects);
5743
objects_show(struct kmem_cache * s,char * buf)5744 static ssize_t objects_show(struct kmem_cache *s, char *buf)
5745 {
5746 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
5747 }
5748 SLAB_ATTR_RO(objects);
5749
sanity_checks_show(struct kmem_cache * s,char * buf)5750 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5751 {
5752 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
5753 }
5754 SLAB_ATTR_RO(sanity_checks);
5755
trace_show(struct kmem_cache * s,char * buf)5756 static ssize_t trace_show(struct kmem_cache *s, char *buf)
5757 {
5758 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
5759 }
5760 SLAB_ATTR_RO(trace);
5761
red_zone_show(struct kmem_cache * s,char * buf)5762 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5763 {
5764 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
5765 }
5766
5767 SLAB_ATTR_RO(red_zone);
5768
poison_show(struct kmem_cache * s,char * buf)5769 static ssize_t poison_show(struct kmem_cache *s, char *buf)
5770 {
5771 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
5772 }
5773
5774 SLAB_ATTR_RO(poison);
5775
store_user_show(struct kmem_cache * s,char * buf)5776 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5777 {
5778 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
5779 }
5780
5781 SLAB_ATTR_RO(store_user);
5782
validate_show(struct kmem_cache * s,char * buf)5783 static ssize_t validate_show(struct kmem_cache *s, char *buf)
5784 {
5785 return 0;
5786 }
5787
validate_store(struct kmem_cache * s,const char * buf,size_t length)5788 static ssize_t validate_store(struct kmem_cache *s,
5789 const char *buf, size_t length)
5790 {
5791 int ret = -EINVAL;
5792
5793 if (buf[0] == '1' && kmem_cache_debug(s)) {
5794 ret = validate_slab_cache(s);
5795 if (ret >= 0)
5796 ret = length;
5797 }
5798 return ret;
5799 }
5800 SLAB_ATTR(validate);
5801
5802 #endif /* CONFIG_SLUB_DEBUG */
5803
5804 #ifdef CONFIG_FAILSLAB
failslab_show(struct kmem_cache * s,char * buf)5805 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5806 {
5807 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
5808 }
5809
failslab_store(struct kmem_cache * s,const char * buf,size_t length)5810 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5811 size_t length)
5812 {
5813 if (s->refcount > 1)
5814 return -EINVAL;
5815
5816 if (buf[0] == '1')
5817 WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
5818 else
5819 WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
5820
5821 return length;
5822 }
5823 SLAB_ATTR(failslab);
5824 #endif
5825
shrink_show(struct kmem_cache * s,char * buf)5826 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5827 {
5828 return 0;
5829 }
5830
shrink_store(struct kmem_cache * s,const char * buf,size_t length)5831 static ssize_t shrink_store(struct kmem_cache *s,
5832 const char *buf, size_t length)
5833 {
5834 if (buf[0] == '1')
5835 kmem_cache_shrink(s);
5836 else
5837 return -EINVAL;
5838 return length;
5839 }
5840 SLAB_ATTR(shrink);
5841
5842 #ifdef CONFIG_NUMA
remote_node_defrag_ratio_show(struct kmem_cache * s,char * buf)5843 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
5844 {
5845 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
5846 }
5847
remote_node_defrag_ratio_store(struct kmem_cache * s,const char * buf,size_t length)5848 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
5849 const char *buf, size_t length)
5850 {
5851 unsigned int ratio;
5852 int err;
5853
5854 err = kstrtouint(buf, 10, &ratio);
5855 if (err)
5856 return err;
5857 if (ratio > 100)
5858 return -ERANGE;
5859
5860 s->remote_node_defrag_ratio = ratio * 10;
5861
5862 return length;
5863 }
5864 SLAB_ATTR(remote_node_defrag_ratio);
5865 #endif
5866
5867 #ifdef CONFIG_SLUB_STATS
show_stat(struct kmem_cache * s,char * buf,enum stat_item si)5868 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5869 {
5870 unsigned long sum = 0;
5871 int cpu;
5872 int len = 0;
5873 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
5874
5875 if (!data)
5876 return -ENOMEM;
5877
5878 for_each_online_cpu(cpu) {
5879 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5880
5881 data[cpu] = x;
5882 sum += x;
5883 }
5884
5885 len += sysfs_emit_at(buf, len, "%lu", sum);
5886
5887 #ifdef CONFIG_SMP
5888 for_each_online_cpu(cpu) {
5889 if (data[cpu])
5890 len += sysfs_emit_at(buf, len, " C%d=%u",
5891 cpu, data[cpu]);
5892 }
5893 #endif
5894 kfree(data);
5895 len += sysfs_emit_at(buf, len, "\n");
5896
5897 return len;
5898 }
5899
clear_stat(struct kmem_cache * s,enum stat_item si)5900 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5901 {
5902 int cpu;
5903
5904 for_each_online_cpu(cpu)
5905 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5906 }
5907
5908 #define STAT_ATTR(si, text) \
5909 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5910 { \
5911 return show_stat(s, buf, si); \
5912 } \
5913 static ssize_t text##_store(struct kmem_cache *s, \
5914 const char *buf, size_t length) \
5915 { \
5916 if (buf[0] != '0') \
5917 return -EINVAL; \
5918 clear_stat(s, si); \
5919 return length; \
5920 } \
5921 SLAB_ATTR(text); \
5922
5923 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5924 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5925 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5926 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5927 STAT_ATTR(FREE_FROZEN, free_frozen);
5928 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5929 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5930 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5931 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5932 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5933 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5934 STAT_ATTR(FREE_SLAB, free_slab);
5935 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5936 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5937 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5938 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5939 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5940 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5941 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5942 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5943 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5944 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5945 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5946 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5947 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5948 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5949 #endif /* CONFIG_SLUB_STATS */
5950
5951 #ifdef CONFIG_KFENCE
skip_kfence_show(struct kmem_cache * s,char * buf)5952 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
5953 {
5954 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
5955 }
5956
skip_kfence_store(struct kmem_cache * s,const char * buf,size_t length)5957 static ssize_t skip_kfence_store(struct kmem_cache *s,
5958 const char *buf, size_t length)
5959 {
5960 int ret = length;
5961
5962 if (buf[0] == '0')
5963 s->flags &= ~SLAB_SKIP_KFENCE;
5964 else if (buf[0] == '1')
5965 s->flags |= SLAB_SKIP_KFENCE;
5966 else
5967 ret = -EINVAL;
5968
5969 return ret;
5970 }
5971 SLAB_ATTR(skip_kfence);
5972 #endif
5973
5974 static struct attribute *slab_attrs[] = {
5975 &slab_size_attr.attr,
5976 &object_size_attr.attr,
5977 &objs_per_slab_attr.attr,
5978 &order_attr.attr,
5979 &min_partial_attr.attr,
5980 &cpu_partial_attr.attr,
5981 &objects_partial_attr.attr,
5982 &partial_attr.attr,
5983 &cpu_slabs_attr.attr,
5984 &ctor_attr.attr,
5985 &aliases_attr.attr,
5986 &align_attr.attr,
5987 &hwcache_align_attr.attr,
5988 &reclaim_account_attr.attr,
5989 &destroy_by_rcu_attr.attr,
5990 &shrink_attr.attr,
5991 &slabs_cpu_partial_attr.attr,
5992 #ifdef CONFIG_SLUB_DEBUG
5993 &total_objects_attr.attr,
5994 &objects_attr.attr,
5995 &slabs_attr.attr,
5996 &sanity_checks_attr.attr,
5997 &trace_attr.attr,
5998 &red_zone_attr.attr,
5999 &poison_attr.attr,
6000 &store_user_attr.attr,
6001 &validate_attr.attr,
6002 #endif
6003 #ifdef CONFIG_ZONE_DMA
6004 &cache_dma_attr.attr,
6005 #endif
6006 #ifdef CONFIG_NUMA
6007 &remote_node_defrag_ratio_attr.attr,
6008 #endif
6009 #ifdef CONFIG_SLUB_STATS
6010 &alloc_fastpath_attr.attr,
6011 &alloc_slowpath_attr.attr,
6012 &free_fastpath_attr.attr,
6013 &free_slowpath_attr.attr,
6014 &free_frozen_attr.attr,
6015 &free_add_partial_attr.attr,
6016 &free_remove_partial_attr.attr,
6017 &alloc_from_partial_attr.attr,
6018 &alloc_slab_attr.attr,
6019 &alloc_refill_attr.attr,
6020 &alloc_node_mismatch_attr.attr,
6021 &free_slab_attr.attr,
6022 &cpuslab_flush_attr.attr,
6023 &deactivate_full_attr.attr,
6024 &deactivate_empty_attr.attr,
6025 &deactivate_to_head_attr.attr,
6026 &deactivate_to_tail_attr.attr,
6027 &deactivate_remote_frees_attr.attr,
6028 &deactivate_bypass_attr.attr,
6029 &order_fallback_attr.attr,
6030 &cmpxchg_double_fail_attr.attr,
6031 &cmpxchg_double_cpu_fail_attr.attr,
6032 &cpu_partial_alloc_attr.attr,
6033 &cpu_partial_free_attr.attr,
6034 &cpu_partial_node_attr.attr,
6035 &cpu_partial_drain_attr.attr,
6036 #endif
6037 #ifdef CONFIG_FAILSLAB
6038 &failslab_attr.attr,
6039 #endif
6040 #ifdef CONFIG_HARDENED_USERCOPY
6041 &usersize_attr.attr,
6042 #endif
6043 #ifdef CONFIG_KFENCE
6044 &skip_kfence_attr.attr,
6045 #endif
6046
6047 NULL
6048 };
6049
6050 static const struct attribute_group slab_attr_group = {
6051 .attrs = slab_attrs,
6052 };
6053
slab_attr_show(struct kobject * kobj,struct attribute * attr,char * buf)6054 static ssize_t slab_attr_show(struct kobject *kobj,
6055 struct attribute *attr,
6056 char *buf)
6057 {
6058 struct slab_attribute *attribute;
6059 struct kmem_cache *s;
6060
6061 attribute = to_slab_attr(attr);
6062 s = to_slab(kobj);
6063
6064 if (!attribute->show)
6065 return -EIO;
6066
6067 return attribute->show(s, buf);
6068 }
6069
slab_attr_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t len)6070 static ssize_t slab_attr_store(struct kobject *kobj,
6071 struct attribute *attr,
6072 const char *buf, size_t len)
6073 {
6074 struct slab_attribute *attribute;
6075 struct kmem_cache *s;
6076
6077 attribute = to_slab_attr(attr);
6078 s = to_slab(kobj);
6079
6080 if (!attribute->store)
6081 return -EIO;
6082
6083 return attribute->store(s, buf, len);
6084 }
6085
kmem_cache_release(struct kobject * k)6086 static void kmem_cache_release(struct kobject *k)
6087 {
6088 slab_kmem_cache_release(to_slab(k));
6089 }
6090
6091 static const struct sysfs_ops slab_sysfs_ops = {
6092 .show = slab_attr_show,
6093 .store = slab_attr_store,
6094 };
6095
6096 static const struct kobj_type slab_ktype = {
6097 .sysfs_ops = &slab_sysfs_ops,
6098 .release = kmem_cache_release,
6099 };
6100
6101 static struct kset *slab_kset;
6102
cache_kset(struct kmem_cache * s)6103 static inline struct kset *cache_kset(struct kmem_cache *s)
6104 {
6105 return slab_kset;
6106 }
6107
6108 #define ID_STR_LENGTH 32
6109
6110 /* Create a unique string id for a slab cache:
6111 *
6112 * Format :[flags-]size
6113 */
create_unique_id(struct kmem_cache * s)6114 static char *create_unique_id(struct kmem_cache *s)
6115 {
6116 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
6117 char *p = name;
6118
6119 if (!name)
6120 return ERR_PTR(-ENOMEM);
6121
6122 *p++ = ':';
6123 /*
6124 * First flags affecting slabcache operations. We will only
6125 * get here for aliasable slabs so we do not need to support
6126 * too many flags. The flags here must cover all flags that
6127 * are matched during merging to guarantee that the id is
6128 * unique.
6129 */
6130 if (s->flags & SLAB_CACHE_DMA)
6131 *p++ = 'd';
6132 if (s->flags & SLAB_CACHE_DMA32)
6133 *p++ = 'D';
6134 if (s->flags & SLAB_RECLAIM_ACCOUNT)
6135 *p++ = 'a';
6136 if (s->flags & SLAB_CONSISTENCY_CHECKS)
6137 *p++ = 'F';
6138 if (s->flags & SLAB_ACCOUNT)
6139 *p++ = 'A';
6140 if (p != name + 1)
6141 *p++ = '-';
6142 p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
6143
6144 if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
6145 kfree(name);
6146 return ERR_PTR(-EINVAL);
6147 }
6148 kmsan_unpoison_memory(name, p - name);
6149 return name;
6150 }
6151
sysfs_slab_add(struct kmem_cache * s)6152 static int sysfs_slab_add(struct kmem_cache *s)
6153 {
6154 int err;
6155 const char *name;
6156 struct kset *kset = cache_kset(s);
6157 int unmergeable = slab_unmergeable(s);
6158
6159 if (!unmergeable && disable_higher_order_debug &&
6160 (slub_debug & DEBUG_METADATA_FLAGS))
6161 unmergeable = 1;
6162
6163 if (unmergeable) {
6164 /*
6165 * Slabcache can never be merged so we can use the name proper.
6166 * This is typically the case for debug situations. In that
6167 * case we can catch duplicate names easily.
6168 */
6169 sysfs_remove_link(&slab_kset->kobj, s->name);
6170 name = s->name;
6171 } else {
6172 /*
6173 * Create a unique name for the slab as a target
6174 * for the symlinks.
6175 */
6176 name = create_unique_id(s);
6177 if (IS_ERR(name))
6178 return PTR_ERR(name);
6179 }
6180
6181 s->kobj.kset = kset;
6182 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
6183 if (err)
6184 goto out;
6185
6186 err = sysfs_create_group(&s->kobj, &slab_attr_group);
6187 if (err)
6188 goto out_del_kobj;
6189
6190 if (!unmergeable) {
6191 /* Setup first alias */
6192 sysfs_slab_alias(s, s->name);
6193 }
6194 out:
6195 if (!unmergeable)
6196 kfree(name);
6197 return err;
6198 out_del_kobj:
6199 kobject_del(&s->kobj);
6200 goto out;
6201 }
6202
sysfs_slab_unlink(struct kmem_cache * s)6203 void sysfs_slab_unlink(struct kmem_cache *s)
6204 {
6205 if (slab_state >= FULL)
6206 kobject_del(&s->kobj);
6207 }
6208
sysfs_slab_release(struct kmem_cache * s)6209 void sysfs_slab_release(struct kmem_cache *s)
6210 {
6211 if (slab_state >= FULL)
6212 kobject_put(&s->kobj);
6213 }
6214
6215 /*
6216 * Need to buffer aliases during bootup until sysfs becomes
6217 * available lest we lose that information.
6218 */
6219 struct saved_alias {
6220 struct kmem_cache *s;
6221 const char *name;
6222 struct saved_alias *next;
6223 };
6224
6225 static struct saved_alias *alias_list;
6226
sysfs_slab_alias(struct kmem_cache * s,const char * name)6227 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
6228 {
6229 struct saved_alias *al;
6230
6231 if (slab_state == FULL) {
6232 /*
6233 * If we have a leftover link then remove it.
6234 */
6235 sysfs_remove_link(&slab_kset->kobj, name);
6236 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
6237 }
6238
6239 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
6240 if (!al)
6241 return -ENOMEM;
6242
6243 al->s = s;
6244 al->name = name;
6245 al->next = alias_list;
6246 alias_list = al;
6247 kmsan_unpoison_memory(al, sizeof(*al));
6248 return 0;
6249 }
6250
slab_sysfs_init(void)6251 static int __init slab_sysfs_init(void)
6252 {
6253 struct kmem_cache *s;
6254 int err;
6255
6256 mutex_lock(&slab_mutex);
6257
6258 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
6259 if (!slab_kset) {
6260 mutex_unlock(&slab_mutex);
6261 pr_err("Cannot register slab subsystem.\n");
6262 return -ENOMEM;
6263 }
6264
6265 slab_state = FULL;
6266
6267 list_for_each_entry(s, &slab_caches, list) {
6268 err = sysfs_slab_add(s);
6269 if (err)
6270 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
6271 s->name);
6272 }
6273
6274 while (alias_list) {
6275 struct saved_alias *al = alias_list;
6276
6277 alias_list = alias_list->next;
6278 err = sysfs_slab_alias(al->s, al->name);
6279 if (err)
6280 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
6281 al->name);
6282 kfree(al);
6283 }
6284
6285 mutex_unlock(&slab_mutex);
6286 return 0;
6287 }
6288 late_initcall(slab_sysfs_init);
6289 #endif /* SLAB_SUPPORTS_SYSFS */
6290
6291 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
slab_debugfs_show(struct seq_file * seq,void * v)6292 static int slab_debugfs_show(struct seq_file *seq, void *v)
6293 {
6294 struct loc_track *t = seq->private;
6295 struct location *l;
6296 unsigned long idx;
6297
6298 idx = (unsigned long) t->idx;
6299 if (idx < t->count) {
6300 l = &t->loc[idx];
6301
6302 seq_printf(seq, "%7ld ", l->count);
6303
6304 if (l->addr)
6305 seq_printf(seq, "%pS", (void *)l->addr);
6306 else
6307 seq_puts(seq, "<not-available>");
6308
6309 if (l->waste)
6310 seq_printf(seq, " waste=%lu/%lu",
6311 l->count * l->waste, l->waste);
6312
6313 if (l->sum_time != l->min_time) {
6314 seq_printf(seq, " age=%ld/%llu/%ld",
6315 l->min_time, div_u64(l->sum_time, l->count),
6316 l->max_time);
6317 } else
6318 seq_printf(seq, " age=%ld", l->min_time);
6319
6320 if (l->min_pid != l->max_pid)
6321 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
6322 else
6323 seq_printf(seq, " pid=%ld",
6324 l->min_pid);
6325
6326 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
6327 seq_printf(seq, " cpus=%*pbl",
6328 cpumask_pr_args(to_cpumask(l->cpus)));
6329
6330 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
6331 seq_printf(seq, " nodes=%*pbl",
6332 nodemask_pr_args(&l->nodes));
6333
6334 #ifdef CONFIG_STACKDEPOT
6335 {
6336 depot_stack_handle_t handle;
6337 unsigned long *entries;
6338 unsigned int nr_entries, j;
6339
6340 handle = READ_ONCE(l->handle);
6341 if (handle) {
6342 nr_entries = stack_depot_fetch(handle, &entries);
6343 seq_puts(seq, "\n");
6344 for (j = 0; j < nr_entries; j++)
6345 seq_printf(seq, " %pS\n", (void *)entries[j]);
6346 }
6347 }
6348 #endif
6349 seq_puts(seq, "\n");
6350 }
6351
6352 if (!idx && !t->count)
6353 seq_puts(seq, "No data\n");
6354
6355 return 0;
6356 }
6357
slab_debugfs_stop(struct seq_file * seq,void * v)6358 static void slab_debugfs_stop(struct seq_file *seq, void *v)
6359 {
6360 }
6361
slab_debugfs_next(struct seq_file * seq,void * v,loff_t * ppos)6362 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
6363 {
6364 struct loc_track *t = seq->private;
6365
6366 t->idx = ++(*ppos);
6367 if (*ppos <= t->count)
6368 return ppos;
6369
6370 return NULL;
6371 }
6372
cmp_loc_by_count(const void * a,const void * b,const void * data)6373 static int cmp_loc_by_count(const void *a, const void *b, const void *data)
6374 {
6375 struct location *loc1 = (struct location *)a;
6376 struct location *loc2 = (struct location *)b;
6377
6378 if (loc1->count > loc2->count)
6379 return -1;
6380 else
6381 return 1;
6382 }
6383
slab_debugfs_start(struct seq_file * seq,loff_t * ppos)6384 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
6385 {
6386 struct loc_track *t = seq->private;
6387
6388 t->idx = *ppos;
6389 return ppos;
6390 }
6391
6392 static const struct seq_operations slab_debugfs_sops = {
6393 .start = slab_debugfs_start,
6394 .next = slab_debugfs_next,
6395 .stop = slab_debugfs_stop,
6396 .show = slab_debugfs_show,
6397 };
6398
slab_debug_trace_open(struct inode * inode,struct file * filep)6399 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
6400 {
6401
6402 struct kmem_cache_node *n;
6403 enum track_item alloc;
6404 int node;
6405 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
6406 sizeof(struct loc_track));
6407 struct kmem_cache *s = file_inode(filep)->i_private;
6408 unsigned long *obj_map;
6409
6410 if (!t)
6411 return -ENOMEM;
6412
6413 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
6414 if (!obj_map) {
6415 seq_release_private(inode, filep);
6416 return -ENOMEM;
6417 }
6418
6419 if (strcmp(filep->f_path.dentry->d_name.name, "alloc_traces") == 0)
6420 alloc = TRACK_ALLOC;
6421 else
6422 alloc = TRACK_FREE;
6423
6424 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
6425 bitmap_free(obj_map);
6426 seq_release_private(inode, filep);
6427 return -ENOMEM;
6428 }
6429
6430 for_each_kmem_cache_node(s, node, n) {
6431 unsigned long flags;
6432 struct slab *slab;
6433
6434 if (!node_nr_slabs(n))
6435 continue;
6436
6437 spin_lock_irqsave(&n->list_lock, flags);
6438 list_for_each_entry(slab, &n->partial, slab_list)
6439 process_slab(t, s, slab, alloc, obj_map);
6440 list_for_each_entry(slab, &n->full, slab_list)
6441 process_slab(t, s, slab, alloc, obj_map);
6442 spin_unlock_irqrestore(&n->list_lock, flags);
6443 }
6444
6445 /* Sort locations by count */
6446 sort_r(t->loc, t->count, sizeof(struct location),
6447 cmp_loc_by_count, NULL, NULL);
6448
6449 bitmap_free(obj_map);
6450 return 0;
6451 }
6452
slab_debug_trace_release(struct inode * inode,struct file * file)6453 static int slab_debug_trace_release(struct inode *inode, struct file *file)
6454 {
6455 struct seq_file *seq = file->private_data;
6456 struct loc_track *t = seq->private;
6457
6458 free_loc_track(t);
6459 return seq_release_private(inode, file);
6460 }
6461
6462 static const struct file_operations slab_debugfs_fops = {
6463 .open = slab_debug_trace_open,
6464 .read = seq_read,
6465 .llseek = seq_lseek,
6466 .release = slab_debug_trace_release,
6467 };
6468
debugfs_slab_add(struct kmem_cache * s)6469 static void debugfs_slab_add(struct kmem_cache *s)
6470 {
6471 struct dentry *slab_cache_dir;
6472
6473 if (unlikely(!slab_debugfs_root))
6474 return;
6475
6476 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
6477
6478 debugfs_create_file("alloc_traces", 0400,
6479 slab_cache_dir, s, &slab_debugfs_fops);
6480
6481 debugfs_create_file("free_traces", 0400,
6482 slab_cache_dir, s, &slab_debugfs_fops);
6483 }
6484
debugfs_slab_release(struct kmem_cache * s)6485 void debugfs_slab_release(struct kmem_cache *s)
6486 {
6487 debugfs_lookup_and_remove(s->name, slab_debugfs_root);
6488 }
6489
slab_debugfs_init(void)6490 static int __init slab_debugfs_init(void)
6491 {
6492 struct kmem_cache *s;
6493
6494 slab_debugfs_root = debugfs_create_dir("slab", NULL);
6495
6496 list_for_each_entry(s, &slab_caches, list)
6497 if (s->flags & SLAB_STORE_USER)
6498 debugfs_slab_add(s);
6499
6500 return 0;
6501
6502 }
6503 __initcall(slab_debugfs_init);
6504 #endif
6505 /*
6506 * The /proc/slabinfo ABI
6507 */
6508 #ifdef CONFIG_SLUB_DEBUG
get_slabinfo(struct kmem_cache * s,struct slabinfo * sinfo)6509 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
6510 {
6511 unsigned long nr_slabs = 0;
6512 unsigned long nr_objs = 0;
6513 unsigned long nr_free = 0;
6514 int node;
6515 struct kmem_cache_node *n;
6516
6517 for_each_kmem_cache_node(s, node, n) {
6518 nr_slabs += node_nr_slabs(n);
6519 nr_objs += node_nr_objs(n);
6520 nr_free += count_partial(n, count_free);
6521 }
6522
6523 sinfo->active_objs = nr_objs - nr_free;
6524 sinfo->num_objs = nr_objs;
6525 sinfo->active_slabs = nr_slabs;
6526 sinfo->num_slabs = nr_slabs;
6527 sinfo->objects_per_slab = oo_objects(s->oo);
6528 sinfo->cache_order = oo_order(s->oo);
6529 }
6530
slabinfo_show_stats(struct seq_file * m,struct kmem_cache * s)6531 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
6532 {
6533 }
6534
slabinfo_write(struct file * file,const char __user * buffer,size_t count,loff_t * ppos)6535 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
6536 size_t count, loff_t *ppos)
6537 {
6538 return -EIO;
6539 }
6540 #endif /* CONFIG_SLUB_DEBUG */
6541