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