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