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