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