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