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