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