]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/slub.c
Merge branch 'slab/for-6.2/kmalloc_redzone' into slab/for-next
[thirdparty/linux.git] / mm / slub.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
81819f0f
CL
2/*
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
5 *
dc84207d 6 * The allocator synchronizes using per slab locks or atomic operations
881db7fb 7 * and only uses a centralized lock to manage a pool of partial slabs.
81819f0f 8 *
cde53535 9 * (C) 2007 SGI, Christoph Lameter
881db7fb 10 * (C) 2011 Linux Foundation, Christoph Lameter
81819f0f
CL
11 */
12
13#include <linux/mm.h>
1eb5ac64 14#include <linux/swap.h> /* struct reclaim_state */
81819f0f
CL
15#include <linux/module.h>
16#include <linux/bit_spinlock.h>
17#include <linux/interrupt.h>
1b3865d0 18#include <linux/swab.h>
81819f0f
CL
19#include <linux/bitops.h>
20#include <linux/slab.h>
97d06609 21#include "slab.h"
7b3c3a50 22#include <linux/proc_fs.h>
81819f0f 23#include <linux/seq_file.h>
a79316c6 24#include <linux/kasan.h>
68ef169a 25#include <linux/kmsan.h>
81819f0f
CL
26#include <linux/cpu.h>
27#include <linux/cpuset.h>
28#include <linux/mempolicy.h>
29#include <linux/ctype.h>
5cf909c5 30#include <linux/stackdepot.h>
3ac7fe5a 31#include <linux/debugobjects.h>
81819f0f 32#include <linux/kallsyms.h>
b89fb5ef 33#include <linux/kfence.h>
b9049e23 34#include <linux/memory.h>
f8bd2258 35#include <linux/math64.h>
773ff60e 36#include <linux/fault-inject.h>
bfa71457 37#include <linux/stacktrace.h>
4de900b4 38#include <linux/prefetch.h>
2633d7a0 39#include <linux/memcontrol.h>
2482ddec 40#include <linux/random.h>
1f9f78b1 41#include <kunit/test.h>
553c0369 42#include <linux/sort.h>
81819f0f 43
64dd6849 44#include <linux/debugfs.h>
4a92379b
RK
45#include <trace/events/kmem.h>
46
072bb0aa
MG
47#include "internal.h"
48
81819f0f
CL
49/*
50 * Lock order:
18004c5d 51 * 1. slab_mutex (Global Mutex)
bd0e7491
VB
52 * 2. node->list_lock (Spinlock)
53 * 3. kmem_cache->cpu_slab->lock (Local lock)
41bec7c3 54 * 4. slab_lock(slab) (Only on some arches)
bd0e7491 55 * 5. object_map_lock (Only for debugging)
81819f0f 56 *
18004c5d 57 * slab_mutex
881db7fb 58 *
18004c5d 59 * The role of the slab_mutex is to protect the list of all the slabs
881db7fb 60 * and to synchronize major metadata changes to slab cache structures.
bd0e7491
VB
61 * Also synchronizes memory hotplug callbacks.
62 *
63 * slab_lock
64 *
65 * The slab_lock is a wrapper around the page lock, thus it is a bit
66 * spinlock.
881db7fb 67 *
41bec7c3
VB
68 * The slab_lock is only used on arches that do not have the ability
69 * to do a cmpxchg_double. It only protects:
70 *
c2092c12
VB
71 * A. slab->freelist -> List of free objects in a slab
72 * B. slab->inuse -> Number of objects in use
73 * C. slab->objects -> Number of objects in slab
74 * D. slab->frozen -> frozen state
881db7fb 75 *
bd0e7491
VB
76 * Frozen slabs
77 *
881db7fb 78 * If a slab is frozen then it is exempt from list management. It is not
632b2ef0 79 * on any list except per cpu partial list. The processor that froze the
c2092c12 80 * slab is the one who can perform list operations on the slab. Other
632b2ef0
LX
81 * processors may put objects onto the freelist but the processor that
82 * froze the slab is the only one that can retrieve the objects from the
c2092c12 83 * slab's freelist.
81819f0f 84 *
bd0e7491
VB
85 * list_lock
86 *
81819f0f
CL
87 * The list_lock protects the partial and full list on each node and
88 * the partial slab counter. If taken then no new slabs may be added or
89 * removed from the lists nor make the number of partial slabs be modified.
90 * (Note that the total number of slabs is an atomic value that may be
91 * modified without taking the list lock).
92 *
93 * The list_lock is a centralized lock and thus we avoid taking it as
94 * much as possible. As long as SLUB does not have to handle partial
95 * slabs, operations can continue without any centralized lock. F.e.
96 * allocating a long series of objects that fill up slabs does not require
97 * the list lock.
bd0e7491 98 *
41bec7c3
VB
99 * For debug caches, all allocations are forced to go through a list_lock
100 * protected region to serialize against concurrent validation.
101 *
bd0e7491
VB
102 * cpu_slab->lock local lock
103 *
104 * This locks protect slowpath manipulation of all kmem_cache_cpu fields
105 * except the stat counters. This is a percpu structure manipulated only by
106 * the local cpu, so the lock protects against being preempted or interrupted
107 * by an irq. Fast path operations rely on lockless operations instead.
1f04b07d
TG
108 *
109 * On PREEMPT_RT, the local lock neither disables interrupts nor preemption
110 * which means the lockless fastpath cannot be used as it might interfere with
111 * an in-progress slow path operations. In this case the local lock is always
112 * taken but it still utilizes the freelist for the common operations.
bd0e7491
VB
113 *
114 * lockless fastpaths
115 *
116 * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
117 * are fully lockless when satisfied from the percpu slab (and when
118 * cmpxchg_double is possible to use, otherwise slab_lock is taken).
119 * They also don't disable preemption or migration or irqs. They rely on
120 * the transaction id (tid) field to detect being preempted or moved to
121 * another cpu.
122 *
123 * irq, preemption, migration considerations
124 *
125 * Interrupts are disabled as part of list_lock or local_lock operations, or
126 * around the slab_lock operation, in order to make the slab allocator safe
127 * to use in the context of an irq.
128 *
129 * In addition, preemption (or migration on PREEMPT_RT) is disabled in the
130 * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
131 * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
132 * doesn't have to be revalidated in each section protected by the local lock.
81819f0f
CL
133 *
134 * SLUB assigns one slab for allocation to each processor.
135 * Allocations only occur from these slabs called cpu slabs.
136 *
672bba3a
CL
137 * Slabs with free elements are kept on a partial list and during regular
138 * operations no list for full slabs is used. If an object in a full slab is
81819f0f 139 * freed then the slab will show up again on the partial lists.
672bba3a
CL
140 * We track full slabs for debugging purposes though because otherwise we
141 * cannot scan all objects.
81819f0f
CL
142 *
143 * Slabs are freed when they become empty. Teardown and setup is
144 * minimal so we rely on the page allocators per cpu caches for
145 * fast frees and allocs.
146 *
c2092c12 147 * slab->frozen The slab is frozen and exempt from list processing.
4b6f0750
CL
148 * This means that the slab is dedicated to a purpose
149 * such as satisfying allocations for a specific
150 * processor. Objects may be freed in the slab while
151 * it is frozen but slab_free will then skip the usual
152 * list operations. It is up to the processor holding
153 * the slab to integrate the slab into the slab lists
154 * when the slab is no longer needed.
155 *
156 * One use of this flag is to mark slabs that are
157 * used for allocations. Then such a slab becomes a cpu
158 * slab. The cpu slab may be equipped with an additional
dfb4f096 159 * freelist that allows lockless access to
894b8788
CL
160 * free objects in addition to the regular freelist
161 * that requires the slab lock.
81819f0f 162 *
aed68148 163 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
81819f0f 164 * options set. This moves slab handling out of
894b8788 165 * the fast path and disables lockless freelists.
81819f0f
CL
166 */
167
25c00c50
VB
168/*
169 * We could simply use migrate_disable()/enable() but as long as it's a
170 * function call even on !PREEMPT_RT, use inline preempt_disable() there.
171 */
172#ifndef CONFIG_PREEMPT_RT
1f04b07d
TG
173#define slub_get_cpu_ptr(var) get_cpu_ptr(var)
174#define slub_put_cpu_ptr(var) put_cpu_ptr(var)
175#define USE_LOCKLESS_FAST_PATH() (true)
25c00c50
VB
176#else
177#define slub_get_cpu_ptr(var) \
178({ \
179 migrate_disable(); \
180 this_cpu_ptr(var); \
181})
182#define slub_put_cpu_ptr(var) \
183do { \
184 (void)(var); \
185 migrate_enable(); \
186} while (0)
1f04b07d 187#define USE_LOCKLESS_FAST_PATH() (false)
25c00c50
VB
188#endif
189
ca0cab65
VB
190#ifdef CONFIG_SLUB_DEBUG
191#ifdef CONFIG_SLUB_DEBUG_ON
192DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
193#else
194DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
195#endif
79270291 196#endif /* CONFIG_SLUB_DEBUG */
ca0cab65 197
6edf2576
FT
198/* Structure holding parameters for get_partial() call chain */
199struct partial_context {
200 struct slab **slab;
201 gfp_t flags;
202 unsigned int orig_size;
203};
204
59052e89
VB
205static inline bool kmem_cache_debug(struct kmem_cache *s)
206{
207 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
af537b0a 208}
5577bd8a 209
6edf2576
FT
210static inline bool slub_debug_orig_size(struct kmem_cache *s)
211{
212 return (kmem_cache_debug_flags(s, SLAB_STORE_USER) &&
213 (s->flags & SLAB_KMALLOC));
214}
215
117d54df 216void *fixup_red_left(struct kmem_cache *s, void *p)
d86bd1be 217{
59052e89 218 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
d86bd1be
JK
219 p += s->red_left_pad;
220
221 return p;
222}
223
345c905d
JK
224static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
225{
226#ifdef CONFIG_SLUB_CPU_PARTIAL
227 return !kmem_cache_debug(s);
228#else
229 return false;
230#endif
231}
232
81819f0f
CL
233/*
234 * Issues still to be resolved:
235 *
81819f0f
CL
236 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
237 *
81819f0f
CL
238 * - Variable sizing of the per node arrays
239 */
240
b789ef51
CL
241/* Enable to log cmpxchg failures */
242#undef SLUB_DEBUG_CMPXCHG
243
2086d26a 244/*
dc84207d 245 * Minimum number of partial slabs. These will be left on the partial
2086d26a
CL
246 * lists even if they are empty. kmem_cache_shrink may reclaim them.
247 */
76be8950 248#define MIN_PARTIAL 5
e95eed57 249
2086d26a
CL
250/*
251 * Maximum number of desirable partial slabs.
252 * The existence of more partial slabs makes kmem_cache_shrink
721ae22a 253 * sort the partial list by the number of objects in use.
2086d26a
CL
254 */
255#define MAX_PARTIAL 10
256
becfda68 257#define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
81819f0f 258 SLAB_POISON | SLAB_STORE_USER)
672bba3a 259
149daaf3
LA
260/*
261 * These debug flags cannot use CMPXCHG because there might be consistency
262 * issues when checking or reading debug information
263 */
264#define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
265 SLAB_TRACE)
266
267
fa5ec8a1 268/*
3de47213
DR
269 * Debugging flags that require metadata to be stored in the slab. These get
270 * disabled when slub_debug=O is used and a cache's min order increases with
271 * metadata.
fa5ec8a1 272 */
3de47213 273#define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
fa5ec8a1 274
210b5c06
CG
275#define OO_SHIFT 16
276#define OO_MASK ((1 << OO_SHIFT) - 1)
c2092c12 277#define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
210b5c06 278
81819f0f 279/* Internal SLUB flags */
d50112ed 280/* Poison object */
4fd0b46e 281#define __OBJECT_POISON ((slab_flags_t __force)0x80000000U)
d50112ed 282/* Use cmpxchg_double */
4fd0b46e 283#define __CMPXCHG_DOUBLE ((slab_flags_t __force)0x40000000U)
81819f0f 284
02cbc874
CL
285/*
286 * Tracking user of a slab.
287 */
d6543e39 288#define TRACK_ADDRS_COUNT 16
02cbc874 289struct track {
ce71e27c 290 unsigned long addr; /* Called from address */
5cf909c5
OG
291#ifdef CONFIG_STACKDEPOT
292 depot_stack_handle_t handle;
d6543e39 293#endif
02cbc874
CL
294 int cpu; /* Was running on cpu */
295 int pid; /* Pid context */
296 unsigned long when; /* When did the operation occur */
297};
298
299enum track_item { TRACK_ALLOC, TRACK_FREE };
300
ab4d5ed5 301#ifdef CONFIG_SYSFS
81819f0f
CL
302static int sysfs_slab_add(struct kmem_cache *);
303static int sysfs_slab_alias(struct kmem_cache *, const char *);
81819f0f 304#else
0c710013
CL
305static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
306static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
307 { return 0; }
81819f0f
CL
308#endif
309
64dd6849
FM
310#if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
311static void debugfs_slab_add(struct kmem_cache *);
312#else
313static inline void debugfs_slab_add(struct kmem_cache *s) { }
314#endif
315
4fdccdfb 316static inline void stat(const struct kmem_cache *s, enum stat_item si)
8ff12cfc
CL
317{
318#ifdef CONFIG_SLUB_STATS
88da03a6
CL
319 /*
320 * The rmw is racy on a preemptible kernel but this is acceptable, so
321 * avoid this_cpu_add()'s irq-disable overhead.
322 */
323 raw_cpu_inc(s->cpu_slab->stat[si]);
8ff12cfc
CL
324#endif
325}
326
7e1fa93d
VB
327/*
328 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
329 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
330 * differ during memory hotplug/hotremove operations.
331 * Protected by slab_mutex.
332 */
333static nodemask_t slab_nodes;
334
e45cc288
ML
335/*
336 * Workqueue used for flush_cpu_slab().
337 */
338static struct workqueue_struct *flushwq;
339
81819f0f
CL
340/********************************************************************
341 * Core slab cache functions
342 *******************************************************************/
343
2482ddec
KC
344/*
345 * Returns freelist pointer (ptr). With hardening, this is obfuscated
346 * with an XOR of the address where the pointer is held and a per-cache
347 * random number.
348 */
349static inline void *freelist_ptr(const struct kmem_cache *s, void *ptr,
350 unsigned long ptr_addr)
351{
352#ifdef CONFIG_SLAB_FREELIST_HARDENED
d36a63a9 353 /*
aa1ef4d7 354 * When CONFIG_KASAN_SW/HW_TAGS is enabled, ptr_addr might be tagged.
d36a63a9
AK
355 * Normally, this doesn't cause any issues, as both set_freepointer()
356 * and get_freepointer() are called with a pointer with the same tag.
357 * However, there are some issues with CONFIG_SLUB_DEBUG code. For
358 * example, when __free_slub() iterates over objects in a cache, it
359 * passes untagged pointers to check_object(). check_object() in turns
360 * calls get_freepointer() with an untagged pointer, which causes the
361 * freepointer to be restored incorrectly.
362 */
363 return (void *)((unsigned long)ptr ^ s->random ^
1ad53d9f 364 swab((unsigned long)kasan_reset_tag((void *)ptr_addr)));
2482ddec
KC
365#else
366 return ptr;
367#endif
368}
369
370/* Returns the freelist pointer recorded at location ptr_addr. */
371static inline void *freelist_dereference(const struct kmem_cache *s,
372 void *ptr_addr)
373{
374 return freelist_ptr(s, (void *)*(unsigned long *)(ptr_addr),
375 (unsigned long)ptr_addr);
376}
377
7656c72b
CL
378static inline void *get_freepointer(struct kmem_cache *s, void *object)
379{
aa1ef4d7 380 object = kasan_reset_tag(object);
2482ddec 381 return freelist_dereference(s, object + s->offset);
7656c72b
CL
382}
383
0ad9500e
ED
384static void prefetch_freepointer(const struct kmem_cache *s, void *object)
385{
04b4b006 386 prefetchw(object + s->offset);
0ad9500e
ED
387}
388
68ef169a
AP
389/*
390 * When running under KMSAN, get_freepointer_safe() may return an uninitialized
391 * pointer value in the case the current thread loses the race for the next
392 * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
393 * slab_alloc_node() will fail, so the uninitialized value won't be used, but
394 * KMSAN will still check all arguments of cmpxchg because of imperfect
395 * handling of inline assembly.
396 * To work around this problem, we apply __no_kmsan_checks to ensure that
397 * get_freepointer_safe() returns initialized memory.
398 */
399__no_kmsan_checks
1393d9a1
CL
400static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
401{
2482ddec 402 unsigned long freepointer_addr;
1393d9a1
CL
403 void *p;
404
8e57f8ac 405 if (!debug_pagealloc_enabled_static())
922d566c
JK
406 return get_freepointer(s, object);
407
f70b0049 408 object = kasan_reset_tag(object);
2482ddec 409 freepointer_addr = (unsigned long)object + s->offset;
fe557319 410 copy_from_kernel_nofault(&p, (void **)freepointer_addr, sizeof(p));
2482ddec 411 return freelist_ptr(s, p, freepointer_addr);
1393d9a1
CL
412}
413
7656c72b
CL
414static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
415{
2482ddec
KC
416 unsigned long freeptr_addr = (unsigned long)object + s->offset;
417
ce6fa91b
AP
418#ifdef CONFIG_SLAB_FREELIST_HARDENED
419 BUG_ON(object == fp); /* naive detection of double free or corruption */
420#endif
421
aa1ef4d7 422 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
2482ddec 423 *(void **)freeptr_addr = freelist_ptr(s, fp, freeptr_addr);
7656c72b
CL
424}
425
426/* Loop over all objects in a slab */
224a88be 427#define for_each_object(__p, __s, __addr, __objects) \
d86bd1be
JK
428 for (__p = fixup_red_left(__s, __addr); \
429 __p < (__addr) + (__objects) * (__s)->size; \
430 __p += (__s)->size)
7656c72b 431
9736d2a9 432static inline unsigned int order_objects(unsigned int order, unsigned int size)
ab9a0f19 433{
9736d2a9 434 return ((unsigned int)PAGE_SIZE << order) / size;
ab9a0f19
LJ
435}
436
19af27af 437static inline struct kmem_cache_order_objects oo_make(unsigned int order,
9736d2a9 438 unsigned int size)
834f3d11
CL
439{
440 struct kmem_cache_order_objects x = {
9736d2a9 441 (order << OO_SHIFT) + order_objects(order, size)
834f3d11
CL
442 };
443
444 return x;
445}
446
19af27af 447static inline unsigned int oo_order(struct kmem_cache_order_objects x)
834f3d11 448{
210b5c06 449 return x.x >> OO_SHIFT;
834f3d11
CL
450}
451
19af27af 452static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
834f3d11 453{
210b5c06 454 return x.x & OO_MASK;
834f3d11
CL
455}
456
b47291ef
VB
457#ifdef CONFIG_SLUB_CPU_PARTIAL
458static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
459{
bb192ed9 460 unsigned int nr_slabs;
b47291ef
VB
461
462 s->cpu_partial = nr_objects;
463
464 /*
465 * We take the number of objects but actually limit the number of
c2092c12
VB
466 * slabs on the per cpu partial list, in order to limit excessive
467 * growth of the list. For simplicity we assume that the slabs will
b47291ef
VB
468 * be half-full.
469 */
bb192ed9
VB
470 nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
471 s->cpu_partial_slabs = nr_slabs;
b47291ef
VB
472}
473#else
474static inline void
475slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
476{
477}
478#endif /* CONFIG_SLUB_CPU_PARTIAL */
479
881db7fb
CL
480/*
481 * Per slab locking using the pagelock
482 */
5875e598 483static __always_inline void slab_lock(struct slab *slab)
881db7fb 484{
0393895b
VB
485 struct page *page = slab_page(slab);
486
48c935ad 487 VM_BUG_ON_PAGE(PageTail(page), page);
881db7fb
CL
488 bit_spin_lock(PG_locked, &page->flags);
489}
490
5875e598 491static __always_inline void slab_unlock(struct slab *slab)
881db7fb 492{
0393895b
VB
493 struct page *page = slab_page(slab);
494
48c935ad 495 VM_BUG_ON_PAGE(PageTail(page), page);
881db7fb
CL
496 __bit_spin_unlock(PG_locked, &page->flags);
497}
498
a2b4ae8b
VB
499/*
500 * Interrupts must be disabled (for the fallback code to work right), typically
5875e598
VB
501 * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
502 * part of bit_spin_lock(), is sufficient because the policy is not to allow any
503 * allocation/ free operation in hardirq context. Therefore nothing can
504 * interrupt the operation.
a2b4ae8b 505 */
bb192ed9 506static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct slab *slab,
1d07171c
CL
507 void *freelist_old, unsigned long counters_old,
508 void *freelist_new, unsigned long counters_new,
509 const char *n)
510{
1f04b07d 511 if (USE_LOCKLESS_FAST_PATH())
a2b4ae8b 512 lockdep_assert_irqs_disabled();
2565409f
HC
513#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
514 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
1d07171c 515 if (s->flags & __CMPXCHG_DOUBLE) {
bb192ed9 516 if (cmpxchg_double(&slab->freelist, &slab->counters,
0aa9a13d
DC
517 freelist_old, counters_old,
518 freelist_new, counters_new))
6f6528a1 519 return true;
1d07171c
CL
520 } else
521#endif
522 {
5875e598 523 slab_lock(slab);
bb192ed9
VB
524 if (slab->freelist == freelist_old &&
525 slab->counters == counters_old) {
526 slab->freelist = freelist_new;
527 slab->counters = counters_new;
5875e598 528 slab_unlock(slab);
6f6528a1 529 return true;
1d07171c 530 }
5875e598 531 slab_unlock(slab);
1d07171c
CL
532 }
533
534 cpu_relax();
535 stat(s, CMPXCHG_DOUBLE_FAIL);
536
537#ifdef SLUB_DEBUG_CMPXCHG
f9f58285 538 pr_info("%s %s: cmpxchg double redo ", n, s->name);
1d07171c
CL
539#endif
540
6f6528a1 541 return false;
1d07171c
CL
542}
543
bb192ed9 544static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct slab *slab,
b789ef51
CL
545 void *freelist_old, unsigned long counters_old,
546 void *freelist_new, unsigned long counters_new,
547 const char *n)
548{
2565409f
HC
549#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
550 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
b789ef51 551 if (s->flags & __CMPXCHG_DOUBLE) {
bb192ed9 552 if (cmpxchg_double(&slab->freelist, &slab->counters,
0aa9a13d
DC
553 freelist_old, counters_old,
554 freelist_new, counters_new))
6f6528a1 555 return true;
b789ef51
CL
556 } else
557#endif
558 {
1d07171c
CL
559 unsigned long flags;
560
561 local_irq_save(flags);
5875e598 562 slab_lock(slab);
bb192ed9
VB
563 if (slab->freelist == freelist_old &&
564 slab->counters == counters_old) {
565 slab->freelist = freelist_new;
566 slab->counters = counters_new;
5875e598 567 slab_unlock(slab);
1d07171c 568 local_irq_restore(flags);
6f6528a1 569 return true;
b789ef51 570 }
5875e598 571 slab_unlock(slab);
1d07171c 572 local_irq_restore(flags);
b789ef51
CL
573 }
574
575 cpu_relax();
576 stat(s, CMPXCHG_DOUBLE_FAIL);
577
578#ifdef SLUB_DEBUG_CMPXCHG
f9f58285 579 pr_info("%s %s: cmpxchg double redo ", n, s->name);
b789ef51
CL
580#endif
581
6f6528a1 582 return false;
b789ef51
CL
583}
584
41ecc55b 585#ifdef CONFIG_SLUB_DEBUG
90e9f6a6 586static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
4ef3f5a3 587static DEFINE_SPINLOCK(object_map_lock);
90e9f6a6 588
b3fd64e1 589static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
bb192ed9 590 struct slab *slab)
b3fd64e1 591{
bb192ed9 592 void *addr = slab_address(slab);
b3fd64e1
VB
593 void *p;
594
bb192ed9 595 bitmap_zero(obj_map, slab->objects);
b3fd64e1 596
bb192ed9 597 for (p = slab->freelist; p; p = get_freepointer(s, p))
b3fd64e1
VB
598 set_bit(__obj_to_index(s, addr, p), obj_map);
599}
600
1f9f78b1
OG
601#if IS_ENABLED(CONFIG_KUNIT)
602static bool slab_add_kunit_errors(void)
603{
604 struct kunit_resource *resource;
605
606 if (likely(!current->kunit_test))
607 return false;
608
609 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
610 if (!resource)
611 return false;
612
613 (*(int *)resource->data)++;
614 kunit_put_resource(resource);
615 return true;
616}
617#else
618static inline bool slab_add_kunit_errors(void) { return false; }
619#endif
620
870b1fbb 621static inline unsigned int size_from_object(struct kmem_cache *s)
d86bd1be
JK
622{
623 if (s->flags & SLAB_RED_ZONE)
624 return s->size - s->red_left_pad;
625
626 return s->size;
627}
628
629static inline void *restore_red_left(struct kmem_cache *s, void *p)
630{
631 if (s->flags & SLAB_RED_ZONE)
632 p -= s->red_left_pad;
633
634 return p;
635}
636
41ecc55b
CL
637/*
638 * Debug settings:
639 */
89d3c87e 640#if defined(CONFIG_SLUB_DEBUG_ON)
d50112ed 641static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
f0630fff 642#else
d50112ed 643static slab_flags_t slub_debug;
f0630fff 644#endif
41ecc55b 645
e17f1dfb 646static char *slub_debug_string;
fa5ec8a1 647static int disable_higher_order_debug;
41ecc55b 648
a79316c6
AR
649/*
650 * slub is about to manipulate internal object metadata. This memory lies
651 * outside the range of the allocated object, so accessing it would normally
652 * be reported by kasan as a bounds error. metadata_access_enable() is used
653 * to tell kasan that these accesses are OK.
654 */
655static inline void metadata_access_enable(void)
656{
657 kasan_disable_current();
658}
659
660static inline void metadata_access_disable(void)
661{
662 kasan_enable_current();
663}
664
81819f0f
CL
665/*
666 * Object debugging
667 */
d86bd1be
JK
668
669/* Verify that a pointer has an address that is valid within a slab page */
670static inline int check_valid_pointer(struct kmem_cache *s,
bb192ed9 671 struct slab *slab, void *object)
d86bd1be
JK
672{
673 void *base;
674
675 if (!object)
676 return 1;
677
bb192ed9 678 base = slab_address(slab);
338cfaad 679 object = kasan_reset_tag(object);
d86bd1be 680 object = restore_red_left(s, object);
bb192ed9 681 if (object < base || object >= base + slab->objects * s->size ||
d86bd1be
JK
682 (object - base) % s->size) {
683 return 0;
684 }
685
686 return 1;
687}
688
aa2efd5e
DT
689static void print_section(char *level, char *text, u8 *addr,
690 unsigned int length)
81819f0f 691{
a79316c6 692 metadata_access_enable();
340caf17
KYL
693 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
694 16, 1, kasan_reset_tag((void *)addr), length, 1);
a79316c6 695 metadata_access_disable();
81819f0f
CL
696}
697
cbfc35a4
WL
698/*
699 * See comment in calculate_sizes().
700 */
701static inline bool freeptr_outside_object(struct kmem_cache *s)
702{
703 return s->offset >= s->inuse;
704}
705
706/*
707 * Return offset of the end of info block which is inuse + free pointer if
708 * not overlapping with object.
709 */
710static inline unsigned int get_info_end(struct kmem_cache *s)
711{
712 if (freeptr_outside_object(s))
713 return s->inuse + sizeof(void *);
714 else
715 return s->inuse;
716}
717
81819f0f
CL
718static struct track *get_track(struct kmem_cache *s, void *object,
719 enum track_item alloc)
720{
721 struct track *p;
722
cbfc35a4 723 p = object + get_info_end(s);
81819f0f 724
aa1ef4d7 725 return kasan_reset_tag(p + alloc);
81819f0f
CL
726}
727
5cf909c5 728#ifdef CONFIG_STACKDEPOT
c4cf6785
SAS
729static noinline depot_stack_handle_t set_track_prepare(void)
730{
731 depot_stack_handle_t handle;
5cf909c5 732 unsigned long entries[TRACK_ADDRS_COUNT];
0cd1a029 733 unsigned int nr_entries;
ae14c63a 734
5cf909c5 735 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
c4cf6785
SAS
736 handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT);
737
738 return handle;
739}
740#else
741static inline depot_stack_handle_t set_track_prepare(void)
742{
743 return 0;
744}
d6543e39 745#endif
5cf909c5 746
c4cf6785
SAS
747static void set_track_update(struct kmem_cache *s, void *object,
748 enum track_item alloc, unsigned long addr,
749 depot_stack_handle_t handle)
750{
751 struct track *p = get_track(s, object, alloc);
752
753#ifdef CONFIG_STACKDEPOT
754 p->handle = handle;
755#endif
0cd1a029
VB
756 p->addr = addr;
757 p->cpu = smp_processor_id();
758 p->pid = current->pid;
759 p->when = jiffies;
81819f0f
CL
760}
761
c4cf6785
SAS
762static __always_inline void set_track(struct kmem_cache *s, void *object,
763 enum track_item alloc, unsigned long addr)
764{
765 depot_stack_handle_t handle = set_track_prepare();
766
767 set_track_update(s, object, alloc, addr, handle);
768}
769
81819f0f
CL
770static void init_tracking(struct kmem_cache *s, void *object)
771{
0cd1a029
VB
772 struct track *p;
773
24922684
CL
774 if (!(s->flags & SLAB_STORE_USER))
775 return;
776
0cd1a029
VB
777 p = get_track(s, object, TRACK_ALLOC);
778 memset(p, 0, 2*sizeof(struct track));
81819f0f
CL
779}
780
86609d33 781static void print_track(const char *s, struct track *t, unsigned long pr_time)
81819f0f 782{
5cf909c5
OG
783 depot_stack_handle_t handle __maybe_unused;
784
81819f0f
CL
785 if (!t->addr)
786 return;
787
96b94abc 788 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
86609d33 789 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
5cf909c5
OG
790#ifdef CONFIG_STACKDEPOT
791 handle = READ_ONCE(t->handle);
792 if (handle)
793 stack_depot_print(handle);
794 else
795 pr_err("object allocation/free stack trace missing\n");
d6543e39 796#endif
24922684
CL
797}
798
e42f174e 799void print_tracking(struct kmem_cache *s, void *object)
24922684 800{
86609d33 801 unsigned long pr_time = jiffies;
24922684
CL
802 if (!(s->flags & SLAB_STORE_USER))
803 return;
804
86609d33
CP
805 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
806 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
24922684
CL
807}
808
fb012e27 809static void print_slab_info(const struct slab *slab)
24922684 810{
fb012e27 811 struct folio *folio = (struct folio *)slab_folio(slab);
24922684 812
fb012e27
MWO
813 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
814 slab, slab->objects, slab->inuse, slab->freelist,
815 folio_flags(folio, 0));
24922684
CL
816}
817
6edf2576
FT
818/*
819 * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
820 * family will round up the real request size to these fixed ones, so
821 * there could be an extra area than what is requested. Save the original
822 * request size in the meta data area, for better debug and sanity check.
823 */
824static inline void set_orig_size(struct kmem_cache *s,
825 void *object, unsigned int orig_size)
826{
827 void *p = kasan_reset_tag(object);
828
829 if (!slub_debug_orig_size(s))
830 return;
831
946fa0db
FT
832#ifdef CONFIG_KASAN_GENERIC
833 /*
834 * KASAN could save its free meta data in object's data area at
835 * offset 0, if the size is larger than 'orig_size', it will
836 * overlap the data redzone in [orig_size+1, object_size], and
837 * the check should be skipped.
838 */
839 if (kasan_metadata_size(s, true) > orig_size)
840 orig_size = s->object_size;
841#endif
842
6edf2576
FT
843 p += get_info_end(s);
844 p += sizeof(struct track) * 2;
845
846 *(unsigned int *)p = orig_size;
847}
848
849static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
850{
851 void *p = kasan_reset_tag(object);
852
853 if (!slub_debug_orig_size(s))
854 return s->object_size;
855
856 p += get_info_end(s);
857 p += sizeof(struct track) * 2;
858
859 return *(unsigned int *)p;
860}
861
946fa0db
FT
862void skip_orig_size_check(struct kmem_cache *s, const void *object)
863{
864 set_orig_size(s, (void *)object, s->object_size);
865}
866
24922684
CL
867static void slab_bug(struct kmem_cache *s, char *fmt, ...)
868{
ecc42fbe 869 struct va_format vaf;
24922684 870 va_list args;
24922684
CL
871
872 va_start(args, fmt);
ecc42fbe
FF
873 vaf.fmt = fmt;
874 vaf.va = &args;
f9f58285 875 pr_err("=============================================================================\n");
ecc42fbe 876 pr_err("BUG %s (%s): %pV\n", s->name, print_tainted(), &vaf);
f9f58285 877 pr_err("-----------------------------------------------------------------------------\n\n");
ecc42fbe 878 va_end(args);
81819f0f
CL
879}
880
582d1212 881__printf(2, 3)
24922684
CL
882static void slab_fix(struct kmem_cache *s, char *fmt, ...)
883{
ecc42fbe 884 struct va_format vaf;
24922684 885 va_list args;
24922684 886
1f9f78b1
OG
887 if (slab_add_kunit_errors())
888 return;
889
24922684 890 va_start(args, fmt);
ecc42fbe
FF
891 vaf.fmt = fmt;
892 vaf.va = &args;
893 pr_err("FIX %s: %pV\n", s->name, &vaf);
24922684 894 va_end(args);
24922684
CL
895}
896
bb192ed9 897static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
81819f0f
CL
898{
899 unsigned int off; /* Offset of last byte */
bb192ed9 900 u8 *addr = slab_address(slab);
24922684
CL
901
902 print_tracking(s, p);
903
bb192ed9 904 print_slab_info(slab);
24922684 905
96b94abc 906 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
f9f58285 907 p, p - addr, get_freepointer(s, p));
24922684 908
d86bd1be 909 if (s->flags & SLAB_RED_ZONE)
8669dbab 910 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
aa2efd5e 911 s->red_left_pad);
d86bd1be 912 else if (p > addr + 16)
aa2efd5e 913 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
81819f0f 914
8669dbab 915 print_section(KERN_ERR, "Object ", p,
1b473f29 916 min_t(unsigned int, s->object_size, PAGE_SIZE));
81819f0f 917 if (s->flags & SLAB_RED_ZONE)
8669dbab 918 print_section(KERN_ERR, "Redzone ", p + s->object_size,
3b0efdfa 919 s->inuse - s->object_size);
81819f0f 920
cbfc35a4 921 off = get_info_end(s);
81819f0f 922
24922684 923 if (s->flags & SLAB_STORE_USER)
81819f0f 924 off += 2 * sizeof(struct track);
81819f0f 925
6edf2576
FT
926 if (slub_debug_orig_size(s))
927 off += sizeof(unsigned int);
928
5d1ba310 929 off += kasan_metadata_size(s, false);
80a9201a 930
d86bd1be 931 if (off != size_from_object(s))
81819f0f 932 /* Beginning of the filler is the free pointer */
8669dbab 933 print_section(KERN_ERR, "Padding ", p + off,
aa2efd5e 934 size_from_object(s) - off);
24922684
CL
935
936 dump_stack();
81819f0f
CL
937}
938
bb192ed9 939static void object_err(struct kmem_cache *s, struct slab *slab,
81819f0f
CL
940 u8 *object, char *reason)
941{
1f9f78b1
OG
942 if (slab_add_kunit_errors())
943 return;
944
3dc50637 945 slab_bug(s, "%s", reason);
bb192ed9 946 print_trailer(s, slab, object);
65ebdeef 947 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
81819f0f
CL
948}
949
bb192ed9 950static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
ae16d059
VB
951 void **freelist, void *nextfree)
952{
953 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
bb192ed9
VB
954 !check_valid_pointer(s, slab, nextfree) && freelist) {
955 object_err(s, slab, *freelist, "Freechain corrupt");
ae16d059
VB
956 *freelist = NULL;
957 slab_fix(s, "Isolate corrupted freechain");
958 return true;
959 }
960
961 return false;
962}
963
bb192ed9 964static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
d0e0ac97 965 const char *fmt, ...)
81819f0f
CL
966{
967 va_list args;
968 char buf[100];
969
1f9f78b1
OG
970 if (slab_add_kunit_errors())
971 return;
972
24922684
CL
973 va_start(args, fmt);
974 vsnprintf(buf, sizeof(buf), fmt, args);
81819f0f 975 va_end(args);
3dc50637 976 slab_bug(s, "%s", buf);
bb192ed9 977 print_slab_info(slab);
81819f0f 978 dump_stack();
65ebdeef 979 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
81819f0f
CL
980}
981
f7cb1933 982static void init_object(struct kmem_cache *s, void *object, u8 val)
81819f0f 983{
aa1ef4d7 984 u8 *p = kasan_reset_tag(object);
946fa0db 985 unsigned int poison_size = s->object_size;
81819f0f 986
946fa0db 987 if (s->flags & SLAB_RED_ZONE) {
d86bd1be
JK
988 memset(p - s->red_left_pad, val, s->red_left_pad);
989
946fa0db
FT
990 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
991 /*
992 * Redzone the extra allocated space by kmalloc than
993 * requested, and the poison size will be limited to
994 * the original request size accordingly.
995 */
996 poison_size = get_orig_size(s, object);
997 }
998 }
999
81819f0f 1000 if (s->flags & __OBJECT_POISON) {
946fa0db
FT
1001 memset(p, POISON_FREE, poison_size - 1);
1002 p[poison_size - 1] = POISON_END;
81819f0f
CL
1003 }
1004
1005 if (s->flags & SLAB_RED_ZONE)
946fa0db 1006 memset(p + poison_size, val, s->inuse - poison_size);
81819f0f
CL
1007}
1008
24922684
CL
1009static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
1010 void *from, void *to)
1011{
582d1212 1012 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
24922684
CL
1013 memset(from, data, to - from);
1014}
1015
bb192ed9 1016static int check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
24922684 1017 u8 *object, char *what,
06428780 1018 u8 *start, unsigned int value, unsigned int bytes)
24922684
CL
1019{
1020 u8 *fault;
1021 u8 *end;
bb192ed9 1022 u8 *addr = slab_address(slab);
24922684 1023
a79316c6 1024 metadata_access_enable();
aa1ef4d7 1025 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
a79316c6 1026 metadata_access_disable();
24922684
CL
1027 if (!fault)
1028 return 1;
1029
1030 end = start + bytes;
1031 while (end > fault && end[-1] == value)
1032 end--;
1033
1f9f78b1
OG
1034 if (slab_add_kunit_errors())
1035 goto skip_bug_print;
1036
24922684 1037 slab_bug(s, "%s overwritten", what);
96b94abc 1038 pr_err("0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
e1b70dd1
MC
1039 fault, end - 1, fault - addr,
1040 fault[0], value);
bb192ed9 1041 print_trailer(s, slab, object);
65ebdeef 1042 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
24922684 1043
1f9f78b1 1044skip_bug_print:
24922684
CL
1045 restore_bytes(s, what, value, fault, end);
1046 return 0;
81819f0f
CL
1047}
1048
81819f0f
CL
1049/*
1050 * Object layout:
1051 *
1052 * object address
1053 * Bytes of the object to be managed.
1054 * If the freepointer may overlay the object then the free
cbfc35a4 1055 * pointer is at the middle of the object.
672bba3a 1056 *
81819f0f
CL
1057 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
1058 * 0xa5 (POISON_END)
1059 *
3b0efdfa 1060 * object + s->object_size
81819f0f 1061 * Padding to reach word boundary. This is also used for Redzoning.
672bba3a 1062 * Padding is extended by another word if Redzoning is enabled and
3b0efdfa 1063 * object_size == inuse.
672bba3a 1064 *
81819f0f
CL
1065 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
1066 * 0xcc (RED_ACTIVE) for objects in use.
1067 *
1068 * object + s->inuse
672bba3a
CL
1069 * Meta data starts here.
1070 *
81819f0f
CL
1071 * A. Free pointer (if we cannot overwrite object on free)
1072 * B. Tracking data for SLAB_STORE_USER
6edf2576
FT
1073 * C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
1074 * D. Padding to reach required alignment boundary or at minimum
6446faa2 1075 * one word if debugging is on to be able to detect writes
672bba3a
CL
1076 * before the word boundary.
1077 *
1078 * Padding is done using 0x5a (POISON_INUSE)
81819f0f
CL
1079 *
1080 * object + s->size
672bba3a 1081 * Nothing is used beyond s->size.
81819f0f 1082 *
3b0efdfa 1083 * If slabcaches are merged then the object_size and inuse boundaries are mostly
672bba3a 1084 * ignored. And therefore no slab options that rely on these boundaries
81819f0f
CL
1085 * may be used with merged slabcaches.
1086 */
1087
bb192ed9 1088static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
81819f0f 1089{
cbfc35a4 1090 unsigned long off = get_info_end(s); /* The end of info */
81819f0f 1091
6edf2576 1092 if (s->flags & SLAB_STORE_USER) {
81819f0f
CL
1093 /* We also have user information there */
1094 off += 2 * sizeof(struct track);
1095
6edf2576
FT
1096 if (s->flags & SLAB_KMALLOC)
1097 off += sizeof(unsigned int);
1098 }
1099
5d1ba310 1100 off += kasan_metadata_size(s, false);
80a9201a 1101
d86bd1be 1102 if (size_from_object(s) == off)
81819f0f
CL
1103 return 1;
1104
bb192ed9 1105 return check_bytes_and_report(s, slab, p, "Object padding",
d86bd1be 1106 p + off, POISON_INUSE, size_from_object(s) - off);
81819f0f
CL
1107}
1108
39b26464 1109/* Check the pad bytes at the end of a slab page */
a204e6d6 1110static void slab_pad_check(struct kmem_cache *s, struct slab *slab)
81819f0f 1111{
24922684
CL
1112 u8 *start;
1113 u8 *fault;
1114 u8 *end;
5d682681 1115 u8 *pad;
24922684
CL
1116 int length;
1117 int remainder;
81819f0f
CL
1118
1119 if (!(s->flags & SLAB_POISON))
a204e6d6 1120 return;
81819f0f 1121
bb192ed9
VB
1122 start = slab_address(slab);
1123 length = slab_size(slab);
39b26464
CL
1124 end = start + length;
1125 remainder = length % s->size;
81819f0f 1126 if (!remainder)
a204e6d6 1127 return;
81819f0f 1128
5d682681 1129 pad = end - remainder;
a79316c6 1130 metadata_access_enable();
aa1ef4d7 1131 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
a79316c6 1132 metadata_access_disable();
24922684 1133 if (!fault)
a204e6d6 1134 return;
24922684
CL
1135 while (end > fault && end[-1] == POISON_INUSE)
1136 end--;
1137
bb192ed9 1138 slab_err(s, slab, "Padding overwritten. 0x%p-0x%p @offset=%tu",
e1b70dd1 1139 fault, end - 1, fault - start);
5d682681 1140 print_section(KERN_ERR, "Padding ", pad, remainder);
24922684 1141
5d682681 1142 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
81819f0f
CL
1143}
1144
bb192ed9 1145static int check_object(struct kmem_cache *s, struct slab *slab,
f7cb1933 1146 void *object, u8 val)
81819f0f
CL
1147{
1148 u8 *p = object;
3b0efdfa 1149 u8 *endobject = object + s->object_size;
946fa0db 1150 unsigned int orig_size;
81819f0f
CL
1151
1152 if (s->flags & SLAB_RED_ZONE) {
bb192ed9 1153 if (!check_bytes_and_report(s, slab, object, "Left Redzone",
d86bd1be
JK
1154 object - s->red_left_pad, val, s->red_left_pad))
1155 return 0;
1156
bb192ed9 1157 if (!check_bytes_and_report(s, slab, object, "Right Redzone",
3b0efdfa 1158 endobject, val, s->inuse - s->object_size))
81819f0f 1159 return 0;
946fa0db
FT
1160
1161 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1162 orig_size = get_orig_size(s, object);
1163
1164 if (s->object_size > orig_size &&
1165 !check_bytes_and_report(s, slab, object,
1166 "kmalloc Redzone", p + orig_size,
1167 val, s->object_size - orig_size)) {
1168 return 0;
1169 }
1170 }
81819f0f 1171 } else {
3b0efdfa 1172 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
bb192ed9 1173 check_bytes_and_report(s, slab, p, "Alignment padding",
d0e0ac97
CG
1174 endobject, POISON_INUSE,
1175 s->inuse - s->object_size);
3adbefee 1176 }
81819f0f
CL
1177 }
1178
1179 if (s->flags & SLAB_POISON) {
f7cb1933 1180 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
bb192ed9 1181 (!check_bytes_and_report(s, slab, p, "Poison", p,
3b0efdfa 1182 POISON_FREE, s->object_size - 1) ||
bb192ed9 1183 !check_bytes_and_report(s, slab, p, "End Poison",
3b0efdfa 1184 p + s->object_size - 1, POISON_END, 1)))
81819f0f 1185 return 0;
81819f0f
CL
1186 /*
1187 * check_pad_bytes cleans up on its own.
1188 */
bb192ed9 1189 check_pad_bytes(s, slab, p);
81819f0f
CL
1190 }
1191
cbfc35a4 1192 if (!freeptr_outside_object(s) && val == SLUB_RED_ACTIVE)
81819f0f
CL
1193 /*
1194 * Object and freepointer overlap. Cannot check
1195 * freepointer while object is allocated.
1196 */
1197 return 1;
1198
1199 /* Check free pointer validity */
bb192ed9
VB
1200 if (!check_valid_pointer(s, slab, get_freepointer(s, p))) {
1201 object_err(s, slab, p, "Freepointer corrupt");
81819f0f 1202 /*
9f6c708e 1203 * No choice but to zap it and thus lose the remainder
81819f0f 1204 * of the free objects in this slab. May cause
672bba3a 1205 * another error because the object count is now wrong.
81819f0f 1206 */
a973e9dd 1207 set_freepointer(s, p, NULL);
81819f0f
CL
1208 return 0;
1209 }
1210 return 1;
1211}
1212
bb192ed9 1213static int check_slab(struct kmem_cache *s, struct slab *slab)
81819f0f 1214{
39b26464
CL
1215 int maxobj;
1216
bb192ed9
VB
1217 if (!folio_test_slab(slab_folio(slab))) {
1218 slab_err(s, slab, "Not a valid slab page");
81819f0f
CL
1219 return 0;
1220 }
39b26464 1221
bb192ed9
VB
1222 maxobj = order_objects(slab_order(slab), s->size);
1223 if (slab->objects > maxobj) {
1224 slab_err(s, slab, "objects %u > max %u",
1225 slab->objects, maxobj);
39b26464
CL
1226 return 0;
1227 }
bb192ed9
VB
1228 if (slab->inuse > slab->objects) {
1229 slab_err(s, slab, "inuse %u > max %u",
1230 slab->inuse, slab->objects);
81819f0f
CL
1231 return 0;
1232 }
1233 /* Slab_pad_check fixes things up after itself */
bb192ed9 1234 slab_pad_check(s, slab);
81819f0f
CL
1235 return 1;
1236}
1237
1238/*
c2092c12 1239 * Determine if a certain object in a slab is on the freelist. Must hold the
672bba3a 1240 * slab lock to guarantee that the chains are in a consistent state.
81819f0f 1241 */
bb192ed9 1242static int on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
81819f0f
CL
1243{
1244 int nr = 0;
881db7fb 1245 void *fp;
81819f0f 1246 void *object = NULL;
f6edde9c 1247 int max_objects;
81819f0f 1248
bb192ed9
VB
1249 fp = slab->freelist;
1250 while (fp && nr <= slab->objects) {
81819f0f
CL
1251 if (fp == search)
1252 return 1;
bb192ed9 1253 if (!check_valid_pointer(s, slab, fp)) {
81819f0f 1254 if (object) {
bb192ed9 1255 object_err(s, slab, object,
81819f0f 1256 "Freechain corrupt");
a973e9dd 1257 set_freepointer(s, object, NULL);
81819f0f 1258 } else {
bb192ed9
VB
1259 slab_err(s, slab, "Freepointer corrupt");
1260 slab->freelist = NULL;
1261 slab->inuse = slab->objects;
24922684 1262 slab_fix(s, "Freelist cleared");
81819f0f
CL
1263 return 0;
1264 }
1265 break;
1266 }
1267 object = fp;
1268 fp = get_freepointer(s, object);
1269 nr++;
1270 }
1271
bb192ed9 1272 max_objects = order_objects(slab_order(slab), s->size);
210b5c06
CG
1273 if (max_objects > MAX_OBJS_PER_PAGE)
1274 max_objects = MAX_OBJS_PER_PAGE;
224a88be 1275
bb192ed9
VB
1276 if (slab->objects != max_objects) {
1277 slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1278 slab->objects, max_objects);
1279 slab->objects = max_objects;
582d1212 1280 slab_fix(s, "Number of objects adjusted");
224a88be 1281 }
bb192ed9
VB
1282 if (slab->inuse != slab->objects - nr) {
1283 slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1284 slab->inuse, slab->objects - nr);
1285 slab->inuse = slab->objects - nr;
582d1212 1286 slab_fix(s, "Object count adjusted");
81819f0f
CL
1287 }
1288 return search == NULL;
1289}
1290
bb192ed9 1291static void trace(struct kmem_cache *s, struct slab *slab, void *object,
0121c619 1292 int alloc)
3ec09742
CL
1293{
1294 if (s->flags & SLAB_TRACE) {
f9f58285 1295 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
3ec09742
CL
1296 s->name,
1297 alloc ? "alloc" : "free",
bb192ed9
VB
1298 object, slab->inuse,
1299 slab->freelist);
3ec09742
CL
1300
1301 if (!alloc)
aa2efd5e 1302 print_section(KERN_INFO, "Object ", (void *)object,
d0e0ac97 1303 s->object_size);
3ec09742
CL
1304
1305 dump_stack();
1306 }
1307}
1308
643b1138 1309/*
672bba3a 1310 * Tracking of fully allocated slabs for debugging purposes.
643b1138 1311 */
5cc6eee8 1312static void add_full(struct kmem_cache *s,
bb192ed9 1313 struct kmem_cache_node *n, struct slab *slab)
643b1138 1314{
5cc6eee8
CL
1315 if (!(s->flags & SLAB_STORE_USER))
1316 return;
1317
255d0884 1318 lockdep_assert_held(&n->list_lock);
bb192ed9 1319 list_add(&slab->slab_list, &n->full);
643b1138
CL
1320}
1321
bb192ed9 1322static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
643b1138 1323{
643b1138
CL
1324 if (!(s->flags & SLAB_STORE_USER))
1325 return;
1326
255d0884 1327 lockdep_assert_held(&n->list_lock);
bb192ed9 1328 list_del(&slab->slab_list);
643b1138
CL
1329}
1330
0f389ec6
CL
1331/* Tracking of the number of slabs for debugging purposes */
1332static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1333{
1334 struct kmem_cache_node *n = get_node(s, node);
1335
1336 return atomic_long_read(&n->nr_slabs);
1337}
1338
26c02cf0
AB
1339static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1340{
1341 return atomic_long_read(&n->nr_slabs);
1342}
1343
205ab99d 1344static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
0f389ec6
CL
1345{
1346 struct kmem_cache_node *n = get_node(s, node);
1347
1348 /*
1349 * May be called early in order to allocate a slab for the
1350 * kmem_cache_node structure. Solve the chicken-egg
1351 * dilemma by deferring the increment of the count during
1352 * bootstrap (see early_kmem_cache_node_alloc).
1353 */
338b2642 1354 if (likely(n)) {
0f389ec6 1355 atomic_long_inc(&n->nr_slabs);
205ab99d
CL
1356 atomic_long_add(objects, &n->total_objects);
1357 }
0f389ec6 1358}
205ab99d 1359static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
0f389ec6
CL
1360{
1361 struct kmem_cache_node *n = get_node(s, node);
1362
1363 atomic_long_dec(&n->nr_slabs);
205ab99d 1364 atomic_long_sub(objects, &n->total_objects);
0f389ec6
CL
1365}
1366
1367/* Object debug checks for alloc/free paths */
c0f81a94 1368static void setup_object_debug(struct kmem_cache *s, void *object)
3ec09742 1369{
8fc8d666 1370 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
3ec09742
CL
1371 return;
1372
f7cb1933 1373 init_object(s, object, SLUB_RED_INACTIVE);
3ec09742
CL
1374 init_tracking(s, object);
1375}
1376
a50b854e 1377static
bb192ed9 1378void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
a7101224 1379{
8fc8d666 1380 if (!kmem_cache_debug_flags(s, SLAB_POISON))
a7101224
AK
1381 return;
1382
1383 metadata_access_enable();
bb192ed9 1384 memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
a7101224
AK
1385 metadata_access_disable();
1386}
1387
becfda68 1388static inline int alloc_consistency_checks(struct kmem_cache *s,
bb192ed9 1389 struct slab *slab, void *object)
81819f0f 1390{
bb192ed9 1391 if (!check_slab(s, slab))
becfda68 1392 return 0;
81819f0f 1393
bb192ed9
VB
1394 if (!check_valid_pointer(s, slab, object)) {
1395 object_err(s, slab, object, "Freelist Pointer check fails");
becfda68 1396 return 0;
81819f0f
CL
1397 }
1398
bb192ed9 1399 if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
becfda68
LA
1400 return 0;
1401
1402 return 1;
1403}
1404
1405static noinline int alloc_debug_processing(struct kmem_cache *s,
6edf2576 1406 struct slab *slab, void *object, int orig_size)
becfda68
LA
1407{
1408 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
bb192ed9 1409 if (!alloc_consistency_checks(s, slab, object))
becfda68
LA
1410 goto bad;
1411 }
81819f0f 1412
c7323a5a 1413 /* Success. Perform special debug activities for allocs */
bb192ed9 1414 trace(s, slab, object, 1);
6edf2576 1415 set_orig_size(s, object, orig_size);
f7cb1933 1416 init_object(s, object, SLUB_RED_ACTIVE);
81819f0f 1417 return 1;
3ec09742 1418
81819f0f 1419bad:
bb192ed9 1420 if (folio_test_slab(slab_folio(slab))) {
81819f0f
CL
1421 /*
1422 * If this is a slab page then lets do the best we can
1423 * to avoid issues in the future. Marking all objects
672bba3a 1424 * as used avoids touching the remaining objects.
81819f0f 1425 */
24922684 1426 slab_fix(s, "Marking all objects used");
bb192ed9
VB
1427 slab->inuse = slab->objects;
1428 slab->freelist = NULL;
81819f0f
CL
1429 }
1430 return 0;
1431}
1432
becfda68 1433static inline int free_consistency_checks(struct kmem_cache *s,
bb192ed9 1434 struct slab *slab, void *object, unsigned long addr)
81819f0f 1435{
bb192ed9
VB
1436 if (!check_valid_pointer(s, slab, object)) {
1437 slab_err(s, slab, "Invalid object pointer 0x%p", object);
becfda68 1438 return 0;
81819f0f
CL
1439 }
1440
bb192ed9
VB
1441 if (on_freelist(s, slab, object)) {
1442 object_err(s, slab, object, "Object already free");
becfda68 1443 return 0;
81819f0f
CL
1444 }
1445
bb192ed9 1446 if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
becfda68 1447 return 0;
81819f0f 1448
bb192ed9
VB
1449 if (unlikely(s != slab->slab_cache)) {
1450 if (!folio_test_slab(slab_folio(slab))) {
1451 slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
756a025f 1452 object);
bb192ed9 1453 } else if (!slab->slab_cache) {
f9f58285
FF
1454 pr_err("SLUB <none>: no slab for object 0x%p.\n",
1455 object);
70d71228 1456 dump_stack();
06428780 1457 } else
bb192ed9 1458 object_err(s, slab, object,
24922684 1459 "page slab pointer corrupt.");
becfda68
LA
1460 return 0;
1461 }
1462 return 1;
1463}
1464
e17f1dfb
VB
1465/*
1466 * Parse a block of slub_debug options. Blocks are delimited by ';'
1467 *
1468 * @str: start of block
1469 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1470 * @slabs: return start of list of slabs, or NULL when there's no list
1471 * @init: assume this is initial parsing and not per-kmem-create parsing
1472 *
1473 * returns the start of next block if there's any, or NULL
1474 */
1475static char *
1476parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
41ecc55b 1477{
e17f1dfb 1478 bool higher_order_disable = false;
f0630fff 1479
e17f1dfb
VB
1480 /* Skip any completely empty blocks */
1481 while (*str && *str == ';')
1482 str++;
1483
1484 if (*str == ',') {
f0630fff
CL
1485 /*
1486 * No options but restriction on slabs. This means full
1487 * debugging for slabs matching a pattern.
1488 */
e17f1dfb 1489 *flags = DEBUG_DEFAULT_FLAGS;
f0630fff 1490 goto check_slabs;
e17f1dfb
VB
1491 }
1492 *flags = 0;
f0630fff 1493
e17f1dfb
VB
1494 /* Determine which debug features should be switched on */
1495 for (; *str && *str != ',' && *str != ';'; str++) {
f0630fff 1496 switch (tolower(*str)) {
e17f1dfb
VB
1497 case '-':
1498 *flags = 0;
1499 break;
f0630fff 1500 case 'f':
e17f1dfb 1501 *flags |= SLAB_CONSISTENCY_CHECKS;
f0630fff
CL
1502 break;
1503 case 'z':
e17f1dfb 1504 *flags |= SLAB_RED_ZONE;
f0630fff
CL
1505 break;
1506 case 'p':
e17f1dfb 1507 *flags |= SLAB_POISON;
f0630fff
CL
1508 break;
1509 case 'u':
e17f1dfb 1510 *flags |= SLAB_STORE_USER;
f0630fff
CL
1511 break;
1512 case 't':
e17f1dfb 1513 *flags |= SLAB_TRACE;
f0630fff 1514 break;
4c13dd3b 1515 case 'a':
e17f1dfb 1516 *flags |= SLAB_FAILSLAB;
4c13dd3b 1517 break;
08303a73
CA
1518 case 'o':
1519 /*
1520 * Avoid enabling debugging on caches if its minimum
1521 * order would increase as a result.
1522 */
e17f1dfb 1523 higher_order_disable = true;
08303a73 1524 break;
f0630fff 1525 default:
e17f1dfb
VB
1526 if (init)
1527 pr_err("slub_debug option '%c' unknown. skipped\n", *str);
f0630fff 1528 }
41ecc55b 1529 }
f0630fff 1530check_slabs:
41ecc55b 1531 if (*str == ',')
e17f1dfb
VB
1532 *slabs = ++str;
1533 else
1534 *slabs = NULL;
1535
1536 /* Skip over the slab list */
1537 while (*str && *str != ';')
1538 str++;
1539
1540 /* Skip any completely empty blocks */
1541 while (*str && *str == ';')
1542 str++;
1543
1544 if (init && higher_order_disable)
1545 disable_higher_order_debug = 1;
1546
1547 if (*str)
1548 return str;
1549 else
1550 return NULL;
1551}
1552
1553static int __init setup_slub_debug(char *str)
1554{
1555 slab_flags_t flags;
a7f1d485 1556 slab_flags_t global_flags;
e17f1dfb
VB
1557 char *saved_str;
1558 char *slab_list;
1559 bool global_slub_debug_changed = false;
1560 bool slab_list_specified = false;
1561
a7f1d485 1562 global_flags = DEBUG_DEFAULT_FLAGS;
e17f1dfb
VB
1563 if (*str++ != '=' || !*str)
1564 /*
1565 * No options specified. Switch on full debugging.
1566 */
1567 goto out;
1568
1569 saved_str = str;
1570 while (str) {
1571 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1572
1573 if (!slab_list) {
a7f1d485 1574 global_flags = flags;
e17f1dfb
VB
1575 global_slub_debug_changed = true;
1576 } else {
1577 slab_list_specified = true;
5cf909c5
OG
1578 if (flags & SLAB_STORE_USER)
1579 stack_depot_want_early_init();
e17f1dfb
VB
1580 }
1581 }
1582
1583 /*
1584 * For backwards compatibility, a single list of flags with list of
a7f1d485
VB
1585 * slabs means debugging is only changed for those slabs, so the global
1586 * slub_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1587 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
e17f1dfb
VB
1588 * long as there is no option specifying flags without a slab list.
1589 */
1590 if (slab_list_specified) {
1591 if (!global_slub_debug_changed)
a7f1d485 1592 global_flags = slub_debug;
e17f1dfb
VB
1593 slub_debug_string = saved_str;
1594 }
f0630fff 1595out:
a7f1d485 1596 slub_debug = global_flags;
5cf909c5
OG
1597 if (slub_debug & SLAB_STORE_USER)
1598 stack_depot_want_early_init();
ca0cab65
VB
1599 if (slub_debug != 0 || slub_debug_string)
1600 static_branch_enable(&slub_debug_enabled);
02ac47d0
SB
1601 else
1602 static_branch_disable(&slub_debug_enabled);
6471384a
AP
1603 if ((static_branch_unlikely(&init_on_alloc) ||
1604 static_branch_unlikely(&init_on_free)) &&
1605 (slub_debug & SLAB_POISON))
1606 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
41ecc55b
CL
1607 return 1;
1608}
1609
1610__setup("slub_debug", setup_slub_debug);
1611
c5fd3ca0
AT
1612/*
1613 * kmem_cache_flags - apply debugging options to the cache
1614 * @object_size: the size of an object without meta data
1615 * @flags: flags to set
1616 * @name: name of the cache
c5fd3ca0
AT
1617 *
1618 * Debug option(s) are applied to @flags. In addition to the debug
1619 * option(s), if a slab name (or multiple) is specified i.e.
1620 * slub_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1621 * then only the select slabs will receive the debug option(s).
1622 */
0293d1fd 1623slab_flags_t kmem_cache_flags(unsigned int object_size,
37540008 1624 slab_flags_t flags, const char *name)
41ecc55b 1625{
c5fd3ca0
AT
1626 char *iter;
1627 size_t len;
e17f1dfb
VB
1628 char *next_block;
1629 slab_flags_t block_flags;
ca220593
JB
1630 slab_flags_t slub_debug_local = slub_debug;
1631
a285909f
HY
1632 if (flags & SLAB_NO_USER_FLAGS)
1633 return flags;
1634
ca220593
JB
1635 /*
1636 * If the slab cache is for debugging (e.g. kmemleak) then
1637 * don't store user (stack trace) information by default,
1638 * but let the user enable it via the command line below.
1639 */
1640 if (flags & SLAB_NOLEAKTRACE)
1641 slub_debug_local &= ~SLAB_STORE_USER;
c5fd3ca0 1642
c5fd3ca0 1643 len = strlen(name);
e17f1dfb
VB
1644 next_block = slub_debug_string;
1645 /* Go through all blocks of debug options, see if any matches our slab's name */
1646 while (next_block) {
1647 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1648 if (!iter)
1649 continue;
1650 /* Found a block that has a slab list, search it */
1651 while (*iter) {
1652 char *end, *glob;
1653 size_t cmplen;
1654
1655 end = strchrnul(iter, ',');
1656 if (next_block && next_block < end)
1657 end = next_block - 1;
1658
1659 glob = strnchr(iter, end - iter, '*');
1660 if (glob)
1661 cmplen = glob - iter;
1662 else
1663 cmplen = max_t(size_t, len, (end - iter));
c5fd3ca0 1664
e17f1dfb
VB
1665 if (!strncmp(name, iter, cmplen)) {
1666 flags |= block_flags;
1667 return flags;
1668 }
c5fd3ca0 1669
e17f1dfb
VB
1670 if (!*end || *end == ';')
1671 break;
1672 iter = end + 1;
c5fd3ca0 1673 }
c5fd3ca0 1674 }
ba0268a8 1675
ca220593 1676 return flags | slub_debug_local;
41ecc55b 1677}
b4a64718 1678#else /* !CONFIG_SLUB_DEBUG */
c0f81a94 1679static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
a50b854e 1680static inline
bb192ed9 1681void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
41ecc55b 1682
3ec09742 1683static inline int alloc_debug_processing(struct kmem_cache *s,
6edf2576 1684 struct slab *slab, void *object, int orig_size) { return 0; }
41ecc55b 1685
c7323a5a 1686static inline void free_debug_processing(
bb192ed9 1687 struct kmem_cache *s, struct slab *slab,
81084651 1688 void *head, void *tail, int bulk_cnt,
c7323a5a 1689 unsigned long addr) {}
41ecc55b 1690
a204e6d6 1691static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
bb192ed9 1692static inline int check_object(struct kmem_cache *s, struct slab *slab,
f7cb1933 1693 void *object, u8 val) { return 1; }
c7323a5a
VB
1694static inline void set_track(struct kmem_cache *s, void *object,
1695 enum track_item alloc, unsigned long addr) {}
5cc6eee8 1696static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
bb192ed9 1697 struct slab *slab) {}
c65c1877 1698static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
bb192ed9 1699 struct slab *slab) {}
0293d1fd 1700slab_flags_t kmem_cache_flags(unsigned int object_size,
37540008 1701 slab_flags_t flags, const char *name)
ba0268a8
CL
1702{
1703 return flags;
1704}
41ecc55b 1705#define slub_debug 0
0f389ec6 1706
fdaa45e9
IM
1707#define disable_higher_order_debug 0
1708
0f389ec6
CL
1709static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1710 { return 0; }
26c02cf0
AB
1711static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1712 { return 0; }
205ab99d
CL
1713static inline void inc_slabs_node(struct kmem_cache *s, int node,
1714 int objects) {}
1715static inline void dec_slabs_node(struct kmem_cache *s, int node,
1716 int objects) {}
7d550c56 1717
bb192ed9 1718static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
dc07a728 1719 void **freelist, void *nextfree)
52f23478
DZ
1720{
1721 return false;
1722}
02e72cc6
AR
1723#endif /* CONFIG_SLUB_DEBUG */
1724
1725/*
1726 * Hooks for other subsystems that check memory allocations. In a typical
1727 * production configuration these hooks all should produce no code at all.
1728 */
d57a964e
AK
1729static __always_inline bool slab_free_hook(struct kmem_cache *s,
1730 void *x, bool init)
d56791b3
RB
1731{
1732 kmemleak_free_recursive(x, s->flags);
68ef169a 1733 kmsan_slab_free(s, x);
7d550c56 1734
84048039 1735 debug_check_no_locks_freed(x, s->object_size);
02e72cc6 1736
02e72cc6
AR
1737 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1738 debug_check_no_obj_freed(x, s->object_size);
0316bec2 1739
cfbe1636
ME
1740 /* Use KCSAN to help debug racy use-after-free. */
1741 if (!(s->flags & SLAB_TYPESAFE_BY_RCU))
1742 __kcsan_check_access(x, s->object_size,
1743 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
1744
d57a964e
AK
1745 /*
1746 * As memory initialization might be integrated into KASAN,
1747 * kasan_slab_free and initialization memset's must be
1748 * kept together to avoid discrepancies in behavior.
1749 *
1750 * The initialization memset's clear the object and the metadata,
1751 * but don't touch the SLAB redzone.
1752 */
1753 if (init) {
1754 int rsize;
1755
1756 if (!kasan_has_integrated_init())
1757 memset(kasan_reset_tag(x), 0, s->object_size);
1758 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
1759 memset((char *)kasan_reset_tag(x) + s->inuse, 0,
1760 s->size - s->inuse - rsize);
1761 }
1762 /* KASAN might put x into memory quarantine, delaying its reuse. */
1763 return kasan_slab_free(s, x, init);
02e72cc6 1764}
205ab99d 1765
c3895391 1766static inline bool slab_free_freelist_hook(struct kmem_cache *s,
899447f6
ML
1767 void **head, void **tail,
1768 int *cnt)
81084651 1769{
6471384a
AP
1770
1771 void *object;
1772 void *next = *head;
1773 void *old_tail = *tail ? *tail : *head;
6471384a 1774
b89fb5ef 1775 if (is_kfence_address(next)) {
d57a964e 1776 slab_free_hook(s, next, false);
b89fb5ef
AP
1777 return true;
1778 }
1779
aea4df4c
LA
1780 /* Head and tail of the reconstructed freelist */
1781 *head = NULL;
1782 *tail = NULL;
1b7e816f 1783
aea4df4c
LA
1784 do {
1785 object = next;
1786 next = get_freepointer(s, object);
1787
c3895391 1788 /* If object's reuse doesn't have to be delayed */
d57a964e 1789 if (!slab_free_hook(s, object, slab_want_init_on_free(s))) {
c3895391
AK
1790 /* Move object to the new freelist */
1791 set_freepointer(s, object, *head);
1792 *head = object;
1793 if (!*tail)
1794 *tail = object;
899447f6
ML
1795 } else {
1796 /*
1797 * Adjust the reconstructed freelist depth
1798 * accordingly if object's reuse is delayed.
1799 */
1800 --(*cnt);
c3895391
AK
1801 }
1802 } while (object != old_tail);
1803
1804 if (*head == *tail)
1805 *tail = NULL;
1806
1807 return *head != NULL;
81084651
JDB
1808}
1809
c0f81a94 1810static void *setup_object(struct kmem_cache *s, void *object)
588f8ba9 1811{
c0f81a94 1812 setup_object_debug(s, object);
4d176711 1813 object = kasan_init_slab_obj(s, object);
588f8ba9
TG
1814 if (unlikely(s->ctor)) {
1815 kasan_unpoison_object_data(s, object);
1816 s->ctor(object);
1817 kasan_poison_object_data(s, object);
1818 }
4d176711 1819 return object;
588f8ba9
TG
1820}
1821
81819f0f
CL
1822/*
1823 * Slab allocation and freeing
1824 */
a485e1da
XS
1825static inline struct slab *alloc_slab_page(gfp_t flags, int node,
1826 struct kmem_cache_order_objects oo)
65c3376a 1827{
45387b8c
VB
1828 struct folio *folio;
1829 struct slab *slab;
19af27af 1830 unsigned int order = oo_order(oo);
65c3376a 1831
2154a336 1832 if (node == NUMA_NO_NODE)
45387b8c 1833 folio = (struct folio *)alloc_pages(flags, order);
65c3376a 1834 else
45387b8c 1835 folio = (struct folio *)__alloc_pages_node(node, flags, order);
5dfb4175 1836
45387b8c
VB
1837 if (!folio)
1838 return NULL;
1839
1840 slab = folio_slab(folio);
1841 __folio_set_slab(folio);
8b881763
VB
1842 /* Make the flag visible before any changes to folio->mapping */
1843 smp_wmb();
45387b8c
VB
1844 if (page_is_pfmemalloc(folio_page(folio, 0)))
1845 slab_set_pfmemalloc(slab);
1846
1847 return slab;
65c3376a
CL
1848}
1849
210e7a43
TG
1850#ifdef CONFIG_SLAB_FREELIST_RANDOM
1851/* Pre-initialize the random sequence cache */
1852static int init_cache_random_seq(struct kmem_cache *s)
1853{
19af27af 1854 unsigned int count = oo_objects(s->oo);
210e7a43 1855 int err;
210e7a43 1856
a810007a
SR
1857 /* Bailout if already initialised */
1858 if (s->random_seq)
1859 return 0;
1860
210e7a43
TG
1861 err = cache_random_seq_create(s, count, GFP_KERNEL);
1862 if (err) {
1863 pr_err("SLUB: Unable to initialize free list for %s\n",
1864 s->name);
1865 return err;
1866 }
1867
1868 /* Transform to an offset on the set of pages */
1869 if (s->random_seq) {
19af27af
AD
1870 unsigned int i;
1871
210e7a43
TG
1872 for (i = 0; i < count; i++)
1873 s->random_seq[i] *= s->size;
1874 }
1875 return 0;
1876}
1877
1878/* Initialize each random sequence freelist per cache */
1879static void __init init_freelist_randomization(void)
1880{
1881 struct kmem_cache *s;
1882
1883 mutex_lock(&slab_mutex);
1884
1885 list_for_each_entry(s, &slab_caches, list)
1886 init_cache_random_seq(s);
1887
1888 mutex_unlock(&slab_mutex);
1889}
1890
1891/* Get the next entry on the pre-computed freelist randomized */
bb192ed9 1892static void *next_freelist_entry(struct kmem_cache *s, struct slab *slab,
210e7a43
TG
1893 unsigned long *pos, void *start,
1894 unsigned long page_limit,
1895 unsigned long freelist_count)
1896{
1897 unsigned int idx;
1898
1899 /*
1900 * If the target page allocation failed, the number of objects on the
1901 * page might be smaller than the usual size defined by the cache.
1902 */
1903 do {
1904 idx = s->random_seq[*pos];
1905 *pos += 1;
1906 if (*pos >= freelist_count)
1907 *pos = 0;
1908 } while (unlikely(idx >= page_limit));
1909
1910 return (char *)start + idx;
1911}
1912
1913/* Shuffle the single linked freelist based on a random pre-computed sequence */
bb192ed9 1914static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
210e7a43
TG
1915{
1916 void *start;
1917 void *cur;
1918 void *next;
1919 unsigned long idx, pos, page_limit, freelist_count;
1920
bb192ed9 1921 if (slab->objects < 2 || !s->random_seq)
210e7a43
TG
1922 return false;
1923
1924 freelist_count = oo_objects(s->oo);
81895a65 1925 pos = prandom_u32_max(freelist_count);
210e7a43 1926
bb192ed9
VB
1927 page_limit = slab->objects * s->size;
1928 start = fixup_red_left(s, slab_address(slab));
210e7a43
TG
1929
1930 /* First entry is used as the base of the freelist */
bb192ed9 1931 cur = next_freelist_entry(s, slab, &pos, start, page_limit,
210e7a43 1932 freelist_count);
c0f81a94 1933 cur = setup_object(s, cur);
bb192ed9 1934 slab->freelist = cur;
210e7a43 1935
bb192ed9
VB
1936 for (idx = 1; idx < slab->objects; idx++) {
1937 next = next_freelist_entry(s, slab, &pos, start, page_limit,
210e7a43 1938 freelist_count);
c0f81a94 1939 next = setup_object(s, next);
210e7a43
TG
1940 set_freepointer(s, cur, next);
1941 cur = next;
1942 }
210e7a43
TG
1943 set_freepointer(s, cur, NULL);
1944
1945 return true;
1946}
1947#else
1948static inline int init_cache_random_seq(struct kmem_cache *s)
1949{
1950 return 0;
1951}
1952static inline void init_freelist_randomization(void) { }
bb192ed9 1953static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
210e7a43
TG
1954{
1955 return false;
1956}
1957#endif /* CONFIG_SLAB_FREELIST_RANDOM */
1958
bb192ed9 1959static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
81819f0f 1960{
bb192ed9 1961 struct slab *slab;
834f3d11 1962 struct kmem_cache_order_objects oo = s->oo;
ba52270d 1963 gfp_t alloc_gfp;
4d176711 1964 void *start, *p, *next;
a50b854e 1965 int idx;
210e7a43 1966 bool shuffle;
81819f0f 1967
7e0528da
CL
1968 flags &= gfp_allowed_mask;
1969
b7a49f0d 1970 flags |= s->allocflags;
e12ba74d 1971
ba52270d
PE
1972 /*
1973 * Let the initial higher-order allocation fail under memory pressure
1974 * so we fall-back to the minimum order allocation.
1975 */
1976 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
d0164adc 1977 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
27c08f75 1978 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
ba52270d 1979
a485e1da 1980 slab = alloc_slab_page(alloc_gfp, node, oo);
bb192ed9 1981 if (unlikely(!slab)) {
65c3376a 1982 oo = s->min;
80c3a998 1983 alloc_gfp = flags;
65c3376a
CL
1984 /*
1985 * Allocation may have failed due to fragmentation.
1986 * Try a lower order alloc if possible
1987 */
a485e1da 1988 slab = alloc_slab_page(alloc_gfp, node, oo);
bb192ed9 1989 if (unlikely(!slab))
c7323a5a 1990 return NULL;
588f8ba9 1991 stat(s, ORDER_FALLBACK);
65c3376a 1992 }
5a896d9e 1993
bb192ed9 1994 slab->objects = oo_objects(oo);
c7323a5a
VB
1995 slab->inuse = 0;
1996 slab->frozen = 0;
81819f0f 1997
bb192ed9 1998 account_slab(slab, oo_order(oo), s, flags);
1f3147b4 1999
bb192ed9 2000 slab->slab_cache = s;
81819f0f 2001
6e48a966 2002 kasan_poison_slab(slab);
81819f0f 2003
bb192ed9 2004 start = slab_address(slab);
81819f0f 2005
bb192ed9 2006 setup_slab_debug(s, slab, start);
0316bec2 2007
bb192ed9 2008 shuffle = shuffle_freelist(s, slab);
210e7a43
TG
2009
2010 if (!shuffle) {
4d176711 2011 start = fixup_red_left(s, start);
c0f81a94 2012 start = setup_object(s, start);
bb192ed9
VB
2013 slab->freelist = start;
2014 for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
18e50661 2015 next = p + s->size;
c0f81a94 2016 next = setup_object(s, next);
18e50661
AK
2017 set_freepointer(s, p, next);
2018 p = next;
2019 }
2020 set_freepointer(s, p, NULL);
81819f0f 2021 }
81819f0f 2022
bb192ed9 2023 return slab;
81819f0f
CL
2024}
2025
bb192ed9 2026static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
588f8ba9 2027{
44405099
LL
2028 if (unlikely(flags & GFP_SLAB_BUG_MASK))
2029 flags = kmalloc_fix_flags(flags);
588f8ba9 2030
53a0de06
VB
2031 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2032
588f8ba9
TG
2033 return allocate_slab(s,
2034 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
2035}
2036
4020b4a2 2037static void __free_slab(struct kmem_cache *s, struct slab *slab)
81819f0f 2038{
4020b4a2
VB
2039 struct folio *folio = slab_folio(slab);
2040 int order = folio_order(folio);
834f3d11 2041 int pages = 1 << order;
81819f0f 2042
4020b4a2 2043 __slab_clear_pfmemalloc(slab);
4020b4a2 2044 folio->mapping = NULL;
8b881763
VB
2045 /* Make the mapping reset visible before clearing the flag */
2046 smp_wmb();
2047 __folio_clear_slab(folio);
1eb5ac64
NP
2048 if (current->reclaim_state)
2049 current->reclaim_state->reclaimed_slab += pages;
4020b4a2
VB
2050 unaccount_slab(slab, order, s);
2051 __free_pages(folio_page(folio, 0), order);
81819f0f
CL
2052}
2053
2054static void rcu_free_slab(struct rcu_head *h)
2055{
bb192ed9 2056 struct slab *slab = container_of(h, struct slab, rcu_head);
da9a638c 2057
bb192ed9 2058 __free_slab(slab->slab_cache, slab);
81819f0f
CL
2059}
2060
bb192ed9 2061static void free_slab(struct kmem_cache *s, struct slab *slab)
81819f0f 2062{
bc29d5bd
VB
2063 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
2064 void *p;
2065
2066 slab_pad_check(s, slab);
2067 for_each_object(p, s, slab_address(slab), slab->objects)
2068 check_object(s, slab, p, SLUB_RED_INACTIVE);
2069 }
2070
2071 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
bb192ed9 2072 call_rcu(&slab->rcu_head, rcu_free_slab);
bc29d5bd 2073 else
bb192ed9 2074 __free_slab(s, slab);
81819f0f
CL
2075}
2076
bb192ed9 2077static void discard_slab(struct kmem_cache *s, struct slab *slab)
81819f0f 2078{
bb192ed9
VB
2079 dec_slabs_node(s, slab_nid(slab), slab->objects);
2080 free_slab(s, slab);
81819f0f
CL
2081}
2082
2083/*
5cc6eee8 2084 * Management of partially allocated slabs.
81819f0f 2085 */
1e4dd946 2086static inline void
bb192ed9 2087__add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
81819f0f 2088{
e95eed57 2089 n->nr_partial++;
136333d1 2090 if (tail == DEACTIVATE_TO_TAIL)
bb192ed9 2091 list_add_tail(&slab->slab_list, &n->partial);
7c2e132c 2092 else
bb192ed9 2093 list_add(&slab->slab_list, &n->partial);
81819f0f
CL
2094}
2095
1e4dd946 2096static inline void add_partial(struct kmem_cache_node *n,
bb192ed9 2097 struct slab *slab, int tail)
62e346a8 2098{
c65c1877 2099 lockdep_assert_held(&n->list_lock);
bb192ed9 2100 __add_partial(n, slab, tail);
1e4dd946 2101}
c65c1877 2102
1e4dd946 2103static inline void remove_partial(struct kmem_cache_node *n,
bb192ed9 2104 struct slab *slab)
1e4dd946
SR
2105{
2106 lockdep_assert_held(&n->list_lock);
bb192ed9 2107 list_del(&slab->slab_list);
52b4b950 2108 n->nr_partial--;
1e4dd946
SR
2109}
2110
c7323a5a
VB
2111/*
2112 * Called only for kmem_cache_debug() caches instead of acquire_slab(), with a
2113 * slab from the n->partial list. Remove only a single object from the slab, do
2114 * the alloc_debug_processing() checks and leave the slab on the list, or move
2115 * it to full list if it was the last free object.
2116 */
2117static void *alloc_single_from_partial(struct kmem_cache *s,
6edf2576 2118 struct kmem_cache_node *n, struct slab *slab, int orig_size)
c7323a5a
VB
2119{
2120 void *object;
2121
2122 lockdep_assert_held(&n->list_lock);
2123
2124 object = slab->freelist;
2125 slab->freelist = get_freepointer(s, object);
2126 slab->inuse++;
2127
6edf2576 2128 if (!alloc_debug_processing(s, slab, object, orig_size)) {
c7323a5a
VB
2129 remove_partial(n, slab);
2130 return NULL;
2131 }
2132
2133 if (slab->inuse == slab->objects) {
2134 remove_partial(n, slab);
2135 add_full(s, n, slab);
2136 }
2137
2138 return object;
2139}
2140
2141/*
2142 * Called only for kmem_cache_debug() caches to allocate from a freshly
2143 * allocated slab. Allocate a single object instead of whole freelist
2144 * and put the slab to the partial (or full) list.
2145 */
2146static void *alloc_single_from_new_slab(struct kmem_cache *s,
6edf2576 2147 struct slab *slab, int orig_size)
c7323a5a
VB
2148{
2149 int nid = slab_nid(slab);
2150 struct kmem_cache_node *n = get_node(s, nid);
2151 unsigned long flags;
2152 void *object;
2153
2154
2155 object = slab->freelist;
2156 slab->freelist = get_freepointer(s, object);
2157 slab->inuse = 1;
2158
6edf2576 2159 if (!alloc_debug_processing(s, slab, object, orig_size))
c7323a5a
VB
2160 /*
2161 * It's not really expected that this would fail on a
2162 * freshly allocated slab, but a concurrent memory
2163 * corruption in theory could cause that.
2164 */
2165 return NULL;
2166
2167 spin_lock_irqsave(&n->list_lock, flags);
2168
2169 if (slab->inuse == slab->objects)
2170 add_full(s, n, slab);
2171 else
2172 add_partial(n, slab, DEACTIVATE_TO_HEAD);
2173
2174 inc_slabs_node(s, nid, slab->objects);
2175 spin_unlock_irqrestore(&n->list_lock, flags);
2176
2177 return object;
2178}
2179
81819f0f 2180/*
7ced3719
CL
2181 * Remove slab from the partial list, freeze it and
2182 * return the pointer to the freelist.
81819f0f 2183 *
497b66f2 2184 * Returns a list of objects or NULL if it fails.
81819f0f 2185 */
497b66f2 2186static inline void *acquire_slab(struct kmem_cache *s,
bb192ed9 2187 struct kmem_cache_node *n, struct slab *slab,
b47291ef 2188 int mode)
81819f0f 2189{
2cfb7455
CL
2190 void *freelist;
2191 unsigned long counters;
bb192ed9 2192 struct slab new;
2cfb7455 2193
c65c1877
PZ
2194 lockdep_assert_held(&n->list_lock);
2195
2cfb7455
CL
2196 /*
2197 * Zap the freelist and set the frozen bit.
2198 * The old freelist is the list of objects for the
2199 * per cpu allocation list.
2200 */
bb192ed9
VB
2201 freelist = slab->freelist;
2202 counters = slab->counters;
7ced3719 2203 new.counters = counters;
23910c50 2204 if (mode) {
bb192ed9 2205 new.inuse = slab->objects;
23910c50
PE
2206 new.freelist = NULL;
2207 } else {
2208 new.freelist = freelist;
2209 }
2cfb7455 2210
a0132ac0 2211 VM_BUG_ON(new.frozen);
7ced3719 2212 new.frozen = 1;
2cfb7455 2213
bb192ed9 2214 if (!__cmpxchg_double_slab(s, slab,
2cfb7455 2215 freelist, counters,
02d7633f 2216 new.freelist, new.counters,
7ced3719 2217 "acquire_slab"))
7ced3719 2218 return NULL;
2cfb7455 2219
bb192ed9 2220 remove_partial(n, slab);
7ced3719 2221 WARN_ON(!freelist);
49e22585 2222 return freelist;
81819f0f
CL
2223}
2224
e0a043aa 2225#ifdef CONFIG_SLUB_CPU_PARTIAL
bb192ed9 2226static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
e0a043aa 2227#else
bb192ed9 2228static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
e0a043aa
VB
2229 int drain) { }
2230#endif
01b34d16 2231static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
49e22585 2232
81819f0f 2233/*
672bba3a 2234 * Try to allocate a partial slab from a specific node.
81819f0f 2235 */
8ba00bb6 2236static void *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n,
6edf2576 2237 struct partial_context *pc)
81819f0f 2238{
bb192ed9 2239 struct slab *slab, *slab2;
49e22585 2240 void *object = NULL;
4b1f449d 2241 unsigned long flags;
bb192ed9 2242 unsigned int partial_slabs = 0;
81819f0f
CL
2243
2244 /*
2245 * Racy check. If we mistakenly see no partial slabs then we
2246 * just allocate an empty slab. If we mistakenly try to get a
70b6d25e 2247 * partial slab and there is none available then get_partial()
672bba3a 2248 * will return NULL.
81819f0f
CL
2249 */
2250 if (!n || !n->nr_partial)
2251 return NULL;
2252
4b1f449d 2253 spin_lock_irqsave(&n->list_lock, flags);
bb192ed9 2254 list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
8ba00bb6 2255 void *t;
49e22585 2256
6edf2576 2257 if (!pfmemalloc_match(slab, pc->flags))
8ba00bb6
JK
2258 continue;
2259
c7323a5a 2260 if (kmem_cache_debug(s)) {
6edf2576
FT
2261 object = alloc_single_from_partial(s, n, slab,
2262 pc->orig_size);
c7323a5a
VB
2263 if (object)
2264 break;
2265 continue;
2266 }
2267
bb192ed9 2268 t = acquire_slab(s, n, slab, object == NULL);
49e22585 2269 if (!t)
9b1ea29b 2270 break;
49e22585 2271
12d79634 2272 if (!object) {
6edf2576 2273 *pc->slab = slab;
49e22585 2274 stat(s, ALLOC_FROM_PARTIAL);
49e22585 2275 object = t;
49e22585 2276 } else {
bb192ed9 2277 put_cpu_partial(s, slab, 0);
8028dcea 2278 stat(s, CPU_PARTIAL_NODE);
bb192ed9 2279 partial_slabs++;
49e22585 2280 }
b47291ef 2281#ifdef CONFIG_SLUB_CPU_PARTIAL
345c905d 2282 if (!kmem_cache_has_cpu_partial(s)
bb192ed9 2283 || partial_slabs > s->cpu_partial_slabs / 2)
49e22585 2284 break;
b47291ef
VB
2285#else
2286 break;
2287#endif
49e22585 2288
497b66f2 2289 }
4b1f449d 2290 spin_unlock_irqrestore(&n->list_lock, flags);
497b66f2 2291 return object;
81819f0f
CL
2292}
2293
2294/*
c2092c12 2295 * Get a slab from somewhere. Search in increasing NUMA distances.
81819f0f 2296 */
6edf2576 2297static void *get_any_partial(struct kmem_cache *s, struct partial_context *pc)
81819f0f
CL
2298{
2299#ifdef CONFIG_NUMA
2300 struct zonelist *zonelist;
dd1a239f 2301 struct zoneref *z;
54a6eb5c 2302 struct zone *zone;
6edf2576 2303 enum zone_type highest_zoneidx = gfp_zone(pc->flags);
497b66f2 2304 void *object;
cc9a6c87 2305 unsigned int cpuset_mems_cookie;
81819f0f
CL
2306
2307 /*
672bba3a
CL
2308 * The defrag ratio allows a configuration of the tradeoffs between
2309 * inter node defragmentation and node local allocations. A lower
2310 * defrag_ratio increases the tendency to do local allocations
2311 * instead of attempting to obtain partial slabs from other nodes.
81819f0f 2312 *
672bba3a
CL
2313 * If the defrag_ratio is set to 0 then kmalloc() always
2314 * returns node local objects. If the ratio is higher then kmalloc()
2315 * may return off node objects because partial slabs are obtained
2316 * from other nodes and filled up.
81819f0f 2317 *
43efd3ea
LP
2318 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2319 * (which makes defrag_ratio = 1000) then every (well almost)
2320 * allocation will first attempt to defrag slab caches on other nodes.
2321 * This means scanning over all nodes to look for partial slabs which
2322 * may be expensive if we do it every time we are trying to find a slab
672bba3a 2323 * with available objects.
81819f0f 2324 */
9824601e
CL
2325 if (!s->remote_node_defrag_ratio ||
2326 get_cycles() % 1024 > s->remote_node_defrag_ratio)
81819f0f
CL
2327 return NULL;
2328
cc9a6c87 2329 do {
d26914d1 2330 cpuset_mems_cookie = read_mems_allowed_begin();
6edf2576 2331 zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
97a225e6 2332 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
cc9a6c87
MG
2333 struct kmem_cache_node *n;
2334
2335 n = get_node(s, zone_to_nid(zone));
2336
6edf2576 2337 if (n && cpuset_zone_allowed(zone, pc->flags) &&
cc9a6c87 2338 n->nr_partial > s->min_partial) {
6edf2576 2339 object = get_partial_node(s, n, pc);
cc9a6c87
MG
2340 if (object) {
2341 /*
d26914d1
MG
2342 * Don't check read_mems_allowed_retry()
2343 * here - if mems_allowed was updated in
2344 * parallel, that was a harmless race
2345 * between allocation and the cpuset
2346 * update
cc9a6c87 2347 */
cc9a6c87
MG
2348 return object;
2349 }
c0ff7453 2350 }
81819f0f 2351 }
d26914d1 2352 } while (read_mems_allowed_retry(cpuset_mems_cookie));
6dfd1b65 2353#endif /* CONFIG_NUMA */
81819f0f
CL
2354 return NULL;
2355}
2356
2357/*
c2092c12 2358 * Get a partial slab, lock it and return it.
81819f0f 2359 */
6edf2576 2360static void *get_partial(struct kmem_cache *s, int node, struct partial_context *pc)
81819f0f 2361{
497b66f2 2362 void *object;
a561ce00
JK
2363 int searchnode = node;
2364
2365 if (node == NUMA_NO_NODE)
2366 searchnode = numa_mem_id();
81819f0f 2367
6edf2576 2368 object = get_partial_node(s, get_node(s, searchnode), pc);
497b66f2
CL
2369 if (object || node != NUMA_NO_NODE)
2370 return object;
81819f0f 2371
6edf2576 2372 return get_any_partial(s, pc);
81819f0f
CL
2373}
2374
923717cb 2375#ifdef CONFIG_PREEMPTION
8a5ec0ba 2376/*
0d645ed1 2377 * Calculate the next globally unique transaction for disambiguation
8a5ec0ba
CL
2378 * during cmpxchg. The transactions start with the cpu number and are then
2379 * incremented by CONFIG_NR_CPUS.
2380 */
2381#define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
2382#else
2383/*
2384 * No preemption supported therefore also no need to check for
2385 * different cpus.
2386 */
2387#define TID_STEP 1
2388#endif
2389
2390static inline unsigned long next_tid(unsigned long tid)
2391{
2392 return tid + TID_STEP;
2393}
2394
9d5f0be0 2395#ifdef SLUB_DEBUG_CMPXCHG
8a5ec0ba
CL
2396static inline unsigned int tid_to_cpu(unsigned long tid)
2397{
2398 return tid % TID_STEP;
2399}
2400
2401static inline unsigned long tid_to_event(unsigned long tid)
2402{
2403 return tid / TID_STEP;
2404}
9d5f0be0 2405#endif
8a5ec0ba
CL
2406
2407static inline unsigned int init_tid(int cpu)
2408{
2409 return cpu;
2410}
2411
2412static inline void note_cmpxchg_failure(const char *n,
2413 const struct kmem_cache *s, unsigned long tid)
2414{
2415#ifdef SLUB_DEBUG_CMPXCHG
2416 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
2417
f9f58285 2418 pr_info("%s %s: cmpxchg redo ", n, s->name);
8a5ec0ba 2419
923717cb 2420#ifdef CONFIG_PREEMPTION
8a5ec0ba 2421 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
f9f58285 2422 pr_warn("due to cpu change %d -> %d\n",
8a5ec0ba
CL
2423 tid_to_cpu(tid), tid_to_cpu(actual_tid));
2424 else
2425#endif
2426 if (tid_to_event(tid) != tid_to_event(actual_tid))
f9f58285 2427 pr_warn("due to cpu running other code. Event %ld->%ld\n",
8a5ec0ba
CL
2428 tid_to_event(tid), tid_to_event(actual_tid));
2429 else
f9f58285 2430 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
8a5ec0ba
CL
2431 actual_tid, tid, next_tid(tid));
2432#endif
4fdccdfb 2433 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
8a5ec0ba
CL
2434}
2435
788e1aad 2436static void init_kmem_cache_cpus(struct kmem_cache *s)
8a5ec0ba 2437{
8a5ec0ba 2438 int cpu;
bd0e7491 2439 struct kmem_cache_cpu *c;
8a5ec0ba 2440
bd0e7491
VB
2441 for_each_possible_cpu(cpu) {
2442 c = per_cpu_ptr(s->cpu_slab, cpu);
2443 local_lock_init(&c->lock);
2444 c->tid = init_tid(cpu);
2445 }
8a5ec0ba 2446}
2cfb7455 2447
81819f0f 2448/*
c2092c12 2449 * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
a019d201
VB
2450 * unfreezes the slabs and puts it on the proper list.
2451 * Assumes the slab has been already safely taken away from kmem_cache_cpu
2452 * by the caller.
81819f0f 2453 */
bb192ed9 2454static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
a019d201 2455 void *freelist)
81819f0f 2456{
a8e53869 2457 enum slab_modes { M_NONE, M_PARTIAL, M_FREE, M_FULL_NOLIST };
bb192ed9 2458 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
6d3a16d0
HY
2459 int free_delta = 0;
2460 enum slab_modes mode = M_NONE;
d930ff03 2461 void *nextfree, *freelist_iter, *freelist_tail;
136333d1 2462 int tail = DEACTIVATE_TO_HEAD;
3406e91b 2463 unsigned long flags = 0;
bb192ed9
VB
2464 struct slab new;
2465 struct slab old;
2cfb7455 2466
bb192ed9 2467 if (slab->freelist) {
84e554e6 2468 stat(s, DEACTIVATE_REMOTE_FREES);
136333d1 2469 tail = DEACTIVATE_TO_TAIL;
2cfb7455
CL
2470 }
2471
894b8788 2472 /*
d930ff03
VB
2473 * Stage one: Count the objects on cpu's freelist as free_delta and
2474 * remember the last object in freelist_tail for later splicing.
2cfb7455 2475 */
d930ff03
VB
2476 freelist_tail = NULL;
2477 freelist_iter = freelist;
2478 while (freelist_iter) {
2479 nextfree = get_freepointer(s, freelist_iter);
2cfb7455 2480
52f23478
DZ
2481 /*
2482 * If 'nextfree' is invalid, it is possible that the object at
d930ff03
VB
2483 * 'freelist_iter' is already corrupted. So isolate all objects
2484 * starting at 'freelist_iter' by skipping them.
52f23478 2485 */
bb192ed9 2486 if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
52f23478
DZ
2487 break;
2488
d930ff03
VB
2489 freelist_tail = freelist_iter;
2490 free_delta++;
2cfb7455 2491
d930ff03 2492 freelist_iter = nextfree;
2cfb7455
CL
2493 }
2494
894b8788 2495 /*
c2092c12
VB
2496 * Stage two: Unfreeze the slab while splicing the per-cpu
2497 * freelist to the head of slab's freelist.
d930ff03 2498 *
c2092c12 2499 * Ensure that the slab is unfrozen while the list presence
d930ff03 2500 * reflects the actual number of objects during unfreeze.
2cfb7455 2501 *
6d3a16d0
HY
2502 * We first perform cmpxchg holding lock and insert to list
2503 * when it succeed. If there is mismatch then the slab is not
2504 * unfrozen and number of objects in the slab may have changed.
2505 * Then release lock and retry cmpxchg again.
894b8788 2506 */
2cfb7455 2507redo:
894b8788 2508
bb192ed9
VB
2509 old.freelist = READ_ONCE(slab->freelist);
2510 old.counters = READ_ONCE(slab->counters);
a0132ac0 2511 VM_BUG_ON(!old.frozen);
7c2e132c 2512
2cfb7455
CL
2513 /* Determine target state of the slab */
2514 new.counters = old.counters;
d930ff03
VB
2515 if (freelist_tail) {
2516 new.inuse -= free_delta;
2517 set_freepointer(s, freelist_tail, old.freelist);
2cfb7455
CL
2518 new.freelist = freelist;
2519 } else
2520 new.freelist = old.freelist;
2521
2522 new.frozen = 0;
2523
6d3a16d0
HY
2524 if (!new.inuse && n->nr_partial >= s->min_partial) {
2525 mode = M_FREE;
2526 } else if (new.freelist) {
2527 mode = M_PARTIAL;
2528 /*
2529 * Taking the spinlock removes the possibility that
2530 * acquire_slab() will see a slab that is frozen
2531 */
2532 spin_lock_irqsave(&n->list_lock, flags);
2cfb7455 2533 } else {
6d3a16d0 2534 mode = M_FULL_NOLIST;
2cfb7455
CL
2535 }
2536
2cfb7455 2537
bb192ed9 2538 if (!cmpxchg_double_slab(s, slab,
2cfb7455
CL
2539 old.freelist, old.counters,
2540 new.freelist, new.counters,
6d3a16d0 2541 "unfreezing slab")) {
a8e53869 2542 if (mode == M_PARTIAL)
6d3a16d0 2543 spin_unlock_irqrestore(&n->list_lock, flags);
2cfb7455 2544 goto redo;
6d3a16d0 2545 }
2cfb7455 2546
2cfb7455 2547
6d3a16d0
HY
2548 if (mode == M_PARTIAL) {
2549 add_partial(n, slab, tail);
2550 spin_unlock_irqrestore(&n->list_lock, flags);
88349a28 2551 stat(s, tail);
6d3a16d0 2552 } else if (mode == M_FREE) {
2cfb7455 2553 stat(s, DEACTIVATE_EMPTY);
bb192ed9 2554 discard_slab(s, slab);
2cfb7455 2555 stat(s, FREE_SLAB);
6d3a16d0
HY
2556 } else if (mode == M_FULL_NOLIST) {
2557 stat(s, DEACTIVATE_FULL);
894b8788 2558 }
81819f0f
CL
2559}
2560
345c905d 2561#ifdef CONFIG_SLUB_CPU_PARTIAL
bb192ed9 2562static void __unfreeze_partials(struct kmem_cache *s, struct slab *partial_slab)
fc1455f4 2563{
43d77867 2564 struct kmem_cache_node *n = NULL, *n2 = NULL;
bb192ed9 2565 struct slab *slab, *slab_to_discard = NULL;
7cf9f3ba 2566 unsigned long flags = 0;
49e22585 2567
bb192ed9
VB
2568 while (partial_slab) {
2569 struct slab new;
2570 struct slab old;
49e22585 2571
bb192ed9
VB
2572 slab = partial_slab;
2573 partial_slab = slab->next;
43d77867 2574
bb192ed9 2575 n2 = get_node(s, slab_nid(slab));
43d77867
JK
2576 if (n != n2) {
2577 if (n)
7cf9f3ba 2578 spin_unlock_irqrestore(&n->list_lock, flags);
43d77867
JK
2579
2580 n = n2;
7cf9f3ba 2581 spin_lock_irqsave(&n->list_lock, flags);
43d77867 2582 }
49e22585
CL
2583
2584 do {
2585
bb192ed9
VB
2586 old.freelist = slab->freelist;
2587 old.counters = slab->counters;
a0132ac0 2588 VM_BUG_ON(!old.frozen);
49e22585
CL
2589
2590 new.counters = old.counters;
2591 new.freelist = old.freelist;
2592
2593 new.frozen = 0;
2594
bb192ed9 2595 } while (!__cmpxchg_double_slab(s, slab,
49e22585
CL
2596 old.freelist, old.counters,
2597 new.freelist, new.counters,
2598 "unfreezing slab"));
2599
8a5b20ae 2600 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) {
bb192ed9
VB
2601 slab->next = slab_to_discard;
2602 slab_to_discard = slab;
43d77867 2603 } else {
bb192ed9 2604 add_partial(n, slab, DEACTIVATE_TO_TAIL);
43d77867 2605 stat(s, FREE_ADD_PARTIAL);
49e22585
CL
2606 }
2607 }
2608
2609 if (n)
7cf9f3ba 2610 spin_unlock_irqrestore(&n->list_lock, flags);
8de06a6f 2611
bb192ed9
VB
2612 while (slab_to_discard) {
2613 slab = slab_to_discard;
2614 slab_to_discard = slab_to_discard->next;
9ada1934
SL
2615
2616 stat(s, DEACTIVATE_EMPTY);
bb192ed9 2617 discard_slab(s, slab);
9ada1934
SL
2618 stat(s, FREE_SLAB);
2619 }
fc1455f4 2620}
f3ab8b6b 2621
fc1455f4
VB
2622/*
2623 * Unfreeze all the cpu partial slabs.
2624 */
2625static void unfreeze_partials(struct kmem_cache *s)
2626{
bb192ed9 2627 struct slab *partial_slab;
fc1455f4
VB
2628 unsigned long flags;
2629
bd0e7491 2630 local_lock_irqsave(&s->cpu_slab->lock, flags);
bb192ed9 2631 partial_slab = this_cpu_read(s->cpu_slab->partial);
fc1455f4 2632 this_cpu_write(s->cpu_slab->partial, NULL);
bd0e7491 2633 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
fc1455f4 2634
bb192ed9
VB
2635 if (partial_slab)
2636 __unfreeze_partials(s, partial_slab);
fc1455f4
VB
2637}
2638
2639static void unfreeze_partials_cpu(struct kmem_cache *s,
2640 struct kmem_cache_cpu *c)
2641{
bb192ed9 2642 struct slab *partial_slab;
fc1455f4 2643
bb192ed9 2644 partial_slab = slub_percpu_partial(c);
fc1455f4
VB
2645 c->partial = NULL;
2646
bb192ed9
VB
2647 if (partial_slab)
2648 __unfreeze_partials(s, partial_slab);
49e22585
CL
2649}
2650
2651/*
c2092c12
VB
2652 * Put a slab that was just frozen (in __slab_free|get_partial_node) into a
2653 * partial slab slot if available.
49e22585
CL
2654 *
2655 * If we did not find a slot then simply move all the partials to the
2656 * per node partial list.
2657 */
bb192ed9 2658static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
49e22585 2659{
bb192ed9
VB
2660 struct slab *oldslab;
2661 struct slab *slab_to_unfreeze = NULL;
e0a043aa 2662 unsigned long flags;
bb192ed9 2663 int slabs = 0;
49e22585 2664
bd0e7491 2665 local_lock_irqsave(&s->cpu_slab->lock, flags);
49e22585 2666
bb192ed9 2667 oldslab = this_cpu_read(s->cpu_slab->partial);
e0a043aa 2668
bb192ed9
VB
2669 if (oldslab) {
2670 if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
e0a043aa
VB
2671 /*
2672 * Partial array is full. Move the existing set to the
2673 * per node partial list. Postpone the actual unfreezing
2674 * outside of the critical section.
2675 */
bb192ed9
VB
2676 slab_to_unfreeze = oldslab;
2677 oldslab = NULL;
e0a043aa 2678 } else {
bb192ed9 2679 slabs = oldslab->slabs;
49e22585 2680 }
e0a043aa 2681 }
49e22585 2682
bb192ed9 2683 slabs++;
49e22585 2684
bb192ed9
VB
2685 slab->slabs = slabs;
2686 slab->next = oldslab;
49e22585 2687
bb192ed9 2688 this_cpu_write(s->cpu_slab->partial, slab);
e0a043aa 2689
bd0e7491 2690 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
e0a043aa 2691
bb192ed9
VB
2692 if (slab_to_unfreeze) {
2693 __unfreeze_partials(s, slab_to_unfreeze);
e0a043aa
VB
2694 stat(s, CPU_PARTIAL_DRAIN);
2695 }
49e22585
CL
2696}
2697
e0a043aa
VB
2698#else /* CONFIG_SLUB_CPU_PARTIAL */
2699
2700static inline void unfreeze_partials(struct kmem_cache *s) { }
2701static inline void unfreeze_partials_cpu(struct kmem_cache *s,
2702 struct kmem_cache_cpu *c) { }
2703
2704#endif /* CONFIG_SLUB_CPU_PARTIAL */
2705
dfb4f096 2706static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
81819f0f 2707{
5a836bf6 2708 unsigned long flags;
bb192ed9 2709 struct slab *slab;
5a836bf6
SAS
2710 void *freelist;
2711
bd0e7491 2712 local_lock_irqsave(&s->cpu_slab->lock, flags);
5a836bf6 2713
bb192ed9 2714 slab = c->slab;
5a836bf6 2715 freelist = c->freelist;
c17dda40 2716
bb192ed9 2717 c->slab = NULL;
a019d201 2718 c->freelist = NULL;
c17dda40 2719 c->tid = next_tid(c->tid);
a019d201 2720
bd0e7491 2721 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
a019d201 2722
bb192ed9
VB
2723 if (slab) {
2724 deactivate_slab(s, slab, freelist);
5a836bf6
SAS
2725 stat(s, CPUSLAB_FLUSH);
2726 }
81819f0f
CL
2727}
2728
0c710013 2729static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
81819f0f 2730{
9dfc6e68 2731 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
08beb547 2732 void *freelist = c->freelist;
bb192ed9 2733 struct slab *slab = c->slab;
81819f0f 2734
bb192ed9 2735 c->slab = NULL;
08beb547
VB
2736 c->freelist = NULL;
2737 c->tid = next_tid(c->tid);
2738
bb192ed9
VB
2739 if (slab) {
2740 deactivate_slab(s, slab, freelist);
08beb547
VB
2741 stat(s, CPUSLAB_FLUSH);
2742 }
49e22585 2743
fc1455f4 2744 unfreeze_partials_cpu(s, c);
81819f0f
CL
2745}
2746
5a836bf6
SAS
2747struct slub_flush_work {
2748 struct work_struct work;
2749 struct kmem_cache *s;
2750 bool skip;
2751};
2752
fc1455f4
VB
2753/*
2754 * Flush cpu slab.
2755 *
5a836bf6 2756 * Called from CPU work handler with migration disabled.
fc1455f4 2757 */
5a836bf6 2758static void flush_cpu_slab(struct work_struct *w)
81819f0f 2759{
5a836bf6
SAS
2760 struct kmem_cache *s;
2761 struct kmem_cache_cpu *c;
2762 struct slub_flush_work *sfw;
2763
2764 sfw = container_of(w, struct slub_flush_work, work);
2765
2766 s = sfw->s;
2767 c = this_cpu_ptr(s->cpu_slab);
fc1455f4 2768
bb192ed9 2769 if (c->slab)
fc1455f4 2770 flush_slab(s, c);
81819f0f 2771
fc1455f4 2772 unfreeze_partials(s);
81819f0f
CL
2773}
2774
5a836bf6 2775static bool has_cpu_slab(int cpu, struct kmem_cache *s)
a8364d55 2776{
a8364d55
GBY
2777 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2778
bb192ed9 2779 return c->slab || slub_percpu_partial(c);
a8364d55
GBY
2780}
2781
5a836bf6
SAS
2782static DEFINE_MUTEX(flush_lock);
2783static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
2784
2785static void flush_all_cpus_locked(struct kmem_cache *s)
2786{
2787 struct slub_flush_work *sfw;
2788 unsigned int cpu;
2789
2790 lockdep_assert_cpus_held();
2791 mutex_lock(&flush_lock);
2792
2793 for_each_online_cpu(cpu) {
2794 sfw = &per_cpu(slub_flush, cpu);
2795 if (!has_cpu_slab(cpu, s)) {
2796 sfw->skip = true;
2797 continue;
2798 }
2799 INIT_WORK(&sfw->work, flush_cpu_slab);
2800 sfw->skip = false;
2801 sfw->s = s;
e45cc288 2802 queue_work_on(cpu, flushwq, &sfw->work);
5a836bf6
SAS
2803 }
2804
2805 for_each_online_cpu(cpu) {
2806 sfw = &per_cpu(slub_flush, cpu);
2807 if (sfw->skip)
2808 continue;
2809 flush_work(&sfw->work);
2810 }
2811
2812 mutex_unlock(&flush_lock);
2813}
2814
81819f0f
CL
2815static void flush_all(struct kmem_cache *s)
2816{
5a836bf6
SAS
2817 cpus_read_lock();
2818 flush_all_cpus_locked(s);
2819 cpus_read_unlock();
81819f0f
CL
2820}
2821
a96a87bf
SAS
2822/*
2823 * Use the cpu notifier to insure that the cpu slabs are flushed when
2824 * necessary.
2825 */
2826static int slub_cpu_dead(unsigned int cpu)
2827{
2828 struct kmem_cache *s;
a96a87bf
SAS
2829
2830 mutex_lock(&slab_mutex);
0e7ac738 2831 list_for_each_entry(s, &slab_caches, list)
a96a87bf 2832 __flush_cpu_slab(s, cpu);
a96a87bf
SAS
2833 mutex_unlock(&slab_mutex);
2834 return 0;
2835}
2836
dfb4f096
CL
2837/*
2838 * Check if the objects in a per cpu structure fit numa
2839 * locality expectations.
2840 */
bb192ed9 2841static inline int node_match(struct slab *slab, int node)
dfb4f096
CL
2842{
2843#ifdef CONFIG_NUMA
bb192ed9 2844 if (node != NUMA_NO_NODE && slab_nid(slab) != node)
dfb4f096
CL
2845 return 0;
2846#endif
2847 return 1;
2848}
2849
9a02d699 2850#ifdef CONFIG_SLUB_DEBUG
bb192ed9 2851static int count_free(struct slab *slab)
781b2ba6 2852{
bb192ed9 2853 return slab->objects - slab->inuse;
781b2ba6
PE
2854}
2855
9a02d699
DR
2856static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2857{
2858 return atomic_long_read(&n->total_objects);
2859}
a579b056
VB
2860
2861/* Supports checking bulk free of a constructed freelist */
c7323a5a 2862static noinline void free_debug_processing(
a579b056
VB
2863 struct kmem_cache *s, struct slab *slab,
2864 void *head, void *tail, int bulk_cnt,
2865 unsigned long addr)
2866{
2867 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
c7323a5a 2868 struct slab *slab_free = NULL;
a579b056
VB
2869 void *object = head;
2870 int cnt = 0;
c7323a5a
VB
2871 unsigned long flags;
2872 bool checks_ok = false;
a579b056
VB
2873 depot_stack_handle_t handle = 0;
2874
2875 if (s->flags & SLAB_STORE_USER)
2876 handle = set_track_prepare();
2877
2878 spin_lock_irqsave(&n->list_lock, flags);
a579b056
VB
2879
2880 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
2881 if (!check_slab(s, slab))
2882 goto out;
2883 }
2884
c7323a5a
VB
2885 if (slab->inuse < bulk_cnt) {
2886 slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
2887 slab->inuse, bulk_cnt);
2888 goto out;
2889 }
2890
a579b056 2891next_object:
c7323a5a
VB
2892
2893 if (++cnt > bulk_cnt)
2894 goto out_cnt;
a579b056
VB
2895
2896 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
2897 if (!free_consistency_checks(s, slab, object, addr))
2898 goto out;
2899 }
2900
2901 if (s->flags & SLAB_STORE_USER)
2902 set_track_update(s, object, TRACK_FREE, addr, handle);
2903 trace(s, slab, object, 0);
2904 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
2905 init_object(s, object, SLUB_RED_INACTIVE);
2906
2907 /* Reached end of constructed freelist yet? */
2908 if (object != tail) {
2909 object = get_freepointer(s, object);
2910 goto next_object;
2911 }
c7323a5a 2912 checks_ok = true;
a579b056 2913
c7323a5a 2914out_cnt:
a579b056 2915 if (cnt != bulk_cnt)
c7323a5a 2916 slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
a579b056
VB
2917 bulk_cnt, cnt);
2918
c7323a5a
VB
2919out:
2920 if (checks_ok) {
2921 void *prior = slab->freelist;
2922
2923 /* Perform the actual freeing while we still hold the locks */
2924 slab->inuse -= cnt;
2925 set_freepointer(s, tail, prior);
2926 slab->freelist = head;
2927
b731e357
FT
2928 /*
2929 * If the slab is empty, and node's partial list is full,
2930 * it should be discarded anyway no matter it's on full or
2931 * partial list.
2932 */
2933 if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
2934 slab_free = slab;
2935
c7323a5a 2936 if (!prior) {
b731e357 2937 /* was on full list */
c7323a5a 2938 remove_full(s, n, slab);
b731e357
FT
2939 if (!slab_free) {
2940 add_partial(n, slab, DEACTIVATE_TO_TAIL);
2941 stat(s, FREE_ADD_PARTIAL);
2942 }
2943 } else if (slab_free) {
c7323a5a
VB
2944 remove_partial(n, slab);
2945 stat(s, FREE_REMOVE_PARTIAL);
2946 }
c7323a5a
VB
2947 }
2948
2949 if (slab_free) {
2950 /*
2951 * Update the counters while still holding n->list_lock to
2952 * prevent spurious validation warnings
2953 */
2954 dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
2955 }
2956
a579b056 2957 spin_unlock_irqrestore(&n->list_lock, flags);
c7323a5a
VB
2958
2959 if (!checks_ok)
a579b056 2960 slab_fix(s, "Object at 0x%p not freed", object);
c7323a5a
VB
2961
2962 if (slab_free) {
2963 stat(s, FREE_SLAB);
2964 free_slab(s, slab_free);
2965 }
a579b056 2966}
9a02d699
DR
2967#endif /* CONFIG_SLUB_DEBUG */
2968
2969#if defined(CONFIG_SLUB_DEBUG) || defined(CONFIG_SYSFS)
781b2ba6 2970static unsigned long count_partial(struct kmem_cache_node *n,
bb192ed9 2971 int (*get_count)(struct slab *))
781b2ba6
PE
2972{
2973 unsigned long flags;
2974 unsigned long x = 0;
bb192ed9 2975 struct slab *slab;
781b2ba6
PE
2976
2977 spin_lock_irqsave(&n->list_lock, flags);
bb192ed9
VB
2978 list_for_each_entry(slab, &n->partial, slab_list)
2979 x += get_count(slab);
781b2ba6
PE
2980 spin_unlock_irqrestore(&n->list_lock, flags);
2981 return x;
2982}
9a02d699 2983#endif /* CONFIG_SLUB_DEBUG || CONFIG_SYSFS */
26c02cf0 2984
781b2ba6
PE
2985static noinline void
2986slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2987{
9a02d699
DR
2988#ifdef CONFIG_SLUB_DEBUG
2989 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
2990 DEFAULT_RATELIMIT_BURST);
781b2ba6 2991 int node;
fa45dc25 2992 struct kmem_cache_node *n;
781b2ba6 2993
9a02d699
DR
2994 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
2995 return;
2996
5b3810e5
VB
2997 pr_warn("SLUB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
2998 nid, gfpflags, &gfpflags);
19af27af 2999 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
f9f58285
FF
3000 s->name, s->object_size, s->size, oo_order(s->oo),
3001 oo_order(s->min));
781b2ba6 3002
3b0efdfa 3003 if (oo_order(s->min) > get_order(s->object_size))
f9f58285
FF
3004 pr_warn(" %s debugging increased min order, use slub_debug=O to disable.\n",
3005 s->name);
fa5ec8a1 3006
fa45dc25 3007 for_each_kmem_cache_node(s, node, n) {
781b2ba6
PE
3008 unsigned long nr_slabs;
3009 unsigned long nr_objs;
3010 unsigned long nr_free;
3011
26c02cf0
AB
3012 nr_free = count_partial(n, count_free);
3013 nr_slabs = node_nr_slabs(n);
3014 nr_objs = node_nr_objs(n);
781b2ba6 3015
f9f58285 3016 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
781b2ba6
PE
3017 node, nr_slabs, nr_objs, nr_free);
3018 }
9a02d699 3019#endif
781b2ba6
PE
3020}
3021
01b34d16 3022static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
072bb0aa 3023{
01b34d16 3024 if (unlikely(slab_test_pfmemalloc(slab)))
0b303fb4
VB
3025 return gfp_pfmemalloc_allowed(gfpflags);
3026
3027 return true;
3028}
3029
213eeb9f 3030/*
c2092c12
VB
3031 * Check the slab->freelist and either transfer the freelist to the
3032 * per cpu freelist or deactivate the slab.
213eeb9f 3033 *
c2092c12 3034 * The slab is still frozen if the return value is not NULL.
213eeb9f 3035 *
c2092c12 3036 * If this function returns NULL then the slab has been unfrozen.
213eeb9f 3037 */
bb192ed9 3038static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
213eeb9f 3039{
bb192ed9 3040 struct slab new;
213eeb9f
CL
3041 unsigned long counters;
3042 void *freelist;
3043
bd0e7491
VB
3044 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3045
213eeb9f 3046 do {
bb192ed9
VB
3047 freelist = slab->freelist;
3048 counters = slab->counters;
6faa6833 3049
213eeb9f 3050 new.counters = counters;
a0132ac0 3051 VM_BUG_ON(!new.frozen);
213eeb9f 3052
bb192ed9 3053 new.inuse = slab->objects;
213eeb9f
CL
3054 new.frozen = freelist != NULL;
3055
bb192ed9 3056 } while (!__cmpxchg_double_slab(s, slab,
213eeb9f
CL
3057 freelist, counters,
3058 NULL, new.counters,
3059 "get_freelist"));
3060
3061 return freelist;
3062}
3063
81819f0f 3064/*
894b8788
CL
3065 * Slow path. The lockless freelist is empty or we need to perform
3066 * debugging duties.
3067 *
894b8788
CL
3068 * Processing is still very fast if new objects have been freed to the
3069 * regular freelist. In that case we simply take over the regular freelist
3070 * as the lockless freelist and zap the regular freelist.
81819f0f 3071 *
894b8788
CL
3072 * If that is not working then we fall back to the partial lists. We take the
3073 * first element of the freelist as the object to allocate now and move the
3074 * rest of the freelist to the lockless freelist.
81819f0f 3075 *
894b8788 3076 * And if we were unable to get a new slab from the partial slab lists then
6446faa2
CL
3077 * we need to allocate a new slab. This is the slowest path since it involves
3078 * a call to the page allocator and the setup of a new slab.
a380a3c7 3079 *
e500059b 3080 * Version of __slab_alloc to use when we know that preemption is
a380a3c7 3081 * already disabled (which is the case for bulk allocation).
81819f0f 3082 */
a380a3c7 3083static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
6edf2576 3084 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
81819f0f 3085{
6faa6833 3086 void *freelist;
bb192ed9 3087 struct slab *slab;
e500059b 3088 unsigned long flags;
6edf2576 3089 struct partial_context pc;
81819f0f 3090
9f986d99
AW
3091 stat(s, ALLOC_SLOWPATH);
3092
c2092c12 3093reread_slab:
0b303fb4 3094
bb192ed9
VB
3095 slab = READ_ONCE(c->slab);
3096 if (!slab) {
0715e6c5
VB
3097 /*
3098 * if the node is not online or has no normal memory, just
3099 * ignore the node constraint
3100 */
3101 if (unlikely(node != NUMA_NO_NODE &&
7e1fa93d 3102 !node_isset(node, slab_nodes)))
0715e6c5 3103 node = NUMA_NO_NODE;
81819f0f 3104 goto new_slab;
0715e6c5 3105 }
49e22585 3106redo:
6faa6833 3107
bb192ed9 3108 if (unlikely(!node_match(slab, node))) {
0715e6c5
VB
3109 /*
3110 * same as above but node_match() being false already
3111 * implies node != NUMA_NO_NODE
3112 */
7e1fa93d 3113 if (!node_isset(node, slab_nodes)) {
0715e6c5 3114 node = NUMA_NO_NODE;
0715e6c5 3115 } else {
a561ce00 3116 stat(s, ALLOC_NODE_MISMATCH);
0b303fb4 3117 goto deactivate_slab;
a561ce00 3118 }
fc59c053 3119 }
6446faa2 3120
072bb0aa
MG
3121 /*
3122 * By rights, we should be searching for a slab page that was
3123 * PFMEMALLOC but right now, we are losing the pfmemalloc
3124 * information when the page leaves the per-cpu allocator
3125 */
bb192ed9 3126 if (unlikely(!pfmemalloc_match(slab, gfpflags)))
0b303fb4 3127 goto deactivate_slab;
072bb0aa 3128
c2092c12 3129 /* must check again c->slab in case we got preempted and it changed */
bd0e7491 3130 local_lock_irqsave(&s->cpu_slab->lock, flags);
bb192ed9 3131 if (unlikely(slab != c->slab)) {
bd0e7491 3132 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
c2092c12 3133 goto reread_slab;
0b303fb4 3134 }
6faa6833
CL
3135 freelist = c->freelist;
3136 if (freelist)
73736e03 3137 goto load_freelist;
03e404af 3138
bb192ed9 3139 freelist = get_freelist(s, slab);
6446faa2 3140
6faa6833 3141 if (!freelist) {
bb192ed9 3142 c->slab = NULL;
eeaa345e 3143 c->tid = next_tid(c->tid);
bd0e7491 3144 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
03e404af 3145 stat(s, DEACTIVATE_BYPASS);
fc59c053 3146 goto new_slab;
03e404af 3147 }
6446faa2 3148
84e554e6 3149 stat(s, ALLOC_REFILL);
6446faa2 3150
894b8788 3151load_freelist:
0b303fb4 3152
bd0e7491 3153 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
0b303fb4 3154
507effea
CL
3155 /*
3156 * freelist is pointing to the list of objects to be used.
c2092c12
VB
3157 * slab is pointing to the slab from which the objects are obtained.
3158 * That slab must be frozen for per cpu allocations to work.
507effea 3159 */
bb192ed9 3160 VM_BUG_ON(!c->slab->frozen);
6faa6833 3161 c->freelist = get_freepointer(s, freelist);
8a5ec0ba 3162 c->tid = next_tid(c->tid);
bd0e7491 3163 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
6faa6833 3164 return freelist;
81819f0f 3165
0b303fb4
VB
3166deactivate_slab:
3167
bd0e7491 3168 local_lock_irqsave(&s->cpu_slab->lock, flags);
bb192ed9 3169 if (slab != c->slab) {
bd0e7491 3170 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
c2092c12 3171 goto reread_slab;
0b303fb4 3172 }
a019d201 3173 freelist = c->freelist;
bb192ed9 3174 c->slab = NULL;
a019d201 3175 c->freelist = NULL;
eeaa345e 3176 c->tid = next_tid(c->tid);
bd0e7491 3177 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
bb192ed9 3178 deactivate_slab(s, slab, freelist);
0b303fb4 3179
81819f0f 3180new_slab:
2cfb7455 3181
a93cf07b 3182 if (slub_percpu_partial(c)) {
bd0e7491 3183 local_lock_irqsave(&s->cpu_slab->lock, flags);
bb192ed9 3184 if (unlikely(c->slab)) {
bd0e7491 3185 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
c2092c12 3186 goto reread_slab;
fa417ab7 3187 }
4b1f449d 3188 if (unlikely(!slub_percpu_partial(c))) {
bd0e7491 3189 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
25c00c50
VB
3190 /* we were preempted and partial list got empty */
3191 goto new_objects;
4b1f449d 3192 }
fa417ab7 3193
bb192ed9
VB
3194 slab = c->slab = slub_percpu_partial(c);
3195 slub_set_percpu_partial(c, slab);
bd0e7491 3196 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
49e22585 3197 stat(s, CPU_PARTIAL_ALLOC);
49e22585 3198 goto redo;
81819f0f
CL
3199 }
3200
fa417ab7
VB
3201new_objects:
3202
6edf2576
FT
3203 pc.flags = gfpflags;
3204 pc.slab = &slab;
3205 pc.orig_size = orig_size;
3206 freelist = get_partial(s, node, &pc);
3f2b77e3 3207 if (freelist)
c2092c12 3208 goto check_new_slab;
2a904905 3209
25c00c50 3210 slub_put_cpu_ptr(s->cpu_slab);
bb192ed9 3211 slab = new_slab(s, gfpflags, node);
25c00c50 3212 c = slub_get_cpu_ptr(s->cpu_slab);
01ad8a7b 3213
bb192ed9 3214 if (unlikely(!slab)) {
9a02d699 3215 slab_out_of_memory(s, gfpflags, node);
f4697436 3216 return NULL;
81819f0f 3217 }
2cfb7455 3218
c7323a5a
VB
3219 stat(s, ALLOC_SLAB);
3220
3221 if (kmem_cache_debug(s)) {
6edf2576 3222 freelist = alloc_single_from_new_slab(s, slab, orig_size);
c7323a5a
VB
3223
3224 if (unlikely(!freelist))
3225 goto new_objects;
3226
3227 if (s->flags & SLAB_STORE_USER)
3228 set_track(s, freelist, TRACK_ALLOC, addr);
3229
3230 return freelist;
3231 }
3232
53a0de06 3233 /*
c2092c12 3234 * No other reference to the slab yet so we can
53a0de06
VB
3235 * muck around with it freely without cmpxchg
3236 */
bb192ed9
VB
3237 freelist = slab->freelist;
3238 slab->freelist = NULL;
c7323a5a
VB
3239 slab->inuse = slab->objects;
3240 slab->frozen = 1;
53a0de06 3241
c7323a5a 3242 inc_slabs_node(s, slab_nid(slab), slab->objects);
53a0de06 3243
c2092c12 3244check_new_slab:
2cfb7455 3245
1572df7c 3246 if (kmem_cache_debug(s)) {
c7323a5a
VB
3247 /*
3248 * For debug caches here we had to go through
3249 * alloc_single_from_partial() so just store the tracking info
3250 * and return the object
3251 */
3252 if (s->flags & SLAB_STORE_USER)
3253 set_track(s, freelist, TRACK_ALLOC, addr);
6edf2576 3254
c7323a5a 3255 return freelist;
1572df7c
VB
3256 }
3257
c7323a5a 3258 if (unlikely(!pfmemalloc_match(slab, gfpflags))) {
1572df7c
VB
3259 /*
3260 * For !pfmemalloc_match() case we don't load freelist so that
3261 * we don't make further mismatched allocations easier.
3262 */
c7323a5a
VB
3263 deactivate_slab(s, slab, get_freepointer(s, freelist));
3264 return freelist;
3265 }
1572df7c 3266
c2092c12 3267retry_load_slab:
cfdf836e 3268
bd0e7491 3269 local_lock_irqsave(&s->cpu_slab->lock, flags);
bb192ed9 3270 if (unlikely(c->slab)) {
cfdf836e 3271 void *flush_freelist = c->freelist;
bb192ed9 3272 struct slab *flush_slab = c->slab;
cfdf836e 3273
bb192ed9 3274 c->slab = NULL;
cfdf836e
VB
3275 c->freelist = NULL;
3276 c->tid = next_tid(c->tid);
3277
bd0e7491 3278 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
cfdf836e 3279
bb192ed9 3280 deactivate_slab(s, flush_slab, flush_freelist);
cfdf836e
VB
3281
3282 stat(s, CPUSLAB_FLUSH);
3283
c2092c12 3284 goto retry_load_slab;
cfdf836e 3285 }
bb192ed9 3286 c->slab = slab;
3f2b77e3 3287
1572df7c 3288 goto load_freelist;
894b8788
CL
3289}
3290
a380a3c7 3291/*
e500059b
VB
3292 * A wrapper for ___slab_alloc() for contexts where preemption is not yet
3293 * disabled. Compensates for possible cpu changes by refetching the per cpu area
3294 * pointer.
a380a3c7
CL
3295 */
3296static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
6edf2576 3297 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
a380a3c7
CL
3298{
3299 void *p;
a380a3c7 3300
e500059b 3301#ifdef CONFIG_PREEMPT_COUNT
a380a3c7
CL
3302 /*
3303 * We may have been preempted and rescheduled on a different
e500059b 3304 * cpu before disabling preemption. Need to reload cpu area
a380a3c7
CL
3305 * pointer.
3306 */
25c00c50 3307 c = slub_get_cpu_ptr(s->cpu_slab);
a380a3c7
CL
3308#endif
3309
6edf2576 3310 p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
e500059b 3311#ifdef CONFIG_PREEMPT_COUNT
25c00c50 3312 slub_put_cpu_ptr(s->cpu_slab);
e500059b 3313#endif
a380a3c7
CL
3314 return p;
3315}
3316
0f181f9f
AP
3317/*
3318 * If the object has been wiped upon free, make sure it's fully initialized by
3319 * zeroing out freelist pointer.
3320 */
3321static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
3322 void *obj)
3323{
3324 if (unlikely(slab_want_init_on_free(s)) && obj)
ce5716c6
AK
3325 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
3326 0, sizeof(void *));
0f181f9f
AP
3327}
3328
894b8788
CL
3329/*
3330 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
3331 * have the fastpath folded into their functions. So no function call
3332 * overhead for requests that can be satisfied on the fastpath.
3333 *
3334 * The fastpath works by first checking if the lockless freelist can be used.
3335 * If not then __slab_alloc is called for slow processing.
3336 *
3337 * Otherwise we can simply pick the next object from the lockless free list.
3338 */
88f2ef73 3339static __always_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
b89fb5ef 3340 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
894b8788 3341{
03ec0ed5 3342 void *object;
dfb4f096 3343 struct kmem_cache_cpu *c;
bb192ed9 3344 struct slab *slab;
8a5ec0ba 3345 unsigned long tid;
964d4bd3 3346 struct obj_cgroup *objcg = NULL;
da844b78 3347 bool init = false;
1f84260c 3348
88f2ef73 3349 s = slab_pre_alloc_hook(s, lru, &objcg, 1, gfpflags);
8135be5a 3350 if (!s)
773ff60e 3351 return NULL;
b89fb5ef
AP
3352
3353 object = kfence_alloc(s, orig_size, gfpflags);
3354 if (unlikely(object))
3355 goto out;
3356
8a5ec0ba 3357redo:
8a5ec0ba
CL
3358 /*
3359 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
3360 * enabled. We may switch back and forth between cpus while
3361 * reading from one cpu area. That does not matter as long
3362 * as we end up on the original cpu again when doing the cmpxchg.
7cccd80b 3363 *
9b4bc85a
VB
3364 * We must guarantee that tid and kmem_cache_cpu are retrieved on the
3365 * same cpu. We read first the kmem_cache_cpu pointer and use it to read
3366 * the tid. If we are preempted and switched to another cpu between the
3367 * two reads, it's OK as the two are still associated with the same cpu
3368 * and cmpxchg later will validate the cpu.
8a5ec0ba 3369 */
9b4bc85a
VB
3370 c = raw_cpu_ptr(s->cpu_slab);
3371 tid = READ_ONCE(c->tid);
9aabf810
JK
3372
3373 /*
3374 * Irqless object alloc/free algorithm used here depends on sequence
3375 * of fetching cpu_slab's data. tid should be fetched before anything
c2092c12 3376 * on c to guarantee that object and slab associated with previous tid
9aabf810 3377 * won't be used with current tid. If we fetch tid first, object and
c2092c12 3378 * slab could be one associated with next tid and our alloc/free
9aabf810
JK
3379 * request will be failed. In this case, we will retry. So, no problem.
3380 */
3381 barrier();
8a5ec0ba 3382
8a5ec0ba
CL
3383 /*
3384 * The transaction ids are globally unique per cpu and per operation on
3385 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
3386 * occurs on the right processor and that there was no operation on the
3387 * linked list in between.
3388 */
8a5ec0ba 3389
9dfc6e68 3390 object = c->freelist;
bb192ed9 3391 slab = c->slab;
1f04b07d
TG
3392
3393 if (!USE_LOCKLESS_FAST_PATH() ||
bb192ed9 3394 unlikely(!object || !slab || !node_match(slab, node))) {
6edf2576 3395 object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
8eae1492 3396 } else {
0ad9500e
ED
3397 void *next_object = get_freepointer_safe(s, object);
3398
8a5ec0ba 3399 /*
25985edc 3400 * The cmpxchg will only match if there was no additional
8a5ec0ba
CL
3401 * operation and if we are on the right processor.
3402 *
d0e0ac97
CG
3403 * The cmpxchg does the following atomically (without lock
3404 * semantics!)
8a5ec0ba
CL
3405 * 1. Relocate first pointer to the current per cpu area.
3406 * 2. Verify that tid and freelist have not been changed
3407 * 3. If they were not changed replace tid and freelist
3408 *
d0e0ac97
CG
3409 * Since this is without lock semantics the protection is only
3410 * against code executing on this cpu *not* from access by
3411 * other cpus.
8a5ec0ba 3412 */
933393f5 3413 if (unlikely(!this_cpu_cmpxchg_double(
8a5ec0ba
CL
3414 s->cpu_slab->freelist, s->cpu_slab->tid,
3415 object, tid,
0ad9500e 3416 next_object, next_tid(tid)))) {
8a5ec0ba
CL
3417
3418 note_cmpxchg_failure("slab_alloc", s, tid);
3419 goto redo;
3420 }
0ad9500e 3421 prefetch_freepointer(s, next_object);
84e554e6 3422 stat(s, ALLOC_FASTPATH);
894b8788 3423 }
0f181f9f 3424
ce5716c6 3425 maybe_wipe_obj_freeptr(s, object);
da844b78 3426 init = slab_want_init_on_alloc(gfpflags, s);
d07dbea4 3427
b89fb5ef 3428out:
9ce67395
FT
3429 /*
3430 * When init equals 'true', like for kzalloc() family, only
3431 * @orig_size bytes might be zeroed instead of s->object_size
3432 */
3433 slab_post_alloc_hook(s, objcg, gfpflags, 1, &object, init, orig_size);
5a896d9e 3434
894b8788 3435 return object;
81819f0f
CL
3436}
3437
88f2ef73 3438static __always_inline void *slab_alloc(struct kmem_cache *s, struct list_lru *lru,
b89fb5ef 3439 gfp_t gfpflags, unsigned long addr, size_t orig_size)
2b847c3c 3440{
88f2ef73 3441 return slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, addr, orig_size);
2b847c3c
EG
3442}
3443
88f2ef73
MS
3444static __always_inline
3445void *__kmem_cache_alloc_lru(struct kmem_cache *s, struct list_lru *lru,
3446 gfp_t gfpflags)
81819f0f 3447{
88f2ef73 3448 void *ret = slab_alloc(s, lru, gfpflags, _RET_IP_, s->object_size);
5b882be4 3449
2c1d697f 3450 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
5b882be4
EGM
3451
3452 return ret;
81819f0f 3453}
88f2ef73
MS
3454
3455void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
3456{
3457 return __kmem_cache_alloc_lru(s, NULL, gfpflags);
3458}
81819f0f
CL
3459EXPORT_SYMBOL(kmem_cache_alloc);
3460
88f2ef73
MS
3461void *kmem_cache_alloc_lru(struct kmem_cache *s, struct list_lru *lru,
3462 gfp_t gfpflags)
3463{
3464 return __kmem_cache_alloc_lru(s, lru, gfpflags);
3465}
3466EXPORT_SYMBOL(kmem_cache_alloc_lru);
3467
ed4cd17e
HY
3468void *__kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags,
3469 int node, size_t orig_size,
3470 unsigned long caller)
4a92379b 3471{
ed4cd17e
HY
3472 return slab_alloc_node(s, NULL, gfpflags, node,
3473 caller, orig_size);
4a92379b 3474}
5b882be4 3475
81819f0f
CL
3476void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
3477{
88f2ef73 3478 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
5b882be4 3479
2c1d697f 3480 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
5b882be4
EGM
3481
3482 return ret;
81819f0f
CL
3483}
3484EXPORT_SYMBOL(kmem_cache_alloc_node);
81819f0f
CL
3485
3486/*
94e4d712 3487 * Slow path handling. This may still be called frequently since objects
894b8788 3488 * have a longer lifetime than the cpu slabs in most processing loads.
81819f0f 3489 *
894b8788 3490 * So we still attempt to reduce cache line usage. Just take the slab
c2092c12 3491 * lock and free the item. If there is no additional partial slab
894b8788 3492 * handling required then we can return immediately.
81819f0f 3493 */
bb192ed9 3494static void __slab_free(struct kmem_cache *s, struct slab *slab,
81084651
JDB
3495 void *head, void *tail, int cnt,
3496 unsigned long addr)
3497
81819f0f
CL
3498{
3499 void *prior;
2cfb7455 3500 int was_frozen;
bb192ed9 3501 struct slab new;
2cfb7455
CL
3502 unsigned long counters;
3503 struct kmem_cache_node *n = NULL;
3f649ab7 3504 unsigned long flags;
81819f0f 3505
8a5ec0ba 3506 stat(s, FREE_SLOWPATH);
81819f0f 3507
b89fb5ef
AP
3508 if (kfence_free(head))
3509 return;
3510
c7323a5a
VB
3511 if (kmem_cache_debug(s)) {
3512 free_debug_processing(s, slab, head, tail, cnt, addr);
80f08c19 3513 return;
c7323a5a 3514 }
6446faa2 3515
2cfb7455 3516 do {
837d678d
JK
3517 if (unlikely(n)) {
3518 spin_unlock_irqrestore(&n->list_lock, flags);
3519 n = NULL;
3520 }
bb192ed9
VB
3521 prior = slab->freelist;
3522 counters = slab->counters;
81084651 3523 set_freepointer(s, tail, prior);
2cfb7455
CL
3524 new.counters = counters;
3525 was_frozen = new.frozen;
81084651 3526 new.inuse -= cnt;
837d678d 3527 if ((!new.inuse || !prior) && !was_frozen) {
49e22585 3528
c65c1877 3529 if (kmem_cache_has_cpu_partial(s) && !prior) {
49e22585
CL
3530
3531 /*
d0e0ac97
CG
3532 * Slab was on no list before and will be
3533 * partially empty
3534 * We can defer the list move and instead
3535 * freeze it.
49e22585
CL
3536 */
3537 new.frozen = 1;
3538
c65c1877 3539 } else { /* Needs to be taken off a list */
49e22585 3540
bb192ed9 3541 n = get_node(s, slab_nid(slab));
49e22585
CL
3542 /*
3543 * Speculatively acquire the list_lock.
3544 * If the cmpxchg does not succeed then we may
3545 * drop the list_lock without any processing.
3546 *
3547 * Otherwise the list_lock will synchronize with
3548 * other processors updating the list of slabs.
3549 */
3550 spin_lock_irqsave(&n->list_lock, flags);
3551
3552 }
2cfb7455 3553 }
81819f0f 3554
bb192ed9 3555 } while (!cmpxchg_double_slab(s, slab,
2cfb7455 3556 prior, counters,
81084651 3557 head, new.counters,
2cfb7455 3558 "__slab_free"));
81819f0f 3559
2cfb7455 3560 if (likely(!n)) {
49e22585 3561
c270cf30
AW
3562 if (likely(was_frozen)) {
3563 /*
3564 * The list lock was not taken therefore no list
3565 * activity can be necessary.
3566 */
3567 stat(s, FREE_FROZEN);
3568 } else if (new.frozen) {
3569 /*
c2092c12 3570 * If we just froze the slab then put it onto the
c270cf30
AW
3571 * per cpu partial list.
3572 */
bb192ed9 3573 put_cpu_partial(s, slab, 1);
8028dcea
AS
3574 stat(s, CPU_PARTIAL_FREE);
3575 }
c270cf30 3576
b455def2
L
3577 return;
3578 }
81819f0f 3579
8a5b20ae 3580 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
837d678d
JK
3581 goto slab_empty;
3582
81819f0f 3583 /*
837d678d
JK
3584 * Objects left in the slab. If it was not on the partial list before
3585 * then add it.
81819f0f 3586 */
345c905d 3587 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
bb192ed9
VB
3588 remove_full(s, n, slab);
3589 add_partial(n, slab, DEACTIVATE_TO_TAIL);
837d678d 3590 stat(s, FREE_ADD_PARTIAL);
8ff12cfc 3591 }
80f08c19 3592 spin_unlock_irqrestore(&n->list_lock, flags);
81819f0f
CL
3593 return;
3594
3595slab_empty:
a973e9dd 3596 if (prior) {
81819f0f 3597 /*
6fbabb20 3598 * Slab on the partial list.
81819f0f 3599 */
bb192ed9 3600 remove_partial(n, slab);
84e554e6 3601 stat(s, FREE_REMOVE_PARTIAL);
c65c1877 3602 } else {
6fbabb20 3603 /* Slab must be on the full list */
bb192ed9 3604 remove_full(s, n, slab);
c65c1877 3605 }
2cfb7455 3606
80f08c19 3607 spin_unlock_irqrestore(&n->list_lock, flags);
84e554e6 3608 stat(s, FREE_SLAB);
bb192ed9 3609 discard_slab(s, slab);
81819f0f
CL
3610}
3611
894b8788
CL
3612/*
3613 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
3614 * can perform fastpath freeing without additional function calls.
3615 *
3616 * The fastpath is only possible if we are freeing to the current cpu slab
3617 * of this processor. This typically the case if we have just allocated
3618 * the item before.
3619 *
3620 * If fastpath is not possible then fall back to __slab_free where we deal
3621 * with all sorts of special processing.
81084651
JDB
3622 *
3623 * Bulk free of a freelist with several objects (all pointing to the
c2092c12 3624 * same slab) possible by specifying head and tail ptr, plus objects
81084651 3625 * count (cnt). Bulk free indicated by tail pointer being set.
894b8788 3626 */
80a9201a 3627static __always_inline void do_slab_free(struct kmem_cache *s,
bb192ed9 3628 struct slab *slab, void *head, void *tail,
80a9201a 3629 int cnt, unsigned long addr)
894b8788 3630{
81084651 3631 void *tail_obj = tail ? : head;
dfb4f096 3632 struct kmem_cache_cpu *c;
8a5ec0ba 3633 unsigned long tid;
1f04b07d 3634 void **freelist;
964d4bd3 3635
8a5ec0ba
CL
3636redo:
3637 /*
3638 * Determine the currently cpus per cpu slab.
3639 * The cpu may change afterward. However that does not matter since
3640 * data is retrieved via this pointer. If we are on the same cpu
2ae44005 3641 * during the cmpxchg then the free will succeed.
8a5ec0ba 3642 */
9b4bc85a
VB
3643 c = raw_cpu_ptr(s->cpu_slab);
3644 tid = READ_ONCE(c->tid);
c016b0bd 3645
9aabf810
JK
3646 /* Same with comment on barrier() in slab_alloc_node() */
3647 barrier();
c016b0bd 3648
1f04b07d
TG
3649 if (unlikely(slab != c->slab)) {
3650 __slab_free(s, slab, head, tail_obj, cnt, addr);
3651 return;
3652 }
3653
3654 if (USE_LOCKLESS_FAST_PATH()) {
3655 freelist = READ_ONCE(c->freelist);
5076190d
LT
3656
3657 set_freepointer(s, tail_obj, freelist);
8a5ec0ba 3658
933393f5 3659 if (unlikely(!this_cpu_cmpxchg_double(
8a5ec0ba 3660 s->cpu_slab->freelist, s->cpu_slab->tid,
5076190d 3661 freelist, tid,
81084651 3662 head, next_tid(tid)))) {
8a5ec0ba
CL
3663
3664 note_cmpxchg_failure("slab_free", s, tid);
3665 goto redo;
3666 }
1f04b07d
TG
3667 } else {
3668 /* Update the free list under the local lock */
bd0e7491
VB
3669 local_lock(&s->cpu_slab->lock);
3670 c = this_cpu_ptr(s->cpu_slab);
bb192ed9 3671 if (unlikely(slab != c->slab)) {
bd0e7491
VB
3672 local_unlock(&s->cpu_slab->lock);
3673 goto redo;
3674 }
3675 tid = c->tid;
3676 freelist = c->freelist;
3677
3678 set_freepointer(s, tail_obj, freelist);
3679 c->freelist = head;
3680 c->tid = next_tid(tid);
3681
3682 local_unlock(&s->cpu_slab->lock);
1f04b07d
TG
3683 }
3684 stat(s, FREE_FASTPATH);
894b8788
CL
3685}
3686
bb192ed9 3687static __always_inline void slab_free(struct kmem_cache *s, struct slab *slab,
b77d5b1b 3688 void *head, void *tail, void **p, int cnt,
80a9201a
AP
3689 unsigned long addr)
3690{
b77d5b1b 3691 memcg_slab_free_hook(s, slab, p, cnt);
80a9201a 3692 /*
c3895391
AK
3693 * With KASAN enabled slab_free_freelist_hook modifies the freelist
3694 * to remove objects, whose reuse must be delayed.
80a9201a 3695 */
899447f6 3696 if (slab_free_freelist_hook(s, &head, &tail, &cnt))
bb192ed9 3697 do_slab_free(s, slab, head, tail, cnt, addr);
80a9201a
AP
3698}
3699
2bd926b4 3700#ifdef CONFIG_KASAN_GENERIC
80a9201a
AP
3701void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
3702{
bb192ed9 3703 do_slab_free(cache, virt_to_slab(x), x, NULL, 1, addr);
80a9201a
AP
3704}
3705#endif
3706
ed4cd17e
HY
3707void __kmem_cache_free(struct kmem_cache *s, void *x, unsigned long caller)
3708{
3709 slab_free(s, virt_to_slab(x), x, NULL, &x, 1, caller);
3710}
3711
81819f0f
CL
3712void kmem_cache_free(struct kmem_cache *s, void *x)
3713{
b9ce5ef4
GC
3714 s = cache_from_obj(s, x);
3715 if (!s)
79576102 3716 return;
2c1d697f 3717 trace_kmem_cache_free(_RET_IP_, x, s);
b77d5b1b 3718 slab_free(s, virt_to_slab(x), x, NULL, &x, 1, _RET_IP_);
81819f0f
CL
3719}
3720EXPORT_SYMBOL(kmem_cache_free);
3721
d0ecd894 3722struct detached_freelist {
cc465c3b 3723 struct slab *slab;
d0ecd894
JDB
3724 void *tail;
3725 void *freelist;
3726 int cnt;
376bf125 3727 struct kmem_cache *s;
d0ecd894 3728};
fbd02630 3729
d0ecd894
JDB
3730/*
3731 * This function progressively scans the array with free objects (with
3732 * a limited look ahead) and extract objects belonging to the same
cc465c3b
MWO
3733 * slab. It builds a detached freelist directly within the given
3734 * slab/objects. This can happen without any need for
d0ecd894
JDB
3735 * synchronization, because the objects are owned by running process.
3736 * The freelist is build up as a single linked list in the objects.
3737 * The idea is, that this detached freelist can then be bulk
3738 * transferred to the real freelist(s), but only requiring a single
3739 * synchronization primitive. Look ahead in the array is limited due
3740 * to performance reasons.
3741 */
376bf125
JDB
3742static inline
3743int build_detached_freelist(struct kmem_cache *s, size_t size,
3744 void **p, struct detached_freelist *df)
d0ecd894 3745{
d0ecd894
JDB
3746 int lookahead = 3;
3747 void *object;
cc465c3b 3748 struct folio *folio;
b77d5b1b 3749 size_t same;
fbd02630 3750
b77d5b1b 3751 object = p[--size];
cc465c3b 3752 folio = virt_to_folio(object);
ca257195
JDB
3753 if (!s) {
3754 /* Handle kalloc'ed objects */
cc465c3b 3755 if (unlikely(!folio_test_slab(folio))) {
d835eef4 3756 free_large_kmalloc(folio, object);
b77d5b1b 3757 df->slab = NULL;
ca257195
JDB
3758 return size;
3759 }
3760 /* Derive kmem_cache from object */
b77d5b1b
MS
3761 df->slab = folio_slab(folio);
3762 df->s = df->slab->slab_cache;
ca257195 3763 } else {
b77d5b1b 3764 df->slab = folio_slab(folio);
ca257195
JDB
3765 df->s = cache_from_obj(s, object); /* Support for memcg */
3766 }
376bf125 3767
d0ecd894 3768 /* Start new detached freelist */
d0ecd894
JDB
3769 df->tail = object;
3770 df->freelist = object;
d0ecd894
JDB
3771 df->cnt = 1;
3772
b77d5b1b
MS
3773 if (is_kfence_address(object))
3774 return size;
3775
3776 set_freepointer(df->s, object, NULL);
3777
3778 same = size;
d0ecd894
JDB
3779 while (size) {
3780 object = p[--size];
cc465c3b
MWO
3781 /* df->slab is always set at this point */
3782 if (df->slab == virt_to_slab(object)) {
d0ecd894 3783 /* Opportunity build freelist */
376bf125 3784 set_freepointer(df->s, object, df->freelist);
d0ecd894
JDB
3785 df->freelist = object;
3786 df->cnt++;
b77d5b1b
MS
3787 same--;
3788 if (size != same)
3789 swap(p[size], p[same]);
d0ecd894 3790 continue;
fbd02630 3791 }
d0ecd894
JDB
3792
3793 /* Limit look ahead search */
3794 if (!--lookahead)
3795 break;
fbd02630 3796 }
d0ecd894 3797
b77d5b1b 3798 return same;
d0ecd894
JDB
3799}
3800
d0ecd894 3801/* Note that interrupts must be enabled when calling this function. */
376bf125 3802void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
d0ecd894 3803{
2055e67b 3804 if (!size)
d0ecd894
JDB
3805 return;
3806
3807 do {
3808 struct detached_freelist df;
3809
3810 size = build_detached_freelist(s, size, p, &df);
cc465c3b 3811 if (!df.slab)
d0ecd894
JDB
3812 continue;
3813
b77d5b1b
MS
3814 slab_free(df.s, df.slab, df.freelist, df.tail, &p[size], df.cnt,
3815 _RET_IP_);
d0ecd894 3816 } while (likely(size));
484748f0
CL
3817}
3818EXPORT_SYMBOL(kmem_cache_free_bulk);
3819
994eb764 3820/* Note that interrupts must be enabled when calling this function. */
865762a8
JDB
3821int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3822 void **p)
484748f0 3823{
994eb764
JDB
3824 struct kmem_cache_cpu *c;
3825 int i;
964d4bd3 3826 struct obj_cgroup *objcg = NULL;
994eb764 3827
03ec0ed5 3828 /* memcg and kmem_cache debug support */
88f2ef73 3829 s = slab_pre_alloc_hook(s, NULL, &objcg, size, flags);
03ec0ed5
JDB
3830 if (unlikely(!s))
3831 return false;
994eb764
JDB
3832 /*
3833 * Drain objects in the per cpu slab, while disabling local
3834 * IRQs, which protects against PREEMPT and interrupts
3835 * handlers invoking normal fastpath.
3836 */
25c00c50 3837 c = slub_get_cpu_ptr(s->cpu_slab);
bd0e7491 3838 local_lock_irq(&s->cpu_slab->lock);
994eb764
JDB
3839
3840 for (i = 0; i < size; i++) {
b89fb5ef 3841 void *object = kfence_alloc(s, s->object_size, flags);
994eb764 3842
b89fb5ef
AP
3843 if (unlikely(object)) {
3844 p[i] = object;
3845 continue;
3846 }
3847
3848 object = c->freelist;
ebe909e0 3849 if (unlikely(!object)) {
fd4d9c7d
JH
3850 /*
3851 * We may have removed an object from c->freelist using
3852 * the fastpath in the previous iteration; in that case,
3853 * c->tid has not been bumped yet.
3854 * Since ___slab_alloc() may reenable interrupts while
3855 * allocating memory, we should bump c->tid now.
3856 */
3857 c->tid = next_tid(c->tid);
3858
bd0e7491 3859 local_unlock_irq(&s->cpu_slab->lock);
e500059b 3860
ebe909e0
JDB
3861 /*
3862 * Invoking slow path likely have side-effect
3863 * of re-populating per CPU c->freelist
3864 */
87098373 3865 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
6edf2576 3866 _RET_IP_, c, s->object_size);
87098373
CL
3867 if (unlikely(!p[i]))
3868 goto error;
3869
ebe909e0 3870 c = this_cpu_ptr(s->cpu_slab);
0f181f9f
AP
3871 maybe_wipe_obj_freeptr(s, p[i]);
3872
bd0e7491 3873 local_lock_irq(&s->cpu_slab->lock);
e500059b 3874
ebe909e0
JDB
3875 continue; /* goto for-loop */
3876 }
994eb764
JDB
3877 c->freelist = get_freepointer(s, object);
3878 p[i] = object;
0f181f9f 3879 maybe_wipe_obj_freeptr(s, p[i]);
994eb764
JDB
3880 }
3881 c->tid = next_tid(c->tid);
bd0e7491 3882 local_unlock_irq(&s->cpu_slab->lock);
25c00c50 3883 slub_put_cpu_ptr(s->cpu_slab);
994eb764 3884
da844b78
AK
3885 /*
3886 * memcg and kmem_cache debug support and memory initialization.
3887 * Done outside of the IRQ disabled fastpath loop.
3888 */
3889 slab_post_alloc_hook(s, objcg, flags, size, p,
9ce67395 3890 slab_want_init_on_alloc(flags, s), s->object_size);
865762a8 3891 return i;
87098373 3892error:
25c00c50 3893 slub_put_cpu_ptr(s->cpu_slab);
9ce67395 3894 slab_post_alloc_hook(s, objcg, flags, i, p, false, s->object_size);
2055e67b 3895 kmem_cache_free_bulk(s, i, p);
865762a8 3896 return 0;
484748f0
CL
3897}
3898EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3899
3900
81819f0f 3901/*
672bba3a
CL
3902 * Object placement in a slab is made very easy because we always start at
3903 * offset 0. If we tune the size of the object to the alignment then we can
3904 * get the required alignment by putting one properly sized object after
3905 * another.
81819f0f
CL
3906 *
3907 * Notice that the allocation order determines the sizes of the per cpu
3908 * caches. Each processor has always one slab available for allocations.
3909 * Increasing the allocation order reduces the number of times that slabs
672bba3a 3910 * must be moved on and off the partial lists and is therefore a factor in
81819f0f 3911 * locking overhead.
81819f0f
CL
3912 */
3913
3914/*
f0953a1b 3915 * Minimum / Maximum order of slab pages. This influences locking overhead
81819f0f
CL
3916 * and slab fragmentation. A higher order reduces the number of partial slabs
3917 * and increases the number of allocations possible without having to
3918 * take the list_lock.
3919 */
19af27af
AD
3920static unsigned int slub_min_order;
3921static unsigned int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
3922static unsigned int slub_min_objects;
81819f0f 3923
81819f0f
CL
3924/*
3925 * Calculate the order of allocation given an slab object size.
3926 *
672bba3a
CL
3927 * The order of allocation has significant impact on performance and other
3928 * system components. Generally order 0 allocations should be preferred since
3929 * order 0 does not cause fragmentation in the page allocator. Larger objects
3930 * be problematic to put into order 0 slabs because there may be too much
c124f5b5 3931 * unused space left. We go to a higher order if more than 1/16th of the slab
672bba3a
CL
3932 * would be wasted.
3933 *
3934 * In order to reach satisfactory performance we must ensure that a minimum
3935 * number of objects is in one slab. Otherwise we may generate too much
3936 * activity on the partial lists which requires taking the list_lock. This is
3937 * less a concern for large slabs though which are rarely used.
81819f0f 3938 *
672bba3a
CL
3939 * slub_max_order specifies the order where we begin to stop considering the
3940 * number of objects in a slab as critical. If we reach slub_max_order then
3941 * we try to keep the page order as low as possible. So we accept more waste
3942 * of space in favor of a small page order.
81819f0f 3943 *
672bba3a
CL
3944 * Higher order allocations also allow the placement of more objects in a
3945 * slab and thereby reduce object handling overhead. If the user has
dc84207d 3946 * requested a higher minimum order then we start with that one instead of
672bba3a 3947 * the smallest order which will fit the object.
81819f0f 3948 */
d122019b 3949static inline unsigned int calc_slab_order(unsigned int size,
19af27af 3950 unsigned int min_objects, unsigned int max_order,
9736d2a9 3951 unsigned int fract_leftover)
81819f0f 3952{
19af27af
AD
3953 unsigned int min_order = slub_min_order;
3954 unsigned int order;
81819f0f 3955
9736d2a9 3956 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
210b5c06 3957 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
39b26464 3958
9736d2a9 3959 for (order = max(min_order, (unsigned int)get_order(min_objects * size));
5e6d444e 3960 order <= max_order; order++) {
81819f0f 3961
19af27af
AD
3962 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
3963 unsigned int rem;
81819f0f 3964
9736d2a9 3965 rem = slab_size % size;
81819f0f 3966
5e6d444e 3967 if (rem <= slab_size / fract_leftover)
81819f0f 3968 break;
81819f0f 3969 }
672bba3a 3970
81819f0f
CL
3971 return order;
3972}
3973
9736d2a9 3974static inline int calculate_order(unsigned int size)
5e6d444e 3975{
19af27af
AD
3976 unsigned int order;
3977 unsigned int min_objects;
3978 unsigned int max_objects;
3286222f 3979 unsigned int nr_cpus;
5e6d444e
CL
3980
3981 /*
3982 * Attempt to find best configuration for a slab. This
3983 * works by first attempting to generate a layout with
3984 * the best configuration and backing off gradually.
3985 *
422ff4d7 3986 * First we increase the acceptable waste in a slab. Then
5e6d444e
CL
3987 * we reduce the minimum objects required in a slab.
3988 */
3989 min_objects = slub_min_objects;
3286222f
VB
3990 if (!min_objects) {
3991 /*
3992 * Some architectures will only update present cpus when
3993 * onlining them, so don't trust the number if it's just 1. But
3994 * we also don't want to use nr_cpu_ids always, as on some other
3995 * architectures, there can be many possible cpus, but never
3996 * onlined. Here we compromise between trying to avoid too high
3997 * order on systems that appear larger than they are, and too
3998 * low order on systems that appear smaller than they are.
3999 */
4000 nr_cpus = num_present_cpus();
4001 if (nr_cpus <= 1)
4002 nr_cpus = nr_cpu_ids;
4003 min_objects = 4 * (fls(nr_cpus) + 1);
4004 }
9736d2a9 4005 max_objects = order_objects(slub_max_order, size);
e8120ff1
ZY
4006 min_objects = min(min_objects, max_objects);
4007
5e6d444e 4008 while (min_objects > 1) {
19af27af
AD
4009 unsigned int fraction;
4010
c124f5b5 4011 fraction = 16;
5e6d444e 4012 while (fraction >= 4) {
d122019b 4013 order = calc_slab_order(size, min_objects,
9736d2a9 4014 slub_max_order, fraction);
5e6d444e
CL
4015 if (order <= slub_max_order)
4016 return order;
4017 fraction /= 2;
4018 }
5086c389 4019 min_objects--;
5e6d444e
CL
4020 }
4021
4022 /*
4023 * We were unable to place multiple objects in a slab. Now
4024 * lets see if we can place a single object there.
4025 */
d122019b 4026 order = calc_slab_order(size, 1, slub_max_order, 1);
5e6d444e
CL
4027 if (order <= slub_max_order)
4028 return order;
4029
4030 /*
4031 * Doh this slab cannot be placed using slub_max_order.
4032 */
d122019b 4033 order = calc_slab_order(size, 1, MAX_ORDER, 1);
818cf590 4034 if (order < MAX_ORDER)
5e6d444e
CL
4035 return order;
4036 return -ENOSYS;
4037}
4038
5595cffc 4039static void
4053497d 4040init_kmem_cache_node(struct kmem_cache_node *n)
81819f0f
CL
4041{
4042 n->nr_partial = 0;
81819f0f
CL
4043 spin_lock_init(&n->list_lock);
4044 INIT_LIST_HEAD(&n->partial);
8ab1372f 4045#ifdef CONFIG_SLUB_DEBUG
0f389ec6 4046 atomic_long_set(&n->nr_slabs, 0);
02b71b70 4047 atomic_long_set(&n->total_objects, 0);
643b1138 4048 INIT_LIST_HEAD(&n->full);
8ab1372f 4049#endif
81819f0f
CL
4050}
4051
55136592 4052static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
4c93c355 4053{
6c182dc0 4054 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
a0dc161a
BH
4055 NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
4056 sizeof(struct kmem_cache_cpu));
4c93c355 4057
8a5ec0ba 4058 /*
d4d84fef
CM
4059 * Must align to double word boundary for the double cmpxchg
4060 * instructions to work; see __pcpu_double_call_return_bool().
8a5ec0ba 4061 */
d4d84fef
CM
4062 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
4063 2 * sizeof(void *));
8a5ec0ba
CL
4064
4065 if (!s->cpu_slab)
4066 return 0;
4067
4068 init_kmem_cache_cpus(s);
4c93c355 4069
8a5ec0ba 4070 return 1;
4c93c355 4071}
4c93c355 4072
51df1142
CL
4073static struct kmem_cache *kmem_cache_node;
4074
81819f0f
CL
4075/*
4076 * No kmalloc_node yet so do it by hand. We know that this is the first
4077 * slab on the node for this slabcache. There are no concurrent accesses
4078 * possible.
4079 *
721ae22a
ZYW
4080 * Note that this function only works on the kmem_cache_node
4081 * when allocating for the kmem_cache_node. This is used for bootstrapping
4c93c355 4082 * memory on a fresh node that has no slab structures yet.
81819f0f 4083 */
55136592 4084static void early_kmem_cache_node_alloc(int node)
81819f0f 4085{
bb192ed9 4086 struct slab *slab;
81819f0f
CL
4087 struct kmem_cache_node *n;
4088
51df1142 4089 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
81819f0f 4090
bb192ed9 4091 slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
81819f0f 4092
bb192ed9 4093 BUG_ON(!slab);
c7323a5a 4094 inc_slabs_node(kmem_cache_node, slab_nid(slab), slab->objects);
bb192ed9 4095 if (slab_nid(slab) != node) {
f9f58285
FF
4096 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
4097 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
a2f92ee7
CL
4098 }
4099
bb192ed9 4100 n = slab->freelist;
81819f0f 4101 BUG_ON(!n);
8ab1372f 4102#ifdef CONFIG_SLUB_DEBUG
f7cb1933 4103 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
51df1142 4104 init_tracking(kmem_cache_node, n);
8ab1372f 4105#endif
da844b78 4106 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
bb192ed9
VB
4107 slab->freelist = get_freepointer(kmem_cache_node, n);
4108 slab->inuse = 1;
12b22386 4109 kmem_cache_node->node[node] = n;
4053497d 4110 init_kmem_cache_node(n);
bb192ed9 4111 inc_slabs_node(kmem_cache_node, node, slab->objects);
6446faa2 4112
67b6c900 4113 /*
1e4dd946
SR
4114 * No locks need to be taken here as it has just been
4115 * initialized and there is no concurrent access.
67b6c900 4116 */
bb192ed9 4117 __add_partial(n, slab, DEACTIVATE_TO_HEAD);
81819f0f
CL
4118}
4119
4120static void free_kmem_cache_nodes(struct kmem_cache *s)
4121{
4122 int node;
fa45dc25 4123 struct kmem_cache_node *n;
81819f0f 4124
fa45dc25 4125 for_each_kmem_cache_node(s, node, n) {
81819f0f 4126 s->node[node] = NULL;
ea37df54 4127 kmem_cache_free(kmem_cache_node, n);
81819f0f
CL
4128 }
4129}
4130
52b4b950
DS
4131void __kmem_cache_release(struct kmem_cache *s)
4132{
210e7a43 4133 cache_random_seq_destroy(s);
52b4b950
DS
4134 free_percpu(s->cpu_slab);
4135 free_kmem_cache_nodes(s);
4136}
4137
55136592 4138static int init_kmem_cache_nodes(struct kmem_cache *s)
81819f0f
CL
4139{
4140 int node;
81819f0f 4141
7e1fa93d 4142 for_each_node_mask(node, slab_nodes) {
81819f0f
CL
4143 struct kmem_cache_node *n;
4144
73367bd8 4145 if (slab_state == DOWN) {
55136592 4146 early_kmem_cache_node_alloc(node);
73367bd8
AD
4147 continue;
4148 }
51df1142 4149 n = kmem_cache_alloc_node(kmem_cache_node,
55136592 4150 GFP_KERNEL, node);
81819f0f 4151
73367bd8
AD
4152 if (!n) {
4153 free_kmem_cache_nodes(s);
4154 return 0;
81819f0f 4155 }
73367bd8 4156
4053497d 4157 init_kmem_cache_node(n);
ea37df54 4158 s->node[node] = n;
81819f0f
CL
4159 }
4160 return 1;
4161}
81819f0f 4162
e6d0e1dc
WY
4163static void set_cpu_partial(struct kmem_cache *s)
4164{
4165#ifdef CONFIG_SLUB_CPU_PARTIAL
b47291ef
VB
4166 unsigned int nr_objects;
4167
e6d0e1dc
WY
4168 /*
4169 * cpu_partial determined the maximum number of objects kept in the
4170 * per cpu partial lists of a processor.
4171 *
4172 * Per cpu partial lists mainly contain slabs that just have one
4173 * object freed. If they are used for allocation then they can be
4174 * filled up again with minimal effort. The slab will never hit the
4175 * per node partial lists and therefore no locking will be required.
4176 *
b47291ef
VB
4177 * For backwards compatibility reasons, this is determined as number
4178 * of objects, even though we now limit maximum number of pages, see
4179 * slub_set_cpu_partial()
e6d0e1dc
WY
4180 */
4181 if (!kmem_cache_has_cpu_partial(s))
b47291ef 4182 nr_objects = 0;
e6d0e1dc 4183 else if (s->size >= PAGE_SIZE)
b47291ef 4184 nr_objects = 6;
e6d0e1dc 4185 else if (s->size >= 1024)
23e98ad1 4186 nr_objects = 24;
e6d0e1dc 4187 else if (s->size >= 256)
23e98ad1 4188 nr_objects = 52;
e6d0e1dc 4189 else
23e98ad1 4190 nr_objects = 120;
b47291ef
VB
4191
4192 slub_set_cpu_partial(s, nr_objects);
e6d0e1dc
WY
4193#endif
4194}
4195
81819f0f
CL
4196/*
4197 * calculate_sizes() determines the order and the distribution of data within
4198 * a slab object.
4199 */
ae44d81d 4200static int calculate_sizes(struct kmem_cache *s)
81819f0f 4201{
d50112ed 4202 slab_flags_t flags = s->flags;
be4a7988 4203 unsigned int size = s->object_size;
19af27af 4204 unsigned int order;
81819f0f 4205
d8b42bf5
CL
4206 /*
4207 * Round up object size to the next word boundary. We can only
4208 * place the free pointer at word boundaries and this determines
4209 * the possible location of the free pointer.
4210 */
4211 size = ALIGN(size, sizeof(void *));
4212
4213#ifdef CONFIG_SLUB_DEBUG
81819f0f
CL
4214 /*
4215 * Determine if we can poison the object itself. If the user of
4216 * the slab may touch the object after free or before allocation
4217 * then we should never poison the object itself.
4218 */
5f0d5a3a 4219 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
c59def9f 4220 !s->ctor)
81819f0f
CL
4221 s->flags |= __OBJECT_POISON;
4222 else
4223 s->flags &= ~__OBJECT_POISON;
4224
81819f0f
CL
4225
4226 /*
672bba3a 4227 * If we are Redzoning then check if there is some space between the
81819f0f 4228 * end of the object and the free pointer. If not then add an
672bba3a 4229 * additional word to have some bytes to store Redzone information.
81819f0f 4230 */
3b0efdfa 4231 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
81819f0f 4232 size += sizeof(void *);
41ecc55b 4233#endif
81819f0f
CL
4234
4235 /*
672bba3a 4236 * With that we have determined the number of bytes in actual use
e41a49fa 4237 * by the object and redzoning.
81819f0f
CL
4238 */
4239 s->inuse = size;
4240
946fa0db
FT
4241 if (slub_debug_orig_size(s) ||
4242 (flags & (SLAB_TYPESAFE_BY_RCU | SLAB_POISON)) ||
74c1d3e0
KC
4243 ((flags & SLAB_RED_ZONE) && s->object_size < sizeof(void *)) ||
4244 s->ctor) {
81819f0f
CL
4245 /*
4246 * Relocate free pointer after the object if it is not
4247 * permitted to overwrite the first word of the object on
4248 * kmem_cache_free.
4249 *
4250 * This is the case if we do RCU, have a constructor or
74c1d3e0
KC
4251 * destructor, are poisoning the objects, or are
4252 * redzoning an object smaller than sizeof(void *).
cbfc35a4
WL
4253 *
4254 * The assumption that s->offset >= s->inuse means free
4255 * pointer is outside of the object is used in the
4256 * freeptr_outside_object() function. If that is no
4257 * longer true, the function needs to be modified.
81819f0f
CL
4258 */
4259 s->offset = size;
4260 size += sizeof(void *);
e41a49fa 4261 } else {
3202fa62
KC
4262 /*
4263 * Store freelist pointer near middle of object to keep
4264 * it away from the edges of the object to avoid small
4265 * sized over/underflows from neighboring allocations.
4266 */
e41a49fa 4267 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
81819f0f
CL
4268 }
4269
c12b3c62 4270#ifdef CONFIG_SLUB_DEBUG
6edf2576 4271 if (flags & SLAB_STORE_USER) {
81819f0f
CL
4272 /*
4273 * Need to store information about allocs and frees after
4274 * the object.
4275 */
4276 size += 2 * sizeof(struct track);
6edf2576
FT
4277
4278 /* Save the original kmalloc request size */
4279 if (flags & SLAB_KMALLOC)
4280 size += sizeof(unsigned int);
4281 }
80a9201a 4282#endif
81819f0f 4283
80a9201a
AP
4284 kasan_cache_create(s, &size, &s->flags);
4285#ifdef CONFIG_SLUB_DEBUG
d86bd1be 4286 if (flags & SLAB_RED_ZONE) {
81819f0f
CL
4287 /*
4288 * Add some empty padding so that we can catch
4289 * overwrites from earlier objects rather than let
4290 * tracking information or the free pointer be
0211a9c8 4291 * corrupted if a user writes before the start
81819f0f
CL
4292 * of the object.
4293 */
4294 size += sizeof(void *);
d86bd1be
JK
4295
4296 s->red_left_pad = sizeof(void *);
4297 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
4298 size += s->red_left_pad;
4299 }
41ecc55b 4300#endif
672bba3a 4301
81819f0f
CL
4302 /*
4303 * SLUB stores one object immediately after another beginning from
4304 * offset 0. In order to align the objects we have to simply size
4305 * each object to conform to the alignment.
4306 */
45906855 4307 size = ALIGN(size, s->align);
81819f0f 4308 s->size = size;
4138fdfc 4309 s->reciprocal_size = reciprocal_value(size);
ae44d81d 4310 order = calculate_order(size);
81819f0f 4311
19af27af 4312 if ((int)order < 0)
81819f0f
CL
4313 return 0;
4314
b7a49f0d 4315 s->allocflags = 0;
834f3d11 4316 if (order)
b7a49f0d
CL
4317 s->allocflags |= __GFP_COMP;
4318
4319 if (s->flags & SLAB_CACHE_DMA)
2c59dd65 4320 s->allocflags |= GFP_DMA;
b7a49f0d 4321
6d6ea1e9
NB
4322 if (s->flags & SLAB_CACHE_DMA32)
4323 s->allocflags |= GFP_DMA32;
4324
b7a49f0d
CL
4325 if (s->flags & SLAB_RECLAIM_ACCOUNT)
4326 s->allocflags |= __GFP_RECLAIMABLE;
4327
81819f0f
CL
4328 /*
4329 * Determine the number of objects per slab
4330 */
9736d2a9
MW
4331 s->oo = oo_make(order, size);
4332 s->min = oo_make(get_order(size), size);
81819f0f 4333
834f3d11 4334 return !!oo_objects(s->oo);
81819f0f
CL
4335}
4336
d50112ed 4337static int kmem_cache_open(struct kmem_cache *s, slab_flags_t flags)
81819f0f 4338{
37540008 4339 s->flags = kmem_cache_flags(s->size, flags, s->name);
2482ddec
KC
4340#ifdef CONFIG_SLAB_FREELIST_HARDENED
4341 s->random = get_random_long();
4342#endif
81819f0f 4343
ae44d81d 4344 if (!calculate_sizes(s))
81819f0f 4345 goto error;
3de47213
DR
4346 if (disable_higher_order_debug) {
4347 /*
4348 * Disable debugging flags that store metadata if the min slab
4349 * order increased.
4350 */
3b0efdfa 4351 if (get_order(s->size) > get_order(s->object_size)) {
3de47213
DR
4352 s->flags &= ~DEBUG_METADATA_FLAGS;
4353 s->offset = 0;
ae44d81d 4354 if (!calculate_sizes(s))
3de47213
DR
4355 goto error;
4356 }
4357 }
81819f0f 4358
2565409f
HC
4359#if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
4360 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
149daaf3 4361 if (system_has_cmpxchg_double() && (s->flags & SLAB_NO_CMPXCHG) == 0)
b789ef51
CL
4362 /* Enable fast mode */
4363 s->flags |= __CMPXCHG_DOUBLE;
4364#endif
4365
3b89d7d8 4366 /*
c2092c12 4367 * The larger the object size is, the more slabs we want on the partial
3b89d7d8
DR
4368 * list to avoid pounding the page allocator excessively.
4369 */
5182f3c9
HY
4370 s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
4371 s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
49e22585 4372
e6d0e1dc 4373 set_cpu_partial(s);
49e22585 4374
81819f0f 4375#ifdef CONFIG_NUMA
e2cb96b7 4376 s->remote_node_defrag_ratio = 1000;
81819f0f 4377#endif
210e7a43
TG
4378
4379 /* Initialize the pre-computed randomized freelist if slab is up */
4380 if (slab_state >= UP) {
4381 if (init_cache_random_seq(s))
4382 goto error;
4383 }
4384
55136592 4385 if (!init_kmem_cache_nodes(s))
dfb4f096 4386 goto error;
81819f0f 4387
55136592 4388 if (alloc_kmem_cache_cpus(s))
278b1bb1 4389 return 0;
ff12059e 4390
81819f0f 4391error:
9037c576 4392 __kmem_cache_release(s);
278b1bb1 4393 return -EINVAL;
81819f0f 4394}
81819f0f 4395
bb192ed9 4396static void list_slab_objects(struct kmem_cache *s, struct slab *slab,
55860d96 4397 const char *text)
33b12c38
CL
4398{
4399#ifdef CONFIG_SLUB_DEBUG
bb192ed9 4400 void *addr = slab_address(slab);
33b12c38 4401 void *p;
aa456c7a 4402
bb192ed9 4403 slab_err(s, slab, text, s->name);
33b12c38 4404
4ef3f5a3
VB
4405 spin_lock(&object_map_lock);
4406 __fill_map(object_map, s, slab);
4407
bb192ed9 4408 for_each_object(p, s, addr, slab->objects) {
33b12c38 4409
4ef3f5a3 4410 if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
96b94abc 4411 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
33b12c38
CL
4412 print_tracking(s, p);
4413 }
4414 }
4ef3f5a3 4415 spin_unlock(&object_map_lock);
33b12c38
CL
4416#endif
4417}
4418
81819f0f 4419/*
599870b1 4420 * Attempt to free all partial slabs on a node.
52b4b950
DS
4421 * This is called from __kmem_cache_shutdown(). We must take list_lock
4422 * because sysfs file might still access partial list after the shutdowning.
81819f0f 4423 */
599870b1 4424static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
81819f0f 4425{
60398923 4426 LIST_HEAD(discard);
bb192ed9 4427 struct slab *slab, *h;
81819f0f 4428
52b4b950
DS
4429 BUG_ON(irqs_disabled());
4430 spin_lock_irq(&n->list_lock);
bb192ed9
VB
4431 list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
4432 if (!slab->inuse) {
4433 remove_partial(n, slab);
4434 list_add(&slab->slab_list, &discard);
33b12c38 4435 } else {
bb192ed9 4436 list_slab_objects(s, slab,
55860d96 4437 "Objects remaining in %s on __kmem_cache_shutdown()");
599870b1 4438 }
33b12c38 4439 }
52b4b950 4440 spin_unlock_irq(&n->list_lock);
60398923 4441
bb192ed9
VB
4442 list_for_each_entry_safe(slab, h, &discard, slab_list)
4443 discard_slab(s, slab);
81819f0f
CL
4444}
4445
f9e13c0a
SB
4446bool __kmem_cache_empty(struct kmem_cache *s)
4447{
4448 int node;
4449 struct kmem_cache_node *n;
4450
4451 for_each_kmem_cache_node(s, node, n)
4452 if (n->nr_partial || slabs_node(s, node))
4453 return false;
4454 return true;
4455}
4456
81819f0f 4457/*
672bba3a 4458 * Release all resources used by a slab cache.
81819f0f 4459 */
52b4b950 4460int __kmem_cache_shutdown(struct kmem_cache *s)
81819f0f
CL
4461{
4462 int node;
fa45dc25 4463 struct kmem_cache_node *n;
81819f0f 4464
5a836bf6 4465 flush_all_cpus_locked(s);
81819f0f 4466 /* Attempt to free all objects */
fa45dc25 4467 for_each_kmem_cache_node(s, node, n) {
599870b1
CL
4468 free_partial(s, n);
4469 if (n->nr_partial || slabs_node(s, node))
81819f0f
CL
4470 return 1;
4471 }
81819f0f
CL
4472 return 0;
4473}
4474
5bb1bb35 4475#ifdef CONFIG_PRINTK
2dfe63e6 4476void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
8e7f37f2
PM
4477{
4478 void *base;
4479 int __maybe_unused i;
4480 unsigned int objnr;
4481 void *objp;
4482 void *objp0;
7213230a 4483 struct kmem_cache *s = slab->slab_cache;
8e7f37f2
PM
4484 struct track __maybe_unused *trackp;
4485
4486 kpp->kp_ptr = object;
7213230a 4487 kpp->kp_slab = slab;
8e7f37f2 4488 kpp->kp_slab_cache = s;
7213230a 4489 base = slab_address(slab);
8e7f37f2
PM
4490 objp0 = kasan_reset_tag(object);
4491#ifdef CONFIG_SLUB_DEBUG
4492 objp = restore_red_left(s, objp0);
4493#else
4494 objp = objp0;
4495#endif
40f3bf0c 4496 objnr = obj_to_index(s, slab, objp);
8e7f37f2
PM
4497 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
4498 objp = base + s->size * objnr;
4499 kpp->kp_objp = objp;
7213230a
MWO
4500 if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
4501 || (objp - base) % s->size) ||
8e7f37f2
PM
4502 !(s->flags & SLAB_STORE_USER))
4503 return;
4504#ifdef CONFIG_SLUB_DEBUG
0cbc124b 4505 objp = fixup_red_left(s, objp);
8e7f37f2
PM
4506 trackp = get_track(s, objp, TRACK_ALLOC);
4507 kpp->kp_ret = (void *)trackp->addr;
5cf909c5
OG
4508#ifdef CONFIG_STACKDEPOT
4509 {
4510 depot_stack_handle_t handle;
4511 unsigned long *entries;
4512 unsigned int nr_entries;
78869146 4513
5cf909c5
OG
4514 handle = READ_ONCE(trackp->handle);
4515 if (handle) {
4516 nr_entries = stack_depot_fetch(handle, &entries);
4517 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
4518 kpp->kp_stack[i] = (void *)entries[i];
4519 }
78869146 4520
5cf909c5
OG
4521 trackp = get_track(s, objp, TRACK_FREE);
4522 handle = READ_ONCE(trackp->handle);
4523 if (handle) {
4524 nr_entries = stack_depot_fetch(handle, &entries);
4525 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
4526 kpp->kp_free_stack[i] = (void *)entries[i];
4527 }
e548eaa1 4528 }
8e7f37f2
PM
4529#endif
4530#endif
4531}
5bb1bb35 4532#endif
8e7f37f2 4533
81819f0f
CL
4534/********************************************************************
4535 * Kmalloc subsystem
4536 *******************************************************************/
4537
81819f0f
CL
4538static int __init setup_slub_min_order(char *str)
4539{
19af27af 4540 get_option(&str, (int *)&slub_min_order);
81819f0f
CL
4541
4542 return 1;
4543}
4544
4545__setup("slub_min_order=", setup_slub_min_order);
4546
4547static int __init setup_slub_max_order(char *str)
4548{
19af27af
AD
4549 get_option(&str, (int *)&slub_max_order);
4550 slub_max_order = min(slub_max_order, (unsigned int)MAX_ORDER - 1);
81819f0f
CL
4551
4552 return 1;
4553}
4554
4555__setup("slub_max_order=", setup_slub_max_order);
4556
4557static int __init setup_slub_min_objects(char *str)
4558{
19af27af 4559 get_option(&str, (int *)&slub_min_objects);
81819f0f
CL
4560
4561 return 1;
4562}
4563
4564__setup("slub_min_objects=", setup_slub_min_objects);
4565
ed18adc1
KC
4566#ifdef CONFIG_HARDENED_USERCOPY
4567/*
afcc90f8
KC
4568 * Rejects incorrectly sized objects and objects that are to be copied
4569 * to/from userspace but do not fall entirely within the containing slab
4570 * cache's usercopy region.
ed18adc1
KC
4571 *
4572 * Returns NULL if check passes, otherwise const char * to name of cache
4573 * to indicate an error.
4574 */
0b3eb091
MWO
4575void __check_heap_object(const void *ptr, unsigned long n,
4576 const struct slab *slab, bool to_user)
ed18adc1
KC
4577{
4578 struct kmem_cache *s;
44065b2e 4579 unsigned int offset;
b89fb5ef 4580 bool is_kfence = is_kfence_address(ptr);
ed18adc1 4581
96fedce2
AK
4582 ptr = kasan_reset_tag(ptr);
4583
ed18adc1 4584 /* Find object and usable object size. */
0b3eb091 4585 s = slab->slab_cache;
ed18adc1
KC
4586
4587 /* Reject impossible pointers. */
0b3eb091 4588 if (ptr < slab_address(slab))
f4e6e289
KC
4589 usercopy_abort("SLUB object not in SLUB page?!", NULL,
4590 to_user, 0, n);
ed18adc1
KC
4591
4592 /* Find offset within object. */
b89fb5ef
AP
4593 if (is_kfence)
4594 offset = ptr - kfence_object_start(ptr);
4595 else
0b3eb091 4596 offset = (ptr - slab_address(slab)) % s->size;
ed18adc1
KC
4597
4598 /* Adjust for redzone and reject if within the redzone. */
b89fb5ef 4599 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
ed18adc1 4600 if (offset < s->red_left_pad)
f4e6e289
KC
4601 usercopy_abort("SLUB object in left red zone",
4602 s->name, to_user, offset, n);
ed18adc1
KC
4603 offset -= s->red_left_pad;
4604 }
4605
afcc90f8
KC
4606 /* Allow address range falling entirely within usercopy region. */
4607 if (offset >= s->useroffset &&
4608 offset - s->useroffset <= s->usersize &&
4609 n <= s->useroffset - offset + s->usersize)
f4e6e289 4610 return;
ed18adc1 4611
f4e6e289 4612 usercopy_abort("SLUB object", s->name, to_user, offset, n);
ed18adc1
KC
4613}
4614#endif /* CONFIG_HARDENED_USERCOPY */
4615
832f37f5
VD
4616#define SHRINK_PROMOTE_MAX 32
4617
2086d26a 4618/*
832f37f5
VD
4619 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
4620 * up most to the head of the partial lists. New allocations will then
4621 * fill those up and thus they can be removed from the partial lists.
672bba3a
CL
4622 *
4623 * The slabs with the least items are placed last. This results in them
4624 * being allocated from last increasing the chance that the last objects
4625 * are freed in them.
2086d26a 4626 */
5a836bf6 4627static int __kmem_cache_do_shrink(struct kmem_cache *s)
2086d26a
CL
4628{
4629 int node;
4630 int i;
4631 struct kmem_cache_node *n;
bb192ed9
VB
4632 struct slab *slab;
4633 struct slab *t;
832f37f5
VD
4634 struct list_head discard;
4635 struct list_head promote[SHRINK_PROMOTE_MAX];
2086d26a 4636 unsigned long flags;
ce3712d7 4637 int ret = 0;
2086d26a 4638
fa45dc25 4639 for_each_kmem_cache_node(s, node, n) {
832f37f5
VD
4640 INIT_LIST_HEAD(&discard);
4641 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
4642 INIT_LIST_HEAD(promote + i);
2086d26a
CL
4643
4644 spin_lock_irqsave(&n->list_lock, flags);
4645
4646 /*
832f37f5 4647 * Build lists of slabs to discard or promote.
2086d26a 4648 *
672bba3a 4649 * Note that concurrent frees may occur while we hold the
c2092c12 4650 * list_lock. slab->inuse here is the upper limit.
2086d26a 4651 */
bb192ed9
VB
4652 list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
4653 int free = slab->objects - slab->inuse;
832f37f5 4654
c2092c12 4655 /* Do not reread slab->inuse */
832f37f5
VD
4656 barrier();
4657
4658 /* We do not keep full slabs on the list */
4659 BUG_ON(free <= 0);
4660
bb192ed9
VB
4661 if (free == slab->objects) {
4662 list_move(&slab->slab_list, &discard);
69cb8e6b 4663 n->nr_partial--;
c7323a5a 4664 dec_slabs_node(s, node, slab->objects);
832f37f5 4665 } else if (free <= SHRINK_PROMOTE_MAX)
bb192ed9 4666 list_move(&slab->slab_list, promote + free - 1);
2086d26a
CL
4667 }
4668
2086d26a 4669 /*
832f37f5
VD
4670 * Promote the slabs filled up most to the head of the
4671 * partial list.
2086d26a 4672 */
832f37f5
VD
4673 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
4674 list_splice(promote + i, &n->partial);
2086d26a 4675
2086d26a 4676 spin_unlock_irqrestore(&n->list_lock, flags);
69cb8e6b
CL
4677
4678 /* Release empty slabs */
bb192ed9 4679 list_for_each_entry_safe(slab, t, &discard, slab_list)
c7323a5a 4680 free_slab(s, slab);
ce3712d7
VD
4681
4682 if (slabs_node(s, node))
4683 ret = 1;
2086d26a
CL
4684 }
4685
ce3712d7 4686 return ret;
2086d26a 4687}
2086d26a 4688
5a836bf6
SAS
4689int __kmem_cache_shrink(struct kmem_cache *s)
4690{
4691 flush_all(s);
4692 return __kmem_cache_do_shrink(s);
4693}
4694
b9049e23
YG
4695static int slab_mem_going_offline_callback(void *arg)
4696{
4697 struct kmem_cache *s;
4698
18004c5d 4699 mutex_lock(&slab_mutex);
5a836bf6
SAS
4700 list_for_each_entry(s, &slab_caches, list) {
4701 flush_all_cpus_locked(s);
4702 __kmem_cache_do_shrink(s);
4703 }
18004c5d 4704 mutex_unlock(&slab_mutex);
b9049e23
YG
4705
4706 return 0;
4707}
4708
4709static void slab_mem_offline_callback(void *arg)
4710{
b9049e23
YG
4711 struct memory_notify *marg = arg;
4712 int offline_node;
4713
b9d5ab25 4714 offline_node = marg->status_change_nid_normal;
b9049e23
YG
4715
4716 /*
4717 * If the node still has available memory. we need kmem_cache_node
4718 * for it yet.
4719 */
4720 if (offline_node < 0)
4721 return;
4722
18004c5d 4723 mutex_lock(&slab_mutex);
7e1fa93d 4724 node_clear(offline_node, slab_nodes);
666716fd
VB
4725 /*
4726 * We no longer free kmem_cache_node structures here, as it would be
4727 * racy with all get_node() users, and infeasible to protect them with
4728 * slab_mutex.
4729 */
18004c5d 4730 mutex_unlock(&slab_mutex);
b9049e23
YG
4731}
4732
4733static int slab_mem_going_online_callback(void *arg)
4734{
4735 struct kmem_cache_node *n;
4736 struct kmem_cache *s;
4737 struct memory_notify *marg = arg;
b9d5ab25 4738 int nid = marg->status_change_nid_normal;
b9049e23
YG
4739 int ret = 0;
4740
4741 /*
4742 * If the node's memory is already available, then kmem_cache_node is
4743 * already created. Nothing to do.
4744 */
4745 if (nid < 0)
4746 return 0;
4747
4748 /*
0121c619 4749 * We are bringing a node online. No memory is available yet. We must
b9049e23
YG
4750 * allocate a kmem_cache_node structure in order to bring the node
4751 * online.
4752 */
18004c5d 4753 mutex_lock(&slab_mutex);
b9049e23 4754 list_for_each_entry(s, &slab_caches, list) {
666716fd
VB
4755 /*
4756 * The structure may already exist if the node was previously
4757 * onlined and offlined.
4758 */
4759 if (get_node(s, nid))
4760 continue;
b9049e23
YG
4761 /*
4762 * XXX: kmem_cache_alloc_node will fallback to other nodes
4763 * since memory is not yet available from the node that
4764 * is brought up.
4765 */
8de66a0c 4766 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
b9049e23
YG
4767 if (!n) {
4768 ret = -ENOMEM;
4769 goto out;
4770 }
4053497d 4771 init_kmem_cache_node(n);
b9049e23
YG
4772 s->node[nid] = n;
4773 }
7e1fa93d
VB
4774 /*
4775 * Any cache created after this point will also have kmem_cache_node
4776 * initialized for the new node.
4777 */
4778 node_set(nid, slab_nodes);
b9049e23 4779out:
18004c5d 4780 mutex_unlock(&slab_mutex);
b9049e23
YG
4781 return ret;
4782}
4783
4784static int slab_memory_callback(struct notifier_block *self,
4785 unsigned long action, void *arg)
4786{
4787 int ret = 0;
4788
4789 switch (action) {
4790 case MEM_GOING_ONLINE:
4791 ret = slab_mem_going_online_callback(arg);
4792 break;
4793 case MEM_GOING_OFFLINE:
4794 ret = slab_mem_going_offline_callback(arg);
4795 break;
4796 case MEM_OFFLINE:
4797 case MEM_CANCEL_ONLINE:
4798 slab_mem_offline_callback(arg);
4799 break;
4800 case MEM_ONLINE:
4801 case MEM_CANCEL_OFFLINE:
4802 break;
4803 }
dc19f9db
KH
4804 if (ret)
4805 ret = notifier_from_errno(ret);
4806 else
4807 ret = NOTIFY_OK;
b9049e23
YG
4808 return ret;
4809}
4810
3ac38faa
AM
4811static struct notifier_block slab_memory_callback_nb = {
4812 .notifier_call = slab_memory_callback,
4813 .priority = SLAB_CALLBACK_PRI,
4814};
b9049e23 4815
81819f0f
CL
4816/********************************************************************
4817 * Basic setup of slabs
4818 *******************************************************************/
4819
51df1142
CL
4820/*
4821 * Used for early kmem_cache structures that were allocated using
dffb4d60
CL
4822 * the page allocator. Allocate them properly then fix up the pointers
4823 * that may be pointing to the wrong kmem_cache structure.
51df1142
CL
4824 */
4825
dffb4d60 4826static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
51df1142
CL
4827{
4828 int node;
dffb4d60 4829 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
fa45dc25 4830 struct kmem_cache_node *n;
51df1142 4831
dffb4d60 4832 memcpy(s, static_cache, kmem_cache->object_size);
51df1142 4833
7d557b3c
GC
4834 /*
4835 * This runs very early, and only the boot processor is supposed to be
4836 * up. Even if it weren't true, IRQs are not up so we couldn't fire
4837 * IPIs around.
4838 */
4839 __flush_cpu_slab(s, smp_processor_id());
fa45dc25 4840 for_each_kmem_cache_node(s, node, n) {
bb192ed9 4841 struct slab *p;
51df1142 4842
916ac052 4843 list_for_each_entry(p, &n->partial, slab_list)
fa45dc25 4844 p->slab_cache = s;
51df1142 4845
607bf324 4846#ifdef CONFIG_SLUB_DEBUG
916ac052 4847 list_for_each_entry(p, &n->full, slab_list)
fa45dc25 4848 p->slab_cache = s;
51df1142 4849#endif
51df1142 4850 }
dffb4d60
CL
4851 list_add(&s->list, &slab_caches);
4852 return s;
51df1142
CL
4853}
4854
81819f0f
CL
4855void __init kmem_cache_init(void)
4856{
dffb4d60
CL
4857 static __initdata struct kmem_cache boot_kmem_cache,
4858 boot_kmem_cache_node;
7e1fa93d 4859 int node;
51df1142 4860
fc8d8620
SG
4861 if (debug_guardpage_minorder())
4862 slub_max_order = 0;
4863
79270291
SB
4864 /* Print slub debugging pointers without hashing */
4865 if (__slub_debug_enabled())
4866 no_hash_pointers_enable(NULL);
4867
dffb4d60
CL
4868 kmem_cache_node = &boot_kmem_cache_node;
4869 kmem_cache = &boot_kmem_cache;
51df1142 4870
7e1fa93d
VB
4871 /*
4872 * Initialize the nodemask for which we will allocate per node
4873 * structures. Here we don't need taking slab_mutex yet.
4874 */
4875 for_each_node_state(node, N_NORMAL_MEMORY)
4876 node_set(node, slab_nodes);
4877
dffb4d60 4878 create_boot_cache(kmem_cache_node, "kmem_cache_node",
8eb8284b 4879 sizeof(struct kmem_cache_node), SLAB_HWCACHE_ALIGN, 0, 0);
b9049e23 4880
3ac38faa 4881 register_hotmemory_notifier(&slab_memory_callback_nb);
81819f0f
CL
4882
4883 /* Able to allocate the per node structures */
4884 slab_state = PARTIAL;
4885
dffb4d60
CL
4886 create_boot_cache(kmem_cache, "kmem_cache",
4887 offsetof(struct kmem_cache, node) +
4888 nr_node_ids * sizeof(struct kmem_cache_node *),
8eb8284b 4889 SLAB_HWCACHE_ALIGN, 0, 0);
8a13a4cc 4890
dffb4d60 4891 kmem_cache = bootstrap(&boot_kmem_cache);
dffb4d60 4892 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
51df1142
CL
4893
4894 /* Now we can use the kmem_cache to allocate kmalloc slabs */
34cc6990 4895 setup_kmalloc_cache_index_table();
f97d5f63 4896 create_kmalloc_caches(0);
81819f0f 4897
210e7a43
TG
4898 /* Setup random freelists for each cache */
4899 init_freelist_randomization();
4900
a96a87bf
SAS
4901 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
4902 slub_cpu_dead);
81819f0f 4903
b9726c26 4904 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
f97d5f63 4905 cache_line_size(),
81819f0f
CL
4906 slub_min_order, slub_max_order, slub_min_objects,
4907 nr_cpu_ids, nr_node_ids);
4908}
4909
7e85ee0c
PE
4910void __init kmem_cache_init_late(void)
4911{
e45cc288
ML
4912 flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
4913 WARN_ON(!flushwq);
7e85ee0c
PE
4914}
4915
2633d7a0 4916struct kmem_cache *
f4957d5b 4917__kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
d50112ed 4918 slab_flags_t flags, void (*ctor)(void *))
81819f0f 4919{
10befea9 4920 struct kmem_cache *s;
81819f0f 4921
a44cb944 4922 s = find_mergeable(size, align, flags, name, ctor);
81819f0f 4923 if (s) {
efb93527
XS
4924 if (sysfs_slab_alias(s, name))
4925 return NULL;
4926
81819f0f 4927 s->refcount++;
84d0ddd6 4928
81819f0f
CL
4929 /*
4930 * Adjust the object sizes so that we clear
4931 * the complete object on kzalloc.
4932 */
1b473f29 4933 s->object_size = max(s->object_size, size);
52ee6d74 4934 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
a0e1d1be 4935 }
6446faa2 4936
cbb79694
CL
4937 return s;
4938}
84c1cf62 4939
d50112ed 4940int __kmem_cache_create(struct kmem_cache *s, slab_flags_t flags)
cbb79694 4941{
aac3a166
PE
4942 int err;
4943
4944 err = kmem_cache_open(s, flags);
4945 if (err)
4946 return err;
20cea968 4947
45530c44
CL
4948 /* Mutex is not taken during early boot */
4949 if (slab_state <= UP)
4950 return 0;
4951
aac3a166 4952 err = sysfs_slab_add(s);
67823a54 4953 if (err) {
52b4b950 4954 __kmem_cache_release(s);
67823a54
ML
4955 return err;
4956 }
20cea968 4957
64dd6849
FM
4958 if (s->flags & SLAB_STORE_USER)
4959 debugfs_slab_add(s);
4960
67823a54 4961 return 0;
81819f0f 4962}
81819f0f 4963
ab4d5ed5 4964#ifdef CONFIG_SYSFS
bb192ed9 4965static int count_inuse(struct slab *slab)
205ab99d 4966{
bb192ed9 4967 return slab->inuse;
205ab99d
CL
4968}
4969
bb192ed9 4970static int count_total(struct slab *slab)
205ab99d 4971{
bb192ed9 4972 return slab->objects;
205ab99d 4973}
ab4d5ed5 4974#endif
205ab99d 4975
ab4d5ed5 4976#ifdef CONFIG_SLUB_DEBUG
bb192ed9 4977static void validate_slab(struct kmem_cache *s, struct slab *slab,
0a19e7dd 4978 unsigned long *obj_map)
53e15af0
CL
4979{
4980 void *p;
bb192ed9 4981 void *addr = slab_address(slab);
53e15af0 4982
bb192ed9 4983 if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
41bec7c3 4984 return;
53e15af0
CL
4985
4986 /* Now we know that a valid freelist exists */
bb192ed9
VB
4987 __fill_map(obj_map, s, slab);
4988 for_each_object(p, s, addr, slab->objects) {
0a19e7dd 4989 u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
dd98afd4 4990 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
53e15af0 4991
bb192ed9 4992 if (!check_object(s, slab, p, val))
dd98afd4
YZ
4993 break;
4994 }
53e15af0
CL
4995}
4996
434e245d 4997static int validate_slab_node(struct kmem_cache *s,
0a19e7dd 4998 struct kmem_cache_node *n, unsigned long *obj_map)
53e15af0
CL
4999{
5000 unsigned long count = 0;
bb192ed9 5001 struct slab *slab;
53e15af0
CL
5002 unsigned long flags;
5003
5004 spin_lock_irqsave(&n->list_lock, flags);
5005
bb192ed9
VB
5006 list_for_each_entry(slab, &n->partial, slab_list) {
5007 validate_slab(s, slab, obj_map);
53e15af0
CL
5008 count++;
5009 }
1f9f78b1 5010 if (count != n->nr_partial) {
f9f58285
FF
5011 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
5012 s->name, count, n->nr_partial);
1f9f78b1
OG
5013 slab_add_kunit_errors();
5014 }
53e15af0
CL
5015
5016 if (!(s->flags & SLAB_STORE_USER))
5017 goto out;
5018
bb192ed9
VB
5019 list_for_each_entry(slab, &n->full, slab_list) {
5020 validate_slab(s, slab, obj_map);
53e15af0
CL
5021 count++;
5022 }
1f9f78b1 5023 if (count != atomic_long_read(&n->nr_slabs)) {
f9f58285
FF
5024 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
5025 s->name, count, atomic_long_read(&n->nr_slabs));
1f9f78b1
OG
5026 slab_add_kunit_errors();
5027 }
53e15af0
CL
5028
5029out:
5030 spin_unlock_irqrestore(&n->list_lock, flags);
5031 return count;
5032}
5033
1f9f78b1 5034long validate_slab_cache(struct kmem_cache *s)
53e15af0
CL
5035{
5036 int node;
5037 unsigned long count = 0;
fa45dc25 5038 struct kmem_cache_node *n;
0a19e7dd
VB
5039 unsigned long *obj_map;
5040
5041 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
5042 if (!obj_map)
5043 return -ENOMEM;
53e15af0
CL
5044
5045 flush_all(s);
fa45dc25 5046 for_each_kmem_cache_node(s, node, n)
0a19e7dd
VB
5047 count += validate_slab_node(s, n, obj_map);
5048
5049 bitmap_free(obj_map);
90e9f6a6 5050
53e15af0
CL
5051 return count;
5052}
1f9f78b1
OG
5053EXPORT_SYMBOL(validate_slab_cache);
5054
64dd6849 5055#ifdef CONFIG_DEBUG_FS
88a420e4 5056/*
672bba3a 5057 * Generate lists of code addresses where slabcache objects are allocated
88a420e4
CL
5058 * and freed.
5059 */
5060
5061struct location {
8ea9fb92 5062 depot_stack_handle_t handle;
88a420e4 5063 unsigned long count;
ce71e27c 5064 unsigned long addr;
6edf2576 5065 unsigned long waste;
45edfa58
CL
5066 long long sum_time;
5067 long min_time;
5068 long max_time;
5069 long min_pid;
5070 long max_pid;
174596a0 5071 DECLARE_BITMAP(cpus, NR_CPUS);
45edfa58 5072 nodemask_t nodes;
88a420e4
CL
5073};
5074
5075struct loc_track {
5076 unsigned long max;
5077 unsigned long count;
5078 struct location *loc;
005a79e5 5079 loff_t idx;
88a420e4
CL
5080};
5081
64dd6849
FM
5082static struct dentry *slab_debugfs_root;
5083
88a420e4
CL
5084static void free_loc_track(struct loc_track *t)
5085{
5086 if (t->max)
5087 free_pages((unsigned long)t->loc,
5088 get_order(sizeof(struct location) * t->max));
5089}
5090
68dff6a9 5091static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
88a420e4
CL
5092{
5093 struct location *l;
5094 int order;
5095
88a420e4
CL
5096 order = get_order(sizeof(struct location) * max);
5097
68dff6a9 5098 l = (void *)__get_free_pages(flags, order);
88a420e4
CL
5099 if (!l)
5100 return 0;
5101
5102 if (t->count) {
5103 memcpy(l, t->loc, sizeof(struct location) * t->count);
5104 free_loc_track(t);
5105 }
5106 t->max = max;
5107 t->loc = l;
5108 return 1;
5109}
5110
5111static int add_location(struct loc_track *t, struct kmem_cache *s,
6edf2576
FT
5112 const struct track *track,
5113 unsigned int orig_size)
88a420e4
CL
5114{
5115 long start, end, pos;
5116 struct location *l;
6edf2576 5117 unsigned long caddr, chandle, cwaste;
45edfa58 5118 unsigned long age = jiffies - track->when;
8ea9fb92 5119 depot_stack_handle_t handle = 0;
6edf2576 5120 unsigned int waste = s->object_size - orig_size;
88a420e4 5121
8ea9fb92
OG
5122#ifdef CONFIG_STACKDEPOT
5123 handle = READ_ONCE(track->handle);
5124#endif
88a420e4
CL
5125 start = -1;
5126 end = t->count;
5127
5128 for ( ; ; ) {
5129 pos = start + (end - start + 1) / 2;
5130
5131 /*
5132 * There is nothing at "end". If we end up there
5133 * we need to add something to before end.
5134 */
5135 if (pos == end)
5136 break;
5137
6edf2576
FT
5138 l = &t->loc[pos];
5139 caddr = l->addr;
5140 chandle = l->handle;
5141 cwaste = l->waste;
5142 if ((track->addr == caddr) && (handle == chandle) &&
5143 (waste == cwaste)) {
45edfa58 5144
45edfa58
CL
5145 l->count++;
5146 if (track->when) {
5147 l->sum_time += age;
5148 if (age < l->min_time)
5149 l->min_time = age;
5150 if (age > l->max_time)
5151 l->max_time = age;
5152
5153 if (track->pid < l->min_pid)
5154 l->min_pid = track->pid;
5155 if (track->pid > l->max_pid)
5156 l->max_pid = track->pid;
5157
174596a0
RR
5158 cpumask_set_cpu(track->cpu,
5159 to_cpumask(l->cpus));
45edfa58
CL
5160 }
5161 node_set(page_to_nid(virt_to_page(track)), l->nodes);
88a420e4
CL
5162 return 1;
5163 }
5164
45edfa58 5165 if (track->addr < caddr)
88a420e4 5166 end = pos;
8ea9fb92
OG
5167 else if (track->addr == caddr && handle < chandle)
5168 end = pos;
6edf2576
FT
5169 else if (track->addr == caddr && handle == chandle &&
5170 waste < cwaste)
5171 end = pos;
88a420e4
CL
5172 else
5173 start = pos;
5174 }
5175
5176 /*
672bba3a 5177 * Not found. Insert new tracking element.
88a420e4 5178 */
68dff6a9 5179 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
88a420e4
CL
5180 return 0;
5181
5182 l = t->loc + pos;
5183 if (pos < t->count)
5184 memmove(l + 1, l,
5185 (t->count - pos) * sizeof(struct location));
5186 t->count++;
5187 l->count = 1;
45edfa58
CL
5188 l->addr = track->addr;
5189 l->sum_time = age;
5190 l->min_time = age;
5191 l->max_time = age;
5192 l->min_pid = track->pid;
5193 l->max_pid = track->pid;
8ea9fb92 5194 l->handle = handle;
6edf2576 5195 l->waste = waste;
174596a0
RR
5196 cpumask_clear(to_cpumask(l->cpus));
5197 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
45edfa58
CL
5198 nodes_clear(l->nodes);
5199 node_set(page_to_nid(virt_to_page(track)), l->nodes);
88a420e4
CL
5200 return 1;
5201}
5202
5203static void process_slab(struct loc_track *t, struct kmem_cache *s,
bb192ed9 5204 struct slab *slab, enum track_item alloc,
b3fd64e1 5205 unsigned long *obj_map)
88a420e4 5206{
bb192ed9 5207 void *addr = slab_address(slab);
6edf2576 5208 bool is_alloc = (alloc == TRACK_ALLOC);
88a420e4
CL
5209 void *p;
5210
bb192ed9 5211 __fill_map(obj_map, s, slab);
b3fd64e1 5212
bb192ed9 5213 for_each_object(p, s, addr, slab->objects)
b3fd64e1 5214 if (!test_bit(__obj_to_index(s, addr, p), obj_map))
6edf2576
FT
5215 add_location(t, s, get_track(s, p, alloc),
5216 is_alloc ? get_orig_size(s, p) :
5217 s->object_size);
88a420e4 5218}
64dd6849 5219#endif /* CONFIG_DEBUG_FS */
6dfd1b65 5220#endif /* CONFIG_SLUB_DEBUG */
88a420e4 5221
ab4d5ed5 5222#ifdef CONFIG_SYSFS
81819f0f 5223enum slab_stat_type {
205ab99d
CL
5224 SL_ALL, /* All slabs */
5225 SL_PARTIAL, /* Only partially allocated slabs */
5226 SL_CPU, /* Only slabs used for cpu caches */
5227 SL_OBJECTS, /* Determine allocated objects not slabs */
5228 SL_TOTAL /* Determine object capacity not slabs */
81819f0f
CL
5229};
5230
205ab99d 5231#define SO_ALL (1 << SL_ALL)
81819f0f
CL
5232#define SO_PARTIAL (1 << SL_PARTIAL)
5233#define SO_CPU (1 << SL_CPU)
5234#define SO_OBJECTS (1 << SL_OBJECTS)
205ab99d 5235#define SO_TOTAL (1 << SL_TOTAL)
81819f0f 5236
62e5c4b4 5237static ssize_t show_slab_objects(struct kmem_cache *s,
bf16d19a 5238 char *buf, unsigned long flags)
81819f0f
CL
5239{
5240 unsigned long total = 0;
81819f0f
CL
5241 int node;
5242 int x;
5243 unsigned long *nodes;
bf16d19a 5244 int len = 0;
81819f0f 5245
6396bb22 5246 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
62e5c4b4
CG
5247 if (!nodes)
5248 return -ENOMEM;
81819f0f 5249
205ab99d
CL
5250 if (flags & SO_CPU) {
5251 int cpu;
81819f0f 5252
205ab99d 5253 for_each_possible_cpu(cpu) {
d0e0ac97
CG
5254 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
5255 cpu);
ec3ab083 5256 int node;
bb192ed9 5257 struct slab *slab;
dfb4f096 5258
bb192ed9
VB
5259 slab = READ_ONCE(c->slab);
5260 if (!slab)
ec3ab083 5261 continue;
205ab99d 5262
bb192ed9 5263 node = slab_nid(slab);
ec3ab083 5264 if (flags & SO_TOTAL)
bb192ed9 5265 x = slab->objects;
ec3ab083 5266 else if (flags & SO_OBJECTS)
bb192ed9 5267 x = slab->inuse;
ec3ab083
CL
5268 else
5269 x = 1;
49e22585 5270
ec3ab083
CL
5271 total += x;
5272 nodes[node] += x;
5273
9c01e9af 5274#ifdef CONFIG_SLUB_CPU_PARTIAL
bb192ed9
VB
5275 slab = slub_percpu_partial_read_once(c);
5276 if (slab) {
5277 node = slab_nid(slab);
8afb1474
LZ
5278 if (flags & SO_TOTAL)
5279 WARN_ON_ONCE(1);
5280 else if (flags & SO_OBJECTS)
5281 WARN_ON_ONCE(1);
5282 else
bb192ed9 5283 x = slab->slabs;
bc6697d8
ED
5284 total += x;
5285 nodes[node] += x;
49e22585 5286 }
9c01e9af 5287#endif
81819f0f
CL
5288 }
5289 }
5290
e4f8e513
QC
5291 /*
5292 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
5293 * already held which will conflict with an existing lock order:
5294 *
5295 * mem_hotplug_lock->slab_mutex->kernfs_mutex
5296 *
5297 * We don't really need mem_hotplug_lock (to hold off
5298 * slab_mem_going_offline_callback) here because slab's memory hot
5299 * unplug code doesn't destroy the kmem_cache->node[] data.
5300 */
5301
ab4d5ed5 5302#ifdef CONFIG_SLUB_DEBUG
205ab99d 5303 if (flags & SO_ALL) {
fa45dc25
CL
5304 struct kmem_cache_node *n;
5305
5306 for_each_kmem_cache_node(s, node, n) {
205ab99d 5307
d0e0ac97
CG
5308 if (flags & SO_TOTAL)
5309 x = atomic_long_read(&n->total_objects);
5310 else if (flags & SO_OBJECTS)
5311 x = atomic_long_read(&n->total_objects) -
5312 count_partial(n, count_free);
81819f0f 5313 else
205ab99d 5314 x = atomic_long_read(&n->nr_slabs);
81819f0f
CL
5315 total += x;
5316 nodes[node] += x;
5317 }
5318
ab4d5ed5
CL
5319 } else
5320#endif
5321 if (flags & SO_PARTIAL) {
fa45dc25 5322 struct kmem_cache_node *n;
81819f0f 5323
fa45dc25 5324 for_each_kmem_cache_node(s, node, n) {
205ab99d
CL
5325 if (flags & SO_TOTAL)
5326 x = count_partial(n, count_total);
5327 else if (flags & SO_OBJECTS)
5328 x = count_partial(n, count_inuse);
81819f0f 5329 else
205ab99d 5330 x = n->nr_partial;
81819f0f
CL
5331 total += x;
5332 nodes[node] += x;
5333 }
5334 }
bf16d19a
JP
5335
5336 len += sysfs_emit_at(buf, len, "%lu", total);
81819f0f 5337#ifdef CONFIG_NUMA
bf16d19a 5338 for (node = 0; node < nr_node_ids; node++) {
81819f0f 5339 if (nodes[node])
bf16d19a
JP
5340 len += sysfs_emit_at(buf, len, " N%d=%lu",
5341 node, nodes[node]);
5342 }
81819f0f 5343#endif
bf16d19a 5344 len += sysfs_emit_at(buf, len, "\n");
81819f0f 5345 kfree(nodes);
bf16d19a
JP
5346
5347 return len;
81819f0f
CL
5348}
5349
81819f0f 5350#define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
497888cf 5351#define to_slab(n) container_of(n, struct kmem_cache, kobj)
81819f0f
CL
5352
5353struct slab_attribute {
5354 struct attribute attr;
5355 ssize_t (*show)(struct kmem_cache *s, char *buf);
5356 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
5357};
5358
5359#define SLAB_ATTR_RO(_name) \
d1d28bd9 5360 static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
81819f0f
CL
5361
5362#define SLAB_ATTR(_name) \
d1d28bd9 5363 static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
81819f0f 5364
81819f0f
CL
5365static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
5366{
bf16d19a 5367 return sysfs_emit(buf, "%u\n", s->size);
81819f0f
CL
5368}
5369SLAB_ATTR_RO(slab_size);
5370
5371static ssize_t align_show(struct kmem_cache *s, char *buf)
5372{
bf16d19a 5373 return sysfs_emit(buf, "%u\n", s->align);
81819f0f
CL
5374}
5375SLAB_ATTR_RO(align);
5376
5377static ssize_t object_size_show(struct kmem_cache *s, char *buf)
5378{
bf16d19a 5379 return sysfs_emit(buf, "%u\n", s->object_size);
81819f0f
CL
5380}
5381SLAB_ATTR_RO(object_size);
5382
5383static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
5384{
bf16d19a 5385 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
81819f0f
CL
5386}
5387SLAB_ATTR_RO(objs_per_slab);
5388
5389static ssize_t order_show(struct kmem_cache *s, char *buf)
5390{
bf16d19a 5391 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
81819f0f 5392}
32a6f409 5393SLAB_ATTR_RO(order);
81819f0f 5394
73d342b1
DR
5395static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
5396{
bf16d19a 5397 return sysfs_emit(buf, "%lu\n", s->min_partial);
73d342b1
DR
5398}
5399
5400static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
5401 size_t length)
5402{
5403 unsigned long min;
5404 int err;
5405
3dbb95f7 5406 err = kstrtoul(buf, 10, &min);
73d342b1
DR
5407 if (err)
5408 return err;
5409
5182f3c9 5410 s->min_partial = min;
73d342b1
DR
5411 return length;
5412}
5413SLAB_ATTR(min_partial);
5414
49e22585
CL
5415static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
5416{
b47291ef
VB
5417 unsigned int nr_partial = 0;
5418#ifdef CONFIG_SLUB_CPU_PARTIAL
5419 nr_partial = s->cpu_partial;
5420#endif
5421
5422 return sysfs_emit(buf, "%u\n", nr_partial);
49e22585
CL
5423}
5424
5425static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
5426 size_t length)
5427{
e5d9998f 5428 unsigned int objects;
49e22585
CL
5429 int err;
5430
e5d9998f 5431 err = kstrtouint(buf, 10, &objects);
49e22585
CL
5432 if (err)
5433 return err;
345c905d 5434 if (objects && !kmem_cache_has_cpu_partial(s))
74ee4ef1 5435 return -EINVAL;
49e22585 5436
e6d0e1dc 5437 slub_set_cpu_partial(s, objects);
49e22585
CL
5438 flush_all(s);
5439 return length;
5440}
5441SLAB_ATTR(cpu_partial);
5442
81819f0f
CL
5443static ssize_t ctor_show(struct kmem_cache *s, char *buf)
5444{
62c70bce
JP
5445 if (!s->ctor)
5446 return 0;
bf16d19a 5447 return sysfs_emit(buf, "%pS\n", s->ctor);
81819f0f
CL
5448}
5449SLAB_ATTR_RO(ctor);
5450
81819f0f
CL
5451static ssize_t aliases_show(struct kmem_cache *s, char *buf)
5452{
bf16d19a 5453 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
81819f0f
CL
5454}
5455SLAB_ATTR_RO(aliases);
5456
81819f0f
CL
5457static ssize_t partial_show(struct kmem_cache *s, char *buf)
5458{
d9acf4b7 5459 return show_slab_objects(s, buf, SO_PARTIAL);
81819f0f
CL
5460}
5461SLAB_ATTR_RO(partial);
5462
5463static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
5464{
d9acf4b7 5465 return show_slab_objects(s, buf, SO_CPU);
81819f0f
CL
5466}
5467SLAB_ATTR_RO(cpu_slabs);
5468
5469static ssize_t objects_show(struct kmem_cache *s, char *buf)
5470{
205ab99d 5471 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
81819f0f
CL
5472}
5473SLAB_ATTR_RO(objects);
5474
205ab99d
CL
5475static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
5476{
5477 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
5478}
5479SLAB_ATTR_RO(objects_partial);
5480
49e22585
CL
5481static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
5482{
5483 int objects = 0;
bb192ed9 5484 int slabs = 0;
9c01e9af 5485 int cpu __maybe_unused;
bf16d19a 5486 int len = 0;
49e22585 5487
9c01e9af 5488#ifdef CONFIG_SLUB_CPU_PARTIAL
49e22585 5489 for_each_online_cpu(cpu) {
bb192ed9 5490 struct slab *slab;
a93cf07b 5491
bb192ed9 5492 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
49e22585 5493
bb192ed9
VB
5494 if (slab)
5495 slabs += slab->slabs;
49e22585 5496 }
9c01e9af 5497#endif
49e22585 5498
c2092c12 5499 /* Approximate half-full slabs, see slub_set_cpu_partial() */
bb192ed9
VB
5500 objects = (slabs * oo_objects(s->oo)) / 2;
5501 len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
49e22585 5502
9c01e9af 5503#if defined(CONFIG_SLUB_CPU_PARTIAL) && defined(CONFIG_SMP)
49e22585 5504 for_each_online_cpu(cpu) {
bb192ed9 5505 struct slab *slab;
a93cf07b 5506
bb192ed9
VB
5507 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
5508 if (slab) {
5509 slabs = READ_ONCE(slab->slabs);
5510 objects = (slabs * oo_objects(s->oo)) / 2;
bf16d19a 5511 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
bb192ed9 5512 cpu, objects, slabs);
b47291ef 5513 }
49e22585
CL
5514 }
5515#endif
bf16d19a
JP
5516 len += sysfs_emit_at(buf, len, "\n");
5517
5518 return len;
49e22585
CL
5519}
5520SLAB_ATTR_RO(slabs_cpu_partial);
5521
a5a84755
CL
5522static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
5523{
bf16d19a 5524 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
a5a84755 5525}
8f58119a 5526SLAB_ATTR_RO(reclaim_account);
a5a84755
CL
5527
5528static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
5529{
bf16d19a 5530 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
a5a84755
CL
5531}
5532SLAB_ATTR_RO(hwcache_align);
5533
5534#ifdef CONFIG_ZONE_DMA
5535static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
5536{
bf16d19a 5537 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
a5a84755
CL
5538}
5539SLAB_ATTR_RO(cache_dma);
5540#endif
5541
8eb8284b
DW
5542static ssize_t usersize_show(struct kmem_cache *s, char *buf)
5543{
bf16d19a 5544 return sysfs_emit(buf, "%u\n", s->usersize);
8eb8284b
DW
5545}
5546SLAB_ATTR_RO(usersize);
5547
a5a84755
CL
5548static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
5549{
bf16d19a 5550 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
a5a84755
CL
5551}
5552SLAB_ATTR_RO(destroy_by_rcu);
5553
ab4d5ed5 5554#ifdef CONFIG_SLUB_DEBUG
a5a84755
CL
5555static ssize_t slabs_show(struct kmem_cache *s, char *buf)
5556{
5557 return show_slab_objects(s, buf, SO_ALL);
5558}
5559SLAB_ATTR_RO(slabs);
5560
205ab99d
CL
5561static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
5562{
5563 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
5564}
5565SLAB_ATTR_RO(total_objects);
5566
81819f0f
CL
5567static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
5568{
bf16d19a 5569 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
81819f0f 5570}
060807f8 5571SLAB_ATTR_RO(sanity_checks);
81819f0f
CL
5572
5573static ssize_t trace_show(struct kmem_cache *s, char *buf)
5574{
bf16d19a 5575 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
81819f0f 5576}
060807f8 5577SLAB_ATTR_RO(trace);
81819f0f 5578
81819f0f
CL
5579static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
5580{
bf16d19a 5581 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
81819f0f
CL
5582}
5583
ad38b5b1 5584SLAB_ATTR_RO(red_zone);
81819f0f
CL
5585
5586static ssize_t poison_show(struct kmem_cache *s, char *buf)
5587{
bf16d19a 5588 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
81819f0f
CL
5589}
5590
ad38b5b1 5591SLAB_ATTR_RO(poison);
81819f0f
CL
5592
5593static ssize_t store_user_show(struct kmem_cache *s, char *buf)
5594{
bf16d19a 5595 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
81819f0f
CL
5596}
5597
ad38b5b1 5598SLAB_ATTR_RO(store_user);
81819f0f 5599
53e15af0
CL
5600static ssize_t validate_show(struct kmem_cache *s, char *buf)
5601{
5602 return 0;
5603}
5604
5605static ssize_t validate_store(struct kmem_cache *s,
5606 const char *buf, size_t length)
5607{
434e245d
CL
5608 int ret = -EINVAL;
5609
c7323a5a 5610 if (buf[0] == '1' && kmem_cache_debug(s)) {
434e245d
CL
5611 ret = validate_slab_cache(s);
5612 if (ret >= 0)
5613 ret = length;
5614 }
5615 return ret;
53e15af0
CL
5616}
5617SLAB_ATTR(validate);
a5a84755 5618
a5a84755
CL
5619#endif /* CONFIG_SLUB_DEBUG */
5620
5621#ifdef CONFIG_FAILSLAB
5622static ssize_t failslab_show(struct kmem_cache *s, char *buf)
5623{
bf16d19a 5624 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
a5a84755 5625}
7c82b3b3
AA
5626
5627static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
5628 size_t length)
5629{
5630 if (s->refcount > 1)
5631 return -EINVAL;
5632
5633 if (buf[0] == '1')
5634 WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
5635 else
5636 WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
5637
5638 return length;
5639}
5640SLAB_ATTR(failslab);
ab4d5ed5 5641#endif
53e15af0 5642
2086d26a
CL
5643static ssize_t shrink_show(struct kmem_cache *s, char *buf)
5644{
5645 return 0;
5646}
5647
5648static ssize_t shrink_store(struct kmem_cache *s,
5649 const char *buf, size_t length)
5650{
832f37f5 5651 if (buf[0] == '1')
10befea9 5652 kmem_cache_shrink(s);
832f37f5 5653 else
2086d26a
CL
5654 return -EINVAL;
5655 return length;
5656}
5657SLAB_ATTR(shrink);
5658
81819f0f 5659#ifdef CONFIG_NUMA
9824601e 5660static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
81819f0f 5661{
bf16d19a 5662 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
81819f0f
CL
5663}
5664
9824601e 5665static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
81819f0f
CL
5666 const char *buf, size_t length)
5667{
eb7235eb 5668 unsigned int ratio;
0121c619
CL
5669 int err;
5670
eb7235eb 5671 err = kstrtouint(buf, 10, &ratio);
0121c619
CL
5672 if (err)
5673 return err;
eb7235eb
AD
5674 if (ratio > 100)
5675 return -ERANGE;
0121c619 5676
eb7235eb 5677 s->remote_node_defrag_ratio = ratio * 10;
81819f0f 5678
81819f0f
CL
5679 return length;
5680}
9824601e 5681SLAB_ATTR(remote_node_defrag_ratio);
81819f0f
CL
5682#endif
5683
8ff12cfc 5684#ifdef CONFIG_SLUB_STATS
8ff12cfc
CL
5685static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
5686{
5687 unsigned long sum = 0;
5688 int cpu;
bf16d19a 5689 int len = 0;
6da2ec56 5690 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
8ff12cfc
CL
5691
5692 if (!data)
5693 return -ENOMEM;
5694
5695 for_each_online_cpu(cpu) {
9dfc6e68 5696 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
8ff12cfc
CL
5697
5698 data[cpu] = x;
5699 sum += x;
5700 }
5701
bf16d19a 5702 len += sysfs_emit_at(buf, len, "%lu", sum);
8ff12cfc 5703
50ef37b9 5704#ifdef CONFIG_SMP
8ff12cfc 5705 for_each_online_cpu(cpu) {
bf16d19a
JP
5706 if (data[cpu])
5707 len += sysfs_emit_at(buf, len, " C%d=%u",
5708 cpu, data[cpu]);
8ff12cfc 5709 }
50ef37b9 5710#endif
8ff12cfc 5711 kfree(data);
bf16d19a
JP
5712 len += sysfs_emit_at(buf, len, "\n");
5713
5714 return len;
8ff12cfc
CL
5715}
5716
78eb00cc
DR
5717static void clear_stat(struct kmem_cache *s, enum stat_item si)
5718{
5719 int cpu;
5720
5721 for_each_online_cpu(cpu)
9dfc6e68 5722 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
78eb00cc
DR
5723}
5724
8ff12cfc
CL
5725#define STAT_ATTR(si, text) \
5726static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5727{ \
5728 return show_stat(s, buf, si); \
5729} \
78eb00cc
DR
5730static ssize_t text##_store(struct kmem_cache *s, \
5731 const char *buf, size_t length) \
5732{ \
5733 if (buf[0] != '0') \
5734 return -EINVAL; \
5735 clear_stat(s, si); \
5736 return length; \
5737} \
5738SLAB_ATTR(text); \
8ff12cfc
CL
5739
5740STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5741STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5742STAT_ATTR(FREE_FASTPATH, free_fastpath);
5743STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5744STAT_ATTR(FREE_FROZEN, free_frozen);
5745STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5746STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5747STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5748STAT_ATTR(ALLOC_SLAB, alloc_slab);
5749STAT_ATTR(ALLOC_REFILL, alloc_refill);
e36a2652 5750STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
8ff12cfc
CL
5751STAT_ATTR(FREE_SLAB, free_slab);
5752STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5753STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5754STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5755STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5756STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5757STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
03e404af 5758STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
65c3376a 5759STAT_ATTR(ORDER_FALLBACK, order_fallback);
b789ef51
CL
5760STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5761STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
49e22585
CL
5762STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5763STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
8028dcea
AS
5764STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5765STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
6dfd1b65 5766#endif /* CONFIG_SLUB_STATS */
8ff12cfc 5767
b84e04f1
IK
5768#ifdef CONFIG_KFENCE
5769static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
5770{
5771 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
5772}
5773
5774static ssize_t skip_kfence_store(struct kmem_cache *s,
5775 const char *buf, size_t length)
5776{
5777 int ret = length;
5778
5779 if (buf[0] == '0')
5780 s->flags &= ~SLAB_SKIP_KFENCE;
5781 else if (buf[0] == '1')
5782 s->flags |= SLAB_SKIP_KFENCE;
5783 else
5784 ret = -EINVAL;
5785
5786 return ret;
5787}
5788SLAB_ATTR(skip_kfence);
5789#endif
5790
06428780 5791static struct attribute *slab_attrs[] = {
81819f0f
CL
5792 &slab_size_attr.attr,
5793 &object_size_attr.attr,
5794 &objs_per_slab_attr.attr,
5795 &order_attr.attr,
73d342b1 5796 &min_partial_attr.attr,
49e22585 5797 &cpu_partial_attr.attr,
81819f0f 5798 &objects_attr.attr,
205ab99d 5799 &objects_partial_attr.attr,
81819f0f
CL
5800 &partial_attr.attr,
5801 &cpu_slabs_attr.attr,
5802 &ctor_attr.attr,
81819f0f
CL
5803 &aliases_attr.attr,
5804 &align_attr.attr,
81819f0f
CL
5805 &hwcache_align_attr.attr,
5806 &reclaim_account_attr.attr,
5807 &destroy_by_rcu_attr.attr,
a5a84755 5808 &shrink_attr.attr,
49e22585 5809 &slabs_cpu_partial_attr.attr,
ab4d5ed5 5810#ifdef CONFIG_SLUB_DEBUG
a5a84755
CL
5811 &total_objects_attr.attr,
5812 &slabs_attr.attr,
5813 &sanity_checks_attr.attr,
5814 &trace_attr.attr,
81819f0f
CL
5815 &red_zone_attr.attr,
5816 &poison_attr.attr,
5817 &store_user_attr.attr,
53e15af0 5818 &validate_attr.attr,
ab4d5ed5 5819#endif
81819f0f
CL
5820#ifdef CONFIG_ZONE_DMA
5821 &cache_dma_attr.attr,
5822#endif
5823#ifdef CONFIG_NUMA
9824601e 5824 &remote_node_defrag_ratio_attr.attr,
8ff12cfc
CL
5825#endif
5826#ifdef CONFIG_SLUB_STATS
5827 &alloc_fastpath_attr.attr,
5828 &alloc_slowpath_attr.attr,
5829 &free_fastpath_attr.attr,
5830 &free_slowpath_attr.attr,
5831 &free_frozen_attr.attr,
5832 &free_add_partial_attr.attr,
5833 &free_remove_partial_attr.attr,
5834 &alloc_from_partial_attr.attr,
5835 &alloc_slab_attr.attr,
5836 &alloc_refill_attr.attr,
e36a2652 5837 &alloc_node_mismatch_attr.attr,
8ff12cfc
CL
5838 &free_slab_attr.attr,
5839 &cpuslab_flush_attr.attr,
5840 &deactivate_full_attr.attr,
5841 &deactivate_empty_attr.attr,
5842 &deactivate_to_head_attr.attr,
5843 &deactivate_to_tail_attr.attr,
5844 &deactivate_remote_frees_attr.attr,
03e404af 5845 &deactivate_bypass_attr.attr,
65c3376a 5846 &order_fallback_attr.attr,
b789ef51
CL
5847 &cmpxchg_double_fail_attr.attr,
5848 &cmpxchg_double_cpu_fail_attr.attr,
49e22585
CL
5849 &cpu_partial_alloc_attr.attr,
5850 &cpu_partial_free_attr.attr,
8028dcea
AS
5851 &cpu_partial_node_attr.attr,
5852 &cpu_partial_drain_attr.attr,
81819f0f 5853#endif
4c13dd3b
DM
5854#ifdef CONFIG_FAILSLAB
5855 &failslab_attr.attr,
5856#endif
8eb8284b 5857 &usersize_attr.attr,
b84e04f1
IK
5858#ifdef CONFIG_KFENCE
5859 &skip_kfence_attr.attr,
5860#endif
4c13dd3b 5861
81819f0f
CL
5862 NULL
5863};
5864
1fdaaa23 5865static const struct attribute_group slab_attr_group = {
81819f0f
CL
5866 .attrs = slab_attrs,
5867};
5868
5869static ssize_t slab_attr_show(struct kobject *kobj,
5870 struct attribute *attr,
5871 char *buf)
5872{
5873 struct slab_attribute *attribute;
5874 struct kmem_cache *s;
81819f0f
CL
5875
5876 attribute = to_slab_attr(attr);
5877 s = to_slab(kobj);
5878
5879 if (!attribute->show)
5880 return -EIO;
5881
2bfbb027 5882 return attribute->show(s, buf);
81819f0f
CL
5883}
5884
5885static ssize_t slab_attr_store(struct kobject *kobj,
5886 struct attribute *attr,
5887 const char *buf, size_t len)
5888{
5889 struct slab_attribute *attribute;
5890 struct kmem_cache *s;
81819f0f
CL
5891
5892 attribute = to_slab_attr(attr);
5893 s = to_slab(kobj);
5894
5895 if (!attribute->store)
5896 return -EIO;
5897
2bfbb027 5898 return attribute->store(s, buf, len);
81819f0f
CL
5899}
5900
41a21285
CL
5901static void kmem_cache_release(struct kobject *k)
5902{
5903 slab_kmem_cache_release(to_slab(k));
5904}
5905
52cf25d0 5906static const struct sysfs_ops slab_sysfs_ops = {
81819f0f
CL
5907 .show = slab_attr_show,
5908 .store = slab_attr_store,
5909};
5910
5911static struct kobj_type slab_ktype = {
5912 .sysfs_ops = &slab_sysfs_ops,
41a21285 5913 .release = kmem_cache_release,
81819f0f
CL
5914};
5915
27c3a314 5916static struct kset *slab_kset;
81819f0f 5917
9a41707b
VD
5918static inline struct kset *cache_kset(struct kmem_cache *s)
5919{
9a41707b
VD
5920 return slab_kset;
5921}
5922
d65360f2 5923#define ID_STR_LENGTH 32
81819f0f
CL
5924
5925/* Create a unique string id for a slab cache:
6446faa2
CL
5926 *
5927 * Format :[flags-]size
81819f0f
CL
5928 */
5929static char *create_unique_id(struct kmem_cache *s)
5930{
5931 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5932 char *p = name;
5933
7e9c323c
CY
5934 if (!name)
5935 return ERR_PTR(-ENOMEM);
81819f0f
CL
5936
5937 *p++ = ':';
5938 /*
5939 * First flags affecting slabcache operations. We will only
5940 * get here for aliasable slabs so we do not need to support
5941 * too many flags. The flags here must cover all flags that
5942 * are matched during merging to guarantee that the id is
5943 * unique.
5944 */
5945 if (s->flags & SLAB_CACHE_DMA)
5946 *p++ = 'd';
6d6ea1e9
NB
5947 if (s->flags & SLAB_CACHE_DMA32)
5948 *p++ = 'D';
81819f0f
CL
5949 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5950 *p++ = 'a';
becfda68 5951 if (s->flags & SLAB_CONSISTENCY_CHECKS)
81819f0f 5952 *p++ = 'F';
230e9fc2
VD
5953 if (s->flags & SLAB_ACCOUNT)
5954 *p++ = 'A';
81819f0f
CL
5955 if (p != name + 1)
5956 *p++ = '-';
d65360f2 5957 p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
2633d7a0 5958
d65360f2
CY
5959 if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
5960 kfree(name);
5961 return ERR_PTR(-EINVAL);
5962 }
68ef169a 5963 kmsan_unpoison_memory(name, p - name);
81819f0f
CL
5964 return name;
5965}
5966
5967static int sysfs_slab_add(struct kmem_cache *s)
5968{
5969 int err;
5970 const char *name;
1663f26d 5971 struct kset *kset = cache_kset(s);
45530c44 5972 int unmergeable = slab_unmergeable(s);
81819f0f 5973
11066386
MC
5974 if (!unmergeable && disable_higher_order_debug &&
5975 (slub_debug & DEBUG_METADATA_FLAGS))
5976 unmergeable = 1;
5977
81819f0f
CL
5978 if (unmergeable) {
5979 /*
5980 * Slabcache can never be merged so we can use the name proper.
5981 * This is typically the case for debug situations. In that
5982 * case we can catch duplicate names easily.
5983 */
27c3a314 5984 sysfs_remove_link(&slab_kset->kobj, s->name);
81819f0f
CL
5985 name = s->name;
5986 } else {
5987 /*
5988 * Create a unique name for the slab as a target
5989 * for the symlinks.
5990 */
5991 name = create_unique_id(s);
7e9c323c
CY
5992 if (IS_ERR(name))
5993 return PTR_ERR(name);
81819f0f
CL
5994 }
5995
1663f26d 5996 s->kobj.kset = kset;
26e4f205 5997 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
757fed1d 5998 if (err)
80da026a 5999 goto out;
81819f0f
CL
6000
6001 err = sysfs_create_group(&s->kobj, &slab_attr_group);
54b6a731
DJ
6002 if (err)
6003 goto out_del_kobj;
9a41707b 6004
81819f0f
CL
6005 if (!unmergeable) {
6006 /* Setup first alias */
6007 sysfs_slab_alias(s, s->name);
81819f0f 6008 }
54b6a731
DJ
6009out:
6010 if (!unmergeable)
6011 kfree(name);
6012 return err;
6013out_del_kobj:
6014 kobject_del(&s->kobj);
54b6a731 6015 goto out;
81819f0f
CL
6016}
6017
d50d82fa
MP
6018void sysfs_slab_unlink(struct kmem_cache *s)
6019{
6020 if (slab_state >= FULL)
6021 kobject_del(&s->kobj);
6022}
6023
bf5eb3de
TH
6024void sysfs_slab_release(struct kmem_cache *s)
6025{
6026 if (slab_state >= FULL)
6027 kobject_put(&s->kobj);
81819f0f
CL
6028}
6029
6030/*
6031 * Need to buffer aliases during bootup until sysfs becomes
9f6c708e 6032 * available lest we lose that information.
81819f0f
CL
6033 */
6034struct saved_alias {
6035 struct kmem_cache *s;
6036 const char *name;
6037 struct saved_alias *next;
6038};
6039
5af328a5 6040static struct saved_alias *alias_list;
81819f0f
CL
6041
6042static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
6043{
6044 struct saved_alias *al;
6045
97d06609 6046 if (slab_state == FULL) {
81819f0f
CL
6047 /*
6048 * If we have a leftover link then remove it.
6049 */
27c3a314
GKH
6050 sysfs_remove_link(&slab_kset->kobj, name);
6051 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
81819f0f
CL
6052 }
6053
6054 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
6055 if (!al)
6056 return -ENOMEM;
6057
6058 al->s = s;
6059 al->name = name;
6060 al->next = alias_list;
6061 alias_list = al;
68ef169a 6062 kmsan_unpoison_memory(al, sizeof(*al));
81819f0f
CL
6063 return 0;
6064}
6065
6066static int __init slab_sysfs_init(void)
6067{
5b95a4ac 6068 struct kmem_cache *s;
81819f0f
CL
6069 int err;
6070
18004c5d 6071 mutex_lock(&slab_mutex);
2bce6485 6072
d7660ce5 6073 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
27c3a314 6074 if (!slab_kset) {
18004c5d 6075 mutex_unlock(&slab_mutex);
f9f58285 6076 pr_err("Cannot register slab subsystem.\n");
81819f0f
CL
6077 return -ENOSYS;
6078 }
6079
97d06609 6080 slab_state = FULL;
26a7bd03 6081
5b95a4ac 6082 list_for_each_entry(s, &slab_caches, list) {
26a7bd03 6083 err = sysfs_slab_add(s);
5d540fb7 6084 if (err)
f9f58285
FF
6085 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
6086 s->name);
26a7bd03 6087 }
81819f0f
CL
6088
6089 while (alias_list) {
6090 struct saved_alias *al = alias_list;
6091
6092 alias_list = alias_list->next;
6093 err = sysfs_slab_alias(al->s, al->name);
5d540fb7 6094 if (err)
f9f58285
FF
6095 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
6096 al->name);
81819f0f
CL
6097 kfree(al);
6098 }
6099
18004c5d 6100 mutex_unlock(&slab_mutex);
81819f0f
CL
6101 return 0;
6102}
1a5ad30b 6103late_initcall(slab_sysfs_init);
ab4d5ed5 6104#endif /* CONFIG_SYSFS */
57ed3eda 6105
64dd6849
FM
6106#if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
6107static int slab_debugfs_show(struct seq_file *seq, void *v)
6108{
64dd6849 6109 struct loc_track *t = seq->private;
005a79e5
GS
6110 struct location *l;
6111 unsigned long idx;
64dd6849 6112
005a79e5 6113 idx = (unsigned long) t->idx;
64dd6849
FM
6114 if (idx < t->count) {
6115 l = &t->loc[idx];
6116
6117 seq_printf(seq, "%7ld ", l->count);
6118
6119 if (l->addr)
6120 seq_printf(seq, "%pS", (void *)l->addr);
6121 else
6122 seq_puts(seq, "<not-available>");
6123
6edf2576
FT
6124 if (l->waste)
6125 seq_printf(seq, " waste=%lu/%lu",
6126 l->count * l->waste, l->waste);
6127
64dd6849
FM
6128 if (l->sum_time != l->min_time) {
6129 seq_printf(seq, " age=%ld/%llu/%ld",
6130 l->min_time, div_u64(l->sum_time, l->count),
6131 l->max_time);
6132 } else
6133 seq_printf(seq, " age=%ld", l->min_time);
6134
6135 if (l->min_pid != l->max_pid)
6136 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
6137 else
6138 seq_printf(seq, " pid=%ld",
6139 l->min_pid);
6140
6141 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
6142 seq_printf(seq, " cpus=%*pbl",
6143 cpumask_pr_args(to_cpumask(l->cpus)));
6144
6145 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
6146 seq_printf(seq, " nodes=%*pbl",
6147 nodemask_pr_args(&l->nodes));
6148
8ea9fb92
OG
6149#ifdef CONFIG_STACKDEPOT
6150 {
6151 depot_stack_handle_t handle;
6152 unsigned long *entries;
6153 unsigned int nr_entries, j;
6154
6155 handle = READ_ONCE(l->handle);
6156 if (handle) {
6157 nr_entries = stack_depot_fetch(handle, &entries);
6158 seq_puts(seq, "\n");
6159 for (j = 0; j < nr_entries; j++)
6160 seq_printf(seq, " %pS\n", (void *)entries[j]);
6161 }
6162 }
6163#endif
64dd6849
FM
6164 seq_puts(seq, "\n");
6165 }
6166
6167 if (!idx && !t->count)
6168 seq_puts(seq, "No data\n");
6169
6170 return 0;
6171}
6172
6173static void slab_debugfs_stop(struct seq_file *seq, void *v)
6174{
6175}
6176
6177static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
6178{
6179 struct loc_track *t = seq->private;
6180
005a79e5 6181 t->idx = ++(*ppos);
64dd6849 6182 if (*ppos <= t->count)
005a79e5 6183 return ppos;
64dd6849
FM
6184
6185 return NULL;
6186}
6187
553c0369
OG
6188static int cmp_loc_by_count(const void *a, const void *b, const void *data)
6189{
6190 struct location *loc1 = (struct location *)a;
6191 struct location *loc2 = (struct location *)b;
6192
6193 if (loc1->count > loc2->count)
6194 return -1;
6195 else
6196 return 1;
6197}
6198
64dd6849
FM
6199static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
6200{
005a79e5
GS
6201 struct loc_track *t = seq->private;
6202
6203 t->idx = *ppos;
64dd6849
FM
6204 return ppos;
6205}
6206
6207static const struct seq_operations slab_debugfs_sops = {
6208 .start = slab_debugfs_start,
6209 .next = slab_debugfs_next,
6210 .stop = slab_debugfs_stop,
6211 .show = slab_debugfs_show,
6212};
6213
6214static int slab_debug_trace_open(struct inode *inode, struct file *filep)
6215{
6216
6217 struct kmem_cache_node *n;
6218 enum track_item alloc;
6219 int node;
6220 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
6221 sizeof(struct loc_track));
6222 struct kmem_cache *s = file_inode(filep)->i_private;
b3fd64e1
VB
6223 unsigned long *obj_map;
6224
2127d225
ML
6225 if (!t)
6226 return -ENOMEM;
6227
b3fd64e1 6228 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
2127d225
ML
6229 if (!obj_map) {
6230 seq_release_private(inode, filep);
b3fd64e1 6231 return -ENOMEM;
2127d225 6232 }
64dd6849
FM
6233
6234 if (strcmp(filep->f_path.dentry->d_name.name, "alloc_traces") == 0)
6235 alloc = TRACK_ALLOC;
6236 else
6237 alloc = TRACK_FREE;
6238
b3fd64e1
VB
6239 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
6240 bitmap_free(obj_map);
2127d225 6241 seq_release_private(inode, filep);
64dd6849 6242 return -ENOMEM;
b3fd64e1 6243 }
64dd6849 6244
64dd6849
FM
6245 for_each_kmem_cache_node(s, node, n) {
6246 unsigned long flags;
bb192ed9 6247 struct slab *slab;
64dd6849
FM
6248
6249 if (!atomic_long_read(&n->nr_slabs))
6250 continue;
6251
6252 spin_lock_irqsave(&n->list_lock, flags);
bb192ed9
VB
6253 list_for_each_entry(slab, &n->partial, slab_list)
6254 process_slab(t, s, slab, alloc, obj_map);
6255 list_for_each_entry(slab, &n->full, slab_list)
6256 process_slab(t, s, slab, alloc, obj_map);
64dd6849
FM
6257 spin_unlock_irqrestore(&n->list_lock, flags);
6258 }
6259
553c0369
OG
6260 /* Sort locations by count */
6261 sort_r(t->loc, t->count, sizeof(struct location),
6262 cmp_loc_by_count, NULL, NULL);
6263
b3fd64e1 6264 bitmap_free(obj_map);
64dd6849
FM
6265 return 0;
6266}
6267
6268static int slab_debug_trace_release(struct inode *inode, struct file *file)
6269{
6270 struct seq_file *seq = file->private_data;
6271 struct loc_track *t = seq->private;
6272
6273 free_loc_track(t);
6274 return seq_release_private(inode, file);
6275}
6276
6277static const struct file_operations slab_debugfs_fops = {
6278 .open = slab_debug_trace_open,
6279 .read = seq_read,
6280 .llseek = seq_lseek,
6281 .release = slab_debug_trace_release,
6282};
6283
6284static void debugfs_slab_add(struct kmem_cache *s)
6285{
6286 struct dentry *slab_cache_dir;
6287
6288 if (unlikely(!slab_debugfs_root))
6289 return;
6290
6291 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
6292
6293 debugfs_create_file("alloc_traces", 0400,
6294 slab_cache_dir, s, &slab_debugfs_fops);
6295
6296 debugfs_create_file("free_traces", 0400,
6297 slab_cache_dir, s, &slab_debugfs_fops);
6298}
6299
6300void debugfs_slab_release(struct kmem_cache *s)
6301{
6302 debugfs_remove_recursive(debugfs_lookup(s->name, slab_debugfs_root));
6303}
6304
6305static int __init slab_debugfs_init(void)
6306{
6307 struct kmem_cache *s;
6308
6309 slab_debugfs_root = debugfs_create_dir("slab", NULL);
6310
6311 list_for_each_entry(s, &slab_caches, list)
6312 if (s->flags & SLAB_STORE_USER)
6313 debugfs_slab_add(s);
6314
6315 return 0;
6316
6317}
6318__initcall(slab_debugfs_init);
6319#endif
57ed3eda
PE
6320/*
6321 * The /proc/slabinfo ABI
6322 */
5b365771 6323#ifdef CONFIG_SLUB_DEBUG
0d7561c6 6324void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
57ed3eda 6325{
57ed3eda 6326 unsigned long nr_slabs = 0;
205ab99d
CL
6327 unsigned long nr_objs = 0;
6328 unsigned long nr_free = 0;
57ed3eda 6329 int node;
fa45dc25 6330 struct kmem_cache_node *n;
57ed3eda 6331
fa45dc25 6332 for_each_kmem_cache_node(s, node, n) {
c17fd13e
WL
6333 nr_slabs += node_nr_slabs(n);
6334 nr_objs += node_nr_objs(n);
205ab99d 6335 nr_free += count_partial(n, count_free);
57ed3eda
PE
6336 }
6337
0d7561c6
GC
6338 sinfo->active_objs = nr_objs - nr_free;
6339 sinfo->num_objs = nr_objs;
6340 sinfo->active_slabs = nr_slabs;
6341 sinfo->num_slabs = nr_slabs;
6342 sinfo->objects_per_slab = oo_objects(s->oo);
6343 sinfo->cache_order = oo_order(s->oo);
57ed3eda
PE
6344}
6345
0d7561c6 6346void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *s)
7b3c3a50 6347{
7b3c3a50
AD
6348}
6349
b7454ad3
GC
6350ssize_t slabinfo_write(struct file *file, const char __user *buffer,
6351 size_t count, loff_t *ppos)
7b3c3a50 6352{
b7454ad3 6353 return -EIO;
7b3c3a50 6354}
5b365771 6355#endif /* CONFIG_SLUB_DEBUG */