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