xref: /linux/mm/slab_common.c (revision aaa44952bbd1d4db14a4d676bf9595bb5db7e7b0)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Slab allocator functions that are independent of the allocator strategy
4  *
5  * (C) 2012 Christoph Lameter <cl@linux.com>
6  */
7 #include <linux/slab.h>
8 
9 #include <linux/mm.h>
10 #include <linux/poison.h>
11 #include <linux/interrupt.h>
12 #include <linux/memory.h>
13 #include <linux/cache.h>
14 #include <linux/compiler.h>
15 #include <linux/kfence.h>
16 #include <linux/module.h>
17 #include <linux/cpu.h>
18 #include <linux/uaccess.h>
19 #include <linux/seq_file.h>
20 #include <linux/proc_fs.h>
21 #include <linux/debugfs.h>
22 #include <linux/kasan.h>
23 #include <asm/cacheflush.h>
24 #include <asm/tlbflush.h>
25 #include <asm/page.h>
26 #include <linux/memcontrol.h>
27 
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/kmem.h>
30 
31 #include "internal.h"
32 
33 #include "slab.h"
34 
35 enum slab_state slab_state;
36 LIST_HEAD(slab_caches);
37 DEFINE_MUTEX(slab_mutex);
38 struct kmem_cache *kmem_cache;
39 
40 #ifdef CONFIG_HARDENED_USERCOPY
41 bool usercopy_fallback __ro_after_init =
42 		IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
43 module_param(usercopy_fallback, bool, 0400);
44 MODULE_PARM_DESC(usercopy_fallback,
45 		"WARN instead of reject usercopy whitelist violations");
46 #endif
47 
48 static LIST_HEAD(slab_caches_to_rcu_destroy);
49 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
50 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
51 		    slab_caches_to_rcu_destroy_workfn);
52 
53 /*
54  * Set of flags that will prevent slab merging
55  */
56 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
57 		SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
58 		SLAB_FAILSLAB | kasan_never_merge())
59 
60 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
61 			 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
62 
63 /*
64  * Merge control. If this is set then no merging of slab caches will occur.
65  */
66 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
67 
68 static int __init setup_slab_nomerge(char *str)
69 {
70 	slab_nomerge = true;
71 	return 1;
72 }
73 
74 static int __init setup_slab_merge(char *str)
75 {
76 	slab_nomerge = false;
77 	return 1;
78 }
79 
80 #ifdef CONFIG_SLUB
81 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
82 __setup_param("slub_merge", slub_merge, setup_slab_merge, 0);
83 #endif
84 
85 __setup("slab_nomerge", setup_slab_nomerge);
86 __setup("slab_merge", setup_slab_merge);
87 
88 /*
89  * Determine the size of a slab object
90  */
91 unsigned int kmem_cache_size(struct kmem_cache *s)
92 {
93 	return s->object_size;
94 }
95 EXPORT_SYMBOL(kmem_cache_size);
96 
97 #ifdef CONFIG_DEBUG_VM
98 static int kmem_cache_sanity_check(const char *name, unsigned int size)
99 {
100 	if (!name || in_interrupt() || size < sizeof(void *) ||
101 		size > KMALLOC_MAX_SIZE) {
102 		pr_err("kmem_cache_create(%s) integrity check failed\n", name);
103 		return -EINVAL;
104 	}
105 
106 	WARN_ON(strchr(name, ' '));	/* It confuses parsers */
107 	return 0;
108 }
109 #else
110 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
111 {
112 	return 0;
113 }
114 #endif
115 
116 void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
117 {
118 	size_t i;
119 
120 	for (i = 0; i < nr; i++) {
121 		if (s)
122 			kmem_cache_free(s, p[i]);
123 		else
124 			kfree(p[i]);
125 	}
126 }
127 
128 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
129 								void **p)
130 {
131 	size_t i;
132 
133 	for (i = 0; i < nr; i++) {
134 		void *x = p[i] = kmem_cache_alloc(s, flags);
135 		if (!x) {
136 			__kmem_cache_free_bulk(s, i, p);
137 			return 0;
138 		}
139 	}
140 	return i;
141 }
142 
143 /*
144  * Figure out what the alignment of the objects will be given a set of
145  * flags, a user specified alignment and the size of the objects.
146  */
147 static unsigned int calculate_alignment(slab_flags_t flags,
148 		unsigned int align, unsigned int size)
149 {
150 	/*
151 	 * If the user wants hardware cache aligned objects then follow that
152 	 * suggestion if the object is sufficiently large.
153 	 *
154 	 * The hardware cache alignment cannot override the specified
155 	 * alignment though. If that is greater then use it.
156 	 */
157 	if (flags & SLAB_HWCACHE_ALIGN) {
158 		unsigned int ralign;
159 
160 		ralign = cache_line_size();
161 		while (size <= ralign / 2)
162 			ralign /= 2;
163 		align = max(align, ralign);
164 	}
165 
166 	if (align < ARCH_SLAB_MINALIGN)
167 		align = ARCH_SLAB_MINALIGN;
168 
169 	return ALIGN(align, sizeof(void *));
170 }
171 
172 /*
173  * Find a mergeable slab cache
174  */
175 int slab_unmergeable(struct kmem_cache *s)
176 {
177 	if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
178 		return 1;
179 
180 	if (s->ctor)
181 		return 1;
182 
183 	if (s->usersize)
184 		return 1;
185 
186 	/*
187 	 * We may have set a slab to be unmergeable during bootstrap.
188 	 */
189 	if (s->refcount < 0)
190 		return 1;
191 
192 	return 0;
193 }
194 
195 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
196 		slab_flags_t flags, const char *name, void (*ctor)(void *))
197 {
198 	struct kmem_cache *s;
199 
200 	if (slab_nomerge)
201 		return NULL;
202 
203 	if (ctor)
204 		return NULL;
205 
206 	size = ALIGN(size, sizeof(void *));
207 	align = calculate_alignment(flags, align, size);
208 	size = ALIGN(size, align);
209 	flags = kmem_cache_flags(size, flags, name);
210 
211 	if (flags & SLAB_NEVER_MERGE)
212 		return NULL;
213 
214 	list_for_each_entry_reverse(s, &slab_caches, list) {
215 		if (slab_unmergeable(s))
216 			continue;
217 
218 		if (size > s->size)
219 			continue;
220 
221 		if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
222 			continue;
223 		/*
224 		 * Check if alignment is compatible.
225 		 * Courtesy of Adrian Drzewiecki
226 		 */
227 		if ((s->size & ~(align - 1)) != s->size)
228 			continue;
229 
230 		if (s->size - size >= sizeof(void *))
231 			continue;
232 
233 		if (IS_ENABLED(CONFIG_SLAB) && align &&
234 			(align > s->align || s->align % align))
235 			continue;
236 
237 		return s;
238 	}
239 	return NULL;
240 }
241 
242 static struct kmem_cache *create_cache(const char *name,
243 		unsigned int object_size, unsigned int align,
244 		slab_flags_t flags, unsigned int useroffset,
245 		unsigned int usersize, void (*ctor)(void *),
246 		struct kmem_cache *root_cache)
247 {
248 	struct kmem_cache *s;
249 	int err;
250 
251 	if (WARN_ON(useroffset + usersize > object_size))
252 		useroffset = usersize = 0;
253 
254 	err = -ENOMEM;
255 	s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
256 	if (!s)
257 		goto out;
258 
259 	s->name = name;
260 	s->size = s->object_size = object_size;
261 	s->align = align;
262 	s->ctor = ctor;
263 	s->useroffset = useroffset;
264 	s->usersize = usersize;
265 
266 	err = __kmem_cache_create(s, flags);
267 	if (err)
268 		goto out_free_cache;
269 
270 	s->refcount = 1;
271 	list_add(&s->list, &slab_caches);
272 out:
273 	if (err)
274 		return ERR_PTR(err);
275 	return s;
276 
277 out_free_cache:
278 	kmem_cache_free(kmem_cache, s);
279 	goto out;
280 }
281 
282 /**
283  * kmem_cache_create_usercopy - Create a cache with a region suitable
284  * for copying to userspace
285  * @name: A string which is used in /proc/slabinfo to identify this cache.
286  * @size: The size of objects to be created in this cache.
287  * @align: The required alignment for the objects.
288  * @flags: SLAB flags
289  * @useroffset: Usercopy region offset
290  * @usersize: Usercopy region size
291  * @ctor: A constructor for the objects.
292  *
293  * Cannot be called within a interrupt, but can be interrupted.
294  * The @ctor is run when new pages are allocated by the cache.
295  *
296  * The flags are
297  *
298  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
299  * to catch references to uninitialised memory.
300  *
301  * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
302  * for buffer overruns.
303  *
304  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
305  * cacheline.  This can be beneficial if you're counting cycles as closely
306  * as davem.
307  *
308  * Return: a pointer to the cache on success, NULL on failure.
309  */
310 struct kmem_cache *
311 kmem_cache_create_usercopy(const char *name,
312 		  unsigned int size, unsigned int align,
313 		  slab_flags_t flags,
314 		  unsigned int useroffset, unsigned int usersize,
315 		  void (*ctor)(void *))
316 {
317 	struct kmem_cache *s = NULL;
318 	const char *cache_name;
319 	int err;
320 
321 	mutex_lock(&slab_mutex);
322 
323 	err = kmem_cache_sanity_check(name, size);
324 	if (err) {
325 		goto out_unlock;
326 	}
327 
328 	/* Refuse requests with allocator specific flags */
329 	if (flags & ~SLAB_FLAGS_PERMITTED) {
330 		err = -EINVAL;
331 		goto out_unlock;
332 	}
333 
334 	/*
335 	 * Some allocators will constraint the set of valid flags to a subset
336 	 * of all flags. We expect them to define CACHE_CREATE_MASK in this
337 	 * case, and we'll just provide them with a sanitized version of the
338 	 * passed flags.
339 	 */
340 	flags &= CACHE_CREATE_MASK;
341 
342 	/* Fail closed on bad usersize of useroffset values. */
343 	if (WARN_ON(!usersize && useroffset) ||
344 	    WARN_ON(size < usersize || size - usersize < useroffset))
345 		usersize = useroffset = 0;
346 
347 	if (!usersize)
348 		s = __kmem_cache_alias(name, size, align, flags, ctor);
349 	if (s)
350 		goto out_unlock;
351 
352 	cache_name = kstrdup_const(name, GFP_KERNEL);
353 	if (!cache_name) {
354 		err = -ENOMEM;
355 		goto out_unlock;
356 	}
357 
358 	s = create_cache(cache_name, size,
359 			 calculate_alignment(flags, align, size),
360 			 flags, useroffset, usersize, ctor, NULL);
361 	if (IS_ERR(s)) {
362 		err = PTR_ERR(s);
363 		kfree_const(cache_name);
364 	}
365 
366 out_unlock:
367 	mutex_unlock(&slab_mutex);
368 
369 	if (err) {
370 		if (flags & SLAB_PANIC)
371 			panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
372 				name, err);
373 		else {
374 			pr_warn("kmem_cache_create(%s) failed with error %d\n",
375 				name, err);
376 			dump_stack();
377 		}
378 		return NULL;
379 	}
380 	return s;
381 }
382 EXPORT_SYMBOL(kmem_cache_create_usercopy);
383 
384 /**
385  * kmem_cache_create - Create a cache.
386  * @name: A string which is used in /proc/slabinfo to identify this cache.
387  * @size: The size of objects to be created in this cache.
388  * @align: The required alignment for the objects.
389  * @flags: SLAB flags
390  * @ctor: A constructor for the objects.
391  *
392  * Cannot be called within a interrupt, but can be interrupted.
393  * The @ctor is run when new pages are allocated by the cache.
394  *
395  * The flags are
396  *
397  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
398  * to catch references to uninitialised memory.
399  *
400  * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
401  * for buffer overruns.
402  *
403  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
404  * cacheline.  This can be beneficial if you're counting cycles as closely
405  * as davem.
406  *
407  * Return: a pointer to the cache on success, NULL on failure.
408  */
409 struct kmem_cache *
410 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
411 		slab_flags_t flags, void (*ctor)(void *))
412 {
413 	return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
414 					  ctor);
415 }
416 EXPORT_SYMBOL(kmem_cache_create);
417 
418 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
419 {
420 	LIST_HEAD(to_destroy);
421 	struct kmem_cache *s, *s2;
422 
423 	/*
424 	 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
425 	 * @slab_caches_to_rcu_destroy list.  The slab pages are freed
426 	 * through RCU and the associated kmem_cache are dereferenced
427 	 * while freeing the pages, so the kmem_caches should be freed only
428 	 * after the pending RCU operations are finished.  As rcu_barrier()
429 	 * is a pretty slow operation, we batch all pending destructions
430 	 * asynchronously.
431 	 */
432 	mutex_lock(&slab_mutex);
433 	list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
434 	mutex_unlock(&slab_mutex);
435 
436 	if (list_empty(&to_destroy))
437 		return;
438 
439 	rcu_barrier();
440 
441 	list_for_each_entry_safe(s, s2, &to_destroy, list) {
442 		kfence_shutdown_cache(s);
443 #ifdef SLAB_SUPPORTS_SYSFS
444 		sysfs_slab_release(s);
445 #else
446 		slab_kmem_cache_release(s);
447 #endif
448 	}
449 }
450 
451 static int shutdown_cache(struct kmem_cache *s)
452 {
453 	/* free asan quarantined objects */
454 	kasan_cache_shutdown(s);
455 
456 	if (__kmem_cache_shutdown(s) != 0)
457 		return -EBUSY;
458 
459 	list_del(&s->list);
460 
461 	if (s->flags & SLAB_TYPESAFE_BY_RCU) {
462 #ifdef SLAB_SUPPORTS_SYSFS
463 		sysfs_slab_unlink(s);
464 #endif
465 		list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
466 		schedule_work(&slab_caches_to_rcu_destroy_work);
467 	} else {
468 		kfence_shutdown_cache(s);
469 #ifdef SLAB_SUPPORTS_SYSFS
470 		sysfs_slab_unlink(s);
471 		sysfs_slab_release(s);
472 #else
473 		slab_kmem_cache_release(s);
474 #endif
475 	}
476 
477 	return 0;
478 }
479 
480 void slab_kmem_cache_release(struct kmem_cache *s)
481 {
482 	__kmem_cache_release(s);
483 	kfree_const(s->name);
484 	kmem_cache_free(kmem_cache, s);
485 }
486 
487 void kmem_cache_destroy(struct kmem_cache *s)
488 {
489 	int err;
490 
491 	if (unlikely(!s))
492 		return;
493 
494 	mutex_lock(&slab_mutex);
495 
496 	s->refcount--;
497 	if (s->refcount)
498 		goto out_unlock;
499 
500 	err = shutdown_cache(s);
501 	if (err) {
502 		pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
503 		       s->name);
504 		dump_stack();
505 	}
506 out_unlock:
507 	mutex_unlock(&slab_mutex);
508 }
509 EXPORT_SYMBOL(kmem_cache_destroy);
510 
511 /**
512  * kmem_cache_shrink - Shrink a cache.
513  * @cachep: The cache to shrink.
514  *
515  * Releases as many slabs as possible for a cache.
516  * To help debugging, a zero exit status indicates all slabs were released.
517  *
518  * Return: %0 if all slabs were released, non-zero otherwise
519  */
520 int kmem_cache_shrink(struct kmem_cache *cachep)
521 {
522 	int ret;
523 
524 
525 	kasan_cache_shrink(cachep);
526 	ret = __kmem_cache_shrink(cachep);
527 
528 	return ret;
529 }
530 EXPORT_SYMBOL(kmem_cache_shrink);
531 
532 bool slab_is_available(void)
533 {
534 	return slab_state >= UP;
535 }
536 
537 #ifdef CONFIG_PRINTK
538 /**
539  * kmem_valid_obj - does the pointer reference a valid slab object?
540  * @object: pointer to query.
541  *
542  * Return: %true if the pointer is to a not-yet-freed object from
543  * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer
544  * is to an already-freed object, and %false otherwise.
545  */
546 bool kmem_valid_obj(void *object)
547 {
548 	struct page *page;
549 
550 	/* Some arches consider ZERO_SIZE_PTR to be a valid address. */
551 	if (object < (void *)PAGE_SIZE || !virt_addr_valid(object))
552 		return false;
553 	page = virt_to_head_page(object);
554 	return PageSlab(page);
555 }
556 EXPORT_SYMBOL_GPL(kmem_valid_obj);
557 
558 /**
559  * kmem_dump_obj - Print available slab provenance information
560  * @object: slab object for which to find provenance information.
561  *
562  * This function uses pr_cont(), so that the caller is expected to have
563  * printed out whatever preamble is appropriate.  The provenance information
564  * depends on the type of object and on how much debugging is enabled.
565  * For a slab-cache object, the fact that it is a slab object is printed,
566  * and, if available, the slab name, return address, and stack trace from
567  * the allocation of that object.
568  *
569  * This function will splat if passed a pointer to a non-slab object.
570  * If you are not sure what type of object you have, you should instead
571  * use mem_dump_obj().
572  */
573 void kmem_dump_obj(void *object)
574 {
575 	char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc";
576 	int i;
577 	struct page *page;
578 	unsigned long ptroffset;
579 	struct kmem_obj_info kp = { };
580 
581 	if (WARN_ON_ONCE(!virt_addr_valid(object)))
582 		return;
583 	page = virt_to_head_page(object);
584 	if (WARN_ON_ONCE(!PageSlab(page))) {
585 		pr_cont(" non-slab memory.\n");
586 		return;
587 	}
588 	kmem_obj_info(&kp, object, page);
589 	if (kp.kp_slab_cache)
590 		pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name);
591 	else
592 		pr_cont(" slab%s", cp);
593 	if (kp.kp_objp)
594 		pr_cont(" start %px", kp.kp_objp);
595 	if (kp.kp_data_offset)
596 		pr_cont(" data offset %lu", kp.kp_data_offset);
597 	if (kp.kp_objp) {
598 		ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset;
599 		pr_cont(" pointer offset %lu", ptroffset);
600 	}
601 	if (kp.kp_slab_cache && kp.kp_slab_cache->usersize)
602 		pr_cont(" size %u", kp.kp_slab_cache->usersize);
603 	if (kp.kp_ret)
604 		pr_cont(" allocated at %pS\n", kp.kp_ret);
605 	else
606 		pr_cont("\n");
607 	for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) {
608 		if (!kp.kp_stack[i])
609 			break;
610 		pr_info("    %pS\n", kp.kp_stack[i]);
611 	}
612 }
613 EXPORT_SYMBOL_GPL(kmem_dump_obj);
614 #endif
615 
616 #ifndef CONFIG_SLOB
617 /* Create a cache during boot when no slab services are available yet */
618 void __init create_boot_cache(struct kmem_cache *s, const char *name,
619 		unsigned int size, slab_flags_t flags,
620 		unsigned int useroffset, unsigned int usersize)
621 {
622 	int err;
623 	unsigned int align = ARCH_KMALLOC_MINALIGN;
624 
625 	s->name = name;
626 	s->size = s->object_size = size;
627 
628 	/*
629 	 * For power of two sizes, guarantee natural alignment for kmalloc
630 	 * caches, regardless of SL*B debugging options.
631 	 */
632 	if (is_power_of_2(size))
633 		align = max(align, size);
634 	s->align = calculate_alignment(flags, align, size);
635 
636 	s->useroffset = useroffset;
637 	s->usersize = usersize;
638 
639 	err = __kmem_cache_create(s, flags);
640 
641 	if (err)
642 		panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
643 					name, size, err);
644 
645 	s->refcount = -1;	/* Exempt from merging for now */
646 }
647 
648 struct kmem_cache *__init create_kmalloc_cache(const char *name,
649 		unsigned int size, slab_flags_t flags,
650 		unsigned int useroffset, unsigned int usersize)
651 {
652 	struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
653 
654 	if (!s)
655 		panic("Out of memory when creating slab %s\n", name);
656 
657 	create_boot_cache(s, name, size, flags, useroffset, usersize);
658 	kasan_cache_create_kmalloc(s);
659 	list_add(&s->list, &slab_caches);
660 	s->refcount = 1;
661 	return s;
662 }
663 
664 struct kmem_cache *
665 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
666 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
667 EXPORT_SYMBOL(kmalloc_caches);
668 
669 /*
670  * Conversion table for small slabs sizes / 8 to the index in the
671  * kmalloc array. This is necessary for slabs < 192 since we have non power
672  * of two cache sizes there. The size of larger slabs can be determined using
673  * fls.
674  */
675 static u8 size_index[24] __ro_after_init = {
676 	3,	/* 8 */
677 	4,	/* 16 */
678 	5,	/* 24 */
679 	5,	/* 32 */
680 	6,	/* 40 */
681 	6,	/* 48 */
682 	6,	/* 56 */
683 	6,	/* 64 */
684 	1,	/* 72 */
685 	1,	/* 80 */
686 	1,	/* 88 */
687 	1,	/* 96 */
688 	7,	/* 104 */
689 	7,	/* 112 */
690 	7,	/* 120 */
691 	7,	/* 128 */
692 	2,	/* 136 */
693 	2,	/* 144 */
694 	2,	/* 152 */
695 	2,	/* 160 */
696 	2,	/* 168 */
697 	2,	/* 176 */
698 	2,	/* 184 */
699 	2	/* 192 */
700 };
701 
702 static inline unsigned int size_index_elem(unsigned int bytes)
703 {
704 	return (bytes - 1) / 8;
705 }
706 
707 /*
708  * Find the kmem_cache structure that serves a given size of
709  * allocation
710  */
711 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
712 {
713 	unsigned int index;
714 
715 	if (size <= 192) {
716 		if (!size)
717 			return ZERO_SIZE_PTR;
718 
719 		index = size_index[size_index_elem(size)];
720 	} else {
721 		if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
722 			return NULL;
723 		index = fls(size - 1);
724 	}
725 
726 	return kmalloc_caches[kmalloc_type(flags)][index];
727 }
728 
729 #ifdef CONFIG_ZONE_DMA
730 #define INIT_KMALLOC_INFO(__size, __short_size)			\
731 {								\
732 	.name[KMALLOC_NORMAL]  = "kmalloc-" #__short_size,	\
733 	.name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size,	\
734 	.name[KMALLOC_DMA]     = "dma-kmalloc-" #__short_size,	\
735 	.size = __size,						\
736 }
737 #else
738 #define INIT_KMALLOC_INFO(__size, __short_size)			\
739 {								\
740 	.name[KMALLOC_NORMAL]  = "kmalloc-" #__short_size,	\
741 	.name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #__short_size,	\
742 	.size = __size,						\
743 }
744 #endif
745 
746 /*
747  * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
748  * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
749  * kmalloc-67108864.
750  */
751 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
752 	INIT_KMALLOC_INFO(0, 0),
753 	INIT_KMALLOC_INFO(96, 96),
754 	INIT_KMALLOC_INFO(192, 192),
755 	INIT_KMALLOC_INFO(8, 8),
756 	INIT_KMALLOC_INFO(16, 16),
757 	INIT_KMALLOC_INFO(32, 32),
758 	INIT_KMALLOC_INFO(64, 64),
759 	INIT_KMALLOC_INFO(128, 128),
760 	INIT_KMALLOC_INFO(256, 256),
761 	INIT_KMALLOC_INFO(512, 512),
762 	INIT_KMALLOC_INFO(1024, 1k),
763 	INIT_KMALLOC_INFO(2048, 2k),
764 	INIT_KMALLOC_INFO(4096, 4k),
765 	INIT_KMALLOC_INFO(8192, 8k),
766 	INIT_KMALLOC_INFO(16384, 16k),
767 	INIT_KMALLOC_INFO(32768, 32k),
768 	INIT_KMALLOC_INFO(65536, 64k),
769 	INIT_KMALLOC_INFO(131072, 128k),
770 	INIT_KMALLOC_INFO(262144, 256k),
771 	INIT_KMALLOC_INFO(524288, 512k),
772 	INIT_KMALLOC_INFO(1048576, 1M),
773 	INIT_KMALLOC_INFO(2097152, 2M),
774 	INIT_KMALLOC_INFO(4194304, 4M),
775 	INIT_KMALLOC_INFO(8388608, 8M),
776 	INIT_KMALLOC_INFO(16777216, 16M),
777 	INIT_KMALLOC_INFO(33554432, 32M),
778 	INIT_KMALLOC_INFO(67108864, 64M)
779 };
780 
781 /*
782  * Patch up the size_index table if we have strange large alignment
783  * requirements for the kmalloc array. This is only the case for
784  * MIPS it seems. The standard arches will not generate any code here.
785  *
786  * Largest permitted alignment is 256 bytes due to the way we
787  * handle the index determination for the smaller caches.
788  *
789  * Make sure that nothing crazy happens if someone starts tinkering
790  * around with ARCH_KMALLOC_MINALIGN
791  */
792 void __init setup_kmalloc_cache_index_table(void)
793 {
794 	unsigned int i;
795 
796 	BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
797 		(KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
798 
799 	for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
800 		unsigned int elem = size_index_elem(i);
801 
802 		if (elem >= ARRAY_SIZE(size_index))
803 			break;
804 		size_index[elem] = KMALLOC_SHIFT_LOW;
805 	}
806 
807 	if (KMALLOC_MIN_SIZE >= 64) {
808 		/*
809 		 * The 96 byte size cache is not used if the alignment
810 		 * is 64 byte.
811 		 */
812 		for (i = 64 + 8; i <= 96; i += 8)
813 			size_index[size_index_elem(i)] = 7;
814 
815 	}
816 
817 	if (KMALLOC_MIN_SIZE >= 128) {
818 		/*
819 		 * The 192 byte sized cache is not used if the alignment
820 		 * is 128 byte. Redirect kmalloc to use the 256 byte cache
821 		 * instead.
822 		 */
823 		for (i = 128 + 8; i <= 192; i += 8)
824 			size_index[size_index_elem(i)] = 8;
825 	}
826 }
827 
828 static void __init
829 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
830 {
831 	if (type == KMALLOC_RECLAIM)
832 		flags |= SLAB_RECLAIM_ACCOUNT;
833 
834 	kmalloc_caches[type][idx] = create_kmalloc_cache(
835 					kmalloc_info[idx].name[type],
836 					kmalloc_info[idx].size, flags, 0,
837 					kmalloc_info[idx].size);
838 }
839 
840 /*
841  * Create the kmalloc array. Some of the regular kmalloc arrays
842  * may already have been created because they were needed to
843  * enable allocations for slab creation.
844  */
845 void __init create_kmalloc_caches(slab_flags_t flags)
846 {
847 	int i;
848 	enum kmalloc_cache_type type;
849 
850 	for (type = KMALLOC_NORMAL; type <= KMALLOC_RECLAIM; type++) {
851 		for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
852 			if (!kmalloc_caches[type][i])
853 				new_kmalloc_cache(i, type, flags);
854 
855 			/*
856 			 * Caches that are not of the two-to-the-power-of size.
857 			 * These have to be created immediately after the
858 			 * earlier power of two caches
859 			 */
860 			if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
861 					!kmalloc_caches[type][1])
862 				new_kmalloc_cache(1, type, flags);
863 			if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
864 					!kmalloc_caches[type][2])
865 				new_kmalloc_cache(2, type, flags);
866 		}
867 	}
868 
869 	/* Kmalloc array is now usable */
870 	slab_state = UP;
871 
872 #ifdef CONFIG_ZONE_DMA
873 	for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
874 		struct kmem_cache *s = kmalloc_caches[KMALLOC_NORMAL][i];
875 
876 		if (s) {
877 			kmalloc_caches[KMALLOC_DMA][i] = create_kmalloc_cache(
878 				kmalloc_info[i].name[KMALLOC_DMA],
879 				kmalloc_info[i].size,
880 				SLAB_CACHE_DMA | flags, 0,
881 				kmalloc_info[i].size);
882 		}
883 	}
884 #endif
885 }
886 #endif /* !CONFIG_SLOB */
887 
888 gfp_t kmalloc_fix_flags(gfp_t flags)
889 {
890 	gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
891 
892 	flags &= ~GFP_SLAB_BUG_MASK;
893 	pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
894 			invalid_mask, &invalid_mask, flags, &flags);
895 	dump_stack();
896 
897 	return flags;
898 }
899 
900 /*
901  * To avoid unnecessary overhead, we pass through large allocation requests
902  * directly to the page allocator. We use __GFP_COMP, because we will need to
903  * know the allocation order to free the pages properly in kfree.
904  */
905 void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
906 {
907 	void *ret = NULL;
908 	struct page *page;
909 
910 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
911 		flags = kmalloc_fix_flags(flags);
912 
913 	flags |= __GFP_COMP;
914 	page = alloc_pages(flags, order);
915 	if (likely(page)) {
916 		ret = page_address(page);
917 		mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
918 				      PAGE_SIZE << order);
919 	}
920 	ret = kasan_kmalloc_large(ret, size, flags);
921 	/* As ret might get tagged, call kmemleak hook after KASAN. */
922 	kmemleak_alloc(ret, size, 1, flags);
923 	return ret;
924 }
925 EXPORT_SYMBOL(kmalloc_order);
926 
927 #ifdef CONFIG_TRACING
928 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
929 {
930 	void *ret = kmalloc_order(size, flags, order);
931 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
932 	return ret;
933 }
934 EXPORT_SYMBOL(kmalloc_order_trace);
935 #endif
936 
937 #ifdef CONFIG_SLAB_FREELIST_RANDOM
938 /* Randomize a generic freelist */
939 static void freelist_randomize(struct rnd_state *state, unsigned int *list,
940 			       unsigned int count)
941 {
942 	unsigned int rand;
943 	unsigned int i;
944 
945 	for (i = 0; i < count; i++)
946 		list[i] = i;
947 
948 	/* Fisher-Yates shuffle */
949 	for (i = count - 1; i > 0; i--) {
950 		rand = prandom_u32_state(state);
951 		rand %= (i + 1);
952 		swap(list[i], list[rand]);
953 	}
954 }
955 
956 /* Create a random sequence per cache */
957 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
958 				    gfp_t gfp)
959 {
960 	struct rnd_state state;
961 
962 	if (count < 2 || cachep->random_seq)
963 		return 0;
964 
965 	cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
966 	if (!cachep->random_seq)
967 		return -ENOMEM;
968 
969 	/* Get best entropy at this stage of boot */
970 	prandom_seed_state(&state, get_random_long());
971 
972 	freelist_randomize(&state, cachep->random_seq, count);
973 	return 0;
974 }
975 
976 /* Destroy the per-cache random freelist sequence */
977 void cache_random_seq_destroy(struct kmem_cache *cachep)
978 {
979 	kfree(cachep->random_seq);
980 	cachep->random_seq = NULL;
981 }
982 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
983 
984 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
985 #ifdef CONFIG_SLAB
986 #define SLABINFO_RIGHTS (0600)
987 #else
988 #define SLABINFO_RIGHTS (0400)
989 #endif
990 
991 static void print_slabinfo_header(struct seq_file *m)
992 {
993 	/*
994 	 * Output format version, so at least we can change it
995 	 * without _too_ many complaints.
996 	 */
997 #ifdef CONFIG_DEBUG_SLAB
998 	seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
999 #else
1000 	seq_puts(m, "slabinfo - version: 2.1\n");
1001 #endif
1002 	seq_puts(m, "# name            <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1003 	seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1004 	seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1005 #ifdef CONFIG_DEBUG_SLAB
1006 	seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1007 	seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1008 #endif
1009 	seq_putc(m, '\n');
1010 }
1011 
1012 void *slab_start(struct seq_file *m, loff_t *pos)
1013 {
1014 	mutex_lock(&slab_mutex);
1015 	return seq_list_start(&slab_caches, *pos);
1016 }
1017 
1018 void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1019 {
1020 	return seq_list_next(p, &slab_caches, pos);
1021 }
1022 
1023 void slab_stop(struct seq_file *m, void *p)
1024 {
1025 	mutex_unlock(&slab_mutex);
1026 }
1027 
1028 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1029 {
1030 	struct slabinfo sinfo;
1031 
1032 	memset(&sinfo, 0, sizeof(sinfo));
1033 	get_slabinfo(s, &sinfo);
1034 
1035 	seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1036 		   s->name, sinfo.active_objs, sinfo.num_objs, s->size,
1037 		   sinfo.objects_per_slab, (1 << sinfo.cache_order));
1038 
1039 	seq_printf(m, " : tunables %4u %4u %4u",
1040 		   sinfo.limit, sinfo.batchcount, sinfo.shared);
1041 	seq_printf(m, " : slabdata %6lu %6lu %6lu",
1042 		   sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1043 	slabinfo_show_stats(m, s);
1044 	seq_putc(m, '\n');
1045 }
1046 
1047 static int slab_show(struct seq_file *m, void *p)
1048 {
1049 	struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1050 
1051 	if (p == slab_caches.next)
1052 		print_slabinfo_header(m);
1053 	cache_show(s, m);
1054 	return 0;
1055 }
1056 
1057 void dump_unreclaimable_slab(void)
1058 {
1059 	struct kmem_cache *s;
1060 	struct slabinfo sinfo;
1061 
1062 	/*
1063 	 * Here acquiring slab_mutex is risky since we don't prefer to get
1064 	 * sleep in oom path. But, without mutex hold, it may introduce a
1065 	 * risk of crash.
1066 	 * Use mutex_trylock to protect the list traverse, dump nothing
1067 	 * without acquiring the mutex.
1068 	 */
1069 	if (!mutex_trylock(&slab_mutex)) {
1070 		pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1071 		return;
1072 	}
1073 
1074 	pr_info("Unreclaimable slab info:\n");
1075 	pr_info("Name                      Used          Total\n");
1076 
1077 	list_for_each_entry(s, &slab_caches, list) {
1078 		if (s->flags & SLAB_RECLAIM_ACCOUNT)
1079 			continue;
1080 
1081 		get_slabinfo(s, &sinfo);
1082 
1083 		if (sinfo.num_objs > 0)
1084 			pr_info("%-17s %10luKB %10luKB\n", s->name,
1085 				(sinfo.active_objs * s->size) / 1024,
1086 				(sinfo.num_objs * s->size) / 1024);
1087 	}
1088 	mutex_unlock(&slab_mutex);
1089 }
1090 
1091 #if defined(CONFIG_MEMCG_KMEM)
1092 int memcg_slab_show(struct seq_file *m, void *p)
1093 {
1094 	/*
1095 	 * Deprecated.
1096 	 * Please, take a look at tools/cgroup/slabinfo.py .
1097 	 */
1098 	return 0;
1099 }
1100 #endif
1101 
1102 /*
1103  * slabinfo_op - iterator that generates /proc/slabinfo
1104  *
1105  * Output layout:
1106  * cache-name
1107  * num-active-objs
1108  * total-objs
1109  * object size
1110  * num-active-slabs
1111  * total-slabs
1112  * num-pages-per-slab
1113  * + further values on SMP and with statistics enabled
1114  */
1115 static const struct seq_operations slabinfo_op = {
1116 	.start = slab_start,
1117 	.next = slab_next,
1118 	.stop = slab_stop,
1119 	.show = slab_show,
1120 };
1121 
1122 static int slabinfo_open(struct inode *inode, struct file *file)
1123 {
1124 	return seq_open(file, &slabinfo_op);
1125 }
1126 
1127 static const struct proc_ops slabinfo_proc_ops = {
1128 	.proc_flags	= PROC_ENTRY_PERMANENT,
1129 	.proc_open	= slabinfo_open,
1130 	.proc_read	= seq_read,
1131 	.proc_write	= slabinfo_write,
1132 	.proc_lseek	= seq_lseek,
1133 	.proc_release	= seq_release,
1134 };
1135 
1136 static int __init slab_proc_init(void)
1137 {
1138 	proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1139 	return 0;
1140 }
1141 module_init(slab_proc_init);
1142 
1143 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1144 
1145 static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1146 					   gfp_t flags)
1147 {
1148 	void *ret;
1149 	size_t ks;
1150 
1151 	/* Don't use instrumented ksize to allow precise KASAN poisoning. */
1152 	if (likely(!ZERO_OR_NULL_PTR(p))) {
1153 		if (!kasan_check_byte(p))
1154 			return NULL;
1155 		ks = kfence_ksize(p) ?: __ksize(p);
1156 	} else
1157 		ks = 0;
1158 
1159 	/* If the object still fits, repoison it precisely. */
1160 	if (ks >= new_size) {
1161 		p = kasan_krealloc((void *)p, new_size, flags);
1162 		return (void *)p;
1163 	}
1164 
1165 	ret = kmalloc_track_caller(new_size, flags);
1166 	if (ret && p) {
1167 		/* Disable KASAN checks as the object's redzone is accessed. */
1168 		kasan_disable_current();
1169 		memcpy(ret, kasan_reset_tag(p), ks);
1170 		kasan_enable_current();
1171 	}
1172 
1173 	return ret;
1174 }
1175 
1176 /**
1177  * krealloc - reallocate memory. The contents will remain unchanged.
1178  * @p: object to reallocate memory for.
1179  * @new_size: how many bytes of memory are required.
1180  * @flags: the type of memory to allocate.
1181  *
1182  * The contents of the object pointed to are preserved up to the
1183  * lesser of the new and old sizes (__GFP_ZERO flag is effectively ignored).
1184  * If @p is %NULL, krealloc() behaves exactly like kmalloc().  If @new_size
1185  * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
1186  *
1187  * Return: pointer to the allocated memory or %NULL in case of error
1188  */
1189 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1190 {
1191 	void *ret;
1192 
1193 	if (unlikely(!new_size)) {
1194 		kfree(p);
1195 		return ZERO_SIZE_PTR;
1196 	}
1197 
1198 	ret = __do_krealloc(p, new_size, flags);
1199 	if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1200 		kfree(p);
1201 
1202 	return ret;
1203 }
1204 EXPORT_SYMBOL(krealloc);
1205 
1206 /**
1207  * kfree_sensitive - Clear sensitive information in memory before freeing
1208  * @p: object to free memory of
1209  *
1210  * The memory of the object @p points to is zeroed before freed.
1211  * If @p is %NULL, kfree_sensitive() does nothing.
1212  *
1213  * Note: this function zeroes the whole allocated buffer which can be a good
1214  * deal bigger than the requested buffer size passed to kmalloc(). So be
1215  * careful when using this function in performance sensitive code.
1216  */
1217 void kfree_sensitive(const void *p)
1218 {
1219 	size_t ks;
1220 	void *mem = (void *)p;
1221 
1222 	ks = ksize(mem);
1223 	if (ks)
1224 		memzero_explicit(mem, ks);
1225 	kfree(mem);
1226 }
1227 EXPORT_SYMBOL(kfree_sensitive);
1228 
1229 /**
1230  * ksize - get the actual amount of memory allocated for a given object
1231  * @objp: Pointer to the object
1232  *
1233  * kmalloc may internally round up allocations and return more memory
1234  * than requested. ksize() can be used to determine the actual amount of
1235  * memory allocated. The caller may use this additional memory, even though
1236  * a smaller amount of memory was initially specified with the kmalloc call.
1237  * The caller must guarantee that objp points to a valid object previously
1238  * allocated with either kmalloc() or kmem_cache_alloc(). The object
1239  * must not be freed during the duration of the call.
1240  *
1241  * Return: size of the actual memory used by @objp in bytes
1242  */
1243 size_t ksize(const void *objp)
1244 {
1245 	size_t size;
1246 
1247 	/*
1248 	 * We need to first check that the pointer to the object is valid, and
1249 	 * only then unpoison the memory. The report printed from ksize() is
1250 	 * more useful, then when it's printed later when the behaviour could
1251 	 * be undefined due to a potential use-after-free or double-free.
1252 	 *
1253 	 * We use kasan_check_byte(), which is supported for the hardware
1254 	 * tag-based KASAN mode, unlike kasan_check_read/write().
1255 	 *
1256 	 * If the pointed to memory is invalid, we return 0 to avoid users of
1257 	 * ksize() writing to and potentially corrupting the memory region.
1258 	 *
1259 	 * We want to perform the check before __ksize(), to avoid potentially
1260 	 * crashing in __ksize() due to accessing invalid metadata.
1261 	 */
1262 	if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
1263 		return 0;
1264 
1265 	size = kfence_ksize(objp) ?: __ksize(objp);
1266 	/*
1267 	 * We assume that ksize callers could use whole allocated area,
1268 	 * so we need to unpoison this area.
1269 	 */
1270 	kasan_unpoison_range(objp, size);
1271 	return size;
1272 }
1273 EXPORT_SYMBOL(ksize);
1274 
1275 /* Tracepoints definitions. */
1276 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1277 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1278 EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1279 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1280 EXPORT_TRACEPOINT_SYMBOL(kfree);
1281 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1282 
1283 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1284 {
1285 	if (__should_failslab(s, gfpflags))
1286 		return -ENOMEM;
1287 	return 0;
1288 }
1289 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);
1290