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