1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2039363f3SChristoph Lameter /*
3039363f3SChristoph Lameter * Slab allocator functions that are independent of the allocator strategy
4039363f3SChristoph Lameter *
5039363f3SChristoph Lameter * (C) 2012 Christoph Lameter <cl@linux.com>
6039363f3SChristoph Lameter */
7039363f3SChristoph Lameter #include <linux/slab.h>
8039363f3SChristoph Lameter
9039363f3SChristoph Lameter #include <linux/mm.h>
10039363f3SChristoph Lameter #include <linux/poison.h>
11039363f3SChristoph Lameter #include <linux/interrupt.h>
12039363f3SChristoph Lameter #include <linux/memory.h>
131c99ba29SAlexey Dobriyan #include <linux/cache.h>
14039363f3SChristoph Lameter #include <linux/compiler.h>
15d3fb45f3SAlexander Potapenko #include <linux/kfence.h>
16039363f3SChristoph Lameter #include <linux/module.h>
1720cea968SChristoph Lameter #include <linux/cpu.h>
1820cea968SChristoph Lameter #include <linux/uaccess.h>
19b7454ad3SGlauber Costa #include <linux/seq_file.h>
20963e84b0SCatalin Marinas #include <linux/dma-mapping.h>
21b035f5a6SCatalin Marinas #include <linux/swiotlb.h>
22b7454ad3SGlauber Costa #include <linux/proc_fs.h>
23fcf8a1e4SWaiman Long #include <linux/debugfs.h>
24e86f8b09SAndrey Konovalov #include <linux/kasan.h>
25039363f3SChristoph Lameter #include <asm/cacheflush.h>
26039363f3SChristoph Lameter #include <asm/tlbflush.h>
27039363f3SChristoph Lameter #include <asm/page.h>
282633d7a0SGlauber Costa #include <linux/memcontrol.h>
295cf909c5SOliver Glitta #include <linux/stackdepot.h>
30928cec9cSAndrey Ryabinin
31b347aa7bSVasily Averin #include "internal.h"
32b347aa7bSVasily Averin #include "slab.h"
33b347aa7bSVasily Averin
34928cec9cSAndrey Ryabinin #define CREATE_TRACE_POINTS
35f1b6eb6eSChristoph Lameter #include <trace/events/kmem.h>
36039363f3SChristoph Lameter
3797d06609SChristoph Lameter enum slab_state slab_state;
3818004c5dSChristoph Lameter LIST_HEAD(slab_caches);
3918004c5dSChristoph Lameter DEFINE_MUTEX(slab_mutex);
409b030cb8SChristoph Lameter struct kmem_cache *kmem_cache;
4197d06609SChristoph Lameter
42657dc2f9STejun Heo static LIST_HEAD(slab_caches_to_rcu_destroy);
43657dc2f9STejun Heo static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work);
44657dc2f9STejun Heo static DECLARE_WORK(slab_caches_to_rcu_destroy_work,
45657dc2f9STejun Heo slab_caches_to_rcu_destroy_workfn);
46657dc2f9STejun Heo
4707f361b2SJoonsoo Kim /*
48423c929cSJoonsoo Kim * Set of flags that will prevent slab merging
49423c929cSJoonsoo Kim */
50423c929cSJoonsoo Kim #define SLAB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
515f0d5a3aSPaul E. McKenney SLAB_TRACE | SLAB_TYPESAFE_BY_RCU | SLAB_NOLEAKTRACE | \
52d0bf7d57SJesper Dangaard Brouer SLAB_FAILSLAB | SLAB_NO_MERGE | kasan_never_merge())
53423c929cSJoonsoo Kim
54230e9fc2SVladimir Davydov #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
556d6ea1e9SNicolas Boichat SLAB_CACHE_DMA32 | SLAB_ACCOUNT)
56423c929cSJoonsoo Kim
57423c929cSJoonsoo Kim /*
58423c929cSJoonsoo Kim * Merge control. If this is set then no merging of slab caches will occur.
59423c929cSJoonsoo Kim */
607660a6fdSKees Cook static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT);
61423c929cSJoonsoo Kim
setup_slab_nomerge(char * str)62423c929cSJoonsoo Kim static int __init setup_slab_nomerge(char *str)
63423c929cSJoonsoo Kim {
647660a6fdSKees Cook slab_nomerge = true;
65423c929cSJoonsoo Kim return 1;
66423c929cSJoonsoo Kim }
67423c929cSJoonsoo Kim
setup_slab_merge(char * str)6882edd9d5SRafael Aquini static int __init setup_slab_merge(char *str)
6982edd9d5SRafael Aquini {
7082edd9d5SRafael Aquini slab_nomerge = false;
7182edd9d5SRafael Aquini return 1;
7282edd9d5SRafael Aquini }
7382edd9d5SRafael Aquini
74423c929cSJoonsoo Kim #ifdef CONFIG_SLUB
75423c929cSJoonsoo Kim __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0);
7682edd9d5SRafael Aquini __setup_param("slub_merge", slub_merge, setup_slab_merge, 0);
77423c929cSJoonsoo Kim #endif
78423c929cSJoonsoo Kim
79423c929cSJoonsoo Kim __setup("slab_nomerge", setup_slab_nomerge);
8082edd9d5SRafael Aquini __setup("slab_merge", setup_slab_merge);
81423c929cSJoonsoo Kim
82423c929cSJoonsoo Kim /*
8307f361b2SJoonsoo Kim * Determine the size of a slab object
8407f361b2SJoonsoo Kim */
kmem_cache_size(struct kmem_cache * s)8507f361b2SJoonsoo Kim unsigned int kmem_cache_size(struct kmem_cache *s)
8607f361b2SJoonsoo Kim {
8707f361b2SJoonsoo Kim return s->object_size;
8807f361b2SJoonsoo Kim }
8907f361b2SJoonsoo Kim EXPORT_SYMBOL(kmem_cache_size);
9007f361b2SJoonsoo Kim
9177be4b13SShuah Khan #ifdef CONFIG_DEBUG_VM
kmem_cache_sanity_check(const char * name,unsigned int size)92f4957d5bSAlexey Dobriyan static int kmem_cache_sanity_check(const char *name, unsigned int size)
9377be4b13SShuah Khan {
9474c1d3e0SKees Cook if (!name || in_interrupt() || size > KMALLOC_MAX_SIZE) {
9577be4b13SShuah Khan pr_err("kmem_cache_create(%s) integrity check failed\n", name);
9677be4b13SShuah Khan return -EINVAL;
9777be4b13SShuah Khan }
9877be4b13SShuah Khan
9977be4b13SShuah Khan WARN_ON(strchr(name, ' ')); /* It confuses parsers */
10077be4b13SShuah Khan return 0;
10177be4b13SShuah Khan }
10277be4b13SShuah Khan #else
kmem_cache_sanity_check(const char * name,unsigned int size)103f4957d5bSAlexey Dobriyan static inline int kmem_cache_sanity_check(const char *name, unsigned int size)
10477be4b13SShuah Khan {
10577be4b13SShuah Khan return 0;
10677be4b13SShuah Khan }
10777be4b13SShuah Khan #endif
10877be4b13SShuah Khan
109039363f3SChristoph Lameter /*
110692ae74aSByongho Lee * Figure out what the alignment of the objects will be given a set of
111692ae74aSByongho Lee * flags, a user specified alignment and the size of the objects.
112692ae74aSByongho Lee */
calculate_alignment(slab_flags_t flags,unsigned int align,unsigned int size)113f4957d5bSAlexey Dobriyan static unsigned int calculate_alignment(slab_flags_t flags,
114f4957d5bSAlexey Dobriyan unsigned int align, unsigned int size)
115692ae74aSByongho Lee {
116692ae74aSByongho Lee /*
117692ae74aSByongho Lee * If the user wants hardware cache aligned objects then follow that
118692ae74aSByongho Lee * suggestion if the object is sufficiently large.
119692ae74aSByongho Lee *
120692ae74aSByongho Lee * The hardware cache alignment cannot override the specified
121692ae74aSByongho Lee * alignment though. If that is greater then use it.
122692ae74aSByongho Lee */
123692ae74aSByongho Lee if (flags & SLAB_HWCACHE_ALIGN) {
124f4957d5bSAlexey Dobriyan unsigned int ralign;
125692ae74aSByongho Lee
126692ae74aSByongho Lee ralign = cache_line_size();
127692ae74aSByongho Lee while (size <= ralign / 2)
128692ae74aSByongho Lee ralign /= 2;
129692ae74aSByongho Lee align = max(align, ralign);
130692ae74aSByongho Lee }
131692ae74aSByongho Lee
132d949a815SPeter Collingbourne align = max(align, arch_slab_minalign());
133692ae74aSByongho Lee
134692ae74aSByongho Lee return ALIGN(align, sizeof(void *));
135692ae74aSByongho Lee }
136692ae74aSByongho Lee
137692ae74aSByongho Lee /*
138423c929cSJoonsoo Kim * Find a mergeable slab cache
139423c929cSJoonsoo Kim */
slab_unmergeable(struct kmem_cache * s)140423c929cSJoonsoo Kim int slab_unmergeable(struct kmem_cache *s)
141423c929cSJoonsoo Kim {
142423c929cSJoonsoo Kim if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE))
143423c929cSJoonsoo Kim return 1;
144423c929cSJoonsoo Kim
145423c929cSJoonsoo Kim if (s->ctor)
146423c929cSJoonsoo Kim return 1;
147423c929cSJoonsoo Kim
148346907ceSVlastimil Babka #ifdef CONFIG_HARDENED_USERCOPY
1498eb8284bSDavid Windsor if (s->usersize)
1508eb8284bSDavid Windsor return 1;
151346907ceSVlastimil Babka #endif
1528eb8284bSDavid Windsor
153423c929cSJoonsoo Kim /*
154423c929cSJoonsoo Kim * We may have set a slab to be unmergeable during bootstrap.
155423c929cSJoonsoo Kim */
156423c929cSJoonsoo Kim if (s->refcount < 0)
157423c929cSJoonsoo Kim return 1;
158423c929cSJoonsoo Kim
159423c929cSJoonsoo Kim return 0;
160423c929cSJoonsoo Kim }
161423c929cSJoonsoo Kim
find_mergeable(unsigned int size,unsigned int align,slab_flags_t flags,const char * name,void (* ctor)(void *))162f4957d5bSAlexey Dobriyan struct kmem_cache *find_mergeable(unsigned int size, unsigned int align,
163d50112edSAlexey Dobriyan slab_flags_t flags, const char *name, void (*ctor)(void *))
164423c929cSJoonsoo Kim {
165423c929cSJoonsoo Kim struct kmem_cache *s;
166423c929cSJoonsoo Kim
167c6e28895SGrygorii Maistrenko if (slab_nomerge)
168423c929cSJoonsoo Kim return NULL;
169423c929cSJoonsoo Kim
170423c929cSJoonsoo Kim if (ctor)
171423c929cSJoonsoo Kim return NULL;
172423c929cSJoonsoo Kim
173423c929cSJoonsoo Kim size = ALIGN(size, sizeof(void *));
174423c929cSJoonsoo Kim align = calculate_alignment(flags, align, size);
175423c929cSJoonsoo Kim size = ALIGN(size, align);
17637540008SNikolay Borisov flags = kmem_cache_flags(size, flags, name);
177423c929cSJoonsoo Kim
178c6e28895SGrygorii Maistrenko if (flags & SLAB_NEVER_MERGE)
179c6e28895SGrygorii Maistrenko return NULL;
180c6e28895SGrygorii Maistrenko
181c7094406SRoman Gushchin list_for_each_entry_reverse(s, &slab_caches, list) {
182423c929cSJoonsoo Kim if (slab_unmergeable(s))
183423c929cSJoonsoo Kim continue;
184423c929cSJoonsoo Kim
185423c929cSJoonsoo Kim if (size > s->size)
186423c929cSJoonsoo Kim continue;
187423c929cSJoonsoo Kim
188423c929cSJoonsoo Kim if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
189423c929cSJoonsoo Kim continue;
190423c929cSJoonsoo Kim /*
191423c929cSJoonsoo Kim * Check if alignment is compatible.
192423c929cSJoonsoo Kim * Courtesy of Adrian Drzewiecki
193423c929cSJoonsoo Kim */
194423c929cSJoonsoo Kim if ((s->size & ~(align - 1)) != s->size)
195423c929cSJoonsoo Kim continue;
196423c929cSJoonsoo Kim
197423c929cSJoonsoo Kim if (s->size - size >= sizeof(void *))
198423c929cSJoonsoo Kim continue;
199423c929cSJoonsoo Kim
20095069ac8SJoonsoo Kim if (IS_ENABLED(CONFIG_SLAB) && align &&
20195069ac8SJoonsoo Kim (align > s->align || s->align % align))
20295069ac8SJoonsoo Kim continue;
20395069ac8SJoonsoo Kim
204423c929cSJoonsoo Kim return s;
205423c929cSJoonsoo Kim }
206423c929cSJoonsoo Kim return NULL;
207423c929cSJoonsoo Kim }
208423c929cSJoonsoo Kim
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 kmem_cache * root_cache)209c9a77a79SVladimir Davydov static struct kmem_cache *create_cache(const char *name,
210613a5eb5SShakeel Butt unsigned int object_size, unsigned int align,
2117bbdb81eSAlexey Dobriyan slab_flags_t flags, unsigned int useroffset,
2127bbdb81eSAlexey Dobriyan unsigned int usersize, void (*ctor)(void *),
2139855609bSRoman Gushchin struct kmem_cache *root_cache)
214794b1248SVladimir Davydov {
215794b1248SVladimir Davydov struct kmem_cache *s;
216794b1248SVladimir Davydov int err;
217794b1248SVladimir Davydov
2188eb8284bSDavid Windsor if (WARN_ON(useroffset + usersize > object_size))
2198eb8284bSDavid Windsor useroffset = usersize = 0;
2208eb8284bSDavid Windsor
221794b1248SVladimir Davydov err = -ENOMEM;
222794b1248SVladimir Davydov s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL);
223794b1248SVladimir Davydov if (!s)
224794b1248SVladimir Davydov goto out;
225794b1248SVladimir Davydov
226794b1248SVladimir Davydov s->name = name;
227613a5eb5SShakeel Butt s->size = s->object_size = object_size;
228794b1248SVladimir Davydov s->align = align;
229794b1248SVladimir Davydov s->ctor = ctor;
230346907ceSVlastimil Babka #ifdef CONFIG_HARDENED_USERCOPY
2318eb8284bSDavid Windsor s->useroffset = useroffset;
2328eb8284bSDavid Windsor s->usersize = usersize;
233346907ceSVlastimil Babka #endif
234794b1248SVladimir Davydov
235794b1248SVladimir Davydov err = __kmem_cache_create(s, flags);
236794b1248SVladimir Davydov if (err)
237794b1248SVladimir Davydov goto out_free_cache;
238794b1248SVladimir Davydov
239794b1248SVladimir Davydov s->refcount = 1;
240794b1248SVladimir Davydov list_add(&s->list, &slab_caches);
241794b1248SVladimir Davydov return s;
242794b1248SVladimir Davydov
243794b1248SVladimir Davydov out_free_cache:
2447c4da061SVaishali Thakkar kmem_cache_free(kmem_cache, s);
245b9dad156SZhen Lei out:
246b9dad156SZhen Lei return ERR_PTR(err);
247794b1248SVladimir Davydov }
24845906855SChristoph Lameter
249f496990fSMike Rapoport /**
250f496990fSMike Rapoport * kmem_cache_create_usercopy - Create a cache with a region suitable
251f496990fSMike Rapoport * for copying to userspace
252039363f3SChristoph Lameter * @name: A string which is used in /proc/slabinfo to identify this cache.
253039363f3SChristoph Lameter * @size: The size of objects to be created in this cache.
254039363f3SChristoph Lameter * @align: The required alignment for the objects.
255039363f3SChristoph Lameter * @flags: SLAB flags
2568eb8284bSDavid Windsor * @useroffset: Usercopy region offset
2578eb8284bSDavid Windsor * @usersize: Usercopy region size
258039363f3SChristoph Lameter * @ctor: A constructor for the objects.
259039363f3SChristoph Lameter *
260039363f3SChristoph Lameter * Cannot be called within a interrupt, but can be interrupted.
261039363f3SChristoph Lameter * The @ctor is run when new pages are allocated by the cache.
262039363f3SChristoph Lameter *
263039363f3SChristoph Lameter * The flags are
264039363f3SChristoph Lameter *
265039363f3SChristoph Lameter * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
266039363f3SChristoph Lameter * to catch references to uninitialised memory.
267039363f3SChristoph Lameter *
268f496990fSMike Rapoport * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
269039363f3SChristoph Lameter * for buffer overruns.
270039363f3SChristoph Lameter *
271039363f3SChristoph Lameter * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
272039363f3SChristoph Lameter * cacheline. This can be beneficial if you're counting cycles as closely
273039363f3SChristoph Lameter * as davem.
274f496990fSMike Rapoport *
275f496990fSMike Rapoport * Return: a pointer to the cache on success, NULL on failure.
276039363f3SChristoph Lameter */
2772633d7a0SGlauber Costa 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 *))278f4957d5bSAlexey Dobriyan kmem_cache_create_usercopy(const char *name,
279f4957d5bSAlexey Dobriyan unsigned int size, unsigned int align,
2807bbdb81eSAlexey Dobriyan slab_flags_t flags,
2817bbdb81eSAlexey Dobriyan unsigned int useroffset, unsigned int usersize,
2828eb8284bSDavid Windsor void (*ctor)(void *))
283039363f3SChristoph Lameter {
28440911a79SAlexandru Moise struct kmem_cache *s = NULL;
2853dec16eaSAndrzej Hajda const char *cache_name;
2863965fc36SVladimir Davydov int err;
287039363f3SChristoph Lameter
288afe0c26dSVlastimil Babka #ifdef CONFIG_SLUB_DEBUG
289afe0c26dSVlastimil Babka /*
290afe0c26dSVlastimil Babka * If no slub_debug was enabled globally, the static key is not yet
291afe0c26dSVlastimil Babka * enabled by setup_slub_debug(). Enable it if the cache is being
292afe0c26dSVlastimil Babka * created with any of the debugging flags passed explicitly.
2935cf909c5SOliver Glitta * It's also possible that this is the first cache created with
2945cf909c5SOliver Glitta * SLAB_STORE_USER and we should init stack_depot for it.
295afe0c26dSVlastimil Babka */
296afe0c26dSVlastimil Babka if (flags & SLAB_DEBUG_FLAGS)
297afe0c26dSVlastimil Babka static_branch_enable(&slub_debug_enabled);
2985cf909c5SOliver Glitta if (flags & SLAB_STORE_USER)
2995cf909c5SOliver Glitta stack_depot_init();
300afe0c26dSVlastimil Babka #endif
301afe0c26dSVlastimil Babka
302b920536aSPekka Enberg mutex_lock(&slab_mutex);
303686d550dSChristoph Lameter
304794b1248SVladimir Davydov err = kmem_cache_sanity_check(name, size);
3053aa24f51SAndrew Morton if (err) {
3063965fc36SVladimir Davydov goto out_unlock;
3073aa24f51SAndrew Morton }
308686d550dSChristoph Lameter
309e70954fdSThomas Garnier /* Refuse requests with allocator specific flags */
310e70954fdSThomas Garnier if (flags & ~SLAB_FLAGS_PERMITTED) {
311e70954fdSThomas Garnier err = -EINVAL;
312e70954fdSThomas Garnier goto out_unlock;
313e70954fdSThomas Garnier }
314e70954fdSThomas Garnier
315d8843922SGlauber Costa /*
316d8843922SGlauber Costa * Some allocators will constraint the set of valid flags to a subset
317d8843922SGlauber Costa * of all flags. We expect them to define CACHE_CREATE_MASK in this
318d8843922SGlauber Costa * case, and we'll just provide them with a sanitized version of the
319d8843922SGlauber Costa * passed flags.
320d8843922SGlauber Costa */
321d8843922SGlauber Costa flags &= CACHE_CREATE_MASK;
322686d550dSChristoph Lameter
3238eb8284bSDavid Windsor /* Fail closed on bad usersize of useroffset values. */
324346907ceSVlastimil Babka if (!IS_ENABLED(CONFIG_HARDENED_USERCOPY) ||
325346907ceSVlastimil Babka WARN_ON(!usersize && useroffset) ||
3268eb8284bSDavid Windsor WARN_ON(size < usersize || size - usersize < useroffset))
3278eb8284bSDavid Windsor usersize = useroffset = 0;
3288eb8284bSDavid Windsor
3298eb8284bSDavid Windsor if (!usersize)
330a44cb944SVladimir Davydov s = __kmem_cache_alias(name, size, align, flags, ctor);
331cbb79694SChristoph Lameter if (s)
3323965fc36SVladimir Davydov goto out_unlock;
333794b1248SVladimir Davydov
3343dec16eaSAndrzej Hajda cache_name = kstrdup_const(name, GFP_KERNEL);
335794b1248SVladimir Davydov if (!cache_name) {
336794b1248SVladimir Davydov err = -ENOMEM;
337794b1248SVladimir Davydov goto out_unlock;
338a44cb944SVladimir Davydov }
339cbb79694SChristoph Lameter
340613a5eb5SShakeel Butt s = create_cache(cache_name, size,
341794b1248SVladimir Davydov calculate_alignment(flags, align, size),
3429855609bSRoman Gushchin flags, useroffset, usersize, ctor, NULL);
343794b1248SVladimir Davydov if (IS_ERR(s)) {
344794b1248SVladimir Davydov err = PTR_ERR(s);
3453dec16eaSAndrzej Hajda kfree_const(cache_name);
346794b1248SVladimir Davydov }
347db265ecaSChristoph Lameter
3483965fc36SVladimir Davydov out_unlock:
34920cea968SChristoph Lameter mutex_unlock(&slab_mutex);
35003afc0e2SVladimir Davydov
351ba3253c7SDave Jones if (err) {
352686d550dSChristoph Lameter if (flags & SLAB_PANIC)
3534acaa7d5Sgumingtao panic("%s: Failed to create slab '%s'. Error %d\n",
3544acaa7d5Sgumingtao __func__, name, err);
355686d550dSChristoph Lameter else {
3564acaa7d5Sgumingtao pr_warn("%s(%s) failed with error %d\n",
3574acaa7d5Sgumingtao __func__, name, err);
358686d550dSChristoph Lameter dump_stack();
359686d550dSChristoph Lameter }
360686d550dSChristoph Lameter return NULL;
361686d550dSChristoph Lameter }
362039363f3SChristoph Lameter return s;
363794b1248SVladimir Davydov }
3648eb8284bSDavid Windsor EXPORT_SYMBOL(kmem_cache_create_usercopy);
3658eb8284bSDavid Windsor
366f496990fSMike Rapoport /**
367f496990fSMike Rapoport * kmem_cache_create - Create a cache.
368f496990fSMike Rapoport * @name: A string which is used in /proc/slabinfo to identify this cache.
369f496990fSMike Rapoport * @size: The size of objects to be created in this cache.
370f496990fSMike Rapoport * @align: The required alignment for the objects.
371f496990fSMike Rapoport * @flags: SLAB flags
372f496990fSMike Rapoport * @ctor: A constructor for the objects.
373f496990fSMike Rapoport *
374f496990fSMike Rapoport * Cannot be called within a interrupt, but can be interrupted.
375f496990fSMike Rapoport * The @ctor is run when new pages are allocated by the cache.
376f496990fSMike Rapoport *
377f496990fSMike Rapoport * The flags are
378f496990fSMike Rapoport *
379f496990fSMike Rapoport * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
380f496990fSMike Rapoport * to catch references to uninitialised memory.
381f496990fSMike Rapoport *
382f496990fSMike Rapoport * %SLAB_RED_ZONE - Insert `Red` zones around the allocated memory to check
383f496990fSMike Rapoport * for buffer overruns.
384f496990fSMike Rapoport *
385f496990fSMike Rapoport * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
386f496990fSMike Rapoport * cacheline. This can be beneficial if you're counting cycles as closely
387f496990fSMike Rapoport * as davem.
388f496990fSMike Rapoport *
389f496990fSMike Rapoport * Return: a pointer to the cache on success, NULL on failure.
390f496990fSMike Rapoport */
3918eb8284bSDavid Windsor struct kmem_cache *
kmem_cache_create(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))392f4957d5bSAlexey Dobriyan kmem_cache_create(const char *name, unsigned int size, unsigned int align,
3938eb8284bSDavid Windsor slab_flags_t flags, void (*ctor)(void *))
3948eb8284bSDavid Windsor {
3956d07d1cdSKees Cook return kmem_cache_create_usercopy(name, size, align, flags, 0, 0,
3968eb8284bSDavid Windsor ctor);
3978eb8284bSDavid Windsor }
398794b1248SVladimir Davydov EXPORT_SYMBOL(kmem_cache_create);
3993965fc36SVladimir Davydov
4000495e337SWaiman Long #ifdef SLAB_SUPPORTS_SYSFS
4010495e337SWaiman Long /*
4020495e337SWaiman Long * For a given kmem_cache, kmem_cache_destroy() should only be called
4030495e337SWaiman Long * once or there will be a use-after-free problem. The actual deletion
4040495e337SWaiman Long * and release of the kobject does not need slab_mutex or cpu_hotplug_lock
4050495e337SWaiman Long * protection. So they are now done without holding those locks.
4060495e337SWaiman Long *
4070495e337SWaiman Long * Note that there will be a slight delay in the deletion of sysfs files
4080495e337SWaiman Long * if kmem_cache_release() is called indrectly from a work function.
4090495e337SWaiman Long */
kmem_cache_release(struct kmem_cache * s)4100495e337SWaiman Long static void kmem_cache_release(struct kmem_cache *s)
4110495e337SWaiman Long {
4120495e337SWaiman Long sysfs_slab_unlink(s);
4130495e337SWaiman Long sysfs_slab_release(s);
4140495e337SWaiman Long }
4150495e337SWaiman Long #else
kmem_cache_release(struct kmem_cache * s)4160495e337SWaiman Long static void kmem_cache_release(struct kmem_cache *s)
4170495e337SWaiman Long {
4180495e337SWaiman Long slab_kmem_cache_release(s);
4190495e337SWaiman Long }
4200495e337SWaiman Long #endif
4210495e337SWaiman Long
slab_caches_to_rcu_destroy_workfn(struct work_struct * work)422657dc2f9STejun Heo static void slab_caches_to_rcu_destroy_workfn(struct work_struct *work)
423d5b3cf71SVladimir Davydov {
424657dc2f9STejun Heo LIST_HEAD(to_destroy);
425d5b3cf71SVladimir Davydov struct kmem_cache *s, *s2;
426d5b3cf71SVladimir Davydov
427657dc2f9STejun Heo /*
4285f0d5a3aSPaul E. McKenney * On destruction, SLAB_TYPESAFE_BY_RCU kmem_caches are put on the
429657dc2f9STejun Heo * @slab_caches_to_rcu_destroy list. The slab pages are freed
430081a06faSRandy Dunlap * through RCU and the associated kmem_cache are dereferenced
431657dc2f9STejun Heo * while freeing the pages, so the kmem_caches should be freed only
432657dc2f9STejun Heo * after the pending RCU operations are finished. As rcu_barrier()
433657dc2f9STejun Heo * is a pretty slow operation, we batch all pending destructions
434657dc2f9STejun Heo * asynchronously.
435657dc2f9STejun Heo */
436657dc2f9STejun Heo mutex_lock(&slab_mutex);
437657dc2f9STejun Heo list_splice_init(&slab_caches_to_rcu_destroy, &to_destroy);
438657dc2f9STejun Heo mutex_unlock(&slab_mutex);
439657dc2f9STejun Heo
440657dc2f9STejun Heo if (list_empty(&to_destroy))
441657dc2f9STejun Heo return;
442657dc2f9STejun Heo
443d5b3cf71SVladimir Davydov rcu_barrier();
444d5b3cf71SVladimir Davydov
445657dc2f9STejun Heo list_for_each_entry_safe(s, s2, &to_destroy, list) {
44664dd6849SFaiyaz Mohammed debugfs_slab_release(s);
447d3fb45f3SAlexander Potapenko kfence_shutdown_cache(s);
4480495e337SWaiman Long kmem_cache_release(s);
449d5b3cf71SVladimir Davydov }
450d5b3cf71SVladimir Davydov }
451d5b3cf71SVladimir Davydov
shutdown_cache(struct kmem_cache * s)452657dc2f9STejun Heo static int shutdown_cache(struct kmem_cache *s)
453657dc2f9STejun Heo {
454f9fa1d91SGreg Thelen /* free asan quarantined objects */
455f9fa1d91SGreg Thelen kasan_cache_shutdown(s);
456f9fa1d91SGreg Thelen
457657dc2f9STejun Heo if (__kmem_cache_shutdown(s) != 0)
458657dc2f9STejun Heo return -EBUSY;
459657dc2f9STejun Heo
460657dc2f9STejun Heo list_del(&s->list);
461657dc2f9STejun Heo
4625f0d5a3aSPaul E. McKenney if (s->flags & SLAB_TYPESAFE_BY_RCU) {
463657dc2f9STejun Heo list_add_tail(&s->list, &slab_caches_to_rcu_destroy);
464657dc2f9STejun Heo schedule_work(&slab_caches_to_rcu_destroy_work);
465657dc2f9STejun Heo } else {
466d3fb45f3SAlexander Potapenko kfence_shutdown_cache(s);
46764dd6849SFaiyaz Mohammed debugfs_slab_release(s);
468657dc2f9STejun Heo }
469657dc2f9STejun Heo
470657dc2f9STejun Heo return 0;
471657dc2f9STejun Heo }
472657dc2f9STejun Heo
slab_kmem_cache_release(struct kmem_cache * s)47341a21285SChristoph Lameter void slab_kmem_cache_release(struct kmem_cache *s)
47441a21285SChristoph Lameter {
47552b4b950SDmitry Safonov __kmem_cache_release(s);
4763dec16eaSAndrzej Hajda kfree_const(s->name);
47741a21285SChristoph Lameter kmem_cache_free(kmem_cache, s);
47841a21285SChristoph Lameter }
47941a21285SChristoph Lameter
kmem_cache_destroy(struct kmem_cache * s)480945cf2b6SChristoph Lameter void kmem_cache_destroy(struct kmem_cache *s)
481945cf2b6SChristoph Lameter {
48246a9ea66SRafael Aquini int err = -EBUSY;
483d71608a8SFeng Tang bool rcu_set;
4840495e337SWaiman Long
485bed0a9b5SMarco Elver if (unlikely(!s) || !kasan_check_byte(s))
4863942d299SSergey Senozhatsky return;
4873942d299SSergey Senozhatsky
4885a836bf6SSebastian Andrzej Siewior cpus_read_lock();
489945cf2b6SChristoph Lameter mutex_lock(&slab_mutex);
490b8529907SVladimir Davydov
491d71608a8SFeng Tang rcu_set = s->flags & SLAB_TYPESAFE_BY_RCU;
492d71608a8SFeng Tang
49346a9ea66SRafael Aquini s->refcount--;
49446a9ea66SRafael Aquini if (s->refcount)
495b8529907SVladimir Davydov goto out_unlock;
496b8529907SVladimir Davydov
49746a9ea66SRafael Aquini err = shutdown_cache(s);
49846a9ea66SRafael Aquini WARN(err, "%s %s: Slab cache still has objects when called from %pS",
4997302e91fSMarco Elver __func__, s->name, (void *)_RET_IP_);
500b8529907SVladimir Davydov out_unlock:
501210ed9deSJiri Kosina mutex_unlock(&slab_mutex);
5025a836bf6SSebastian Andrzej Siewior cpus_read_unlock();
50346a9ea66SRafael Aquini if (!err && !rcu_set)
5040495e337SWaiman Long kmem_cache_release(s);
505945cf2b6SChristoph Lameter }
506945cf2b6SChristoph Lameter EXPORT_SYMBOL(kmem_cache_destroy);
507945cf2b6SChristoph Lameter
50803afc0e2SVladimir Davydov /**
50903afc0e2SVladimir Davydov * kmem_cache_shrink - Shrink a cache.
51003afc0e2SVladimir Davydov * @cachep: The cache to shrink.
51103afc0e2SVladimir Davydov *
51203afc0e2SVladimir Davydov * Releases as many slabs as possible for a cache.
51303afc0e2SVladimir Davydov * To help debugging, a zero exit status indicates all slabs were released.
514a862f68aSMike Rapoport *
515a862f68aSMike Rapoport * Return: %0 if all slabs were released, non-zero otherwise
51603afc0e2SVladimir Davydov */
kmem_cache_shrink(struct kmem_cache * cachep)51703afc0e2SVladimir Davydov int kmem_cache_shrink(struct kmem_cache *cachep)
51803afc0e2SVladimir Davydov {
51955834c59SAlexander Potapenko kasan_cache_shrink(cachep);
5207e1fa93dSVlastimil Babka
521610f9c00Sye xingchen return __kmem_cache_shrink(cachep);
52203afc0e2SVladimir Davydov }
52303afc0e2SVladimir Davydov EXPORT_SYMBOL(kmem_cache_shrink);
52403afc0e2SVladimir Davydov
slab_is_available(void)525fda90124SDenis Kirjanov bool slab_is_available(void)
52697d06609SChristoph Lameter {
52797d06609SChristoph Lameter return slab_state >= UP;
52897d06609SChristoph Lameter }
529b7454ad3SGlauber Costa
5305bb1bb35SPaul E. McKenney #ifdef CONFIG_PRINTK
kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct slab * slab)5312dfe63e6SMarco Elver static void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
5322dfe63e6SMarco Elver {
5332dfe63e6SMarco Elver if (__kfence_obj_info(kpp, object, slab))
5342dfe63e6SMarco Elver return;
5352dfe63e6SMarco Elver __kmem_obj_info(kpp, object, slab);
5362dfe63e6SMarco Elver }
5372dfe63e6SMarco Elver
5388e7f37f2SPaul E. McKenney /**
5398e7f37f2SPaul E. McKenney * kmem_dump_obj - Print available slab provenance information
5408e7f37f2SPaul E. McKenney * @object: slab object for which to find provenance information.
5418e7f37f2SPaul E. McKenney *
5428e7f37f2SPaul E. McKenney * This function uses pr_cont(), so that the caller is expected to have
5438e7f37f2SPaul E. McKenney * printed out whatever preamble is appropriate. The provenance information
5448e7f37f2SPaul E. McKenney * depends on the type of object and on how much debugging is enabled.
5458e7f37f2SPaul E. McKenney * For a slab-cache object, the fact that it is a slab object is printed,
5468e7f37f2SPaul E. McKenney * and, if available, the slab name, return address, and stack trace from
547e548eaa1SManinder Singh * the allocation and last free path of that object.
5488e7f37f2SPaul E. McKenney *
5494a2f0946SZhen Lei * Return: %true if the pointer is to a not-yet-freed object from
5504a2f0946SZhen Lei * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer
5514a2f0946SZhen Lei * is to an already-freed object, and %false otherwise.
5528e7f37f2SPaul E. McKenney */
kmem_dump_obj(void * object)5534a2f0946SZhen Lei bool kmem_dump_obj(void *object)
5548e7f37f2SPaul E. McKenney {
5558e7f37f2SPaul E. McKenney char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc";
5568e7f37f2SPaul E. McKenney int i;
5577213230aSMatthew Wilcox (Oracle) struct slab *slab;
5588e7f37f2SPaul E. McKenney unsigned long ptroffset;
5598e7f37f2SPaul E. McKenney struct kmem_obj_info kp = { };
5608e7f37f2SPaul E. McKenney
5614a2f0946SZhen Lei /* Some arches consider ZERO_SIZE_PTR to be a valid address. */
5624a2f0946SZhen Lei if (object < (void *)PAGE_SIZE || !virt_addr_valid(object))
5634a2f0946SZhen Lei return false;
5647213230aSMatthew Wilcox (Oracle) slab = virt_to_slab(object);
5654a2f0946SZhen Lei if (!slab)
5664a2f0946SZhen Lei return false;
5674a2f0946SZhen Lei
5687213230aSMatthew Wilcox (Oracle) kmem_obj_info(&kp, object, slab);
5698e7f37f2SPaul E. McKenney if (kp.kp_slab_cache)
5708e7f37f2SPaul E. McKenney pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name);
5718e7f37f2SPaul E. McKenney else
5728e7f37f2SPaul E. McKenney pr_cont(" slab%s", cp);
5732dfe63e6SMarco Elver if (is_kfence_address(object))
5742dfe63e6SMarco Elver pr_cont(" (kfence)");
5758e7f37f2SPaul E. McKenney if (kp.kp_objp)
5768e7f37f2SPaul E. McKenney pr_cont(" start %px", kp.kp_objp);
5778e7f37f2SPaul E. McKenney if (kp.kp_data_offset)
5788e7f37f2SPaul E. McKenney pr_cont(" data offset %lu", kp.kp_data_offset);
5798e7f37f2SPaul E. McKenney if (kp.kp_objp) {
5808e7f37f2SPaul E. McKenney ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset;
5818e7f37f2SPaul E. McKenney pr_cont(" pointer offset %lu", ptroffset);
5828e7f37f2SPaul E. McKenney }
583346907ceSVlastimil Babka if (kp.kp_slab_cache && kp.kp_slab_cache->object_size)
584346907ceSVlastimil Babka pr_cont(" size %u", kp.kp_slab_cache->object_size);
5858e7f37f2SPaul E. McKenney if (kp.kp_ret)
5868e7f37f2SPaul E. McKenney pr_cont(" allocated at %pS\n", kp.kp_ret);
5878e7f37f2SPaul E. McKenney else
5888e7f37f2SPaul E. McKenney pr_cont("\n");
5898e7f37f2SPaul E. McKenney for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) {
5908e7f37f2SPaul E. McKenney if (!kp.kp_stack[i])
5918e7f37f2SPaul E. McKenney break;
5928e7f37f2SPaul E. McKenney pr_info(" %pS\n", kp.kp_stack[i]);
5938e7f37f2SPaul E. McKenney }
594e548eaa1SManinder Singh
595e548eaa1SManinder Singh if (kp.kp_free_stack[0])
596e548eaa1SManinder Singh pr_cont(" Free path:\n");
597e548eaa1SManinder Singh
598e548eaa1SManinder Singh for (i = 0; i < ARRAY_SIZE(kp.kp_free_stack); i++) {
599e548eaa1SManinder Singh if (!kp.kp_free_stack[i])
600e548eaa1SManinder Singh break;
601e548eaa1SManinder Singh pr_info(" %pS\n", kp.kp_free_stack[i]);
602e548eaa1SManinder Singh }
603e548eaa1SManinder Singh
6044a2f0946SZhen Lei return true;
6058e7f37f2SPaul E. McKenney }
6060d3dd2c8SPaul E. McKenney EXPORT_SYMBOL_GPL(kmem_dump_obj);
6075bb1bb35SPaul E. McKenney #endif
6088e7f37f2SPaul E. McKenney
60945530c44SChristoph Lameter /* 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)610361d575eSAlexey Dobriyan void __init create_boot_cache(struct kmem_cache *s, const char *name,
611361d575eSAlexey Dobriyan unsigned int size, slab_flags_t flags,
612361d575eSAlexey Dobriyan unsigned int useroffset, unsigned int usersize)
61345530c44SChristoph Lameter {
61445530c44SChristoph Lameter int err;
61559bb4798SVlastimil Babka unsigned int align = ARCH_KMALLOC_MINALIGN;
61645530c44SChristoph Lameter
61745530c44SChristoph Lameter s->name = name;
61845530c44SChristoph Lameter s->size = s->object_size = size;
61959bb4798SVlastimil Babka
62059bb4798SVlastimil Babka /*
62159bb4798SVlastimil Babka * For power of two sizes, guarantee natural alignment for kmalloc
62259bb4798SVlastimil Babka * caches, regardless of SL*B debugging options.
62359bb4798SVlastimil Babka */
62459bb4798SVlastimil Babka if (is_power_of_2(size))
62559bb4798SVlastimil Babka align = max(align, size);
62659bb4798SVlastimil Babka s->align = calculate_alignment(flags, align, size);
62759bb4798SVlastimil Babka
628346907ceSVlastimil Babka #ifdef CONFIG_HARDENED_USERCOPY
6298eb8284bSDavid Windsor s->useroffset = useroffset;
6308eb8284bSDavid Windsor s->usersize = usersize;
631346907ceSVlastimil Babka #endif
632f7ce3190SVladimir Davydov
63345530c44SChristoph Lameter err = __kmem_cache_create(s, flags);
63445530c44SChristoph Lameter
63545530c44SChristoph Lameter if (err)
636361d575eSAlexey Dobriyan panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n",
63745530c44SChristoph Lameter name, size, err);
63845530c44SChristoph Lameter
63945530c44SChristoph Lameter s->refcount = -1; /* Exempt from merging for now */
64045530c44SChristoph Lameter }
64145530c44SChristoph Lameter
create_kmalloc_cache(const char * name,unsigned int size,slab_flags_t flags)6420c474d31SCatalin Marinas static struct kmem_cache *__init create_kmalloc_cache(const char *name,
6430c474d31SCatalin Marinas unsigned int size,
6440c474d31SCatalin Marinas slab_flags_t flags)
64545530c44SChristoph Lameter {
64645530c44SChristoph Lameter struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
64745530c44SChristoph Lameter
64845530c44SChristoph Lameter if (!s)
64945530c44SChristoph Lameter panic("Out of memory when creating slab %s\n", name);
65045530c44SChristoph Lameter
6510c474d31SCatalin Marinas create_boot_cache(s, name, size, flags | SLAB_KMALLOC, 0, size);
65245530c44SChristoph Lameter list_add(&s->list, &slab_caches);
65345530c44SChristoph Lameter s->refcount = 1;
65445530c44SChristoph Lameter return s;
65545530c44SChristoph Lameter }
65645530c44SChristoph Lameter
657cc252eaeSVlastimil Babka struct kmem_cache *
658a07057dcSArnd Bergmann kmalloc_caches[NR_KMALLOC_TYPES][KMALLOC_SHIFT_HIGH + 1] __ro_after_init =
659a07057dcSArnd Bergmann { /* initialization for https://bugs.llvm.org/show_bug.cgi?id=42570 */ };
6609425c58eSChristoph Lameter EXPORT_SYMBOL(kmalloc_caches);
6619425c58eSChristoph Lameter
6623c615294SGONG, Ruiqi #ifdef CONFIG_RANDOM_KMALLOC_CACHES
6633c615294SGONG, Ruiqi unsigned long random_kmalloc_seed __ro_after_init;
6643c615294SGONG, Ruiqi EXPORT_SYMBOL(random_kmalloc_seed);
6653c615294SGONG, Ruiqi #endif
6663c615294SGONG, Ruiqi
667f97d5f63SChristoph Lameter /*
6682c59dd65SChristoph Lameter * Conversion table for small slabs sizes / 8 to the index in the
6692c59dd65SChristoph Lameter * kmalloc array. This is necessary for slabs < 192 since we have non power
6702c59dd65SChristoph Lameter * of two cache sizes there. The size of larger slabs can be determined using
6712c59dd65SChristoph Lameter * fls.
6722c59dd65SChristoph Lameter */
673d5f86655SAlexey Dobriyan static u8 size_index[24] __ro_after_init = {
6742c59dd65SChristoph Lameter 3, /* 8 */
6752c59dd65SChristoph Lameter 4, /* 16 */
6762c59dd65SChristoph Lameter 5, /* 24 */
6772c59dd65SChristoph Lameter 5, /* 32 */
6782c59dd65SChristoph Lameter 6, /* 40 */
6792c59dd65SChristoph Lameter 6, /* 48 */
6802c59dd65SChristoph Lameter 6, /* 56 */
6812c59dd65SChristoph Lameter 6, /* 64 */
6822c59dd65SChristoph Lameter 1, /* 72 */
6832c59dd65SChristoph Lameter 1, /* 80 */
6842c59dd65SChristoph Lameter 1, /* 88 */
6852c59dd65SChristoph Lameter 1, /* 96 */
6862c59dd65SChristoph Lameter 7, /* 104 */
6872c59dd65SChristoph Lameter 7, /* 112 */
6882c59dd65SChristoph Lameter 7, /* 120 */
6892c59dd65SChristoph Lameter 7, /* 128 */
6902c59dd65SChristoph Lameter 2, /* 136 */
6912c59dd65SChristoph Lameter 2, /* 144 */
6922c59dd65SChristoph Lameter 2, /* 152 */
6932c59dd65SChristoph Lameter 2, /* 160 */
6942c59dd65SChristoph Lameter 2, /* 168 */
6952c59dd65SChristoph Lameter 2, /* 176 */
6962c59dd65SChristoph Lameter 2, /* 184 */
6972c59dd65SChristoph Lameter 2 /* 192 */
6982c59dd65SChristoph Lameter };
6992c59dd65SChristoph Lameter
size_index_elem(unsigned int bytes)700ac914d08SAlexey Dobriyan static inline unsigned int size_index_elem(unsigned int bytes)
7012c59dd65SChristoph Lameter {
7022c59dd65SChristoph Lameter return (bytes - 1) / 8;
7032c59dd65SChristoph Lameter }
7042c59dd65SChristoph Lameter
7052c59dd65SChristoph Lameter /*
7062c59dd65SChristoph Lameter * Find the kmem_cache structure that serves a given size of
7072c59dd65SChristoph Lameter * allocation
7082c59dd65SChristoph Lameter */
kmalloc_slab(size_t size,gfp_t flags,unsigned long caller)7093c615294SGONG, Ruiqi struct kmem_cache *kmalloc_slab(size_t size, gfp_t flags, unsigned long caller)
7102c59dd65SChristoph Lameter {
711d5f86655SAlexey Dobriyan unsigned int index;
7122c59dd65SChristoph Lameter
7132c59dd65SChristoph Lameter if (size <= 192) {
7142c59dd65SChristoph Lameter if (!size)
7152c59dd65SChristoph Lameter return ZERO_SIZE_PTR;
7162c59dd65SChristoph Lameter
7172c59dd65SChristoph Lameter index = size_index[size_index_elem(size)];
71861448479SDmitry Vyukov } else {
719221d7da6SYangtao Li if (WARN_ON_ONCE(size > KMALLOC_MAX_CACHE_SIZE))
72061448479SDmitry Vyukov return NULL;
7212c59dd65SChristoph Lameter index = fls(size - 1);
72261448479SDmitry Vyukov }
7232c59dd65SChristoph Lameter
7243c615294SGONG, Ruiqi return kmalloc_caches[kmalloc_type(flags, caller)][index];
7252c59dd65SChristoph Lameter }
7262c59dd65SChristoph Lameter
kmalloc_size_roundup(size_t size)72705a94065SKees Cook size_t kmalloc_size_roundup(size_t size)
72805a94065SKees Cook {
7298446a4deSDavid Laight if (size && size <= KMALLOC_MAX_CACHE_SIZE) {
7303c615294SGONG, Ruiqi /*
7313c615294SGONG, Ruiqi * The flags don't matter since size_index is common to all.
7323c615294SGONG, Ruiqi * Neither does the caller for just getting ->object_size.
7333c615294SGONG, Ruiqi */
7348446a4deSDavid Laight return kmalloc_slab(size, GFP_KERNEL, 0)->object_size;
7358446a4deSDavid Laight }
7368446a4deSDavid Laight
7378446a4deSDavid Laight /* Above the smaller buckets, size is a multiple of page size. */
7388446a4deSDavid Laight if (size && size <= KMALLOC_MAX_SIZE)
7398446a4deSDavid Laight return PAGE_SIZE << get_order(size);
7408446a4deSDavid Laight
7418446a4deSDavid Laight /*
7428446a4deSDavid Laight * Return 'size' for 0 - kmalloc() returns ZERO_SIZE_PTR
7438446a4deSDavid Laight * and very large size - kmalloc() may fail.
7448446a4deSDavid Laight */
7458446a4deSDavid Laight return size;
7468446a4deSDavid Laight
74705a94065SKees Cook }
74805a94065SKees Cook EXPORT_SYMBOL(kmalloc_size_roundup);
74905a94065SKees Cook
750cb5d9fb3SPengfei Li #ifdef CONFIG_ZONE_DMA
751494c1dfeSWaiman Long #define KMALLOC_DMA_NAME(sz) .name[KMALLOC_DMA] = "dma-kmalloc-" #sz,
752cb5d9fb3SPengfei Li #else
753494c1dfeSWaiman Long #define KMALLOC_DMA_NAME(sz)
754494c1dfeSWaiman Long #endif
755494c1dfeSWaiman Long
756494c1dfeSWaiman Long #ifdef CONFIG_MEMCG_KMEM
757494c1dfeSWaiman Long #define KMALLOC_CGROUP_NAME(sz) .name[KMALLOC_CGROUP] = "kmalloc-cg-" #sz,
758494c1dfeSWaiman Long #else
759494c1dfeSWaiman Long #define KMALLOC_CGROUP_NAME(sz)
760494c1dfeSWaiman Long #endif
761494c1dfeSWaiman Long
7622f7c1c13SVlastimil Babka #ifndef CONFIG_SLUB_TINY
7632f7c1c13SVlastimil Babka #define KMALLOC_RCL_NAME(sz) .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #sz,
7642f7c1c13SVlastimil Babka #else
7652f7c1c13SVlastimil Babka #define KMALLOC_RCL_NAME(sz)
7662f7c1c13SVlastimil Babka #endif
7672f7c1c13SVlastimil Babka
7683c615294SGONG, Ruiqi #ifdef CONFIG_RANDOM_KMALLOC_CACHES
7693c615294SGONG, Ruiqi #define __KMALLOC_RANDOM_CONCAT(a, b) a ## b
7703c615294SGONG, Ruiqi #define KMALLOC_RANDOM_NAME(N, sz) __KMALLOC_RANDOM_CONCAT(KMA_RAND_, N)(sz)
7713c615294SGONG, Ruiqi #define KMA_RAND_1(sz) .name[KMALLOC_RANDOM_START + 1] = "kmalloc-rnd-01-" #sz,
7723c615294SGONG, Ruiqi #define KMA_RAND_2(sz) KMA_RAND_1(sz) .name[KMALLOC_RANDOM_START + 2] = "kmalloc-rnd-02-" #sz,
7733c615294SGONG, Ruiqi #define KMA_RAND_3(sz) KMA_RAND_2(sz) .name[KMALLOC_RANDOM_START + 3] = "kmalloc-rnd-03-" #sz,
7743c615294SGONG, Ruiqi #define KMA_RAND_4(sz) KMA_RAND_3(sz) .name[KMALLOC_RANDOM_START + 4] = "kmalloc-rnd-04-" #sz,
7753c615294SGONG, Ruiqi #define KMA_RAND_5(sz) KMA_RAND_4(sz) .name[KMALLOC_RANDOM_START + 5] = "kmalloc-rnd-05-" #sz,
7763c615294SGONG, Ruiqi #define KMA_RAND_6(sz) KMA_RAND_5(sz) .name[KMALLOC_RANDOM_START + 6] = "kmalloc-rnd-06-" #sz,
7773c615294SGONG, Ruiqi #define KMA_RAND_7(sz) KMA_RAND_6(sz) .name[KMALLOC_RANDOM_START + 7] = "kmalloc-rnd-07-" #sz,
7783c615294SGONG, Ruiqi #define KMA_RAND_8(sz) KMA_RAND_7(sz) .name[KMALLOC_RANDOM_START + 8] = "kmalloc-rnd-08-" #sz,
7793c615294SGONG, Ruiqi #define KMA_RAND_9(sz) KMA_RAND_8(sz) .name[KMALLOC_RANDOM_START + 9] = "kmalloc-rnd-09-" #sz,
7803c615294SGONG, Ruiqi #define KMA_RAND_10(sz) KMA_RAND_9(sz) .name[KMALLOC_RANDOM_START + 10] = "kmalloc-rnd-10-" #sz,
7813c615294SGONG, Ruiqi #define KMA_RAND_11(sz) KMA_RAND_10(sz) .name[KMALLOC_RANDOM_START + 11] = "kmalloc-rnd-11-" #sz,
7823c615294SGONG, Ruiqi #define KMA_RAND_12(sz) KMA_RAND_11(sz) .name[KMALLOC_RANDOM_START + 12] = "kmalloc-rnd-12-" #sz,
7833c615294SGONG, Ruiqi #define KMA_RAND_13(sz) KMA_RAND_12(sz) .name[KMALLOC_RANDOM_START + 13] = "kmalloc-rnd-13-" #sz,
7843c615294SGONG, Ruiqi #define KMA_RAND_14(sz) KMA_RAND_13(sz) .name[KMALLOC_RANDOM_START + 14] = "kmalloc-rnd-14-" #sz,
7853c615294SGONG, Ruiqi #define KMA_RAND_15(sz) KMA_RAND_14(sz) .name[KMALLOC_RANDOM_START + 15] = "kmalloc-rnd-15-" #sz,
7863c615294SGONG, Ruiqi #else // CONFIG_RANDOM_KMALLOC_CACHES
7873c615294SGONG, Ruiqi #define KMALLOC_RANDOM_NAME(N, sz)
7883c615294SGONG, Ruiqi #endif
7893c615294SGONG, Ruiqi
790cb5d9fb3SPengfei Li #define INIT_KMALLOC_INFO(__size, __short_size) \
791cb5d9fb3SPengfei Li { \
792cb5d9fb3SPengfei Li .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \
7932f7c1c13SVlastimil Babka KMALLOC_RCL_NAME(__short_size) \
794494c1dfeSWaiman Long KMALLOC_CGROUP_NAME(__short_size) \
795494c1dfeSWaiman Long KMALLOC_DMA_NAME(__short_size) \
7963c615294SGONG, Ruiqi KMALLOC_RANDOM_NAME(RANDOM_KMALLOC_CACHES_NR, __short_size) \
797cb5d9fb3SPengfei Li .size = __size, \
798cb5d9fb3SPengfei Li }
799cb5d9fb3SPengfei Li
8002c59dd65SChristoph Lameter /*
8014066c33dSGavin Guo * kmalloc_info[] is to make slub_debug=,kmalloc-xx option work at boot time.
802d6a71648SHyeonggon Yoo * kmalloc_index() supports up to 2^21=2MB, so the final entry of the table is
803d6a71648SHyeonggon Yoo * kmalloc-2M.
8044066c33dSGavin Guo */
805af3b5f87SVlastimil Babka const struct kmalloc_info_struct kmalloc_info[] __initconst = {
806cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(0, 0),
807cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(96, 96),
808cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(192, 192),
809cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(8, 8),
810cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(16, 16),
811cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(32, 32),
812cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(64, 64),
813cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(128, 128),
814cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(256, 256),
815cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(512, 512),
816cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(1024, 1k),
817cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(2048, 2k),
818cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(4096, 4k),
819cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(8192, 8k),
820cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(16384, 16k),
821cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(32768, 32k),
822cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(65536, 64k),
823cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(131072, 128k),
824cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(262144, 256k),
825cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(524288, 512k),
826cb5d9fb3SPengfei Li INIT_KMALLOC_INFO(1048576, 1M),
827d6a71648SHyeonggon Yoo INIT_KMALLOC_INFO(2097152, 2M)
8284066c33dSGavin Guo };
8294066c33dSGavin Guo
8304066c33dSGavin Guo /*
8312c59dd65SChristoph Lameter * Patch up the size_index table if we have strange large alignment
8322c59dd65SChristoph Lameter * requirements for the kmalloc array. This is only the case for
8332c59dd65SChristoph Lameter * MIPS it seems. The standard arches will not generate any code here.
8342c59dd65SChristoph Lameter *
8352c59dd65SChristoph Lameter * Largest permitted alignment is 256 bytes due to the way we
8362c59dd65SChristoph Lameter * handle the index determination for the smaller caches.
8372c59dd65SChristoph Lameter *
8382c59dd65SChristoph Lameter * Make sure that nothing crazy happens if someone starts tinkering
8392c59dd65SChristoph Lameter * around with ARCH_KMALLOC_MINALIGN
8402c59dd65SChristoph Lameter */
setup_kmalloc_cache_index_table(void)84134cc6990SDaniel Sanders void __init setup_kmalloc_cache_index_table(void)
84234cc6990SDaniel Sanders {
843ac914d08SAlexey Dobriyan unsigned int i;
84434cc6990SDaniel Sanders
8452c59dd65SChristoph Lameter BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
8467d6b6cc3SMiaohe Lin !is_power_of_2(KMALLOC_MIN_SIZE));
8472c59dd65SChristoph Lameter
8482c59dd65SChristoph Lameter for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
849ac914d08SAlexey Dobriyan unsigned int elem = size_index_elem(i);
8502c59dd65SChristoph Lameter
8512c59dd65SChristoph Lameter if (elem >= ARRAY_SIZE(size_index))
8522c59dd65SChristoph Lameter break;
8532c59dd65SChristoph Lameter size_index[elem] = KMALLOC_SHIFT_LOW;
8542c59dd65SChristoph Lameter }
8552c59dd65SChristoph Lameter
8562c59dd65SChristoph Lameter if (KMALLOC_MIN_SIZE >= 64) {
8572c59dd65SChristoph Lameter /*
8580b8f0d87SQuanfa Fu * The 96 byte sized cache is not used if the alignment
8592c59dd65SChristoph Lameter * is 64 byte.
8602c59dd65SChristoph Lameter */
8612c59dd65SChristoph Lameter for (i = 64 + 8; i <= 96; i += 8)
8622c59dd65SChristoph Lameter size_index[size_index_elem(i)] = 7;
8632c59dd65SChristoph Lameter
8642c59dd65SChristoph Lameter }
8652c59dd65SChristoph Lameter
8662c59dd65SChristoph Lameter if (KMALLOC_MIN_SIZE >= 128) {
8672c59dd65SChristoph Lameter /*
8682c59dd65SChristoph Lameter * The 192 byte sized cache is not used if the alignment
8692c59dd65SChristoph Lameter * is 128 byte. Redirect kmalloc to use the 256 byte cache
8702c59dd65SChristoph Lameter * instead.
8712c59dd65SChristoph Lameter */
8722c59dd65SChristoph Lameter for (i = 128 + 8; i <= 192; i += 8)
8732c59dd65SChristoph Lameter size_index[size_index_elem(i)] = 8;
8742c59dd65SChristoph Lameter }
87534cc6990SDaniel Sanders }
87634cc6990SDaniel Sanders
__kmalloc_minalign(void)877963e84b0SCatalin Marinas static unsigned int __kmalloc_minalign(void)
878963e84b0SCatalin Marinas {
879c15cdea5SCatalin Marinas unsigned int minalign = dma_get_cache_alignment();
880c15cdea5SCatalin Marinas
88105ee7741SPetr Tesarik if (IS_ENABLED(CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC) &&
88205ee7741SPetr Tesarik is_swiotlb_allocated())
883c15cdea5SCatalin Marinas minalign = ARCH_KMALLOC_MINALIGN;
884c15cdea5SCatalin Marinas
885c15cdea5SCatalin Marinas return max(minalign, arch_slab_minalign());
886963e84b0SCatalin Marinas }
887963e84b0SCatalin Marinas
8880c474d31SCatalin Marinas void __init
new_kmalloc_cache(int idx,enum kmalloc_cache_type type,slab_flags_t flags)88913657d0aSPengfei Li new_kmalloc_cache(int idx, enum kmalloc_cache_type type, slab_flags_t flags)
890a9730fcaSChristoph Lameter {
891963e84b0SCatalin Marinas unsigned int minalign = __kmalloc_minalign();
892963e84b0SCatalin Marinas unsigned int aligned_size = kmalloc_info[idx].size;
893963e84b0SCatalin Marinas int aligned_idx = idx;
894963e84b0SCatalin Marinas
8952f7c1c13SVlastimil Babka if ((KMALLOC_RECLAIM != KMALLOC_NORMAL) && (type == KMALLOC_RECLAIM)) {
8961291523fSVlastimil Babka flags |= SLAB_RECLAIM_ACCOUNT;
897494c1dfeSWaiman Long } else if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_CGROUP)) {
89817c17367SMuchun Song if (mem_cgroup_kmem_disabled()) {
899494c1dfeSWaiman Long kmalloc_caches[type][idx] = kmalloc_caches[KMALLOC_NORMAL][idx];
900494c1dfeSWaiman Long return;
901494c1dfeSWaiman Long }
902494c1dfeSWaiman Long flags |= SLAB_ACCOUNT;
90333647783SOhhoon Kwon } else if (IS_ENABLED(CONFIG_ZONE_DMA) && (type == KMALLOC_DMA)) {
90433647783SOhhoon Kwon flags |= SLAB_CACHE_DMA;
905494c1dfeSWaiman Long }
9061291523fSVlastimil Babka
9073c615294SGONG, Ruiqi #ifdef CONFIG_RANDOM_KMALLOC_CACHES
9083c615294SGONG, Ruiqi if (type >= KMALLOC_RANDOM_START && type <= KMALLOC_RANDOM_END)
9093c615294SGONG, Ruiqi flags |= SLAB_NO_MERGE;
9103c615294SGONG, Ruiqi #endif
9113c615294SGONG, Ruiqi
91213e680fbSWaiman Long /*
91313e680fbSWaiman Long * If CONFIG_MEMCG_KMEM is enabled, disable cache merging for
91413e680fbSWaiman Long * KMALLOC_NORMAL caches.
91513e680fbSWaiman Long */
91613e680fbSWaiman Long if (IS_ENABLED(CONFIG_MEMCG_KMEM) && (type == KMALLOC_NORMAL))
917d5bf4857SVlastimil Babka flags |= SLAB_NO_MERGE;
918d5bf4857SVlastimil Babka
919963e84b0SCatalin Marinas if (minalign > ARCH_KMALLOC_MINALIGN) {
920963e84b0SCatalin Marinas aligned_size = ALIGN(aligned_size, minalign);
921963e84b0SCatalin Marinas aligned_idx = __kmalloc_index(aligned_size, false);
922963e84b0SCatalin Marinas }
923963e84b0SCatalin Marinas
924963e84b0SCatalin Marinas if (!kmalloc_caches[type][aligned_idx])
925963e84b0SCatalin Marinas kmalloc_caches[type][aligned_idx] = create_kmalloc_cache(
926963e84b0SCatalin Marinas kmalloc_info[aligned_idx].name[type],
927963e84b0SCatalin Marinas aligned_size, flags);
928963e84b0SCatalin Marinas if (idx != aligned_idx)
929963e84b0SCatalin Marinas kmalloc_caches[type][idx] = kmalloc_caches[type][aligned_idx];
930a9730fcaSChristoph Lameter }
931a9730fcaSChristoph Lameter
93234cc6990SDaniel Sanders /*
93334cc6990SDaniel Sanders * Create the kmalloc array. Some of the regular kmalloc arrays
93434cc6990SDaniel Sanders * may already have been created because they were needed to
93534cc6990SDaniel Sanders * enable allocations for slab creation.
93634cc6990SDaniel Sanders */
create_kmalloc_caches(slab_flags_t flags)937d50112edSAlexey Dobriyan void __init create_kmalloc_caches(slab_flags_t flags)
93834cc6990SDaniel Sanders {
93913657d0aSPengfei Li int i;
94013657d0aSPengfei Li enum kmalloc_cache_type type;
94134cc6990SDaniel Sanders
942494c1dfeSWaiman Long /*
943494c1dfeSWaiman Long * Including KMALLOC_CGROUP if CONFIG_MEMCG_KMEM defined
944494c1dfeSWaiman Long */
94533647783SOhhoon Kwon for (type = KMALLOC_NORMAL; type < NR_KMALLOC_TYPES; type++) {
946a9730fcaSChristoph Lameter for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
947cc252eaeSVlastimil Babka if (!kmalloc_caches[type][i])
9481291523fSVlastimil Babka new_kmalloc_cache(i, type, flags);
949f97d5f63SChristoph Lameter
9508a965b3bSChristoph Lameter /*
951a9730fcaSChristoph Lameter * Caches that are not of the two-to-the-power-of size.
952a9730fcaSChristoph Lameter * These have to be created immediately after the
953a9730fcaSChristoph Lameter * earlier power of two caches
9548a965b3bSChristoph Lameter */
9551291523fSVlastimil Babka if (KMALLOC_MIN_SIZE <= 32 && i == 6 &&
9561291523fSVlastimil Babka !kmalloc_caches[type][1])
9571291523fSVlastimil Babka new_kmalloc_cache(1, type, flags);
9581291523fSVlastimil Babka if (KMALLOC_MIN_SIZE <= 64 && i == 7 &&
9591291523fSVlastimil Babka !kmalloc_caches[type][2])
9601291523fSVlastimil Babka new_kmalloc_cache(2, type, flags);
9611291523fSVlastimil Babka }
9628a965b3bSChristoph Lameter }
9633c615294SGONG, Ruiqi #ifdef CONFIG_RANDOM_KMALLOC_CACHES
9643c615294SGONG, Ruiqi random_kmalloc_seed = get_random_u64();
9653c615294SGONG, Ruiqi #endif
9668a965b3bSChristoph Lameter
967f97d5f63SChristoph Lameter /* Kmalloc array is now usable */
968f97d5f63SChristoph Lameter slab_state = UP;
969f97d5f63SChristoph Lameter }
970d6a71648SHyeonggon Yoo
free_large_kmalloc(struct folio * folio,void * object)971d6a71648SHyeonggon Yoo void free_large_kmalloc(struct folio *folio, void *object)
972d6a71648SHyeonggon Yoo {
973d6a71648SHyeonggon Yoo unsigned int order = folio_order(folio);
974d6a71648SHyeonggon Yoo
975d6a71648SHyeonggon Yoo if (WARN_ON_ONCE(order == 0))
976d6a71648SHyeonggon Yoo pr_warn_once("object pointer: 0x%p\n", object);
977d6a71648SHyeonggon Yoo
978d6a71648SHyeonggon Yoo kmemleak_free(object);
979d6a71648SHyeonggon Yoo kasan_kfree_large(object);
98027bc50fcSLinus Torvalds kmsan_kfree_large(object);
981d6a71648SHyeonggon Yoo
982d6a71648SHyeonggon Yoo mod_lruvec_page_state(folio_page(folio, 0), NR_SLAB_UNRECLAIMABLE_B,
983d6a71648SHyeonggon Yoo -(PAGE_SIZE << order));
984d6a71648SHyeonggon Yoo __free_pages(folio_page(folio, 0), order);
985d6a71648SHyeonggon Yoo }
986b1405135SHyeonggon Yoo
987b1405135SHyeonggon Yoo static void *__kmalloc_large_node(size_t size, gfp_t flags, int node);
988b1405135SHyeonggon Yoo static __always_inline
__do_kmalloc_node(size_t size,gfp_t flags,int node,unsigned long caller)989b1405135SHyeonggon Yoo void *__do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
990b1405135SHyeonggon Yoo {
991b1405135SHyeonggon Yoo struct kmem_cache *s;
992b1405135SHyeonggon Yoo void *ret;
993b1405135SHyeonggon Yoo
994b1405135SHyeonggon Yoo if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
995b1405135SHyeonggon Yoo ret = __kmalloc_large_node(size, flags, node);
99632868715SKees Cook trace_kmalloc(caller, ret, size,
99711e9734bSHyeonggon Yoo PAGE_SIZE << get_order(size), flags, node);
998b1405135SHyeonggon Yoo return ret;
999b1405135SHyeonggon Yoo }
1000b1405135SHyeonggon Yoo
10013c615294SGONG, Ruiqi s = kmalloc_slab(size, flags, caller);
1002b1405135SHyeonggon Yoo
1003b1405135SHyeonggon Yoo if (unlikely(ZERO_OR_NULL_PTR(s)))
1004b1405135SHyeonggon Yoo return s;
1005b1405135SHyeonggon Yoo
1006b1405135SHyeonggon Yoo ret = __kmem_cache_alloc_node(s, flags, node, size, caller);
1007b1405135SHyeonggon Yoo ret = kasan_kmalloc(s, ret, size, flags);
100832868715SKees Cook trace_kmalloc(caller, ret, size, s->size, flags, node);
1009b1405135SHyeonggon Yoo return ret;
1010b1405135SHyeonggon Yoo }
1011b1405135SHyeonggon Yoo
__kmalloc_node(size_t size,gfp_t flags,int node)1012b1405135SHyeonggon Yoo void *__kmalloc_node(size_t size, gfp_t flags, int node)
1013b1405135SHyeonggon Yoo {
1014b1405135SHyeonggon Yoo return __do_kmalloc_node(size, flags, node, _RET_IP_);
1015b1405135SHyeonggon Yoo }
1016b1405135SHyeonggon Yoo EXPORT_SYMBOL(__kmalloc_node);
1017b1405135SHyeonggon Yoo
__kmalloc(size_t size,gfp_t flags)1018b1405135SHyeonggon Yoo void *__kmalloc(size_t size, gfp_t flags)
1019b1405135SHyeonggon Yoo {
1020b1405135SHyeonggon Yoo return __do_kmalloc_node(size, flags, NUMA_NO_NODE, _RET_IP_);
1021b1405135SHyeonggon Yoo }
1022b1405135SHyeonggon Yoo EXPORT_SYMBOL(__kmalloc);
1023b1405135SHyeonggon Yoo
__kmalloc_node_track_caller(size_t size,gfp_t flags,int node,unsigned long caller)1024b1405135SHyeonggon Yoo void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
1025b1405135SHyeonggon Yoo int node, unsigned long caller)
1026b1405135SHyeonggon Yoo {
1027b1405135SHyeonggon Yoo return __do_kmalloc_node(size, flags, node, caller);
1028b1405135SHyeonggon Yoo }
1029b1405135SHyeonggon Yoo EXPORT_SYMBOL(__kmalloc_node_track_caller);
1030b1405135SHyeonggon Yoo
1031b1405135SHyeonggon Yoo /**
1032b1405135SHyeonggon Yoo * kfree - free previously allocated memory
1033ae65a521SVlastimil Babka * @object: pointer returned by kmalloc() or kmem_cache_alloc()
1034b1405135SHyeonggon Yoo *
1035b1405135SHyeonggon Yoo * If @object is NULL, no operation is performed.
1036b1405135SHyeonggon Yoo */
kfree(const void * object)1037b1405135SHyeonggon Yoo void kfree(const void *object)
1038b1405135SHyeonggon Yoo {
1039b1405135SHyeonggon Yoo struct folio *folio;
1040b1405135SHyeonggon Yoo struct slab *slab;
1041b1405135SHyeonggon Yoo struct kmem_cache *s;
1042b1405135SHyeonggon Yoo
1043b1405135SHyeonggon Yoo trace_kfree(_RET_IP_, object);
1044b1405135SHyeonggon Yoo
1045b1405135SHyeonggon Yoo if (unlikely(ZERO_OR_NULL_PTR(object)))
1046b1405135SHyeonggon Yoo return;
1047b1405135SHyeonggon Yoo
1048b1405135SHyeonggon Yoo folio = virt_to_folio(object);
1049b1405135SHyeonggon Yoo if (unlikely(!folio_test_slab(folio))) {
1050b1405135SHyeonggon Yoo free_large_kmalloc(folio, (void *)object);
1051b1405135SHyeonggon Yoo return;
1052b1405135SHyeonggon Yoo }
1053b1405135SHyeonggon Yoo
1054b1405135SHyeonggon Yoo slab = folio_slab(folio);
1055b1405135SHyeonggon Yoo s = slab->slab_cache;
1056b1405135SHyeonggon Yoo __kmem_cache_free(s, (void *)object, _RET_IP_);
1057b1405135SHyeonggon Yoo }
1058b1405135SHyeonggon Yoo EXPORT_SYMBOL(kfree);
1059b1405135SHyeonggon Yoo
1060445d41d7SVlastimil Babka /**
1061445d41d7SVlastimil Babka * __ksize -- Report full size of underlying allocation
1062a2076201SLukas Bulwahn * @object: pointer to the object
1063445d41d7SVlastimil Babka *
1064445d41d7SVlastimil Babka * This should only be used internally to query the true size of allocations.
1065445d41d7SVlastimil Babka * It is not meant to be a way to discover the usable size of an allocation
1066445d41d7SVlastimil Babka * after the fact. Instead, use kmalloc_size_roundup(). Using memory beyond
1067445d41d7SVlastimil Babka * the originally requested allocation size may trigger KASAN, UBSAN_BOUNDS,
1068445d41d7SVlastimil Babka * and/or FORTIFY_SOURCE.
1069445d41d7SVlastimil Babka *
1070a2076201SLukas Bulwahn * Return: size of the actual memory used by @object in bytes
1071445d41d7SVlastimil Babka */
__ksize(const void * object)1072b1405135SHyeonggon Yoo size_t __ksize(const void *object)
1073b1405135SHyeonggon Yoo {
1074b1405135SHyeonggon Yoo struct folio *folio;
1075b1405135SHyeonggon Yoo
1076b1405135SHyeonggon Yoo if (unlikely(object == ZERO_SIZE_PTR))
1077b1405135SHyeonggon Yoo return 0;
1078b1405135SHyeonggon Yoo
1079b1405135SHyeonggon Yoo folio = virt_to_folio(object);
1080b1405135SHyeonggon Yoo
1081d5eff736SHyeonggon Yoo if (unlikely(!folio_test_slab(folio))) {
1082d5eff736SHyeonggon Yoo if (WARN_ON(folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE))
1083d5eff736SHyeonggon Yoo return 0;
1084d5eff736SHyeonggon Yoo if (WARN_ON(object != folio_address(folio)))
1085d5eff736SHyeonggon Yoo return 0;
1086b1405135SHyeonggon Yoo return folio_size(folio);
1087d5eff736SHyeonggon Yoo }
1088b1405135SHyeonggon Yoo
1089946fa0dbSFeng Tang #ifdef CONFIG_SLUB_DEBUG
1090946fa0dbSFeng Tang skip_orig_size_check(folio_slab(folio)->slab_cache, object);
1091946fa0dbSFeng Tang #endif
1092946fa0dbSFeng Tang
1093b1405135SHyeonggon Yoo return slab_ksize(folio_slab(folio)->slab_cache);
1094b1405135SHyeonggon Yoo }
109526a40990SHyeonggon Yoo
kmalloc_trace(struct kmem_cache * s,gfp_t gfpflags,size_t size)109626a40990SHyeonggon Yoo void *kmalloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
109726a40990SHyeonggon Yoo {
109826a40990SHyeonggon Yoo void *ret = __kmem_cache_alloc_node(s, gfpflags, NUMA_NO_NODE,
109926a40990SHyeonggon Yoo size, _RET_IP_);
110026a40990SHyeonggon Yoo
11012c1d697fSHyeonggon Yoo trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
110226a40990SHyeonggon Yoo
110326a40990SHyeonggon Yoo ret = kasan_kmalloc(s, ret, size, gfpflags);
110426a40990SHyeonggon Yoo return ret;
110526a40990SHyeonggon Yoo }
110626a40990SHyeonggon Yoo EXPORT_SYMBOL(kmalloc_trace);
110726a40990SHyeonggon Yoo
kmalloc_node_trace(struct kmem_cache * s,gfp_t gfpflags,int node,size_t size)110826a40990SHyeonggon Yoo void *kmalloc_node_trace(struct kmem_cache *s, gfp_t gfpflags,
110926a40990SHyeonggon Yoo int node, size_t size)
111026a40990SHyeonggon Yoo {
111126a40990SHyeonggon Yoo void *ret = __kmem_cache_alloc_node(s, gfpflags, node, size, _RET_IP_);
111226a40990SHyeonggon Yoo
11132c1d697fSHyeonggon Yoo trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
111426a40990SHyeonggon Yoo
111526a40990SHyeonggon Yoo ret = kasan_kmalloc(s, ret, size, gfpflags);
111626a40990SHyeonggon Yoo return ret;
111726a40990SHyeonggon Yoo }
111826a40990SHyeonggon Yoo EXPORT_SYMBOL(kmalloc_node_trace);
111945530c44SChristoph Lameter
kmalloc_fix_flags(gfp_t flags)112044405099SLong Li gfp_t kmalloc_fix_flags(gfp_t flags)
112144405099SLong Li {
112244405099SLong Li gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
112344405099SLong Li
112444405099SLong Li flags &= ~GFP_SLAB_BUG_MASK;
112544405099SLong Li pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
112644405099SLong Li invalid_mask, &invalid_mask, flags, &flags);
112744405099SLong Li dump_stack();
112844405099SLong Li
112944405099SLong Li return flags;
113044405099SLong Li }
113144405099SLong Li
1132cea371f4SVladimir Davydov /*
1133cea371f4SVladimir Davydov * To avoid unnecessary overhead, we pass through large allocation requests
1134cea371f4SVladimir Davydov * directly to the page allocator. We use __GFP_COMP, because we will need to
1135cea371f4SVladimir Davydov * know the allocation order to free the pages properly in kfree.
1136cea371f4SVladimir Davydov */
113745530c44SChristoph Lameter
__kmalloc_large_node(size_t size,gfp_t flags,int node)1138b1405135SHyeonggon Yoo static void *__kmalloc_large_node(size_t size, gfp_t flags, int node)
1139749c5415SGlauber Costa {
1140749c5415SGlauber Costa struct page *page;
1141a0c3b940SHyeonggon Yoo void *ptr = NULL;
1142a0c3b940SHyeonggon Yoo unsigned int order = get_order(size);
1143749c5415SGlauber Costa
1144749c5415SGlauber Costa if (unlikely(flags & GFP_SLAB_BUG_MASK))
1145749c5415SGlauber Costa flags = kmalloc_fix_flags(flags);
1146749c5415SGlauber Costa
1147749c5415SGlauber Costa flags |= __GFP_COMP;
1148a0c3b940SHyeonggon Yoo page = alloc_pages_node(node, flags, order);
1149a0c3b940SHyeonggon Yoo if (page) {
1150a0c3b940SHyeonggon Yoo ptr = page_address(page);
1151bcee6e2aSGlauber Costa mod_lruvec_page_state(page, NR_SLAB_UNRECLAIMABLE_B,
1152bcee6e2aSGlauber Costa PAGE_SIZE << order);
1153bcee6e2aSGlauber Costa }
1154749c5415SGlauber Costa
1155a0c3b940SHyeonggon Yoo ptr = kasan_kmalloc_large(ptr, size, flags);
1156a0c3b940SHyeonggon Yoo /* As ptr might get tagged, call kmemleak hook after KASAN. */
1157a0c3b940SHyeonggon Yoo kmemleak_alloc(ptr, size, 1, flags);
115827bc50fcSLinus Torvalds kmsan_kmalloc_large(ptr, size, flags);
1159a0c3b940SHyeonggon Yoo
1160a0c3b940SHyeonggon Yoo return ptr;
1161a0c3b940SHyeonggon Yoo }
1162bf37d791SHyeonggon Yoo
kmalloc_large(size_t size,gfp_t flags)1163c4cab557SHyeonggon Yoo void *kmalloc_large(size_t size, gfp_t flags)
1164749c5415SGlauber Costa {
1165b1405135SHyeonggon Yoo void *ret = __kmalloc_large_node(size, flags, NUMA_NO_NODE);
1166c4cab557SHyeonggon Yoo
11672c1d697fSHyeonggon Yoo trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
11682c1d697fSHyeonggon Yoo flags, NUMA_NO_NODE);
1169b7454ad3SGlauber Costa return ret;
1170b7454ad3SGlauber Costa }
1171c4cab557SHyeonggon Yoo EXPORT_SYMBOL(kmalloc_large);
1172c4cab557SHyeonggon Yoo
kmalloc_large_node(size_t size,gfp_t flags,int node)1173bf37d791SHyeonggon Yoo void *kmalloc_large_node(size_t size, gfp_t flags, int node)
1174bf37d791SHyeonggon Yoo {
1175b1405135SHyeonggon Yoo void *ret = __kmalloc_large_node(size, flags, node);
1176bf37d791SHyeonggon Yoo
11772c1d697fSHyeonggon Yoo trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
11782c1d697fSHyeonggon Yoo flags, node);
1179bf37d791SHyeonggon Yoo return ret;
1180bf37d791SHyeonggon Yoo }
1181a0c3b940SHyeonggon Yoo EXPORT_SYMBOL(kmalloc_large_node);
1182749c5415SGlauber Costa
11837c00fce9SThomas Garnier #ifdef CONFIG_SLAB_FREELIST_RANDOM
11847c00fce9SThomas Garnier /* Randomize a generic freelist */
freelist_randomize(unsigned int * list,unsigned int count)1185ffe4dfe0SDavid Keisar Schmidt static void freelist_randomize(unsigned int *list,
1186302d55d5SAlexey Dobriyan unsigned int count)
11877c00fce9SThomas Garnier {
11887c00fce9SThomas Garnier unsigned int rand;
1189302d55d5SAlexey Dobriyan unsigned int i;
11907c00fce9SThomas Garnier
11917c00fce9SThomas Garnier for (i = 0; i < count; i++)
11927c00fce9SThomas Garnier list[i] = i;
11937c00fce9SThomas Garnier
11947c00fce9SThomas Garnier /* Fisher-Yates shuffle */
11957c00fce9SThomas Garnier for (i = count - 1; i > 0; i--) {
1196ffe4dfe0SDavid Keisar Schmidt rand = get_random_u32_below(i + 1);
11977c00fce9SThomas Garnier swap(list[i], list[rand]);
11987c00fce9SThomas Garnier }
11997c00fce9SThomas Garnier }
12007c00fce9SThomas Garnier
12017c00fce9SThomas Garnier /* Create a random sequence per cache */
cache_random_seq_create(struct kmem_cache * cachep,unsigned int count,gfp_t gfp)12027c00fce9SThomas Garnier int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count,
12037c00fce9SThomas Garnier gfp_t gfp)
12047c00fce9SThomas Garnier {
12057c00fce9SThomas Garnier
12067c00fce9SThomas Garnier if (count < 2 || cachep->random_seq)
12077c00fce9SThomas Garnier return 0;
12087c00fce9SThomas Garnier
12097c00fce9SThomas Garnier cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp);
12107c00fce9SThomas Garnier if (!cachep->random_seq)
12117c00fce9SThomas Garnier return -ENOMEM;
12127c00fce9SThomas Garnier
1213ffe4dfe0SDavid Keisar Schmidt freelist_randomize(cachep->random_seq, count);
12147c00fce9SThomas Garnier return 0;
12157c00fce9SThomas Garnier }
12167c00fce9SThomas Garnier
12177c00fce9SThomas Garnier /* Destroy the per-cache random freelist sequence */
cache_random_seq_destroy(struct kmem_cache * cachep)12187c00fce9SThomas Garnier void cache_random_seq_destroy(struct kmem_cache *cachep)
12197c00fce9SThomas Garnier {
12207c00fce9SThomas Garnier kfree(cachep->random_seq);
12217c00fce9SThomas Garnier cachep->random_seq = NULL;
12227c00fce9SThomas Garnier }
12237c00fce9SThomas Garnier #endif /* CONFIG_SLAB_FREELIST_RANDOM */
12247c00fce9SThomas Garnier
12255b365771SYang Shi #if defined(CONFIG_SLAB) || defined(CONFIG_SLUB_DEBUG)
1226749c5415SGlauber Costa #ifdef CONFIG_SLAB
12270825a6f9SJoe Perches #define SLABINFO_RIGHTS (0600)
1228b7454ad3SGlauber Costa #else
12290825a6f9SJoe Perches #define SLABINFO_RIGHTS (0400)
1230b7454ad3SGlauber Costa #endif
1231b7454ad3SGlauber Costa
print_slabinfo_header(struct seq_file * m)1232b047501cSVladimir Davydov static void print_slabinfo_header(struct seq_file *m)
1233b7454ad3SGlauber Costa {
1234b7454ad3SGlauber Costa /*
1235b7454ad3SGlauber Costa * Output format version, so at least we can change it
1236b7454ad3SGlauber Costa * without _too_ many complaints.
1237b7454ad3SGlauber Costa */
1238b7454ad3SGlauber Costa #ifdef CONFIG_DEBUG_SLAB
1239b7454ad3SGlauber Costa seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
1240b7454ad3SGlauber Costa #else
1241b7454ad3SGlauber Costa seq_puts(m, "slabinfo - version: 2.1\n");
1242b7454ad3SGlauber Costa #endif
1243756a025fSJoe Perches seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
1244b7454ad3SGlauber Costa seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
1245b7454ad3SGlauber Costa seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
1246b7454ad3SGlauber Costa #ifdef CONFIG_DEBUG_SLAB
1247756a025fSJoe Perches seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
1248b7454ad3SGlauber Costa seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
1249b7454ad3SGlauber Costa #endif
1250b7454ad3SGlauber Costa seq_putc(m, '\n');
1251b7454ad3SGlauber Costa }
1252b7454ad3SGlauber Costa
slab_start(struct seq_file * m,loff_t * pos)1253c29b5b3dSMuchun Song static void *slab_start(struct seq_file *m, loff_t *pos)
1254b7454ad3SGlauber Costa {
1255b7454ad3SGlauber Costa mutex_lock(&slab_mutex);
1256c7094406SRoman Gushchin return seq_list_start(&slab_caches, *pos);
1257b7454ad3SGlauber Costa }
1258b7454ad3SGlauber Costa
slab_next(struct seq_file * m,void * p,loff_t * pos)1259c29b5b3dSMuchun Song static void *slab_next(struct seq_file *m, void *p, loff_t *pos)
1260b7454ad3SGlauber Costa {
1261c7094406SRoman Gushchin return seq_list_next(p, &slab_caches, pos);
1262b7454ad3SGlauber Costa }
1263b7454ad3SGlauber Costa
slab_stop(struct seq_file * m,void * p)1264c29b5b3dSMuchun Song static void slab_stop(struct seq_file *m, void *p)
1265b7454ad3SGlauber Costa {
1266b7454ad3SGlauber Costa mutex_unlock(&slab_mutex);
1267b7454ad3SGlauber Costa }
1268b7454ad3SGlauber Costa
cache_show(struct kmem_cache * s,struct seq_file * m)1269b047501cSVladimir Davydov static void cache_show(struct kmem_cache *s, struct seq_file *m)
1270b7454ad3SGlauber Costa {
1271b7454ad3SGlauber Costa struct slabinfo sinfo;
12720d7561c6SGlauber Costa
12730d7561c6SGlauber Costa memset(&sinfo, 0, sizeof(sinfo));
12740d7561c6SGlauber Costa get_slabinfo(s, &sinfo);
12750d7561c6SGlauber Costa
12760d7561c6SGlauber Costa seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
127710befea9SRoman Gushchin s->name, sinfo.active_objs, sinfo.num_objs, s->size,
12780d7561c6SGlauber Costa sinfo.objects_per_slab, (1 << sinfo.cache_order));
12790d7561c6SGlauber Costa
12800d7561c6SGlauber Costa seq_printf(m, " : tunables %4u %4u %4u",
12810d7561c6SGlauber Costa sinfo.limit, sinfo.batchcount, sinfo.shared);
12820d7561c6SGlauber Costa seq_printf(m, " : slabdata %6lu %6lu %6lu",
12830d7561c6SGlauber Costa sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail);
12840d7561c6SGlauber Costa slabinfo_show_stats(m, s);
12850d7561c6SGlauber Costa seq_putc(m, '\n');
1286b7454ad3SGlauber Costa }
1287b7454ad3SGlauber Costa
slab_show(struct seq_file * m,void * p)12881df3b26fSVladimir Davydov static int slab_show(struct seq_file *m, void *p)
1289749c5415SGlauber Costa {
1290c7094406SRoman Gushchin struct kmem_cache *s = list_entry(p, struct kmem_cache, list);
1291749c5415SGlauber Costa
1292c7094406SRoman Gushchin if (p == slab_caches.next)
12931df3b26fSVladimir Davydov print_slabinfo_header(m);
1294b047501cSVladimir Davydov cache_show(s, m);
1295749c5415SGlauber Costa return 0;
1296749c5415SGlauber Costa }
1297749c5415SGlauber Costa
dump_unreclaimable_slab(void)1298852d8be0SYang Shi void dump_unreclaimable_slab(void)
1299852d8be0SYang Shi {
13007714304fSHui Su struct kmem_cache *s;
1301852d8be0SYang Shi struct slabinfo sinfo;
1302852d8be0SYang Shi
1303852d8be0SYang Shi /*
1304852d8be0SYang Shi * Here acquiring slab_mutex is risky since we don't prefer to get
1305852d8be0SYang Shi * sleep in oom path. But, without mutex hold, it may introduce a
1306852d8be0SYang Shi * risk of crash.
1307852d8be0SYang Shi * Use mutex_trylock to protect the list traverse, dump nothing
1308852d8be0SYang Shi * without acquiring the mutex.
1309852d8be0SYang Shi */
1310852d8be0SYang Shi if (!mutex_trylock(&slab_mutex)) {
1311852d8be0SYang Shi pr_warn("excessive unreclaimable slab but cannot dump stats\n");
1312852d8be0SYang Shi return;
1313852d8be0SYang Shi }
1314852d8be0SYang Shi
1315852d8be0SYang Shi pr_info("Unreclaimable slab info:\n");
1316852d8be0SYang Shi pr_info("Name Used Total\n");
1317852d8be0SYang Shi
13187714304fSHui Su list_for_each_entry(s, &slab_caches, list) {
131910befea9SRoman Gushchin if (s->flags & SLAB_RECLAIM_ACCOUNT)
1320852d8be0SYang Shi continue;
1321852d8be0SYang Shi
1322852d8be0SYang Shi get_slabinfo(s, &sinfo);
1323852d8be0SYang Shi
1324852d8be0SYang Shi if (sinfo.num_objs > 0)
132510befea9SRoman Gushchin pr_info("%-17s %10luKB %10luKB\n", s->name,
1326852d8be0SYang Shi (sinfo.active_objs * s->size) / 1024,
1327852d8be0SYang Shi (sinfo.num_objs * s->size) / 1024);
1328852d8be0SYang Shi }
1329852d8be0SYang Shi mutex_unlock(&slab_mutex);
1330852d8be0SYang Shi }
1331852d8be0SYang Shi
1332b7454ad3SGlauber Costa /*
1333b7454ad3SGlauber Costa * slabinfo_op - iterator that generates /proc/slabinfo
1334b7454ad3SGlauber Costa *
1335b7454ad3SGlauber Costa * Output layout:
1336b7454ad3SGlauber Costa * cache-name
1337b7454ad3SGlauber Costa * num-active-objs
1338b7454ad3SGlauber Costa * total-objs
1339b7454ad3SGlauber Costa * object size
1340b7454ad3SGlauber Costa * num-active-slabs
1341b7454ad3SGlauber Costa * total-slabs
1342b7454ad3SGlauber Costa * num-pages-per-slab
1343b7454ad3SGlauber Costa * + further values on SMP and with statistics enabled
1344b7454ad3SGlauber Costa */
1345b7454ad3SGlauber Costa static const struct seq_operations slabinfo_op = {
13461df3b26fSVladimir Davydov .start = slab_start,
1347276a2439SWanpeng Li .next = slab_next,
1348276a2439SWanpeng Li .stop = slab_stop,
13491df3b26fSVladimir Davydov .show = slab_show,
1350b7454ad3SGlauber Costa };
1351b7454ad3SGlauber Costa
slabinfo_open(struct inode * inode,struct file * file)1352b7454ad3SGlauber Costa static int slabinfo_open(struct inode *inode, struct file *file)
1353b7454ad3SGlauber Costa {
1354b7454ad3SGlauber Costa return seq_open(file, &slabinfo_op);
1355b7454ad3SGlauber Costa }
1356b7454ad3SGlauber Costa
135797a32539SAlexey Dobriyan static const struct proc_ops slabinfo_proc_ops = {
1358d919b33dSAlexey Dobriyan .proc_flags = PROC_ENTRY_PERMANENT,
135997a32539SAlexey Dobriyan .proc_open = slabinfo_open,
136097a32539SAlexey Dobriyan .proc_read = seq_read,
136197a32539SAlexey Dobriyan .proc_write = slabinfo_write,
136297a32539SAlexey Dobriyan .proc_lseek = seq_lseek,
136397a32539SAlexey Dobriyan .proc_release = seq_release,
1364b7454ad3SGlauber Costa };
1365b7454ad3SGlauber Costa
slab_proc_init(void)1366b7454ad3SGlauber Costa static int __init slab_proc_init(void)
1367b7454ad3SGlauber Costa {
136897a32539SAlexey Dobriyan proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops);
1369b7454ad3SGlauber Costa return 0;
1370b7454ad3SGlauber Costa }
1371b7454ad3SGlauber Costa module_init(slab_proc_init);
1372fcf8a1e4SWaiman Long
13735b365771SYang Shi #endif /* CONFIG_SLAB || CONFIG_SLUB_DEBUG */
1374928cec9cSAndrey Ryabinin
13759ed9cac1SKees Cook static __always_inline __realloc_size(2) void *
__do_krealloc(const void * p,size_t new_size,gfp_t flags)13769ed9cac1SKees Cook __do_krealloc(const void *p, size_t new_size, gfp_t flags)
1377928cec9cSAndrey Ryabinin {
1378928cec9cSAndrey Ryabinin void *ret;
1379fa9ba3aaSWilliam Kucharski size_t ks;
1380928cec9cSAndrey Ryabinin
138138931d89SKees Cook /* Check for double-free before calling ksize. */
1382d12d9ad8SAndrey Konovalov if (likely(!ZERO_OR_NULL_PTR(p))) {
1383d12d9ad8SAndrey Konovalov if (!kasan_check_byte(p))
138426a5ca7aSAndrey Konovalov return NULL;
138538931d89SKees Cook ks = ksize(p);
1386d12d9ad8SAndrey Konovalov } else
1387d12d9ad8SAndrey Konovalov ks = 0;
138826a5ca7aSAndrey Konovalov
1389d12d9ad8SAndrey Konovalov /* If the object still fits, repoison it precisely. */
13900316bec2SAndrey Ryabinin if (ks >= new_size) {
1391e3a9fc15SDanilo Krummrich /* Zero out spare memory. */
1392e3a9fc15SDanilo Krummrich if (want_init_on_alloc(flags)) {
1393e3a9fc15SDanilo Krummrich kasan_disable_current();
1394*71548fadSQun-Wei Lin memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
1395e3a9fc15SDanilo Krummrich kasan_enable_current();
1396e3a9fc15SDanilo Krummrich }
1397e3a9fc15SDanilo Krummrich
13980116523cSAndrey Konovalov p = kasan_krealloc((void *)p, new_size, flags);
1399928cec9cSAndrey Ryabinin return (void *)p;
14000316bec2SAndrey Ryabinin }
1401928cec9cSAndrey Ryabinin
1402928cec9cSAndrey Ryabinin ret = kmalloc_track_caller(new_size, flags);
1403d12d9ad8SAndrey Konovalov if (ret && p) {
1404d12d9ad8SAndrey Konovalov /* Disable KASAN checks as the object's redzone is accessed. */
1405d12d9ad8SAndrey Konovalov kasan_disable_current();
1406d12d9ad8SAndrey Konovalov memcpy(ret, kasan_reset_tag(p), ks);
1407d12d9ad8SAndrey Konovalov kasan_enable_current();
1408d12d9ad8SAndrey Konovalov }
1409928cec9cSAndrey Ryabinin
1410928cec9cSAndrey Ryabinin return ret;
1411928cec9cSAndrey Ryabinin }
1412928cec9cSAndrey Ryabinin
1413928cec9cSAndrey Ryabinin /**
1414928cec9cSAndrey Ryabinin * krealloc - reallocate memory. The contents will remain unchanged.
1415928cec9cSAndrey Ryabinin * @p: object to reallocate memory for.
1416928cec9cSAndrey Ryabinin * @new_size: how many bytes of memory are required.
1417928cec9cSAndrey Ryabinin * @flags: the type of memory to allocate.
1418928cec9cSAndrey Ryabinin *
1419928cec9cSAndrey Ryabinin * The contents of the object pointed to are preserved up to the
142015d5de49SBartosz Golaszewski * lesser of the new and old sizes (__GFP_ZERO flag is effectively ignored).
142115d5de49SBartosz Golaszewski * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size
142215d5de49SBartosz Golaszewski * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
1423a862f68aSMike Rapoport *
1424a862f68aSMike Rapoport * Return: pointer to the allocated memory or %NULL in case of error
1425928cec9cSAndrey Ryabinin */
krealloc(const void * p,size_t new_size,gfp_t flags)1426928cec9cSAndrey Ryabinin void *krealloc(const void *p, size_t new_size, gfp_t flags)
1427928cec9cSAndrey Ryabinin {
1428928cec9cSAndrey Ryabinin void *ret;
1429928cec9cSAndrey Ryabinin
1430928cec9cSAndrey Ryabinin if (unlikely(!new_size)) {
1431928cec9cSAndrey Ryabinin kfree(p);
1432928cec9cSAndrey Ryabinin return ZERO_SIZE_PTR;
1433928cec9cSAndrey Ryabinin }
1434928cec9cSAndrey Ryabinin
1435928cec9cSAndrey Ryabinin ret = __do_krealloc(p, new_size, flags);
1436772a2fa5SAndrey Konovalov if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
1437928cec9cSAndrey Ryabinin kfree(p);
1438928cec9cSAndrey Ryabinin
1439928cec9cSAndrey Ryabinin return ret;
1440928cec9cSAndrey Ryabinin }
1441928cec9cSAndrey Ryabinin EXPORT_SYMBOL(krealloc);
1442928cec9cSAndrey Ryabinin
1443928cec9cSAndrey Ryabinin /**
1444453431a5SWaiman Long * kfree_sensitive - Clear sensitive information in memory before freeing
1445928cec9cSAndrey Ryabinin * @p: object to free memory of
1446928cec9cSAndrey Ryabinin *
1447928cec9cSAndrey Ryabinin * The memory of the object @p points to is zeroed before freed.
1448453431a5SWaiman Long * If @p is %NULL, kfree_sensitive() does nothing.
1449928cec9cSAndrey Ryabinin *
1450928cec9cSAndrey Ryabinin * Note: this function zeroes the whole allocated buffer which can be a good
1451928cec9cSAndrey Ryabinin * deal bigger than the requested buffer size passed to kmalloc(). So be
1452928cec9cSAndrey Ryabinin * careful when using this function in performance sensitive code.
1453928cec9cSAndrey Ryabinin */
kfree_sensitive(const void * p)1454453431a5SWaiman Long void kfree_sensitive(const void *p)
1455928cec9cSAndrey Ryabinin {
1456928cec9cSAndrey Ryabinin size_t ks;
1457928cec9cSAndrey Ryabinin void *mem = (void *)p;
1458928cec9cSAndrey Ryabinin
1459928cec9cSAndrey Ryabinin ks = ksize(mem);
146038931d89SKees Cook if (ks) {
146138931d89SKees Cook kasan_unpoison_range(mem, ks);
14628982ae52SWaiman Long memzero_explicit(mem, ks);
146338931d89SKees Cook }
1464928cec9cSAndrey Ryabinin kfree(mem);
1465928cec9cSAndrey Ryabinin }
1466453431a5SWaiman Long EXPORT_SYMBOL(kfree_sensitive);
1467928cec9cSAndrey Ryabinin
ksize(const void * objp)146810d1f8cbSMarco Elver size_t ksize(const void *objp)
146910d1f8cbSMarco Elver {
14700d4ca4c9SMarco Elver /*
147138931d89SKees Cook * We need to first check that the pointer to the object is valid.
147238931d89SKees Cook * The KASAN report printed from ksize() is more useful, then when
147338931d89SKees Cook * it's printed later when the behaviour could be undefined due to
147438931d89SKees Cook * a potential use-after-free or double-free.
14750d4ca4c9SMarco Elver *
1476611806b4SAndrey Konovalov * We use kasan_check_byte(), which is supported for the hardware
1477611806b4SAndrey Konovalov * tag-based KASAN mode, unlike kasan_check_read/write().
1478611806b4SAndrey Konovalov *
1479611806b4SAndrey Konovalov * If the pointed to memory is invalid, we return 0 to avoid users of
14800d4ca4c9SMarco Elver * ksize() writing to and potentially corrupting the memory region.
14810d4ca4c9SMarco Elver *
14820d4ca4c9SMarco Elver * We want to perform the check before __ksize(), to avoid potentially
14830d4ca4c9SMarco Elver * crashing in __ksize() due to accessing invalid metadata.
14840d4ca4c9SMarco Elver */
1485611806b4SAndrey Konovalov if (unlikely(ZERO_OR_NULL_PTR(objp)) || !kasan_check_byte(objp))
14860d4ca4c9SMarco Elver return 0;
14870d4ca4c9SMarco Elver
148838931d89SKees Cook return kfence_ksize(objp) ?: __ksize(objp);
148910d1f8cbSMarco Elver }
149010d1f8cbSMarco Elver EXPORT_SYMBOL(ksize);
149110d1f8cbSMarco Elver
1492928cec9cSAndrey Ryabinin /* Tracepoints definitions. */
1493928cec9cSAndrey Ryabinin EXPORT_TRACEPOINT_SYMBOL(kmalloc);
1494928cec9cSAndrey Ryabinin EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc);
1495928cec9cSAndrey Ryabinin EXPORT_TRACEPOINT_SYMBOL(kfree);
1496928cec9cSAndrey Ryabinin EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free);
14974f6923fbSHoward McLauchlan
should_failslab(struct kmem_cache * s,gfp_t gfpflags)14984f6923fbSHoward McLauchlan int should_failslab(struct kmem_cache *s, gfp_t gfpflags)
14994f6923fbSHoward McLauchlan {
15004f6923fbSHoward McLauchlan if (__should_failslab(s, gfpflags))
15014f6923fbSHoward McLauchlan return -ENOMEM;
15024f6923fbSHoward McLauchlan return 0;
15034f6923fbSHoward McLauchlan }
15044f6923fbSHoward McLauchlan ALLOW_ERROR_INJECTION(should_failslab, ERRNO);
1505