xref: /linux/mm/slub.c (revision 335c347686e76df9d2c7d7f61b5ea627a4c5cb4c)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * SLUB: A slab allocator with low overhead percpu array caches and mostly
4  * lockless freeing of objects to slabs in the slowpath.
5  *
6  * The allocator synchronizes using spin_trylock for percpu arrays in the
7  * fastpath, and cmpxchg_double (or bit spinlock) for slowpath freeing.
8  * Uses a centralized lock to manage a pool of partial slabs.
9  *
10  * (C) 2007 SGI, Christoph Lameter
11  * (C) 2011 Linux Foundation, Christoph Lameter
12  * (C) 2025 SUSE, Vlastimil Babka
13  */
14 
15 #include <linux/mm.h>
16 #include <linux/swap.h> /* mm_account_reclaimed_pages() */
17 #include <linux/module.h>
18 #include <linux/bit_spinlock.h>
19 #include <linux/interrupt.h>
20 #include <linux/swab.h>
21 #include <linux/bitops.h>
22 #include <linux/slab.h>
23 #include "slab.h"
24 #include <linux/vmalloc.h>
25 #include <linux/proc_fs.h>
26 #include <linux/seq_file.h>
27 #include <linux/kasan.h>
28 #include <linux/node.h>
29 #include <linux/kmsan.h>
30 #include <linux/cpu.h>
31 #include <linux/cpuset.h>
32 #include <linux/mempolicy.h>
33 #include <linux/ctype.h>
34 #include <linux/stackdepot.h>
35 #include <linux/debugobjects.h>
36 #include <linux/kallsyms.h>
37 #include <linux/kfence.h>
38 #include <linux/memory.h>
39 #include <linux/math64.h>
40 #include <linux/fault-inject.h>
41 #include <linux/kmemleak.h>
42 #include <linux/stacktrace.h>
43 #include <linux/prefetch.h>
44 #include <linux/memcontrol.h>
45 #include <linux/random.h>
46 #include <linux/prandom.h>
47 #include <kunit/test.h>
48 #include <kunit/test-bug.h>
49 #include <linux/sort.h>
50 #include <linux/irq_work.h>
51 #include <linux/kprobes.h>
52 #include <linux/debugfs.h>
53 #include <trace/events/kmem.h>
54 
55 #include "internal.h"
56 
57 /*
58  * Lock order:
59  *   0.  cpu_hotplug_lock
60  *   1.  slab_mutex (Global Mutex)
61  *   2a. kmem_cache->cpu_sheaves->lock (Local trylock)
62  *   2b. barn->lock (Spinlock)
63  *   2c. node->list_lock (Spinlock)
64  *   3.  slab_lock(slab) (Only on some arches)
65  *   4.  object_map_lock (Only for debugging)
66  *
67  *   slab_mutex
68  *
69  *   The role of the slab_mutex is to protect the list of all the slabs
70  *   and to synchronize major metadata changes to slab cache structures.
71  *   Also synchronizes memory hotplug callbacks.
72  *
73  *   slab_lock
74  *
75  *   The slab_lock is a wrapper around the page lock, thus it is a bit
76  *   spinlock.
77  *
78  *   The slab_lock is only used on arches that do not have the ability
79  *   to do a cmpxchg_double. It only protects:
80  *
81  *	A. slab->freelist	-> List of free objects in a slab
82  *	B. slab->inuse		-> Number of objects in use
83  *	C. slab->objects	-> Number of objects in slab
84  *	D. slab->frozen		-> frozen state
85  *
86  *   SL_partial slabs
87  *
88  *   Slabs on node partial list have at least one free object. A limited number
89  *   of slabs on the list can be fully free (slab->inuse == 0), until we start
90  *   discarding them. These slabs are marked with SL_partial, and the flag is
91  *   cleared while removing them, usually to grab their freelist afterwards.
92  *   This clearing also exempts them from list management. Please see
93  *   __slab_free() for more details.
94  *
95  *   Full slabs
96  *
97  *   For caches without debugging enabled, full slabs (slab->inuse ==
98  *   slab->objects and slab->freelist == NULL) are not placed on any list.
99  *   The __slab_free() freeing the first object from such a slab will place
100  *   it on the partial list. Caches with debugging enabled place such slab
101  *   on the full list and use different allocation and freeing paths.
102  *
103  *   Frozen slabs
104  *
105  *   If a slab is frozen then it is exempt from list management. It is used to
106  *   indicate a slab that has failed consistency checks and thus cannot be
107  *   allocated from anymore - it is also marked as full. Any previously
108  *   allocated objects will be simply leaked upon freeing instead of attempting
109  *   to modify the potentially corrupted freelist and metadata.
110  *
111  *   To sum up, the current scheme is:
112  *   - node partial slab:            SL_partial && !full && !frozen
113  *   - taken off partial list:      !SL_partial && !full && !frozen
114  *   - full slab, not on any list:  !SL_partial &&  full && !frozen
115  *   - frozen due to inconsistency: !SL_partial &&  full &&  frozen
116  *
117  *   node->list_lock (spinlock)
118  *
119  *   The list_lock protects the partial and full list on each node and
120  *   the partial slab counter. If taken then no new slabs may be added or
121  *   removed from the lists nor make the number of partial slabs be modified.
122  *   (Note that the total number of slabs is an atomic value that may be
123  *   modified without taking the list lock).
124  *
125  *   The list_lock is a centralized lock and thus we avoid taking it as
126  *   much as possible. As long as SLUB does not have to handle partial
127  *   slabs, operations can continue without any centralized lock.
128  *
129  *   For debug caches, all allocations are forced to go through a list_lock
130  *   protected region to serialize against concurrent validation.
131  *
132  *   cpu_sheaves->lock (local_trylock)
133  *
134  *   This lock protects fastpath operations on the percpu sheaves. On !RT it
135  *   only disables preemption and does no atomic operations. As long as the main
136  *   or spare sheaf can handle the allocation or free, there is no other
137  *   overhead.
138  *
139  *   barn->lock (spinlock)
140  *
141  *   This lock protects the operations on per-NUMA-node barn. It can quickly
142  *   serve an empty or full sheaf if available, and avoid more expensive refill
143  *   or flush operation.
144  *
145  *   Lockless freeing
146  *
147  *   Objects may have to be freed to their slabs when they are from a remote
148  *   node (where we want to avoid filling local sheaves with remote objects)
149  *   or when there are too many full sheaves. On architectures supporting
150  *   cmpxchg_double this is done by a lockless update of slab's freelist and
151  *   counters, otherwise slab_lock is taken. This only needs to take the
152  *   list_lock if it's a first free to a full slab, or when a slab becomes empty
153  *   after the free.
154  *
155  *   irq, preemption, migration considerations
156  *
157  *   Interrupts are disabled as part of list_lock or barn lock operations, or
158  *   around the slab_lock operation, in order to make the slab allocator safe
159  *   to use in the context of an irq.
160  *   Preemption is disabled as part of local_trylock operations.
161  *   kmalloc_nolock() and kfree_nolock() are safe in NMI context but see
162  *   their limitations.
163  *
164  * SLUB assigns two object arrays called sheaves for caching allocations and
165  * frees on each cpu, with a NUMA node shared barn for balancing between cpus.
166  * Allocations and frees are primarily served from these sheaves.
167  *
168  * Slabs with free elements are kept on a partial list and during regular
169  * operations no list for full slabs is used. If an object in a full slab is
170  * freed then the slab will show up again on the partial lists.
171  * We track full slabs for debugging purposes though because otherwise we
172  * cannot scan all objects.
173  *
174  * Slabs are freed when they become empty. Teardown and setup is minimal so we
175  * rely on the page allocators per cpu caches for fast frees and allocs.
176  *
177  * SLAB_DEBUG_FLAGS	Slab requires special handling due to debug
178  * 			options set. This moves	slab handling out of
179  * 			the fast path and disables lockless freelists.
180  */
181 
182 /**
183  * enum slab_flags - How the slab flags bits are used.
184  * @SL_locked: Is locked with slab_lock()
185  * @SL_partial: On the per-node partial list
186  * @SL_pfmemalloc: Was allocated from PF_MEMALLOC reserves
187  *
188  * The slab flags share space with the page flags but some bits have
189  * different interpretations.  The high bits are used for information
190  * like zone/node/section.
191  */
192 enum slab_flags {
193 	SL_locked = PG_locked,
194 	SL_partial = PG_workingset,	/* Historical reasons for this bit */
195 	SL_pfmemalloc = PG_active,	/* Historical reasons for this bit */
196 };
197 
198 #ifndef CONFIG_SLUB_TINY
199 #define __fastpath_inline __always_inline
200 #else
201 #define __fastpath_inline
202 #endif
203 
204 #ifdef CONFIG_SLUB_DEBUG
205 #ifdef CONFIG_SLUB_DEBUG_ON
206 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
207 #else
208 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
209 #endif
210 #endif		/* CONFIG_SLUB_DEBUG */
211 
212 #ifdef CONFIG_NUMA
213 static DEFINE_STATIC_KEY_FALSE(strict_numa);
214 #endif
215 
216 /* Structure holding extra parameters for slab allocations */
217 struct slab_alloc_context {
218 	unsigned long caller_addr;
219 	size_t orig_size;
220 	unsigned int alloc_flags;
221 	struct list_lru *lru;
222 };
223 
224 /* Structure holding parameters for get_partial_node_bulk() */
225 struct partial_bulk_context {
226 	gfp_t flags;
227 	unsigned int min_objects;
228 	unsigned int max_objects;
229 	struct list_head slabs;
230 };
231 
232 /* Structure used to iterate over objects within a slab */
233 struct slab_obj_iter {
234 	unsigned long pos;
235 	void *start;
236 #ifdef CONFIG_SLAB_FREELIST_RANDOM
237 	unsigned long freelist_count;
238 	unsigned long page_limit;
239 	bool random;
240 #endif
241 };
242 
243 static inline bool kmem_cache_debug(struct kmem_cache *s)
244 {
245 	return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
246 }
247 
248 void *fixup_red_left(struct kmem_cache *s, void *p)
249 {
250 	if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
251 		p += s->red_left_pad;
252 
253 	return p;
254 }
255 
256 /*
257  * Issues still to be resolved:
258  *
259  * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
260  *
261  * - Variable sizing of the per node arrays
262  */
263 
264 /* Enable to log cmpxchg failures */
265 #undef SLUB_DEBUG_CMPXCHG
266 
267 #ifndef CONFIG_SLUB_TINY
268 /*
269  * Minimum number of partial slabs. These will be left on the partial
270  * lists even if they are empty. kmem_cache_shrink may reclaim them.
271  */
272 #define MIN_PARTIAL 5
273 
274 /*
275  * Maximum number of desirable partial slabs.
276  * The existence of more partial slabs makes kmem_cache_shrink
277  * sort the partial list by the number of objects in use.
278  */
279 #define MAX_PARTIAL 10
280 #else
281 #define MIN_PARTIAL 0
282 #define MAX_PARTIAL 0
283 #endif
284 
285 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
286 				SLAB_POISON | SLAB_STORE_USER)
287 
288 /*
289  * These debug flags cannot use CMPXCHG because there might be consistency
290  * issues when checking or reading debug information
291  */
292 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
293 				SLAB_TRACE)
294 
295 
296 /*
297  * Debugging flags that require metadata to be stored in the slab.  These get
298  * disabled when slab_debug=O is used and a cache's min order increases with
299  * metadata.
300  */
301 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
302 
303 #define OO_SHIFT	16
304 #define OO_MASK		((1 << OO_SHIFT) - 1)
305 #define MAX_OBJS_PER_PAGE	32767 /* since slab.objects is u15 */
306 
307 /* Internal SLUB flags */
308 /* Poison object */
309 #define __OBJECT_POISON		__SLAB_FLAG_BIT(_SLAB_OBJECT_POISON)
310 /* Use cmpxchg_double */
311 
312 #ifdef system_has_freelist_aba
313 #define __CMPXCHG_DOUBLE	__SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE)
314 #else
315 #define __CMPXCHG_DOUBLE	__SLAB_FLAG_UNUSED
316 #endif
317 
318 /*
319  * Tracking user of a slab.
320  */
321 #define TRACK_ADDRS_COUNT 16
322 struct track {
323 	unsigned long addr;	/* Called from address */
324 #ifdef CONFIG_STACKDEPOT
325 	depot_stack_handle_t handle;
326 #endif
327 	int cpu;		/* Was running on cpu */
328 	int pid;		/* Pid context */
329 	unsigned long when;	/* When did the operation occur */
330 };
331 
332 enum track_item { TRACK_ALLOC, TRACK_FREE };
333 
334 #ifdef SLAB_SUPPORTS_SYSFS
335 static int sysfs_slab_add(struct kmem_cache *);
336 #else
337 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
338 #endif
339 
340 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
341 static void debugfs_slab_add(struct kmem_cache *);
342 #else
343 static inline void debugfs_slab_add(struct kmem_cache *s) { }
344 #endif
345 
346 enum add_mode {
347 	ADD_TO_HEAD,
348 	ADD_TO_TAIL,
349 };
350 
351 enum stat_item {
352 	ALLOC_FASTPATH,		/* Allocation from percpu sheaves */
353 	ALLOC_SLOWPATH,		/* Allocation from partial or new slab */
354 	FREE_RCU_SHEAF,		/* Free to rcu_free sheaf */
355 	FREE_RCU_SHEAF_FAIL,	/* Failed to free to a rcu_free sheaf */
356 	FREE_FASTPATH,		/* Free to percpu sheaves */
357 	FREE_SLOWPATH,		/* Free to a slab */
358 	FREE_ADD_PARTIAL,	/* Freeing moves slab to partial list */
359 	FREE_REMOVE_PARTIAL,	/* Freeing removes last object */
360 	ALLOC_SLAB,		/* New slab acquired from page allocator */
361 	ALLOC_NODE_MISMATCH,	/* Requested node different from cpu sheaf */
362 	FREE_SLAB,		/* Slab freed to the page allocator */
363 	ORDER_FALLBACK,		/* Number of times fallback was necessary */
364 	CMPXCHG_DOUBLE_FAIL,	/* Failures of slab freelist update */
365 	SHEAF_FLUSH,		/* Objects flushed from a sheaf */
366 	SHEAF_REFILL,		/* Objects refilled to a sheaf */
367 	SHEAF_ALLOC,		/* Allocation of an empty sheaf including oversized ones */
368 	SHEAF_FREE,		/* Freeing of an empty sheaf including oversized ones */
369 	BARN_GET,		/* Got full sheaf from barn */
370 	BARN_GET_FAIL,		/* Failed to get full sheaf from barn */
371 	BARN_PUT,		/* Put full sheaf to barn */
372 	BARN_PUT_FAIL,		/* Failed to put full sheaf to barn */
373 	SHEAF_PREFILL_FAST,	/* Sheaf prefill grabbed the spare sheaf */
374 	SHEAF_PREFILL_SLOW,	/* Sheaf prefill found no spare sheaf */
375 	SHEAF_PREFILL_OVERSIZE,	/* Allocation of oversize sheaf for prefill */
376 	SHEAF_RETURN_FAST,	/* Sheaf return reattached spare sheaf */
377 	SHEAF_RETURN_SLOW,	/* Sheaf return could not reattach spare */
378 	NR_SLUB_STAT_ITEMS
379 };
380 
381 #ifdef CONFIG_SLUB_STATS
382 struct kmem_cache_stats {
383 	unsigned int stat[NR_SLUB_STAT_ITEMS];
384 };
385 #endif
386 
387 static inline void stat(const struct kmem_cache *s, enum stat_item si)
388 {
389 #ifdef CONFIG_SLUB_STATS
390 	/*
391 	 * The rmw is racy on a preemptible kernel but this is acceptable, so
392 	 * avoid this_cpu_add()'s irq-disable overhead.
393 	 */
394 	raw_cpu_inc(s->cpu_stats->stat[si]);
395 #endif
396 }
397 
398 static inline
399 void stat_add(const struct kmem_cache *s, enum stat_item si, int v)
400 {
401 #ifdef CONFIG_SLUB_STATS
402 	raw_cpu_add(s->cpu_stats->stat[si], v);
403 #endif
404 }
405 
406 #define MAX_FULL_SHEAVES	10
407 #define MAX_EMPTY_SHEAVES	10
408 
409 struct node_barn {
410 	spinlock_t lock;
411 	struct list_head sheaves_full;
412 	struct list_head sheaves_empty;
413 	unsigned int nr_full;
414 	unsigned int nr_empty;
415 };
416 
417 struct slab_sheaf {
418 	union {
419 		struct rcu_head rcu_head;
420 		struct list_head barn_list;
421 		/* only used for prefilled sheafs */
422 		struct {
423 			unsigned int capacity;
424 			bool pfmemalloc;
425 		};
426 	};
427 	struct kmem_cache *cache;
428 	unsigned int size;
429 	int node; /* only used for rcu_sheaf */
430 	void *objects[];
431 };
432 
433 struct slub_percpu_sheaves {
434 	local_trylock_t lock;
435 	struct slab_sheaf *main; /* never NULL when unlocked */
436 	struct slab_sheaf *spare; /* empty or full, may be NULL */
437 	struct slab_sheaf *rcu_free; /* for batching kfree_rcu() */
438 };
439 
440 /*
441  * The slab lists for all objects.
442  */
443 struct kmem_cache_node {
444 	spinlock_t list_lock;
445 	unsigned long nr_partial;
446 	struct list_head partial;
447 #ifdef CONFIG_SLUB_DEBUG
448 	atomic_long_t nr_slabs;
449 	atomic_long_t total_objects;
450 	struct list_head full;
451 #endif
452 };
453 
454 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
455 {
456 	return s->per_node[node].node;
457 }
458 
459 static inline struct node_barn *get_barn_node(struct kmem_cache *s, int node)
460 {
461 	return s->per_node[node].barn;
462 }
463 
464 /*
465  * Get the barn of the current cpu's NUMA node. It may be a memoryless node.
466  */
467 static inline struct node_barn *get_barn(struct kmem_cache *s)
468 {
469 	return get_barn_node(s, numa_node_id());
470 }
471 
472 /*
473  * Iterator over all nodes. The body will be executed for each node that has
474  * a kmem_cache_node structure allocated (which is true for all online nodes)
475  */
476 #define for_each_kmem_cache_node(__s, __node, __n) \
477 	for (__node = 0; __node < nr_node_ids; __node++) \
478 		 if ((__n = get_node(__s, __node)))
479 
480 /*
481  * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
482  * Corresponds to node_state[N_MEMORY], but can temporarily
483  * differ during memory hotplug/hotremove operations.
484  * Protected by slab_mutex.
485  */
486 static nodemask_t slab_nodes;
487 
488 /*
489  * Similar to slab_nodes but for where we have node_barn allocated.
490  * Corresponds to N_ONLINE nodes.
491  */
492 static nodemask_t slab_barn_nodes;
493 
494 /*
495  * Workqueue used for flushing cpu and kfree_rcu sheaves.
496  */
497 static struct workqueue_struct *flushwq;
498 
499 struct slub_flush_work {
500 	struct work_struct work;
501 	struct kmem_cache *s;
502 	bool skip;
503 };
504 
505 static DEFINE_MUTEX(flush_lock);
506 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
507 
508 /********************************************************************
509  * 			Core slab cache functions
510  *******************************************************************/
511 
512 /*
513  * Returns freelist pointer (ptr). With hardening, this is obfuscated
514  * with an XOR of the address where the pointer is held and a per-cache
515  * random number.
516  */
517 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
518 					    void *ptr, unsigned long ptr_addr)
519 {
520 	unsigned long encoded;
521 
522 #ifdef CONFIG_SLAB_FREELIST_HARDENED
523 	encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
524 #else
525 	encoded = (unsigned long)ptr;
526 #endif
527 	return (freeptr_t){.v = encoded};
528 }
529 
530 static inline void *freelist_ptr_decode(const struct kmem_cache *s,
531 					freeptr_t ptr, unsigned long ptr_addr)
532 {
533 	void *decoded;
534 
535 #ifdef CONFIG_SLAB_FREELIST_HARDENED
536 	decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
537 #else
538 	decoded = (void *)ptr.v;
539 #endif
540 	return decoded;
541 }
542 
543 static inline void *get_freepointer(struct kmem_cache *s, void *object)
544 {
545 	unsigned long ptr_addr;
546 	freeptr_t p;
547 
548 	object = kasan_reset_tag(object);
549 	ptr_addr = (unsigned long)object + s->offset;
550 	p = *(freeptr_t *)(ptr_addr);
551 	return freelist_ptr_decode(s, p, ptr_addr);
552 }
553 
554 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
555 {
556 	unsigned long freeptr_addr = (unsigned long)object + s->offset;
557 
558 #ifdef CONFIG_SLAB_FREELIST_HARDENED
559 	BUG_ON(object == fp); /* naive detection of double free or corruption */
560 #endif
561 
562 	freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
563 	*(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
564 }
565 
566 /*
567  * See comment in calculate_sizes().
568  */
569 static inline bool freeptr_outside_object(struct kmem_cache *s)
570 {
571 	return s->offset >= s->inuse;
572 }
573 
574 /*
575  * Return offset of the end of info block which is inuse + free pointer if
576  * not overlapping with object.
577  */
578 static inline unsigned int get_info_end(struct kmem_cache *s)
579 {
580 	if (freeptr_outside_object(s))
581 		return s->inuse + sizeof(void *);
582 	else
583 		return s->inuse;
584 }
585 
586 /* Loop over all objects in a slab */
587 #define for_each_object(__p, __s, __addr, __objects) \
588 	for (__p = fixup_red_left(__s, __addr); \
589 		__p < (__addr) + (__objects) * (__s)->size; \
590 		__p += (__s)->size)
591 
592 static inline unsigned int order_objects(unsigned int order, unsigned int size)
593 {
594 	return ((unsigned int)PAGE_SIZE << order) / size;
595 }
596 
597 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
598 		unsigned int size)
599 {
600 	struct kmem_cache_order_objects x = {
601 		(order << OO_SHIFT) + order_objects(order, size)
602 	};
603 
604 	return x;
605 }
606 
607 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
608 {
609 	return x.x >> OO_SHIFT;
610 }
611 
612 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
613 {
614 	return x.x & OO_MASK;
615 }
616 
617 /*
618  * If network-based swap is enabled, slub must keep track of whether memory
619  * were allocated from pfmemalloc reserves.
620  */
621 static inline bool slab_test_pfmemalloc(const struct slab *slab)
622 {
623 	return test_bit(SL_pfmemalloc, &slab->flags.f);
624 }
625 
626 static inline void slab_set_pfmemalloc(struct slab *slab)
627 {
628 	set_bit(SL_pfmemalloc, &slab->flags.f);
629 }
630 
631 static inline void __slab_clear_pfmemalloc(struct slab *slab)
632 {
633 	__clear_bit(SL_pfmemalloc, &slab->flags.f);
634 }
635 
636 /*
637  * Per slab locking using the pagelock
638  */
639 static __always_inline void slab_lock(struct slab *slab)
640 {
641 	bit_spin_lock(SL_locked, &slab->flags.f);
642 }
643 
644 static __always_inline void slab_unlock(struct slab *slab)
645 {
646 	bit_spin_unlock(SL_locked, &slab->flags.f);
647 }
648 
649 static inline bool
650 __update_freelist_fast(struct slab *slab, struct freelist_counters *old,
651 		       struct freelist_counters *new)
652 {
653 #ifdef system_has_freelist_aba
654 	return try_cmpxchg_freelist(&slab->freelist_counters,
655 				    &old->freelist_counters,
656 				    new->freelist_counters);
657 #else
658 	return false;
659 #endif
660 }
661 
662 static inline bool
663 __update_freelist_slow(struct slab *slab, struct freelist_counters *old,
664 		       struct freelist_counters *new)
665 {
666 	bool ret = false;
667 
668 	slab_lock(slab);
669 	if (slab->freelist == old->freelist &&
670 	    slab->counters == old->counters) {
671 		slab->freelist = new->freelist;
672 		/* prevent tearing for the read in get_partial_node_bulk() */
673 		WRITE_ONCE(slab->counters, new->counters);
674 		ret = true;
675 	}
676 	slab_unlock(slab);
677 
678 	return ret;
679 }
680 
681 /*
682  * Interrupts must be disabled (for the fallback code to work right), typically
683  * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
684  * part of bit_spin_lock(), is sufficient because the policy is not to allow any
685  * allocation/ free operation in hardirq context. Therefore nothing can
686  * interrupt the operation.
687  */
688 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
689 		struct freelist_counters *old, struct freelist_counters *new, const char *n)
690 {
691 	bool ret;
692 
693 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
694 		lockdep_assert_irqs_disabled();
695 
696 	if (s->flags & __CMPXCHG_DOUBLE)
697 		ret = __update_freelist_fast(slab, old, new);
698 	else
699 		ret = __update_freelist_slow(slab, old, new);
700 
701 	if (likely(ret))
702 		return true;
703 
704 	cpu_relax();
705 	stat(s, CMPXCHG_DOUBLE_FAIL);
706 
707 #ifdef SLUB_DEBUG_CMPXCHG
708 	pr_info("%s %s: cmpxchg double redo ", n, s->name);
709 #endif
710 
711 	return false;
712 }
713 
714 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
715 		struct freelist_counters *old, struct freelist_counters *new, const char *n)
716 {
717 	bool ret;
718 
719 	if (s->flags & __CMPXCHG_DOUBLE) {
720 		ret = __update_freelist_fast(slab, old, new);
721 	} else {
722 		unsigned long flags;
723 
724 		local_irq_save(flags);
725 		ret = __update_freelist_slow(slab, old, new);
726 		local_irq_restore(flags);
727 	}
728 	if (likely(ret))
729 		return true;
730 
731 	cpu_relax();
732 	stat(s, CMPXCHG_DOUBLE_FAIL);
733 
734 #ifdef SLUB_DEBUG_CMPXCHG
735 	pr_info("%s %s: cmpxchg double redo ", n, s->name);
736 #endif
737 
738 	return false;
739 }
740 
741 /*
742  * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
743  * family will round up the real request size to these fixed ones, so
744  * there could be an extra area than what is requested. Save the original
745  * request size in the meta data area, for better debug and sanity check.
746  */
747 static inline void set_orig_size(struct kmem_cache *s,
748 				void *object, unsigned long orig_size)
749 {
750 	void *p = kasan_reset_tag(object);
751 
752 	if (!slub_debug_orig_size(s))
753 		return;
754 
755 	p += get_info_end(s);
756 	p += sizeof(struct track) * 2;
757 
758 	*(unsigned long *)p = orig_size;
759 }
760 
761 static inline unsigned long get_orig_size(struct kmem_cache *s, void *object)
762 {
763 	void *p = kasan_reset_tag(object);
764 
765 	if (is_kfence_address(object))
766 		return kfence_ksize(object);
767 
768 	if (!slub_debug_orig_size(s))
769 		return s->object_size;
770 
771 	p += get_info_end(s);
772 	p += sizeof(struct track) * 2;
773 
774 	return *(unsigned long *)p;
775 }
776 
777 #ifdef CONFIG_SLAB_OBJ_EXT
778 
779 /*
780  * Check if memory cgroup or memory allocation profiling is enabled.
781  * If enabled, SLUB tries to reduce memory overhead of accounting
782  * slab objects. If neither is enabled when this function is called,
783  * the optimization is simply skipped to avoid affecting caches that do not
784  * need slabobj_ext metadata.
785  *
786  * However, this may disable optimization when memory cgroup or memory
787  * allocation profiling is used, but slabs are created too early
788  * even before those subsystems are initialized.
789  */
790 static inline bool need_slab_obj_exts(struct kmem_cache *s)
791 {
792 	if (s->flags & SLAB_NO_OBJ_EXT)
793 		return false;
794 
795 	if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT))
796 		return true;
797 
798 	if (mem_alloc_profiling_enabled())
799 		return true;
800 
801 	return false;
802 }
803 
804 static inline unsigned int obj_exts_size_in_slab(struct slab *slab)
805 {
806 	return sizeof(struct slabobj_ext) * slab->objects;
807 }
808 
809 static inline unsigned long obj_exts_offset_in_slab(struct kmem_cache *s,
810 						    struct slab *slab)
811 {
812 	unsigned long objext_offset;
813 
814 	objext_offset = s->size * slab->objects;
815 	objext_offset = ALIGN(objext_offset, sizeof(struct slabobj_ext));
816 	return objext_offset;
817 }
818 
819 static inline bool obj_exts_fit_within_slab_leftover(struct kmem_cache *s,
820 						     struct slab *slab)
821 {
822 	unsigned long objext_offset = obj_exts_offset_in_slab(s, slab);
823 	unsigned long objext_size = obj_exts_size_in_slab(slab);
824 
825 	return objext_offset + objext_size <= slab_size(slab);
826 }
827 
828 static inline bool obj_exts_in_slab(struct kmem_cache *s, struct slab *slab)
829 {
830 	unsigned long obj_exts;
831 	unsigned long start;
832 	unsigned long end;
833 
834 	obj_exts = slab_obj_exts(slab);
835 	if (!obj_exts)
836 		return false;
837 
838 	start = (unsigned long)slab_address(slab);
839 	end = start + slab_size(slab);
840 	return (obj_exts >= start) && (obj_exts < end);
841 }
842 #else
843 static inline bool need_slab_obj_exts(struct kmem_cache *s)
844 {
845 	return false;
846 }
847 
848 static inline unsigned int obj_exts_size_in_slab(struct slab *slab)
849 {
850 	return 0;
851 }
852 
853 static inline unsigned long obj_exts_offset_in_slab(struct kmem_cache *s,
854 						    struct slab *slab)
855 {
856 	return 0;
857 }
858 
859 static inline bool obj_exts_fit_within_slab_leftover(struct kmem_cache *s,
860 						     struct slab *slab)
861 {
862 	return false;
863 }
864 
865 static inline bool obj_exts_in_slab(struct kmem_cache *s, struct slab *slab)
866 {
867 	return false;
868 }
869 
870 #endif
871 
872 #if defined(CONFIG_SLAB_OBJ_EXT) && defined(CONFIG_64BIT)
873 static bool obj_exts_in_object(struct kmem_cache *s, struct slab *slab)
874 {
875 	/*
876 	 * Note we cannot rely on the SLAB_OBJ_EXT_IN_OBJ flag here and need to
877 	 * check the stride. A cache can have SLAB_OBJ_EXT_IN_OBJ set, but
878 	 * allocations within_slab_leftover are preferred. And those may be
879 	 * possible or not depending on the particular slab's size.
880 	 */
881 	return obj_exts_in_slab(s, slab) &&
882 	       (slab_get_stride(slab) == s->size);
883 }
884 
885 static unsigned int obj_exts_offset_in_object(struct kmem_cache *s)
886 {
887 	unsigned int offset = get_info_end(s);
888 
889 	if (kmem_cache_debug_flags(s, SLAB_STORE_USER))
890 		offset += sizeof(struct track) * 2;
891 
892 	if (slub_debug_orig_size(s))
893 		offset += sizeof(unsigned long);
894 
895 	offset += kasan_metadata_size(s, false);
896 
897 	return offset;
898 }
899 #else
900 static inline bool obj_exts_in_object(struct kmem_cache *s, struct slab *slab)
901 {
902 	return false;
903 }
904 
905 static inline unsigned int obj_exts_offset_in_object(struct kmem_cache *s)
906 {
907 	return 0;
908 }
909 #endif
910 
911 #ifdef CONFIG_SLUB_DEBUG
912 
913 /*
914  * For debugging context when we want to check if the struct slab pointer
915  * appears to be valid.
916  */
917 static inline bool validate_slab_ptr(struct slab *slab)
918 {
919 	return PageSlab(slab_page(slab));
920 }
921 
922 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
923 static DEFINE_SPINLOCK(object_map_lock);
924 
925 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
926 		       struct slab *slab)
927 {
928 	void *addr = slab_address(slab);
929 	void *p;
930 
931 	bitmap_zero(obj_map, slab->objects);
932 
933 	for (p = slab->freelist; p; p = get_freepointer(s, p))
934 		set_bit(__obj_to_index(s, addr, p), obj_map);
935 }
936 
937 #if IS_ENABLED(CONFIG_KUNIT)
938 static bool slab_add_kunit_errors(void)
939 {
940 	struct kunit_resource *resource;
941 
942 	if (!kunit_get_current_test())
943 		return false;
944 
945 	resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
946 	if (!resource)
947 		return false;
948 
949 	(*(int *)resource->data)++;
950 	kunit_put_resource(resource);
951 	return true;
952 }
953 
954 bool slab_in_kunit_test(void)
955 {
956 	struct kunit_resource *resource;
957 
958 	if (!kunit_get_current_test())
959 		return false;
960 
961 	resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
962 	if (!resource)
963 		return false;
964 
965 	kunit_put_resource(resource);
966 	return true;
967 }
968 #else
969 static inline bool slab_add_kunit_errors(void) { return false; }
970 #endif
971 
972 static inline unsigned int size_from_object(struct kmem_cache *s)
973 {
974 	if (s->flags & SLAB_RED_ZONE)
975 		return s->size - s->red_left_pad;
976 
977 	return s->size;
978 }
979 
980 static inline void *restore_red_left(struct kmem_cache *s, void *p)
981 {
982 	if (s->flags & SLAB_RED_ZONE)
983 		p -= s->red_left_pad;
984 
985 	return p;
986 }
987 
988 /*
989  * Debug settings:
990  */
991 #if defined(CONFIG_SLUB_DEBUG_ON)
992 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
993 #else
994 static slab_flags_t slub_debug;
995 #endif
996 
997 static const char *slub_debug_string __ro_after_init;
998 static int disable_higher_order_debug;
999 
1000 /*
1001  * Object debugging
1002  */
1003 
1004 /* Verify that a pointer has an address that is valid within a slab page */
1005 static inline int check_valid_pointer(struct kmem_cache *s,
1006 				struct slab *slab, void *object)
1007 {
1008 	void *base;
1009 
1010 	if (!object)
1011 		return 1;
1012 
1013 	base = slab_address(slab);
1014 	object = kasan_reset_tag(object);
1015 	object = restore_red_left(s, object);
1016 	if (object < base || object >= base + slab->objects * s->size ||
1017 		(object - base) % s->size) {
1018 		return 0;
1019 	}
1020 
1021 	return 1;
1022 }
1023 
1024 static void print_section(char *level, char *text, u8 *addr,
1025 			  unsigned int length)
1026 {
1027 	metadata_access_enable();
1028 	print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
1029 			16, 1, kasan_reset_tag((void *)addr), length, 1);
1030 	metadata_access_disable();
1031 }
1032 
1033 static struct track *get_track(struct kmem_cache *s, void *object,
1034 	enum track_item alloc)
1035 {
1036 	struct track *p;
1037 
1038 	p = object + get_info_end(s);
1039 
1040 	return kasan_reset_tag(p + alloc);
1041 }
1042 
1043 #ifdef CONFIG_STACKDEPOT
1044 static noinline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
1045 {
1046 	depot_stack_handle_t handle;
1047 	unsigned long entries[TRACK_ADDRS_COUNT];
1048 	unsigned int nr_entries;
1049 
1050 	nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
1051 	handle = stack_depot_save(entries, nr_entries, gfp_flags);
1052 
1053 	return handle;
1054 }
1055 #else
1056 static inline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
1057 {
1058 	return 0;
1059 }
1060 #endif
1061 
1062 static void set_track_update(struct kmem_cache *s, void *object,
1063 			     enum track_item alloc, unsigned long addr,
1064 			     depot_stack_handle_t handle)
1065 {
1066 	struct track *p = get_track(s, object, alloc);
1067 
1068 #ifdef CONFIG_STACKDEPOT
1069 	p->handle = handle;
1070 #endif
1071 	p->addr = addr;
1072 	p->cpu = raw_smp_processor_id();
1073 	p->pid = current->pid;
1074 	p->when = jiffies;
1075 }
1076 
1077 static __always_inline void set_track(struct kmem_cache *s, void *object,
1078 				      enum track_item alloc, unsigned long addr, gfp_t gfp_flags)
1079 {
1080 	depot_stack_handle_t handle = set_track_prepare(gfp_flags);
1081 
1082 	set_track_update(s, object, alloc, addr, handle);
1083 }
1084 
1085 static void init_tracking(struct kmem_cache *s, void *object)
1086 {
1087 	struct track *p;
1088 
1089 	if (!(s->flags & SLAB_STORE_USER))
1090 		return;
1091 
1092 	p = get_track(s, object, TRACK_ALLOC);
1093 	memset(p, 0, 2*sizeof(struct track));
1094 }
1095 
1096 static void print_track(const char *s, struct track *t, unsigned long pr_time)
1097 {
1098 	depot_stack_handle_t handle __maybe_unused;
1099 
1100 	if (!t->addr)
1101 		return;
1102 
1103 	pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
1104 	       s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
1105 #ifdef CONFIG_STACKDEPOT
1106 	handle = READ_ONCE(t->handle);
1107 	if (handle)
1108 		stack_depot_print(handle);
1109 	else
1110 		pr_err("object allocation/free stack trace missing\n");
1111 #endif
1112 }
1113 
1114 void print_tracking(struct kmem_cache *s, void *object)
1115 {
1116 	unsigned long pr_time = jiffies;
1117 	if (!(s->flags & SLAB_STORE_USER))
1118 		return;
1119 
1120 	print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
1121 	print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
1122 }
1123 
1124 static void print_slab_info(const struct slab *slab)
1125 {
1126 	pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
1127 	       slab, slab->objects, slab->inuse, slab->freelist,
1128 	       &slab->flags.f);
1129 }
1130 
1131 void skip_orig_size_check(struct kmem_cache *s, const void *object)
1132 {
1133 	set_orig_size(s, (void *)object, s->object_size);
1134 }
1135 
1136 static void __slab_bug(struct kmem_cache *s, const char *fmt, va_list argsp)
1137 {
1138 	struct va_format vaf;
1139 	va_list args;
1140 
1141 	va_copy(args, argsp);
1142 	vaf.fmt = fmt;
1143 	vaf.va = &args;
1144 	pr_err("=============================================================================\n");
1145 	pr_err("BUG %s (%s): %pV\n", s ? s->name : "<unknown>", print_tainted(), &vaf);
1146 	pr_err("-----------------------------------------------------------------------------\n\n");
1147 	va_end(args);
1148 }
1149 
1150 static void slab_bug(struct kmem_cache *s, const char *fmt, ...)
1151 {
1152 	va_list args;
1153 
1154 	va_start(args, fmt);
1155 	__slab_bug(s, fmt, args);
1156 	va_end(args);
1157 }
1158 
1159 __printf(2, 3)
1160 static void slab_fix(struct kmem_cache *s, const char *fmt, ...)
1161 {
1162 	struct va_format vaf;
1163 	va_list args;
1164 
1165 	if (slab_add_kunit_errors())
1166 		return;
1167 
1168 	va_start(args, fmt);
1169 	vaf.fmt = fmt;
1170 	vaf.va = &args;
1171 	pr_err("FIX %s: %pV\n", s->name, &vaf);
1172 	va_end(args);
1173 }
1174 
1175 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
1176 {
1177 	unsigned int off;	/* Offset of last byte */
1178 	u8 *addr = slab_address(slab);
1179 
1180 	print_tracking(s, p);
1181 
1182 	print_slab_info(slab);
1183 
1184 	pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
1185 	       p, p - addr, get_freepointer(s, p));
1186 
1187 	if (s->flags & SLAB_RED_ZONE)
1188 		print_section(KERN_ERR, "Redzone  ", p - s->red_left_pad,
1189 			      s->red_left_pad);
1190 	else if (p > addr + 16)
1191 		print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
1192 
1193 	print_section(KERN_ERR,         "Object   ", p,
1194 		      min_t(unsigned int, s->object_size, PAGE_SIZE));
1195 	if (s->flags & SLAB_RED_ZONE)
1196 		print_section(KERN_ERR, "Redzone  ", p + s->object_size,
1197 			s->inuse - s->object_size);
1198 
1199 	off = get_info_end(s);
1200 
1201 	if (s->flags & SLAB_STORE_USER)
1202 		off += 2 * sizeof(struct track);
1203 
1204 	if (slub_debug_orig_size(s))
1205 		off += sizeof(unsigned long);
1206 
1207 	off += kasan_metadata_size(s, false);
1208 
1209 	if (obj_exts_in_object(s, slab))
1210 		off += sizeof(struct slabobj_ext);
1211 
1212 	if (off != size_from_object(s))
1213 		/* Beginning of the filler is the free pointer */
1214 		print_section(KERN_ERR, "Padding  ", p + off,
1215 			      size_from_object(s) - off);
1216 }
1217 
1218 static void object_err(struct kmem_cache *s, struct slab *slab,
1219 			u8 *object, const char *reason)
1220 {
1221 	if (slab_add_kunit_errors())
1222 		return;
1223 
1224 	slab_bug(s, reason);
1225 	if (!object || !check_valid_pointer(s, slab, object)) {
1226 		print_slab_info(slab);
1227 		pr_err("Invalid pointer 0x%p\n", object);
1228 	} else {
1229 		print_trailer(s, slab, object);
1230 	}
1231 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1232 
1233 	WARN_ON(1);
1234 }
1235 
1236 static void __slab_err(struct slab *slab)
1237 {
1238 	if (slab_in_kunit_test())
1239 		return;
1240 
1241 	print_slab_info(slab);
1242 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1243 
1244 	WARN_ON(1);
1245 }
1246 
1247 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
1248 			const char *fmt, ...)
1249 {
1250 	va_list args;
1251 
1252 	if (slab_add_kunit_errors())
1253 		return;
1254 
1255 	va_start(args, fmt);
1256 	__slab_bug(s, fmt, args);
1257 	va_end(args);
1258 
1259 	__slab_err(slab);
1260 }
1261 
1262 static void init_object(struct kmem_cache *s, void *object, u8 val)
1263 {
1264 	u8 *p = kasan_reset_tag(object);
1265 	unsigned int poison_size = s->object_size;
1266 
1267 	if (s->flags & SLAB_RED_ZONE) {
1268 		/*
1269 		 * Here and below, avoid overwriting the KMSAN shadow. Keeping
1270 		 * the shadow makes it possible to distinguish uninit-value
1271 		 * from use-after-free.
1272 		 */
1273 		memset_no_sanitize_memory(p - s->red_left_pad, val,
1274 					  s->red_left_pad);
1275 
1276 		if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1277 			/*
1278 			 * Redzone the extra allocated space by kmalloc than
1279 			 * requested, and the poison size will be limited to
1280 			 * the original request size accordingly.
1281 			 */
1282 			poison_size = get_orig_size(s, object);
1283 		}
1284 	}
1285 
1286 	if (s->flags & __OBJECT_POISON) {
1287 		memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1);
1288 		memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1);
1289 	}
1290 
1291 	if (s->flags & SLAB_RED_ZONE)
1292 		memset_no_sanitize_memory(p + poison_size, val,
1293 					  s->inuse - poison_size);
1294 }
1295 
1296 static void restore_bytes(struct kmem_cache *s, const char *message, u8 data,
1297 						void *from, void *to)
1298 {
1299 	slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
1300 	memset(from, data, to - from);
1301 }
1302 
1303 #ifdef CONFIG_KMSAN
1304 #define pad_check_attributes noinline __no_kmsan_checks
1305 #else
1306 #define pad_check_attributes
1307 #endif
1308 
1309 static pad_check_attributes int
1310 check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
1311 		       u8 *object, const char *what, u8 *start, unsigned int value,
1312 		       unsigned int bytes, bool slab_obj_print)
1313 {
1314 	u8 *fault;
1315 	u8 *end;
1316 	u8 *addr = slab_address(slab);
1317 
1318 	metadata_access_enable();
1319 	fault = memchr_inv(kasan_reset_tag(start), value, bytes);
1320 	metadata_access_disable();
1321 	if (!fault)
1322 		return 1;
1323 
1324 	end = start + bytes;
1325 	while (end > fault && end[-1] == value)
1326 		end--;
1327 
1328 	if (slab_add_kunit_errors())
1329 		goto skip_bug_print;
1330 
1331 	pr_err("[%s overwritten] 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
1332 	       what, fault, end - 1, fault - addr, fault[0], value);
1333 
1334 	if (slab_obj_print)
1335 		object_err(s, slab, object, "Object corrupt");
1336 
1337 skip_bug_print:
1338 	restore_bytes(s, what, value, fault, end);
1339 	return 0;
1340 }
1341 
1342 /*
1343  * Object field layout:
1344  *
1345  * [Left redzone padding] (if SLAB_RED_ZONE)
1346  *   - Field size: s->red_left_pad
1347  *   - Immediately precedes each object when SLAB_RED_ZONE is set.
1348  *   - Filled with 0xbb (SLUB_RED_INACTIVE) for inactive objects and
1349  *     0xcc (SLUB_RED_ACTIVE) for objects in use when SLAB_RED_ZONE.
1350  *
1351  * [Object bytes] (object address starts here)
1352  *   - Field size: s->object_size
1353  *   - Object payload bytes.
1354  *   - If the freepointer may overlap the object, it is stored inside
1355  *     the object (typically near the middle).
1356  *   - Poisoning uses 0x6b (POISON_FREE) and the last byte is
1357  *     0xa5 (POISON_END) when __OBJECT_POISON is enabled.
1358  *
1359  * [Word-align padding] (right redzone when SLAB_RED_ZONE is set)
1360  *   - Field size: s->inuse - s->object_size
1361  *   - If redzoning is enabled and ALIGN(size, sizeof(void *)) adds no
1362  *     padding, explicitly extend by one word so the right redzone is
1363  *     non-empty.
1364  *   - Filled with 0xbb (SLUB_RED_INACTIVE) for inactive objects and
1365  *     0xcc (SLUB_RED_ACTIVE) for objects in use when SLAB_RED_ZONE.
1366  *
1367  * [Metadata starts at object + s->inuse]
1368  *   - A. freelist pointer (if freeptr_outside_object)
1369  *   - B. alloc tracking (SLAB_STORE_USER)
1370  *   - C. free tracking (SLAB_STORE_USER)
1371  *   - D. original request size (SLAB_KMALLOC && SLAB_STORE_USER)
1372  *   - E. KASAN metadata (if enabled)
1373  *
1374  * [Mandatory padding] (if CONFIG_SLUB_DEBUG && SLAB_RED_ZONE)
1375  *   - One mandatory debug word to guarantee a minimum poisoned gap
1376  *     between metadata and the next object, independent of alignment.
1377  *   - Filled with 0x5a (POISON_INUSE) when SLAB_POISON is set.
1378  * [Final alignment padding]
1379  *   - Bytes added by ALIGN(size, s->align) to reach s->size.
1380  *   - When the padding is large enough, it can be used to store
1381  *     struct slabobj_ext for accounting metadata (obj_exts_in_object()).
1382  *   - The remaining bytes (if any) are filled with 0x5a (POISON_INUSE)
1383  *     when SLAB_POISON is set.
1384  *
1385  * Notes:
1386  * - Redzones are filled by init_object() with SLUB_RED_ACTIVE/INACTIVE.
1387  * - Object contents are poisoned with POISON_FREE/END when __OBJECT_POISON.
1388  * - The trailing padding is pre-filled with POISON_INUSE by
1389  *   setup_slab_debug() when SLAB_POISON is set, and is validated by
1390  *   check_pad_bytes().
1391  * - The first object pointer is slab_address(slab) +
1392  *   (s->red_left_pad if redzoning); subsequent objects are reached by
1393  *   adding s->size each time.
1394  *
1395  * If a slab cache flag relies on specific metadata to exist at a fixed
1396  * offset, the flag must be included in SLAB_NEVER_MERGE to prevent merging.
1397  * Otherwise, the cache would misbehave as s->object_size and s->inuse are
1398  * adjusted during cache merging (see __kmem_cache_alias()).
1399  */
1400 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
1401 {
1402 	unsigned long off = get_info_end(s);	/* The end of info */
1403 
1404 	if (s->flags & SLAB_STORE_USER) {
1405 		/* We also have user information there */
1406 		off += 2 * sizeof(struct track);
1407 
1408 		if (s->flags & SLAB_KMALLOC)
1409 			off += sizeof(unsigned long);
1410 	}
1411 
1412 	off += kasan_metadata_size(s, false);
1413 
1414 	if (obj_exts_in_object(s, slab))
1415 		off += sizeof(struct slabobj_ext);
1416 
1417 	if (size_from_object(s) == off)
1418 		return 1;
1419 
1420 	return check_bytes_and_report(s, slab, p, "Object padding",
1421 			p + off, POISON_INUSE, size_from_object(s) - off, true);
1422 }
1423 
1424 /* Check the pad bytes at the end of a slab page */
1425 static pad_check_attributes void
1426 slab_pad_check(struct kmem_cache *s, struct slab *slab)
1427 {
1428 	u8 *start;
1429 	u8 *fault;
1430 	u8 *end;
1431 	u8 *pad;
1432 	int length;
1433 	int remainder;
1434 
1435 	if (!(s->flags & SLAB_POISON))
1436 		return;
1437 
1438 	start = slab_address(slab);
1439 	length = slab_size(slab);
1440 	end = start + length;
1441 
1442 	if (obj_exts_in_slab(s, slab) && !obj_exts_in_object(s, slab)) {
1443 		remainder = length;
1444 		remainder -= obj_exts_offset_in_slab(s, slab);
1445 		remainder -= obj_exts_size_in_slab(slab);
1446 	} else {
1447 		remainder = length % s->size;
1448 	}
1449 
1450 	if (!remainder)
1451 		return;
1452 
1453 	pad = end - remainder;
1454 	metadata_access_enable();
1455 	fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
1456 	metadata_access_disable();
1457 	if (!fault)
1458 		return;
1459 	while (end > fault && end[-1] == POISON_INUSE)
1460 		end--;
1461 
1462 	slab_bug(s, "Padding overwritten. 0x%p-0x%p @offset=%tu",
1463 		 fault, end - 1, fault - start);
1464 	print_section(KERN_ERR, "Padding ", pad, remainder);
1465 	__slab_err(slab);
1466 
1467 	restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
1468 }
1469 
1470 static int check_object(struct kmem_cache *s, struct slab *slab,
1471 					void *object, u8 val)
1472 {
1473 	u8 *p = object;
1474 	u8 *endobject = object + s->object_size;
1475 	unsigned int orig_size, kasan_meta_size;
1476 	int ret = 1;
1477 
1478 	if (s->flags & SLAB_RED_ZONE) {
1479 		if (!check_bytes_and_report(s, slab, object, "Left Redzone",
1480 			object - s->red_left_pad, val, s->red_left_pad, ret))
1481 			ret = 0;
1482 
1483 		if (!check_bytes_and_report(s, slab, object, "Right Redzone",
1484 			endobject, val, s->inuse - s->object_size, ret))
1485 			ret = 0;
1486 
1487 		if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1488 			orig_size = get_orig_size(s, object);
1489 
1490 			if (s->object_size > orig_size  &&
1491 				!check_bytes_and_report(s, slab, object,
1492 					"kmalloc Redzone", p + orig_size,
1493 					val, s->object_size - orig_size, ret)) {
1494 				ret = 0;
1495 			}
1496 		}
1497 	} else {
1498 		if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
1499 			if (!check_bytes_and_report(s, slab, p, "Alignment padding",
1500 				endobject, POISON_INUSE,
1501 				s->inuse - s->object_size, ret))
1502 				ret = 0;
1503 		}
1504 	}
1505 
1506 	if (s->flags & SLAB_POISON) {
1507 		if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) {
1508 			/*
1509 			 * KASAN can save its free meta data inside of the
1510 			 * object at offset 0. Thus, skip checking the part of
1511 			 * the redzone that overlaps with the meta data.
1512 			 */
1513 			kasan_meta_size = kasan_metadata_size(s, true);
1514 			if (kasan_meta_size < s->object_size - 1 &&
1515 			    !check_bytes_and_report(s, slab, p, "Poison",
1516 					p + kasan_meta_size, POISON_FREE,
1517 					s->object_size - kasan_meta_size - 1, ret))
1518 				ret = 0;
1519 			if (kasan_meta_size < s->object_size &&
1520 			    !check_bytes_and_report(s, slab, p, "End Poison",
1521 					p + s->object_size - 1, POISON_END, 1, ret))
1522 				ret = 0;
1523 		}
1524 		/*
1525 		 * check_pad_bytes cleans up on its own.
1526 		 */
1527 		if (!check_pad_bytes(s, slab, p))
1528 			ret = 0;
1529 	}
1530 
1531 	/*
1532 	 * Cannot check freepointer while object is allocated if
1533 	 * object and freepointer overlap.
1534 	 */
1535 	if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
1536 	    !check_valid_pointer(s, slab, get_freepointer(s, p))) {
1537 		object_err(s, slab, p, "Freepointer corrupt");
1538 		/*
1539 		 * No choice but to zap it and thus lose the remainder
1540 		 * of the free objects in this slab. May cause
1541 		 * another error because the object count is now wrong.
1542 		 */
1543 		set_freepointer(s, p, NULL);
1544 		ret = 0;
1545 	}
1546 
1547 	return ret;
1548 }
1549 
1550 /*
1551  * Checks if the slab state looks sane. Assumes the struct slab pointer
1552  * was either obtained in a way that ensures it's valid, or validated
1553  * by validate_slab_ptr()
1554  */
1555 static int check_slab(struct kmem_cache *s, struct slab *slab)
1556 {
1557 	int maxobj;
1558 
1559 	maxobj = order_objects(slab_order(slab), s->size);
1560 	if (slab->objects > maxobj) {
1561 		slab_err(s, slab, "objects %u > max %u",
1562 			slab->objects, maxobj);
1563 		return 0;
1564 	}
1565 	if (slab->inuse > slab->objects) {
1566 		slab_err(s, slab, "inuse %u > max %u",
1567 			slab->inuse, slab->objects);
1568 		return 0;
1569 	}
1570 	if (slab->frozen) {
1571 		slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
1572 		return 0;
1573 	}
1574 
1575 	/* Slab_pad_check fixes things up after itself */
1576 	slab_pad_check(s, slab);
1577 	return 1;
1578 }
1579 
1580 /*
1581  * Determine if a certain object in a slab is on the freelist. Must hold the
1582  * slab lock to guarantee that the chains are in a consistent state.
1583  */
1584 static bool on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
1585 {
1586 	int nr = 0;
1587 	void *fp;
1588 	void *object = NULL;
1589 	int max_objects;
1590 
1591 	fp = slab->freelist;
1592 	while (fp && nr <= slab->objects) {
1593 		if (fp == search)
1594 			return true;
1595 		if (!check_valid_pointer(s, slab, fp)) {
1596 			if (object) {
1597 				object_err(s, slab, object,
1598 					"Freechain corrupt");
1599 				set_freepointer(s, object, NULL);
1600 				break;
1601 			} else {
1602 				slab_err(s, slab, "Freepointer corrupt");
1603 				slab->freelist = NULL;
1604 				slab->inuse = slab->objects;
1605 				slab_fix(s, "Freelist cleared");
1606 				return false;
1607 			}
1608 		}
1609 		object = fp;
1610 		fp = get_freepointer(s, object);
1611 		nr++;
1612 	}
1613 
1614 	if (nr > slab->objects) {
1615 		slab_err(s, slab, "Freelist cycle detected");
1616 		slab->freelist = NULL;
1617 		slab->inuse = slab->objects;
1618 		slab_fix(s, "Freelist cleared");
1619 		return false;
1620 	}
1621 
1622 	max_objects = order_objects(slab_order(slab), s->size);
1623 	if (max_objects > MAX_OBJS_PER_PAGE)
1624 		max_objects = MAX_OBJS_PER_PAGE;
1625 
1626 	if (slab->objects != max_objects) {
1627 		slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1628 			 slab->objects, max_objects);
1629 		slab->objects = max_objects;
1630 		slab_fix(s, "Number of objects adjusted");
1631 	}
1632 	if (slab->inuse != slab->objects - nr) {
1633 		slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1634 			 slab->inuse, slab->objects - nr);
1635 		slab->inuse = slab->objects - nr;
1636 		slab_fix(s, "Object count adjusted");
1637 	}
1638 	return search == NULL;
1639 }
1640 
1641 static void trace(struct kmem_cache *s, struct slab *slab, void *object,
1642 								int alloc)
1643 {
1644 	if (s->flags & SLAB_TRACE) {
1645 		pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1646 			s->name,
1647 			alloc ? "alloc" : "free",
1648 			object, slab->inuse,
1649 			slab->freelist);
1650 
1651 		if (!alloc)
1652 			print_section(KERN_INFO, "Object ", (void *)object,
1653 					s->object_size);
1654 
1655 		dump_stack();
1656 	}
1657 }
1658 
1659 /*
1660  * Tracking of fully allocated slabs for debugging purposes.
1661  */
1662 static void add_full(struct kmem_cache *s,
1663 	struct kmem_cache_node *n, struct slab *slab)
1664 {
1665 	if (!(s->flags & SLAB_STORE_USER))
1666 		return;
1667 
1668 	lockdep_assert_held(&n->list_lock);
1669 	list_add(&slab->slab_list, &n->full);
1670 }
1671 
1672 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
1673 {
1674 	if (!(s->flags & SLAB_STORE_USER))
1675 		return;
1676 
1677 	lockdep_assert_held(&n->list_lock);
1678 	list_del(&slab->slab_list);
1679 }
1680 
1681 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1682 {
1683 	return atomic_long_read(&n->nr_slabs);
1684 }
1685 
1686 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1687 {
1688 	struct kmem_cache_node *n = get_node(s, node);
1689 
1690 	atomic_long_inc(&n->nr_slabs);
1691 	atomic_long_add(objects, &n->total_objects);
1692 }
1693 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1694 {
1695 	struct kmem_cache_node *n = get_node(s, node);
1696 
1697 	atomic_long_dec(&n->nr_slabs);
1698 	atomic_long_sub(objects, &n->total_objects);
1699 }
1700 
1701 /* Object debug checks for alloc/free paths */
1702 static void setup_object_debug(struct kmem_cache *s, void *object)
1703 {
1704 	if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1705 		return;
1706 
1707 	init_object(s, object, SLUB_RED_INACTIVE);
1708 	init_tracking(s, object);
1709 }
1710 
1711 static
1712 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
1713 {
1714 	if (!kmem_cache_debug_flags(s, SLAB_POISON))
1715 		return;
1716 
1717 	metadata_access_enable();
1718 	memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
1719 	metadata_access_disable();
1720 }
1721 
1722 static inline int alloc_consistency_checks(struct kmem_cache *s,
1723 					struct slab *slab, void *object)
1724 {
1725 	if (!check_slab(s, slab))
1726 		return 0;
1727 
1728 	if (!check_valid_pointer(s, slab, object)) {
1729 		object_err(s, slab, object, "Freelist Pointer check fails");
1730 		return 0;
1731 	}
1732 
1733 	if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
1734 		return 0;
1735 
1736 	return 1;
1737 }
1738 
1739 static noinline bool alloc_debug_processing(struct kmem_cache *s,
1740 			struct slab *slab, void *object, int orig_size)
1741 {
1742 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1743 		if (!alloc_consistency_checks(s, slab, object))
1744 			goto bad;
1745 	}
1746 
1747 	/* Success. Perform special debug activities for allocs */
1748 	trace(s, slab, object, 1);
1749 	set_orig_size(s, object, orig_size);
1750 	init_object(s, object, SLUB_RED_ACTIVE);
1751 	return true;
1752 
1753 bad:
1754 	/*
1755 	 * Let's do the best we can to avoid issues in the future. Marking all
1756 	 * objects as used avoids touching the remaining objects.
1757 	 */
1758 	slab_fix(s, "Marking all objects used");
1759 	slab->inuse = slab->objects;
1760 	slab->freelist = NULL;
1761 	slab->frozen = 1; /* mark consistency-failed slab as frozen */
1762 
1763 	return false;
1764 }
1765 
1766 static inline int free_consistency_checks(struct kmem_cache *s,
1767 		struct slab *slab, void *object, unsigned long addr)
1768 {
1769 	if (!check_valid_pointer(s, slab, object)) {
1770 		slab_err(s, slab, "Invalid object pointer 0x%p", object);
1771 		return 0;
1772 	}
1773 
1774 	if (on_freelist(s, slab, object)) {
1775 		object_err(s, slab, object, "Object already free");
1776 		return 0;
1777 	}
1778 
1779 	if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
1780 		return 0;
1781 
1782 	if (unlikely(s != slab->slab_cache)) {
1783 		if (!slab->slab_cache) {
1784 			slab_err(NULL, slab, "No slab cache for object 0x%p",
1785 				 object);
1786 		} else {
1787 			object_err(s, slab, object,
1788 				   "page slab pointer corrupt.");
1789 		}
1790 		return 0;
1791 	}
1792 	return 1;
1793 }
1794 
1795 /*
1796  * Parse a block of slab_debug options. Blocks are delimited by ';'
1797  *
1798  * @str:    start of block
1799  * @flags:  returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1800  * @slabs:  return start of list of slabs, or NULL when there's no list
1801  * @init:   assume this is initial parsing and not per-kmem-create parsing
1802  *
1803  * returns the start of next block if there's any, or NULL
1804  */
1805 static const char *
1806 parse_slub_debug_flags(const char *str, slab_flags_t *flags, const char **slabs, bool init)
1807 {
1808 	bool higher_order_disable = false;
1809 
1810 	/* Skip any completely empty blocks */
1811 	while (*str && *str == ';')
1812 		str++;
1813 
1814 	if (*str == ',') {
1815 		/*
1816 		 * No options but restriction on slabs. This means full
1817 		 * debugging for slabs matching a pattern.
1818 		 */
1819 		*flags = DEBUG_DEFAULT_FLAGS;
1820 		goto check_slabs;
1821 	}
1822 	*flags = 0;
1823 
1824 	/* Determine which debug features should be switched on */
1825 	for (; *str && *str != ',' && *str != ';'; str++) {
1826 		switch (tolower(*str)) {
1827 		case '-':
1828 			*flags = 0;
1829 			break;
1830 		case 'f':
1831 			*flags |= SLAB_CONSISTENCY_CHECKS;
1832 			break;
1833 		case 'z':
1834 			*flags |= SLAB_RED_ZONE;
1835 			break;
1836 		case 'p':
1837 			*flags |= SLAB_POISON;
1838 			break;
1839 		case 'u':
1840 			*flags |= SLAB_STORE_USER;
1841 			break;
1842 		case 't':
1843 			*flags |= SLAB_TRACE;
1844 			break;
1845 		case 'a':
1846 			*flags |= SLAB_FAILSLAB;
1847 			break;
1848 		case 'o':
1849 			/*
1850 			 * Avoid enabling debugging on caches if its minimum
1851 			 * order would increase as a result.
1852 			 */
1853 			higher_order_disable = true;
1854 			break;
1855 		default:
1856 			if (init)
1857 				pr_err("slab_debug option '%c' unknown. skipped\n", *str);
1858 		}
1859 	}
1860 check_slabs:
1861 	if (*str == ',')
1862 		*slabs = ++str;
1863 	else
1864 		*slabs = NULL;
1865 
1866 	/* Skip over the slab list */
1867 	while (*str && *str != ';')
1868 		str++;
1869 
1870 	/* Skip any completely empty blocks */
1871 	while (*str && *str == ';')
1872 		str++;
1873 
1874 	if (init && higher_order_disable)
1875 		disable_higher_order_debug = 1;
1876 
1877 	if (*str)
1878 		return str;
1879 	else
1880 		return NULL;
1881 }
1882 
1883 static int __init setup_slub_debug(const char *str, const struct kernel_param *kp)
1884 {
1885 	slab_flags_t flags;
1886 	slab_flags_t global_flags;
1887 	const char *saved_str;
1888 	const char *slab_list;
1889 	bool global_slub_debug_changed = false;
1890 	bool slab_list_specified = false;
1891 
1892 	global_flags = DEBUG_DEFAULT_FLAGS;
1893 	if (!str || !*str)
1894 		/*
1895 		 * No options specified. Switch on full debugging.
1896 		 */
1897 		goto out;
1898 
1899 	saved_str = str;
1900 	while (str) {
1901 		str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1902 
1903 		if (!slab_list) {
1904 			global_flags = flags;
1905 			global_slub_debug_changed = true;
1906 		} else {
1907 			slab_list_specified = true;
1908 			if (flags & SLAB_STORE_USER)
1909 				stack_depot_request_early_init();
1910 		}
1911 	}
1912 
1913 	/*
1914 	 * For backwards compatibility, a single list of flags with list of
1915 	 * slabs means debugging is only changed for those slabs, so the global
1916 	 * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1917 	 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
1918 	 * long as there is no option specifying flags without a slab list.
1919 	 */
1920 	if (slab_list_specified) {
1921 		if (!global_slub_debug_changed)
1922 			global_flags = slub_debug;
1923 		slub_debug_string = saved_str;
1924 	}
1925 out:
1926 	slub_debug = global_flags;
1927 	if (slub_debug & SLAB_STORE_USER)
1928 		stack_depot_request_early_init();
1929 	if (slub_debug != 0 || slub_debug_string)
1930 		static_branch_enable(&slub_debug_enabled);
1931 	else
1932 		static_branch_disable(&slub_debug_enabled);
1933 	if ((static_branch_unlikely(&init_on_alloc) ||
1934 	     static_branch_unlikely(&init_on_free)) &&
1935 	    (slub_debug & SLAB_POISON))
1936 		pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1937 	return 0;
1938 }
1939 
1940 static const struct kernel_param_ops param_ops_slab_debug __initconst = {
1941 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
1942 	.set = setup_slub_debug,
1943 };
1944 __core_param_cb(slab_debug, &param_ops_slab_debug, NULL, 0);
1945 __core_param_cb(slub_debug, &param_ops_slab_debug, NULL, 0);
1946 
1947 /*
1948  * kmem_cache_flags - apply debugging options to the cache
1949  * @flags:		flags to set
1950  * @name:		name of the cache
1951  *
1952  * Debug option(s) are applied to @flags. In addition to the debug
1953  * option(s), if a slab name (or multiple) is specified i.e.
1954  * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1955  * then only the select slabs will receive the debug option(s).
1956  */
1957 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1958 {
1959 	const char *iter;
1960 	size_t len;
1961 	const char *next_block;
1962 	slab_flags_t block_flags;
1963 	slab_flags_t slub_debug_local = slub_debug;
1964 
1965 	if (flags & SLAB_NO_USER_FLAGS)
1966 		return flags;
1967 
1968 	/*
1969 	 * If the slab cache is for debugging (e.g. kmemleak) then
1970 	 * don't store user (stack trace) information by default,
1971 	 * but let the user enable it via the command line below.
1972 	 */
1973 	if (flags & SLAB_NOLEAKTRACE)
1974 		slub_debug_local &= ~SLAB_STORE_USER;
1975 
1976 	len = strlen(name);
1977 	next_block = slub_debug_string;
1978 	/* Go through all blocks of debug options, see if any matches our slab's name */
1979 	while (next_block) {
1980 		next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1981 		if (!iter)
1982 			continue;
1983 		/* Found a block that has a slab list, search it */
1984 		while (*iter) {
1985 			const char *end, *glob;
1986 			size_t cmplen;
1987 
1988 			end = strchrnul(iter, ',');
1989 			if (next_block && next_block < end)
1990 				end = next_block - 1;
1991 
1992 			glob = strnchr(iter, end - iter, '*');
1993 			if (glob)
1994 				cmplen = glob - iter;
1995 			else
1996 				cmplen = max_t(size_t, len, (end - iter));
1997 
1998 			if (!strncmp(name, iter, cmplen)) {
1999 				flags |= block_flags;
2000 				return flags;
2001 			}
2002 
2003 			if (!*end || *end == ';')
2004 				break;
2005 			iter = end + 1;
2006 		}
2007 	}
2008 
2009 	return flags | slub_debug_local;
2010 }
2011 #else /* !CONFIG_SLUB_DEBUG */
2012 static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
2013 static inline
2014 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
2015 
2016 static inline bool alloc_debug_processing(struct kmem_cache *s,
2017 	struct slab *slab, void *object, int orig_size) { return true; }
2018 
2019 static inline bool free_debug_processing(struct kmem_cache *s,
2020 	struct slab *slab, void *head, void *tail, int *bulk_cnt,
2021 	unsigned long addr, depot_stack_handle_t handle) { return true; }
2022 
2023 static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
2024 static inline int check_object(struct kmem_cache *s, struct slab *slab,
2025 			void *object, u8 val) { return 1; }
2026 static inline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags) { return 0; }
2027 static inline void set_track(struct kmem_cache *s, void *object,
2028 			     enum track_item alloc, unsigned long addr, gfp_t gfp_flags) {}
2029 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
2030 					struct slab *slab) {}
2031 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
2032 					struct slab *slab) {}
2033 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
2034 {
2035 	return flags;
2036 }
2037 #define slub_debug 0
2038 
2039 #define disable_higher_order_debug 0
2040 
2041 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
2042 							{ return 0; }
2043 static inline void inc_slabs_node(struct kmem_cache *s, int node,
2044 							int objects) {}
2045 static inline void dec_slabs_node(struct kmem_cache *s, int node,
2046 							int objects) {}
2047 #endif /* CONFIG_SLUB_DEBUG */
2048 
2049 /*
2050  * The allocated objcg pointers array or sheaf is not accounted directly.
2051  * Moreover, it should not come from DMA buffer and is not readily
2052  * reclaimable. Node restriction for the parent allocation also should
2053  * not apply to the slab's internal objects, as well as __GFP_COMP used
2054  * for new slab allocations.
2055  * So those GFP bits should be masked off.
2056  */
2057 #define OBJCGS_CLEAR_MASK	(__GFP_DMA | __GFP_RECLAIMABLE | \
2058 				__GFP_ACCOUNT | __GFP_NOFAIL | \
2059 				__GFP_THISNODE | __GFP_COMP)
2060 
2061 #ifdef CONFIG_SLAB_OBJ_EXT
2062 
2063 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
2064 
2065 static inline void mark_obj_codetag_empty(const void *obj)
2066 {
2067 	struct slab *obj_slab;
2068 	unsigned long slab_exts;
2069 
2070 	obj_slab = virt_to_slab(obj);
2071 	slab_exts = slab_obj_exts(obj_slab);
2072 	if (slab_exts) {
2073 		get_slab_obj_exts(slab_exts);
2074 		unsigned int offs = obj_to_index(obj_slab->slab_cache,
2075 						 obj_slab, obj);
2076 		struct slabobj_ext *ext = slab_obj_ext(obj_slab,
2077 						       slab_exts, offs);
2078 
2079 		if (unlikely(is_codetag_empty(&ext->ref))) {
2080 			put_slab_obj_exts(slab_exts);
2081 			return;
2082 		}
2083 
2084 		/* codetag should be NULL here */
2085 		WARN_ON(ext->ref.ct);
2086 		set_codetag_empty(&ext->ref);
2087 		put_slab_obj_exts(slab_exts);
2088 	}
2089 }
2090 
2091 static inline bool mark_failed_objexts_alloc(struct slab *slab)
2092 {
2093 	return cmpxchg(&slab->obj_exts, 0, OBJEXTS_ALLOC_FAIL) == 0;
2094 }
2095 
2096 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
2097 			struct slabobj_ext *vec, unsigned int objects)
2098 {
2099 	/*
2100 	 * If vector previously failed to allocate then we have live
2101 	 * objects with no tag reference. Mark all references in this
2102 	 * vector as empty to avoid warnings later on.
2103 	 */
2104 	if (obj_exts == OBJEXTS_ALLOC_FAIL) {
2105 		unsigned int i;
2106 
2107 		for (i = 0; i < objects; i++)
2108 			set_codetag_empty(&vec[i].ref);
2109 	}
2110 }
2111 
2112 #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2113 
2114 static inline void mark_obj_codetag_empty(const void *obj) {}
2115 static inline bool mark_failed_objexts_alloc(struct slab *slab) { return false; }
2116 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
2117 			struct slabobj_ext *vec, unsigned int objects) {}
2118 
2119 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2120 
2121 static inline void init_slab_obj_exts(struct slab *slab)
2122 {
2123 	slab->obj_exts = 0;
2124 }
2125 
2126 /*
2127  * Calculate the allocation size for slabobj_ext array.
2128  *
2129  * When memory allocation profiling is enabled, the obj_exts array
2130  * could be allocated from the same slab cache it's being allocated for.
2131  * This would prevent the slab from ever being freed because it would
2132  * always contain at least one allocated object (its own obj_exts array).
2133  *
2134  * To avoid this, increase the allocation size when we detect the array
2135  * may come from the same cache, forcing it to use a different cache.
2136  */
2137 static inline size_t obj_exts_alloc_size(struct kmem_cache *s,
2138 					 struct slab *slab, gfp_t gfp)
2139 {
2140 	size_t sz = sizeof(struct slabobj_ext) * slab->objects;
2141 	struct kmem_cache *obj_exts_cache;
2142 
2143 	if (sz > KMALLOC_MAX_CACHE_SIZE)
2144 		return sz;
2145 
2146 	if (!is_kmalloc_normal(s))
2147 		return sz;
2148 
2149 	obj_exts_cache = kmalloc_slab(sz, NULL, gfp, __kmalloc_token(0));
2150 	/*
2151 	 * We can't simply compare s with obj_exts_cache, because partitioned kmalloc
2152 	 * caches have multiple caches per size, selected by caller address or type.
2153 	 * Since caller address or type may differ between kmalloc_slab() and actual
2154 	 * allocation, bump size when sizes are equal.
2155 	 */
2156 	if (s->object_size == obj_exts_cache->object_size)
2157 		return obj_exts_cache->object_size + 1;
2158 
2159 	return sz;
2160 }
2161 
2162 int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2163 			gfp_t gfp, unsigned int alloc_flags)
2164 {
2165 	const bool allow_spin = alloc_flags_allow_spinning(alloc_flags);
2166 	unsigned int objects = objs_per_slab(s, slab);
2167 	bool new_slab = alloc_flags & SLAB_ALLOC_NEW_SLAB;
2168 	unsigned long new_exts;
2169 	unsigned long old_exts;
2170 	struct slabobj_ext *vec;
2171 	size_t sz;
2172 
2173 	gfp &= ~OBJCGS_CLEAR_MASK;
2174 	/* Prevent recursive extension vector allocation */
2175 	alloc_flags |= SLAB_ALLOC_NO_RECURSE;
2176 	alloc_flags &= ~SLAB_ALLOC_NEW_SLAB;
2177 
2178 	sz = obj_exts_alloc_size(s, slab, gfp);
2179 
2180 	/* This will use kmalloc_nolock() if alloc_flags say so */
2181 	vec = kmalloc_flags(sz, gfp | __GFP_ZERO, alloc_flags, slab_nid(slab));
2182 
2183 	if (!vec) {
2184 		/*
2185 		 * Try to mark vectors which failed to allocate.
2186 		 * If this operation fails, there may be a racing process
2187 		 * that has already completed the allocation.
2188 		 */
2189 		if (!mark_failed_objexts_alloc(slab) &&
2190 		    slab_obj_exts(slab))
2191 			return 0;
2192 
2193 		return -ENOMEM;
2194 	}
2195 
2196 	VM_WARN_ON_ONCE(virt_to_slab(vec) != NULL &&
2197 			virt_to_slab(vec)->slab_cache == s);
2198 
2199 	new_exts = (unsigned long)vec;
2200 #ifdef CONFIG_MEMCG
2201 	new_exts |= MEMCG_DATA_OBJEXTS;
2202 #endif
2203 retry:
2204 	old_exts = READ_ONCE(slab->obj_exts);
2205 	handle_failed_objexts_alloc(old_exts, vec, objects);
2206 
2207 	if (new_slab) {
2208 		/*
2209 		 * If the slab is brand new and nobody can yet access its
2210 		 * obj_exts, no synchronization is required and obj_exts can
2211 		 * be simply assigned.
2212 		 */
2213 		slab->obj_exts = new_exts;
2214 	} else if (old_exts & ~OBJEXTS_FLAGS_MASK) {
2215 		/*
2216 		 * If the slab is already in use, somebody can allocate and
2217 		 * assign slabobj_exts in parallel. In this case the existing
2218 		 * objcg vector should be reused.
2219 		 */
2220 		mark_obj_codetag_empty(vec);
2221 		if (unlikely(!allow_spin))
2222 			kfree_nolock(vec);
2223 		else
2224 			kfree(vec);
2225 		return 0;
2226 	} else if (cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) {
2227 		/* Retry if a racing thread changed slab->obj_exts from under us. */
2228 		goto retry;
2229 	}
2230 
2231 	if (allow_spin)
2232 		kmemleak_not_leak(vec);
2233 	return 0;
2234 }
2235 
2236 static inline void free_slab_obj_exts(struct slab *slab, bool allow_spin)
2237 {
2238 	struct slabobj_ext *obj_exts;
2239 
2240 	obj_exts = (struct slabobj_ext *)slab_obj_exts(slab);
2241 	if (!obj_exts) {
2242 		/*
2243 		 * If obj_exts allocation failed, slab->obj_exts is set to
2244 		 * OBJEXTS_ALLOC_FAIL. In this case, we end up here and should
2245 		 * clear the flag.
2246 		 */
2247 		slab->obj_exts = 0;
2248 		return;
2249 	}
2250 
2251 	if (obj_exts_in_slab(slab->slab_cache, slab)) {
2252 		slab->obj_exts = 0;
2253 		return;
2254 	}
2255 
2256 	/*
2257 	 * obj_exts was created with SLAB_ALLOC_NO_RECURSE flag, therefore its
2258 	 * corresponding extension will be NULL. alloc_tag_sub() will throw a
2259 	 * warning if slab has extensions but the extension of an object is
2260 	 * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that
2261 	 * the extension for obj_exts is expected to be NULL.
2262 	 */
2263 	mark_obj_codetag_empty(obj_exts);
2264 	if (allow_spin)
2265 		kfree(obj_exts);
2266 	else
2267 		kfree_nolock(obj_exts);
2268 	slab->obj_exts = 0;
2269 }
2270 
2271 /*
2272  * Try to allocate slabobj_ext array from unused space.
2273  * This function must be called on a freshly allocated slab to prevent
2274  * concurrency problems.
2275  */
2276 static void alloc_slab_obj_exts_early(struct kmem_cache *s, struct slab *slab)
2277 {
2278 	void *addr;
2279 	unsigned long obj_exts;
2280 
2281 	/* Initialize stride early to avoid memory ordering issues */
2282 	slab_set_stride(slab, sizeof(struct slabobj_ext));
2283 
2284 	if (!need_slab_obj_exts(s))
2285 		return;
2286 
2287 	if (obj_exts_fit_within_slab_leftover(s, slab)) {
2288 		addr = slab_address(slab) + obj_exts_offset_in_slab(s, slab);
2289 		addr = kasan_reset_tag(addr);
2290 		obj_exts = (unsigned long)addr;
2291 
2292 		get_slab_obj_exts(obj_exts);
2293 		memset(addr, 0, obj_exts_size_in_slab(slab));
2294 		put_slab_obj_exts(obj_exts);
2295 
2296 #ifdef CONFIG_MEMCG
2297 		obj_exts |= MEMCG_DATA_OBJEXTS;
2298 #endif
2299 		slab->obj_exts = obj_exts;
2300 	} else if (s->flags & SLAB_OBJ_EXT_IN_OBJ) {
2301 		unsigned int offset = obj_exts_offset_in_object(s);
2302 
2303 		obj_exts = (unsigned long)slab_address(slab);
2304 		obj_exts += s->red_left_pad;
2305 		obj_exts += offset;
2306 
2307 		get_slab_obj_exts(obj_exts);
2308 		for_each_object(addr, s, slab_address(slab), slab->objects)
2309 			memset(kasan_reset_tag(addr) + offset, 0,
2310 			       sizeof(struct slabobj_ext));
2311 		put_slab_obj_exts(obj_exts);
2312 
2313 #ifdef CONFIG_MEMCG
2314 		obj_exts |= MEMCG_DATA_OBJEXTS;
2315 #endif
2316 		slab->obj_exts = obj_exts;
2317 		slab_set_stride(slab, s->size);
2318 	}
2319 }
2320 
2321 #else /* CONFIG_SLAB_OBJ_EXT */
2322 
2323 static inline void mark_obj_codetag_empty(const void *obj)
2324 {
2325 }
2326 
2327 static inline void init_slab_obj_exts(struct slab *slab)
2328 {
2329 }
2330 
2331 static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2332 			       gfp_t gfp, unsigned int alloc_flags)
2333 {
2334 	return 0;
2335 }
2336 
2337 static inline void free_slab_obj_exts(struct slab *slab, bool allow_spin)
2338 {
2339 }
2340 
2341 static inline void alloc_slab_obj_exts_early(struct kmem_cache *s,
2342 						       struct slab *slab)
2343 {
2344 }
2345 
2346 #endif /* CONFIG_SLAB_OBJ_EXT */
2347 
2348 #ifdef CONFIG_MEM_ALLOC_PROFILING
2349 
2350 static inline unsigned long
2351 prepare_slab_obj_exts_hook(struct kmem_cache *s, struct slab *slab,
2352 			   gfp_t flags, unsigned int alloc_flags, void *p)
2353 {
2354 	if (!slab_obj_exts(slab) &&
2355 	    alloc_slab_obj_exts(slab, s, flags, alloc_flags)) {
2356 		pr_warn_once("%s, %s: Failed to create slab extension vector!\n",
2357 			     __func__, s->name);
2358 		return 0;
2359 	}
2360 
2361 	return slab_obj_exts(slab);
2362 }
2363 
2364 
2365 /* Should be called only if mem_alloc_profiling_enabled() */
2366 static noinline void
2367 __alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags,
2368 				unsigned int alloc_flags)
2369 {
2370 	unsigned long obj_exts;
2371 	struct slabobj_ext *obj_ext;
2372 	struct slab *slab;
2373 
2374 	if (!object)
2375 		return;
2376 
2377 	if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2378 		return;
2379 
2380 	if (alloc_flags & SLAB_ALLOC_NO_RECURSE)
2381 		return;
2382 
2383 	slab = virt_to_slab(object);
2384 	obj_exts = prepare_slab_obj_exts_hook(s, slab, flags, alloc_flags, object);
2385 	/*
2386 	 * Currently obj_exts is used only for allocation profiling.
2387 	 * If other users appear then mem_alloc_profiling_enabled()
2388 	 * check should be added before alloc_tag_add().
2389 	 */
2390 	if (obj_exts) {
2391 		unsigned int obj_idx = obj_to_index(s, slab, object);
2392 
2393 		get_slab_obj_exts(obj_exts);
2394 		obj_ext = slab_obj_ext(slab, obj_exts, obj_idx);
2395 		alloc_tag_add(&obj_ext->ref, current->alloc_tag, s->size);
2396 		put_slab_obj_exts(obj_exts);
2397 	} else {
2398 		alloc_tag_set_inaccurate(current->alloc_tag);
2399 	}
2400 }
2401 
2402 static inline void
2403 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags,
2404 			      unsigned int alloc_flags)
2405 {
2406 	if (mem_alloc_profiling_enabled())
2407 		__alloc_tagging_slab_alloc_hook(s, object, flags, alloc_flags);
2408 }
2409 
2410 /* Should be called only if mem_alloc_profiling_enabled() */
2411 static noinline void
2412 __alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2413 			       int objects)
2414 {
2415 	int i;
2416 	unsigned long obj_exts;
2417 
2418 	/* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */
2419 	if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2420 		return;
2421 
2422 	obj_exts = slab_obj_exts(slab);
2423 	if (!obj_exts)
2424 		return;
2425 
2426 	get_slab_obj_exts(obj_exts);
2427 	for (i = 0; i < objects; i++) {
2428 		unsigned int off = obj_to_index(s, slab, p[i]);
2429 
2430 		alloc_tag_sub(&slab_obj_ext(slab, obj_exts, off)->ref, s->size);
2431 	}
2432 	put_slab_obj_exts(obj_exts);
2433 }
2434 
2435 static inline void
2436 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2437 			     int objects)
2438 {
2439 	if (mem_alloc_profiling_enabled())
2440 		__alloc_tagging_slab_free_hook(s, slab, p, objects);
2441 }
2442 
2443 #else /* CONFIG_MEM_ALLOC_PROFILING */
2444 
2445 static inline void
2446 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags,
2447 			      unsigned int alloc_flags)
2448 {
2449 }
2450 
2451 static inline void
2452 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2453 			     int objects)
2454 {
2455 }
2456 
2457 #endif /* CONFIG_MEM_ALLOC_PROFILING */
2458 
2459 
2460 #ifdef CONFIG_MEMCG
2461 
2462 static void memcg_alloc_abort_single(struct kmem_cache *s, void *object);
2463 
2464 static __fastpath_inline
2465 bool memcg_slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags,
2466 				size_t size, void **p,
2467 				const struct slab_alloc_context *ac)
2468 {
2469 	if (likely(!memcg_kmem_online()))
2470 		return true;
2471 
2472 	if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT)))
2473 		return true;
2474 
2475 	if (likely(__memcg_slab_post_alloc_hook(s, ac->lru, flags,
2476 						ac->alloc_flags, size, p)))
2477 		return true;
2478 
2479 	if (likely(size == 1)) {
2480 		memcg_alloc_abort_single(s, *p);
2481 		*p = NULL;
2482 	} else {
2483 		kmem_cache_free_bulk(s, size, p);
2484 	}
2485 
2486 	return false;
2487 }
2488 
2489 static __fastpath_inline
2490 void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2491 			  int objects)
2492 {
2493 	unsigned long obj_exts;
2494 
2495 	if (!memcg_kmem_online())
2496 		return;
2497 
2498 	obj_exts = slab_obj_exts(slab);
2499 	if (likely(!obj_exts))
2500 		return;
2501 
2502 	get_slab_obj_exts(obj_exts);
2503 	__memcg_slab_free_hook(s, slab, p, objects, obj_exts);
2504 	put_slab_obj_exts(obj_exts);
2505 }
2506 
2507 static __fastpath_inline
2508 bool memcg_slab_post_charge(void *p, gfp_t flags)
2509 {
2510 	unsigned long obj_exts;
2511 	struct slabobj_ext *obj_ext;
2512 	struct kmem_cache *s;
2513 	struct page *page;
2514 	struct slab *slab;
2515 	unsigned long off;
2516 
2517 	page = virt_to_page(p);
2518 	if (PageLargeKmalloc(page)) {
2519 		unsigned int order;
2520 		int size;
2521 
2522 		if (PageMemcgKmem(page))
2523 			return true;
2524 
2525 		order = large_kmalloc_order(page);
2526 		if (__memcg_kmem_charge_page(page, flags, order))
2527 			return false;
2528 
2529 		/*
2530 		 * This page has already been accounted in the global stats but
2531 		 * not in the memcg stats. So, subtract from the global and use
2532 		 * the interface which adds to both global and memcg stats.
2533 		 */
2534 		size = PAGE_SIZE << order;
2535 		mod_node_page_state(page_pgdat(page), NR_SLAB_UNRECLAIMABLE_B, -size);
2536 		mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B, size);
2537 		return true;
2538 	}
2539 
2540 	slab = page_slab(page);
2541 	s = slab->slab_cache;
2542 
2543 	/*
2544 	 * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency
2545 	 * of slab_obj_exts being allocated from the same slab and thus the slab
2546 	 * becoming effectively unfreeable.
2547 	 */
2548 	if (is_kmalloc_normal(s))
2549 		return true;
2550 
2551 	/* Ignore already charged objects. */
2552 	obj_exts = slab_obj_exts(slab);
2553 	if (obj_exts) {
2554 		get_slab_obj_exts(obj_exts);
2555 		off = obj_to_index(s, slab, p);
2556 		obj_ext = slab_obj_ext(slab, obj_exts, off);
2557 		if (unlikely(obj_ext->objcg)) {
2558 			put_slab_obj_exts(obj_exts);
2559 			return true;
2560 		}
2561 		put_slab_obj_exts(obj_exts);
2562 	}
2563 
2564 	return __memcg_slab_post_alloc_hook(s, NULL, flags, SLAB_ALLOC_DEFAULT,
2565 					    1, &p);
2566 }
2567 
2568 #else /* CONFIG_MEMCG */
2569 static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s,
2570 					      gfp_t flags,
2571 					      size_t size, void **p,
2572 					      const struct slab_alloc_context *ac)
2573 {
2574 	return true;
2575 }
2576 
2577 static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
2578 					void **p, int objects)
2579 {
2580 }
2581 
2582 static inline bool memcg_slab_post_charge(void *p, gfp_t flags)
2583 {
2584 	return true;
2585 }
2586 #endif /* CONFIG_MEMCG */
2587 
2588 #ifdef CONFIG_SLUB_RCU_DEBUG
2589 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head);
2590 
2591 struct rcu_delayed_free {
2592 	struct rcu_head head;
2593 	void *object;
2594 };
2595 #endif
2596 
2597 /*
2598  * Hooks for other subsystems that check memory allocations. In a typical
2599  * production configuration these hooks all should produce no code at all.
2600  *
2601  * Returns true if freeing of the object can proceed, false if its reuse
2602  * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned
2603  * to KFENCE.
2604  *
2605  * For objects allocated via kmalloc_nolock(), only a subset of alloc hooks
2606  * are invoked, so some free hooks must handle asymmetric hook calls.
2607  *
2608  * Alloc hooks called for kmalloc_nolock():
2609  * - kmsan_slab_alloc()
2610  * - kasan_slab_alloc()
2611  * - memcg_slab_post_alloc_hook()
2612  * - alloc_tagging_slab_alloc_hook()
2613  *
2614  * Free hooks that must handle missing corresponding alloc hooks:
2615  * - kmemleak_free_recursive()
2616  * - kfence_free()
2617  *
2618  * Free hooks that have no alloc hook counterpart, and thus safe to call:
2619  * - debug_check_no_locks_freed()
2620  * - debug_check_no_obj_freed()
2621  * - __kcsan_check_access()
2622  */
2623 static __always_inline
2624 bool slab_free_hook(struct kmem_cache *s, void *x, bool init,
2625 		    bool after_rcu_delay)
2626 {
2627 	/* Are the object contents still accessible? */
2628 	bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
2629 
2630 	kmemleak_free_recursive(x, s->flags);
2631 	kmsan_slab_free(s, x);
2632 
2633 	debug_check_no_locks_freed(x, s->object_size);
2634 
2635 	if (!(s->flags & SLAB_DEBUG_OBJECTS))
2636 		debug_check_no_obj_freed(x, s->object_size);
2637 
2638 	/* Use KCSAN to help debug racy use-after-free. */
2639 	if (!still_accessible)
2640 		__kcsan_check_access(x, s->object_size,
2641 				     KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
2642 
2643 	if (kfence_free(x))
2644 		return false;
2645 
2646 	/*
2647 	 * Give KASAN a chance to notice an invalid free operation before we
2648 	 * modify the object.
2649 	 */
2650 	if (kasan_slab_pre_free(s, x))
2651 		return false;
2652 
2653 #ifdef CONFIG_SLUB_RCU_DEBUG
2654 	if (still_accessible) {
2655 		struct rcu_delayed_free *delayed_free;
2656 
2657 		delayed_free = kmalloc_obj(*delayed_free, GFP_NOWAIT);
2658 		if (delayed_free) {
2659 			/*
2660 			 * Let KASAN track our call stack as a "related work
2661 			 * creation", just like if the object had been freed
2662 			 * normally via kfree_rcu().
2663 			 * We have to do this manually because the rcu_head is
2664 			 * not located inside the object.
2665 			 */
2666 			kasan_record_aux_stack(x);
2667 
2668 			delayed_free->object = x;
2669 			call_rcu(&delayed_free->head, slab_free_after_rcu_debug);
2670 			return false;
2671 		}
2672 	}
2673 #endif /* CONFIG_SLUB_RCU_DEBUG */
2674 
2675 	/*
2676 	 * As memory initialization might be integrated into KASAN,
2677 	 * kasan_slab_free and initialization memset's must be
2678 	 * kept together to avoid discrepancies in behavior.
2679 	 *
2680 	 * The initialization memset's clear the object and the metadata,
2681 	 * but don't touch the SLAB redzone.
2682 	 *
2683 	 * The object's freepointer is also avoided if stored outside the
2684 	 * object.
2685 	 */
2686 	if (unlikely(init)) {
2687 		int rsize;
2688 		unsigned int inuse, orig_size;
2689 
2690 		inuse = get_info_end(s);
2691 		orig_size = get_orig_size(s, x);
2692 		if (!kasan_has_integrated_init())
2693 			memset(kasan_reset_tag(x), 0, orig_size);
2694 		rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
2695 		memset((char *)kasan_reset_tag(x) + inuse, 0,
2696 		       s->size - inuse - rsize);
2697 		/*
2698 		 * Restore orig_size, otherwise kmalloc redzone overwritten
2699 		 * would be reported
2700 		 */
2701 		set_orig_size(s, x, orig_size);
2702 
2703 	}
2704 	/* KASAN might put x into memory quarantine, delaying its reuse. */
2705 	return !kasan_slab_free(s, x, init, still_accessible, false);
2706 }
2707 
2708 static __fastpath_inline
2709 bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail,
2710 			     int *cnt)
2711 {
2712 
2713 	void *object;
2714 	void *next = *head;
2715 	void *old_tail = *tail;
2716 	bool init;
2717 
2718 	if (is_kfence_address(next)) {
2719 		slab_free_hook(s, next, false, false);
2720 		return false;
2721 	}
2722 
2723 	/* Head and tail of the reconstructed freelist */
2724 	*head = NULL;
2725 	*tail = NULL;
2726 
2727 	init = slab_want_init_on_free(s);
2728 
2729 	do {
2730 		object = next;
2731 		next = get_freepointer(s, object);
2732 
2733 		/* If object's reuse doesn't have to be delayed */
2734 		if (likely(slab_free_hook(s, object, init, false))) {
2735 			/* Move object to the new freelist */
2736 			set_freepointer(s, object, *head);
2737 			*head = object;
2738 			if (!*tail)
2739 				*tail = object;
2740 		} else {
2741 			/*
2742 			 * Adjust the reconstructed freelist depth
2743 			 * accordingly if object's reuse is delayed.
2744 			 */
2745 			--(*cnt);
2746 		}
2747 	} while (object != old_tail);
2748 
2749 	return *head != NULL;
2750 }
2751 
2752 static inline void *setup_object(struct kmem_cache *s, void *object)
2753 {
2754 	setup_object_debug(s, object);
2755 	object = kasan_init_slab_obj(s, object);
2756 	if (unlikely(s->ctor)) {
2757 		kasan_unpoison_new_object(s, object);
2758 		s->ctor(object);
2759 		kasan_poison_new_object(s, object);
2760 	}
2761 	return object;
2762 }
2763 
2764 static struct slab_sheaf *__alloc_empty_sheaf(struct kmem_cache *s, gfp_t gfp,
2765 				unsigned int alloc_flags, unsigned int capacity)
2766 {
2767 	struct slab_sheaf *sheaf;
2768 	size_t sheaf_size;
2769 
2770 	/*
2771 	 * Prevent recursion to the same cache, or a deep stack of kmallocs of
2772 	 * varying sizes (sheaf capacity might differ for each kmalloc size
2773 	 * bucket)
2774 	 */
2775 	if (s->flags & SLAB_KMALLOC)
2776 		alloc_flags |= SLAB_ALLOC_NO_RECURSE;
2777 
2778 	sheaf_size = struct_size(sheaf, objects, capacity);
2779 	sheaf = kmalloc_flags(sheaf_size, gfp | __GFP_ZERO, alloc_flags, NUMA_NO_NODE);
2780 
2781 	if (unlikely(!sheaf))
2782 		return NULL;
2783 
2784 	sheaf->cache = s;
2785 
2786 	stat(s, SHEAF_ALLOC);
2787 
2788 	return sheaf;
2789 }
2790 
2791 static inline struct slab_sheaf *alloc_empty_sheaf(struct kmem_cache *s,
2792 				gfp_t gfp, unsigned int alloc_flags)
2793 {
2794 	if (alloc_flags & SLAB_ALLOC_NO_RECURSE)
2795 		return NULL;
2796 
2797 	gfp &= ~OBJCGS_CLEAR_MASK;
2798 
2799 	return __alloc_empty_sheaf(s, gfp, alloc_flags, s->sheaf_capacity);
2800 }
2801 
2802 static void free_empty_sheaf(struct kmem_cache *s, struct slab_sheaf *sheaf)
2803 {
2804 	/*
2805 	 * If the sheaf was created with SLAB_ALLOC_NO_RECURSE flag then its
2806 	 * corresponding extension is NULL and alloc_tag_sub() will throw a
2807 	 * warning, therefore replace NULL with CODETAG_EMPTY to indicate
2808 	 * that the extension for this sheaf is expected to be NULL.
2809 	 */
2810 	if (s->flags & SLAB_KMALLOC)
2811 		mark_obj_codetag_empty(sheaf);
2812 
2813 	VM_WARN_ON_ONCE(sheaf->size > 0);
2814 	kfree(sheaf);
2815 
2816 	stat(s, SHEAF_FREE);
2817 }
2818 
2819 static unsigned int
2820 refill_objects(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
2821 	       unsigned int max);
2822 
2823 static int refill_sheaf(struct kmem_cache *s, struct slab_sheaf *sheaf,
2824 			 gfp_t gfp)
2825 {
2826 	int to_fill = s->sheaf_capacity - sheaf->size;
2827 	int filled;
2828 
2829 	if (!to_fill)
2830 		return 0;
2831 
2832 	filled = refill_objects(s, &sheaf->objects[sheaf->size], gfp, to_fill,
2833 				to_fill);
2834 
2835 	sheaf->size += filled;
2836 
2837 	stat_add(s, SHEAF_REFILL, filled);
2838 
2839 	if (filled < to_fill)
2840 		return -ENOMEM;
2841 
2842 	return 0;
2843 }
2844 
2845 /*
2846  * Maximum number of objects freed during a single flush of main pcs sheaf.
2847  * Translates directly to an on-stack array size.
2848  */
2849 #define PCS_BATCH_MAX	32U
2850 
2851 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p);
2852 
2853 /*
2854  * Free all objects from the main sheaf. In order to perform
2855  * __kmem_cache_free_bulk() outside of cpu_sheaves->lock, work in batches where
2856  * object pointers are moved to a on-stack array under the lock. To bound the
2857  * stack usage, limit each batch to PCS_BATCH_MAX.
2858  *
2859  * Must be called with s->cpu_sheaves->lock locked, returns with the lock
2860  * unlocked.
2861  *
2862  * Returns how many objects are remaining to be flushed
2863  */
2864 static unsigned int __sheaf_flush_main_batch(struct kmem_cache *s)
2865 {
2866 	struct slub_percpu_sheaves *pcs;
2867 	unsigned int batch, remaining;
2868 	void *objects[PCS_BATCH_MAX];
2869 	struct slab_sheaf *sheaf;
2870 
2871 	lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
2872 
2873 	pcs = this_cpu_ptr(s->cpu_sheaves);
2874 	sheaf = pcs->main;
2875 
2876 	batch = min(PCS_BATCH_MAX, sheaf->size);
2877 
2878 	sheaf->size -= batch;
2879 	memcpy(objects, sheaf->objects + sheaf->size, batch * sizeof(void *));
2880 
2881 	remaining = sheaf->size;
2882 
2883 	local_unlock(&s->cpu_sheaves->lock);
2884 
2885 	__kmem_cache_free_bulk(s, batch, &objects[0]);
2886 
2887 	stat_add(s, SHEAF_FLUSH, batch);
2888 
2889 	return remaining;
2890 }
2891 
2892 static void sheaf_flush_main(struct kmem_cache *s)
2893 {
2894 	unsigned int remaining;
2895 
2896 	do {
2897 		local_lock(&s->cpu_sheaves->lock);
2898 
2899 		remaining = __sheaf_flush_main_batch(s);
2900 
2901 	} while (remaining);
2902 }
2903 
2904 /*
2905  * Returns true if the main sheaf was at least partially flushed.
2906  */
2907 static bool sheaf_try_flush_main(struct kmem_cache *s)
2908 {
2909 	unsigned int remaining;
2910 	bool ret = false;
2911 
2912 	do {
2913 		if (!local_trylock(&s->cpu_sheaves->lock))
2914 			return ret;
2915 
2916 		ret = true;
2917 		remaining = __sheaf_flush_main_batch(s);
2918 
2919 	} while (remaining);
2920 
2921 	return ret;
2922 }
2923 
2924 /*
2925  * Free all objects from a sheaf that's unused, i.e. not linked to any
2926  * cpu_sheaves, so we need no locking and batching. The locking is also not
2927  * necessary when flushing cpu's sheaves (both spare and main) during cpu
2928  * hotremove as the cpu is not executing anymore.
2929  */
2930 static void sheaf_flush_unused(struct kmem_cache *s, struct slab_sheaf *sheaf)
2931 {
2932 	if (!sheaf->size)
2933 		return;
2934 
2935 	stat_add(s, SHEAF_FLUSH, sheaf->size);
2936 
2937 	__kmem_cache_free_bulk(s, sheaf->size, &sheaf->objects[0]);
2938 
2939 	sheaf->size = 0;
2940 }
2941 
2942 static bool __rcu_free_sheaf_prepare(struct kmem_cache *s,
2943 				     struct slab_sheaf *sheaf)
2944 {
2945 	bool init = slab_want_init_on_free(s);
2946 	void **p = &sheaf->objects[0];
2947 	unsigned int i = 0;
2948 	bool pfmemalloc = false;
2949 
2950 	while (i < sheaf->size) {
2951 		struct slab *slab = virt_to_slab(p[i]);
2952 
2953 		memcg_slab_free_hook(s, slab, p + i, 1);
2954 		alloc_tagging_slab_free_hook(s, slab, p + i, 1);
2955 
2956 		if (unlikely(!slab_free_hook(s, p[i], init, true))) {
2957 			p[i] = p[--sheaf->size];
2958 			continue;
2959 		}
2960 
2961 		if (slab_test_pfmemalloc(slab))
2962 			pfmemalloc = true;
2963 
2964 		i++;
2965 	}
2966 
2967 	return pfmemalloc;
2968 }
2969 
2970 static void rcu_free_sheaf_nobarn(struct rcu_head *head)
2971 {
2972 	struct slab_sheaf *sheaf;
2973 	struct kmem_cache *s;
2974 
2975 	sheaf = container_of(head, struct slab_sheaf, rcu_head);
2976 	s = sheaf->cache;
2977 
2978 	__rcu_free_sheaf_prepare(s, sheaf);
2979 
2980 	sheaf_flush_unused(s, sheaf);
2981 
2982 	free_empty_sheaf(s, sheaf);
2983 }
2984 
2985 /*
2986  * Caller needs to make sure migration is disabled in order to fully flush
2987  * single cpu's sheaves
2988  *
2989  * must not be called from an irq
2990  *
2991  * flushing operations are rare so let's keep it simple and flush to slabs
2992  * directly, skipping the barn
2993  */
2994 static void pcs_flush_all(struct kmem_cache *s)
2995 {
2996 	struct slub_percpu_sheaves *pcs;
2997 	struct slab_sheaf *spare, *rcu_free;
2998 
2999 	local_lock(&s->cpu_sheaves->lock);
3000 	pcs = this_cpu_ptr(s->cpu_sheaves);
3001 
3002 	spare = pcs->spare;
3003 	pcs->spare = NULL;
3004 
3005 	rcu_free = pcs->rcu_free;
3006 	pcs->rcu_free = NULL;
3007 
3008 	local_unlock(&s->cpu_sheaves->lock);
3009 
3010 	if (spare) {
3011 		sheaf_flush_unused(s, spare);
3012 		free_empty_sheaf(s, spare);
3013 	}
3014 
3015 	if (rcu_free)
3016 		call_rcu(&rcu_free->rcu_head, rcu_free_sheaf_nobarn);
3017 
3018 	sheaf_flush_main(s);
3019 }
3020 
3021 static void __pcs_flush_all_cpu(struct kmem_cache *s, unsigned int cpu)
3022 {
3023 	struct slub_percpu_sheaves *pcs;
3024 
3025 	pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
3026 
3027 	/* The cpu is not executing anymore so we don't need pcs->lock */
3028 	sheaf_flush_unused(s, pcs->main);
3029 	if (pcs->spare) {
3030 		sheaf_flush_unused(s, pcs->spare);
3031 		free_empty_sheaf(s, pcs->spare);
3032 		pcs->spare = NULL;
3033 	}
3034 
3035 	if (pcs->rcu_free) {
3036 		call_rcu(&pcs->rcu_free->rcu_head, rcu_free_sheaf_nobarn);
3037 		pcs->rcu_free = NULL;
3038 	}
3039 }
3040 
3041 static void pcs_destroy(struct kmem_cache *s)
3042 {
3043 	int cpu;
3044 
3045 	/*
3046 	 * We may be unwinding cache creation that failed before or during the
3047 	 * allocation of this.
3048 	 */
3049 	if (!s->cpu_sheaves)
3050 		return;
3051 
3052 	/* pcs->main can only point to the bootstrap sheaf, nothing to free */
3053 	if (!cache_has_sheaves(s))
3054 		goto free_pcs;
3055 
3056 	for_each_possible_cpu(cpu) {
3057 		struct slub_percpu_sheaves *pcs;
3058 
3059 		pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
3060 
3061 		/* This can happen when unwinding failed cache creation. */
3062 		if (!pcs->main)
3063 			continue;
3064 
3065 		/*
3066 		 * We have already passed __kmem_cache_shutdown() so everything
3067 		 * was flushed and there should be no objects allocated from
3068 		 * slabs, otherwise kmem_cache_destroy() would have aborted.
3069 		 * Therefore something would have to be really wrong if the
3070 		 * warnings here trigger, and we should rather leave objects and
3071 		 * sheaves to leak in that case.
3072 		 */
3073 
3074 		WARN_ON(pcs->spare);
3075 		WARN_ON(pcs->rcu_free);
3076 
3077 		if (!WARN_ON(pcs->main->size)) {
3078 			free_empty_sheaf(s, pcs->main);
3079 			pcs->main = NULL;
3080 		}
3081 	}
3082 
3083 free_pcs:
3084 	free_percpu(s->cpu_sheaves);
3085 	s->cpu_sheaves = NULL;
3086 }
3087 
3088 static struct slab_sheaf *barn_get_empty_sheaf(struct node_barn *barn,
3089 					       bool allow_spin)
3090 {
3091 	struct slab_sheaf *empty = NULL;
3092 	unsigned long flags;
3093 
3094 	if (!data_race(barn->nr_empty))
3095 		return NULL;
3096 
3097 	if (likely(allow_spin))
3098 		spin_lock_irqsave(&barn->lock, flags);
3099 	else if (!spin_trylock_irqsave(&barn->lock, flags))
3100 		return NULL;
3101 
3102 	if (likely(barn->nr_empty)) {
3103 		empty = list_first_entry(&barn->sheaves_empty,
3104 					 struct slab_sheaf, barn_list);
3105 		list_del(&empty->barn_list);
3106 		barn->nr_empty--;
3107 	}
3108 
3109 	spin_unlock_irqrestore(&barn->lock, flags);
3110 
3111 	return empty;
3112 }
3113 
3114 /*
3115  * The following two functions are used mainly in cases where we have to undo an
3116  * intended action due to a race or cpu migration. Thus they do not check the
3117  * empty or full sheaf limits for simplicity.
3118  */
3119 
3120 static void barn_put_empty_sheaf(struct node_barn *barn, struct slab_sheaf *sheaf)
3121 {
3122 	unsigned long flags;
3123 
3124 	spin_lock_irqsave(&barn->lock, flags);
3125 
3126 	list_add(&sheaf->barn_list, &barn->sheaves_empty);
3127 	barn->nr_empty++;
3128 
3129 	spin_unlock_irqrestore(&barn->lock, flags);
3130 }
3131 
3132 static void barn_put_full_sheaf(struct node_barn *barn, struct slab_sheaf *sheaf)
3133 {
3134 	unsigned long flags;
3135 
3136 	spin_lock_irqsave(&barn->lock, flags);
3137 
3138 	list_add(&sheaf->barn_list, &barn->sheaves_full);
3139 	barn->nr_full++;
3140 
3141 	spin_unlock_irqrestore(&barn->lock, flags);
3142 }
3143 
3144 static struct slab_sheaf *barn_get_full_or_empty_sheaf(struct node_barn *barn)
3145 {
3146 	struct slab_sheaf *sheaf = NULL;
3147 	unsigned long flags;
3148 
3149 	if (!data_race(barn->nr_full) && !data_race(barn->nr_empty))
3150 		return NULL;
3151 
3152 	spin_lock_irqsave(&barn->lock, flags);
3153 
3154 	if (barn->nr_full) {
3155 		sheaf = list_first_entry(&barn->sheaves_full, struct slab_sheaf,
3156 					barn_list);
3157 		list_del(&sheaf->barn_list);
3158 		barn->nr_full--;
3159 	} else if (barn->nr_empty) {
3160 		sheaf = list_first_entry(&barn->sheaves_empty,
3161 					 struct slab_sheaf, barn_list);
3162 		list_del(&sheaf->barn_list);
3163 		barn->nr_empty--;
3164 	}
3165 
3166 	spin_unlock_irqrestore(&barn->lock, flags);
3167 
3168 	return sheaf;
3169 }
3170 
3171 /*
3172  * If a full sheaf is available, return it and put the supplied empty one to
3173  * barn. We ignore the limit on empty sheaves as the number of sheaves doesn't
3174  * change.
3175  */
3176 static struct slab_sheaf *
3177 barn_replace_empty_sheaf(struct node_barn *barn, struct slab_sheaf *empty,
3178 			 bool allow_spin)
3179 {
3180 	struct slab_sheaf *full = NULL;
3181 	unsigned long flags;
3182 
3183 	if (!data_race(barn->nr_full))
3184 		return NULL;
3185 
3186 	if (likely(allow_spin))
3187 		spin_lock_irqsave(&barn->lock, flags);
3188 	else if (!spin_trylock_irqsave(&barn->lock, flags))
3189 		return NULL;
3190 
3191 	if (likely(barn->nr_full)) {
3192 		full = list_first_entry(&barn->sheaves_full, struct slab_sheaf,
3193 					barn_list);
3194 		list_del(&full->barn_list);
3195 		list_add(&empty->barn_list, &barn->sheaves_empty);
3196 		barn->nr_full--;
3197 		barn->nr_empty++;
3198 	}
3199 
3200 	spin_unlock_irqrestore(&barn->lock, flags);
3201 
3202 	return full;
3203 }
3204 
3205 /*
3206  * If an empty sheaf is available, return it and put the supplied full one to
3207  * barn. But if there are too many full sheaves, reject this with -E2BIG.
3208  */
3209 static struct slab_sheaf *
3210 barn_replace_full_sheaf(struct node_barn *barn, struct slab_sheaf *full,
3211 			bool allow_spin)
3212 {
3213 	struct slab_sheaf *empty;
3214 	unsigned long flags;
3215 
3216 	/* we don't repeat this check under barn->lock as it's not critical */
3217 	if (data_race(barn->nr_full) >= MAX_FULL_SHEAVES)
3218 		return ERR_PTR(-E2BIG);
3219 	if (!data_race(barn->nr_empty))
3220 		return ERR_PTR(-ENOMEM);
3221 
3222 	if (likely(allow_spin))
3223 		spin_lock_irqsave(&barn->lock, flags);
3224 	else if (!spin_trylock_irqsave(&barn->lock, flags))
3225 		return ERR_PTR(-EBUSY);
3226 
3227 	if (likely(barn->nr_empty)) {
3228 		empty = list_first_entry(&barn->sheaves_empty, struct slab_sheaf,
3229 					 barn_list);
3230 		list_del(&empty->barn_list);
3231 		list_add(&full->barn_list, &barn->sheaves_full);
3232 		barn->nr_empty--;
3233 		barn->nr_full++;
3234 	} else {
3235 		empty = ERR_PTR(-ENOMEM);
3236 	}
3237 
3238 	spin_unlock_irqrestore(&barn->lock, flags);
3239 
3240 	return empty;
3241 }
3242 
3243 static void barn_init(struct node_barn *barn)
3244 {
3245 	spin_lock_init(&barn->lock);
3246 	INIT_LIST_HEAD(&barn->sheaves_full);
3247 	INIT_LIST_HEAD(&barn->sheaves_empty);
3248 	barn->nr_full = 0;
3249 	barn->nr_empty = 0;
3250 }
3251 
3252 static void barn_shrink(struct kmem_cache *s, struct node_barn *barn)
3253 {
3254 	LIST_HEAD(empty_list);
3255 	LIST_HEAD(full_list);
3256 	struct slab_sheaf *sheaf, *sheaf2;
3257 	unsigned long flags;
3258 
3259 	spin_lock_irqsave(&barn->lock, flags);
3260 
3261 	list_splice_init(&barn->sheaves_full, &full_list);
3262 	barn->nr_full = 0;
3263 	list_splice_init(&barn->sheaves_empty, &empty_list);
3264 	barn->nr_empty = 0;
3265 
3266 	spin_unlock_irqrestore(&barn->lock, flags);
3267 
3268 	list_for_each_entry_safe(sheaf, sheaf2, &full_list, barn_list) {
3269 		sheaf_flush_unused(s, sheaf);
3270 		free_empty_sheaf(s, sheaf);
3271 	}
3272 
3273 	list_for_each_entry_safe(sheaf, sheaf2, &empty_list, barn_list)
3274 		free_empty_sheaf(s, sheaf);
3275 }
3276 
3277 /*
3278  * Slab allocation and freeing
3279  */
3280 static inline struct slab *alloc_slab_page(gfp_t flags, int node,
3281 					   struct kmem_cache_order_objects oo,
3282 					   bool allow_spin)
3283 {
3284 	struct page *page;
3285 	struct slab *slab;
3286 	unsigned int order = oo_order(oo);
3287 
3288 	if (unlikely(!allow_spin))
3289 		page = alloc_frozen_pages_nolock(0/* __GFP_COMP is implied */,
3290 								  node, order);
3291 	else if (node == NUMA_NO_NODE)
3292 		page = alloc_frozen_pages(flags, order);
3293 	else
3294 		page = __alloc_frozen_pages(flags, order, node, NULL);
3295 
3296 	if (!page)
3297 		return NULL;
3298 
3299 	__SetPageSlab(page);
3300 	slab = page_slab(page);
3301 	if (page_is_pfmemalloc(page))
3302 		slab_set_pfmemalloc(slab);
3303 
3304 	return slab;
3305 }
3306 
3307 #ifdef CONFIG_SLAB_FREELIST_RANDOM
3308 /* Pre-initialize the random sequence cache */
3309 static int init_cache_random_seq(struct kmem_cache *s)
3310 {
3311 	unsigned int count = oo_objects(s->oo);
3312 	int err;
3313 
3314 	/* Bailout if already initialised */
3315 	if (s->random_seq)
3316 		return 0;
3317 
3318 	err = cache_random_seq_create(s, count, GFP_KERNEL);
3319 	if (err) {
3320 		pr_err("SLUB: Unable to initialize free list for %s\n",
3321 			s->name);
3322 		return err;
3323 	}
3324 
3325 	/* Transform to an offset on the set of pages */
3326 	if (s->random_seq) {
3327 		unsigned int i;
3328 
3329 		for (i = 0; i < count; i++)
3330 			s->random_seq[i] *= s->size;
3331 	}
3332 	return 0;
3333 }
3334 
3335 /* Initialize each random sequence freelist per cache */
3336 static void __init init_freelist_randomization(void)
3337 {
3338 	struct kmem_cache *s;
3339 
3340 	mutex_lock(&slab_mutex);
3341 
3342 	list_for_each_entry(s, &slab_caches, list)
3343 		init_cache_random_seq(s);
3344 
3345 	mutex_unlock(&slab_mutex);
3346 }
3347 
3348 static DEFINE_PER_CPU(struct rnd_state, slab_rnd_state);
3349 
3350 #else
3351 static inline int init_cache_random_seq(struct kmem_cache *s)
3352 {
3353 	return 0;
3354 }
3355 static inline void init_freelist_randomization(void) { }
3356 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
3357 
3358 static __always_inline void account_slab(struct slab *slab, int order,
3359 					 struct kmem_cache *s, gfp_t gfp,
3360 					 unsigned int alloc_flags)
3361 {
3362 	if (memcg_kmem_online() &&
3363 			(s->flags & SLAB_ACCOUNT) &&
3364 			!slab_obj_exts(slab))
3365 		alloc_slab_obj_exts(slab, s, gfp,
3366 				    alloc_flags | SLAB_ALLOC_NEW_SLAB);
3367 
3368 	mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
3369 			    PAGE_SIZE << order);
3370 }
3371 
3372 static __always_inline void unaccount_slab(struct slab *slab, int order,
3373 					   struct kmem_cache *s, bool allow_spin)
3374 {
3375 	/*
3376 	 * The slab object extensions should now be freed regardless of
3377 	 * whether mem_alloc_profiling_enabled() or not because profiling
3378 	 * might have been disabled after slab->obj_exts got allocated.
3379 	 */
3380 	free_slab_obj_exts(slab, allow_spin);
3381 
3382 	mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
3383 			    -(PAGE_SIZE << order));
3384 }
3385 
3386 /* Allocate and initialize a slab without building its freelist. */
3387 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
3388 				  unsigned int alloc_flags, int node)
3389 {
3390 	bool allow_spin = alloc_flags_allow_spinning(alloc_flags);
3391 	struct slab *slab;
3392 	struct kmem_cache_order_objects oo = s->oo;
3393 	gfp_t alloc_gfp;
3394 	void *start;
3395 
3396 	flags &= gfp_allowed_mask;
3397 
3398 	flags |= s->allocflags;
3399 
3400 	/*
3401 	 * Let the initial higher-order allocation fail under memory pressure
3402 	 * so we fall-back to the minimum order allocation.
3403 	 */
3404 	alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
3405 	if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
3406 		alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
3407 
3408 	slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
3409 	if (unlikely(!slab)) {
3410 		oo = s->min;
3411 		alloc_gfp = flags;
3412 		/*
3413 		 * Allocation may have failed due to fragmentation.
3414 		 * Try a lower order alloc if possible
3415 		 */
3416 		slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
3417 		if (unlikely(!slab))
3418 			return NULL;
3419 		stat(s, ORDER_FALLBACK);
3420 	}
3421 
3422 	slab->objects = oo_objects(oo);
3423 	slab->inuse = 0;
3424 	slab->frozen = 0;
3425 
3426 	slab->slab_cache = s;
3427 
3428 	kasan_poison_slab(slab);
3429 
3430 	start = slab_address(slab);
3431 
3432 	setup_slab_debug(s, slab, start);
3433 	init_slab_obj_exts(slab);
3434 	/*
3435 	 * Poison the slab before initializing the slabobj_ext array
3436 	 * to prevent the array from being overwritten.
3437 	 */
3438 	alloc_slab_obj_exts_early(s, slab);
3439 	account_slab(slab, oo_order(oo), s, flags, alloc_flags);
3440 
3441 	return slab;
3442 }
3443 
3444 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags,
3445 			     unsigned int alloc_flags, int node)
3446 {
3447 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
3448 		flags = kmalloc_fix_flags(flags);
3449 
3450 	WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
3451 
3452 	flags &= GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK;
3453 
3454 	return allocate_slab(s, flags, alloc_flags, node);
3455 }
3456 
3457 static void __free_slab(struct kmem_cache *s, struct slab *slab, bool allow_spin)
3458 {
3459 	struct page *page = slab_page(slab);
3460 	int order = compound_order(page);
3461 	int pages = 1 << order;
3462 
3463 	__slab_clear_pfmemalloc(slab);
3464 	page->mapping = NULL;
3465 	__ClearPageSlab(page);
3466 	mm_account_reclaimed_pages(pages);
3467 	unaccount_slab(slab, order, s, allow_spin);
3468 	if (allow_spin)
3469 		free_frozen_pages(page, order);
3470 	else
3471 		free_frozen_pages_nolock(page, order);
3472 }
3473 
3474 static void free_new_slab_nolock(struct kmem_cache *s, struct slab *slab)
3475 {
3476 	/*
3477 	 * Since it was just allocated, we can skip the actions in
3478 	 * discard_slab() and free_slab().
3479 	 */
3480 	__free_slab(s, slab, false);
3481 }
3482 
3483 static void rcu_free_slab(struct rcu_head *h)
3484 {
3485 	struct slab *slab = container_of(h, struct slab, rcu_head);
3486 
3487 	__free_slab(slab->slab_cache, slab, true);
3488 }
3489 
3490 static void free_slab(struct kmem_cache *s, struct slab *slab)
3491 {
3492 	if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
3493 		void *p;
3494 
3495 		slab_pad_check(s, slab);
3496 		for_each_object(p, s, slab_address(slab), slab->objects)
3497 			check_object(s, slab, p, SLUB_RED_INACTIVE);
3498 	}
3499 
3500 	if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
3501 		call_rcu(&slab->rcu_head, rcu_free_slab);
3502 	else
3503 		__free_slab(s, slab, true);
3504 }
3505 
3506 static void discard_slab(struct kmem_cache *s, struct slab *slab)
3507 {
3508 	dec_slabs_node(s, slab_nid(slab), slab->objects);
3509 	free_slab(s, slab);
3510 }
3511 
3512 static inline bool slab_test_node_partial(const struct slab *slab)
3513 {
3514 	return test_bit(SL_partial, &slab->flags.f);
3515 }
3516 
3517 static inline void slab_set_node_partial(struct slab *slab)
3518 {
3519 	set_bit(SL_partial, &slab->flags.f);
3520 }
3521 
3522 static inline void slab_clear_node_partial(struct slab *slab)
3523 {
3524 	clear_bit(SL_partial, &slab->flags.f);
3525 }
3526 
3527 /*
3528  * Management of partially allocated slabs.
3529  */
3530 static inline void set_node_partial_state(struct kmem_cache_node *n,
3531 					struct slab *slab)
3532 {
3533 	slab_set_node_partial(slab);
3534 	n->nr_partial++;
3535 }
3536 
3537 static inline void
3538 __add_partial(struct kmem_cache_node *n, struct slab *slab, enum add_mode mode)
3539 {
3540 	if (mode == ADD_TO_TAIL)
3541 		list_add_tail(&slab->slab_list, &n->partial);
3542 	else
3543 		list_add(&slab->slab_list, &n->partial);
3544 	set_node_partial_state(n, slab);
3545 }
3546 
3547 static inline void add_partial(struct kmem_cache_node *n,
3548 				struct slab *slab, enum add_mode mode)
3549 {
3550 	lockdep_assert_held(&n->list_lock);
3551 	__add_partial(n, slab, mode);
3552 }
3553 
3554 static inline void clear_node_partial_state(struct kmem_cache_node *n,
3555 					struct slab *slab)
3556 {
3557 	slab_clear_node_partial(slab);
3558 	n->nr_partial--;
3559 }
3560 
3561 static inline void remove_partial(struct kmem_cache_node *n,
3562 					struct slab *slab)
3563 {
3564 	lockdep_assert_held(&n->list_lock);
3565 	list_del(&slab->slab_list);
3566 	clear_node_partial_state(n, slab);
3567 }
3568 
3569 /*
3570  * Called only for kmem_cache_debug() caches instead of remove_partial(), with a
3571  * slab from the n->partial list. Remove only a single object from the slab, do
3572  * the alloc_debug_processing() checks and leave the slab on the list, or move
3573  * it to full list if it was the last free object.
3574  */
3575 static void *alloc_single_from_partial(struct kmem_cache *s,
3576 		struct kmem_cache_node *n, struct slab *slab, int orig_size)
3577 {
3578 	void *object;
3579 
3580 	lockdep_assert_held(&n->list_lock);
3581 
3582 #ifdef CONFIG_SLUB_DEBUG
3583 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3584 		if (!validate_slab_ptr(slab)) {
3585 			slab_err(s, slab, "Not a valid slab page");
3586 			return NULL;
3587 		}
3588 	}
3589 #endif
3590 
3591 	object = slab->freelist;
3592 	slab->freelist = get_freepointer(s, object);
3593 	slab->inuse++;
3594 
3595 	if (!alloc_debug_processing(s, slab, object, orig_size)) {
3596 		remove_partial(n, slab);
3597 		return NULL;
3598 	}
3599 
3600 	if (slab->inuse == slab->objects) {
3601 		remove_partial(n, slab);
3602 		add_full(s, n, slab);
3603 	}
3604 
3605 	return object;
3606 }
3607 
3608 /* Return the next free object in allocation order. */
3609 static inline void *next_slab_obj(struct kmem_cache *s,
3610 				  struct slab_obj_iter *iter)
3611 {
3612 #ifdef CONFIG_SLAB_FREELIST_RANDOM
3613 	if (iter->random) {
3614 		unsigned long idx;
3615 
3616 		/*
3617 		 * If the target page allocation failed, the number of objects on the
3618 		 * page might be smaller than the usual size defined by the cache.
3619 		 */
3620 		do {
3621 			idx = s->random_seq[iter->pos];
3622 			iter->pos++;
3623 			if (iter->pos >= iter->freelist_count)
3624 				iter->pos = 0;
3625 		} while (unlikely(idx >= iter->page_limit));
3626 
3627 		return setup_object(s, (char *)iter->start + idx);
3628 	}
3629 #endif
3630 	return setup_object(s, (char *)iter->start + iter->pos++ * s->size);
3631 }
3632 
3633 /* Build a freelist from the objects not yet allocated from a fresh slab. */
3634 static inline void build_slab_freelist(struct kmem_cache *s, struct slab *slab,
3635 				       struct slab_obj_iter *iter)
3636 {
3637 	unsigned int nr = slab->objects - slab->inuse;
3638 	unsigned int i;
3639 	void *cur, *next;
3640 
3641 	if (!nr) {
3642 		slab->freelist = NULL;
3643 		return;
3644 	}
3645 
3646 	cur = next_slab_obj(s, iter);
3647 	slab->freelist = cur;
3648 
3649 	for (i = 1; i < nr; i++) {
3650 		next = next_slab_obj(s, iter);
3651 		set_freepointer(s, cur, next);
3652 		cur = next;
3653 	}
3654 
3655 	set_freepointer(s, cur, NULL);
3656 }
3657 
3658 /* Initialize an iterator over free objects in allocation order. */
3659 static inline void init_slab_obj_iter(struct kmem_cache *s, struct slab *slab,
3660 				      struct slab_obj_iter *iter,
3661 				      bool allow_spin)
3662 {
3663 	iter->pos = 0;
3664 	iter->start = fixup_red_left(s, slab_address(slab));
3665 
3666 #ifdef CONFIG_SLAB_FREELIST_RANDOM
3667 	iter->random = (slab->objects >= 2 && s->random_seq);
3668 	if (!iter->random)
3669 		return;
3670 
3671 	iter->freelist_count = oo_objects(s->oo);
3672 	iter->page_limit = slab->objects * s->size;
3673 
3674 	if (allow_spin) {
3675 		iter->pos = get_random_u32_below(iter->freelist_count);
3676 	} else {
3677 		struct rnd_state *state;
3678 
3679 		/*
3680 		 * An interrupt or NMI handler might interrupt and change
3681 		 * the state in the middle, but that's safe.
3682 		 */
3683 		state = &get_cpu_var(slab_rnd_state);
3684 		iter->pos = prandom_u32_state(state) % iter->freelist_count;
3685 		put_cpu_var(slab_rnd_state);
3686 	}
3687 #endif
3688 }
3689 
3690 /*
3691  * Called only for kmem_cache_debug() caches to allocate from a freshly
3692  * allocated slab. Allocate a single object instead of whole freelist
3693  * and put the slab to the partial (or full) list.
3694  */
3695 static void *alloc_single_from_new_slab(struct kmem_cache *s, struct slab *slab,
3696 					const struct slab_alloc_context *ac)
3697 {
3698 	bool allow_spin = alloc_flags_allow_spinning(ac->alloc_flags);
3699 	struct kmem_cache_node *n;
3700 	struct slab_obj_iter iter;
3701 	bool needs_add_partial;
3702 	unsigned long flags;
3703 	void *object;
3704 
3705 	init_slab_obj_iter(s, slab, &iter, allow_spin);
3706 	object = next_slab_obj(s, &iter);
3707 	slab->inuse = 1;
3708 
3709 	needs_add_partial = (slab->objects > 1);
3710 	build_slab_freelist(s, slab, &iter);
3711 
3712 	/* alloc_debug_processing() always expects a valid freepointer */
3713 	set_freepointer(s, object, slab->freelist);
3714 
3715 	if (!alloc_debug_processing(s, slab, object, ac->orig_size)) {
3716 		/*
3717 		 * It's not really expected that this would fail on a
3718 		 * freshly allocated slab, but a concurrent memory
3719 		 * corruption in theory could cause that.
3720 		 * Leak memory of allocated slab.
3721 		 */
3722 		return NULL;
3723 	}
3724 
3725 	n = get_node(s, slab_nid(slab));
3726 	if (allow_spin) {
3727 		spin_lock_irqsave(&n->list_lock, flags);
3728 	} else if (!spin_trylock_irqsave(&n->list_lock, flags)) {
3729 		/*
3730 		 * Unlucky, discard newly allocated slab.
3731 		 * The slab is not fully free, but it's fine as
3732 		 * objects are not allocated to users.
3733 		 */
3734 		free_new_slab_nolock(s, slab);
3735 		return NULL;
3736 	}
3737 
3738 	if (needs_add_partial)
3739 		add_partial(n, slab, ADD_TO_HEAD);
3740 	else
3741 		add_full(s, n, slab);
3742 
3743 	/*
3744 	 * Debug caches require nr_slabs updates under n->list_lock so validation
3745 	 * cannot race with slab (de)allocations and observe inconsistent state.
3746 	 */
3747 	inc_slabs_node(s, slab_nid(slab), slab->objects);
3748 	spin_unlock_irqrestore(&n->list_lock, flags);
3749 
3750 	return object;
3751 }
3752 
3753 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
3754 
3755 static bool get_partial_node_bulk(struct kmem_cache *s,
3756 				  struct kmem_cache_node *n,
3757 				  struct partial_bulk_context *pc,
3758 				  bool allow_spin)
3759 {
3760 	struct slab *slab, *slab2;
3761 	struct slab *first = NULL, *last = NULL;
3762 	unsigned int total_free = 0;
3763 	unsigned long flags;
3764 
3765 	/* Racy check to avoid taking the lock unnecessarily. */
3766 	if (!n || data_race(!n->nr_partial))
3767 		return false;
3768 
3769 	INIT_LIST_HEAD(&pc->slabs);
3770 
3771 	if (allow_spin)
3772 		spin_lock_irqsave(&n->list_lock, flags);
3773 	else if (!spin_trylock_irqsave(&n->list_lock, flags))
3774 		return false;
3775 
3776 	list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
3777 		struct freelist_counters flc;
3778 		unsigned int slab_free;
3779 
3780 		if (!pfmemalloc_match(slab, pc->flags)) {
3781 			if (first) {
3782 				list_bulk_move_tail(&pc->slabs,
3783 						    &first->slab_list,
3784 						    &last->slab_list);
3785 				first = NULL;
3786 			}
3787 			continue;
3788 		}
3789 
3790 		/*
3791 		 * determine the number of free objects in the slab racily
3792 		 *
3793 		 * slab_free is a lower bound due to possible subsequent
3794 		 * concurrent freeing, so the caller may get more objects than
3795 		 * requested and must handle that
3796 		 */
3797 		flc.counters = data_race(READ_ONCE(slab->counters));
3798 		slab_free = flc.objects - flc.inuse;
3799 
3800 		/* we have already min and this would get us over the max */
3801 		if (total_free >= pc->min_objects
3802 		    && total_free + slab_free > pc->max_objects)
3803 			break;
3804 
3805 		if (!first)
3806 			first = slab;
3807 		last = slab;
3808 		clear_node_partial_state(n, slab);
3809 
3810 		total_free += slab_free;
3811 		if (total_free >= pc->max_objects)
3812 			break;
3813 	}
3814 
3815 	if (first)
3816 		list_bulk_move_tail(&pc->slabs, &first->slab_list,
3817 				    &last->slab_list);
3818 
3819 	spin_unlock_irqrestore(&n->list_lock, flags);
3820 	return total_free > 0;
3821 }
3822 
3823 /*
3824  * Try to allocate object from a partial slab on a specific node.
3825  */
3826 static void *get_from_partial_node(struct kmem_cache *s,
3827 				   struct kmem_cache_node *n,
3828 				   gfp_t gfp_flags,
3829 				   const struct slab_alloc_context *ac)
3830 {
3831 	struct slab *slab, *slab2;
3832 	unsigned long flags;
3833 	void *object = NULL;
3834 
3835 	/*
3836 	 * Racy check. If we mistakenly see no partial slabs then we
3837 	 * just allocate an empty slab. If we mistakenly try to get a
3838 	 * partial slab and there is none available then get_from_partial()
3839 	 * will return NULL.
3840 	 */
3841 	if (!n || !n->nr_partial)
3842 		return NULL;
3843 
3844 	if (alloc_flags_allow_spinning(ac->alloc_flags))
3845 		spin_lock_irqsave(&n->list_lock, flags);
3846 	else if (!spin_trylock_irqsave(&n->list_lock, flags))
3847 		return NULL;
3848 	list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
3849 
3850 		struct freelist_counters old, new;
3851 
3852 		if (!pfmemalloc_match(slab, gfp_flags))
3853 			continue;
3854 
3855 		if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
3856 			object = alloc_single_from_partial(s, n, slab,
3857 							ac->orig_size);
3858 			if (object)
3859 				break;
3860 			continue;
3861 		}
3862 
3863 		/*
3864 		 * get a single object from the slab. This might race against
3865 		 * __slab_free(), which however has to take the list_lock if
3866 		 * it's about to make the slab fully free.
3867 		 */
3868 		do {
3869 			old.freelist = slab->freelist;
3870 			old.counters = slab->counters;
3871 
3872 			new.freelist = get_freepointer(s, old.freelist);
3873 			new.counters = old.counters;
3874 			new.inuse++;
3875 
3876 		} while (!__slab_update_freelist(s, slab, &old, &new, "get_from_partial_node"));
3877 
3878 		object = old.freelist;
3879 		if (!new.freelist)
3880 			remove_partial(n, slab);
3881 
3882 		break;
3883 	}
3884 	spin_unlock_irqrestore(&n->list_lock, flags);
3885 	return object;
3886 }
3887 
3888 /*
3889  * Get an object from somewhere. Search in increasing NUMA distances.
3890  */
3891 static void *get_from_any_partial(struct kmem_cache *s, gfp_t gfp_flags,
3892 				  const struct slab_alloc_context *ac)
3893 {
3894 #ifdef CONFIG_NUMA
3895 	struct zonelist *zonelist;
3896 	struct zoneref *z;
3897 	struct zone *zone;
3898 	enum zone_type highest_zoneidx = gfp_zone(gfp_flags);
3899 	unsigned int cpuset_mems_cookie;
3900 	bool allow_spin = alloc_flags_allow_spinning(ac->alloc_flags);
3901 
3902 	/*
3903 	 * The defrag ratio allows a configuration of the tradeoffs between
3904 	 * inter node defragmentation and node local allocations. A lower
3905 	 * defrag_ratio increases the tendency to do local allocations
3906 	 * instead of attempting to obtain partial slabs from other nodes.
3907 	 *
3908 	 * If the defrag_ratio is set to 0 then kmalloc() always
3909 	 * returns node local objects. If the ratio is higher then kmalloc()
3910 	 * may return off node objects because partial slabs are obtained
3911 	 * from other nodes and filled up.
3912 	 *
3913 	 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
3914 	 * (which makes defrag_ratio = 1000) then every (well almost)
3915 	 * allocation will first attempt to defrag slab caches on other nodes.
3916 	 * This means scanning over all nodes to look for partial slabs which
3917 	 * may be expensive if we do it every time we are trying to find a slab
3918 	 * with available objects.
3919 	 */
3920 	if (!s->remote_node_defrag_ratio ||
3921 			get_cycles() % 1024 > s->remote_node_defrag_ratio)
3922 		return NULL;
3923 
3924 	do {
3925 		/*
3926 		 * read_mems_allowed_begin() accesses current->mems_allowed_seq,
3927 		 * a seqcount_spinlock_t that is not NMI-safe. Do not access
3928 		 * current->mems_allowed_seq and avoid retry when GFP flags
3929 		 * indicate spinning is not allowed.
3930 		 */
3931 		if (allow_spin)
3932 			cpuset_mems_cookie = read_mems_allowed_begin();
3933 
3934 		zonelist = node_zonelist(mempolicy_slab_node(), gfp_flags);
3935 		for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
3936 			struct kmem_cache_node *n;
3937 
3938 			n = get_node(s, zone_to_nid(zone));
3939 
3940 			if (n && cpuset_zone_allowed(zone, gfp_flags) &&
3941 					n->nr_partial > s->min_partial) {
3942 
3943 				void *object = get_from_partial_node(s, n,
3944 								gfp_flags, ac);
3945 
3946 				if (object) {
3947 					/*
3948 					 * Don't check read_mems_allowed_retry()
3949 					 * here - if mems_allowed was updated in
3950 					 * parallel, that was a harmless race
3951 					 * between allocation and the cpuset
3952 					 * update
3953 					 */
3954 					return object;
3955 				}
3956 			}
3957 		}
3958 	} while (allow_spin && read_mems_allowed_retry(cpuset_mems_cookie));
3959 #endif	/* CONFIG_NUMA */
3960 	return NULL;
3961 }
3962 
3963 /*
3964  * Get an object from a partial slab
3965  */
3966 static void *get_from_partial(struct kmem_cache *s, int node, gfp_t flags,
3967 			      const struct slab_alloc_context *ac)
3968 {
3969 	int searchnode = node;
3970 	void *object;
3971 
3972 	if (node == NUMA_NO_NODE)
3973 		searchnode = numa_mem_id();
3974 
3975 	object = get_from_partial_node(s, get_node(s, searchnode), flags, ac);
3976 	if (object || (node != NUMA_NO_NODE && (flags & __GFP_THISNODE)))
3977 		return object;
3978 
3979 	return get_from_any_partial(s, flags, ac);
3980 }
3981 
3982 static bool has_pcs_used(int cpu, struct kmem_cache *s)
3983 {
3984 	struct slub_percpu_sheaves *pcs;
3985 
3986 	if (!cache_has_sheaves(s))
3987 		return false;
3988 
3989 	pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
3990 
3991 	return (pcs->spare || pcs->rcu_free || pcs->main->size);
3992 }
3993 
3994 /*
3995  * Flush percpu sheaves
3996  *
3997  * Called from CPU work handler with migration disabled.
3998  */
3999 static void flush_cpu_sheaves(struct work_struct *w)
4000 {
4001 	struct kmem_cache *s;
4002 	struct slub_flush_work *sfw;
4003 
4004 	sfw = container_of(w, struct slub_flush_work, work);
4005 
4006 	s = sfw->s;
4007 
4008 	if (cache_has_sheaves(s))
4009 		pcs_flush_all(s);
4010 }
4011 
4012 static void flush_all_cpus_locked(struct kmem_cache *s)
4013 {
4014 	struct slub_flush_work *sfw;
4015 	unsigned int cpu;
4016 
4017 	lockdep_assert_cpus_held();
4018 	mutex_lock(&flush_lock);
4019 
4020 	for_each_online_cpu(cpu) {
4021 		sfw = &per_cpu(slub_flush, cpu);
4022 		if (!has_pcs_used(cpu, s)) {
4023 			sfw->skip = true;
4024 			continue;
4025 		}
4026 		INIT_WORK(&sfw->work, flush_cpu_sheaves);
4027 		sfw->skip = false;
4028 		sfw->s = s;
4029 		queue_work_on(cpu, flushwq, &sfw->work);
4030 	}
4031 
4032 	for_each_online_cpu(cpu) {
4033 		sfw = &per_cpu(slub_flush, cpu);
4034 		if (sfw->skip)
4035 			continue;
4036 		flush_work(&sfw->work);
4037 	}
4038 
4039 	mutex_unlock(&flush_lock);
4040 }
4041 
4042 static void flush_all(struct kmem_cache *s)
4043 {
4044 	cpus_read_lock();
4045 	flush_all_cpus_locked(s);
4046 	cpus_read_unlock();
4047 }
4048 
4049 static void flush_rcu_sheaf(struct work_struct *w)
4050 {
4051 	struct slub_percpu_sheaves *pcs;
4052 	struct slab_sheaf *rcu_free;
4053 	struct slub_flush_work *sfw;
4054 	struct kmem_cache *s;
4055 
4056 	sfw = container_of(w, struct slub_flush_work, work);
4057 	s = sfw->s;
4058 
4059 	local_lock(&s->cpu_sheaves->lock);
4060 	pcs = this_cpu_ptr(s->cpu_sheaves);
4061 
4062 	rcu_free = pcs->rcu_free;
4063 	pcs->rcu_free = NULL;
4064 
4065 	local_unlock(&s->cpu_sheaves->lock);
4066 
4067 	if (rcu_free)
4068 		call_rcu(&rcu_free->rcu_head, rcu_free_sheaf_nobarn);
4069 }
4070 
4071 
4072 /* needed for kvfree_rcu_barrier() */
4073 void flush_rcu_sheaves_on_cache(struct kmem_cache *s)
4074 {
4075 	struct slub_flush_work *sfw;
4076 	unsigned int cpu;
4077 
4078 	lockdep_assert_cpus_held();
4079 	mutex_lock(&flush_lock);
4080 
4081 	for_each_online_cpu(cpu) {
4082 		sfw = &per_cpu(slub_flush, cpu);
4083 
4084 		/*
4085 		 * we don't check if rcu_free sheaf exists - racing
4086 		 * __kfree_rcu_sheaf() might have just removed it.
4087 		 * by executing flush_rcu_sheaf() on the cpu we make
4088 		 * sure the __kfree_rcu_sheaf() finished its call_rcu()
4089 		 */
4090 
4091 		INIT_WORK(&sfw->work, flush_rcu_sheaf);
4092 		sfw->s = s;
4093 		queue_work_on(cpu, flushwq, &sfw->work);
4094 	}
4095 
4096 	for_each_online_cpu(cpu) {
4097 		sfw = &per_cpu(slub_flush, cpu);
4098 		flush_work(&sfw->work);
4099 	}
4100 
4101 	mutex_unlock(&flush_lock);
4102 }
4103 
4104 void flush_all_rcu_sheaves(void)
4105 {
4106 	struct kmem_cache *s;
4107 
4108 	cpus_read_lock();
4109 	mutex_lock(&slab_mutex);
4110 
4111 	list_for_each_entry(s, &slab_caches, list) {
4112 		if (!cache_has_sheaves(s))
4113 			continue;
4114 		flush_rcu_sheaves_on_cache(s);
4115 	}
4116 
4117 	mutex_unlock(&slab_mutex);
4118 	cpus_read_unlock();
4119 
4120 	rcu_barrier();
4121 }
4122 
4123 static int slub_cpu_setup(unsigned int cpu)
4124 {
4125 	int nid = cpu_to_node(cpu);
4126 	struct kmem_cache *s;
4127 	int ret = 0;
4128 
4129 	/*
4130 	 * we never clear a nid so it's safe to do a quick check before taking
4131 	 * the mutex, and then recheck to handle parallel cpu hotplug safely
4132 	 */
4133 	if (node_isset(nid, slab_barn_nodes))
4134 		return 0;
4135 
4136 	mutex_lock(&slab_mutex);
4137 
4138 	if (node_isset(nid, slab_barn_nodes))
4139 		goto out;
4140 
4141 	list_for_each_entry(s, &slab_caches, list) {
4142 		struct node_barn *barn;
4143 
4144 		/*
4145 		 * barn might already exist if a previous callback failed midway
4146 		 */
4147 		if (!cache_has_sheaves(s) || get_barn_node(s, nid))
4148 			continue;
4149 
4150 		barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, nid);
4151 
4152 		if (!barn) {
4153 			ret = -ENOMEM;
4154 			goto out;
4155 		}
4156 
4157 		barn_init(barn);
4158 		s->per_node[nid].barn = barn;
4159 	}
4160 	node_set(nid, slab_barn_nodes);
4161 
4162 out:
4163 	mutex_unlock(&slab_mutex);
4164 
4165 	return ret;
4166 }
4167 
4168 /*
4169  * Use the cpu notifier to insure that the cpu slabs are flushed when
4170  * necessary.
4171  */
4172 static int slub_cpu_dead(unsigned int cpu)
4173 {
4174 	struct kmem_cache *s;
4175 
4176 	mutex_lock(&slab_mutex);
4177 	list_for_each_entry(s, &slab_caches, list) {
4178 		if (cache_has_sheaves(s))
4179 			__pcs_flush_all_cpu(s, cpu);
4180 	}
4181 	mutex_unlock(&slab_mutex);
4182 	return 0;
4183 }
4184 
4185 #ifdef CONFIG_SLUB_DEBUG
4186 static int count_free(struct slab *slab)
4187 {
4188 	return slab->objects - slab->inuse;
4189 }
4190 
4191 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
4192 {
4193 	return atomic_long_read(&n->total_objects);
4194 }
4195 
4196 /* Supports checking bulk free of a constructed freelist */
4197 static inline bool free_debug_processing(struct kmem_cache *s,
4198 	struct slab *slab, void *head, void *tail, int *bulk_cnt,
4199 	unsigned long addr, depot_stack_handle_t handle)
4200 {
4201 	bool checks_ok = false;
4202 	void *object = head;
4203 	int cnt = 0;
4204 
4205 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
4206 		if (!check_slab(s, slab))
4207 			goto out;
4208 	}
4209 
4210 	if (slab->inuse < *bulk_cnt) {
4211 		slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
4212 			 slab->inuse, *bulk_cnt);
4213 		goto out;
4214 	}
4215 
4216 next_object:
4217 
4218 	if (++cnt > *bulk_cnt)
4219 		goto out_cnt;
4220 
4221 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
4222 		if (!free_consistency_checks(s, slab, object, addr))
4223 			goto out;
4224 	}
4225 
4226 	if (s->flags & SLAB_STORE_USER)
4227 		set_track_update(s, object, TRACK_FREE, addr, handle);
4228 	trace(s, slab, object, 0);
4229 	/* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
4230 	init_object(s, object, SLUB_RED_INACTIVE);
4231 
4232 	/* Reached end of constructed freelist yet? */
4233 	if (object != tail) {
4234 		object = get_freepointer(s, object);
4235 		goto next_object;
4236 	}
4237 	checks_ok = true;
4238 
4239 out_cnt:
4240 	if (cnt != *bulk_cnt) {
4241 		slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
4242 			 *bulk_cnt, cnt);
4243 		*bulk_cnt = cnt;
4244 	}
4245 
4246 out:
4247 
4248 	if (!checks_ok)
4249 		slab_fix(s, "Object at 0x%p not freed", object);
4250 
4251 	return checks_ok;
4252 }
4253 #endif /* CONFIG_SLUB_DEBUG */
4254 
4255 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
4256 static unsigned long count_partial(struct kmem_cache_node *n,
4257 					int (*get_count)(struct slab *))
4258 {
4259 	unsigned long flags;
4260 	unsigned long x = 0;
4261 	struct slab *slab;
4262 
4263 	spin_lock_irqsave(&n->list_lock, flags);
4264 	list_for_each_entry(slab, &n->partial, slab_list)
4265 		x += get_count(slab);
4266 	spin_unlock_irqrestore(&n->list_lock, flags);
4267 	return x;
4268 }
4269 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
4270 
4271 #ifdef CONFIG_SLUB_DEBUG
4272 #define MAX_PARTIAL_TO_SCAN 10000
4273 
4274 static unsigned long count_partial_free_approx(struct kmem_cache_node *n)
4275 {
4276 	unsigned long flags;
4277 	unsigned long x = 0;
4278 	struct slab *slab;
4279 
4280 	spin_lock_irqsave(&n->list_lock, flags);
4281 	if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
4282 		list_for_each_entry(slab, &n->partial, slab_list)
4283 			x += slab->objects - slab->inuse;
4284 	} else {
4285 		/*
4286 		 * For a long list, approximate the total count of objects in
4287 		 * it to meet the limit on the number of slabs to scan.
4288 		 * Scan from both the list's head and tail for better accuracy.
4289 		 */
4290 		unsigned long scanned = 0;
4291 
4292 		list_for_each_entry(slab, &n->partial, slab_list) {
4293 			x += slab->objects - slab->inuse;
4294 			if (++scanned == MAX_PARTIAL_TO_SCAN / 2)
4295 				break;
4296 		}
4297 		list_for_each_entry_reverse(slab, &n->partial, slab_list) {
4298 			x += slab->objects - slab->inuse;
4299 			if (++scanned == MAX_PARTIAL_TO_SCAN)
4300 				break;
4301 		}
4302 		x = mult_frac(x, n->nr_partial, scanned);
4303 		x = min(x, node_nr_objs(n));
4304 	}
4305 	spin_unlock_irqrestore(&n->list_lock, flags);
4306 	return x;
4307 }
4308 
4309 static noinline void
4310 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
4311 {
4312 	static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
4313 				      DEFAULT_RATELIMIT_BURST);
4314 	int cpu = raw_smp_processor_id();
4315 	int node;
4316 	struct kmem_cache_node *n;
4317 
4318 	if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
4319 		return;
4320 
4321 	pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
4322 		cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
4323 	pr_warn("  cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
4324 		s->name, s->object_size, s->size, oo_order(s->oo),
4325 		oo_order(s->min));
4326 
4327 	if (oo_order(s->min) > get_order(s->object_size))
4328 		pr_warn("  %s debugging increased min order, use slab_debug=O to disable.\n",
4329 			s->name);
4330 
4331 	for_each_kmem_cache_node(s, node, n) {
4332 		unsigned long nr_slabs;
4333 		unsigned long nr_objs;
4334 		unsigned long nr_free;
4335 
4336 		nr_free  = count_partial_free_approx(n);
4337 		nr_slabs = node_nr_slabs(n);
4338 		nr_objs  = node_nr_objs(n);
4339 
4340 		pr_warn("  node %d: slabs: %ld, objs: %ld, free: %ld\n",
4341 			node, nr_slabs, nr_objs, nr_free);
4342 	}
4343 }
4344 #else /* CONFIG_SLUB_DEBUG */
4345 static inline void
4346 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
4347 #endif
4348 
4349 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
4350 {
4351 	if (unlikely(slab_test_pfmemalloc(slab)))
4352 		return gfp_pfmemalloc_allowed(gfpflags);
4353 
4354 	return true;
4355 }
4356 
4357 /*
4358  * Get the slab's freelist and do not freeze it.
4359  *
4360  * Assumes the slab is isolated from node partial list and not frozen.
4361  *
4362  * Assumes this is performed only for caches without debugging so we
4363  * don't need to worry about adding the slab to the full list.
4364  */
4365 static inline void *get_freelist_nofreeze(struct kmem_cache *s, struct slab *slab,
4366 					  unsigned int *count)
4367 {
4368 	struct freelist_counters old, new;
4369 
4370 	do {
4371 		old.freelist = slab->freelist;
4372 		old.counters = slab->counters;
4373 
4374 		new.freelist = NULL;
4375 		new.counters = old.counters;
4376 		VM_WARN_ON_ONCE(new.frozen);
4377 
4378 		new.inuse = old.objects;
4379 
4380 	} while (!slab_update_freelist(s, slab, &old, &new, "get_freelist_nofreeze"));
4381 
4382 	*count = old.objects - old.inuse;
4383 	return old.freelist;
4384 }
4385 
4386 /*
4387  * If the object has been wiped upon free, make sure it's fully initialized by
4388  * zeroing out freelist pointer.
4389  *
4390  * Note that we also wipe custom freelist pointers.
4391  */
4392 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
4393 						   void *obj)
4394 {
4395 	if (unlikely(slab_want_init_on_free(s)) && obj &&
4396 	    !freeptr_outside_object(s))
4397 		memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
4398 			0, sizeof(void *));
4399 }
4400 
4401 static unsigned int alloc_from_new_slab(struct kmem_cache *s, struct slab *slab,
4402 		void **p, unsigned int count, bool allow_spin)
4403 {
4404 	unsigned int allocated = 0;
4405 	struct slab_obj_iter iter;
4406 	bool needs_add_partial = true;
4407 	unsigned long flags;
4408 
4409 	/*
4410 	 * Are we going to put the slab on the partial list?
4411 	 * Note slab->inuse is 0 on a new slab.
4412 	 */
4413 	if (count >= slab->objects) {
4414 		needs_add_partial = false;
4415 		count = slab->objects;
4416 	}
4417 
4418 	init_slab_obj_iter(s, slab, &iter, allow_spin);
4419 
4420 	while (allocated < count) {
4421 		p[allocated] = next_slab_obj(s, &iter);
4422 		allocated++;
4423 	}
4424 	slab->inuse = count;
4425 	build_slab_freelist(s, slab, &iter);
4426 
4427 	if (needs_add_partial) {
4428 		struct kmem_cache_node *n = get_node(s, slab_nid(slab));
4429 
4430 		if (allow_spin) {
4431 			spin_lock_irqsave(&n->list_lock, flags);
4432 		} else if (!spin_trylock_irqsave(&n->list_lock, flags)) {
4433 			/*
4434 			 * Unlucky, discard newly allocated slab.
4435 			 * The slab is not fully free, but it's fine as
4436 			 * objects are not allocated to users.
4437 			 */
4438 			free_new_slab_nolock(s, slab);
4439 			return 0;
4440 		}
4441 		add_partial(n, slab, ADD_TO_HEAD);
4442 		spin_unlock_irqrestore(&n->list_lock, flags);
4443 	}
4444 
4445 	inc_slabs_node(s, slab_nid(slab), slab->objects);
4446 	return allocated;
4447 }
4448 
4449 /*
4450  * Slow path. We failed to allocate via percpu sheaves or they are not available
4451  * due to bootstrap or debugging enabled or SLUB_TINY.
4452  *
4453  * We try to allocate from partial slab lists and fall back to allocating a new
4454  * slab.
4455  */
4456 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
4457 			   const struct slab_alloc_context *ac)
4458 {
4459 	bool allow_spin = alloc_flags_allow_spinning(ac->alloc_flags);
4460 	gfp_t trynode_flags;
4461 	void *object;
4462 	struct slab *slab;
4463 	bool try_thisnode = true;
4464 
4465 	stat(s, ALLOC_SLOWPATH);
4466 
4467 new_objects:
4468 
4469 	trynode_flags = gfpflags;
4470 	/*
4471 	 * When a preferred node is indicated but no __GFP_THISNODE
4472 	 *
4473 	 * 1) try to get a partial slab from target node only by having
4474 	 *    __GFP_THISNODE in trynode_flags for get_from_partial()
4475 	 * 2) if 1) failed, try to allocate a new slab from target node with
4476 	 *    (at most) GFP_NOWAIT | __GFP_THISNODE opportunistically
4477 	 * 3) if 2) failed, retry with original gfpflags which will allow
4478 	 *    get_from_partial() try partial lists of other nodes before
4479 	 *    potentially allocating new page from other nodes
4480 	 */
4481 	if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
4482 		     && try_thisnode)) {
4483 		trynode_flags &= GFP_NOWAIT | __GFP_NOMEMALLOC | __GFP_ACCOUNT;
4484 		trynode_flags |= __GFP_NOWARN | __GFP_THISNODE;
4485 	}
4486 
4487 	object = get_from_partial(s, node, trynode_flags, ac);
4488 	if (object)
4489 		goto success;
4490 
4491 	slab = new_slab(s, trynode_flags, ac->alloc_flags, node);
4492 
4493 	if (unlikely(!slab)) {
4494 		if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
4495 		    && try_thisnode) {
4496 			try_thisnode = false;
4497 			goto new_objects;
4498 		}
4499 		slab_out_of_memory(s, gfpflags, node);
4500 		return NULL;
4501 	}
4502 
4503 	stat(s, ALLOC_SLAB);
4504 
4505 	if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
4506 		object = alloc_single_from_new_slab(s, slab, ac);
4507 
4508 		if (likely(object))
4509 			goto success;
4510 	} else {
4511 		/* we don't need to check SLAB_STORE_USER here */
4512 		if (alloc_from_new_slab(s, slab, &object, 1, allow_spin))
4513 			return object;
4514 	}
4515 
4516 	if (allow_spin)
4517 		goto new_objects;
4518 
4519 	/* This could cause an endless loop. Fail instead. */
4520 	return NULL;
4521 
4522 success:
4523 	if (kmem_cache_debug_flags(s, SLAB_STORE_USER))
4524 		set_track(s, object, TRACK_ALLOC, ac->caller_addr, gfpflags);
4525 
4526 	return object;
4527 }
4528 
4529 static void *__slab_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node,
4530 			       const struct slab_alloc_context *ac)
4531 {
4532 	void *object;
4533 
4534 #ifdef CONFIG_NUMA
4535 	if (static_branch_unlikely(&strict_numa) &&
4536 			node == NUMA_NO_NODE) {
4537 
4538 		struct mempolicy *mpol = current->mempolicy;
4539 
4540 		if (mpol) {
4541 			/*
4542 			 * Special BIND rule support. If the local node
4543 			 * is in permitted set then do not redirect
4544 			 * to a particular node.
4545 			 * Otherwise we apply the memory policy to get
4546 			 * the node we need to allocate on.
4547 			 */
4548 			if (mpol->mode != MPOL_BIND ||
4549 					!node_isset(numa_mem_id(), mpol->nodes))
4550 				node = mempolicy_slab_node();
4551 		}
4552 	}
4553 #endif
4554 
4555 	object = ___slab_alloc(s, gfpflags, node, ac);
4556 
4557 	return object;
4558 }
4559 
4560 static __fastpath_inline
4561 struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
4562 {
4563 	flags &= gfp_allowed_mask;
4564 
4565 	might_alloc(flags);
4566 
4567 	if (unlikely(should_failslab(s, flags)))
4568 		return NULL;
4569 
4570 	return s;
4571 }
4572 
4573 static __fastpath_inline
4574 bool slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags, size_t size,
4575 			  void **p, const struct slab_alloc_context *ac)
4576 {
4577 	bool init = slab_want_init_on_alloc(flags, s);
4578 	unsigned int zero_size = s->object_size;
4579 	gfp_t init_flags = flags & gfp_allowed_mask;
4580 	bool kasan_init = false;
4581 
4582 	/*
4583 	 * For kmalloc object, the allocated size (object_size) can be larger
4584 	 * than the requested size (orig_size). We however need to zero the
4585 	 * whole object_size to handle possible later krealloc() with
4586 	 *__GFP_ZERO properly.
4587 	 *
4588 	 * But if we keep track of the requested size, krealloc() uses that
4589 	 * information. Additionally if red zoning is enabled, the extra space
4590 	 * is also red zone, so we should not overwrite it. So limit zeroing to
4591 	 * orig_size if we track it.
4592 	 */
4593 	if (slub_debug_orig_size(s))
4594 		zero_size = ac->orig_size;
4595 
4596 	/*
4597 	 * ARM64 can set memory tags and zero the memory using a single
4598 	 * instruction. Since HW_TAGS KASAN uses that while tagging the object,
4599 	 * separate zeroing is unnecessary.
4600 	 *
4601 	 * However, KASAN never zeroes memory when slab_debug is enabled to
4602 	 * avoid overwriting SLUB redzones. This does not lead to a performance
4603 	 * penalty on production builds, as slab_debug is not intended to be
4604 	 * enabled there.
4605 	 */
4606 	if (kasan_has_integrated_init() && !__slub_debug_enabled()) {
4607 		kasan_init = init;
4608 		init = false;
4609 	}
4610 
4611 	for (size_t i = 0; i < size; i++) {
4612 		p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init);
4613 
4614 		/*
4615 		 * memset and hooks come after KASAN as p[i] might get tagged
4616 		 *
4617 		 * kfence zeroes the object instead of SLUB to avoid overwriting
4618 		 * its own redzone starting at orig_size, which could happen
4619 		 * with SLUB zeroing full s->object_size
4620 		 */
4621 		if (init && p[i] && !is_kfence_address(p[i]))
4622 			memset(p[i], 0, zero_size);
4623 
4624 		if (alloc_flags_allow_spinning(ac->alloc_flags))
4625 			kmemleak_alloc_recursive(p[i], s->object_size, 1,
4626 						 s->flags, init_flags);
4627 		kmsan_slab_alloc(s, p[i], init_flags);
4628 		alloc_tagging_slab_alloc_hook(s, p[i], flags, ac->alloc_flags);
4629 	}
4630 
4631 	return memcg_slab_post_alloc_hook(s, flags, size, p, ac);
4632 }
4633 
4634 /*
4635  * Replace the empty main sheaf with a (at least partially) full sheaf.
4636  *
4637  * Must be called with the cpu_sheaves local lock locked. If successful, returns
4638  * the pcs pointer and the local lock locked (possibly on a different cpu than
4639  * initially called). If not successful, returns NULL and the local lock
4640  * unlocked.
4641  */
4642 static struct slub_percpu_sheaves *
4643 __pcs_replace_empty_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs,
4644 			 gfp_t gfp, unsigned int alloc_flags)
4645 {
4646 	struct slab_sheaf *empty = NULL;
4647 	struct slab_sheaf *full;
4648 	struct node_barn *barn;
4649 	bool allow_spin;
4650 
4651 	lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
4652 
4653 	/* Bootstrap or debug cache, back off */
4654 	if (unlikely(!cache_has_sheaves(s))) {
4655 		local_unlock(&s->cpu_sheaves->lock);
4656 		return NULL;
4657 	}
4658 
4659 	if (pcs->spare && pcs->spare->size > 0) {
4660 		swap(pcs->main, pcs->spare);
4661 		return pcs;
4662 	}
4663 
4664 	barn = get_barn(s);
4665 	if (!barn) {
4666 		local_unlock(&s->cpu_sheaves->lock);
4667 		return NULL;
4668 	}
4669 
4670 	allow_spin = alloc_flags_allow_spinning(alloc_flags);
4671 
4672 	full = barn_replace_empty_sheaf(barn, pcs->main, allow_spin);
4673 
4674 	if (full) {
4675 		stat(s, BARN_GET);
4676 		pcs->main = full;
4677 		return pcs;
4678 	}
4679 
4680 	stat(s, BARN_GET_FAIL);
4681 
4682 	if (allow_spin) {
4683 		if (pcs->spare) {
4684 			empty = pcs->spare;
4685 			pcs->spare = NULL;
4686 		} else {
4687 			empty = barn_get_empty_sheaf(barn, true);
4688 		}
4689 	}
4690 
4691 	local_unlock(&s->cpu_sheaves->lock);
4692 	pcs = NULL;
4693 
4694 	if (!allow_spin)
4695 		return NULL;
4696 
4697 	if (!empty) {
4698 		empty = alloc_empty_sheaf(s, gfp, alloc_flags);
4699 		if (!empty)
4700 			return NULL;
4701 	}
4702 
4703 	if (refill_sheaf(s, empty, gfp | __GFP_NOMEMALLOC | __GFP_NOWARN)) {
4704 		/*
4705 		 * we must be very low on memory so don't bother
4706 		 * with the barn
4707 		 */
4708 		sheaf_flush_unused(s, empty);
4709 		free_empty_sheaf(s, empty);
4710 
4711 		return NULL;
4712 	}
4713 
4714 	full = empty;
4715 	empty = NULL;
4716 
4717 	if (!local_trylock(&s->cpu_sheaves->lock))
4718 		goto barn_put;
4719 	pcs = this_cpu_ptr(s->cpu_sheaves);
4720 
4721 	/*
4722 	 * If we put any empty or full sheaf to the barn below, it's due to
4723 	 * racing or being migrated to a different cpu. Breaching the barn's
4724 	 * sheaf limits should be thus rare enough so just ignore them to
4725 	 * simplify the recovery.
4726 	 */
4727 
4728 	if (pcs->main->size == 0) {
4729 		if (!pcs->spare)
4730 			pcs->spare = pcs->main;
4731 		else
4732 			barn_put_empty_sheaf(barn, pcs->main);
4733 		pcs->main = full;
4734 		return pcs;
4735 	}
4736 
4737 	if (!pcs->spare) {
4738 		pcs->spare = full;
4739 		return pcs;
4740 	}
4741 
4742 	if (pcs->spare->size == 0) {
4743 		barn_put_empty_sheaf(barn, pcs->spare);
4744 		pcs->spare = full;
4745 		return pcs;
4746 	}
4747 
4748 barn_put:
4749 	barn_put_full_sheaf(barn, full);
4750 	stat(s, BARN_PUT);
4751 
4752 	return pcs;
4753 }
4754 
4755 static __fastpath_inline
4756 void *alloc_from_pcs(struct kmem_cache *s, gfp_t gfp, unsigned int alloc_flags, int node)
4757 {
4758 	struct slub_percpu_sheaves *pcs;
4759 	bool node_requested;
4760 	void *object;
4761 
4762 #ifdef CONFIG_NUMA
4763 	if (static_branch_unlikely(&strict_numa) &&
4764 			 node == NUMA_NO_NODE) {
4765 
4766 		struct mempolicy *mpol = current->mempolicy;
4767 
4768 		if (mpol) {
4769 			/*
4770 			 * Special BIND rule support. If the local node
4771 			 * is in permitted set then do not redirect
4772 			 * to a particular node.
4773 			 * Otherwise we apply the memory policy to get
4774 			 * the node we need to allocate on.
4775 			 */
4776 			if (mpol->mode != MPOL_BIND ||
4777 					!node_isset(numa_mem_id(), mpol->nodes))
4778 
4779 				node = mempolicy_slab_node();
4780 		}
4781 	}
4782 #endif
4783 
4784 	node_requested = IS_ENABLED(CONFIG_NUMA) && node != NUMA_NO_NODE;
4785 
4786 	/*
4787 	 * We assume the percpu sheaves contain only local objects although it's
4788 	 * not completely guaranteed, so we verify later.
4789 	 */
4790 	if (unlikely(node_requested && node != numa_mem_id())) {
4791 		stat(s, ALLOC_NODE_MISMATCH);
4792 		return NULL;
4793 	}
4794 
4795 	if (!local_trylock(&s->cpu_sheaves->lock))
4796 		return NULL;
4797 
4798 	pcs = this_cpu_ptr(s->cpu_sheaves);
4799 
4800 	if (unlikely(pcs->main->size == 0)) {
4801 		pcs = __pcs_replace_empty_main(s, pcs, gfp, alloc_flags);
4802 		if (unlikely(!pcs))
4803 			return NULL;
4804 	}
4805 
4806 	object = pcs->main->objects[pcs->main->size - 1];
4807 
4808 	if (unlikely(node_requested)) {
4809 		/*
4810 		 * Verify that the object was from the node we want. This could
4811 		 * be false because of cpu migration during an unlocked part of
4812 		 * the current allocation or previous freeing process.
4813 		 */
4814 		if (page_to_nid(virt_to_page(object)) != node) {
4815 			local_unlock(&s->cpu_sheaves->lock);
4816 			stat(s, ALLOC_NODE_MISMATCH);
4817 			return NULL;
4818 		}
4819 	}
4820 
4821 	pcs->main->size--;
4822 
4823 	local_unlock(&s->cpu_sheaves->lock);
4824 
4825 	stat(s, ALLOC_FASTPATH);
4826 
4827 	return object;
4828 }
4829 
4830 static __fastpath_inline
4831 unsigned int alloc_from_pcs_bulk(struct kmem_cache *s, size_t size, void **p)
4832 {
4833 	struct slub_percpu_sheaves *pcs;
4834 	struct slab_sheaf *main;
4835 	unsigned int allocated = 0;
4836 	unsigned int batch;
4837 
4838 next_batch:
4839 	if (!local_trylock(&s->cpu_sheaves->lock))
4840 		return allocated;
4841 
4842 	pcs = this_cpu_ptr(s->cpu_sheaves);
4843 
4844 	if (unlikely(pcs->main->size == 0)) {
4845 
4846 		struct slab_sheaf *full;
4847 		struct node_barn *barn;
4848 
4849 		if (unlikely(!cache_has_sheaves(s))) {
4850 			local_unlock(&s->cpu_sheaves->lock);
4851 			return allocated;
4852 		}
4853 
4854 		if (pcs->spare && pcs->spare->size > 0) {
4855 			swap(pcs->main, pcs->spare);
4856 			goto do_alloc;
4857 		}
4858 
4859 		barn = get_barn(s);
4860 		if (!barn) {
4861 			local_unlock(&s->cpu_sheaves->lock);
4862 			return allocated;
4863 		}
4864 
4865 		full = barn_replace_empty_sheaf(barn, pcs->main,
4866 						/* allow_spin = */ true);
4867 
4868 		if (full) {
4869 			stat(s, BARN_GET);
4870 			pcs->main = full;
4871 			goto do_alloc;
4872 		}
4873 
4874 		stat(s, BARN_GET_FAIL);
4875 
4876 		local_unlock(&s->cpu_sheaves->lock);
4877 
4878 		/*
4879 		 * Once full sheaves in barn are depleted, let the bulk
4880 		 * allocation continue from slab pages, otherwise we would just
4881 		 * be copying arrays of pointers twice.
4882 		 */
4883 		return allocated;
4884 	}
4885 
4886 do_alloc:
4887 
4888 	main = pcs->main;
4889 	batch = min(size, main->size);
4890 
4891 	main->size -= batch;
4892 	memcpy(p, main->objects + main->size, batch * sizeof(void *));
4893 
4894 	local_unlock(&s->cpu_sheaves->lock);
4895 
4896 	stat_add(s, ALLOC_FASTPATH, batch);
4897 
4898 	allocated += batch;
4899 
4900 	if (batch < size) {
4901 		p += batch;
4902 		size -= batch;
4903 		goto next_batch;
4904 	}
4905 
4906 	return allocated;
4907 }
4908 
4909 
4910 /*
4911  * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
4912  * have the fastpath folded into their functions. So no function call
4913  * overhead for requests that can be satisfied on the fastpath.
4914  *
4915  * The fastpath works by first checking if the lockless freelist can be used.
4916  * If not then __slab_alloc is called for slow processing.
4917  *
4918  * Otherwise we can simply pick the next object from the lockless free list.
4919  */
4920 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s,
4921 		gfp_t gfpflags, int node, const struct slab_alloc_context *ac)
4922 {
4923 	void *object;
4924 
4925 	s = slab_pre_alloc_hook(s, gfpflags);
4926 	if (unlikely(!s))
4927 		return NULL;
4928 
4929 	object = kfence_alloc(s, ac->orig_size, gfpflags);
4930 	if (unlikely(object))
4931 		goto out;
4932 
4933 	object = alloc_from_pcs(s, gfpflags, ac->alloc_flags, node);
4934 
4935 	if (unlikely(!object))
4936 		object = __slab_alloc_node(s, gfpflags, node, ac);
4937 
4938 	maybe_wipe_obj_freeptr(s, object);
4939 
4940 out:
4941 	/*
4942 	 * In case this fails due to memcg_slab_post_alloc_hook(),
4943 	 * object is set to NULL
4944 	 */
4945 	slab_post_alloc_hook(s, gfpflags, 1, &object, ac);
4946 
4947 	return object;
4948 }
4949 
4950 void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)
4951 {
4952 	void *ret;
4953 	const struct slab_alloc_context ac = {
4954 		.caller_addr = _RET_IP_,
4955 		.orig_size = s->object_size,
4956 		.alloc_flags = SLAB_ALLOC_DEFAULT,
4957 	};
4958 
4959 	ret = slab_alloc_node(s, gfpflags, NUMA_NO_NODE, &ac);
4960 
4961 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4962 
4963 	return ret;
4964 }
4965 EXPORT_SYMBOL(kmem_cache_alloc_noprof);
4966 
4967 void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,
4968 			   gfp_t gfpflags)
4969 {
4970 	void *ret;
4971 	const struct slab_alloc_context ac = {
4972 		.caller_addr = _RET_IP_,
4973 		.orig_size = s->object_size,
4974 		.alloc_flags = SLAB_ALLOC_DEFAULT,
4975 		.lru = lru,
4976 	};
4977 
4978 	ret = slab_alloc_node(s, gfpflags, NUMA_NO_NODE, &ac);
4979 
4980 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4981 
4982 	return ret;
4983 }
4984 EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);
4985 
4986 bool kmem_cache_charge(void *objp, gfp_t gfpflags)
4987 {
4988 	if (!memcg_kmem_online())
4989 		return true;
4990 
4991 	return memcg_slab_post_charge(objp, gfpflags);
4992 }
4993 EXPORT_SYMBOL(kmem_cache_charge);
4994 
4995 /**
4996  * kmem_cache_alloc_node - Allocate an object on the specified node
4997  * @s: The cache to allocate from.
4998  * @gfpflags: See kmalloc().
4999  * @node: node number of the target node.
5000  *
5001  * Identical to kmem_cache_alloc but it will allocate memory on the given
5002  * node, which can improve the performance for cpu bound structures.
5003  *
5004  * Fallback to other node is possible if __GFP_THISNODE is not set.
5005  *
5006  * Return: pointer to the new object or %NULL in case of error
5007  */
5008 void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
5009 {
5010 	void *ret;
5011 	const struct slab_alloc_context ac = {
5012 		.caller_addr = _RET_IP_,
5013 		.orig_size = s->object_size,
5014 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5015 	};
5016 
5017 	ret = slab_alloc_node(s, gfpflags, node, &ac);
5018 
5019 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
5020 
5021 	return ret;
5022 }
5023 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
5024 
5025 static int __prefill_sheaf_pfmemalloc(struct kmem_cache *s,
5026 				      struct slab_sheaf *sheaf, gfp_t gfp)
5027 {
5028 	gfp_t gfp_nomemalloc;
5029 	int ret;
5030 
5031 	gfp_nomemalloc = gfp | __GFP_NOMEMALLOC;
5032 	if (gfp_pfmemalloc_allowed(gfp))
5033 		gfp_nomemalloc |= __GFP_NOWARN;
5034 
5035 	ret = refill_sheaf(s, sheaf, gfp_nomemalloc);
5036 
5037 	if (likely(!ret || !gfp_pfmemalloc_allowed(gfp)))
5038 		return ret;
5039 
5040 	/*
5041 	 * if we are allowed to, refill sheaf with pfmemalloc but then remember
5042 	 * it for when it's returned
5043 	 */
5044 	ret = refill_sheaf(s, sheaf, gfp);
5045 	sheaf->pfmemalloc = true;
5046 
5047 	return ret;
5048 }
5049 
5050 static bool __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
5051 		size_t size, void **p);
5052 
5053 /*
5054  * returns a sheaf that has at least the requested size
5055  * when prefilling is needed, do so with given gfp flags
5056  *
5057  * return NULL if sheaf allocation or prefilling failed
5058  */
5059 struct slab_sheaf *
5060 kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)
5061 {
5062 	struct slub_percpu_sheaves *pcs;
5063 	struct slab_sheaf *sheaf = NULL;
5064 	struct node_barn *barn;
5065 
5066 	if (unlikely(!size))
5067 		return NULL;
5068 
5069 	if (unlikely(size > s->sheaf_capacity)) {
5070 
5071 		sheaf = __alloc_empty_sheaf(s, gfp, SLAB_ALLOC_DEFAULT, size);
5072 		if (!sheaf)
5073 			return NULL;
5074 
5075 		stat(s, SHEAF_PREFILL_OVERSIZE);
5076 		sheaf->capacity = size;
5077 
5078 		/*
5079 		 * we do not need to care about pfmemalloc here because oversize
5080 		 * sheaves are always flushed and freed when returned
5081 		 */
5082 		if (!__kmem_cache_alloc_bulk(s, gfp, size,
5083 					     &sheaf->objects[0])) {
5084 			free_empty_sheaf(s, sheaf);
5085 			return NULL;
5086 		}
5087 
5088 		sheaf->size = size;
5089 
5090 		return sheaf;
5091 	}
5092 
5093 	local_lock(&s->cpu_sheaves->lock);
5094 	pcs = this_cpu_ptr(s->cpu_sheaves);
5095 
5096 	if (pcs->spare) {
5097 		sheaf = pcs->spare;
5098 		pcs->spare = NULL;
5099 		stat(s, SHEAF_PREFILL_FAST);
5100 	} else {
5101 		barn = get_barn(s);
5102 
5103 		stat(s, SHEAF_PREFILL_SLOW);
5104 		if (barn)
5105 			sheaf = barn_get_full_or_empty_sheaf(barn);
5106 		if (sheaf && sheaf->size)
5107 			stat(s, BARN_GET);
5108 		else
5109 			stat(s, BARN_GET_FAIL);
5110 	}
5111 
5112 	local_unlock(&s->cpu_sheaves->lock);
5113 
5114 
5115 	if (!sheaf)
5116 		sheaf = alloc_empty_sheaf(s, gfp, SLAB_ALLOC_DEFAULT);
5117 
5118 	if (sheaf) {
5119 		sheaf->capacity = s->sheaf_capacity;
5120 		sheaf->pfmemalloc = false;
5121 
5122 		if (sheaf->size < size &&
5123 		    __prefill_sheaf_pfmemalloc(s, sheaf, gfp)) {
5124 			sheaf_flush_unused(s, sheaf);
5125 			free_empty_sheaf(s, sheaf);
5126 			sheaf = NULL;
5127 		}
5128 	}
5129 
5130 	return sheaf;
5131 }
5132 
5133 /*
5134  * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()
5135  *
5136  * If the sheaf cannot simply become the percpu spare sheaf, but there's space
5137  * for a full sheaf in the barn, we try to refill the sheaf back to the cache's
5138  * sheaf_capacity to avoid handling partially full sheaves.
5139  *
5140  * If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full, the
5141  * sheaf is instead flushed and freed.
5142  */
5143 void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,
5144 			     struct slab_sheaf *sheaf)
5145 {
5146 	struct slub_percpu_sheaves *pcs;
5147 	struct node_barn *barn;
5148 
5149 	if (unlikely((sheaf->capacity != s->sheaf_capacity)
5150 		     || sheaf->pfmemalloc)) {
5151 		sheaf_flush_unused(s, sheaf);
5152 		free_empty_sheaf(s, sheaf);
5153 		return;
5154 	}
5155 
5156 	local_lock(&s->cpu_sheaves->lock);
5157 	pcs = this_cpu_ptr(s->cpu_sheaves);
5158 	barn = get_barn(s);
5159 
5160 	if (!pcs->spare) {
5161 		pcs->spare = sheaf;
5162 		sheaf = NULL;
5163 		stat(s, SHEAF_RETURN_FAST);
5164 	}
5165 
5166 	local_unlock(&s->cpu_sheaves->lock);
5167 
5168 	if (!sheaf)
5169 		return;
5170 
5171 	stat(s, SHEAF_RETURN_SLOW);
5172 
5173 	/*
5174 	 * If the barn has too many full sheaves or we fail to refill the sheaf,
5175 	 * simply flush and free it.
5176 	 */
5177 	if (!barn || data_race(barn->nr_full) >= MAX_FULL_SHEAVES ||
5178 	    refill_sheaf(s, sheaf, gfp)) {
5179 		sheaf_flush_unused(s, sheaf);
5180 		free_empty_sheaf(s, sheaf);
5181 		return;
5182 	}
5183 
5184 	barn_put_full_sheaf(barn, sheaf);
5185 	stat(s, BARN_PUT);
5186 }
5187 
5188 /*
5189  * Refill a sheaf previously returned by kmem_cache_prefill_sheaf to at least
5190  * the given size.
5191  *
5192  * Return: 0 on success. The sheaf will contain at least @size objects.
5193  * The sheaf might have been replaced with a new one if more than
5194  * sheaf->capacity objects are requested.
5195  *
5196  * Return: -ENOMEM on failure. Some objects might have been added to the sheaf
5197  * but the sheaf will not be replaced.
5198  *
5199  * In practice we always refill to full sheaf's capacity.
5200  */
5201 int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,
5202 			    struct slab_sheaf **sheafp, unsigned int size)
5203 {
5204 	struct slab_sheaf *sheaf;
5205 
5206 	/*
5207 	 * TODO: do we want to support *sheaf == NULL to be equivalent of
5208 	 * kmem_cache_prefill_sheaf() ?
5209 	 */
5210 	if (!sheafp || !(*sheafp))
5211 		return -EINVAL;
5212 
5213 	sheaf = *sheafp;
5214 	if (sheaf->size >= size)
5215 		return 0;
5216 
5217 	if (likely(sheaf->capacity >= size)) {
5218 		if (likely(sheaf->capacity == s->sheaf_capacity))
5219 			return __prefill_sheaf_pfmemalloc(s, sheaf, gfp);
5220 
5221 		if (!__kmem_cache_alloc_bulk(s, gfp, sheaf->capacity - sheaf->size,
5222 					     &sheaf->objects[sheaf->size]))
5223 			return -ENOMEM;
5224 		sheaf->size = sheaf->capacity;
5225 
5226 		return 0;
5227 	}
5228 
5229 	/*
5230 	 * We had a regular sized sheaf and need an oversize one, or we had an
5231 	 * oversize one already but need a larger one now.
5232 	 * This should be a very rare path so let's not complicate it.
5233 	 */
5234 	sheaf = kmem_cache_prefill_sheaf(s, gfp, size);
5235 	if (!sheaf)
5236 		return -ENOMEM;
5237 
5238 	kmem_cache_return_sheaf(s, gfp, *sheafp);
5239 	*sheafp = sheaf;
5240 	return 0;
5241 }
5242 
5243 /*
5244  * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()
5245  *
5246  * Guaranteed not to fail as many allocations as was the requested size.
5247  * After the sheaf is emptied, it fails - no fallback to the slab cache itself.
5248  *
5249  * The gfp parameter is meant only to specify __GFP_ZERO or __GFP_ACCOUNT
5250  * memcg charging is forced over limit if necessary, to avoid failure.
5251  *
5252  * It is possible that the allocation comes from kfence and then the sheaf
5253  * size is not decreased.
5254  */
5255 void *
5256 kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,
5257 				   struct slab_sheaf *sheaf)
5258 {
5259 	void *ret = NULL;
5260 	const struct slab_alloc_context ac = {
5261 		.orig_size = s->object_size,
5262 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5263 	};
5264 
5265 	if (sheaf->size == 0)
5266 		goto out;
5267 
5268 	ret = kfence_alloc(s, s->object_size, gfp);
5269 
5270 	if (likely(!ret))
5271 		ret = sheaf->objects[--sheaf->size];
5272 
5273 	/* add __GFP_NOFAIL to force successful memcg charging */
5274 	slab_post_alloc_hook(s, gfp | __GFP_NOFAIL, 1, &ret, &ac);
5275 out:
5276 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfp, NUMA_NO_NODE);
5277 
5278 	return ret;
5279 }
5280 
5281 unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)
5282 {
5283 	return sheaf->size;
5284 }
5285 /*
5286  * To avoid unnecessary overhead, we pass through large allocation requests
5287  * directly to the page allocator. We use __GFP_COMP, because we will need to
5288  * know the allocation order to free the pages properly in kfree.
5289  */
5290 static void *___kmalloc_large_node(size_t size, gfp_t flags, int node)
5291 {
5292 	struct page *page;
5293 	void *ptr = NULL;
5294 	unsigned int order = get_order(size);
5295 
5296 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
5297 		flags = kmalloc_fix_flags(flags);
5298 
5299 	flags |= __GFP_COMP;
5300 
5301 	if (node == NUMA_NO_NODE)
5302 		page = alloc_frozen_pages_noprof(flags, order);
5303 	else
5304 		page = __alloc_frozen_pages_noprof(flags, order, node, NULL);
5305 
5306 	if (page) {
5307 		ptr = page_address(page);
5308 		mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
5309 				      PAGE_SIZE << order);
5310 		__SetPageLargeKmalloc(page);
5311 	}
5312 
5313 	ptr = kasan_kmalloc_large(ptr, size, flags);
5314 	/* As ptr might get tagged, call kmemleak hook after KASAN. */
5315 	kmemleak_alloc(ptr, size, 1, flags);
5316 	kmsan_kmalloc_large(ptr, size, flags);
5317 
5318 	return ptr;
5319 }
5320 
5321 void *__kmalloc_large_noprof(size_t size, gfp_t flags)
5322 {
5323 	void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE);
5324 
5325 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
5326 		      flags, NUMA_NO_NODE);
5327 	return ret;
5328 }
5329 EXPORT_SYMBOL(__kmalloc_large_noprof);
5330 
5331 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
5332 {
5333 	void *ret = ___kmalloc_large_node(size, flags, node);
5334 
5335 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
5336 		      flags, node);
5337 	return ret;
5338 }
5339 EXPORT_SYMBOL(__kmalloc_large_node_noprof);
5340 
5341 static __always_inline
5342 void *__do_kmalloc_node(kmem_buckets *b, gfp_t flags, int node,
5343 			kmalloc_token_t token, const struct slab_alloc_context *ac)
5344 {
5345 	const size_t size = ac->orig_size;
5346 	struct kmem_cache *s;
5347 	void *ret;
5348 
5349 	if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
5350 		ret = __kmalloc_large_node_noprof(size, flags, node);
5351 		trace_kmalloc(ac->caller_addr, ret, size,
5352 			      PAGE_SIZE << get_order(size), flags, node);
5353 		return ret;
5354 	}
5355 
5356 	if (unlikely(!size))
5357 		return ZERO_SIZE_PTR;
5358 
5359 	s = kmalloc_slab(size, b, flags, token);
5360 
5361 	ret = slab_alloc_node(s, flags, node, ac);
5362 	ret = kasan_kmalloc(s, ret, size, flags);
5363 	trace_kmalloc(ac->caller_addr, ret, size, s->size, flags, node);
5364 	return ret;
5365 }
5366 void *__kmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags, int node)
5367 {
5368 	const struct slab_alloc_context ac = {
5369 		.caller_addr = _RET_IP_,
5370 		.orig_size = size,
5371 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5372 	};
5373 
5374 	return __do_kmalloc_node(PASS_BUCKET_PARAM(b), flags, node,
5375 				 PASS_TOKEN_PARAM(token), &ac);
5376 }
5377 EXPORT_SYMBOL(__kmalloc_node_noprof);
5378 
5379 void *__kmalloc_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags)
5380 {
5381 	const struct slab_alloc_context ac = {
5382 		.caller_addr = _RET_IP_,
5383 		.orig_size = size,
5384 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5385 	};
5386 
5387 	return __do_kmalloc_node(NULL, flags,  NUMA_NO_NODE,
5388 				 PASS_TOKEN_PARAM(token), &ac);
5389 }
5390 EXPORT_SYMBOL(__kmalloc_noprof);
5391 
5392 static void *__kmalloc_nolock_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t gfp_flags,
5393 				     int node, const struct slab_alloc_context *ac)
5394 {
5395 	struct kmem_cache *s;
5396 	bool can_retry = true;
5397 	void *ret;
5398 
5399 	VM_WARN_ON_ONCE(alloc_flags_allow_spinning(ac->alloc_flags));
5400 	VM_WARN_ON_ONCE(gfp_flags & ~(__GFP_ACCOUNT | __GFP_ZERO |
5401 				      __GFP_NOWARN | __GFP_NOMEMALLOC));
5402 
5403 	gfp_flags |= __GFP_NOWARN | __GFP_NOMEMALLOC;
5404 
5405 	if (unlikely(!size))
5406 		return ZERO_SIZE_PTR;
5407 
5408 	/*
5409 	 * See the comment for the same check in
5410 	 * alloc_frozen_pages_nolock_noprof()
5411 	 */
5412 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
5413 		return NULL;
5414 
5415 	/* On UP, spin_trylock() always succeeds even when it is locked */
5416 	if (!IS_ENABLED(CONFIG_SMP) && in_nmi())
5417 		return NULL;
5418 
5419 retry:
5420 	if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
5421 		return NULL;
5422 	s = kmalloc_slab(size, NULL, gfp_flags, PASS_TOKEN_PARAM(token));
5423 
5424 	if (!(s->flags & __CMPXCHG_DOUBLE) && !kmem_cache_debug(s))
5425 		/*
5426 		 * kmalloc_nolock() is not supported on architectures that
5427 		 * don't implement cmpxchg16b and thus need slab_lock()
5428 		 * which could be preempted by a nmi.
5429 		 * But debug caches don't use that and only rely on
5430 		 * kmem_cache_node->list_lock, so kmalloc_nolock() can attempt
5431 		 * to allocate from debug caches by
5432 		 * spin_trylock_irqsave(&n->list_lock, ...)
5433 		 */
5434 		return NULL;
5435 
5436 	ret = alloc_from_pcs(s, gfp_flags, ac->alloc_flags, node);
5437 	if (ret)
5438 		goto success;
5439 
5440 	/*
5441 	 * Do not call slab_alloc_node(), since trylock mode isn't
5442 	 * compatible with slab_pre_alloc_hook/should_failslab and
5443 	 * kfence_alloc. Hence call __slab_alloc_node() (at most twice)
5444 	 * and slab_post_alloc_hook() directly.
5445 	 */
5446 	ret = __slab_alloc_node(s, gfp_flags, node, ac);
5447 
5448 	/*
5449 	 * It's possible we failed due to trylock as we preempted someone with
5450 	 * the sheaves locked, and the list_lock is also held by another cpu.
5451 	 * But it should be rare that multiple kmalloc buckets would have
5452 	 * sheaves locked, so try a larger one.
5453 	 */
5454 	if (!ret && can_retry) {
5455 		/* pick the next kmalloc bucket */
5456 		size = s->object_size + 1;
5457 		/*
5458 		 * Another alternative is to
5459 		 * if (memcg) gfp_flags &= ~__GFP_ACCOUNT;
5460 		 * else if (!memcg) gfp_flags |= __GFP_ACCOUNT;
5461 		 * to retry from bucket of the same size.
5462 		 */
5463 		can_retry = false;
5464 		goto retry;
5465 	}
5466 
5467 success:
5468 	maybe_wipe_obj_freeptr(s, ret);
5469 	slab_post_alloc_hook(s, gfp_flags, 1, &ret, ac);
5470 
5471 	ret = kasan_kmalloc(s, ret, ac->orig_size, gfp_flags);
5472 	return ret;
5473 }
5474 
5475 void *_kmalloc_nolock_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t gfp_flags, int node)
5476 {
5477 	const struct slab_alloc_context ac = {
5478 		.caller_addr = _RET_IP_,
5479 		.orig_size = size,
5480 		.alloc_flags = SLAB_ALLOC_NOLOCK,
5481 	};
5482 
5483 	return __kmalloc_nolock_noprof(PASS_TOKEN_PARAMS(size, token),
5484 				       gfp_flags, node, &ac);
5485 }
5486 EXPORT_SYMBOL_GPL(_kmalloc_nolock_noprof);
5487 
5488 void *__kmalloc_node_track_caller_noprof(DECL_KMALLOC_PARAMS(size, b, token), gfp_t flags,
5489 					 int node, unsigned long caller)
5490 {
5491 	const struct slab_alloc_context ac = {
5492 		.caller_addr = caller,
5493 		.orig_size = size,
5494 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5495 	};
5496 
5497 	return __do_kmalloc_node(PASS_BUCKET_PARAM(b), flags, node,
5498 				 PASS_TOKEN_PARAM(token), &ac);
5499 }
5500 EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof);
5501 
5502 void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size)
5503 {
5504 	void *ret;
5505 	const struct slab_alloc_context ac = {
5506 		.caller_addr = _RET_IP_,
5507 		.orig_size = size,
5508 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5509 	};
5510 
5511 	ret = slab_alloc_node(s, gfpflags, NUMA_NO_NODE, &ac);
5512 
5513 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
5514 
5515 	ret = kasan_kmalloc(s, ret, size, gfpflags);
5516 	return ret;
5517 }
5518 EXPORT_SYMBOL(__kmalloc_cache_noprof);
5519 
5520 void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags,
5521 				  int node, size_t size)
5522 {
5523 	void *ret;
5524 	const struct slab_alloc_context ac = {
5525 		.caller_addr = _RET_IP_,
5526 		.orig_size = size,
5527 		.alloc_flags = SLAB_ALLOC_DEFAULT,
5528 	};
5529 
5530 	ret = slab_alloc_node(s, gfpflags, node, &ac);
5531 
5532 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
5533 
5534 	ret = kasan_kmalloc(s, ret, size, gfpflags);
5535 	return ret;
5536 }
5537 EXPORT_SYMBOL(__kmalloc_cache_node_noprof);
5538 
5539 /*
5540  * The only version of kmalloc_node() that takes alloc_flags and thus can
5541  * determine on its own whether to handle the allocation via kmalloc_nolock() or
5542  * normally
5543  */
5544 void *__kmalloc_flags_noprof(DECL_TOKEN_PARAMS(size, token), gfp_t flags,
5545 			     unsigned int alloc_flags, int node)
5546 {
5547 	const struct slab_alloc_context ac = {
5548 		.caller_addr = _RET_IP_,
5549 		.orig_size = size,
5550 		.alloc_flags = alloc_flags,
5551 	};
5552 
5553 	if (alloc_flags_allow_spinning(alloc_flags)) {
5554 		return __do_kmalloc_node(NULL, flags, node,
5555 				PASS_TOKEN_PARAM(token), &ac);
5556 	} else {
5557 		return __kmalloc_nolock_noprof(PASS_TOKEN_PARAMS(size, token),
5558 					       flags, node, &ac);
5559 	}
5560 }
5561 
5562 
5563 static noinline void free_to_partial_list(
5564 	struct kmem_cache *s, struct slab *slab,
5565 	void *head, void *tail, int bulk_cnt,
5566 	unsigned long addr)
5567 {
5568 	struct kmem_cache_node *n = get_node(s, slab_nid(slab));
5569 	struct slab *slab_free = NULL;
5570 	int cnt = bulk_cnt;
5571 	unsigned long flags;
5572 	depot_stack_handle_t handle = 0;
5573 
5574 	/*
5575 	 * We cannot use GFP_NOWAIT as there are callsites where waking up
5576 	 * kswapd could deadlock
5577 	 */
5578 	if (s->flags & SLAB_STORE_USER)
5579 		handle = set_track_prepare(__GFP_NOWARN);
5580 
5581 	spin_lock_irqsave(&n->list_lock, flags);
5582 
5583 	if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
5584 		void *prior = slab->freelist;
5585 
5586 		/* Perform the actual freeing while we still hold the locks */
5587 		slab->inuse -= cnt;
5588 		set_freepointer(s, tail, prior);
5589 		slab->freelist = head;
5590 
5591 		/*
5592 		 * If the slab is empty, and node's partial list is full,
5593 		 * it should be discarded anyway no matter it's on full or
5594 		 * partial list.
5595 		 */
5596 		if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
5597 			slab_free = slab;
5598 
5599 		if (!prior) {
5600 			/* was on full list */
5601 			remove_full(s, n, slab);
5602 			if (!slab_free) {
5603 				add_partial(n, slab, ADD_TO_TAIL);
5604 				stat(s, FREE_ADD_PARTIAL);
5605 			}
5606 		} else if (slab_free) {
5607 			remove_partial(n, slab);
5608 			stat(s, FREE_REMOVE_PARTIAL);
5609 		}
5610 	}
5611 
5612 	if (slab_free) {
5613 		/*
5614 		 * Update the counters while still holding n->list_lock to
5615 		 * prevent spurious validation warnings
5616 		 */
5617 		dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
5618 	}
5619 
5620 	spin_unlock_irqrestore(&n->list_lock, flags);
5621 
5622 	if (slab_free) {
5623 		stat(s, FREE_SLAB);
5624 		free_slab(s, slab_free);
5625 	}
5626 }
5627 
5628 /*
5629  * Try returning (remainder of) the freelist that we just detached from the
5630  * slab.  Optimistically assume the slab is still full, so we don't need to find
5631  * the tail of the detached freelist.
5632  *
5633  * Fail if the slab isn't full anymore due to a concurrent free.
5634  */
5635 static bool __slab_try_return_freelist(struct kmem_cache *s, struct slab *slab,
5636 				       void *head, int cnt)
5637 {
5638 	struct freelist_counters old, new;
5639 
5640 	old.freelist = slab->freelist;
5641 	old.counters = slab->counters;
5642 
5643 	if (old.freelist)
5644 		return false;
5645 
5646 	new.freelist = head;
5647 	new.counters = old.counters;
5648 	new.inuse -= cnt;
5649 
5650 	if (!slab_update_freelist(s, slab, &old, &new, "__slab_try_return_freelist"))
5651 		return false;
5652 
5653 	return true;
5654 }
5655 
5656 /*
5657  * Slow path handling. This may still be called frequently since objects
5658  * have a longer lifetime than the cpu slabs in most processing loads.
5659  *
5660  * So we still attempt to reduce cache line usage. Just take the slab
5661  * lock and free the item. If there is no additional partial slab
5662  * handling required then we can return immediately.
5663  */
5664 static void __slab_free(struct kmem_cache *s, struct slab *slab,
5665 			void *head, void *tail, int cnt,
5666 			unsigned long addr)
5667 
5668 {
5669 	bool was_full;
5670 	struct freelist_counters old, new;
5671 	struct kmem_cache_node *n = NULL;
5672 	unsigned long flags;
5673 	bool on_node_partial;
5674 
5675 	if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
5676 		free_to_partial_list(s, slab, head, tail, cnt, addr);
5677 		return;
5678 	}
5679 
5680 	do {
5681 		if (unlikely(n)) {
5682 			spin_unlock_irqrestore(&n->list_lock, flags);
5683 			n = NULL;
5684 		}
5685 
5686 		old.freelist = slab->freelist;
5687 		old.counters = slab->counters;
5688 
5689 		was_full = (old.freelist == NULL);
5690 
5691 		set_freepointer(s, tail, old.freelist);
5692 
5693 		new.freelist = head;
5694 		new.counters = old.counters;
5695 		new.inuse -= cnt;
5696 
5697 		/*
5698 		 * Might need to be taken off (due to becoming empty) or added
5699 		 * to (due to not being full anymore) the partial list.
5700 		 * Unless it's frozen.
5701 		 */
5702 		if (!new.inuse || was_full) {
5703 
5704 			n = get_node(s, slab_nid(slab));
5705 			/*
5706 			 * Speculatively acquire the list_lock.
5707 			 * If the cmpxchg does not succeed then we may
5708 			 * drop the list_lock without any processing.
5709 			 *
5710 			 * Otherwise the list_lock will synchronize with
5711 			 * other processors updating the list of slabs.
5712 			 */
5713 			spin_lock_irqsave(&n->list_lock, flags);
5714 
5715 			on_node_partial = slab_test_node_partial(slab);
5716 		}
5717 
5718 	} while (!slab_update_freelist(s, slab, &old, &new, "__slab_free"));
5719 
5720 	if (likely(!n)) {
5721 		/*
5722 		 * We didn't take the list_lock because the slab was already on
5723 		 * the partial list and will remain there.
5724 		 */
5725 		return;
5726 	}
5727 
5728 	/*
5729 	 * This slab was partially empty but not on the per-node partial list,
5730 	 * in which case we shouldn't manipulate its list, just return.
5731 	 */
5732 	if (!was_full && !on_node_partial) {
5733 		spin_unlock_irqrestore(&n->list_lock, flags);
5734 		return;
5735 	}
5736 
5737 	/*
5738 	 * If slab became empty, should we add/keep it on the partial list or we
5739 	 * have enough?
5740 	 */
5741 	if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
5742 		goto slab_empty;
5743 
5744 	/*
5745 	 * Objects left in the slab. If it was not on the partial list before
5746 	 * then add it.
5747 	 */
5748 	if (unlikely(was_full)) {
5749 		add_partial(n, slab, ADD_TO_TAIL);
5750 		stat(s, FREE_ADD_PARTIAL);
5751 	}
5752 	spin_unlock_irqrestore(&n->list_lock, flags);
5753 	return;
5754 
5755 slab_empty:
5756 	/*
5757 	 * The slab could have a single object and thus go from full to empty in
5758 	 * a single free, but more likely it was on the partial list. Remove it.
5759 	 */
5760 	if (likely(!was_full)) {
5761 		remove_partial(n, slab);
5762 		stat(s, FREE_REMOVE_PARTIAL);
5763 	}
5764 
5765 	spin_unlock_irqrestore(&n->list_lock, flags);
5766 	stat(s, FREE_SLAB);
5767 	discard_slab(s, slab);
5768 }
5769 
5770 /*
5771  * pcs is locked. We should have get rid of the spare sheaf and obtained an
5772  * empty sheaf, while the main sheaf is full. We want to install the empty sheaf
5773  * as a main sheaf, and make the current main sheaf a spare sheaf.
5774  *
5775  * However due to having relinquished the cpu_sheaves lock when obtaining
5776  * the empty sheaf, we need to handle some unlikely but possible cases.
5777  *
5778  * If we put any sheaf to barn here, it's because we were interrupted or have
5779  * been migrated to a different cpu, which should be rare enough so just ignore
5780  * the barn's limits to simplify the handling.
5781  *
5782  * An alternative scenario that gets us here is when we fail
5783  * barn_replace_full_sheaf(), because there's no empty sheaf available in the
5784  * barn, so we had to allocate it by alloc_empty_sheaf(). But because we saw the
5785  * limit on full sheaves was not exceeded, we assume it didn't change and just
5786  * put the full sheaf there.
5787  */
5788 static void __pcs_install_empty_sheaf(struct kmem_cache *s,
5789 		struct slub_percpu_sheaves *pcs, struct slab_sheaf *empty,
5790 		struct node_barn *barn)
5791 {
5792 	lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
5793 
5794 	/* This is what we expect to find if nobody interrupted us. */
5795 	if (likely(!pcs->spare)) {
5796 		pcs->spare = pcs->main;
5797 		pcs->main = empty;
5798 		return;
5799 	}
5800 
5801 	/*
5802 	 * Unlikely because if the main sheaf had space, we would have just
5803 	 * freed to it. Get rid of our empty sheaf.
5804 	 */
5805 	if (pcs->main->size < s->sheaf_capacity) {
5806 		barn_put_empty_sheaf(barn, empty);
5807 		return;
5808 	}
5809 
5810 	/* Also unlikely for the same reason */
5811 	if (pcs->spare->size < s->sheaf_capacity) {
5812 		swap(pcs->main, pcs->spare);
5813 		barn_put_empty_sheaf(barn, empty);
5814 		return;
5815 	}
5816 
5817 	/*
5818 	 * We probably failed barn_replace_full_sheaf() due to no empty sheaf
5819 	 * available there, but we allocated one, so finish the job.
5820 	 */
5821 	barn_put_full_sheaf(barn, pcs->main);
5822 	stat(s, BARN_PUT);
5823 	pcs->main = empty;
5824 }
5825 
5826 /*
5827  * Replace the full main sheaf with a (at least partially) empty sheaf.
5828  *
5829  * Must be called with the cpu_sheaves local lock locked. If successful, returns
5830  * the pcs pointer and the local lock locked (possibly on a different cpu than
5831  * initially called). If not successful, returns NULL and the local lock
5832  * unlocked.
5833  */
5834 static struct slub_percpu_sheaves *
5835 __pcs_replace_full_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs,
5836 			bool allow_spin)
5837 {
5838 	struct slab_sheaf *empty;
5839 	struct node_barn *barn;
5840 	bool put_fail;
5841 
5842 restart:
5843 	lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
5844 
5845 	/* Bootstrap or debug cache, back off */
5846 	if (unlikely(!cache_has_sheaves(s))) {
5847 		local_unlock(&s->cpu_sheaves->lock);
5848 		return NULL;
5849 	}
5850 
5851 	barn = get_barn(s);
5852 	if (!barn) {
5853 		local_unlock(&s->cpu_sheaves->lock);
5854 		return NULL;
5855 	}
5856 
5857 	put_fail = false;
5858 
5859 	if (!pcs->spare) {
5860 		empty = barn_get_empty_sheaf(barn, allow_spin);
5861 		if (empty) {
5862 			pcs->spare = pcs->main;
5863 			pcs->main = empty;
5864 			return pcs;
5865 		}
5866 		goto alloc_empty;
5867 	}
5868 
5869 	if (pcs->spare->size < s->sheaf_capacity) {
5870 		swap(pcs->main, pcs->spare);
5871 		return pcs;
5872 	}
5873 
5874 	empty = barn_replace_full_sheaf(barn, pcs->main, allow_spin);
5875 
5876 	if (!IS_ERR(empty)) {
5877 		stat(s, BARN_PUT);
5878 		pcs->main = empty;
5879 		return pcs;
5880 	}
5881 
5882 	/* sheaf_flush_unused() doesn't support !allow_spin */
5883 	if (PTR_ERR(empty) == -E2BIG && allow_spin) {
5884 		/* Since we got here, spare exists and is full */
5885 		struct slab_sheaf *to_flush = pcs->spare;
5886 
5887 		stat(s, BARN_PUT_FAIL);
5888 
5889 		pcs->spare = NULL;
5890 		local_unlock(&s->cpu_sheaves->lock);
5891 
5892 		sheaf_flush_unused(s, to_flush);
5893 		empty = to_flush;
5894 		goto got_empty;
5895 	}
5896 
5897 	/*
5898 	 * We could not replace full sheaf because barn had no empty
5899 	 * sheaves. We can still allocate it and put the full sheaf in
5900 	 * __pcs_install_empty_sheaf(), but if we fail to allocate it,
5901 	 * make sure to count the fail.
5902 	 */
5903 	put_fail = true;
5904 
5905 alloc_empty:
5906 	local_unlock(&s->cpu_sheaves->lock);
5907 
5908 	/*
5909 	 * alloc_empty_sheaf() doesn't support !allow_spin and it's
5910 	 * easier to fall back to freeing directly without sheaves
5911 	 * than add the support (and to sheaf_flush_unused() above)
5912 	 */
5913 	if (!allow_spin)
5914 		return NULL;
5915 
5916 	empty = alloc_empty_sheaf(s, GFP_NOWAIT, SLAB_ALLOC_DEFAULT);
5917 	if (empty)
5918 		goto got_empty;
5919 
5920 	if (put_fail)
5921 		 stat(s, BARN_PUT_FAIL);
5922 
5923 	if (!sheaf_try_flush_main(s))
5924 		return NULL;
5925 
5926 	if (!local_trylock(&s->cpu_sheaves->lock))
5927 		return NULL;
5928 
5929 	pcs = this_cpu_ptr(s->cpu_sheaves);
5930 
5931 	/*
5932 	 * we flushed the main sheaf so it should be empty now,
5933 	 * but in case we got preempted or migrated, we need to
5934 	 * check again
5935 	 */
5936 	if (pcs->main->size == s->sheaf_capacity)
5937 		goto restart;
5938 
5939 	return pcs;
5940 
5941 got_empty:
5942 	if (!local_trylock(&s->cpu_sheaves->lock)) {
5943 		barn_put_empty_sheaf(barn, empty);
5944 		return NULL;
5945 	}
5946 
5947 	pcs = this_cpu_ptr(s->cpu_sheaves);
5948 	__pcs_install_empty_sheaf(s, pcs, empty, barn);
5949 
5950 	return pcs;
5951 }
5952 
5953 /*
5954  * Free an object to the percpu sheaves.
5955  * The object is expected to have passed slab_free_hook() already.
5956  */
5957 static __fastpath_inline
5958 bool free_to_pcs(struct kmem_cache *s, void *object, bool allow_spin)
5959 {
5960 	struct slub_percpu_sheaves *pcs;
5961 
5962 	if (!local_trylock(&s->cpu_sheaves->lock))
5963 		return false;
5964 
5965 	pcs = this_cpu_ptr(s->cpu_sheaves);
5966 
5967 	if (unlikely(pcs->main->size == s->sheaf_capacity)) {
5968 
5969 		pcs = __pcs_replace_full_main(s, pcs, allow_spin);
5970 		if (unlikely(!pcs))
5971 			return false;
5972 	}
5973 
5974 	pcs->main->objects[pcs->main->size++] = object;
5975 
5976 	local_unlock(&s->cpu_sheaves->lock);
5977 
5978 	stat(s, FREE_FASTPATH);
5979 
5980 	return true;
5981 }
5982 
5983 static void rcu_free_sheaf(struct rcu_head *head)
5984 {
5985 	struct slab_sheaf *sheaf;
5986 	struct node_barn *barn = NULL;
5987 	struct kmem_cache *s;
5988 
5989 	sheaf = container_of(head, struct slab_sheaf, rcu_head);
5990 
5991 	s = sheaf->cache;
5992 
5993 	/*
5994 	 * This may remove some objects due to slab_free_hook() returning false,
5995 	 * so that the sheaf might no longer be completely full. But it's easier
5996 	 * to handle it as full (unless it became completely empty), as the code
5997 	 * handles it fine. The only downside is that sheaf will serve fewer
5998 	 * allocations when reused. It only happens due to debugging, which is a
5999 	 * performance hit anyway.
6000 	 *
6001 	 * If it returns true, there was at least one object from pfmemalloc
6002 	 * slab so simply flush everything.
6003 	 */
6004 	if (__rcu_free_sheaf_prepare(s, sheaf))
6005 		goto flush;
6006 
6007 	barn = get_barn_node(s, sheaf->node);
6008 	if (!barn)
6009 		goto flush;
6010 
6011 	/* due to slab_free_hook() */
6012 	if (unlikely(sheaf->size == 0))
6013 		goto empty;
6014 
6015 	/*
6016 	 * Checking nr_full/nr_empty outside lock avoids contention in case the
6017 	 * barn is at the respective limit. Due to the race we might go over the
6018 	 * limit but that should be rare and harmless.
6019 	 */
6020 
6021 	if (data_race(barn->nr_full) < MAX_FULL_SHEAVES) {
6022 		stat(s, BARN_PUT);
6023 		barn_put_full_sheaf(barn, sheaf);
6024 		return;
6025 	}
6026 
6027 flush:
6028 	stat(s, BARN_PUT_FAIL);
6029 	sheaf_flush_unused(s, sheaf);
6030 
6031 empty:
6032 	if (barn && data_race(barn->nr_empty) < MAX_EMPTY_SHEAVES) {
6033 		barn_put_empty_sheaf(barn, sheaf);
6034 		return;
6035 	}
6036 
6037 	free_empty_sheaf(s, sheaf);
6038 }
6039 
6040 /*
6041  * kvfree_call_rcu() can be called while holding a raw_spinlock_t. Since
6042  * __kfree_rcu_sheaf() may acquire a spinlock_t (sleeping lock on PREEMPT_RT),
6043  * this would violate lock nesting rules. Therefore, kvfree_call_rcu() avoids
6044  * this problem by bypassing the sheaves layer entirely on PREEMPT_RT.
6045  *
6046  * However, lockdep still complains that it is invalid to acquire spinlock_t
6047  * while holding raw_spinlock_t, even on !PREEMPT_RT where spinlock_t is a
6048  * spinning lock. Tell lockdep that acquiring spinlock_t is valid here
6049  * by temporarily raising the wait-type to LD_WAIT_CONFIG.
6050  */
6051 static DEFINE_WAIT_OVERRIDE_MAP(kfree_rcu_sheaf_map, LD_WAIT_CONFIG);
6052 
6053 bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj)
6054 {
6055 	struct slub_percpu_sheaves *pcs;
6056 	struct slab_sheaf *rcu_sheaf;
6057 
6058 	if (WARN_ON_ONCE(IS_ENABLED(CONFIG_PREEMPT_RT)))
6059 		return false;
6060 
6061 	lock_map_acquire_try(&kfree_rcu_sheaf_map);
6062 
6063 	if (!local_trylock(&s->cpu_sheaves->lock))
6064 		goto fail;
6065 
6066 	pcs = this_cpu_ptr(s->cpu_sheaves);
6067 
6068 	if (unlikely(!pcs->rcu_free)) {
6069 
6070 		struct slab_sheaf *empty;
6071 		struct node_barn *barn;
6072 
6073 		/* Bootstrap or debug cache, fall back */
6074 		if (unlikely(!cache_has_sheaves(s))) {
6075 			local_unlock(&s->cpu_sheaves->lock);
6076 			goto fail;
6077 		}
6078 
6079 		if (pcs->spare && pcs->spare->size == 0) {
6080 			pcs->rcu_free = pcs->spare;
6081 			pcs->spare = NULL;
6082 			goto do_free;
6083 		}
6084 
6085 		barn = get_barn(s);
6086 		if (!barn) {
6087 			local_unlock(&s->cpu_sheaves->lock);
6088 			goto fail;
6089 		}
6090 
6091 		empty = barn_get_empty_sheaf(barn, true);
6092 
6093 		if (empty) {
6094 			pcs->rcu_free = empty;
6095 			goto do_free;
6096 		}
6097 
6098 		local_unlock(&s->cpu_sheaves->lock);
6099 
6100 		empty = alloc_empty_sheaf(s, GFP_NOWAIT, SLAB_ALLOC_DEFAULT);
6101 
6102 		if (!empty)
6103 			goto fail;
6104 
6105 		if (!local_trylock(&s->cpu_sheaves->lock)) {
6106 			barn_put_empty_sheaf(barn, empty);
6107 			goto fail;
6108 		}
6109 
6110 		pcs = this_cpu_ptr(s->cpu_sheaves);
6111 
6112 		if (unlikely(pcs->rcu_free))
6113 			barn_put_empty_sheaf(barn, empty);
6114 		else
6115 			pcs->rcu_free = empty;
6116 	}
6117 
6118 do_free:
6119 
6120 	rcu_sheaf = pcs->rcu_free;
6121 
6122 	/*
6123 	 * Since we flush immediately when size reaches capacity, we never reach
6124 	 * this with size already at capacity, so no OOB write is possible.
6125 	 */
6126 	rcu_sheaf->objects[rcu_sheaf->size++] = obj;
6127 
6128 	if (likely(rcu_sheaf->size < s->sheaf_capacity)) {
6129 		rcu_sheaf = NULL;
6130 	} else {
6131 		pcs->rcu_free = NULL;
6132 		rcu_sheaf->node = numa_node_id();
6133 	}
6134 
6135 	/*
6136 	 * we flush before local_unlock to make sure a racing
6137 	 * flush_all_rcu_sheaves() doesn't miss this sheaf
6138 	 */
6139 	if (rcu_sheaf)
6140 		call_rcu(&rcu_sheaf->rcu_head, rcu_free_sheaf);
6141 
6142 	local_unlock(&s->cpu_sheaves->lock);
6143 
6144 	stat(s, FREE_RCU_SHEAF);
6145 	lock_map_release(&kfree_rcu_sheaf_map);
6146 	return true;
6147 
6148 fail:
6149 	stat(s, FREE_RCU_SHEAF_FAIL);
6150 	lock_map_release(&kfree_rcu_sheaf_map);
6151 	return false;
6152 }
6153 
6154 static __always_inline bool can_free_to_pcs(struct slab *slab)
6155 {
6156 	int slab_node;
6157 	int numa_node;
6158 
6159 	if (!IS_ENABLED(CONFIG_NUMA))
6160 		goto check_pfmemalloc;
6161 
6162 	slab_node = slab_nid(slab);
6163 
6164 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6165 	/*
6166 	 * numa_mem_id() points to the closest node with memory so only allow
6167 	 * objects from that node to the percpu sheaves
6168 	 */
6169 	numa_node = numa_mem_id();
6170 
6171 	if (likely(slab_node == numa_node))
6172 		goto check_pfmemalloc;
6173 #else
6174 
6175 	/*
6176 	 * numa_mem_id() is only a wrapper to numa_node_id() which is where this
6177 	 * cpu belongs to, but it might be a memoryless node anyway. We don't
6178 	 * know what the closest node is.
6179 	 */
6180 	numa_node = numa_node_id();
6181 
6182 	/* freed object is from this cpu's node, proceed */
6183 	if (likely(slab_node == numa_node))
6184 		goto check_pfmemalloc;
6185 
6186 	/*
6187 	 * Freed object isn't from this cpu's node, but that node is memoryless
6188 	 * or only has ZONE_MOVABLE memory, which slab cannot allocate from.
6189 	 * Proceed as it's better to cache remote objects than falling back to
6190 	 * the slowpath for everything. The allocation side can never obtain
6191 	 * a local object anyway, if none exist. We don't have numa_mem_id() to
6192 	 * point to the closest node as we would on a proper memoryless node
6193 	 * setup.
6194 	 */
6195 	if (unlikely(!node_state(numa_node, N_NORMAL_MEMORY)))
6196 		goto check_pfmemalloc;
6197 #endif
6198 
6199 	return false;
6200 
6201 check_pfmemalloc:
6202 	return likely(!slab_test_pfmemalloc(slab));
6203 }
6204 
6205 /*
6206  * Bulk free objects to the percpu sheaves.
6207  * Unlike free_to_pcs() this includes the calls to all necessary hooks
6208  * and the fallback to freeing to slab pages.
6209  */
6210 static void free_to_pcs_bulk(struct kmem_cache *s, size_t size, void **p)
6211 {
6212 	struct slub_percpu_sheaves *pcs;
6213 	struct slab_sheaf *main, *empty;
6214 	bool init = slab_want_init_on_free(s);
6215 	unsigned int batch, i = 0;
6216 	struct node_barn *barn;
6217 	void *remote_objects[PCS_BATCH_MAX];
6218 	unsigned int remote_nr = 0;
6219 
6220 next_remote_batch:
6221 	while (i < size) {
6222 		struct slab *slab = virt_to_slab(p[i]);
6223 
6224 		memcg_slab_free_hook(s, slab, p + i, 1);
6225 		alloc_tagging_slab_free_hook(s, slab, p + i, 1);
6226 
6227 		if (unlikely(!slab_free_hook(s, p[i], init, false))) {
6228 			p[i] = p[--size];
6229 			continue;
6230 		}
6231 
6232 		if (unlikely(!can_free_to_pcs(slab))) {
6233 			remote_objects[remote_nr] = p[i];
6234 			p[i] = p[--size];
6235 			if (++remote_nr >= PCS_BATCH_MAX)
6236 				goto flush_remote;
6237 			continue;
6238 		}
6239 
6240 		i++;
6241 	}
6242 
6243 	if (!size)
6244 		goto flush_remote;
6245 
6246 next_batch:
6247 	if (!local_trylock(&s->cpu_sheaves->lock))
6248 		goto fallback;
6249 
6250 	pcs = this_cpu_ptr(s->cpu_sheaves);
6251 
6252 	if (likely(pcs->main->size < s->sheaf_capacity))
6253 		goto do_free;
6254 
6255 	barn = get_barn(s);
6256 	if (!barn)
6257 		goto no_empty;
6258 
6259 	if (!pcs->spare) {
6260 		empty = barn_get_empty_sheaf(barn, true);
6261 		if (!empty)
6262 			goto no_empty;
6263 
6264 		pcs->spare = pcs->main;
6265 		pcs->main = empty;
6266 		goto do_free;
6267 	}
6268 
6269 	if (pcs->spare->size < s->sheaf_capacity) {
6270 		swap(pcs->main, pcs->spare);
6271 		goto do_free;
6272 	}
6273 
6274 	empty = barn_replace_full_sheaf(barn, pcs->main, true);
6275 	if (IS_ERR(empty)) {
6276 		stat(s, BARN_PUT_FAIL);
6277 		goto no_empty;
6278 	}
6279 
6280 	stat(s, BARN_PUT);
6281 	pcs->main = empty;
6282 
6283 do_free:
6284 	main = pcs->main;
6285 	batch = min(size, s->sheaf_capacity - main->size);
6286 
6287 	memcpy(main->objects + main->size, p, batch * sizeof(void *));
6288 	main->size += batch;
6289 
6290 	local_unlock(&s->cpu_sheaves->lock);
6291 
6292 	stat_add(s, FREE_FASTPATH, batch);
6293 
6294 	if (batch < size) {
6295 		p += batch;
6296 		size -= batch;
6297 		goto next_batch;
6298 	}
6299 
6300 	if (remote_nr)
6301 		goto flush_remote;
6302 
6303 	return;
6304 
6305 no_empty:
6306 	local_unlock(&s->cpu_sheaves->lock);
6307 
6308 	/*
6309 	 * if we depleted all empty sheaves in the barn or there are too
6310 	 * many full sheaves, free the rest to slab pages
6311 	 */
6312 fallback:
6313 	__kmem_cache_free_bulk(s, size, p);
6314 	stat_add(s, FREE_SLOWPATH, size);
6315 
6316 flush_remote:
6317 	if (remote_nr) {
6318 		__kmem_cache_free_bulk(s, remote_nr, &remote_objects[0]);
6319 		stat_add(s, FREE_SLOWPATH, remote_nr);
6320 		if (i < size) {
6321 			remote_nr = 0;
6322 			goto next_remote_batch;
6323 		}
6324 	}
6325 }
6326 
6327 struct defer_free {
6328 	struct llist_head objects;
6329 	struct irq_work work;
6330 };
6331 
6332 static void free_deferred_objects(struct irq_work *work);
6333 
6334 static DEFINE_PER_CPU(struct defer_free, defer_free_objects) = {
6335 	.objects = LLIST_HEAD_INIT(objects),
6336 	.work = IRQ_WORK_INIT(free_deferred_objects),
6337 };
6338 
6339 /*
6340  * In PREEMPT_RT irq_work runs in per-cpu kthread, so it's safe
6341  * to take sleeping spin_locks from __slab_free().
6342  * In !PREEMPT_RT irq_work will run after local_unlock_irqrestore().
6343  */
6344 static void free_deferred_objects(struct irq_work *work)
6345 {
6346 	struct defer_free *df = container_of(work, struct defer_free, work);
6347 	struct llist_head *objs = &df->objects;
6348 	struct llist_node *llnode, *pos, *t;
6349 
6350 	if (llist_empty(objs))
6351 		return;
6352 
6353 	llnode = llist_del_all(objs);
6354 	llist_for_each_safe(pos, t, llnode) {
6355 		struct kmem_cache *s;
6356 		struct slab *slab;
6357 		void *x = pos;
6358 
6359 		slab = virt_to_slab(x);
6360 		s = slab->slab_cache;
6361 
6362 		/* Point 'x' back to the beginning of allocated object */
6363 		x -= s->offset;
6364 
6365 		/*
6366 		 * We used freepointer in 'x' to link 'x' into df->objects.
6367 		 * Clear it to NULL to avoid false positive detection
6368 		 * of "Freepointer corruption".
6369 		 */
6370 		set_freepointer(s, x, NULL);
6371 
6372 		__slab_free(s, slab, x, x, 1, _THIS_IP_);
6373 		stat(s, FREE_SLOWPATH);
6374 	}
6375 }
6376 
6377 static void defer_free(struct kmem_cache *s, void *head)
6378 {
6379 	struct defer_free *df;
6380 
6381 	guard(preempt)();
6382 
6383 	head = kasan_reset_tag(head);
6384 
6385 	df = this_cpu_ptr(&defer_free_objects);
6386 	if (llist_add(head + s->offset, &df->objects))
6387 		irq_work_queue(&df->work);
6388 }
6389 
6390 void defer_free_barrier(void)
6391 {
6392 	int cpu;
6393 
6394 	for_each_possible_cpu(cpu)
6395 		irq_work_sync(&per_cpu_ptr(&defer_free_objects, cpu)->work);
6396 }
6397 
6398 static __fastpath_inline
6399 void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
6400 	       unsigned long addr)
6401 {
6402 	memcg_slab_free_hook(s, slab, &object, 1);
6403 	alloc_tagging_slab_free_hook(s, slab, &object, 1);
6404 
6405 	if (unlikely(!slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6406 		return;
6407 
6408 	if (likely(can_free_to_pcs(slab)) && likely(free_to_pcs(s, object, true)))
6409 		return;
6410 
6411 	__slab_free(s, slab, object, object, 1, addr);
6412 	stat(s, FREE_SLOWPATH);
6413 }
6414 
6415 #ifdef CONFIG_MEMCG
6416 /* Do not inline the rare memcg charging failed path into the allocation path */
6417 static noinline
6418 void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
6419 {
6420 	struct slab *slab = virt_to_slab(object);
6421 
6422 	alloc_tagging_slab_free_hook(s, slab, &object, 1);
6423 
6424 	if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6425 		__slab_free(s, slab, object, object, 1, _RET_IP_);
6426 }
6427 #endif
6428 
6429 static __fastpath_inline
6430 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
6431 		    void *tail, void **p, int cnt, unsigned long addr)
6432 {
6433 	memcg_slab_free_hook(s, slab, p, cnt);
6434 	alloc_tagging_slab_free_hook(s, slab, p, cnt);
6435 	/*
6436 	 * With KASAN enabled slab_free_freelist_hook modifies the freelist
6437 	 * to remove objects, whose reuse must be delayed.
6438 	 */
6439 	if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt))) {
6440 		__slab_free(s, slab, head, tail, cnt, addr);
6441 		stat_add(s, FREE_SLOWPATH, cnt);
6442 	}
6443 }
6444 
6445 #ifdef CONFIG_SLUB_RCU_DEBUG
6446 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
6447 {
6448 	struct rcu_delayed_free *delayed_free =
6449 			container_of(rcu_head, struct rcu_delayed_free, head);
6450 	void *object = delayed_free->object;
6451 	struct slab *slab = virt_to_slab(object);
6452 	struct kmem_cache *s;
6453 
6454 	kfree(delayed_free);
6455 
6456 	if (WARN_ON(is_kfence_address(object)))
6457 		return;
6458 
6459 	/* find the object and the cache again */
6460 	if (WARN_ON(!slab))
6461 		return;
6462 	s = slab->slab_cache;
6463 	if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
6464 		return;
6465 
6466 	/* resume freeing */
6467 	if (slab_free_hook(s, object, slab_want_init_on_free(s), true)) {
6468 		__slab_free(s, slab, object, object, 1, _THIS_IP_);
6469 		stat(s, FREE_SLOWPATH);
6470 	}
6471 }
6472 #endif /* CONFIG_SLUB_RCU_DEBUG */
6473 
6474 #ifdef CONFIG_KASAN_GENERIC
6475 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
6476 {
6477 	__slab_free(cache, virt_to_slab(x), x, x, 1, addr);
6478 	stat(cache, FREE_SLOWPATH);
6479 }
6480 #endif
6481 
6482 static noinline void warn_free_bad_obj(struct kmem_cache *s, void *obj)
6483 {
6484 	struct kmem_cache *cachep;
6485 	struct slab *slab;
6486 
6487 	slab = virt_to_slab(obj);
6488 	if (WARN_ONCE(!slab,
6489 			"kmem_cache_free(%s, %p): object is not in a slab page\n",
6490 			s->name, obj))
6491 		return;
6492 
6493 	cachep = slab->slab_cache;
6494 
6495 	if (WARN_ONCE(cachep != s,
6496 			"kmem_cache_free(%s, %p): object belongs to different cache %s\n",
6497 			s->name, obj, cachep ? cachep->name : "(NULL)")) {
6498 		if (cachep)
6499 			print_tracking(cachep, obj);
6500 		return;
6501 	}
6502 }
6503 
6504 /**
6505  * kmem_cache_free - Deallocate an object
6506  * @s: The cache the allocation was from.
6507  * @x: The previously allocated object.
6508  *
6509  * Free an object which was previously allocated from this
6510  * cache.
6511  */
6512 void kmem_cache_free(struct kmem_cache *s, void *x)
6513 {
6514 	struct slab *slab;
6515 
6516 	slab = virt_to_slab(x);
6517 
6518 	if (IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) ||
6519 	    kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
6520 
6521 		/*
6522 		 * Intentionally leak the object in these cases, because it
6523 		 * would be too dangerous to continue.
6524 		 */
6525 		if (unlikely(!slab || (slab->slab_cache != s))) {
6526 			warn_free_bad_obj(s, x);
6527 			return;
6528 		}
6529 	}
6530 
6531 	trace_kmem_cache_free(_RET_IP_, x, s);
6532 	slab_free(s, slab, x, _RET_IP_);
6533 }
6534 EXPORT_SYMBOL(kmem_cache_free);
6535 
6536 static inline size_t slab_ksize(struct slab *slab)
6537 {
6538 	struct kmem_cache *s = slab->slab_cache;
6539 
6540 #ifdef CONFIG_SLUB_DEBUG
6541 	/*
6542 	 * Debugging requires use of the padding between object
6543 	 * and whatever may come after it.
6544 	 */
6545 	if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
6546 		return s->object_size;
6547 #endif
6548 	if (s->flags & SLAB_KASAN)
6549 		return s->object_size;
6550 	/*
6551 	 * If we have the need to store the freelist pointer
6552 	 * or any other metadata back there then we can
6553 	 * only use the space before that information.
6554 	 */
6555 	if (s->flags & (SLAB_TYPESAFE_BY_RCU | SLAB_STORE_USER))
6556 		return s->inuse;
6557 	else if (obj_exts_in_object(s, slab))
6558 		return s->inuse;
6559 	/*
6560 	 * Else we can use all the padding etc for the allocation
6561 	 */
6562 	return s->size;
6563 }
6564 
6565 static size_t __ksize(const void *object)
6566 {
6567 	struct page *page;
6568 	struct slab *slab;
6569 
6570 	if (unlikely(object == ZERO_SIZE_PTR))
6571 		return 0;
6572 
6573 	page = virt_to_page(object);
6574 
6575 	if (unlikely(PageLargeKmalloc(page)))
6576 		return large_kmalloc_size(page);
6577 
6578 	slab = page_slab(page);
6579 	/* Delete this after we're sure there are no users */
6580 	if (WARN_ON(!slab))
6581 		return page_size(page);
6582 
6583 #ifdef CONFIG_SLUB_DEBUG
6584 	skip_orig_size_check(slab->slab_cache, object);
6585 #endif
6586 
6587 	return slab_ksize(slab);
6588 }
6589 
6590 /**
6591  * ksize -- Report full size of underlying allocation
6592  * @objp: pointer to the object
6593  *
6594  * This should only be used internally to query the true size of allocations.
6595  * It is not meant to be a way to discover the usable size of an allocation
6596  * after the fact. Instead, use kmalloc_size_roundup(). Using memory beyond
6597  * the originally requested allocation size may trigger KASAN, UBSAN_BOUNDS,
6598  * and/or FORTIFY_SOURCE.
6599  *
6600  * Return: size of the actual memory used by @objp in bytes
6601  */
6602 size_t ksize(const void *objp)
6603 {
6604 	/*
6605 	 * We need to first check that the pointer to the object is valid.
6606 	 * The KASAN report printed from ksize() is more useful, then when
6607 	 * it's printed later when the behaviour could be undefined due to
6608 	 * a potential use-after-free or double-free.
6609 	 *
6610 	 * We use kasan_check_byte(), which is supported for the hardware
6611 	 * tag-based KASAN mode, unlike kasan_check_read/write().
6612 	 *
6613 	 * If the pointed to memory is invalid, we return 0 to avoid users of
6614 	 * ksize() writing to and potentially corrupting the memory region.
6615 	 *
6616 	 * We want to perform the check before __ksize(), to avoid potentially
6617 	 * crashing in __ksize() due to accessing invalid metadata.
6618 	 */
6619 	if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
6620 		return 0;
6621 
6622 	return kfence_ksize(objp) ?: __ksize(objp);
6623 }
6624 EXPORT_SYMBOL(ksize);
6625 
6626 static void free_large_kmalloc(struct page *page, void *object)
6627 {
6628 	unsigned int order = compound_order(page);
6629 
6630 	if (WARN_ON_ONCE(!PageLargeKmalloc(page))) {
6631 		dump_page(page, "Not a kmalloc allocation");
6632 		return;
6633 	}
6634 
6635 	if (WARN_ON_ONCE(order == 0))
6636 		pr_warn_once("object pointer: 0x%p\n", object);
6637 
6638 	kmemleak_free(object);
6639 	kasan_kfree_large(object);
6640 	kmsan_kfree_large(object);
6641 
6642 	mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
6643 			      -(PAGE_SIZE << order));
6644 	__ClearPageLargeKmalloc(page);
6645 	free_frozen_pages(page, order);
6646 }
6647 
6648 /*
6649  * Given an rcu_head embedded within an object obtained from kvmalloc at an
6650  * offset < 4k, free the object in question.
6651  */
6652 void kvfree_rcu_cb(struct rcu_head *head)
6653 {
6654 	void *obj = head;
6655 	struct page *page;
6656 	struct slab *slab;
6657 	struct kmem_cache *s;
6658 	void *slab_addr;
6659 
6660 	if (is_vmalloc_addr(obj)) {
6661 		obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
6662 		vfree(obj);
6663 		return;
6664 	}
6665 
6666 	page = virt_to_page(obj);
6667 	slab = page_slab(page);
6668 	if (!slab) {
6669 		/*
6670 		 * rcu_head offset can be only less than page size so no need to
6671 		 * consider allocation order
6672 		 */
6673 		obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
6674 		free_large_kmalloc(page, obj);
6675 		return;
6676 	}
6677 
6678 	s = slab->slab_cache;
6679 	slab_addr = slab_address(slab);
6680 
6681 	if (is_kfence_address(obj)) {
6682 		obj = kfence_object_start(obj);
6683 	} else {
6684 		unsigned int idx = __obj_to_index(s, slab_addr, obj);
6685 
6686 		obj = slab_addr + s->size * idx;
6687 		obj = fixup_red_left(s, obj);
6688 	}
6689 
6690 	slab_free(s, slab, obj, _RET_IP_);
6691 }
6692 
6693 /**
6694  * kfree - free previously allocated memory
6695  * @object: pointer returned by kmalloc(), kmalloc_nolock(), or kmem_cache_alloc()
6696  *
6697  * If @object is NULL, no operation is performed.
6698  */
6699 void kfree(const void *object)
6700 {
6701 	struct page *page;
6702 	struct slab *slab;
6703 	struct kmem_cache *s;
6704 	void *x = (void *)object;
6705 
6706 	trace_kfree(_RET_IP_, object);
6707 
6708 	if (unlikely(ZERO_OR_NULL_PTR(object)))
6709 		return;
6710 
6711 	page = virt_to_page(object);
6712 	slab = page_slab(page);
6713 	if (!slab) {
6714 		/* kmalloc_nolock() doesn't support large kmalloc */
6715 		free_large_kmalloc(page, (void *)object);
6716 		return;
6717 	}
6718 
6719 	s = slab->slab_cache;
6720 	slab_free(s, slab, x, _RET_IP_);
6721 }
6722 EXPORT_SYMBOL(kfree);
6723 
6724 /*
6725  * Can be called while holding raw_spinlock_t or from IRQ and NMI,
6726  * but ONLY for objects allocated by kmalloc_nolock().
6727  * Debug checks (like kmemleak and kfence) were skipped on allocation,
6728  * hence
6729  * obj = kmalloc(); kfree_nolock(obj);
6730  * will miss kmemleak/kfence book keeping and will cause false positives.
6731  * large_kmalloc is not supported either.
6732  */
6733 void kfree_nolock(const void *object)
6734 {
6735 	struct slab *slab;
6736 	struct kmem_cache *s;
6737 	void *x = (void *)object;
6738 
6739 	if (unlikely(ZERO_OR_NULL_PTR(object)))
6740 		return;
6741 
6742 	slab = virt_to_slab(object);
6743 	if (unlikely(!slab)) {
6744 		WARN_ONCE(1, "large_kmalloc is not supported by kfree_nolock()");
6745 		return;
6746 	}
6747 
6748 	s = slab->slab_cache;
6749 
6750 	memcg_slab_free_hook(s, slab, &x, 1);
6751 	alloc_tagging_slab_free_hook(s, slab, &x, 1);
6752 	/*
6753 	 * Unlike slab_free() do NOT call the following:
6754 	 * kmemleak_free_recursive(x, s->flags);
6755 	 * debug_check_no_locks_freed(x, s->object_size);
6756 	 * debug_check_no_obj_freed(x, s->object_size);
6757 	 * __kcsan_check_access(x, s->object_size, ..);
6758 	 * kfence_free(x);
6759 	 * since they take spinlocks or not safe from any context.
6760 	 */
6761 	kmsan_slab_free(s, x);
6762 	/*
6763 	 * If KASAN finds a kernel bug it will do kasan_report_invalid_free()
6764 	 * which will call raw_spin_lock_irqsave() which is technically
6765 	 * unsafe from NMI, but take chance and report kernel bug.
6766 	 * The sequence of
6767 	 * kasan_report_invalid_free() -> raw_spin_lock_irqsave() -> NMI
6768 	 *  -> kfree_nolock() -> kasan_report_invalid_free() on the same CPU
6769 	 * is double buggy and deserves to deadlock.
6770 	 */
6771 	if (kasan_slab_pre_free(s, x))
6772 		return;
6773 	/*
6774 	 * memcg, kasan_slab_pre_free are done for 'x'.
6775 	 * The only thing left is kasan_poison without quarantine,
6776 	 * since kasan quarantine takes locks and not supported from NMI.
6777 	 */
6778 	kasan_slab_free(s, x, false, false, /* skip quarantine */true);
6779 
6780 	if (likely(can_free_to_pcs(slab)) && likely(free_to_pcs(s, x, false)))
6781 		return;
6782 
6783 	/*
6784 	 * __slab_free() can locklessly cmpxchg16 into a slab, but then it might
6785 	 * need to take spin_lock for further processing.
6786 	 * Avoid the complexity and simply add to a deferred list.
6787 	 */
6788 	defer_free(s, x);
6789 }
6790 EXPORT_SYMBOL_GPL(kfree_nolock);
6791 
6792 static __always_inline __realloc_size(2) void *
6793 __do_krealloc(const void *p, size_t new_size, unsigned long align, gfp_t flags, int nid, kmalloc_token_t token)
6794 {
6795 	void *ret;
6796 	size_t ks = 0;
6797 	int orig_size = 0;
6798 	struct kmem_cache *s = NULL;
6799 
6800 	if (unlikely(ZERO_OR_NULL_PTR(p)))
6801 		goto alloc_new;
6802 
6803 	/* Check for double-free. */
6804 	if (!kasan_check_byte(p))
6805 		return NULL;
6806 
6807 	if (is_kfence_address(p)) {
6808 		ks = orig_size = kfence_ksize(p);
6809 	} else {
6810 		struct page *page = virt_to_page(p);
6811 		struct slab *slab = page_slab(page);
6812 
6813 		if (!slab) {
6814 			/* Big kmalloc object */
6815 			ks = page_size(page);
6816 			WARN_ON(ks <= KMALLOC_MAX_CACHE_SIZE);
6817 			WARN_ON(p != page_address(page));
6818 		} else {
6819 			s = slab->slab_cache;
6820 			orig_size = get_orig_size(s, (void *)p);
6821 			ks = s->object_size;
6822 		}
6823 	}
6824 
6825 	/*
6826 	 * If reallocation is not necessary (e. g. the new size is less
6827 	 * than the current allocated size), the current allocation will be
6828 	 * preserved unless __GFP_THISNODE is set. In the latter case a new
6829 	 * allocation on the requested node will be attempted.
6830 	 */
6831 	if (unlikely(flags & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
6832 		     nid != page_to_nid(virt_to_page(p)))
6833 		goto alloc_new;
6834 
6835 	/* If the old object doesn't fit, allocate a bigger one */
6836 	if (new_size > ks)
6837 		goto alloc_new;
6838 
6839 	/* If the old object doesn't satisfy the new alignment, allocate a new one */
6840 	if (!IS_ALIGNED((unsigned long)p, align))
6841 		goto alloc_new;
6842 
6843 	/* Zero out spare memory. */
6844 	if (want_init_on_alloc(flags)) {
6845 		kasan_disable_current();
6846 		if (orig_size && orig_size < new_size)
6847 			memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size);
6848 		else
6849 			memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
6850 		kasan_enable_current();
6851 	}
6852 
6853 	/* Setup kmalloc redzone when needed */
6854 	if (s && slub_debug_orig_size(s)) {
6855 		set_orig_size(s, (void *)p, new_size);
6856 		if (s->flags & SLAB_RED_ZONE && new_size < ks)
6857 			memset_no_sanitize_memory(kasan_reset_tag(p) + new_size,
6858 						SLUB_RED_ACTIVE, ks - new_size);
6859 	}
6860 
6861 	p = kasan_krealloc(p, new_size, flags);
6862 	return (void *)p;
6863 
6864 alloc_new:
6865 	ret = __kmalloc_node_track_caller_noprof(PASS_KMALLOC_PARAMS(new_size, NULL, token), flags, nid, _RET_IP_);
6866 	if (ret && p) {
6867 		/* Disable KASAN checks as the object's redzone is accessed. */
6868 		kasan_disable_current();
6869 		memcpy(ret, kasan_reset_tag(p), min(new_size, (size_t)(orig_size ?: ks)));
6870 		kasan_enable_current();
6871 	}
6872 
6873 	return ret;
6874 }
6875 
6876 void *krealloc_node_align_noprof(const void *p, DECL_TOKEN_PARAMS(new_size, token), unsigned long align,
6877 				 gfp_t flags, int nid)
6878 {
6879 	void *ret;
6880 
6881 	if (unlikely(!new_size)) {
6882 		kfree(p);
6883 		return ZERO_SIZE_PTR;
6884 	}
6885 
6886 	ret = __do_krealloc(p, new_size, align, flags, nid, PASS_TOKEN_PARAM(token));
6887 	if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
6888 		kfree(p);
6889 
6890 	return ret;
6891 }
6892 EXPORT_SYMBOL(krealloc_node_align_noprof);
6893 
6894 static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
6895 {
6896 	/*
6897 	 * We want to attempt a large physically contiguous block first because
6898 	 * it is less likely to fragment multiple larger blocks and therefore
6899 	 * contribute to a long term fragmentation less than vmalloc fallback.
6900 	 * However make sure that larger requests are not too disruptive - i.e.
6901 	 * do not direct reclaim unless physically continuous memory is preferred
6902 	 * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to
6903 	 * start working in the background
6904 	 */
6905 	if (size > PAGE_SIZE) {
6906 		flags |= __GFP_NOWARN;
6907 
6908 		if (!(flags & __GFP_RETRY_MAYFAIL))
6909 			flags &= ~__GFP_DIRECT_RECLAIM;
6910 
6911 		/* nofail semantic is implemented by the vmalloc fallback */
6912 		flags &= ~__GFP_NOFAIL;
6913 	}
6914 
6915 	return flags;
6916 }
6917 
6918 void *__kvmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), unsigned long align,
6919 			     gfp_t flags, int node)
6920 {
6921 	bool allow_block;
6922 	void *ret;
6923 	const struct slab_alloc_context ac = {
6924 		.caller_addr = _RET_IP_,
6925 		.orig_size = size,
6926 		.alloc_flags = SLAB_ALLOC_DEFAULT,
6927 	};
6928 
6929 	/*
6930 	 * It doesn't really make sense to fallback to vmalloc for sub page
6931 	 * requests
6932 	 */
6933 	ret = __do_kmalloc_node(PASS_BUCKET_PARAM(b),
6934 				kmalloc_gfp_adjust(flags, size),
6935 				node, PASS_TOKEN_PARAM(token), &ac);
6936 	if (ret || size <= PAGE_SIZE)
6937 		return ret;
6938 
6939 	/* Don't even allow crazy sizes */
6940 	if (unlikely(size > INT_MAX)) {
6941 		WARN_ON_ONCE(!(flags & __GFP_NOWARN));
6942 		return NULL;
6943 	}
6944 
6945 	/*
6946 	 * For non-blocking the VM_ALLOW_HUGE_VMAP is not used
6947 	 * because the huge-mapping path in vmalloc contains at
6948 	 * least one might_sleep() call.
6949 	 *
6950 	 * TODO: Revise huge-mapping path to support non-blocking
6951 	 * flags.
6952 	 */
6953 	allow_block = gfpflags_allow_blocking(flags);
6954 
6955 	/*
6956 	 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP,
6957 	 * since the callers already cannot assume anything
6958 	 * about the resulting pointer, and cannot play
6959 	 * protection games.
6960 	 */
6961 	return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END,
6962 			flags, PAGE_KERNEL, allow_block ? VM_ALLOW_HUGE_VMAP:0,
6963 			node, __builtin_return_address(0));
6964 }
6965 EXPORT_SYMBOL(__kvmalloc_node_noprof);
6966 
6967 /**
6968  * kvfree() - Free memory.
6969  * @addr: Pointer to allocated memory.
6970  *
6971  * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
6972  * It is slightly more efficient to use kfree() or vfree() if you are certain
6973  * that you know which one to use.
6974  *
6975  * Context: Either preemptible task context or not-NMI interrupt.
6976  */
6977 void kvfree(const void *addr)
6978 {
6979 	if (is_vmalloc_addr(addr))
6980 		vfree(addr);
6981 	else
6982 		kfree(addr);
6983 }
6984 EXPORT_SYMBOL(kvfree);
6985 
6986 /**
6987  * kvfree_atomic() - Free memory.
6988  * @addr: Pointer to allocated memory.
6989  *
6990  * Same as kvfree(), but uses vfree_atomic() for vmalloc
6991  * backed memory. Must not be called from NMI context.
6992  */
6993 void kvfree_atomic(const void *addr)
6994 {
6995 	if (is_vmalloc_addr(addr))
6996 		vfree_atomic(addr);
6997 	else
6998 		kfree(addr);
6999 }
7000 EXPORT_SYMBOL(kvfree_atomic);
7001 
7002 /**
7003  * kvfree_sensitive - Free a data object containing sensitive information.
7004  * @addr: address of the data object to be freed.
7005  * @len: length of the data object.
7006  *
7007  * Use the special memzero_explicit() function to clear the content of a
7008  * kvmalloc'ed object containing sensitive data to make sure that the
7009  * compiler won't optimize out the data clearing.
7010  */
7011 void kvfree_sensitive(const void *addr, size_t len)
7012 {
7013 	if (likely(!ZERO_OR_NULL_PTR(addr))) {
7014 		memzero_explicit((void *)addr, len);
7015 		kvfree(addr);
7016 	}
7017 }
7018 EXPORT_SYMBOL(kvfree_sensitive);
7019 
7020 void *kvrealloc_node_align_noprof(const void *p, DECL_TOKEN_PARAMS(size, token), unsigned long align,
7021 				  gfp_t flags, int nid)
7022 {
7023 	void *n;
7024 
7025 	if (is_vmalloc_addr(p))
7026 		return vrealloc_node_align_noprof(p, size, align, flags, nid);
7027 
7028 	n = krealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(size, token), align, kmalloc_gfp_adjust(flags, size), nid);
7029 	if (!n) {
7030 		/* We failed to krealloc(), fall back to kvmalloc(). */
7031 		n = __kvmalloc_node_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), align, flags, nid);
7032 		if (!n)
7033 			return NULL;
7034 
7035 		if (p) {
7036 			/* We already know that `p` is not a vmalloc address. */
7037 			kasan_disable_current();
7038 			memcpy(n, kasan_reset_tag(p), min(size, ksize(p)));
7039 			kasan_enable_current();
7040 
7041 			kfree(p);
7042 		}
7043 	}
7044 
7045 	return n;
7046 }
7047 EXPORT_SYMBOL(kvrealloc_node_align_noprof);
7048 
7049 struct detached_freelist {
7050 	struct slab *slab;
7051 	void *tail;
7052 	void *freelist;
7053 	int cnt;
7054 	struct kmem_cache *s;
7055 };
7056 
7057 /*
7058  * This function progressively scans the array with free objects (with
7059  * a limited look ahead) and extract objects belonging to the same
7060  * slab.  It builds a detached freelist directly within the given
7061  * slab/objects.  This can happen without any need for
7062  * synchronization, because the objects are owned by running process.
7063  * The freelist is build up as a single linked list in the objects.
7064  * The idea is, that this detached freelist can then be bulk
7065  * transferred to the real freelist(s), but only requiring a single
7066  * synchronization primitive.  Look ahead in the array is limited due
7067  * to performance reasons.
7068  */
7069 static inline
7070 int build_detached_freelist(struct kmem_cache *s, size_t size,
7071 			    void **p, struct detached_freelist *df)
7072 {
7073 	int lookahead = 3;
7074 	void *object;
7075 	struct page *page;
7076 	struct slab *slab;
7077 	size_t same;
7078 
7079 	object = p[--size];
7080 	page = virt_to_page(object);
7081 	slab = page_slab(page);
7082 	if (!s) {
7083 		/* Handle kalloc'ed objects */
7084 		if (!slab) {
7085 			free_large_kmalloc(page, object);
7086 			df->slab = NULL;
7087 			return size;
7088 		}
7089 		/* Derive kmem_cache from object */
7090 		df->slab = slab;
7091 		df->s = slab->slab_cache;
7092 	} else {
7093 		df->slab = slab;
7094 		df->s = s;
7095 	}
7096 
7097 	/* Start new detached freelist */
7098 	df->tail = object;
7099 	df->freelist = object;
7100 	df->cnt = 1;
7101 
7102 	if (is_kfence_address(object))
7103 		return size;
7104 
7105 	set_freepointer(df->s, object, NULL);
7106 
7107 	same = size;
7108 	while (size) {
7109 		object = p[--size];
7110 		/* df->slab is always set at this point */
7111 		if (df->slab == virt_to_slab(object)) {
7112 			/* Opportunity build freelist */
7113 			set_freepointer(df->s, object, df->freelist);
7114 			df->freelist = object;
7115 			df->cnt++;
7116 			same--;
7117 			if (size != same)
7118 				swap(p[size], p[same]);
7119 			continue;
7120 		}
7121 
7122 		/* Limit look ahead search */
7123 		if (!--lookahead)
7124 			break;
7125 	}
7126 
7127 	return same;
7128 }
7129 
7130 /*
7131  * Internal bulk free of objects that were not initialised by the post alloc
7132  * hooks and thus should not be processed by the free hooks
7133  */
7134 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7135 {
7136 	if (!size)
7137 		return;
7138 
7139 	do {
7140 		struct detached_freelist df;
7141 
7142 		size = build_detached_freelist(s, size, p, &df);
7143 		if (!df.slab)
7144 			continue;
7145 
7146 		if (kfence_free(df.freelist))
7147 			continue;
7148 
7149 		__slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
7150 			     _RET_IP_);
7151 	} while (likely(size));
7152 }
7153 
7154 /* Note that interrupts must be enabled when calling this function. */
7155 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7156 {
7157 	if (!size)
7158 		return;
7159 
7160 	/*
7161 	 * freeing to sheaves is so incompatible with the detached freelist so
7162 	 * once we go that way, we have to do everything differently
7163 	 */
7164 	if (s && cache_has_sheaves(s)) {
7165 		free_to_pcs_bulk(s, size, p);
7166 		return;
7167 	}
7168 
7169 	do {
7170 		struct detached_freelist df;
7171 
7172 		size = build_detached_freelist(s, size, p, &df);
7173 		if (!df.slab)
7174 			continue;
7175 
7176 		slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
7177 			       df.cnt, _RET_IP_);
7178 	} while (likely(size));
7179 }
7180 EXPORT_SYMBOL(kmem_cache_free_bulk);
7181 
7182 static unsigned int
7183 __refill_objects_node(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7184 		      unsigned int max, struct kmem_cache_node *n,
7185 		      bool allow_spin)
7186 {
7187 	struct partial_bulk_context pc;
7188 	struct slab *slab, *slab2;
7189 	unsigned int refilled = 0;
7190 	unsigned long flags;
7191 	void *object;
7192 
7193 	pc.flags = gfp;
7194 	pc.min_objects = min;
7195 	pc.max_objects = max;
7196 
7197 	if (!get_partial_node_bulk(s, n, &pc, allow_spin))
7198 		return 0;
7199 
7200 	list_for_each_entry_safe(slab, slab2, &pc.slabs, slab_list) {
7201 
7202 		unsigned int count;
7203 
7204 		list_del(&slab->slab_list);
7205 
7206 		object = get_freelist_nofreeze(s, slab, &count);
7207 
7208 		while (count && refilled < max) {
7209 			p[refilled] = object;
7210 			object = get_freepointer(s, object);
7211 			maybe_wipe_obj_freeptr(s, p[refilled]);
7212 
7213 			refilled++;
7214 			count--;
7215 		}
7216 
7217 		/*
7218 		 * Freelist had more objects than we can accommodate, we need to
7219 		 * free them back. First we try to be optimistic and assume the
7220 		 * slab is still full since we just detached its freelist.
7221 		 * Otherwise we must find the tail object.
7222 		 */
7223 		if (unlikely(count)) {
7224 			void *head = object;
7225 			void *tail;
7226 
7227 			if (__slab_try_return_freelist(s, slab, head, count)) {
7228 				list_add(&slab->slab_list, &pc.slabs);
7229 				break;
7230 			}
7231 
7232 			do {
7233 				tail = object;
7234 				object = get_freepointer(s, object);
7235 			} while (object);
7236 			__slab_free(s, slab, head, tail, count, _RET_IP_);
7237 		}
7238 
7239 		if (refilled >= max)
7240 			break;
7241 	}
7242 
7243 	if (!list_empty(&pc.slabs)) {
7244 		spin_lock_irqsave(&n->list_lock, flags);
7245 
7246 		list_for_each_entry(slab, &pc.slabs, slab_list)
7247 			set_node_partial_state(n, slab);
7248 
7249 		list_splice_tail(&pc.slabs, &n->partial);
7250 
7251 		spin_unlock_irqrestore(&n->list_lock, flags);
7252 	}
7253 
7254 	return refilled;
7255 }
7256 
7257 #ifdef CONFIG_NUMA
7258 static unsigned int
7259 __refill_objects_any(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7260 		     unsigned int max)
7261 {
7262 	struct zonelist *zonelist;
7263 	struct zoneref *z;
7264 	struct zone *zone;
7265 	enum zone_type highest_zoneidx = gfp_zone(gfp);
7266 	unsigned int cpuset_mems_cookie;
7267 	unsigned int refilled = 0;
7268 
7269 	/* see get_from_any_partial() for the defrag ratio description */
7270 	if (!s->remote_node_defrag_ratio ||
7271 			get_cycles() % 1024 > s->remote_node_defrag_ratio)
7272 		return 0;
7273 
7274 	do {
7275 		cpuset_mems_cookie = read_mems_allowed_begin();
7276 		zonelist = node_zonelist(mempolicy_slab_node(), gfp);
7277 		for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
7278 			struct kmem_cache_node *n;
7279 			unsigned int r;
7280 
7281 			n = get_node(s, zone_to_nid(zone));
7282 
7283 			if (!n || !cpuset_zone_allowed(zone, gfp) ||
7284 					n->nr_partial <= s->min_partial)
7285 				continue;
7286 
7287 			r = __refill_objects_node(s, p, gfp, min, max, n,
7288 						  /* allow_spin = */ false);
7289 			refilled += r;
7290 
7291 			if (r >= min) {
7292 				/*
7293 				 * Don't check read_mems_allowed_retry() here -
7294 				 * if mems_allowed was updated in parallel, that
7295 				 * was a harmless race between allocation and
7296 				 * the cpuset update
7297 				 */
7298 				return refilled;
7299 			}
7300 			p += r;
7301 			min -= r;
7302 			max -= r;
7303 		}
7304 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
7305 
7306 	return refilled;
7307 }
7308 #else
7309 static inline unsigned int
7310 __refill_objects_any(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7311 		     unsigned int max)
7312 {
7313 	return 0;
7314 }
7315 #endif
7316 
7317 static unsigned int
7318 refill_objects(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7319 	       unsigned int max)
7320 {
7321 	int local_node = numa_mem_id();
7322 	unsigned int refilled;
7323 	struct slab *slab;
7324 
7325 	refilled = __refill_objects_node(s, p, gfp, min, max,
7326 					 get_node(s, local_node),
7327 					 /* allow_spin = */ true);
7328 	if (refilled >= min)
7329 		return refilled;
7330 
7331 	refilled += __refill_objects_any(s, p + refilled, gfp, min - refilled,
7332 					 max - refilled);
7333 	if (refilled >= min)
7334 		return refilled;
7335 
7336 new_slab:
7337 
7338 	slab = new_slab(s, gfp, SLAB_ALLOC_DEFAULT, local_node);
7339 	if (!slab)
7340 		goto out;
7341 
7342 	stat(s, ALLOC_SLAB);
7343 
7344 	refilled += alloc_from_new_slab(s, slab, p + refilled, max - refilled,
7345 					/* allow_spin = */ true);
7346 
7347 	if (refilled < min)
7348 		goto new_slab;
7349 
7350 out:
7351 	return refilled;
7352 }
7353 
7354 static bool __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
7355 		size_t size, void **p)
7356 {
7357 	int i;
7358 
7359 	if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
7360 		const struct slab_alloc_context ac = {
7361 			.caller_addr = _RET_IP_,
7362 			.orig_size = s->object_size,
7363 			.alloc_flags = SLAB_ALLOC_DEFAULT,
7364 		};
7365 		for (i = 0; i < size; i++) {
7366 
7367 			p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE, &ac);
7368 			if (unlikely(!p[i]))
7369 				goto error;
7370 
7371 			maybe_wipe_obj_freeptr(s, p[i]);
7372 		}
7373 	} else {
7374 		i = refill_objects(s, p, flags, size, size);
7375 		if (i < size)
7376 			goto error;
7377 		stat_add(s, ALLOC_SLOWPATH, i);
7378 	}
7379 
7380 	return true;
7381 
7382 error:
7383 	__kmem_cache_free_bulk(s, i, p);
7384 	return false;
7385 }
7386 
7387 /**
7388  * kmem_cache_alloc_bulk - Allocate multiple objects
7389  * @s:		The cache to allocate from
7390  * @flags:	GFP_* flags. See kmalloc().
7391  * @size:	Number of objects to allocate
7392  * @p:		Array of allocated objects
7393  *
7394  * Allocate @size objects from @s and places them into @p.  @size must be larger
7395  * than 0.
7396  *
7397  * Interrupts must be enabled when calling this function.
7398  *
7399  * Unlike alloc_pages_bulk(), this function does not check for already allocated
7400  * objects in @p, and thus the caller does not need to zero it.
7401  *
7402  * Return: %true if the allocation succeeded, or %false if it failed.
7403  */
7404 bool kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags,
7405 		size_t size, void **p)
7406 {
7407 	unsigned int i = 0;
7408 	void *kfence_obj;
7409 	const struct slab_alloc_context ac = {
7410 		.orig_size = s->object_size,
7411 		.alloc_flags = SLAB_ALLOC_DEFAULT,
7412 	};
7413 
7414 	if (!size)
7415 		return false;
7416 
7417 	s = slab_pre_alloc_hook(s, flags);
7418 	if (unlikely(!s))
7419 		return false;
7420 
7421 	/*
7422 	 * to make things simpler, only assume at most once kfence allocated
7423 	 * object per bulk allocation and choose its index randomly
7424 	 */
7425 	kfence_obj = kfence_alloc(s, s->object_size, flags);
7426 
7427 	if (unlikely(kfence_obj)) {
7428 		if (unlikely(size == 1)) {
7429 			p[0] = kfence_obj;
7430 			goto out;
7431 		}
7432 		size--;
7433 	}
7434 
7435 	i = alloc_from_pcs_bulk(s, size, p);
7436 	if (i < size) {
7437 		/*
7438 		 * If we ran out of memory, don't bother with freeing back to
7439 		 * the percpu sheaves, we have bigger problems.
7440 		 */
7441 		if (unlikely(!__kmem_cache_alloc_bulk(s, flags, size - i,
7442 				p + i))) {
7443 			if (i > 0)
7444 				__kmem_cache_free_bulk(s, i, p);
7445 			if (kfence_obj)
7446 				__kfence_free(kfence_obj);
7447 			return false;
7448 		}
7449 	}
7450 
7451 	if (unlikely(kfence_obj)) {
7452 		int idx = get_random_u32_below(size + 1);
7453 
7454 		if (idx != size)
7455 			p[size] = p[idx];
7456 		p[idx] = kfence_obj;
7457 
7458 		size++;
7459 	}
7460 
7461 out:
7462 	/* memcg and kmem_cache debug support and memory initialization */
7463 	return likely(slab_post_alloc_hook(s, flags, size, p, &ac));
7464 }
7465 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
7466 
7467 /*
7468  * Object placement in a slab is made very easy because we always start at
7469  * offset 0. If we tune the size of the object to the alignment then we can
7470  * get the required alignment by putting one properly sized object after
7471  * another.
7472  *
7473  * Notice that the allocation order determines the sizes of the per cpu
7474  * caches. Each processor has always one slab available for allocations.
7475  * Increasing the allocation order reduces the number of times that slabs
7476  * must be moved on and off the partial lists and is therefore a factor in
7477  * locking overhead.
7478  */
7479 
7480 /*
7481  * Minimum / Maximum order of slab pages. This influences locking overhead
7482  * and slab fragmentation. A higher order reduces the number of partial slabs
7483  * and increases the number of allocations possible without having to
7484  * take the list_lock.
7485  */
7486 static unsigned int slub_min_order;
7487 static unsigned int slub_max_order =
7488 	IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
7489 static unsigned int slub_min_objects;
7490 
7491 /*
7492  * Calculate the order of allocation given an slab object size.
7493  *
7494  * The order of allocation has significant impact on performance and other
7495  * system components. Generally order 0 allocations should be preferred since
7496  * order 0 does not cause fragmentation in the page allocator. Larger objects
7497  * be problematic to put into order 0 slabs because there may be too much
7498  * unused space left. We go to a higher order if more than 1/16th of the slab
7499  * would be wasted.
7500  *
7501  * In order to reach satisfactory performance we must ensure that a minimum
7502  * number of objects is in one slab. Otherwise we may generate too much
7503  * activity on the partial lists which requires taking the list_lock. This is
7504  * less a concern for large slabs though which are rarely used.
7505  *
7506  * slab_max_order specifies the order where we begin to stop considering the
7507  * number of objects in a slab as critical. If we reach slab_max_order then
7508  * we try to keep the page order as low as possible. So we accept more waste
7509  * of space in favor of a small page order.
7510  *
7511  * Higher order allocations also allow the placement of more objects in a
7512  * slab and thereby reduce object handling overhead. If the user has
7513  * requested a higher minimum order then we start with that one instead of
7514  * the smallest order which will fit the object.
7515  */
7516 static inline unsigned int calc_slab_order(unsigned int size,
7517 		unsigned int min_order, unsigned int max_order,
7518 		unsigned int fract_leftover)
7519 {
7520 	unsigned int order;
7521 
7522 	for (order = min_order; order <= max_order; order++) {
7523 
7524 		unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
7525 		unsigned int rem;
7526 
7527 		rem = slab_size % size;
7528 
7529 		if (rem <= slab_size / fract_leftover)
7530 			break;
7531 	}
7532 
7533 	return order;
7534 }
7535 
7536 static inline int calculate_order(unsigned int size)
7537 {
7538 	unsigned int order;
7539 	unsigned int min_objects;
7540 	unsigned int max_objects;
7541 	unsigned int min_order;
7542 
7543 	min_objects = slub_min_objects;
7544 	if (!min_objects) {
7545 		/*
7546 		 * Some architectures will only update present cpus when
7547 		 * onlining them, so don't trust the number if it's just 1. But
7548 		 * we also don't want to use nr_cpu_ids always, as on some other
7549 		 * architectures, there can be many possible cpus, but never
7550 		 * onlined. Here we compromise between trying to avoid too high
7551 		 * order on systems that appear larger than they are, and too
7552 		 * low order on systems that appear smaller than they are.
7553 		 */
7554 		unsigned int nr_cpus = num_present_cpus();
7555 		if (nr_cpus <= 1)
7556 			nr_cpus = nr_cpu_ids;
7557 		min_objects = 4 * (fls(nr_cpus) + 1);
7558 	}
7559 	/* min_objects can't be 0 because get_order(0) is undefined */
7560 	max_objects = max(order_objects(slub_max_order, size), 1U);
7561 	min_objects = min(min_objects, max_objects);
7562 
7563 	min_order = max_t(unsigned int, slub_min_order,
7564 			  get_order(min_objects * size));
7565 	if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
7566 		return get_order(size * MAX_OBJS_PER_PAGE) - 1;
7567 
7568 	/*
7569 	 * Attempt to find best configuration for a slab. This works by first
7570 	 * attempting to generate a layout with the best possible configuration
7571 	 * and backing off gradually.
7572 	 *
7573 	 * We start with accepting at most 1/16 waste and try to find the
7574 	 * smallest order from min_objects-derived/slab_min_order up to
7575 	 * slab_max_order that will satisfy the constraint. Note that increasing
7576 	 * the order can only result in same or less fractional waste, not more.
7577 	 *
7578 	 * If that fails, we increase the acceptable fraction of waste and try
7579 	 * again. The last iteration with fraction of 1/2 would effectively
7580 	 * accept any waste and give us the order determined by min_objects, as
7581 	 * long as at least single object fits within slab_max_order.
7582 	 */
7583 	for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
7584 		order = calc_slab_order(size, min_order, slub_max_order,
7585 					fraction);
7586 		if (order <= slub_max_order)
7587 			return order;
7588 	}
7589 
7590 	/*
7591 	 * Doh this slab cannot be placed using slab_max_order.
7592 	 */
7593 	order = get_order(size);
7594 	if (order <= MAX_PAGE_ORDER)
7595 		return order;
7596 	return -ENOSYS;
7597 }
7598 
7599 static void
7600 init_kmem_cache_node(struct kmem_cache_node *n)
7601 {
7602 	n->nr_partial = 0;
7603 	spin_lock_init(&n->list_lock);
7604 	INIT_LIST_HEAD(&n->partial);
7605 #ifdef CONFIG_SLUB_DEBUG
7606 	atomic_long_set(&n->nr_slabs, 0);
7607 	atomic_long_set(&n->total_objects, 0);
7608 	INIT_LIST_HEAD(&n->full);
7609 #endif
7610 }
7611 
7612 #ifdef CONFIG_SLUB_STATS
7613 static inline int alloc_kmem_cache_stats(struct kmem_cache *s)
7614 {
7615 	BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
7616 			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
7617 			sizeof(struct kmem_cache_stats));
7618 
7619 	s->cpu_stats = alloc_percpu(struct kmem_cache_stats);
7620 
7621 	if (!s->cpu_stats)
7622 		return 0;
7623 
7624 	return 1;
7625 }
7626 #endif
7627 
7628 static int init_percpu_sheaves(struct kmem_cache *s)
7629 {
7630 	static struct slab_sheaf bootstrap_sheaf = {};
7631 	int cpu;
7632 
7633 	for_each_possible_cpu(cpu) {
7634 		struct slub_percpu_sheaves *pcs;
7635 
7636 		pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
7637 
7638 		local_trylock_init(&pcs->lock);
7639 
7640 		/*
7641 		 * Bootstrap sheaf has zero size so fast-path allocation fails.
7642 		 * It has also size == s->sheaf_capacity, so fast-path free
7643 		 * fails. In the slow paths we recognize the situation by
7644 		 * checking s->sheaf_capacity. This allows fast paths to assume
7645 		 * s->cpu_sheaves and pcs->main always exists and are valid.
7646 		 * It's also safe to share the single static bootstrap_sheaf
7647 		 * with zero-sized objects array as it's never modified.
7648 		 *
7649 		 * Bootstrap_sheaf also has NULL pointer to kmem_cache so we
7650 		 * recognize it and not attempt to free it when destroying the
7651 		 * cache.
7652 		 *
7653 		 * We keep bootstrap_sheaf for kmem_cache and kmem_cache_node,
7654 		 * caches with debug enabled, and all caches with SLUB_TINY.
7655 		 * For kmalloc caches it's used temporarily during the initial
7656 		 * bootstrap.
7657 		 */
7658 		if (!s->sheaf_capacity)
7659 			pcs->main = &bootstrap_sheaf;
7660 		else
7661 			pcs->main = alloc_empty_sheaf(s, GFP_KERNEL, SLAB_ALLOC_DEFAULT);
7662 
7663 		if (!pcs->main)
7664 			return -ENOMEM;
7665 	}
7666 
7667 	return 0;
7668 }
7669 
7670 static struct kmem_cache *kmem_cache_node;
7671 
7672 /*
7673  * No kmalloc_node yet so do it by hand. We know that this is the first
7674  * slab on the node for this slabcache. There are no concurrent accesses
7675  * possible.
7676  *
7677  * Note that this function only works on the kmem_cache_node
7678  * when allocating for the kmem_cache_node. This is used for bootstrapping
7679  * memory on a fresh node that has no slab structures yet.
7680  */
7681 static void early_kmem_cache_node_alloc(int node)
7682 {
7683 	struct slab *slab;
7684 	struct kmem_cache_node *n;
7685 	struct slab_obj_iter iter;
7686 
7687 	BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
7688 
7689 	slab = new_slab(kmem_cache_node, GFP_NOWAIT, SLAB_ALLOC_DEFAULT, node);
7690 
7691 	BUG_ON(!slab);
7692 	if (slab_nid(slab) != node) {
7693 		pr_err("SLUB: Unable to allocate memory from node %d\n", node);
7694 		pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
7695 	}
7696 
7697 	init_slab_obj_iter(kmem_cache_node, slab, &iter, true);
7698 
7699 	n = next_slab_obj(kmem_cache_node, &iter);
7700 	BUG_ON(!n);
7701 
7702 	slab->inuse = 1;
7703 	build_slab_freelist(kmem_cache_node, slab, &iter);
7704 
7705 #ifdef CONFIG_SLUB_DEBUG
7706 	init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
7707 #endif
7708 	n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
7709 	kmem_cache_node->per_node[node].node = n;
7710 	init_kmem_cache_node(n);
7711 	inc_slabs_node(kmem_cache_node, node, slab->objects);
7712 
7713 	/*
7714 	 * No locks need to be taken here as it has just been
7715 	 * initialized and there is no concurrent access.
7716 	 */
7717 	__add_partial(n, slab, ADD_TO_HEAD);
7718 }
7719 
7720 static void free_kmem_cache_nodes(struct kmem_cache *s)
7721 {
7722 	int node;
7723 	struct kmem_cache_node *n;
7724 
7725 	for_each_node(node) {
7726 		struct node_barn *barn = get_barn_node(s, node);
7727 
7728 		if (!barn)
7729 			continue;
7730 
7731 		WARN_ON(barn->nr_full);
7732 		WARN_ON(barn->nr_empty);
7733 		kfree(barn);
7734 		s->per_node[node].barn = NULL;
7735 	}
7736 
7737 	for_each_kmem_cache_node(s, node, n) {
7738 		s->per_node[node].node = NULL;
7739 		kmem_cache_free(kmem_cache_node, n);
7740 	}
7741 }
7742 
7743 void __kmem_cache_release(struct kmem_cache *s)
7744 {
7745 	cache_random_seq_destroy(s);
7746 	pcs_destroy(s);
7747 #ifdef CONFIG_SLUB_STATS
7748 	free_percpu(s->cpu_stats);
7749 #endif
7750 	free_kmem_cache_nodes(s);
7751 }
7752 
7753 static int init_kmem_cache_nodes(struct kmem_cache *s)
7754 {
7755 	int node;
7756 
7757 	for_each_node_mask(node, slab_nodes) {
7758 		struct kmem_cache_node *n;
7759 
7760 		if (slab_state == DOWN) {
7761 			early_kmem_cache_node_alloc(node);
7762 			continue;
7763 		}
7764 
7765 		n = kmem_cache_alloc_node(kmem_cache_node,
7766 						GFP_KERNEL, node);
7767 		if (!n)
7768 			return 0;
7769 
7770 		init_kmem_cache_node(n);
7771 		s->per_node[node].node = n;
7772 	}
7773 
7774 	if (slab_state == DOWN || !cache_has_sheaves(s))
7775 		return 1;
7776 
7777 	for_each_node_mask(node, slab_barn_nodes) {
7778 		struct node_barn *barn;
7779 
7780 		barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, node);
7781 
7782 		if (!barn)
7783 			return 0;
7784 
7785 		barn_init(barn);
7786 		s->per_node[node].barn = barn;
7787 	}
7788 
7789 	return 1;
7790 }
7791 
7792 static unsigned int calculate_sheaf_capacity(struct kmem_cache *s,
7793 					     struct kmem_cache_args *args)
7794 
7795 {
7796 	unsigned int capacity;
7797 	size_t size;
7798 
7799 
7800 	if (IS_ENABLED(CONFIG_SLUB_TINY) || s->flags & SLAB_DEBUG_FLAGS)
7801 		return 0;
7802 
7803 	/*
7804 	 * Bootstrap caches can't have sheaves for now (SLAB_NO_OBJ_EXT).
7805 	 * SLAB_NOLEAKTRACE caches (e.g., kmemleak's object_cache) must not
7806 	 * have sheaves to avoid recursion when sheaf allocation triggers
7807 	 * kmemleak tracking.
7808 	 */
7809 	if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
7810 		return 0;
7811 
7812 	/*
7813 	 * For now we use roughly similar formula (divided by two as there are
7814 	 * two percpu sheaves) as what was used for percpu partial slabs, which
7815 	 * should result in similar lock contention (barn or list_lock)
7816 	 */
7817 	if (s->size >= PAGE_SIZE)
7818 		capacity = 4;
7819 	else if (s->size >= 1024)
7820 		capacity = 12;
7821 	else if (s->size >= 256)
7822 		capacity = 26;
7823 	else
7824 		capacity = 60;
7825 
7826 	/* Increment capacity to make sheaf exactly a kmalloc size bucket */
7827 	size = struct_size_t(struct slab_sheaf, objects, capacity);
7828 	size = kmalloc_size_roundup(size);
7829 	capacity = (size - struct_size_t(struct slab_sheaf, objects, 0)) / sizeof(void *);
7830 
7831 	/*
7832 	 * Respect an explicit request for capacity that's typically motivated by
7833 	 * expected maximum size of kmem_cache_prefill_sheaf() to not end up
7834 	 * using low-performance oversize sheaves
7835 	 */
7836 	return max(capacity, args->sheaf_capacity);
7837 }
7838 
7839 /*
7840  * calculate_sizes() determines the order and the distribution of data within
7841  * a slab object.
7842  */
7843 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
7844 {
7845 	slab_flags_t flags = s->flags;
7846 	unsigned int size = s->object_size;
7847 	unsigned int aligned_size;
7848 	unsigned int order;
7849 
7850 	/*
7851 	 * Round up object size to the next word boundary. We can only
7852 	 * place the free pointer at word boundaries and this determines
7853 	 * the possible location of the free pointer.
7854 	 */
7855 	size = ALIGN(size, sizeof(void *));
7856 
7857 #ifdef CONFIG_SLUB_DEBUG
7858 	/*
7859 	 * Determine if we can poison the object itself. If the user of
7860 	 * the slab may touch the object after free or before allocation
7861 	 * then we should never poison the object itself.
7862 	 */
7863 	if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
7864 			!s->ctor)
7865 		s->flags |= __OBJECT_POISON;
7866 	else
7867 		s->flags &= ~__OBJECT_POISON;
7868 
7869 
7870 	/*
7871 	 * If we are Redzoning and there is no space between the end of the
7872 	 * object and the following fields, add one word so the right Redzone
7873 	 * is non-empty.
7874 	 */
7875 	if ((flags & SLAB_RED_ZONE) && size == s->object_size)
7876 		size += sizeof(void *);
7877 #endif
7878 
7879 	/*
7880 	 * With that we have determined the number of bytes in actual use
7881 	 * by the object and redzoning.
7882 	 */
7883 	s->inuse = size;
7884 
7885 	if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
7886 	    (flags & SLAB_POISON) ||
7887 	    (s->ctor && !args->use_freeptr_offset) ||
7888 	    ((flags & SLAB_RED_ZONE) &&
7889 	     (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
7890 		/*
7891 		 * Relocate free pointer after the object if it is not
7892 		 * permitted to overwrite the first word of the object on
7893 		 * kmem_cache_free.
7894 		 *
7895 		 * This is the case if we do RCU, have a constructor, are
7896 		 * poisoning the objects, or are redzoning an object smaller
7897 		 * than sizeof(void *) or are redzoning an object with
7898 		 * slub_debug_orig_size() enabled, in which case the right
7899 		 * redzone may be extended.
7900 		 *
7901 		 * The assumption that s->offset >= s->inuse means free
7902 		 * pointer is outside of the object is used in the
7903 		 * freeptr_outside_object() function. If that is no
7904 		 * longer true, the function needs to be modified.
7905 		 */
7906 		s->offset = size;
7907 		size += sizeof(void *);
7908 	} else if (((flags & SLAB_TYPESAFE_BY_RCU) || s->ctor) &&
7909 			args->use_freeptr_offset) {
7910 		s->offset = args->freeptr_offset;
7911 	} else {
7912 		/*
7913 		 * Store freelist pointer near middle of object to keep
7914 		 * it away from the edges of the object to avoid small
7915 		 * sized over/underflows from neighboring allocations.
7916 		 */
7917 		s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
7918 	}
7919 
7920 #ifdef CONFIG_SLUB_DEBUG
7921 	if (flags & SLAB_STORE_USER) {
7922 		/*
7923 		 * Need to store information about allocs and frees after
7924 		 * the object.
7925 		 */
7926 		size += 2 * sizeof(struct track);
7927 
7928 		/* Save the original kmalloc request size */
7929 		if (flags & SLAB_KMALLOC)
7930 			size += sizeof(unsigned long);
7931 	}
7932 #endif
7933 
7934 	kasan_cache_create(s, &size, &s->flags);
7935 #ifdef CONFIG_SLUB_DEBUG
7936 	if (flags & SLAB_RED_ZONE) {
7937 		/*
7938 		 * Add some empty padding so that we can catch
7939 		 * overwrites from earlier objects rather than let
7940 		 * tracking information or the free pointer be
7941 		 * corrupted if a user writes before the start
7942 		 * of the object.
7943 		 */
7944 		size += sizeof(void *);
7945 
7946 		s->red_left_pad = sizeof(void *);
7947 		s->red_left_pad = ALIGN(s->red_left_pad, s->align);
7948 		size += s->red_left_pad;
7949 	}
7950 #endif
7951 
7952 	/*
7953 	 * SLUB stores one object immediately after another beginning from
7954 	 * offset 0. In order to align the objects we have to simply size
7955 	 * each object to conform to the alignment.
7956 	 */
7957 	aligned_size = ALIGN(size, s->align);
7958 #if defined(CONFIG_SLAB_OBJ_EXT) && defined(CONFIG_64BIT)
7959 	if (slab_args_unmergeable(args, s->flags) &&
7960 			(aligned_size - size >= sizeof(struct slabobj_ext)))
7961 		s->flags |= SLAB_OBJ_EXT_IN_OBJ;
7962 #endif
7963 	size = aligned_size;
7964 
7965 	s->size = size;
7966 	s->reciprocal_size = reciprocal_value(size);
7967 	order = calculate_order(size);
7968 
7969 	if ((int)order < 0)
7970 		return 0;
7971 
7972 	s->allocflags = __GFP_COMP;
7973 
7974 	if (s->flags & SLAB_CACHE_DMA)
7975 		s->allocflags |= GFP_DMA;
7976 
7977 	if (s->flags & SLAB_CACHE_DMA32)
7978 		s->allocflags |= GFP_DMA32;
7979 
7980 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
7981 		s->allocflags |= __GFP_RECLAIMABLE;
7982 
7983 	/*
7984 	 * For KMALLOC_NORMAL caches we enable sheaves later by
7985 	 * bootstrap_kmalloc_sheaves() to avoid recursion
7986 	 */
7987 	if (!is_kmalloc_normal(s))
7988 		s->sheaf_capacity = calculate_sheaf_capacity(s, args);
7989 
7990 	/*
7991 	 * Determine the number of objects per slab
7992 	 */
7993 	s->oo = oo_make(order, size);
7994 	s->min = oo_make(get_order(size), size);
7995 
7996 	return !!oo_objects(s->oo);
7997 }
7998 
7999 static void list_slab_objects(struct kmem_cache *s, struct slab *slab)
8000 {
8001 #ifdef CONFIG_SLUB_DEBUG
8002 	void *addr = slab_address(slab);
8003 	void *p;
8004 
8005 	if (!slab_add_kunit_errors())
8006 		slab_bug(s, "Objects remaining on __kmem_cache_shutdown()");
8007 
8008 	spin_lock(&object_map_lock);
8009 	__fill_map(object_map, s, slab);
8010 
8011 	for_each_object(p, s, addr, slab->objects) {
8012 
8013 		if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
8014 			if (slab_add_kunit_errors())
8015 				continue;
8016 			pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
8017 			print_tracking(s, p);
8018 		}
8019 	}
8020 	spin_unlock(&object_map_lock);
8021 
8022 	__slab_err(slab);
8023 #endif
8024 }
8025 
8026 /*
8027  * Attempt to free all partial slabs on a node.
8028  * This is called from __kmem_cache_shutdown(). We must take list_lock
8029  * because sysfs file might still access partial list after the shutdowning.
8030  */
8031 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
8032 {
8033 	LIST_HEAD(discard);
8034 	struct slab *slab, *h;
8035 
8036 	BUG_ON(irqs_disabled());
8037 	spin_lock_irq(&n->list_lock);
8038 	list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
8039 		if (!slab->inuse) {
8040 			remove_partial(n, slab);
8041 			list_add(&slab->slab_list, &discard);
8042 		} else {
8043 			list_slab_objects(s, slab);
8044 		}
8045 	}
8046 	spin_unlock_irq(&n->list_lock);
8047 
8048 	list_for_each_entry_safe(slab, h, &discard, slab_list)
8049 		discard_slab(s, slab);
8050 }
8051 
8052 bool __kmem_cache_empty(struct kmem_cache *s)
8053 {
8054 	int node;
8055 	struct kmem_cache_node *n;
8056 
8057 	for_each_kmem_cache_node(s, node, n)
8058 		if (n->nr_partial || node_nr_slabs(n))
8059 			return false;
8060 	return true;
8061 }
8062 
8063 /*
8064  * Release all resources used by a slab cache.
8065  */
8066 int __kmem_cache_shutdown(struct kmem_cache *s)
8067 {
8068 	int node;
8069 	struct kmem_cache_node *n;
8070 
8071 	flush_all_cpus_locked(s);
8072 
8073 	/* we might have rcu sheaves in flight */
8074 	if (cache_has_sheaves(s))
8075 		rcu_barrier();
8076 
8077 	for_each_node(node) {
8078 		struct node_barn *barn = get_barn_node(s, node);
8079 
8080 		if (barn)
8081 			barn_shrink(s, barn);
8082 	}
8083 
8084 	/* Attempt to free all objects */
8085 	for_each_kmem_cache_node(s, node, n) {
8086 		free_partial(s, n);
8087 		if (n->nr_partial || node_nr_slabs(n))
8088 			return 1;
8089 	}
8090 	return 0;
8091 }
8092 
8093 #ifdef CONFIG_PRINTK
8094 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
8095 {
8096 	void *base;
8097 	int __maybe_unused i;
8098 	unsigned int objnr;
8099 	void *objp;
8100 	void *objp0;
8101 	struct kmem_cache *s = slab->slab_cache;
8102 	struct track __maybe_unused *trackp;
8103 
8104 	kpp->kp_ptr = object;
8105 	kpp->kp_slab = slab;
8106 	kpp->kp_slab_cache = s;
8107 	base = slab_address(slab);
8108 	objp0 = kasan_reset_tag(object);
8109 #ifdef CONFIG_SLUB_DEBUG
8110 	objp = restore_red_left(s, objp0);
8111 #else
8112 	objp = objp0;
8113 #endif
8114 	objnr = obj_to_index(s, slab, objp);
8115 	kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
8116 	objp = base + s->size * objnr;
8117 	kpp->kp_objp = objp;
8118 	if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
8119 			 || (objp - base) % s->size) ||
8120 	    !(s->flags & SLAB_STORE_USER))
8121 		return;
8122 #ifdef CONFIG_SLUB_DEBUG
8123 	objp = fixup_red_left(s, objp);
8124 	trackp = get_track(s, objp, TRACK_ALLOC);
8125 	kpp->kp_ret = (void *)trackp->addr;
8126 #ifdef CONFIG_STACKDEPOT
8127 	{
8128 		depot_stack_handle_t handle;
8129 		unsigned long *entries;
8130 		unsigned int nr_entries;
8131 
8132 		handle = READ_ONCE(trackp->handle);
8133 		if (handle) {
8134 			nr_entries = stack_depot_fetch(handle, &entries);
8135 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8136 				kpp->kp_stack[i] = (void *)entries[i];
8137 		}
8138 
8139 		trackp = get_track(s, objp, TRACK_FREE);
8140 		handle = READ_ONCE(trackp->handle);
8141 		if (handle) {
8142 			nr_entries = stack_depot_fetch(handle, &entries);
8143 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8144 				kpp->kp_free_stack[i] = (void *)entries[i];
8145 		}
8146 	}
8147 #endif
8148 #endif
8149 }
8150 #endif
8151 
8152 /********************************************************************
8153  *		Kmalloc subsystem
8154  *******************************************************************/
8155 
8156 static int __init setup_slub_min_order(const char *str, const struct kernel_param *kp)
8157 {
8158 	int ret;
8159 
8160 	ret = kstrtouint(str, 0, &slub_min_order);
8161 	if (ret)
8162 		return ret;
8163 
8164 	if (slub_min_order > slub_max_order)
8165 		slub_max_order = slub_min_order;
8166 
8167 	return 0;
8168 }
8169 
8170 static const struct kernel_param_ops param_ops_slab_min_order __initconst = {
8171 	.set = setup_slub_min_order,
8172 };
8173 __core_param_cb(slab_min_order, &param_ops_slab_min_order, &slub_min_order, 0);
8174 __core_param_cb(slub_min_order, &param_ops_slab_min_order, &slub_min_order, 0);
8175 
8176 static int __init setup_slub_max_order(const char *str, const struct kernel_param *kp)
8177 {
8178 	int ret;
8179 
8180 	ret = kstrtouint(str, 0, &slub_max_order);
8181 	if (ret)
8182 		return ret;
8183 
8184 	slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
8185 
8186 	if (slub_min_order > slub_max_order)
8187 		slub_min_order = slub_max_order;
8188 
8189 	return 0;
8190 }
8191 
8192 static const struct kernel_param_ops param_ops_slab_max_order __initconst = {
8193 	.set = setup_slub_max_order,
8194 };
8195 __core_param_cb(slab_max_order, &param_ops_slab_max_order, &slub_max_order, 0);
8196 __core_param_cb(slub_max_order, &param_ops_slab_max_order, &slub_max_order, 0);
8197 
8198 core_param(slab_min_objects, slub_min_objects, uint, 0);
8199 core_param(slub_min_objects, slub_min_objects, uint, 0);
8200 
8201 #ifdef CONFIG_NUMA
8202 static int __init setup_slab_strict_numa(const char *str, const struct kernel_param *kp)
8203 {
8204 	if (nr_node_ids > 1) {
8205 		static_branch_enable(&strict_numa);
8206 		pr_info("SLUB: Strict NUMA enabled.\n");
8207 	} else {
8208 		pr_warn("slab_strict_numa parameter set on non NUMA system.\n");
8209 	}
8210 
8211 	return 0;
8212 }
8213 
8214 static const struct kernel_param_ops param_ops_slab_strict_numa __initconst = {
8215 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
8216 	.set = setup_slab_strict_numa,
8217 };
8218 __core_param_cb(slab_strict_numa, &param_ops_slab_strict_numa, NULL, 0);
8219 #endif
8220 
8221 
8222 #ifdef CONFIG_HARDENED_USERCOPY
8223 /*
8224  * Rejects incorrectly sized objects and objects that are to be copied
8225  * to/from userspace but do not fall entirely within the containing slab
8226  * cache's usercopy region.
8227  *
8228  * Returns NULL if check passes, otherwise const char * to name of cache
8229  * to indicate an error.
8230  */
8231 void __check_heap_object(const void *ptr, unsigned long n,
8232 			 const struct slab *slab, bool to_user)
8233 {
8234 	struct kmem_cache *s;
8235 	unsigned int offset;
8236 	bool is_kfence = is_kfence_address(ptr);
8237 
8238 	ptr = kasan_reset_tag(ptr);
8239 
8240 	/* Find object and usable object size. */
8241 	s = slab->slab_cache;
8242 
8243 	/* Reject impossible pointers. */
8244 	if (ptr < slab_address(slab))
8245 		usercopy_abort("SLUB object not in SLUB page?!", NULL,
8246 			       to_user, 0, n);
8247 
8248 	/* Find offset within object. */
8249 	if (is_kfence)
8250 		offset = ptr - kfence_object_start(ptr);
8251 	else
8252 		offset = (ptr - slab_address(slab)) % s->size;
8253 
8254 	/* Adjust for redzone and reject if within the redzone. */
8255 	if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
8256 		if (offset < s->red_left_pad)
8257 			usercopy_abort("SLUB object in left red zone",
8258 				       s->name, to_user, offset, n);
8259 		offset -= s->red_left_pad;
8260 	}
8261 
8262 	/* Allow address range falling entirely within usercopy region. */
8263 	if (offset >= s->useroffset &&
8264 	    offset - s->useroffset <= s->usersize &&
8265 	    n <= s->useroffset - offset + s->usersize)
8266 		return;
8267 
8268 	usercopy_abort("SLUB object", s->name, to_user, offset, n);
8269 }
8270 #endif /* CONFIG_HARDENED_USERCOPY */
8271 
8272 #define SHRINK_PROMOTE_MAX 32
8273 
8274 /*
8275  * kmem_cache_shrink discards empty slabs and promotes the slabs filled
8276  * up most to the head of the partial lists. New allocations will then
8277  * fill those up and thus they can be removed from the partial lists.
8278  *
8279  * The slabs with the least items are placed last. This results in them
8280  * being allocated from last increasing the chance that the last objects
8281  * are freed in them.
8282  */
8283 static int __kmem_cache_do_shrink(struct kmem_cache *s)
8284 {
8285 	int node;
8286 	int i;
8287 	struct kmem_cache_node *n;
8288 	struct slab *slab;
8289 	struct slab *t;
8290 	struct list_head discard;
8291 	struct list_head promote[SHRINK_PROMOTE_MAX];
8292 	unsigned long flags;
8293 	int ret = 0;
8294 
8295 	for_each_node(node) {
8296 		struct node_barn *barn = get_barn_node(s, node);
8297 
8298 		if (barn)
8299 			barn_shrink(s, barn);
8300 	}
8301 
8302 	for_each_kmem_cache_node(s, node, n) {
8303 		INIT_LIST_HEAD(&discard);
8304 		for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
8305 			INIT_LIST_HEAD(promote + i);
8306 
8307 		spin_lock_irqsave(&n->list_lock, flags);
8308 
8309 		/*
8310 		 * Build lists of slabs to discard or promote.
8311 		 *
8312 		 * Note that concurrent frees may occur while we hold the
8313 		 * list_lock. slab->inuse here is the upper limit.
8314 		 */
8315 		list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
8316 			int free = slab->objects - slab->inuse;
8317 
8318 			/* Do not reread slab->inuse */
8319 			barrier();
8320 
8321 			/* We do not keep full slabs on the list */
8322 			BUG_ON(free <= 0);
8323 
8324 			if (free == slab->objects) {
8325 				list_move(&slab->slab_list, &discard);
8326 				clear_node_partial_state(n, slab);
8327 				dec_slabs_node(s, node, slab->objects);
8328 			} else if (free <= SHRINK_PROMOTE_MAX)
8329 				list_move(&slab->slab_list, promote + free - 1);
8330 		}
8331 
8332 		/*
8333 		 * Promote the slabs filled up most to the head of the
8334 		 * partial list.
8335 		 */
8336 		for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
8337 			list_splice(promote + i, &n->partial);
8338 
8339 		spin_unlock_irqrestore(&n->list_lock, flags);
8340 
8341 		/* Release empty slabs */
8342 		list_for_each_entry_safe(slab, t, &discard, slab_list)
8343 			free_slab(s, slab);
8344 
8345 		if (node_nr_slabs(n))
8346 			ret = 1;
8347 	}
8348 
8349 	return ret;
8350 }
8351 
8352 int __kmem_cache_shrink(struct kmem_cache *s)
8353 {
8354 	flush_all(s);
8355 	return __kmem_cache_do_shrink(s);
8356 }
8357 
8358 static int slab_mem_going_offline_callback(void)
8359 {
8360 	struct kmem_cache *s;
8361 
8362 	mutex_lock(&slab_mutex);
8363 	list_for_each_entry(s, &slab_caches, list) {
8364 		flush_all_cpus_locked(s);
8365 		__kmem_cache_do_shrink(s);
8366 	}
8367 	mutex_unlock(&slab_mutex);
8368 
8369 	return 0;
8370 }
8371 
8372 static int slab_mem_going_online_callback(int nid)
8373 {
8374 	struct kmem_cache_node *n;
8375 	struct kmem_cache *s;
8376 	int ret = 0;
8377 
8378 	/*
8379 	 * We are bringing a node online. No memory is available yet. We must
8380 	 * allocate a kmem_cache_node structure in order to bring the node
8381 	 * online.
8382 	 */
8383 	mutex_lock(&slab_mutex);
8384 	list_for_each_entry(s, &slab_caches, list) {
8385 		struct node_barn *barn = NULL;
8386 
8387 		/*
8388 		 * The structure may already exist if the node was previously
8389 		 * onlined and offlined.
8390 		 */
8391 		if (get_node(s, nid))
8392 			continue;
8393 
8394 		if (cache_has_sheaves(s) && !get_barn_node(s, nid)) {
8395 
8396 			barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, nid);
8397 
8398 			if (!barn) {
8399 				ret = -ENOMEM;
8400 				goto out;
8401 			}
8402 		}
8403 
8404 		/*
8405 		 * XXX: kmem_cache_alloc_node will fallback to other nodes
8406 		 *      since memory is not yet available from the node that
8407 		 *      is brought up.
8408 		 */
8409 		n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
8410 		if (!n) {
8411 			kfree(barn);
8412 			ret = -ENOMEM;
8413 			goto out;
8414 		}
8415 
8416 		init_kmem_cache_node(n);
8417 		s->per_node[nid].node = n;
8418 
8419 		if (barn) {
8420 			barn_init(barn);
8421 			s->per_node[nid].barn = barn;
8422 		}
8423 	}
8424 	/*
8425 	 * Any cache created after this point will also have kmem_cache_node
8426 	 * and barn initialized for the new node.
8427 	 */
8428 	node_set(nid, slab_nodes);
8429 	node_set(nid, slab_barn_nodes);
8430 out:
8431 	mutex_unlock(&slab_mutex);
8432 	return ret;
8433 }
8434 
8435 static int slab_memory_callback(struct notifier_block *self,
8436 				unsigned long action, void *arg)
8437 {
8438 	struct node_notify *nn = arg;
8439 	int nid = nn->nid;
8440 	int ret = 0;
8441 
8442 	switch (action) {
8443 	case NODE_ADDING_FIRST_MEMORY:
8444 		ret = slab_mem_going_online_callback(nid);
8445 		break;
8446 	case NODE_REMOVING_LAST_MEMORY:
8447 		ret = slab_mem_going_offline_callback();
8448 		break;
8449 	}
8450 	if (ret)
8451 		ret = notifier_from_errno(ret);
8452 	else
8453 		ret = NOTIFY_OK;
8454 	return ret;
8455 }
8456 
8457 /********************************************************************
8458  *			Basic setup of slabs
8459  *******************************************************************/
8460 
8461 /*
8462  * Used for early kmem_cache structures that were allocated using
8463  * the page allocator. Allocate them properly then fix up the pointers
8464  * that may be pointing to the wrong kmem_cache structure.
8465  */
8466 
8467 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
8468 {
8469 	int node;
8470 	struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
8471 	struct kmem_cache_node *n;
8472 
8473 	memcpy(s, static_cache, kmem_cache->object_size);
8474 
8475 	for_each_kmem_cache_node(s, node, n) {
8476 		struct slab *p;
8477 
8478 		list_for_each_entry(p, &n->partial, slab_list)
8479 			p->slab_cache = s;
8480 
8481 #ifdef CONFIG_SLUB_DEBUG
8482 		list_for_each_entry(p, &n->full, slab_list)
8483 			p->slab_cache = s;
8484 #endif
8485 	}
8486 	list_add(&s->list, &slab_caches);
8487 	return s;
8488 }
8489 
8490 /*
8491  * Finish the sheaves initialization done normally by init_percpu_sheaves() and
8492  * init_kmem_cache_nodes(). For normal kmalloc caches we have to bootstrap it
8493  * since sheaves and barns are allocated by kmalloc.
8494  */
8495 static void __init bootstrap_cache_sheaves(struct kmem_cache *s)
8496 {
8497 	struct kmem_cache_args empty_args = {};
8498 	unsigned int capacity;
8499 	bool failed = false;
8500 	int node, cpu;
8501 
8502 	capacity = calculate_sheaf_capacity(s, &empty_args);
8503 
8504 	/* capacity can be 0 due to debugging or SLUB_TINY */
8505 	if (!capacity)
8506 		return;
8507 
8508 	for_each_node_mask(node, slab_barn_nodes) {
8509 		struct node_barn *barn;
8510 
8511 		barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, node);
8512 
8513 		if (!barn) {
8514 			failed = true;
8515 			goto out;
8516 		}
8517 
8518 		barn_init(barn);
8519 		s->per_node[node].barn = barn;
8520 	}
8521 
8522 	for_each_possible_cpu(cpu) {
8523 		struct slub_percpu_sheaves *pcs;
8524 
8525 		pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
8526 
8527 		pcs->main = __alloc_empty_sheaf(s, GFP_KERNEL,
8528 				SLAB_ALLOC_DEFAULT, capacity);
8529 
8530 		if (!pcs->main) {
8531 			failed = true;
8532 			break;
8533 		}
8534 	}
8535 
8536 out:
8537 	/*
8538 	 * It's still early in boot so treat this like same as a failure to
8539 	 * create the kmalloc cache in the first place
8540 	 */
8541 	if (failed)
8542 		panic("Out of memory when creating kmem_cache %s\n", s->name);
8543 
8544 	s->sheaf_capacity = capacity;
8545 }
8546 
8547 static void __init bootstrap_kmalloc_sheaves(void)
8548 {
8549 	enum kmalloc_cache_type type;
8550 
8551 	for (type = KMALLOC_NORMAL; type <= KMALLOC_PARTITION_END; type++) {
8552 		for (int idx = 0; idx < KMALLOC_SHIFT_HIGH + 1; idx++) {
8553 			if (kmalloc_caches[type][idx])
8554 				bootstrap_cache_sheaves(kmalloc_caches[type][idx]);
8555 		}
8556 	}
8557 }
8558 
8559 void __init kmem_cache_init(void)
8560 {
8561 	static __initdata struct kmem_cache boot_kmem_cache,
8562 		boot_kmem_cache_node;
8563 	int node;
8564 
8565 	if (debug_guardpage_minorder())
8566 		slub_max_order = 0;
8567 
8568 	/* Inform pointer hashing choice about slub debugging state. */
8569 	hash_pointers_finalize(__slub_debug_enabled());
8570 
8571 	kmem_cache_node = &boot_kmem_cache_node;
8572 	kmem_cache = &boot_kmem_cache;
8573 
8574 	/*
8575 	 * Initialize the nodemask for which we will allocate per node
8576 	 * structures. Here we don't need taking slab_mutex yet.
8577 	 */
8578 	for_each_node_state(node, N_MEMORY)
8579 		node_set(node, slab_nodes);
8580 
8581 	for_each_online_node(node)
8582 		node_set(node, slab_barn_nodes);
8583 
8584 	create_boot_cache(kmem_cache_node, "kmem_cache_node",
8585 			sizeof(struct kmem_cache_node),
8586 			SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
8587 
8588 	hotplug_node_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
8589 
8590 	/* Able to allocate the per node structures */
8591 	slab_state = PARTIAL;
8592 
8593 	create_boot_cache(kmem_cache, "kmem_cache",
8594 			offsetof(struct kmem_cache, per_node) +
8595 				nr_node_ids * sizeof(struct kmem_cache_per_node_ptrs),
8596 			SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
8597 
8598 	kmem_cache = bootstrap(&boot_kmem_cache);
8599 	kmem_cache_node = bootstrap(&boot_kmem_cache_node);
8600 
8601 	/* Now we can use the kmem_cache to allocate kmalloc slabs */
8602 	setup_kmalloc_cache_index_table();
8603 	create_kmalloc_caches();
8604 
8605 	bootstrap_kmalloc_sheaves();
8606 
8607 	/* Setup random freelists for each cache */
8608 	init_freelist_randomization();
8609 
8610 	cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", slub_cpu_setup,
8611 				  slub_cpu_dead);
8612 
8613 	pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
8614 		cache_line_size(),
8615 		slub_min_order, slub_max_order, slub_min_objects,
8616 		nr_cpu_ids, nr_node_ids);
8617 }
8618 
8619 void __init kmem_cache_init_late(void)
8620 {
8621 	flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM | WQ_PERCPU,
8622 				  0);
8623 	WARN_ON(!flushwq);
8624 #ifdef CONFIG_SLAB_FREELIST_RANDOM
8625 	prandom_init_once(&slab_rnd_state);
8626 #endif
8627 }
8628 
8629 int do_kmem_cache_create(struct kmem_cache *s, const char *name,
8630 			 unsigned int size, struct kmem_cache_args *args,
8631 			 slab_flags_t flags)
8632 {
8633 	int err = -EINVAL;
8634 
8635 	s->name = name;
8636 	s->size = s->object_size = size;
8637 
8638 	s->flags = kmem_cache_flags(flags, s->name);
8639 #ifdef CONFIG_SLAB_FREELIST_HARDENED
8640 	s->random = get_random_long();
8641 #endif
8642 	s->align = args->align;
8643 	s->ctor = args->ctor;
8644 #ifdef CONFIG_HARDENED_USERCOPY
8645 	s->useroffset = args->useroffset;
8646 	s->usersize = args->usersize;
8647 #endif
8648 
8649 	if (!calculate_sizes(args, s))
8650 		goto out;
8651 	if (disable_higher_order_debug) {
8652 		/*
8653 		 * Disable debugging flags that store metadata if the min slab
8654 		 * order increased.
8655 		 */
8656 		if (get_order(s->size) > get_order(s->object_size)) {
8657 			s->flags &= ~DEBUG_METADATA_FLAGS;
8658 			s->offset = 0;
8659 			if (!calculate_sizes(args, s))
8660 				goto out;
8661 		}
8662 	}
8663 
8664 #ifdef system_has_freelist_aba
8665 	if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
8666 		/* Enable fast mode */
8667 		s->flags |= __CMPXCHG_DOUBLE;
8668 	}
8669 #endif
8670 
8671 	/*
8672 	 * The larger the object size is, the more slabs we want on the partial
8673 	 * list to avoid pounding the page allocator excessively.
8674 	 */
8675 	s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
8676 	s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
8677 
8678 	s->cpu_sheaves = alloc_percpu(struct slub_percpu_sheaves);
8679 	if (!s->cpu_sheaves) {
8680 		err = -ENOMEM;
8681 		goto out;
8682 	}
8683 
8684 #ifdef CONFIG_NUMA
8685 	s->remote_node_defrag_ratio = 1000;
8686 #endif
8687 
8688 	/* Initialize the pre-computed randomized freelist if slab is up */
8689 	if (slab_state >= UP) {
8690 		if (init_cache_random_seq(s))
8691 			goto out;
8692 	}
8693 
8694 	if (!init_kmem_cache_nodes(s))
8695 		goto out;
8696 
8697 #ifdef CONFIG_SLUB_STATS
8698 	if (!alloc_kmem_cache_stats(s))
8699 		goto out;
8700 #endif
8701 
8702 	err = init_percpu_sheaves(s);
8703 	if (err)
8704 		goto out;
8705 
8706 	err = 0;
8707 
8708 	/* Mutex is not taken during early boot */
8709 	if (slab_state <= UP)
8710 		goto out;
8711 
8712 	/*
8713 	 * Failing to create sysfs files is not critical to SLUB functionality.
8714 	 * If it fails, proceed with cache creation without these files.
8715 	 */
8716 	if (sysfs_slab_add(s))
8717 		pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name);
8718 
8719 	if (s->flags & SLAB_STORE_USER)
8720 		debugfs_slab_add(s);
8721 
8722 out:
8723 	if (err)
8724 		__kmem_cache_release(s);
8725 	return err;
8726 }
8727 
8728 #ifdef SLAB_SUPPORTS_SYSFS
8729 static int count_inuse(struct slab *slab)
8730 {
8731 	return slab->inuse;
8732 }
8733 
8734 static int count_total(struct slab *slab)
8735 {
8736 	return slab->objects;
8737 }
8738 #endif
8739 
8740 #ifdef CONFIG_SLUB_DEBUG
8741 static void validate_slab(struct kmem_cache *s, struct slab *slab,
8742 			  unsigned long *obj_map)
8743 {
8744 	void *p;
8745 	void *addr = slab_address(slab);
8746 
8747 	if (!validate_slab_ptr(slab)) {
8748 		slab_err(s, slab, "Not a valid slab page");
8749 		return;
8750 	}
8751 
8752 	if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
8753 		return;
8754 
8755 	/* Now we know that a valid freelist exists */
8756 	__fill_map(obj_map, s, slab);
8757 	for_each_object(p, s, addr, slab->objects) {
8758 		u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
8759 			 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
8760 
8761 		if (!check_object(s, slab, p, val))
8762 			break;
8763 	}
8764 }
8765 
8766 static int validate_slab_node(struct kmem_cache *s,
8767 		struct kmem_cache_node *n, unsigned long *obj_map)
8768 {
8769 	unsigned long count = 0;
8770 	struct slab *slab;
8771 	unsigned long flags;
8772 
8773 	spin_lock_irqsave(&n->list_lock, flags);
8774 
8775 	list_for_each_entry(slab, &n->partial, slab_list) {
8776 		validate_slab(s, slab, obj_map);
8777 		count++;
8778 	}
8779 	if (count != n->nr_partial) {
8780 		pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
8781 		       s->name, count, n->nr_partial);
8782 		slab_add_kunit_errors();
8783 	}
8784 
8785 	if (!(s->flags & SLAB_STORE_USER))
8786 		goto out;
8787 
8788 	list_for_each_entry(slab, &n->full, slab_list) {
8789 		validate_slab(s, slab, obj_map);
8790 		count++;
8791 	}
8792 	if (count != node_nr_slabs(n)) {
8793 		pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
8794 		       s->name, count, node_nr_slabs(n));
8795 		slab_add_kunit_errors();
8796 	}
8797 
8798 out:
8799 	spin_unlock_irqrestore(&n->list_lock, flags);
8800 	return count;
8801 }
8802 
8803 long validate_slab_cache(struct kmem_cache *s)
8804 {
8805 	int node;
8806 	unsigned long count = 0;
8807 	struct kmem_cache_node *n;
8808 	unsigned long *obj_map;
8809 
8810 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
8811 	if (!obj_map)
8812 		return -ENOMEM;
8813 
8814 	flush_all(s);
8815 	for_each_kmem_cache_node(s, node, n)
8816 		count += validate_slab_node(s, n, obj_map);
8817 
8818 	bitmap_free(obj_map);
8819 
8820 	return count;
8821 }
8822 EXPORT_SYMBOL(validate_slab_cache);
8823 
8824 #ifdef CONFIG_DEBUG_FS
8825 /*
8826  * Generate lists of code addresses where slabcache objects are allocated
8827  * and freed.
8828  */
8829 
8830 struct location {
8831 	depot_stack_handle_t handle;
8832 	unsigned long count;
8833 	unsigned long addr;
8834 	unsigned long waste;
8835 	long long sum_time;
8836 	long min_time;
8837 	long max_time;
8838 	long min_pid;
8839 	long max_pid;
8840 	DECLARE_BITMAP(cpus, NR_CPUS);
8841 	nodemask_t nodes;
8842 };
8843 
8844 struct loc_track {
8845 	unsigned long max;
8846 	unsigned long count;
8847 	struct location *loc;
8848 	loff_t idx;
8849 };
8850 
8851 static struct dentry *slab_debugfs_root;
8852 
8853 static void free_loc_track(struct loc_track *t)
8854 {
8855 	if (t->max)
8856 		free_pages((unsigned long)t->loc,
8857 			get_order(sizeof(struct location) * t->max));
8858 }
8859 
8860 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
8861 {
8862 	struct location *l;
8863 	int order;
8864 
8865 	order = get_order(sizeof(struct location) * max);
8866 
8867 	l = (void *)__get_free_pages(flags, order);
8868 	if (!l)
8869 		return 0;
8870 
8871 	if (t->count) {
8872 		memcpy(l, t->loc, sizeof(struct location) * t->count);
8873 		free_loc_track(t);
8874 	}
8875 	t->max = max;
8876 	t->loc = l;
8877 	return 1;
8878 }
8879 
8880 static int add_location(struct loc_track *t, struct kmem_cache *s,
8881 				const struct track *track,
8882 				unsigned int orig_size)
8883 {
8884 	long start, end, pos;
8885 	struct location *l;
8886 	unsigned long caddr, chandle, cwaste;
8887 	unsigned long age = jiffies - track->when;
8888 	depot_stack_handle_t handle = 0;
8889 	unsigned int waste = s->object_size - orig_size;
8890 
8891 #ifdef CONFIG_STACKDEPOT
8892 	handle = READ_ONCE(track->handle);
8893 #endif
8894 	start = -1;
8895 	end = t->count;
8896 
8897 	for ( ; ; ) {
8898 		pos = start + (end - start + 1) / 2;
8899 
8900 		/*
8901 		 * There is nothing at "end". If we end up there
8902 		 * we need to add something to before end.
8903 		 */
8904 		if (pos == end)
8905 			break;
8906 
8907 		l = &t->loc[pos];
8908 		caddr = l->addr;
8909 		chandle = l->handle;
8910 		cwaste = l->waste;
8911 		if ((track->addr == caddr) && (handle == chandle) &&
8912 			(waste == cwaste)) {
8913 
8914 			l->count++;
8915 			if (track->when) {
8916 				l->sum_time += age;
8917 				if (age < l->min_time)
8918 					l->min_time = age;
8919 				if (age > l->max_time)
8920 					l->max_time = age;
8921 
8922 				if (track->pid < l->min_pid)
8923 					l->min_pid = track->pid;
8924 				if (track->pid > l->max_pid)
8925 					l->max_pid = track->pid;
8926 
8927 				cpumask_set_cpu(track->cpu,
8928 						to_cpumask(l->cpus));
8929 			}
8930 			node_set(page_to_nid(virt_to_page(track)), l->nodes);
8931 			return 1;
8932 		}
8933 
8934 		if (track->addr < caddr)
8935 			end = pos;
8936 		else if (track->addr == caddr && handle < chandle)
8937 			end = pos;
8938 		else if (track->addr == caddr && handle == chandle &&
8939 				waste < cwaste)
8940 			end = pos;
8941 		else
8942 			start = pos;
8943 	}
8944 
8945 	/*
8946 	 * Not found. Insert new tracking element.
8947 	 */
8948 	if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
8949 		return 0;
8950 
8951 	l = t->loc + pos;
8952 	if (pos < t->count)
8953 		memmove(l + 1, l,
8954 			(t->count - pos) * sizeof(struct location));
8955 	t->count++;
8956 	l->count = 1;
8957 	l->addr = track->addr;
8958 	l->sum_time = age;
8959 	l->min_time = age;
8960 	l->max_time = age;
8961 	l->min_pid = track->pid;
8962 	l->max_pid = track->pid;
8963 	l->handle = handle;
8964 	l->waste = waste;
8965 	cpumask_clear(to_cpumask(l->cpus));
8966 	cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
8967 	nodes_clear(l->nodes);
8968 	node_set(page_to_nid(virt_to_page(track)), l->nodes);
8969 	return 1;
8970 }
8971 
8972 static void process_slab(struct loc_track *t, struct kmem_cache *s,
8973 		struct slab *slab, enum track_item alloc,
8974 		unsigned long *obj_map)
8975 {
8976 	void *addr = slab_address(slab);
8977 	bool is_alloc = (alloc == TRACK_ALLOC);
8978 	void *p;
8979 
8980 	__fill_map(obj_map, s, slab);
8981 
8982 	for_each_object(p, s, addr, slab->objects)
8983 		if (!test_bit(__obj_to_index(s, addr, p), obj_map))
8984 			add_location(t, s, get_track(s, p, alloc),
8985 				     is_alloc ? get_orig_size(s, p) :
8986 						s->object_size);
8987 }
8988 #endif  /* CONFIG_DEBUG_FS   */
8989 #endif	/* CONFIG_SLUB_DEBUG */
8990 
8991 #ifdef SLAB_SUPPORTS_SYSFS
8992 enum slab_stat_type {
8993 	SL_ALL,			/* All slabs */
8994 	SL_PARTIAL,		/* Only partially allocated slabs */
8995 	SL_CPU,			/* Only slabs used for cpu caches */
8996 	SL_OBJECTS,		/* Determine allocated objects not slabs */
8997 	SL_TOTAL		/* Determine object capacity not slabs */
8998 };
8999 
9000 #define SO_ALL		(1 << SL_ALL)
9001 #define SO_PARTIAL	(1 << SL_PARTIAL)
9002 #define SO_CPU		(1 << SL_CPU)
9003 #define SO_OBJECTS	(1 << SL_OBJECTS)
9004 #define SO_TOTAL	(1 << SL_TOTAL)
9005 
9006 static ssize_t show_slab_objects(struct kmem_cache *s,
9007 				 char *buf, unsigned long flags)
9008 {
9009 	unsigned long total = 0;
9010 	int node;
9011 	int x;
9012 	unsigned long *nodes;
9013 	int len = 0;
9014 
9015 	nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
9016 	if (!nodes)
9017 		return -ENOMEM;
9018 
9019 	/*
9020 	 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
9021 	 * already held which will conflict with an existing lock order:
9022 	 *
9023 	 * mem_hotplug_lock->slab_mutex->kernfs_mutex
9024 	 *
9025 	 * We don't really need mem_hotplug_lock (to hold off
9026 	 * slab_mem_going_offline_callback) here because slab's memory hot
9027 	 * unplug code doesn't destroy the kmem_cache->node[] data.
9028 	 */
9029 
9030 #ifdef CONFIG_SLUB_DEBUG
9031 	if (flags & SO_ALL) {
9032 		struct kmem_cache_node *n;
9033 
9034 		for_each_kmem_cache_node(s, node, n) {
9035 
9036 			if (flags & SO_TOTAL)
9037 				x = node_nr_objs(n);
9038 			else if (flags & SO_OBJECTS)
9039 				x = node_nr_objs(n) - count_partial(n, count_free);
9040 			else
9041 				x = node_nr_slabs(n);
9042 			total += x;
9043 			nodes[node] += x;
9044 		}
9045 
9046 	} else
9047 #endif
9048 	if (flags & SO_PARTIAL) {
9049 		struct kmem_cache_node *n;
9050 
9051 		for_each_kmem_cache_node(s, node, n) {
9052 			if (flags & SO_TOTAL)
9053 				x = count_partial(n, count_total);
9054 			else if (flags & SO_OBJECTS)
9055 				x = count_partial(n, count_inuse);
9056 			else
9057 				x = n->nr_partial;
9058 			total += x;
9059 			nodes[node] += x;
9060 		}
9061 	}
9062 
9063 	len += sysfs_emit_at(buf, len, "%lu", total);
9064 #ifdef CONFIG_NUMA
9065 	for (node = 0; node < nr_node_ids; node++) {
9066 		if (nodes[node])
9067 			len += sysfs_emit_at(buf, len, " N%d=%lu",
9068 					     node, nodes[node]);
9069 	}
9070 #endif
9071 	len += sysfs_emit_at(buf, len, "\n");
9072 	kfree(nodes);
9073 
9074 	return len;
9075 }
9076 
9077 #define to_slab_attr(n) container_of_const(n, struct slab_attribute, attr)
9078 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
9079 
9080 struct slab_attribute {
9081 	struct attribute attr;
9082 	ssize_t (*show)(struct kmem_cache *s, char *buf);
9083 	ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
9084 };
9085 
9086 #define SLAB_ATTR_RO(_name) \
9087 	static const struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
9088 
9089 #define SLAB_ATTR(_name) \
9090 	static const struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
9091 
9092 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
9093 {
9094 	return sysfs_emit(buf, "%u\n", s->size);
9095 }
9096 SLAB_ATTR_RO(slab_size);
9097 
9098 static ssize_t align_show(struct kmem_cache *s, char *buf)
9099 {
9100 	return sysfs_emit(buf, "%u\n", s->align);
9101 }
9102 SLAB_ATTR_RO(align);
9103 
9104 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
9105 {
9106 	return sysfs_emit(buf, "%u\n", s->object_size);
9107 }
9108 SLAB_ATTR_RO(object_size);
9109 
9110 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
9111 {
9112 	return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
9113 }
9114 SLAB_ATTR_RO(objs_per_slab);
9115 
9116 static ssize_t order_show(struct kmem_cache *s, char *buf)
9117 {
9118 	return sysfs_emit(buf, "%u\n", oo_order(s->oo));
9119 }
9120 SLAB_ATTR_RO(order);
9121 
9122 static ssize_t sheaf_capacity_show(struct kmem_cache *s, char *buf)
9123 {
9124 	return sysfs_emit(buf, "%u\n", s->sheaf_capacity);
9125 }
9126 SLAB_ATTR_RO(sheaf_capacity);
9127 
9128 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
9129 {
9130 	return sysfs_emit(buf, "%lu\n", s->min_partial);
9131 }
9132 
9133 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
9134 				 size_t length)
9135 {
9136 	unsigned long min;
9137 	int err;
9138 
9139 	err = kstrtoul(buf, 10, &min);
9140 	if (err)
9141 		return err;
9142 
9143 	s->min_partial = min;
9144 	return length;
9145 }
9146 SLAB_ATTR(min_partial);
9147 
9148 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
9149 {
9150 	return sysfs_emit(buf, "0\n");
9151 }
9152 
9153 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
9154 				 size_t length)
9155 {
9156 	unsigned int objects;
9157 	int err;
9158 
9159 	err = kstrtouint(buf, 10, &objects);
9160 	if (err)
9161 		return err;
9162 	if (objects)
9163 		return -EINVAL;
9164 
9165 	return length;
9166 }
9167 SLAB_ATTR(cpu_partial);
9168 
9169 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
9170 {
9171 	if (!s->ctor)
9172 		return 0;
9173 	return sysfs_emit(buf, "%pS\n", s->ctor);
9174 }
9175 SLAB_ATTR_RO(ctor);
9176 
9177 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
9178 {
9179 	return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
9180 }
9181 SLAB_ATTR_RO(aliases);
9182 
9183 static ssize_t partial_show(struct kmem_cache *s, char *buf)
9184 {
9185 	return show_slab_objects(s, buf, SO_PARTIAL);
9186 }
9187 SLAB_ATTR_RO(partial);
9188 
9189 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
9190 {
9191 	return show_slab_objects(s, buf, SO_CPU);
9192 }
9193 SLAB_ATTR_RO(cpu_slabs);
9194 
9195 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
9196 {
9197 	return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
9198 }
9199 SLAB_ATTR_RO(objects_partial);
9200 
9201 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
9202 {
9203 	return sysfs_emit(buf, "0(0)\n");
9204 }
9205 SLAB_ATTR_RO(slabs_cpu_partial);
9206 
9207 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
9208 {
9209 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
9210 }
9211 SLAB_ATTR_RO(reclaim_account);
9212 
9213 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
9214 {
9215 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
9216 }
9217 SLAB_ATTR_RO(hwcache_align);
9218 
9219 #ifdef CONFIG_ZONE_DMA
9220 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
9221 {
9222 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
9223 }
9224 SLAB_ATTR_RO(cache_dma);
9225 #endif
9226 
9227 #ifdef CONFIG_HARDENED_USERCOPY
9228 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
9229 {
9230 	return sysfs_emit(buf, "%u\n", s->usersize);
9231 }
9232 SLAB_ATTR_RO(usersize);
9233 #endif
9234 
9235 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
9236 {
9237 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
9238 }
9239 SLAB_ATTR_RO(destroy_by_rcu);
9240 
9241 #ifdef CONFIG_SLUB_DEBUG
9242 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
9243 {
9244 	return show_slab_objects(s, buf, SO_ALL);
9245 }
9246 SLAB_ATTR_RO(slabs);
9247 
9248 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
9249 {
9250 	return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
9251 }
9252 SLAB_ATTR_RO(total_objects);
9253 
9254 static ssize_t objects_show(struct kmem_cache *s, char *buf)
9255 {
9256 	return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
9257 }
9258 SLAB_ATTR_RO(objects);
9259 
9260 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
9261 {
9262 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
9263 }
9264 SLAB_ATTR_RO(sanity_checks);
9265 
9266 static ssize_t trace_show(struct kmem_cache *s, char *buf)
9267 {
9268 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
9269 }
9270 SLAB_ATTR_RO(trace);
9271 
9272 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
9273 {
9274 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
9275 }
9276 
9277 SLAB_ATTR_RO(red_zone);
9278 
9279 static ssize_t poison_show(struct kmem_cache *s, char *buf)
9280 {
9281 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
9282 }
9283 
9284 SLAB_ATTR_RO(poison);
9285 
9286 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
9287 {
9288 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
9289 }
9290 
9291 SLAB_ATTR_RO(store_user);
9292 
9293 static ssize_t validate_show(struct kmem_cache *s, char *buf)
9294 {
9295 	return 0;
9296 }
9297 
9298 static ssize_t validate_store(struct kmem_cache *s,
9299 			const char *buf, size_t length)
9300 {
9301 	int ret = -EINVAL;
9302 
9303 	if (buf[0] == '1' && kmem_cache_debug(s)) {
9304 		ret = validate_slab_cache(s);
9305 		if (ret >= 0)
9306 			ret = length;
9307 	}
9308 	return ret;
9309 }
9310 SLAB_ATTR(validate);
9311 
9312 #endif /* CONFIG_SLUB_DEBUG */
9313 
9314 #ifdef CONFIG_FAILSLAB
9315 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
9316 {
9317 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
9318 }
9319 
9320 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
9321 				size_t length)
9322 {
9323 	if (s->refcount > 1)
9324 		return -EINVAL;
9325 
9326 	if (buf[0] == '1')
9327 		WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
9328 	else
9329 		WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
9330 
9331 	return length;
9332 }
9333 SLAB_ATTR(failslab);
9334 #endif
9335 
9336 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
9337 {
9338 	return 0;
9339 }
9340 
9341 static ssize_t shrink_store(struct kmem_cache *s,
9342 			const char *buf, size_t length)
9343 {
9344 	if (buf[0] == '1')
9345 		kmem_cache_shrink(s);
9346 	else
9347 		return -EINVAL;
9348 	return length;
9349 }
9350 SLAB_ATTR(shrink);
9351 
9352 #ifdef CONFIG_NUMA
9353 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
9354 {
9355 	return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
9356 }
9357 
9358 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
9359 				const char *buf, size_t length)
9360 {
9361 	unsigned int ratio;
9362 	int err;
9363 
9364 	err = kstrtouint(buf, 10, &ratio);
9365 	if (err)
9366 		return err;
9367 	if (ratio > 100)
9368 		return -ERANGE;
9369 
9370 	s->remote_node_defrag_ratio = ratio * 10;
9371 
9372 	return length;
9373 }
9374 SLAB_ATTR(remote_node_defrag_ratio);
9375 #endif
9376 
9377 #ifdef CONFIG_SLUB_STATS
9378 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
9379 {
9380 	unsigned long sum  = 0;
9381 	int cpu;
9382 	int len = 0;
9383 	int *data = kmalloc_objs(int, nr_cpu_ids);
9384 
9385 	if (!data)
9386 		return -ENOMEM;
9387 
9388 	for_each_online_cpu(cpu) {
9389 		unsigned int x = per_cpu_ptr(s->cpu_stats, cpu)->stat[si];
9390 
9391 		data[cpu] = x;
9392 		sum += x;
9393 	}
9394 
9395 	len += sysfs_emit_at(buf, len, "%lu", sum);
9396 
9397 #ifdef CONFIG_SMP
9398 	for_each_online_cpu(cpu) {
9399 		if (data[cpu])
9400 			len += sysfs_emit_at(buf, len, " C%d=%u",
9401 					     cpu, data[cpu]);
9402 	}
9403 #endif
9404 	kfree(data);
9405 	len += sysfs_emit_at(buf, len, "\n");
9406 
9407 	return len;
9408 }
9409 
9410 static void clear_stat(struct kmem_cache *s, enum stat_item si)
9411 {
9412 	int cpu;
9413 
9414 	for_each_online_cpu(cpu)
9415 		per_cpu_ptr(s->cpu_stats, cpu)->stat[si] = 0;
9416 }
9417 
9418 #define STAT_ATTR(si, text) 					\
9419 static ssize_t text##_show(struct kmem_cache *s, char *buf)	\
9420 {								\
9421 	return show_stat(s, buf, si);				\
9422 }								\
9423 static ssize_t text##_store(struct kmem_cache *s,		\
9424 				const char *buf, size_t length)	\
9425 {								\
9426 	if (buf[0] != '0')					\
9427 		return -EINVAL;					\
9428 	clear_stat(s, si);					\
9429 	return length;						\
9430 }								\
9431 SLAB_ATTR(text);						\
9432 
9433 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
9434 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
9435 STAT_ATTR(FREE_RCU_SHEAF, free_rcu_sheaf);
9436 STAT_ATTR(FREE_RCU_SHEAF_FAIL, free_rcu_sheaf_fail);
9437 STAT_ATTR(FREE_FASTPATH, free_fastpath);
9438 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
9439 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
9440 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
9441 STAT_ATTR(ALLOC_SLAB, alloc_slab);
9442 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
9443 STAT_ATTR(FREE_SLAB, free_slab);
9444 STAT_ATTR(ORDER_FALLBACK, order_fallback);
9445 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
9446 STAT_ATTR(SHEAF_FLUSH, sheaf_flush);
9447 STAT_ATTR(SHEAF_REFILL, sheaf_refill);
9448 STAT_ATTR(SHEAF_ALLOC, sheaf_alloc);
9449 STAT_ATTR(SHEAF_FREE, sheaf_free);
9450 STAT_ATTR(BARN_GET, barn_get);
9451 STAT_ATTR(BARN_GET_FAIL, barn_get_fail);
9452 STAT_ATTR(BARN_PUT, barn_put);
9453 STAT_ATTR(BARN_PUT_FAIL, barn_put_fail);
9454 STAT_ATTR(SHEAF_PREFILL_FAST, sheaf_prefill_fast);
9455 STAT_ATTR(SHEAF_PREFILL_SLOW, sheaf_prefill_slow);
9456 STAT_ATTR(SHEAF_PREFILL_OVERSIZE, sheaf_prefill_oversize);
9457 STAT_ATTR(SHEAF_RETURN_FAST, sheaf_return_fast);
9458 STAT_ATTR(SHEAF_RETURN_SLOW, sheaf_return_slow);
9459 #endif	/* CONFIG_SLUB_STATS */
9460 
9461 #ifdef CONFIG_KFENCE
9462 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
9463 {
9464 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
9465 }
9466 
9467 static ssize_t skip_kfence_store(struct kmem_cache *s,
9468 			const char *buf, size_t length)
9469 {
9470 	int ret = length;
9471 
9472 	if (buf[0] == '0')
9473 		s->flags &= ~SLAB_SKIP_KFENCE;
9474 	else if (buf[0] == '1')
9475 		s->flags |= SLAB_SKIP_KFENCE;
9476 	else
9477 		ret = -EINVAL;
9478 
9479 	return ret;
9480 }
9481 SLAB_ATTR(skip_kfence);
9482 #endif
9483 
9484 static const struct attribute *const slab_attrs[] = {
9485 	&slab_size_attr.attr,
9486 	&object_size_attr.attr,
9487 	&objs_per_slab_attr.attr,
9488 	&order_attr.attr,
9489 	&sheaf_capacity_attr.attr,
9490 	&min_partial_attr.attr,
9491 	&cpu_partial_attr.attr,
9492 	&objects_partial_attr.attr,
9493 	&partial_attr.attr,
9494 	&cpu_slabs_attr.attr,
9495 	&ctor_attr.attr,
9496 	&aliases_attr.attr,
9497 	&align_attr.attr,
9498 	&hwcache_align_attr.attr,
9499 	&reclaim_account_attr.attr,
9500 	&destroy_by_rcu_attr.attr,
9501 	&shrink_attr.attr,
9502 	&slabs_cpu_partial_attr.attr,
9503 #ifdef CONFIG_SLUB_DEBUG
9504 	&total_objects_attr.attr,
9505 	&objects_attr.attr,
9506 	&slabs_attr.attr,
9507 	&sanity_checks_attr.attr,
9508 	&trace_attr.attr,
9509 	&red_zone_attr.attr,
9510 	&poison_attr.attr,
9511 	&store_user_attr.attr,
9512 	&validate_attr.attr,
9513 #endif
9514 #ifdef CONFIG_ZONE_DMA
9515 	&cache_dma_attr.attr,
9516 #endif
9517 #ifdef CONFIG_NUMA
9518 	&remote_node_defrag_ratio_attr.attr,
9519 #endif
9520 #ifdef CONFIG_SLUB_STATS
9521 	&alloc_fastpath_attr.attr,
9522 	&alloc_slowpath_attr.attr,
9523 	&free_rcu_sheaf_attr.attr,
9524 	&free_rcu_sheaf_fail_attr.attr,
9525 	&free_fastpath_attr.attr,
9526 	&free_slowpath_attr.attr,
9527 	&free_add_partial_attr.attr,
9528 	&free_remove_partial_attr.attr,
9529 	&alloc_slab_attr.attr,
9530 	&alloc_node_mismatch_attr.attr,
9531 	&free_slab_attr.attr,
9532 	&order_fallback_attr.attr,
9533 	&cmpxchg_double_fail_attr.attr,
9534 	&sheaf_flush_attr.attr,
9535 	&sheaf_refill_attr.attr,
9536 	&sheaf_alloc_attr.attr,
9537 	&sheaf_free_attr.attr,
9538 	&barn_get_attr.attr,
9539 	&barn_get_fail_attr.attr,
9540 	&barn_put_attr.attr,
9541 	&barn_put_fail_attr.attr,
9542 	&sheaf_prefill_fast_attr.attr,
9543 	&sheaf_prefill_slow_attr.attr,
9544 	&sheaf_prefill_oversize_attr.attr,
9545 	&sheaf_return_fast_attr.attr,
9546 	&sheaf_return_slow_attr.attr,
9547 #endif
9548 #ifdef CONFIG_FAILSLAB
9549 	&failslab_attr.attr,
9550 #endif
9551 #ifdef CONFIG_HARDENED_USERCOPY
9552 	&usersize_attr.attr,
9553 #endif
9554 #ifdef CONFIG_KFENCE
9555 	&skip_kfence_attr.attr,
9556 #endif
9557 
9558 	NULL
9559 };
9560 
9561 ATTRIBUTE_GROUPS(slab);
9562 
9563 static ssize_t slab_attr_show(struct kobject *kobj,
9564 				struct attribute *attr,
9565 				char *buf)
9566 {
9567 	const struct slab_attribute *attribute;
9568 	struct kmem_cache *s;
9569 
9570 	attribute = to_slab_attr(attr);
9571 	s = to_slab(kobj);
9572 
9573 	if (!attribute->show)
9574 		return -EIO;
9575 
9576 	return attribute->show(s, buf);
9577 }
9578 
9579 static ssize_t slab_attr_store(struct kobject *kobj,
9580 				struct attribute *attr,
9581 				const char *buf, size_t len)
9582 {
9583 	const struct slab_attribute *attribute;
9584 	struct kmem_cache *s;
9585 
9586 	attribute = to_slab_attr(attr);
9587 	s = to_slab(kobj);
9588 
9589 	if (!attribute->store)
9590 		return -EIO;
9591 
9592 	return attribute->store(s, buf, len);
9593 }
9594 
9595 static void kmem_cache_release(struct kobject *k)
9596 {
9597 	slab_kmem_cache_release(to_slab(k));
9598 }
9599 
9600 static const struct sysfs_ops slab_sysfs_ops = {
9601 	.show = slab_attr_show,
9602 	.store = slab_attr_store,
9603 };
9604 
9605 static const struct kobj_type slab_ktype = {
9606 	.sysfs_ops = &slab_sysfs_ops,
9607 	.release = kmem_cache_release,
9608 	.default_groups = slab_groups,
9609 };
9610 
9611 static struct kset *slab_kset;
9612 
9613 static inline struct kset *cache_kset(struct kmem_cache *s)
9614 {
9615 	return slab_kset;
9616 }
9617 
9618 #define ID_STR_LENGTH 32
9619 
9620 /* Create a unique string id for a slab cache:
9621  *
9622  * Format	:[flags-]size
9623  */
9624 static char *create_unique_id(struct kmem_cache *s)
9625 {
9626 	char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
9627 	char *p = name;
9628 
9629 	if (!name)
9630 		return ERR_PTR(-ENOMEM);
9631 
9632 	*p++ = ':';
9633 	/*
9634 	 * First flags affecting slabcache operations. We will only
9635 	 * get here for aliasable slabs so we do not need to support
9636 	 * too many flags. The flags here must cover all flags that
9637 	 * are matched during merging to guarantee that the id is
9638 	 * unique.
9639 	 */
9640 	if (s->flags & SLAB_CACHE_DMA)
9641 		*p++ = 'd';
9642 	if (s->flags & SLAB_CACHE_DMA32)
9643 		*p++ = 'D';
9644 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
9645 		*p++ = 'a';
9646 	if (s->flags & SLAB_CONSISTENCY_CHECKS)
9647 		*p++ = 'F';
9648 	if (s->flags & SLAB_ACCOUNT)
9649 		*p++ = 'A';
9650 	if (p != name + 1)
9651 		*p++ = '-';
9652 	p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
9653 
9654 	if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
9655 		kfree(name);
9656 		return ERR_PTR(-EINVAL);
9657 	}
9658 	kmsan_unpoison_memory(name, p - name);
9659 	return name;
9660 }
9661 
9662 static int sysfs_slab_add(struct kmem_cache *s)
9663 {
9664 	int err;
9665 	const char *name;
9666 	struct kset *kset = cache_kset(s);
9667 	int unmergeable = slab_unmergeable(s);
9668 
9669 	if (!unmergeable && disable_higher_order_debug &&
9670 			(slub_debug & DEBUG_METADATA_FLAGS))
9671 		unmergeable = 1;
9672 
9673 	if (unmergeable) {
9674 		/*
9675 		 * Slabcache can never be merged so we can use the name proper.
9676 		 * This is typically the case for debug situations. In that
9677 		 * case we can catch duplicate names easily.
9678 		 */
9679 		sysfs_remove_link(&slab_kset->kobj, s->name);
9680 		name = s->name;
9681 	} else {
9682 		/*
9683 		 * Create a unique name for the slab as a target
9684 		 * for the symlinks.
9685 		 */
9686 		name = create_unique_id(s);
9687 		if (IS_ERR(name))
9688 			return PTR_ERR(name);
9689 	}
9690 
9691 	s->kobj.kset = kset;
9692 	err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
9693 	if (err)
9694 		goto out;
9695 
9696 	if (!unmergeable) {
9697 		/* Setup first alias */
9698 		sysfs_slab_alias(s, s->name);
9699 	}
9700 out:
9701 	if (!unmergeable)
9702 		kfree(name);
9703 	return err;
9704 }
9705 
9706 void sysfs_slab_unlink(struct kmem_cache *s)
9707 {
9708 	if (s->kobj.state_in_sysfs)
9709 		kobject_del(&s->kobj);
9710 }
9711 
9712 void sysfs_slab_release(struct kmem_cache *s)
9713 {
9714 	kobject_put(&s->kobj);
9715 }
9716 
9717 /*
9718  * Need to buffer aliases during bootup until sysfs becomes
9719  * available lest we lose that information.
9720  */
9721 struct saved_alias {
9722 	struct kmem_cache *s;
9723 	const char *name;
9724 	struct saved_alias *next;
9725 };
9726 
9727 static struct saved_alias *alias_list;
9728 
9729 int sysfs_slab_alias(struct kmem_cache *s, const char *name)
9730 {
9731 	struct saved_alias *al;
9732 
9733 	if (slab_state == FULL) {
9734 		/*
9735 		 * If we have a leftover link then remove it.
9736 		 */
9737 		sysfs_remove_link(&slab_kset->kobj, name);
9738 		/*
9739 		 * The original cache may have failed to generate sysfs file.
9740 		 * In that case, sysfs_create_link() returns -ENOENT and
9741 		 * symbolic link creation is skipped.
9742 		 */
9743 		return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
9744 	}
9745 
9746 	al = kmalloc_obj(struct saved_alias);
9747 	if (!al)
9748 		return -ENOMEM;
9749 
9750 	al->s = s;
9751 	al->name = name;
9752 	al->next = alias_list;
9753 	alias_list = al;
9754 	kmsan_unpoison_memory(al, sizeof(*al));
9755 	return 0;
9756 }
9757 
9758 static int __init slab_sysfs_init(void)
9759 {
9760 	struct kmem_cache *s;
9761 	int err;
9762 
9763 	mutex_lock(&slab_mutex);
9764 
9765 	slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
9766 	if (!slab_kset) {
9767 		mutex_unlock(&slab_mutex);
9768 		pr_err("Cannot register slab subsystem.\n");
9769 		return -ENOMEM;
9770 	}
9771 
9772 	slab_state = FULL;
9773 
9774 	list_for_each_entry(s, &slab_caches, list) {
9775 		err = sysfs_slab_add(s);
9776 		if (err)
9777 			pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
9778 			       s->name);
9779 	}
9780 
9781 	while (alias_list) {
9782 		struct saved_alias *al = alias_list;
9783 
9784 		alias_list = alias_list->next;
9785 		err = sysfs_slab_alias(al->s, al->name);
9786 		if (err)
9787 			pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
9788 			       al->name);
9789 		kfree(al);
9790 	}
9791 
9792 	mutex_unlock(&slab_mutex);
9793 	return 0;
9794 }
9795 late_initcall(slab_sysfs_init);
9796 #endif /* SLAB_SUPPORTS_SYSFS */
9797 
9798 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
9799 static int slab_debugfs_show(struct seq_file *seq, void *v)
9800 {
9801 	struct loc_track *t = seq->private;
9802 	struct location *l;
9803 	unsigned long idx;
9804 
9805 	idx = (unsigned long) t->idx;
9806 	if (idx < t->count) {
9807 		l = &t->loc[idx];
9808 
9809 		seq_printf(seq, "%7ld ", l->count);
9810 
9811 		if (l->addr)
9812 			seq_printf(seq, "%pS", (void *)l->addr);
9813 		else
9814 			seq_puts(seq, "<not-available>");
9815 
9816 		if (l->waste)
9817 			seq_printf(seq, " waste=%lu/%lu",
9818 				l->count * l->waste, l->waste);
9819 
9820 		if (l->sum_time != l->min_time) {
9821 			seq_printf(seq, " age=%ld/%llu/%ld",
9822 				l->min_time, div_u64(l->sum_time, l->count),
9823 				l->max_time);
9824 		} else
9825 			seq_printf(seq, " age=%ld", l->min_time);
9826 
9827 		if (l->min_pid != l->max_pid)
9828 			seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
9829 		else
9830 			seq_printf(seq, " pid=%ld",
9831 				l->min_pid);
9832 
9833 		if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
9834 			seq_printf(seq, " cpus=%*pbl",
9835 				 cpumask_pr_args(to_cpumask(l->cpus)));
9836 
9837 		if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
9838 			seq_printf(seq, " nodes=%*pbl",
9839 				 nodemask_pr_args(&l->nodes));
9840 
9841 #ifdef CONFIG_STACKDEPOT
9842 		{
9843 			depot_stack_handle_t handle;
9844 			unsigned long *entries;
9845 			unsigned int nr_entries, j;
9846 
9847 			handle = READ_ONCE(l->handle);
9848 			if (handle) {
9849 				nr_entries = stack_depot_fetch(handle, &entries);
9850 				seq_puts(seq, "\n");
9851 				for (j = 0; j < nr_entries; j++)
9852 					seq_printf(seq, "        %pS\n", (void *)entries[j]);
9853 			}
9854 		}
9855 #endif
9856 		seq_puts(seq, "\n");
9857 	}
9858 
9859 	if (!idx && !t->count)
9860 		seq_puts(seq, "No data\n");
9861 
9862 	return 0;
9863 }
9864 
9865 static void slab_debugfs_stop(struct seq_file *seq, void *v)
9866 {
9867 }
9868 
9869 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
9870 {
9871 	struct loc_track *t = seq->private;
9872 
9873 	t->idx = ++(*ppos);
9874 	if (*ppos <= t->count)
9875 		return ppos;
9876 
9877 	return NULL;
9878 }
9879 
9880 static int cmp_loc_by_count(const void *a, const void *b)
9881 {
9882 	struct location *loc1 = (struct location *)a;
9883 	struct location *loc2 = (struct location *)b;
9884 
9885 	return cmp_int(loc2->count, loc1->count);
9886 }
9887 
9888 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
9889 {
9890 	struct loc_track *t = seq->private;
9891 
9892 	t->idx = *ppos;
9893 	return ppos;
9894 }
9895 
9896 static const struct seq_operations slab_debugfs_sops = {
9897 	.start  = slab_debugfs_start,
9898 	.next   = slab_debugfs_next,
9899 	.stop   = slab_debugfs_stop,
9900 	.show   = slab_debugfs_show,
9901 };
9902 
9903 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
9904 {
9905 
9906 	struct kmem_cache_node *n;
9907 	enum track_item alloc;
9908 	int node;
9909 	struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
9910 						sizeof(struct loc_track));
9911 	struct kmem_cache *s = file_inode(filep)->i_private;
9912 	unsigned long *obj_map;
9913 
9914 	if (!t)
9915 		return -ENOMEM;
9916 
9917 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
9918 	if (!obj_map) {
9919 		seq_release_private(inode, filep);
9920 		return -ENOMEM;
9921 	}
9922 
9923 	alloc = debugfs_get_aux_num(filep);
9924 
9925 	if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
9926 		bitmap_free(obj_map);
9927 		seq_release_private(inode, filep);
9928 		return -ENOMEM;
9929 	}
9930 
9931 	for_each_kmem_cache_node(s, node, n) {
9932 		unsigned long flags;
9933 		struct slab *slab;
9934 
9935 		if (!node_nr_slabs(n))
9936 			continue;
9937 
9938 		spin_lock_irqsave(&n->list_lock, flags);
9939 		list_for_each_entry(slab, &n->partial, slab_list)
9940 			process_slab(t, s, slab, alloc, obj_map);
9941 		list_for_each_entry(slab, &n->full, slab_list)
9942 			process_slab(t, s, slab, alloc, obj_map);
9943 		spin_unlock_irqrestore(&n->list_lock, flags);
9944 	}
9945 
9946 	/* Sort locations by count */
9947 	sort(t->loc, t->count, sizeof(struct location),
9948 	     cmp_loc_by_count, NULL);
9949 
9950 	bitmap_free(obj_map);
9951 	return 0;
9952 }
9953 
9954 static int slab_debug_trace_release(struct inode *inode, struct file *file)
9955 {
9956 	struct seq_file *seq = file->private_data;
9957 	struct loc_track *t = seq->private;
9958 
9959 	free_loc_track(t);
9960 	return seq_release_private(inode, file);
9961 }
9962 
9963 static const struct file_operations slab_debugfs_fops = {
9964 	.open    = slab_debug_trace_open,
9965 	.read    = seq_read,
9966 	.llseek  = seq_lseek,
9967 	.release = slab_debug_trace_release,
9968 };
9969 
9970 static void debugfs_slab_add(struct kmem_cache *s)
9971 {
9972 	struct dentry *slab_cache_dir;
9973 
9974 	if (unlikely(!slab_debugfs_root))
9975 		return;
9976 
9977 	slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
9978 
9979 	debugfs_create_file_aux_num("alloc_traces", 0400, slab_cache_dir, s,
9980 					TRACK_ALLOC, &slab_debugfs_fops);
9981 
9982 	debugfs_create_file_aux_num("free_traces", 0400, slab_cache_dir, s,
9983 					TRACK_FREE, &slab_debugfs_fops);
9984 }
9985 
9986 void debugfs_slab_release(struct kmem_cache *s)
9987 {
9988 	debugfs_lookup_and_remove(s->name, slab_debugfs_root);
9989 }
9990 
9991 static int __init slab_debugfs_init(void)
9992 {
9993 	struct kmem_cache *s;
9994 
9995 	slab_debugfs_root = debugfs_create_dir("slab", NULL);
9996 
9997 	list_for_each_entry(s, &slab_caches, list)
9998 		if (s->flags & SLAB_STORE_USER)
9999 			debugfs_slab_add(s);
10000 
10001 	return 0;
10002 
10003 }
10004 __initcall(slab_debugfs_init);
10005 #endif
10006 /*
10007  * The /proc/slabinfo ABI
10008  */
10009 #ifdef CONFIG_SLUB_DEBUG
10010 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
10011 {
10012 	unsigned long nr_slabs = 0;
10013 	unsigned long nr_objs = 0;
10014 	unsigned long nr_free = 0;
10015 	int node;
10016 	struct kmem_cache_node *n;
10017 
10018 	for_each_kmem_cache_node(s, node, n) {
10019 		nr_slabs += node_nr_slabs(n);
10020 		nr_objs += node_nr_objs(n);
10021 		nr_free += count_partial_free_approx(n);
10022 	}
10023 
10024 	sinfo->active_objs = nr_objs - nr_free;
10025 	sinfo->num_objs = nr_objs;
10026 	sinfo->active_slabs = nr_slabs;
10027 	sinfo->num_slabs = nr_slabs;
10028 	sinfo->objects_per_slab = oo_objects(s->oo);
10029 	sinfo->cache_order = oo_order(s->oo);
10030 }
10031 #endif /* CONFIG_SLUB_DEBUG */
10032