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