• 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/dma-mapping.h>
21 #include <linux/swiotlb.h>
22 #include <linux/proc_fs.h>
23 #include <linux/debugfs.h>
24 #include <linux/kasan.h>
25 #include <asm/cacheflush.h>
26 #include <asm/tlbflush.h>
27 #include <asm/page.h>
28 #include <linux/memcontrol.h>
29 #include <linux/stackdepot.h>
30 
31 #include "internal.h"
32 #include "slab.h"
33 
34 #define CREATE_TRACE_POINTS
35 #include <trace/events/kmem.h>
36 #undef CREATE_TRACE_POINTS
37 #include <trace/hooks/mm.h>
38 
39 enum slab_state slab_state;
40 LIST_HEAD(slab_caches);
41 DEFINE_MUTEX(slab_mutex);
42 struct kmem_cache *kmem_cache;
43 
44 static LIST_HEAD(slab_caches_to_rcu_destroy);
45 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
46 static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
47 		    slab_caches_to_rcu_destroy_workfn);
48 
49 /*
50  * Set of flags that will prevent slab merging
51  */
52 #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
53 		SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
54 		SLAB_FAILSLAB | SLAB_NO_MERGE | kasan_never_merge())
55 
56 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
57 			 SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
58 
59 /*
60  * Merge control. If this is set then no merging of slab caches will occur.
61  */
62 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
63 
setup_slab_nomerge(char * str)64 static int __init setup_slab_nomerge(char *str)
65 {
66 	slab_nomerge = true;
67 	return 1;
68 }
69 
setup_slab_merge(char * str)70 static int __init setup_slab_merge(char *str)
71 {
72 	slab_nomerge = false;
73 	return 1;
74 }
75 
76 #ifdef CONFIG_SLUB
77 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
78 __setup_param("slub_merge", slub_merge, setup_slab_merge, 0);
79 #endif
80 
81 __setup("slab_nomerge", setup_slab_nomerge);
82 __setup("slab_merge", setup_slab_merge);
83 
84 /*
85  * Determine the size of a slab object
86  */
kmem_cache_size(struct kmem_cache * s)87 unsigned int kmem_cache_size(struct kmem_cache *s)
88 {
89 	return s->object_size;
90 }
91 EXPORT_SYMBOL(kmem_cache_size);
92 
93 #ifdef CONFIG_DEBUG_VM
kmem_cache_sanity_check(const char * name,unsigned int size)94 static int kmem_cache_sanity_check(const char *name, unsigned int size)
95 {
96 	if (!name || in_interrupt() || size > KMALLOC_MAX_SIZE) {
97 		pr_err("kmem_cache_create(%s) integrity check failed\n", name);
98 		return -EINVAL;
99 	}
100 
101 	WARN_ON(strchr(name, ' '));	/* It confuses parsers */
102 	return 0;
103 }
104 #else
kmem_cache_sanity_check(const char * name,unsigned int size)105 static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
106 {
107 	return 0;
108 }
109 #endif
110 
111 /*
112  * Figure out what the alignment of the objects will be given a set of
113  * flags, a user specified alignment and the size of the objects.
114  */
calculate_alignment(slab_flags_t flags,unsigned int align,unsigned int size)115 static unsigned int calculate_alignment(slab_flags_t flags,
116 		unsigned int align, unsigned int size)
117 {
118 	/*
119 	 * If the user wants hardware cache aligned objects then follow that
120 	 * suggestion if the object is sufficiently large.
121 	 *
122 	 * The hardware cache alignment cannot override the specified
123 	 * alignment though. If that is greater then use it.
124 	 */
125 	if (flags & SLAB_HWCACHE_ALIGN) {
126 		unsigned int ralign;
127 
128 		ralign = cache_line_size();
129 		while (size <= ralign / 2)
130 			ralign /= 2;
131 		align = max(align, ralign);
132 	}
133 
134 	align = max(align, arch_slab_minalign());
135 
136 	return ALIGN(align, sizeof(void *));
137 }
138 
139 /*
140  * Find a mergeable slab cache
141  */
slab_unmergeable(struct kmem_cache * s)142 int slab_unmergeable(struct kmem_cache *s)
143 {
144 	if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
145 		return 1;
146 
147 	if (s->ctor)
148 		return 1;
149 
150 #ifdef CONFIG_HARDENED_USERCOPY
151 	if (s->usersize)
152 		return 1;
153 #endif
154 
155 	/*
156 	 * We may have set a slab to be unmergeable during bootstrap.
157 	 */
158 	if (s->refcount < 0)
159 		return 1;
160 
161 	return 0;
162 }
163 
find_mergeable(unsigned int size,unsigned int align,slab_flags_t flags,const char * name,void (* ctor)(void *))164 struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
165 		slab_flags_t flags, const char *name, void (*ctor)(void *))
166 {
167 	struct kmem_cache *s;
168 
169 	if (slab_nomerge)
170 		return NULL;
171 
172 	if (ctor)
173 		return NULL;
174 
175 	size = ALIGN(size, sizeof(void *));
176 	align = calculate_alignment(flags, align, size);
177 	size = ALIGN(size, align);
178 	flags = kmem_cache_flags(size, flags, name);
179 
180 	if (flags & SLAB_NEVER_MERGE)
181 		return NULL;
182 
183 	list_for_each_entry_reverse(s, &slab_caches, list) {
184 		if (slab_unmergeable(s))
185 			continue;
186 
187 		if (size > s->size)
188 			continue;
189 
190 		if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
191 			continue;
192 		/*
193 		 * Check if alignment is compatible.
194 		 * Courtesy of Adrian Drzewiecki
195 		 */
196 		if ((s->size & ~(align - 1)) != s->size)
197 			continue;
198 
199 		if (s->size - size >= sizeof(void *))
200 			continue;
201 
202 		if (IS_ENABLED(CONFIG_SLAB) && align &&
203 			(align > s->align || s->align % align))
204 			continue;
205 
206 		return s;
207 	}
208 	return NULL;
209 }
210 
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)211 static struct kmem_cache *create_cache(const char *name,
212 		unsigned int object_size, unsigned int align,
213 		slab_flags_t flags, unsigned int useroffset,
214 		unsigned int usersize, void (*ctor)(void *),
215 		struct kmem_cache *root_cache)
216 {
217 	struct kmem_cache *s;
218 	int err;
219 
220 	if (WARN_ON(useroffset + usersize > object_size))
221 		useroffset = usersize = 0;
222 
223 	err = -ENOMEM;
224 	s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
225 	if (!s)
226 		goto out;
227 
228 	s->name = name;
229 	s->size = s->object_size = object_size;
230 	s->align = align;
231 	s->ctor = ctor;
232 #ifdef CONFIG_HARDENED_USERCOPY
233 	s->useroffset = useroffset;
234 	s->usersize = usersize;
235 #endif
236 
237 	err = __kmem_cache_create(s, flags);
238 	if (err)
239 		goto out_free_cache;
240 
241 	s->refcount = 1;
242 	list_add(&s->list, &slab_caches);
243 	return s;
244 
245 out_free_cache:
246 	kmem_cache_free(kmem_cache, s);
247 out:
248 	return ERR_PTR(err);
249 }
250 
251 /**
252  * kmem_cache_create_usercopy - Create a cache with a region suitable
253  * for copying to userspace
254  * @name: A string which is used in /proc/slabinfo to identify this cache.
255  * @size: The size of objects to be created in this cache.
256  * @align: The required alignment for the objects.
257  * @flags: SLAB flags
258  * @useroffset: Usercopy region offset
259  * @usersize: Usercopy region size
260  * @ctor: A constructor for the objects.
261  *
262  * Cannot be called within a interrupt, but can be interrupted.
263  * The @ctor is run when new pages are allocated by the cache.
264  *
265  * The flags are
266  *
267  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
268  * to catch references to uninitialised memory.
269  *
270  * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
271  * for buffer overruns.
272  *
273  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
274  * cacheline.  This can be beneficial if you're counting cycles as closely
275  * as davem.
276  *
277  * Return: a pointer to the cache on success, NULL on failure.
278  */
279 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 *))280 kmem_cache_create_usercopy(const char *name,
281 		  unsigned int size, unsigned int align,
282 		  slab_flags_t flags,
283 		  unsigned int useroffset, unsigned int usersize,
284 		  void (*ctor)(void *))
285 {
286 	struct kmem_cache *s = NULL;
287 	const char *cache_name;
288 	int err;
289 
290 #ifdef CONFIG_SLUB_DEBUG
291 	/*
292 	 * If no slub_debug was enabled globally, the static key is not yet
293 	 * enabled by setup_slub_debug(). Enable it if the cache is being
294 	 * created with any of the debugging flags passed explicitly.
295 	 * It's also possible that this is the first cache created with
296 	 * SLAB_STORE_USER and we should init stack_depot for it.
297 	 */
298 	if (flags & SLAB_DEBUG_FLAGS)
299 		static_branch_enable(&slub_debug_enabled);
300 	if (flags & SLAB_STORE_USER)
301 		stack_depot_init();
302 #endif
303 
304 	mutex_lock(&slab_mutex);
305 
306 	err = kmem_cache_sanity_check(name, size);
307 	if (err) {
308 		goto out_unlock;
309 	}
310 
311 	/* Refuse requests with allocator specific flags */
312 	if (flags & ~SLAB_FLAGS_PERMITTED) {
313 		err = -EINVAL;
314 		goto out_unlock;
315 	}
316 
317 	/*
318 	 * Some allocators will constraint the set of valid flags to a subset
319 	 * of all flags. We expect them to define CACHE_CREATE_MASK in this
320 	 * case, and we'll just provide them with a sanitized version of the
321 	 * passed flags.
322 	 */
323 	flags &= CACHE_CREATE_MASK;
324 
325 	/* Fail closed on bad usersize of useroffset values. */
326 	if (!IS_ENABLED(CONFIG_HARDENED_USERCOPY) ||
327 	    WARN_ON(!usersize && useroffset) ||
328 	    WARN_ON(size < usersize || size - usersize < useroffset))
329 		usersize = useroffset = 0;
330 
331 	if (!usersize)
332 		s = __kmem_cache_alias(name, size, align, flags, ctor);
333 	if (s)
334 		goto out_unlock;
335 
336 	cache_name = kstrdup_const(name, GFP_KERNEL);
337 	if (!cache_name) {
338 		err = -ENOMEM;
339 		goto out_unlock;
340 	}
341 
342 	s = create_cache(cache_name, size,
343 			 calculate_alignment(flags, align, size),
344 			 flags, useroffset, usersize, ctor, NULL);
345 	if (IS_ERR(s)) {
346 		err = PTR_ERR(s);
347 		kfree_const(cache_name);
348 	}
349 
350 out_unlock:
351 	mutex_unlock(&slab_mutex);
352 
353 	if (err) {
354 		if (flags & SLAB_PANIC)
355 			panic("%s: Failed to create slab '%s'. Error %d\n",
356 				__func__, name, err);
357 		else {
358 			pr_warn("%s(%s) failed with error %d\n",
359 				__func__, name, err);
360 			dump_stack();
361 		}
362 		return NULL;
363 	}
364 	return s;
365 }
366 EXPORT_SYMBOL(kmem_cache_create_usercopy);
367 
368 /**
369  * kmem_cache_create - Create a cache.
370  * @name: A string which is used in /proc/slabinfo to identify this cache.
371  * @size: The size of objects to be created in this cache.
372  * @align: The required alignment for the objects.
373  * @flags: SLAB flags
374  * @ctor: A constructor for the objects.
375  *
376  * Cannot be called within a interrupt, but can be interrupted.
377  * The @ctor is run when new pages are allocated by the cache.
378  *
379  * The flags are
380  *
381  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
382  * to catch references to uninitialised memory.
383  *
384  * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
385  * for buffer overruns.
386  *
387  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
388  * cacheline.  This can be beneficial if you're counting cycles as closely
389  * as davem.
390  *
391  * Return: a pointer to the cache on success, NULL on failure.
392  */
393 struct kmem_cache *
kmem_cache_create(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))394 kmem_cache_create(const char *name, unsigned int size, unsigned int align,
395 		slab_flags_t flags, void (*ctor)(void *))
396 {
397 	return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
398 					  ctor);
399 }
400 EXPORT_SYMBOL(kmem_cache_create);
401 
402 #ifdef SLAB_SUPPORTS_SYSFS
403 /*
404  * For a given kmem_cache, kmem_cache_destroy() should only be called
405  * once or there will be a use-after-free problem. The actual deletion
406  * and release of the kobject does not need slab_mutex or cpu_hotplug_lock
407  * protection. So they are now done without holding those locks.
408  *
409  * Note that there will be a slight delay in the deletion of sysfs files
410  * if kmem_cache_release() is called indrectly from a work function.
411  */
kmem_cache_release(struct kmem_cache * s)412 static void kmem_cache_release(struct kmem_cache *s)
413 {
414 	sysfs_slab_unlink(s);
415 	sysfs_slab_release(s);
416 }
417 #else
kmem_cache_release(struct kmem_cache * s)418 static void kmem_cache_release(struct kmem_cache *s)
419 {
420 	slab_kmem_cache_release(s);
421 }
422 #endif
423 
slab_caches_to_rcu_destroy_workfn(struct work_struct * work)424 static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
425 {
426 	LIST_HEAD(to_destroy);
427 	struct kmem_cache *s, *s2;
428 
429 	/*
430 	 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
431 	 * @slab_caches_to_rcu_destroy list.  The slab pages are freed
432 	 * through RCU and the associated kmem_cache are dereferenced
433 	 * while freeing the pages, so the kmem_caches should be freed only
434 	 * after the pending RCU operations are finished.  As rcu_barrier()
435 	 * is a pretty slow operation, we batch all pending destructions
436 	 * asynchronously.
437 	 */
438 	mutex_lock(&slab_mutex);
439 	list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
440 	mutex_unlock(&slab_mutex);
441 
442 	if (list_empty(&to_destroy))
443 		return;
444 
445 	rcu_barrier();
446 
447 	list_for_each_entry_safe(s, s2, &to_destroy, list) {
448 		debugfs_slab_release(s);
449 		kfence_shutdown_cache(s);
450 		kmem_cache_release(s);
451 	}
452 }
453 
shutdown_cache(struct kmem_cache * s)454 static int shutdown_cache(struct kmem_cache *s)
455 {
456 	/* free asan quarantined objects */
457 	kasan_cache_shutdown(s);
458 
459 	if (__kmem_cache_shutdown(s) != 0)
460 		return -EBUSY;
461 
462 	list_del(&s->list);
463 
464 	if (s->flags & SLAB_TYPESAFE_BY_RCU) {
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 		debugfs_slab_release(s);
470 	}
471 
472 	return 0;
473 }
474 
slab_kmem_cache_release(struct kmem_cache * s)475 void slab_kmem_cache_release(struct kmem_cache *s)
476 {
477 	__kmem_cache_release(s);
478 	kfree_const(s->name);
479 	kmem_cache_free(kmem_cache, s);
480 }
481 
kmem_cache_destroy(struct kmem_cache * s)482 void kmem_cache_destroy(struct kmem_cache *s)
483 {
484 	int err = -EBUSY;
485 	bool rcu_set;
486 
487 	if (unlikely(!s) || !kasan_check_byte(s))
488 		return;
489 
490 	cpus_read_lock();
491 	mutex_lock(&slab_mutex);
492 
493 	rcu_set = s->flags & SLAB_TYPESAFE_BY_RCU;
494 
495 	s->refcount--;
496 	if (s->refcount)
497 		goto out_unlock;
498 
499 	err = shutdown_cache(s);
500 	WARN(err, "%s %s: Slab cache still has objects when called from %pS",
501 	     __func__, s->name, (void *)_RET_IP_);
502 out_unlock:
503 	mutex_unlock(&slab_mutex);
504 	cpus_read_unlock();
505 	if (!err && !rcu_set)
506 		kmem_cache_release(s);
507 }
508 EXPORT_SYMBOL(kmem_cache_destroy);
509 
510 /**
511  * kmem_cache_shrink - Shrink a cache.
512  * @cachep: The cache to shrink.
513  *
514  * Releases as many slabs as possible for a cache.
515  * To help debugging, a zero exit status indicates all slabs were released.
516  *
517  * Return: %0 if all slabs were released, non-zero otherwise
518  */
kmem_cache_shrink(struct kmem_cache * cachep)519 int kmem_cache_shrink(struct kmem_cache *cachep)
520 {
521 	kasan_cache_shrink(cachep);
522 
523 	return __kmem_cache_shrink(cachep);
524 }
525 EXPORT_SYMBOL(kmem_cache_shrink);
526 
slab_is_available(void)527 bool slab_is_available(void)
528 {
529 	return slab_state >= UP;
530 }
531 
532 #ifdef CONFIG_PRINTK
kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct slab * slab)533 static void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
534 {
535 	if (__kfence_obj_info(kpp, object, slab))
536 		return;
537 	__kmem_obj_info(kpp, object, slab);
538 }
539 
540 /**
541  * kmem_dump_obj - Print available slab provenance information
542  * @object: slab object for which to find provenance information.
543  *
544  * This function uses pr_cont(), so that the caller is expected to have
545  * printed out whatever preamble is appropriate.  The provenance information
546  * depends on the type of object and on how much debugging is enabled.
547  * For a slab-cache object, the fact that it is a slab object is printed,
548  * and, if available, the slab name, return address, and stack trace from
549  * the allocation and last free path of that object.
550  *
551  * Return: %true if the pointer is to a not-yet-freed object from
552  * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer
553  * is to an already-freed object, and %false otherwise.
554  */
kmem_dump_obj(void * object)555 bool kmem_dump_obj(void *object)
556 {
557 	char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc";
558 	int i;
559 	struct slab *slab;
560 	unsigned long ptroffset;
561 	struct kmem_obj_info kp = { };
562 
563 	/* Some arches consider ZERO_SIZE_PTR to be a valid address. */
564 	if (object < (void *)PAGE_SIZE || !virt_addr_valid(object))
565 		return false;
566 	slab = virt_to_slab(object);
567 	if (!slab)
568 		return false;
569 
570 	kmem_obj_info(&kp, object, slab);
571 	if (kp.kp_slab_cache)
572 		pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name);
573 	else
574 		pr_cont(" slab%s", cp);
575 	if (is_kfence_address(object))
576 		pr_cont(" (kfence)");
577 	if (kp.kp_objp)
578 		pr_cont(" start %px", kp.kp_objp);
579 	if (kp.kp_data_offset)
580 		pr_cont(" data offset %lu", kp.kp_data_offset);
581 	if (kp.kp_objp) {
582 		ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset;
583 		pr_cont(" pointer offset %lu", ptroffset);
584 	}
585 	if (kp.kp_slab_cache && kp.kp_slab_cache->object_size)
586 		pr_cont(" size %u", kp.kp_slab_cache->object_size);
587 	if (kp.kp_ret)
588 		pr_cont(" allocated at %pS\n", kp.kp_ret);
589 	else
590 		pr_cont("\n");
591 	for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) {
592 		if (!kp.kp_stack[i])
593 			break;
594 		pr_info("    %pS\n", kp.kp_stack[i]);
595 	}
596 
597 	if (kp.kp_free_stack[0])
598 		pr_cont(" Free path:\n");
599 
600 	for (i = 0; i < ARRAY_SIZE(kp.kp_free_stack); i++) {
601 		if (!kp.kp_free_stack[i])
602 			break;
603 		pr_info("    %pS\n", kp.kp_free_stack[i]);
604 	}
605 
606 	return true;
607 }
608 EXPORT_SYMBOL_GPL(kmem_dump_obj);
609 #endif
610 
611 /* 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)612 void __init create_boot_cache(struct kmem_cache *s, const char *name,
613 		unsigned int size, slab_flags_t flags,
614 		unsigned int useroffset, unsigned int usersize)
615 {
616 	int err;
617 	unsigned int align = ARCH_KMALLOC_MINALIGN;
618 
619 	s->name = name;
620 	s->size = s->object_size = size;
621 
622 	/*
623 	 * For power of two sizes, guarantee natural alignment for kmalloc
624 	 * caches, regardless of SL*B debugging options.
625 	 */
626 	if (is_power_of_2(size))
627 		align = max(align, size);
628 	s->align = calculate_alignment(flags, align, size);
629 
630 #ifdef CONFIG_HARDENED_USERCOPY
631 	s->useroffset = useroffset;
632 	s->usersize = usersize;
633 #endif
634 
635 	err = __kmem_cache_create(s, flags);
636 
637 	if (err)
638 		panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
639 					name, size, err);
640 
641 	s->refcount = -1;	/* Exempt from merging for now */
642 }
643 
create_kmalloc_cache(const char * name,unsigned int size,slab_flags_t flags)644 static struct kmem_cache *__init create_kmalloc_cache(const char *name,
645 						      unsigned int size,
646 						      slab_flags_t flags)
647 {
648 	struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
649 
650 	if (!s)
651 		panic("Out of memory when creating slab %s\n", name);
652 
653 	create_boot_cache(s, name, size, flags | SLAB_KMALLOC, 0, size);
654 	list_add(&s->list, &slab_caches);
655 	s->refcount = 1;
656 	return s;
657 }
658 
659 struct kmem_cache *
660 kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
661 { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
662 EXPORT_SYMBOL(kmalloc_caches);
663 
664 #ifdef CONFIG_RANDOM_KMALLOC_CACHES
665 unsigned long random_kmalloc_seed __ro_after_init;
666 EXPORT_SYMBOL(random_kmalloc_seed);
667 #endif
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 
size_index_elem(unsigned int bytes)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  */
kmalloc_slab(size_t size,gfp_t flags,unsigned long caller)711 struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags, unsigned long caller)
712 {
713 	unsigned int index;
714 	struct kmem_cache *s = NULL;
715 
716 	if (size <= 192) {
717 		if (!size)
718 			return ZERO_SIZE_PTR;
719 
720 		index = size_index[size_index_elem(size)];
721 	} else {
722 		if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
723 			return NULL;
724 		index = fls(size - 1);
725 	}
726 
727 	trace_android_vh_kmalloc_slab(index, flags, &s);
728 	if (s)
729 		return s;
730 
731 	return kmalloc_caches[kmalloc_type(flags, caller)][index];
732 }
733 
kmalloc_size_roundup(size_t size)734 size_t kmalloc_size_roundup(size_t size)
735 {
736 	if (size && size <= KMALLOC_MAX_CACHE_SIZE) {
737 		/*
738 		 * The flags don't matter since size_index is common to all.
739 		 * Neither does the caller for just getting ->object_size.
740 		 */
741 		return kmalloc_slab(size, GFP_KERNEL, 0)->object_size;
742 	}
743 
744 	/* Above the smaller buckets, size is a multiple of page size. */
745 	if (size && size <= KMALLOC_MAX_SIZE)
746 		return PAGE_SIZE << get_order(size);
747 
748 	/*
749 	 * Return 'size' for 0 - kmalloc() returns ZERO_SIZE_PTR
750 	 * and very large size - kmalloc() may fail.
751 	 */
752 	return size;
753 
754 }
755 EXPORT_SYMBOL(kmalloc_size_roundup);
756 
757 #ifdef CONFIG_ZONE_DMA
758 #define KMALLOC_DMA_NAME(sz)	.name[KMALLOC_DMA] = "dma-kmalloc-" #sz,
759 #else
760 #define KMALLOC_DMA_NAME(sz)
761 #endif
762 
763 #ifdef CONFIG_MEMCG_KMEM
764 #define KMALLOC_CGROUP_NAME(sz)	.name[KMALLOC_CGROUP] = "kmalloc-cg-" #sz,
765 #else
766 #define KMALLOC_CGROUP_NAME(sz)
767 #endif
768 
769 #ifndef CONFIG_SLUB_TINY
770 #define KMALLOC_RCL_NAME(sz)	.name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #sz,
771 #else
772 #define KMALLOC_RCL_NAME(sz)
773 #endif
774 
775 #ifdef CONFIG_RANDOM_KMALLOC_CACHES
776 #define __KMALLOC_RANDOM_CONCAT(a, b) a ## b
777 #define KMALLOC_RANDOM_NAME(N, sz) __KMALLOC_RANDOM_CONCAT(KMA_RAND_, N)(sz)
778 #define KMA_RAND_1(sz)                  .name[KMALLOC_RANDOM_START +  1] = "kmalloc-rnd-01-" #sz,
779 #define KMA_RAND_2(sz)  KMA_RAND_1(sz)  .name[KMALLOC_RANDOM_START +  2] = "kmalloc-rnd-02-" #sz,
780 #define KMA_RAND_3(sz)  KMA_RAND_2(sz)  .name[KMALLOC_RANDOM_START +  3] = "kmalloc-rnd-03-" #sz,
781 #define KMA_RAND_4(sz)  KMA_RAND_3(sz)  .name[KMALLOC_RANDOM_START +  4] = "kmalloc-rnd-04-" #sz,
782 #define KMA_RAND_5(sz)  KMA_RAND_4(sz)  .name[KMALLOC_RANDOM_START +  5] = "kmalloc-rnd-05-" #sz,
783 #define KMA_RAND_6(sz)  KMA_RAND_5(sz)  .name[KMALLOC_RANDOM_START +  6] = "kmalloc-rnd-06-" #sz,
784 #define KMA_RAND_7(sz)  KMA_RAND_6(sz)  .name[KMALLOC_RANDOM_START +  7] = "kmalloc-rnd-07-" #sz,
785 #define KMA_RAND_8(sz)  KMA_RAND_7(sz)  .name[KMALLOC_RANDOM_START +  8] = "kmalloc-rnd-08-" #sz,
786 #define KMA_RAND_9(sz)  KMA_RAND_8(sz)  .name[KMALLOC_RANDOM_START +  9] = "kmalloc-rnd-09-" #sz,
787 #define KMA_RAND_10(sz) KMA_RAND_9(sz)  .name[KMALLOC_RANDOM_START + 10] = "kmalloc-rnd-10-" #sz,
788 #define KMA_RAND_11(sz) KMA_RAND_10(sz) .name[KMALLOC_RANDOM_START + 11] = "kmalloc-rnd-11-" #sz,
789 #define KMA_RAND_12(sz) KMA_RAND_11(sz) .name[KMALLOC_RANDOM_START + 12] = "kmalloc-rnd-12-" #sz,
790 #define KMA_RAND_13(sz) KMA_RAND_12(sz) .name[KMALLOC_RANDOM_START + 13] = "kmalloc-rnd-13-" #sz,
791 #define KMA_RAND_14(sz) KMA_RAND_13(sz) .name[KMALLOC_RANDOM_START + 14] = "kmalloc-rnd-14-" #sz,
792 #define KMA_RAND_15(sz) KMA_RAND_14(sz) .name[KMALLOC_RANDOM_START + 15] = "kmalloc-rnd-15-" #sz,
793 #else // CONFIG_RANDOM_KMALLOC_CACHES
794 #define KMALLOC_RANDOM_NAME(N, sz)
795 #endif
796 
797 #define INIT_KMALLOC_INFO(__size, __short_size)			\
798 {								\
799 	.name[KMALLOC_NORMAL]  = "kmalloc-" #__short_size,	\
800 	KMALLOC_RCL_NAME(__short_size)				\
801 	KMALLOC_CGROUP_NAME(__short_size)			\
802 	KMALLOC_DMA_NAME(__short_size)				\
803 	KMALLOC_RANDOM_NAME(RANDOM_KMALLOC_CACHES_NR, __short_size)	\
804 	.size = __size,						\
805 }
806 
807 /*
808  * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
809  * kmalloc_index() supports up to 2^21=2MB, so the final entry of the table is
810  * kmalloc-2M.
811  */
812 const struct kmalloc_info_struct kmalloc_info[] __initconst = {
813 	INIT_KMALLOC_INFO(0, 0),
814 	INIT_KMALLOC_INFO(96, 96),
815 	INIT_KMALLOC_INFO(192, 192),
816 	INIT_KMALLOC_INFO(8, 8),
817 	INIT_KMALLOC_INFO(16, 16),
818 	INIT_KMALLOC_INFO(32, 32),
819 	INIT_KMALLOC_INFO(64, 64),
820 	INIT_KMALLOC_INFO(128, 128),
821 	INIT_KMALLOC_INFO(256, 256),
822 	INIT_KMALLOC_INFO(512, 512),
823 	INIT_KMALLOC_INFO(1024, 1k),
824 	INIT_KMALLOC_INFO(2048, 2k),
825 	INIT_KMALLOC_INFO(4096, 4k),
826 	INIT_KMALLOC_INFO(8192, 8k),
827 	INIT_KMALLOC_INFO(16384, 16k),
828 	INIT_KMALLOC_INFO(32768, 32k),
829 	INIT_KMALLOC_INFO(65536, 64k),
830 	INIT_KMALLOC_INFO(131072, 128k),
831 	INIT_KMALLOC_INFO(262144, 256k),
832 	INIT_KMALLOC_INFO(524288, 512k),
833 	INIT_KMALLOC_INFO(1048576, 1M),
834 	INIT_KMALLOC_INFO(2097152, 2M)
835 };
836 
837 /*
838  * Patch up the size_index table if we have strange large alignment
839  * requirements for the kmalloc array. This is only the case for
840  * MIPS it seems. The standard arches will not generate any code here.
841  *
842  * Largest permitted alignment is 256 bytes due to the way we
843  * handle the index determination for the smaller caches.
844  *
845  * Make sure that nothing crazy happens if someone starts tinkering
846  * around with ARCH_KMALLOC_MINALIGN
847  */
setup_kmalloc_cache_index_table(void)848 void __init setup_kmalloc_cache_index_table(void)
849 {
850 	unsigned int i;
851 
852 	BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
853 		!is_power_of_2(KMALLOC_MIN_SIZE));
854 
855 	for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
856 		unsigned int elem = size_index_elem(i);
857 
858 		if (elem >= ARRAY_SIZE(size_index))
859 			break;
860 		size_index[elem] = KMALLOC_SHIFT_LOW;
861 	}
862 
863 	if (KMALLOC_MIN_SIZE >= 64) {
864 		/*
865 		 * The 96 byte sized cache is not used if the alignment
866 		 * is 64 byte.
867 		 */
868 		for (i = 64 + 8; i <= 96; i += 8)
869 			size_index[size_index_elem(i)] = 7;
870 
871 	}
872 
873 	if (KMALLOC_MIN_SIZE >= 128) {
874 		/*
875 		 * The 192 byte sized cache is not used if the alignment
876 		 * is 128 byte. Redirect kmalloc to use the 256 byte cache
877 		 * instead.
878 		 */
879 		for (i = 128 + 8; i <= 192; i += 8)
880 			size_index[size_index_elem(i)] = 8;
881 	}
882 }
883 
__kmalloc_minalign(void)884 static unsigned int __kmalloc_minalign(void)
885 {
886 	unsigned int minalign = dma_get_cache_alignment();
887 
888 	if (IS_ENABLED(CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC) &&
889 	    is_swiotlb_allocated())
890 		minalign = ARCH_KMALLOC_MINALIGN;
891 
892 	return max(minalign, arch_slab_minalign());
893 }
894 
895 void __init
new_kmalloc_cache(int idx,enum kmalloc_cache_type type,slab_flags_t flags)896 new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
897 {
898 	unsigned int minalign = __kmalloc_minalign();
899 	unsigned int aligned_size = kmalloc_info[idx].size;
900 	int aligned_idx = idx;
901 
902 	if ((KMALLOC_RECLAIM != KMALLOC_NORMAL) && (type == KMALLOC_RECLAIM)) {
903 		flags |= SLAB_RECLAIM_ACCOUNT;
904 	} else if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_CGROUP)) {
905 		if (mem_cgroup_kmem_disabled()) {
906 			kmalloc_caches[type][idx] = kmalloc_caches[KMALLOC_NORMAL][idx];
907 			return;
908 		}
909 		flags |= SLAB_ACCOUNT;
910 	} else if (IS_ENABLED(CONFIG_ZONE_DMA) && (type == KMALLOC_DMA)) {
911 		flags |= SLAB_CACHE_DMA;
912 	}
913 
914 #ifdef CONFIG_RANDOM_KMALLOC_CACHES
915 	if (type >= KMALLOC_RANDOM_START && type <= KMALLOC_RANDOM_END)
916 		flags |= SLAB_NO_MERGE;
917 #endif
918 
919 	/*
920 	 * If CONFIG_MEMCG_KMEM is enabled, disable cache merging for
921 	 * KMALLOC_NORMAL caches.
922 	 */
923 	if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_NORMAL))
924 		flags |= SLAB_NO_MERGE;
925 
926 	if (minalign > ARCH_KMALLOC_MINALIGN) {
927 		aligned_size = ALIGN(aligned_size, minalign);
928 		aligned_idx = __kmalloc_index(aligned_size, false);
929 	}
930 
931 	if (!kmalloc_caches[type][aligned_idx])
932 		kmalloc_caches[type][aligned_idx] = create_kmalloc_cache(
933 					kmalloc_info[aligned_idx].name[type],
934 					aligned_size, flags);
935 	if (idx != aligned_idx)
936 		kmalloc_caches[type][idx] = kmalloc_caches[type][aligned_idx];
937 }
938 
939 /*
940  * Create the kmalloc array. Some of the regular kmalloc arrays
941  * may already have been created because they were needed to
942  * enable allocations for slab creation.
943  */
create_kmalloc_caches(slab_flags_t flags)944 void __init create_kmalloc_caches(slab_flags_t flags)
945 {
946 	int i;
947 	enum kmalloc_cache_type type;
948 
949 	/*
950 	 * Including KMALLOC_CGROUP if CONFIG_MEMCG_KMEM defined
951 	 */
952 	for (type = KMALLOC_NORMAL; type < NR_KMALLOC_TYPES; type++) {
953 		for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
954 			if (!kmalloc_caches[type][i])
955 				new_kmalloc_cache(i, type, flags);
956 
957 			/*
958 			 * Caches that are not of the two-to-the-power-of size.
959 			 * These have to be created immediately after the
960 			 * earlier power of two caches
961 			 */
962 			if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
963 					!kmalloc_caches[type][1])
964 				new_kmalloc_cache(1, type, flags);
965 			if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
966 					!kmalloc_caches[type][2])
967 				new_kmalloc_cache(2, type, flags);
968 		}
969 	}
970 #ifdef CONFIG_RANDOM_KMALLOC_CACHES
971 	random_kmalloc_seed = get_random_u64();
972 #endif
973 
974 	/* Kmalloc array is now usable */
975 	slab_state = UP;
976 }
977 
free_large_kmalloc(struct folio * folio,void * object)978 void free_large_kmalloc(struct folio *folio, void *object)
979 {
980 	unsigned int order = folio_order(folio);
981 
982 	if (WARN_ON_ONCE(order == 0))
983 		pr_warn_once("object pointer: 0x%p\n", object);
984 
985 	kmemleak_free(object);
986 	kasan_kfree_large(object);
987 	kmsan_kfree_large(object);
988 
989 	mod_lruvec_page_state(folio_page(folio, 0), NR_SLAB_UNRECLAIMABLE_B,
990 			      -(PAGE_SIZE << order));
991 	__free_pages(folio_page(folio, 0), order);
992 }
993 
994 static void *__kmalloc_large_node(size_t size, gfp_t flags, int node);
995 static __always_inline
__do_kmalloc_node(size_t size,gfp_t flags,int node,unsigned long caller)996 void *__do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
997 {
998 	struct kmem_cache *s;
999 	void *ret;
1000 
1001 	if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
1002 		ret = __kmalloc_large_node(size, flags, node);
1003 		trace_kmalloc(caller, ret, size,
1004 			      PAGE_SIZE << get_order(size), flags, node);
1005 		return ret;
1006 	}
1007 
1008 	s = kmalloc_slab(size, flags, caller);
1009 
1010 	if (unlikely(ZERO_OR_NULL_PTR(s)))
1011 		return s;
1012 
1013 	ret = __kmem_cache_alloc_node(s, flags, node, size, caller);
1014 	ret = kasan_kmalloc(s, ret, size, flags);
1015 	trace_kmalloc(caller, ret, size, s->size, flags, node);
1016 	return ret;
1017 }
1018 
__kmalloc_node(size_t size,gfp_t flags,int node)1019 void *__kmalloc_node(size_t size, gfp_t flags, int node)
1020 {
1021 	return __do_kmalloc_node(size, flags, node, _RET_IP_);
1022 }
1023 EXPORT_SYMBOL(__kmalloc_node);
1024 
__kmalloc(size_t size,gfp_t flags)1025 void *__kmalloc(size_t size, gfp_t flags)
1026 {
1027 	return __do_kmalloc_node(size, flags, NUMA_NO_NODE, _RET_IP_);
1028 }
1029 EXPORT_SYMBOL(__kmalloc);
1030 
__kmalloc_node_track_caller(size_t size,gfp_t flags,int node,unsigned long caller)1031 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
1032 				  int node, unsigned long caller)
1033 {
1034 	return __do_kmalloc_node(size, flags, node, caller);
1035 }
1036 EXPORT_SYMBOL(__kmalloc_node_track_caller);
1037 
1038 /**
1039  * kfree - free previously allocated memory
1040  * @object: pointer returned by kmalloc() or kmem_cache_alloc()
1041  *
1042  * If @object is NULL, no operation is performed.
1043  */
kfree(const void * object)1044 void kfree(const void *object)
1045 {
1046 	struct folio *folio;
1047 	struct slab *slab;
1048 	struct kmem_cache *s;
1049 
1050 	trace_kfree(_RET_IP_, object);
1051 
1052 	if (unlikely(ZERO_OR_NULL_PTR(object)))
1053 		return;
1054 
1055 	folio = virt_to_folio(object);
1056 	if (unlikely(!folio_test_slab(folio))) {
1057 		free_large_kmalloc(folio, (void *)object);
1058 		return;
1059 	}
1060 
1061 	slab = folio_slab(folio);
1062 	s = slab->slab_cache;
1063 	__kmem_cache_free(s, (void *)object, _RET_IP_);
1064 }
1065 EXPORT_SYMBOL(kfree);
1066 
1067 /**
1068  * __ksize -- Report full size of underlying allocation
1069  * @object: pointer to the object
1070  *
1071  * This should only be used internally to query the true size of allocations.
1072  * It is not meant to be a way to discover the usable size of an allocation
1073  * after the fact. Instead, use kmalloc_size_roundup(). Using memory beyond
1074  * the originally requested allocation size may trigger KASAN, UBSAN_BOUNDS,
1075  * and/or FORTIFY_SOURCE.
1076  *
1077  * Return: size of the actual memory used by @object in bytes
1078  */
__ksize(const void * object)1079 size_t __ksize(const void *object)
1080 {
1081 	struct folio *folio;
1082 
1083 	if (unlikely(object == ZERO_SIZE_PTR))
1084 		return 0;
1085 
1086 	folio = virt_to_folio(object);
1087 
1088 	if (unlikely(!folio_test_slab(folio))) {
1089 		if (WARN_ON(folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE))
1090 			return 0;
1091 		if (WARN_ON(object != folio_address(folio)))
1092 			return 0;
1093 		return folio_size(folio);
1094 	}
1095 
1096 #ifdef CONFIG_SLUB_DEBUG
1097 	skip_orig_size_check(folio_slab(folio)->slab_cache, object);
1098 #endif
1099 
1100 	return slab_ksize(folio_slab(folio)->slab_cache);
1101 }
1102 
kmalloc_trace(struct kmem_cache * s,gfp_t gfpflags,size_t size)1103 void *kmalloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
1104 {
1105 	void *ret = __kmem_cache_alloc_node(s, gfpflags, NUMA_NO_NODE,
1106 					    size, _RET_IP_);
1107 
1108 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
1109 
1110 	ret = kasan_kmalloc(s, ret, size, gfpflags);
1111 	return ret;
1112 }
1113 EXPORT_SYMBOL(kmalloc_trace);
1114 
kmalloc_node_trace(struct kmem_cache * s,gfp_t gfpflags,int node,size_t size)1115 void *kmalloc_node_trace(struct kmem_cache *s, gfp_t gfpflags,
1116 			 int node, size_t size)
1117 {
1118 	void *ret = __kmem_cache_alloc_node(s, gfpflags, node, size, _RET_IP_);
1119 
1120 	trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
1121 
1122 	ret = kasan_kmalloc(s, ret, size, gfpflags);
1123 	return ret;
1124 }
1125 EXPORT_SYMBOL(kmalloc_node_trace);
1126 
kmalloc_fix_flags(gfp_t flags)1127 gfp_t kmalloc_fix_flags(gfp_t flags)
1128 {
1129 	gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
1130 
1131 	flags &= ~GFP_SLAB_BUG_MASK;
1132 	pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
1133 			invalid_mask, &invalid_mask, flags, &flags);
1134 	dump_stack();
1135 
1136 	return flags;
1137 }
1138 
1139 /*
1140  * To avoid unnecessary overhead, we pass through large allocation requests
1141  * directly to the page allocator. We use __GFP_COMP, because we will need to
1142  * know the allocation order to free the pages properly in kfree.
1143  */
1144 
__kmalloc_large_node(size_t size,gfp_t flags,int node)1145 static void *__kmalloc_large_node(size_t size, gfp_t flags, int node)
1146 {
1147 	struct page *page;
1148 	void *ptr = NULL;
1149 	unsigned int order = get_order(size);
1150 
1151 	if (unlikely(flags & GFP_SLAB_BUG_MASK))
1152 		flags = kmalloc_fix_flags(flags);
1153 
1154 	flags |= __GFP_COMP;
1155 	page = alloc_pages_node(node, flags, order);
1156 	if (page) {
1157 		ptr = page_address(page);
1158 		mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
1159 				      PAGE_SIZE << order);
1160 	}
1161 
1162 	trace_android_vh_kmalloc_large_alloced(page, order, flags);
1163 
1164 	ptr = kasan_kmalloc_large(ptr, size, flags);
1165 	/* As ptr might get tagged, call kmemleak hook after KASAN. */
1166 	kmemleak_alloc(ptr, size, 1, flags);
1167 	kmsan_kmalloc_large(ptr, size, flags);
1168 
1169 	return ptr;
1170 }
1171 
kmalloc_large(size_t size,gfp_t flags)1172 void *kmalloc_large(size_t size, gfp_t flags)
1173 {
1174 	void *ret = __kmalloc_large_node(size, flags, NUMA_NO_NODE);
1175 
1176 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
1177 		      flags, NUMA_NO_NODE);
1178 	return ret;
1179 }
1180 EXPORT_SYMBOL(kmalloc_large);
1181 
kmalloc_large_node(size_t size,gfp_t flags,int node)1182 void *kmalloc_large_node(size_t size, gfp_t flags, int node)
1183 {
1184 	void *ret = __kmalloc_large_node(size, flags, node);
1185 
1186 	trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
1187 		      flags, node);
1188 	return ret;
1189 }
1190 EXPORT_SYMBOL(kmalloc_large_node);
1191 
1192 #ifdef CONFIG_SLAB_FREELIST_RANDOM
1193 /* Randomize a generic freelist */
freelist_randomize(unsigned int * list,unsigned int count)1194 static void freelist_randomize(unsigned int *list,
1195 			       unsigned int count)
1196 {
1197 	unsigned int rand;
1198 	unsigned int i;
1199 
1200 	for (i = 0; i < count; i++)
1201 		list[i] = i;
1202 
1203 	/* Fisher-Yates shuffle */
1204 	for (i = count - 1; i > 0; i--) {
1205 		rand = get_random_u32_below(i + 1);
1206 		swap(list[i], list[rand]);
1207 	}
1208 }
1209 
1210 /* Create a random sequence per cache */
cache_random_seq_create(struct kmem_cache * cachep,unsigned int count,gfp_t gfp)1211 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1212 				    gfp_t gfp)
1213 {
1214 
1215 	if (count < 2 || cachep->random_seq)
1216 		return 0;
1217 
1218 	cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1219 	if (!cachep->random_seq)
1220 		return -ENOMEM;
1221 
1222 	freelist_randomize(cachep->random_seq, count);
1223 	return 0;
1224 }
1225 
1226 /* Destroy the per-cache random freelist sequence */
cache_random_seq_destroy(struct kmem_cache * cachep)1227 void cache_random_seq_destroy(struct kmem_cache *cachep)
1228 {
1229 	kfree(cachep->random_seq);
1230 	cachep->random_seq = NULL;
1231 }
1232 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
1233 
1234 #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1235 #ifdef CONFIG_SLAB
1236 #define SLABINFO_RIGHTS (0600)
1237 #else
1238 #define SLABINFO_RIGHTS (0400)
1239 #endif
1240 
print_slabinfo_header(struct seq_file * m)1241 static void print_slabinfo_header(struct seq_file *m)
1242 {
1243 	/*
1244 	 * Output format version, so at least we can change it
1245 	 * without _too_ many complaints.
1246 	 */
1247 #ifdef CONFIG_DEBUG_SLAB
1248 	seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1249 #else
1250 	seq_puts(m, "slabinfo - version: 2.1\n");
1251 #endif
1252 	seq_puts(m, "# name            <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1253 	seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1254 	seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1255 #ifdef CONFIG_DEBUG_SLAB
1256 	seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1257 	seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1258 #endif
1259 	trace_android_vh_print_slabinfo_header(m);
1260 	seq_putc(m, '\n');
1261 }
1262 
slab_start(struct seq_file * m,loff_t * pos)1263 static void *slab_start(struct seq_file *m, loff_t *pos)
1264 {
1265 	mutex_lock(&slab_mutex);
1266 	return seq_list_start(&slab_caches, *pos);
1267 }
1268 
slab_next(struct seq_file * m,void * p,loff_t * pos)1269 static void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1270 {
1271 	return seq_list_next(p, &slab_caches, pos);
1272 }
1273 
slab_stop(struct seq_file * m,void * p)1274 static void slab_stop(struct seq_file *m, void *p)
1275 {
1276 	mutex_unlock(&slab_mutex);
1277 }
1278 
cache_show(struct kmem_cache * s,struct seq_file * m)1279 static void cache_show(struct kmem_cache *s, struct seq_file *m)
1280 {
1281 	struct slabinfo sinfo;
1282 
1283 	memset(&sinfo, 0, sizeof(sinfo));
1284 	get_slabinfo(s, &sinfo);
1285 
1286 	seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
1287 		   s->name, sinfo.active_objs, sinfo.num_objs, s->size,
1288 		   sinfo.objects_per_slab, (1 << sinfo.cache_order));
1289 
1290 	seq_printf(m, " : tunables %4u %4u %4u",
1291 		   sinfo.limit, sinfo.batchcount, sinfo.shared);
1292 	seq_printf(m, " : slabdata %6lu %6lu %6lu",
1293 		   sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1294 	slabinfo_show_stats(m, s);
1295 	trace_android_vh_cache_show(m, &sinfo, s);
1296 	seq_putc(m, '\n');
1297 }
1298 
slab_show(struct seq_file * m,void * p)1299 static int slab_show(struct seq_file *m, void *p)
1300 {
1301 	struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1302 
1303 	if (p == slab_caches.next)
1304 		print_slabinfo_header(m);
1305 	cache_show(s, m);
1306 	return 0;
1307 }
1308 
dump_unreclaimable_slab(void)1309 void dump_unreclaimable_slab(void)
1310 {
1311 	struct kmem_cache *s;
1312 	struct slabinfo sinfo;
1313 
1314 	/*
1315 	 * Here acquiring slab_mutex is risky since we don't prefer to get
1316 	 * sleep in oom path. But, without mutex hold, it may introduce a
1317 	 * risk of crash.
1318 	 * Use mutex_trylock to protect the list traverse, dump nothing
1319 	 * without acquiring the mutex.
1320 	 */
1321 	if (!mutex_trylock(&slab_mutex)) {
1322 		pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1323 		return;
1324 	}
1325 
1326 	pr_info("Unreclaimable slab info:\n");
1327 	pr_info("Name                      Used          Total\n");
1328 
1329 	list_for_each_entry(s, &slab_caches, list) {
1330 		if (s->flags & SLAB_RECLAIM_ACCOUNT)
1331 			continue;
1332 
1333 		get_slabinfo(s, &sinfo);
1334 
1335 		if (sinfo.num_objs > 0)
1336 			pr_info("%-17s %10luKB %10luKB\n", s->name,
1337 				(sinfo.active_objs * s->size) / 1024,
1338 				(sinfo.num_objs * s->size) / 1024);
1339 	}
1340 	mutex_unlock(&slab_mutex);
1341 }
1342 
1343 /*
1344  * slabinfo_op - iterator that generates /proc/slabinfo
1345  *
1346  * Output layout:
1347  * cache-name
1348  * num-active-objs
1349  * total-objs
1350  * object size
1351  * num-active-slabs
1352  * total-slabs
1353  * num-pages-per-slab
1354  * + further values on SMP and with statistics enabled
1355  */
1356 static const struct seq_operations slabinfo_op = {
1357 	.start = slab_start,
1358 	.next = slab_next,
1359 	.stop = slab_stop,
1360 	.show = slab_show,
1361 };
1362 
slabinfo_open(struct inode * inode,struct file * file)1363 static int slabinfo_open(struct inode *inode, struct file *file)
1364 {
1365 	return seq_open(file, &slabinfo_op);
1366 }
1367 
1368 static const struct proc_ops slabinfo_proc_ops = {
1369 	.proc_flags	= PROC_ENTRY_PERMANENT,
1370 	.proc_open	= slabinfo_open,
1371 	.proc_read	= seq_read,
1372 	.proc_write	= slabinfo_write,
1373 	.proc_lseek	= seq_lseek,
1374 	.proc_release	= seq_release,
1375 };
1376 
slab_proc_init(void)1377 static int __init slab_proc_init(void)
1378 {
1379 	proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1380 	return 0;
1381 }
1382 module_init(slab_proc_init);
1383 
1384 #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1385 
1386 static __always_inline __realloc_size(2) void *
__do_krealloc(const void * p,size_t new_size,gfp_t flags)1387 __do_krealloc(const void *p, size_t new_size, gfp_t flags)
1388 {
1389 	void *ret;
1390 	size_t ks;
1391 
1392 	/* Check for double-free before calling ksize. */
1393 	if (likely(!ZERO_OR_NULL_PTR(p))) {
1394 		if (!kasan_check_byte(p))
1395 			return NULL;
1396 		ks = ksize(p);
1397 	} else
1398 		ks = 0;
1399 
1400 	/* If the object still fits, repoison it precisely. */
1401 	if (ks >= new_size) {
1402 		p = kasan_krealloc((void *)p, new_size, flags);
1403 		return (void *)p;
1404 	}
1405 
1406 	ret = kmalloc_track_caller(new_size, flags);
1407 	if (ret && p) {
1408 		/* Disable KASAN checks as the object's redzone is accessed. */
1409 		kasan_disable_current();
1410 		memcpy(ret, kasan_reset_tag(p), ks);
1411 		kasan_enable_current();
1412 	}
1413 
1414 	return ret;
1415 }
1416 
1417 /**
1418  * krealloc - reallocate memory. The contents will remain unchanged.
1419  * @p: object to reallocate memory for.
1420  * @new_size: how many bytes of memory are required.
1421  * @flags: the type of memory to allocate.
1422  *
1423  * The contents of the object pointed to are preserved up to the
1424  * lesser of the new and old sizes (__GFP_ZERO flag is effectively ignored).
1425  * If @p is %NULL, krealloc() behaves exactly like kmalloc().  If @new_size
1426  * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
1427  *
1428  * Return: pointer to the allocated memory or %NULL in case of error
1429  */
krealloc(const void * p,size_t new_size,gfp_t flags)1430 void *krealloc(const void *p, size_t new_size, gfp_t flags)
1431 {
1432 	void *ret;
1433 
1434 	if (unlikely(!new_size)) {
1435 		kfree(p);
1436 		return ZERO_SIZE_PTR;
1437 	}
1438 
1439 	ret = __do_krealloc(p, new_size, flags);
1440 	if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1441 		kfree(p);
1442 
1443 	return ret;
1444 }
1445 EXPORT_SYMBOL(krealloc);
1446 
1447 /**
1448  * kfree_sensitive - Clear sensitive information in memory before freeing
1449  * @p: object to free memory of
1450  *
1451  * The memory of the object @p points to is zeroed before freed.
1452  * If @p is %NULL, kfree_sensitive() does nothing.
1453  *
1454  * Note: this function zeroes the whole allocated buffer which can be a good
1455  * deal bigger than the requested buffer size passed to kmalloc(). So be
1456  * careful when using this function in performance sensitive code.
1457  */
kfree_sensitive(const void * p)1458 void kfree_sensitive(const void *p)
1459 {
1460 	size_t ks;
1461 	void *mem = (void *)p;
1462 
1463 	ks = ksize(mem);
1464 	if (ks) {
1465 		kasan_unpoison_range(mem, ks);
1466 		memzero_explicit(mem, ks);
1467 	}
1468 	kfree(mem);
1469 }
1470 EXPORT_SYMBOL(kfree_sensitive);
1471 
ksize(const void * objp)1472 size_t ksize(const void *objp)
1473 {
1474 	/*
1475 	 * We need to first check that the pointer to the object is valid.
1476 	 * The KASAN report printed from ksize() is more useful, then when
1477 	 * it's printed later when the behaviour could be undefined due to
1478 	 * a potential use-after-free or double-free.
1479 	 *
1480 	 * We use kasan_check_byte(), which is supported for the hardware
1481 	 * tag-based KASAN mode, unlike kasan_check_read/write().
1482 	 *
1483 	 * If the pointed to memory is invalid, we return 0 to avoid users of
1484 	 * ksize() writing to and potentially corrupting the memory region.
1485 	 *
1486 	 * We want to perform the check before __ksize(), to avoid potentially
1487 	 * crashing in __ksize() due to accessing invalid metadata.
1488 	 */
1489 	if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
1490 		return 0;
1491 
1492 	return kfence_ksize(objp) ?: __ksize(objp);
1493 }
1494 EXPORT_SYMBOL(ksize);
1495 
1496 /* Tracepoints definitions. */
1497 EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1498 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1499 EXPORT_TRACEPOINT_SYMBOL(kfree);
1500 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
1501 
should_failslab(struct kmem_cache * s,gfp_t gfpflags)1502 int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
1503 {
1504 	if (__should_failslab(s, gfpflags))
1505 		return -ENOMEM;
1506 	return 0;
1507 }
1508 ALLOW_ERROR_INJECTION(should_failslab, ERRNO);
1509