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