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