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