]> git.ipfire.org Git - thirdparty/kernel/stable.git/blame - mm/slab_common.c
slab: use 32-bit arithmetic in freelist_randomize()
[thirdparty/kernel/stable.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
CL
14#include <linux/compiler.h>
15#include <linux/module.h>
20cea968
CL
16#include <linux/cpu.h>
17#include <linux/uaccess.h>
b7454ad3
GC
18#include <linux/seq_file.h>
19#include <linux/proc_fs.h>
039363f3
CL
20#include <asm/cacheflush.h>
21#include <asm/tlbflush.h>
22#include <asm/page.h>
2633d7a0 23#include <linux/memcontrol.h>
928cec9c
AR
24
25#define CREATE_TRACE_POINTS
f1b6eb6e 26#include <trace/events/kmem.h>
039363f3 27
97d06609
CL
28#include "slab.h"
29
30enum slab_state slab_state;
18004c5d
CL
31LIST_HEAD(slab_caches);
32DEFINE_MUTEX(slab_mutex);
9b030cb8 33struct kmem_cache *kmem_cache;
97d06609 34
2d891fbc
KC
35#ifdef CONFIG_HARDENED_USERCOPY
36bool usercopy_fallback __ro_after_init =
37 IS_ENABLED(CONFIG_HARDENED_USERCOPY_FALLBACK);
38module_param(usercopy_fallback, bool, 0400);
39MODULE_PARM_DESC(usercopy_fallback,
40 "WARN instead of reject usercopy whitelist violations");
41#endif
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 | \
7ed2f9e6 53 SLAB_FAILSLAB | SLAB_KASAN)
423c929c 54
230e9fc2 55#define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
75f296d9 56 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
69#ifdef CONFIG_SLUB
70__setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
71#endif
72
73__setup("slab_nomerge", setup_slab_nomerge);
74
07f361b2
JK
75/*
76 * Determine the size of a slab object
77 */
78unsigned int kmem_cache_size(struct kmem_cache *s)
79{
80 return s->object_size;
81}
82EXPORT_SYMBOL(kmem_cache_size);
83
77be4b13 84#ifdef CONFIG_DEBUG_VM
f4957d5b 85static int kmem_cache_sanity_check(const char *name, unsigned int size)
039363f3
CL
86{
87 struct kmem_cache *s = NULL;
88
039363f3
CL
89 if (!name || in_interrupt() || size < sizeof(void *) ||
90 size > KMALLOC_MAX_SIZE) {
77be4b13
SK
91 pr_err("kmem_cache_create(%s) integrity check failed\n", name);
92 return -EINVAL;
039363f3 93 }
b920536a 94
20cea968
CL
95 list_for_each_entry(s, &slab_caches, list) {
96 char tmp;
97 int res;
98
99 /*
100 * This happens when the module gets unloaded and doesn't
101 * destroy its slab cache and no-one else reuses the vmalloc
102 * area of the module. Print a warning.
103 */
104 res = probe_kernel_address(s->name, tmp);
105 if (res) {
1b473f29 106 pr_err("Slab cache with size %u has lost its name\n",
20cea968
CL
107 s->object_size);
108 continue;
109 }
20cea968
CL
110 }
111
112 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
77be4b13
SK
113 return 0;
114}
115#else
f4957d5b 116static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
77be4b13
SK
117{
118 return 0;
119}
20cea968
CL
120#endif
121
484748f0
CL
122void __kmem_cache_free_bulk(struct kmem_cache *s, size_t nr, void **p)
123{
124 size_t i;
125
ca257195
JDB
126 for (i = 0; i < nr; i++) {
127 if (s)
128 kmem_cache_free(s, p[i]);
129 else
130 kfree(p[i]);
131 }
484748f0
CL
132}
133
865762a8 134int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t nr,
484748f0
CL
135 void **p)
136{
137 size_t i;
138
139 for (i = 0; i < nr; i++) {
140 void *x = p[i] = kmem_cache_alloc(s, flags);
141 if (!x) {
142 __kmem_cache_free_bulk(s, i, p);
865762a8 143 return 0;
484748f0
CL
144 }
145 }
865762a8 146 return i;
484748f0
CL
147}
148
127424c8 149#if defined(CONFIG_MEMCG) && !defined(CONFIG_SLOB)
510ded33
TH
150
151LIST_HEAD(slab_root_caches);
152
f7ce3190 153void slab_init_memcg_params(struct kmem_cache *s)
33a690c4 154{
9eeadc8b 155 s->memcg_params.root_cache = NULL;
f7ce3190 156 RCU_INIT_POINTER(s->memcg_params.memcg_caches, NULL);
9eeadc8b 157 INIT_LIST_HEAD(&s->memcg_params.children);
f7ce3190
VD
158}
159
160static int init_memcg_params(struct kmem_cache *s,
161 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
162{
163 struct memcg_cache_array *arr;
33a690c4 164
9eeadc8b 165 if (root_cache) {
f7ce3190 166 s->memcg_params.root_cache = root_cache;
9eeadc8b
TH
167 s->memcg_params.memcg = memcg;
168 INIT_LIST_HEAD(&s->memcg_params.children_node);
bc2791f8 169 INIT_LIST_HEAD(&s->memcg_params.kmem_caches_node);
33a690c4 170 return 0;
f7ce3190 171 }
33a690c4 172
f7ce3190 173 slab_init_memcg_params(s);
33a690c4 174
f7ce3190
VD
175 if (!memcg_nr_cache_ids)
176 return 0;
33a690c4 177
f80c7dab
JW
178 arr = kvzalloc(sizeof(struct memcg_cache_array) +
179 memcg_nr_cache_ids * sizeof(void *),
180 GFP_KERNEL);
f7ce3190
VD
181 if (!arr)
182 return -ENOMEM;
33a690c4 183
f7ce3190 184 RCU_INIT_POINTER(s->memcg_params.memcg_caches, arr);
33a690c4
VD
185 return 0;
186}
187
f7ce3190 188static void destroy_memcg_params(struct kmem_cache *s)
33a690c4 189{
f7ce3190 190 if (is_root_cache(s))
f80c7dab
JW
191 kvfree(rcu_access_pointer(s->memcg_params.memcg_caches));
192}
193
194static void free_memcg_params(struct rcu_head *rcu)
195{
196 struct memcg_cache_array *old;
197
198 old = container_of(rcu, struct memcg_cache_array, rcu);
199 kvfree(old);
33a690c4
VD
200}
201
f7ce3190 202static int update_memcg_params(struct kmem_cache *s, int new_array_size)
6f817f4c 203{
f7ce3190 204 struct memcg_cache_array *old, *new;
6f817f4c 205
f80c7dab
JW
206 new = kvzalloc(sizeof(struct memcg_cache_array) +
207 new_array_size * sizeof(void *), GFP_KERNEL);
f7ce3190 208 if (!new)
6f817f4c
VD
209 return -ENOMEM;
210
f7ce3190
VD
211 old = rcu_dereference_protected(s->memcg_params.memcg_caches,
212 lockdep_is_held(&slab_mutex));
213 if (old)
214 memcpy(new->entries, old->entries,
215 memcg_nr_cache_ids * sizeof(void *));
6f817f4c 216
f7ce3190
VD
217 rcu_assign_pointer(s->memcg_params.memcg_caches, new);
218 if (old)
f80c7dab 219 call_rcu(&old->rcu, free_memcg_params);
6f817f4c
VD
220 return 0;
221}
222
55007d84
GC
223int memcg_update_all_caches(int num_memcgs)
224{
225 struct kmem_cache *s;
226 int ret = 0;
55007d84 227
05257a1a 228 mutex_lock(&slab_mutex);
510ded33 229 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
f7ce3190 230 ret = update_memcg_params(s, num_memcgs);
55007d84 231 /*
55007d84
GC
232 * Instead of freeing the memory, we'll just leave the caches
233 * up to this point in an updated state.
234 */
235 if (ret)
05257a1a 236 break;
55007d84 237 }
55007d84
GC
238 mutex_unlock(&slab_mutex);
239 return ret;
240}
657dc2f9 241
510ded33 242void memcg_link_cache(struct kmem_cache *s)
657dc2f9 243{
510ded33
TH
244 if (is_root_cache(s)) {
245 list_add(&s->root_caches_node, &slab_root_caches);
246 } else {
247 list_add(&s->memcg_params.children_node,
248 &s->memcg_params.root_cache->memcg_params.children);
249 list_add(&s->memcg_params.kmem_caches_node,
250 &s->memcg_params.memcg->kmem_caches);
251 }
252}
253
254static void memcg_unlink_cache(struct kmem_cache *s)
255{
256 if (is_root_cache(s)) {
257 list_del(&s->root_caches_node);
258 } else {
259 list_del(&s->memcg_params.children_node);
260 list_del(&s->memcg_params.kmem_caches_node);
261 }
657dc2f9 262}
33a690c4 263#else
f7ce3190
VD
264static inline int init_memcg_params(struct kmem_cache *s,
265 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
33a690c4
VD
266{
267 return 0;
268}
269
f7ce3190 270static inline void destroy_memcg_params(struct kmem_cache *s)
33a690c4
VD
271{
272}
657dc2f9 273
510ded33 274static inline void memcg_unlink_cache(struct kmem_cache *s)
657dc2f9
TH
275{
276}
127424c8 277#endif /* CONFIG_MEMCG && !CONFIG_SLOB */
55007d84 278
692ae74a
BL
279/*
280 * Figure out what the alignment of the objects will be given a set of
281 * flags, a user specified alignment and the size of the objects.
282 */
f4957d5b
AD
283static unsigned int calculate_alignment(slab_flags_t flags,
284 unsigned int align, unsigned int size)
692ae74a
BL
285{
286 /*
287 * If the user wants hardware cache aligned objects then follow that
288 * suggestion if the object is sufficiently large.
289 *
290 * The hardware cache alignment cannot override the specified
291 * alignment though. If that is greater then use it.
292 */
293 if (flags & SLAB_HWCACHE_ALIGN) {
f4957d5b 294 unsigned int ralign;
692ae74a
BL
295
296 ralign = cache_line_size();
297 while (size <= ralign / 2)
298 ralign /= 2;
299 align = max(align, ralign);
300 }
301
302 if (align < ARCH_SLAB_MINALIGN)
303 align = ARCH_SLAB_MINALIGN;
304
305 return ALIGN(align, sizeof(void *));
306}
307
423c929c
JK
308/*
309 * Find a mergeable slab cache
310 */
311int slab_unmergeable(struct kmem_cache *s)
312{
313 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
314 return 1;
315
316 if (!is_root_cache(s))
317 return 1;
318
319 if (s->ctor)
320 return 1;
321
8eb8284b
DW
322 if (s->usersize)
323 return 1;
324
423c929c
JK
325 /*
326 * We may have set a slab to be unmergeable during bootstrap.
327 */
328 if (s->refcount < 0)
329 return 1;
330
331 return 0;
332}
333
f4957d5b 334struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
d50112ed 335 slab_flags_t flags, const char *name, void (*ctor)(void *))
423c929c
JK
336{
337 struct kmem_cache *s;
338
c6e28895 339 if (slab_nomerge)
423c929c
JK
340 return NULL;
341
342 if (ctor)
343 return NULL;
344
345 size = ALIGN(size, sizeof(void *));
346 align = calculate_alignment(flags, align, size);
347 size = ALIGN(size, align);
348 flags = kmem_cache_flags(size, flags, name, NULL);
349
c6e28895
GM
350 if (flags & SLAB_NEVER_MERGE)
351 return NULL;
352
510ded33 353 list_for_each_entry_reverse(s, &slab_root_caches, root_caches_node) {
423c929c
JK
354 if (slab_unmergeable(s))
355 continue;
356
357 if (size > s->size)
358 continue;
359
360 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
361 continue;
362 /*
363 * Check if alignment is compatible.
364 * Courtesy of Adrian Drzewiecki
365 */
366 if ((s->size & ~(align - 1)) != s->size)
367 continue;
368
369 if (s->size - size >= sizeof(void *))
370 continue;
371
95069ac8
JK
372 if (IS_ENABLED(CONFIG_SLAB) && align &&
373 (align > s->align || s->align % align))
374 continue;
375
423c929c
JK
376 return s;
377 }
378 return NULL;
379}
380
c9a77a79 381static struct kmem_cache *create_cache(const char *name,
f4957d5b 382 unsigned int object_size, unsigned int size, unsigned int align,
7bbdb81e
AD
383 slab_flags_t flags, unsigned int useroffset,
384 unsigned int usersize, void (*ctor)(void *),
c9a77a79 385 struct mem_cgroup *memcg, struct kmem_cache *root_cache)
794b1248
VD
386{
387 struct kmem_cache *s;
388 int err;
389
8eb8284b
DW
390 if (WARN_ON(useroffset + usersize > object_size))
391 useroffset = usersize = 0;
392
794b1248
VD
393 err = -ENOMEM;
394 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
395 if (!s)
396 goto out;
397
398 s->name = name;
399 s->object_size = object_size;
400 s->size = size;
401 s->align = align;
402 s->ctor = ctor;
8eb8284b
DW
403 s->useroffset = useroffset;
404 s->usersize = usersize;
794b1248 405
f7ce3190 406 err = init_memcg_params(s, memcg, root_cache);
794b1248
VD
407 if (err)
408 goto out_free_cache;
409
410 err = __kmem_cache_create(s, flags);
411 if (err)
412 goto out_free_cache;
413
414 s->refcount = 1;
415 list_add(&s->list, &slab_caches);
510ded33 416 memcg_link_cache(s);
794b1248
VD
417out:
418 if (err)
419 return ERR_PTR(err);
420 return s;
421
422out_free_cache:
f7ce3190 423 destroy_memcg_params(s);
7c4da061 424 kmem_cache_free(kmem_cache, s);
794b1248
VD
425 goto out;
426}
45906855 427
77be4b13 428/*
8eb8284b 429 * kmem_cache_create_usercopy - Create a cache.
77be4b13
SK
430 * @name: A string which is used in /proc/slabinfo to identify this cache.
431 * @size: The size of objects to be created in this cache.
432 * @align: The required alignment for the objects.
433 * @flags: SLAB flags
8eb8284b
DW
434 * @useroffset: Usercopy region offset
435 * @usersize: Usercopy region size
77be4b13
SK
436 * @ctor: A constructor for the objects.
437 *
438 * Returns a ptr to the cache on success, NULL on failure.
439 * Cannot be called within a interrupt, but can be interrupted.
440 * The @ctor is run when new pages are allocated by the cache.
441 *
442 * The flags are
443 *
444 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
445 * to catch references to uninitialised memory.
446 *
447 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
448 * for buffer overruns.
449 *
450 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
451 * cacheline. This can be beneficial if you're counting cycles as closely
452 * as davem.
453 */
2633d7a0 454struct kmem_cache *
f4957d5b
AD
455kmem_cache_create_usercopy(const char *name,
456 unsigned int size, unsigned int align,
7bbdb81e
AD
457 slab_flags_t flags,
458 unsigned int useroffset, unsigned int usersize,
8eb8284b 459 void (*ctor)(void *))
77be4b13 460{
40911a79 461 struct kmem_cache *s = NULL;
3dec16ea 462 const char *cache_name;
3965fc36 463 int err;
039363f3 464
77be4b13 465 get_online_cpus();
03afc0e2 466 get_online_mems();
05257a1a 467 memcg_get_cache_ids();
03afc0e2 468
77be4b13 469 mutex_lock(&slab_mutex);
686d550d 470
794b1248 471 err = kmem_cache_sanity_check(name, size);
3aa24f51 472 if (err) {
3965fc36 473 goto out_unlock;
3aa24f51 474 }
686d550d 475
e70954fd
TG
476 /* Refuse requests with allocator specific flags */
477 if (flags & ~SLAB_FLAGS_PERMITTED) {
478 err = -EINVAL;
479 goto out_unlock;
480 }
481
d8843922
GC
482 /*
483 * Some allocators will constraint the set of valid flags to a subset
484 * of all flags. We expect them to define CACHE_CREATE_MASK in this
485 * case, and we'll just provide them with a sanitized version of the
486 * passed flags.
487 */
488 flags &= CACHE_CREATE_MASK;
686d550d 489
8eb8284b
DW
490 /* Fail closed on bad usersize of useroffset values. */
491 if (WARN_ON(!usersize && useroffset) ||
492 WARN_ON(size < usersize || size - usersize < useroffset))
493 usersize = useroffset = 0;
494
495 if (!usersize)
496 s = __kmem_cache_alias(name, size, align, flags, ctor);
794b1248 497 if (s)
3965fc36 498 goto out_unlock;
2633d7a0 499
3dec16ea 500 cache_name = kstrdup_const(name, GFP_KERNEL);
794b1248
VD
501 if (!cache_name) {
502 err = -ENOMEM;
503 goto out_unlock;
504 }
7c9adf5a 505
c9a77a79
VD
506 s = create_cache(cache_name, size, size,
507 calculate_alignment(flags, align, size),
8eb8284b 508 flags, useroffset, usersize, ctor, NULL, NULL);
794b1248
VD
509 if (IS_ERR(s)) {
510 err = PTR_ERR(s);
3dec16ea 511 kfree_const(cache_name);
794b1248 512 }
3965fc36
VD
513
514out_unlock:
20cea968 515 mutex_unlock(&slab_mutex);
03afc0e2 516
05257a1a 517 memcg_put_cache_ids();
03afc0e2 518 put_online_mems();
20cea968
CL
519 put_online_cpus();
520
ba3253c7 521 if (err) {
686d550d
CL
522 if (flags & SLAB_PANIC)
523 panic("kmem_cache_create: Failed to create slab '%s'. Error %d\n",
524 name, err);
525 else {
1170532b 526 pr_warn("kmem_cache_create(%s) failed with error %d\n",
686d550d
CL
527 name, err);
528 dump_stack();
529 }
686d550d
CL
530 return NULL;
531 }
039363f3
CL
532 return s;
533}
8eb8284b
DW
534EXPORT_SYMBOL(kmem_cache_create_usercopy);
535
536struct kmem_cache *
f4957d5b 537kmem_cache_create(const char *name, unsigned int size, unsigned int align,
8eb8284b
DW
538 slab_flags_t flags, void (*ctor)(void *))
539{
6d07d1cd 540 return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
8eb8284b
DW
541 ctor);
542}
794b1248 543EXPORT_SYMBOL(kmem_cache_create);
2633d7a0 544
657dc2f9 545static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
d5b3cf71 546{
657dc2f9
TH
547 LIST_HEAD(to_destroy);
548 struct kmem_cache *s, *s2;
d5b3cf71 549
657dc2f9 550 /*
5f0d5a3a 551 * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
657dc2f9
TH
552 * @slab_caches_to_rcu_destroy list. The slab pages are freed
553 * through RCU and and the associated kmem_cache are dereferenced
554 * while freeing the pages, so the kmem_caches should be freed only
555 * after the pending RCU operations are finished. As rcu_barrier()
556 * is a pretty slow operation, we batch all pending destructions
557 * asynchronously.
558 */
559 mutex_lock(&slab_mutex);
560 list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
561 mutex_unlock(&slab_mutex);
d5b3cf71 562
657dc2f9
TH
563 if (list_empty(&to_destroy))
564 return;
565
566 rcu_barrier();
567
568 list_for_each_entry_safe(s, s2, &to_destroy, list) {
569#ifdef SLAB_SUPPORTS_SYSFS
570 sysfs_slab_release(s);
571#else
572 slab_kmem_cache_release(s);
573#endif
574 }
d5b3cf71
VD
575}
576
657dc2f9 577static int shutdown_cache(struct kmem_cache *s)
d5b3cf71 578{
f9fa1d91
GT
579 /* free asan quarantined objects */
580 kasan_cache_shutdown(s);
581
657dc2f9
TH
582 if (__kmem_cache_shutdown(s) != 0)
583 return -EBUSY;
d5b3cf71 584
510ded33 585 memcg_unlink_cache(s);
657dc2f9 586 list_del(&s->list);
d5b3cf71 587
5f0d5a3a 588 if (s->flags & SLAB_TYPESAFE_BY_RCU) {
657dc2f9
TH
589 list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
590 schedule_work(&slab_caches_to_rcu_destroy_work);
591 } else {
d5b3cf71 592#ifdef SLAB_SUPPORTS_SYSFS
bf5eb3de 593 sysfs_slab_release(s);
d5b3cf71
VD
594#else
595 slab_kmem_cache_release(s);
596#endif
597 }
657dc2f9
TH
598
599 return 0;
d5b3cf71
VD
600}
601
127424c8 602#if defined(CONFIG_MEMCG) && !defined(CONFIG_SLOB)
794b1248 603/*
776ed0f0 604 * memcg_create_kmem_cache - Create a cache for a memory cgroup.
794b1248
VD
605 * @memcg: The memory cgroup the new cache is for.
606 * @root_cache: The parent of the new cache.
607 *
608 * This function attempts to create a kmem cache that will serve allocation
609 * requests going from @memcg to @root_cache. The new cache inherits properties
610 * from its parent.
611 */
d5b3cf71
VD
612void memcg_create_kmem_cache(struct mem_cgroup *memcg,
613 struct kmem_cache *root_cache)
2633d7a0 614{
3e0350a3 615 static char memcg_name_buf[NAME_MAX + 1]; /* protected by slab_mutex */
33398cf2 616 struct cgroup_subsys_state *css = &memcg->css;
f7ce3190 617 struct memcg_cache_array *arr;
bd673145 618 struct kmem_cache *s = NULL;
794b1248 619 char *cache_name;
f7ce3190 620 int idx;
794b1248
VD
621
622 get_online_cpus();
03afc0e2
VD
623 get_online_mems();
624
794b1248
VD
625 mutex_lock(&slab_mutex);
626
2a4db7eb 627 /*
567e9ab2 628 * The memory cgroup could have been offlined while the cache
2a4db7eb
VD
629 * creation work was pending.
630 */
b6ecd2de 631 if (memcg->kmem_state != KMEM_ONLINE)
2a4db7eb
VD
632 goto out_unlock;
633
f7ce3190
VD
634 idx = memcg_cache_id(memcg);
635 arr = rcu_dereference_protected(root_cache->memcg_params.memcg_caches,
636 lockdep_is_held(&slab_mutex));
637
d5b3cf71
VD
638 /*
639 * Since per-memcg caches are created asynchronously on first
640 * allocation (see memcg_kmem_get_cache()), several threads can try to
641 * create the same cache, but only one of them may succeed.
642 */
f7ce3190 643 if (arr->entries[idx])
d5b3cf71
VD
644 goto out_unlock;
645
f1008365 646 cgroup_name(css->cgroup, memcg_name_buf, sizeof(memcg_name_buf));
73f576c0
JW
647 cache_name = kasprintf(GFP_KERNEL, "%s(%llu:%s)", root_cache->name,
648 css->serial_nr, memcg_name_buf);
794b1248
VD
649 if (!cache_name)
650 goto out_unlock;
651
c9a77a79
VD
652 s = create_cache(cache_name, root_cache->object_size,
653 root_cache->size, root_cache->align,
f773e36d 654 root_cache->flags & CACHE_CREATE_MASK,
8eb8284b 655 root_cache->useroffset, root_cache->usersize,
f773e36d 656 root_cache->ctor, memcg, root_cache);
d5b3cf71
VD
657 /*
658 * If we could not create a memcg cache, do not complain, because
659 * that's not critical at all as we can always proceed with the root
660 * cache.
661 */
bd673145 662 if (IS_ERR(s)) {
794b1248 663 kfree(cache_name);
d5b3cf71 664 goto out_unlock;
bd673145 665 }
794b1248 666
d5b3cf71
VD
667 /*
668 * Since readers won't lock (see cache_from_memcg_idx()), we need a
669 * barrier here to ensure nobody will see the kmem_cache partially
670 * initialized.
671 */
672 smp_wmb();
f7ce3190 673 arr->entries[idx] = s;
d5b3cf71 674
794b1248
VD
675out_unlock:
676 mutex_unlock(&slab_mutex);
03afc0e2
VD
677
678 put_online_mems();
794b1248 679 put_online_cpus();
2633d7a0 680}
b8529907 681
01fb58bc
TH
682static void kmemcg_deactivate_workfn(struct work_struct *work)
683{
684 struct kmem_cache *s = container_of(work, struct kmem_cache,
685 memcg_params.deact_work);
686
687 get_online_cpus();
688 get_online_mems();
689
690 mutex_lock(&slab_mutex);
691
692 s->memcg_params.deact_fn(s);
693
694 mutex_unlock(&slab_mutex);
695
696 put_online_mems();
697 put_online_cpus();
698
699 /* done, put the ref from slab_deactivate_memcg_cache_rcu_sched() */
700 css_put(&s->memcg_params.memcg->css);
701}
702
703static void kmemcg_deactivate_rcufn(struct rcu_head *head)
704{
705 struct kmem_cache *s = container_of(head, struct kmem_cache,
706 memcg_params.deact_rcu_head);
707
708 /*
709 * We need to grab blocking locks. Bounce to ->deact_work. The
710 * work item shares the space with the RCU head and can't be
711 * initialized eariler.
712 */
713 INIT_WORK(&s->memcg_params.deact_work, kmemcg_deactivate_workfn);
17cc4dfe 714 queue_work(memcg_kmem_cache_wq, &s->memcg_params.deact_work);
01fb58bc
TH
715}
716
717/**
718 * slab_deactivate_memcg_cache_rcu_sched - schedule deactivation after a
719 * sched RCU grace period
720 * @s: target kmem_cache
721 * @deact_fn: deactivation function to call
722 *
723 * Schedule @deact_fn to be invoked with online cpus, mems and slab_mutex
724 * held after a sched RCU grace period. The slab is guaranteed to stay
725 * alive until @deact_fn is finished. This is to be used from
726 * __kmemcg_cache_deactivate().
727 */
728void slab_deactivate_memcg_cache_rcu_sched(struct kmem_cache *s,
729 void (*deact_fn)(struct kmem_cache *))
730{
731 if (WARN_ON_ONCE(is_root_cache(s)) ||
732 WARN_ON_ONCE(s->memcg_params.deact_fn))
733 return;
734
735 /* pin memcg so that @s doesn't get destroyed in the middle */
736 css_get(&s->memcg_params.memcg->css);
737
738 s->memcg_params.deact_fn = deact_fn;
739 call_rcu_sched(&s->memcg_params.deact_rcu_head, kmemcg_deactivate_rcufn);
740}
741
2a4db7eb
VD
742void memcg_deactivate_kmem_caches(struct mem_cgroup *memcg)
743{
744 int idx;
745 struct memcg_cache_array *arr;
d6e0b7fa 746 struct kmem_cache *s, *c;
2a4db7eb
VD
747
748 idx = memcg_cache_id(memcg);
749
d6e0b7fa
VD
750 get_online_cpus();
751 get_online_mems();
752
2a4db7eb 753 mutex_lock(&slab_mutex);
510ded33 754 list_for_each_entry(s, &slab_root_caches, root_caches_node) {
2a4db7eb
VD
755 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
756 lockdep_is_held(&slab_mutex));
d6e0b7fa
VD
757 c = arr->entries[idx];
758 if (!c)
759 continue;
760
c9fc5864 761 __kmemcg_cache_deactivate(c);
2a4db7eb
VD
762 arr->entries[idx] = NULL;
763 }
764 mutex_unlock(&slab_mutex);
d6e0b7fa
VD
765
766 put_online_mems();
767 put_online_cpus();
2a4db7eb
VD
768}
769
d5b3cf71 770void memcg_destroy_kmem_caches(struct mem_cgroup *memcg)
b8529907 771{
d5b3cf71 772 struct kmem_cache *s, *s2;
b8529907 773
d5b3cf71
VD
774 get_online_cpus();
775 get_online_mems();
b8529907 776
b8529907 777 mutex_lock(&slab_mutex);
bc2791f8
TH
778 list_for_each_entry_safe(s, s2, &memcg->kmem_caches,
779 memcg_params.kmem_caches_node) {
d5b3cf71
VD
780 /*
781 * The cgroup is about to be freed and therefore has no charges
782 * left. Hence, all its caches must be empty by now.
783 */
657dc2f9 784 BUG_ON(shutdown_cache(s));
d5b3cf71
VD
785 }
786 mutex_unlock(&slab_mutex);
b8529907 787
d5b3cf71
VD
788 put_online_mems();
789 put_online_cpus();
b8529907 790}
d60fdcc9 791
657dc2f9 792static int shutdown_memcg_caches(struct kmem_cache *s)
d60fdcc9
VD
793{
794 struct memcg_cache_array *arr;
795 struct kmem_cache *c, *c2;
796 LIST_HEAD(busy);
797 int i;
798
799 BUG_ON(!is_root_cache(s));
800
801 /*
802 * First, shutdown active caches, i.e. caches that belong to online
803 * memory cgroups.
804 */
805 arr = rcu_dereference_protected(s->memcg_params.memcg_caches,
806 lockdep_is_held(&slab_mutex));
807 for_each_memcg_cache_index(i) {
808 c = arr->entries[i];
809 if (!c)
810 continue;
657dc2f9 811 if (shutdown_cache(c))
d60fdcc9
VD
812 /*
813 * The cache still has objects. Move it to a temporary
814 * list so as not to try to destroy it for a second
815 * time while iterating over inactive caches below.
816 */
9eeadc8b 817 list_move(&c->memcg_params.children_node, &busy);
d60fdcc9
VD
818 else
819 /*
820 * The cache is empty and will be destroyed soon. Clear
821 * the pointer to it in the memcg_caches array so that
822 * it will never be accessed even if the root cache
823 * stays alive.
824 */
825 arr->entries[i] = NULL;
826 }
827
828 /*
829 * Second, shutdown all caches left from memory cgroups that are now
830 * offline.
831 */
9eeadc8b
TH
832 list_for_each_entry_safe(c, c2, &s->memcg_params.children,
833 memcg_params.children_node)
657dc2f9 834 shutdown_cache(c);
d60fdcc9 835
9eeadc8b 836 list_splice(&busy, &s->memcg_params.children);
d60fdcc9
VD
837
838 /*
839 * A cache being destroyed must be empty. In particular, this means
840 * that all per memcg caches attached to it must be empty too.
841 */
9eeadc8b 842 if (!list_empty(&s->memcg_params.children))
d60fdcc9
VD
843 return -EBUSY;
844 return 0;
845}
846#else
657dc2f9 847static inline int shutdown_memcg_caches(struct kmem_cache *s)
d60fdcc9
VD
848{
849 return 0;
850}
127424c8 851#endif /* CONFIG_MEMCG && !CONFIG_SLOB */
97d06609 852
41a21285
CL
853void slab_kmem_cache_release(struct kmem_cache *s)
854{
52b4b950 855 __kmem_cache_release(s);
f7ce3190 856 destroy_memcg_params(s);
3dec16ea 857 kfree_const(s->name);
41a21285
CL
858 kmem_cache_free(kmem_cache, s);
859}
860
945cf2b6
CL
861void kmem_cache_destroy(struct kmem_cache *s)
862{
d60fdcc9 863 int err;
d5b3cf71 864
3942d299
SS
865 if (unlikely(!s))
866 return;
867
945cf2b6 868 get_online_cpus();
03afc0e2
VD
869 get_online_mems();
870
945cf2b6 871 mutex_lock(&slab_mutex);
b8529907 872
945cf2b6 873 s->refcount--;
b8529907
VD
874 if (s->refcount)
875 goto out_unlock;
876
657dc2f9 877 err = shutdown_memcg_caches(s);
d60fdcc9 878 if (!err)
657dc2f9 879 err = shutdown_cache(s);
b8529907 880
cd918c55 881 if (err) {
756a025f
JP
882 pr_err("kmem_cache_destroy %s: Slab cache still has objects\n",
883 s->name);
cd918c55
VD
884 dump_stack();
885 }
b8529907
VD
886out_unlock:
887 mutex_unlock(&slab_mutex);
d5b3cf71 888
03afc0e2 889 put_online_mems();
945cf2b6
CL
890 put_online_cpus();
891}
892EXPORT_SYMBOL(kmem_cache_destroy);
893
03afc0e2
VD
894/**
895 * kmem_cache_shrink - Shrink a cache.
896 * @cachep: The cache to shrink.
897 *
898 * Releases as many slabs as possible for a cache.
899 * To help debugging, a zero exit status indicates all slabs were released.
900 */
901int kmem_cache_shrink(struct kmem_cache *cachep)
902{
903 int ret;
904
905 get_online_cpus();
906 get_online_mems();
55834c59 907 kasan_cache_shrink(cachep);
c9fc5864 908 ret = __kmem_cache_shrink(cachep);
03afc0e2
VD
909 put_online_mems();
910 put_online_cpus();
911 return ret;
912}
913EXPORT_SYMBOL(kmem_cache_shrink);
914
fda90124 915bool slab_is_available(void)
97d06609
CL
916{
917 return slab_state >= UP;
918}
b7454ad3 919
45530c44
CL
920#ifndef CONFIG_SLOB
921/* Create a cache during boot when no slab services are available yet */
361d575e
AD
922void __init create_boot_cache(struct kmem_cache *s, const char *name,
923 unsigned int size, slab_flags_t flags,
924 unsigned int useroffset, unsigned int usersize)
45530c44
CL
925{
926 int err;
927
928 s->name = name;
929 s->size = s->object_size = size;
45906855 930 s->align = calculate_alignment(flags, ARCH_KMALLOC_MINALIGN, size);
8eb8284b
DW
931 s->useroffset = useroffset;
932 s->usersize = usersize;
f7ce3190
VD
933
934 slab_init_memcg_params(s);
935
45530c44
CL
936 err = __kmem_cache_create(s, flags);
937
938 if (err)
361d575e 939 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
45530c44
CL
940 name, size, err);
941
942 s->refcount = -1; /* Exempt from merging for now */
943}
944
55de8b9c
AD
945struct kmem_cache *__init create_kmalloc_cache(const char *name,
946 unsigned int size, slab_flags_t flags,
947 unsigned int useroffset, unsigned int usersize)
45530c44
CL
948{
949 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
950
951 if (!s)
952 panic("Out of memory when creating slab %s\n", name);
953
6c0c21ad 954 create_boot_cache(s, name, size, flags, useroffset, usersize);
45530c44 955 list_add(&s->list, &slab_caches);
510ded33 956 memcg_link_cache(s);
45530c44
CL
957 s->refcount = 1;
958 return s;
959}
960
1c99ba29 961struct kmem_cache *kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
9425c58e
CL
962EXPORT_SYMBOL(kmalloc_caches);
963
964#ifdef CONFIG_ZONE_DMA
1c99ba29 965struct kmem_cache *kmalloc_dma_caches[KMALLOC_SHIFT_HIGH + 1] __ro_after_init;
9425c58e
CL
966EXPORT_SYMBOL(kmalloc_dma_caches);
967#endif
968
2c59dd65
CL
969/*
970 * Conversion table for small slabs sizes / 8 to the index in the
971 * kmalloc array. This is necessary for slabs < 192 since we have non power
972 * of two cache sizes there. The size of larger slabs can be determined using
973 * fls.
974 */
d5f86655 975static u8 size_index[24] __ro_after_init = {
2c59dd65
CL
976 3, /* 8 */
977 4, /* 16 */
978 5, /* 24 */
979 5, /* 32 */
980 6, /* 40 */
981 6, /* 48 */
982 6, /* 56 */
983 6, /* 64 */
984 1, /* 72 */
985 1, /* 80 */
986 1, /* 88 */
987 1, /* 96 */
988 7, /* 104 */
989 7, /* 112 */
990 7, /* 120 */
991 7, /* 128 */
992 2, /* 136 */
993 2, /* 144 */
994 2, /* 152 */
995 2, /* 160 */
996 2, /* 168 */
997 2, /* 176 */
998 2, /* 184 */
999 2 /* 192 */
1000};
1001
ac914d08 1002static inline unsigned int size_index_elem(unsigned int bytes)
2c59dd65
CL
1003{
1004 return (bytes - 1) / 8;
1005}
1006
1007/*
1008 * Find the kmem_cache structure that serves a given size of
1009 * allocation
1010 */
1011struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags)
1012{
d5f86655 1013 unsigned int index;
2c59dd65 1014
9de1bc87 1015 if (unlikely(size > KMALLOC_MAX_SIZE)) {
907985f4 1016 WARN_ON_ONCE(!(flags & __GFP_NOWARN));
6286ae97 1017 return NULL;
907985f4 1018 }
6286ae97 1019
2c59dd65
CL
1020 if (size <= 192) {
1021 if (!size)
1022 return ZERO_SIZE_PTR;
1023
1024 index = size_index[size_index_elem(size)];
1025 } else
1026 index = fls(size - 1);
1027
1028#ifdef CONFIG_ZONE_DMA
b1e05416 1029 if (unlikely((flags & GFP_DMA)))
2c59dd65
CL
1030 return kmalloc_dma_caches[index];
1031
1032#endif
1033 return kmalloc_caches[index];
1034}
1035
4066c33d
GG
1036/*
1037 * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
1038 * kmalloc_index() supports up to 2^26=64MB, so the final entry of the table is
1039 * kmalloc-67108864.
1040 */
af3b5f87 1041const struct kmalloc_info_struct kmalloc_info[] __initconst = {
4066c33d
GG
1042 {NULL, 0}, {"kmalloc-96", 96},
1043 {"kmalloc-192", 192}, {"kmalloc-8", 8},
1044 {"kmalloc-16", 16}, {"kmalloc-32", 32},
1045 {"kmalloc-64", 64}, {"kmalloc-128", 128},
1046 {"kmalloc-256", 256}, {"kmalloc-512", 512},
1047 {"kmalloc-1024", 1024}, {"kmalloc-2048", 2048},
1048 {"kmalloc-4096", 4096}, {"kmalloc-8192", 8192},
1049 {"kmalloc-16384", 16384}, {"kmalloc-32768", 32768},
1050 {"kmalloc-65536", 65536}, {"kmalloc-131072", 131072},
1051 {"kmalloc-262144", 262144}, {"kmalloc-524288", 524288},
1052 {"kmalloc-1048576", 1048576}, {"kmalloc-2097152", 2097152},
1053 {"kmalloc-4194304", 4194304}, {"kmalloc-8388608", 8388608},
1054 {"kmalloc-16777216", 16777216}, {"kmalloc-33554432", 33554432},
1055 {"kmalloc-67108864", 67108864}
1056};
1057
f97d5f63 1058/*
34cc6990
DS
1059 * Patch up the size_index table if we have strange large alignment
1060 * requirements for the kmalloc array. This is only the case for
1061 * MIPS it seems. The standard arches will not generate any code here.
1062 *
1063 * Largest permitted alignment is 256 bytes due to the way we
1064 * handle the index determination for the smaller caches.
1065 *
1066 * Make sure that nothing crazy happens if someone starts tinkering
1067 * around with ARCH_KMALLOC_MINALIGN
f97d5f63 1068 */
34cc6990 1069void __init setup_kmalloc_cache_index_table(void)
f97d5f63 1070{
ac914d08 1071 unsigned int i;
f97d5f63 1072
2c59dd65
CL
1073 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
1074 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
1075
1076 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
ac914d08 1077 unsigned int elem = size_index_elem(i);
2c59dd65
CL
1078
1079 if (elem >= ARRAY_SIZE(size_index))
1080 break;
1081 size_index[elem] = KMALLOC_SHIFT_LOW;
1082 }
1083
1084 if (KMALLOC_MIN_SIZE >= 64) {
1085 /*
1086 * The 96 byte size cache is not used if the alignment
1087 * is 64 byte.
1088 */
1089 for (i = 64 + 8; i <= 96; i += 8)
1090 size_index[size_index_elem(i)] = 7;
1091
1092 }
1093
1094 if (KMALLOC_MIN_SIZE >= 128) {
1095 /*
1096 * The 192 byte sized cache is not used if the alignment
1097 * is 128 byte. Redirect kmalloc to use the 256 byte cache
1098 * instead.
1099 */
1100 for (i = 128 + 8; i <= 192; i += 8)
1101 size_index[size_index_elem(i)] = 8;
1102 }
34cc6990
DS
1103}
1104
d50112ed 1105static void __init new_kmalloc_cache(int idx, slab_flags_t flags)
a9730fca
CL
1106{
1107 kmalloc_caches[idx] = create_kmalloc_cache(kmalloc_info[idx].name,
6c0c21ad
DW
1108 kmalloc_info[idx].size, flags, 0,
1109 kmalloc_info[idx].size);
a9730fca
CL
1110}
1111
34cc6990
DS
1112/*
1113 * Create the kmalloc array. Some of the regular kmalloc arrays
1114 * may already have been created because they were needed to
1115 * enable allocations for slab creation.
1116 */
d50112ed 1117void __init create_kmalloc_caches(slab_flags_t flags)
34cc6990
DS
1118{
1119 int i;
1120
a9730fca
CL
1121 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
1122 if (!kmalloc_caches[i])
1123 new_kmalloc_cache(i, flags);
f97d5f63 1124
956e46ef 1125 /*
a9730fca
CL
1126 * Caches that are not of the two-to-the-power-of size.
1127 * These have to be created immediately after the
1128 * earlier power of two caches
956e46ef 1129 */
a9730fca
CL
1130 if (KMALLOC_MIN_SIZE <= 32 && !kmalloc_caches[1] && i == 6)
1131 new_kmalloc_cache(1, flags);
1132 if (KMALLOC_MIN_SIZE <= 64 && !kmalloc_caches[2] && i == 7)
1133 new_kmalloc_cache(2, flags);
8a965b3b
CL
1134 }
1135
f97d5f63
CL
1136 /* Kmalloc array is now usable */
1137 slab_state = UP;
1138
f97d5f63
CL
1139#ifdef CONFIG_ZONE_DMA
1140 for (i = 0; i <= KMALLOC_SHIFT_HIGH; i++) {
1141 struct kmem_cache *s = kmalloc_caches[i];
1142
1143 if (s) {
0be70327 1144 unsigned int size = kmalloc_size(i);
f97d5f63 1145 char *n = kasprintf(GFP_NOWAIT,
0be70327 1146 "dma-kmalloc-%u", size);
f97d5f63
CL
1147
1148 BUG_ON(!n);
1149 kmalloc_dma_caches[i] = create_kmalloc_cache(n,
6c0c21ad 1150 size, SLAB_CACHE_DMA | flags, 0, 0);
f97d5f63
CL
1151 }
1152 }
1153#endif
1154}
45530c44
CL
1155#endif /* !CONFIG_SLOB */
1156
cea371f4
VD
1157/*
1158 * To avoid unnecessary overhead, we pass through large allocation requests
1159 * directly to the page allocator. We use __GFP_COMP, because we will need to
1160 * know the allocation order to free the pages properly in kfree.
1161 */
52383431
VD
1162void *kmalloc_order(size_t size, gfp_t flags, unsigned int order)
1163{
1164 void *ret;
1165 struct page *page;
1166
1167 flags |= __GFP_COMP;
4949148a 1168 page = alloc_pages(flags, order);
52383431
VD
1169 ret = page ? page_address(page) : NULL;
1170 kmemleak_alloc(ret, size, 1, flags);
505f5dcb 1171 kasan_kmalloc_large(ret, size, flags);
52383431
VD
1172 return ret;
1173}
1174EXPORT_SYMBOL(kmalloc_order);
1175
f1b6eb6e
CL
1176#ifdef CONFIG_TRACING
1177void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
1178{
1179 void *ret = kmalloc_order(size, flags, order);
1180 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
1181 return ret;
1182}
1183EXPORT_SYMBOL(kmalloc_order_trace);
1184#endif
45530c44 1185
7c00fce9
TG
1186#ifdef CONFIG_SLAB_FREELIST_RANDOM
1187/* Randomize a generic freelist */
1188static void freelist_randomize(struct rnd_state *state, unsigned int *list,
302d55d5 1189 unsigned int count)
7c00fce9 1190{
7c00fce9 1191 unsigned int rand;
302d55d5 1192 unsigned int i;
7c00fce9
TG
1193
1194 for (i = 0; i < count; i++)
1195 list[i] = i;
1196
1197 /* Fisher-Yates shuffle */
1198 for (i = count - 1; i > 0; i--) {
1199 rand = prandom_u32_state(state);
1200 rand %= (i + 1);
1201 swap(list[i], list[rand]);
1202 }
1203}
1204
1205/* Create a random sequence per cache */
1206int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
1207 gfp_t gfp)
1208{
1209 struct rnd_state state;
1210
1211 if (count < 2 || cachep->random_seq)
1212 return 0;
1213
1214 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
1215 if (!cachep->random_seq)
1216 return -ENOMEM;
1217
1218 /* Get best entropy at this stage of boot */
1219 prandom_seed_state(&state, get_random_long());
1220
1221 freelist_randomize(&state, cachep->random_seq, count);
1222 return 0;
1223}
1224
1225/* Destroy the per-cache random freelist sequence */
1226void cache_random_seq_destroy(struct kmem_cache *cachep)
1227{
1228 kfree(cachep->random_seq);
1229 cachep->random_seq = NULL;
1230}
1231#endif /* CONFIG_SLAB_FREELIST_RANDOM */
1232
5b365771 1233#if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
e9b4db2b
WL
1234#ifdef CONFIG_SLAB
1235#define SLABINFO_RIGHTS (S_IWUSR | S_IRUSR)
1236#else
1237#define SLABINFO_RIGHTS S_IRUSR
1238#endif
1239
b047501c 1240static void print_slabinfo_header(struct seq_file *m)
bcee6e2a
GC
1241{
1242 /*
1243 * Output format version, so at least we can change it
1244 * without _too_ many complaints.
1245 */
1246#ifdef CONFIG_DEBUG_SLAB
1247 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1248#else
1249 seq_puts(m, "slabinfo - version: 2.1\n");
1250#endif
756a025f 1251 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
bcee6e2a
GC
1252 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1253 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1254#ifdef CONFIG_DEBUG_SLAB
756a025f 1255 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
bcee6e2a
GC
1256 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1257#endif
1258 seq_putc(m, '\n');
1259}
1260
1df3b26f 1261void *slab_start(struct seq_file *m, loff_t *pos)
b7454ad3 1262{
b7454ad3 1263 mutex_lock(&slab_mutex);
510ded33 1264 return seq_list_start(&slab_root_caches, *pos);
b7454ad3
GC
1265}
1266
276a2439 1267void *slab_next(struct seq_file *m, void *p, loff_t *pos)
b7454ad3 1268{
510ded33 1269 return seq_list_next(p, &slab_root_caches, pos);
b7454ad3
GC
1270}
1271
276a2439 1272void slab_stop(struct seq_file *m, void *p)
b7454ad3
GC
1273{
1274 mutex_unlock(&slab_mutex);
1275}
1276
749c5415
GC
1277static void
1278memcg_accumulate_slabinfo(struct kmem_cache *s, struct slabinfo *info)
1279{
1280 struct kmem_cache *c;
1281 struct slabinfo sinfo;
749c5415
GC
1282
1283 if (!is_root_cache(s))
1284 return;
1285
426589f5 1286 for_each_memcg_cache(c, s) {
749c5415
GC
1287 memset(&sinfo, 0, sizeof(sinfo));
1288 get_slabinfo(c, &sinfo);
1289
1290 info->active_slabs += sinfo.active_slabs;
1291 info->num_slabs += sinfo.num_slabs;
1292 info->shared_avail += sinfo.shared_avail;
1293 info->active_objs += sinfo.active_objs;
1294 info->num_objs += sinfo.num_objs;
1295 }
1296}
1297
b047501c 1298static void cache_show(struct kmem_cache *s, struct seq_file *m)
b7454ad3 1299{
0d7561c6
GC
1300 struct slabinfo sinfo;
1301
1302 memset(&sinfo, 0, sizeof(sinfo));
1303 get_slabinfo(s, &sinfo);
1304
749c5415
GC
1305 memcg_accumulate_slabinfo(s, &sinfo);
1306
0d7561c6 1307 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
749c5415 1308 cache_name(s), sinfo.active_objs, sinfo.num_objs, s->size,
0d7561c6
GC
1309 sinfo.objects_per_slab, (1 << sinfo.cache_order));
1310
1311 seq_printf(m, " : tunables %4u %4u %4u",
1312 sinfo.limit, sinfo.batchcount, sinfo.shared);
1313 seq_printf(m, " : slabdata %6lu %6lu %6lu",
1314 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
1315 slabinfo_show_stats(m, s);
1316 seq_putc(m, '\n');
b7454ad3
GC
1317}
1318
1df3b26f 1319static int slab_show(struct seq_file *m, void *p)
749c5415 1320{
510ded33 1321 struct kmem_cache *s = list_entry(p, struct kmem_cache, root_caches_node);
749c5415 1322
510ded33 1323 if (p == slab_root_caches.next)
1df3b26f 1324 print_slabinfo_header(m);
510ded33 1325 cache_show(s, m);
b047501c
VD
1326 return 0;
1327}
1328
852d8be0
YS
1329void dump_unreclaimable_slab(void)
1330{
1331 struct kmem_cache *s, *s2;
1332 struct slabinfo sinfo;
1333
1334 /*
1335 * Here acquiring slab_mutex is risky since we don't prefer to get
1336 * sleep in oom path. But, without mutex hold, it may introduce a
1337 * risk of crash.
1338 * Use mutex_trylock to protect the list traverse, dump nothing
1339 * without acquiring the mutex.
1340 */
1341 if (!mutex_trylock(&slab_mutex)) {
1342 pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1343 return;
1344 }
1345
1346 pr_info("Unreclaimable slab info:\n");
1347 pr_info("Name Used Total\n");
1348
1349 list_for_each_entry_safe(s, s2, &slab_caches, list) {
1350 if (!is_root_cache(s) || (s->flags & SLAB_RECLAIM_ACCOUNT))
1351 continue;
1352
1353 get_slabinfo(s, &sinfo);
1354
1355 if (sinfo.num_objs > 0)
1356 pr_info("%-17s %10luKB %10luKB\n", cache_name(s),
1357 (sinfo.active_objs * s->size) / 1024,
1358 (sinfo.num_objs * s->size) / 1024);
1359 }
1360 mutex_unlock(&slab_mutex);
1361}
1362
5b365771 1363#if defined(CONFIG_MEMCG)
bc2791f8
TH
1364void *memcg_slab_start(struct seq_file *m, loff_t *pos)
1365{
1366 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1367
1368 mutex_lock(&slab_mutex);
1369 return seq_list_start(&memcg->kmem_caches, *pos);
1370}
1371
1372void *memcg_slab_next(struct seq_file *m, void *p, loff_t *pos)
1373{
1374 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1375
1376 return seq_list_next(p, &memcg->kmem_caches, pos);
1377}
1378
1379void memcg_slab_stop(struct seq_file *m, void *p)
1380{
1381 mutex_unlock(&slab_mutex);
1382}
1383
b047501c
VD
1384int memcg_slab_show(struct seq_file *m, void *p)
1385{
bc2791f8
TH
1386 struct kmem_cache *s = list_entry(p, struct kmem_cache,
1387 memcg_params.kmem_caches_node);
b047501c
VD
1388 struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
1389
bc2791f8 1390 if (p == memcg->kmem_caches.next)
b047501c 1391 print_slabinfo_header(m);
bc2791f8 1392 cache_show(s, m);
b047501c 1393 return 0;
749c5415 1394}
b047501c 1395#endif
749c5415 1396
b7454ad3
GC
1397/*
1398 * slabinfo_op - iterator that generates /proc/slabinfo
1399 *
1400 * Output layout:
1401 * cache-name
1402 * num-active-objs
1403 * total-objs
1404 * object size
1405 * num-active-slabs
1406 * total-slabs
1407 * num-pages-per-slab
1408 * + further values on SMP and with statistics enabled
1409 */
1410static const struct seq_operations slabinfo_op = {
1df3b26f 1411 .start = slab_start,
276a2439
WL
1412 .next = slab_next,
1413 .stop = slab_stop,
1df3b26f 1414 .show = slab_show,
b7454ad3
GC
1415};
1416
1417static int slabinfo_open(struct inode *inode, struct file *file)
1418{
1419 return seq_open(file, &slabinfo_op);
1420}
1421
1422static const struct file_operations proc_slabinfo_operations = {
1423 .open = slabinfo_open,
1424 .read = seq_read,
1425 .write = slabinfo_write,
1426 .llseek = seq_lseek,
1427 .release = seq_release,
1428};
1429
1430static int __init slab_proc_init(void)
1431{
e9b4db2b
WL
1432 proc_create("slabinfo", SLABINFO_RIGHTS, NULL,
1433 &proc_slabinfo_operations);
b7454ad3
GC
1434 return 0;
1435}
1436module_init(slab_proc_init);
5b365771 1437#endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
928cec9c
AR
1438
1439static __always_inline void *__do_krealloc(const void *p, size_t new_size,
1440 gfp_t flags)
1441{
1442 void *ret;
1443 size_t ks = 0;
1444
1445 if (p)
1446 ks = ksize(p);
1447
0316bec2 1448 if (ks >= new_size) {
505f5dcb 1449 kasan_krealloc((void *)p, new_size, flags);
928cec9c 1450 return (void *)p;
0316bec2 1451 }
928cec9c
AR
1452
1453 ret = kmalloc_track_caller(new_size, flags);
1454 if (ret && p)
1455 memcpy(ret, p, ks);
1456
1457 return ret;
1458}
1459
1460/**
1461 * __krealloc - like krealloc() but don't free @p.
1462 * @p: object to reallocate memory for.
1463 * @new_size: how many bytes of memory are required.
1464 * @flags: the type of memory to allocate.
1465 *
1466 * This function is like krealloc() except it never frees the originally
1467 * allocated buffer. Use this if you don't want to free the buffer immediately
1468 * like, for example, with RCU.
1469 */
1470void *__krealloc(const void *p, size_t new_size, gfp_t flags)
1471{
1472 if (unlikely(!new_size))
1473 return ZERO_SIZE_PTR;
1474
1475 return __do_krealloc(p, new_size, flags);
1476
1477}
1478EXPORT_SYMBOL(__krealloc);
1479
1480/**
1481 * krealloc - reallocate memory. The contents will remain unchanged.
1482 * @p: object to reallocate memory for.
1483 * @new_size: how many bytes of memory are required.
1484 * @flags: the type of memory to allocate.
1485 *
1486 * The contents of the object pointed to are preserved up to the
1487 * lesser of the new and old sizes. If @p is %NULL, krealloc()
1488 * behaves exactly like kmalloc(). If @new_size is 0 and @p is not a
1489 * %NULL pointer, the object pointed to is freed.
1490 */
1491void *krealloc(const void *p, size_t new_size, gfp_t flags)
1492{
1493 void *ret;
1494
1495 if (unlikely(!new_size)) {
1496 kfree(p);
1497 return ZERO_SIZE_PTR;
1498 }
1499
1500 ret = __do_krealloc(p, new_size, flags);
1501 if (ret && p != ret)
1502 kfree(p);
1503
1504 return ret;
1505}
1506EXPORT_SYMBOL(krealloc);
1507
1508/**
1509 * kzfree - like kfree but zero memory
1510 * @p: object to free memory of
1511 *
1512 * The memory of the object @p points to is zeroed before freed.
1513 * If @p is %NULL, kzfree() does nothing.
1514 *
1515 * Note: this function zeroes the whole allocated buffer which can be a good
1516 * deal bigger than the requested buffer size passed to kmalloc(). So be
1517 * careful when using this function in performance sensitive code.
1518 */
1519void kzfree(const void *p)
1520{
1521 size_t ks;
1522 void *mem = (void *)p;
1523
1524 if (unlikely(ZERO_OR_NULL_PTR(mem)))
1525 return;
1526 ks = ksize(mem);
1527 memset(mem, 0, ks);
1528 kfree(mem);
1529}
1530EXPORT_SYMBOL(kzfree);
1531
1532/* Tracepoints definitions. */
1533EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1534EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1535EXPORT_TRACEPOINT_SYMBOL(kmalloc_node);
1536EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc_node);
1537EXPORT_TRACEPOINT_SYMBOL(kfree);
1538EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);