xref: /linux/mm/slub.c (revision beb69e81724634063b9dbae4bc79e2e011fdeeb1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * SLUB: A slab allocator that limits cache line use instead of queuing
4  * objects in per cpu and per node lists.
5  *
6  * The allocator synchronizes using per slab locks or atomic operations
7  * and only uses a centralized lock to manage a pool of partial slabs.
8  *
9  * (C) 2007 SGI, Christoph Lameter
10  * (C) 2011 Linux Foundation, Christoph Lameter
11  */
12 
13 #include <linux/mm.h>
14 #include <linux/swap.h> /* mm_account_reclaimed_pages() */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
21 #include "slab.h"
22 #include <linux/vmalloc.h>
23 #include <linux/proc_fs.h>
24 #include <linux/seq_file.h>
25 #include <linux/kasan.h>
26 #include <linux/node.h>
27 #include <linux/kmsan.h>
28 #include <linux/cpu.h>
29 #include <linux/cpuset.h>
30 #include <linux/mempolicy.h>
31 #include <linux/ctype.h>
32 #include <linux/stackdepot.h>
33 #include <linux/debugobjects.h>
34 #include <linux/kallsyms.h>
35 #include <linux/kfence.h>
36 #include <linux/memory.h>
37 #include <linux/math64.h>
38 #include <linux/fault-inject.h>
39 #include <linux/kmemleak.h>
40 #include <linux/stacktrace.h>
41 #include <linux/prefetch.h>
42 #include <linux/memcontrol.h>
43 #include <linux/random.h>
44 #include <kunit/test.h>
45 #include <kunit/test-bug.h>
46 #include <linux/sort.h>
47 
48 #include <linux/debugfs.h>
49 #include <trace/events/kmem.h>
50 
51 #include "internal.h"
52 
53 /*
54  * Lock order:
55  *   1. slab_mutex (Global Mutex)
56  *   2. node->list_lock (Spinlock)
57  *   3. kmem_cache->cpu_slab->lock (Local lock)
58  *   4. slab_lock(slab) (Only on some arches)
59  *   5. object_map_lock (Only for debugging)
60  *
61  *   slab_mutex
62  *
63  *   The role of the slab_mutex is to protect the list of all the slabs
64  *   and to synchronize major metadata changes to slab cache structures.
65  *   Also synchronizes memory hotplug callbacks.
66  *
67  *   slab_lock
68  *
69  *   The slab_lock is a wrapper around the page lock, thus it is a bit
70  *   spinlock.
71  *
72  *   The slab_lock is only used on arches that do not have the ability
73  *   to do a cmpxchg_double. It only protects:
74  *
75  *	A. slab->freelist	-> List of free objects in a slab
76  *	B. slab->inuse		-> Number of objects in use
77  *	C. slab->objects	-> Number of objects in slab
78  *	D. slab->frozen		-> frozen state
79  *
80  *   Frozen slabs
81  *
82  *   If a slab is frozen then it is exempt from list management. It is
83  *   the cpu slab which is actively allocated from by the processor that
84  *   froze it and it is not on any list. The processor that froze the
85  *   slab is the one who can perform list operations on the slab. Other
86  *   processors may put objects onto the freelist but the processor that
87  *   froze the slab is the only one that can retrieve the objects from the
88  *   slab's freelist.
89  *
90  *   CPU partial slabs
91  *
92  *   The partially empty slabs cached on the CPU partial list are used
93  *   for performance reasons, which speeds up the allocation process.
94  *   These slabs are not frozen, but are also exempt from list management,
95  *   by clearing the PG_workingset flag when moving out of the node
96  *   partial list. Please see __slab_free() for more details.
97  *
98  *   To sum up, the current scheme is:
99  *   - node partial slab: PG_Workingset && !frozen
100  *   - cpu partial slab: !PG_Workingset && !frozen
101  *   - cpu slab: !PG_Workingset && frozen
102  *   - full slab: !PG_Workingset && !frozen
103  *
104  *   list_lock
105  *
106  *   The list_lock protects the partial and full list on each node and
107  *   the partial slab counter. If taken then no new slabs may be added or
108  *   removed from the lists nor make the number of partial slabs be modified.
109  *   (Note that the total number of slabs is an atomic value that may be
110  *   modified without taking the list lock).
111  *
112  *   The list_lock is a centralized lock and thus we avoid taking it as
113  *   much as possible. As long as SLUB does not have to handle partial
114  *   slabs, operations can continue without any centralized lock. F.e.
115  *   allocating a long series of objects that fill up slabs does not require
116  *   the list lock.
117  *
118  *   For debug caches, all allocations are forced to go through a list_lock
119  *   protected region to serialize against concurrent validation.
120  *
121  *   cpu_slab->lock local lock
122  *
123  *   This locks protect slowpath manipulation of all kmem_cache_cpu fields
124  *   except the stat counters. This is a percpu structure manipulated only by
125  *   the local cpu, so the lock protects against being preempted or interrupted
126  *   by an irq. Fast path operations rely on lockless operations instead.
127  *
128  *   On PREEMPT_RT, the local lock neither disables interrupts nor preemption
129  *   which means the lockless fastpath cannot be used as it might interfere with
130  *   an in-progress slow path operations. In this case the local lock is always
131  *   taken but it still utilizes the freelist for the common operations.
132  *
133  *   lockless fastpaths
134  *
135  *   The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
136  *   are fully lockless when satisfied from the percpu slab (and when
137  *   cmpxchg_double is possible to use, otherwise slab_lock is taken).
138  *   They also don't disable preemption or migration or irqs. They rely on
139  *   the transaction id (tid) field to detect being preempted or moved to
140  *   another cpu.
141  *
142  *   irq, preemption, migration considerations
143  *
144  *   Interrupts are disabled as part of list_lock or local_lock operations, or
145  *   around the slab_lock operation, in order to make the slab allocator safe
146  *   to use in the context of an irq.
147  *
148  *   In addition, preemption (or migration on PREEMPT_RT) is disabled in the
149  *   allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
150  *   local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
151  *   doesn't have to be revalidated in each section protected by the local lock.
152  *
153  * SLUB assigns one slab for allocation to each processor.
154  * Allocations only occur from these slabs called cpu slabs.
155  *
156  * Slabs with free elements are kept on a partial list and during regular
157  * operations no list for full slabs is used. If an object in a full slab is
158  * freed then the slab will show up again on the partial lists.
159  * We track full slabs for debugging purposes though because otherwise we
160  * cannot scan all objects.
161  *
162  * Slabs are freed when they become empty. Teardown and setup is
163  * minimal so we rely on the page allocators per cpu caches for
164  * fast frees and allocs.
165  *
166  * slab->frozen		The slab is frozen and exempt from list processing.
167  * 			This means that the slab is dedicated to a purpose
168  * 			such as satisfying allocations for a specific
169  * 			processor. Objects may be freed in the slab while
170  * 			it is frozen but slab_free will then skip the usual
171  * 			list operations. It is up to the processor holding
172  * 			the slab to integrate the slab into the slab lists
173  * 			when the slab is no longer needed.
174  *
175  * 			One use of this flag is to mark slabs that are
176  * 			used for allocations. Then such a slab becomes a cpu
177  * 			slab. The cpu slab may be equipped with an additional
178  * 			freelist that allows lockless access to
179  * 			free objects in addition to the regular freelist
180  * 			that requires the slab lock.
181  *
182  * SLAB_DEBUG_FLAGS	Slab requires special handling due to debug
183  * 			options set. This moves	slab handling out of
184  * 			the fast path and disables lockless freelists.
185  */
186 
187 /*
188  * We could simply use migrate_disable()/enable() but as long as it's a
189  * function call even on !PREEMPT_RT, use inline preempt_disable() there.
190  */
191 #ifndef CONFIG_PREEMPT_RT
192 #define slub_get_cpu_ptr(var)		get_cpu_ptr(var)
193 #define slub_put_cpu_ptr(var)		put_cpu_ptr(var)
194 #define USE_LOCKLESS_FAST_PATH()	(true)
195 #else
196 #define slub_get_cpu_ptr(var)		\
197 ({					\
198 	migrate_disable();		\
199 	this_cpu_ptr(var);		\
200 })
201 #define slub_put_cpu_ptr(var)		\
202 do {					\
203 	(void)(var);			\
204 	migrate_enable();		\
205 } while (0)
206 #define USE_LOCKLESS_FAST_PATH()	(false)
207 #endif
208 
209 #ifndef CONFIG_SLUB_TINY
210 #define __fastpath_inline __always_inline
211 #else
212 #define __fastpath_inline
213 #endif
214 
215 #ifdef CONFIG_SLUB_DEBUG
216 #ifdef CONFIG_SLUB_DEBUG_ON
217 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
218 #else
219 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
220 #endif
221 #endif		/* CONFIG_SLUB_DEBUG */
222 
223 #ifdef CONFIG_NUMA
224 static DEFINE_STATIC_KEY_FALSE(strict_numa);
225 #endif
226 
227 /* Structure holding parameters for get_partial() call chain */
228 struct partial_context {
229 	gfp_t flags;
230 	unsigned int orig_size;
231 	void *object;
232 };
233 
234 static inline bool kmem_cache_debug(struct kmem_cache *s)
235 {
236 	return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
237 }
238 
239 void *fixup_red_left(struct kmem_cache *s, void *p)
240 {
241 	if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
242 		p += s->red_left_pad;
243 
244 	return p;
245 }
246 
247 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
248 {
249 #ifdef CONFIG_SLUB_CPU_PARTIAL
250 	return !kmem_cache_debug(s);
251 #else
252 	return false;
253 #endif
254 }
255 
256 /*
257  * Issues still to be resolved:
258  *
259  * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
260  *
261  * - Variable sizing of the per node arrays
262  */
263 
264 /* Enable to log cmpxchg failures */
265 #undef SLUB_DEBUG_CMPXCHG
266 
267 #ifndef CONFIG_SLUB_TINY
268 /*
269  * Minimum number of partial slabs. These will be left on the partial
270  * lists even if they are empty. kmem_cache_shrink may reclaim them.
271  */
272 #define MIN_PARTIAL 5
273 
274 /*
275  * Maximum number of desirable partial slabs.
276  * The existence of more partial slabs makes kmem_cache_shrink
277  * sort the partial list by the number of objects in use.
278  */
279 #define MAX_PARTIAL 10
280 #else
281 #define MIN_PARTIAL 0
282 #define MAX_PARTIAL 0
283 #endif
284 
285 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
286 				SLAB_POISON | SLAB_STORE_USER)
287 
288 /*
289  * These debug flags cannot use CMPXCHG because there might be consistency
290  * issues when checking or reading debug information
291  */
292 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
293 				SLAB_TRACE)
294 
295 
296 /*
297  * Debugging flags that require metadata to be stored in the slab.  These get
298  * disabled when slab_debug=O is used and a cache's min order increases with
299  * metadata.
300  */
301 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
302 
303 #define OO_SHIFT	16
304 #define OO_MASK		((1 << OO_SHIFT) - 1)
305 #define MAX_OBJS_PER_PAGE	32767 /* since slab.objects is u15 */
306 
307 /* Internal SLUB flags */
308 /* Poison object */
309 #define __OBJECT_POISON		__SLAB_FLAG_BIT(_SLAB_OBJECT_POISON)
310 /* Use cmpxchg_double */
311 
312 #ifdef system_has_freelist_aba
313 #define __CMPXCHG_DOUBLE	__SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE)
314 #else
315 #define __CMPXCHG_DOUBLE	__SLAB_FLAG_UNUSED
316 #endif
317 
318 /*
319  * Tracking user of a slab.
320  */
321 #define TRACK_ADDRS_COUNT 16
322 struct track {
323 	unsigned long addr;	/* Called from address */
324 #ifdef CONFIG_STACKDEPOT
325 	depot_stack_handle_t handle;
326 #endif
327 	int cpu;		/* Was running on cpu */
328 	int pid;		/* Pid context */
329 	unsigned long when;	/* When did the operation occur */
330 };
331 
332 enum track_item { TRACK_ALLOC, TRACK_FREE };
333 
334 #ifdef SLAB_SUPPORTS_SYSFS
335 static int sysfs_slab_add(struct kmem_cache *);
336 static int sysfs_slab_alias(struct kmem_cache *, const char *);
337 #else
338 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
339 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
340 							{ return 0; }
341 #endif
342 
343 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
344 static void debugfs_slab_add(struct kmem_cache *);
345 #else
346 static inline void debugfs_slab_add(struct kmem_cache *s) { }
347 #endif
348 
349 enum stat_item {
350 	ALLOC_FASTPATH,		/* Allocation from cpu slab */
351 	ALLOC_SLOWPATH,		/* Allocation by getting a new cpu slab */
352 	FREE_FASTPATH,		/* Free to cpu slab */
353 	FREE_SLOWPATH,		/* Freeing not to cpu slab */
354 	FREE_FROZEN,		/* Freeing to frozen slab */
355 	FREE_ADD_PARTIAL,	/* Freeing moves slab to partial list */
356 	FREE_REMOVE_PARTIAL,	/* Freeing removes last object */
357 	ALLOC_FROM_PARTIAL,	/* Cpu slab acquired from node partial list */
358 	ALLOC_SLAB,		/* Cpu slab acquired from page allocator */
359 	ALLOC_REFILL,		/* Refill cpu slab from slab freelist */
360 	ALLOC_NODE_MISMATCH,	/* Switching cpu slab */
361 	FREE_SLAB,		/* Slab freed to the page allocator */
362 	CPUSLAB_FLUSH,		/* Abandoning of the cpu slab */
363 	DEACTIVATE_FULL,	/* Cpu slab was full when deactivated */
364 	DEACTIVATE_EMPTY,	/* Cpu slab was empty when deactivated */
365 	DEACTIVATE_TO_HEAD,	/* Cpu slab was moved to the head of partials */
366 	DEACTIVATE_TO_TAIL,	/* Cpu slab was moved to the tail of partials */
367 	DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */
368 	DEACTIVATE_BYPASS,	/* Implicit deactivation */
369 	ORDER_FALLBACK,		/* Number of times fallback was necessary */
370 	CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */
371 	CMPXCHG_DOUBLE_FAIL,	/* Failures of slab freelist update */
372 	CPU_PARTIAL_ALLOC,	/* Used cpu partial on alloc */
373 	CPU_PARTIAL_FREE,	/* Refill cpu partial on free */
374 	CPU_PARTIAL_NODE,	/* Refill cpu partial from node partial */
375 	CPU_PARTIAL_DRAIN,	/* Drain cpu partial to node partial */
376 	NR_SLUB_STAT_ITEMS
377 };
378 
379 #ifndef CONFIG_SLUB_TINY
380 /*
381  * When changing the layout, make sure freelist and tid are still compatible
382  * with this_cpu_cmpxchg_double() alignment requirements.
383  */
384 struct kmem_cache_cpu {
385 	union {
386 		struct {
387 			void **freelist;	/* Pointer to next available object */
388 			unsigned long tid;	/* Globally unique transaction id */
389 		};
390 		freelist_aba_t freelist_tid;
391 	};
392 	struct slab *slab;	/* The slab from which we are allocating */
393 #ifdef CONFIG_SLUB_CPU_PARTIAL
394 	struct slab *partial;	/* Partially allocated slabs */
395 #endif
396 	local_lock_t lock;	/* Protects the fields above */
397 #ifdef CONFIG_SLUB_STATS
398 	unsigned int stat[NR_SLUB_STAT_ITEMS];
399 #endif
400 };
401 #endif /* CONFIG_SLUB_TINY */
402 
403 static inline void stat(const struct kmem_cache *s, enum stat_item si)
404 {
405 #ifdef CONFIG_SLUB_STATS
406 	/*
407 	 * The rmw is racy on a preemptible kernel but this is acceptable, so
408 	 * avoid this_cpu_add()'s irq-disable overhead.
409 	 */
410 	raw_cpu_inc(s->cpu_slab->stat[si]);
411 #endif
412 }
413 
414 static inline
415 void stat_add(const struct kmem_cache *s, enum stat_item si, int v)
416 {
417 #ifdef CONFIG_SLUB_STATS
418 	raw_cpu_add(s->cpu_slab->stat[si], v);
419 #endif
420 }
421 
422 /*
423  * The slab lists for all objects.
424  */
425 struct kmem_cache_node {
426 	spinlock_t list_lock;
427 	unsigned long nr_partial;
428 	struct list_head partial;
429 #ifdef CONFIG_SLUB_DEBUG
430 	atomic_long_t nr_slabs;
431 	atomic_long_t total_objects;
432 	struct list_head full;
433 #endif
434 };
435 
436 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
437 {
438 	return s->node[node];
439 }
440 
441 /*
442  * Iterator over all nodes. The body will be executed for each node that has
443  * a kmem_cache_node structure allocated (which is true for all online nodes)
444  */
445 #define for_each_kmem_cache_node(__s, __node, __n) \
446 	for (__node = 0; __node < nr_node_ids; __node++) \
447 		 if ((__n = get_node(__s, __node)))
448 
449 /*
450  * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
451  * Corresponds to node_state[N_MEMORY], but can temporarily
452  * differ during memory hotplug/hotremove operations.
453  * Protected by slab_mutex.
454  */
455 static nodemask_t slab_nodes;
456 
457 #ifndef CONFIG_SLUB_TINY
458 /*
459  * Workqueue used for flush_cpu_slab().
460  */
461 static struct workqueue_struct *flushwq;
462 #endif
463 
464 /********************************************************************
465  * 			Core slab cache functions
466  *******************************************************************/
467 
468 /*
469  * Returns freelist pointer (ptr). With hardening, this is obfuscated
470  * with an XOR of the address where the pointer is held and a per-cache
471  * random number.
472  */
473 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
474 					    void *ptr, unsigned long ptr_addr)
475 {
476 	unsigned long encoded;
477 
478 #ifdef CONFIG_SLAB_FREELIST_HARDENED
479 	encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
480 #else
481 	encoded = (unsigned long)ptr;
482 #endif
483 	return (freeptr_t){.v = encoded};
484 }
485 
486 static inline void *freelist_ptr_decode(const struct kmem_cache *s,
487 					freeptr_t ptr, unsigned long ptr_addr)
488 {
489 	void *decoded;
490 
491 #ifdef CONFIG_SLAB_FREELIST_HARDENED
492 	decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
493 #else
494 	decoded = (void *)ptr.v;
495 #endif
496 	return decoded;
497 }
498 
499 static inline void *get_freepointer(struct kmem_cache *s, void *object)
500 {
501 	unsigned long ptr_addr;
502 	freeptr_t p;
503 
504 	object = kasan_reset_tag(object);
505 	ptr_addr = (unsigned long)object + s->offset;
506 	p = *(freeptr_t *)(ptr_addr);
507 	return freelist_ptr_decode(s, p, ptr_addr);
508 }
509 
510 #ifndef CONFIG_SLUB_TINY
511 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
512 {
513 	prefetchw(object + s->offset);
514 }
515 #endif
516 
517 /*
518  * When running under KMSAN, get_freepointer_safe() may return an uninitialized
519  * pointer value in the case the current thread loses the race for the next
520  * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
521  * slab_alloc_node() will fail, so the uninitialized value won't be used, but
522  * KMSAN will still check all arguments of cmpxchg because of imperfect
523  * handling of inline assembly.
524  * To work around this problem, we apply __no_kmsan_checks to ensure that
525  * get_freepointer_safe() returns initialized memory.
526  */
527 __no_kmsan_checks
528 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
529 {
530 	unsigned long freepointer_addr;
531 	freeptr_t p;
532 
533 	if (!debug_pagealloc_enabled_static())
534 		return get_freepointer(s, object);
535 
536 	object = kasan_reset_tag(object);
537 	freepointer_addr = (unsigned long)object + s->offset;
538 	copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p));
539 	return freelist_ptr_decode(s, p, freepointer_addr);
540 }
541 
542 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
543 {
544 	unsigned long freeptr_addr = (unsigned long)object + s->offset;
545 
546 #ifdef CONFIG_SLAB_FREELIST_HARDENED
547 	BUG_ON(object == fp); /* naive detection of double free or corruption */
548 #endif
549 
550 	freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
551 	*(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
552 }
553 
554 /*
555  * See comment in calculate_sizes().
556  */
557 static inline bool freeptr_outside_object(struct kmem_cache *s)
558 {
559 	return s->offset >= s->inuse;
560 }
561 
562 /*
563  * Return offset of the end of info block which is inuse + free pointer if
564  * not overlapping with object.
565  */
566 static inline unsigned int get_info_end(struct kmem_cache *s)
567 {
568 	if (freeptr_outside_object(s))
569 		return s->inuse + sizeof(void *);
570 	else
571 		return s->inuse;
572 }
573 
574 /* Loop over all objects in a slab */
575 #define for_each_object(__p, __s, __addr, __objects) \
576 	for (__p = fixup_red_left(__s, __addr); \
577 		__p < (__addr) + (__objects) * (__s)->size; \
578 		__p += (__s)->size)
579 
580 static inline unsigned int order_objects(unsigned int order, unsigned int size)
581 {
582 	return ((unsigned int)PAGE_SIZE << order) / size;
583 }
584 
585 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
586 		unsigned int size)
587 {
588 	struct kmem_cache_order_objects x = {
589 		(order << OO_SHIFT) + order_objects(order, size)
590 	};
591 
592 	return x;
593 }
594 
595 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
596 {
597 	return x.x >> OO_SHIFT;
598 }
599 
600 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
601 {
602 	return x.x & OO_MASK;
603 }
604 
605 #ifdef CONFIG_SLUB_CPU_PARTIAL
606 static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
607 {
608 	unsigned int nr_slabs;
609 
610 	s->cpu_partial = nr_objects;
611 
612 	/*
613 	 * We take the number of objects but actually limit the number of
614 	 * slabs on the per cpu partial list, in order to limit excessive
615 	 * growth of the list. For simplicity we assume that the slabs will
616 	 * be half-full.
617 	 */
618 	nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
619 	s->cpu_partial_slabs = nr_slabs;
620 }
621 
622 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
623 {
624 	return s->cpu_partial_slabs;
625 }
626 #else
627 static inline void
628 slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
629 {
630 }
631 
632 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
633 {
634 	return 0;
635 }
636 #endif /* CONFIG_SLUB_CPU_PARTIAL */
637 
638 /*
639  * Per slab locking using the pagelock
640  */
641 static __always_inline void slab_lock(struct slab *slab)
642 {
643 	bit_spin_lock(PG_locked, &slab->__page_flags);
644 }
645 
646 static __always_inline void slab_unlock(struct slab *slab)
647 {
648 	bit_spin_unlock(PG_locked, &slab->__page_flags);
649 }
650 
651 static inline bool
652 __update_freelist_fast(struct slab *slab,
653 		      void *freelist_old, unsigned long counters_old,
654 		      void *freelist_new, unsigned long counters_new)
655 {
656 #ifdef system_has_freelist_aba
657 	freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old };
658 	freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new };
659 
660 	return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full);
661 #else
662 	return false;
663 #endif
664 }
665 
666 static inline bool
667 __update_freelist_slow(struct slab *slab,
668 		      void *freelist_old, unsigned long counters_old,
669 		      void *freelist_new, unsigned long counters_new)
670 {
671 	bool ret = false;
672 
673 	slab_lock(slab);
674 	if (slab->freelist == freelist_old &&
675 	    slab->counters == counters_old) {
676 		slab->freelist = freelist_new;
677 		slab->counters = counters_new;
678 		ret = true;
679 	}
680 	slab_unlock(slab);
681 
682 	return ret;
683 }
684 
685 /*
686  * Interrupts must be disabled (for the fallback code to work right), typically
687  * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
688  * part of bit_spin_lock(), is sufficient because the policy is not to allow any
689  * allocation/ free operation in hardirq context. Therefore nothing can
690  * interrupt the operation.
691  */
692 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
693 		void *freelist_old, unsigned long counters_old,
694 		void *freelist_new, unsigned long counters_new,
695 		const char *n)
696 {
697 	bool ret;
698 
699 	if (USE_LOCKLESS_FAST_PATH())
700 		lockdep_assert_irqs_disabled();
701 
702 	if (s->flags & __CMPXCHG_DOUBLE) {
703 		ret = __update_freelist_fast(slab, freelist_old, counters_old,
704 				            freelist_new, counters_new);
705 	} else {
706 		ret = __update_freelist_slow(slab, freelist_old, counters_old,
707 				            freelist_new, counters_new);
708 	}
709 	if (likely(ret))
710 		return true;
711 
712 	cpu_relax();
713 	stat(s, CMPXCHG_DOUBLE_FAIL);
714 
715 #ifdef SLUB_DEBUG_CMPXCHG
716 	pr_info("%s %s: cmpxchg double redo ", n, s->name);
717 #endif
718 
719 	return false;
720 }
721 
722 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
723 		void *freelist_old, unsigned long counters_old,
724 		void *freelist_new, unsigned long counters_new,
725 		const char *n)
726 {
727 	bool ret;
728 
729 	if (s->flags & __CMPXCHG_DOUBLE) {
730 		ret = __update_freelist_fast(slab, freelist_old, counters_old,
731 				            freelist_new, counters_new);
732 	} else {
733 		unsigned long flags;
734 
735 		local_irq_save(flags);
736 		ret = __update_freelist_slow(slab, freelist_old, counters_old,
737 				            freelist_new, counters_new);
738 		local_irq_restore(flags);
739 	}
740 	if (likely(ret))
741 		return true;
742 
743 	cpu_relax();
744 	stat(s, CMPXCHG_DOUBLE_FAIL);
745 
746 #ifdef SLUB_DEBUG_CMPXCHG
747 	pr_info("%s %s: cmpxchg double redo ", n, s->name);
748 #endif
749 
750 	return false;
751 }
752 
753 /*
754  * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
755  * family will round up the real request size to these fixed ones, so
756  * there could be an extra area than what is requested. Save the original
757  * request size in the meta data area, for better debug and sanity check.
758  */
759 static inline void set_orig_size(struct kmem_cache *s,
760 				void *object, unsigned int orig_size)
761 {
762 	void *p = kasan_reset_tag(object);
763 
764 	if (!slub_debug_orig_size(s))
765 		return;
766 
767 	p += get_info_end(s);
768 	p += sizeof(struct track) * 2;
769 
770 	*(unsigned int *)p = orig_size;
771 }
772 
773 static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
774 {
775 	void *p = kasan_reset_tag(object);
776 
777 	if (is_kfence_address(object))
778 		return kfence_ksize(object);
779 
780 	if (!slub_debug_orig_size(s))
781 		return s->object_size;
782 
783 	p += get_info_end(s);
784 	p += sizeof(struct track) * 2;
785 
786 	return *(unsigned int *)p;
787 }
788 
789 #ifdef CONFIG_SLUB_DEBUG
790 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
791 static DEFINE_SPINLOCK(object_map_lock);
792 
793 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
794 		       struct slab *slab)
795 {
796 	void *addr = slab_address(slab);
797 	void *p;
798 
799 	bitmap_zero(obj_map, slab->objects);
800 
801 	for (p = slab->freelist; p; p = get_freepointer(s, p))
802 		set_bit(__obj_to_index(s, addr, p), obj_map);
803 }
804 
805 #if IS_ENABLED(CONFIG_KUNIT)
806 static bool slab_add_kunit_errors(void)
807 {
808 	struct kunit_resource *resource;
809 
810 	if (!kunit_get_current_test())
811 		return false;
812 
813 	resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
814 	if (!resource)
815 		return false;
816 
817 	(*(int *)resource->data)++;
818 	kunit_put_resource(resource);
819 	return true;
820 }
821 
822 bool slab_in_kunit_test(void)
823 {
824 	struct kunit_resource *resource;
825 
826 	if (!kunit_get_current_test())
827 		return false;
828 
829 	resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
830 	if (!resource)
831 		return false;
832 
833 	kunit_put_resource(resource);
834 	return true;
835 }
836 #else
837 static inline bool slab_add_kunit_errors(void) { return false; }
838 #endif
839 
840 static inline unsigned int size_from_object(struct kmem_cache *s)
841 {
842 	if (s->flags & SLAB_RED_ZONE)
843 		return s->size - s->red_left_pad;
844 
845 	return s->size;
846 }
847 
848 static inline void *restore_red_left(struct kmem_cache *s, void *p)
849 {
850 	if (s->flags & SLAB_RED_ZONE)
851 		p -= s->red_left_pad;
852 
853 	return p;
854 }
855 
856 /*
857  * Debug settings:
858  */
859 #if defined(CONFIG_SLUB_DEBUG_ON)
860 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
861 #else
862 static slab_flags_t slub_debug;
863 #endif
864 
865 static char *slub_debug_string;
866 static int disable_higher_order_debug;
867 
868 /*
869  * slub is about to manipulate internal object metadata.  This memory lies
870  * outside the range of the allocated object, so accessing it would normally
871  * be reported by kasan as a bounds error.  metadata_access_enable() is used
872  * to tell kasan that these accesses are OK.
873  */
874 static inline void metadata_access_enable(void)
875 {
876 	kasan_disable_current();
877 	kmsan_disable_current();
878 }
879 
880 static inline void metadata_access_disable(void)
881 {
882 	kmsan_enable_current();
883 	kasan_enable_current();
884 }
885 
886 /*
887  * Object debugging
888  */
889 
890 /* Verify that a pointer has an address that is valid within a slab page */
891 static inline int check_valid_pointer(struct kmem_cache *s,
892 				struct slab *slab, void *object)
893 {
894 	void *base;
895 
896 	if (!object)
897 		return 1;
898 
899 	base = slab_address(slab);
900 	object = kasan_reset_tag(object);
901 	object = restore_red_left(s, object);
902 	if (object < base || object >= base + slab->objects * s->size ||
903 		(object - base) % s->size) {
904 		return 0;
905 	}
906 
907 	return 1;
908 }
909 
910 static void print_section(char *level, char *text, u8 *addr,
911 			  unsigned int length)
912 {
913 	metadata_access_enable();
914 	print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
915 			16, 1, kasan_reset_tag((void *)addr), length, 1);
916 	metadata_access_disable();
917 }
918 
919 static struct track *get_track(struct kmem_cache *s, void *object,
920 	enum track_item alloc)
921 {
922 	struct track *p;
923 
924 	p = object + get_info_end(s);
925 
926 	return kasan_reset_tag(p + alloc);
927 }
928 
929 #ifdef CONFIG_STACKDEPOT
930 static noinline depot_stack_handle_t set_track_prepare(void)
931 {
932 	depot_stack_handle_t handle;
933 	unsigned long entries[TRACK_ADDRS_COUNT];
934 	unsigned int nr_entries;
935 
936 	nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
937 	handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT);
938 
939 	return handle;
940 }
941 #else
942 static inline depot_stack_handle_t set_track_prepare(void)
943 {
944 	return 0;
945 }
946 #endif
947 
948 static void set_track_update(struct kmem_cache *s, void *object,
949 			     enum track_item alloc, unsigned long addr,
950 			     depot_stack_handle_t handle)
951 {
952 	struct track *p = get_track(s, object, alloc);
953 
954 #ifdef CONFIG_STACKDEPOT
955 	p->handle = handle;
956 #endif
957 	p->addr = addr;
958 	p->cpu = smp_processor_id();
959 	p->pid = current->pid;
960 	p->when = jiffies;
961 }
962 
963 static __always_inline void set_track(struct kmem_cache *s, void *object,
964 				      enum track_item alloc, unsigned long addr)
965 {
966 	depot_stack_handle_t handle = set_track_prepare();
967 
968 	set_track_update(s, object, alloc, addr, handle);
969 }
970 
971 static void init_tracking(struct kmem_cache *s, void *object)
972 {
973 	struct track *p;
974 
975 	if (!(s->flags & SLAB_STORE_USER))
976 		return;
977 
978 	p = get_track(s, object, TRACK_ALLOC);
979 	memset(p, 0, 2*sizeof(struct track));
980 }
981 
982 static void print_track(const char *s, struct track *t, unsigned long pr_time)
983 {
984 	depot_stack_handle_t handle __maybe_unused;
985 
986 	if (!t->addr)
987 		return;
988 
989 	pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
990 	       s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
991 #ifdef CONFIG_STACKDEPOT
992 	handle = READ_ONCE(t->handle);
993 	if (handle)
994 		stack_depot_print(handle);
995 	else
996 		pr_err("object allocation/free stack trace missing\n");
997 #endif
998 }
999 
1000 void print_tracking(struct kmem_cache *s, void *object)
1001 {
1002 	unsigned long pr_time = jiffies;
1003 	if (!(s->flags & SLAB_STORE_USER))
1004 		return;
1005 
1006 	print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
1007 	print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
1008 }
1009 
1010 static void print_slab_info(const struct slab *slab)
1011 {
1012 	pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
1013 	       slab, slab->objects, slab->inuse, slab->freelist,
1014 	       &slab->__page_flags);
1015 }
1016 
1017 void skip_orig_size_check(struct kmem_cache *s, const void *object)
1018 {
1019 	set_orig_size(s, (void *)object, s->object_size);
1020 }
1021 
1022 static void __slab_bug(struct kmem_cache *s, const char *fmt, va_list argsp)
1023 {
1024 	struct va_format vaf;
1025 	va_list args;
1026 
1027 	va_copy(args, argsp);
1028 	vaf.fmt = fmt;
1029 	vaf.va = &args;
1030 	pr_err("=============================================================================\n");
1031 	pr_err("BUG %s (%s): %pV\n", s ? s->name : "<unknown>", print_tainted(), &vaf);
1032 	pr_err("-----------------------------------------------------------------------------\n\n");
1033 	va_end(args);
1034 }
1035 
1036 static void slab_bug(struct kmem_cache *s, const char *fmt, ...)
1037 {
1038 	va_list args;
1039 
1040 	va_start(args, fmt);
1041 	__slab_bug(s, fmt, args);
1042 	va_end(args);
1043 }
1044 
1045 __printf(2, 3)
1046 static void slab_fix(struct kmem_cache *s, const char *fmt, ...)
1047 {
1048 	struct va_format vaf;
1049 	va_list args;
1050 
1051 	if (slab_add_kunit_errors())
1052 		return;
1053 
1054 	va_start(args, fmt);
1055 	vaf.fmt = fmt;
1056 	vaf.va = &args;
1057 	pr_err("FIX %s: %pV\n", s->name, &vaf);
1058 	va_end(args);
1059 }
1060 
1061 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
1062 {
1063 	unsigned int off;	/* Offset of last byte */
1064 	u8 *addr = slab_address(slab);
1065 
1066 	print_tracking(s, p);
1067 
1068 	print_slab_info(slab);
1069 
1070 	pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
1071 	       p, p - addr, get_freepointer(s, p));
1072 
1073 	if (s->flags & SLAB_RED_ZONE)
1074 		print_section(KERN_ERR, "Redzone  ", p - s->red_left_pad,
1075 			      s->red_left_pad);
1076 	else if (p > addr + 16)
1077 		print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
1078 
1079 	print_section(KERN_ERR,         "Object   ", p,
1080 		      min_t(unsigned int, s->object_size, PAGE_SIZE));
1081 	if (s->flags & SLAB_RED_ZONE)
1082 		print_section(KERN_ERR, "Redzone  ", p + s->object_size,
1083 			s->inuse - s->object_size);
1084 
1085 	off = get_info_end(s);
1086 
1087 	if (s->flags & SLAB_STORE_USER)
1088 		off += 2 * sizeof(struct track);
1089 
1090 	if (slub_debug_orig_size(s))
1091 		off += sizeof(unsigned int);
1092 
1093 	off += kasan_metadata_size(s, false);
1094 
1095 	if (off != size_from_object(s))
1096 		/* Beginning of the filler is the free pointer */
1097 		print_section(KERN_ERR, "Padding  ", p + off,
1098 			      size_from_object(s) - off);
1099 }
1100 
1101 static void object_err(struct kmem_cache *s, struct slab *slab,
1102 			u8 *object, const char *reason)
1103 {
1104 	if (slab_add_kunit_errors())
1105 		return;
1106 
1107 	slab_bug(s, reason);
1108 	print_trailer(s, slab, object);
1109 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1110 
1111 	WARN_ON(1);
1112 }
1113 
1114 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1115 			       void **freelist, void *nextfree)
1116 {
1117 	if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
1118 	    !check_valid_pointer(s, slab, nextfree) && freelist) {
1119 		object_err(s, slab, *freelist, "Freechain corrupt");
1120 		*freelist = NULL;
1121 		slab_fix(s, "Isolate corrupted freechain");
1122 		return true;
1123 	}
1124 
1125 	return false;
1126 }
1127 
1128 static void __slab_err(struct slab *slab)
1129 {
1130 	if (slab_in_kunit_test())
1131 		return;
1132 
1133 	print_slab_info(slab);
1134 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1135 
1136 	WARN_ON(1);
1137 }
1138 
1139 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
1140 			const char *fmt, ...)
1141 {
1142 	va_list args;
1143 
1144 	if (slab_add_kunit_errors())
1145 		return;
1146 
1147 	va_start(args, fmt);
1148 	__slab_bug(s, fmt, args);
1149 	va_end(args);
1150 
1151 	__slab_err(slab);
1152 }
1153 
1154 static void init_object(struct kmem_cache *s, void *object, u8 val)
1155 {
1156 	u8 *p = kasan_reset_tag(object);
1157 	unsigned int poison_size = s->object_size;
1158 
1159 	if (s->flags & SLAB_RED_ZONE) {
1160 		/*
1161 		 * Here and below, avoid overwriting the KMSAN shadow. Keeping
1162 		 * the shadow makes it possible to distinguish uninit-value
1163 		 * from use-after-free.
1164 		 */
1165 		memset_no_sanitize_memory(p - s->red_left_pad, val,
1166 					  s->red_left_pad);
1167 
1168 		if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1169 			/*
1170 			 * Redzone the extra allocated space by kmalloc than
1171 			 * requested, and the poison size will be limited to
1172 			 * the original request size accordingly.
1173 			 */
1174 			poison_size = get_orig_size(s, object);
1175 		}
1176 	}
1177 
1178 	if (s->flags & __OBJECT_POISON) {
1179 		memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1);
1180 		memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1);
1181 	}
1182 
1183 	if (s->flags & SLAB_RED_ZONE)
1184 		memset_no_sanitize_memory(p + poison_size, val,
1185 					  s->inuse - poison_size);
1186 }
1187 
1188 static void restore_bytes(struct kmem_cache *s, const char *message, u8 data,
1189 						void *from, void *to)
1190 {
1191 	slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
1192 	memset(from, data, to - from);
1193 }
1194 
1195 #ifdef CONFIG_KMSAN
1196 #define pad_check_attributes noinline __no_kmsan_checks
1197 #else
1198 #define pad_check_attributes
1199 #endif
1200 
1201 static pad_check_attributes int
1202 check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
1203 		       u8 *object, const char *what, u8 *start, unsigned int value,
1204 		       unsigned int bytes, bool slab_obj_print)
1205 {
1206 	u8 *fault;
1207 	u8 *end;
1208 	u8 *addr = slab_address(slab);
1209 
1210 	metadata_access_enable();
1211 	fault = memchr_inv(kasan_reset_tag(start), value, bytes);
1212 	metadata_access_disable();
1213 	if (!fault)
1214 		return 1;
1215 
1216 	end = start + bytes;
1217 	while (end > fault && end[-1] == value)
1218 		end--;
1219 
1220 	if (slab_add_kunit_errors())
1221 		goto skip_bug_print;
1222 
1223 	pr_err("[%s overwritten] 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
1224 	       what, fault, end - 1, fault - addr, fault[0], value);
1225 
1226 	if (slab_obj_print)
1227 		object_err(s, slab, object, "Object corrupt");
1228 
1229 skip_bug_print:
1230 	restore_bytes(s, what, value, fault, end);
1231 	return 0;
1232 }
1233 
1234 /*
1235  * Object layout:
1236  *
1237  * object address
1238  * 	Bytes of the object to be managed.
1239  * 	If the freepointer may overlay the object then the free
1240  *	pointer is at the middle of the object.
1241  *
1242  * 	Poisoning uses 0x6b (POISON_FREE) and the last byte is
1243  * 	0xa5 (POISON_END)
1244  *
1245  * object + s->object_size
1246  * 	Padding to reach word boundary. This is also used for Redzoning.
1247  * 	Padding is extended by another word if Redzoning is enabled and
1248  * 	object_size == inuse.
1249  *
1250  * 	We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with
1251  * 	0xcc (SLUB_RED_ACTIVE) for objects in use.
1252  *
1253  * object + s->inuse
1254  * 	Meta data starts here.
1255  *
1256  * 	A. Free pointer (if we cannot overwrite object on free)
1257  * 	B. Tracking data for SLAB_STORE_USER
1258  *	C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
1259  *	D. Padding to reach required alignment boundary or at minimum
1260  * 		one word if debugging is on to be able to detect writes
1261  * 		before the word boundary.
1262  *
1263  *	Padding is done using 0x5a (POISON_INUSE)
1264  *
1265  * object + s->size
1266  * 	Nothing is used beyond s->size.
1267  *
1268  * If slabcaches are merged then the object_size and inuse boundaries are mostly
1269  * ignored. And therefore no slab options that rely on these boundaries
1270  * may be used with merged slabcaches.
1271  */
1272 
1273 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
1274 {
1275 	unsigned long off = get_info_end(s);	/* The end of info */
1276 
1277 	if (s->flags & SLAB_STORE_USER) {
1278 		/* We also have user information there */
1279 		off += 2 * sizeof(struct track);
1280 
1281 		if (s->flags & SLAB_KMALLOC)
1282 			off += sizeof(unsigned int);
1283 	}
1284 
1285 	off += kasan_metadata_size(s, false);
1286 
1287 	if (size_from_object(s) == off)
1288 		return 1;
1289 
1290 	return check_bytes_and_report(s, slab, p, "Object padding",
1291 			p + off, POISON_INUSE, size_from_object(s) - off, true);
1292 }
1293 
1294 /* Check the pad bytes at the end of a slab page */
1295 static pad_check_attributes void
1296 slab_pad_check(struct kmem_cache *s, struct slab *slab)
1297 {
1298 	u8 *start;
1299 	u8 *fault;
1300 	u8 *end;
1301 	u8 *pad;
1302 	int length;
1303 	int remainder;
1304 
1305 	if (!(s->flags & SLAB_POISON))
1306 		return;
1307 
1308 	start = slab_address(slab);
1309 	length = slab_size(slab);
1310 	end = start + length;
1311 	remainder = length % s->size;
1312 	if (!remainder)
1313 		return;
1314 
1315 	pad = end - remainder;
1316 	metadata_access_enable();
1317 	fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
1318 	metadata_access_disable();
1319 	if (!fault)
1320 		return;
1321 	while (end > fault && end[-1] == POISON_INUSE)
1322 		end--;
1323 
1324 	slab_bug(s, "Padding overwritten. 0x%p-0x%p @offset=%tu",
1325 		 fault, end - 1, fault - start);
1326 	print_section(KERN_ERR, "Padding ", pad, remainder);
1327 	__slab_err(slab);
1328 
1329 	restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
1330 }
1331 
1332 static int check_object(struct kmem_cache *s, struct slab *slab,
1333 					void *object, u8 val)
1334 {
1335 	u8 *p = object;
1336 	u8 *endobject = object + s->object_size;
1337 	unsigned int orig_size, kasan_meta_size;
1338 	int ret = 1;
1339 
1340 	if (s->flags & SLAB_RED_ZONE) {
1341 		if (!check_bytes_and_report(s, slab, object, "Left Redzone",
1342 			object - s->red_left_pad, val, s->red_left_pad, ret))
1343 			ret = 0;
1344 
1345 		if (!check_bytes_and_report(s, slab, object, "Right Redzone",
1346 			endobject, val, s->inuse - s->object_size, ret))
1347 			ret = 0;
1348 
1349 		if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1350 			orig_size = get_orig_size(s, object);
1351 
1352 			if (s->object_size > orig_size  &&
1353 				!check_bytes_and_report(s, slab, object,
1354 					"kmalloc Redzone", p + orig_size,
1355 					val, s->object_size - orig_size, ret)) {
1356 				ret = 0;
1357 			}
1358 		}
1359 	} else {
1360 		if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
1361 			if (!check_bytes_and_report(s, slab, p, "Alignment padding",
1362 				endobject, POISON_INUSE,
1363 				s->inuse - s->object_size, ret))
1364 				ret = 0;
1365 		}
1366 	}
1367 
1368 	if (s->flags & SLAB_POISON) {
1369 		if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) {
1370 			/*
1371 			 * KASAN can save its free meta data inside of the
1372 			 * object at offset 0. Thus, skip checking the part of
1373 			 * the redzone that overlaps with the meta data.
1374 			 */
1375 			kasan_meta_size = kasan_metadata_size(s, true);
1376 			if (kasan_meta_size < s->object_size - 1 &&
1377 			    !check_bytes_and_report(s, slab, p, "Poison",
1378 					p + kasan_meta_size, POISON_FREE,
1379 					s->object_size - kasan_meta_size - 1, ret))
1380 				ret = 0;
1381 			if (kasan_meta_size < s->object_size &&
1382 			    !check_bytes_and_report(s, slab, p, "End Poison",
1383 					p + s->object_size - 1, POISON_END, 1, ret))
1384 				ret = 0;
1385 		}
1386 		/*
1387 		 * check_pad_bytes cleans up on its own.
1388 		 */
1389 		if (!check_pad_bytes(s, slab, p))
1390 			ret = 0;
1391 	}
1392 
1393 	/*
1394 	 * Cannot check freepointer while object is allocated if
1395 	 * object and freepointer overlap.
1396 	 */
1397 	if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
1398 	    !check_valid_pointer(s, slab, get_freepointer(s, p))) {
1399 		object_err(s, slab, p, "Freepointer corrupt");
1400 		/*
1401 		 * No choice but to zap it and thus lose the remainder
1402 		 * of the free objects in this slab. May cause
1403 		 * another error because the object count is now wrong.
1404 		 */
1405 		set_freepointer(s, p, NULL);
1406 		ret = 0;
1407 	}
1408 
1409 	return ret;
1410 }
1411 
1412 static int check_slab(struct kmem_cache *s, struct slab *slab)
1413 {
1414 	int maxobj;
1415 
1416 	if (!folio_test_slab(slab_folio(slab))) {
1417 		slab_err(s, slab, "Not a valid slab page");
1418 		return 0;
1419 	}
1420 
1421 	maxobj = order_objects(slab_order(slab), s->size);
1422 	if (slab->objects > maxobj) {
1423 		slab_err(s, slab, "objects %u > max %u",
1424 			slab->objects, maxobj);
1425 		return 0;
1426 	}
1427 	if (slab->inuse > slab->objects) {
1428 		slab_err(s, slab, "inuse %u > max %u",
1429 			slab->inuse, slab->objects);
1430 		return 0;
1431 	}
1432 	if (slab->frozen) {
1433 		slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
1434 		return 0;
1435 	}
1436 
1437 	/* Slab_pad_check fixes things up after itself */
1438 	slab_pad_check(s, slab);
1439 	return 1;
1440 }
1441 
1442 /*
1443  * Determine if a certain object in a slab is on the freelist. Must hold the
1444  * slab lock to guarantee that the chains are in a consistent state.
1445  */
1446 static bool on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
1447 {
1448 	int nr = 0;
1449 	void *fp;
1450 	void *object = NULL;
1451 	int max_objects;
1452 
1453 	fp = slab->freelist;
1454 	while (fp && nr <= slab->objects) {
1455 		if (fp == search)
1456 			return true;
1457 		if (!check_valid_pointer(s, slab, fp)) {
1458 			if (object) {
1459 				object_err(s, slab, object,
1460 					"Freechain corrupt");
1461 				set_freepointer(s, object, NULL);
1462 				break;
1463 			} else {
1464 				slab_err(s, slab, "Freepointer corrupt");
1465 				slab->freelist = NULL;
1466 				slab->inuse = slab->objects;
1467 				slab_fix(s, "Freelist cleared");
1468 				return false;
1469 			}
1470 		}
1471 		object = fp;
1472 		fp = get_freepointer(s, object);
1473 		nr++;
1474 	}
1475 
1476 	if (nr > slab->objects) {
1477 		slab_err(s, slab, "Freelist cycle detected");
1478 		slab->freelist = NULL;
1479 		slab->inuse = slab->objects;
1480 		slab_fix(s, "Freelist cleared");
1481 		return false;
1482 	}
1483 
1484 	max_objects = order_objects(slab_order(slab), s->size);
1485 	if (max_objects > MAX_OBJS_PER_PAGE)
1486 		max_objects = MAX_OBJS_PER_PAGE;
1487 
1488 	if (slab->objects != max_objects) {
1489 		slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1490 			 slab->objects, max_objects);
1491 		slab->objects = max_objects;
1492 		slab_fix(s, "Number of objects adjusted");
1493 	}
1494 	if (slab->inuse != slab->objects - nr) {
1495 		slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1496 			 slab->inuse, slab->objects - nr);
1497 		slab->inuse = slab->objects - nr;
1498 		slab_fix(s, "Object count adjusted");
1499 	}
1500 	return search == NULL;
1501 }
1502 
1503 static void trace(struct kmem_cache *s, struct slab *slab, void *object,
1504 								int alloc)
1505 {
1506 	if (s->flags & SLAB_TRACE) {
1507 		pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1508 			s->name,
1509 			alloc ? "alloc" : "free",
1510 			object, slab->inuse,
1511 			slab->freelist);
1512 
1513 		if (!alloc)
1514 			print_section(KERN_INFO, "Object ", (void *)object,
1515 					s->object_size);
1516 
1517 		dump_stack();
1518 	}
1519 }
1520 
1521 /*
1522  * Tracking of fully allocated slabs for debugging purposes.
1523  */
1524 static void add_full(struct kmem_cache *s,
1525 	struct kmem_cache_node *n, struct slab *slab)
1526 {
1527 	if (!(s->flags & SLAB_STORE_USER))
1528 		return;
1529 
1530 	lockdep_assert_held(&n->list_lock);
1531 	list_add(&slab->slab_list, &n->full);
1532 }
1533 
1534 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
1535 {
1536 	if (!(s->flags & SLAB_STORE_USER))
1537 		return;
1538 
1539 	lockdep_assert_held(&n->list_lock);
1540 	list_del(&slab->slab_list);
1541 }
1542 
1543 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1544 {
1545 	return atomic_long_read(&n->nr_slabs);
1546 }
1547 
1548 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1549 {
1550 	struct kmem_cache_node *n = get_node(s, node);
1551 
1552 	atomic_long_inc(&n->nr_slabs);
1553 	atomic_long_add(objects, &n->total_objects);
1554 }
1555 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1556 {
1557 	struct kmem_cache_node *n = get_node(s, node);
1558 
1559 	atomic_long_dec(&n->nr_slabs);
1560 	atomic_long_sub(objects, &n->total_objects);
1561 }
1562 
1563 /* Object debug checks for alloc/free paths */
1564 static void setup_object_debug(struct kmem_cache *s, void *object)
1565 {
1566 	if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1567 		return;
1568 
1569 	init_object(s, object, SLUB_RED_INACTIVE);
1570 	init_tracking(s, object);
1571 }
1572 
1573 static
1574 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
1575 {
1576 	if (!kmem_cache_debug_flags(s, SLAB_POISON))
1577 		return;
1578 
1579 	metadata_access_enable();
1580 	memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
1581 	metadata_access_disable();
1582 }
1583 
1584 static inline int alloc_consistency_checks(struct kmem_cache *s,
1585 					struct slab *slab, void *object)
1586 {
1587 	if (!check_slab(s, slab))
1588 		return 0;
1589 
1590 	if (!check_valid_pointer(s, slab, object)) {
1591 		object_err(s, slab, object, "Freelist Pointer check fails");
1592 		return 0;
1593 	}
1594 
1595 	if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
1596 		return 0;
1597 
1598 	return 1;
1599 }
1600 
1601 static noinline bool alloc_debug_processing(struct kmem_cache *s,
1602 			struct slab *slab, void *object, int orig_size)
1603 {
1604 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1605 		if (!alloc_consistency_checks(s, slab, object))
1606 			goto bad;
1607 	}
1608 
1609 	/* Success. Perform special debug activities for allocs */
1610 	trace(s, slab, object, 1);
1611 	set_orig_size(s, object, orig_size);
1612 	init_object(s, object, SLUB_RED_ACTIVE);
1613 	return true;
1614 
1615 bad:
1616 	if (folio_test_slab(slab_folio(slab))) {
1617 		/*
1618 		 * If this is a slab page then lets do the best we can
1619 		 * to avoid issues in the future. Marking all objects
1620 		 * as used avoids touching the remaining objects.
1621 		 */
1622 		slab_fix(s, "Marking all objects used");
1623 		slab->inuse = slab->objects;
1624 		slab->freelist = NULL;
1625 		slab->frozen = 1; /* mark consistency-failed slab as frozen */
1626 	}
1627 	return false;
1628 }
1629 
1630 static inline int free_consistency_checks(struct kmem_cache *s,
1631 		struct slab *slab, void *object, unsigned long addr)
1632 {
1633 	if (!check_valid_pointer(s, slab, object)) {
1634 		slab_err(s, slab, "Invalid object pointer 0x%p", object);
1635 		return 0;
1636 	}
1637 
1638 	if (on_freelist(s, slab, object)) {
1639 		object_err(s, slab, object, "Object already free");
1640 		return 0;
1641 	}
1642 
1643 	if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
1644 		return 0;
1645 
1646 	if (unlikely(s != slab->slab_cache)) {
1647 		if (!folio_test_slab(slab_folio(slab))) {
1648 			slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
1649 				 object);
1650 		} else if (!slab->slab_cache) {
1651 			slab_err(NULL, slab, "No slab cache for object 0x%p",
1652 				 object);
1653 		} else {
1654 			object_err(s, slab, object,
1655 				   "page slab pointer corrupt.");
1656 		}
1657 		return 0;
1658 	}
1659 	return 1;
1660 }
1661 
1662 /*
1663  * Parse a block of slab_debug options. Blocks are delimited by ';'
1664  *
1665  * @str:    start of block
1666  * @flags:  returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1667  * @slabs:  return start of list of slabs, or NULL when there's no list
1668  * @init:   assume this is initial parsing and not per-kmem-create parsing
1669  *
1670  * returns the start of next block if there's any, or NULL
1671  */
1672 static char *
1673 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1674 {
1675 	bool higher_order_disable = false;
1676 
1677 	/* Skip any completely empty blocks */
1678 	while (*str && *str == ';')
1679 		str++;
1680 
1681 	if (*str == ',') {
1682 		/*
1683 		 * No options but restriction on slabs. This means full
1684 		 * debugging for slabs matching a pattern.
1685 		 */
1686 		*flags = DEBUG_DEFAULT_FLAGS;
1687 		goto check_slabs;
1688 	}
1689 	*flags = 0;
1690 
1691 	/* Determine which debug features should be switched on */
1692 	for (; *str && *str != ',' && *str != ';'; str++) {
1693 		switch (tolower(*str)) {
1694 		case '-':
1695 			*flags = 0;
1696 			break;
1697 		case 'f':
1698 			*flags |= SLAB_CONSISTENCY_CHECKS;
1699 			break;
1700 		case 'z':
1701 			*flags |= SLAB_RED_ZONE;
1702 			break;
1703 		case 'p':
1704 			*flags |= SLAB_POISON;
1705 			break;
1706 		case 'u':
1707 			*flags |= SLAB_STORE_USER;
1708 			break;
1709 		case 't':
1710 			*flags |= SLAB_TRACE;
1711 			break;
1712 		case 'a':
1713 			*flags |= SLAB_FAILSLAB;
1714 			break;
1715 		case 'o':
1716 			/*
1717 			 * Avoid enabling debugging on caches if its minimum
1718 			 * order would increase as a result.
1719 			 */
1720 			higher_order_disable = true;
1721 			break;
1722 		default:
1723 			if (init)
1724 				pr_err("slab_debug option '%c' unknown. skipped\n", *str);
1725 		}
1726 	}
1727 check_slabs:
1728 	if (*str == ',')
1729 		*slabs = ++str;
1730 	else
1731 		*slabs = NULL;
1732 
1733 	/* Skip over the slab list */
1734 	while (*str && *str != ';')
1735 		str++;
1736 
1737 	/* Skip any completely empty blocks */
1738 	while (*str && *str == ';')
1739 		str++;
1740 
1741 	if (init && higher_order_disable)
1742 		disable_higher_order_debug = 1;
1743 
1744 	if (*str)
1745 		return str;
1746 	else
1747 		return NULL;
1748 }
1749 
1750 static int __init setup_slub_debug(char *str)
1751 {
1752 	slab_flags_t flags;
1753 	slab_flags_t global_flags;
1754 	char *saved_str;
1755 	char *slab_list;
1756 	bool global_slub_debug_changed = false;
1757 	bool slab_list_specified = false;
1758 
1759 	global_flags = DEBUG_DEFAULT_FLAGS;
1760 	if (*str++ != '=' || !*str)
1761 		/*
1762 		 * No options specified. Switch on full debugging.
1763 		 */
1764 		goto out;
1765 
1766 	saved_str = str;
1767 	while (str) {
1768 		str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1769 
1770 		if (!slab_list) {
1771 			global_flags = flags;
1772 			global_slub_debug_changed = true;
1773 		} else {
1774 			slab_list_specified = true;
1775 			if (flags & SLAB_STORE_USER)
1776 				stack_depot_request_early_init();
1777 		}
1778 	}
1779 
1780 	/*
1781 	 * For backwards compatibility, a single list of flags with list of
1782 	 * slabs means debugging is only changed for those slabs, so the global
1783 	 * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1784 	 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
1785 	 * long as there is no option specifying flags without a slab list.
1786 	 */
1787 	if (slab_list_specified) {
1788 		if (!global_slub_debug_changed)
1789 			global_flags = slub_debug;
1790 		slub_debug_string = saved_str;
1791 	}
1792 out:
1793 	slub_debug = global_flags;
1794 	if (slub_debug & SLAB_STORE_USER)
1795 		stack_depot_request_early_init();
1796 	if (slub_debug != 0 || slub_debug_string)
1797 		static_branch_enable(&slub_debug_enabled);
1798 	else
1799 		static_branch_disable(&slub_debug_enabled);
1800 	if ((static_branch_unlikely(&init_on_alloc) ||
1801 	     static_branch_unlikely(&init_on_free)) &&
1802 	    (slub_debug & SLAB_POISON))
1803 		pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1804 	return 1;
1805 }
1806 
1807 __setup("slab_debug", setup_slub_debug);
1808 __setup_param("slub_debug", slub_debug, setup_slub_debug, 0);
1809 
1810 /*
1811  * kmem_cache_flags - apply debugging options to the cache
1812  * @flags:		flags to set
1813  * @name:		name of the cache
1814  *
1815  * Debug option(s) are applied to @flags. In addition to the debug
1816  * option(s), if a slab name (or multiple) is specified i.e.
1817  * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1818  * then only the select slabs will receive the debug option(s).
1819  */
1820 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1821 {
1822 	char *iter;
1823 	size_t len;
1824 	char *next_block;
1825 	slab_flags_t block_flags;
1826 	slab_flags_t slub_debug_local = slub_debug;
1827 
1828 	if (flags & SLAB_NO_USER_FLAGS)
1829 		return flags;
1830 
1831 	/*
1832 	 * If the slab cache is for debugging (e.g. kmemleak) then
1833 	 * don't store user (stack trace) information by default,
1834 	 * but let the user enable it via the command line below.
1835 	 */
1836 	if (flags & SLAB_NOLEAKTRACE)
1837 		slub_debug_local &= ~SLAB_STORE_USER;
1838 
1839 	len = strlen(name);
1840 	next_block = slub_debug_string;
1841 	/* Go through all blocks of debug options, see if any matches our slab's name */
1842 	while (next_block) {
1843 		next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1844 		if (!iter)
1845 			continue;
1846 		/* Found a block that has a slab list, search it */
1847 		while (*iter) {
1848 			char *end, *glob;
1849 			size_t cmplen;
1850 
1851 			end = strchrnul(iter, ',');
1852 			if (next_block && next_block < end)
1853 				end = next_block - 1;
1854 
1855 			glob = strnchr(iter, end - iter, '*');
1856 			if (glob)
1857 				cmplen = glob - iter;
1858 			else
1859 				cmplen = max_t(size_t, len, (end - iter));
1860 
1861 			if (!strncmp(name, iter, cmplen)) {
1862 				flags |= block_flags;
1863 				return flags;
1864 			}
1865 
1866 			if (!*end || *end == ';')
1867 				break;
1868 			iter = end + 1;
1869 		}
1870 	}
1871 
1872 	return flags | slub_debug_local;
1873 }
1874 #else /* !CONFIG_SLUB_DEBUG */
1875 static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
1876 static inline
1877 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
1878 
1879 static inline bool alloc_debug_processing(struct kmem_cache *s,
1880 	struct slab *slab, void *object, int orig_size) { return true; }
1881 
1882 static inline bool free_debug_processing(struct kmem_cache *s,
1883 	struct slab *slab, void *head, void *tail, int *bulk_cnt,
1884 	unsigned long addr, depot_stack_handle_t handle) { return true; }
1885 
1886 static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
1887 static inline int check_object(struct kmem_cache *s, struct slab *slab,
1888 			void *object, u8 val) { return 1; }
1889 static inline depot_stack_handle_t set_track_prepare(void) { return 0; }
1890 static inline void set_track(struct kmem_cache *s, void *object,
1891 			     enum track_item alloc, unsigned long addr) {}
1892 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1893 					struct slab *slab) {}
1894 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1895 					struct slab *slab) {}
1896 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1897 {
1898 	return flags;
1899 }
1900 #define slub_debug 0
1901 
1902 #define disable_higher_order_debug 0
1903 
1904 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1905 							{ return 0; }
1906 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1907 							int objects) {}
1908 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1909 							int objects) {}
1910 #ifndef CONFIG_SLUB_TINY
1911 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1912 			       void **freelist, void *nextfree)
1913 {
1914 	return false;
1915 }
1916 #endif
1917 #endif /* CONFIG_SLUB_DEBUG */
1918 
1919 #ifdef CONFIG_SLAB_OBJ_EXT
1920 
1921 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
1922 
1923 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts)
1924 {
1925 	struct slabobj_ext *slab_exts;
1926 	struct slab *obj_exts_slab;
1927 
1928 	obj_exts_slab = virt_to_slab(obj_exts);
1929 	slab_exts = slab_obj_exts(obj_exts_slab);
1930 	if (slab_exts) {
1931 		unsigned int offs = obj_to_index(obj_exts_slab->slab_cache,
1932 						 obj_exts_slab, obj_exts);
1933 		/* codetag should be NULL */
1934 		WARN_ON(slab_exts[offs].ref.ct);
1935 		set_codetag_empty(&slab_exts[offs].ref);
1936 	}
1937 }
1938 
1939 static inline void mark_failed_objexts_alloc(struct slab *slab)
1940 {
1941 	slab->obj_exts = OBJEXTS_ALLOC_FAIL;
1942 }
1943 
1944 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
1945 			struct slabobj_ext *vec, unsigned int objects)
1946 {
1947 	/*
1948 	 * If vector previously failed to allocate then we have live
1949 	 * objects with no tag reference. Mark all references in this
1950 	 * vector as empty to avoid warnings later on.
1951 	 */
1952 	if (obj_exts & OBJEXTS_ALLOC_FAIL) {
1953 		unsigned int i;
1954 
1955 		for (i = 0; i < objects; i++)
1956 			set_codetag_empty(&vec[i].ref);
1957 	}
1958 }
1959 
1960 #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
1961 
1962 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) {}
1963 static inline void mark_failed_objexts_alloc(struct slab *slab) {}
1964 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
1965 			struct slabobj_ext *vec, unsigned int objects) {}
1966 
1967 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
1968 
1969 /*
1970  * The allocated objcg pointers array is not accounted directly.
1971  * Moreover, it should not come from DMA buffer and is not readily
1972  * reclaimable. So those GFP bits should be masked off.
1973  */
1974 #define OBJCGS_CLEAR_MASK	(__GFP_DMA | __GFP_RECLAIMABLE | \
1975 				__GFP_ACCOUNT | __GFP_NOFAIL)
1976 
1977 static inline void init_slab_obj_exts(struct slab *slab)
1978 {
1979 	slab->obj_exts = 0;
1980 }
1981 
1982 int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
1983 		        gfp_t gfp, bool new_slab)
1984 {
1985 	unsigned int objects = objs_per_slab(s, slab);
1986 	unsigned long new_exts;
1987 	unsigned long old_exts;
1988 	struct slabobj_ext *vec;
1989 
1990 	gfp &= ~OBJCGS_CLEAR_MASK;
1991 	/* Prevent recursive extension vector allocation */
1992 	gfp |= __GFP_NO_OBJ_EXT;
1993 	vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp,
1994 			   slab_nid(slab));
1995 	if (!vec) {
1996 		/* Mark vectors which failed to allocate */
1997 		if (new_slab)
1998 			mark_failed_objexts_alloc(slab);
1999 
2000 		return -ENOMEM;
2001 	}
2002 
2003 	new_exts = (unsigned long)vec;
2004 #ifdef CONFIG_MEMCG
2005 	new_exts |= MEMCG_DATA_OBJEXTS;
2006 #endif
2007 	old_exts = READ_ONCE(slab->obj_exts);
2008 	handle_failed_objexts_alloc(old_exts, vec, objects);
2009 	if (new_slab) {
2010 		/*
2011 		 * If the slab is brand new and nobody can yet access its
2012 		 * obj_exts, no synchronization is required and obj_exts can
2013 		 * be simply assigned.
2014 		 */
2015 		slab->obj_exts = new_exts;
2016 	} else if ((old_exts & ~OBJEXTS_FLAGS_MASK) ||
2017 		   cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) {
2018 		/*
2019 		 * If the slab is already in use, somebody can allocate and
2020 		 * assign slabobj_exts in parallel. In this case the existing
2021 		 * objcg vector should be reused.
2022 		 */
2023 		mark_objexts_empty(vec);
2024 		kfree(vec);
2025 		return 0;
2026 	}
2027 
2028 	kmemleak_not_leak(vec);
2029 	return 0;
2030 }
2031 
2032 static inline void free_slab_obj_exts(struct slab *slab)
2033 {
2034 	struct slabobj_ext *obj_exts;
2035 
2036 	obj_exts = slab_obj_exts(slab);
2037 	if (!obj_exts)
2038 		return;
2039 
2040 	/*
2041 	 * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its
2042 	 * corresponding extension will be NULL. alloc_tag_sub() will throw a
2043 	 * warning if slab has extensions but the extension of an object is
2044 	 * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that
2045 	 * the extension for obj_exts is expected to be NULL.
2046 	 */
2047 	mark_objexts_empty(obj_exts);
2048 	kfree(obj_exts);
2049 	slab->obj_exts = 0;
2050 }
2051 
2052 #else /* CONFIG_SLAB_OBJ_EXT */
2053 
2054 static inline void init_slab_obj_exts(struct slab *slab)
2055 {
2056 }
2057 
2058 static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2059 			       gfp_t gfp, bool new_slab)
2060 {
2061 	return 0;
2062 }
2063 
2064 static inline void free_slab_obj_exts(struct slab *slab)
2065 {
2066 }
2067 
2068 #endif /* CONFIG_SLAB_OBJ_EXT */
2069 
2070 #ifdef CONFIG_MEM_ALLOC_PROFILING
2071 
2072 static inline struct slabobj_ext *
2073 prepare_slab_obj_exts_hook(struct kmem_cache *s, gfp_t flags, void *p)
2074 {
2075 	struct slab *slab;
2076 
2077 	if (!p)
2078 		return NULL;
2079 
2080 	if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2081 		return NULL;
2082 
2083 	if (flags & __GFP_NO_OBJ_EXT)
2084 		return NULL;
2085 
2086 	slab = virt_to_slab(p);
2087 	if (!slab_obj_exts(slab) &&
2088 	    alloc_slab_obj_exts(slab, s, flags, false)) {
2089 		pr_warn_once("%s, %s: Failed to create slab extension vector!\n",
2090 			     __func__, s->name);
2091 		return NULL;
2092 	}
2093 
2094 	return slab_obj_exts(slab) + obj_to_index(s, slab, p);
2095 }
2096 
2097 /* Should be called only if mem_alloc_profiling_enabled() */
2098 static noinline void
2099 __alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2100 {
2101 	struct slabobj_ext *obj_exts;
2102 
2103 	obj_exts = prepare_slab_obj_exts_hook(s, flags, object);
2104 	/*
2105 	 * Currently obj_exts is used only for allocation profiling.
2106 	 * If other users appear then mem_alloc_profiling_enabled()
2107 	 * check should be added before alloc_tag_add().
2108 	 */
2109 	if (likely(obj_exts))
2110 		alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size);
2111 }
2112 
2113 static inline void
2114 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2115 {
2116 	if (mem_alloc_profiling_enabled())
2117 		__alloc_tagging_slab_alloc_hook(s, object, flags);
2118 }
2119 
2120 /* Should be called only if mem_alloc_profiling_enabled() */
2121 static noinline void
2122 __alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2123 			       int objects)
2124 {
2125 	struct slabobj_ext *obj_exts;
2126 	int i;
2127 
2128 	/* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */
2129 	if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2130 		return;
2131 
2132 	obj_exts = slab_obj_exts(slab);
2133 	if (!obj_exts)
2134 		return;
2135 
2136 	for (i = 0; i < objects; i++) {
2137 		unsigned int off = obj_to_index(s, slab, p[i]);
2138 
2139 		alloc_tag_sub(&obj_exts[off].ref, s->size);
2140 	}
2141 }
2142 
2143 static inline void
2144 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2145 			     int objects)
2146 {
2147 	if (mem_alloc_profiling_enabled())
2148 		__alloc_tagging_slab_free_hook(s, slab, p, objects);
2149 }
2150 
2151 #else /* CONFIG_MEM_ALLOC_PROFILING */
2152 
2153 static inline void
2154 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2155 {
2156 }
2157 
2158 static inline void
2159 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2160 			     int objects)
2161 {
2162 }
2163 
2164 #endif /* CONFIG_MEM_ALLOC_PROFILING */
2165 
2166 
2167 #ifdef CONFIG_MEMCG
2168 
2169 static void memcg_alloc_abort_single(struct kmem_cache *s, void *object);
2170 
2171 static __fastpath_inline
2172 bool memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
2173 				gfp_t flags, size_t size, void **p)
2174 {
2175 	if (likely(!memcg_kmem_online()))
2176 		return true;
2177 
2178 	if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT)))
2179 		return true;
2180 
2181 	if (likely(__memcg_slab_post_alloc_hook(s, lru, flags, size, p)))
2182 		return true;
2183 
2184 	if (likely(size == 1)) {
2185 		memcg_alloc_abort_single(s, *p);
2186 		*p = NULL;
2187 	} else {
2188 		kmem_cache_free_bulk(s, size, p);
2189 	}
2190 
2191 	return false;
2192 }
2193 
2194 static __fastpath_inline
2195 void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2196 			  int objects)
2197 {
2198 	struct slabobj_ext *obj_exts;
2199 
2200 	if (!memcg_kmem_online())
2201 		return;
2202 
2203 	obj_exts = slab_obj_exts(slab);
2204 	if (likely(!obj_exts))
2205 		return;
2206 
2207 	__memcg_slab_free_hook(s, slab, p, objects, obj_exts);
2208 }
2209 
2210 static __fastpath_inline
2211 bool memcg_slab_post_charge(void *p, gfp_t flags)
2212 {
2213 	struct slabobj_ext *slab_exts;
2214 	struct kmem_cache *s;
2215 	struct folio *folio;
2216 	struct slab *slab;
2217 	unsigned long off;
2218 
2219 	folio = virt_to_folio(p);
2220 	if (!folio_test_slab(folio)) {
2221 		int size;
2222 
2223 		if (folio_memcg_kmem(folio))
2224 			return true;
2225 
2226 		if (__memcg_kmem_charge_page(folio_page(folio, 0), flags,
2227 					     folio_order(folio)))
2228 			return false;
2229 
2230 		/*
2231 		 * This folio has already been accounted in the global stats but
2232 		 * not in the memcg stats. So, subtract from the global and use
2233 		 * the interface which adds to both global and memcg stats.
2234 		 */
2235 		size = folio_size(folio);
2236 		node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size);
2237 		lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size);
2238 		return true;
2239 	}
2240 
2241 	slab = folio_slab(folio);
2242 	s = slab->slab_cache;
2243 
2244 	/*
2245 	 * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency
2246 	 * of slab_obj_exts being allocated from the same slab and thus the slab
2247 	 * becoming effectively unfreeable.
2248 	 */
2249 	if (is_kmalloc_normal(s))
2250 		return true;
2251 
2252 	/* Ignore already charged objects. */
2253 	slab_exts = slab_obj_exts(slab);
2254 	if (slab_exts) {
2255 		off = obj_to_index(s, slab, p);
2256 		if (unlikely(slab_exts[off].objcg))
2257 			return true;
2258 	}
2259 
2260 	return __memcg_slab_post_alloc_hook(s, NULL, flags, 1, &p);
2261 }
2262 
2263 #else /* CONFIG_MEMCG */
2264 static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s,
2265 					      struct list_lru *lru,
2266 					      gfp_t flags, size_t size,
2267 					      void **p)
2268 {
2269 	return true;
2270 }
2271 
2272 static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
2273 					void **p, int objects)
2274 {
2275 }
2276 
2277 static inline bool memcg_slab_post_charge(void *p, gfp_t flags)
2278 {
2279 	return true;
2280 }
2281 #endif /* CONFIG_MEMCG */
2282 
2283 #ifdef CONFIG_SLUB_RCU_DEBUG
2284 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head);
2285 
2286 struct rcu_delayed_free {
2287 	struct rcu_head head;
2288 	void *object;
2289 };
2290 #endif
2291 
2292 /*
2293  * Hooks for other subsystems that check memory allocations. In a typical
2294  * production configuration these hooks all should produce no code at all.
2295  *
2296  * Returns true if freeing of the object can proceed, false if its reuse
2297  * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned
2298  * to KFENCE.
2299  */
2300 static __always_inline
2301 bool slab_free_hook(struct kmem_cache *s, void *x, bool init,
2302 		    bool after_rcu_delay)
2303 {
2304 	/* Are the object contents still accessible? */
2305 	bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
2306 
2307 	kmemleak_free_recursive(x, s->flags);
2308 	kmsan_slab_free(s, x);
2309 
2310 	debug_check_no_locks_freed(x, s->object_size);
2311 
2312 	if (!(s->flags & SLAB_DEBUG_OBJECTS))
2313 		debug_check_no_obj_freed(x, s->object_size);
2314 
2315 	/* Use KCSAN to help debug racy use-after-free. */
2316 	if (!still_accessible)
2317 		__kcsan_check_access(x, s->object_size,
2318 				     KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
2319 
2320 	if (kfence_free(x))
2321 		return false;
2322 
2323 	/*
2324 	 * Give KASAN a chance to notice an invalid free operation before we
2325 	 * modify the object.
2326 	 */
2327 	if (kasan_slab_pre_free(s, x))
2328 		return false;
2329 
2330 #ifdef CONFIG_SLUB_RCU_DEBUG
2331 	if (still_accessible) {
2332 		struct rcu_delayed_free *delayed_free;
2333 
2334 		delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT);
2335 		if (delayed_free) {
2336 			/*
2337 			 * Let KASAN track our call stack as a "related work
2338 			 * creation", just like if the object had been freed
2339 			 * normally via kfree_rcu().
2340 			 * We have to do this manually because the rcu_head is
2341 			 * not located inside the object.
2342 			 */
2343 			kasan_record_aux_stack(x);
2344 
2345 			delayed_free->object = x;
2346 			call_rcu(&delayed_free->head, slab_free_after_rcu_debug);
2347 			return false;
2348 		}
2349 	}
2350 #endif /* CONFIG_SLUB_RCU_DEBUG */
2351 
2352 	/*
2353 	 * As memory initialization might be integrated into KASAN,
2354 	 * kasan_slab_free and initialization memset's must be
2355 	 * kept together to avoid discrepancies in behavior.
2356 	 *
2357 	 * The initialization memset's clear the object and the metadata,
2358 	 * but don't touch the SLAB redzone.
2359 	 *
2360 	 * The object's freepointer is also avoided if stored outside the
2361 	 * object.
2362 	 */
2363 	if (unlikely(init)) {
2364 		int rsize;
2365 		unsigned int inuse, orig_size;
2366 
2367 		inuse = get_info_end(s);
2368 		orig_size = get_orig_size(s, x);
2369 		if (!kasan_has_integrated_init())
2370 			memset(kasan_reset_tag(x), 0, orig_size);
2371 		rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
2372 		memset((char *)kasan_reset_tag(x) + inuse, 0,
2373 		       s->size - inuse - rsize);
2374 		/*
2375 		 * Restore orig_size, otherwize kmalloc redzone overwritten
2376 		 * would be reported
2377 		 */
2378 		set_orig_size(s, x, orig_size);
2379 
2380 	}
2381 	/* KASAN might put x into memory quarantine, delaying its reuse. */
2382 	return !kasan_slab_free(s, x, init, still_accessible);
2383 }
2384 
2385 static __fastpath_inline
2386 bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail,
2387 			     int *cnt)
2388 {
2389 
2390 	void *object;
2391 	void *next = *head;
2392 	void *old_tail = *tail;
2393 	bool init;
2394 
2395 	if (is_kfence_address(next)) {
2396 		slab_free_hook(s, next, false, false);
2397 		return false;
2398 	}
2399 
2400 	/* Head and tail of the reconstructed freelist */
2401 	*head = NULL;
2402 	*tail = NULL;
2403 
2404 	init = slab_want_init_on_free(s);
2405 
2406 	do {
2407 		object = next;
2408 		next = get_freepointer(s, object);
2409 
2410 		/* If object's reuse doesn't have to be delayed */
2411 		if (likely(slab_free_hook(s, object, init, false))) {
2412 			/* Move object to the new freelist */
2413 			set_freepointer(s, object, *head);
2414 			*head = object;
2415 			if (!*tail)
2416 				*tail = object;
2417 		} else {
2418 			/*
2419 			 * Adjust the reconstructed freelist depth
2420 			 * accordingly if object's reuse is delayed.
2421 			 */
2422 			--(*cnt);
2423 		}
2424 	} while (object != old_tail);
2425 
2426 	return *head != NULL;
2427 }
2428 
2429 static void *setup_object(struct kmem_cache *s, void *object)
2430 {
2431 	setup_object_debug(s, object);
2432 	object = kasan_init_slab_obj(s, object);
2433 	if (unlikely(s->ctor)) {
2434 		kasan_unpoison_new_object(s, object);
2435 		s->ctor(object);
2436 		kasan_poison_new_object(s, object);
2437 	}
2438 	return object;
2439 }
2440 
2441 /*
2442  * Slab allocation and freeing
2443  */
2444 static inline struct slab *alloc_slab_page(gfp_t flags, int node,
2445 		struct kmem_cache_order_objects oo)
2446 {
2447 	struct folio *folio;
2448 	struct slab *slab;
2449 	unsigned int order = oo_order(oo);
2450 
2451 	if (node == NUMA_NO_NODE)
2452 		folio = (struct folio *)alloc_frozen_pages(flags, order);
2453 	else
2454 		folio = (struct folio *)__alloc_frozen_pages(flags, order, node, NULL);
2455 
2456 	if (!folio)
2457 		return NULL;
2458 
2459 	slab = folio_slab(folio);
2460 	__folio_set_slab(folio);
2461 	if (folio_is_pfmemalloc(folio))
2462 		slab_set_pfmemalloc(slab);
2463 
2464 	return slab;
2465 }
2466 
2467 #ifdef CONFIG_SLAB_FREELIST_RANDOM
2468 /* Pre-initialize the random sequence cache */
2469 static int init_cache_random_seq(struct kmem_cache *s)
2470 {
2471 	unsigned int count = oo_objects(s->oo);
2472 	int err;
2473 
2474 	/* Bailout if already initialised */
2475 	if (s->random_seq)
2476 		return 0;
2477 
2478 	err = cache_random_seq_create(s, count, GFP_KERNEL);
2479 	if (err) {
2480 		pr_err("SLUB: Unable to initialize free list for %s\n",
2481 			s->name);
2482 		return err;
2483 	}
2484 
2485 	/* Transform to an offset on the set of pages */
2486 	if (s->random_seq) {
2487 		unsigned int i;
2488 
2489 		for (i = 0; i < count; i++)
2490 			s->random_seq[i] *= s->size;
2491 	}
2492 	return 0;
2493 }
2494 
2495 /* Initialize each random sequence freelist per cache */
2496 static void __init init_freelist_randomization(void)
2497 {
2498 	struct kmem_cache *s;
2499 
2500 	mutex_lock(&slab_mutex);
2501 
2502 	list_for_each_entry(s, &slab_caches, list)
2503 		init_cache_random_seq(s);
2504 
2505 	mutex_unlock(&slab_mutex);
2506 }
2507 
2508 /* Get the next entry on the pre-computed freelist randomized */
2509 static void *next_freelist_entry(struct kmem_cache *s,
2510 				unsigned long *pos, void *start,
2511 				unsigned long page_limit,
2512 				unsigned long freelist_count)
2513 {
2514 	unsigned int idx;
2515 
2516 	/*
2517 	 * If the target page allocation failed, the number of objects on the
2518 	 * page might be smaller than the usual size defined by the cache.
2519 	 */
2520 	do {
2521 		idx = s->random_seq[*pos];
2522 		*pos += 1;
2523 		if (*pos >= freelist_count)
2524 			*pos = 0;
2525 	} while (unlikely(idx >= page_limit));
2526 
2527 	return (char *)start + idx;
2528 }
2529 
2530 /* Shuffle the single linked freelist based on a random pre-computed sequence */
2531 static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
2532 {
2533 	void *start;
2534 	void *cur;
2535 	void *next;
2536 	unsigned long idx, pos, page_limit, freelist_count;
2537 
2538 	if (slab->objects < 2 || !s->random_seq)
2539 		return false;
2540 
2541 	freelist_count = oo_objects(s->oo);
2542 	pos = get_random_u32_below(freelist_count);
2543 
2544 	page_limit = slab->objects * s->size;
2545 	start = fixup_red_left(s, slab_address(slab));
2546 
2547 	/* First entry is used as the base of the freelist */
2548 	cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count);
2549 	cur = setup_object(s, cur);
2550 	slab->freelist = cur;
2551 
2552 	for (idx = 1; idx < slab->objects; idx++) {
2553 		next = next_freelist_entry(s, &pos, start, page_limit,
2554 			freelist_count);
2555 		next = setup_object(s, next);
2556 		set_freepointer(s, cur, next);
2557 		cur = next;
2558 	}
2559 	set_freepointer(s, cur, NULL);
2560 
2561 	return true;
2562 }
2563 #else
2564 static inline int init_cache_random_seq(struct kmem_cache *s)
2565 {
2566 	return 0;
2567 }
2568 static inline void init_freelist_randomization(void) { }
2569 static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
2570 {
2571 	return false;
2572 }
2573 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
2574 
2575 static __always_inline void account_slab(struct slab *slab, int order,
2576 					 struct kmem_cache *s, gfp_t gfp)
2577 {
2578 	if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT))
2579 		alloc_slab_obj_exts(slab, s, gfp, true);
2580 
2581 	mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
2582 			    PAGE_SIZE << order);
2583 }
2584 
2585 static __always_inline void unaccount_slab(struct slab *slab, int order,
2586 					   struct kmem_cache *s)
2587 {
2588 	/*
2589 	 * The slab object extensions should now be freed regardless of
2590 	 * whether mem_alloc_profiling_enabled() or not because profiling
2591 	 * might have been disabled after slab->obj_exts got allocated.
2592 	 */
2593 	free_slab_obj_exts(slab);
2594 
2595 	mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
2596 			    -(PAGE_SIZE << order));
2597 }
2598 
2599 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
2600 {
2601 	struct slab *slab;
2602 	struct kmem_cache_order_objects oo = s->oo;
2603 	gfp_t alloc_gfp;
2604 	void *start, *p, *next;
2605 	int idx;
2606 	bool shuffle;
2607 
2608 	flags &= gfp_allowed_mask;
2609 
2610 	flags |= s->allocflags;
2611 
2612 	/*
2613 	 * Let the initial higher-order allocation fail under memory pressure
2614 	 * so we fall-back to the minimum order allocation.
2615 	 */
2616 	alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
2617 	if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
2618 		alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
2619 
2620 	slab = alloc_slab_page(alloc_gfp, node, oo);
2621 	if (unlikely(!slab)) {
2622 		oo = s->min;
2623 		alloc_gfp = flags;
2624 		/*
2625 		 * Allocation may have failed due to fragmentation.
2626 		 * Try a lower order alloc if possible
2627 		 */
2628 		slab = alloc_slab_page(alloc_gfp, node, oo);
2629 		if (unlikely(!slab))
2630 			return NULL;
2631 		stat(s, ORDER_FALLBACK);
2632 	}
2633 
2634 	slab->objects = oo_objects(oo);
2635 	slab->inuse = 0;
2636 	slab->frozen = 0;
2637 	init_slab_obj_exts(slab);
2638 
2639 	account_slab(slab, oo_order(oo), s, flags);
2640 
2641 	slab->slab_cache = s;
2642 
2643 	kasan_poison_slab(slab);
2644 
2645 	start = slab_address(slab);
2646 
2647 	setup_slab_debug(s, slab, start);
2648 
2649 	shuffle = shuffle_freelist(s, slab);
2650 
2651 	if (!shuffle) {
2652 		start = fixup_red_left(s, start);
2653 		start = setup_object(s, start);
2654 		slab->freelist = start;
2655 		for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
2656 			next = p + s->size;
2657 			next = setup_object(s, next);
2658 			set_freepointer(s, p, next);
2659 			p = next;
2660 		}
2661 		set_freepointer(s, p, NULL);
2662 	}
2663 
2664 	return slab;
2665 }
2666 
2667 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
2668 {
2669 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
2670 		flags = kmalloc_fix_flags(flags);
2671 
2672 	WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2673 
2674 	return allocate_slab(s,
2675 		flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
2676 }
2677 
2678 static void __free_slab(struct kmem_cache *s, struct slab *slab)
2679 {
2680 	struct folio *folio = slab_folio(slab);
2681 	int order = folio_order(folio);
2682 	int pages = 1 << order;
2683 
2684 	__slab_clear_pfmemalloc(slab);
2685 	folio->mapping = NULL;
2686 	__folio_clear_slab(folio);
2687 	mm_account_reclaimed_pages(pages);
2688 	unaccount_slab(slab, order, s);
2689 	free_frozen_pages(&folio->page, order);
2690 }
2691 
2692 static void rcu_free_slab(struct rcu_head *h)
2693 {
2694 	struct slab *slab = container_of(h, struct slab, rcu_head);
2695 
2696 	__free_slab(slab->slab_cache, slab);
2697 }
2698 
2699 static void free_slab(struct kmem_cache *s, struct slab *slab)
2700 {
2701 	if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
2702 		void *p;
2703 
2704 		slab_pad_check(s, slab);
2705 		for_each_object(p, s, slab_address(slab), slab->objects)
2706 			check_object(s, slab, p, SLUB_RED_INACTIVE);
2707 	}
2708 
2709 	if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
2710 		call_rcu(&slab->rcu_head, rcu_free_slab);
2711 	else
2712 		__free_slab(s, slab);
2713 }
2714 
2715 static void discard_slab(struct kmem_cache *s, struct slab *slab)
2716 {
2717 	dec_slabs_node(s, slab_nid(slab), slab->objects);
2718 	free_slab(s, slab);
2719 }
2720 
2721 /*
2722  * SLUB reuses PG_workingset bit to keep track of whether it's on
2723  * the per-node partial list.
2724  */
2725 static inline bool slab_test_node_partial(const struct slab *slab)
2726 {
2727 	return folio_test_workingset(slab_folio(slab));
2728 }
2729 
2730 static inline void slab_set_node_partial(struct slab *slab)
2731 {
2732 	set_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
2733 }
2734 
2735 static inline void slab_clear_node_partial(struct slab *slab)
2736 {
2737 	clear_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
2738 }
2739 
2740 /*
2741  * Management of partially allocated slabs.
2742  */
2743 static inline void
2744 __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
2745 {
2746 	n->nr_partial++;
2747 	if (tail == DEACTIVATE_TO_TAIL)
2748 		list_add_tail(&slab->slab_list, &n->partial);
2749 	else
2750 		list_add(&slab->slab_list, &n->partial);
2751 	slab_set_node_partial(slab);
2752 }
2753 
2754 static inline void add_partial(struct kmem_cache_node *n,
2755 				struct slab *slab, int tail)
2756 {
2757 	lockdep_assert_held(&n->list_lock);
2758 	__add_partial(n, slab, tail);
2759 }
2760 
2761 static inline void remove_partial(struct kmem_cache_node *n,
2762 					struct slab *slab)
2763 {
2764 	lockdep_assert_held(&n->list_lock);
2765 	list_del(&slab->slab_list);
2766 	slab_clear_node_partial(slab);
2767 	n->nr_partial--;
2768 }
2769 
2770 /*
2771  * Called only for kmem_cache_debug() caches instead of remove_partial(), with a
2772  * slab from the n->partial list. Remove only a single object from the slab, do
2773  * the alloc_debug_processing() checks and leave the slab on the list, or move
2774  * it to full list if it was the last free object.
2775  */
2776 static void *alloc_single_from_partial(struct kmem_cache *s,
2777 		struct kmem_cache_node *n, struct slab *slab, int orig_size)
2778 {
2779 	void *object;
2780 
2781 	lockdep_assert_held(&n->list_lock);
2782 
2783 	object = slab->freelist;
2784 	slab->freelist = get_freepointer(s, object);
2785 	slab->inuse++;
2786 
2787 	if (!alloc_debug_processing(s, slab, object, orig_size)) {
2788 		if (folio_test_slab(slab_folio(slab)))
2789 			remove_partial(n, slab);
2790 		return NULL;
2791 	}
2792 
2793 	if (slab->inuse == slab->objects) {
2794 		remove_partial(n, slab);
2795 		add_full(s, n, slab);
2796 	}
2797 
2798 	return object;
2799 }
2800 
2801 /*
2802  * Called only for kmem_cache_debug() caches to allocate from a freshly
2803  * allocated slab. Allocate a single object instead of whole freelist
2804  * and put the slab to the partial (or full) list.
2805  */
2806 static void *alloc_single_from_new_slab(struct kmem_cache *s,
2807 					struct slab *slab, int orig_size)
2808 {
2809 	int nid = slab_nid(slab);
2810 	struct kmem_cache_node *n = get_node(s, nid);
2811 	unsigned long flags;
2812 	void *object;
2813 
2814 
2815 	object = slab->freelist;
2816 	slab->freelist = get_freepointer(s, object);
2817 	slab->inuse = 1;
2818 
2819 	if (!alloc_debug_processing(s, slab, object, orig_size))
2820 		/*
2821 		 * It's not really expected that this would fail on a
2822 		 * freshly allocated slab, but a concurrent memory
2823 		 * corruption in theory could cause that.
2824 		 */
2825 		return NULL;
2826 
2827 	spin_lock_irqsave(&n->list_lock, flags);
2828 
2829 	if (slab->inuse == slab->objects)
2830 		add_full(s, n, slab);
2831 	else
2832 		add_partial(n, slab, DEACTIVATE_TO_HEAD);
2833 
2834 	inc_slabs_node(s, nid, slab->objects);
2835 	spin_unlock_irqrestore(&n->list_lock, flags);
2836 
2837 	return object;
2838 }
2839 
2840 #ifdef CONFIG_SLUB_CPU_PARTIAL
2841 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
2842 #else
2843 static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
2844 				   int drain) { }
2845 #endif
2846 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
2847 
2848 /*
2849  * Try to allocate a partial slab from a specific node.
2850  */
2851 static struct slab *get_partial_node(struct kmem_cache *s,
2852 				     struct kmem_cache_node *n,
2853 				     struct partial_context *pc)
2854 {
2855 	struct slab *slab, *slab2, *partial = NULL;
2856 	unsigned long flags;
2857 	unsigned int partial_slabs = 0;
2858 
2859 	/*
2860 	 * Racy check. If we mistakenly see no partial slabs then we
2861 	 * just allocate an empty slab. If we mistakenly try to get a
2862 	 * partial slab and there is none available then get_partial()
2863 	 * will return NULL.
2864 	 */
2865 	if (!n || !n->nr_partial)
2866 		return NULL;
2867 
2868 	spin_lock_irqsave(&n->list_lock, flags);
2869 	list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
2870 		if (!pfmemalloc_match(slab, pc->flags))
2871 			continue;
2872 
2873 		if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
2874 			void *object = alloc_single_from_partial(s, n, slab,
2875 							pc->orig_size);
2876 			if (object) {
2877 				partial = slab;
2878 				pc->object = object;
2879 				break;
2880 			}
2881 			continue;
2882 		}
2883 
2884 		remove_partial(n, slab);
2885 
2886 		if (!partial) {
2887 			partial = slab;
2888 			stat(s, ALLOC_FROM_PARTIAL);
2889 
2890 			if ((slub_get_cpu_partial(s) == 0)) {
2891 				break;
2892 			}
2893 		} else {
2894 			put_cpu_partial(s, slab, 0);
2895 			stat(s, CPU_PARTIAL_NODE);
2896 
2897 			if (++partial_slabs > slub_get_cpu_partial(s) / 2) {
2898 				break;
2899 			}
2900 		}
2901 	}
2902 	spin_unlock_irqrestore(&n->list_lock, flags);
2903 	return partial;
2904 }
2905 
2906 /*
2907  * Get a slab from somewhere. Search in increasing NUMA distances.
2908  */
2909 static struct slab *get_any_partial(struct kmem_cache *s,
2910 				    struct partial_context *pc)
2911 {
2912 #ifdef CONFIG_NUMA
2913 	struct zonelist *zonelist;
2914 	struct zoneref *z;
2915 	struct zone *zone;
2916 	enum zone_type highest_zoneidx = gfp_zone(pc->flags);
2917 	struct slab *slab;
2918 	unsigned int cpuset_mems_cookie;
2919 
2920 	/*
2921 	 * The defrag ratio allows a configuration of the tradeoffs between
2922 	 * inter node defragmentation and node local allocations. A lower
2923 	 * defrag_ratio increases the tendency to do local allocations
2924 	 * instead of attempting to obtain partial slabs from other nodes.
2925 	 *
2926 	 * If the defrag_ratio is set to 0 then kmalloc() always
2927 	 * returns node local objects. If the ratio is higher then kmalloc()
2928 	 * may return off node objects because partial slabs are obtained
2929 	 * from other nodes and filled up.
2930 	 *
2931 	 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2932 	 * (which makes defrag_ratio = 1000) then every (well almost)
2933 	 * allocation will first attempt to defrag slab caches on other nodes.
2934 	 * This means scanning over all nodes to look for partial slabs which
2935 	 * may be expensive if we do it every time we are trying to find a slab
2936 	 * with available objects.
2937 	 */
2938 	if (!s->remote_node_defrag_ratio ||
2939 			get_cycles() % 1024 > s->remote_node_defrag_ratio)
2940 		return NULL;
2941 
2942 	do {
2943 		cpuset_mems_cookie = read_mems_allowed_begin();
2944 		zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
2945 		for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2946 			struct kmem_cache_node *n;
2947 
2948 			n = get_node(s, zone_to_nid(zone));
2949 
2950 			if (n && cpuset_zone_allowed(zone, pc->flags) &&
2951 					n->nr_partial > s->min_partial) {
2952 				slab = get_partial_node(s, n, pc);
2953 				if (slab) {
2954 					/*
2955 					 * Don't check read_mems_allowed_retry()
2956 					 * here - if mems_allowed was updated in
2957 					 * parallel, that was a harmless race
2958 					 * between allocation and the cpuset
2959 					 * update
2960 					 */
2961 					return slab;
2962 				}
2963 			}
2964 		}
2965 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
2966 #endif	/* CONFIG_NUMA */
2967 	return NULL;
2968 }
2969 
2970 /*
2971  * Get a partial slab, lock it and return it.
2972  */
2973 static struct slab *get_partial(struct kmem_cache *s, int node,
2974 				struct partial_context *pc)
2975 {
2976 	struct slab *slab;
2977 	int searchnode = node;
2978 
2979 	if (node == NUMA_NO_NODE)
2980 		searchnode = numa_mem_id();
2981 
2982 	slab = get_partial_node(s, get_node(s, searchnode), pc);
2983 	if (slab || (node != NUMA_NO_NODE && (pc->flags & __GFP_THISNODE)))
2984 		return slab;
2985 
2986 	return get_any_partial(s, pc);
2987 }
2988 
2989 #ifndef CONFIG_SLUB_TINY
2990 
2991 #ifdef CONFIG_PREEMPTION
2992 /*
2993  * Calculate the next globally unique transaction for disambiguation
2994  * during cmpxchg. The transactions start with the cpu number and are then
2995  * incremented by CONFIG_NR_CPUS.
2996  */
2997 #define TID_STEP  roundup_pow_of_two(CONFIG_NR_CPUS)
2998 #else
2999 /*
3000  * No preemption supported therefore also no need to check for
3001  * different cpus.
3002  */
3003 #define TID_STEP 1
3004 #endif /* CONFIG_PREEMPTION */
3005 
3006 static inline unsigned long next_tid(unsigned long tid)
3007 {
3008 	return tid + TID_STEP;
3009 }
3010 
3011 #ifdef SLUB_DEBUG_CMPXCHG
3012 static inline unsigned int tid_to_cpu(unsigned long tid)
3013 {
3014 	return tid % TID_STEP;
3015 }
3016 
3017 static inline unsigned long tid_to_event(unsigned long tid)
3018 {
3019 	return tid / TID_STEP;
3020 }
3021 #endif
3022 
3023 static inline unsigned int init_tid(int cpu)
3024 {
3025 	return cpu;
3026 }
3027 
3028 static inline void note_cmpxchg_failure(const char *n,
3029 		const struct kmem_cache *s, unsigned long tid)
3030 {
3031 #ifdef SLUB_DEBUG_CMPXCHG
3032 	unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
3033 
3034 	pr_info("%s %s: cmpxchg redo ", n, s->name);
3035 
3036 #ifdef CONFIG_PREEMPTION
3037 	if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
3038 		pr_warn("due to cpu change %d -> %d\n",
3039 			tid_to_cpu(tid), tid_to_cpu(actual_tid));
3040 	else
3041 #endif
3042 	if (tid_to_event(tid) != tid_to_event(actual_tid))
3043 		pr_warn("due to cpu running other code. Event %ld->%ld\n",
3044 			tid_to_event(tid), tid_to_event(actual_tid));
3045 	else
3046 		pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
3047 			actual_tid, tid, next_tid(tid));
3048 #endif
3049 	stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
3050 }
3051 
3052 static void init_kmem_cache_cpus(struct kmem_cache *s)
3053 {
3054 	int cpu;
3055 	struct kmem_cache_cpu *c;
3056 
3057 	for_each_possible_cpu(cpu) {
3058 		c = per_cpu_ptr(s->cpu_slab, cpu);
3059 		local_lock_init(&c->lock);
3060 		c->tid = init_tid(cpu);
3061 	}
3062 }
3063 
3064 /*
3065  * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
3066  * unfreezes the slabs and puts it on the proper list.
3067  * Assumes the slab has been already safely taken away from kmem_cache_cpu
3068  * by the caller.
3069  */
3070 static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
3071 			    void *freelist)
3072 {
3073 	struct kmem_cache_node *n = get_node(s, slab_nid(slab));
3074 	int free_delta = 0;
3075 	void *nextfree, *freelist_iter, *freelist_tail;
3076 	int tail = DEACTIVATE_TO_HEAD;
3077 	unsigned long flags = 0;
3078 	struct slab new;
3079 	struct slab old;
3080 
3081 	if (READ_ONCE(slab->freelist)) {
3082 		stat(s, DEACTIVATE_REMOTE_FREES);
3083 		tail = DEACTIVATE_TO_TAIL;
3084 	}
3085 
3086 	/*
3087 	 * Stage one: Count the objects on cpu's freelist as free_delta and
3088 	 * remember the last object in freelist_tail for later splicing.
3089 	 */
3090 	freelist_tail = NULL;
3091 	freelist_iter = freelist;
3092 	while (freelist_iter) {
3093 		nextfree = get_freepointer(s, freelist_iter);
3094 
3095 		/*
3096 		 * If 'nextfree' is invalid, it is possible that the object at
3097 		 * 'freelist_iter' is already corrupted.  So isolate all objects
3098 		 * starting at 'freelist_iter' by skipping them.
3099 		 */
3100 		if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
3101 			break;
3102 
3103 		freelist_tail = freelist_iter;
3104 		free_delta++;
3105 
3106 		freelist_iter = nextfree;
3107 	}
3108 
3109 	/*
3110 	 * Stage two: Unfreeze the slab while splicing the per-cpu
3111 	 * freelist to the head of slab's freelist.
3112 	 */
3113 	do {
3114 		old.freelist = READ_ONCE(slab->freelist);
3115 		old.counters = READ_ONCE(slab->counters);
3116 		VM_BUG_ON(!old.frozen);
3117 
3118 		/* Determine target state of the slab */
3119 		new.counters = old.counters;
3120 		new.frozen = 0;
3121 		if (freelist_tail) {
3122 			new.inuse -= free_delta;
3123 			set_freepointer(s, freelist_tail, old.freelist);
3124 			new.freelist = freelist;
3125 		} else {
3126 			new.freelist = old.freelist;
3127 		}
3128 	} while (!slab_update_freelist(s, slab,
3129 		old.freelist, old.counters,
3130 		new.freelist, new.counters,
3131 		"unfreezing slab"));
3132 
3133 	/*
3134 	 * Stage three: Manipulate the slab list based on the updated state.
3135 	 */
3136 	if (!new.inuse && n->nr_partial >= s->min_partial) {
3137 		stat(s, DEACTIVATE_EMPTY);
3138 		discard_slab(s, slab);
3139 		stat(s, FREE_SLAB);
3140 	} else if (new.freelist) {
3141 		spin_lock_irqsave(&n->list_lock, flags);
3142 		add_partial(n, slab, tail);
3143 		spin_unlock_irqrestore(&n->list_lock, flags);
3144 		stat(s, tail);
3145 	} else {
3146 		stat(s, DEACTIVATE_FULL);
3147 	}
3148 }
3149 
3150 #ifdef CONFIG_SLUB_CPU_PARTIAL
3151 static void __put_partials(struct kmem_cache *s, struct slab *partial_slab)
3152 {
3153 	struct kmem_cache_node *n = NULL, *n2 = NULL;
3154 	struct slab *slab, *slab_to_discard = NULL;
3155 	unsigned long flags = 0;
3156 
3157 	while (partial_slab) {
3158 		slab = partial_slab;
3159 		partial_slab = slab->next;
3160 
3161 		n2 = get_node(s, slab_nid(slab));
3162 		if (n != n2) {
3163 			if (n)
3164 				spin_unlock_irqrestore(&n->list_lock, flags);
3165 
3166 			n = n2;
3167 			spin_lock_irqsave(&n->list_lock, flags);
3168 		}
3169 
3170 		if (unlikely(!slab->inuse && n->nr_partial >= s->min_partial)) {
3171 			slab->next = slab_to_discard;
3172 			slab_to_discard = slab;
3173 		} else {
3174 			add_partial(n, slab, DEACTIVATE_TO_TAIL);
3175 			stat(s, FREE_ADD_PARTIAL);
3176 		}
3177 	}
3178 
3179 	if (n)
3180 		spin_unlock_irqrestore(&n->list_lock, flags);
3181 
3182 	while (slab_to_discard) {
3183 		slab = slab_to_discard;
3184 		slab_to_discard = slab_to_discard->next;
3185 
3186 		stat(s, DEACTIVATE_EMPTY);
3187 		discard_slab(s, slab);
3188 		stat(s, FREE_SLAB);
3189 	}
3190 }
3191 
3192 /*
3193  * Put all the cpu partial slabs to the node partial list.
3194  */
3195 static void put_partials(struct kmem_cache *s)
3196 {
3197 	struct slab *partial_slab;
3198 	unsigned long flags;
3199 
3200 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3201 	partial_slab = this_cpu_read(s->cpu_slab->partial);
3202 	this_cpu_write(s->cpu_slab->partial, NULL);
3203 	local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3204 
3205 	if (partial_slab)
3206 		__put_partials(s, partial_slab);
3207 }
3208 
3209 static void put_partials_cpu(struct kmem_cache *s,
3210 			     struct kmem_cache_cpu *c)
3211 {
3212 	struct slab *partial_slab;
3213 
3214 	partial_slab = slub_percpu_partial(c);
3215 	c->partial = NULL;
3216 
3217 	if (partial_slab)
3218 		__put_partials(s, partial_slab);
3219 }
3220 
3221 /*
3222  * Put a slab into a partial slab slot if available.
3223  *
3224  * If we did not find a slot then simply move all the partials to the
3225  * per node partial list.
3226  */
3227 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
3228 {
3229 	struct slab *oldslab;
3230 	struct slab *slab_to_put = NULL;
3231 	unsigned long flags;
3232 	int slabs = 0;
3233 
3234 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3235 
3236 	oldslab = this_cpu_read(s->cpu_slab->partial);
3237 
3238 	if (oldslab) {
3239 		if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
3240 			/*
3241 			 * Partial array is full. Move the existing set to the
3242 			 * per node partial list. Postpone the actual unfreezing
3243 			 * outside of the critical section.
3244 			 */
3245 			slab_to_put = oldslab;
3246 			oldslab = NULL;
3247 		} else {
3248 			slabs = oldslab->slabs;
3249 		}
3250 	}
3251 
3252 	slabs++;
3253 
3254 	slab->slabs = slabs;
3255 	slab->next = oldslab;
3256 
3257 	this_cpu_write(s->cpu_slab->partial, slab);
3258 
3259 	local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3260 
3261 	if (slab_to_put) {
3262 		__put_partials(s, slab_to_put);
3263 		stat(s, CPU_PARTIAL_DRAIN);
3264 	}
3265 }
3266 
3267 #else	/* CONFIG_SLUB_CPU_PARTIAL */
3268 
3269 static inline void put_partials(struct kmem_cache *s) { }
3270 static inline void put_partials_cpu(struct kmem_cache *s,
3271 				    struct kmem_cache_cpu *c) { }
3272 
3273 #endif	/* CONFIG_SLUB_CPU_PARTIAL */
3274 
3275 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
3276 {
3277 	unsigned long flags;
3278 	struct slab *slab;
3279 	void *freelist;
3280 
3281 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3282 
3283 	slab = c->slab;
3284 	freelist = c->freelist;
3285 
3286 	c->slab = NULL;
3287 	c->freelist = NULL;
3288 	c->tid = next_tid(c->tid);
3289 
3290 	local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3291 
3292 	if (slab) {
3293 		deactivate_slab(s, slab, freelist);
3294 		stat(s, CPUSLAB_FLUSH);
3295 	}
3296 }
3297 
3298 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
3299 {
3300 	struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
3301 	void *freelist = c->freelist;
3302 	struct slab *slab = c->slab;
3303 
3304 	c->slab = NULL;
3305 	c->freelist = NULL;
3306 	c->tid = next_tid(c->tid);
3307 
3308 	if (slab) {
3309 		deactivate_slab(s, slab, freelist);
3310 		stat(s, CPUSLAB_FLUSH);
3311 	}
3312 
3313 	put_partials_cpu(s, c);
3314 }
3315 
3316 struct slub_flush_work {
3317 	struct work_struct work;
3318 	struct kmem_cache *s;
3319 	bool skip;
3320 };
3321 
3322 /*
3323  * Flush cpu slab.
3324  *
3325  * Called from CPU work handler with migration disabled.
3326  */
3327 static void flush_cpu_slab(struct work_struct *w)
3328 {
3329 	struct kmem_cache *s;
3330 	struct kmem_cache_cpu *c;
3331 	struct slub_flush_work *sfw;
3332 
3333 	sfw = container_of(w, struct slub_flush_work, work);
3334 
3335 	s = sfw->s;
3336 	c = this_cpu_ptr(s->cpu_slab);
3337 
3338 	if (c->slab)
3339 		flush_slab(s, c);
3340 
3341 	put_partials(s);
3342 }
3343 
3344 static bool has_cpu_slab(int cpu, struct kmem_cache *s)
3345 {
3346 	struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
3347 
3348 	return c->slab || slub_percpu_partial(c);
3349 }
3350 
3351 static DEFINE_MUTEX(flush_lock);
3352 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
3353 
3354 static void flush_all_cpus_locked(struct kmem_cache *s)
3355 {
3356 	struct slub_flush_work *sfw;
3357 	unsigned int cpu;
3358 
3359 	lockdep_assert_cpus_held();
3360 	mutex_lock(&flush_lock);
3361 
3362 	for_each_online_cpu(cpu) {
3363 		sfw = &per_cpu(slub_flush, cpu);
3364 		if (!has_cpu_slab(cpu, s)) {
3365 			sfw->skip = true;
3366 			continue;
3367 		}
3368 		INIT_WORK(&sfw->work, flush_cpu_slab);
3369 		sfw->skip = false;
3370 		sfw->s = s;
3371 		queue_work_on(cpu, flushwq, &sfw->work);
3372 	}
3373 
3374 	for_each_online_cpu(cpu) {
3375 		sfw = &per_cpu(slub_flush, cpu);
3376 		if (sfw->skip)
3377 			continue;
3378 		flush_work(&sfw->work);
3379 	}
3380 
3381 	mutex_unlock(&flush_lock);
3382 }
3383 
3384 static void flush_all(struct kmem_cache *s)
3385 {
3386 	cpus_read_lock();
3387 	flush_all_cpus_locked(s);
3388 	cpus_read_unlock();
3389 }
3390 
3391 /*
3392  * Use the cpu notifier to insure that the cpu slabs are flushed when
3393  * necessary.
3394  */
3395 static int slub_cpu_dead(unsigned int cpu)
3396 {
3397 	struct kmem_cache *s;
3398 
3399 	mutex_lock(&slab_mutex);
3400 	list_for_each_entry(s, &slab_caches, list)
3401 		__flush_cpu_slab(s, cpu);
3402 	mutex_unlock(&slab_mutex);
3403 	return 0;
3404 }
3405 
3406 #else /* CONFIG_SLUB_TINY */
3407 static inline void flush_all_cpus_locked(struct kmem_cache *s) { }
3408 static inline void flush_all(struct kmem_cache *s) { }
3409 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { }
3410 static inline int slub_cpu_dead(unsigned int cpu) { return 0; }
3411 #endif /* CONFIG_SLUB_TINY */
3412 
3413 /*
3414  * Check if the objects in a per cpu structure fit numa
3415  * locality expectations.
3416  */
3417 static inline int node_match(struct slab *slab, int node)
3418 {
3419 #ifdef CONFIG_NUMA
3420 	if (node != NUMA_NO_NODE && slab_nid(slab) != node)
3421 		return 0;
3422 #endif
3423 	return 1;
3424 }
3425 
3426 #ifdef CONFIG_SLUB_DEBUG
3427 static int count_free(struct slab *slab)
3428 {
3429 	return slab->objects - slab->inuse;
3430 }
3431 
3432 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
3433 {
3434 	return atomic_long_read(&n->total_objects);
3435 }
3436 
3437 /* Supports checking bulk free of a constructed freelist */
3438 static inline bool free_debug_processing(struct kmem_cache *s,
3439 	struct slab *slab, void *head, void *tail, int *bulk_cnt,
3440 	unsigned long addr, depot_stack_handle_t handle)
3441 {
3442 	bool checks_ok = false;
3443 	void *object = head;
3444 	int cnt = 0;
3445 
3446 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3447 		if (!check_slab(s, slab))
3448 			goto out;
3449 	}
3450 
3451 	if (slab->inuse < *bulk_cnt) {
3452 		slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
3453 			 slab->inuse, *bulk_cnt);
3454 		goto out;
3455 	}
3456 
3457 next_object:
3458 
3459 	if (++cnt > *bulk_cnt)
3460 		goto out_cnt;
3461 
3462 	if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3463 		if (!free_consistency_checks(s, slab, object, addr))
3464 			goto out;
3465 	}
3466 
3467 	if (s->flags & SLAB_STORE_USER)
3468 		set_track_update(s, object, TRACK_FREE, addr, handle);
3469 	trace(s, slab, object, 0);
3470 	/* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
3471 	init_object(s, object, SLUB_RED_INACTIVE);
3472 
3473 	/* Reached end of constructed freelist yet? */
3474 	if (object != tail) {
3475 		object = get_freepointer(s, object);
3476 		goto next_object;
3477 	}
3478 	checks_ok = true;
3479 
3480 out_cnt:
3481 	if (cnt != *bulk_cnt) {
3482 		slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
3483 			 *bulk_cnt, cnt);
3484 		*bulk_cnt = cnt;
3485 	}
3486 
3487 out:
3488 
3489 	if (!checks_ok)
3490 		slab_fix(s, "Object at 0x%p not freed", object);
3491 
3492 	return checks_ok;
3493 }
3494 #endif /* CONFIG_SLUB_DEBUG */
3495 
3496 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
3497 static unsigned long count_partial(struct kmem_cache_node *n,
3498 					int (*get_count)(struct slab *))
3499 {
3500 	unsigned long flags;
3501 	unsigned long x = 0;
3502 	struct slab *slab;
3503 
3504 	spin_lock_irqsave(&n->list_lock, flags);
3505 	list_for_each_entry(slab, &n->partial, slab_list)
3506 		x += get_count(slab);
3507 	spin_unlock_irqrestore(&n->list_lock, flags);
3508 	return x;
3509 }
3510 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
3511 
3512 #ifdef CONFIG_SLUB_DEBUG
3513 #define MAX_PARTIAL_TO_SCAN 10000
3514 
3515 static unsigned long count_partial_free_approx(struct kmem_cache_node *n)
3516 {
3517 	unsigned long flags;
3518 	unsigned long x = 0;
3519 	struct slab *slab;
3520 
3521 	spin_lock_irqsave(&n->list_lock, flags);
3522 	if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
3523 		list_for_each_entry(slab, &n->partial, slab_list)
3524 			x += slab->objects - slab->inuse;
3525 	} else {
3526 		/*
3527 		 * For a long list, approximate the total count of objects in
3528 		 * it to meet the limit on the number of slabs to scan.
3529 		 * Scan from both the list's head and tail for better accuracy.
3530 		 */
3531 		unsigned long scanned = 0;
3532 
3533 		list_for_each_entry(slab, &n->partial, slab_list) {
3534 			x += slab->objects - slab->inuse;
3535 			if (++scanned == MAX_PARTIAL_TO_SCAN / 2)
3536 				break;
3537 		}
3538 		list_for_each_entry_reverse(slab, &n->partial, slab_list) {
3539 			x += slab->objects - slab->inuse;
3540 			if (++scanned == MAX_PARTIAL_TO_SCAN)
3541 				break;
3542 		}
3543 		x = mult_frac(x, n->nr_partial, scanned);
3544 		x = min(x, node_nr_objs(n));
3545 	}
3546 	spin_unlock_irqrestore(&n->list_lock, flags);
3547 	return x;
3548 }
3549 
3550 static noinline void
3551 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
3552 {
3553 	static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
3554 				      DEFAULT_RATELIMIT_BURST);
3555 	int cpu = raw_smp_processor_id();
3556 	int node;
3557 	struct kmem_cache_node *n;
3558 
3559 	if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
3560 		return;
3561 
3562 	pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
3563 		cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
3564 	pr_warn("  cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
3565 		s->name, s->object_size, s->size, oo_order(s->oo),
3566 		oo_order(s->min));
3567 
3568 	if (oo_order(s->min) > get_order(s->object_size))
3569 		pr_warn("  %s debugging increased min order, use slab_debug=O to disable.\n",
3570 			s->name);
3571 
3572 	for_each_kmem_cache_node(s, node, n) {
3573 		unsigned long nr_slabs;
3574 		unsigned long nr_objs;
3575 		unsigned long nr_free;
3576 
3577 		nr_free  = count_partial_free_approx(n);
3578 		nr_slabs = node_nr_slabs(n);
3579 		nr_objs  = node_nr_objs(n);
3580 
3581 		pr_warn("  node %d: slabs: %ld, objs: %ld, free: %ld\n",
3582 			node, nr_slabs, nr_objs, nr_free);
3583 	}
3584 }
3585 #else /* CONFIG_SLUB_DEBUG */
3586 static inline void
3587 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
3588 #endif
3589 
3590 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
3591 {
3592 	if (unlikely(slab_test_pfmemalloc(slab)))
3593 		return gfp_pfmemalloc_allowed(gfpflags);
3594 
3595 	return true;
3596 }
3597 
3598 #ifndef CONFIG_SLUB_TINY
3599 static inline bool
3600 __update_cpu_freelist_fast(struct kmem_cache *s,
3601 			   void *freelist_old, void *freelist_new,
3602 			   unsigned long tid)
3603 {
3604 	freelist_aba_t old = { .freelist = freelist_old, .counter = tid };
3605 	freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) };
3606 
3607 	return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full,
3608 					     &old.full, new.full);
3609 }
3610 
3611 /*
3612  * Check the slab->freelist and either transfer the freelist to the
3613  * per cpu freelist or deactivate the slab.
3614  *
3615  * The slab is still frozen if the return value is not NULL.
3616  *
3617  * If this function returns NULL then the slab has been unfrozen.
3618  */
3619 static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
3620 {
3621 	struct slab new;
3622 	unsigned long counters;
3623 	void *freelist;
3624 
3625 	lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3626 
3627 	do {
3628 		freelist = slab->freelist;
3629 		counters = slab->counters;
3630 
3631 		new.counters = counters;
3632 
3633 		new.inuse = slab->objects;
3634 		new.frozen = freelist != NULL;
3635 
3636 	} while (!__slab_update_freelist(s, slab,
3637 		freelist, counters,
3638 		NULL, new.counters,
3639 		"get_freelist"));
3640 
3641 	return freelist;
3642 }
3643 
3644 /*
3645  * Freeze the partial slab and return the pointer to the freelist.
3646  */
3647 static inline void *freeze_slab(struct kmem_cache *s, struct slab *slab)
3648 {
3649 	struct slab new;
3650 	unsigned long counters;
3651 	void *freelist;
3652 
3653 	do {
3654 		freelist = slab->freelist;
3655 		counters = slab->counters;
3656 
3657 		new.counters = counters;
3658 		VM_BUG_ON(new.frozen);
3659 
3660 		new.inuse = slab->objects;
3661 		new.frozen = 1;
3662 
3663 	} while (!slab_update_freelist(s, slab,
3664 		freelist, counters,
3665 		NULL, new.counters,
3666 		"freeze_slab"));
3667 
3668 	return freelist;
3669 }
3670 
3671 /*
3672  * Slow path. The lockless freelist is empty or we need to perform
3673  * debugging duties.
3674  *
3675  * Processing is still very fast if new objects have been freed to the
3676  * regular freelist. In that case we simply take over the regular freelist
3677  * as the lockless freelist and zap the regular freelist.
3678  *
3679  * If that is not working then we fall back to the partial lists. We take the
3680  * first element of the freelist as the object to allocate now and move the
3681  * rest of the freelist to the lockless freelist.
3682  *
3683  * And if we were unable to get a new slab from the partial slab lists then
3684  * we need to allocate a new slab. This is the slowest path since it involves
3685  * a call to the page allocator and the setup of a new slab.
3686  *
3687  * Version of __slab_alloc to use when we know that preemption is
3688  * already disabled (which is the case for bulk allocation).
3689  */
3690 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3691 			  unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3692 {
3693 	void *freelist;
3694 	struct slab *slab;
3695 	unsigned long flags;
3696 	struct partial_context pc;
3697 	bool try_thisnode = true;
3698 
3699 	stat(s, ALLOC_SLOWPATH);
3700 
3701 reread_slab:
3702 
3703 	slab = READ_ONCE(c->slab);
3704 	if (!slab) {
3705 		/*
3706 		 * if the node is not online or has no normal memory, just
3707 		 * ignore the node constraint
3708 		 */
3709 		if (unlikely(node != NUMA_NO_NODE &&
3710 			     !node_isset(node, slab_nodes)))
3711 			node = NUMA_NO_NODE;
3712 		goto new_slab;
3713 	}
3714 
3715 	if (unlikely(!node_match(slab, node))) {
3716 		/*
3717 		 * same as above but node_match() being false already
3718 		 * implies node != NUMA_NO_NODE
3719 		 */
3720 		if (!node_isset(node, slab_nodes)) {
3721 			node = NUMA_NO_NODE;
3722 		} else {
3723 			stat(s, ALLOC_NODE_MISMATCH);
3724 			goto deactivate_slab;
3725 		}
3726 	}
3727 
3728 	/*
3729 	 * By rights, we should be searching for a slab page that was
3730 	 * PFMEMALLOC but right now, we are losing the pfmemalloc
3731 	 * information when the page leaves the per-cpu allocator
3732 	 */
3733 	if (unlikely(!pfmemalloc_match(slab, gfpflags)))
3734 		goto deactivate_slab;
3735 
3736 	/* must check again c->slab in case we got preempted and it changed */
3737 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3738 	if (unlikely(slab != c->slab)) {
3739 		local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3740 		goto reread_slab;
3741 	}
3742 	freelist = c->freelist;
3743 	if (freelist)
3744 		goto load_freelist;
3745 
3746 	freelist = get_freelist(s, slab);
3747 
3748 	if (!freelist) {
3749 		c->slab = NULL;
3750 		c->tid = next_tid(c->tid);
3751 		local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3752 		stat(s, DEACTIVATE_BYPASS);
3753 		goto new_slab;
3754 	}
3755 
3756 	stat(s, ALLOC_REFILL);
3757 
3758 load_freelist:
3759 
3760 	lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3761 
3762 	/*
3763 	 * freelist is pointing to the list of objects to be used.
3764 	 * slab is pointing to the slab from which the objects are obtained.
3765 	 * That slab must be frozen for per cpu allocations to work.
3766 	 */
3767 	VM_BUG_ON(!c->slab->frozen);
3768 	c->freelist = get_freepointer(s, freelist);
3769 	c->tid = next_tid(c->tid);
3770 	local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3771 	return freelist;
3772 
3773 deactivate_slab:
3774 
3775 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3776 	if (slab != c->slab) {
3777 		local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3778 		goto reread_slab;
3779 	}
3780 	freelist = c->freelist;
3781 	c->slab = NULL;
3782 	c->freelist = NULL;
3783 	c->tid = next_tid(c->tid);
3784 	local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3785 	deactivate_slab(s, slab, freelist);
3786 
3787 new_slab:
3788 
3789 #ifdef CONFIG_SLUB_CPU_PARTIAL
3790 	while (slub_percpu_partial(c)) {
3791 		local_lock_irqsave(&s->cpu_slab->lock, flags);
3792 		if (unlikely(c->slab)) {
3793 			local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3794 			goto reread_slab;
3795 		}
3796 		if (unlikely(!slub_percpu_partial(c))) {
3797 			local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3798 			/* we were preempted and partial list got empty */
3799 			goto new_objects;
3800 		}
3801 
3802 		slab = slub_percpu_partial(c);
3803 		slub_set_percpu_partial(c, slab);
3804 
3805 		if (likely(node_match(slab, node) &&
3806 			   pfmemalloc_match(slab, gfpflags))) {
3807 			c->slab = slab;
3808 			freelist = get_freelist(s, slab);
3809 			VM_BUG_ON(!freelist);
3810 			stat(s, CPU_PARTIAL_ALLOC);
3811 			goto load_freelist;
3812 		}
3813 
3814 		local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3815 
3816 		slab->next = NULL;
3817 		__put_partials(s, slab);
3818 	}
3819 #endif
3820 
3821 new_objects:
3822 
3823 	pc.flags = gfpflags;
3824 	/*
3825 	 * When a preferred node is indicated but no __GFP_THISNODE
3826 	 *
3827 	 * 1) try to get a partial slab from target node only by having
3828 	 *    __GFP_THISNODE in pc.flags for get_partial()
3829 	 * 2) if 1) failed, try to allocate a new slab from target node with
3830 	 *    GPF_NOWAIT | __GFP_THISNODE opportunistically
3831 	 * 3) if 2) failed, retry with original gfpflags which will allow
3832 	 *    get_partial() try partial lists of other nodes before potentially
3833 	 *    allocating new page from other nodes
3834 	 */
3835 	if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
3836 		     && try_thisnode))
3837 		pc.flags = GFP_NOWAIT | __GFP_THISNODE;
3838 
3839 	pc.orig_size = orig_size;
3840 	slab = get_partial(s, node, &pc);
3841 	if (slab) {
3842 		if (kmem_cache_debug(s)) {
3843 			freelist = pc.object;
3844 			/*
3845 			 * For debug caches here we had to go through
3846 			 * alloc_single_from_partial() so just store the
3847 			 * tracking info and return the object.
3848 			 */
3849 			if (s->flags & SLAB_STORE_USER)
3850 				set_track(s, freelist, TRACK_ALLOC, addr);
3851 
3852 			return freelist;
3853 		}
3854 
3855 		freelist = freeze_slab(s, slab);
3856 		goto retry_load_slab;
3857 	}
3858 
3859 	slub_put_cpu_ptr(s->cpu_slab);
3860 	slab = new_slab(s, pc.flags, node);
3861 	c = slub_get_cpu_ptr(s->cpu_slab);
3862 
3863 	if (unlikely(!slab)) {
3864 		if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
3865 		    && try_thisnode) {
3866 			try_thisnode = false;
3867 			goto new_objects;
3868 		}
3869 		slab_out_of_memory(s, gfpflags, node);
3870 		return NULL;
3871 	}
3872 
3873 	stat(s, ALLOC_SLAB);
3874 
3875 	if (kmem_cache_debug(s)) {
3876 		freelist = alloc_single_from_new_slab(s, slab, orig_size);
3877 
3878 		if (unlikely(!freelist))
3879 			goto new_objects;
3880 
3881 		if (s->flags & SLAB_STORE_USER)
3882 			set_track(s, freelist, TRACK_ALLOC, addr);
3883 
3884 		return freelist;
3885 	}
3886 
3887 	/*
3888 	 * No other reference to the slab yet so we can
3889 	 * muck around with it freely without cmpxchg
3890 	 */
3891 	freelist = slab->freelist;
3892 	slab->freelist = NULL;
3893 	slab->inuse = slab->objects;
3894 	slab->frozen = 1;
3895 
3896 	inc_slabs_node(s, slab_nid(slab), slab->objects);
3897 
3898 	if (unlikely(!pfmemalloc_match(slab, gfpflags))) {
3899 		/*
3900 		 * For !pfmemalloc_match() case we don't load freelist so that
3901 		 * we don't make further mismatched allocations easier.
3902 		 */
3903 		deactivate_slab(s, slab, get_freepointer(s, freelist));
3904 		return freelist;
3905 	}
3906 
3907 retry_load_slab:
3908 
3909 	local_lock_irqsave(&s->cpu_slab->lock, flags);
3910 	if (unlikely(c->slab)) {
3911 		void *flush_freelist = c->freelist;
3912 		struct slab *flush_slab = c->slab;
3913 
3914 		c->slab = NULL;
3915 		c->freelist = NULL;
3916 		c->tid = next_tid(c->tid);
3917 
3918 		local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3919 
3920 		deactivate_slab(s, flush_slab, flush_freelist);
3921 
3922 		stat(s, CPUSLAB_FLUSH);
3923 
3924 		goto retry_load_slab;
3925 	}
3926 	c->slab = slab;
3927 
3928 	goto load_freelist;
3929 }
3930 
3931 /*
3932  * A wrapper for ___slab_alloc() for contexts where preemption is not yet
3933  * disabled. Compensates for possible cpu changes by refetching the per cpu area
3934  * pointer.
3935  */
3936 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3937 			  unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3938 {
3939 	void *p;
3940 
3941 #ifdef CONFIG_PREEMPT_COUNT
3942 	/*
3943 	 * We may have been preempted and rescheduled on a different
3944 	 * cpu before disabling preemption. Need to reload cpu area
3945 	 * pointer.
3946 	 */
3947 	c = slub_get_cpu_ptr(s->cpu_slab);
3948 #endif
3949 
3950 	p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
3951 #ifdef CONFIG_PREEMPT_COUNT
3952 	slub_put_cpu_ptr(s->cpu_slab);
3953 #endif
3954 	return p;
3955 }
3956 
3957 static __always_inline void *__slab_alloc_node(struct kmem_cache *s,
3958 		gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
3959 {
3960 	struct kmem_cache_cpu *c;
3961 	struct slab *slab;
3962 	unsigned long tid;
3963 	void *object;
3964 
3965 redo:
3966 	/*
3967 	 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
3968 	 * enabled. We may switch back and forth between cpus while
3969 	 * reading from one cpu area. That does not matter as long
3970 	 * as we end up on the original cpu again when doing the cmpxchg.
3971 	 *
3972 	 * We must guarantee that tid and kmem_cache_cpu are retrieved on the
3973 	 * same cpu. We read first the kmem_cache_cpu pointer and use it to read
3974 	 * the tid. If we are preempted and switched to another cpu between the
3975 	 * two reads, it's OK as the two are still associated with the same cpu
3976 	 * and cmpxchg later will validate the cpu.
3977 	 */
3978 	c = raw_cpu_ptr(s->cpu_slab);
3979 	tid = READ_ONCE(c->tid);
3980 
3981 	/*
3982 	 * Irqless object alloc/free algorithm used here depends on sequence
3983 	 * of fetching cpu_slab's data. tid should be fetched before anything
3984 	 * on c to guarantee that object and slab associated with previous tid
3985 	 * won't be used with current tid. If we fetch tid first, object and
3986 	 * slab could be one associated with next tid and our alloc/free
3987 	 * request will be failed. In this case, we will retry. So, no problem.
3988 	 */
3989 	barrier();
3990 
3991 	/*
3992 	 * The transaction ids are globally unique per cpu and per operation on
3993 	 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
3994 	 * occurs on the right processor and that there was no operation on the
3995 	 * linked list in between.
3996 	 */
3997 
3998 	object = c->freelist;
3999 	slab = c->slab;
4000 
4001 #ifdef CONFIG_NUMA
4002 	if (static_branch_unlikely(&strict_numa) &&
4003 			node == NUMA_NO_NODE) {
4004 
4005 		struct mempolicy *mpol = current->mempolicy;
4006 
4007 		if (mpol) {
4008 			/*
4009 			 * Special BIND rule support. If existing slab
4010 			 * is in permitted set then do not redirect
4011 			 * to a particular node.
4012 			 * Otherwise we apply the memory policy to get
4013 			 * the node we need to allocate on.
4014 			 */
4015 			if (mpol->mode != MPOL_BIND || !slab ||
4016 					!node_isset(slab_nid(slab), mpol->nodes))
4017 
4018 				node = mempolicy_slab_node();
4019 		}
4020 	}
4021 #endif
4022 
4023 	if (!USE_LOCKLESS_FAST_PATH() ||
4024 	    unlikely(!object || !slab || !node_match(slab, node))) {
4025 		object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
4026 	} else {
4027 		void *next_object = get_freepointer_safe(s, object);
4028 
4029 		/*
4030 		 * The cmpxchg will only match if there was no additional
4031 		 * operation and if we are on the right processor.
4032 		 *
4033 		 * The cmpxchg does the following atomically (without lock
4034 		 * semantics!)
4035 		 * 1. Relocate first pointer to the current per cpu area.
4036 		 * 2. Verify that tid and freelist have not been changed
4037 		 * 3. If they were not changed replace tid and freelist
4038 		 *
4039 		 * Since this is without lock semantics the protection is only
4040 		 * against code executing on this cpu *not* from access by
4041 		 * other cpus.
4042 		 */
4043 		if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
4044 			note_cmpxchg_failure("slab_alloc", s, tid);
4045 			goto redo;
4046 		}
4047 		prefetch_freepointer(s, next_object);
4048 		stat(s, ALLOC_FASTPATH);
4049 	}
4050 
4051 	return object;
4052 }
4053 #else /* CONFIG_SLUB_TINY */
4054 static void *__slab_alloc_node(struct kmem_cache *s,
4055 		gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4056 {
4057 	struct partial_context pc;
4058 	struct slab *slab;
4059 	void *object;
4060 
4061 	pc.flags = gfpflags;
4062 	pc.orig_size = orig_size;
4063 	slab = get_partial(s, node, &pc);
4064 
4065 	if (slab)
4066 		return pc.object;
4067 
4068 	slab = new_slab(s, gfpflags, node);
4069 	if (unlikely(!slab)) {
4070 		slab_out_of_memory(s, gfpflags, node);
4071 		return NULL;
4072 	}
4073 
4074 	object = alloc_single_from_new_slab(s, slab, orig_size);
4075 
4076 	return object;
4077 }
4078 #endif /* CONFIG_SLUB_TINY */
4079 
4080 /*
4081  * If the object has been wiped upon free, make sure it's fully initialized by
4082  * zeroing out freelist pointer.
4083  *
4084  * Note that we also wipe custom freelist pointers.
4085  */
4086 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
4087 						   void *obj)
4088 {
4089 	if (unlikely(slab_want_init_on_free(s)) && obj &&
4090 	    !freeptr_outside_object(s))
4091 		memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
4092 			0, sizeof(void *));
4093 }
4094 
4095 static __fastpath_inline
4096 struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
4097 {
4098 	flags &= gfp_allowed_mask;
4099 
4100 	might_alloc(flags);
4101 
4102 	if (unlikely(should_failslab(s, flags)))
4103 		return NULL;
4104 
4105 	return s;
4106 }
4107 
4108 static __fastpath_inline
4109 bool slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
4110 			  gfp_t flags, size_t size, void **p, bool init,
4111 			  unsigned int orig_size)
4112 {
4113 	unsigned int zero_size = s->object_size;
4114 	bool kasan_init = init;
4115 	size_t i;
4116 	gfp_t init_flags = flags & gfp_allowed_mask;
4117 
4118 	/*
4119 	 * For kmalloc object, the allocated memory size(object_size) is likely
4120 	 * larger than the requested size(orig_size). If redzone check is
4121 	 * enabled for the extra space, don't zero it, as it will be redzoned
4122 	 * soon. The redzone operation for this extra space could be seen as a
4123 	 * replacement of current poisoning under certain debug option, and
4124 	 * won't break other sanity checks.
4125 	 */
4126 	if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) &&
4127 	    (s->flags & SLAB_KMALLOC))
4128 		zero_size = orig_size;
4129 
4130 	/*
4131 	 * When slab_debug is enabled, avoid memory initialization integrated
4132 	 * into KASAN and instead zero out the memory via the memset below with
4133 	 * the proper size. Otherwise, KASAN might overwrite SLUB redzones and
4134 	 * cause false-positive reports. This does not lead to a performance
4135 	 * penalty on production builds, as slab_debug is not intended to be
4136 	 * enabled there.
4137 	 */
4138 	if (__slub_debug_enabled())
4139 		kasan_init = false;
4140 
4141 	/*
4142 	 * As memory initialization might be integrated into KASAN,
4143 	 * kasan_slab_alloc and initialization memset must be
4144 	 * kept together to avoid discrepancies in behavior.
4145 	 *
4146 	 * As p[i] might get tagged, memset and kmemleak hook come after KASAN.
4147 	 */
4148 	for (i = 0; i < size; i++) {
4149 		p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init);
4150 		if (p[i] && init && (!kasan_init ||
4151 				     !kasan_has_integrated_init()))
4152 			memset(p[i], 0, zero_size);
4153 		kmemleak_alloc_recursive(p[i], s->object_size, 1,
4154 					 s->flags, init_flags);
4155 		kmsan_slab_alloc(s, p[i], init_flags);
4156 		alloc_tagging_slab_alloc_hook(s, p[i], flags);
4157 	}
4158 
4159 	return memcg_slab_post_alloc_hook(s, lru, flags, size, p);
4160 }
4161 
4162 /*
4163  * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
4164  * have the fastpath folded into their functions. So no function call
4165  * overhead for requests that can be satisfied on the fastpath.
4166  *
4167  * The fastpath works by first checking if the lockless freelist can be used.
4168  * If not then __slab_alloc is called for slow processing.
4169  *
4170  * Otherwise we can simply pick the next object from the lockless free list.
4171  */
4172 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
4173 		gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4174 {
4175 	void *object;
4176 	bool init = false;
4177 
4178 	s = slab_pre_alloc_hook(s, gfpflags);
4179 	if (unlikely(!s))
4180 		return NULL;
4181 
4182 	object = kfence_alloc(s, orig_size, gfpflags);
4183 	if (unlikely(object))
4184 		goto out;
4185 
4186 	object = __slab_alloc_node(s, gfpflags, node, addr, orig_size);
4187 
4188 	maybe_wipe_obj_freeptr(s, object);
4189 	init = slab_want_init_on_alloc(gfpflags, s);
4190 
4191 out:
4192 	/*
4193 	 * When init equals 'true', like for kzalloc() family, only
4194 	 * @orig_size bytes might be zeroed instead of s->object_size
4195 	 * In case this fails due to memcg_slab_post_alloc_hook(),
4196 	 * object is set to NULL
4197 	 */
4198 	slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size);
4199 
4200 	return object;
4201 }
4202 
4203 void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)
4204 {
4205 	void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, _RET_IP_,
4206 				    s->object_size);
4207 
4208 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4209 
4210 	return ret;
4211 }
4212 EXPORT_SYMBOL(kmem_cache_alloc_noprof);
4213 
4214 void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,
4215 			   gfp_t gfpflags)
4216 {
4217 	void *ret = slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, _RET_IP_,
4218 				    s->object_size);
4219 
4220 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4221 
4222 	return ret;
4223 }
4224 EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);
4225 
4226 bool kmem_cache_charge(void *objp, gfp_t gfpflags)
4227 {
4228 	if (!memcg_kmem_online())
4229 		return true;
4230 
4231 	return memcg_slab_post_charge(objp, gfpflags);
4232 }
4233 EXPORT_SYMBOL(kmem_cache_charge);
4234 
4235 /**
4236  * kmem_cache_alloc_node - Allocate an object on the specified node
4237  * @s: The cache to allocate from.
4238  * @gfpflags: See kmalloc().
4239  * @node: node number of the target node.
4240  *
4241  * Identical to kmem_cache_alloc but it will allocate memory on the given
4242  * node, which can improve the performance for cpu bound structures.
4243  *
4244  * Fallback to other node is possible if __GFP_THISNODE is not set.
4245  *
4246  * Return: pointer to the new object or %NULL in case of error
4247  */
4248 void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
4249 {
4250 	void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
4251 
4252 	trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
4253 
4254 	return ret;
4255 }
4256 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
4257 
4258 /*
4259  * To avoid unnecessary overhead, we pass through large allocation requests
4260  * directly to the page allocator. We use __GFP_COMP, because we will need to
4261  * know the allocation order to free the pages properly in kfree.
4262  */
4263 static void *___kmalloc_large_node(size_t size, gfp_t flags, int node)
4264 {
4265 	struct folio *folio;
4266 	void *ptr = NULL;
4267 	unsigned int order = get_order(size);
4268 
4269 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
4270 		flags = kmalloc_fix_flags(flags);
4271 
4272 	flags |= __GFP_COMP;
4273 	folio = (struct folio *)alloc_pages_node_noprof(node, flags, order);
4274 	if (folio) {
4275 		ptr = folio_address(folio);
4276 		lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
4277 				      PAGE_SIZE << order);
4278 		__folio_set_large_kmalloc(folio);
4279 	}
4280 
4281 	ptr = kasan_kmalloc_large(ptr, size, flags);
4282 	/* As ptr might get tagged, call kmemleak hook after KASAN. */
4283 	kmemleak_alloc(ptr, size, 1, flags);
4284 	kmsan_kmalloc_large(ptr, size, flags);
4285 
4286 	return ptr;
4287 }
4288 
4289 void *__kmalloc_large_noprof(size_t size, gfp_t flags)
4290 {
4291 	void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE);
4292 
4293 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
4294 		      flags, NUMA_NO_NODE);
4295 	return ret;
4296 }
4297 EXPORT_SYMBOL(__kmalloc_large_noprof);
4298 
4299 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
4300 {
4301 	void *ret = ___kmalloc_large_node(size, flags, node);
4302 
4303 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
4304 		      flags, node);
4305 	return ret;
4306 }
4307 EXPORT_SYMBOL(__kmalloc_large_node_noprof);
4308 
4309 static __always_inline
4310 void *__do_kmalloc_node(size_t size, kmem_buckets *b, gfp_t flags, int node,
4311 			unsigned long caller)
4312 {
4313 	struct kmem_cache *s;
4314 	void *ret;
4315 
4316 	if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4317 		ret = __kmalloc_large_node_noprof(size, flags, node);
4318 		trace_kmalloc(caller, ret, size,
4319 			      PAGE_SIZE << get_order(size), flags, node);
4320 		return ret;
4321 	}
4322 
4323 	if (unlikely(!size))
4324 		return ZERO_SIZE_PTR;
4325 
4326 	s = kmalloc_slab(size, b, flags, caller);
4327 
4328 	ret = slab_alloc_node(s, NULL, flags, node, caller, size);
4329 	ret = kasan_kmalloc(s, ret, size, flags);
4330 	trace_kmalloc(caller, ret, size, s->size, flags, node);
4331 	return ret;
4332 }
4333 void *__kmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
4334 {
4335 	return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, _RET_IP_);
4336 }
4337 EXPORT_SYMBOL(__kmalloc_node_noprof);
4338 
4339 void *__kmalloc_noprof(size_t size, gfp_t flags)
4340 {
4341 	return __do_kmalloc_node(size, NULL, flags, NUMA_NO_NODE, _RET_IP_);
4342 }
4343 EXPORT_SYMBOL(__kmalloc_noprof);
4344 
4345 void *__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags,
4346 					 int node, unsigned long caller)
4347 {
4348 	return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, caller);
4349 
4350 }
4351 EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof);
4352 
4353 void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size)
4354 {
4355 	void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE,
4356 					    _RET_IP_, size);
4357 
4358 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
4359 
4360 	ret = kasan_kmalloc(s, ret, size, gfpflags);
4361 	return ret;
4362 }
4363 EXPORT_SYMBOL(__kmalloc_cache_noprof);
4364 
4365 void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags,
4366 				  int node, size_t size)
4367 {
4368 	void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, size);
4369 
4370 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
4371 
4372 	ret = kasan_kmalloc(s, ret, size, gfpflags);
4373 	return ret;
4374 }
4375 EXPORT_SYMBOL(__kmalloc_cache_node_noprof);
4376 
4377 static noinline void free_to_partial_list(
4378 	struct kmem_cache *s, struct slab *slab,
4379 	void *head, void *tail, int bulk_cnt,
4380 	unsigned long addr)
4381 {
4382 	struct kmem_cache_node *n = get_node(s, slab_nid(slab));
4383 	struct slab *slab_free = NULL;
4384 	int cnt = bulk_cnt;
4385 	unsigned long flags;
4386 	depot_stack_handle_t handle = 0;
4387 
4388 	if (s->flags & SLAB_STORE_USER)
4389 		handle = set_track_prepare();
4390 
4391 	spin_lock_irqsave(&n->list_lock, flags);
4392 
4393 	if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
4394 		void *prior = slab->freelist;
4395 
4396 		/* Perform the actual freeing while we still hold the locks */
4397 		slab->inuse -= cnt;
4398 		set_freepointer(s, tail, prior);
4399 		slab->freelist = head;
4400 
4401 		/*
4402 		 * If the slab is empty, and node's partial list is full,
4403 		 * it should be discarded anyway no matter it's on full or
4404 		 * partial list.
4405 		 */
4406 		if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
4407 			slab_free = slab;
4408 
4409 		if (!prior) {
4410 			/* was on full list */
4411 			remove_full(s, n, slab);
4412 			if (!slab_free) {
4413 				add_partial(n, slab, DEACTIVATE_TO_TAIL);
4414 				stat(s, FREE_ADD_PARTIAL);
4415 			}
4416 		} else if (slab_free) {
4417 			remove_partial(n, slab);
4418 			stat(s, FREE_REMOVE_PARTIAL);
4419 		}
4420 	}
4421 
4422 	if (slab_free) {
4423 		/*
4424 		 * Update the counters while still holding n->list_lock to
4425 		 * prevent spurious validation warnings
4426 		 */
4427 		dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
4428 	}
4429 
4430 	spin_unlock_irqrestore(&n->list_lock, flags);
4431 
4432 	if (slab_free) {
4433 		stat(s, FREE_SLAB);
4434 		free_slab(s, slab_free);
4435 	}
4436 }
4437 
4438 /*
4439  * Slow path handling. This may still be called frequently since objects
4440  * have a longer lifetime than the cpu slabs in most processing loads.
4441  *
4442  * So we still attempt to reduce cache line usage. Just take the slab
4443  * lock and free the item. If there is no additional partial slab
4444  * handling required then we can return immediately.
4445  */
4446 static void __slab_free(struct kmem_cache *s, struct slab *slab,
4447 			void *head, void *tail, int cnt,
4448 			unsigned long addr)
4449 
4450 {
4451 	void *prior;
4452 	int was_frozen;
4453 	struct slab new;
4454 	unsigned long counters;
4455 	struct kmem_cache_node *n = NULL;
4456 	unsigned long flags;
4457 	bool on_node_partial;
4458 
4459 	stat(s, FREE_SLOWPATH);
4460 
4461 	if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
4462 		free_to_partial_list(s, slab, head, tail, cnt, addr);
4463 		return;
4464 	}
4465 
4466 	do {
4467 		if (unlikely(n)) {
4468 			spin_unlock_irqrestore(&n->list_lock, flags);
4469 			n = NULL;
4470 		}
4471 		prior = slab->freelist;
4472 		counters = slab->counters;
4473 		set_freepointer(s, tail, prior);
4474 		new.counters = counters;
4475 		was_frozen = new.frozen;
4476 		new.inuse -= cnt;
4477 		if ((!new.inuse || !prior) && !was_frozen) {
4478 			/* Needs to be taken off a list */
4479 			if (!kmem_cache_has_cpu_partial(s) || prior) {
4480 
4481 				n = get_node(s, slab_nid(slab));
4482 				/*
4483 				 * Speculatively acquire the list_lock.
4484 				 * If the cmpxchg does not succeed then we may
4485 				 * drop the list_lock without any processing.
4486 				 *
4487 				 * Otherwise the list_lock will synchronize with
4488 				 * other processors updating the list of slabs.
4489 				 */
4490 				spin_lock_irqsave(&n->list_lock, flags);
4491 
4492 				on_node_partial = slab_test_node_partial(slab);
4493 			}
4494 		}
4495 
4496 	} while (!slab_update_freelist(s, slab,
4497 		prior, counters,
4498 		head, new.counters,
4499 		"__slab_free"));
4500 
4501 	if (likely(!n)) {
4502 
4503 		if (likely(was_frozen)) {
4504 			/*
4505 			 * The list lock was not taken therefore no list
4506 			 * activity can be necessary.
4507 			 */
4508 			stat(s, FREE_FROZEN);
4509 		} else if (kmem_cache_has_cpu_partial(s) && !prior) {
4510 			/*
4511 			 * If we started with a full slab then put it onto the
4512 			 * per cpu partial list.
4513 			 */
4514 			put_cpu_partial(s, slab, 1);
4515 			stat(s, CPU_PARTIAL_FREE);
4516 		}
4517 
4518 		return;
4519 	}
4520 
4521 	/*
4522 	 * This slab was partially empty but not on the per-node partial list,
4523 	 * in which case we shouldn't manipulate its list, just return.
4524 	 */
4525 	if (prior && !on_node_partial) {
4526 		spin_unlock_irqrestore(&n->list_lock, flags);
4527 		return;
4528 	}
4529 
4530 	if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
4531 		goto slab_empty;
4532 
4533 	/*
4534 	 * Objects left in the slab. If it was not on the partial list before
4535 	 * then add it.
4536 	 */
4537 	if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
4538 		add_partial(n, slab, DEACTIVATE_TO_TAIL);
4539 		stat(s, FREE_ADD_PARTIAL);
4540 	}
4541 	spin_unlock_irqrestore(&n->list_lock, flags);
4542 	return;
4543 
4544 slab_empty:
4545 	if (prior) {
4546 		/*
4547 		 * Slab on the partial list.
4548 		 */
4549 		remove_partial(n, slab);
4550 		stat(s, FREE_REMOVE_PARTIAL);
4551 	}
4552 
4553 	spin_unlock_irqrestore(&n->list_lock, flags);
4554 	stat(s, FREE_SLAB);
4555 	discard_slab(s, slab);
4556 }
4557 
4558 #ifndef CONFIG_SLUB_TINY
4559 /*
4560  * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
4561  * can perform fastpath freeing without additional function calls.
4562  *
4563  * The fastpath is only possible if we are freeing to the current cpu slab
4564  * of this processor. This typically the case if we have just allocated
4565  * the item before.
4566  *
4567  * If fastpath is not possible then fall back to __slab_free where we deal
4568  * with all sorts of special processing.
4569  *
4570  * Bulk free of a freelist with several objects (all pointing to the
4571  * same slab) possible by specifying head and tail ptr, plus objects
4572  * count (cnt). Bulk free indicated by tail pointer being set.
4573  */
4574 static __always_inline void do_slab_free(struct kmem_cache *s,
4575 				struct slab *slab, void *head, void *tail,
4576 				int cnt, unsigned long addr)
4577 {
4578 	struct kmem_cache_cpu *c;
4579 	unsigned long tid;
4580 	void **freelist;
4581 
4582 redo:
4583 	/*
4584 	 * Determine the currently cpus per cpu slab.
4585 	 * The cpu may change afterward. However that does not matter since
4586 	 * data is retrieved via this pointer. If we are on the same cpu
4587 	 * during the cmpxchg then the free will succeed.
4588 	 */
4589 	c = raw_cpu_ptr(s->cpu_slab);
4590 	tid = READ_ONCE(c->tid);
4591 
4592 	/* Same with comment on barrier() in __slab_alloc_node() */
4593 	barrier();
4594 
4595 	if (unlikely(slab != c->slab)) {
4596 		__slab_free(s, slab, head, tail, cnt, addr);
4597 		return;
4598 	}
4599 
4600 	if (USE_LOCKLESS_FAST_PATH()) {
4601 		freelist = READ_ONCE(c->freelist);
4602 
4603 		set_freepointer(s, tail, freelist);
4604 
4605 		if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
4606 			note_cmpxchg_failure("slab_free", s, tid);
4607 			goto redo;
4608 		}
4609 	} else {
4610 		/* Update the free list under the local lock */
4611 		local_lock(&s->cpu_slab->lock);
4612 		c = this_cpu_ptr(s->cpu_slab);
4613 		if (unlikely(slab != c->slab)) {
4614 			local_unlock(&s->cpu_slab->lock);
4615 			goto redo;
4616 		}
4617 		tid = c->tid;
4618 		freelist = c->freelist;
4619 
4620 		set_freepointer(s, tail, freelist);
4621 		c->freelist = head;
4622 		c->tid = next_tid(tid);
4623 
4624 		local_unlock(&s->cpu_slab->lock);
4625 	}
4626 	stat_add(s, FREE_FASTPATH, cnt);
4627 }
4628 #else /* CONFIG_SLUB_TINY */
4629 static void do_slab_free(struct kmem_cache *s,
4630 				struct slab *slab, void *head, void *tail,
4631 				int cnt, unsigned long addr)
4632 {
4633 	__slab_free(s, slab, head, tail, cnt, addr);
4634 }
4635 #endif /* CONFIG_SLUB_TINY */
4636 
4637 static __fastpath_inline
4638 void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
4639 	       unsigned long addr)
4640 {
4641 	memcg_slab_free_hook(s, slab, &object, 1);
4642 	alloc_tagging_slab_free_hook(s, slab, &object, 1);
4643 
4644 	if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
4645 		do_slab_free(s, slab, object, object, 1, addr);
4646 }
4647 
4648 #ifdef CONFIG_MEMCG
4649 /* Do not inline the rare memcg charging failed path into the allocation path */
4650 static noinline
4651 void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
4652 {
4653 	if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
4654 		do_slab_free(s, virt_to_slab(object), object, object, 1, _RET_IP_);
4655 }
4656 #endif
4657 
4658 static __fastpath_inline
4659 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
4660 		    void *tail, void **p, int cnt, unsigned long addr)
4661 {
4662 	memcg_slab_free_hook(s, slab, p, cnt);
4663 	alloc_tagging_slab_free_hook(s, slab, p, cnt);
4664 	/*
4665 	 * With KASAN enabled slab_free_freelist_hook modifies the freelist
4666 	 * to remove objects, whose reuse must be delayed.
4667 	 */
4668 	if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt)))
4669 		do_slab_free(s, slab, head, tail, cnt, addr);
4670 }
4671 
4672 #ifdef CONFIG_SLUB_RCU_DEBUG
4673 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
4674 {
4675 	struct rcu_delayed_free *delayed_free =
4676 			container_of(rcu_head, struct rcu_delayed_free, head);
4677 	void *object = delayed_free->object;
4678 	struct slab *slab = virt_to_slab(object);
4679 	struct kmem_cache *s;
4680 
4681 	kfree(delayed_free);
4682 
4683 	if (WARN_ON(is_kfence_address(object)))
4684 		return;
4685 
4686 	/* find the object and the cache again */
4687 	if (WARN_ON(!slab))
4688 		return;
4689 	s = slab->slab_cache;
4690 	if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
4691 		return;
4692 
4693 	/* resume freeing */
4694 	if (slab_free_hook(s, object, slab_want_init_on_free(s), true))
4695 		do_slab_free(s, slab, object, object, 1, _THIS_IP_);
4696 }
4697 #endif /* CONFIG_SLUB_RCU_DEBUG */
4698 
4699 #ifdef CONFIG_KASAN_GENERIC
4700 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
4701 {
4702 	do_slab_free(cache, virt_to_slab(x), x, x, 1, addr);
4703 }
4704 #endif
4705 
4706 static inline struct kmem_cache *virt_to_cache(const void *obj)
4707 {
4708 	struct slab *slab;
4709 
4710 	slab = virt_to_slab(obj);
4711 	if (WARN_ONCE(!slab, "%s: Object is not a Slab page!\n", __func__))
4712 		return NULL;
4713 	return slab->slab_cache;
4714 }
4715 
4716 static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x)
4717 {
4718 	struct kmem_cache *cachep;
4719 
4720 	if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
4721 	    !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS))
4722 		return s;
4723 
4724 	cachep = virt_to_cache(x);
4725 	if (WARN(cachep && cachep != s,
4726 		 "%s: Wrong slab cache. %s but object is from %s\n",
4727 		 __func__, s->name, cachep->name))
4728 		print_tracking(cachep, x);
4729 	return cachep;
4730 }
4731 
4732 /**
4733  * kmem_cache_free - Deallocate an object
4734  * @s: The cache the allocation was from.
4735  * @x: The previously allocated object.
4736  *
4737  * Free an object which was previously allocated from this
4738  * cache.
4739  */
4740 void kmem_cache_free(struct kmem_cache *s, void *x)
4741 {
4742 	s = cache_from_obj(s, x);
4743 	if (!s)
4744 		return;
4745 	trace_kmem_cache_free(_RET_IP_, x, s);
4746 	slab_free(s, virt_to_slab(x), x, _RET_IP_);
4747 }
4748 EXPORT_SYMBOL(kmem_cache_free);
4749 
4750 static void free_large_kmalloc(struct folio *folio, void *object)
4751 {
4752 	unsigned int order = folio_order(folio);
4753 
4754 	if (WARN_ON_ONCE(!folio_test_large_kmalloc(folio))) {
4755 		dump_page(&folio->page, "Not a kmalloc allocation");
4756 		return;
4757 	}
4758 
4759 	if (WARN_ON_ONCE(order == 0))
4760 		pr_warn_once("object pointer: 0x%p\n", object);
4761 
4762 	kmemleak_free(object);
4763 	kasan_kfree_large(object);
4764 	kmsan_kfree_large(object);
4765 
4766 	lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
4767 			      -(PAGE_SIZE << order));
4768 	__folio_clear_large_kmalloc(folio);
4769 	folio_put(folio);
4770 }
4771 
4772 /*
4773  * Given an rcu_head embedded within an object obtained from kvmalloc at an
4774  * offset < 4k, free the object in question.
4775  */
4776 void kvfree_rcu_cb(struct rcu_head *head)
4777 {
4778 	void *obj = head;
4779 	struct folio *folio;
4780 	struct slab *slab;
4781 	struct kmem_cache *s;
4782 	void *slab_addr;
4783 
4784 	if (is_vmalloc_addr(obj)) {
4785 		obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
4786 		vfree(obj);
4787 		return;
4788 	}
4789 
4790 	folio = virt_to_folio(obj);
4791 	if (!folio_test_slab(folio)) {
4792 		/*
4793 		 * rcu_head offset can be only less than page size so no need to
4794 		 * consider folio order
4795 		 */
4796 		obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
4797 		free_large_kmalloc(folio, obj);
4798 		return;
4799 	}
4800 
4801 	slab = folio_slab(folio);
4802 	s = slab->slab_cache;
4803 	slab_addr = folio_address(folio);
4804 
4805 	if (is_kfence_address(obj)) {
4806 		obj = kfence_object_start(obj);
4807 	} else {
4808 		unsigned int idx = __obj_to_index(s, slab_addr, obj);
4809 
4810 		obj = slab_addr + s->size * idx;
4811 		obj = fixup_red_left(s, obj);
4812 	}
4813 
4814 	slab_free(s, slab, obj, _RET_IP_);
4815 }
4816 
4817 /**
4818  * kfree - free previously allocated memory
4819  * @object: pointer returned by kmalloc() or kmem_cache_alloc()
4820  *
4821  * If @object is NULL, no operation is performed.
4822  */
4823 void kfree(const void *object)
4824 {
4825 	struct folio *folio;
4826 	struct slab *slab;
4827 	struct kmem_cache *s;
4828 	void *x = (void *)object;
4829 
4830 	trace_kfree(_RET_IP_, object);
4831 
4832 	if (unlikely(ZERO_OR_NULL_PTR(object)))
4833 		return;
4834 
4835 	folio = virt_to_folio(object);
4836 	if (unlikely(!folio_test_slab(folio))) {
4837 		free_large_kmalloc(folio, (void *)object);
4838 		return;
4839 	}
4840 
4841 	slab = folio_slab(folio);
4842 	s = slab->slab_cache;
4843 	slab_free(s, slab, x, _RET_IP_);
4844 }
4845 EXPORT_SYMBOL(kfree);
4846 
4847 static __always_inline __realloc_size(2) void *
4848 __do_krealloc(const void *p, size_t new_size, gfp_t flags)
4849 {
4850 	void *ret;
4851 	size_t ks = 0;
4852 	int orig_size = 0;
4853 	struct kmem_cache *s = NULL;
4854 
4855 	if (unlikely(ZERO_OR_NULL_PTR(p)))
4856 		goto alloc_new;
4857 
4858 	/* Check for double-free. */
4859 	if (!kasan_check_byte(p))
4860 		return NULL;
4861 
4862 	if (is_kfence_address(p)) {
4863 		ks = orig_size = kfence_ksize(p);
4864 	} else {
4865 		struct folio *folio;
4866 
4867 		folio = virt_to_folio(p);
4868 		if (unlikely(!folio_test_slab(folio))) {
4869 			/* Big kmalloc object */
4870 			WARN_ON(folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE);
4871 			WARN_ON(p != folio_address(folio));
4872 			ks = folio_size(folio);
4873 		} else {
4874 			s = folio_slab(folio)->slab_cache;
4875 			orig_size = get_orig_size(s, (void *)p);
4876 			ks = s->object_size;
4877 		}
4878 	}
4879 
4880 	/* If the old object doesn't fit, allocate a bigger one */
4881 	if (new_size > ks)
4882 		goto alloc_new;
4883 
4884 	/* Zero out spare memory. */
4885 	if (want_init_on_alloc(flags)) {
4886 		kasan_disable_current();
4887 		if (orig_size && orig_size < new_size)
4888 			memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size);
4889 		else
4890 			memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
4891 		kasan_enable_current();
4892 	}
4893 
4894 	/* Setup kmalloc redzone when needed */
4895 	if (s && slub_debug_orig_size(s)) {
4896 		set_orig_size(s, (void *)p, new_size);
4897 		if (s->flags & SLAB_RED_ZONE && new_size < ks)
4898 			memset_no_sanitize_memory(kasan_reset_tag(p) + new_size,
4899 						SLUB_RED_ACTIVE, ks - new_size);
4900 	}
4901 
4902 	p = kasan_krealloc(p, new_size, flags);
4903 	return (void *)p;
4904 
4905 alloc_new:
4906 	ret = kmalloc_node_track_caller_noprof(new_size, flags, NUMA_NO_NODE, _RET_IP_);
4907 	if (ret && p) {
4908 		/* Disable KASAN checks as the object's redzone is accessed. */
4909 		kasan_disable_current();
4910 		memcpy(ret, kasan_reset_tag(p), orig_size ?: ks);
4911 		kasan_enable_current();
4912 	}
4913 
4914 	return ret;
4915 }
4916 
4917 /**
4918  * krealloc - reallocate memory. The contents will remain unchanged.
4919  * @p: object to reallocate memory for.
4920  * @new_size: how many bytes of memory are required.
4921  * @flags: the type of memory to allocate.
4922  *
4923  * If @p is %NULL, krealloc() behaves exactly like kmalloc().  If @new_size
4924  * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
4925  *
4926  * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
4927  * initial memory allocation, every subsequent call to this API for the same
4928  * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
4929  * __GFP_ZERO is not fully honored by this API.
4930  *
4931  * When slub_debug_orig_size() is off, krealloc() only knows about the bucket
4932  * size of an allocation (but not the exact size it was allocated with) and
4933  * hence implements the following semantics for shrinking and growing buffers
4934  * with __GFP_ZERO.
4935  *
4936  *         new             bucket
4937  * 0       size             size
4938  * |--------|----------------|
4939  * |  keep  |      zero      |
4940  *
4941  * Otherwise, the original allocation size 'orig_size' could be used to
4942  * precisely clear the requested size, and the new size will also be stored
4943  * as the new 'orig_size'.
4944  *
4945  * In any case, the contents of the object pointed to are preserved up to the
4946  * lesser of the new and old sizes.
4947  *
4948  * Return: pointer to the allocated memory or %NULL in case of error
4949  */
4950 void *krealloc_noprof(const void *p, size_t new_size, gfp_t flags)
4951 {
4952 	void *ret;
4953 
4954 	if (unlikely(!new_size)) {
4955 		kfree(p);
4956 		return ZERO_SIZE_PTR;
4957 	}
4958 
4959 	ret = __do_krealloc(p, new_size, flags);
4960 	if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
4961 		kfree(p);
4962 
4963 	return ret;
4964 }
4965 EXPORT_SYMBOL(krealloc_noprof);
4966 
4967 static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
4968 {
4969 	/*
4970 	 * We want to attempt a large physically contiguous block first because
4971 	 * it is less likely to fragment multiple larger blocks and therefore
4972 	 * contribute to a long term fragmentation less than vmalloc fallback.
4973 	 * However make sure that larger requests are not too disruptive - i.e.
4974 	 * do not direct reclaim unless physically continuous memory is preferred
4975 	 * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to
4976 	 * start working in the background
4977 	 */
4978 	if (size > PAGE_SIZE) {
4979 		flags |= __GFP_NOWARN;
4980 
4981 		if (!(flags & __GFP_RETRY_MAYFAIL))
4982 			flags &= ~__GFP_DIRECT_RECLAIM;
4983 
4984 		/* nofail semantic is implemented by the vmalloc fallback */
4985 		flags &= ~__GFP_NOFAIL;
4986 	}
4987 
4988 	return flags;
4989 }
4990 
4991 /**
4992  * __kvmalloc_node - attempt to allocate physically contiguous memory, but upon
4993  * failure, fall back to non-contiguous (vmalloc) allocation.
4994  * @size: size of the request.
4995  * @b: which set of kmalloc buckets to allocate from.
4996  * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
4997  * @node: numa node to allocate from
4998  *
4999  * Uses kmalloc to get the memory but if the allocation fails then falls back
5000  * to the vmalloc allocator. Use kvfree for freeing the memory.
5001  *
5002  * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier.
5003  * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
5004  * preferable to the vmalloc fallback, due to visible performance drawbacks.
5005  *
5006  * Return: pointer to the allocated memory of %NULL in case of failure
5007  */
5008 void *__kvmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
5009 {
5010 	void *ret;
5011 
5012 	/*
5013 	 * It doesn't really make sense to fallback to vmalloc for sub page
5014 	 * requests
5015 	 */
5016 	ret = __do_kmalloc_node(size, PASS_BUCKET_PARAM(b),
5017 				kmalloc_gfp_adjust(flags, size),
5018 				node, _RET_IP_);
5019 	if (ret || size <= PAGE_SIZE)
5020 		return ret;
5021 
5022 	/* non-sleeping allocations are not supported by vmalloc */
5023 	if (!gfpflags_allow_blocking(flags))
5024 		return NULL;
5025 
5026 	/* Don't even allow crazy sizes */
5027 	if (unlikely(size > INT_MAX)) {
5028 		WARN_ON_ONCE(!(flags & __GFP_NOWARN));
5029 		return NULL;
5030 	}
5031 
5032 	/*
5033 	 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP,
5034 	 * since the callers already cannot assume anything
5035 	 * about the resulting pointer, and cannot play
5036 	 * protection games.
5037 	 */
5038 	return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END,
5039 			flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
5040 			node, __builtin_return_address(0));
5041 }
5042 EXPORT_SYMBOL(__kvmalloc_node_noprof);
5043 
5044 /**
5045  * kvfree() - Free memory.
5046  * @addr: Pointer to allocated memory.
5047  *
5048  * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
5049  * It is slightly more efficient to use kfree() or vfree() if you are certain
5050  * that you know which one to use.
5051  *
5052  * Context: Either preemptible task context or not-NMI interrupt.
5053  */
5054 void kvfree(const void *addr)
5055 {
5056 	if (is_vmalloc_addr(addr))
5057 		vfree(addr);
5058 	else
5059 		kfree(addr);
5060 }
5061 EXPORT_SYMBOL(kvfree);
5062 
5063 /**
5064  * kvfree_sensitive - Free a data object containing sensitive information.
5065  * @addr: address of the data object to be freed.
5066  * @len: length of the data object.
5067  *
5068  * Use the special memzero_explicit() function to clear the content of a
5069  * kvmalloc'ed object containing sensitive data to make sure that the
5070  * compiler won't optimize out the data clearing.
5071  */
5072 void kvfree_sensitive(const void *addr, size_t len)
5073 {
5074 	if (likely(!ZERO_OR_NULL_PTR(addr))) {
5075 		memzero_explicit((void *)addr, len);
5076 		kvfree(addr);
5077 	}
5078 }
5079 EXPORT_SYMBOL(kvfree_sensitive);
5080 
5081 /**
5082  * kvrealloc - reallocate memory; contents remain unchanged
5083  * @p: object to reallocate memory for
5084  * @size: the size to reallocate
5085  * @flags: the flags for the page level allocator
5086  *
5087  * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0
5088  * and @p is not a %NULL pointer, the object pointed to is freed.
5089  *
5090  * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
5091  * initial memory allocation, every subsequent call to this API for the same
5092  * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
5093  * __GFP_ZERO is not fully honored by this API.
5094  *
5095  * In any case, the contents of the object pointed to are preserved up to the
5096  * lesser of the new and old sizes.
5097  *
5098  * This function must not be called concurrently with itself or kvfree() for the
5099  * same memory allocation.
5100  *
5101  * Return: pointer to the allocated memory or %NULL in case of error
5102  */
5103 void *kvrealloc_noprof(const void *p, size_t size, gfp_t flags)
5104 {
5105 	void *n;
5106 
5107 	if (is_vmalloc_addr(p))
5108 		return vrealloc_noprof(p, size, flags);
5109 
5110 	n = krealloc_noprof(p, size, kmalloc_gfp_adjust(flags, size));
5111 	if (!n) {
5112 		/* We failed to krealloc(), fall back to kvmalloc(). */
5113 		n = kvmalloc_noprof(size, flags);
5114 		if (!n)
5115 			return NULL;
5116 
5117 		if (p) {
5118 			/* We already know that `p` is not a vmalloc address. */
5119 			kasan_disable_current();
5120 			memcpy(n, kasan_reset_tag(p), ksize(p));
5121 			kasan_enable_current();
5122 
5123 			kfree(p);
5124 		}
5125 	}
5126 
5127 	return n;
5128 }
5129 EXPORT_SYMBOL(kvrealloc_noprof);
5130 
5131 struct detached_freelist {
5132 	struct slab *slab;
5133 	void *tail;
5134 	void *freelist;
5135 	int cnt;
5136 	struct kmem_cache *s;
5137 };
5138 
5139 /*
5140  * This function progressively scans the array with free objects (with
5141  * a limited look ahead) and extract objects belonging to the same
5142  * slab.  It builds a detached freelist directly within the given
5143  * slab/objects.  This can happen without any need for
5144  * synchronization, because the objects are owned by running process.
5145  * The freelist is build up as a single linked list in the objects.
5146  * The idea is, that this detached freelist can then be bulk
5147  * transferred to the real freelist(s), but only requiring a single
5148  * synchronization primitive.  Look ahead in the array is limited due
5149  * to performance reasons.
5150  */
5151 static inline
5152 int build_detached_freelist(struct kmem_cache *s, size_t size,
5153 			    void **p, struct detached_freelist *df)
5154 {
5155 	int lookahead = 3;
5156 	void *object;
5157 	struct folio *folio;
5158 	size_t same;
5159 
5160 	object = p[--size];
5161 	folio = virt_to_folio(object);
5162 	if (!s) {
5163 		/* Handle kalloc'ed objects */
5164 		if (unlikely(!folio_test_slab(folio))) {
5165 			free_large_kmalloc(folio, object);
5166 			df->slab = NULL;
5167 			return size;
5168 		}
5169 		/* Derive kmem_cache from object */
5170 		df->slab = folio_slab(folio);
5171 		df->s = df->slab->slab_cache;
5172 	} else {
5173 		df->slab = folio_slab(folio);
5174 		df->s = cache_from_obj(s, object); /* Support for memcg */
5175 	}
5176 
5177 	/* Start new detached freelist */
5178 	df->tail = object;
5179 	df->freelist = object;
5180 	df->cnt = 1;
5181 
5182 	if (is_kfence_address(object))
5183 		return size;
5184 
5185 	set_freepointer(df->s, object, NULL);
5186 
5187 	same = size;
5188 	while (size) {
5189 		object = p[--size];
5190 		/* df->slab is always set at this point */
5191 		if (df->slab == virt_to_slab(object)) {
5192 			/* Opportunity build freelist */
5193 			set_freepointer(df->s, object, df->freelist);
5194 			df->freelist = object;
5195 			df->cnt++;
5196 			same--;
5197 			if (size != same)
5198 				swap(p[size], p[same]);
5199 			continue;
5200 		}
5201 
5202 		/* Limit look ahead search */
5203 		if (!--lookahead)
5204 			break;
5205 	}
5206 
5207 	return same;
5208 }
5209 
5210 /*
5211  * Internal bulk free of objects that were not initialised by the post alloc
5212  * hooks and thus should not be processed by the free hooks
5213  */
5214 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
5215 {
5216 	if (!size)
5217 		return;
5218 
5219 	do {
5220 		struct detached_freelist df;
5221 
5222 		size = build_detached_freelist(s, size, p, &df);
5223 		if (!df.slab)
5224 			continue;
5225 
5226 		if (kfence_free(df.freelist))
5227 			continue;
5228 
5229 		do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
5230 			     _RET_IP_);
5231 	} while (likely(size));
5232 }
5233 
5234 /* Note that interrupts must be enabled when calling this function. */
5235 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
5236 {
5237 	if (!size)
5238 		return;
5239 
5240 	do {
5241 		struct detached_freelist df;
5242 
5243 		size = build_detached_freelist(s, size, p, &df);
5244 		if (!df.slab)
5245 			continue;
5246 
5247 		slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
5248 			       df.cnt, _RET_IP_);
5249 	} while (likely(size));
5250 }
5251 EXPORT_SYMBOL(kmem_cache_free_bulk);
5252 
5253 #ifndef CONFIG_SLUB_TINY
5254 static inline
5255 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
5256 			    void **p)
5257 {
5258 	struct kmem_cache_cpu *c;
5259 	unsigned long irqflags;
5260 	int i;
5261 
5262 	/*
5263 	 * Drain objects in the per cpu slab, while disabling local
5264 	 * IRQs, which protects against PREEMPT and interrupts
5265 	 * handlers invoking normal fastpath.
5266 	 */
5267 	c = slub_get_cpu_ptr(s->cpu_slab);
5268 	local_lock_irqsave(&s->cpu_slab->lock, irqflags);
5269 
5270 	for (i = 0; i < size; i++) {
5271 		void *object = kfence_alloc(s, s->object_size, flags);
5272 
5273 		if (unlikely(object)) {
5274 			p[i] = object;
5275 			continue;
5276 		}
5277 
5278 		object = c->freelist;
5279 		if (unlikely(!object)) {
5280 			/*
5281 			 * We may have removed an object from c->freelist using
5282 			 * the fastpath in the previous iteration; in that case,
5283 			 * c->tid has not been bumped yet.
5284 			 * Since ___slab_alloc() may reenable interrupts while
5285 			 * allocating memory, we should bump c->tid now.
5286 			 */
5287 			c->tid = next_tid(c->tid);
5288 
5289 			local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
5290 
5291 			/*
5292 			 * Invoking slow path likely have side-effect
5293 			 * of re-populating per CPU c->freelist
5294 			 */
5295 			p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
5296 					    _RET_IP_, c, s->object_size);
5297 			if (unlikely(!p[i]))
5298 				goto error;
5299 
5300 			c = this_cpu_ptr(s->cpu_slab);
5301 			maybe_wipe_obj_freeptr(s, p[i]);
5302 
5303 			local_lock_irqsave(&s->cpu_slab->lock, irqflags);
5304 
5305 			continue; /* goto for-loop */
5306 		}
5307 		c->freelist = get_freepointer(s, object);
5308 		p[i] = object;
5309 		maybe_wipe_obj_freeptr(s, p[i]);
5310 		stat(s, ALLOC_FASTPATH);
5311 	}
5312 	c->tid = next_tid(c->tid);
5313 	local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
5314 	slub_put_cpu_ptr(s->cpu_slab);
5315 
5316 	return i;
5317 
5318 error:
5319 	slub_put_cpu_ptr(s->cpu_slab);
5320 	__kmem_cache_free_bulk(s, i, p);
5321 	return 0;
5322 
5323 }
5324 #else /* CONFIG_SLUB_TINY */
5325 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
5326 				   size_t size, void **p)
5327 {
5328 	int i;
5329 
5330 	for (i = 0; i < size; i++) {
5331 		void *object = kfence_alloc(s, s->object_size, flags);
5332 
5333 		if (unlikely(object)) {
5334 			p[i] = object;
5335 			continue;
5336 		}
5337 
5338 		p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE,
5339 					 _RET_IP_, s->object_size);
5340 		if (unlikely(!p[i]))
5341 			goto error;
5342 
5343 		maybe_wipe_obj_freeptr(s, p[i]);
5344 	}
5345 
5346 	return i;
5347 
5348 error:
5349 	__kmem_cache_free_bulk(s, i, p);
5350 	return 0;
5351 }
5352 #endif /* CONFIG_SLUB_TINY */
5353 
5354 /* Note that interrupts must be enabled when calling this function. */
5355 int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size,
5356 				 void **p)
5357 {
5358 	int i;
5359 
5360 	if (!size)
5361 		return 0;
5362 
5363 	s = slab_pre_alloc_hook(s, flags);
5364 	if (unlikely(!s))
5365 		return 0;
5366 
5367 	i = __kmem_cache_alloc_bulk(s, flags, size, p);
5368 	if (unlikely(i == 0))
5369 		return 0;
5370 
5371 	/*
5372 	 * memcg and kmem_cache debug support and memory initialization.
5373 	 * Done outside of the IRQ disabled fastpath loop.
5374 	 */
5375 	if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p,
5376 		    slab_want_init_on_alloc(flags, s), s->object_size))) {
5377 		return 0;
5378 	}
5379 	return i;
5380 }
5381 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
5382 
5383 
5384 /*
5385  * Object placement in a slab is made very easy because we always start at
5386  * offset 0. If we tune the size of the object to the alignment then we can
5387  * get the required alignment by putting one properly sized object after
5388  * another.
5389  *
5390  * Notice that the allocation order determines the sizes of the per cpu
5391  * caches. Each processor has always one slab available for allocations.
5392  * Increasing the allocation order reduces the number of times that slabs
5393  * must be moved on and off the partial lists and is therefore a factor in
5394  * locking overhead.
5395  */
5396 
5397 /*
5398  * Minimum / Maximum order of slab pages. This influences locking overhead
5399  * and slab fragmentation. A higher order reduces the number of partial slabs
5400  * and increases the number of allocations possible without having to
5401  * take the list_lock.
5402  */
5403 static unsigned int slub_min_order;
5404 static unsigned int slub_max_order =
5405 	IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
5406 static unsigned int slub_min_objects;
5407 
5408 /*
5409  * Calculate the order of allocation given an slab object size.
5410  *
5411  * The order of allocation has significant impact on performance and other
5412  * system components. Generally order 0 allocations should be preferred since
5413  * order 0 does not cause fragmentation in the page allocator. Larger objects
5414  * be problematic to put into order 0 slabs because there may be too much
5415  * unused space left. We go to a higher order if more than 1/16th of the slab
5416  * would be wasted.
5417  *
5418  * In order to reach satisfactory performance we must ensure that a minimum
5419  * number of objects is in one slab. Otherwise we may generate too much
5420  * activity on the partial lists which requires taking the list_lock. This is
5421  * less a concern for large slabs though which are rarely used.
5422  *
5423  * slab_max_order specifies the order where we begin to stop considering the
5424  * number of objects in a slab as critical. If we reach slab_max_order then
5425  * we try to keep the page order as low as possible. So we accept more waste
5426  * of space in favor of a small page order.
5427  *
5428  * Higher order allocations also allow the placement of more objects in a
5429  * slab and thereby reduce object handling overhead. If the user has
5430  * requested a higher minimum order then we start with that one instead of
5431  * the smallest order which will fit the object.
5432  */
5433 static inline unsigned int calc_slab_order(unsigned int size,
5434 		unsigned int min_order, unsigned int max_order,
5435 		unsigned int fract_leftover)
5436 {
5437 	unsigned int order;
5438 
5439 	for (order = min_order; order <= max_order; order++) {
5440 
5441 		unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
5442 		unsigned int rem;
5443 
5444 		rem = slab_size % size;
5445 
5446 		if (rem <= slab_size / fract_leftover)
5447 			break;
5448 	}
5449 
5450 	return order;
5451 }
5452 
5453 static inline int calculate_order(unsigned int size)
5454 {
5455 	unsigned int order;
5456 	unsigned int min_objects;
5457 	unsigned int max_objects;
5458 	unsigned int min_order;
5459 
5460 	min_objects = slub_min_objects;
5461 	if (!min_objects) {
5462 		/*
5463 		 * Some architectures will only update present cpus when
5464 		 * onlining them, so don't trust the number if it's just 1. But
5465 		 * we also don't want to use nr_cpu_ids always, as on some other
5466 		 * architectures, there can be many possible cpus, but never
5467 		 * onlined. Here we compromise between trying to avoid too high
5468 		 * order on systems that appear larger than they are, and too
5469 		 * low order on systems that appear smaller than they are.
5470 		 */
5471 		unsigned int nr_cpus = num_present_cpus();
5472 		if (nr_cpus <= 1)
5473 			nr_cpus = nr_cpu_ids;
5474 		min_objects = 4 * (fls(nr_cpus) + 1);
5475 	}
5476 	/* min_objects can't be 0 because get_order(0) is undefined */
5477 	max_objects = max(order_objects(slub_max_order, size), 1U);
5478 	min_objects = min(min_objects, max_objects);
5479 
5480 	min_order = max_t(unsigned int, slub_min_order,
5481 			  get_order(min_objects * size));
5482 	if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
5483 		return get_order(size * MAX_OBJS_PER_PAGE) - 1;
5484 
5485 	/*
5486 	 * Attempt to find best configuration for a slab. This works by first
5487 	 * attempting to generate a layout with the best possible configuration
5488 	 * and backing off gradually.
5489 	 *
5490 	 * We start with accepting at most 1/16 waste and try to find the
5491 	 * smallest order from min_objects-derived/slab_min_order up to
5492 	 * slab_max_order that will satisfy the constraint. Note that increasing
5493 	 * the order can only result in same or less fractional waste, not more.
5494 	 *
5495 	 * If that fails, we increase the acceptable fraction of waste and try
5496 	 * again. The last iteration with fraction of 1/2 would effectively
5497 	 * accept any waste and give us the order determined by min_objects, as
5498 	 * long as at least single object fits within slab_max_order.
5499 	 */
5500 	for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
5501 		order = calc_slab_order(size, min_order, slub_max_order,
5502 					fraction);
5503 		if (order <= slub_max_order)
5504 			return order;
5505 	}
5506 
5507 	/*
5508 	 * Doh this slab cannot be placed using slab_max_order.
5509 	 */
5510 	order = get_order(size);
5511 	if (order <= MAX_PAGE_ORDER)
5512 		return order;
5513 	return -ENOSYS;
5514 }
5515 
5516 static void
5517 init_kmem_cache_node(struct kmem_cache_node *n)
5518 {
5519 	n->nr_partial = 0;
5520 	spin_lock_init(&n->list_lock);
5521 	INIT_LIST_HEAD(&n->partial);
5522 #ifdef CONFIG_SLUB_DEBUG
5523 	atomic_long_set(&n->nr_slabs, 0);
5524 	atomic_long_set(&n->total_objects, 0);
5525 	INIT_LIST_HEAD(&n->full);
5526 #endif
5527 }
5528 
5529 #ifndef CONFIG_SLUB_TINY
5530 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
5531 {
5532 	BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
5533 			NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
5534 			sizeof(struct kmem_cache_cpu));
5535 
5536 	/*
5537 	 * Must align to double word boundary for the double cmpxchg
5538 	 * instructions to work; see __pcpu_double_call_return_bool().
5539 	 */
5540 	s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
5541 				     2 * sizeof(void *));
5542 
5543 	if (!s->cpu_slab)
5544 		return 0;
5545 
5546 	init_kmem_cache_cpus(s);
5547 
5548 	return 1;
5549 }
5550 #else
5551 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
5552 {
5553 	return 1;
5554 }
5555 #endif /* CONFIG_SLUB_TINY */
5556 
5557 static struct kmem_cache *kmem_cache_node;
5558 
5559 /*
5560  * No kmalloc_node yet so do it by hand. We know that this is the first
5561  * slab on the node for this slabcache. There are no concurrent accesses
5562  * possible.
5563  *
5564  * Note that this function only works on the kmem_cache_node
5565  * when allocating for the kmem_cache_node. This is used for bootstrapping
5566  * memory on a fresh node that has no slab structures yet.
5567  */
5568 static void early_kmem_cache_node_alloc(int node)
5569 {
5570 	struct slab *slab;
5571 	struct kmem_cache_node *n;
5572 
5573 	BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
5574 
5575 	slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
5576 
5577 	BUG_ON(!slab);
5578 	if (slab_nid(slab) != node) {
5579 		pr_err("SLUB: Unable to allocate memory from node %d\n", node);
5580 		pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
5581 	}
5582 
5583 	n = slab->freelist;
5584 	BUG_ON(!n);
5585 #ifdef CONFIG_SLUB_DEBUG
5586 	init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
5587 #endif
5588 	n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
5589 	slab->freelist = get_freepointer(kmem_cache_node, n);
5590 	slab->inuse = 1;
5591 	kmem_cache_node->node[node] = n;
5592 	init_kmem_cache_node(n);
5593 	inc_slabs_node(kmem_cache_node, node, slab->objects);
5594 
5595 	/*
5596 	 * No locks need to be taken here as it has just been
5597 	 * initialized and there is no concurrent access.
5598 	 */
5599 	__add_partial(n, slab, DEACTIVATE_TO_HEAD);
5600 }
5601 
5602 static void free_kmem_cache_nodes(struct kmem_cache *s)
5603 {
5604 	int node;
5605 	struct kmem_cache_node *n;
5606 
5607 	for_each_kmem_cache_node(s, node, n) {
5608 		s->node[node] = NULL;
5609 		kmem_cache_free(kmem_cache_node, n);
5610 	}
5611 }
5612 
5613 void __kmem_cache_release(struct kmem_cache *s)
5614 {
5615 	cache_random_seq_destroy(s);
5616 #ifndef CONFIG_SLUB_TINY
5617 	free_percpu(s->cpu_slab);
5618 #endif
5619 	free_kmem_cache_nodes(s);
5620 }
5621 
5622 static int init_kmem_cache_nodes(struct kmem_cache *s)
5623 {
5624 	int node;
5625 
5626 	for_each_node_mask(node, slab_nodes) {
5627 		struct kmem_cache_node *n;
5628 
5629 		if (slab_state == DOWN) {
5630 			early_kmem_cache_node_alloc(node);
5631 			continue;
5632 		}
5633 		n = kmem_cache_alloc_node(kmem_cache_node,
5634 						GFP_KERNEL, node);
5635 
5636 		if (!n) {
5637 			free_kmem_cache_nodes(s);
5638 			return 0;
5639 		}
5640 
5641 		init_kmem_cache_node(n);
5642 		s->node[node] = n;
5643 	}
5644 	return 1;
5645 }
5646 
5647 static void set_cpu_partial(struct kmem_cache *s)
5648 {
5649 #ifdef CONFIG_SLUB_CPU_PARTIAL
5650 	unsigned int nr_objects;
5651 
5652 	/*
5653 	 * cpu_partial determined the maximum number of objects kept in the
5654 	 * per cpu partial lists of a processor.
5655 	 *
5656 	 * Per cpu partial lists mainly contain slabs that just have one
5657 	 * object freed. If they are used for allocation then they can be
5658 	 * filled up again with minimal effort. The slab will never hit the
5659 	 * per node partial lists and therefore no locking will be required.
5660 	 *
5661 	 * For backwards compatibility reasons, this is determined as number
5662 	 * of objects, even though we now limit maximum number of pages, see
5663 	 * slub_set_cpu_partial()
5664 	 */
5665 	if (!kmem_cache_has_cpu_partial(s))
5666 		nr_objects = 0;
5667 	else if (s->size >= PAGE_SIZE)
5668 		nr_objects = 6;
5669 	else if (s->size >= 1024)
5670 		nr_objects = 24;
5671 	else if (s->size >= 256)
5672 		nr_objects = 52;
5673 	else
5674 		nr_objects = 120;
5675 
5676 	slub_set_cpu_partial(s, nr_objects);
5677 #endif
5678 }
5679 
5680 /*
5681  * calculate_sizes() determines the order and the distribution of data within
5682  * a slab object.
5683  */
5684 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
5685 {
5686 	slab_flags_t flags = s->flags;
5687 	unsigned int size = s->object_size;
5688 	unsigned int order;
5689 
5690 	/*
5691 	 * Round up object size to the next word boundary. We can only
5692 	 * place the free pointer at word boundaries and this determines
5693 	 * the possible location of the free pointer.
5694 	 */
5695 	size = ALIGN(size, sizeof(void *));
5696 
5697 #ifdef CONFIG_SLUB_DEBUG
5698 	/*
5699 	 * Determine if we can poison the object itself. If the user of
5700 	 * the slab may touch the object after free or before allocation
5701 	 * then we should never poison the object itself.
5702 	 */
5703 	if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
5704 			!s->ctor)
5705 		s->flags |= __OBJECT_POISON;
5706 	else
5707 		s->flags &= ~__OBJECT_POISON;
5708 
5709 
5710 	/*
5711 	 * If we are Redzoning then check if there is some space between the
5712 	 * end of the object and the free pointer. If not then add an
5713 	 * additional word to have some bytes to store Redzone information.
5714 	 */
5715 	if ((flags & SLAB_RED_ZONE) && size == s->object_size)
5716 		size += sizeof(void *);
5717 #endif
5718 
5719 	/*
5720 	 * With that we have determined the number of bytes in actual use
5721 	 * by the object and redzoning.
5722 	 */
5723 	s->inuse = size;
5724 
5725 	if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
5726 	    (flags & SLAB_POISON) || s->ctor ||
5727 	    ((flags & SLAB_RED_ZONE) &&
5728 	     (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
5729 		/*
5730 		 * Relocate free pointer after the object if it is not
5731 		 * permitted to overwrite the first word of the object on
5732 		 * kmem_cache_free.
5733 		 *
5734 		 * This is the case if we do RCU, have a constructor or
5735 		 * destructor, are poisoning the objects, or are
5736 		 * redzoning an object smaller than sizeof(void *) or are
5737 		 * redzoning an object with slub_debug_orig_size() enabled,
5738 		 * in which case the right redzone may be extended.
5739 		 *
5740 		 * The assumption that s->offset >= s->inuse means free
5741 		 * pointer is outside of the object is used in the
5742 		 * freeptr_outside_object() function. If that is no
5743 		 * longer true, the function needs to be modified.
5744 		 */
5745 		s->offset = size;
5746 		size += sizeof(void *);
5747 	} else if ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) {
5748 		s->offset = args->freeptr_offset;
5749 	} else {
5750 		/*
5751 		 * Store freelist pointer near middle of object to keep
5752 		 * it away from the edges of the object to avoid small
5753 		 * sized over/underflows from neighboring allocations.
5754 		 */
5755 		s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
5756 	}
5757 
5758 #ifdef CONFIG_SLUB_DEBUG
5759 	if (flags & SLAB_STORE_USER) {
5760 		/*
5761 		 * Need to store information about allocs and frees after
5762 		 * the object.
5763 		 */
5764 		size += 2 * sizeof(struct track);
5765 
5766 		/* Save the original kmalloc request size */
5767 		if (flags & SLAB_KMALLOC)
5768 			size += sizeof(unsigned int);
5769 	}
5770 #endif
5771 
5772 	kasan_cache_create(s, &size, &s->flags);
5773 #ifdef CONFIG_SLUB_DEBUG
5774 	if (flags & SLAB_RED_ZONE) {
5775 		/*
5776 		 * Add some empty padding so that we can catch
5777 		 * overwrites from earlier objects rather than let
5778 		 * tracking information or the free pointer be
5779 		 * corrupted if a user writes before the start
5780 		 * of the object.
5781 		 */
5782 		size += sizeof(void *);
5783 
5784 		s->red_left_pad = sizeof(void *);
5785 		s->red_left_pad = ALIGN(s->red_left_pad, s->align);
5786 		size += s->red_left_pad;
5787 	}
5788 #endif
5789 
5790 	/*
5791 	 * SLUB stores one object immediately after another beginning from
5792 	 * offset 0. In order to align the objects we have to simply size
5793 	 * each object to conform to the alignment.
5794 	 */
5795 	size = ALIGN(size, s->align);
5796 	s->size = size;
5797 	s->reciprocal_size = reciprocal_value(size);
5798 	order = calculate_order(size);
5799 
5800 	if ((int)order < 0)
5801 		return 0;
5802 
5803 	s->allocflags = __GFP_COMP;
5804 
5805 	if (s->flags & SLAB_CACHE_DMA)
5806 		s->allocflags |= GFP_DMA;
5807 
5808 	if (s->flags & SLAB_CACHE_DMA32)
5809 		s->allocflags |= GFP_DMA32;
5810 
5811 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
5812 		s->allocflags |= __GFP_RECLAIMABLE;
5813 
5814 	/*
5815 	 * Determine the number of objects per slab
5816 	 */
5817 	s->oo = oo_make(order, size);
5818 	s->min = oo_make(get_order(size), size);
5819 
5820 	return !!oo_objects(s->oo);
5821 }
5822 
5823 static void list_slab_objects(struct kmem_cache *s, struct slab *slab)
5824 {
5825 #ifdef CONFIG_SLUB_DEBUG
5826 	void *addr = slab_address(slab);
5827 	void *p;
5828 
5829 	if (!slab_add_kunit_errors())
5830 		slab_bug(s, "Objects remaining on __kmem_cache_shutdown()");
5831 
5832 	spin_lock(&object_map_lock);
5833 	__fill_map(object_map, s, slab);
5834 
5835 	for_each_object(p, s, addr, slab->objects) {
5836 
5837 		if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
5838 			if (slab_add_kunit_errors())
5839 				continue;
5840 			pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
5841 			print_tracking(s, p);
5842 		}
5843 	}
5844 	spin_unlock(&object_map_lock);
5845 
5846 	__slab_err(slab);
5847 #endif
5848 }
5849 
5850 /*
5851  * Attempt to free all partial slabs on a node.
5852  * This is called from __kmem_cache_shutdown(). We must take list_lock
5853  * because sysfs file might still access partial list after the shutdowning.
5854  */
5855 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
5856 {
5857 	LIST_HEAD(discard);
5858 	struct slab *slab, *h;
5859 
5860 	BUG_ON(irqs_disabled());
5861 	spin_lock_irq(&n->list_lock);
5862 	list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
5863 		if (!slab->inuse) {
5864 			remove_partial(n, slab);
5865 			list_add(&slab->slab_list, &discard);
5866 		} else {
5867 			list_slab_objects(s, slab);
5868 		}
5869 	}
5870 	spin_unlock_irq(&n->list_lock);
5871 
5872 	list_for_each_entry_safe(slab, h, &discard, slab_list)
5873 		discard_slab(s, slab);
5874 }
5875 
5876 bool __kmem_cache_empty(struct kmem_cache *s)
5877 {
5878 	int node;
5879 	struct kmem_cache_node *n;
5880 
5881 	for_each_kmem_cache_node(s, node, n)
5882 		if (n->nr_partial || node_nr_slabs(n))
5883 			return false;
5884 	return true;
5885 }
5886 
5887 /*
5888  * Release all resources used by a slab cache.
5889  */
5890 int __kmem_cache_shutdown(struct kmem_cache *s)
5891 {
5892 	int node;
5893 	struct kmem_cache_node *n;
5894 
5895 	flush_all_cpus_locked(s);
5896 	/* Attempt to free all objects */
5897 	for_each_kmem_cache_node(s, node, n) {
5898 		free_partial(s, n);
5899 		if (n->nr_partial || node_nr_slabs(n))
5900 			return 1;
5901 	}
5902 	return 0;
5903 }
5904 
5905 #ifdef CONFIG_PRINTK
5906 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
5907 {
5908 	void *base;
5909 	int __maybe_unused i;
5910 	unsigned int objnr;
5911 	void *objp;
5912 	void *objp0;
5913 	struct kmem_cache *s = slab->slab_cache;
5914 	struct track __maybe_unused *trackp;
5915 
5916 	kpp->kp_ptr = object;
5917 	kpp->kp_slab = slab;
5918 	kpp->kp_slab_cache = s;
5919 	base = slab_address(slab);
5920 	objp0 = kasan_reset_tag(object);
5921 #ifdef CONFIG_SLUB_DEBUG
5922 	objp = restore_red_left(s, objp0);
5923 #else
5924 	objp = objp0;
5925 #endif
5926 	objnr = obj_to_index(s, slab, objp);
5927 	kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
5928 	objp = base + s->size * objnr;
5929 	kpp->kp_objp = objp;
5930 	if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
5931 			 || (objp - base) % s->size) ||
5932 	    !(s->flags & SLAB_STORE_USER))
5933 		return;
5934 #ifdef CONFIG_SLUB_DEBUG
5935 	objp = fixup_red_left(s, objp);
5936 	trackp = get_track(s, objp, TRACK_ALLOC);
5937 	kpp->kp_ret = (void *)trackp->addr;
5938 #ifdef CONFIG_STACKDEPOT
5939 	{
5940 		depot_stack_handle_t handle;
5941 		unsigned long *entries;
5942 		unsigned int nr_entries;
5943 
5944 		handle = READ_ONCE(trackp->handle);
5945 		if (handle) {
5946 			nr_entries = stack_depot_fetch(handle, &entries);
5947 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
5948 				kpp->kp_stack[i] = (void *)entries[i];
5949 		}
5950 
5951 		trackp = get_track(s, objp, TRACK_FREE);
5952 		handle = READ_ONCE(trackp->handle);
5953 		if (handle) {
5954 			nr_entries = stack_depot_fetch(handle, &entries);
5955 			for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
5956 				kpp->kp_free_stack[i] = (void *)entries[i];
5957 		}
5958 	}
5959 #endif
5960 #endif
5961 }
5962 #endif
5963 
5964 /********************************************************************
5965  *		Kmalloc subsystem
5966  *******************************************************************/
5967 
5968 static int __init setup_slub_min_order(char *str)
5969 {
5970 	get_option(&str, (int *)&slub_min_order);
5971 
5972 	if (slub_min_order > slub_max_order)
5973 		slub_max_order = slub_min_order;
5974 
5975 	return 1;
5976 }
5977 
5978 __setup("slab_min_order=", setup_slub_min_order);
5979 __setup_param("slub_min_order=", slub_min_order, setup_slub_min_order, 0);
5980 
5981 
5982 static int __init setup_slub_max_order(char *str)
5983 {
5984 	get_option(&str, (int *)&slub_max_order);
5985 	slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
5986 
5987 	if (slub_min_order > slub_max_order)
5988 		slub_min_order = slub_max_order;
5989 
5990 	return 1;
5991 }
5992 
5993 __setup("slab_max_order=", setup_slub_max_order);
5994 __setup_param("slub_max_order=", slub_max_order, setup_slub_max_order, 0);
5995 
5996 static int __init setup_slub_min_objects(char *str)
5997 {
5998 	get_option(&str, (int *)&slub_min_objects);
5999 
6000 	return 1;
6001 }
6002 
6003 __setup("slab_min_objects=", setup_slub_min_objects);
6004 __setup_param("slub_min_objects=", slub_min_objects, setup_slub_min_objects, 0);
6005 
6006 #ifdef CONFIG_NUMA
6007 static int __init setup_slab_strict_numa(char *str)
6008 {
6009 	if (nr_node_ids > 1) {
6010 		static_branch_enable(&strict_numa);
6011 		pr_info("SLUB: Strict NUMA enabled.\n");
6012 	} else {
6013 		pr_warn("slab_strict_numa parameter set on non NUMA system.\n");
6014 	}
6015 
6016 	return 1;
6017 }
6018 
6019 __setup("slab_strict_numa", setup_slab_strict_numa);
6020 #endif
6021 
6022 
6023 #ifdef CONFIG_HARDENED_USERCOPY
6024 /*
6025  * Rejects incorrectly sized objects and objects that are to be copied
6026  * to/from userspace but do not fall entirely within the containing slab
6027  * cache's usercopy region.
6028  *
6029  * Returns NULL if check passes, otherwise const char * to name of cache
6030  * to indicate an error.
6031  */
6032 void __check_heap_object(const void *ptr, unsigned long n,
6033 			 const struct slab *slab, bool to_user)
6034 {
6035 	struct kmem_cache *s;
6036 	unsigned int offset;
6037 	bool is_kfence = is_kfence_address(ptr);
6038 
6039 	ptr = kasan_reset_tag(ptr);
6040 
6041 	/* Find object and usable object size. */
6042 	s = slab->slab_cache;
6043 
6044 	/* Reject impossible pointers. */
6045 	if (ptr < slab_address(slab))
6046 		usercopy_abort("SLUB object not in SLUB page?!", NULL,
6047 			       to_user, 0, n);
6048 
6049 	/* Find offset within object. */
6050 	if (is_kfence)
6051 		offset = ptr - kfence_object_start(ptr);
6052 	else
6053 		offset = (ptr - slab_address(slab)) % s->size;
6054 
6055 	/* Adjust for redzone and reject if within the redzone. */
6056 	if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
6057 		if (offset < s->red_left_pad)
6058 			usercopy_abort("SLUB object in left red zone",
6059 				       s->name, to_user, offset, n);
6060 		offset -= s->red_left_pad;
6061 	}
6062 
6063 	/* Allow address range falling entirely within usercopy region. */
6064 	if (offset >= s->useroffset &&
6065 	    offset - s->useroffset <= s->usersize &&
6066 	    n <= s->useroffset - offset + s->usersize)
6067 		return;
6068 
6069 	usercopy_abort("SLUB object", s->name, to_user, offset, n);
6070 }
6071 #endif /* CONFIG_HARDENED_USERCOPY */
6072 
6073 #define SHRINK_PROMOTE_MAX 32
6074 
6075 /*
6076  * kmem_cache_shrink discards empty slabs and promotes the slabs filled
6077  * up most to the head of the partial lists. New allocations will then
6078  * fill those up and thus they can be removed from the partial lists.
6079  *
6080  * The slabs with the least items are placed last. This results in them
6081  * being allocated from last increasing the chance that the last objects
6082  * are freed in them.
6083  */
6084 static int __kmem_cache_do_shrink(struct kmem_cache *s)
6085 {
6086 	int node;
6087 	int i;
6088 	struct kmem_cache_node *n;
6089 	struct slab *slab;
6090 	struct slab *t;
6091 	struct list_head discard;
6092 	struct list_head promote[SHRINK_PROMOTE_MAX];
6093 	unsigned long flags;
6094 	int ret = 0;
6095 
6096 	for_each_kmem_cache_node(s, node, n) {
6097 		INIT_LIST_HEAD(&discard);
6098 		for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
6099 			INIT_LIST_HEAD(promote + i);
6100 
6101 		spin_lock_irqsave(&n->list_lock, flags);
6102 
6103 		/*
6104 		 * Build lists of slabs to discard or promote.
6105 		 *
6106 		 * Note that concurrent frees may occur while we hold the
6107 		 * list_lock. slab->inuse here is the upper limit.
6108 		 */
6109 		list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
6110 			int free = slab->objects - slab->inuse;
6111 
6112 			/* Do not reread slab->inuse */
6113 			barrier();
6114 
6115 			/* We do not keep full slabs on the list */
6116 			BUG_ON(free <= 0);
6117 
6118 			if (free == slab->objects) {
6119 				list_move(&slab->slab_list, &discard);
6120 				slab_clear_node_partial(slab);
6121 				n->nr_partial--;
6122 				dec_slabs_node(s, node, slab->objects);
6123 			} else if (free <= SHRINK_PROMOTE_MAX)
6124 				list_move(&slab->slab_list, promote + free - 1);
6125 		}
6126 
6127 		/*
6128 		 * Promote the slabs filled up most to the head of the
6129 		 * partial list.
6130 		 */
6131 		for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
6132 			list_splice(promote + i, &n->partial);
6133 
6134 		spin_unlock_irqrestore(&n->list_lock, flags);
6135 
6136 		/* Release empty slabs */
6137 		list_for_each_entry_safe(slab, t, &discard, slab_list)
6138 			free_slab(s, slab);
6139 
6140 		if (node_nr_slabs(n))
6141 			ret = 1;
6142 	}
6143 
6144 	return ret;
6145 }
6146 
6147 int __kmem_cache_shrink(struct kmem_cache *s)
6148 {
6149 	flush_all(s);
6150 	return __kmem_cache_do_shrink(s);
6151 }
6152 
6153 static int slab_mem_going_offline_callback(void)
6154 {
6155 	struct kmem_cache *s;
6156 
6157 	mutex_lock(&slab_mutex);
6158 	list_for_each_entry(s, &slab_caches, list) {
6159 		flush_all_cpus_locked(s);
6160 		__kmem_cache_do_shrink(s);
6161 	}
6162 	mutex_unlock(&slab_mutex);
6163 
6164 	return 0;
6165 }
6166 
6167 static int slab_mem_going_online_callback(int nid)
6168 {
6169 	struct kmem_cache_node *n;
6170 	struct kmem_cache *s;
6171 	int ret = 0;
6172 
6173 	/*
6174 	 * We are bringing a node online. No memory is available yet. We must
6175 	 * allocate a kmem_cache_node structure in order to bring the node
6176 	 * online.
6177 	 */
6178 	mutex_lock(&slab_mutex);
6179 	list_for_each_entry(s, &slab_caches, list) {
6180 		/*
6181 		 * The structure may already exist if the node was previously
6182 		 * onlined and offlined.
6183 		 */
6184 		if (get_node(s, nid))
6185 			continue;
6186 		/*
6187 		 * XXX: kmem_cache_alloc_node will fallback to other nodes
6188 		 *      since memory is not yet available from the node that
6189 		 *      is brought up.
6190 		 */
6191 		n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
6192 		if (!n) {
6193 			ret = -ENOMEM;
6194 			goto out;
6195 		}
6196 		init_kmem_cache_node(n);
6197 		s->node[nid] = n;
6198 	}
6199 	/*
6200 	 * Any cache created after this point will also have kmem_cache_node
6201 	 * initialized for the new node.
6202 	 */
6203 	node_set(nid, slab_nodes);
6204 out:
6205 	mutex_unlock(&slab_mutex);
6206 	return ret;
6207 }
6208 
6209 static int slab_memory_callback(struct notifier_block *self,
6210 				unsigned long action, void *arg)
6211 {
6212 	struct node_notify *nn = arg;
6213 	int nid = nn->nid;
6214 	int ret = 0;
6215 
6216 	switch (action) {
6217 	case NODE_ADDING_FIRST_MEMORY:
6218 		ret = slab_mem_going_online_callback(nid);
6219 		break;
6220 	case NODE_REMOVING_LAST_MEMORY:
6221 		ret = slab_mem_going_offline_callback();
6222 		break;
6223 	}
6224 	if (ret)
6225 		ret = notifier_from_errno(ret);
6226 	else
6227 		ret = NOTIFY_OK;
6228 	return ret;
6229 }
6230 
6231 /********************************************************************
6232  *			Basic setup of slabs
6233  *******************************************************************/
6234 
6235 /*
6236  * Used for early kmem_cache structures that were allocated using
6237  * the page allocator. Allocate them properly then fix up the pointers
6238  * that may be pointing to the wrong kmem_cache structure.
6239  */
6240 
6241 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
6242 {
6243 	int node;
6244 	struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
6245 	struct kmem_cache_node *n;
6246 
6247 	memcpy(s, static_cache, kmem_cache->object_size);
6248 
6249 	/*
6250 	 * This runs very early, and only the boot processor is supposed to be
6251 	 * up.  Even if it weren't true, IRQs are not up so we couldn't fire
6252 	 * IPIs around.
6253 	 */
6254 	__flush_cpu_slab(s, smp_processor_id());
6255 	for_each_kmem_cache_node(s, node, n) {
6256 		struct slab *p;
6257 
6258 		list_for_each_entry(p, &n->partial, slab_list)
6259 			p->slab_cache = s;
6260 
6261 #ifdef CONFIG_SLUB_DEBUG
6262 		list_for_each_entry(p, &n->full, slab_list)
6263 			p->slab_cache = s;
6264 #endif
6265 	}
6266 	list_add(&s->list, &slab_caches);
6267 	return s;
6268 }
6269 
6270 void __init kmem_cache_init(void)
6271 {
6272 	static __initdata struct kmem_cache boot_kmem_cache,
6273 		boot_kmem_cache_node;
6274 	int node;
6275 
6276 	if (debug_guardpage_minorder())
6277 		slub_max_order = 0;
6278 
6279 	/* Print slub debugging pointers without hashing */
6280 	if (__slub_debug_enabled())
6281 		no_hash_pointers_enable(NULL);
6282 
6283 	kmem_cache_node = &boot_kmem_cache_node;
6284 	kmem_cache = &boot_kmem_cache;
6285 
6286 	/*
6287 	 * Initialize the nodemask for which we will allocate per node
6288 	 * structures. Here we don't need taking slab_mutex yet.
6289 	 */
6290 	for_each_node_state(node, N_MEMORY)
6291 		node_set(node, slab_nodes);
6292 
6293 	create_boot_cache(kmem_cache_node, "kmem_cache_node",
6294 			sizeof(struct kmem_cache_node),
6295 			SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
6296 
6297 	hotplug_node_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
6298 
6299 	/* Able to allocate the per node structures */
6300 	slab_state = PARTIAL;
6301 
6302 	create_boot_cache(kmem_cache, "kmem_cache",
6303 			offsetof(struct kmem_cache, node) +
6304 				nr_node_ids * sizeof(struct kmem_cache_node *),
6305 			SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
6306 
6307 	kmem_cache = bootstrap(&boot_kmem_cache);
6308 	kmem_cache_node = bootstrap(&boot_kmem_cache_node);
6309 
6310 	/* Now we can use the kmem_cache to allocate kmalloc slabs */
6311 	setup_kmalloc_cache_index_table();
6312 	create_kmalloc_caches();
6313 
6314 	/* Setup random freelists for each cache */
6315 	init_freelist_randomization();
6316 
6317 	cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
6318 				  slub_cpu_dead);
6319 
6320 	pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
6321 		cache_line_size(),
6322 		slub_min_order, slub_max_order, slub_min_objects,
6323 		nr_cpu_ids, nr_node_ids);
6324 }
6325 
6326 void __init kmem_cache_init_late(void)
6327 {
6328 #ifndef CONFIG_SLUB_TINY
6329 	flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
6330 	WARN_ON(!flushwq);
6331 #endif
6332 }
6333 
6334 struct kmem_cache *
6335 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
6336 		   slab_flags_t flags, void (*ctor)(void *))
6337 {
6338 	struct kmem_cache *s;
6339 
6340 	s = find_mergeable(size, align, flags, name, ctor);
6341 	if (s) {
6342 		if (sysfs_slab_alias(s, name))
6343 			pr_err("SLUB: Unable to add cache alias %s to sysfs\n",
6344 			       name);
6345 
6346 		s->refcount++;
6347 
6348 		/*
6349 		 * Adjust the object sizes so that we clear
6350 		 * the complete object on kzalloc.
6351 		 */
6352 		s->object_size = max(s->object_size, size);
6353 		s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
6354 	}
6355 
6356 	return s;
6357 }
6358 
6359 int do_kmem_cache_create(struct kmem_cache *s, const char *name,
6360 			 unsigned int size, struct kmem_cache_args *args,
6361 			 slab_flags_t flags)
6362 {
6363 	int err = -EINVAL;
6364 
6365 	s->name = name;
6366 	s->size = s->object_size = size;
6367 
6368 	s->flags = kmem_cache_flags(flags, s->name);
6369 #ifdef CONFIG_SLAB_FREELIST_HARDENED
6370 	s->random = get_random_long();
6371 #endif
6372 	s->align = args->align;
6373 	s->ctor = args->ctor;
6374 #ifdef CONFIG_HARDENED_USERCOPY
6375 	s->useroffset = args->useroffset;
6376 	s->usersize = args->usersize;
6377 #endif
6378 
6379 	if (!calculate_sizes(args, s))
6380 		goto out;
6381 	if (disable_higher_order_debug) {
6382 		/*
6383 		 * Disable debugging flags that store metadata if the min slab
6384 		 * order increased.
6385 		 */
6386 		if (get_order(s->size) > get_order(s->object_size)) {
6387 			s->flags &= ~DEBUG_METADATA_FLAGS;
6388 			s->offset = 0;
6389 			if (!calculate_sizes(args, s))
6390 				goto out;
6391 		}
6392 	}
6393 
6394 #ifdef system_has_freelist_aba
6395 	if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
6396 		/* Enable fast mode */
6397 		s->flags |= __CMPXCHG_DOUBLE;
6398 	}
6399 #endif
6400 
6401 	/*
6402 	 * The larger the object size is, the more slabs we want on the partial
6403 	 * list to avoid pounding the page allocator excessively.
6404 	 */
6405 	s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
6406 	s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
6407 
6408 	set_cpu_partial(s);
6409 
6410 #ifdef CONFIG_NUMA
6411 	s->remote_node_defrag_ratio = 1000;
6412 #endif
6413 
6414 	/* Initialize the pre-computed randomized freelist if slab is up */
6415 	if (slab_state >= UP) {
6416 		if (init_cache_random_seq(s))
6417 			goto out;
6418 	}
6419 
6420 	if (!init_kmem_cache_nodes(s))
6421 		goto out;
6422 
6423 	if (!alloc_kmem_cache_cpus(s))
6424 		goto out;
6425 
6426 	err = 0;
6427 
6428 	/* Mutex is not taken during early boot */
6429 	if (slab_state <= UP)
6430 		goto out;
6431 
6432 	/*
6433 	 * Failing to create sysfs files is not critical to SLUB functionality.
6434 	 * If it fails, proceed with cache creation without these files.
6435 	 */
6436 	if (sysfs_slab_add(s))
6437 		pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name);
6438 
6439 	if (s->flags & SLAB_STORE_USER)
6440 		debugfs_slab_add(s);
6441 
6442 out:
6443 	if (err)
6444 		__kmem_cache_release(s);
6445 	return err;
6446 }
6447 
6448 #ifdef SLAB_SUPPORTS_SYSFS
6449 static int count_inuse(struct slab *slab)
6450 {
6451 	return slab->inuse;
6452 }
6453 
6454 static int count_total(struct slab *slab)
6455 {
6456 	return slab->objects;
6457 }
6458 #endif
6459 
6460 #ifdef CONFIG_SLUB_DEBUG
6461 static void validate_slab(struct kmem_cache *s, struct slab *slab,
6462 			  unsigned long *obj_map)
6463 {
6464 	void *p;
6465 	void *addr = slab_address(slab);
6466 
6467 	if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
6468 		return;
6469 
6470 	/* Now we know that a valid freelist exists */
6471 	__fill_map(obj_map, s, slab);
6472 	for_each_object(p, s, addr, slab->objects) {
6473 		u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
6474 			 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
6475 
6476 		if (!check_object(s, slab, p, val))
6477 			break;
6478 	}
6479 }
6480 
6481 static int validate_slab_node(struct kmem_cache *s,
6482 		struct kmem_cache_node *n, unsigned long *obj_map)
6483 {
6484 	unsigned long count = 0;
6485 	struct slab *slab;
6486 	unsigned long flags;
6487 
6488 	spin_lock_irqsave(&n->list_lock, flags);
6489 
6490 	list_for_each_entry(slab, &n->partial, slab_list) {
6491 		validate_slab(s, slab, obj_map);
6492 		count++;
6493 	}
6494 	if (count != n->nr_partial) {
6495 		pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
6496 		       s->name, count, n->nr_partial);
6497 		slab_add_kunit_errors();
6498 	}
6499 
6500 	if (!(s->flags & SLAB_STORE_USER))
6501 		goto out;
6502 
6503 	list_for_each_entry(slab, &n->full, slab_list) {
6504 		validate_slab(s, slab, obj_map);
6505 		count++;
6506 	}
6507 	if (count != node_nr_slabs(n)) {
6508 		pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
6509 		       s->name, count, node_nr_slabs(n));
6510 		slab_add_kunit_errors();
6511 	}
6512 
6513 out:
6514 	spin_unlock_irqrestore(&n->list_lock, flags);
6515 	return count;
6516 }
6517 
6518 long validate_slab_cache(struct kmem_cache *s)
6519 {
6520 	int node;
6521 	unsigned long count = 0;
6522 	struct kmem_cache_node *n;
6523 	unsigned long *obj_map;
6524 
6525 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
6526 	if (!obj_map)
6527 		return -ENOMEM;
6528 
6529 	flush_all(s);
6530 	for_each_kmem_cache_node(s, node, n)
6531 		count += validate_slab_node(s, n, obj_map);
6532 
6533 	bitmap_free(obj_map);
6534 
6535 	return count;
6536 }
6537 EXPORT_SYMBOL(validate_slab_cache);
6538 
6539 #ifdef CONFIG_DEBUG_FS
6540 /*
6541  * Generate lists of code addresses where slabcache objects are allocated
6542  * and freed.
6543  */
6544 
6545 struct location {
6546 	depot_stack_handle_t handle;
6547 	unsigned long count;
6548 	unsigned long addr;
6549 	unsigned long waste;
6550 	long long sum_time;
6551 	long min_time;
6552 	long max_time;
6553 	long min_pid;
6554 	long max_pid;
6555 	DECLARE_BITMAP(cpus, NR_CPUS);
6556 	nodemask_t nodes;
6557 };
6558 
6559 struct loc_track {
6560 	unsigned long max;
6561 	unsigned long count;
6562 	struct location *loc;
6563 	loff_t idx;
6564 };
6565 
6566 static struct dentry *slab_debugfs_root;
6567 
6568 static void free_loc_track(struct loc_track *t)
6569 {
6570 	if (t->max)
6571 		free_pages((unsigned long)t->loc,
6572 			get_order(sizeof(struct location) * t->max));
6573 }
6574 
6575 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
6576 {
6577 	struct location *l;
6578 	int order;
6579 
6580 	order = get_order(sizeof(struct location) * max);
6581 
6582 	l = (void *)__get_free_pages(flags, order);
6583 	if (!l)
6584 		return 0;
6585 
6586 	if (t->count) {
6587 		memcpy(l, t->loc, sizeof(struct location) * t->count);
6588 		free_loc_track(t);
6589 	}
6590 	t->max = max;
6591 	t->loc = l;
6592 	return 1;
6593 }
6594 
6595 static int add_location(struct loc_track *t, struct kmem_cache *s,
6596 				const struct track *track,
6597 				unsigned int orig_size)
6598 {
6599 	long start, end, pos;
6600 	struct location *l;
6601 	unsigned long caddr, chandle, cwaste;
6602 	unsigned long age = jiffies - track->when;
6603 	depot_stack_handle_t handle = 0;
6604 	unsigned int waste = s->object_size - orig_size;
6605 
6606 #ifdef CONFIG_STACKDEPOT
6607 	handle = READ_ONCE(track->handle);
6608 #endif
6609 	start = -1;
6610 	end = t->count;
6611 
6612 	for ( ; ; ) {
6613 		pos = start + (end - start + 1) / 2;
6614 
6615 		/*
6616 		 * There is nothing at "end". If we end up there
6617 		 * we need to add something to before end.
6618 		 */
6619 		if (pos == end)
6620 			break;
6621 
6622 		l = &t->loc[pos];
6623 		caddr = l->addr;
6624 		chandle = l->handle;
6625 		cwaste = l->waste;
6626 		if ((track->addr == caddr) && (handle == chandle) &&
6627 			(waste == cwaste)) {
6628 
6629 			l->count++;
6630 			if (track->when) {
6631 				l->sum_time += age;
6632 				if (age < l->min_time)
6633 					l->min_time = age;
6634 				if (age > l->max_time)
6635 					l->max_time = age;
6636 
6637 				if (track->pid < l->min_pid)
6638 					l->min_pid = track->pid;
6639 				if (track->pid > l->max_pid)
6640 					l->max_pid = track->pid;
6641 
6642 				cpumask_set_cpu(track->cpu,
6643 						to_cpumask(l->cpus));
6644 			}
6645 			node_set(page_to_nid(virt_to_page(track)), l->nodes);
6646 			return 1;
6647 		}
6648 
6649 		if (track->addr < caddr)
6650 			end = pos;
6651 		else if (track->addr == caddr && handle < chandle)
6652 			end = pos;
6653 		else if (track->addr == caddr && handle == chandle &&
6654 				waste < cwaste)
6655 			end = pos;
6656 		else
6657 			start = pos;
6658 	}
6659 
6660 	/*
6661 	 * Not found. Insert new tracking element.
6662 	 */
6663 	if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
6664 		return 0;
6665 
6666 	l = t->loc + pos;
6667 	if (pos < t->count)
6668 		memmove(l + 1, l,
6669 			(t->count - pos) * sizeof(struct location));
6670 	t->count++;
6671 	l->count = 1;
6672 	l->addr = track->addr;
6673 	l->sum_time = age;
6674 	l->min_time = age;
6675 	l->max_time = age;
6676 	l->min_pid = track->pid;
6677 	l->max_pid = track->pid;
6678 	l->handle = handle;
6679 	l->waste = waste;
6680 	cpumask_clear(to_cpumask(l->cpus));
6681 	cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
6682 	nodes_clear(l->nodes);
6683 	node_set(page_to_nid(virt_to_page(track)), l->nodes);
6684 	return 1;
6685 }
6686 
6687 static void process_slab(struct loc_track *t, struct kmem_cache *s,
6688 		struct slab *slab, enum track_item alloc,
6689 		unsigned long *obj_map)
6690 {
6691 	void *addr = slab_address(slab);
6692 	bool is_alloc = (alloc == TRACK_ALLOC);
6693 	void *p;
6694 
6695 	__fill_map(obj_map, s, slab);
6696 
6697 	for_each_object(p, s, addr, slab->objects)
6698 		if (!test_bit(__obj_to_index(s, addr, p), obj_map))
6699 			add_location(t, s, get_track(s, p, alloc),
6700 				     is_alloc ? get_orig_size(s, p) :
6701 						s->object_size);
6702 }
6703 #endif  /* CONFIG_DEBUG_FS   */
6704 #endif	/* CONFIG_SLUB_DEBUG */
6705 
6706 #ifdef SLAB_SUPPORTS_SYSFS
6707 enum slab_stat_type {
6708 	SL_ALL,			/* All slabs */
6709 	SL_PARTIAL,		/* Only partially allocated slabs */
6710 	SL_CPU,			/* Only slabs used for cpu caches */
6711 	SL_OBJECTS,		/* Determine allocated objects not slabs */
6712 	SL_TOTAL		/* Determine object capacity not slabs */
6713 };
6714 
6715 #define SO_ALL		(1 << SL_ALL)
6716 #define SO_PARTIAL	(1 << SL_PARTIAL)
6717 #define SO_CPU		(1 << SL_CPU)
6718 #define SO_OBJECTS	(1 << SL_OBJECTS)
6719 #define SO_TOTAL	(1 << SL_TOTAL)
6720 
6721 static ssize_t show_slab_objects(struct kmem_cache *s,
6722 				 char *buf, unsigned long flags)
6723 {
6724 	unsigned long total = 0;
6725 	int node;
6726 	int x;
6727 	unsigned long *nodes;
6728 	int len = 0;
6729 
6730 	nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
6731 	if (!nodes)
6732 		return -ENOMEM;
6733 
6734 	if (flags & SO_CPU) {
6735 		int cpu;
6736 
6737 		for_each_possible_cpu(cpu) {
6738 			struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
6739 							       cpu);
6740 			int node;
6741 			struct slab *slab;
6742 
6743 			slab = READ_ONCE(c->slab);
6744 			if (!slab)
6745 				continue;
6746 
6747 			node = slab_nid(slab);
6748 			if (flags & SO_TOTAL)
6749 				x = slab->objects;
6750 			else if (flags & SO_OBJECTS)
6751 				x = slab->inuse;
6752 			else
6753 				x = 1;
6754 
6755 			total += x;
6756 			nodes[node] += x;
6757 
6758 #ifdef CONFIG_SLUB_CPU_PARTIAL
6759 			slab = slub_percpu_partial_read_once(c);
6760 			if (slab) {
6761 				node = slab_nid(slab);
6762 				if (flags & SO_TOTAL)
6763 					WARN_ON_ONCE(1);
6764 				else if (flags & SO_OBJECTS)
6765 					WARN_ON_ONCE(1);
6766 				else
6767 					x = data_race(slab->slabs);
6768 				total += x;
6769 				nodes[node] += x;
6770 			}
6771 #endif
6772 		}
6773 	}
6774 
6775 	/*
6776 	 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
6777 	 * already held which will conflict with an existing lock order:
6778 	 *
6779 	 * mem_hotplug_lock->slab_mutex->kernfs_mutex
6780 	 *
6781 	 * We don't really need mem_hotplug_lock (to hold off
6782 	 * slab_mem_going_offline_callback) here because slab's memory hot
6783 	 * unplug code doesn't destroy the kmem_cache->node[] data.
6784 	 */
6785 
6786 #ifdef CONFIG_SLUB_DEBUG
6787 	if (flags & SO_ALL) {
6788 		struct kmem_cache_node *n;
6789 
6790 		for_each_kmem_cache_node(s, node, n) {
6791 
6792 			if (flags & SO_TOTAL)
6793 				x = node_nr_objs(n);
6794 			else if (flags & SO_OBJECTS)
6795 				x = node_nr_objs(n) - count_partial(n, count_free);
6796 			else
6797 				x = node_nr_slabs(n);
6798 			total += x;
6799 			nodes[node] += x;
6800 		}
6801 
6802 	} else
6803 #endif
6804 	if (flags & SO_PARTIAL) {
6805 		struct kmem_cache_node *n;
6806 
6807 		for_each_kmem_cache_node(s, node, n) {
6808 			if (flags & SO_TOTAL)
6809 				x = count_partial(n, count_total);
6810 			else if (flags & SO_OBJECTS)
6811 				x = count_partial(n, count_inuse);
6812 			else
6813 				x = n->nr_partial;
6814 			total += x;
6815 			nodes[node] += x;
6816 		}
6817 	}
6818 
6819 	len += sysfs_emit_at(buf, len, "%lu", total);
6820 #ifdef CONFIG_NUMA
6821 	for (node = 0; node < nr_node_ids; node++) {
6822 		if (nodes[node])
6823 			len += sysfs_emit_at(buf, len, " N%d=%lu",
6824 					     node, nodes[node]);
6825 	}
6826 #endif
6827 	len += sysfs_emit_at(buf, len, "\n");
6828 	kfree(nodes);
6829 
6830 	return len;
6831 }
6832 
6833 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
6834 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
6835 
6836 struct slab_attribute {
6837 	struct attribute attr;
6838 	ssize_t (*show)(struct kmem_cache *s, char *buf);
6839 	ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
6840 };
6841 
6842 #define SLAB_ATTR_RO(_name) \
6843 	static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
6844 
6845 #define SLAB_ATTR(_name) \
6846 	static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
6847 
6848 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
6849 {
6850 	return sysfs_emit(buf, "%u\n", s->size);
6851 }
6852 SLAB_ATTR_RO(slab_size);
6853 
6854 static ssize_t align_show(struct kmem_cache *s, char *buf)
6855 {
6856 	return sysfs_emit(buf, "%u\n", s->align);
6857 }
6858 SLAB_ATTR_RO(align);
6859 
6860 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
6861 {
6862 	return sysfs_emit(buf, "%u\n", s->object_size);
6863 }
6864 SLAB_ATTR_RO(object_size);
6865 
6866 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
6867 {
6868 	return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
6869 }
6870 SLAB_ATTR_RO(objs_per_slab);
6871 
6872 static ssize_t order_show(struct kmem_cache *s, char *buf)
6873 {
6874 	return sysfs_emit(buf, "%u\n", oo_order(s->oo));
6875 }
6876 SLAB_ATTR_RO(order);
6877 
6878 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
6879 {
6880 	return sysfs_emit(buf, "%lu\n", s->min_partial);
6881 }
6882 
6883 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
6884 				 size_t length)
6885 {
6886 	unsigned long min;
6887 	int err;
6888 
6889 	err = kstrtoul(buf, 10, &min);
6890 	if (err)
6891 		return err;
6892 
6893 	s->min_partial = min;
6894 	return length;
6895 }
6896 SLAB_ATTR(min_partial);
6897 
6898 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
6899 {
6900 	unsigned int nr_partial = 0;
6901 #ifdef CONFIG_SLUB_CPU_PARTIAL
6902 	nr_partial = s->cpu_partial;
6903 #endif
6904 
6905 	return sysfs_emit(buf, "%u\n", nr_partial);
6906 }
6907 
6908 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
6909 				 size_t length)
6910 {
6911 	unsigned int objects;
6912 	int err;
6913 
6914 	err = kstrtouint(buf, 10, &objects);
6915 	if (err)
6916 		return err;
6917 	if (objects && !kmem_cache_has_cpu_partial(s))
6918 		return -EINVAL;
6919 
6920 	slub_set_cpu_partial(s, objects);
6921 	flush_all(s);
6922 	return length;
6923 }
6924 SLAB_ATTR(cpu_partial);
6925 
6926 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
6927 {
6928 	if (!s->ctor)
6929 		return 0;
6930 	return sysfs_emit(buf, "%pS\n", s->ctor);
6931 }
6932 SLAB_ATTR_RO(ctor);
6933 
6934 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
6935 {
6936 	return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
6937 }
6938 SLAB_ATTR_RO(aliases);
6939 
6940 static ssize_t partial_show(struct kmem_cache *s, char *buf)
6941 {
6942 	return show_slab_objects(s, buf, SO_PARTIAL);
6943 }
6944 SLAB_ATTR_RO(partial);
6945 
6946 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
6947 {
6948 	return show_slab_objects(s, buf, SO_CPU);
6949 }
6950 SLAB_ATTR_RO(cpu_slabs);
6951 
6952 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
6953 {
6954 	return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
6955 }
6956 SLAB_ATTR_RO(objects_partial);
6957 
6958 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
6959 {
6960 	int objects = 0;
6961 	int slabs = 0;
6962 	int cpu __maybe_unused;
6963 	int len = 0;
6964 
6965 #ifdef CONFIG_SLUB_CPU_PARTIAL
6966 	for_each_online_cpu(cpu) {
6967 		struct slab *slab;
6968 
6969 		slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
6970 
6971 		if (slab)
6972 			slabs += data_race(slab->slabs);
6973 	}
6974 #endif
6975 
6976 	/* Approximate half-full slabs, see slub_set_cpu_partial() */
6977 	objects = (slabs * oo_objects(s->oo)) / 2;
6978 	len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
6979 
6980 #ifdef CONFIG_SLUB_CPU_PARTIAL
6981 	for_each_online_cpu(cpu) {
6982 		struct slab *slab;
6983 
6984 		slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
6985 		if (slab) {
6986 			slabs = data_race(slab->slabs);
6987 			objects = (slabs * oo_objects(s->oo)) / 2;
6988 			len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
6989 					     cpu, objects, slabs);
6990 		}
6991 	}
6992 #endif
6993 	len += sysfs_emit_at(buf, len, "\n");
6994 
6995 	return len;
6996 }
6997 SLAB_ATTR_RO(slabs_cpu_partial);
6998 
6999 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
7000 {
7001 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
7002 }
7003 SLAB_ATTR_RO(reclaim_account);
7004 
7005 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
7006 {
7007 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
7008 }
7009 SLAB_ATTR_RO(hwcache_align);
7010 
7011 #ifdef CONFIG_ZONE_DMA
7012 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
7013 {
7014 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
7015 }
7016 SLAB_ATTR_RO(cache_dma);
7017 #endif
7018 
7019 #ifdef CONFIG_HARDENED_USERCOPY
7020 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
7021 {
7022 	return sysfs_emit(buf, "%u\n", s->usersize);
7023 }
7024 SLAB_ATTR_RO(usersize);
7025 #endif
7026 
7027 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
7028 {
7029 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
7030 }
7031 SLAB_ATTR_RO(destroy_by_rcu);
7032 
7033 #ifdef CONFIG_SLUB_DEBUG
7034 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
7035 {
7036 	return show_slab_objects(s, buf, SO_ALL);
7037 }
7038 SLAB_ATTR_RO(slabs);
7039 
7040 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
7041 {
7042 	return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
7043 }
7044 SLAB_ATTR_RO(total_objects);
7045 
7046 static ssize_t objects_show(struct kmem_cache *s, char *buf)
7047 {
7048 	return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
7049 }
7050 SLAB_ATTR_RO(objects);
7051 
7052 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
7053 {
7054 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
7055 }
7056 SLAB_ATTR_RO(sanity_checks);
7057 
7058 static ssize_t trace_show(struct kmem_cache *s, char *buf)
7059 {
7060 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
7061 }
7062 SLAB_ATTR_RO(trace);
7063 
7064 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
7065 {
7066 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
7067 }
7068 
7069 SLAB_ATTR_RO(red_zone);
7070 
7071 static ssize_t poison_show(struct kmem_cache *s, char *buf)
7072 {
7073 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
7074 }
7075 
7076 SLAB_ATTR_RO(poison);
7077 
7078 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
7079 {
7080 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
7081 }
7082 
7083 SLAB_ATTR_RO(store_user);
7084 
7085 static ssize_t validate_show(struct kmem_cache *s, char *buf)
7086 {
7087 	return 0;
7088 }
7089 
7090 static ssize_t validate_store(struct kmem_cache *s,
7091 			const char *buf, size_t length)
7092 {
7093 	int ret = -EINVAL;
7094 
7095 	if (buf[0] == '1' && kmem_cache_debug(s)) {
7096 		ret = validate_slab_cache(s);
7097 		if (ret >= 0)
7098 			ret = length;
7099 	}
7100 	return ret;
7101 }
7102 SLAB_ATTR(validate);
7103 
7104 #endif /* CONFIG_SLUB_DEBUG */
7105 
7106 #ifdef CONFIG_FAILSLAB
7107 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
7108 {
7109 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
7110 }
7111 
7112 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
7113 				size_t length)
7114 {
7115 	if (s->refcount > 1)
7116 		return -EINVAL;
7117 
7118 	if (buf[0] == '1')
7119 		WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
7120 	else
7121 		WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
7122 
7123 	return length;
7124 }
7125 SLAB_ATTR(failslab);
7126 #endif
7127 
7128 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
7129 {
7130 	return 0;
7131 }
7132 
7133 static ssize_t shrink_store(struct kmem_cache *s,
7134 			const char *buf, size_t length)
7135 {
7136 	if (buf[0] == '1')
7137 		kmem_cache_shrink(s);
7138 	else
7139 		return -EINVAL;
7140 	return length;
7141 }
7142 SLAB_ATTR(shrink);
7143 
7144 #ifdef CONFIG_NUMA
7145 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
7146 {
7147 	return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
7148 }
7149 
7150 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
7151 				const char *buf, size_t length)
7152 {
7153 	unsigned int ratio;
7154 	int err;
7155 
7156 	err = kstrtouint(buf, 10, &ratio);
7157 	if (err)
7158 		return err;
7159 	if (ratio > 100)
7160 		return -ERANGE;
7161 
7162 	s->remote_node_defrag_ratio = ratio * 10;
7163 
7164 	return length;
7165 }
7166 SLAB_ATTR(remote_node_defrag_ratio);
7167 #endif
7168 
7169 #ifdef CONFIG_SLUB_STATS
7170 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
7171 {
7172 	unsigned long sum  = 0;
7173 	int cpu;
7174 	int len = 0;
7175 	int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
7176 
7177 	if (!data)
7178 		return -ENOMEM;
7179 
7180 	for_each_online_cpu(cpu) {
7181 		unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
7182 
7183 		data[cpu] = x;
7184 		sum += x;
7185 	}
7186 
7187 	len += sysfs_emit_at(buf, len, "%lu", sum);
7188 
7189 #ifdef CONFIG_SMP
7190 	for_each_online_cpu(cpu) {
7191 		if (data[cpu])
7192 			len += sysfs_emit_at(buf, len, " C%d=%u",
7193 					     cpu, data[cpu]);
7194 	}
7195 #endif
7196 	kfree(data);
7197 	len += sysfs_emit_at(buf, len, "\n");
7198 
7199 	return len;
7200 }
7201 
7202 static void clear_stat(struct kmem_cache *s, enum stat_item si)
7203 {
7204 	int cpu;
7205 
7206 	for_each_online_cpu(cpu)
7207 		per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
7208 }
7209 
7210 #define STAT_ATTR(si, text) 					\
7211 static ssize_t text##_show(struct kmem_cache *s, char *buf)	\
7212 {								\
7213 	return show_stat(s, buf, si);				\
7214 }								\
7215 static ssize_t text##_store(struct kmem_cache *s,		\
7216 				const char *buf, size_t length)	\
7217 {								\
7218 	if (buf[0] != '0')					\
7219 		return -EINVAL;					\
7220 	clear_stat(s, si);					\
7221 	return length;						\
7222 }								\
7223 SLAB_ATTR(text);						\
7224 
7225 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
7226 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
7227 STAT_ATTR(FREE_FASTPATH, free_fastpath);
7228 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
7229 STAT_ATTR(FREE_FROZEN, free_frozen);
7230 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
7231 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
7232 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
7233 STAT_ATTR(ALLOC_SLAB, alloc_slab);
7234 STAT_ATTR(ALLOC_REFILL, alloc_refill);
7235 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
7236 STAT_ATTR(FREE_SLAB, free_slab);
7237 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
7238 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
7239 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
7240 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
7241 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
7242 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
7243 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
7244 STAT_ATTR(ORDER_FALLBACK, order_fallback);
7245 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
7246 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
7247 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
7248 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
7249 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
7250 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
7251 #endif	/* CONFIG_SLUB_STATS */
7252 
7253 #ifdef CONFIG_KFENCE
7254 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
7255 {
7256 	return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
7257 }
7258 
7259 static ssize_t skip_kfence_store(struct kmem_cache *s,
7260 			const char *buf, size_t length)
7261 {
7262 	int ret = length;
7263 
7264 	if (buf[0] == '0')
7265 		s->flags &= ~SLAB_SKIP_KFENCE;
7266 	else if (buf[0] == '1')
7267 		s->flags |= SLAB_SKIP_KFENCE;
7268 	else
7269 		ret = -EINVAL;
7270 
7271 	return ret;
7272 }
7273 SLAB_ATTR(skip_kfence);
7274 #endif
7275 
7276 static struct attribute *slab_attrs[] = {
7277 	&slab_size_attr.attr,
7278 	&object_size_attr.attr,
7279 	&objs_per_slab_attr.attr,
7280 	&order_attr.attr,
7281 	&min_partial_attr.attr,
7282 	&cpu_partial_attr.attr,
7283 	&objects_partial_attr.attr,
7284 	&partial_attr.attr,
7285 	&cpu_slabs_attr.attr,
7286 	&ctor_attr.attr,
7287 	&aliases_attr.attr,
7288 	&align_attr.attr,
7289 	&hwcache_align_attr.attr,
7290 	&reclaim_account_attr.attr,
7291 	&destroy_by_rcu_attr.attr,
7292 	&shrink_attr.attr,
7293 	&slabs_cpu_partial_attr.attr,
7294 #ifdef CONFIG_SLUB_DEBUG
7295 	&total_objects_attr.attr,
7296 	&objects_attr.attr,
7297 	&slabs_attr.attr,
7298 	&sanity_checks_attr.attr,
7299 	&trace_attr.attr,
7300 	&red_zone_attr.attr,
7301 	&poison_attr.attr,
7302 	&store_user_attr.attr,
7303 	&validate_attr.attr,
7304 #endif
7305 #ifdef CONFIG_ZONE_DMA
7306 	&cache_dma_attr.attr,
7307 #endif
7308 #ifdef CONFIG_NUMA
7309 	&remote_node_defrag_ratio_attr.attr,
7310 #endif
7311 #ifdef CONFIG_SLUB_STATS
7312 	&alloc_fastpath_attr.attr,
7313 	&alloc_slowpath_attr.attr,
7314 	&free_fastpath_attr.attr,
7315 	&free_slowpath_attr.attr,
7316 	&free_frozen_attr.attr,
7317 	&free_add_partial_attr.attr,
7318 	&free_remove_partial_attr.attr,
7319 	&alloc_from_partial_attr.attr,
7320 	&alloc_slab_attr.attr,
7321 	&alloc_refill_attr.attr,
7322 	&alloc_node_mismatch_attr.attr,
7323 	&free_slab_attr.attr,
7324 	&cpuslab_flush_attr.attr,
7325 	&deactivate_full_attr.attr,
7326 	&deactivate_empty_attr.attr,
7327 	&deactivate_to_head_attr.attr,
7328 	&deactivate_to_tail_attr.attr,
7329 	&deactivate_remote_frees_attr.attr,
7330 	&deactivate_bypass_attr.attr,
7331 	&order_fallback_attr.attr,
7332 	&cmpxchg_double_fail_attr.attr,
7333 	&cmpxchg_double_cpu_fail_attr.attr,
7334 	&cpu_partial_alloc_attr.attr,
7335 	&cpu_partial_free_attr.attr,
7336 	&cpu_partial_node_attr.attr,
7337 	&cpu_partial_drain_attr.attr,
7338 #endif
7339 #ifdef CONFIG_FAILSLAB
7340 	&failslab_attr.attr,
7341 #endif
7342 #ifdef CONFIG_HARDENED_USERCOPY
7343 	&usersize_attr.attr,
7344 #endif
7345 #ifdef CONFIG_KFENCE
7346 	&skip_kfence_attr.attr,
7347 #endif
7348 
7349 	NULL
7350 };
7351 
7352 static const struct attribute_group slab_attr_group = {
7353 	.attrs = slab_attrs,
7354 };
7355 
7356 static ssize_t slab_attr_show(struct kobject *kobj,
7357 				struct attribute *attr,
7358 				char *buf)
7359 {
7360 	struct slab_attribute *attribute;
7361 	struct kmem_cache *s;
7362 
7363 	attribute = to_slab_attr(attr);
7364 	s = to_slab(kobj);
7365 
7366 	if (!attribute->show)
7367 		return -EIO;
7368 
7369 	return attribute->show(s, buf);
7370 }
7371 
7372 static ssize_t slab_attr_store(struct kobject *kobj,
7373 				struct attribute *attr,
7374 				const char *buf, size_t len)
7375 {
7376 	struct slab_attribute *attribute;
7377 	struct kmem_cache *s;
7378 
7379 	attribute = to_slab_attr(attr);
7380 	s = to_slab(kobj);
7381 
7382 	if (!attribute->store)
7383 		return -EIO;
7384 
7385 	return attribute->store(s, buf, len);
7386 }
7387 
7388 static void kmem_cache_release(struct kobject *k)
7389 {
7390 	slab_kmem_cache_release(to_slab(k));
7391 }
7392 
7393 static const struct sysfs_ops slab_sysfs_ops = {
7394 	.show = slab_attr_show,
7395 	.store = slab_attr_store,
7396 };
7397 
7398 static const struct kobj_type slab_ktype = {
7399 	.sysfs_ops = &slab_sysfs_ops,
7400 	.release = kmem_cache_release,
7401 };
7402 
7403 static struct kset *slab_kset;
7404 
7405 static inline struct kset *cache_kset(struct kmem_cache *s)
7406 {
7407 	return slab_kset;
7408 }
7409 
7410 #define ID_STR_LENGTH 32
7411 
7412 /* Create a unique string id for a slab cache:
7413  *
7414  * Format	:[flags-]size
7415  */
7416 static char *create_unique_id(struct kmem_cache *s)
7417 {
7418 	char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
7419 	char *p = name;
7420 
7421 	if (!name)
7422 		return ERR_PTR(-ENOMEM);
7423 
7424 	*p++ = ':';
7425 	/*
7426 	 * First flags affecting slabcache operations. We will only
7427 	 * get here for aliasable slabs so we do not need to support
7428 	 * too many flags. The flags here must cover all flags that
7429 	 * are matched during merging to guarantee that the id is
7430 	 * unique.
7431 	 */
7432 	if (s->flags & SLAB_CACHE_DMA)
7433 		*p++ = 'd';
7434 	if (s->flags & SLAB_CACHE_DMA32)
7435 		*p++ = 'D';
7436 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
7437 		*p++ = 'a';
7438 	if (s->flags & SLAB_CONSISTENCY_CHECKS)
7439 		*p++ = 'F';
7440 	if (s->flags & SLAB_ACCOUNT)
7441 		*p++ = 'A';
7442 	if (p != name + 1)
7443 		*p++ = '-';
7444 	p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
7445 
7446 	if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
7447 		kfree(name);
7448 		return ERR_PTR(-EINVAL);
7449 	}
7450 	kmsan_unpoison_memory(name, p - name);
7451 	return name;
7452 }
7453 
7454 static int sysfs_slab_add(struct kmem_cache *s)
7455 {
7456 	int err;
7457 	const char *name;
7458 	struct kset *kset = cache_kset(s);
7459 	int unmergeable = slab_unmergeable(s);
7460 
7461 	if (!unmergeable && disable_higher_order_debug &&
7462 			(slub_debug & DEBUG_METADATA_FLAGS))
7463 		unmergeable = 1;
7464 
7465 	if (unmergeable) {
7466 		/*
7467 		 * Slabcache can never be merged so we can use the name proper.
7468 		 * This is typically the case for debug situations. In that
7469 		 * case we can catch duplicate names easily.
7470 		 */
7471 		sysfs_remove_link(&slab_kset->kobj, s->name);
7472 		name = s->name;
7473 	} else {
7474 		/*
7475 		 * Create a unique name for the slab as a target
7476 		 * for the symlinks.
7477 		 */
7478 		name = create_unique_id(s);
7479 		if (IS_ERR(name))
7480 			return PTR_ERR(name);
7481 	}
7482 
7483 	s->kobj.kset = kset;
7484 	err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
7485 	if (err)
7486 		goto out;
7487 
7488 	err = sysfs_create_group(&s->kobj, &slab_attr_group);
7489 	if (err)
7490 		goto out_del_kobj;
7491 
7492 	if (!unmergeable) {
7493 		/* Setup first alias */
7494 		sysfs_slab_alias(s, s->name);
7495 	}
7496 out:
7497 	if (!unmergeable)
7498 		kfree(name);
7499 	return err;
7500 out_del_kobj:
7501 	kobject_del(&s->kobj);
7502 	goto out;
7503 }
7504 
7505 void sysfs_slab_unlink(struct kmem_cache *s)
7506 {
7507 	if (s->kobj.state_in_sysfs)
7508 		kobject_del(&s->kobj);
7509 }
7510 
7511 void sysfs_slab_release(struct kmem_cache *s)
7512 {
7513 	kobject_put(&s->kobj);
7514 }
7515 
7516 /*
7517  * Need to buffer aliases during bootup until sysfs becomes
7518  * available lest we lose that information.
7519  */
7520 struct saved_alias {
7521 	struct kmem_cache *s;
7522 	const char *name;
7523 	struct saved_alias *next;
7524 };
7525 
7526 static struct saved_alias *alias_list;
7527 
7528 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
7529 {
7530 	struct saved_alias *al;
7531 
7532 	if (slab_state == FULL) {
7533 		/*
7534 		 * If we have a leftover link then remove it.
7535 		 */
7536 		sysfs_remove_link(&slab_kset->kobj, name);
7537 		/*
7538 		 * The original cache may have failed to generate sysfs file.
7539 		 * In that case, sysfs_create_link() returns -ENOENT and
7540 		 * symbolic link creation is skipped.
7541 		 */
7542 		return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
7543 	}
7544 
7545 	al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
7546 	if (!al)
7547 		return -ENOMEM;
7548 
7549 	al->s = s;
7550 	al->name = name;
7551 	al->next = alias_list;
7552 	alias_list = al;
7553 	kmsan_unpoison_memory(al, sizeof(*al));
7554 	return 0;
7555 }
7556 
7557 static int __init slab_sysfs_init(void)
7558 {
7559 	struct kmem_cache *s;
7560 	int err;
7561 
7562 	mutex_lock(&slab_mutex);
7563 
7564 	slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
7565 	if (!slab_kset) {
7566 		mutex_unlock(&slab_mutex);
7567 		pr_err("Cannot register slab subsystem.\n");
7568 		return -ENOMEM;
7569 	}
7570 
7571 	slab_state = FULL;
7572 
7573 	list_for_each_entry(s, &slab_caches, list) {
7574 		err = sysfs_slab_add(s);
7575 		if (err)
7576 			pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
7577 			       s->name);
7578 	}
7579 
7580 	while (alias_list) {
7581 		struct saved_alias *al = alias_list;
7582 
7583 		alias_list = alias_list->next;
7584 		err = sysfs_slab_alias(al->s, al->name);
7585 		if (err)
7586 			pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
7587 			       al->name);
7588 		kfree(al);
7589 	}
7590 
7591 	mutex_unlock(&slab_mutex);
7592 	return 0;
7593 }
7594 late_initcall(slab_sysfs_init);
7595 #endif /* SLAB_SUPPORTS_SYSFS */
7596 
7597 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
7598 static int slab_debugfs_show(struct seq_file *seq, void *v)
7599 {
7600 	struct loc_track *t = seq->private;
7601 	struct location *l;
7602 	unsigned long idx;
7603 
7604 	idx = (unsigned long) t->idx;
7605 	if (idx < t->count) {
7606 		l = &t->loc[idx];
7607 
7608 		seq_printf(seq, "%7ld ", l->count);
7609 
7610 		if (l->addr)
7611 			seq_printf(seq, "%pS", (void *)l->addr);
7612 		else
7613 			seq_puts(seq, "<not-available>");
7614 
7615 		if (l->waste)
7616 			seq_printf(seq, " waste=%lu/%lu",
7617 				l->count * l->waste, l->waste);
7618 
7619 		if (l->sum_time != l->min_time) {
7620 			seq_printf(seq, " age=%ld/%llu/%ld",
7621 				l->min_time, div_u64(l->sum_time, l->count),
7622 				l->max_time);
7623 		} else
7624 			seq_printf(seq, " age=%ld", l->min_time);
7625 
7626 		if (l->min_pid != l->max_pid)
7627 			seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
7628 		else
7629 			seq_printf(seq, " pid=%ld",
7630 				l->min_pid);
7631 
7632 		if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
7633 			seq_printf(seq, " cpus=%*pbl",
7634 				 cpumask_pr_args(to_cpumask(l->cpus)));
7635 
7636 		if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
7637 			seq_printf(seq, " nodes=%*pbl",
7638 				 nodemask_pr_args(&l->nodes));
7639 
7640 #ifdef CONFIG_STACKDEPOT
7641 		{
7642 			depot_stack_handle_t handle;
7643 			unsigned long *entries;
7644 			unsigned int nr_entries, j;
7645 
7646 			handle = READ_ONCE(l->handle);
7647 			if (handle) {
7648 				nr_entries = stack_depot_fetch(handle, &entries);
7649 				seq_puts(seq, "\n");
7650 				for (j = 0; j < nr_entries; j++)
7651 					seq_printf(seq, "        %pS\n", (void *)entries[j]);
7652 			}
7653 		}
7654 #endif
7655 		seq_puts(seq, "\n");
7656 	}
7657 
7658 	if (!idx && !t->count)
7659 		seq_puts(seq, "No data\n");
7660 
7661 	return 0;
7662 }
7663 
7664 static void slab_debugfs_stop(struct seq_file *seq, void *v)
7665 {
7666 }
7667 
7668 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
7669 {
7670 	struct loc_track *t = seq->private;
7671 
7672 	t->idx = ++(*ppos);
7673 	if (*ppos <= t->count)
7674 		return ppos;
7675 
7676 	return NULL;
7677 }
7678 
7679 static int cmp_loc_by_count(const void *a, const void *b, const void *data)
7680 {
7681 	struct location *loc1 = (struct location *)a;
7682 	struct location *loc2 = (struct location *)b;
7683 
7684 	if (loc1->count > loc2->count)
7685 		return -1;
7686 	else
7687 		return 1;
7688 }
7689 
7690 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
7691 {
7692 	struct loc_track *t = seq->private;
7693 
7694 	t->idx = *ppos;
7695 	return ppos;
7696 }
7697 
7698 static const struct seq_operations slab_debugfs_sops = {
7699 	.start  = slab_debugfs_start,
7700 	.next   = slab_debugfs_next,
7701 	.stop   = slab_debugfs_stop,
7702 	.show   = slab_debugfs_show,
7703 };
7704 
7705 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
7706 {
7707 
7708 	struct kmem_cache_node *n;
7709 	enum track_item alloc;
7710 	int node;
7711 	struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
7712 						sizeof(struct loc_track));
7713 	struct kmem_cache *s = file_inode(filep)->i_private;
7714 	unsigned long *obj_map;
7715 
7716 	if (!t)
7717 		return -ENOMEM;
7718 
7719 	obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
7720 	if (!obj_map) {
7721 		seq_release_private(inode, filep);
7722 		return -ENOMEM;
7723 	}
7724 
7725 	alloc = debugfs_get_aux_num(filep);
7726 
7727 	if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
7728 		bitmap_free(obj_map);
7729 		seq_release_private(inode, filep);
7730 		return -ENOMEM;
7731 	}
7732 
7733 	for_each_kmem_cache_node(s, node, n) {
7734 		unsigned long flags;
7735 		struct slab *slab;
7736 
7737 		if (!node_nr_slabs(n))
7738 			continue;
7739 
7740 		spin_lock_irqsave(&n->list_lock, flags);
7741 		list_for_each_entry(slab, &n->partial, slab_list)
7742 			process_slab(t, s, slab, alloc, obj_map);
7743 		list_for_each_entry(slab, &n->full, slab_list)
7744 			process_slab(t, s, slab, alloc, obj_map);
7745 		spin_unlock_irqrestore(&n->list_lock, flags);
7746 	}
7747 
7748 	/* Sort locations by count */
7749 	sort_r(t->loc, t->count, sizeof(struct location),
7750 		cmp_loc_by_count, NULL, NULL);
7751 
7752 	bitmap_free(obj_map);
7753 	return 0;
7754 }
7755 
7756 static int slab_debug_trace_release(struct inode *inode, struct file *file)
7757 {
7758 	struct seq_file *seq = file->private_data;
7759 	struct loc_track *t = seq->private;
7760 
7761 	free_loc_track(t);
7762 	return seq_release_private(inode, file);
7763 }
7764 
7765 static const struct file_operations slab_debugfs_fops = {
7766 	.open    = slab_debug_trace_open,
7767 	.read    = seq_read,
7768 	.llseek  = seq_lseek,
7769 	.release = slab_debug_trace_release,
7770 };
7771 
7772 static void debugfs_slab_add(struct kmem_cache *s)
7773 {
7774 	struct dentry *slab_cache_dir;
7775 
7776 	if (unlikely(!slab_debugfs_root))
7777 		return;
7778 
7779 	slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
7780 
7781 	debugfs_create_file_aux_num("alloc_traces", 0400, slab_cache_dir, s,
7782 					TRACK_ALLOC, &slab_debugfs_fops);
7783 
7784 	debugfs_create_file_aux_num("free_traces", 0400, slab_cache_dir, s,
7785 					TRACK_FREE, &slab_debugfs_fops);
7786 }
7787 
7788 void debugfs_slab_release(struct kmem_cache *s)
7789 {
7790 	debugfs_lookup_and_remove(s->name, slab_debugfs_root);
7791 }
7792 
7793 static int __init slab_debugfs_init(void)
7794 {
7795 	struct kmem_cache *s;
7796 
7797 	slab_debugfs_root = debugfs_create_dir("slab", NULL);
7798 
7799 	list_for_each_entry(s, &slab_caches, list)
7800 		if (s->flags & SLAB_STORE_USER)
7801 			debugfs_slab_add(s);
7802 
7803 	return 0;
7804 
7805 }
7806 __initcall(slab_debugfs_init);
7807 #endif
7808 /*
7809  * The /proc/slabinfo ABI
7810  */
7811 #ifdef CONFIG_SLUB_DEBUG
7812 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
7813 {
7814 	unsigned long nr_slabs = 0;
7815 	unsigned long nr_objs = 0;
7816 	unsigned long nr_free = 0;
7817 	int node;
7818 	struct kmem_cache_node *n;
7819 
7820 	for_each_kmem_cache_node(s, node, n) {
7821 		nr_slabs += node_nr_slabs(n);
7822 		nr_objs += node_nr_objs(n);
7823 		nr_free += count_partial_free_approx(n);
7824 	}
7825 
7826 	sinfo->active_objs = nr_objs - nr_free;
7827 	sinfo->num_objs = nr_objs;
7828 	sinfo->active_slabs = nr_slabs;
7829 	sinfo->num_slabs = nr_slabs;
7830 	sinfo->objects_per_slab = oo_objects(s->oo);
7831 	sinfo->cache_order = oo_order(s->oo);
7832 }
7833 #endif /* CONFIG_SLUB_DEBUG */
7834