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