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