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