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