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