xref: /linux/mm/slub.c (revision d866d5bafc5e1417032255002e95f8ec3121754b)
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, after_rcu_delay))
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_mark_rcu_free_pending(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 	if (unlikely(kasan_slab_pre_free(s, obj, false))) {
6302 		local_unlock(&s->cpu_sheaves->lock);
6303 		goto out;
6304 	}
6305 
6306 	kasan_mark_rcu_free_pending(obj);
6307 
6308 	rcu_sheaf = pcs->rcu_free;
6309 
6310 	/*
6311 	 * Since we flush immediately when size reaches capacity, we never reach
6312 	 * this with size already at capacity, so no OOB write is possible.
6313 	 */
6314 	rcu_sheaf->objects[rcu_sheaf->size++] = obj;
6315 
6316 	if (likely(rcu_sheaf->size < s->sheaf_capacity)) {
6317 		rcu_sheaf = NULL;
6318 	} else {
6319 		pcs->rcu_free = NULL;
6320 		rcu_sheaf->node = numa_node_id();
6321 	}
6322 
6323 	/*
6324 	 * we flush before local_unlock to make sure a racing
6325 	 * flush_all_rcu_sheaves() doesn't miss this sheaf
6326 	 */
6327 	if (rcu_sheaf) {
6328 		/*
6329 		 * With !allow_spin, we might have interrupted call_rcu()'s
6330 		 * IRQ-disabled critical section. If IRQs are not disabled,
6331 		 * we know that's not the case.
6332 		 */
6333 		if (unlikely(!allow_spin && irqs_disabled())) {
6334 			struct deferred_percpu_work *dpw;
6335 
6336 			dpw = this_cpu_ptr(&deferred_percpu_work);
6337 			if (llist_add(&rcu_sheaf->llnode, &dpw->rcu_sheaves))
6338 				irq_work_queue(&dpw->work);
6339 		} else {
6340 			call_rcu(&rcu_sheaf->rcu_head, rcu_free_sheaf);
6341 		}
6342 	}
6343 
6344 	local_unlock(&s->cpu_sheaves->lock);
6345 
6346 	stat(s, FREE_RCU_SHEAF);
6347 out:
6348 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6349 		lock_map_release(&kfree_rcu_sheaf_map);
6350 	return true;
6351 
6352 fail:
6353 	stat(s, FREE_RCU_SHEAF_FAIL);
6354 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
6355 		lock_map_release(&kfree_rcu_sheaf_map);
6356 	return false;
6357 }
6358 
6359 static __always_inline bool can_free_to_pcs(struct slab *slab)
6360 {
6361 	int slab_node;
6362 	int numa_node;
6363 
6364 	if (!IS_ENABLED(CONFIG_NUMA))
6365 		goto check_pfmemalloc;
6366 
6367 	slab_node = slab_nid(slab);
6368 
6369 #ifdef CONFIG_HAVE_MEMORYLESS_NODES
6370 	/*
6371 	 * numa_mem_id() points to the closest node with memory so only allow
6372 	 * objects from that node to the percpu sheaves
6373 	 */
6374 	numa_node = numa_mem_id();
6375 
6376 	if (likely(slab_node == numa_node))
6377 		goto check_pfmemalloc;
6378 #else
6379 
6380 	/*
6381 	 * numa_mem_id() is only a wrapper to numa_node_id() which is where this
6382 	 * cpu belongs to, but it might be a memoryless node anyway. We don't
6383 	 * know what the closest node is.
6384 	 */
6385 	numa_node = numa_node_id();
6386 
6387 	/* freed object is from this cpu's node, proceed */
6388 	if (likely(slab_node == numa_node))
6389 		goto check_pfmemalloc;
6390 
6391 	/*
6392 	 * Freed object isn't from this cpu's node, but that node is memoryless
6393 	 * or only has ZONE_MOVABLE memory, which slab cannot allocate from.
6394 	 * Proceed as it's better to cache remote objects than falling back to
6395 	 * the slowpath for everything. The allocation side can never obtain
6396 	 * a local object anyway, if none exist. We don't have numa_mem_id() to
6397 	 * point to the closest node as we would on a proper memoryless node
6398 	 * setup.
6399 	 */
6400 	if (unlikely(!node_state(numa_node, N_NORMAL_MEMORY)))
6401 		goto check_pfmemalloc;
6402 #endif
6403 
6404 	return false;
6405 
6406 check_pfmemalloc:
6407 	return likely(!slab_test_pfmemalloc(slab));
6408 }
6409 
6410 /*
6411  * Try to free as many objects (already processed by free hooks) as possible to
6412  * a single per-cpu sheaf.
6413  *
6414  * Returns how many objects were freed. Zero means failure and the caller should
6415  * fall back to __kmem_cache_free_bulk().
6416  */
6417 static unsigned int __free_to_pcs_batch(struct kmem_cache *s, size_t size, void **p)
6418 {
6419 	struct slub_percpu_sheaves *pcs;
6420 	struct slab_sheaf *main, *empty;
6421 	struct node_barn *barn;
6422 	unsigned int batch;
6423 
6424 	if (!local_trylock(&s->cpu_sheaves->lock))
6425 		return 0;
6426 
6427 	pcs = this_cpu_ptr(s->cpu_sheaves);
6428 
6429 	if (likely(pcs->main->size < s->sheaf_capacity))
6430 		goto do_free;
6431 
6432 	barn = get_barn(s);
6433 	if (!barn)
6434 		goto no_empty;
6435 
6436 	if (!pcs->spare) {
6437 		empty = barn_get_empty_sheaf(barn, true);
6438 		if (!empty)
6439 			goto no_empty;
6440 
6441 		pcs->spare = pcs->main;
6442 		pcs->main = empty;
6443 		goto do_free;
6444 	}
6445 
6446 	if (pcs->spare->size < s->sheaf_capacity) {
6447 		swap(pcs->main, pcs->spare);
6448 		goto do_free;
6449 	}
6450 
6451 	empty = barn_replace_full_sheaf(barn, pcs->main, true);
6452 	if (IS_ERR(empty)) {
6453 		stat(s, BARN_PUT_FAIL);
6454 		goto no_empty;
6455 	}
6456 
6457 	stat(s, BARN_PUT);
6458 	pcs->main = empty;
6459 
6460 do_free:
6461 	main = pcs->main;
6462 	batch = min(size, s->sheaf_capacity - main->size);
6463 
6464 	memcpy(main->objects + main->size, p, batch * sizeof(void *));
6465 	main->size += batch;
6466 
6467 	local_unlock(&s->cpu_sheaves->lock);
6468 
6469 	stat_add(s, FREE_FASTPATH, batch);
6470 
6471 	return batch;
6472 
6473 no_empty:
6474 	local_unlock(&s->cpu_sheaves->lock);
6475 
6476 	return 0;
6477 }
6478 
6479 /*
6480  * Bulk free objects to the percpu sheaves.
6481  * Unlike free_to_pcs() this includes the calls to all necessary hooks
6482  * and the fallback to freeing to slab pages.
6483  */
6484 static void free_to_pcs_bulk(struct kmem_cache *s, size_t size, void **p)
6485 {
6486 	bool init = slab_want_init_on_free(s);
6487 	void **remote_objects = p;
6488 	unsigned int remote_nr = 0;
6489 
6490 	/*
6491 	 * Process the free hooks and separate out remote objects by
6492 	 * partitioning the 'p' array in place:
6493 	 *
6494 	 * [0, remote_nr) - processed remote objects
6495 	 * [remote_nr, i) - processed local objects
6496 	 * [i, size)      - unprocessed objects
6497 	 */
6498 	for (unsigned int i = 0; i < size;) {
6499 		struct slab *slab = virt_to_slab(p[i]);
6500 
6501 		memcg_slab_free_hook(s, slab, p + i, 1);
6502 		alloc_tagging_slab_free_hook(s, slab, p + i, 1);
6503 
6504 		if (unlikely(!slab_free_hook(s, p[i], init, false))) {
6505 			p[i] = p[--size];
6506 			continue;
6507 		}
6508 
6509 		if (unlikely(!can_free_to_pcs(slab))) {
6510 			if (i != remote_nr)
6511 				swap(remote_objects[remote_nr], p[i]);
6512 			remote_nr++;
6513 		}
6514 
6515 		i++;
6516 	}
6517 
6518 	p += remote_nr;
6519 	size -= remote_nr;
6520 
6521 	while (size) {
6522 		unsigned int batch_freed = __free_to_pcs_batch(s, size, p);
6523 
6524 		if (!batch_freed) {
6525 			__kmem_cache_free_bulk(s, size, p);
6526 			stat_add(s, FREE_SLOWPATH, size);
6527 			break;
6528 		}
6529 
6530 		p += batch_freed;
6531 		size -= batch_freed;
6532 	}
6533 
6534 	/*
6535 	 * Processing remote objects last decreases the chances of cpu migration
6536 	 * while freeing to sheaves and compromising object locality
6537 	 */
6538 	if (remote_nr) {
6539 		__kmem_cache_free_bulk(s, remote_nr, remote_objects);
6540 		stat_add(s, FREE_SLOWPATH, remote_nr);
6541 	}
6542 }
6543 
6544 /*
6545  * In PREEMPT_RT irq_work runs in per-cpu kthread, so it's safe
6546  * to take sleeping spin_locks from __slab_free().
6547  * In !PREEMPT_RT irq_work will run after local_unlock_irqrestore().
6548  */
6549 static void deferred_percpu_work_fn(struct irq_work *work)
6550 {
6551 	struct deferred_percpu_work *dpw;
6552 	struct llist_head *objs, *objs_by_rcu, *rcu_sheaves;
6553 	struct llist_node *llnode, *pos, *t;
6554 	struct slab_sheaf *sheaf, *next;
6555 
6556 	dpw = container_of(work, struct deferred_percpu_work, work);
6557 	rcu_sheaves = &dpw->rcu_sheaves;
6558 	objs = &dpw->objects;
6559 	objs_by_rcu = &dpw->objects_by_rcu;
6560 
6561 	llnode = llist_del_all(objs);
6562 	llist_for_each_safe(pos, t, llnode) {
6563 		struct kmem_cache *s;
6564 		struct slab *slab;
6565 		void *x = pos;
6566 
6567 		slab = virt_to_slab(x);
6568 		s = slab->slab_cache;
6569 
6570 		/* Point 'x' back to the beginning of allocated object */
6571 		x -= s->offset;
6572 
6573 		/*
6574 		 * We used freepointer in 'x' to link 'x' into df->objects.
6575 		 * Clear it to NULL to avoid false positive detection
6576 		 * of "Freepointer corruption".
6577 		 */
6578 		set_freepointer(s, x, NULL);
6579 
6580 		__slab_free(s, slab, x, x, 1, _THIS_IP_);
6581 		stat(s, FREE_SLOWPATH);
6582 	}
6583 
6584 	llnode = llist_del_all(objs_by_rcu);
6585 	llist_for_each_safe(pos, t, llnode) {
6586 		void *head = pos;
6587 		void *objp = kvmalloc_obj_start_addr(head);
6588 
6589 		kvfree_call_rcu(head, objp);
6590 	}
6591 
6592 	llnode = llist_del_all(rcu_sheaves);
6593 	llist_for_each_entry_safe(sheaf, next, llnode, llnode)
6594 		call_rcu(&sheaf->rcu_head, rcu_free_sheaf);
6595 }
6596 
6597 static void defer_free(struct kmem_cache *s, void *head)
6598 {
6599 	struct deferred_percpu_work *dpw;
6600 
6601 	guard(preempt)();
6602 
6603 	head = kasan_reset_tag(head);
6604 
6605 	dpw = this_cpu_ptr(&deferred_percpu_work);
6606 	if (llist_add(head + s->offset, &dpw->objects))
6607 		irq_work_queue(&dpw->work);
6608 }
6609 
6610 void defer_kfree_rcu(struct kvfree_rcu_head *head)
6611 {
6612 	struct deferred_percpu_work *dpw;
6613 
6614 	guard(preempt)();
6615 
6616 	dpw = this_cpu_ptr(&deferred_percpu_work);
6617 	if (llist_add((struct llist_node *)head, &dpw->objects_by_rcu))
6618 		irq_work_queue(&dpw->work);
6619 }
6620 
6621 /* Must be called before flush_rcu_sheaves_on_cache() */
6622 void deferred_work_barrier(void)
6623 {
6624 	int cpu;
6625 
6626 	for_each_possible_cpu(cpu)
6627 		irq_work_sync(&per_cpu_ptr(&deferred_percpu_work, cpu)->work);
6628 }
6629 
6630 static __fastpath_inline
6631 void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
6632 	       unsigned long addr)
6633 {
6634 	memcg_slab_free_hook(s, slab, &object, 1);
6635 	alloc_tagging_slab_free_hook(s, slab, &object, 1);
6636 
6637 	if (unlikely(!slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6638 		return;
6639 
6640 	if (likely(can_free_to_pcs(slab)) && likely(free_to_pcs(s, object, true)))
6641 		return;
6642 
6643 	__slab_free(s, slab, object, object, 1, addr);
6644 	stat(s, FREE_SLOWPATH);
6645 }
6646 
6647 #ifdef CONFIG_MEMCG
6648 /* Do not inline the rare memcg charging failed path into the allocation path */
6649 static noinline
6650 void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
6651 {
6652 	struct slab *slab = virt_to_slab(object);
6653 
6654 	alloc_tagging_slab_free_hook(s, slab, &object, 1);
6655 
6656 	if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6657 		__slab_free(s, slab, object, object, 1, _RET_IP_);
6658 }
6659 #endif
6660 
6661 static __fastpath_inline
6662 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
6663 		    void *tail, void **p, int cnt, unsigned long addr)
6664 {
6665 	memcg_slab_free_hook(s, slab, p, cnt);
6666 	alloc_tagging_slab_free_hook(s, slab, p, cnt);
6667 	/*
6668 	 * With KASAN enabled slab_free_freelist_hook modifies the freelist
6669 	 * to remove objects, whose reuse must be delayed.
6670 	 */
6671 	if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt))) {
6672 		__slab_free(s, slab, head, tail, cnt, addr);
6673 		stat_add(s, FREE_SLOWPATH, cnt);
6674 	}
6675 }
6676 
6677 #ifdef CONFIG_SLUB_RCU_DEBUG
6678 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
6679 {
6680 	struct rcu_delayed_free *delayed_free =
6681 			container_of(rcu_head, struct rcu_delayed_free, head);
6682 	void *object = delayed_free->object;
6683 	struct slab *slab = virt_to_slab(object);
6684 	struct kmem_cache *s;
6685 
6686 	kfree(delayed_free);
6687 
6688 	if (WARN_ON(is_kfence_address(object)))
6689 		return;
6690 
6691 	/* find the object and the cache again */
6692 	if (WARN_ON(!slab))
6693 		return;
6694 	s = slab->slab_cache;
6695 	if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
6696 		return;
6697 
6698 	/* resume freeing */
6699 	if (slab_free_hook(s, object, slab_want_init_on_free(s), true)) {
6700 		__slab_free(s, slab, object, object, 1, _THIS_IP_);
6701 		stat(s, FREE_SLOWPATH);
6702 	}
6703 }
6704 #endif /* CONFIG_SLUB_RCU_DEBUG */
6705 
6706 #ifdef CONFIG_KASAN_GENERIC
6707 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
6708 {
6709 	__slab_free(cache, virt_to_slab(x), x, x, 1, addr);
6710 	stat(cache, FREE_SLOWPATH);
6711 }
6712 #endif
6713 
6714 static noinline void warn_free_bad_obj(struct kmem_cache *s, void *obj)
6715 {
6716 	struct kmem_cache *cachep;
6717 	struct slab *slab;
6718 
6719 	slab = virt_to_slab(obj);
6720 	if (WARN_ONCE(!slab,
6721 			"kmem_cache_free(%s, %p): object is not in a slab page\n",
6722 			s->name, obj))
6723 		return;
6724 
6725 	cachep = slab->slab_cache;
6726 
6727 	if (WARN_ONCE(cachep != s,
6728 			"kmem_cache_free(%s, %p): object belongs to different cache %s\n",
6729 			s->name, obj, cachep ? cachep->name : "(NULL)")) {
6730 		if (cachep)
6731 			print_tracking(cachep, obj);
6732 		return;
6733 	}
6734 }
6735 
6736 /**
6737  * kmem_cache_free - Deallocate an object
6738  * @s: The cache the allocation was from.
6739  * @x: The previously allocated object.
6740  *
6741  * Free an object which was previously allocated from this
6742  * cache.
6743  */
6744 void kmem_cache_free(struct kmem_cache *s, void *x)
6745 {
6746 	struct slab *slab;
6747 
6748 	slab = virt_to_slab(x);
6749 
6750 	if (IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) ||
6751 	    kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
6752 
6753 		/*
6754 		 * Intentionally leak the object in these cases, because it
6755 		 * would be too dangerous to continue.
6756 		 */
6757 		if (unlikely(!slab || (slab->slab_cache != s))) {
6758 			warn_free_bad_obj(s, x);
6759 			return;
6760 		}
6761 	}
6762 
6763 	trace_kmem_cache_free(_RET_IP_, x, s);
6764 	slab_free(s, slab, x, _RET_IP_);
6765 }
6766 EXPORT_SYMBOL(kmem_cache_free);
6767 
6768 static inline size_t slab_ksize(struct slab *slab)
6769 {
6770 	struct kmem_cache *s = slab->slab_cache;
6771 
6772 #ifdef CONFIG_SLUB_DEBUG
6773 	/*
6774 	 * Debugging requires use of the padding between object
6775 	 * and whatever may come after it.
6776 	 */
6777 	if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
6778 		return s->object_size;
6779 #endif
6780 	if (s->flags & SLAB_KASAN)
6781 		return s->object_size;
6782 	/*
6783 	 * If we have the need to store the freelist pointer
6784 	 * or any other metadata back there then we can
6785 	 * only use the space before that information.
6786 	 */
6787 	if (s->flags & (SLAB_TYPESAFE_BY_RCU | SLAB_STORE_USER))
6788 		return s->inuse;
6789 	else if (obj_exts_in_object(slab))
6790 		return s->inuse;
6791 	/*
6792 	 * Else we can use all the padding etc for the allocation
6793 	 */
6794 	return s->size;
6795 }
6796 
6797 static size_t __ksize(const void *object)
6798 {
6799 	struct page *page;
6800 	struct slab *slab;
6801 
6802 	if (unlikely(object == ZERO_SIZE_PTR))
6803 		return 0;
6804 
6805 	page = virt_to_page(object);
6806 
6807 	if (unlikely(PageLargeKmalloc(page)))
6808 		return large_kmalloc_size(page);
6809 
6810 	slab = page_slab(page);
6811 	/* Delete this after we're sure there are no users */
6812 	if (WARN_ON(!slab))
6813 		return page_size(page);
6814 
6815 #ifdef CONFIG_SLUB_DEBUG
6816 	skip_orig_size_check(slab->slab_cache, object);
6817 #endif
6818 
6819 	return slab_ksize(slab);
6820 }
6821 
6822 /**
6823  * ksize -- Report full size of underlying allocation
6824  * @objp: pointer to the object
6825  *
6826  * This should only be used internally to query the true size of allocations.
6827  * It is not meant to be a way to discover the usable size of an allocation
6828  * after the fact. Instead, use kmalloc_size_roundup(). Using memory beyond
6829  * the originally requested allocation size may trigger KASAN, UBSAN_BOUNDS,
6830  * and/or FORTIFY_SOURCE.
6831  *
6832  * Return: size of the actual memory used by @objp in bytes
6833  */
6834 size_t ksize(const void *objp)
6835 {
6836 	/*
6837 	 * We need to first check that the pointer to the object is valid.
6838 	 * The KASAN report printed from ksize() is more useful, then when
6839 	 * it's printed later when the behaviour could be undefined due to
6840 	 * a potential use-after-free or double-free.
6841 	 *
6842 	 * We use kasan_check_byte(), which is supported for the hardware
6843 	 * tag-based KASAN mode, unlike kasan_check_read/write().
6844 	 *
6845 	 * If the pointed to memory is invalid, we return 0 to avoid users of
6846 	 * ksize() writing to and potentially corrupting the memory region.
6847 	 *
6848 	 * We want to perform the check before __ksize(), to avoid potentially
6849 	 * crashing in __ksize() due to accessing invalid metadata.
6850 	 */
6851 	if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
6852 		return 0;
6853 
6854 	return kfence_ksize(objp) ?: __ksize(objp);
6855 }
6856 EXPORT_SYMBOL(ksize);
6857 
6858 static void free_large_kmalloc(struct page *page, void *object)
6859 {
6860 	unsigned int order = compound_order(page);
6861 
6862 	if (WARN_ON_ONCE(!PageLargeKmalloc(page))) {
6863 		dump_page(page, "Not a kmalloc allocation");
6864 		return;
6865 	}
6866 
6867 	if (WARN_ON_ONCE(order == 0))
6868 		pr_warn_once("object pointer: 0x%p\n", object);
6869 
6870 	kmemleak_free(object);
6871 	kasan_kfree_large(object);
6872 	kmsan_kfree_large(object);
6873 
6874 	mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
6875 			      -(PAGE_SIZE << order));
6876 	__ClearPageLargeKmalloc(page);
6877 	free_frozen_pages(page, order);
6878 }
6879 
6880 /*
6881  * Given an rcu_head embedded within an object obtained from kvmalloc at an
6882  * offset < 4k, free the object in question.
6883  */
6884 void kvfree_rcu_cb(struct rcu_head *head)
6885 {
6886 	void *obj;
6887 
6888 	obj = kvmalloc_obj_start_addr(head);
6889 
6890 	if (is_vmalloc_addr(obj)) {
6891 		vfree(obj);
6892 	} else {
6893 		struct page *page = virt_to_page(obj);
6894 		struct slab *slab = page_slab(page);
6895 
6896 		if (slab)
6897 			slab_free(slab->slab_cache, slab, obj, _RET_IP_);
6898 		else
6899 			free_large_kmalloc(page, obj);
6900 	}
6901 }
6902 
6903 /**
6904  * kfree - free previously allocated memory
6905  * @object: pointer returned by kmalloc(), kmalloc_nolock(), or kmem_cache_alloc()
6906  *
6907  * If @object is NULL, no operation is performed.
6908  */
6909 void kfree(const void *object)
6910 {
6911 	struct page *page;
6912 	struct slab *slab;
6913 	struct kmem_cache *s;
6914 	void *x = (void *)object;
6915 
6916 	trace_kfree(_RET_IP_, object);
6917 
6918 	if (unlikely(ZERO_OR_NULL_PTR(object)))
6919 		return;
6920 
6921 	page = virt_to_page(object);
6922 	slab = page_slab(page);
6923 	if (!slab) {
6924 		/* kmalloc_nolock() doesn't support large kmalloc */
6925 		free_large_kmalloc(page, (void *)object);
6926 		return;
6927 	}
6928 
6929 	s = slab->slab_cache;
6930 	slab_free(s, slab, x, _RET_IP_);
6931 }
6932 EXPORT_SYMBOL(kfree);
6933 
6934 /*
6935  * Can be called while holding raw_spinlock_t or from IRQ and NMI,
6936  * but ONLY for objects allocated by kmalloc_nolock().
6937  * Debug checks (like kmemleak and kfence) were skipped on allocation,
6938  * hence
6939  * obj = kmalloc(); kfree_nolock(obj);
6940  * will miss kmemleak/kfence book keeping and will cause false positives.
6941  * large_kmalloc is not supported either.
6942  */
6943 void kfree_nolock(const void *object)
6944 {
6945 	struct slab *slab;
6946 	struct kmem_cache *s;
6947 	void *x = (void *)object;
6948 
6949 	if (unlikely(ZERO_OR_NULL_PTR(object)))
6950 		return;
6951 
6952 	slab = virt_to_slab(object);
6953 	if (unlikely(!slab)) {
6954 		WARN_ONCE(1, "large_kmalloc is not supported by kfree_nolock()");
6955 		return;
6956 	}
6957 
6958 	s = slab->slab_cache;
6959 
6960 	memcg_slab_free_hook(s, slab, &x, 1);
6961 	alloc_tagging_slab_free_hook(s, slab, &x, 1);
6962 	/*
6963 	 * Unlike slab_free() do NOT call the following:
6964 	 * kmemleak_free_recursive(x, s->flags);
6965 	 * debug_check_no_locks_freed(x, s->object_size);
6966 	 * debug_check_no_obj_freed(x, s->object_size);
6967 	 * __kcsan_check_access(x, s->object_size, ..);
6968 	 * kfence_free(x);
6969 	 * since they take spinlocks or not safe from any context.
6970 	 */
6971 	kmsan_slab_free(s, x);
6972 	/*
6973 	 * If KASAN finds a kernel bug it will do kasan_report_invalid_free()
6974 	 * which will call raw_spin_lock_irqsave() which is technically
6975 	 * unsafe from NMI, but take chance and report kernel bug.
6976 	 * The sequence of
6977 	 * kasan_report_invalid_free() -> raw_spin_lock_irqsave() -> NMI
6978 	 *  -> kfree_nolock() -> kasan_report_invalid_free() on the same CPU
6979 	 * is double buggy and deserves to deadlock.
6980 	 */
6981 	if (kasan_slab_pre_free(s, x, false))
6982 		return;
6983 	/*
6984 	 * memcg, kasan_slab_pre_free are done for 'x'.
6985 	 * The only thing left is kasan_poison without quarantine,
6986 	 * since kasan quarantine takes locks and not supported from NMI.
6987 	 */
6988 	kasan_slab_free(s, x, false, false, /* skip quarantine */true);
6989 
6990 	if (likely(can_free_to_pcs(slab)) && likely(free_to_pcs(s, x, false)))
6991 		return;
6992 
6993 	/*
6994 	 * __slab_free() can locklessly cmpxchg16 into a slab, but then it might
6995 	 * need to take spin_lock for further processing.
6996 	 * Avoid the complexity and simply add to a deferred list.
6997 	 */
6998 	defer_free(s, x);
6999 }
7000 EXPORT_SYMBOL_GPL(kfree_nolock);
7001 
7002 static __always_inline __realloc_size(2) void *
7003 __do_krealloc(const void *p, size_t new_size, unsigned long align, gfp_t flags, int nid, kmalloc_token_t token)
7004 {
7005 	void *ret;
7006 	size_t ks = 0;
7007 	int orig_size = 0;
7008 	struct kmem_cache *s = NULL;
7009 
7010 	if (unlikely(ZERO_OR_NULL_PTR(p)))
7011 		goto alloc_new;
7012 
7013 	/* Check for double-free. */
7014 	if (!kasan_check_byte(p))
7015 		return NULL;
7016 
7017 	if (is_kfence_address(p)) {
7018 		ks = orig_size = kfence_ksize(p);
7019 	} else {
7020 		struct page *page = virt_to_page(p);
7021 		struct slab *slab = page_slab(page);
7022 
7023 		if (!slab) {
7024 			/* Big kmalloc object */
7025 			ks = page_size(page);
7026 			WARN_ON(ks <= KMALLOC_MAX_CACHE_SIZE);
7027 			WARN_ON(p != page_address(page));
7028 		} else {
7029 			s = slab->slab_cache;
7030 			orig_size = get_orig_size(s, (void *)p);
7031 			ks = s->object_size;
7032 		}
7033 	}
7034 
7035 	/*
7036 	 * If reallocation is not necessary (e. g. the new size is less
7037 	 * than the current allocated size), the current allocation will be
7038 	 * preserved unless __GFP_THISNODE is set. In the latter case a new
7039 	 * allocation on the requested node will be attempted.
7040 	 */
7041 	if (unlikely(flags & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
7042 		     nid != page_to_nid(virt_to_page(p)))
7043 		goto alloc_new;
7044 
7045 	/* If the old object doesn't fit, allocate a bigger one */
7046 	if (new_size > ks)
7047 		goto alloc_new;
7048 
7049 	/* If the old object doesn't satisfy the new alignment, allocate a new one */
7050 	if (!IS_ALIGNED((unsigned long)p, align))
7051 		goto alloc_new;
7052 
7053 	/* Zero out spare memory. */
7054 	if (want_init_on_alloc(flags)) {
7055 		kasan_disable_current();
7056 		if (orig_size && orig_size < new_size)
7057 			memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size);
7058 		else
7059 			memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
7060 		kasan_enable_current();
7061 	}
7062 
7063 	/* Setup kmalloc redzone when needed */
7064 	if (s && slub_debug_orig_size(s)) {
7065 		set_orig_size(s, (void *)p, new_size);
7066 		if (s->flags & SLAB_RED_ZONE && new_size < ks)
7067 			memset_no_sanitize_memory(kasan_reset_tag(p) + new_size,
7068 						SLUB_RED_ACTIVE, ks - new_size);
7069 	}
7070 
7071 	p = kasan_krealloc(p, new_size, flags);
7072 	return (void *)p;
7073 
7074 alloc_new:
7075 	ret = __kmalloc_node_track_caller_noprof(PASS_KMALLOC_PARAMS(new_size, NULL, token), flags, nid, _RET_IP_);
7076 	if (ret && p) {
7077 		/* Disable KASAN checks as the object's redzone is accessed. */
7078 		kasan_disable_current();
7079 		memcpy(ret, kasan_reset_tag(p), min(new_size, (size_t)(orig_size ?: ks)));
7080 		kasan_enable_current();
7081 	}
7082 
7083 	return ret;
7084 }
7085 
7086 void *krealloc_node_align_noprof(const void *p, DECL_TOKEN_PARAMS(new_size, token), unsigned long align,
7087 				 gfp_t flags, int nid)
7088 {
7089 	void *ret;
7090 
7091 	if (unlikely(!new_size)) {
7092 		kfree(p);
7093 		return ZERO_SIZE_PTR;
7094 	}
7095 
7096 	ret = __do_krealloc(p, new_size, align, flags, nid, PASS_TOKEN_PARAM(token));
7097 	if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
7098 		kfree(p);
7099 
7100 	return ret;
7101 }
7102 EXPORT_SYMBOL(krealloc_node_align_noprof);
7103 
7104 static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
7105 {
7106 	/*
7107 	 * We want to attempt a large physically contiguous block first because
7108 	 * it is less likely to fragment multiple larger blocks and therefore
7109 	 * contribute to a long term fragmentation less than vmalloc fallback.
7110 	 * However make sure that larger requests are not too disruptive - i.e.
7111 	 * do not direct reclaim unless physically continuous memory is preferred
7112 	 * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to
7113 	 * start working in the background
7114 	 */
7115 	if (size > PAGE_SIZE) {
7116 		flags |= __GFP_NOWARN;
7117 
7118 		if (!(flags & __GFP_RETRY_MAYFAIL))
7119 			flags &= ~__GFP_DIRECT_RECLAIM;
7120 
7121 		/* nofail semantic is implemented by the vmalloc fallback */
7122 		flags &= ~__GFP_NOFAIL;
7123 	}
7124 
7125 	return flags;
7126 }
7127 
7128 void *__kvmalloc_node_noprof(DECL_KMALLOC_PARAMS(size, b, token), unsigned long align,
7129 			     gfp_t flags, int node)
7130 {
7131 	bool allow_block;
7132 	void *ret;
7133 	const struct slab_alloc_context ac = {
7134 		.caller_addr = _RET_IP_,
7135 		.orig_size = size,
7136 		.alloc_flags = SLAB_ALLOC_DEFAULT,
7137 	};
7138 
7139 	/*
7140 	 * It doesn't really make sense to fallback to vmalloc for sub page
7141 	 * requests
7142 	 */
7143 	ret = __do_kmalloc_node(PASS_BUCKET_PARAM(b),
7144 				kmalloc_gfp_adjust(flags, size),
7145 				node, PASS_TOKEN_PARAM(token), &ac);
7146 	if (ret || size <= PAGE_SIZE)
7147 		return ret;
7148 
7149 	/* Don't even allow crazy sizes */
7150 	if (unlikely(size > INT_MAX)) {
7151 		WARN_ON_ONCE(!(flags & __GFP_NOWARN));
7152 		return NULL;
7153 	}
7154 
7155 	/*
7156 	 * For non-blocking the VM_ALLOW_HUGE_VMAP is not used
7157 	 * because the huge-mapping path in vmalloc contains at
7158 	 * least one might_sleep() call.
7159 	 *
7160 	 * TODO: Revise huge-mapping path to support non-blocking
7161 	 * flags.
7162 	 */
7163 	allow_block = gfpflags_allow_blocking(flags);
7164 
7165 	/*
7166 	 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP,
7167 	 * since the callers already cannot assume anything
7168 	 * about the resulting pointer, and cannot play
7169 	 * protection games.
7170 	 */
7171 	return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END,
7172 			flags, PAGE_KERNEL, allow_block ? VM_ALLOW_HUGE_VMAP:0,
7173 			node, __builtin_return_address(0));
7174 }
7175 EXPORT_SYMBOL(__kvmalloc_node_noprof);
7176 
7177 /**
7178  * kvfree() - Free memory.
7179  * @addr: Pointer to allocated memory.
7180  *
7181  * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
7182  * It is slightly more efficient to use kfree() or vfree() if you are certain
7183  * that you know which one to use.
7184  *
7185  * Context: Either preemptible task context or not-NMI interrupt.
7186  */
7187 void kvfree(const void *addr)
7188 {
7189 	if (is_vmalloc_addr(addr))
7190 		vfree(addr);
7191 	else
7192 		kfree(addr);
7193 }
7194 EXPORT_SYMBOL(kvfree);
7195 
7196 /**
7197  * kvfree_atomic() - Free memory.
7198  * @addr: Pointer to allocated memory.
7199  *
7200  * Same as kvfree(), but uses vfree_atomic() for vmalloc
7201  * backed memory. Must not be called from NMI context.
7202  */
7203 void kvfree_atomic(const void *addr)
7204 {
7205 	if (is_vmalloc_addr(addr))
7206 		vfree_atomic(addr);
7207 	else
7208 		kfree(addr);
7209 }
7210 EXPORT_SYMBOL(kvfree_atomic);
7211 
7212 /**
7213  * kvfree_sensitive - Free a data object containing sensitive information.
7214  * @addr: address of the data object to be freed.
7215  * @len: length of the data object.
7216  *
7217  * Use the special memzero_explicit() function to clear the content of a
7218  * kvmalloc'ed object containing sensitive data to make sure that the
7219  * compiler won't optimize out the data clearing.
7220  */
7221 void kvfree_sensitive(const void *addr, size_t len)
7222 {
7223 	if (likely(!ZERO_OR_NULL_PTR(addr))) {
7224 		memzero_explicit((void *)addr, len);
7225 		kvfree(addr);
7226 	}
7227 }
7228 EXPORT_SYMBOL(kvfree_sensitive);
7229 
7230 void *kvrealloc_node_align_noprof(const void *p, DECL_TOKEN_PARAMS(size, token), unsigned long align,
7231 				  gfp_t flags, int nid)
7232 {
7233 	void *n;
7234 
7235 	if (is_vmalloc_addr(p))
7236 		return vrealloc_node_align_noprof(p, size, align, flags, nid);
7237 
7238 	n = krealloc_node_align_noprof(p, PASS_TOKEN_PARAMS(size, token), align, kmalloc_gfp_adjust(flags, size), nid);
7239 	if (!n) {
7240 		/* We failed to krealloc(), fall back to kvmalloc(). */
7241 		n = __kvmalloc_node_noprof(PASS_KMALLOC_PARAMS(size, NULL, token), align, flags, nid);
7242 		if (!n)
7243 			return NULL;
7244 
7245 		if (p) {
7246 			/* We already know that `p` is not a vmalloc address. */
7247 			kasan_disable_current();
7248 			memcpy(n, kasan_reset_tag(p), min(size, ksize(p)));
7249 			kasan_enable_current();
7250 
7251 			kfree(p);
7252 		}
7253 	}
7254 
7255 	return n;
7256 }
7257 EXPORT_SYMBOL(kvrealloc_node_align_noprof);
7258 
7259 struct detached_freelist {
7260 	struct slab *slab;
7261 	void *tail;
7262 	void *freelist;
7263 	int cnt;
7264 	struct kmem_cache *s;
7265 };
7266 
7267 /*
7268  * This function progressively scans the array with free objects (with
7269  * a limited look ahead) and extract objects belonging to the same
7270  * slab.  It builds a detached freelist directly within the given
7271  * slab/objects.  This can happen without any need for
7272  * synchronization, because the objects are owned by running process.
7273  * The freelist is build up as a single linked list in the objects.
7274  * The idea is, that this detached freelist can then be bulk
7275  * transferred to the real freelist(s), but only requiring a single
7276  * synchronization primitive.  Look ahead in the array is limited due
7277  * to performance reasons.
7278  */
7279 static inline
7280 int build_detached_freelist(struct kmem_cache *s, size_t size,
7281 			    void **p, struct detached_freelist *df)
7282 {
7283 	int lookahead = 3;
7284 	void *object;
7285 	struct page *page;
7286 	struct slab *slab;
7287 	size_t same;
7288 
7289 	object = p[--size];
7290 	page = virt_to_page(object);
7291 	slab = page_slab(page);
7292 	if (!s) {
7293 		/* Handle kalloc'ed objects */
7294 		if (!slab) {
7295 			free_large_kmalloc(page, object);
7296 			df->slab = NULL;
7297 			return size;
7298 		}
7299 		/* Derive kmem_cache from object */
7300 		df->slab = slab;
7301 		df->s = slab->slab_cache;
7302 	} else {
7303 		df->slab = slab;
7304 		df->s = s;
7305 	}
7306 
7307 	/* Start new detached freelist */
7308 	df->tail = object;
7309 	df->freelist = object;
7310 	df->cnt = 1;
7311 
7312 	if (is_kfence_address(object))
7313 		return size;
7314 
7315 	set_freepointer(df->s, object, NULL);
7316 
7317 	same = size;
7318 	while (size) {
7319 		object = p[--size];
7320 		/* df->slab is always set at this point */
7321 		if (df->slab == virt_to_slab(object)) {
7322 			/* Opportunity build freelist */
7323 			set_freepointer(df->s, object, df->freelist);
7324 			df->freelist = object;
7325 			df->cnt++;
7326 			same--;
7327 			if (size != same)
7328 				swap(p[size], p[same]);
7329 			continue;
7330 		}
7331 
7332 		/* Limit look ahead search */
7333 		if (!--lookahead)
7334 			break;
7335 	}
7336 
7337 	return same;
7338 }
7339 
7340 /*
7341  * Internal bulk free of objects that were not initialised by the post alloc
7342  * hooks and thus should not be processed by the free hooks
7343  */
7344 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7345 {
7346 	if (!size)
7347 		return;
7348 
7349 	do {
7350 		struct detached_freelist df;
7351 
7352 		size = build_detached_freelist(s, size, p, &df);
7353 		if (!df.slab)
7354 			continue;
7355 
7356 		if (kfence_free(df.freelist))
7357 			continue;
7358 
7359 		__slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
7360 			     _RET_IP_);
7361 	} while (likely(size));
7362 }
7363 
7364 /* Note that interrupts must be enabled when calling this function. */
7365 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7366 {
7367 	if (!size)
7368 		return;
7369 
7370 	/*
7371 	 * freeing to sheaves is so incompatible with the detached freelist so
7372 	 * once we go that way, we have to do everything differently
7373 	 */
7374 	if (s && cache_has_sheaves(s)) {
7375 		free_to_pcs_bulk(s, size, p);
7376 		return;
7377 	}
7378 
7379 	do {
7380 		struct detached_freelist df;
7381 
7382 		size = build_detached_freelist(s, size, p, &df);
7383 		if (!df.slab)
7384 			continue;
7385 
7386 		slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
7387 			       df.cnt, _RET_IP_);
7388 	} while (likely(size));
7389 }
7390 EXPORT_SYMBOL(kmem_cache_free_bulk);
7391 
7392 static unsigned int
7393 __refill_objects_node(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7394 		      unsigned int max, struct kmem_cache_node *n,
7395 		      bool allow_spin)
7396 {
7397 	struct partial_bulk_context pc;
7398 	struct slab *slab, *slab2;
7399 	unsigned int refilled = 0;
7400 	unsigned long flags;
7401 	void *object;
7402 
7403 	pc.flags = gfp;
7404 	pc.min_objects = min;
7405 	pc.max_objects = max;
7406 
7407 	if (!get_partial_node_bulk(s, n, &pc, allow_spin))
7408 		return 0;
7409 
7410 	list_for_each_entry_safe(slab, slab2, &pc.slabs, slab_list) {
7411 
7412 		unsigned int count;
7413 
7414 		list_del(&slab->slab_list);
7415 
7416 		object = get_freelist_nofreeze(s, slab, &count);
7417 
7418 		while (count && refilled < max) {
7419 			p[refilled] = object;
7420 			object = get_freepointer(s, object);
7421 			maybe_wipe_obj_freeptr(s, p[refilled]);
7422 
7423 			refilled++;
7424 			count--;
7425 		}
7426 
7427 		/*
7428 		 * Freelist had more objects than we can accommodate, we need to
7429 		 * free them back. First we try to be optimistic and assume the
7430 		 * slab is still full since we just detached its freelist.
7431 		 * Otherwise we must find the tail object.
7432 		 */
7433 		if (unlikely(count)) {
7434 			void *head = object;
7435 			void *tail;
7436 
7437 			if (__slab_try_return_freelist(s, n, slab, head, count))
7438 				break;
7439 
7440 			do {
7441 				tail = object;
7442 				object = get_freepointer(s, object);
7443 			} while (object);
7444 			__slab_free(s, slab, head, tail, count, _RET_IP_);
7445 		}
7446 
7447 		if (refilled >= max)
7448 			break;
7449 	}
7450 
7451 	if (unlikely(!list_empty(&pc.slabs))) {
7452 		spin_lock_irqsave(&n->list_lock, flags);
7453 
7454 		list_for_each_entry(slab, &pc.slabs, slab_list)
7455 			set_node_partial_state(n, slab);
7456 
7457 		list_splice_tail(&pc.slabs, &n->partial);
7458 
7459 		spin_unlock_irqrestore(&n->list_lock, flags);
7460 	}
7461 
7462 	return refilled;
7463 }
7464 
7465 #ifdef CONFIG_NUMA
7466 static unsigned int
7467 __refill_objects_any(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7468 		     unsigned int max)
7469 {
7470 	struct zonelist *zonelist;
7471 	struct zoneref *z;
7472 	struct zone *zone;
7473 	enum zone_type highest_zoneidx = gfp_zone(gfp);
7474 	unsigned int cpuset_mems_cookie;
7475 	unsigned int refilled = 0;
7476 
7477 	/* see get_from_any_partial() for the defrag ratio description */
7478 	if (!s->remote_node_defrag_ratio ||
7479 			get_cycles() % 1024 > s->remote_node_defrag_ratio)
7480 		return 0;
7481 
7482 	do {
7483 		cpuset_mems_cookie = read_mems_allowed_begin();
7484 		zonelist = node_zonelist(mempolicy_slab_node(), gfp);
7485 		for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
7486 			struct kmem_cache_node *n;
7487 			unsigned int r;
7488 
7489 			n = get_node(s, zone_to_nid(zone));
7490 
7491 			if (!n || !cpuset_zone_allowed(zone, gfp) ||
7492 					n->nr_partial <= s->min_partial)
7493 				continue;
7494 
7495 			r = __refill_objects_node(s, p, gfp, min, max, n,
7496 						  /* allow_spin = */ false);
7497 			refilled += r;
7498 
7499 			if (r >= min) {
7500 				/*
7501 				 * Don't check read_mems_allowed_retry() here -
7502 				 * if mems_allowed was updated in parallel, that
7503 				 * was a harmless race between allocation and
7504 				 * the cpuset update
7505 				 */
7506 				return refilled;
7507 			}
7508 			p += r;
7509 			min -= r;
7510 			max -= r;
7511 		}
7512 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
7513 
7514 	return refilled;
7515 }
7516 #else
7517 static inline unsigned int
7518 __refill_objects_any(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7519 		     unsigned int max)
7520 {
7521 	return 0;
7522 }
7523 #endif
7524 
7525 static unsigned int
7526 refill_objects(struct kmem_cache *s, void **p, gfp_t gfp, unsigned int min,
7527 	       unsigned int max)
7528 {
7529 	int local_node = numa_mem_id();
7530 	unsigned int refilled;
7531 	struct slab *slab;
7532 
7533 	refilled = __refill_objects_node(s, p, gfp, min, max,
7534 					 get_node(s, local_node),
7535 					 /* allow_spin = */ true);
7536 	if (refilled >= min)
7537 		return refilled;
7538 
7539 	refilled += __refill_objects_any(s, p + refilled, gfp, min - refilled,
7540 					 max - refilled);
7541 	if (refilled >= min)
7542 		return refilled;
7543 
7544 new_slab:
7545 
7546 	slab = new_slab(s, gfp, SLAB_ALLOC_DEFAULT, local_node);
7547 	if (!slab)
7548 		goto out;
7549 
7550 	stat(s, ALLOC_SLAB);
7551 
7552 	refilled += alloc_from_new_slab(s, slab, p + refilled, max - refilled,
7553 					/* allow_spin = */ true);
7554 
7555 	if (refilled < min)
7556 		goto new_slab;
7557 
7558 out:
7559 	return refilled;
7560 }
7561 
7562 static bool __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
7563 		size_t size, void **p)
7564 {
7565 	int i;
7566 
7567 	if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
7568 		const struct slab_alloc_context ac = {
7569 			.caller_addr = _RET_IP_,
7570 			.orig_size = s->object_size,
7571 			.alloc_flags = SLAB_ALLOC_DEFAULT,
7572 		};
7573 		for (i = 0; i < size; i++) {
7574 
7575 			p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE, &ac);
7576 			if (unlikely(!p[i]))
7577 				goto error;
7578 
7579 			maybe_wipe_obj_freeptr(s, p[i]);
7580 		}
7581 	} else {
7582 		i = refill_objects(s, p, flags, size, size);
7583 		if (i < size)
7584 			goto error;
7585 		stat_add(s, ALLOC_SLOWPATH, i);
7586 	}
7587 
7588 	return true;
7589 
7590 error:
7591 	__kmem_cache_free_bulk(s, i, p);
7592 	return false;
7593 }
7594 
7595 /**
7596  * kmem_cache_alloc_bulk - Allocate multiple objects
7597  * @s:		The cache to allocate from
7598  * @flags:	GFP_* flags. See kmalloc().
7599  * @size:	Number of objects to allocate
7600  * @p:		Array of allocated objects
7601  *
7602  * Allocate @size objects from @s and places them into @p.  @size must be larger
7603  * than 0.
7604  *
7605  * Interrupts must be enabled when calling this function.
7606  *
7607  * Unlike alloc_pages_bulk(), this function does not check for already allocated
7608  * objects in @p, and thus the caller does not need to zero it.
7609  *
7610  * Return: %true if the allocation succeeded, or %false if it failed.
7611  */
7612 bool kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags,
7613 		size_t size, void **p)
7614 {
7615 	unsigned int i = 0;
7616 	void *kfence_obj;
7617 	const struct slab_alloc_context ac = {
7618 		.orig_size = s->object_size,
7619 		.alloc_flags = SLAB_ALLOC_DEFAULT,
7620 	};
7621 
7622 	if (!size)
7623 		return false;
7624 
7625 	s = slab_pre_alloc_hook(s, flags);
7626 	if (unlikely(!s))
7627 		return false;
7628 
7629 	/*
7630 	 * to make things simpler, only assume at most once kfence allocated
7631 	 * object per bulk allocation and choose its index randomly
7632 	 */
7633 	kfence_obj = kfence_alloc(s, s->object_size, flags);
7634 
7635 	if (unlikely(kfence_obj)) {
7636 		if (unlikely(size == 1)) {
7637 			p[0] = kfence_obj;
7638 			goto out;
7639 		}
7640 		size--;
7641 	}
7642 
7643 	i = alloc_from_pcs_bulk(s, size, p);
7644 	if (i < size) {
7645 		/*
7646 		 * If we ran out of memory, don't bother with freeing back to
7647 		 * the percpu sheaves, we have bigger problems.
7648 		 */
7649 		if (unlikely(!__kmem_cache_alloc_bulk(s, flags, size - i,
7650 				p + i))) {
7651 			if (i > 0)
7652 				__kmem_cache_free_bulk(s, i, p);
7653 			if (kfence_obj)
7654 				__kfence_free(kfence_obj);
7655 			return false;
7656 		}
7657 	}
7658 
7659 	if (unlikely(kfence_obj)) {
7660 		int idx = get_random_u32_below(size + 1);
7661 
7662 		if (idx != size)
7663 			p[size] = p[idx];
7664 		p[idx] = kfence_obj;
7665 
7666 		size++;
7667 	}
7668 
7669 out:
7670 	/* memcg and kmem_cache debug support and memory initialization */
7671 	return likely(slab_post_alloc_hook(s, flags, size, p, &ac));
7672 }
7673 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
7674 
7675 /*
7676  * Object placement in a slab is made very easy because we always start at
7677  * offset 0. If we tune the size of the object to the alignment then we can
7678  * get the required alignment by putting one properly sized object after
7679  * another.
7680  *
7681  * Notice that the allocation order determines the sizes of the per cpu
7682  * caches. Each processor has always one slab available for allocations.
7683  * Increasing the allocation order reduces the number of times that slabs
7684  * must be moved on and off the partial lists and is therefore a factor in
7685  * locking overhead.
7686  */
7687 
7688 /*
7689  * Minimum / Maximum order of slab pages. This influences locking overhead
7690  * and slab fragmentation. A higher order reduces the number of partial slabs
7691  * and increases the number of allocations possible without having to
7692  * take the list_lock.
7693  */
7694 static unsigned int slub_min_order;
7695 static unsigned int slub_max_order =
7696 	IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
7697 static unsigned int slub_min_objects;
7698 
7699 /*
7700  * Calculate the order of allocation given an slab object size.
7701  *
7702  * The order of allocation has significant impact on performance and other
7703  * system components. Generally order 0 allocations should be preferred since
7704  * order 0 does not cause fragmentation in the page allocator. Larger objects
7705  * be problematic to put into order 0 slabs because there may be too much
7706  * unused space left. We go to a higher order if more than 1/16th of the slab
7707  * would be wasted.
7708  *
7709  * In order to reach satisfactory performance we must ensure that a minimum
7710  * number of objects is in one slab. Otherwise we may generate too much
7711  * activity on the partial lists which requires taking the list_lock. This is
7712  * less a concern for large slabs though which are rarely used.
7713  *
7714  * slab_max_order specifies the order where we begin to stop considering the
7715  * number of objects in a slab as critical. If we reach slab_max_order then
7716  * we try to keep the page order as low as possible. So we accept more waste
7717  * of space in favor of a small page order.
7718  *
7719  * Higher order allocations also allow the placement of more objects in a
7720  * slab and thereby reduce object handling overhead. If the user has
7721  * requested a higher minimum order then we start with that one instead of
7722  * the smallest order which will fit the object.
7723  */
7724 static inline unsigned int calc_slab_order(unsigned int size,
7725 		unsigned int min_order, unsigned int max_order,
7726 		unsigned int fract_leftover)
7727 {
7728 	unsigned int order;
7729 
7730 	for (order = min_order; order <= max_order; order++) {
7731 
7732 		unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
7733 		unsigned int rem;
7734 
7735 		rem = slab_size % size;
7736 
7737 		if (rem <= slab_size / fract_leftover)
7738 			break;
7739 	}
7740 
7741 	return order;
7742 }
7743 
7744 static inline int calculate_order(unsigned int size)
7745 {
7746 	unsigned int order;
7747 	unsigned int min_objects;
7748 	unsigned int max_objects;
7749 	unsigned int min_order;
7750 
7751 	min_objects = slub_min_objects;
7752 	if (!min_objects) {
7753 		/*
7754 		 * Some architectures will only update present cpus when
7755 		 * onlining them, so don't trust the number if it's just 1. But
7756 		 * we also don't want to use nr_cpu_ids always, as on some other
7757 		 * architectures, there can be many possible cpus, but never
7758 		 * onlined. Here we compromise between trying to avoid too high
7759 		 * order on systems that appear larger than they are, and too
7760 		 * low order on systems that appear smaller than they are.
7761 		 */
7762 		unsigned int nr_cpus = num_present_cpus();
7763 		if (nr_cpus <= 1)
7764 			nr_cpus = nr_cpu_ids;
7765 		min_objects = 4 * (fls(nr_cpus) + 1);
7766 	}
7767 	/* min_objects can't be 0 because get_order(0) is undefined */
7768 	max_objects = max(order_objects(slub_max_order, size), 1U);
7769 	min_objects = min(min_objects, max_objects);
7770 
7771 	min_order = max_t(unsigned int, slub_min_order,
7772 			  get_order(min_objects * size));
7773 	if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
7774 		return get_order(size * MAX_OBJS_PER_PAGE) - 1;
7775 
7776 	/*
7777 	 * Attempt to find best configuration for a slab. This works by first
7778 	 * attempting to generate a layout with the best possible configuration
7779 	 * and backing off gradually.
7780 	 *
7781 	 * We start with accepting at most 1/16 waste and try to find the
7782 	 * smallest order from min_objects-derived/slab_min_order up to
7783 	 * slab_max_order that will satisfy the constraint. Note that increasing
7784 	 * the order can only result in same or less fractional waste, not more.
7785 	 *
7786 	 * If that fails, we increase the acceptable fraction of waste and try
7787 	 * again. The last iteration with fraction of 1/2 would effectively
7788 	 * accept any waste and give us the order determined by min_objects, as
7789 	 * long as at least single object fits within slab_max_order.
7790 	 */
7791 	for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
7792 		order = calc_slab_order(size, min_order, slub_max_order,
7793 					fraction);
7794 		if (order <= slub_max_order)
7795 			return order;
7796 	}
7797 
7798 	/*
7799 	 * Doh this slab cannot be placed using slab_max_order.
7800 	 */
7801 	order = get_order(size);
7802 	if (order <= MAX_PAGE_ORDER)
7803 		return order;
7804 	return -ENOSYS;
7805 }
7806 
7807 static void
7808 init_kmem_cache_node(struct kmem_cache_node *n)
7809 {
7810 	n->nr_partial = 0;
7811 	spin_lock_init(&n->list_lock);
7812 	INIT_LIST_HEAD(&n->partial);
7813 #ifdef CONFIG_SLUB_DEBUG
7814 	atomic_long_set(&n->nr_slabs, 0);
7815 	atomic_long_set(&n->total_objects, 0);
7816 	INIT_LIST_HEAD(&n->full);
7817 #endif
7818 }
7819 
7820 #ifdef CONFIG_SLUB_STATS
7821 static inline int alloc_kmem_cache_stats(struct kmem_cache *s)
7822 {
7823 	BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
7824 			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
7825 			sizeof(struct kmem_cache_stats));
7826 
7827 	s->cpu_stats = alloc_percpu(struct kmem_cache_stats);
7828 
7829 	if (!s->cpu_stats)
7830 		return 0;
7831 
7832 	return 1;
7833 }
7834 #endif
7835 
7836 static int init_percpu_sheaves(struct kmem_cache *s)
7837 {
7838 	static struct slab_sheaf bootstrap_sheaf = {};
7839 	int cpu;
7840 
7841 	for_each_possible_cpu(cpu) {
7842 		struct slub_percpu_sheaves *pcs;
7843 
7844 		pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
7845 
7846 		local_trylock_init(&pcs->lock);
7847 
7848 		/*
7849 		 * Bootstrap sheaf has zero size so fast-path allocation fails.
7850 		 * It has also size == s->sheaf_capacity, so fast-path free
7851 		 * fails. In the slow paths we recognize the situation by
7852 		 * checking s->sheaf_capacity. This allows fast paths to assume
7853 		 * s->cpu_sheaves and pcs->main always exists and are valid.
7854 		 * It's also safe to share the single static bootstrap_sheaf
7855 		 * with zero-sized objects array as it's never modified.
7856 		 *
7857 		 * Bootstrap_sheaf also has NULL pointer to kmem_cache so we
7858 		 * recognize it and not attempt to free it when destroying the
7859 		 * cache.
7860 		 *
7861 		 * We keep bootstrap_sheaf for kmem_cache and kmem_cache_node,
7862 		 * caches with debug enabled, and all caches with SLUB_TINY.
7863 		 * For kmalloc caches it's used temporarily during the initial
7864 		 * bootstrap.
7865 		 */
7866 		if (!s->sheaf_capacity)
7867 			pcs->main = &bootstrap_sheaf;
7868 		else
7869 			pcs->main = alloc_empty_sheaf(s, GFP_KERNEL, SLAB_ALLOC_DEFAULT);
7870 
7871 		if (!pcs->main)
7872 			return -ENOMEM;
7873 	}
7874 
7875 	return 0;
7876 }
7877 
7878 static struct kmem_cache *kmem_cache_node;
7879 
7880 /*
7881  * No kmalloc_node yet so do it by hand. We know that this is the first
7882  * slab on the node for this slabcache. There are no concurrent accesses
7883  * possible.
7884  *
7885  * Note that this function only works on the kmem_cache_node
7886  * when allocating for the kmem_cache_node. This is used for bootstrapping
7887  * memory on a fresh node that has no slab structures yet.
7888  */
7889 static void early_kmem_cache_node_alloc(int node)
7890 {
7891 	struct slab *slab;
7892 	struct kmem_cache_node *n;
7893 	struct slab_obj_iter iter;
7894 
7895 	BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
7896 
7897 	slab = new_slab(kmem_cache_node, GFP_NOWAIT, SLAB_ALLOC_DEFAULT, node);
7898 
7899 	BUG_ON(!slab);
7900 	if (slab_nid(slab) != node) {
7901 		pr_err("SLUB: Unable to allocate memory from node %d\n", node);
7902 		pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
7903 	}
7904 
7905 	init_slab_obj_iter(kmem_cache_node, slab, &iter, true);
7906 
7907 	n = next_slab_obj(kmem_cache_node, &iter);
7908 	BUG_ON(!n);
7909 	set_freepointer(kmem_cache_node, n, NULL);
7910 
7911 	slab->inuse = 1;
7912 	build_slab_freelist(kmem_cache_node, slab, &iter);
7913 
7914 #ifdef CONFIG_SLUB_DEBUG
7915 	init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
7916 #endif
7917 	n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
7918 	kmem_cache_node->per_node[node].node = n;
7919 	init_kmem_cache_node(n);
7920 	inc_slabs_node(kmem_cache_node, node, slab->objects);
7921 
7922 	/*
7923 	 * No locks need to be taken here as it has just been
7924 	 * initialized and there is no concurrent access.
7925 	 */
7926 	__add_partial(n, slab, ADD_TO_HEAD);
7927 }
7928 
7929 static void free_kmem_cache_nodes(struct kmem_cache *s)
7930 {
7931 	int node;
7932 	struct kmem_cache_node *n;
7933 
7934 	for_each_node(node) {
7935 		struct node_barn *barn = get_barn_node(s, node);
7936 
7937 		if (!barn)
7938 			continue;
7939 
7940 		WARN_ON(barn->nr_full);
7941 		WARN_ON(barn->nr_empty);
7942 		kfree(barn);
7943 		s->per_node[node].barn = NULL;
7944 	}
7945 
7946 	for_each_kmem_cache_node(s, node, n) {
7947 		s->per_node[node].node = NULL;
7948 		kmem_cache_free(kmem_cache_node, n);
7949 	}
7950 }
7951 
7952 void __kmem_cache_release(struct kmem_cache *s)
7953 {
7954 	cache_random_seq_destroy(s);
7955 	pcs_destroy(s);
7956 #ifdef CONFIG_SLUB_STATS
7957 	free_percpu(s->cpu_stats);
7958 #endif
7959 	free_kmem_cache_nodes(s);
7960 }
7961 
7962 static int init_kmem_cache_nodes(struct kmem_cache *s)
7963 {
7964 	int node;
7965 
7966 	for_each_node_mask(node, slab_nodes) {
7967 		struct kmem_cache_node *n;
7968 
7969 		if (slab_state == DOWN) {
7970 			early_kmem_cache_node_alloc(node);
7971 			continue;
7972 		}
7973 
7974 		n = kmem_cache_alloc_node(kmem_cache_node,
7975 						GFP_KERNEL, node);
7976 		if (!n)
7977 			return 0;
7978 
7979 		init_kmem_cache_node(n);
7980 		s->per_node[node].node = n;
7981 	}
7982 
7983 	if (slab_state == DOWN || !cache_has_sheaves(s))
7984 		return 1;
7985 
7986 	for_each_node_mask(node, slab_barn_nodes) {
7987 		struct node_barn *barn;
7988 
7989 		barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, node);
7990 
7991 		if (!barn)
7992 			return 0;
7993 
7994 		barn_init(barn);
7995 		s->per_node[node].barn = barn;
7996 	}
7997 
7998 	return 1;
7999 }
8000 
8001 static unsigned int calculate_sheaf_capacity(struct kmem_cache *s,
8002 					     struct kmem_cache_args *args)
8003 
8004 {
8005 	unsigned int capacity;
8006 	size_t size;
8007 
8008 
8009 	if (IS_ENABLED(CONFIG_SLUB_TINY) || s->flags & SLAB_DEBUG_FLAGS)
8010 		return 0;
8011 
8012 	/*
8013 	 * Bootstrap caches can't have sheaves for now (SLAB_NO_SHEAVES).
8014 	 * SLAB_NOLEAKTRACE caches (e.g., kmemleak's object_cache) must not
8015 	 * have sheaves to avoid recursion when sheaf allocation triggers
8016 	 * kmemleak tracking.
8017 	 */
8018 	if (s->flags & (SLAB_NO_SHEAVES | SLAB_NOLEAKTRACE))
8019 		return 0;
8020 
8021 	/*
8022 	 * For now we use roughly similar formula (divided by two as there are
8023 	 * two percpu sheaves) as what was used for percpu partial slabs, which
8024 	 * should result in similar lock contention (barn or list_lock)
8025 	 */
8026 	if (s->size >= PAGE_SIZE)
8027 		capacity = 4;
8028 	else if (s->size >= 1024)
8029 		capacity = 12;
8030 	else if (s->size >= 256)
8031 		capacity = 26;
8032 	else
8033 		capacity = 60;
8034 
8035 	/* Increment capacity to make sheaf exactly a kmalloc size bucket */
8036 	size = struct_size_t(struct slab_sheaf, objects, capacity);
8037 	size = kmalloc_size_roundup(size);
8038 	capacity = (size - struct_size_t(struct slab_sheaf, objects, 0)) / sizeof(void *);
8039 
8040 	/*
8041 	 * Respect an explicit request for capacity that's typically motivated by
8042 	 * expected maximum size of kmem_cache_prefill_sheaf() to not end up
8043 	 * using low-performance oversize sheaves
8044 	 */
8045 	return max(capacity, args->sheaf_capacity);
8046 }
8047 
8048 /*
8049  * calculate_sizes() determines the order and the distribution of data within
8050  * a slab object.
8051  */
8052 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
8053 {
8054 	slab_flags_t flags = s->flags;
8055 	unsigned int size = s->object_size;
8056 	unsigned int aligned_size;
8057 	unsigned int order;
8058 
8059 	/*
8060 	 * Round up object size to the next word boundary. We can only
8061 	 * place the free pointer at word boundaries and this determines
8062 	 * the possible location of the free pointer.
8063 	 */
8064 	size = ALIGN(size, sizeof(void *));
8065 
8066 #ifdef CONFIG_SLUB_DEBUG
8067 	/*
8068 	 * Determine if we can poison the object itself. If the user of
8069 	 * the slab may touch the object after free or before allocation
8070 	 * then we should never poison the object itself.
8071 	 */
8072 	if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
8073 			!s->ctor)
8074 		s->flags |= __OBJECT_POISON;
8075 	else
8076 		s->flags &= ~__OBJECT_POISON;
8077 
8078 
8079 	/*
8080 	 * If we are Redzoning and there is no space between the end of the
8081 	 * object and the following fields, add one word so the right Redzone
8082 	 * is non-empty.
8083 	 */
8084 	if ((flags & SLAB_RED_ZONE) && size == s->object_size)
8085 		size += sizeof(void *);
8086 #endif
8087 
8088 	/*
8089 	 * With that we have determined the number of bytes in actual use
8090 	 * by the object and redzoning.
8091 	 */
8092 	s->inuse = size;
8093 
8094 	if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
8095 	    (flags & SLAB_POISON) ||
8096 	    (s->ctor && !args->use_freeptr_offset) ||
8097 	    ((flags & SLAB_RED_ZONE) &&
8098 	     (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
8099 		/*
8100 		 * Relocate free pointer after the object if it is not
8101 		 * permitted to overwrite the first word of the object on
8102 		 * kmem_cache_free.
8103 		 *
8104 		 * This is the case if we do RCU, have a constructor, are
8105 		 * poisoning the objects, or are redzoning an object smaller
8106 		 * than sizeof(void *) or are redzoning an object with
8107 		 * slub_debug_orig_size() enabled, in which case the right
8108 		 * redzone may be extended.
8109 		 *
8110 		 * The assumption that s->offset >= s->inuse means free
8111 		 * pointer is outside of the object is used in the
8112 		 * freeptr_outside_object() function. If that is no
8113 		 * longer true, the function needs to be modified.
8114 		 */
8115 		s->offset = size;
8116 		size += sizeof(void *);
8117 	} else if (((flags & SLAB_TYPESAFE_BY_RCU) || s->ctor) &&
8118 			args->use_freeptr_offset) {
8119 		s->offset = args->freeptr_offset;
8120 	} else {
8121 		/*
8122 		 * Store freelist pointer near middle of object to keep
8123 		 * it away from the edges of the object to avoid small
8124 		 * sized over/underflows from neighboring allocations.
8125 		 */
8126 		s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
8127 	}
8128 
8129 #ifdef CONFIG_SLUB_DEBUG
8130 	if (flags & SLAB_STORE_USER) {
8131 		/*
8132 		 * Need to store information about allocs and frees after
8133 		 * the object.
8134 		 */
8135 		size += 2 * sizeof(struct track);
8136 
8137 		/* Save the original kmalloc request size */
8138 		if (flags & SLAB_KMALLOC)
8139 			size += sizeof(unsigned long);
8140 	}
8141 #endif
8142 
8143 	kasan_cache_create(s, &size, &s->flags);
8144 #ifdef CONFIG_SLUB_DEBUG
8145 	if (flags & SLAB_RED_ZONE) {
8146 		/*
8147 		 * Add some empty padding so that we can catch
8148 		 * overwrites from earlier objects rather than let
8149 		 * tracking information or the free pointer be
8150 		 * corrupted if a user writes before the start
8151 		 * of the object.
8152 		 */
8153 		size += sizeof(void *);
8154 
8155 		s->red_left_pad = sizeof(void *);
8156 		s->red_left_pad = ALIGN(s->red_left_pad, s->align);
8157 		size += s->red_left_pad;
8158 	}
8159 #endif
8160 
8161 	/*
8162 	 * SLUB stores one object immediately after another beginning from
8163 	 * offset 0. In order to align the objects we have to simply size
8164 	 * each object to conform to the alignment.
8165 	 */
8166 	aligned_size = ALIGN(size, s->align);
8167 #if defined(CONFIG_SLAB_OBJ_EXT) && defined(CONFIG_64BIT)
8168 	if (slab_args_unmergeable(args, s->flags) &&
8169 			(aligned_size - size >= cache_obj_ext_size(s)))
8170 		s->flags |= SLAB_OBJ_EXT_IN_OBJ;
8171 #endif
8172 	size = aligned_size;
8173 
8174 	s->size = size;
8175 	s->reciprocal_size = reciprocal_value(size);
8176 	order = calculate_order(size);
8177 
8178 	if ((int)order < 0)
8179 		return 0;
8180 
8181 	s->allocflags = __GFP_COMP;
8182 
8183 	if (s->flags & SLAB_CACHE_DMA)
8184 		s->allocflags |= GFP_DMA;
8185 
8186 	if (s->flags & SLAB_CACHE_DMA32)
8187 		s->allocflags |= GFP_DMA32;
8188 
8189 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
8190 		s->allocflags |= __GFP_RECLAIMABLE;
8191 
8192 	/*
8193 	 * For kmalloc caches we enable sheaves later by
8194 	 * bootstrap_kmalloc_sheaves() to avoid recursion.
8195 	 */
8196 	if (!is_kmalloc_cache(s))
8197 		s->sheaf_capacity = calculate_sheaf_capacity(s, args);
8198 
8199 	/*
8200 	 * Determine the number of objects per slab
8201 	 */
8202 	s->oo = oo_make(order, size);
8203 	s->min = oo_make(get_order(size), size);
8204 
8205 	return !!oo_objects(s->oo);
8206 }
8207 
8208 static void list_slab_objects(struct kmem_cache *s, struct slab *slab)
8209 {
8210 #ifdef CONFIG_SLUB_DEBUG
8211 	void *addr = slab_address(slab);
8212 	void *p;
8213 
8214 	if (!slab_add_kunit_errors())
8215 		slab_bug(s, "Objects remaining on __kmem_cache_shutdown()");
8216 
8217 	spin_lock(&object_map_lock);
8218 	__fill_map(object_map, s, slab);
8219 
8220 	for_each_object(p, s, addr, slab->objects) {
8221 
8222 		if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
8223 			if (slab_add_kunit_errors())
8224 				continue;
8225 			pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
8226 			print_tracking(s, p);
8227 		}
8228 	}
8229 	spin_unlock(&object_map_lock);
8230 
8231 	__slab_err(slab);
8232 #endif
8233 }
8234 
8235 /*
8236  * Attempt to free all partial slabs on a node.
8237  * This is called from __kmem_cache_shutdown(). We must take list_lock
8238  * because sysfs file might still access partial list after the shutdowning.
8239  */
8240 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
8241 {
8242 	LIST_HEAD(discard);
8243 	struct slab *slab, *h;
8244 
8245 	BUG_ON(irqs_disabled());
8246 	spin_lock_irq(&n->list_lock);
8247 	list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
8248 		if (!slab->inuse) {
8249 			remove_partial(n, slab);
8250 			list_add(&slab->slab_list, &discard);
8251 		} else {
8252 			list_slab_objects(s, slab);
8253 		}
8254 	}
8255 	spin_unlock_irq(&n->list_lock);
8256 
8257 	list_for_each_entry_safe(slab, h, &discard, slab_list)
8258 		discard_slab(s, slab);
8259 }
8260 
8261 bool __kmem_cache_empty(struct kmem_cache *s)
8262 {
8263 	int node;
8264 	struct kmem_cache_node *n;
8265 
8266 	for_each_kmem_cache_node(s, node, n)
8267 		if (n->nr_partial || node_nr_slabs(n))
8268 			return false;
8269 	return true;
8270 }
8271 
8272 /*
8273  * Release all resources used by a slab cache.
8274  */
8275 int __kmem_cache_shutdown(struct kmem_cache *s)
8276 {
8277 	int node;
8278 	struct kmem_cache_node *n;
8279 
8280 	flush_all_cpus_locked(s);
8281 
8282 	/* we might have rcu sheaves in flight */
8283 	if (cache_has_sheaves(s))
8284 		rcu_barrier();
8285 
8286 	for_each_node(node) {
8287 		struct node_barn *barn = get_barn_node(s, node);
8288 
8289 		if (barn)
8290 			barn_shrink(s, barn);
8291 	}
8292 
8293 	/* Attempt to free all objects */
8294 	for_each_kmem_cache_node(s, node, n) {
8295 		free_partial(s, n);
8296 		if (n->nr_partial || node_nr_slabs(n))
8297 			return 1;
8298 	}
8299 	return 0;
8300 }
8301 
8302 #ifdef CONFIG_PRINTK
8303 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
8304 {
8305 	void *base;
8306 	int __maybe_unused i;
8307 	unsigned int objnr;
8308 	void *objp;
8309 	void *objp0;
8310 	struct kmem_cache *s = slab->slab_cache;
8311 	struct track __maybe_unused *trackp;
8312 
8313 	kpp->kp_ptr = object;
8314 	kpp->kp_slab = slab;
8315 	kpp->kp_slab_cache = s;
8316 	base = slab_address(slab);
8317 	objp0 = kasan_reset_tag(object);
8318 #ifdef CONFIG_SLUB_DEBUG
8319 	objp = restore_red_left(s, objp0);
8320 #else
8321 	objp = objp0;
8322 #endif
8323 	objnr = obj_to_index(s, slab, objp);
8324 	kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
8325 	objp = base + s->size * objnr;
8326 	kpp->kp_objp = objp;
8327 	if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
8328 			 || (objp - base) % s->size) ||
8329 	    !(s->flags & SLAB_STORE_USER))
8330 		return;
8331 #ifdef CONFIG_SLUB_DEBUG
8332 	objp = fixup_red_left(s, objp);
8333 	trackp = get_track(s, objp, TRACK_ALLOC);
8334 	kpp->kp_ret = (void *)trackp->addr;
8335 #ifdef CONFIG_STACKDEPOT
8336 	{
8337 		depot_stack_handle_t handle;
8338 		unsigned long *entries;
8339 		unsigned int nr_entries;
8340 
8341 		handle = READ_ONCE(trackp->handle);
8342 		if (handle) {
8343 			nr_entries = stack_depot_fetch(handle, &entries);
8344 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8345 				kpp->kp_stack[i] = (void *)entries[i];
8346 		}
8347 
8348 		trackp = get_track(s, objp, TRACK_FREE);
8349 		handle = READ_ONCE(trackp->handle);
8350 		if (handle) {
8351 			nr_entries = stack_depot_fetch(handle, &entries);
8352 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8353 				kpp->kp_free_stack[i] = (void *)entries[i];
8354 		}
8355 	}
8356 #endif
8357 #endif
8358 }
8359 #endif
8360 
8361 /********************************************************************
8362  *		Kmalloc subsystem
8363  *******************************************************************/
8364 
8365 static int __init setup_slub_min_order(const char *str, const struct kernel_param *kp)
8366 {
8367 	int ret;
8368 
8369 	ret = kstrtouint(str, 0, &slub_min_order);
8370 	if (ret)
8371 		return ret;
8372 
8373 	if (slub_min_order > slub_max_order)
8374 		slub_max_order = slub_min_order;
8375 
8376 	return 0;
8377 }
8378 
8379 static const struct kernel_param_ops param_ops_slab_min_order __initconst = {
8380 	.set = setup_slub_min_order,
8381 };
8382 __core_param_cb(slab_min_order, &param_ops_slab_min_order, &slub_min_order, 0);
8383 __core_param_cb(slub_min_order, &param_ops_slab_min_order, &slub_min_order, 0);
8384 
8385 static int __init setup_slub_max_order(const char *str, const struct kernel_param *kp)
8386 {
8387 	int ret;
8388 
8389 	ret = kstrtouint(str, 0, &slub_max_order);
8390 	if (ret)
8391 		return ret;
8392 
8393 	slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
8394 
8395 	if (slub_min_order > slub_max_order)
8396 		slub_min_order = slub_max_order;
8397 
8398 	return 0;
8399 }
8400 
8401 static const struct kernel_param_ops param_ops_slab_max_order __initconst = {
8402 	.set = setup_slub_max_order,
8403 };
8404 __core_param_cb(slab_max_order, &param_ops_slab_max_order, &slub_max_order, 0);
8405 __core_param_cb(slub_max_order, &param_ops_slab_max_order, &slub_max_order, 0);
8406 
8407 core_param(slab_min_objects, slub_min_objects, uint, 0);
8408 core_param(slub_min_objects, slub_min_objects, uint, 0);
8409 
8410 #ifdef CONFIG_NUMA
8411 static int __init setup_slab_strict_numa(const char *str, const struct kernel_param *kp)
8412 {
8413 	if (nr_node_ids > 1) {
8414 		static_branch_enable(&strict_numa);
8415 		pr_info("SLUB: Strict NUMA enabled.\n");
8416 	} else {
8417 		pr_warn("slab_strict_numa parameter set on non NUMA system.\n");
8418 	}
8419 
8420 	return 0;
8421 }
8422 
8423 static const struct kernel_param_ops param_ops_slab_strict_numa __initconst = {
8424 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
8425 	.set = setup_slab_strict_numa,
8426 };
8427 __core_param_cb(slab_strict_numa, &param_ops_slab_strict_numa, NULL, 0);
8428 #endif
8429 
8430 
8431 #ifdef CONFIG_HARDENED_USERCOPY
8432 /*
8433  * Rejects incorrectly sized objects and objects that are to be copied
8434  * to/from userspace but do not fall entirely within the containing slab
8435  * cache's usercopy region.
8436  *
8437  * Returns NULL if check passes, otherwise const char * to name of cache
8438  * to indicate an error.
8439  */
8440 void __check_heap_object(const void *ptr, unsigned long n,
8441 			 const struct slab *slab, bool to_user)
8442 {
8443 	struct kmem_cache *s;
8444 	unsigned int offset;
8445 	bool is_kfence = is_kfence_address(ptr);
8446 
8447 	ptr = kasan_reset_tag(ptr);
8448 
8449 	/* Find object and usable object size. */
8450 	s = slab->slab_cache;
8451 
8452 	/* Reject impossible pointers. */
8453 	if (ptr < slab_address(slab))
8454 		usercopy_abort("SLUB object not in SLUB page?!", NULL,
8455 			       to_user, 0, n);
8456 
8457 	/* Find offset within object. */
8458 	if (is_kfence)
8459 		offset = ptr - kfence_object_start(ptr);
8460 	else
8461 		offset = (ptr - slab_address(slab)) % s->size;
8462 
8463 	/* Adjust for redzone and reject if within the redzone. */
8464 	if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
8465 		if (offset < s->red_left_pad)
8466 			usercopy_abort("SLUB object in left red zone",
8467 				       s->name, to_user, offset, n);
8468 		offset -= s->red_left_pad;
8469 	}
8470 
8471 	/* Allow address range falling entirely within usercopy region. */
8472 	if (offset >= s->useroffset &&
8473 	    offset - s->useroffset <= s->usersize &&
8474 	    n <= s->useroffset - offset + s->usersize)
8475 		return;
8476 
8477 	usercopy_abort("SLUB object", s->name, to_user, offset, n);
8478 }
8479 #endif /* CONFIG_HARDENED_USERCOPY */
8480 
8481 #define SHRINK_PROMOTE_MAX 32
8482 
8483 /*
8484  * kmem_cache_shrink discards empty slabs and promotes the slabs filled
8485  * up most to the head of the partial lists. New allocations will then
8486  * fill those up and thus they can be removed from the partial lists.
8487  *
8488  * The slabs with the least items are placed last. This results in them
8489  * being allocated from last increasing the chance that the last objects
8490  * are freed in them.
8491  */
8492 static int __kmem_cache_do_shrink(struct kmem_cache *s)
8493 {
8494 	int node;
8495 	int i;
8496 	struct kmem_cache_node *n;
8497 	struct slab *slab;
8498 	struct slab *t;
8499 	struct list_head discard;
8500 	struct list_head promote[SHRINK_PROMOTE_MAX];
8501 	unsigned long flags;
8502 	int ret = 0;
8503 
8504 	for_each_node(node) {
8505 		struct node_barn *barn = get_barn_node(s, node);
8506 
8507 		if (barn)
8508 			barn_shrink(s, barn);
8509 	}
8510 
8511 	for_each_kmem_cache_node(s, node, n) {
8512 		INIT_LIST_HEAD(&discard);
8513 		for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
8514 			INIT_LIST_HEAD(promote + i);
8515 
8516 		spin_lock_irqsave(&n->list_lock, flags);
8517 
8518 		/*
8519 		 * Build lists of slabs to discard or promote.
8520 		 *
8521 		 * Note that concurrent frees may occur while we hold the
8522 		 * list_lock. slab->inuse here is the upper limit.
8523 		 */
8524 		list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
8525 			int free = slab->objects - slab->inuse;
8526 
8527 			/* Do not reread slab->inuse */
8528 			barrier();
8529 
8530 			/* We do not keep full slabs on the list */
8531 			BUG_ON(free <= 0);
8532 
8533 			if (free == slab->objects) {
8534 				list_move(&slab->slab_list, &discard);
8535 				clear_node_partial_state(n, slab);
8536 				dec_slabs_node(s, node, slab->objects);
8537 			} else if (free <= SHRINK_PROMOTE_MAX)
8538 				list_move(&slab->slab_list, promote + free - 1);
8539 		}
8540 
8541 		/*
8542 		 * Promote the slabs filled up most to the head of the
8543 		 * partial list.
8544 		 */
8545 		for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
8546 			list_splice(promote + i, &n->partial);
8547 
8548 		spin_unlock_irqrestore(&n->list_lock, flags);
8549 
8550 		/* Release empty slabs */
8551 		list_for_each_entry_safe(slab, t, &discard, slab_list)
8552 			free_slab(s, slab);
8553 
8554 		if (node_nr_slabs(n))
8555 			ret = 1;
8556 	}
8557 
8558 	return ret;
8559 }
8560 
8561 int __kmem_cache_shrink(struct kmem_cache *s)
8562 {
8563 	flush_all(s);
8564 	return __kmem_cache_do_shrink(s);
8565 }
8566 
8567 static int slab_mem_going_offline_callback(void)
8568 {
8569 	struct kmem_cache *s;
8570 
8571 	mutex_lock(&slab_mutex);
8572 	list_for_each_entry(s, &slab_caches, list) {
8573 		flush_all_cpus_locked(s);
8574 		__kmem_cache_do_shrink(s);
8575 	}
8576 	mutex_unlock(&slab_mutex);
8577 
8578 	return 0;
8579 }
8580 
8581 static int slab_mem_going_online_callback(int nid)
8582 {
8583 	struct kmem_cache_node *n;
8584 	struct kmem_cache *s;
8585 	int ret = 0;
8586 
8587 	/*
8588 	 * We are bringing a node online. No memory is available yet. We must
8589 	 * allocate a kmem_cache_node structure in order to bring the node
8590 	 * online.
8591 	 */
8592 	mutex_lock(&slab_mutex);
8593 	list_for_each_entry(s, &slab_caches, list) {
8594 		struct node_barn *barn = NULL;
8595 
8596 		/*
8597 		 * The structure may already exist if the node was previously
8598 		 * onlined and offlined.
8599 		 */
8600 		if (get_node(s, nid))
8601 			continue;
8602 
8603 		if (cache_has_sheaves(s) && !get_barn_node(s, nid)) {
8604 
8605 			barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, nid);
8606 
8607 			if (!barn) {
8608 				ret = -ENOMEM;
8609 				goto out;
8610 			}
8611 		}
8612 
8613 		/*
8614 		 * XXX: kmem_cache_alloc_node will fallback to other nodes
8615 		 *      since memory is not yet available from the node that
8616 		 *      is brought up.
8617 		 */
8618 		n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
8619 		if (!n) {
8620 			kfree(barn);
8621 			ret = -ENOMEM;
8622 			goto out;
8623 		}
8624 
8625 		init_kmem_cache_node(n);
8626 		s->per_node[nid].node = n;
8627 
8628 		if (barn) {
8629 			barn_init(barn);
8630 			s->per_node[nid].barn = barn;
8631 		}
8632 	}
8633 	/*
8634 	 * Any cache created after this point will also have kmem_cache_node
8635 	 * and barn initialized for the new node.
8636 	 */
8637 	node_set(nid, slab_nodes);
8638 	node_set(nid, slab_barn_nodes);
8639 out:
8640 	mutex_unlock(&slab_mutex);
8641 	return ret;
8642 }
8643 
8644 static int slab_memory_callback(struct notifier_block *self,
8645 				unsigned long action, void *arg)
8646 {
8647 	struct node_notify *nn = arg;
8648 	int nid = nn->nid;
8649 	int ret = 0;
8650 
8651 	switch (action) {
8652 	case NODE_ADDING_FIRST_MEMORY:
8653 		ret = slab_mem_going_online_callback(nid);
8654 		break;
8655 	case NODE_REMOVING_LAST_MEMORY:
8656 		ret = slab_mem_going_offline_callback();
8657 		break;
8658 	}
8659 	if (ret)
8660 		ret = notifier_from_errno(ret);
8661 	else
8662 		ret = NOTIFY_OK;
8663 	return ret;
8664 }
8665 
8666 /********************************************************************
8667  *			Basic setup of slabs
8668  *******************************************************************/
8669 
8670 /*
8671  * Used for early kmem_cache structures that were allocated using
8672  * the page allocator. Allocate them properly then fix up the pointers
8673  * that may be pointing to the wrong kmem_cache structure.
8674  */
8675 
8676 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
8677 {
8678 	int node;
8679 	struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
8680 	struct kmem_cache_node *n;
8681 
8682 	memcpy(s, static_cache, kmem_cache->object_size);
8683 
8684 	for_each_kmem_cache_node(s, node, n) {
8685 		struct slab *p;
8686 
8687 		list_for_each_entry(p, &n->partial, slab_list)
8688 			p->slab_cache = s;
8689 
8690 #ifdef CONFIG_SLUB_DEBUG
8691 		list_for_each_entry(p, &n->full, slab_list)
8692 			p->slab_cache = s;
8693 #endif
8694 	}
8695 	list_add(&s->list, &slab_caches);
8696 	return s;
8697 }
8698 
8699 /*
8700  * Finish the sheaves initialization done normally by init_percpu_sheaves() and
8701  * init_kmem_cache_nodes(). For normal kmalloc caches we have to bootstrap it
8702  * since sheaves and barns are allocated by kmalloc.
8703  */
8704 static void __init bootstrap_cache_sheaves(struct kmem_cache *s)
8705 {
8706 	struct kmem_cache_args empty_args = {};
8707 	unsigned int capacity;
8708 	bool failed = false;
8709 	int node, cpu;
8710 
8711 	VM_WARN_ON_ONCE(cache_has_sheaves(s));
8712 
8713 	capacity = calculate_sheaf_capacity(s, &empty_args);
8714 
8715 	/* capacity can be 0 due to debugging or SLUB_TINY */
8716 	if (!capacity)
8717 		return;
8718 
8719 	for_each_node_mask(node, slab_barn_nodes) {
8720 		struct node_barn *barn;
8721 
8722 		barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, node);
8723 
8724 		if (!barn) {
8725 			failed = true;
8726 			goto out;
8727 		}
8728 
8729 		barn_init(barn);
8730 		s->per_node[node].barn = barn;
8731 	}
8732 
8733 	for_each_possible_cpu(cpu) {
8734 		struct slub_percpu_sheaves *pcs;
8735 
8736 		pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
8737 
8738 		pcs->main = __alloc_empty_sheaf(s, GFP_KERNEL,
8739 				SLAB_ALLOC_DEFAULT, capacity);
8740 
8741 		if (!pcs->main) {
8742 			failed = true;
8743 			break;
8744 		}
8745 	}
8746 
8747 out:
8748 	/*
8749 	 * It's still early in boot so treat this like same as a failure to
8750 	 * create the kmalloc cache in the first place
8751 	 */
8752 	if (failed)
8753 		panic("Out of memory when creating kmem_cache %s\n", s->name);
8754 
8755 	s->sheaf_capacity = capacity;
8756 }
8757 
8758 static void __init bootstrap_kmalloc_sheaves(void)
8759 {
8760 	enum kmalloc_cache_type type;
8761 
8762 	for (type = KMALLOC_NORMAL; type < NR_KMALLOC_TYPES; type++) {
8763 		for (int idx = 0; idx < KMALLOC_SHIFT_HIGH + 1; idx++) {
8764 			struct kmem_cache *s = kmalloc_caches[type][idx];
8765 
8766 			/* Do not bootstrap twice when caches are aliased */
8767 			if (s && !cache_has_sheaves(s))
8768 				bootstrap_cache_sheaves(s);
8769 		}
8770 	}
8771 }
8772 
8773 void __init kmem_cache_init(void)
8774 {
8775 	static __initdata struct kmem_cache boot_kmem_cache,
8776 		boot_kmem_cache_node;
8777 	int node;
8778 
8779 	slab_obj_ext_has_codetag_init();
8780 
8781 	if (debug_guardpage_minorder())
8782 		slub_max_order = 0;
8783 
8784 	/* Inform pointer hashing choice about slub debugging state. */
8785 	hash_pointers_finalize(__slub_debug_enabled());
8786 
8787 	kmem_cache_node = &boot_kmem_cache_node;
8788 	kmem_cache = &boot_kmem_cache;
8789 
8790 	/*
8791 	 * Initialize the nodemask for which we will allocate per node
8792 	 * structures. Here we don't need taking slab_mutex yet.
8793 	 */
8794 	for_each_node_state(node, N_MEMORY)
8795 		node_set(node, slab_nodes);
8796 
8797 	for_each_online_node(node)
8798 		node_set(node, slab_barn_nodes);
8799 
8800 	create_boot_cache(kmem_cache_node, "kmem_cache_node",
8801 			sizeof(struct kmem_cache_node),
8802 			SLAB_HWCACHE_ALIGN | SLAB_NO_SHEAVES | SLAB_NO_OBJ_EXT,
8803 			0, 0);
8804 
8805 	hotplug_node_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
8806 
8807 	/* Able to allocate the per node structures */
8808 	slab_state = PARTIAL;
8809 
8810 	create_boot_cache(kmem_cache, "kmem_cache",
8811 			offsetof(struct kmem_cache, per_node) +
8812 				nr_node_ids * sizeof(struct kmem_cache_per_node_ptrs),
8813 			SLAB_HWCACHE_ALIGN | SLAB_NO_SHEAVES | SLAB_NO_OBJ_EXT,
8814 			0, 0);
8815 
8816 	kmem_cache = bootstrap(&boot_kmem_cache);
8817 	kmem_cache_node = bootstrap(&boot_kmem_cache_node);
8818 
8819 	/* Now we can use the kmem_cache to allocate kmalloc slabs */
8820 	setup_kmalloc_cache_index_table();
8821 	create_kmalloc_caches();
8822 
8823 	bootstrap_kmalloc_sheaves();
8824 
8825 	/* Setup random freelists for each cache */
8826 	init_freelist_randomization();
8827 
8828 	cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", slub_cpu_setup,
8829 				  slub_cpu_dead);
8830 
8831 	pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
8832 		cache_line_size(),
8833 		slub_min_order, slub_max_order, slub_min_objects,
8834 		nr_cpu_ids, nr_node_ids);
8835 }
8836 
8837 void __init kmem_cache_init_late(void)
8838 {
8839 	flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM | WQ_PERCPU,
8840 				  0);
8841 	WARN_ON(!flushwq);
8842 #ifdef CONFIG_SLAB_FREELIST_RANDOM
8843 	prandom_init_once(&slab_rnd_state);
8844 #endif
8845 }
8846 
8847 int do_kmem_cache_create(struct kmem_cache *s, const char *name,
8848 			 unsigned int size, struct kmem_cache_args *args,
8849 			 slab_flags_t flags)
8850 {
8851 	int err = -EINVAL;
8852 
8853 	s->name = name;
8854 	s->size = s->object_size = size;
8855 
8856 	s->flags = kmem_cache_flags(flags, s->name);
8857 #ifdef CONFIG_SLAB_FREELIST_HARDENED
8858 	s->random = get_random_long();
8859 #endif
8860 	s->align = args->align;
8861 	s->ctor = args->ctor;
8862 #ifdef CONFIG_HARDENED_USERCOPY
8863 	s->useroffset = args->useroffset;
8864 	s->usersize = args->usersize;
8865 #endif
8866 
8867 	if (!calculate_sizes(args, s))
8868 		goto out;
8869 	if (disable_higher_order_debug) {
8870 		/*
8871 		 * Disable debugging flags that store metadata if the min slab
8872 		 * order increased.
8873 		 */
8874 		if (get_order(s->size) > get_order(s->object_size)) {
8875 			s->flags &= ~DEBUG_METADATA_FLAGS;
8876 			s->offset = 0;
8877 			if (!calculate_sizes(args, s))
8878 				goto out;
8879 		}
8880 	}
8881 
8882 #ifdef system_has_freelist_aba
8883 	if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
8884 		/* Enable fast mode */
8885 		s->flags |= __CMPXCHG_DOUBLE;
8886 	}
8887 #endif
8888 
8889 	/*
8890 	 * The larger the object size is, the more slabs we want on the partial
8891 	 * list to avoid pounding the page allocator excessively.
8892 	 */
8893 	s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
8894 	s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
8895 
8896 	s->cpu_sheaves = alloc_percpu(struct slub_percpu_sheaves);
8897 	if (!s->cpu_sheaves) {
8898 		err = -ENOMEM;
8899 		goto out;
8900 	}
8901 
8902 #ifdef CONFIG_NUMA
8903 	s->remote_node_defrag_ratio = 1000;
8904 #endif
8905 
8906 	/* Initialize the pre-computed randomized freelist if slab is up */
8907 	if (slab_state >= UP) {
8908 		if (init_cache_random_seq(s))
8909 			goto out;
8910 	}
8911 
8912 	if (!init_kmem_cache_nodes(s))
8913 		goto out;
8914 
8915 #ifdef CONFIG_SLUB_STATS
8916 	if (!alloc_kmem_cache_stats(s))
8917 		goto out;
8918 #endif
8919 
8920 	err = init_percpu_sheaves(s);
8921 	if (err)
8922 		goto out;
8923 
8924 	err = 0;
8925 
8926 	/* Mutex is not taken during early boot */
8927 	if (slab_state <= UP)
8928 		goto out;
8929 
8930 	/*
8931 	 * Failing to create sysfs files is not critical to SLUB functionality.
8932 	 * If it fails, proceed with cache creation without these files.
8933 	 */
8934 	if (sysfs_slab_add(s))
8935 		pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name);
8936 
8937 	if (s->flags & SLAB_STORE_USER)
8938 		debugfs_slab_add(s);
8939 
8940 out:
8941 	if (err)
8942 		__kmem_cache_release(s);
8943 	return err;
8944 }
8945 
8946 #ifdef SLAB_SUPPORTS_SYSFS
8947 static int count_inuse(struct slab *slab)
8948 {
8949 	return slab->inuse;
8950 }
8951 
8952 static int count_total(struct slab *slab)
8953 {
8954 	return slab->objects;
8955 }
8956 #endif
8957 
8958 #ifdef CONFIG_SLUB_DEBUG
8959 static void validate_slab(struct kmem_cache *s, struct slab *slab,
8960 			  unsigned long *obj_map)
8961 {
8962 	void *p;
8963 	void *addr = slab_address(slab);
8964 
8965 	if (!validate_slab_ptr(slab)) {
8966 		slab_err(s, slab, "Not a valid slab page");
8967 		return;
8968 	}
8969 
8970 	if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
8971 		return;
8972 
8973 	/* Now we know that a valid freelist exists */
8974 	__fill_map(obj_map, s, slab);
8975 	for_each_object(p, s, addr, slab->objects) {
8976 		u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
8977 			 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
8978 
8979 		if (!check_object(s, slab, p, val))
8980 			break;
8981 	}
8982 }
8983 
8984 static int validate_slab_node(struct kmem_cache *s,
8985 		struct kmem_cache_node *n, unsigned long *obj_map)
8986 {
8987 	unsigned long count = 0;
8988 	struct slab *slab;
8989 	unsigned long flags;
8990 
8991 	spin_lock_irqsave(&n->list_lock, flags);
8992 
8993 	list_for_each_entry(slab, &n->partial, slab_list) {
8994 		validate_slab(s, slab, obj_map);
8995 		count++;
8996 	}
8997 	if (count != n->nr_partial) {
8998 		pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
8999 		       s->name, count, n->nr_partial);
9000 		slab_add_kunit_errors();
9001 	}
9002 
9003 	if (!(s->flags & SLAB_STORE_USER))
9004 		goto out;
9005 
9006 	list_for_each_entry(slab, &n->full, slab_list) {
9007 		validate_slab(s, slab, obj_map);
9008 		count++;
9009 	}
9010 	if (count != node_nr_slabs(n)) {
9011 		pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
9012 		       s->name, count, node_nr_slabs(n));
9013 		slab_add_kunit_errors();
9014 	}
9015 
9016 out:
9017 	spin_unlock_irqrestore(&n->list_lock, flags);
9018 	return count;
9019 }
9020 
9021 long validate_slab_cache(struct kmem_cache *s)
9022 {
9023 	int node;
9024 	unsigned long count = 0;
9025 	struct kmem_cache_node *n;
9026 	unsigned long *obj_map;
9027 
9028 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
9029 	if (!obj_map)
9030 		return -ENOMEM;
9031 
9032 	flush_all(s);
9033 	for_each_kmem_cache_node(s, node, n)
9034 		count += validate_slab_node(s, n, obj_map);
9035 
9036 	bitmap_free(obj_map);
9037 
9038 	return count;
9039 }
9040 EXPORT_SYMBOL(validate_slab_cache);
9041 
9042 #ifdef CONFIG_DEBUG_FS
9043 /*
9044  * Generate lists of code addresses where slabcache objects are allocated
9045  * and freed.
9046  */
9047 
9048 struct location {
9049 	depot_stack_handle_t handle;
9050 	unsigned long count;
9051 	unsigned long addr;
9052 	unsigned long waste;
9053 	long long sum_time;
9054 	long min_time;
9055 	long max_time;
9056 	long min_pid;
9057 	long max_pid;
9058 	DECLARE_BITMAP(cpus, NR_CPUS);
9059 	nodemask_t nodes;
9060 };
9061 
9062 struct loc_track {
9063 	unsigned long max;
9064 	unsigned long count;
9065 	struct location *loc;
9066 	loff_t idx;
9067 };
9068 
9069 static struct dentry *slab_debugfs_root;
9070 
9071 static void free_loc_track(struct loc_track *t)
9072 {
9073 	if (t->max)
9074 		free_pages((unsigned long)t->loc,
9075 			get_order(sizeof(struct location) * t->max));
9076 }
9077 
9078 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
9079 {
9080 	struct location *l;
9081 	int order;
9082 
9083 	order = get_order(sizeof(struct location) * max);
9084 
9085 	l = (void *)__get_free_pages(flags, order);
9086 	if (!l)
9087 		return 0;
9088 
9089 	if (t->count) {
9090 		memcpy(l, t->loc, sizeof(struct location) * t->count);
9091 		free_loc_track(t);
9092 	}
9093 	t->max = max;
9094 	t->loc = l;
9095 	return 1;
9096 }
9097 
9098 static int add_location(struct loc_track *t, struct kmem_cache *s,
9099 				const struct track *track,
9100 				unsigned int orig_size)
9101 {
9102 	long start, end, pos;
9103 	struct location *l;
9104 	unsigned long caddr, chandle, cwaste;
9105 	unsigned long age = jiffies - track->when;
9106 	depot_stack_handle_t handle = 0;
9107 	unsigned int waste = s->object_size - orig_size;
9108 
9109 #ifdef CONFIG_STACKDEPOT
9110 	handle = READ_ONCE(track->handle);
9111 #endif
9112 	start = -1;
9113 	end = t->count;
9114 
9115 	for ( ; ; ) {
9116 		pos = start + (end - start + 1) / 2;
9117 
9118 		/*
9119 		 * There is nothing at "end". If we end up there
9120 		 * we need to add something to before end.
9121 		 */
9122 		if (pos == end)
9123 			break;
9124 
9125 		l = &t->loc[pos];
9126 		caddr = l->addr;
9127 		chandle = l->handle;
9128 		cwaste = l->waste;
9129 		if ((track->addr == caddr) && (handle == chandle) &&
9130 			(waste == cwaste)) {
9131 
9132 			l->count++;
9133 			if (track->when) {
9134 				l->sum_time += age;
9135 				if (age < l->min_time)
9136 					l->min_time = age;
9137 				if (age > l->max_time)
9138 					l->max_time = age;
9139 
9140 				if (track->pid < l->min_pid)
9141 					l->min_pid = track->pid;
9142 				if (track->pid > l->max_pid)
9143 					l->max_pid = track->pid;
9144 
9145 				cpumask_set_cpu(track->cpu,
9146 						to_cpumask(l->cpus));
9147 			}
9148 			node_set(page_to_nid(virt_to_page(track)), l->nodes);
9149 			return 1;
9150 		}
9151 
9152 		if (track->addr < caddr)
9153 			end = pos;
9154 		else if (track->addr == caddr && handle < chandle)
9155 			end = pos;
9156 		else if (track->addr == caddr && handle == chandle &&
9157 				waste < cwaste)
9158 			end = pos;
9159 		else
9160 			start = pos;
9161 	}
9162 
9163 	/*
9164 	 * Not found. Insert new tracking element.
9165 	 */
9166 	if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
9167 		return 0;
9168 
9169 	l = t->loc + pos;
9170 	if (pos < t->count)
9171 		memmove(l + 1, l,
9172 			(t->count - pos) * sizeof(struct location));
9173 	t->count++;
9174 	l->count = 1;
9175 	l->addr = track->addr;
9176 	l->sum_time = age;
9177 	l->min_time = age;
9178 	l->max_time = age;
9179 	l->min_pid = track->pid;
9180 	l->max_pid = track->pid;
9181 	l->handle = handle;
9182 	l->waste = waste;
9183 	cpumask_clear(to_cpumask(l->cpus));
9184 	cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
9185 	nodes_clear(l->nodes);
9186 	node_set(page_to_nid(virt_to_page(track)), l->nodes);
9187 	return 1;
9188 }
9189 
9190 static void process_slab(struct loc_track *t, struct kmem_cache *s,
9191 		struct slab *slab, enum track_item alloc,
9192 		unsigned long *obj_map)
9193 {
9194 	void *addr = slab_address(slab);
9195 	bool is_alloc = (alloc == TRACK_ALLOC);
9196 	void *p;
9197 
9198 	__fill_map(obj_map, s, slab);
9199 
9200 	for_each_object(p, s, addr, slab->objects)
9201 		if (!test_bit(__obj_to_index(s, addr, p), obj_map))
9202 			add_location(t, s, get_track(s, p, alloc),
9203 				     is_alloc ? get_orig_size(s, p) :
9204 						s->object_size);
9205 }
9206 #endif  /* CONFIG_DEBUG_FS   */
9207 #endif	/* CONFIG_SLUB_DEBUG */
9208 
9209 #ifdef SLAB_SUPPORTS_SYSFS
9210 enum slab_stat_type {
9211 	SL_ALL,			/* All slabs */
9212 	SL_PARTIAL,		/* Only partially allocated slabs */
9213 	SL_OBJECTS,		/* Determine allocated objects not slabs */
9214 	SL_TOTAL		/* Determine object capacity not slabs */
9215 };
9216 
9217 #define SO_ALL		(1 << SL_ALL)
9218 #define SO_PARTIAL	(1 << SL_PARTIAL)
9219 #define SO_OBJECTS	(1 << SL_OBJECTS)
9220 #define SO_TOTAL	(1 << SL_TOTAL)
9221 
9222 static ssize_t show_slab_objects(struct kmem_cache *s,
9223 				 char *buf, unsigned long flags)
9224 {
9225 	unsigned long total = 0;
9226 	int node;
9227 	int x;
9228 	unsigned long *nodes;
9229 	int len = 0;
9230 
9231 	nodes = kzalloc_objs(unsigned long, nr_node_ids);
9232 	if (!nodes)
9233 		return -ENOMEM;
9234 
9235 	/*
9236 	 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
9237 	 * already held which will conflict with an existing lock order:
9238 	 *
9239 	 * mem_hotplug_lock->slab_mutex->kernfs_mutex
9240 	 *
9241 	 * We don't really need mem_hotplug_lock (to hold off
9242 	 * slab_mem_going_offline_callback) here because slab's memory hot
9243 	 * unplug code doesn't destroy the kmem_cache->node[] data.
9244 	 */
9245 
9246 #ifdef CONFIG_SLUB_DEBUG
9247 	if (flags & SO_ALL) {
9248 		struct kmem_cache_node *n;
9249 
9250 		for_each_kmem_cache_node(s, node, n) {
9251 
9252 			if (flags & SO_TOTAL)
9253 				x = node_nr_objs(n);
9254 			else if (flags & SO_OBJECTS)
9255 				x = node_nr_objs(n) - count_partial(n, count_free);
9256 			else
9257 				x = node_nr_slabs(n);
9258 			total += x;
9259 			nodes[node] += x;
9260 		}
9261 
9262 	} else
9263 #endif
9264 	if (flags & SO_PARTIAL) {
9265 		struct kmem_cache_node *n;
9266 
9267 		for_each_kmem_cache_node(s, node, n) {
9268 			if (flags & SO_TOTAL)
9269 				x = count_partial(n, count_total);
9270 			else if (flags & SO_OBJECTS)
9271 				x = count_partial(n, count_inuse);
9272 			else
9273 				x = n->nr_partial;
9274 			total += x;
9275 			nodes[node] += x;
9276 		}
9277 	}
9278 
9279 	len += sysfs_emit_at(buf, len, "%lu", total);
9280 #ifdef CONFIG_NUMA
9281 	for (node = 0; node < nr_node_ids; node++) {
9282 		if (nodes[node])
9283 			len += sysfs_emit_at(buf, len, " N%d=%lu",
9284 					     node, nodes[node]);
9285 	}
9286 #endif
9287 	len += sysfs_emit_at(buf, len, "\n");
9288 	kfree(nodes);
9289 
9290 	return len;
9291 }
9292 
9293 #define to_slab_attr(n) container_of_const(n, struct slab_attribute, attr)
9294 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
9295 
9296 struct slab_attribute {
9297 	struct attribute attr;
9298 	ssize_t (*show)(struct kmem_cache *s, char *buf);
9299 	ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
9300 };
9301 
9302 #define SLAB_ATTR_RO(_name) \
9303 	static const struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
9304 
9305 #define SLAB_ATTR(_name) \
9306 	static const struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
9307 
9308 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
9309 {
9310 	return sysfs_emit(buf, "%u\n", s->size);
9311 }
9312 SLAB_ATTR_RO(slab_size);
9313 
9314 static ssize_t align_show(struct kmem_cache *s, char *buf)
9315 {
9316 	return sysfs_emit(buf, "%u\n", s->align);
9317 }
9318 SLAB_ATTR_RO(align);
9319 
9320 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
9321 {
9322 	return sysfs_emit(buf, "%u\n", s->object_size);
9323 }
9324 SLAB_ATTR_RO(object_size);
9325 
9326 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
9327 {
9328 	return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
9329 }
9330 SLAB_ATTR_RO(objs_per_slab);
9331 
9332 static ssize_t order_show(struct kmem_cache *s, char *buf)
9333 {
9334 	return sysfs_emit(buf, "%u\n", oo_order(s->oo));
9335 }
9336 SLAB_ATTR_RO(order);
9337 
9338 static ssize_t sheaf_capacity_show(struct kmem_cache *s, char *buf)
9339 {
9340 	return sysfs_emit(buf, "%u\n", s->sheaf_capacity);
9341 }
9342 SLAB_ATTR_RO(sheaf_capacity);
9343 
9344 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
9345 {
9346 	return sysfs_emit(buf, "%lu\n", s->min_partial);
9347 }
9348 
9349 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
9350 				 size_t length)
9351 {
9352 	unsigned long min;
9353 	int err;
9354 
9355 	err = kstrtoul(buf, 10, &min);
9356 	if (err)
9357 		return err;
9358 
9359 	s->min_partial = min;
9360 	return length;
9361 }
9362 SLAB_ATTR(min_partial);
9363 
9364 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
9365 {
9366 	return sysfs_emit(buf, "0\n");
9367 }
9368 
9369 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
9370 				 size_t length)
9371 {
9372 	unsigned int objects;
9373 	int err;
9374 
9375 	err = kstrtouint(buf, 10, &objects);
9376 	if (err)
9377 		return err;
9378 	if (objects)
9379 		return -EINVAL;
9380 
9381 	return length;
9382 }
9383 SLAB_ATTR(cpu_partial);
9384 
9385 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
9386 {
9387 	if (!s->ctor)
9388 		return 0;
9389 	return sysfs_emit(buf, "%pS\n", s->ctor);
9390 }
9391 SLAB_ATTR_RO(ctor);
9392 
9393 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
9394 {
9395 	return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
9396 }
9397 SLAB_ATTR_RO(aliases);
9398 
9399 static ssize_t partial_show(struct kmem_cache *s, char *buf)
9400 {
9401 	return show_slab_objects(s, buf, SO_PARTIAL);
9402 }
9403 SLAB_ATTR_RO(partial);
9404 
9405 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
9406 {
9407 	return sysfs_emit(buf, "0\n");
9408 }
9409 SLAB_ATTR_RO(cpu_slabs);
9410 
9411 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
9412 {
9413 	return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
9414 }
9415 SLAB_ATTR_RO(objects_partial);
9416 
9417 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
9418 {
9419 	return sysfs_emit(buf, "0(0)\n");
9420 }
9421 SLAB_ATTR_RO(slabs_cpu_partial);
9422 
9423 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
9424 {
9425 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
9426 }
9427 SLAB_ATTR_RO(reclaim_account);
9428 
9429 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
9430 {
9431 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
9432 }
9433 SLAB_ATTR_RO(hwcache_align);
9434 
9435 #ifdef CONFIG_ZONE_DMA
9436 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
9437 {
9438 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
9439 }
9440 SLAB_ATTR_RO(cache_dma);
9441 #endif
9442 
9443 #ifdef CONFIG_HARDENED_USERCOPY
9444 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
9445 {
9446 	return sysfs_emit(buf, "%u\n", s->usersize);
9447 }
9448 SLAB_ATTR_RO(usersize);
9449 #endif
9450 
9451 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
9452 {
9453 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
9454 }
9455 SLAB_ATTR_RO(destroy_by_rcu);
9456 
9457 #ifdef CONFIG_SLUB_DEBUG
9458 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
9459 {
9460 	return show_slab_objects(s, buf, SO_ALL);
9461 }
9462 SLAB_ATTR_RO(slabs);
9463 
9464 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
9465 {
9466 	return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
9467 }
9468 SLAB_ATTR_RO(total_objects);
9469 
9470 static ssize_t objects_show(struct kmem_cache *s, char *buf)
9471 {
9472 	return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
9473 }
9474 SLAB_ATTR_RO(objects);
9475 
9476 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
9477 {
9478 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
9479 }
9480 SLAB_ATTR_RO(sanity_checks);
9481 
9482 static ssize_t trace_show(struct kmem_cache *s, char *buf)
9483 {
9484 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
9485 }
9486 SLAB_ATTR_RO(trace);
9487 
9488 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
9489 {
9490 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
9491 }
9492 
9493 SLAB_ATTR_RO(red_zone);
9494 
9495 static ssize_t poison_show(struct kmem_cache *s, char *buf)
9496 {
9497 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
9498 }
9499 
9500 SLAB_ATTR_RO(poison);
9501 
9502 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
9503 {
9504 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
9505 }
9506 
9507 SLAB_ATTR_RO(store_user);
9508 
9509 static ssize_t validate_show(struct kmem_cache *s, char *buf)
9510 {
9511 	return 0;
9512 }
9513 
9514 static ssize_t validate_store(struct kmem_cache *s,
9515 			const char *buf, size_t length)
9516 {
9517 	int ret = -EINVAL;
9518 
9519 	if (buf[0] == '1' && kmem_cache_debug(s)) {
9520 		ret = validate_slab_cache(s);
9521 		if (ret >= 0)
9522 			ret = length;
9523 	}
9524 	return ret;
9525 }
9526 SLAB_ATTR(validate);
9527 
9528 #endif /* CONFIG_SLUB_DEBUG */
9529 
9530 #ifdef CONFIG_FAILSLAB
9531 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
9532 {
9533 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
9534 }
9535 
9536 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
9537 				size_t length)
9538 {
9539 	if (s->refcount > 1)
9540 		return -EINVAL;
9541 
9542 	if (buf[0] == '1')
9543 		WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
9544 	else
9545 		WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
9546 
9547 	return length;
9548 }
9549 SLAB_ATTR(failslab);
9550 #endif
9551 
9552 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
9553 {
9554 	return 0;
9555 }
9556 
9557 static ssize_t shrink_store(struct kmem_cache *s,
9558 			const char *buf, size_t length)
9559 {
9560 	if (buf[0] == '1')
9561 		kmem_cache_shrink(s);
9562 	else
9563 		return -EINVAL;
9564 	return length;
9565 }
9566 SLAB_ATTR(shrink);
9567 
9568 #ifdef CONFIG_NUMA
9569 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
9570 {
9571 	return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
9572 }
9573 
9574 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
9575 				const char *buf, size_t length)
9576 {
9577 	unsigned int ratio;
9578 	int err;
9579 
9580 	err = kstrtouint(buf, 10, &ratio);
9581 	if (err)
9582 		return err;
9583 	if (ratio > 100)
9584 		return -ERANGE;
9585 
9586 	s->remote_node_defrag_ratio = ratio * 10;
9587 
9588 	return length;
9589 }
9590 SLAB_ATTR(remote_node_defrag_ratio);
9591 #endif
9592 
9593 #ifdef CONFIG_SLUB_STATS
9594 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
9595 {
9596 	unsigned long sum  = 0;
9597 	int cpu;
9598 	int len = 0;
9599 	int *data = kmalloc_objs(int, nr_cpu_ids);
9600 
9601 	if (!data)
9602 		return -ENOMEM;
9603 
9604 	for_each_online_cpu(cpu) {
9605 		unsigned int x = per_cpu_ptr(s->cpu_stats, cpu)->stat[si];
9606 
9607 		data[cpu] = x;
9608 		sum += x;
9609 	}
9610 
9611 	len += sysfs_emit_at(buf, len, "%lu", sum);
9612 
9613 #ifdef CONFIG_SMP
9614 	for_each_online_cpu(cpu) {
9615 		if (data[cpu])
9616 			len += sysfs_emit_at(buf, len, " C%d=%u",
9617 					     cpu, data[cpu]);
9618 	}
9619 #endif
9620 	kfree(data);
9621 	len += sysfs_emit_at(buf, len, "\n");
9622 
9623 	return len;
9624 }
9625 
9626 static void clear_stat(struct kmem_cache *s, enum stat_item si)
9627 {
9628 	int cpu;
9629 
9630 	for_each_online_cpu(cpu)
9631 		per_cpu_ptr(s->cpu_stats, cpu)->stat[si] = 0;
9632 }
9633 
9634 #define STAT_ATTR(si, text) 					\
9635 static ssize_t text##_show(struct kmem_cache *s, char *buf)	\
9636 {								\
9637 	return show_stat(s, buf, si);				\
9638 }								\
9639 static ssize_t text##_store(struct kmem_cache *s,		\
9640 				const char *buf, size_t length)	\
9641 {								\
9642 	if (buf[0] != '0')					\
9643 		return -EINVAL;					\
9644 	clear_stat(s, si);					\
9645 	return length;						\
9646 }								\
9647 SLAB_ATTR(text);
9648 
9649 #define ITEM_EXP(name, text) STAT_ATTR(name, text)
9650 STAT_ITEMS
9651 #undef ITEM_EXP
9652 
9653 #endif	/* CONFIG_SLUB_STATS */
9654 
9655 #ifdef CONFIG_KFENCE
9656 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
9657 {
9658 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
9659 }
9660 
9661 static ssize_t skip_kfence_store(struct kmem_cache *s,
9662 			const char *buf, size_t length)
9663 {
9664 	int ret = length;
9665 
9666 	if (buf[0] == '0')
9667 		s->flags &= ~SLAB_SKIP_KFENCE;
9668 	else if (buf[0] == '1')
9669 		s->flags |= SLAB_SKIP_KFENCE;
9670 	else
9671 		ret = -EINVAL;
9672 
9673 	return ret;
9674 }
9675 SLAB_ATTR(skip_kfence);
9676 #endif
9677 
9678 static const struct attribute *const slab_attrs[] = {
9679 	&slab_size_attr.attr,
9680 	&object_size_attr.attr,
9681 	&objs_per_slab_attr.attr,
9682 	&order_attr.attr,
9683 	&sheaf_capacity_attr.attr,
9684 	&min_partial_attr.attr,
9685 	&cpu_partial_attr.attr,
9686 	&objects_partial_attr.attr,
9687 	&partial_attr.attr,
9688 	&cpu_slabs_attr.attr,
9689 	&ctor_attr.attr,
9690 	&aliases_attr.attr,
9691 	&align_attr.attr,
9692 	&hwcache_align_attr.attr,
9693 	&reclaim_account_attr.attr,
9694 	&destroy_by_rcu_attr.attr,
9695 	&shrink_attr.attr,
9696 	&slabs_cpu_partial_attr.attr,
9697 #ifdef CONFIG_SLUB_DEBUG
9698 	&total_objects_attr.attr,
9699 	&objects_attr.attr,
9700 	&slabs_attr.attr,
9701 	&sanity_checks_attr.attr,
9702 	&trace_attr.attr,
9703 	&red_zone_attr.attr,
9704 	&poison_attr.attr,
9705 	&store_user_attr.attr,
9706 	&validate_attr.attr,
9707 #endif
9708 #ifdef CONFIG_ZONE_DMA
9709 	&cache_dma_attr.attr,
9710 #endif
9711 #ifdef CONFIG_NUMA
9712 	&remote_node_defrag_ratio_attr.attr,
9713 #endif
9714 #ifdef CONFIG_SLUB_STATS
9715 #define ITEM_EXP(unused, text) &text##_attr.attr,
9716 	STAT_ITEMS
9717 #undef ITEM_EXP
9718 #endif
9719 #ifdef CONFIG_FAILSLAB
9720 	&failslab_attr.attr,
9721 #endif
9722 #ifdef CONFIG_HARDENED_USERCOPY
9723 	&usersize_attr.attr,
9724 #endif
9725 #ifdef CONFIG_KFENCE
9726 	&skip_kfence_attr.attr,
9727 #endif
9728 
9729 	NULL
9730 };
9731 
9732 ATTRIBUTE_GROUPS(slab);
9733 
9734 static ssize_t slab_attr_show(struct kobject *kobj,
9735 				struct attribute *attr,
9736 				char *buf)
9737 {
9738 	const struct slab_attribute *attribute;
9739 	struct kmem_cache *s;
9740 
9741 	attribute = to_slab_attr(attr);
9742 	s = to_slab(kobj);
9743 
9744 	if (!attribute->show)
9745 		return -EIO;
9746 
9747 	return attribute->show(s, buf);
9748 }
9749 
9750 static ssize_t slab_attr_store(struct kobject *kobj,
9751 				struct attribute *attr,
9752 				const char *buf, size_t len)
9753 {
9754 	const struct slab_attribute *attribute;
9755 	struct kmem_cache *s;
9756 
9757 	attribute = to_slab_attr(attr);
9758 	s = to_slab(kobj);
9759 
9760 	if (!attribute->store)
9761 		return -EIO;
9762 
9763 	return attribute->store(s, buf, len);
9764 }
9765 
9766 static void kmem_cache_release(struct kobject *k)
9767 {
9768 	slab_kmem_cache_release(to_slab(k));
9769 }
9770 
9771 static const struct sysfs_ops slab_sysfs_ops = {
9772 	.show = slab_attr_show,
9773 	.store = slab_attr_store,
9774 };
9775 
9776 static const struct kobj_type slab_ktype = {
9777 	.sysfs_ops = &slab_sysfs_ops,
9778 	.release = kmem_cache_release,
9779 	.default_groups = slab_groups,
9780 };
9781 
9782 static struct kset *slab_kset;
9783 
9784 static inline struct kset *cache_kset(struct kmem_cache *s)
9785 {
9786 	return slab_kset;
9787 }
9788 
9789 #define ID_STR_LENGTH 32
9790 
9791 /* Create a unique string id for a slab cache:
9792  *
9793  * Format	:[flags-]size
9794  */
9795 static char *create_unique_id(struct kmem_cache *s)
9796 {
9797 	char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
9798 	char *p = name;
9799 
9800 	if (!name)
9801 		return ERR_PTR(-ENOMEM);
9802 
9803 	*p++ = ':';
9804 	/*
9805 	 * First flags affecting slabcache operations. We will only
9806 	 * get here for aliasable slabs so we do not need to support
9807 	 * too many flags. The flags here must cover all flags that
9808 	 * are matched during merging to guarantee that the id is
9809 	 * unique.
9810 	 */
9811 	if (s->flags & SLAB_CACHE_DMA)
9812 		*p++ = 'd';
9813 	if (s->flags & SLAB_CACHE_DMA32)
9814 		*p++ = 'D';
9815 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
9816 		*p++ = 'a';
9817 	if (s->flags & SLAB_CONSISTENCY_CHECKS)
9818 		*p++ = 'F';
9819 	if (s->flags & SLAB_ACCOUNT)
9820 		*p++ = 'A';
9821 	if (p != name + 1)
9822 		*p++ = '-';
9823 	p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
9824 
9825 	if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
9826 		kfree(name);
9827 		return ERR_PTR(-EINVAL);
9828 	}
9829 	kmsan_unpoison_memory(name, p - name);
9830 	return name;
9831 }
9832 
9833 static int sysfs_slab_add(struct kmem_cache *s)
9834 {
9835 	int err;
9836 	const char *name;
9837 	struct kset *kset = cache_kset(s);
9838 	int unmergeable = slab_unmergeable(s);
9839 
9840 	if (!unmergeable && disable_higher_order_debug &&
9841 			(slub_debug & DEBUG_METADATA_FLAGS))
9842 		unmergeable = 1;
9843 
9844 	if (unmergeable) {
9845 		/*
9846 		 * Slabcache can never be merged so we can use the name proper.
9847 		 * This is typically the case for debug situations. In that
9848 		 * case we can catch duplicate names easily.
9849 		 */
9850 		sysfs_remove_link(&slab_kset->kobj, s->name);
9851 		name = s->name;
9852 	} else {
9853 		/*
9854 		 * Create a unique name for the slab as a target
9855 		 * for the symlinks.
9856 		 */
9857 		name = create_unique_id(s);
9858 		if (IS_ERR(name))
9859 			return PTR_ERR(name);
9860 	}
9861 
9862 	s->kobj.kset = kset;
9863 	err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
9864 	/*
9865 	 * Intentionally skip kobject_put(). See commit 2420baa8e046
9866 	 * ("mm/slab: Allow cache creation to proceed even if sysfs
9867 	 * registration fails")
9868 	 */
9869 	if (err)
9870 		goto out;
9871 
9872 	if (!unmergeable) {
9873 		/* Setup first alias */
9874 		sysfs_slab_alias(s, s->name);
9875 	}
9876 out:
9877 	if (!unmergeable)
9878 		kfree(name);
9879 	return err;
9880 }
9881 
9882 void sysfs_slab_unlink(struct kmem_cache *s)
9883 {
9884 	if (s->kobj.state_in_sysfs)
9885 		kobject_del(&s->kobj);
9886 }
9887 
9888 void sysfs_slab_release(struct kmem_cache *s)
9889 {
9890 	kobject_put(&s->kobj);
9891 }
9892 
9893 /*
9894  * Need to buffer aliases during bootup until sysfs becomes
9895  * available lest we lose that information.
9896  */
9897 struct saved_alias {
9898 	struct kmem_cache *s;
9899 	const char *name;
9900 	struct saved_alias *next;
9901 };
9902 
9903 static struct saved_alias *alias_list;
9904 
9905 int sysfs_slab_alias(struct kmem_cache *s, const char *name)
9906 {
9907 	struct saved_alias *al;
9908 
9909 	if (slab_state == FULL) {
9910 		/*
9911 		 * If we have a leftover link then remove it.
9912 		 */
9913 		sysfs_remove_link(&slab_kset->kobj, name);
9914 		/*
9915 		 * The original cache may have failed to generate sysfs file.
9916 		 * In that case, sysfs_create_link() returns -ENOENT and
9917 		 * symbolic link creation is skipped.
9918 		 */
9919 		return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
9920 	}
9921 
9922 	al = kmalloc_obj(struct saved_alias);
9923 	if (!al)
9924 		return -ENOMEM;
9925 
9926 	al->s = s;
9927 	al->name = name;
9928 	al->next = alias_list;
9929 	alias_list = al;
9930 	kmsan_unpoison_memory(al, sizeof(*al));
9931 	return 0;
9932 }
9933 
9934 static int __init slab_kset_init(void)
9935 {
9936 	slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
9937 	if (!slab_kset) {
9938 		pr_err("Cannot register slab subsystem.\n");
9939 		return -ENOMEM;
9940 	}
9941 
9942 	return 0;
9943 }
9944 
9945 static void __init slab_sysfs_process_aliases(void)
9946 {
9947 	int err;
9948 
9949 	while (alias_list) {
9950 		struct saved_alias *al = alias_list;
9951 
9952 		alias_list = alias_list->next;
9953 		err = sysfs_slab_alias(al->s, al->name);
9954 		if (err)
9955 			pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
9956 			       al->name);
9957 		kfree(al);
9958 	}
9959 }
9960 #endif /* SLAB_SUPPORTS_SYSFS */
9961 
9962 #if defined(SLAB_SUPPORTS_SYSFS) || \
9963 	(defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS))
9964 static int __init slab_late_init(void)
9965 {
9966 	struct kmem_cache *s;
9967 	int err;
9968 
9969 	mutex_lock(&slab_mutex);
9970 
9971 	err = slab_kset_init();
9972 	if (err)
9973 		goto out;
9974 
9975 	slab_debugfs_root_init();
9976 	slab_state = FULL;
9977 
9978 	list_for_each_entry(s, &slab_caches, list) {
9979 		if (sysfs_slab_add(s))
9980 			pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
9981 			       s->name);
9982 
9983 		if (s->flags & SLAB_STORE_USER)
9984 			debugfs_slab_add(s);
9985 	}
9986 
9987 	slab_sysfs_process_aliases();
9988 out:
9989 	mutex_unlock(&slab_mutex);
9990 	return err;
9991 }
9992 late_initcall(slab_late_init);
9993 #endif
9994 
9995 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
9996 static int slab_debugfs_show(struct seq_file *seq, void *v)
9997 {
9998 	struct loc_track *t = seq->private;
9999 	struct location *l;
10000 	unsigned long idx;
10001 
10002 	idx = (unsigned long) t->idx;
10003 	if (idx < t->count) {
10004 		l = &t->loc[idx];
10005 
10006 		seq_printf(seq, "%7ld ", l->count);
10007 
10008 		if (l->addr)
10009 			seq_printf(seq, "%pS", (void *)l->addr);
10010 		else
10011 			seq_puts(seq, "<not-available>");
10012 
10013 		if (l->waste)
10014 			seq_printf(seq, " waste=%lu/%lu",
10015 				l->count * l->waste, l->waste);
10016 
10017 		if (l->sum_time != l->min_time) {
10018 			seq_printf(seq, " age=%ld/%llu/%ld",
10019 				l->min_time, div_u64(l->sum_time, l->count),
10020 				l->max_time);
10021 		} else
10022 			seq_printf(seq, " age=%ld", l->min_time);
10023 
10024 		if (l->min_pid != l->max_pid)
10025 			seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
10026 		else
10027 			seq_printf(seq, " pid=%ld",
10028 				l->min_pid);
10029 
10030 		if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
10031 			seq_printf(seq, " cpus=%*pbl",
10032 				 cpumask_pr_args(to_cpumask(l->cpus)));
10033 
10034 		if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
10035 			seq_printf(seq, " nodes=%*pbl",
10036 				 nodemask_pr_args(&l->nodes));
10037 
10038 #ifdef CONFIG_STACKDEPOT
10039 		{
10040 			depot_stack_handle_t handle;
10041 			unsigned long *entries;
10042 			unsigned int nr_entries, j;
10043 
10044 			handle = READ_ONCE(l->handle);
10045 			if (handle) {
10046 				nr_entries = stack_depot_fetch(handle, &entries);
10047 				seq_puts(seq, "\n");
10048 				for (j = 0; j < nr_entries; j++)
10049 					seq_printf(seq, "        %pS\n", (void *)entries[j]);
10050 			}
10051 		}
10052 #endif
10053 		seq_puts(seq, "\n");
10054 	}
10055 
10056 	if (!idx && !t->count)
10057 		seq_puts(seq, "No data\n");
10058 
10059 	return 0;
10060 }
10061 
10062 static void slab_debugfs_stop(struct seq_file *seq, void *v)
10063 {
10064 }
10065 
10066 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
10067 {
10068 	struct loc_track *t = seq->private;
10069 
10070 	t->idx = ++(*ppos);
10071 	if (*ppos <= t->count)
10072 		return ppos;
10073 
10074 	return NULL;
10075 }
10076 
10077 static int cmp_loc_by_count(const void *a, const void *b)
10078 {
10079 	struct location *loc1 = (struct location *)a;
10080 	struct location *loc2 = (struct location *)b;
10081 
10082 	return cmp_int(loc2->count, loc1->count);
10083 }
10084 
10085 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
10086 {
10087 	struct loc_track *t = seq->private;
10088 
10089 	t->idx = *ppos;
10090 	return ppos;
10091 }
10092 
10093 static const struct seq_operations slab_debugfs_sops = {
10094 	.start  = slab_debugfs_start,
10095 	.next   = slab_debugfs_next,
10096 	.stop   = slab_debugfs_stop,
10097 	.show   = slab_debugfs_show,
10098 };
10099 
10100 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
10101 {
10102 
10103 	struct kmem_cache_node *n;
10104 	enum track_item alloc;
10105 	int node;
10106 	struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
10107 						sizeof(struct loc_track));
10108 	struct kmem_cache *s = file_inode(filep)->i_private;
10109 	unsigned long *obj_map;
10110 
10111 	if (!t)
10112 		return -ENOMEM;
10113 
10114 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
10115 	if (!obj_map) {
10116 		seq_release_private(inode, filep);
10117 		return -ENOMEM;
10118 	}
10119 
10120 	alloc = debugfs_get_aux_num(filep);
10121 
10122 	if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
10123 		bitmap_free(obj_map);
10124 		seq_release_private(inode, filep);
10125 		return -ENOMEM;
10126 	}
10127 
10128 	for_each_kmem_cache_node(s, node, n) {
10129 		unsigned long flags;
10130 		struct slab *slab;
10131 
10132 		if (!node_nr_slabs(n))
10133 			continue;
10134 
10135 		spin_lock_irqsave(&n->list_lock, flags);
10136 		list_for_each_entry(slab, &n->partial, slab_list)
10137 			process_slab(t, s, slab, alloc, obj_map);
10138 		list_for_each_entry(slab, &n->full, slab_list)
10139 			process_slab(t, s, slab, alloc, obj_map);
10140 		spin_unlock_irqrestore(&n->list_lock, flags);
10141 	}
10142 
10143 	/* Sort locations by count */
10144 	sort(t->loc, t->count, sizeof(struct location),
10145 	     cmp_loc_by_count, NULL);
10146 
10147 	bitmap_free(obj_map);
10148 	return 0;
10149 }
10150 
10151 static int slab_debug_trace_release(struct inode *inode, struct file *file)
10152 {
10153 	struct seq_file *seq = file->private_data;
10154 	struct loc_track *t = seq->private;
10155 
10156 	free_loc_track(t);
10157 	return seq_release_private(inode, file);
10158 }
10159 
10160 static const struct file_operations slab_debugfs_fops = {
10161 	.open    = slab_debug_trace_open,
10162 	.read    = seq_read,
10163 	.llseek  = seq_lseek,
10164 	.release = slab_debug_trace_release,
10165 };
10166 
10167 static void debugfs_slab_add(struct kmem_cache *s)
10168 {
10169 	struct dentry *slab_cache_dir;
10170 
10171 	if (unlikely(!slab_debugfs_root))
10172 		return;
10173 
10174 	slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
10175 
10176 	debugfs_create_file_aux_num("alloc_traces", 0400, slab_cache_dir, s,
10177 					TRACK_ALLOC, &slab_debugfs_fops);
10178 
10179 	debugfs_create_file_aux_num("free_traces", 0400, slab_cache_dir, s,
10180 					TRACK_FREE, &slab_debugfs_fops);
10181 }
10182 
10183 void debugfs_slab_release(struct kmem_cache *s)
10184 {
10185 	if (unlikely(!slab_debugfs_root))
10186 		return;
10187 
10188 	debugfs_lookup_and_remove(s->name, slab_debugfs_root);
10189 }
10190 
10191 static void __init slab_debugfs_root_init(void)
10192 {
10193 	slab_debugfs_root = debugfs_create_dir("slab", NULL);
10194 }
10195 #endif
10196 /*
10197  * The /proc/slabinfo ABI
10198  */
10199 #ifdef CONFIG_SLUB_DEBUG
10200 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
10201 {
10202 	unsigned long nr_slabs = 0;
10203 	unsigned long nr_objs = 0;
10204 	unsigned long nr_free = 0;
10205 	int node;
10206 	struct kmem_cache_node *n;
10207 
10208 	for_each_kmem_cache_node(s, node, n) {
10209 		nr_slabs += node_nr_slabs(n);
10210 		nr_objs += node_nr_objs(n);
10211 		nr_free += count_partial_free_approx(n);
10212 	}
10213 
10214 	sinfo->active_objs = nr_objs - nr_free;
10215 	sinfo->num_objs = nr_objs;
10216 	sinfo->active_slabs = nr_slabs;
10217 	sinfo->num_slabs = nr_slabs;
10218 	sinfo->objects_per_slab = oo_objects(s->oo);
10219 	sinfo->cache_order = oo_order(s->oo);
10220 }
10221 #endif /* CONFIG_SLUB_DEBUG */
10222