1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
5 *
6 * The allocator synchronizes using per slab locks or atomic operations
7 * and only uses a centralized lock to manage a pool of partial slabs.
8 *
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
11 */
12
13 #include <linux/mm.h>
14 #include <linux/swap.h> /* mm_account_reclaimed_pages() */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
21 #include "slab.h"
22 #include <linux/vmalloc.h>
23 #include <linux/proc_fs.h>
24 #include <linux/seq_file.h>
25 #include <linux/kasan.h>
26 #include <linux/node.h>
27 #include <linux/kmsan.h>
28 #include <linux/cpu.h>
29 #include <linux/cpuset.h>
30 #include <linux/mempolicy.h>
31 #include <linux/ctype.h>
32 #include <linux/stackdepot.h>
33 #include <linux/debugobjects.h>
34 #include <linux/kallsyms.h>
35 #include <linux/kfence.h>
36 #include <linux/memory.h>
37 #include <linux/math64.h>
38 #include <linux/fault-inject.h>
39 #include <linux/kmemleak.h>
40 #include <linux/stacktrace.h>
41 #include <linux/prefetch.h>
42 #include <linux/memcontrol.h>
43 #include <linux/random.h>
44 #include <kunit/test.h>
45 #include <kunit/test-bug.h>
46 #include <linux/sort.h>
47 #include <linux/irq_work.h>
48 #include <linux/kprobes.h>
49 #include <linux/debugfs.h>
50 #include <trace/events/kmem.h>
51
52 #include "internal.h"
53
54 /*
55 * Lock order:
56 * 1. slab_mutex (Global Mutex)
57 * 2. node->list_lock (Spinlock)
58 * 3. kmem_cache->cpu_slab->lock (Local lock)
59 * 4. slab_lock(slab) (Only on some arches)
60 * 5. object_map_lock (Only for debugging)
61 *
62 * slab_mutex
63 *
64 * The role of the slab_mutex is to protect the list of all the slabs
65 * and to synchronize major metadata changes to slab cache structures.
66 * Also synchronizes memory hotplug callbacks.
67 *
68 * slab_lock
69 *
70 * The slab_lock is a wrapper around the page lock, thus it is a bit
71 * spinlock.
72 *
73 * The slab_lock is only used on arches that do not have the ability
74 * to do a cmpxchg_double. It only protects:
75 *
76 * A. slab->freelist -> List of free objects in a slab
77 * B. slab->inuse -> Number of objects in use
78 * C. slab->objects -> Number of objects in slab
79 * D. slab->frozen -> frozen state
80 *
81 * Frozen slabs
82 *
83 * If a slab is frozen then it is exempt from list management. It is
84 * the cpu slab which is actively allocated from by the processor that
85 * froze it and it is not on any list. The processor that froze the
86 * slab is the one who can perform list operations on the slab. Other
87 * processors may put objects onto the freelist but the processor that
88 * froze the slab is the only one that can retrieve the objects from the
89 * slab's freelist.
90 *
91 * CPU partial slabs
92 *
93 * The partially empty slabs cached on the CPU partial list are used
94 * for performance reasons, which speeds up the allocation process.
95 * These slabs are not frozen, but are also exempt from list management,
96 * by clearing the SL_partial flag when moving out of the node
97 * partial list. Please see __slab_free() for more details.
98 *
99 * To sum up, the current scheme is:
100 * - node partial slab: SL_partial && !frozen
101 * - cpu partial slab: !SL_partial && !frozen
102 * - cpu slab: !SL_partial && frozen
103 * - full slab: !SL_partial && !frozen
104 *
105 * list_lock
106 *
107 * The list_lock protects the partial and full list on each node and
108 * the partial slab counter. If taken then no new slabs may be added or
109 * removed from the lists nor make the number of partial slabs be modified.
110 * (Note that the total number of slabs is an atomic value that may be
111 * modified without taking the list lock).
112 *
113 * The list_lock is a centralized lock and thus we avoid taking it as
114 * much as possible. As long as SLUB does not have to handle partial
115 * slabs, operations can continue without any centralized lock. F.e.
116 * allocating a long series of objects that fill up slabs does not require
117 * the list lock.
118 *
119 * For debug caches, all allocations are forced to go through a list_lock
120 * protected region to serialize against concurrent validation.
121 *
122 * cpu_slab->lock local lock
123 *
124 * This locks protect slowpath manipulation of all kmem_cache_cpu fields
125 * except the stat counters. This is a percpu structure manipulated only by
126 * the local cpu, so the lock protects against being preempted or interrupted
127 * by an irq. Fast path operations rely on lockless operations instead.
128 *
129 * On PREEMPT_RT, the local lock neither disables interrupts nor preemption
130 * which means the lockless fastpath cannot be used as it might interfere with
131 * an in-progress slow path operations. In this case the local lock is always
132 * taken but it still utilizes the freelist for the common operations.
133 *
134 * lockless fastpaths
135 *
136 * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
137 * are fully lockless when satisfied from the percpu slab (and when
138 * cmpxchg_double is possible to use, otherwise slab_lock is taken).
139 * They also don't disable preemption or migration or irqs. They rely on
140 * the transaction id (tid) field to detect being preempted or moved to
141 * another cpu.
142 *
143 * irq, preemption, migration considerations
144 *
145 * Interrupts are disabled as part of list_lock or local_lock operations, or
146 * around the slab_lock operation, in order to make the slab allocator safe
147 * to use in the context of an irq.
148 *
149 * In addition, preemption (or migration on PREEMPT_RT) is disabled in the
150 * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
151 * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
152 * doesn't have to be revalidated in each section protected by the local lock.
153 *
154 * SLUB assigns one slab for allocation to each processor.
155 * Allocations only occur from these slabs called cpu slabs.
156 *
157 * Slabs with free elements are kept on a partial list and during regular
158 * operations no list for full slabs is used. If an object in a full slab is
159 * freed then the slab will show up again on the partial lists.
160 * We track full slabs for debugging purposes though because otherwise we
161 * cannot scan all objects.
162 *
163 * Slabs are freed when they become empty. Teardown and setup is
164 * minimal so we rely on the page allocators per cpu caches for
165 * fast frees and allocs.
166 *
167 * slab->frozen The slab is frozen and exempt from list processing.
168 * This means that the slab is dedicated to a purpose
169 * such as satisfying allocations for a specific
170 * processor. Objects may be freed in the slab while
171 * it is frozen but slab_free will then skip the usual
172 * list operations. It is up to the processor holding
173 * the slab to integrate the slab into the slab lists
174 * when the slab is no longer needed.
175 *
176 * One use of this flag is to mark slabs that are
177 * used for allocations. Then such a slab becomes a cpu
178 * slab. The cpu slab may be equipped with an additional
179 * freelist that allows lockless access to
180 * free objects in addition to the regular freelist
181 * that requires the slab lock.
182 *
183 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
184 * options set. This moves slab handling out of
185 * the fast path and disables lockless freelists.
186 */
187
188 /**
189 * enum slab_flags - How the slab flags bits are used.
190 * @SL_locked: Is locked with slab_lock()
191 * @SL_partial: On the per-node partial list
192 * @SL_pfmemalloc: Was allocated from PF_MEMALLOC reserves
193 *
194 * The slab flags share space with the page flags but some bits have
195 * different interpretations. The high bits are used for information
196 * like zone/node/section.
197 */
198 enum slab_flags {
199 SL_locked = PG_locked,
200 SL_partial = PG_workingset, /* Historical reasons for this bit */
201 SL_pfmemalloc = PG_active, /* Historical reasons for this bit */
202 };
203
204 /*
205 * We could simply use migrate_disable()/enable() but as long as it's a
206 * function call even on !PREEMPT_RT, use inline preempt_disable() there.
207 */
208 #ifndef CONFIG_PREEMPT_RT
209 #define slub_get_cpu_ptr(var) get_cpu_ptr(var)
210 #define slub_put_cpu_ptr(var) put_cpu_ptr(var)
211 #define USE_LOCKLESS_FAST_PATH() (true)
212 #else
213 #define slub_get_cpu_ptr(var) \
214 ({ \
215 migrate_disable(); \
216 this_cpu_ptr(var); \
217 })
218 #define slub_put_cpu_ptr(var) \
219 do { \
220 (void)(var); \
221 migrate_enable(); \
222 } while (0)
223 #define USE_LOCKLESS_FAST_PATH() (false)
224 #endif
225
226 #ifndef CONFIG_SLUB_TINY
227 #define __fastpath_inline __always_inline
228 #else
229 #define __fastpath_inline
230 #endif
231
232 #ifdef CONFIG_SLUB_DEBUG
233 #ifdef CONFIG_SLUB_DEBUG_ON
234 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
235 #else
236 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
237 #endif
238 #endif /* CONFIG_SLUB_DEBUG */
239
240 #ifdef CONFIG_NUMA
241 static DEFINE_STATIC_KEY_FALSE(strict_numa);
242 #endif
243
244 /* Structure holding parameters for get_partial() call chain */
245 struct partial_context {
246 gfp_t flags;
247 unsigned int orig_size;
248 void *object;
249 };
250
kmem_cache_debug(struct kmem_cache * s)251 static inline bool kmem_cache_debug(struct kmem_cache *s)
252 {
253 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
254 }
255
fixup_red_left(struct kmem_cache * s,void * p)256 void *fixup_red_left(struct kmem_cache *s, void *p)
257 {
258 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
259 p += s->red_left_pad;
260
261 return p;
262 }
263
kmem_cache_has_cpu_partial(struct kmem_cache * s)264 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
265 {
266 #ifdef CONFIG_SLUB_CPU_PARTIAL
267 return !kmem_cache_debug(s);
268 #else
269 return false;
270 #endif
271 }
272
273 /*
274 * Issues still to be resolved:
275 *
276 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
277 *
278 * - Variable sizing of the per node arrays
279 */
280
281 /* Enable to log cmpxchg failures */
282 #undef SLUB_DEBUG_CMPXCHG
283
284 #ifndef CONFIG_SLUB_TINY
285 /*
286 * Minimum number of partial slabs. These will be left on the partial
287 * lists even if they are empty. kmem_cache_shrink may reclaim them.
288 */
289 #define MIN_PARTIAL 5
290
291 /*
292 * Maximum number of desirable partial slabs.
293 * The existence of more partial slabs makes kmem_cache_shrink
294 * sort the partial list by the number of objects in use.
295 */
296 #define MAX_PARTIAL 10
297 #else
298 #define MIN_PARTIAL 0
299 #define MAX_PARTIAL 0
300 #endif
301
302 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
303 SLAB_POISON | SLAB_STORE_USER)
304
305 /*
306 * These debug flags cannot use CMPXCHG because there might be consistency
307 * issues when checking or reading debug information
308 */
309 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
310 SLAB_TRACE)
311
312
313 /*
314 * Debugging flags that require metadata to be stored in the slab. These get
315 * disabled when slab_debug=O is used and a cache's min order increases with
316 * metadata.
317 */
318 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
319
320 #define OO_SHIFT 16
321 #define OO_MASK ((1 << OO_SHIFT) - 1)
322 #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
323
324 /* Internal SLUB flags */
325 /* Poison object */
326 #define __OBJECT_POISON __SLAB_FLAG_BIT(_SLAB_OBJECT_POISON)
327 /* Use cmpxchg_double */
328
329 #ifdef system_has_freelist_aba
330 #define __CMPXCHG_DOUBLE __SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE)
331 #else
332 #define __CMPXCHG_DOUBLE __SLAB_FLAG_UNUSED
333 #endif
334
335 /*
336 * Tracking user of a slab.
337 */
338 #define TRACK_ADDRS_COUNT 16
339 struct track {
340 unsigned long addr; /* Called from address */
341 #ifdef CONFIG_STACKDEPOT
342 depot_stack_handle_t handle;
343 #endif
344 int cpu; /* Was running on cpu */
345 int pid; /* Pid context */
346 unsigned long when; /* When did the operation occur */
347 };
348
349 enum track_item { TRACK_ALLOC, TRACK_FREE };
350
351 #ifdef SLAB_SUPPORTS_SYSFS
352 static int sysfs_slab_add(struct kmem_cache *);
353 static int sysfs_slab_alias(struct kmem_cache *, const char *);
354 #else
sysfs_slab_add(struct kmem_cache * s)355 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
sysfs_slab_alias(struct kmem_cache * s,const char * p)356 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
357 { return 0; }
358 #endif
359
360 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG)
361 static void debugfs_slab_add(struct kmem_cache *);
362 #else
debugfs_slab_add(struct kmem_cache * s)363 static inline void debugfs_slab_add(struct kmem_cache *s) { }
364 #endif
365
366 enum stat_item {
367 ALLOC_PCS, /* Allocation from percpu sheaf */
368 ALLOC_FASTPATH, /* Allocation from cpu slab */
369 ALLOC_SLOWPATH, /* Allocation by getting a new cpu slab */
370 FREE_PCS, /* Free to percpu sheaf */
371 FREE_RCU_SHEAF, /* Free to rcu_free sheaf */
372 FREE_RCU_SHEAF_FAIL, /* Failed to free to a rcu_free sheaf */
373 FREE_FASTPATH, /* Free to cpu slab */
374 FREE_SLOWPATH, /* Freeing not to cpu slab */
375 FREE_FROZEN, /* Freeing to frozen slab */
376 FREE_ADD_PARTIAL, /* Freeing moves slab to partial list */
377 FREE_REMOVE_PARTIAL, /* Freeing removes last object */
378 ALLOC_FROM_PARTIAL, /* Cpu slab acquired from node partial list */
379 ALLOC_SLAB, /* Cpu slab acquired from page allocator */
380 ALLOC_REFILL, /* Refill cpu slab from slab freelist */
381 ALLOC_NODE_MISMATCH, /* Switching cpu slab */
382 FREE_SLAB, /* Slab freed to the page allocator */
383 CPUSLAB_FLUSH, /* Abandoning of the cpu slab */
384 DEACTIVATE_FULL, /* Cpu slab was full when deactivated */
385 DEACTIVATE_EMPTY, /* Cpu slab was empty when deactivated */
386 DEACTIVATE_TO_HEAD, /* Cpu slab was moved to the head of partials */
387 DEACTIVATE_TO_TAIL, /* Cpu slab was moved to the tail of partials */
388 DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */
389 DEACTIVATE_BYPASS, /* Implicit deactivation */
390 ORDER_FALLBACK, /* Number of times fallback was necessary */
391 CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */
392 CMPXCHG_DOUBLE_FAIL, /* Failures of slab freelist update */
393 CPU_PARTIAL_ALLOC, /* Used cpu partial on alloc */
394 CPU_PARTIAL_FREE, /* Refill cpu partial on free */
395 CPU_PARTIAL_NODE, /* Refill cpu partial from node partial */
396 CPU_PARTIAL_DRAIN, /* Drain cpu partial to node partial */
397 SHEAF_FLUSH, /* Objects flushed from a sheaf */
398 SHEAF_REFILL, /* Objects refilled to a sheaf */
399 SHEAF_ALLOC, /* Allocation of an empty sheaf */
400 SHEAF_FREE, /* Freeing of an empty sheaf */
401 BARN_GET, /* Got full sheaf from barn */
402 BARN_GET_FAIL, /* Failed to get full sheaf from barn */
403 BARN_PUT, /* Put full sheaf to barn */
404 BARN_PUT_FAIL, /* Failed to put full sheaf to barn */
405 SHEAF_PREFILL_FAST, /* Sheaf prefill grabbed the spare sheaf */
406 SHEAF_PREFILL_SLOW, /* Sheaf prefill found no spare sheaf */
407 SHEAF_PREFILL_OVERSIZE, /* Allocation of oversize sheaf for prefill */
408 SHEAF_RETURN_FAST, /* Sheaf return reattached spare sheaf */
409 SHEAF_RETURN_SLOW, /* Sheaf return could not reattach spare */
410 NR_SLUB_STAT_ITEMS
411 };
412
413 #ifndef CONFIG_SLUB_TINY
414 /*
415 * When changing the layout, make sure freelist and tid are still compatible
416 * with this_cpu_cmpxchg_double() alignment requirements.
417 */
418 struct kmem_cache_cpu {
419 union {
420 struct {
421 void **freelist; /* Pointer to next available object */
422 unsigned long tid; /* Globally unique transaction id */
423 };
424 freelist_aba_t freelist_tid;
425 };
426 struct slab *slab; /* The slab from which we are allocating */
427 #ifdef CONFIG_SLUB_CPU_PARTIAL
428 struct slab *partial; /* Partially allocated slabs */
429 #endif
430 local_trylock_t lock; /* Protects the fields above */
431 #ifdef CONFIG_SLUB_STATS
432 unsigned int stat[NR_SLUB_STAT_ITEMS];
433 #endif
434 };
435 #endif /* CONFIG_SLUB_TINY */
436
stat(const struct kmem_cache * s,enum stat_item si)437 static inline void stat(const struct kmem_cache *s, enum stat_item si)
438 {
439 #ifdef CONFIG_SLUB_STATS
440 /*
441 * The rmw is racy on a preemptible kernel but this is acceptable, so
442 * avoid this_cpu_add()'s irq-disable overhead.
443 */
444 raw_cpu_inc(s->cpu_slab->stat[si]);
445 #endif
446 }
447
448 static inline
stat_add(const struct kmem_cache * s,enum stat_item si,int v)449 void stat_add(const struct kmem_cache *s, enum stat_item si, int v)
450 {
451 #ifdef CONFIG_SLUB_STATS
452 raw_cpu_add(s->cpu_slab->stat[si], v);
453 #endif
454 }
455
456 #define MAX_FULL_SHEAVES 10
457 #define MAX_EMPTY_SHEAVES 10
458
459 struct node_barn {
460 spinlock_t lock;
461 struct list_head sheaves_full;
462 struct list_head sheaves_empty;
463 unsigned int nr_full;
464 unsigned int nr_empty;
465 };
466
467 struct slab_sheaf {
468 union {
469 struct rcu_head rcu_head;
470 struct list_head barn_list;
471 /* only used for prefilled sheafs */
472 unsigned int capacity;
473 };
474 struct kmem_cache *cache;
475 unsigned int size;
476 int node; /* only used for rcu_sheaf */
477 void *objects[];
478 };
479
480 struct slub_percpu_sheaves {
481 local_trylock_t lock;
482 struct slab_sheaf *main; /* never NULL when unlocked */
483 struct slab_sheaf *spare; /* empty or full, may be NULL */
484 struct slab_sheaf *rcu_free; /* for batching kfree_rcu() */
485 };
486
487 /*
488 * The slab lists for all objects.
489 */
490 struct kmem_cache_node {
491 spinlock_t list_lock;
492 unsigned long nr_partial;
493 struct list_head partial;
494 #ifdef CONFIG_SLUB_DEBUG
495 atomic_long_t nr_slabs;
496 atomic_long_t total_objects;
497 struct list_head full;
498 #endif
499 struct node_barn *barn;
500 };
501
get_node(struct kmem_cache * s,int node)502 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
503 {
504 return s->node[node];
505 }
506
507 /*
508 * Get the barn of the current cpu's closest memory node. It may not exist on
509 * systems with memoryless nodes but without CONFIG_HAVE_MEMORYLESS_NODES
510 */
get_barn(struct kmem_cache * s)511 static inline struct node_barn *get_barn(struct kmem_cache *s)
512 {
513 struct kmem_cache_node *n = get_node(s, numa_mem_id());
514
515 if (!n)
516 return NULL;
517
518 return n->barn;
519 }
520
521 /*
522 * Iterator over all nodes. The body will be executed for each node that has
523 * a kmem_cache_node structure allocated (which is true for all online nodes)
524 */
525 #define for_each_kmem_cache_node(__s, __node, __n) \
526 for (__node = 0; __node < nr_node_ids; __node++) \
527 if ((__n = get_node(__s, __node)))
528
529 /*
530 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
531 * Corresponds to node_state[N_MEMORY], but can temporarily
532 * differ during memory hotplug/hotremove operations.
533 * Protected by slab_mutex.
534 */
535 static nodemask_t slab_nodes;
536
537 /*
538 * Workqueue used for flush_cpu_slab().
539 */
540 static struct workqueue_struct *flushwq;
541
542 struct slub_flush_work {
543 struct work_struct work;
544 struct kmem_cache *s;
545 bool skip;
546 };
547
548 static DEFINE_MUTEX(flush_lock);
549 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
550
551 /********************************************************************
552 * Core slab cache functions
553 *******************************************************************/
554
555 /*
556 * Returns freelist pointer (ptr). With hardening, this is obfuscated
557 * with an XOR of the address where the pointer is held and a per-cache
558 * random number.
559 */
freelist_ptr_encode(const struct kmem_cache * s,void * ptr,unsigned long ptr_addr)560 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
561 void *ptr, unsigned long ptr_addr)
562 {
563 unsigned long encoded;
564
565 #ifdef CONFIG_SLAB_FREELIST_HARDENED
566 encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
567 #else
568 encoded = (unsigned long)ptr;
569 #endif
570 return (freeptr_t){.v = encoded};
571 }
572
freelist_ptr_decode(const struct kmem_cache * s,freeptr_t ptr,unsigned long ptr_addr)573 static inline void *freelist_ptr_decode(const struct kmem_cache *s,
574 freeptr_t ptr, unsigned long ptr_addr)
575 {
576 void *decoded;
577
578 #ifdef CONFIG_SLAB_FREELIST_HARDENED
579 decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
580 #else
581 decoded = (void *)ptr.v;
582 #endif
583 return decoded;
584 }
585
get_freepointer(struct kmem_cache * s,void * object)586 static inline void *get_freepointer(struct kmem_cache *s, void *object)
587 {
588 unsigned long ptr_addr;
589 freeptr_t p;
590
591 object = kasan_reset_tag(object);
592 ptr_addr = (unsigned long)object + s->offset;
593 p = *(freeptr_t *)(ptr_addr);
594 return freelist_ptr_decode(s, p, ptr_addr);
595 }
596
597 #ifndef CONFIG_SLUB_TINY
prefetch_freepointer(const struct kmem_cache * s,void * object)598 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
599 {
600 prefetchw(object + s->offset);
601 }
602 #endif
603
604 /*
605 * When running under KMSAN, get_freepointer_safe() may return an uninitialized
606 * pointer value in the case the current thread loses the race for the next
607 * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
608 * slab_alloc_node() will fail, so the uninitialized value won't be used, but
609 * KMSAN will still check all arguments of cmpxchg because of imperfect
610 * handling of inline assembly.
611 * To work around this problem, we apply __no_kmsan_checks to ensure that
612 * get_freepointer_safe() returns initialized memory.
613 */
614 __no_kmsan_checks
get_freepointer_safe(struct kmem_cache * s,void * object)615 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
616 {
617 unsigned long freepointer_addr;
618 freeptr_t p;
619
620 if (!debug_pagealloc_enabled_static())
621 return get_freepointer(s, object);
622
623 object = kasan_reset_tag(object);
624 freepointer_addr = (unsigned long)object + s->offset;
625 copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p));
626 return freelist_ptr_decode(s, p, freepointer_addr);
627 }
628
set_freepointer(struct kmem_cache * s,void * object,void * fp)629 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
630 {
631 unsigned long freeptr_addr = (unsigned long)object + s->offset;
632
633 #ifdef CONFIG_SLAB_FREELIST_HARDENED
634 BUG_ON(object == fp); /* naive detection of double free or corruption */
635 #endif
636
637 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
638 *(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
639 }
640
641 /*
642 * See comment in calculate_sizes().
643 */
freeptr_outside_object(struct kmem_cache * s)644 static inline bool freeptr_outside_object(struct kmem_cache *s)
645 {
646 return s->offset >= s->inuse;
647 }
648
649 /*
650 * Return offset of the end of info block which is inuse + free pointer if
651 * not overlapping with object.
652 */
get_info_end(struct kmem_cache * s)653 static inline unsigned int get_info_end(struct kmem_cache *s)
654 {
655 if (freeptr_outside_object(s))
656 return s->inuse + sizeof(void *);
657 else
658 return s->inuse;
659 }
660
661 /* Loop over all objects in a slab */
662 #define for_each_object(__p, __s, __addr, __objects) \
663 for (__p = fixup_red_left(__s, __addr); \
664 __p < (__addr) + (__objects) * (__s)->size; \
665 __p += (__s)->size)
666
order_objects(unsigned int order,unsigned int size)667 static inline unsigned int order_objects(unsigned int order, unsigned int size)
668 {
669 return ((unsigned int)PAGE_SIZE << order) / size;
670 }
671
oo_make(unsigned int order,unsigned int size)672 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
673 unsigned int size)
674 {
675 struct kmem_cache_order_objects x = {
676 (order << OO_SHIFT) + order_objects(order, size)
677 };
678
679 return x;
680 }
681
oo_order(struct kmem_cache_order_objects x)682 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
683 {
684 return x.x >> OO_SHIFT;
685 }
686
oo_objects(struct kmem_cache_order_objects x)687 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
688 {
689 return x.x & OO_MASK;
690 }
691
692 #ifdef CONFIG_SLUB_CPU_PARTIAL
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)693 static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
694 {
695 unsigned int nr_slabs;
696
697 s->cpu_partial = nr_objects;
698
699 /*
700 * We take the number of objects but actually limit the number of
701 * slabs on the per cpu partial list, in order to limit excessive
702 * growth of the list. For simplicity we assume that the slabs will
703 * be half-full.
704 */
705 nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
706 s->cpu_partial_slabs = nr_slabs;
707 }
708
slub_get_cpu_partial(struct kmem_cache * s)709 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
710 {
711 return s->cpu_partial_slabs;
712 }
713 #else
714 static inline void
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)715 slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
716 {
717 }
718
slub_get_cpu_partial(struct kmem_cache * s)719 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
720 {
721 return 0;
722 }
723 #endif /* CONFIG_SLUB_CPU_PARTIAL */
724
725 /*
726 * If network-based swap is enabled, slub must keep track of whether memory
727 * were allocated from pfmemalloc reserves.
728 */
slab_test_pfmemalloc(const struct slab * slab)729 static inline bool slab_test_pfmemalloc(const struct slab *slab)
730 {
731 return test_bit(SL_pfmemalloc, &slab->flags.f);
732 }
733
slab_set_pfmemalloc(struct slab * slab)734 static inline void slab_set_pfmemalloc(struct slab *slab)
735 {
736 set_bit(SL_pfmemalloc, &slab->flags.f);
737 }
738
__slab_clear_pfmemalloc(struct slab * slab)739 static inline void __slab_clear_pfmemalloc(struct slab *slab)
740 {
741 __clear_bit(SL_pfmemalloc, &slab->flags.f);
742 }
743
744 /*
745 * Per slab locking using the pagelock
746 */
slab_lock(struct slab * slab)747 static __always_inline void slab_lock(struct slab *slab)
748 {
749 bit_spin_lock(SL_locked, &slab->flags.f);
750 }
751
slab_unlock(struct slab * slab)752 static __always_inline void slab_unlock(struct slab *slab)
753 {
754 bit_spin_unlock(SL_locked, &slab->flags.f);
755 }
756
757 static inline bool
__update_freelist_fast(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)758 __update_freelist_fast(struct slab *slab,
759 void *freelist_old, unsigned long counters_old,
760 void *freelist_new, unsigned long counters_new)
761 {
762 #ifdef system_has_freelist_aba
763 freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old };
764 freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new };
765
766 return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full);
767 #else
768 return false;
769 #endif
770 }
771
772 static inline bool
__update_freelist_slow(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)773 __update_freelist_slow(struct slab *slab,
774 void *freelist_old, unsigned long counters_old,
775 void *freelist_new, unsigned long counters_new)
776 {
777 bool ret = false;
778
779 slab_lock(slab);
780 if (slab->freelist == freelist_old &&
781 slab->counters == counters_old) {
782 slab->freelist = freelist_new;
783 slab->counters = counters_new;
784 ret = true;
785 }
786 slab_unlock(slab);
787
788 return ret;
789 }
790
791 /*
792 * Interrupts must be disabled (for the fallback code to work right), typically
793 * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
794 * part of bit_spin_lock(), is sufficient because the policy is not to allow any
795 * allocation/ free operation in hardirq context. Therefore nothing can
796 * interrupt the operation.
797 */
__slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)798 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
799 void *freelist_old, unsigned long counters_old,
800 void *freelist_new, unsigned long counters_new,
801 const char *n)
802 {
803 bool ret;
804
805 if (USE_LOCKLESS_FAST_PATH())
806 lockdep_assert_irqs_disabled();
807
808 if (s->flags & __CMPXCHG_DOUBLE) {
809 ret = __update_freelist_fast(slab, freelist_old, counters_old,
810 freelist_new, counters_new);
811 } else {
812 ret = __update_freelist_slow(slab, freelist_old, counters_old,
813 freelist_new, counters_new);
814 }
815 if (likely(ret))
816 return true;
817
818 cpu_relax();
819 stat(s, CMPXCHG_DOUBLE_FAIL);
820
821 #ifdef SLUB_DEBUG_CMPXCHG
822 pr_info("%s %s: cmpxchg double redo ", n, s->name);
823 #endif
824
825 return false;
826 }
827
slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)828 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
829 void *freelist_old, unsigned long counters_old,
830 void *freelist_new, unsigned long counters_new,
831 const char *n)
832 {
833 bool ret;
834
835 if (s->flags & __CMPXCHG_DOUBLE) {
836 ret = __update_freelist_fast(slab, freelist_old, counters_old,
837 freelist_new, counters_new);
838 } else {
839 unsigned long flags;
840
841 local_irq_save(flags);
842 ret = __update_freelist_slow(slab, freelist_old, counters_old,
843 freelist_new, counters_new);
844 local_irq_restore(flags);
845 }
846 if (likely(ret))
847 return true;
848
849 cpu_relax();
850 stat(s, CMPXCHG_DOUBLE_FAIL);
851
852 #ifdef SLUB_DEBUG_CMPXCHG
853 pr_info("%s %s: cmpxchg double redo ", n, s->name);
854 #endif
855
856 return false;
857 }
858
859 /*
860 * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
861 * family will round up the real request size to these fixed ones, so
862 * there could be an extra area than what is requested. Save the original
863 * request size in the meta data area, for better debug and sanity check.
864 */
set_orig_size(struct kmem_cache * s,void * object,unsigned int orig_size)865 static inline void set_orig_size(struct kmem_cache *s,
866 void *object, unsigned int orig_size)
867 {
868 void *p = kasan_reset_tag(object);
869
870 if (!slub_debug_orig_size(s))
871 return;
872
873 p += get_info_end(s);
874 p += sizeof(struct track) * 2;
875
876 *(unsigned int *)p = orig_size;
877 }
878
get_orig_size(struct kmem_cache * s,void * object)879 static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
880 {
881 void *p = kasan_reset_tag(object);
882
883 if (is_kfence_address(object))
884 return kfence_ksize(object);
885
886 if (!slub_debug_orig_size(s))
887 return s->object_size;
888
889 p += get_info_end(s);
890 p += sizeof(struct track) * 2;
891
892 return *(unsigned int *)p;
893 }
894
895 #ifdef CONFIG_SLUB_DEBUG
896
897 /*
898 * For debugging context when we want to check if the struct slab pointer
899 * appears to be valid.
900 */
validate_slab_ptr(struct slab * slab)901 static inline bool validate_slab_ptr(struct slab *slab)
902 {
903 return PageSlab(slab_page(slab));
904 }
905
906 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
907 static DEFINE_SPINLOCK(object_map_lock);
908
__fill_map(unsigned long * obj_map,struct kmem_cache * s,struct slab * slab)909 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
910 struct slab *slab)
911 {
912 void *addr = slab_address(slab);
913 void *p;
914
915 bitmap_zero(obj_map, slab->objects);
916
917 for (p = slab->freelist; p; p = get_freepointer(s, p))
918 set_bit(__obj_to_index(s, addr, p), obj_map);
919 }
920
921 #if IS_ENABLED(CONFIG_KUNIT)
slab_add_kunit_errors(void)922 static bool slab_add_kunit_errors(void)
923 {
924 struct kunit_resource *resource;
925
926 if (!kunit_get_current_test())
927 return false;
928
929 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
930 if (!resource)
931 return false;
932
933 (*(int *)resource->data)++;
934 kunit_put_resource(resource);
935 return true;
936 }
937
slab_in_kunit_test(void)938 bool slab_in_kunit_test(void)
939 {
940 struct kunit_resource *resource;
941
942 if (!kunit_get_current_test())
943 return false;
944
945 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
946 if (!resource)
947 return false;
948
949 kunit_put_resource(resource);
950 return true;
951 }
952 #else
slab_add_kunit_errors(void)953 static inline bool slab_add_kunit_errors(void) { return false; }
954 #endif
955
size_from_object(struct kmem_cache * s)956 static inline unsigned int size_from_object(struct kmem_cache *s)
957 {
958 if (s->flags & SLAB_RED_ZONE)
959 return s->size - s->red_left_pad;
960
961 return s->size;
962 }
963
restore_red_left(struct kmem_cache * s,void * p)964 static inline void *restore_red_left(struct kmem_cache *s, void *p)
965 {
966 if (s->flags & SLAB_RED_ZONE)
967 p -= s->red_left_pad;
968
969 return p;
970 }
971
972 /*
973 * Debug settings:
974 */
975 #if defined(CONFIG_SLUB_DEBUG_ON)
976 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
977 #else
978 static slab_flags_t slub_debug;
979 #endif
980
981 static char *slub_debug_string;
982 static int disable_higher_order_debug;
983
984 /*
985 * slub is about to manipulate internal object metadata. This memory lies
986 * outside the range of the allocated object, so accessing it would normally
987 * be reported by kasan as a bounds error. metadata_access_enable() is used
988 * to tell kasan that these accesses are OK.
989 */
metadata_access_enable(void)990 static inline void metadata_access_enable(void)
991 {
992 kasan_disable_current();
993 kmsan_disable_current();
994 }
995
metadata_access_disable(void)996 static inline void metadata_access_disable(void)
997 {
998 kmsan_enable_current();
999 kasan_enable_current();
1000 }
1001
1002 /*
1003 * Object debugging
1004 */
1005
1006 /* Verify that a pointer has an address that is valid within a slab page */
check_valid_pointer(struct kmem_cache * s,struct slab * slab,void * object)1007 static inline int check_valid_pointer(struct kmem_cache *s,
1008 struct slab *slab, void *object)
1009 {
1010 void *base;
1011
1012 if (!object)
1013 return 1;
1014
1015 base = slab_address(slab);
1016 object = kasan_reset_tag(object);
1017 object = restore_red_left(s, object);
1018 if (object < base || object >= base + slab->objects * s->size ||
1019 (object - base) % s->size) {
1020 return 0;
1021 }
1022
1023 return 1;
1024 }
1025
print_section(char * level,char * text,u8 * addr,unsigned int length)1026 static void print_section(char *level, char *text, u8 *addr,
1027 unsigned int length)
1028 {
1029 metadata_access_enable();
1030 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
1031 16, 1, kasan_reset_tag((void *)addr), length, 1);
1032 metadata_access_disable();
1033 }
1034
get_track(struct kmem_cache * s,void * object,enum track_item alloc)1035 static struct track *get_track(struct kmem_cache *s, void *object,
1036 enum track_item alloc)
1037 {
1038 struct track *p;
1039
1040 p = object + get_info_end(s);
1041
1042 return kasan_reset_tag(p + alloc);
1043 }
1044
1045 #ifdef CONFIG_STACKDEPOT
set_track_prepare(gfp_t gfp_flags)1046 static noinline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
1047 {
1048 depot_stack_handle_t handle;
1049 unsigned long entries[TRACK_ADDRS_COUNT];
1050 unsigned int nr_entries;
1051
1052 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
1053 handle = stack_depot_save(entries, nr_entries, gfp_flags);
1054
1055 return handle;
1056 }
1057 #else
set_track_prepare(gfp_t gfp_flags)1058 static inline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
1059 {
1060 return 0;
1061 }
1062 #endif
1063
set_track_update(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,depot_stack_handle_t handle)1064 static void set_track_update(struct kmem_cache *s, void *object,
1065 enum track_item alloc, unsigned long addr,
1066 depot_stack_handle_t handle)
1067 {
1068 struct track *p = get_track(s, object, alloc);
1069
1070 #ifdef CONFIG_STACKDEPOT
1071 p->handle = handle;
1072 #endif
1073 p->addr = addr;
1074 p->cpu = smp_processor_id();
1075 p->pid = current->pid;
1076 p->when = jiffies;
1077 }
1078
set_track(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,gfp_t gfp_flags)1079 static __always_inline void set_track(struct kmem_cache *s, void *object,
1080 enum track_item alloc, unsigned long addr, gfp_t gfp_flags)
1081 {
1082 depot_stack_handle_t handle = set_track_prepare(gfp_flags);
1083
1084 set_track_update(s, object, alloc, addr, handle);
1085 }
1086
init_tracking(struct kmem_cache * s,void * object)1087 static void init_tracking(struct kmem_cache *s, void *object)
1088 {
1089 struct track *p;
1090
1091 if (!(s->flags & SLAB_STORE_USER))
1092 return;
1093
1094 p = get_track(s, object, TRACK_ALLOC);
1095 memset(p, 0, 2*sizeof(struct track));
1096 }
1097
print_track(const char * s,struct track * t,unsigned long pr_time)1098 static void print_track(const char *s, struct track *t, unsigned long pr_time)
1099 {
1100 depot_stack_handle_t handle __maybe_unused;
1101
1102 if (!t->addr)
1103 return;
1104
1105 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
1106 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
1107 #ifdef CONFIG_STACKDEPOT
1108 handle = READ_ONCE(t->handle);
1109 if (handle)
1110 stack_depot_print(handle);
1111 else
1112 pr_err("object allocation/free stack trace missing\n");
1113 #endif
1114 }
1115
print_tracking(struct kmem_cache * s,void * object)1116 void print_tracking(struct kmem_cache *s, void *object)
1117 {
1118 unsigned long pr_time = jiffies;
1119 if (!(s->flags & SLAB_STORE_USER))
1120 return;
1121
1122 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
1123 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
1124 }
1125
print_slab_info(const struct slab * slab)1126 static void print_slab_info(const struct slab *slab)
1127 {
1128 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
1129 slab, slab->objects, slab->inuse, slab->freelist,
1130 &slab->flags.f);
1131 }
1132
skip_orig_size_check(struct kmem_cache * s,const void * object)1133 void skip_orig_size_check(struct kmem_cache *s, const void *object)
1134 {
1135 set_orig_size(s, (void *)object, s->object_size);
1136 }
1137
__slab_bug(struct kmem_cache * s,const char * fmt,va_list argsp)1138 static void __slab_bug(struct kmem_cache *s, const char *fmt, va_list argsp)
1139 {
1140 struct va_format vaf;
1141 va_list args;
1142
1143 va_copy(args, argsp);
1144 vaf.fmt = fmt;
1145 vaf.va = &args;
1146 pr_err("=============================================================================\n");
1147 pr_err("BUG %s (%s): %pV\n", s ? s->name : "<unknown>", print_tainted(), &vaf);
1148 pr_err("-----------------------------------------------------------------------------\n\n");
1149 va_end(args);
1150 }
1151
slab_bug(struct kmem_cache * s,const char * fmt,...)1152 static void slab_bug(struct kmem_cache *s, const char *fmt, ...)
1153 {
1154 va_list args;
1155
1156 va_start(args, fmt);
1157 __slab_bug(s, fmt, args);
1158 va_end(args);
1159 }
1160
1161 __printf(2, 3)
slab_fix(struct kmem_cache * s,const char * fmt,...)1162 static void slab_fix(struct kmem_cache *s, const char *fmt, ...)
1163 {
1164 struct va_format vaf;
1165 va_list args;
1166
1167 if (slab_add_kunit_errors())
1168 return;
1169
1170 va_start(args, fmt);
1171 vaf.fmt = fmt;
1172 vaf.va = &args;
1173 pr_err("FIX %s: %pV\n", s->name, &vaf);
1174 va_end(args);
1175 }
1176
print_trailer(struct kmem_cache * s,struct slab * slab,u8 * p)1177 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
1178 {
1179 unsigned int off; /* Offset of last byte */
1180 u8 *addr = slab_address(slab);
1181
1182 print_tracking(s, p);
1183
1184 print_slab_info(slab);
1185
1186 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
1187 p, p - addr, get_freepointer(s, p));
1188
1189 if (s->flags & SLAB_RED_ZONE)
1190 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
1191 s->red_left_pad);
1192 else if (p > addr + 16)
1193 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
1194
1195 print_section(KERN_ERR, "Object ", p,
1196 min_t(unsigned int, s->object_size, PAGE_SIZE));
1197 if (s->flags & SLAB_RED_ZONE)
1198 print_section(KERN_ERR, "Redzone ", p + s->object_size,
1199 s->inuse - s->object_size);
1200
1201 off = get_info_end(s);
1202
1203 if (s->flags & SLAB_STORE_USER)
1204 off += 2 * sizeof(struct track);
1205
1206 if (slub_debug_orig_size(s))
1207 off += sizeof(unsigned int);
1208
1209 off += kasan_metadata_size(s, false);
1210
1211 if (off != size_from_object(s))
1212 /* Beginning of the filler is the free pointer */
1213 print_section(KERN_ERR, "Padding ", p + off,
1214 size_from_object(s) - off);
1215 }
1216
object_err(struct kmem_cache * s,struct slab * slab,u8 * object,const char * reason)1217 static void object_err(struct kmem_cache *s, struct slab *slab,
1218 u8 *object, const char *reason)
1219 {
1220 if (slab_add_kunit_errors())
1221 return;
1222
1223 slab_bug(s, reason);
1224 if (!object || !check_valid_pointer(s, slab, object)) {
1225 print_slab_info(slab);
1226 pr_err("Invalid pointer 0x%p\n", object);
1227 } else {
1228 print_trailer(s, slab, object);
1229 }
1230 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1231
1232 WARN_ON(1);
1233 }
1234
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)1235 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1236 void **freelist, void *nextfree)
1237 {
1238 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
1239 !check_valid_pointer(s, slab, nextfree) && freelist) {
1240 object_err(s, slab, *freelist, "Freechain corrupt");
1241 *freelist = NULL;
1242 slab_fix(s, "Isolate corrupted freechain");
1243 return true;
1244 }
1245
1246 return false;
1247 }
1248
__slab_err(struct slab * slab)1249 static void __slab_err(struct slab *slab)
1250 {
1251 if (slab_in_kunit_test())
1252 return;
1253
1254 print_slab_info(slab);
1255 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1256
1257 WARN_ON(1);
1258 }
1259
slab_err(struct kmem_cache * s,struct slab * slab,const char * fmt,...)1260 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
1261 const char *fmt, ...)
1262 {
1263 va_list args;
1264
1265 if (slab_add_kunit_errors())
1266 return;
1267
1268 va_start(args, fmt);
1269 __slab_bug(s, fmt, args);
1270 va_end(args);
1271
1272 __slab_err(slab);
1273 }
1274
init_object(struct kmem_cache * s,void * object,u8 val)1275 static void init_object(struct kmem_cache *s, void *object, u8 val)
1276 {
1277 u8 *p = kasan_reset_tag(object);
1278 unsigned int poison_size = s->object_size;
1279
1280 if (s->flags & SLAB_RED_ZONE) {
1281 /*
1282 * Here and below, avoid overwriting the KMSAN shadow. Keeping
1283 * the shadow makes it possible to distinguish uninit-value
1284 * from use-after-free.
1285 */
1286 memset_no_sanitize_memory(p - s->red_left_pad, val,
1287 s->red_left_pad);
1288
1289 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1290 /*
1291 * Redzone the extra allocated space by kmalloc than
1292 * requested, and the poison size will be limited to
1293 * the original request size accordingly.
1294 */
1295 poison_size = get_orig_size(s, object);
1296 }
1297 }
1298
1299 if (s->flags & __OBJECT_POISON) {
1300 memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1);
1301 memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1);
1302 }
1303
1304 if (s->flags & SLAB_RED_ZONE)
1305 memset_no_sanitize_memory(p + poison_size, val,
1306 s->inuse - poison_size);
1307 }
1308
restore_bytes(struct kmem_cache * s,const char * message,u8 data,void * from,void * to)1309 static void restore_bytes(struct kmem_cache *s, const char *message, u8 data,
1310 void *from, void *to)
1311 {
1312 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
1313 memset(from, data, to - from);
1314 }
1315
1316 #ifdef CONFIG_KMSAN
1317 #define pad_check_attributes noinline __no_kmsan_checks
1318 #else
1319 #define pad_check_attributes
1320 #endif
1321
1322 static pad_check_attributes int
check_bytes_and_report(struct kmem_cache * s,struct slab * slab,u8 * object,const char * what,u8 * start,unsigned int value,unsigned int bytes,bool slab_obj_print)1323 check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
1324 u8 *object, const char *what, u8 *start, unsigned int value,
1325 unsigned int bytes, bool slab_obj_print)
1326 {
1327 u8 *fault;
1328 u8 *end;
1329 u8 *addr = slab_address(slab);
1330
1331 metadata_access_enable();
1332 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
1333 metadata_access_disable();
1334 if (!fault)
1335 return 1;
1336
1337 end = start + bytes;
1338 while (end > fault && end[-1] == value)
1339 end--;
1340
1341 if (slab_add_kunit_errors())
1342 goto skip_bug_print;
1343
1344 pr_err("[%s overwritten] 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
1345 what, fault, end - 1, fault - addr, fault[0], value);
1346
1347 if (slab_obj_print)
1348 object_err(s, slab, object, "Object corrupt");
1349
1350 skip_bug_print:
1351 restore_bytes(s, what, value, fault, end);
1352 return 0;
1353 }
1354
1355 /*
1356 * Object layout:
1357 *
1358 * object address
1359 * Bytes of the object to be managed.
1360 * If the freepointer may overlay the object then the free
1361 * pointer is at the middle of the object.
1362 *
1363 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
1364 * 0xa5 (POISON_END)
1365 *
1366 * object + s->object_size
1367 * Padding to reach word boundary. This is also used for Redzoning.
1368 * Padding is extended by another word if Redzoning is enabled and
1369 * object_size == inuse.
1370 *
1371 * We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with
1372 * 0xcc (SLUB_RED_ACTIVE) for objects in use.
1373 *
1374 * object + s->inuse
1375 * Meta data starts here.
1376 *
1377 * A. Free pointer (if we cannot overwrite object on free)
1378 * B. Tracking data for SLAB_STORE_USER
1379 * C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
1380 * D. Padding to reach required alignment boundary or at minimum
1381 * one word if debugging is on to be able to detect writes
1382 * before the word boundary.
1383 *
1384 * Padding is done using 0x5a (POISON_INUSE)
1385 *
1386 * object + s->size
1387 * Nothing is used beyond s->size.
1388 *
1389 * If slabcaches are merged then the object_size and inuse boundaries are mostly
1390 * ignored. And therefore no slab options that rely on these boundaries
1391 * may be used with merged slabcaches.
1392 */
1393
check_pad_bytes(struct kmem_cache * s,struct slab * slab,u8 * p)1394 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
1395 {
1396 unsigned long off = get_info_end(s); /* The end of info */
1397
1398 if (s->flags & SLAB_STORE_USER) {
1399 /* We also have user information there */
1400 off += 2 * sizeof(struct track);
1401
1402 if (s->flags & SLAB_KMALLOC)
1403 off += sizeof(unsigned int);
1404 }
1405
1406 off += kasan_metadata_size(s, false);
1407
1408 if (size_from_object(s) == off)
1409 return 1;
1410
1411 return check_bytes_and_report(s, slab, p, "Object padding",
1412 p + off, POISON_INUSE, size_from_object(s) - off, true);
1413 }
1414
1415 /* Check the pad bytes at the end of a slab page */
1416 static pad_check_attributes void
slab_pad_check(struct kmem_cache * s,struct slab * slab)1417 slab_pad_check(struct kmem_cache *s, struct slab *slab)
1418 {
1419 u8 *start;
1420 u8 *fault;
1421 u8 *end;
1422 u8 *pad;
1423 int length;
1424 int remainder;
1425
1426 if (!(s->flags & SLAB_POISON))
1427 return;
1428
1429 start = slab_address(slab);
1430 length = slab_size(slab);
1431 end = start + length;
1432 remainder = length % s->size;
1433 if (!remainder)
1434 return;
1435
1436 pad = end - remainder;
1437 metadata_access_enable();
1438 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
1439 metadata_access_disable();
1440 if (!fault)
1441 return;
1442 while (end > fault && end[-1] == POISON_INUSE)
1443 end--;
1444
1445 slab_bug(s, "Padding overwritten. 0x%p-0x%p @offset=%tu",
1446 fault, end - 1, fault - start);
1447 print_section(KERN_ERR, "Padding ", pad, remainder);
1448 __slab_err(slab);
1449
1450 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
1451 }
1452
check_object(struct kmem_cache * s,struct slab * slab,void * object,u8 val)1453 static int check_object(struct kmem_cache *s, struct slab *slab,
1454 void *object, u8 val)
1455 {
1456 u8 *p = object;
1457 u8 *endobject = object + s->object_size;
1458 unsigned int orig_size, kasan_meta_size;
1459 int ret = 1;
1460
1461 if (s->flags & SLAB_RED_ZONE) {
1462 if (!check_bytes_and_report(s, slab, object, "Left Redzone",
1463 object - s->red_left_pad, val, s->red_left_pad, ret))
1464 ret = 0;
1465
1466 if (!check_bytes_and_report(s, slab, object, "Right Redzone",
1467 endobject, val, s->inuse - s->object_size, ret))
1468 ret = 0;
1469
1470 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1471 orig_size = get_orig_size(s, object);
1472
1473 if (s->object_size > orig_size &&
1474 !check_bytes_and_report(s, slab, object,
1475 "kmalloc Redzone", p + orig_size,
1476 val, s->object_size - orig_size, ret)) {
1477 ret = 0;
1478 }
1479 }
1480 } else {
1481 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
1482 if (!check_bytes_and_report(s, slab, p, "Alignment padding",
1483 endobject, POISON_INUSE,
1484 s->inuse - s->object_size, ret))
1485 ret = 0;
1486 }
1487 }
1488
1489 if (s->flags & SLAB_POISON) {
1490 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) {
1491 /*
1492 * KASAN can save its free meta data inside of the
1493 * object at offset 0. Thus, skip checking the part of
1494 * the redzone that overlaps with the meta data.
1495 */
1496 kasan_meta_size = kasan_metadata_size(s, true);
1497 if (kasan_meta_size < s->object_size - 1 &&
1498 !check_bytes_and_report(s, slab, p, "Poison",
1499 p + kasan_meta_size, POISON_FREE,
1500 s->object_size - kasan_meta_size - 1, ret))
1501 ret = 0;
1502 if (kasan_meta_size < s->object_size &&
1503 !check_bytes_and_report(s, slab, p, "End Poison",
1504 p + s->object_size - 1, POISON_END, 1, ret))
1505 ret = 0;
1506 }
1507 /*
1508 * check_pad_bytes cleans up on its own.
1509 */
1510 if (!check_pad_bytes(s, slab, p))
1511 ret = 0;
1512 }
1513
1514 /*
1515 * Cannot check freepointer while object is allocated if
1516 * object and freepointer overlap.
1517 */
1518 if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
1519 !check_valid_pointer(s, slab, get_freepointer(s, p))) {
1520 object_err(s, slab, p, "Freepointer corrupt");
1521 /*
1522 * No choice but to zap it and thus lose the remainder
1523 * of the free objects in this slab. May cause
1524 * another error because the object count is now wrong.
1525 */
1526 set_freepointer(s, p, NULL);
1527 ret = 0;
1528 }
1529
1530 return ret;
1531 }
1532
1533 /*
1534 * Checks if the slab state looks sane. Assumes the struct slab pointer
1535 * was either obtained in a way that ensures it's valid, or validated
1536 * by validate_slab_ptr()
1537 */
check_slab(struct kmem_cache * s,struct slab * slab)1538 static int check_slab(struct kmem_cache *s, struct slab *slab)
1539 {
1540 int maxobj;
1541
1542 maxobj = order_objects(slab_order(slab), s->size);
1543 if (slab->objects > maxobj) {
1544 slab_err(s, slab, "objects %u > max %u",
1545 slab->objects, maxobj);
1546 return 0;
1547 }
1548 if (slab->inuse > slab->objects) {
1549 slab_err(s, slab, "inuse %u > max %u",
1550 slab->inuse, slab->objects);
1551 return 0;
1552 }
1553 if (slab->frozen) {
1554 slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
1555 return 0;
1556 }
1557
1558 /* Slab_pad_check fixes things up after itself */
1559 slab_pad_check(s, slab);
1560 return 1;
1561 }
1562
1563 /*
1564 * Determine if a certain object in a slab is on the freelist. Must hold the
1565 * slab lock to guarantee that the chains are in a consistent state.
1566 */
on_freelist(struct kmem_cache * s,struct slab * slab,void * search)1567 static bool on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
1568 {
1569 int nr = 0;
1570 void *fp;
1571 void *object = NULL;
1572 int max_objects;
1573
1574 fp = slab->freelist;
1575 while (fp && nr <= slab->objects) {
1576 if (fp == search)
1577 return true;
1578 if (!check_valid_pointer(s, slab, fp)) {
1579 if (object) {
1580 object_err(s, slab, object,
1581 "Freechain corrupt");
1582 set_freepointer(s, object, NULL);
1583 break;
1584 } else {
1585 slab_err(s, slab, "Freepointer corrupt");
1586 slab->freelist = NULL;
1587 slab->inuse = slab->objects;
1588 slab_fix(s, "Freelist cleared");
1589 return false;
1590 }
1591 }
1592 object = fp;
1593 fp = get_freepointer(s, object);
1594 nr++;
1595 }
1596
1597 if (nr > slab->objects) {
1598 slab_err(s, slab, "Freelist cycle detected");
1599 slab->freelist = NULL;
1600 slab->inuse = slab->objects;
1601 slab_fix(s, "Freelist cleared");
1602 return false;
1603 }
1604
1605 max_objects = order_objects(slab_order(slab), s->size);
1606 if (max_objects > MAX_OBJS_PER_PAGE)
1607 max_objects = MAX_OBJS_PER_PAGE;
1608
1609 if (slab->objects != max_objects) {
1610 slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1611 slab->objects, max_objects);
1612 slab->objects = max_objects;
1613 slab_fix(s, "Number of objects adjusted");
1614 }
1615 if (slab->inuse != slab->objects - nr) {
1616 slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1617 slab->inuse, slab->objects - nr);
1618 slab->inuse = slab->objects - nr;
1619 slab_fix(s, "Object count adjusted");
1620 }
1621 return search == NULL;
1622 }
1623
trace(struct kmem_cache * s,struct slab * slab,void * object,int alloc)1624 static void trace(struct kmem_cache *s, struct slab *slab, void *object,
1625 int alloc)
1626 {
1627 if (s->flags & SLAB_TRACE) {
1628 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1629 s->name,
1630 alloc ? "alloc" : "free",
1631 object, slab->inuse,
1632 slab->freelist);
1633
1634 if (!alloc)
1635 print_section(KERN_INFO, "Object ", (void *)object,
1636 s->object_size);
1637
1638 dump_stack();
1639 }
1640 }
1641
1642 /*
1643 * Tracking of fully allocated slabs for debugging purposes.
1644 */
add_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1645 static void add_full(struct kmem_cache *s,
1646 struct kmem_cache_node *n, struct slab *slab)
1647 {
1648 if (!(s->flags & SLAB_STORE_USER))
1649 return;
1650
1651 lockdep_assert_held(&n->list_lock);
1652 list_add(&slab->slab_list, &n->full);
1653 }
1654
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1655 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
1656 {
1657 if (!(s->flags & SLAB_STORE_USER))
1658 return;
1659
1660 lockdep_assert_held(&n->list_lock);
1661 list_del(&slab->slab_list);
1662 }
1663
node_nr_slabs(struct kmem_cache_node * n)1664 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1665 {
1666 return atomic_long_read(&n->nr_slabs);
1667 }
1668
inc_slabs_node(struct kmem_cache * s,int node,int objects)1669 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1670 {
1671 struct kmem_cache_node *n = get_node(s, node);
1672
1673 atomic_long_inc(&n->nr_slabs);
1674 atomic_long_add(objects, &n->total_objects);
1675 }
dec_slabs_node(struct kmem_cache * s,int node,int objects)1676 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1677 {
1678 struct kmem_cache_node *n = get_node(s, node);
1679
1680 atomic_long_dec(&n->nr_slabs);
1681 atomic_long_sub(objects, &n->total_objects);
1682 }
1683
1684 /* Object debug checks for alloc/free paths */
setup_object_debug(struct kmem_cache * s,void * object)1685 static void setup_object_debug(struct kmem_cache *s, void *object)
1686 {
1687 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1688 return;
1689
1690 init_object(s, object, SLUB_RED_INACTIVE);
1691 init_tracking(s, object);
1692 }
1693
1694 static
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1695 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
1696 {
1697 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1698 return;
1699
1700 metadata_access_enable();
1701 memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
1702 metadata_access_disable();
1703 }
1704
alloc_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object)1705 static inline int alloc_consistency_checks(struct kmem_cache *s,
1706 struct slab *slab, void *object)
1707 {
1708 if (!check_slab(s, slab))
1709 return 0;
1710
1711 if (!check_valid_pointer(s, slab, object)) {
1712 object_err(s, slab, object, "Freelist Pointer check fails");
1713 return 0;
1714 }
1715
1716 if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
1717 return 0;
1718
1719 return 1;
1720 }
1721
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1722 static noinline bool alloc_debug_processing(struct kmem_cache *s,
1723 struct slab *slab, void *object, int orig_size)
1724 {
1725 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1726 if (!alloc_consistency_checks(s, slab, object))
1727 goto bad;
1728 }
1729
1730 /* Success. Perform special debug activities for allocs */
1731 trace(s, slab, object, 1);
1732 set_orig_size(s, object, orig_size);
1733 init_object(s, object, SLUB_RED_ACTIVE);
1734 return true;
1735
1736 bad:
1737 /*
1738 * Let's do the best we can to avoid issues in the future. Marking all
1739 * objects as used avoids touching the remaining objects.
1740 */
1741 slab_fix(s, "Marking all objects used");
1742 slab->inuse = slab->objects;
1743 slab->freelist = NULL;
1744 slab->frozen = 1; /* mark consistency-failed slab as frozen */
1745
1746 return false;
1747 }
1748
free_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object,unsigned long addr)1749 static inline int free_consistency_checks(struct kmem_cache *s,
1750 struct slab *slab, void *object, unsigned long addr)
1751 {
1752 if (!check_valid_pointer(s, slab, object)) {
1753 slab_err(s, slab, "Invalid object pointer 0x%p", object);
1754 return 0;
1755 }
1756
1757 if (on_freelist(s, slab, object)) {
1758 object_err(s, slab, object, "Object already free");
1759 return 0;
1760 }
1761
1762 if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
1763 return 0;
1764
1765 if (unlikely(s != slab->slab_cache)) {
1766 if (!slab->slab_cache) {
1767 slab_err(NULL, slab, "No slab cache for object 0x%p",
1768 object);
1769 } else {
1770 object_err(s, slab, object,
1771 "page slab pointer corrupt.");
1772 }
1773 return 0;
1774 }
1775 return 1;
1776 }
1777
1778 /*
1779 * Parse a block of slab_debug options. Blocks are delimited by ';'
1780 *
1781 * @str: start of block
1782 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1783 * @slabs: return start of list of slabs, or NULL when there's no list
1784 * @init: assume this is initial parsing and not per-kmem-create parsing
1785 *
1786 * returns the start of next block if there's any, or NULL
1787 */
1788 static char *
parse_slub_debug_flags(char * str,slab_flags_t * flags,char ** slabs,bool init)1789 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1790 {
1791 bool higher_order_disable = false;
1792
1793 /* Skip any completely empty blocks */
1794 while (*str && *str == ';')
1795 str++;
1796
1797 if (*str == ',') {
1798 /*
1799 * No options but restriction on slabs. This means full
1800 * debugging for slabs matching a pattern.
1801 */
1802 *flags = DEBUG_DEFAULT_FLAGS;
1803 goto check_slabs;
1804 }
1805 *flags = 0;
1806
1807 /* Determine which debug features should be switched on */
1808 for (; *str && *str != ',' && *str != ';'; str++) {
1809 switch (tolower(*str)) {
1810 case '-':
1811 *flags = 0;
1812 break;
1813 case 'f':
1814 *flags |= SLAB_CONSISTENCY_CHECKS;
1815 break;
1816 case 'z':
1817 *flags |= SLAB_RED_ZONE;
1818 break;
1819 case 'p':
1820 *flags |= SLAB_POISON;
1821 break;
1822 case 'u':
1823 *flags |= SLAB_STORE_USER;
1824 break;
1825 case 't':
1826 *flags |= SLAB_TRACE;
1827 break;
1828 case 'a':
1829 *flags |= SLAB_FAILSLAB;
1830 break;
1831 case 'o':
1832 /*
1833 * Avoid enabling debugging on caches if its minimum
1834 * order would increase as a result.
1835 */
1836 higher_order_disable = true;
1837 break;
1838 default:
1839 if (init)
1840 pr_err("slab_debug option '%c' unknown. skipped\n", *str);
1841 }
1842 }
1843 check_slabs:
1844 if (*str == ',')
1845 *slabs = ++str;
1846 else
1847 *slabs = NULL;
1848
1849 /* Skip over the slab list */
1850 while (*str && *str != ';')
1851 str++;
1852
1853 /* Skip any completely empty blocks */
1854 while (*str && *str == ';')
1855 str++;
1856
1857 if (init && higher_order_disable)
1858 disable_higher_order_debug = 1;
1859
1860 if (*str)
1861 return str;
1862 else
1863 return NULL;
1864 }
1865
setup_slub_debug(char * str)1866 static int __init setup_slub_debug(char *str)
1867 {
1868 slab_flags_t flags;
1869 slab_flags_t global_flags;
1870 char *saved_str;
1871 char *slab_list;
1872 bool global_slub_debug_changed = false;
1873 bool slab_list_specified = false;
1874
1875 global_flags = DEBUG_DEFAULT_FLAGS;
1876 if (*str++ != '=' || !*str)
1877 /*
1878 * No options specified. Switch on full debugging.
1879 */
1880 goto out;
1881
1882 saved_str = str;
1883 while (str) {
1884 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1885
1886 if (!slab_list) {
1887 global_flags = flags;
1888 global_slub_debug_changed = true;
1889 } else {
1890 slab_list_specified = true;
1891 if (flags & SLAB_STORE_USER)
1892 stack_depot_request_early_init();
1893 }
1894 }
1895
1896 /*
1897 * For backwards compatibility, a single list of flags with list of
1898 * slabs means debugging is only changed for those slabs, so the global
1899 * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1900 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
1901 * long as there is no option specifying flags without a slab list.
1902 */
1903 if (slab_list_specified) {
1904 if (!global_slub_debug_changed)
1905 global_flags = slub_debug;
1906 slub_debug_string = saved_str;
1907 }
1908 out:
1909 slub_debug = global_flags;
1910 if (slub_debug & SLAB_STORE_USER)
1911 stack_depot_request_early_init();
1912 if (slub_debug != 0 || slub_debug_string)
1913 static_branch_enable(&slub_debug_enabled);
1914 else
1915 static_branch_disable(&slub_debug_enabled);
1916 if ((static_branch_unlikely(&init_on_alloc) ||
1917 static_branch_unlikely(&init_on_free)) &&
1918 (slub_debug & SLAB_POISON))
1919 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1920 return 1;
1921 }
1922
1923 __setup("slab_debug", setup_slub_debug);
1924 __setup_param("slub_debug", slub_debug, setup_slub_debug, 0);
1925
1926 /*
1927 * kmem_cache_flags - apply debugging options to the cache
1928 * @flags: flags to set
1929 * @name: name of the cache
1930 *
1931 * Debug option(s) are applied to @flags. In addition to the debug
1932 * option(s), if a slab name (or multiple) is specified i.e.
1933 * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1934 * then only the select slabs will receive the debug option(s).
1935 */
kmem_cache_flags(slab_flags_t flags,const char * name)1936 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1937 {
1938 char *iter;
1939 size_t len;
1940 char *next_block;
1941 slab_flags_t block_flags;
1942 slab_flags_t slub_debug_local = slub_debug;
1943
1944 if (flags & SLAB_NO_USER_FLAGS)
1945 return flags;
1946
1947 /*
1948 * If the slab cache is for debugging (e.g. kmemleak) then
1949 * don't store user (stack trace) information by default,
1950 * but let the user enable it via the command line below.
1951 */
1952 if (flags & SLAB_NOLEAKTRACE)
1953 slub_debug_local &= ~SLAB_STORE_USER;
1954
1955 len = strlen(name);
1956 next_block = slub_debug_string;
1957 /* Go through all blocks of debug options, see if any matches our slab's name */
1958 while (next_block) {
1959 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1960 if (!iter)
1961 continue;
1962 /* Found a block that has a slab list, search it */
1963 while (*iter) {
1964 char *end, *glob;
1965 size_t cmplen;
1966
1967 end = strchrnul(iter, ',');
1968 if (next_block && next_block < end)
1969 end = next_block - 1;
1970
1971 glob = strnchr(iter, end - iter, '*');
1972 if (glob)
1973 cmplen = glob - iter;
1974 else
1975 cmplen = max_t(size_t, len, (end - iter));
1976
1977 if (!strncmp(name, iter, cmplen)) {
1978 flags |= block_flags;
1979 return flags;
1980 }
1981
1982 if (!*end || *end == ';')
1983 break;
1984 iter = end + 1;
1985 }
1986 }
1987
1988 return flags | slub_debug_local;
1989 }
1990 #else /* !CONFIG_SLUB_DEBUG */
setup_object_debug(struct kmem_cache * s,void * object)1991 static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
1992 static inline
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1993 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
1994
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1995 static inline bool alloc_debug_processing(struct kmem_cache *s,
1996 struct slab *slab, void *object, int orig_size) { return true; }
1997
free_debug_processing(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int * bulk_cnt,unsigned long addr,depot_stack_handle_t handle)1998 static inline bool free_debug_processing(struct kmem_cache *s,
1999 struct slab *slab, void *head, void *tail, int *bulk_cnt,
2000 unsigned long addr, depot_stack_handle_t handle) { return true; }
2001
slab_pad_check(struct kmem_cache * s,struct slab * slab)2002 static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {}
check_object(struct kmem_cache * s,struct slab * slab,void * object,u8 val)2003 static inline int check_object(struct kmem_cache *s, struct slab *slab,
2004 void *object, u8 val) { return 1; }
set_track_prepare(gfp_t gfp_flags)2005 static inline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags) { return 0; }
set_track(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,gfp_t gfp_flags)2006 static inline void set_track(struct kmem_cache *s, void *object,
2007 enum track_item alloc, unsigned long addr, gfp_t gfp_flags) {}
add_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)2008 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
2009 struct slab *slab) {}
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)2010 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
2011 struct slab *slab) {}
kmem_cache_flags(slab_flags_t flags,const char * name)2012 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
2013 {
2014 return flags;
2015 }
2016 #define slub_debug 0
2017
2018 #define disable_higher_order_debug 0
2019
node_nr_slabs(struct kmem_cache_node * n)2020 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
2021 { return 0; }
inc_slabs_node(struct kmem_cache * s,int node,int objects)2022 static inline void inc_slabs_node(struct kmem_cache *s, int node,
2023 int objects) {}
dec_slabs_node(struct kmem_cache * s,int node,int objects)2024 static inline void dec_slabs_node(struct kmem_cache *s, int node,
2025 int objects) {}
2026 #ifndef CONFIG_SLUB_TINY
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)2027 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
2028 void **freelist, void *nextfree)
2029 {
2030 return false;
2031 }
2032 #endif
2033 #endif /* CONFIG_SLUB_DEBUG */
2034
2035 #ifdef CONFIG_SLAB_OBJ_EXT
2036
2037 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
2038
mark_objexts_empty(struct slabobj_ext * obj_exts)2039 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts)
2040 {
2041 struct slabobj_ext *slab_exts;
2042 struct slab *obj_exts_slab;
2043
2044 obj_exts_slab = virt_to_slab(obj_exts);
2045 slab_exts = slab_obj_exts(obj_exts_slab);
2046 if (slab_exts) {
2047 unsigned int offs = obj_to_index(obj_exts_slab->slab_cache,
2048 obj_exts_slab, obj_exts);
2049
2050 if (unlikely(is_codetag_empty(&slab_exts[offs].ref)))
2051 return;
2052
2053 /* codetag should be NULL here */
2054 WARN_ON(slab_exts[offs].ref.ct);
2055 set_codetag_empty(&slab_exts[offs].ref);
2056 }
2057 }
2058
mark_failed_objexts_alloc(struct slab * slab)2059 static inline bool mark_failed_objexts_alloc(struct slab *slab)
2060 {
2061 return cmpxchg(&slab->obj_exts, 0, OBJEXTS_ALLOC_FAIL) == 0;
2062 }
2063
handle_failed_objexts_alloc(unsigned long obj_exts,struct slabobj_ext * vec,unsigned int objects)2064 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
2065 struct slabobj_ext *vec, unsigned int objects)
2066 {
2067 /*
2068 * If vector previously failed to allocate then we have live
2069 * objects with no tag reference. Mark all references in this
2070 * vector as empty to avoid warnings later on.
2071 */
2072 if (obj_exts == OBJEXTS_ALLOC_FAIL) {
2073 unsigned int i;
2074
2075 for (i = 0; i < objects; i++)
2076 set_codetag_empty(&vec[i].ref);
2077 }
2078 }
2079
2080 #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2081
mark_objexts_empty(struct slabobj_ext * obj_exts)2082 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) {}
mark_failed_objexts_alloc(struct slab * slab)2083 static inline bool mark_failed_objexts_alloc(struct slab *slab) { return false; }
handle_failed_objexts_alloc(unsigned long obj_exts,struct slabobj_ext * vec,unsigned int objects)2084 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
2085 struct slabobj_ext *vec, unsigned int objects) {}
2086
2087 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2088
2089 /*
2090 * The allocated objcg pointers array is not accounted directly.
2091 * Moreover, it should not come from DMA buffer and is not readily
2092 * reclaimable. So those GFP bits should be masked off.
2093 */
2094 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
2095 __GFP_ACCOUNT | __GFP_NOFAIL)
2096
init_slab_obj_exts(struct slab * slab)2097 static inline void init_slab_obj_exts(struct slab *slab)
2098 {
2099 slab->obj_exts = 0;
2100 }
2101
alloc_slab_obj_exts(struct slab * slab,struct kmem_cache * s,gfp_t gfp,bool new_slab)2102 int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2103 gfp_t gfp, bool new_slab)
2104 {
2105 bool allow_spin = gfpflags_allow_spinning(gfp);
2106 unsigned int objects = objs_per_slab(s, slab);
2107 unsigned long new_exts;
2108 unsigned long old_exts;
2109 struct slabobj_ext *vec;
2110
2111 gfp &= ~OBJCGS_CLEAR_MASK;
2112 /* Prevent recursive extension vector allocation */
2113 gfp |= __GFP_NO_OBJ_EXT;
2114
2115 /*
2116 * Note that allow_spin may be false during early boot and its
2117 * restricted GFP_BOOT_MASK. Due to kmalloc_nolock() only supporting
2118 * architectures with cmpxchg16b, early obj_exts will be missing for
2119 * very early allocations on those.
2120 */
2121 if (unlikely(!allow_spin)) {
2122 size_t sz = objects * sizeof(struct slabobj_ext);
2123
2124 vec = kmalloc_nolock(sz, __GFP_ZERO | __GFP_NO_OBJ_EXT,
2125 slab_nid(slab));
2126 } else {
2127 vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp,
2128 slab_nid(slab));
2129 }
2130 if (!vec) {
2131 /*
2132 * Try to mark vectors which failed to allocate.
2133 * If this operation fails, there may be a racing process
2134 * that has already completed the allocation.
2135 */
2136 if (!mark_failed_objexts_alloc(slab) &&
2137 slab_obj_exts(slab))
2138 return 0;
2139
2140 return -ENOMEM;
2141 }
2142
2143 new_exts = (unsigned long)vec;
2144 if (unlikely(!allow_spin))
2145 new_exts |= OBJEXTS_NOSPIN_ALLOC;
2146 #ifdef CONFIG_MEMCG
2147 new_exts |= MEMCG_DATA_OBJEXTS;
2148 #endif
2149 retry:
2150 old_exts = READ_ONCE(slab->obj_exts);
2151 handle_failed_objexts_alloc(old_exts, vec, objects);
2152 if (new_slab) {
2153 /*
2154 * If the slab is brand new and nobody can yet access its
2155 * obj_exts, no synchronization is required and obj_exts can
2156 * be simply assigned.
2157 */
2158 slab->obj_exts = new_exts;
2159 } else if (old_exts & ~OBJEXTS_FLAGS_MASK) {
2160 /*
2161 * If the slab is already in use, somebody can allocate and
2162 * assign slabobj_exts in parallel. In this case the existing
2163 * objcg vector should be reused.
2164 */
2165 mark_objexts_empty(vec);
2166 if (unlikely(!allow_spin))
2167 kfree_nolock(vec);
2168 else
2169 kfree(vec);
2170 return 0;
2171 } else if (cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) {
2172 /* Retry if a racing thread changed slab->obj_exts from under us. */
2173 goto retry;
2174 }
2175
2176 if (allow_spin)
2177 kmemleak_not_leak(vec);
2178 return 0;
2179 }
2180
free_slab_obj_exts(struct slab * slab)2181 static inline void free_slab_obj_exts(struct slab *slab)
2182 {
2183 struct slabobj_ext *obj_exts;
2184
2185 obj_exts = slab_obj_exts(slab);
2186 if (!obj_exts) {
2187 /*
2188 * If obj_exts allocation failed, slab->obj_exts is set to
2189 * OBJEXTS_ALLOC_FAIL. In this case, we end up here and should
2190 * clear the flag.
2191 */
2192 slab->obj_exts = 0;
2193 return;
2194 }
2195
2196 /*
2197 * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its
2198 * corresponding extension will be NULL. alloc_tag_sub() will throw a
2199 * warning if slab has extensions but the extension of an object is
2200 * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that
2201 * the extension for obj_exts is expected to be NULL.
2202 */
2203 mark_objexts_empty(obj_exts);
2204 if (unlikely(READ_ONCE(slab->obj_exts) & OBJEXTS_NOSPIN_ALLOC))
2205 kfree_nolock(obj_exts);
2206 else
2207 kfree(obj_exts);
2208 slab->obj_exts = 0;
2209 }
2210
2211 #else /* CONFIG_SLAB_OBJ_EXT */
2212
init_slab_obj_exts(struct slab * slab)2213 static inline void init_slab_obj_exts(struct slab *slab)
2214 {
2215 }
2216
alloc_slab_obj_exts(struct slab * slab,struct kmem_cache * s,gfp_t gfp,bool new_slab)2217 static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2218 gfp_t gfp, bool new_slab)
2219 {
2220 return 0;
2221 }
2222
free_slab_obj_exts(struct slab * slab)2223 static inline void free_slab_obj_exts(struct slab *slab)
2224 {
2225 }
2226
2227 #endif /* CONFIG_SLAB_OBJ_EXT */
2228
2229 #ifdef CONFIG_MEM_ALLOC_PROFILING
2230
2231 static inline struct slabobj_ext *
prepare_slab_obj_exts_hook(struct kmem_cache * s,gfp_t flags,void * p)2232 prepare_slab_obj_exts_hook(struct kmem_cache *s, gfp_t flags, void *p)
2233 {
2234 struct slab *slab;
2235
2236 slab = virt_to_slab(p);
2237 if (!slab_obj_exts(slab) &&
2238 alloc_slab_obj_exts(slab, s, flags, false)) {
2239 pr_warn_once("%s, %s: Failed to create slab extension vector!\n",
2240 __func__, s->name);
2241 return NULL;
2242 }
2243
2244 return slab_obj_exts(slab) + obj_to_index(s, slab, p);
2245 }
2246
2247 /* Should be called only if mem_alloc_profiling_enabled() */
2248 static noinline void
__alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2249 __alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2250 {
2251 struct slabobj_ext *obj_exts;
2252
2253 if (!object)
2254 return;
2255
2256 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2257 return;
2258
2259 if (flags & __GFP_NO_OBJ_EXT)
2260 return;
2261
2262 obj_exts = prepare_slab_obj_exts_hook(s, flags, object);
2263 /*
2264 * Currently obj_exts is used only for allocation profiling.
2265 * If other users appear then mem_alloc_profiling_enabled()
2266 * check should be added before alloc_tag_add().
2267 */
2268 if (likely(obj_exts))
2269 alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size);
2270 else
2271 alloc_tag_set_inaccurate(current->alloc_tag);
2272 }
2273
2274 static inline void
alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2275 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2276 {
2277 if (mem_alloc_profiling_enabled())
2278 __alloc_tagging_slab_alloc_hook(s, object, flags);
2279 }
2280
2281 /* Should be called only if mem_alloc_profiling_enabled() */
2282 static noinline void
__alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2283 __alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2284 int objects)
2285 {
2286 struct slabobj_ext *obj_exts;
2287 int i;
2288
2289 /* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */
2290 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2291 return;
2292
2293 obj_exts = slab_obj_exts(slab);
2294 if (!obj_exts)
2295 return;
2296
2297 for (i = 0; i < objects; i++) {
2298 unsigned int off = obj_to_index(s, slab, p[i]);
2299
2300 alloc_tag_sub(&obj_exts[off].ref, s->size);
2301 }
2302 }
2303
2304 static inline void
alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2305 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2306 int objects)
2307 {
2308 if (mem_alloc_profiling_enabled())
2309 __alloc_tagging_slab_free_hook(s, slab, p, objects);
2310 }
2311
2312 #else /* CONFIG_MEM_ALLOC_PROFILING */
2313
2314 static inline void
alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2315 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2316 {
2317 }
2318
2319 static inline void
alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2320 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2321 int objects)
2322 {
2323 }
2324
2325 #endif /* CONFIG_MEM_ALLOC_PROFILING */
2326
2327
2328 #ifdef CONFIG_MEMCG
2329
2330 static void memcg_alloc_abort_single(struct kmem_cache *s, void *object);
2331
2332 static __fastpath_inline
memcg_slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p)2333 bool memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
2334 gfp_t flags, size_t size, void **p)
2335 {
2336 if (likely(!memcg_kmem_online()))
2337 return true;
2338
2339 if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT)))
2340 return true;
2341
2342 if (likely(__memcg_slab_post_alloc_hook(s, lru, flags, size, p)))
2343 return true;
2344
2345 if (likely(size == 1)) {
2346 memcg_alloc_abort_single(s, *p);
2347 *p = NULL;
2348 } else {
2349 kmem_cache_free_bulk(s, size, p);
2350 }
2351
2352 return false;
2353 }
2354
2355 static __fastpath_inline
memcg_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2356 void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2357 int objects)
2358 {
2359 struct slabobj_ext *obj_exts;
2360
2361 if (!memcg_kmem_online())
2362 return;
2363
2364 obj_exts = slab_obj_exts(slab);
2365 if (likely(!obj_exts))
2366 return;
2367
2368 __memcg_slab_free_hook(s, slab, p, objects, obj_exts);
2369 }
2370
2371 static __fastpath_inline
memcg_slab_post_charge(void * p,gfp_t flags)2372 bool memcg_slab_post_charge(void *p, gfp_t flags)
2373 {
2374 struct slabobj_ext *slab_exts;
2375 struct kmem_cache *s;
2376 struct folio *folio;
2377 struct slab *slab;
2378 unsigned long off;
2379
2380 folio = virt_to_folio(p);
2381 if (!folio_test_slab(folio)) {
2382 int size;
2383
2384 if (folio_memcg_kmem(folio))
2385 return true;
2386
2387 if (__memcg_kmem_charge_page(folio_page(folio, 0), flags,
2388 folio_order(folio)))
2389 return false;
2390
2391 /*
2392 * This folio has already been accounted in the global stats but
2393 * not in the memcg stats. So, subtract from the global and use
2394 * the interface which adds to both global and memcg stats.
2395 */
2396 size = folio_size(folio);
2397 node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size);
2398 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size);
2399 return true;
2400 }
2401
2402 slab = folio_slab(folio);
2403 s = slab->slab_cache;
2404
2405 /*
2406 * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency
2407 * of slab_obj_exts being allocated from the same slab and thus the slab
2408 * becoming effectively unfreeable.
2409 */
2410 if (is_kmalloc_normal(s))
2411 return true;
2412
2413 /* Ignore already charged objects. */
2414 slab_exts = slab_obj_exts(slab);
2415 if (slab_exts) {
2416 off = obj_to_index(s, slab, p);
2417 if (unlikely(slab_exts[off].objcg))
2418 return true;
2419 }
2420
2421 return __memcg_slab_post_alloc_hook(s, NULL, flags, 1, &p);
2422 }
2423
2424 #else /* CONFIG_MEMCG */
memcg_slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p)2425 static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s,
2426 struct list_lru *lru,
2427 gfp_t flags, size_t size,
2428 void **p)
2429 {
2430 return true;
2431 }
2432
memcg_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2433 static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
2434 void **p, int objects)
2435 {
2436 }
2437
memcg_slab_post_charge(void * p,gfp_t flags)2438 static inline bool memcg_slab_post_charge(void *p, gfp_t flags)
2439 {
2440 return true;
2441 }
2442 #endif /* CONFIG_MEMCG */
2443
2444 #ifdef CONFIG_SLUB_RCU_DEBUG
2445 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head);
2446
2447 struct rcu_delayed_free {
2448 struct rcu_head head;
2449 void *object;
2450 };
2451 #endif
2452
2453 /*
2454 * Hooks for other subsystems that check memory allocations. In a typical
2455 * production configuration these hooks all should produce no code at all.
2456 *
2457 * Returns true if freeing of the object can proceed, false if its reuse
2458 * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned
2459 * to KFENCE.
2460 */
2461 static __always_inline
slab_free_hook(struct kmem_cache * s,void * x,bool init,bool after_rcu_delay)2462 bool slab_free_hook(struct kmem_cache *s, void *x, bool init,
2463 bool after_rcu_delay)
2464 {
2465 /* Are the object contents still accessible? */
2466 bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
2467
2468 kmemleak_free_recursive(x, s->flags);
2469 kmsan_slab_free(s, x);
2470
2471 debug_check_no_locks_freed(x, s->object_size);
2472
2473 if (!(s->flags & SLAB_DEBUG_OBJECTS))
2474 debug_check_no_obj_freed(x, s->object_size);
2475
2476 /* Use KCSAN to help debug racy use-after-free. */
2477 if (!still_accessible)
2478 __kcsan_check_access(x, s->object_size,
2479 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
2480
2481 if (kfence_free(x))
2482 return false;
2483
2484 /*
2485 * Give KASAN a chance to notice an invalid free operation before we
2486 * modify the object.
2487 */
2488 if (kasan_slab_pre_free(s, x))
2489 return false;
2490
2491 #ifdef CONFIG_SLUB_RCU_DEBUG
2492 if (still_accessible) {
2493 struct rcu_delayed_free *delayed_free;
2494
2495 delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT);
2496 if (delayed_free) {
2497 /*
2498 * Let KASAN track our call stack as a "related work
2499 * creation", just like if the object had been freed
2500 * normally via kfree_rcu().
2501 * We have to do this manually because the rcu_head is
2502 * not located inside the object.
2503 */
2504 kasan_record_aux_stack(x);
2505
2506 delayed_free->object = x;
2507 call_rcu(&delayed_free->head, slab_free_after_rcu_debug);
2508 return false;
2509 }
2510 }
2511 #endif /* CONFIG_SLUB_RCU_DEBUG */
2512
2513 /*
2514 * As memory initialization might be integrated into KASAN,
2515 * kasan_slab_free and initialization memset's must be
2516 * kept together to avoid discrepancies in behavior.
2517 *
2518 * The initialization memset's clear the object and the metadata,
2519 * but don't touch the SLAB redzone.
2520 *
2521 * The object's freepointer is also avoided if stored outside the
2522 * object.
2523 */
2524 if (unlikely(init)) {
2525 int rsize;
2526 unsigned int inuse, orig_size;
2527
2528 inuse = get_info_end(s);
2529 orig_size = get_orig_size(s, x);
2530 if (!kasan_has_integrated_init())
2531 memset(kasan_reset_tag(x), 0, orig_size);
2532 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
2533 memset((char *)kasan_reset_tag(x) + inuse, 0,
2534 s->size - inuse - rsize);
2535 /*
2536 * Restore orig_size, otherwize kmalloc redzone overwritten
2537 * would be reported
2538 */
2539 set_orig_size(s, x, orig_size);
2540
2541 }
2542 /* KASAN might put x into memory quarantine, delaying its reuse. */
2543 return !kasan_slab_free(s, x, init, still_accessible, false);
2544 }
2545
2546 static __fastpath_inline
slab_free_freelist_hook(struct kmem_cache * s,void ** head,void ** tail,int * cnt)2547 bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail,
2548 int *cnt)
2549 {
2550
2551 void *object;
2552 void *next = *head;
2553 void *old_tail = *tail;
2554 bool init;
2555
2556 if (is_kfence_address(next)) {
2557 slab_free_hook(s, next, false, false);
2558 return false;
2559 }
2560
2561 /* Head and tail of the reconstructed freelist */
2562 *head = NULL;
2563 *tail = NULL;
2564
2565 init = slab_want_init_on_free(s);
2566
2567 do {
2568 object = next;
2569 next = get_freepointer(s, object);
2570
2571 /* If object's reuse doesn't have to be delayed */
2572 if (likely(slab_free_hook(s, object, init, false))) {
2573 /* Move object to the new freelist */
2574 set_freepointer(s, object, *head);
2575 *head = object;
2576 if (!*tail)
2577 *tail = object;
2578 } else {
2579 /*
2580 * Adjust the reconstructed freelist depth
2581 * accordingly if object's reuse is delayed.
2582 */
2583 --(*cnt);
2584 }
2585 } while (object != old_tail);
2586
2587 return *head != NULL;
2588 }
2589
setup_object(struct kmem_cache * s,void * object)2590 static void *setup_object(struct kmem_cache *s, void *object)
2591 {
2592 setup_object_debug(s, object);
2593 object = kasan_init_slab_obj(s, object);
2594 if (unlikely(s->ctor)) {
2595 kasan_unpoison_new_object(s, object);
2596 s->ctor(object);
2597 kasan_poison_new_object(s, object);
2598 }
2599 return object;
2600 }
2601
alloc_empty_sheaf(struct kmem_cache * s,gfp_t gfp)2602 static struct slab_sheaf *alloc_empty_sheaf(struct kmem_cache *s, gfp_t gfp)
2603 {
2604 struct slab_sheaf *sheaf = kzalloc(struct_size(sheaf, objects,
2605 s->sheaf_capacity), gfp);
2606
2607 if (unlikely(!sheaf))
2608 return NULL;
2609
2610 sheaf->cache = s;
2611
2612 stat(s, SHEAF_ALLOC);
2613
2614 return sheaf;
2615 }
2616
free_empty_sheaf(struct kmem_cache * s,struct slab_sheaf * sheaf)2617 static void free_empty_sheaf(struct kmem_cache *s, struct slab_sheaf *sheaf)
2618 {
2619 kfree(sheaf);
2620
2621 stat(s, SHEAF_FREE);
2622 }
2623
2624 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
2625 size_t size, void **p);
2626
2627
refill_sheaf(struct kmem_cache * s,struct slab_sheaf * sheaf,gfp_t gfp)2628 static int refill_sheaf(struct kmem_cache *s, struct slab_sheaf *sheaf,
2629 gfp_t gfp)
2630 {
2631 int to_fill = s->sheaf_capacity - sheaf->size;
2632 int filled;
2633
2634 if (!to_fill)
2635 return 0;
2636
2637 filled = __kmem_cache_alloc_bulk(s, gfp, to_fill,
2638 &sheaf->objects[sheaf->size]);
2639
2640 sheaf->size += filled;
2641
2642 stat_add(s, SHEAF_REFILL, filled);
2643
2644 if (filled < to_fill)
2645 return -ENOMEM;
2646
2647 return 0;
2648 }
2649
2650
alloc_full_sheaf(struct kmem_cache * s,gfp_t gfp)2651 static struct slab_sheaf *alloc_full_sheaf(struct kmem_cache *s, gfp_t gfp)
2652 {
2653 struct slab_sheaf *sheaf = alloc_empty_sheaf(s, gfp);
2654
2655 if (!sheaf)
2656 return NULL;
2657
2658 if (refill_sheaf(s, sheaf, gfp)) {
2659 free_empty_sheaf(s, sheaf);
2660 return NULL;
2661 }
2662
2663 return sheaf;
2664 }
2665
2666 /*
2667 * Maximum number of objects freed during a single flush of main pcs sheaf.
2668 * Translates directly to an on-stack array size.
2669 */
2670 #define PCS_BATCH_MAX 32U
2671
2672 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p);
2673
2674 /*
2675 * Free all objects from the main sheaf. In order to perform
2676 * __kmem_cache_free_bulk() outside of cpu_sheaves->lock, work in batches where
2677 * object pointers are moved to a on-stack array under the lock. To bound the
2678 * stack usage, limit each batch to PCS_BATCH_MAX.
2679 *
2680 * returns true if at least partially flushed
2681 */
sheaf_flush_main(struct kmem_cache * s)2682 static bool sheaf_flush_main(struct kmem_cache *s)
2683 {
2684 struct slub_percpu_sheaves *pcs;
2685 unsigned int batch, remaining;
2686 void *objects[PCS_BATCH_MAX];
2687 struct slab_sheaf *sheaf;
2688 bool ret = false;
2689
2690 next_batch:
2691 if (!local_trylock(&s->cpu_sheaves->lock))
2692 return ret;
2693
2694 pcs = this_cpu_ptr(s->cpu_sheaves);
2695 sheaf = pcs->main;
2696
2697 batch = min(PCS_BATCH_MAX, sheaf->size);
2698
2699 sheaf->size -= batch;
2700 memcpy(objects, sheaf->objects + sheaf->size, batch * sizeof(void *));
2701
2702 remaining = sheaf->size;
2703
2704 local_unlock(&s->cpu_sheaves->lock);
2705
2706 __kmem_cache_free_bulk(s, batch, &objects[0]);
2707
2708 stat_add(s, SHEAF_FLUSH, batch);
2709
2710 ret = true;
2711
2712 if (remaining)
2713 goto next_batch;
2714
2715 return ret;
2716 }
2717
2718 /*
2719 * Free all objects from a sheaf that's unused, i.e. not linked to any
2720 * cpu_sheaves, so we need no locking and batching. The locking is also not
2721 * necessary when flushing cpu's sheaves (both spare and main) during cpu
2722 * hotremove as the cpu is not executing anymore.
2723 */
sheaf_flush_unused(struct kmem_cache * s,struct slab_sheaf * sheaf)2724 static void sheaf_flush_unused(struct kmem_cache *s, struct slab_sheaf *sheaf)
2725 {
2726 if (!sheaf->size)
2727 return;
2728
2729 stat_add(s, SHEAF_FLUSH, sheaf->size);
2730
2731 __kmem_cache_free_bulk(s, sheaf->size, &sheaf->objects[0]);
2732
2733 sheaf->size = 0;
2734 }
2735
__rcu_free_sheaf_prepare(struct kmem_cache * s,struct slab_sheaf * sheaf)2736 static void __rcu_free_sheaf_prepare(struct kmem_cache *s,
2737 struct slab_sheaf *sheaf)
2738 {
2739 bool init = slab_want_init_on_free(s);
2740 void **p = &sheaf->objects[0];
2741 unsigned int i = 0;
2742
2743 while (i < sheaf->size) {
2744 struct slab *slab = virt_to_slab(p[i]);
2745
2746 memcg_slab_free_hook(s, slab, p + i, 1);
2747 alloc_tagging_slab_free_hook(s, slab, p + i, 1);
2748
2749 if (unlikely(!slab_free_hook(s, p[i], init, true))) {
2750 p[i] = p[--sheaf->size];
2751 continue;
2752 }
2753
2754 i++;
2755 }
2756 }
2757
rcu_free_sheaf_nobarn(struct rcu_head * head)2758 static void rcu_free_sheaf_nobarn(struct rcu_head *head)
2759 {
2760 struct slab_sheaf *sheaf;
2761 struct kmem_cache *s;
2762
2763 sheaf = container_of(head, struct slab_sheaf, rcu_head);
2764 s = sheaf->cache;
2765
2766 __rcu_free_sheaf_prepare(s, sheaf);
2767
2768 sheaf_flush_unused(s, sheaf);
2769
2770 free_empty_sheaf(s, sheaf);
2771 }
2772
2773 /*
2774 * Caller needs to make sure migration is disabled in order to fully flush
2775 * single cpu's sheaves
2776 *
2777 * must not be called from an irq
2778 *
2779 * flushing operations are rare so let's keep it simple and flush to slabs
2780 * directly, skipping the barn
2781 */
pcs_flush_all(struct kmem_cache * s)2782 static void pcs_flush_all(struct kmem_cache *s)
2783 {
2784 struct slub_percpu_sheaves *pcs;
2785 struct slab_sheaf *spare, *rcu_free;
2786
2787 local_lock(&s->cpu_sheaves->lock);
2788 pcs = this_cpu_ptr(s->cpu_sheaves);
2789
2790 spare = pcs->spare;
2791 pcs->spare = NULL;
2792
2793 rcu_free = pcs->rcu_free;
2794 pcs->rcu_free = NULL;
2795
2796 local_unlock(&s->cpu_sheaves->lock);
2797
2798 if (spare) {
2799 sheaf_flush_unused(s, spare);
2800 free_empty_sheaf(s, spare);
2801 }
2802
2803 if (rcu_free)
2804 call_rcu(&rcu_free->rcu_head, rcu_free_sheaf_nobarn);
2805
2806 sheaf_flush_main(s);
2807 }
2808
__pcs_flush_all_cpu(struct kmem_cache * s,unsigned int cpu)2809 static void __pcs_flush_all_cpu(struct kmem_cache *s, unsigned int cpu)
2810 {
2811 struct slub_percpu_sheaves *pcs;
2812
2813 pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
2814
2815 /* The cpu is not executing anymore so we don't need pcs->lock */
2816 sheaf_flush_unused(s, pcs->main);
2817 if (pcs->spare) {
2818 sheaf_flush_unused(s, pcs->spare);
2819 free_empty_sheaf(s, pcs->spare);
2820 pcs->spare = NULL;
2821 }
2822
2823 if (pcs->rcu_free) {
2824 call_rcu(&pcs->rcu_free->rcu_head, rcu_free_sheaf_nobarn);
2825 pcs->rcu_free = NULL;
2826 }
2827 }
2828
pcs_destroy(struct kmem_cache * s)2829 static void pcs_destroy(struct kmem_cache *s)
2830 {
2831 int cpu;
2832
2833 for_each_possible_cpu(cpu) {
2834 struct slub_percpu_sheaves *pcs;
2835
2836 pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
2837
2838 /* can happen when unwinding failed create */
2839 if (!pcs->main)
2840 continue;
2841
2842 /*
2843 * We have already passed __kmem_cache_shutdown() so everything
2844 * was flushed and there should be no objects allocated from
2845 * slabs, otherwise kmem_cache_destroy() would have aborted.
2846 * Therefore something would have to be really wrong if the
2847 * warnings here trigger, and we should rather leave objects and
2848 * sheaves to leak in that case.
2849 */
2850
2851 WARN_ON(pcs->spare);
2852 WARN_ON(pcs->rcu_free);
2853
2854 if (!WARN_ON(pcs->main->size)) {
2855 free_empty_sheaf(s, pcs->main);
2856 pcs->main = NULL;
2857 }
2858 }
2859
2860 free_percpu(s->cpu_sheaves);
2861 s->cpu_sheaves = NULL;
2862 }
2863
barn_get_empty_sheaf(struct node_barn * barn)2864 static struct slab_sheaf *barn_get_empty_sheaf(struct node_barn *barn)
2865 {
2866 struct slab_sheaf *empty = NULL;
2867 unsigned long flags;
2868
2869 if (!data_race(barn->nr_empty))
2870 return NULL;
2871
2872 spin_lock_irqsave(&barn->lock, flags);
2873
2874 if (likely(barn->nr_empty)) {
2875 empty = list_first_entry(&barn->sheaves_empty,
2876 struct slab_sheaf, barn_list);
2877 list_del(&empty->barn_list);
2878 barn->nr_empty--;
2879 }
2880
2881 spin_unlock_irqrestore(&barn->lock, flags);
2882
2883 return empty;
2884 }
2885
2886 /*
2887 * The following two functions are used mainly in cases where we have to undo an
2888 * intended action due to a race or cpu migration. Thus they do not check the
2889 * empty or full sheaf limits for simplicity.
2890 */
2891
barn_put_empty_sheaf(struct node_barn * barn,struct slab_sheaf * sheaf)2892 static void barn_put_empty_sheaf(struct node_barn *barn, struct slab_sheaf *sheaf)
2893 {
2894 unsigned long flags;
2895
2896 spin_lock_irqsave(&barn->lock, flags);
2897
2898 list_add(&sheaf->barn_list, &barn->sheaves_empty);
2899 barn->nr_empty++;
2900
2901 spin_unlock_irqrestore(&barn->lock, flags);
2902 }
2903
barn_put_full_sheaf(struct node_barn * barn,struct slab_sheaf * sheaf)2904 static void barn_put_full_sheaf(struct node_barn *barn, struct slab_sheaf *sheaf)
2905 {
2906 unsigned long flags;
2907
2908 spin_lock_irqsave(&barn->lock, flags);
2909
2910 list_add(&sheaf->barn_list, &barn->sheaves_full);
2911 barn->nr_full++;
2912
2913 spin_unlock_irqrestore(&barn->lock, flags);
2914 }
2915
barn_get_full_or_empty_sheaf(struct node_barn * barn)2916 static struct slab_sheaf *barn_get_full_or_empty_sheaf(struct node_barn *barn)
2917 {
2918 struct slab_sheaf *sheaf = NULL;
2919 unsigned long flags;
2920
2921 if (!data_race(barn->nr_full) && !data_race(barn->nr_empty))
2922 return NULL;
2923
2924 spin_lock_irqsave(&barn->lock, flags);
2925
2926 if (barn->nr_full) {
2927 sheaf = list_first_entry(&barn->sheaves_full, struct slab_sheaf,
2928 barn_list);
2929 list_del(&sheaf->barn_list);
2930 barn->nr_full--;
2931 } else if (barn->nr_empty) {
2932 sheaf = list_first_entry(&barn->sheaves_empty,
2933 struct slab_sheaf, barn_list);
2934 list_del(&sheaf->barn_list);
2935 barn->nr_empty--;
2936 }
2937
2938 spin_unlock_irqrestore(&barn->lock, flags);
2939
2940 return sheaf;
2941 }
2942
2943 /*
2944 * If a full sheaf is available, return it and put the supplied empty one to
2945 * barn. We ignore the limit on empty sheaves as the number of sheaves doesn't
2946 * change.
2947 */
2948 static struct slab_sheaf *
barn_replace_empty_sheaf(struct node_barn * barn,struct slab_sheaf * empty)2949 barn_replace_empty_sheaf(struct node_barn *barn, struct slab_sheaf *empty)
2950 {
2951 struct slab_sheaf *full = NULL;
2952 unsigned long flags;
2953
2954 if (!data_race(barn->nr_full))
2955 return NULL;
2956
2957 spin_lock_irqsave(&barn->lock, flags);
2958
2959 if (likely(barn->nr_full)) {
2960 full = list_first_entry(&barn->sheaves_full, struct slab_sheaf,
2961 barn_list);
2962 list_del(&full->barn_list);
2963 list_add(&empty->barn_list, &barn->sheaves_empty);
2964 barn->nr_full--;
2965 barn->nr_empty++;
2966 }
2967
2968 spin_unlock_irqrestore(&barn->lock, flags);
2969
2970 return full;
2971 }
2972
2973 /*
2974 * If an empty sheaf is available, return it and put the supplied full one to
2975 * barn. But if there are too many full sheaves, reject this with -E2BIG.
2976 */
2977 static struct slab_sheaf *
barn_replace_full_sheaf(struct node_barn * barn,struct slab_sheaf * full)2978 barn_replace_full_sheaf(struct node_barn *barn, struct slab_sheaf *full)
2979 {
2980 struct slab_sheaf *empty;
2981 unsigned long flags;
2982
2983 /* we don't repeat this check under barn->lock as it's not critical */
2984 if (data_race(barn->nr_full) >= MAX_FULL_SHEAVES)
2985 return ERR_PTR(-E2BIG);
2986 if (!data_race(barn->nr_empty))
2987 return ERR_PTR(-ENOMEM);
2988
2989 spin_lock_irqsave(&barn->lock, flags);
2990
2991 if (likely(barn->nr_empty)) {
2992 empty = list_first_entry(&barn->sheaves_empty, struct slab_sheaf,
2993 barn_list);
2994 list_del(&empty->barn_list);
2995 list_add(&full->barn_list, &barn->sheaves_full);
2996 barn->nr_empty--;
2997 barn->nr_full++;
2998 } else {
2999 empty = ERR_PTR(-ENOMEM);
3000 }
3001
3002 spin_unlock_irqrestore(&barn->lock, flags);
3003
3004 return empty;
3005 }
3006
barn_init(struct node_barn * barn)3007 static void barn_init(struct node_barn *barn)
3008 {
3009 spin_lock_init(&barn->lock);
3010 INIT_LIST_HEAD(&barn->sheaves_full);
3011 INIT_LIST_HEAD(&barn->sheaves_empty);
3012 barn->nr_full = 0;
3013 barn->nr_empty = 0;
3014 }
3015
barn_shrink(struct kmem_cache * s,struct node_barn * barn)3016 static void barn_shrink(struct kmem_cache *s, struct node_barn *barn)
3017 {
3018 struct list_head empty_list;
3019 struct list_head full_list;
3020 struct slab_sheaf *sheaf, *sheaf2;
3021 unsigned long flags;
3022
3023 INIT_LIST_HEAD(&empty_list);
3024 INIT_LIST_HEAD(&full_list);
3025
3026 spin_lock_irqsave(&barn->lock, flags);
3027
3028 list_splice_init(&barn->sheaves_full, &full_list);
3029 barn->nr_full = 0;
3030 list_splice_init(&barn->sheaves_empty, &empty_list);
3031 barn->nr_empty = 0;
3032
3033 spin_unlock_irqrestore(&barn->lock, flags);
3034
3035 list_for_each_entry_safe(sheaf, sheaf2, &full_list, barn_list) {
3036 sheaf_flush_unused(s, sheaf);
3037 free_empty_sheaf(s, sheaf);
3038 }
3039
3040 list_for_each_entry_safe(sheaf, sheaf2, &empty_list, barn_list)
3041 free_empty_sheaf(s, sheaf);
3042 }
3043
3044 /*
3045 * Slab allocation and freeing
3046 */
alloc_slab_page(gfp_t flags,int node,struct kmem_cache_order_objects oo,bool allow_spin)3047 static inline struct slab *alloc_slab_page(gfp_t flags, int node,
3048 struct kmem_cache_order_objects oo,
3049 bool allow_spin)
3050 {
3051 struct folio *folio;
3052 struct slab *slab;
3053 unsigned int order = oo_order(oo);
3054
3055 if (unlikely(!allow_spin))
3056 folio = (struct folio *)alloc_frozen_pages_nolock(0/* __GFP_COMP is implied */,
3057 node, order);
3058 else if (node == NUMA_NO_NODE)
3059 folio = (struct folio *)alloc_frozen_pages(flags, order);
3060 else
3061 folio = (struct folio *)__alloc_frozen_pages(flags, order, node, NULL);
3062
3063 if (!folio)
3064 return NULL;
3065
3066 slab = folio_slab(folio);
3067 __folio_set_slab(folio);
3068 if (folio_is_pfmemalloc(folio))
3069 slab_set_pfmemalloc(slab);
3070
3071 return slab;
3072 }
3073
3074 #ifdef CONFIG_SLAB_FREELIST_RANDOM
3075 /* Pre-initialize the random sequence cache */
init_cache_random_seq(struct kmem_cache * s)3076 static int init_cache_random_seq(struct kmem_cache *s)
3077 {
3078 unsigned int count = oo_objects(s->oo);
3079 int err;
3080
3081 /* Bailout if already initialised */
3082 if (s->random_seq)
3083 return 0;
3084
3085 err = cache_random_seq_create(s, count, GFP_KERNEL);
3086 if (err) {
3087 pr_err("SLUB: Unable to initialize free list for %s\n",
3088 s->name);
3089 return err;
3090 }
3091
3092 /* Transform to an offset on the set of pages */
3093 if (s->random_seq) {
3094 unsigned int i;
3095
3096 for (i = 0; i < count; i++)
3097 s->random_seq[i] *= s->size;
3098 }
3099 return 0;
3100 }
3101
3102 /* Initialize each random sequence freelist per cache */
init_freelist_randomization(void)3103 static void __init init_freelist_randomization(void)
3104 {
3105 struct kmem_cache *s;
3106
3107 mutex_lock(&slab_mutex);
3108
3109 list_for_each_entry(s, &slab_caches, list)
3110 init_cache_random_seq(s);
3111
3112 mutex_unlock(&slab_mutex);
3113 }
3114
3115 /* Get the next entry on the pre-computed freelist randomized */
next_freelist_entry(struct kmem_cache * s,unsigned long * pos,void * start,unsigned long page_limit,unsigned long freelist_count)3116 static void *next_freelist_entry(struct kmem_cache *s,
3117 unsigned long *pos, void *start,
3118 unsigned long page_limit,
3119 unsigned long freelist_count)
3120 {
3121 unsigned int idx;
3122
3123 /*
3124 * If the target page allocation failed, the number of objects on the
3125 * page might be smaller than the usual size defined by the cache.
3126 */
3127 do {
3128 idx = s->random_seq[*pos];
3129 *pos += 1;
3130 if (*pos >= freelist_count)
3131 *pos = 0;
3132 } while (unlikely(idx >= page_limit));
3133
3134 return (char *)start + idx;
3135 }
3136
3137 /* Shuffle the single linked freelist based on a random pre-computed sequence */
shuffle_freelist(struct kmem_cache * s,struct slab * slab)3138 static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
3139 {
3140 void *start;
3141 void *cur;
3142 void *next;
3143 unsigned long idx, pos, page_limit, freelist_count;
3144
3145 if (slab->objects < 2 || !s->random_seq)
3146 return false;
3147
3148 freelist_count = oo_objects(s->oo);
3149 pos = get_random_u32_below(freelist_count);
3150
3151 page_limit = slab->objects * s->size;
3152 start = fixup_red_left(s, slab_address(slab));
3153
3154 /* First entry is used as the base of the freelist */
3155 cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count);
3156 cur = setup_object(s, cur);
3157 slab->freelist = cur;
3158
3159 for (idx = 1; idx < slab->objects; idx++) {
3160 next = next_freelist_entry(s, &pos, start, page_limit,
3161 freelist_count);
3162 next = setup_object(s, next);
3163 set_freepointer(s, cur, next);
3164 cur = next;
3165 }
3166 set_freepointer(s, cur, NULL);
3167
3168 return true;
3169 }
3170 #else
init_cache_random_seq(struct kmem_cache * s)3171 static inline int init_cache_random_seq(struct kmem_cache *s)
3172 {
3173 return 0;
3174 }
init_freelist_randomization(void)3175 static inline void init_freelist_randomization(void) { }
shuffle_freelist(struct kmem_cache * s,struct slab * slab)3176 static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
3177 {
3178 return false;
3179 }
3180 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
3181
account_slab(struct slab * slab,int order,struct kmem_cache * s,gfp_t gfp)3182 static __always_inline void account_slab(struct slab *slab, int order,
3183 struct kmem_cache *s, gfp_t gfp)
3184 {
3185 if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT))
3186 alloc_slab_obj_exts(slab, s, gfp, true);
3187
3188 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
3189 PAGE_SIZE << order);
3190 }
3191
unaccount_slab(struct slab * slab,int order,struct kmem_cache * s)3192 static __always_inline void unaccount_slab(struct slab *slab, int order,
3193 struct kmem_cache *s)
3194 {
3195 /*
3196 * The slab object extensions should now be freed regardless of
3197 * whether mem_alloc_profiling_enabled() or not because profiling
3198 * might have been disabled after slab->obj_exts got allocated.
3199 */
3200 free_slab_obj_exts(slab);
3201
3202 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
3203 -(PAGE_SIZE << order));
3204 }
3205
allocate_slab(struct kmem_cache * s,gfp_t flags,int node)3206 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
3207 {
3208 bool allow_spin = gfpflags_allow_spinning(flags);
3209 struct slab *slab;
3210 struct kmem_cache_order_objects oo = s->oo;
3211 gfp_t alloc_gfp;
3212 void *start, *p, *next;
3213 int idx;
3214 bool shuffle;
3215
3216 flags &= gfp_allowed_mask;
3217
3218 flags |= s->allocflags;
3219
3220 /*
3221 * Let the initial higher-order allocation fail under memory pressure
3222 * so we fall-back to the minimum order allocation.
3223 */
3224 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
3225 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
3226 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
3227
3228 /*
3229 * __GFP_RECLAIM could be cleared on the first allocation attempt,
3230 * so pass allow_spin flag directly.
3231 */
3232 slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
3233 if (unlikely(!slab)) {
3234 oo = s->min;
3235 alloc_gfp = flags;
3236 /*
3237 * Allocation may have failed due to fragmentation.
3238 * Try a lower order alloc if possible
3239 */
3240 slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
3241 if (unlikely(!slab))
3242 return NULL;
3243 stat(s, ORDER_FALLBACK);
3244 }
3245
3246 slab->objects = oo_objects(oo);
3247 slab->inuse = 0;
3248 slab->frozen = 0;
3249 init_slab_obj_exts(slab);
3250
3251 account_slab(slab, oo_order(oo), s, flags);
3252
3253 slab->slab_cache = s;
3254
3255 kasan_poison_slab(slab);
3256
3257 start = slab_address(slab);
3258
3259 setup_slab_debug(s, slab, start);
3260
3261 shuffle = shuffle_freelist(s, slab);
3262
3263 if (!shuffle) {
3264 start = fixup_red_left(s, start);
3265 start = setup_object(s, start);
3266 slab->freelist = start;
3267 for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
3268 next = p + s->size;
3269 next = setup_object(s, next);
3270 set_freepointer(s, p, next);
3271 p = next;
3272 }
3273 set_freepointer(s, p, NULL);
3274 }
3275
3276 return slab;
3277 }
3278
new_slab(struct kmem_cache * s,gfp_t flags,int node)3279 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
3280 {
3281 if (unlikely(flags & GFP_SLAB_BUG_MASK))
3282 flags = kmalloc_fix_flags(flags);
3283
3284 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
3285
3286 return allocate_slab(s,
3287 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
3288 }
3289
__free_slab(struct kmem_cache * s,struct slab * slab)3290 static void __free_slab(struct kmem_cache *s, struct slab *slab)
3291 {
3292 struct folio *folio = slab_folio(slab);
3293 int order = folio_order(folio);
3294 int pages = 1 << order;
3295
3296 __slab_clear_pfmemalloc(slab);
3297 folio->mapping = NULL;
3298 __folio_clear_slab(folio);
3299 mm_account_reclaimed_pages(pages);
3300 unaccount_slab(slab, order, s);
3301 free_frozen_pages(&folio->page, order);
3302 }
3303
rcu_free_slab(struct rcu_head * h)3304 static void rcu_free_slab(struct rcu_head *h)
3305 {
3306 struct slab *slab = container_of(h, struct slab, rcu_head);
3307
3308 __free_slab(slab->slab_cache, slab);
3309 }
3310
free_slab(struct kmem_cache * s,struct slab * slab)3311 static void free_slab(struct kmem_cache *s, struct slab *slab)
3312 {
3313 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
3314 void *p;
3315
3316 slab_pad_check(s, slab);
3317 for_each_object(p, s, slab_address(slab), slab->objects)
3318 check_object(s, slab, p, SLUB_RED_INACTIVE);
3319 }
3320
3321 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
3322 call_rcu(&slab->rcu_head, rcu_free_slab);
3323 else
3324 __free_slab(s, slab);
3325 }
3326
discard_slab(struct kmem_cache * s,struct slab * slab)3327 static void discard_slab(struct kmem_cache *s, struct slab *slab)
3328 {
3329 dec_slabs_node(s, slab_nid(slab), slab->objects);
3330 free_slab(s, slab);
3331 }
3332
slab_test_node_partial(const struct slab * slab)3333 static inline bool slab_test_node_partial(const struct slab *slab)
3334 {
3335 return test_bit(SL_partial, &slab->flags.f);
3336 }
3337
slab_set_node_partial(struct slab * slab)3338 static inline void slab_set_node_partial(struct slab *slab)
3339 {
3340 set_bit(SL_partial, &slab->flags.f);
3341 }
3342
slab_clear_node_partial(struct slab * slab)3343 static inline void slab_clear_node_partial(struct slab *slab)
3344 {
3345 clear_bit(SL_partial, &slab->flags.f);
3346 }
3347
3348 /*
3349 * Management of partially allocated slabs.
3350 */
3351 static inline void
__add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)3352 __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
3353 {
3354 n->nr_partial++;
3355 if (tail == DEACTIVATE_TO_TAIL)
3356 list_add_tail(&slab->slab_list, &n->partial);
3357 else
3358 list_add(&slab->slab_list, &n->partial);
3359 slab_set_node_partial(slab);
3360 }
3361
add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)3362 static inline void add_partial(struct kmem_cache_node *n,
3363 struct slab *slab, int tail)
3364 {
3365 lockdep_assert_held(&n->list_lock);
3366 __add_partial(n, slab, tail);
3367 }
3368
remove_partial(struct kmem_cache_node * n,struct slab * slab)3369 static inline void remove_partial(struct kmem_cache_node *n,
3370 struct slab *slab)
3371 {
3372 lockdep_assert_held(&n->list_lock);
3373 list_del(&slab->slab_list);
3374 slab_clear_node_partial(slab);
3375 n->nr_partial--;
3376 }
3377
3378 /*
3379 * Called only for kmem_cache_debug() caches instead of remove_partial(), with a
3380 * slab from the n->partial list. Remove only a single object from the slab, do
3381 * the alloc_debug_processing() checks and leave the slab on the list, or move
3382 * it to full list if it was the last free object.
3383 */
alloc_single_from_partial(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab,int orig_size)3384 static void *alloc_single_from_partial(struct kmem_cache *s,
3385 struct kmem_cache_node *n, struct slab *slab, int orig_size)
3386 {
3387 void *object;
3388
3389 lockdep_assert_held(&n->list_lock);
3390
3391 #ifdef CONFIG_SLUB_DEBUG
3392 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3393 if (!validate_slab_ptr(slab)) {
3394 slab_err(s, slab, "Not a valid slab page");
3395 return NULL;
3396 }
3397 }
3398 #endif
3399
3400 object = slab->freelist;
3401 slab->freelist = get_freepointer(s, object);
3402 slab->inuse++;
3403
3404 if (!alloc_debug_processing(s, slab, object, orig_size)) {
3405 remove_partial(n, slab);
3406 return NULL;
3407 }
3408
3409 if (slab->inuse == slab->objects) {
3410 remove_partial(n, slab);
3411 add_full(s, n, slab);
3412 }
3413
3414 return object;
3415 }
3416
3417 static void defer_deactivate_slab(struct slab *slab, void *flush_freelist);
3418
3419 /*
3420 * Called only for kmem_cache_debug() caches to allocate from a freshly
3421 * allocated slab. Allocate a single object instead of whole freelist
3422 * and put the slab to the partial (or full) list.
3423 */
alloc_single_from_new_slab(struct kmem_cache * s,struct slab * slab,int orig_size,gfp_t gfpflags)3424 static void *alloc_single_from_new_slab(struct kmem_cache *s, struct slab *slab,
3425 int orig_size, gfp_t gfpflags)
3426 {
3427 bool allow_spin = gfpflags_allow_spinning(gfpflags);
3428 int nid = slab_nid(slab);
3429 struct kmem_cache_node *n = get_node(s, nid);
3430 unsigned long flags;
3431 void *object;
3432
3433 if (!allow_spin && !spin_trylock_irqsave(&n->list_lock, flags)) {
3434 /* Unlucky, discard newly allocated slab */
3435 defer_deactivate_slab(slab, NULL);
3436 return NULL;
3437 }
3438
3439 object = slab->freelist;
3440 slab->freelist = get_freepointer(s, object);
3441 slab->inuse = 1;
3442
3443 if (!alloc_debug_processing(s, slab, object, orig_size)) {
3444 /*
3445 * It's not really expected that this would fail on a
3446 * freshly allocated slab, but a concurrent memory
3447 * corruption in theory could cause that.
3448 * Leak memory of allocated slab.
3449 */
3450 if (!allow_spin)
3451 spin_unlock_irqrestore(&n->list_lock, flags);
3452 return NULL;
3453 }
3454
3455 if (allow_spin)
3456 spin_lock_irqsave(&n->list_lock, flags);
3457
3458 if (slab->inuse == slab->objects)
3459 add_full(s, n, slab);
3460 else
3461 add_partial(n, slab, DEACTIVATE_TO_HEAD);
3462
3463 inc_slabs_node(s, nid, slab->objects);
3464 spin_unlock_irqrestore(&n->list_lock, flags);
3465
3466 return object;
3467 }
3468
3469 #ifdef CONFIG_SLUB_CPU_PARTIAL
3470 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
3471 #else
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)3472 static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
3473 int drain) { }
3474 #endif
3475 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
3476
3477 /*
3478 * Try to allocate a partial slab from a specific node.
3479 */
get_partial_node(struct kmem_cache * s,struct kmem_cache_node * n,struct partial_context * pc)3480 static struct slab *get_partial_node(struct kmem_cache *s,
3481 struct kmem_cache_node *n,
3482 struct partial_context *pc)
3483 {
3484 struct slab *slab, *slab2, *partial = NULL;
3485 unsigned long flags;
3486 unsigned int partial_slabs = 0;
3487
3488 /*
3489 * Racy check. If we mistakenly see no partial slabs then we
3490 * just allocate an empty slab. If we mistakenly try to get a
3491 * partial slab and there is none available then get_partial()
3492 * will return NULL.
3493 */
3494 if (!n || !n->nr_partial)
3495 return NULL;
3496
3497 if (gfpflags_allow_spinning(pc->flags))
3498 spin_lock_irqsave(&n->list_lock, flags);
3499 else if (!spin_trylock_irqsave(&n->list_lock, flags))
3500 return NULL;
3501 list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
3502 if (!pfmemalloc_match(slab, pc->flags))
3503 continue;
3504
3505 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
3506 void *object = alloc_single_from_partial(s, n, slab,
3507 pc->orig_size);
3508 if (object) {
3509 partial = slab;
3510 pc->object = object;
3511 break;
3512 }
3513 continue;
3514 }
3515
3516 remove_partial(n, slab);
3517
3518 if (!partial) {
3519 partial = slab;
3520 stat(s, ALLOC_FROM_PARTIAL);
3521
3522 if ((slub_get_cpu_partial(s) == 0)) {
3523 break;
3524 }
3525 } else {
3526 put_cpu_partial(s, slab, 0);
3527 stat(s, CPU_PARTIAL_NODE);
3528
3529 if (++partial_slabs > slub_get_cpu_partial(s) / 2) {
3530 break;
3531 }
3532 }
3533 }
3534 spin_unlock_irqrestore(&n->list_lock, flags);
3535 return partial;
3536 }
3537
3538 /*
3539 * Get a slab from somewhere. Search in increasing NUMA distances.
3540 */
get_any_partial(struct kmem_cache * s,struct partial_context * pc)3541 static struct slab *get_any_partial(struct kmem_cache *s,
3542 struct partial_context *pc)
3543 {
3544 #ifdef CONFIG_NUMA
3545 struct zonelist *zonelist;
3546 struct zoneref *z;
3547 struct zone *zone;
3548 enum zone_type highest_zoneidx = gfp_zone(pc->flags);
3549 struct slab *slab;
3550 unsigned int cpuset_mems_cookie;
3551
3552 /*
3553 * The defrag ratio allows a configuration of the tradeoffs between
3554 * inter node defragmentation and node local allocations. A lower
3555 * defrag_ratio increases the tendency to do local allocations
3556 * instead of attempting to obtain partial slabs from other nodes.
3557 *
3558 * If the defrag_ratio is set to 0 then kmalloc() always
3559 * returns node local objects. If the ratio is higher then kmalloc()
3560 * may return off node objects because partial slabs are obtained
3561 * from other nodes and filled up.
3562 *
3563 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
3564 * (which makes defrag_ratio = 1000) then every (well almost)
3565 * allocation will first attempt to defrag slab caches on other nodes.
3566 * This means scanning over all nodes to look for partial slabs which
3567 * may be expensive if we do it every time we are trying to find a slab
3568 * with available objects.
3569 */
3570 if (!s->remote_node_defrag_ratio ||
3571 get_cycles() % 1024 > s->remote_node_defrag_ratio)
3572 return NULL;
3573
3574 do {
3575 cpuset_mems_cookie = read_mems_allowed_begin();
3576 zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
3577 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
3578 struct kmem_cache_node *n;
3579
3580 n = get_node(s, zone_to_nid(zone));
3581
3582 if (n && cpuset_zone_allowed(zone, pc->flags) &&
3583 n->nr_partial > s->min_partial) {
3584 slab = get_partial_node(s, n, pc);
3585 if (slab) {
3586 /*
3587 * Don't check read_mems_allowed_retry()
3588 * here - if mems_allowed was updated in
3589 * parallel, that was a harmless race
3590 * between allocation and the cpuset
3591 * update
3592 */
3593 return slab;
3594 }
3595 }
3596 }
3597 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3598 #endif /* CONFIG_NUMA */
3599 return NULL;
3600 }
3601
3602 /*
3603 * Get a partial slab, lock it and return it.
3604 */
get_partial(struct kmem_cache * s,int node,struct partial_context * pc)3605 static struct slab *get_partial(struct kmem_cache *s, int node,
3606 struct partial_context *pc)
3607 {
3608 struct slab *slab;
3609 int searchnode = node;
3610
3611 if (node == NUMA_NO_NODE)
3612 searchnode = numa_mem_id();
3613
3614 slab = get_partial_node(s, get_node(s, searchnode), pc);
3615 if (slab || (node != NUMA_NO_NODE && (pc->flags & __GFP_THISNODE)))
3616 return slab;
3617
3618 return get_any_partial(s, pc);
3619 }
3620
3621 #ifndef CONFIG_SLUB_TINY
3622
3623 #ifdef CONFIG_PREEMPTION
3624 /*
3625 * Calculate the next globally unique transaction for disambiguation
3626 * during cmpxchg. The transactions start with the cpu number and are then
3627 * incremented by CONFIG_NR_CPUS.
3628 */
3629 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
3630 #else
3631 /*
3632 * No preemption supported therefore also no need to check for
3633 * different cpus.
3634 */
3635 #define TID_STEP 1
3636 #endif /* CONFIG_PREEMPTION */
3637
next_tid(unsigned long tid)3638 static inline unsigned long next_tid(unsigned long tid)
3639 {
3640 return tid + TID_STEP;
3641 }
3642
3643 #ifdef SLUB_DEBUG_CMPXCHG
tid_to_cpu(unsigned long tid)3644 static inline unsigned int tid_to_cpu(unsigned long tid)
3645 {
3646 return tid % TID_STEP;
3647 }
3648
tid_to_event(unsigned long tid)3649 static inline unsigned long tid_to_event(unsigned long tid)
3650 {
3651 return tid / TID_STEP;
3652 }
3653 #endif
3654
init_tid(int cpu)3655 static inline unsigned int init_tid(int cpu)
3656 {
3657 return cpu;
3658 }
3659
note_cmpxchg_failure(const char * n,const struct kmem_cache * s,unsigned long tid)3660 static inline void note_cmpxchg_failure(const char *n,
3661 const struct kmem_cache *s, unsigned long tid)
3662 {
3663 #ifdef SLUB_DEBUG_CMPXCHG
3664 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
3665
3666 pr_info("%s %s: cmpxchg redo ", n, s->name);
3667
3668 if (IS_ENABLED(CONFIG_PREEMPTION) &&
3669 tid_to_cpu(tid) != tid_to_cpu(actual_tid)) {
3670 pr_warn("due to cpu change %d -> %d\n",
3671 tid_to_cpu(tid), tid_to_cpu(actual_tid));
3672 } else if (tid_to_event(tid) != tid_to_event(actual_tid)) {
3673 pr_warn("due to cpu running other code. Event %ld->%ld\n",
3674 tid_to_event(tid), tid_to_event(actual_tid));
3675 } else {
3676 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
3677 actual_tid, tid, next_tid(tid));
3678 }
3679 #endif
3680 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
3681 }
3682
init_kmem_cache_cpus(struct kmem_cache * s)3683 static void init_kmem_cache_cpus(struct kmem_cache *s)
3684 {
3685 #ifdef CONFIG_PREEMPT_RT
3686 /*
3687 * Register lockdep key for non-boot kmem caches to avoid
3688 * WARN_ON_ONCE(static_obj(key))) in lockdep_register_key()
3689 */
3690 bool finegrain_lockdep = !init_section_contains(s, 1);
3691 #else
3692 /*
3693 * Don't bother with different lockdep classes for each
3694 * kmem_cache, since we only use local_trylock_irqsave().
3695 */
3696 bool finegrain_lockdep = false;
3697 #endif
3698 int cpu;
3699 struct kmem_cache_cpu *c;
3700
3701 if (finegrain_lockdep)
3702 lockdep_register_key(&s->lock_key);
3703 for_each_possible_cpu(cpu) {
3704 c = per_cpu_ptr(s->cpu_slab, cpu);
3705 local_trylock_init(&c->lock);
3706 if (finegrain_lockdep)
3707 lockdep_set_class(&c->lock, &s->lock_key);
3708 c->tid = init_tid(cpu);
3709 }
3710 }
3711
3712 /*
3713 * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
3714 * unfreezes the slabs and puts it on the proper list.
3715 * Assumes the slab has been already safely taken away from kmem_cache_cpu
3716 * by the caller.
3717 */
deactivate_slab(struct kmem_cache * s,struct slab * slab,void * freelist)3718 static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
3719 void *freelist)
3720 {
3721 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
3722 int free_delta = 0;
3723 void *nextfree, *freelist_iter, *freelist_tail;
3724 int tail = DEACTIVATE_TO_HEAD;
3725 unsigned long flags = 0;
3726 struct slab new;
3727 struct slab old;
3728
3729 if (READ_ONCE(slab->freelist)) {
3730 stat(s, DEACTIVATE_REMOTE_FREES);
3731 tail = DEACTIVATE_TO_TAIL;
3732 }
3733
3734 /*
3735 * Stage one: Count the objects on cpu's freelist as free_delta and
3736 * remember the last object in freelist_tail for later splicing.
3737 */
3738 freelist_tail = NULL;
3739 freelist_iter = freelist;
3740 while (freelist_iter) {
3741 nextfree = get_freepointer(s, freelist_iter);
3742
3743 /*
3744 * If 'nextfree' is invalid, it is possible that the object at
3745 * 'freelist_iter' is already corrupted. So isolate all objects
3746 * starting at 'freelist_iter' by skipping them.
3747 */
3748 if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
3749 break;
3750
3751 freelist_tail = freelist_iter;
3752 free_delta++;
3753
3754 freelist_iter = nextfree;
3755 }
3756
3757 /*
3758 * Stage two: Unfreeze the slab while splicing the per-cpu
3759 * freelist to the head of slab's freelist.
3760 */
3761 do {
3762 old.freelist = READ_ONCE(slab->freelist);
3763 old.counters = READ_ONCE(slab->counters);
3764 VM_BUG_ON(!old.frozen);
3765
3766 /* Determine target state of the slab */
3767 new.counters = old.counters;
3768 new.frozen = 0;
3769 if (freelist_tail) {
3770 new.inuse -= free_delta;
3771 set_freepointer(s, freelist_tail, old.freelist);
3772 new.freelist = freelist;
3773 } else {
3774 new.freelist = old.freelist;
3775 }
3776 } while (!slab_update_freelist(s, slab,
3777 old.freelist, old.counters,
3778 new.freelist, new.counters,
3779 "unfreezing slab"));
3780
3781 /*
3782 * Stage three: Manipulate the slab list based on the updated state.
3783 */
3784 if (!new.inuse && n->nr_partial >= s->min_partial) {
3785 stat(s, DEACTIVATE_EMPTY);
3786 discard_slab(s, slab);
3787 stat(s, FREE_SLAB);
3788 } else if (new.freelist) {
3789 spin_lock_irqsave(&n->list_lock, flags);
3790 add_partial(n, slab, tail);
3791 spin_unlock_irqrestore(&n->list_lock, flags);
3792 stat(s, tail);
3793 } else {
3794 stat(s, DEACTIVATE_FULL);
3795 }
3796 }
3797
3798 /*
3799 * ___slab_alloc()'s caller is supposed to check if kmem_cache::kmem_cache_cpu::lock
3800 * can be acquired without a deadlock before invoking the function.
3801 *
3802 * Without LOCKDEP we trust the code to be correct. kmalloc_nolock() is
3803 * using local_lock_is_locked() properly before calling local_lock_cpu_slab(),
3804 * and kmalloc() is not used in an unsupported context.
3805 *
3806 * With LOCKDEP, on PREEMPT_RT lockdep does its checking in local_lock_irqsave().
3807 * On !PREEMPT_RT we use trylock to avoid false positives in NMI, but
3808 * lockdep_assert() will catch a bug in case:
3809 * #1
3810 * kmalloc() -> ___slab_alloc() -> irqsave -> NMI -> bpf -> kmalloc_nolock()
3811 * or
3812 * #2
3813 * kmalloc() -> ___slab_alloc() -> irqsave -> tracepoint/kprobe -> bpf -> kmalloc_nolock()
3814 *
3815 * On PREEMPT_RT an invocation is not possible from IRQ-off or preempt
3816 * disabled context. The lock will always be acquired and if needed it
3817 * block and sleep until the lock is available.
3818 * #1 is possible in !PREEMPT_RT only.
3819 * #2 is possible in both with a twist that irqsave is replaced with rt_spinlock:
3820 * kmalloc() -> ___slab_alloc() -> rt_spin_lock(kmem_cache_A) ->
3821 * tracepoint/kprobe -> bpf -> kmalloc_nolock() -> rt_spin_lock(kmem_cache_B)
3822 *
3823 * local_lock_is_locked() prevents the case kmem_cache_A == kmem_cache_B
3824 */
3825 #if defined(CONFIG_PREEMPT_RT) || !defined(CONFIG_LOCKDEP)
3826 #define local_lock_cpu_slab(s, flags) \
3827 local_lock_irqsave(&(s)->cpu_slab->lock, flags)
3828 #else
3829 #define local_lock_cpu_slab(s, flags) \
3830 do { \
3831 bool __l = local_trylock_irqsave(&(s)->cpu_slab->lock, flags); \
3832 lockdep_assert(__l); \
3833 } while (0)
3834 #endif
3835
3836 #define local_unlock_cpu_slab(s, flags) \
3837 local_unlock_irqrestore(&(s)->cpu_slab->lock, flags)
3838
3839 #ifdef CONFIG_SLUB_CPU_PARTIAL
__put_partials(struct kmem_cache * s,struct slab * partial_slab)3840 static void __put_partials(struct kmem_cache *s, struct slab *partial_slab)
3841 {
3842 struct kmem_cache_node *n = NULL, *n2 = NULL;
3843 struct slab *slab, *slab_to_discard = NULL;
3844 unsigned long flags = 0;
3845
3846 while (partial_slab) {
3847 slab = partial_slab;
3848 partial_slab = slab->next;
3849
3850 n2 = get_node(s, slab_nid(slab));
3851 if (n != n2) {
3852 if (n)
3853 spin_unlock_irqrestore(&n->list_lock, flags);
3854
3855 n = n2;
3856 spin_lock_irqsave(&n->list_lock, flags);
3857 }
3858
3859 if (unlikely(!slab->inuse && n->nr_partial >= s->min_partial)) {
3860 slab->next = slab_to_discard;
3861 slab_to_discard = slab;
3862 } else {
3863 add_partial(n, slab, DEACTIVATE_TO_TAIL);
3864 stat(s, FREE_ADD_PARTIAL);
3865 }
3866 }
3867
3868 if (n)
3869 spin_unlock_irqrestore(&n->list_lock, flags);
3870
3871 while (slab_to_discard) {
3872 slab = slab_to_discard;
3873 slab_to_discard = slab_to_discard->next;
3874
3875 stat(s, DEACTIVATE_EMPTY);
3876 discard_slab(s, slab);
3877 stat(s, FREE_SLAB);
3878 }
3879 }
3880
3881 /*
3882 * Put all the cpu partial slabs to the node partial list.
3883 */
put_partials(struct kmem_cache * s)3884 static void put_partials(struct kmem_cache *s)
3885 {
3886 struct slab *partial_slab;
3887 unsigned long flags;
3888
3889 local_lock_irqsave(&s->cpu_slab->lock, flags);
3890 partial_slab = this_cpu_read(s->cpu_slab->partial);
3891 this_cpu_write(s->cpu_slab->partial, NULL);
3892 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3893
3894 if (partial_slab)
3895 __put_partials(s, partial_slab);
3896 }
3897
put_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)3898 static void put_partials_cpu(struct kmem_cache *s,
3899 struct kmem_cache_cpu *c)
3900 {
3901 struct slab *partial_slab;
3902
3903 partial_slab = slub_percpu_partial(c);
3904 c->partial = NULL;
3905
3906 if (partial_slab)
3907 __put_partials(s, partial_slab);
3908 }
3909
3910 /*
3911 * Put a slab into a partial slab slot if available.
3912 *
3913 * If we did not find a slot then simply move all the partials to the
3914 * per node partial list.
3915 */
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)3916 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
3917 {
3918 struct slab *oldslab;
3919 struct slab *slab_to_put = NULL;
3920 unsigned long flags;
3921 int slabs = 0;
3922
3923 local_lock_cpu_slab(s, flags);
3924
3925 oldslab = this_cpu_read(s->cpu_slab->partial);
3926
3927 if (oldslab) {
3928 if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
3929 /*
3930 * Partial array is full. Move the existing set to the
3931 * per node partial list. Postpone the actual unfreezing
3932 * outside of the critical section.
3933 */
3934 slab_to_put = oldslab;
3935 oldslab = NULL;
3936 } else {
3937 slabs = oldslab->slabs;
3938 }
3939 }
3940
3941 slabs++;
3942
3943 slab->slabs = slabs;
3944 slab->next = oldslab;
3945
3946 this_cpu_write(s->cpu_slab->partial, slab);
3947
3948 local_unlock_cpu_slab(s, flags);
3949
3950 if (slab_to_put) {
3951 __put_partials(s, slab_to_put);
3952 stat(s, CPU_PARTIAL_DRAIN);
3953 }
3954 }
3955
3956 #else /* CONFIG_SLUB_CPU_PARTIAL */
3957
put_partials(struct kmem_cache * s)3958 static inline void put_partials(struct kmem_cache *s) { }
put_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)3959 static inline void put_partials_cpu(struct kmem_cache *s,
3960 struct kmem_cache_cpu *c) { }
3961
3962 #endif /* CONFIG_SLUB_CPU_PARTIAL */
3963
flush_slab(struct kmem_cache * s,struct kmem_cache_cpu * c)3964 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
3965 {
3966 unsigned long flags;
3967 struct slab *slab;
3968 void *freelist;
3969
3970 local_lock_irqsave(&s->cpu_slab->lock, flags);
3971
3972 slab = c->slab;
3973 freelist = c->freelist;
3974
3975 c->slab = NULL;
3976 c->freelist = NULL;
3977 c->tid = next_tid(c->tid);
3978
3979 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3980
3981 if (slab) {
3982 deactivate_slab(s, slab, freelist);
3983 stat(s, CPUSLAB_FLUSH);
3984 }
3985 }
3986
__flush_cpu_slab(struct kmem_cache * s,int cpu)3987 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
3988 {
3989 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
3990 void *freelist = c->freelist;
3991 struct slab *slab = c->slab;
3992
3993 c->slab = NULL;
3994 c->freelist = NULL;
3995 c->tid = next_tid(c->tid);
3996
3997 if (slab) {
3998 deactivate_slab(s, slab, freelist);
3999 stat(s, CPUSLAB_FLUSH);
4000 }
4001
4002 put_partials_cpu(s, c);
4003 }
4004
flush_this_cpu_slab(struct kmem_cache * s)4005 static inline void flush_this_cpu_slab(struct kmem_cache *s)
4006 {
4007 struct kmem_cache_cpu *c = this_cpu_ptr(s->cpu_slab);
4008
4009 if (c->slab)
4010 flush_slab(s, c);
4011
4012 put_partials(s);
4013 }
4014
has_cpu_slab(int cpu,struct kmem_cache * s)4015 static bool has_cpu_slab(int cpu, struct kmem_cache *s)
4016 {
4017 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
4018
4019 return c->slab || slub_percpu_partial(c);
4020 }
4021
4022 #else /* CONFIG_SLUB_TINY */
__flush_cpu_slab(struct kmem_cache * s,int cpu)4023 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { }
has_cpu_slab(int cpu,struct kmem_cache * s)4024 static inline bool has_cpu_slab(int cpu, struct kmem_cache *s) { return false; }
flush_this_cpu_slab(struct kmem_cache * s)4025 static inline void flush_this_cpu_slab(struct kmem_cache *s) { }
4026 #endif /* CONFIG_SLUB_TINY */
4027
has_pcs_used(int cpu,struct kmem_cache * s)4028 static bool has_pcs_used(int cpu, struct kmem_cache *s)
4029 {
4030 struct slub_percpu_sheaves *pcs;
4031
4032 if (!s->cpu_sheaves)
4033 return false;
4034
4035 pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
4036
4037 return (pcs->spare || pcs->rcu_free || pcs->main->size);
4038 }
4039
4040 /*
4041 * Flush cpu slab.
4042 *
4043 * Called from CPU work handler with migration disabled.
4044 */
flush_cpu_slab(struct work_struct * w)4045 static void flush_cpu_slab(struct work_struct *w)
4046 {
4047 struct kmem_cache *s;
4048 struct slub_flush_work *sfw;
4049
4050 sfw = container_of(w, struct slub_flush_work, work);
4051
4052 s = sfw->s;
4053
4054 if (s->cpu_sheaves)
4055 pcs_flush_all(s);
4056
4057 flush_this_cpu_slab(s);
4058 }
4059
flush_all_cpus_locked(struct kmem_cache * s)4060 static void flush_all_cpus_locked(struct kmem_cache *s)
4061 {
4062 struct slub_flush_work *sfw;
4063 unsigned int cpu;
4064
4065 lockdep_assert_cpus_held();
4066 mutex_lock(&flush_lock);
4067
4068 for_each_online_cpu(cpu) {
4069 sfw = &per_cpu(slub_flush, cpu);
4070 if (!has_cpu_slab(cpu, s) && !has_pcs_used(cpu, s)) {
4071 sfw->skip = true;
4072 continue;
4073 }
4074 INIT_WORK(&sfw->work, flush_cpu_slab);
4075 sfw->skip = false;
4076 sfw->s = s;
4077 queue_work_on(cpu, flushwq, &sfw->work);
4078 }
4079
4080 for_each_online_cpu(cpu) {
4081 sfw = &per_cpu(slub_flush, cpu);
4082 if (sfw->skip)
4083 continue;
4084 flush_work(&sfw->work);
4085 }
4086
4087 mutex_unlock(&flush_lock);
4088 }
4089
flush_all(struct kmem_cache * s)4090 static void flush_all(struct kmem_cache *s)
4091 {
4092 cpus_read_lock();
4093 flush_all_cpus_locked(s);
4094 cpus_read_unlock();
4095 }
4096
flush_rcu_sheaf(struct work_struct * w)4097 static void flush_rcu_sheaf(struct work_struct *w)
4098 {
4099 struct slub_percpu_sheaves *pcs;
4100 struct slab_sheaf *rcu_free;
4101 struct slub_flush_work *sfw;
4102 struct kmem_cache *s;
4103
4104 sfw = container_of(w, struct slub_flush_work, work);
4105 s = sfw->s;
4106
4107 local_lock(&s->cpu_sheaves->lock);
4108 pcs = this_cpu_ptr(s->cpu_sheaves);
4109
4110 rcu_free = pcs->rcu_free;
4111 pcs->rcu_free = NULL;
4112
4113 local_unlock(&s->cpu_sheaves->lock);
4114
4115 if (rcu_free)
4116 call_rcu(&rcu_free->rcu_head, rcu_free_sheaf_nobarn);
4117 }
4118
4119
4120 /* needed for kvfree_rcu_barrier() */
flush_all_rcu_sheaves(void)4121 void flush_all_rcu_sheaves(void)
4122 {
4123 struct slub_flush_work *sfw;
4124 struct kmem_cache *s;
4125 unsigned int cpu;
4126
4127 cpus_read_lock();
4128 mutex_lock(&slab_mutex);
4129
4130 list_for_each_entry(s, &slab_caches, list) {
4131 if (!s->cpu_sheaves)
4132 continue;
4133
4134 mutex_lock(&flush_lock);
4135
4136 for_each_online_cpu(cpu) {
4137 sfw = &per_cpu(slub_flush, cpu);
4138
4139 /*
4140 * we don't check if rcu_free sheaf exists - racing
4141 * __kfree_rcu_sheaf() might have just removed it.
4142 * by executing flush_rcu_sheaf() on the cpu we make
4143 * sure the __kfree_rcu_sheaf() finished its call_rcu()
4144 */
4145
4146 INIT_WORK(&sfw->work, flush_rcu_sheaf);
4147 sfw->s = s;
4148 queue_work_on(cpu, flushwq, &sfw->work);
4149 }
4150
4151 for_each_online_cpu(cpu) {
4152 sfw = &per_cpu(slub_flush, cpu);
4153 flush_work(&sfw->work);
4154 }
4155
4156 mutex_unlock(&flush_lock);
4157 }
4158
4159 mutex_unlock(&slab_mutex);
4160 cpus_read_unlock();
4161
4162 rcu_barrier();
4163 }
4164
4165 /*
4166 * Use the cpu notifier to insure that the cpu slabs are flushed when
4167 * necessary.
4168 */
slub_cpu_dead(unsigned int cpu)4169 static int slub_cpu_dead(unsigned int cpu)
4170 {
4171 struct kmem_cache *s;
4172
4173 mutex_lock(&slab_mutex);
4174 list_for_each_entry(s, &slab_caches, list) {
4175 __flush_cpu_slab(s, cpu);
4176 if (s->cpu_sheaves)
4177 __pcs_flush_all_cpu(s, cpu);
4178 }
4179 mutex_unlock(&slab_mutex);
4180 return 0;
4181 }
4182
4183 /*
4184 * Check if the objects in a per cpu structure fit numa
4185 * locality expectations.
4186 */
node_match(struct slab * slab,int node)4187 static inline int node_match(struct slab *slab, int node)
4188 {
4189 #ifdef CONFIG_NUMA
4190 if (node != NUMA_NO_NODE && slab_nid(slab) != node)
4191 return 0;
4192 #endif
4193 return 1;
4194 }
4195
4196 #ifdef CONFIG_SLUB_DEBUG
count_free(struct slab * slab)4197 static int count_free(struct slab *slab)
4198 {
4199 return slab->objects - slab->inuse;
4200 }
4201
node_nr_objs(struct kmem_cache_node * n)4202 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
4203 {
4204 return atomic_long_read(&n->total_objects);
4205 }
4206
4207 /* Supports checking bulk free of a constructed freelist */
free_debug_processing(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int * bulk_cnt,unsigned long addr,depot_stack_handle_t handle)4208 static inline bool free_debug_processing(struct kmem_cache *s,
4209 struct slab *slab, void *head, void *tail, int *bulk_cnt,
4210 unsigned long addr, depot_stack_handle_t handle)
4211 {
4212 bool checks_ok = false;
4213 void *object = head;
4214 int cnt = 0;
4215
4216 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
4217 if (!check_slab(s, slab))
4218 goto out;
4219 }
4220
4221 if (slab->inuse < *bulk_cnt) {
4222 slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
4223 slab->inuse, *bulk_cnt);
4224 goto out;
4225 }
4226
4227 next_object:
4228
4229 if (++cnt > *bulk_cnt)
4230 goto out_cnt;
4231
4232 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
4233 if (!free_consistency_checks(s, slab, object, addr))
4234 goto out;
4235 }
4236
4237 if (s->flags & SLAB_STORE_USER)
4238 set_track_update(s, object, TRACK_FREE, addr, handle);
4239 trace(s, slab, object, 0);
4240 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
4241 init_object(s, object, SLUB_RED_INACTIVE);
4242
4243 /* Reached end of constructed freelist yet? */
4244 if (object != tail) {
4245 object = get_freepointer(s, object);
4246 goto next_object;
4247 }
4248 checks_ok = true;
4249
4250 out_cnt:
4251 if (cnt != *bulk_cnt) {
4252 slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
4253 *bulk_cnt, cnt);
4254 *bulk_cnt = cnt;
4255 }
4256
4257 out:
4258
4259 if (!checks_ok)
4260 slab_fix(s, "Object at 0x%p not freed", object);
4261
4262 return checks_ok;
4263 }
4264 #endif /* CONFIG_SLUB_DEBUG */
4265
4266 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
count_partial(struct kmem_cache_node * n,int (* get_count)(struct slab *))4267 static unsigned long count_partial(struct kmem_cache_node *n,
4268 int (*get_count)(struct slab *))
4269 {
4270 unsigned long flags;
4271 unsigned long x = 0;
4272 struct slab *slab;
4273
4274 spin_lock_irqsave(&n->list_lock, flags);
4275 list_for_each_entry(slab, &n->partial, slab_list)
4276 x += get_count(slab);
4277 spin_unlock_irqrestore(&n->list_lock, flags);
4278 return x;
4279 }
4280 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
4281
4282 #ifdef CONFIG_SLUB_DEBUG
4283 #define MAX_PARTIAL_TO_SCAN 10000
4284
count_partial_free_approx(struct kmem_cache_node * n)4285 static unsigned long count_partial_free_approx(struct kmem_cache_node *n)
4286 {
4287 unsigned long flags;
4288 unsigned long x = 0;
4289 struct slab *slab;
4290
4291 spin_lock_irqsave(&n->list_lock, flags);
4292 if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
4293 list_for_each_entry(slab, &n->partial, slab_list)
4294 x += slab->objects - slab->inuse;
4295 } else {
4296 /*
4297 * For a long list, approximate the total count of objects in
4298 * it to meet the limit on the number of slabs to scan.
4299 * Scan from both the list's head and tail for better accuracy.
4300 */
4301 unsigned long scanned = 0;
4302
4303 list_for_each_entry(slab, &n->partial, slab_list) {
4304 x += slab->objects - slab->inuse;
4305 if (++scanned == MAX_PARTIAL_TO_SCAN / 2)
4306 break;
4307 }
4308 list_for_each_entry_reverse(slab, &n->partial, slab_list) {
4309 x += slab->objects - slab->inuse;
4310 if (++scanned == MAX_PARTIAL_TO_SCAN)
4311 break;
4312 }
4313 x = mult_frac(x, n->nr_partial, scanned);
4314 x = min(x, node_nr_objs(n));
4315 }
4316 spin_unlock_irqrestore(&n->list_lock, flags);
4317 return x;
4318 }
4319
4320 static noinline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)4321 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
4322 {
4323 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
4324 DEFAULT_RATELIMIT_BURST);
4325 int cpu = raw_smp_processor_id();
4326 int node;
4327 struct kmem_cache_node *n;
4328
4329 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
4330 return;
4331
4332 pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
4333 cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
4334 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
4335 s->name, s->object_size, s->size, oo_order(s->oo),
4336 oo_order(s->min));
4337
4338 if (oo_order(s->min) > get_order(s->object_size))
4339 pr_warn(" %s debugging increased min order, use slab_debug=O to disable.\n",
4340 s->name);
4341
4342 for_each_kmem_cache_node(s, node, n) {
4343 unsigned long nr_slabs;
4344 unsigned long nr_objs;
4345 unsigned long nr_free;
4346
4347 nr_free = count_partial_free_approx(n);
4348 nr_slabs = node_nr_slabs(n);
4349 nr_objs = node_nr_objs(n);
4350
4351 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
4352 node, nr_slabs, nr_objs, nr_free);
4353 }
4354 }
4355 #else /* CONFIG_SLUB_DEBUG */
4356 static inline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)4357 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
4358 #endif
4359
pfmemalloc_match(struct slab * slab,gfp_t gfpflags)4360 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
4361 {
4362 if (unlikely(slab_test_pfmemalloc(slab)))
4363 return gfp_pfmemalloc_allowed(gfpflags);
4364
4365 return true;
4366 }
4367
4368 #ifndef CONFIG_SLUB_TINY
4369 static inline bool
__update_cpu_freelist_fast(struct kmem_cache * s,void * freelist_old,void * freelist_new,unsigned long tid)4370 __update_cpu_freelist_fast(struct kmem_cache *s,
4371 void *freelist_old, void *freelist_new,
4372 unsigned long tid)
4373 {
4374 freelist_aba_t old = { .freelist = freelist_old, .counter = tid };
4375 freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) };
4376
4377 return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full,
4378 &old.full, new.full);
4379 }
4380
4381 /*
4382 * Check the slab->freelist and either transfer the freelist to the
4383 * per cpu freelist or deactivate the slab.
4384 *
4385 * The slab is still frozen if the return value is not NULL.
4386 *
4387 * If this function returns NULL then the slab has been unfrozen.
4388 */
get_freelist(struct kmem_cache * s,struct slab * slab)4389 static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
4390 {
4391 struct slab new;
4392 unsigned long counters;
4393 void *freelist;
4394
4395 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
4396
4397 do {
4398 freelist = slab->freelist;
4399 counters = slab->counters;
4400
4401 new.counters = counters;
4402
4403 new.inuse = slab->objects;
4404 new.frozen = freelist != NULL;
4405
4406 } while (!__slab_update_freelist(s, slab,
4407 freelist, counters,
4408 NULL, new.counters,
4409 "get_freelist"));
4410
4411 return freelist;
4412 }
4413
4414 /*
4415 * Freeze the partial slab and return the pointer to the freelist.
4416 */
freeze_slab(struct kmem_cache * s,struct slab * slab)4417 static inline void *freeze_slab(struct kmem_cache *s, struct slab *slab)
4418 {
4419 struct slab new;
4420 unsigned long counters;
4421 void *freelist;
4422
4423 do {
4424 freelist = slab->freelist;
4425 counters = slab->counters;
4426
4427 new.counters = counters;
4428 VM_BUG_ON(new.frozen);
4429
4430 new.inuse = slab->objects;
4431 new.frozen = 1;
4432
4433 } while (!slab_update_freelist(s, slab,
4434 freelist, counters,
4435 NULL, new.counters,
4436 "freeze_slab"));
4437
4438 return freelist;
4439 }
4440
4441 /*
4442 * Slow path. The lockless freelist is empty or we need to perform
4443 * debugging duties.
4444 *
4445 * Processing is still very fast if new objects have been freed to the
4446 * regular freelist. In that case we simply take over the regular freelist
4447 * as the lockless freelist and zap the regular freelist.
4448 *
4449 * If that is not working then we fall back to the partial lists. We take the
4450 * first element of the freelist as the object to allocate now and move the
4451 * rest of the freelist to the lockless freelist.
4452 *
4453 * And if we were unable to get a new slab from the partial slab lists then
4454 * we need to allocate a new slab. This is the slowest path since it involves
4455 * a call to the page allocator and the setup of a new slab.
4456 *
4457 * Version of __slab_alloc to use when we know that preemption is
4458 * already disabled (which is the case for bulk allocation).
4459 */
___slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)4460 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
4461 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
4462 {
4463 bool allow_spin = gfpflags_allow_spinning(gfpflags);
4464 void *freelist;
4465 struct slab *slab;
4466 unsigned long flags;
4467 struct partial_context pc;
4468 bool try_thisnode = true;
4469
4470 stat(s, ALLOC_SLOWPATH);
4471
4472 reread_slab:
4473
4474 slab = READ_ONCE(c->slab);
4475 if (!slab) {
4476 /*
4477 * if the node is not online or has no normal memory, just
4478 * ignore the node constraint
4479 */
4480 if (unlikely(node != NUMA_NO_NODE &&
4481 !node_isset(node, slab_nodes)))
4482 node = NUMA_NO_NODE;
4483 goto new_slab;
4484 }
4485
4486 if (unlikely(!node_match(slab, node))) {
4487 /*
4488 * same as above but node_match() being false already
4489 * implies node != NUMA_NO_NODE.
4490 *
4491 * We don't strictly honor pfmemalloc and NUMA preferences
4492 * when !allow_spin because:
4493 *
4494 * 1. Most kmalloc() users allocate objects on the local node,
4495 * so kmalloc_nolock() tries not to interfere with them by
4496 * deactivating the cpu slab.
4497 *
4498 * 2. Deactivating due to NUMA or pfmemalloc mismatch may cause
4499 * unnecessary slab allocations even when n->partial list
4500 * is not empty.
4501 */
4502 if (!node_isset(node, slab_nodes) ||
4503 !allow_spin) {
4504 node = NUMA_NO_NODE;
4505 } else {
4506 stat(s, ALLOC_NODE_MISMATCH);
4507 goto deactivate_slab;
4508 }
4509 }
4510
4511 /*
4512 * By rights, we should be searching for a slab page that was
4513 * PFMEMALLOC but right now, we are losing the pfmemalloc
4514 * information when the page leaves the per-cpu allocator
4515 */
4516 if (unlikely(!pfmemalloc_match(slab, gfpflags) && allow_spin))
4517 goto deactivate_slab;
4518
4519 /* must check again c->slab in case we got preempted and it changed */
4520 local_lock_cpu_slab(s, flags);
4521
4522 if (unlikely(slab != c->slab)) {
4523 local_unlock_cpu_slab(s, flags);
4524 goto reread_slab;
4525 }
4526 freelist = c->freelist;
4527 if (freelist)
4528 goto load_freelist;
4529
4530 freelist = get_freelist(s, slab);
4531
4532 if (!freelist) {
4533 c->slab = NULL;
4534 c->tid = next_tid(c->tid);
4535 local_unlock_cpu_slab(s, flags);
4536 stat(s, DEACTIVATE_BYPASS);
4537 goto new_slab;
4538 }
4539
4540 stat(s, ALLOC_REFILL);
4541
4542 load_freelist:
4543
4544 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
4545
4546 /*
4547 * freelist is pointing to the list of objects to be used.
4548 * slab is pointing to the slab from which the objects are obtained.
4549 * That slab must be frozen for per cpu allocations to work.
4550 */
4551 VM_BUG_ON(!c->slab->frozen);
4552 c->freelist = get_freepointer(s, freelist);
4553 c->tid = next_tid(c->tid);
4554 local_unlock_cpu_slab(s, flags);
4555 return freelist;
4556
4557 deactivate_slab:
4558
4559 local_lock_cpu_slab(s, flags);
4560 if (slab != c->slab) {
4561 local_unlock_cpu_slab(s, flags);
4562 goto reread_slab;
4563 }
4564 freelist = c->freelist;
4565 c->slab = NULL;
4566 c->freelist = NULL;
4567 c->tid = next_tid(c->tid);
4568 local_unlock_cpu_slab(s, flags);
4569 deactivate_slab(s, slab, freelist);
4570
4571 new_slab:
4572
4573 #ifdef CONFIG_SLUB_CPU_PARTIAL
4574 while (slub_percpu_partial(c)) {
4575 local_lock_cpu_slab(s, flags);
4576 if (unlikely(c->slab)) {
4577 local_unlock_cpu_slab(s, flags);
4578 goto reread_slab;
4579 }
4580 if (unlikely(!slub_percpu_partial(c))) {
4581 local_unlock_cpu_slab(s, flags);
4582 /* we were preempted and partial list got empty */
4583 goto new_objects;
4584 }
4585
4586 slab = slub_percpu_partial(c);
4587 slub_set_percpu_partial(c, slab);
4588
4589 if (likely(node_match(slab, node) &&
4590 pfmemalloc_match(slab, gfpflags)) ||
4591 !allow_spin) {
4592 c->slab = slab;
4593 freelist = get_freelist(s, slab);
4594 VM_BUG_ON(!freelist);
4595 stat(s, CPU_PARTIAL_ALLOC);
4596 goto load_freelist;
4597 }
4598
4599 local_unlock_cpu_slab(s, flags);
4600
4601 slab->next = NULL;
4602 __put_partials(s, slab);
4603 }
4604 #endif
4605
4606 new_objects:
4607
4608 pc.flags = gfpflags;
4609 /*
4610 * When a preferred node is indicated but no __GFP_THISNODE
4611 *
4612 * 1) try to get a partial slab from target node only by having
4613 * __GFP_THISNODE in pc.flags for get_partial()
4614 * 2) if 1) failed, try to allocate a new slab from target node with
4615 * GPF_NOWAIT | __GFP_THISNODE opportunistically
4616 * 3) if 2) failed, retry with original gfpflags which will allow
4617 * get_partial() try partial lists of other nodes before potentially
4618 * allocating new page from other nodes
4619 */
4620 if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
4621 && try_thisnode)) {
4622 if (unlikely(!allow_spin))
4623 /* Do not upgrade gfp to NOWAIT from more restrictive mode */
4624 pc.flags = gfpflags | __GFP_THISNODE;
4625 else
4626 pc.flags = GFP_NOWAIT | __GFP_THISNODE;
4627 }
4628
4629 pc.orig_size = orig_size;
4630 slab = get_partial(s, node, &pc);
4631 if (slab) {
4632 if (kmem_cache_debug(s)) {
4633 freelist = pc.object;
4634 /*
4635 * For debug caches here we had to go through
4636 * alloc_single_from_partial() so just store the
4637 * tracking info and return the object.
4638 *
4639 * Due to disabled preemption we need to disallow
4640 * blocking. The flags are further adjusted by
4641 * gfp_nested_mask() in stack_depot itself.
4642 */
4643 if (s->flags & SLAB_STORE_USER)
4644 set_track(s, freelist, TRACK_ALLOC, addr,
4645 gfpflags & ~(__GFP_DIRECT_RECLAIM));
4646
4647 return freelist;
4648 }
4649
4650 freelist = freeze_slab(s, slab);
4651 goto retry_load_slab;
4652 }
4653
4654 slub_put_cpu_ptr(s->cpu_slab);
4655 slab = new_slab(s, pc.flags, node);
4656 c = slub_get_cpu_ptr(s->cpu_slab);
4657
4658 if (unlikely(!slab)) {
4659 if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
4660 && try_thisnode) {
4661 try_thisnode = false;
4662 goto new_objects;
4663 }
4664 slab_out_of_memory(s, gfpflags, node);
4665 return NULL;
4666 }
4667
4668 stat(s, ALLOC_SLAB);
4669
4670 if (kmem_cache_debug(s)) {
4671 freelist = alloc_single_from_new_slab(s, slab, orig_size, gfpflags);
4672
4673 if (unlikely(!freelist)) {
4674 /* This could cause an endless loop. Fail instead. */
4675 if (!allow_spin)
4676 return NULL;
4677 goto new_objects;
4678 }
4679
4680 if (s->flags & SLAB_STORE_USER)
4681 set_track(s, freelist, TRACK_ALLOC, addr,
4682 gfpflags & ~(__GFP_DIRECT_RECLAIM));
4683
4684 return freelist;
4685 }
4686
4687 /*
4688 * No other reference to the slab yet so we can
4689 * muck around with it freely without cmpxchg
4690 */
4691 freelist = slab->freelist;
4692 slab->freelist = NULL;
4693 slab->inuse = slab->objects;
4694 slab->frozen = 1;
4695
4696 inc_slabs_node(s, slab_nid(slab), slab->objects);
4697
4698 if (unlikely(!pfmemalloc_match(slab, gfpflags) && allow_spin)) {
4699 /*
4700 * For !pfmemalloc_match() case we don't load freelist so that
4701 * we don't make further mismatched allocations easier.
4702 */
4703 deactivate_slab(s, slab, get_freepointer(s, freelist));
4704 return freelist;
4705 }
4706
4707 retry_load_slab:
4708
4709 local_lock_cpu_slab(s, flags);
4710 if (unlikely(c->slab)) {
4711 void *flush_freelist = c->freelist;
4712 struct slab *flush_slab = c->slab;
4713
4714 c->slab = NULL;
4715 c->freelist = NULL;
4716 c->tid = next_tid(c->tid);
4717
4718 local_unlock_cpu_slab(s, flags);
4719
4720 if (unlikely(!allow_spin)) {
4721 /* Reentrant slub cannot take locks, defer */
4722 defer_deactivate_slab(flush_slab, flush_freelist);
4723 } else {
4724 deactivate_slab(s, flush_slab, flush_freelist);
4725 }
4726
4727 stat(s, CPUSLAB_FLUSH);
4728
4729 goto retry_load_slab;
4730 }
4731 c->slab = slab;
4732
4733 goto load_freelist;
4734 }
4735 /*
4736 * We disallow kprobes in ___slab_alloc() to prevent reentrance
4737 *
4738 * kmalloc() -> ___slab_alloc() -> local_lock_cpu_slab() protected part of
4739 * ___slab_alloc() manipulating c->freelist -> kprobe -> bpf ->
4740 * kmalloc_nolock() or kfree_nolock() -> __update_cpu_freelist_fast()
4741 * manipulating c->freelist without lock.
4742 *
4743 * This does not prevent kprobe in functions called from ___slab_alloc() such as
4744 * local_lock_irqsave() itself, and that is fine, we only need to protect the
4745 * c->freelist manipulation in ___slab_alloc() itself.
4746 */
4747 NOKPROBE_SYMBOL(___slab_alloc);
4748
4749 /*
4750 * A wrapper for ___slab_alloc() for contexts where preemption is not yet
4751 * disabled. Compensates for possible cpu changes by refetching the per cpu area
4752 * pointer.
4753 */
__slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)4754 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
4755 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
4756 {
4757 void *p;
4758
4759 #ifdef CONFIG_PREEMPT_COUNT
4760 /*
4761 * We may have been preempted and rescheduled on a different
4762 * cpu before disabling preemption. Need to reload cpu area
4763 * pointer.
4764 */
4765 c = slub_get_cpu_ptr(s->cpu_slab);
4766 #endif
4767 if (unlikely(!gfpflags_allow_spinning(gfpflags))) {
4768 if (local_lock_is_locked(&s->cpu_slab->lock)) {
4769 /*
4770 * EBUSY is an internal signal to kmalloc_nolock() to
4771 * retry a different bucket. It's not propagated
4772 * to the caller.
4773 */
4774 p = ERR_PTR(-EBUSY);
4775 goto out;
4776 }
4777 }
4778 p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
4779 out:
4780 #ifdef CONFIG_PREEMPT_COUNT
4781 slub_put_cpu_ptr(s->cpu_slab);
4782 #endif
4783 return p;
4784 }
4785
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)4786 static __always_inline void *__slab_alloc_node(struct kmem_cache *s,
4787 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4788 {
4789 struct kmem_cache_cpu *c;
4790 struct slab *slab;
4791 unsigned long tid;
4792 void *object;
4793
4794 redo:
4795 /*
4796 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
4797 * enabled. We may switch back and forth between cpus while
4798 * reading from one cpu area. That does not matter as long
4799 * as we end up on the original cpu again when doing the cmpxchg.
4800 *
4801 * We must guarantee that tid and kmem_cache_cpu are retrieved on the
4802 * same cpu. We read first the kmem_cache_cpu pointer and use it to read
4803 * the tid. If we are preempted and switched to another cpu between the
4804 * two reads, it's OK as the two are still associated with the same cpu
4805 * and cmpxchg later will validate the cpu.
4806 */
4807 c = raw_cpu_ptr(s->cpu_slab);
4808 tid = READ_ONCE(c->tid);
4809
4810 /*
4811 * Irqless object alloc/free algorithm used here depends on sequence
4812 * of fetching cpu_slab's data. tid should be fetched before anything
4813 * on c to guarantee that object and slab associated with previous tid
4814 * won't be used with current tid. If we fetch tid first, object and
4815 * slab could be one associated with next tid and our alloc/free
4816 * request will be failed. In this case, we will retry. So, no problem.
4817 */
4818 barrier();
4819
4820 /*
4821 * The transaction ids are globally unique per cpu and per operation on
4822 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
4823 * occurs on the right processor and that there was no operation on the
4824 * linked list in between.
4825 */
4826
4827 object = c->freelist;
4828 slab = c->slab;
4829
4830 #ifdef CONFIG_NUMA
4831 if (static_branch_unlikely(&strict_numa) &&
4832 node == NUMA_NO_NODE) {
4833
4834 struct mempolicy *mpol = current->mempolicy;
4835
4836 if (mpol) {
4837 /*
4838 * Special BIND rule support. If existing slab
4839 * is in permitted set then do not redirect
4840 * to a particular node.
4841 * Otherwise we apply the memory policy to get
4842 * the node we need to allocate on.
4843 */
4844 if (mpol->mode != MPOL_BIND || !slab ||
4845 !node_isset(slab_nid(slab), mpol->nodes))
4846
4847 node = mempolicy_slab_node();
4848 }
4849 }
4850 #endif
4851
4852 if (!USE_LOCKLESS_FAST_PATH() ||
4853 unlikely(!object || !slab || !node_match(slab, node))) {
4854 object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
4855 } else {
4856 void *next_object = get_freepointer_safe(s, object);
4857
4858 /*
4859 * The cmpxchg will only match if there was no additional
4860 * operation and if we are on the right processor.
4861 *
4862 * The cmpxchg does the following atomically (without lock
4863 * semantics!)
4864 * 1. Relocate first pointer to the current per cpu area.
4865 * 2. Verify that tid and freelist have not been changed
4866 * 3. If they were not changed replace tid and freelist
4867 *
4868 * Since this is without lock semantics the protection is only
4869 * against code executing on this cpu *not* from access by
4870 * other cpus.
4871 */
4872 if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
4873 note_cmpxchg_failure("slab_alloc", s, tid);
4874 goto redo;
4875 }
4876 prefetch_freepointer(s, next_object);
4877 stat(s, ALLOC_FASTPATH);
4878 }
4879
4880 return object;
4881 }
4882 #else /* CONFIG_SLUB_TINY */
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)4883 static void *__slab_alloc_node(struct kmem_cache *s,
4884 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4885 {
4886 struct partial_context pc;
4887 struct slab *slab;
4888 void *object;
4889
4890 pc.flags = gfpflags;
4891 pc.orig_size = orig_size;
4892 slab = get_partial(s, node, &pc);
4893
4894 if (slab)
4895 return pc.object;
4896
4897 slab = new_slab(s, gfpflags, node);
4898 if (unlikely(!slab)) {
4899 slab_out_of_memory(s, gfpflags, node);
4900 return NULL;
4901 }
4902
4903 object = alloc_single_from_new_slab(s, slab, orig_size, gfpflags);
4904
4905 return object;
4906 }
4907 #endif /* CONFIG_SLUB_TINY */
4908
4909 /*
4910 * If the object has been wiped upon free, make sure it's fully initialized by
4911 * zeroing out freelist pointer.
4912 *
4913 * Note that we also wipe custom freelist pointers.
4914 */
maybe_wipe_obj_freeptr(struct kmem_cache * s,void * obj)4915 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
4916 void *obj)
4917 {
4918 if (unlikely(slab_want_init_on_free(s)) && obj &&
4919 !freeptr_outside_object(s))
4920 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
4921 0, sizeof(void *));
4922 }
4923
4924 static __fastpath_inline
slab_pre_alloc_hook(struct kmem_cache * s,gfp_t flags)4925 struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
4926 {
4927 flags &= gfp_allowed_mask;
4928
4929 might_alloc(flags);
4930
4931 if (unlikely(should_failslab(s, flags)))
4932 return NULL;
4933
4934 return s;
4935 }
4936
4937 static __fastpath_inline
slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p,bool init,unsigned int orig_size)4938 bool slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
4939 gfp_t flags, size_t size, void **p, bool init,
4940 unsigned int orig_size)
4941 {
4942 unsigned int zero_size = s->object_size;
4943 bool kasan_init = init;
4944 size_t i;
4945 gfp_t init_flags = flags & gfp_allowed_mask;
4946
4947 /*
4948 * For kmalloc object, the allocated memory size(object_size) is likely
4949 * larger than the requested size(orig_size). If redzone check is
4950 * enabled for the extra space, don't zero it, as it will be redzoned
4951 * soon. The redzone operation for this extra space could be seen as a
4952 * replacement of current poisoning under certain debug option, and
4953 * won't break other sanity checks.
4954 */
4955 if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) &&
4956 (s->flags & SLAB_KMALLOC))
4957 zero_size = orig_size;
4958
4959 /*
4960 * When slab_debug is enabled, avoid memory initialization integrated
4961 * into KASAN and instead zero out the memory via the memset below with
4962 * the proper size. Otherwise, KASAN might overwrite SLUB redzones and
4963 * cause false-positive reports. This does not lead to a performance
4964 * penalty on production builds, as slab_debug is not intended to be
4965 * enabled there.
4966 */
4967 if (__slub_debug_enabled())
4968 kasan_init = false;
4969
4970 /*
4971 * As memory initialization might be integrated into KASAN,
4972 * kasan_slab_alloc and initialization memset must be
4973 * kept together to avoid discrepancies in behavior.
4974 *
4975 * As p[i] might get tagged, memset and kmemleak hook come after KASAN.
4976 */
4977 for (i = 0; i < size; i++) {
4978 p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init);
4979 if (p[i] && init && (!kasan_init ||
4980 !kasan_has_integrated_init()))
4981 memset(p[i], 0, zero_size);
4982 if (gfpflags_allow_spinning(flags))
4983 kmemleak_alloc_recursive(p[i], s->object_size, 1,
4984 s->flags, init_flags);
4985 kmsan_slab_alloc(s, p[i], init_flags);
4986 alloc_tagging_slab_alloc_hook(s, p[i], flags);
4987 }
4988
4989 return memcg_slab_post_alloc_hook(s, lru, flags, size, p);
4990 }
4991
4992 /*
4993 * Replace the empty main sheaf with a (at least partially) full sheaf.
4994 *
4995 * Must be called with the cpu_sheaves local lock locked. If successful, returns
4996 * the pcs pointer and the local lock locked (possibly on a different cpu than
4997 * initially called). If not successful, returns NULL and the local lock
4998 * unlocked.
4999 */
5000 static struct slub_percpu_sheaves *
__pcs_replace_empty_main(struct kmem_cache * s,struct slub_percpu_sheaves * pcs,gfp_t gfp)5001 __pcs_replace_empty_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs, gfp_t gfp)
5002 {
5003 struct slab_sheaf *empty = NULL;
5004 struct slab_sheaf *full;
5005 struct node_barn *barn;
5006 bool can_alloc;
5007
5008 lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
5009
5010 if (pcs->spare && pcs->spare->size > 0) {
5011 swap(pcs->main, pcs->spare);
5012 return pcs;
5013 }
5014
5015 barn = get_barn(s);
5016 if (!barn) {
5017 local_unlock(&s->cpu_sheaves->lock);
5018 return NULL;
5019 }
5020
5021 full = barn_replace_empty_sheaf(barn, pcs->main);
5022
5023 if (full) {
5024 stat(s, BARN_GET);
5025 pcs->main = full;
5026 return pcs;
5027 }
5028
5029 stat(s, BARN_GET_FAIL);
5030
5031 can_alloc = gfpflags_allow_blocking(gfp);
5032
5033 if (can_alloc) {
5034 if (pcs->spare) {
5035 empty = pcs->spare;
5036 pcs->spare = NULL;
5037 } else {
5038 empty = barn_get_empty_sheaf(barn);
5039 }
5040 }
5041
5042 local_unlock(&s->cpu_sheaves->lock);
5043
5044 if (!can_alloc)
5045 return NULL;
5046
5047 if (empty) {
5048 if (!refill_sheaf(s, empty, gfp)) {
5049 full = empty;
5050 } else {
5051 /*
5052 * we must be very low on memory so don't bother
5053 * with the barn
5054 */
5055 free_empty_sheaf(s, empty);
5056 }
5057 } else {
5058 full = alloc_full_sheaf(s, gfp);
5059 }
5060
5061 if (!full)
5062 return NULL;
5063
5064 /*
5065 * we can reach here only when gfpflags_allow_blocking
5066 * so this must not be an irq
5067 */
5068 local_lock(&s->cpu_sheaves->lock);
5069 pcs = this_cpu_ptr(s->cpu_sheaves);
5070
5071 /*
5072 * If we are returning empty sheaf, we either got it from the
5073 * barn or had to allocate one. If we are returning a full
5074 * sheaf, it's due to racing or being migrated to a different
5075 * cpu. Breaching the barn's sheaf limits should be thus rare
5076 * enough so just ignore them to simplify the recovery.
5077 */
5078
5079 if (pcs->main->size == 0) {
5080 barn_put_empty_sheaf(barn, pcs->main);
5081 pcs->main = full;
5082 return pcs;
5083 }
5084
5085 if (!pcs->spare) {
5086 pcs->spare = full;
5087 return pcs;
5088 }
5089
5090 if (pcs->spare->size == 0) {
5091 barn_put_empty_sheaf(barn, pcs->spare);
5092 pcs->spare = full;
5093 return pcs;
5094 }
5095
5096 barn_put_full_sheaf(barn, full);
5097 stat(s, BARN_PUT);
5098
5099 return pcs;
5100 }
5101
5102 static __fastpath_inline
alloc_from_pcs(struct kmem_cache * s,gfp_t gfp,int node)5103 void *alloc_from_pcs(struct kmem_cache *s, gfp_t gfp, int node)
5104 {
5105 struct slub_percpu_sheaves *pcs;
5106 bool node_requested;
5107 void *object;
5108
5109 #ifdef CONFIG_NUMA
5110 if (static_branch_unlikely(&strict_numa) &&
5111 node == NUMA_NO_NODE) {
5112
5113 struct mempolicy *mpol = current->mempolicy;
5114
5115 if (mpol) {
5116 /*
5117 * Special BIND rule support. If the local node
5118 * is in permitted set then do not redirect
5119 * to a particular node.
5120 * Otherwise we apply the memory policy to get
5121 * the node we need to allocate on.
5122 */
5123 if (mpol->mode != MPOL_BIND ||
5124 !node_isset(numa_mem_id(), mpol->nodes))
5125
5126 node = mempolicy_slab_node();
5127 }
5128 }
5129 #endif
5130
5131 node_requested = IS_ENABLED(CONFIG_NUMA) && node != NUMA_NO_NODE;
5132
5133 /*
5134 * We assume the percpu sheaves contain only local objects although it's
5135 * not completely guaranteed, so we verify later.
5136 */
5137 if (unlikely(node_requested && node != numa_mem_id()))
5138 return NULL;
5139
5140 if (!local_trylock(&s->cpu_sheaves->lock))
5141 return NULL;
5142
5143 pcs = this_cpu_ptr(s->cpu_sheaves);
5144
5145 if (unlikely(pcs->main->size == 0)) {
5146 pcs = __pcs_replace_empty_main(s, pcs, gfp);
5147 if (unlikely(!pcs))
5148 return NULL;
5149 }
5150
5151 object = pcs->main->objects[pcs->main->size - 1];
5152
5153 if (unlikely(node_requested)) {
5154 /*
5155 * Verify that the object was from the node we want. This could
5156 * be false because of cpu migration during an unlocked part of
5157 * the current allocation or previous freeing process.
5158 */
5159 if (folio_nid(virt_to_folio(object)) != node) {
5160 local_unlock(&s->cpu_sheaves->lock);
5161 return NULL;
5162 }
5163 }
5164
5165 pcs->main->size--;
5166
5167 local_unlock(&s->cpu_sheaves->lock);
5168
5169 stat(s, ALLOC_PCS);
5170
5171 return object;
5172 }
5173
5174 static __fastpath_inline
alloc_from_pcs_bulk(struct kmem_cache * s,size_t size,void ** p)5175 unsigned int alloc_from_pcs_bulk(struct kmem_cache *s, size_t size, void **p)
5176 {
5177 struct slub_percpu_sheaves *pcs;
5178 struct slab_sheaf *main;
5179 unsigned int allocated = 0;
5180 unsigned int batch;
5181
5182 next_batch:
5183 if (!local_trylock(&s->cpu_sheaves->lock))
5184 return allocated;
5185
5186 pcs = this_cpu_ptr(s->cpu_sheaves);
5187
5188 if (unlikely(pcs->main->size == 0)) {
5189
5190 struct slab_sheaf *full;
5191 struct node_barn *barn;
5192
5193 if (pcs->spare && pcs->spare->size > 0) {
5194 swap(pcs->main, pcs->spare);
5195 goto do_alloc;
5196 }
5197
5198 barn = get_barn(s);
5199 if (!barn) {
5200 local_unlock(&s->cpu_sheaves->lock);
5201 return allocated;
5202 }
5203
5204 full = barn_replace_empty_sheaf(barn, pcs->main);
5205
5206 if (full) {
5207 stat(s, BARN_GET);
5208 pcs->main = full;
5209 goto do_alloc;
5210 }
5211
5212 stat(s, BARN_GET_FAIL);
5213
5214 local_unlock(&s->cpu_sheaves->lock);
5215
5216 /*
5217 * Once full sheaves in barn are depleted, let the bulk
5218 * allocation continue from slab pages, otherwise we would just
5219 * be copying arrays of pointers twice.
5220 */
5221 return allocated;
5222 }
5223
5224 do_alloc:
5225
5226 main = pcs->main;
5227 batch = min(size, main->size);
5228
5229 main->size -= batch;
5230 memcpy(p, main->objects + main->size, batch * sizeof(void *));
5231
5232 local_unlock(&s->cpu_sheaves->lock);
5233
5234 stat_add(s, ALLOC_PCS, batch);
5235
5236 allocated += batch;
5237
5238 if (batch < size) {
5239 p += batch;
5240 size -= batch;
5241 goto next_batch;
5242 }
5243
5244 return allocated;
5245 }
5246
5247
5248 /*
5249 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
5250 * have the fastpath folded into their functions. So no function call
5251 * overhead for requests that can be satisfied on the fastpath.
5252 *
5253 * The fastpath works by first checking if the lockless freelist can be used.
5254 * If not then __slab_alloc is called for slow processing.
5255 *
5256 * Otherwise we can simply pick the next object from the lockless free list.
5257 */
slab_alloc_node(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)5258 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
5259 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
5260 {
5261 void *object;
5262 bool init = false;
5263
5264 s = slab_pre_alloc_hook(s, gfpflags);
5265 if (unlikely(!s))
5266 return NULL;
5267
5268 object = kfence_alloc(s, orig_size, gfpflags);
5269 if (unlikely(object))
5270 goto out;
5271
5272 if (s->cpu_sheaves)
5273 object = alloc_from_pcs(s, gfpflags, node);
5274
5275 if (!object)
5276 object = __slab_alloc_node(s, gfpflags, node, addr, orig_size);
5277
5278 maybe_wipe_obj_freeptr(s, object);
5279 init = slab_want_init_on_alloc(gfpflags, s);
5280
5281 out:
5282 /*
5283 * When init equals 'true', like for kzalloc() family, only
5284 * @orig_size bytes might be zeroed instead of s->object_size
5285 * In case this fails due to memcg_slab_post_alloc_hook(),
5286 * object is set to NULL
5287 */
5288 slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size);
5289
5290 return object;
5291 }
5292
kmem_cache_alloc_noprof(struct kmem_cache * s,gfp_t gfpflags)5293 void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)
5294 {
5295 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, _RET_IP_,
5296 s->object_size);
5297
5298 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
5299
5300 return ret;
5301 }
5302 EXPORT_SYMBOL(kmem_cache_alloc_noprof);
5303
kmem_cache_alloc_lru_noprof(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags)5304 void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,
5305 gfp_t gfpflags)
5306 {
5307 void *ret = slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, _RET_IP_,
5308 s->object_size);
5309
5310 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
5311
5312 return ret;
5313 }
5314 EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);
5315
kmem_cache_charge(void * objp,gfp_t gfpflags)5316 bool kmem_cache_charge(void *objp, gfp_t gfpflags)
5317 {
5318 if (!memcg_kmem_online())
5319 return true;
5320
5321 return memcg_slab_post_charge(objp, gfpflags);
5322 }
5323 EXPORT_SYMBOL(kmem_cache_charge);
5324
5325 /**
5326 * kmem_cache_alloc_node - Allocate an object on the specified node
5327 * @s: The cache to allocate from.
5328 * @gfpflags: See kmalloc().
5329 * @node: node number of the target node.
5330 *
5331 * Identical to kmem_cache_alloc but it will allocate memory on the given
5332 * node, which can improve the performance for cpu bound structures.
5333 *
5334 * Fallback to other node is possible if __GFP_THISNODE is not set.
5335 *
5336 * Return: pointer to the new object or %NULL in case of error
5337 */
kmem_cache_alloc_node_noprof(struct kmem_cache * s,gfp_t gfpflags,int node)5338 void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
5339 {
5340 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
5341
5342 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
5343
5344 return ret;
5345 }
5346 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
5347
5348 /*
5349 * returns a sheaf that has at least the requested size
5350 * when prefilling is needed, do so with given gfp flags
5351 *
5352 * return NULL if sheaf allocation or prefilling failed
5353 */
5354 struct slab_sheaf *
kmem_cache_prefill_sheaf(struct kmem_cache * s,gfp_t gfp,unsigned int size)5355 kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)
5356 {
5357 struct slub_percpu_sheaves *pcs;
5358 struct slab_sheaf *sheaf = NULL;
5359 struct node_barn *barn;
5360
5361 if (unlikely(size > s->sheaf_capacity)) {
5362
5363 /*
5364 * slab_debug disables cpu sheaves intentionally so all
5365 * prefilled sheaves become "oversize" and we give up on
5366 * performance for the debugging. Same with SLUB_TINY.
5367 * Creating a cache without sheaves and then requesting a
5368 * prefilled sheaf is however not expected, so warn.
5369 */
5370 WARN_ON_ONCE(s->sheaf_capacity == 0 &&
5371 !IS_ENABLED(CONFIG_SLUB_TINY) &&
5372 !(s->flags & SLAB_DEBUG_FLAGS));
5373
5374 sheaf = kzalloc(struct_size(sheaf, objects, size), gfp);
5375 if (!sheaf)
5376 return NULL;
5377
5378 stat(s, SHEAF_PREFILL_OVERSIZE);
5379 sheaf->cache = s;
5380 sheaf->capacity = size;
5381
5382 if (!__kmem_cache_alloc_bulk(s, gfp, size,
5383 &sheaf->objects[0])) {
5384 kfree(sheaf);
5385 return NULL;
5386 }
5387
5388 sheaf->size = size;
5389
5390 return sheaf;
5391 }
5392
5393 local_lock(&s->cpu_sheaves->lock);
5394 pcs = this_cpu_ptr(s->cpu_sheaves);
5395
5396 if (pcs->spare) {
5397 sheaf = pcs->spare;
5398 pcs->spare = NULL;
5399 stat(s, SHEAF_PREFILL_FAST);
5400 } else {
5401 barn = get_barn(s);
5402
5403 stat(s, SHEAF_PREFILL_SLOW);
5404 if (barn)
5405 sheaf = barn_get_full_or_empty_sheaf(barn);
5406 if (sheaf && sheaf->size)
5407 stat(s, BARN_GET);
5408 else
5409 stat(s, BARN_GET_FAIL);
5410 }
5411
5412 local_unlock(&s->cpu_sheaves->lock);
5413
5414
5415 if (!sheaf)
5416 sheaf = alloc_empty_sheaf(s, gfp);
5417
5418 if (sheaf && sheaf->size < size) {
5419 if (refill_sheaf(s, sheaf, gfp)) {
5420 sheaf_flush_unused(s, sheaf);
5421 free_empty_sheaf(s, sheaf);
5422 sheaf = NULL;
5423 }
5424 }
5425
5426 if (sheaf)
5427 sheaf->capacity = s->sheaf_capacity;
5428
5429 return sheaf;
5430 }
5431
5432 /*
5433 * Use this to return a sheaf obtained by kmem_cache_prefill_sheaf()
5434 *
5435 * If the sheaf cannot simply become the percpu spare sheaf, but there's space
5436 * for a full sheaf in the barn, we try to refill the sheaf back to the cache's
5437 * sheaf_capacity to avoid handling partially full sheaves.
5438 *
5439 * If the refill fails because gfp is e.g. GFP_NOWAIT, or the barn is full, the
5440 * sheaf is instead flushed and freed.
5441 */
kmem_cache_return_sheaf(struct kmem_cache * s,gfp_t gfp,struct slab_sheaf * sheaf)5442 void kmem_cache_return_sheaf(struct kmem_cache *s, gfp_t gfp,
5443 struct slab_sheaf *sheaf)
5444 {
5445 struct slub_percpu_sheaves *pcs;
5446 struct node_barn *barn;
5447
5448 if (unlikely(sheaf->capacity != s->sheaf_capacity)) {
5449 sheaf_flush_unused(s, sheaf);
5450 kfree(sheaf);
5451 return;
5452 }
5453
5454 local_lock(&s->cpu_sheaves->lock);
5455 pcs = this_cpu_ptr(s->cpu_sheaves);
5456 barn = get_barn(s);
5457
5458 if (!pcs->spare) {
5459 pcs->spare = sheaf;
5460 sheaf = NULL;
5461 stat(s, SHEAF_RETURN_FAST);
5462 }
5463
5464 local_unlock(&s->cpu_sheaves->lock);
5465
5466 if (!sheaf)
5467 return;
5468
5469 stat(s, SHEAF_RETURN_SLOW);
5470
5471 /*
5472 * If the barn has too many full sheaves or we fail to refill the sheaf,
5473 * simply flush and free it.
5474 */
5475 if (!barn || data_race(barn->nr_full) >= MAX_FULL_SHEAVES ||
5476 refill_sheaf(s, sheaf, gfp)) {
5477 sheaf_flush_unused(s, sheaf);
5478 free_empty_sheaf(s, sheaf);
5479 return;
5480 }
5481
5482 barn_put_full_sheaf(barn, sheaf);
5483 stat(s, BARN_PUT);
5484 }
5485
5486 /*
5487 * refill a sheaf previously returned by kmem_cache_prefill_sheaf to at least
5488 * the given size
5489 *
5490 * the sheaf might be replaced by a new one when requesting more than
5491 * s->sheaf_capacity objects if such replacement is necessary, but the refill
5492 * fails (returning -ENOMEM), the existing sheaf is left intact
5493 *
5494 * In practice we always refill to full sheaf's capacity.
5495 */
kmem_cache_refill_sheaf(struct kmem_cache * s,gfp_t gfp,struct slab_sheaf ** sheafp,unsigned int size)5496 int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,
5497 struct slab_sheaf **sheafp, unsigned int size)
5498 {
5499 struct slab_sheaf *sheaf;
5500
5501 /*
5502 * TODO: do we want to support *sheaf == NULL to be equivalent of
5503 * kmem_cache_prefill_sheaf() ?
5504 */
5505 if (!sheafp || !(*sheafp))
5506 return -EINVAL;
5507
5508 sheaf = *sheafp;
5509 if (sheaf->size >= size)
5510 return 0;
5511
5512 if (likely(sheaf->capacity >= size)) {
5513 if (likely(sheaf->capacity == s->sheaf_capacity))
5514 return refill_sheaf(s, sheaf, gfp);
5515
5516 if (!__kmem_cache_alloc_bulk(s, gfp, sheaf->capacity - sheaf->size,
5517 &sheaf->objects[sheaf->size])) {
5518 return -ENOMEM;
5519 }
5520 sheaf->size = sheaf->capacity;
5521
5522 return 0;
5523 }
5524
5525 /*
5526 * We had a regular sized sheaf and need an oversize one, or we had an
5527 * oversize one already but need a larger one now.
5528 * This should be a very rare path so let's not complicate it.
5529 */
5530 sheaf = kmem_cache_prefill_sheaf(s, gfp, size);
5531 if (!sheaf)
5532 return -ENOMEM;
5533
5534 kmem_cache_return_sheaf(s, gfp, *sheafp);
5535 *sheafp = sheaf;
5536 return 0;
5537 }
5538
5539 /*
5540 * Allocate from a sheaf obtained by kmem_cache_prefill_sheaf()
5541 *
5542 * Guaranteed not to fail as many allocations as was the requested size.
5543 * After the sheaf is emptied, it fails - no fallback to the slab cache itself.
5544 *
5545 * The gfp parameter is meant only to specify __GFP_ZERO or __GFP_ACCOUNT
5546 * memcg charging is forced over limit if necessary, to avoid failure.
5547 */
5548 void *
kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache * s,gfp_t gfp,struct slab_sheaf * sheaf)5549 kmem_cache_alloc_from_sheaf_noprof(struct kmem_cache *s, gfp_t gfp,
5550 struct slab_sheaf *sheaf)
5551 {
5552 void *ret = NULL;
5553 bool init;
5554
5555 if (sheaf->size == 0)
5556 goto out;
5557
5558 ret = sheaf->objects[--sheaf->size];
5559
5560 init = slab_want_init_on_alloc(gfp, s);
5561
5562 /* add __GFP_NOFAIL to force successful memcg charging */
5563 slab_post_alloc_hook(s, NULL, gfp | __GFP_NOFAIL, 1, &ret, init, s->object_size);
5564 out:
5565 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfp, NUMA_NO_NODE);
5566
5567 return ret;
5568 }
5569
kmem_cache_sheaf_size(struct slab_sheaf * sheaf)5570 unsigned int kmem_cache_sheaf_size(struct slab_sheaf *sheaf)
5571 {
5572 return sheaf->size;
5573 }
5574 /*
5575 * To avoid unnecessary overhead, we pass through large allocation requests
5576 * directly to the page allocator. We use __GFP_COMP, because we will need to
5577 * know the allocation order to free the pages properly in kfree.
5578 */
___kmalloc_large_node(size_t size,gfp_t flags,int node)5579 static void *___kmalloc_large_node(size_t size, gfp_t flags, int node)
5580 {
5581 struct folio *folio;
5582 void *ptr = NULL;
5583 unsigned int order = get_order(size);
5584
5585 if (unlikely(flags & GFP_SLAB_BUG_MASK))
5586 flags = kmalloc_fix_flags(flags);
5587
5588 flags |= __GFP_COMP;
5589
5590 if (node == NUMA_NO_NODE)
5591 folio = (struct folio *)alloc_frozen_pages_noprof(flags, order);
5592 else
5593 folio = (struct folio *)__alloc_frozen_pages_noprof(flags, order, node, NULL);
5594
5595 if (folio) {
5596 ptr = folio_address(folio);
5597 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
5598 PAGE_SIZE << order);
5599 __folio_set_large_kmalloc(folio);
5600 }
5601
5602 ptr = kasan_kmalloc_large(ptr, size, flags);
5603 /* As ptr might get tagged, call kmemleak hook after KASAN. */
5604 kmemleak_alloc(ptr, size, 1, flags);
5605 kmsan_kmalloc_large(ptr, size, flags);
5606
5607 return ptr;
5608 }
5609
__kmalloc_large_noprof(size_t size,gfp_t flags)5610 void *__kmalloc_large_noprof(size_t size, gfp_t flags)
5611 {
5612 void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE);
5613
5614 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
5615 flags, NUMA_NO_NODE);
5616 return ret;
5617 }
5618 EXPORT_SYMBOL(__kmalloc_large_noprof);
5619
__kmalloc_large_node_noprof(size_t size,gfp_t flags,int node)5620 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
5621 {
5622 void *ret = ___kmalloc_large_node(size, flags, node);
5623
5624 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
5625 flags, node);
5626 return ret;
5627 }
5628 EXPORT_SYMBOL(__kmalloc_large_node_noprof);
5629
5630 static __always_inline
__do_kmalloc_node(size_t size,kmem_buckets * b,gfp_t flags,int node,unsigned long caller)5631 void *__do_kmalloc_node(size_t size, kmem_buckets *b, gfp_t flags, int node,
5632 unsigned long caller)
5633 {
5634 struct kmem_cache *s;
5635 void *ret;
5636
5637 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
5638 ret = __kmalloc_large_node_noprof(size, flags, node);
5639 trace_kmalloc(caller, ret, size,
5640 PAGE_SIZE << get_order(size), flags, node);
5641 return ret;
5642 }
5643
5644 if (unlikely(!size))
5645 return ZERO_SIZE_PTR;
5646
5647 s = kmalloc_slab(size, b, flags, caller);
5648
5649 ret = slab_alloc_node(s, NULL, flags, node, caller, size);
5650 ret = kasan_kmalloc(s, ret, size, flags);
5651 trace_kmalloc(caller, ret, size, s->size, flags, node);
5652 return ret;
5653 }
__kmalloc_node_noprof(DECL_BUCKET_PARAMS (size,b),gfp_t flags,int node)5654 void *__kmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
5655 {
5656 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, _RET_IP_);
5657 }
5658 EXPORT_SYMBOL(__kmalloc_node_noprof);
5659
__kmalloc_noprof(size_t size,gfp_t flags)5660 void *__kmalloc_noprof(size_t size, gfp_t flags)
5661 {
5662 return __do_kmalloc_node(size, NULL, flags, NUMA_NO_NODE, _RET_IP_);
5663 }
5664 EXPORT_SYMBOL(__kmalloc_noprof);
5665
5666 /**
5667 * kmalloc_nolock - Allocate an object of given size from any context.
5668 * @size: size to allocate
5669 * @gfp_flags: GFP flags. Only __GFP_ACCOUNT, __GFP_ZERO, __GFP_NO_OBJ_EXT
5670 * allowed.
5671 * @node: node number of the target node.
5672 *
5673 * Return: pointer to the new object or NULL in case of error.
5674 * NULL does not mean EBUSY or EAGAIN. It means ENOMEM.
5675 * There is no reason to call it again and expect !NULL.
5676 */
kmalloc_nolock_noprof(size_t size,gfp_t gfp_flags,int node)5677 void *kmalloc_nolock_noprof(size_t size, gfp_t gfp_flags, int node)
5678 {
5679 gfp_t alloc_gfp = __GFP_NOWARN | __GFP_NOMEMALLOC | gfp_flags;
5680 struct kmem_cache *s;
5681 bool can_retry = true;
5682 void *ret = ERR_PTR(-EBUSY);
5683
5684 VM_WARN_ON_ONCE(gfp_flags & ~(__GFP_ACCOUNT | __GFP_ZERO |
5685 __GFP_NO_OBJ_EXT));
5686
5687 if (unlikely(!size))
5688 return ZERO_SIZE_PTR;
5689
5690 if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
5691 /* kmalloc_nolock() in PREEMPT_RT is not supported from irq */
5692 return NULL;
5693 retry:
5694 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE))
5695 return NULL;
5696 s = kmalloc_slab(size, NULL, alloc_gfp, _RET_IP_);
5697
5698 if (!(s->flags & __CMPXCHG_DOUBLE) && !kmem_cache_debug(s))
5699 /*
5700 * kmalloc_nolock() is not supported on architectures that
5701 * don't implement cmpxchg16b, but debug caches don't use
5702 * per-cpu slab and per-cpu partial slabs. They rely on
5703 * kmem_cache_node->list_lock, so kmalloc_nolock() can
5704 * attempt to allocate from debug caches by
5705 * spin_trylock_irqsave(&n->list_lock, ...)
5706 */
5707 return NULL;
5708
5709 /*
5710 * Do not call slab_alloc_node(), since trylock mode isn't
5711 * compatible with slab_pre_alloc_hook/should_failslab and
5712 * kfence_alloc. Hence call __slab_alloc_node() (at most twice)
5713 * and slab_post_alloc_hook() directly.
5714 *
5715 * In !PREEMPT_RT ___slab_alloc() manipulates (freelist,tid) pair
5716 * in irq saved region. It assumes that the same cpu will not
5717 * __update_cpu_freelist_fast() into the same (freelist,tid) pair.
5718 * Therefore use in_nmi() to check whether particular bucket is in
5719 * irq protected section.
5720 *
5721 * If in_nmi() && local_lock_is_locked(s->cpu_slab) then it means that
5722 * this cpu was interrupted somewhere inside ___slab_alloc() after
5723 * it did local_lock_irqsave(&s->cpu_slab->lock, flags).
5724 * In this case fast path with __update_cpu_freelist_fast() is not safe.
5725 */
5726 #ifndef CONFIG_SLUB_TINY
5727 if (!in_nmi() || !local_lock_is_locked(&s->cpu_slab->lock))
5728 #endif
5729 ret = __slab_alloc_node(s, alloc_gfp, node, _RET_IP_, size);
5730
5731 if (PTR_ERR(ret) == -EBUSY) {
5732 if (can_retry) {
5733 /* pick the next kmalloc bucket */
5734 size = s->object_size + 1;
5735 /*
5736 * Another alternative is to
5737 * if (memcg) alloc_gfp &= ~__GFP_ACCOUNT;
5738 * else if (!memcg) alloc_gfp |= __GFP_ACCOUNT;
5739 * to retry from bucket of the same size.
5740 */
5741 can_retry = false;
5742 goto retry;
5743 }
5744 ret = NULL;
5745 }
5746
5747 maybe_wipe_obj_freeptr(s, ret);
5748 slab_post_alloc_hook(s, NULL, alloc_gfp, 1, &ret,
5749 slab_want_init_on_alloc(alloc_gfp, s), size);
5750
5751 ret = kasan_kmalloc(s, ret, size, alloc_gfp);
5752 return ret;
5753 }
5754 EXPORT_SYMBOL_GPL(kmalloc_nolock_noprof);
5755
__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS (size,b),gfp_t flags,int node,unsigned long caller)5756 void *__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags,
5757 int node, unsigned long caller)
5758 {
5759 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, caller);
5760
5761 }
5762 EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof);
5763
__kmalloc_cache_noprof(struct kmem_cache * s,gfp_t gfpflags,size_t size)5764 void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size)
5765 {
5766 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE,
5767 _RET_IP_, size);
5768
5769 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
5770
5771 ret = kasan_kmalloc(s, ret, size, gfpflags);
5772 return ret;
5773 }
5774 EXPORT_SYMBOL(__kmalloc_cache_noprof);
5775
__kmalloc_cache_node_noprof(struct kmem_cache * s,gfp_t gfpflags,int node,size_t size)5776 void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags,
5777 int node, size_t size)
5778 {
5779 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, size);
5780
5781 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
5782
5783 ret = kasan_kmalloc(s, ret, size, gfpflags);
5784 return ret;
5785 }
5786 EXPORT_SYMBOL(__kmalloc_cache_node_noprof);
5787
free_to_partial_list(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int bulk_cnt,unsigned long addr)5788 static noinline void free_to_partial_list(
5789 struct kmem_cache *s, struct slab *slab,
5790 void *head, void *tail, int bulk_cnt,
5791 unsigned long addr)
5792 {
5793 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
5794 struct slab *slab_free = NULL;
5795 int cnt = bulk_cnt;
5796 unsigned long flags;
5797 depot_stack_handle_t handle = 0;
5798
5799 /*
5800 * We cannot use GFP_NOWAIT as there are callsites where waking up
5801 * kswapd could deadlock
5802 */
5803 if (s->flags & SLAB_STORE_USER)
5804 handle = set_track_prepare(__GFP_NOWARN);
5805
5806 spin_lock_irqsave(&n->list_lock, flags);
5807
5808 if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
5809 void *prior = slab->freelist;
5810
5811 /* Perform the actual freeing while we still hold the locks */
5812 slab->inuse -= cnt;
5813 set_freepointer(s, tail, prior);
5814 slab->freelist = head;
5815
5816 /*
5817 * If the slab is empty, and node's partial list is full,
5818 * it should be discarded anyway no matter it's on full or
5819 * partial list.
5820 */
5821 if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
5822 slab_free = slab;
5823
5824 if (!prior) {
5825 /* was on full list */
5826 remove_full(s, n, slab);
5827 if (!slab_free) {
5828 add_partial(n, slab, DEACTIVATE_TO_TAIL);
5829 stat(s, FREE_ADD_PARTIAL);
5830 }
5831 } else if (slab_free) {
5832 remove_partial(n, slab);
5833 stat(s, FREE_REMOVE_PARTIAL);
5834 }
5835 }
5836
5837 if (slab_free) {
5838 /*
5839 * Update the counters while still holding n->list_lock to
5840 * prevent spurious validation warnings
5841 */
5842 dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
5843 }
5844
5845 spin_unlock_irqrestore(&n->list_lock, flags);
5846
5847 if (slab_free) {
5848 stat(s, FREE_SLAB);
5849 free_slab(s, slab_free);
5850 }
5851 }
5852
5853 /*
5854 * Slow path handling. This may still be called frequently since objects
5855 * have a longer lifetime than the cpu slabs in most processing loads.
5856 *
5857 * So we still attempt to reduce cache line usage. Just take the slab
5858 * lock and free the item. If there is no additional partial slab
5859 * handling required then we can return immediately.
5860 */
__slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)5861 static void __slab_free(struct kmem_cache *s, struct slab *slab,
5862 void *head, void *tail, int cnt,
5863 unsigned long addr)
5864
5865 {
5866 void *prior;
5867 int was_frozen;
5868 struct slab new;
5869 unsigned long counters;
5870 struct kmem_cache_node *n = NULL;
5871 unsigned long flags;
5872 bool on_node_partial;
5873
5874 stat(s, FREE_SLOWPATH);
5875
5876 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
5877 free_to_partial_list(s, slab, head, tail, cnt, addr);
5878 return;
5879 }
5880
5881 do {
5882 if (unlikely(n)) {
5883 spin_unlock_irqrestore(&n->list_lock, flags);
5884 n = NULL;
5885 }
5886 prior = slab->freelist;
5887 counters = slab->counters;
5888 set_freepointer(s, tail, prior);
5889 new.counters = counters;
5890 was_frozen = new.frozen;
5891 new.inuse -= cnt;
5892 if ((!new.inuse || !prior) && !was_frozen) {
5893 /* Needs to be taken off a list */
5894 if (!kmem_cache_has_cpu_partial(s) || prior) {
5895
5896 n = get_node(s, slab_nid(slab));
5897 /*
5898 * Speculatively acquire the list_lock.
5899 * If the cmpxchg does not succeed then we may
5900 * drop the list_lock without any processing.
5901 *
5902 * Otherwise the list_lock will synchronize with
5903 * other processors updating the list of slabs.
5904 */
5905 spin_lock_irqsave(&n->list_lock, flags);
5906
5907 on_node_partial = slab_test_node_partial(slab);
5908 }
5909 }
5910
5911 } while (!slab_update_freelist(s, slab,
5912 prior, counters,
5913 head, new.counters,
5914 "__slab_free"));
5915
5916 if (likely(!n)) {
5917
5918 if (likely(was_frozen)) {
5919 /*
5920 * The list lock was not taken therefore no list
5921 * activity can be necessary.
5922 */
5923 stat(s, FREE_FROZEN);
5924 } else if (kmem_cache_has_cpu_partial(s) && !prior) {
5925 /*
5926 * If we started with a full slab then put it onto the
5927 * per cpu partial list.
5928 */
5929 put_cpu_partial(s, slab, 1);
5930 stat(s, CPU_PARTIAL_FREE);
5931 }
5932
5933 return;
5934 }
5935
5936 /*
5937 * This slab was partially empty but not on the per-node partial list,
5938 * in which case we shouldn't manipulate its list, just return.
5939 */
5940 if (prior && !on_node_partial) {
5941 spin_unlock_irqrestore(&n->list_lock, flags);
5942 return;
5943 }
5944
5945 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
5946 goto slab_empty;
5947
5948 /*
5949 * Objects left in the slab. If it was not on the partial list before
5950 * then add it.
5951 */
5952 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
5953 add_partial(n, slab, DEACTIVATE_TO_TAIL);
5954 stat(s, FREE_ADD_PARTIAL);
5955 }
5956 spin_unlock_irqrestore(&n->list_lock, flags);
5957 return;
5958
5959 slab_empty:
5960 if (prior) {
5961 /*
5962 * Slab on the partial list.
5963 */
5964 remove_partial(n, slab);
5965 stat(s, FREE_REMOVE_PARTIAL);
5966 }
5967
5968 spin_unlock_irqrestore(&n->list_lock, flags);
5969 stat(s, FREE_SLAB);
5970 discard_slab(s, slab);
5971 }
5972
5973 /*
5974 * pcs is locked. We should have get rid of the spare sheaf and obtained an
5975 * empty sheaf, while the main sheaf is full. We want to install the empty sheaf
5976 * as a main sheaf, and make the current main sheaf a spare sheaf.
5977 *
5978 * However due to having relinquished the cpu_sheaves lock when obtaining
5979 * the empty sheaf, we need to handle some unlikely but possible cases.
5980 *
5981 * If we put any sheaf to barn here, it's because we were interrupted or have
5982 * been migrated to a different cpu, which should be rare enough so just ignore
5983 * the barn's limits to simplify the handling.
5984 *
5985 * An alternative scenario that gets us here is when we fail
5986 * barn_replace_full_sheaf(), because there's no empty sheaf available in the
5987 * barn, so we had to allocate it by alloc_empty_sheaf(). But because we saw the
5988 * limit on full sheaves was not exceeded, we assume it didn't change and just
5989 * put the full sheaf there.
5990 */
__pcs_install_empty_sheaf(struct kmem_cache * s,struct slub_percpu_sheaves * pcs,struct slab_sheaf * empty,struct node_barn * barn)5991 static void __pcs_install_empty_sheaf(struct kmem_cache *s,
5992 struct slub_percpu_sheaves *pcs, struct slab_sheaf *empty,
5993 struct node_barn *barn)
5994 {
5995 lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
5996
5997 /* This is what we expect to find if nobody interrupted us. */
5998 if (likely(!pcs->spare)) {
5999 pcs->spare = pcs->main;
6000 pcs->main = empty;
6001 return;
6002 }
6003
6004 /*
6005 * Unlikely because if the main sheaf had space, we would have just
6006 * freed to it. Get rid of our empty sheaf.
6007 */
6008 if (pcs->main->size < s->sheaf_capacity) {
6009 barn_put_empty_sheaf(barn, empty);
6010 return;
6011 }
6012
6013 /* Also unlikely for the same reason */
6014 if (pcs->spare->size < s->sheaf_capacity) {
6015 swap(pcs->main, pcs->spare);
6016 barn_put_empty_sheaf(barn, empty);
6017 return;
6018 }
6019
6020 /*
6021 * We probably failed barn_replace_full_sheaf() due to no empty sheaf
6022 * available there, but we allocated one, so finish the job.
6023 */
6024 barn_put_full_sheaf(barn, pcs->main);
6025 stat(s, BARN_PUT);
6026 pcs->main = empty;
6027 }
6028
6029 /*
6030 * Replace the full main sheaf with a (at least partially) empty sheaf.
6031 *
6032 * Must be called with the cpu_sheaves local lock locked. If successful, returns
6033 * the pcs pointer and the local lock locked (possibly on a different cpu than
6034 * initially called). If not successful, returns NULL and the local lock
6035 * unlocked.
6036 */
6037 static struct slub_percpu_sheaves *
__pcs_replace_full_main(struct kmem_cache * s,struct slub_percpu_sheaves * pcs)6038 __pcs_replace_full_main(struct kmem_cache *s, struct slub_percpu_sheaves *pcs)
6039 {
6040 struct slab_sheaf *empty;
6041 struct node_barn *barn;
6042 bool put_fail;
6043
6044 restart:
6045 lockdep_assert_held(this_cpu_ptr(&s->cpu_sheaves->lock));
6046
6047 barn = get_barn(s);
6048 if (!barn) {
6049 local_unlock(&s->cpu_sheaves->lock);
6050 return NULL;
6051 }
6052
6053 put_fail = false;
6054
6055 if (!pcs->spare) {
6056 empty = barn_get_empty_sheaf(barn);
6057 if (empty) {
6058 pcs->spare = pcs->main;
6059 pcs->main = empty;
6060 return pcs;
6061 }
6062 goto alloc_empty;
6063 }
6064
6065 if (pcs->spare->size < s->sheaf_capacity) {
6066 swap(pcs->main, pcs->spare);
6067 return pcs;
6068 }
6069
6070 empty = barn_replace_full_sheaf(barn, pcs->main);
6071
6072 if (!IS_ERR(empty)) {
6073 stat(s, BARN_PUT);
6074 pcs->main = empty;
6075 return pcs;
6076 }
6077
6078 if (PTR_ERR(empty) == -E2BIG) {
6079 /* Since we got here, spare exists and is full */
6080 struct slab_sheaf *to_flush = pcs->spare;
6081
6082 stat(s, BARN_PUT_FAIL);
6083
6084 pcs->spare = NULL;
6085 local_unlock(&s->cpu_sheaves->lock);
6086
6087 sheaf_flush_unused(s, to_flush);
6088 empty = to_flush;
6089 goto got_empty;
6090 }
6091
6092 /*
6093 * We could not replace full sheaf because barn had no empty
6094 * sheaves. We can still allocate it and put the full sheaf in
6095 * __pcs_install_empty_sheaf(), but if we fail to allocate it,
6096 * make sure to count the fail.
6097 */
6098 put_fail = true;
6099
6100 alloc_empty:
6101 local_unlock(&s->cpu_sheaves->lock);
6102
6103 empty = alloc_empty_sheaf(s, GFP_NOWAIT);
6104 if (empty)
6105 goto got_empty;
6106
6107 if (put_fail)
6108 stat(s, BARN_PUT_FAIL);
6109
6110 if (!sheaf_flush_main(s))
6111 return NULL;
6112
6113 if (!local_trylock(&s->cpu_sheaves->lock))
6114 return NULL;
6115
6116 pcs = this_cpu_ptr(s->cpu_sheaves);
6117
6118 /*
6119 * we flushed the main sheaf so it should be empty now,
6120 * but in case we got preempted or migrated, we need to
6121 * check again
6122 */
6123 if (pcs->main->size == s->sheaf_capacity)
6124 goto restart;
6125
6126 return pcs;
6127
6128 got_empty:
6129 if (!local_trylock(&s->cpu_sheaves->lock)) {
6130 barn_put_empty_sheaf(barn, empty);
6131 return NULL;
6132 }
6133
6134 pcs = this_cpu_ptr(s->cpu_sheaves);
6135 __pcs_install_empty_sheaf(s, pcs, empty, barn);
6136
6137 return pcs;
6138 }
6139
6140 /*
6141 * Free an object to the percpu sheaves.
6142 * The object is expected to have passed slab_free_hook() already.
6143 */
6144 static __fastpath_inline
free_to_pcs(struct kmem_cache * s,void * object)6145 bool free_to_pcs(struct kmem_cache *s, void *object)
6146 {
6147 struct slub_percpu_sheaves *pcs;
6148
6149 if (!local_trylock(&s->cpu_sheaves->lock))
6150 return false;
6151
6152 pcs = this_cpu_ptr(s->cpu_sheaves);
6153
6154 if (unlikely(pcs->main->size == s->sheaf_capacity)) {
6155
6156 pcs = __pcs_replace_full_main(s, pcs);
6157 if (unlikely(!pcs))
6158 return false;
6159 }
6160
6161 pcs->main->objects[pcs->main->size++] = object;
6162
6163 local_unlock(&s->cpu_sheaves->lock);
6164
6165 stat(s, FREE_PCS);
6166
6167 return true;
6168 }
6169
rcu_free_sheaf(struct rcu_head * head)6170 static void rcu_free_sheaf(struct rcu_head *head)
6171 {
6172 struct kmem_cache_node *n;
6173 struct slab_sheaf *sheaf;
6174 struct node_barn *barn = NULL;
6175 struct kmem_cache *s;
6176
6177 sheaf = container_of(head, struct slab_sheaf, rcu_head);
6178
6179 s = sheaf->cache;
6180
6181 /*
6182 * This may remove some objects due to slab_free_hook() returning false,
6183 * so that the sheaf might no longer be completely full. But it's easier
6184 * to handle it as full (unless it became completely empty), as the code
6185 * handles it fine. The only downside is that sheaf will serve fewer
6186 * allocations when reused. It only happens due to debugging, which is a
6187 * performance hit anyway.
6188 */
6189 __rcu_free_sheaf_prepare(s, sheaf);
6190
6191 n = get_node(s, sheaf->node);
6192 if (!n)
6193 goto flush;
6194
6195 barn = n->barn;
6196
6197 /* due to slab_free_hook() */
6198 if (unlikely(sheaf->size == 0))
6199 goto empty;
6200
6201 /*
6202 * Checking nr_full/nr_empty outside lock avoids contention in case the
6203 * barn is at the respective limit. Due to the race we might go over the
6204 * limit but that should be rare and harmless.
6205 */
6206
6207 if (data_race(barn->nr_full) < MAX_FULL_SHEAVES) {
6208 stat(s, BARN_PUT);
6209 barn_put_full_sheaf(barn, sheaf);
6210 return;
6211 }
6212
6213 flush:
6214 stat(s, BARN_PUT_FAIL);
6215 sheaf_flush_unused(s, sheaf);
6216
6217 empty:
6218 if (barn && data_race(barn->nr_empty) < MAX_EMPTY_SHEAVES) {
6219 barn_put_empty_sheaf(barn, sheaf);
6220 return;
6221 }
6222
6223 free_empty_sheaf(s, sheaf);
6224 }
6225
__kfree_rcu_sheaf(struct kmem_cache * s,void * obj)6226 bool __kfree_rcu_sheaf(struct kmem_cache *s, void *obj)
6227 {
6228 struct slub_percpu_sheaves *pcs;
6229 struct slab_sheaf *rcu_sheaf;
6230
6231 if (!local_trylock(&s->cpu_sheaves->lock))
6232 goto fail;
6233
6234 pcs = this_cpu_ptr(s->cpu_sheaves);
6235
6236 if (unlikely(!pcs->rcu_free)) {
6237
6238 struct slab_sheaf *empty;
6239 struct node_barn *barn;
6240
6241 if (pcs->spare && pcs->spare->size == 0) {
6242 pcs->rcu_free = pcs->spare;
6243 pcs->spare = NULL;
6244 goto do_free;
6245 }
6246
6247 barn = get_barn(s);
6248 if (!barn) {
6249 local_unlock(&s->cpu_sheaves->lock);
6250 goto fail;
6251 }
6252
6253 empty = barn_get_empty_sheaf(barn);
6254
6255 if (empty) {
6256 pcs->rcu_free = empty;
6257 goto do_free;
6258 }
6259
6260 local_unlock(&s->cpu_sheaves->lock);
6261
6262 empty = alloc_empty_sheaf(s, GFP_NOWAIT);
6263
6264 if (!empty)
6265 goto fail;
6266
6267 if (!local_trylock(&s->cpu_sheaves->lock)) {
6268 barn_put_empty_sheaf(barn, empty);
6269 goto fail;
6270 }
6271
6272 pcs = this_cpu_ptr(s->cpu_sheaves);
6273
6274 if (unlikely(pcs->rcu_free))
6275 barn_put_empty_sheaf(barn, empty);
6276 else
6277 pcs->rcu_free = empty;
6278 }
6279
6280 do_free:
6281
6282 rcu_sheaf = pcs->rcu_free;
6283
6284 /*
6285 * Since we flush immediately when size reaches capacity, we never reach
6286 * this with size already at capacity, so no OOB write is possible.
6287 */
6288 rcu_sheaf->objects[rcu_sheaf->size++] = obj;
6289
6290 if (likely(rcu_sheaf->size < s->sheaf_capacity)) {
6291 rcu_sheaf = NULL;
6292 } else {
6293 pcs->rcu_free = NULL;
6294 rcu_sheaf->node = numa_mem_id();
6295 }
6296
6297 /*
6298 * we flush before local_unlock to make sure a racing
6299 * flush_all_rcu_sheaves() doesn't miss this sheaf
6300 */
6301 if (rcu_sheaf)
6302 call_rcu(&rcu_sheaf->rcu_head, rcu_free_sheaf);
6303
6304 local_unlock(&s->cpu_sheaves->lock);
6305
6306 stat(s, FREE_RCU_SHEAF);
6307 return true;
6308
6309 fail:
6310 stat(s, FREE_RCU_SHEAF_FAIL);
6311 return false;
6312 }
6313
6314 /*
6315 * Bulk free objects to the percpu sheaves.
6316 * Unlike free_to_pcs() this includes the calls to all necessary hooks
6317 * and the fallback to freeing to slab pages.
6318 */
free_to_pcs_bulk(struct kmem_cache * s,size_t size,void ** p)6319 static void free_to_pcs_bulk(struct kmem_cache *s, size_t size, void **p)
6320 {
6321 struct slub_percpu_sheaves *pcs;
6322 struct slab_sheaf *main, *empty;
6323 bool init = slab_want_init_on_free(s);
6324 unsigned int batch, i = 0;
6325 struct node_barn *barn;
6326 void *remote_objects[PCS_BATCH_MAX];
6327 unsigned int remote_nr = 0;
6328 int node = numa_mem_id();
6329
6330 next_remote_batch:
6331 while (i < size) {
6332 struct slab *slab = virt_to_slab(p[i]);
6333
6334 memcg_slab_free_hook(s, slab, p + i, 1);
6335 alloc_tagging_slab_free_hook(s, slab, p + i, 1);
6336
6337 if (unlikely(!slab_free_hook(s, p[i], init, false))) {
6338 p[i] = p[--size];
6339 continue;
6340 }
6341
6342 if (unlikely(IS_ENABLED(CONFIG_NUMA) && slab_nid(slab) != node)) {
6343 remote_objects[remote_nr] = p[i];
6344 p[i] = p[--size];
6345 if (++remote_nr >= PCS_BATCH_MAX)
6346 goto flush_remote;
6347 continue;
6348 }
6349
6350 i++;
6351 }
6352
6353 if (!size)
6354 goto flush_remote;
6355
6356 next_batch:
6357 if (!local_trylock(&s->cpu_sheaves->lock))
6358 goto fallback;
6359
6360 pcs = this_cpu_ptr(s->cpu_sheaves);
6361
6362 if (likely(pcs->main->size < s->sheaf_capacity))
6363 goto do_free;
6364
6365 barn = get_barn(s);
6366 if (!barn)
6367 goto no_empty;
6368
6369 if (!pcs->spare) {
6370 empty = barn_get_empty_sheaf(barn);
6371 if (!empty)
6372 goto no_empty;
6373
6374 pcs->spare = pcs->main;
6375 pcs->main = empty;
6376 goto do_free;
6377 }
6378
6379 if (pcs->spare->size < s->sheaf_capacity) {
6380 swap(pcs->main, pcs->spare);
6381 goto do_free;
6382 }
6383
6384 empty = barn_replace_full_sheaf(barn, pcs->main);
6385 if (IS_ERR(empty)) {
6386 stat(s, BARN_PUT_FAIL);
6387 goto no_empty;
6388 }
6389
6390 stat(s, BARN_PUT);
6391 pcs->main = empty;
6392
6393 do_free:
6394 main = pcs->main;
6395 batch = min(size, s->sheaf_capacity - main->size);
6396
6397 memcpy(main->objects + main->size, p, batch * sizeof(void *));
6398 main->size += batch;
6399
6400 local_unlock(&s->cpu_sheaves->lock);
6401
6402 stat_add(s, FREE_PCS, batch);
6403
6404 if (batch < size) {
6405 p += batch;
6406 size -= batch;
6407 goto next_batch;
6408 }
6409
6410 if (remote_nr)
6411 goto flush_remote;
6412
6413 return;
6414
6415 no_empty:
6416 local_unlock(&s->cpu_sheaves->lock);
6417
6418 /*
6419 * if we depleted all empty sheaves in the barn or there are too
6420 * many full sheaves, free the rest to slab pages
6421 */
6422 fallback:
6423 __kmem_cache_free_bulk(s, size, p);
6424
6425 flush_remote:
6426 if (remote_nr) {
6427 __kmem_cache_free_bulk(s, remote_nr, &remote_objects[0]);
6428 if (i < size) {
6429 remote_nr = 0;
6430 goto next_remote_batch;
6431 }
6432 }
6433 }
6434
6435 struct defer_free {
6436 struct llist_head objects;
6437 struct llist_head slabs;
6438 struct irq_work work;
6439 };
6440
6441 static void free_deferred_objects(struct irq_work *work);
6442
6443 static DEFINE_PER_CPU(struct defer_free, defer_free_objects) = {
6444 .objects = LLIST_HEAD_INIT(objects),
6445 .slabs = LLIST_HEAD_INIT(slabs),
6446 .work = IRQ_WORK_INIT(free_deferred_objects),
6447 };
6448
6449 /*
6450 * In PREEMPT_RT irq_work runs in per-cpu kthread, so it's safe
6451 * to take sleeping spin_locks from __slab_free() and deactivate_slab().
6452 * In !PREEMPT_RT irq_work will run after local_unlock_irqrestore().
6453 */
free_deferred_objects(struct irq_work * work)6454 static void free_deferred_objects(struct irq_work *work)
6455 {
6456 struct defer_free *df = container_of(work, struct defer_free, work);
6457 struct llist_head *objs = &df->objects;
6458 struct llist_head *slabs = &df->slabs;
6459 struct llist_node *llnode, *pos, *t;
6460
6461 if (llist_empty(objs) && llist_empty(slabs))
6462 return;
6463
6464 llnode = llist_del_all(objs);
6465 llist_for_each_safe(pos, t, llnode) {
6466 struct kmem_cache *s;
6467 struct slab *slab;
6468 void *x = pos;
6469
6470 slab = virt_to_slab(x);
6471 s = slab->slab_cache;
6472
6473 /* Point 'x' back to the beginning of allocated object */
6474 x -= s->offset;
6475
6476 /*
6477 * We used freepointer in 'x' to link 'x' into df->objects.
6478 * Clear it to NULL to avoid false positive detection
6479 * of "Freepointer corruption".
6480 */
6481 set_freepointer(s, x, NULL);
6482
6483 __slab_free(s, slab, x, x, 1, _THIS_IP_);
6484 }
6485
6486 llnode = llist_del_all(slabs);
6487 llist_for_each_safe(pos, t, llnode) {
6488 struct slab *slab = container_of(pos, struct slab, llnode);
6489
6490 #ifdef CONFIG_SLUB_TINY
6491 free_slab(slab->slab_cache, slab);
6492 #else
6493 if (slab->frozen)
6494 deactivate_slab(slab->slab_cache, slab, slab->flush_freelist);
6495 else
6496 free_slab(slab->slab_cache, slab);
6497 #endif
6498 }
6499 }
6500
defer_free(struct kmem_cache * s,void * head)6501 static void defer_free(struct kmem_cache *s, void *head)
6502 {
6503 struct defer_free *df;
6504
6505 guard(preempt)();
6506
6507 df = this_cpu_ptr(&defer_free_objects);
6508 if (llist_add(head + s->offset, &df->objects))
6509 irq_work_queue(&df->work);
6510 }
6511
defer_deactivate_slab(struct slab * slab,void * flush_freelist)6512 static void defer_deactivate_slab(struct slab *slab, void *flush_freelist)
6513 {
6514 struct defer_free *df;
6515
6516 slab->flush_freelist = flush_freelist;
6517
6518 guard(preempt)();
6519
6520 df = this_cpu_ptr(&defer_free_objects);
6521 if (llist_add(&slab->llnode, &df->slabs))
6522 irq_work_queue(&df->work);
6523 }
6524
defer_free_barrier(void)6525 void defer_free_barrier(void)
6526 {
6527 int cpu;
6528
6529 for_each_possible_cpu(cpu)
6530 irq_work_sync(&per_cpu_ptr(&defer_free_objects, cpu)->work);
6531 }
6532
6533 #ifndef CONFIG_SLUB_TINY
6534 /*
6535 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
6536 * can perform fastpath freeing without additional function calls.
6537 *
6538 * The fastpath is only possible if we are freeing to the current cpu slab
6539 * of this processor. This typically the case if we have just allocated
6540 * the item before.
6541 *
6542 * If fastpath is not possible then fall back to __slab_free where we deal
6543 * with all sorts of special processing.
6544 *
6545 * Bulk free of a freelist with several objects (all pointing to the
6546 * same slab) possible by specifying head and tail ptr, plus objects
6547 * count (cnt). Bulk free indicated by tail pointer being set.
6548 */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)6549 static __always_inline void do_slab_free(struct kmem_cache *s,
6550 struct slab *slab, void *head, void *tail,
6551 int cnt, unsigned long addr)
6552 {
6553 /* cnt == 0 signals that it's called from kfree_nolock() */
6554 bool allow_spin = cnt;
6555 struct kmem_cache_cpu *c;
6556 unsigned long tid;
6557 void **freelist;
6558
6559 redo:
6560 /*
6561 * Determine the currently cpus per cpu slab.
6562 * The cpu may change afterward. However that does not matter since
6563 * data is retrieved via this pointer. If we are on the same cpu
6564 * during the cmpxchg then the free will succeed.
6565 */
6566 c = raw_cpu_ptr(s->cpu_slab);
6567 tid = READ_ONCE(c->tid);
6568
6569 /* Same with comment on barrier() in __slab_alloc_node() */
6570 barrier();
6571
6572 if (unlikely(slab != c->slab)) {
6573 if (unlikely(!allow_spin)) {
6574 /*
6575 * __slab_free() can locklessly cmpxchg16 into a slab,
6576 * but then it might need to take spin_lock or local_lock
6577 * in put_cpu_partial() for further processing.
6578 * Avoid the complexity and simply add to a deferred list.
6579 */
6580 defer_free(s, head);
6581 } else {
6582 __slab_free(s, slab, head, tail, cnt, addr);
6583 }
6584 return;
6585 }
6586
6587 if (unlikely(!allow_spin)) {
6588 if ((in_nmi() || !USE_LOCKLESS_FAST_PATH()) &&
6589 local_lock_is_locked(&s->cpu_slab->lock)) {
6590 defer_free(s, head);
6591 return;
6592 }
6593 cnt = 1; /* restore cnt. kfree_nolock() frees one object at a time */
6594 }
6595
6596 if (USE_LOCKLESS_FAST_PATH()) {
6597 freelist = READ_ONCE(c->freelist);
6598
6599 set_freepointer(s, tail, freelist);
6600
6601 if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
6602 note_cmpxchg_failure("slab_free", s, tid);
6603 goto redo;
6604 }
6605 } else {
6606 __maybe_unused unsigned long flags = 0;
6607
6608 /* Update the free list under the local lock */
6609 local_lock_cpu_slab(s, flags);
6610 c = this_cpu_ptr(s->cpu_slab);
6611 if (unlikely(slab != c->slab)) {
6612 local_unlock_cpu_slab(s, flags);
6613 goto redo;
6614 }
6615 tid = c->tid;
6616 freelist = c->freelist;
6617
6618 set_freepointer(s, tail, freelist);
6619 c->freelist = head;
6620 c->tid = next_tid(tid);
6621
6622 local_unlock_cpu_slab(s, flags);
6623 }
6624 stat_add(s, FREE_FASTPATH, cnt);
6625 }
6626 #else /* CONFIG_SLUB_TINY */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)6627 static void do_slab_free(struct kmem_cache *s,
6628 struct slab *slab, void *head, void *tail,
6629 int cnt, unsigned long addr)
6630 {
6631 __slab_free(s, slab, head, tail, cnt, addr);
6632 }
6633 #endif /* CONFIG_SLUB_TINY */
6634
6635 static __fastpath_inline
slab_free(struct kmem_cache * s,struct slab * slab,void * object,unsigned long addr)6636 void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
6637 unsigned long addr)
6638 {
6639 memcg_slab_free_hook(s, slab, &object, 1);
6640 alloc_tagging_slab_free_hook(s, slab, &object, 1);
6641
6642 if (unlikely(!slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6643 return;
6644
6645 if (s->cpu_sheaves && likely(!IS_ENABLED(CONFIG_NUMA) ||
6646 slab_nid(slab) == numa_mem_id())) {
6647 if (likely(free_to_pcs(s, object)))
6648 return;
6649 }
6650
6651 do_slab_free(s, slab, object, object, 1, addr);
6652 }
6653
6654 #ifdef CONFIG_MEMCG
6655 /* Do not inline the rare memcg charging failed path into the allocation path */
6656 static noinline
memcg_alloc_abort_single(struct kmem_cache * s,void * object)6657 void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
6658 {
6659 if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
6660 do_slab_free(s, virt_to_slab(object), object, object, 1, _RET_IP_);
6661 }
6662 #endif
6663
6664 static __fastpath_inline
slab_free_bulk(struct kmem_cache * s,struct slab * slab,void * head,void * tail,void ** p,int cnt,unsigned long addr)6665 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
6666 void *tail, void **p, int cnt, unsigned long addr)
6667 {
6668 memcg_slab_free_hook(s, slab, p, cnt);
6669 alloc_tagging_slab_free_hook(s, slab, p, cnt);
6670 /*
6671 * With KASAN enabled slab_free_freelist_hook modifies the freelist
6672 * to remove objects, whose reuse must be delayed.
6673 */
6674 if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt)))
6675 do_slab_free(s, slab, head, tail, cnt, addr);
6676 }
6677
6678 #ifdef CONFIG_SLUB_RCU_DEBUG
slab_free_after_rcu_debug(struct rcu_head * rcu_head)6679 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
6680 {
6681 struct rcu_delayed_free *delayed_free =
6682 container_of(rcu_head, struct rcu_delayed_free, head);
6683 void *object = delayed_free->object;
6684 struct slab *slab = virt_to_slab(object);
6685 struct kmem_cache *s;
6686
6687 kfree(delayed_free);
6688
6689 if (WARN_ON(is_kfence_address(object)))
6690 return;
6691
6692 /* find the object and the cache again */
6693 if (WARN_ON(!slab))
6694 return;
6695 s = slab->slab_cache;
6696 if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
6697 return;
6698
6699 /* resume freeing */
6700 if (slab_free_hook(s, object, slab_want_init_on_free(s), true))
6701 do_slab_free(s, slab, object, object, 1, _THIS_IP_);
6702 }
6703 #endif /* CONFIG_SLUB_RCU_DEBUG */
6704
6705 #ifdef CONFIG_KASAN_GENERIC
___cache_free(struct kmem_cache * cache,void * x,unsigned long addr)6706 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
6707 {
6708 do_slab_free(cache, virt_to_slab(x), x, x, 1, addr);
6709 }
6710 #endif
6711
virt_to_cache(const void * obj)6712 static inline struct kmem_cache *virt_to_cache(const void *obj)
6713 {
6714 struct slab *slab;
6715
6716 slab = virt_to_slab(obj);
6717 if (WARN_ONCE(!slab, "%s: Object is not a Slab page!\n", __func__))
6718 return NULL;
6719 return slab->slab_cache;
6720 }
6721
cache_from_obj(struct kmem_cache * s,void * x)6722 static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x)
6723 {
6724 struct kmem_cache *cachep;
6725
6726 if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
6727 !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS))
6728 return s;
6729
6730 cachep = virt_to_cache(x);
6731 if (WARN(cachep && cachep != s,
6732 "%s: Wrong slab cache. %s but object is from %s\n",
6733 __func__, s->name, cachep->name))
6734 print_tracking(cachep, x);
6735 return cachep;
6736 }
6737
6738 /**
6739 * kmem_cache_free - Deallocate an object
6740 * @s: The cache the allocation was from.
6741 * @x: The previously allocated object.
6742 *
6743 * Free an object which was previously allocated from this
6744 * cache.
6745 */
kmem_cache_free(struct kmem_cache * s,void * x)6746 void kmem_cache_free(struct kmem_cache *s, void *x)
6747 {
6748 s = cache_from_obj(s, x);
6749 if (!s)
6750 return;
6751 trace_kmem_cache_free(_RET_IP_, x, s);
6752 slab_free(s, virt_to_slab(x), x, _RET_IP_);
6753 }
6754 EXPORT_SYMBOL(kmem_cache_free);
6755
free_large_kmalloc(struct folio * folio,void * object)6756 static void free_large_kmalloc(struct folio *folio, void *object)
6757 {
6758 unsigned int order = folio_order(folio);
6759
6760 if (WARN_ON_ONCE(!folio_test_large_kmalloc(folio))) {
6761 dump_page(&folio->page, "Not a kmalloc allocation");
6762 return;
6763 }
6764
6765 if (WARN_ON_ONCE(order == 0))
6766 pr_warn_once("object pointer: 0x%p\n", object);
6767
6768 kmemleak_free(object);
6769 kasan_kfree_large(object);
6770 kmsan_kfree_large(object);
6771
6772 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
6773 -(PAGE_SIZE << order));
6774 __folio_clear_large_kmalloc(folio);
6775 free_frozen_pages(&folio->page, order);
6776 }
6777
6778 /*
6779 * Given an rcu_head embedded within an object obtained from kvmalloc at an
6780 * offset < 4k, free the object in question.
6781 */
kvfree_rcu_cb(struct rcu_head * head)6782 void kvfree_rcu_cb(struct rcu_head *head)
6783 {
6784 void *obj = head;
6785 struct folio *folio;
6786 struct slab *slab;
6787 struct kmem_cache *s;
6788 void *slab_addr;
6789
6790 if (is_vmalloc_addr(obj)) {
6791 obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
6792 vfree(obj);
6793 return;
6794 }
6795
6796 folio = virt_to_folio(obj);
6797 if (!folio_test_slab(folio)) {
6798 /*
6799 * rcu_head offset can be only less than page size so no need to
6800 * consider folio order
6801 */
6802 obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj);
6803 free_large_kmalloc(folio, obj);
6804 return;
6805 }
6806
6807 slab = folio_slab(folio);
6808 s = slab->slab_cache;
6809 slab_addr = folio_address(folio);
6810
6811 if (is_kfence_address(obj)) {
6812 obj = kfence_object_start(obj);
6813 } else {
6814 unsigned int idx = __obj_to_index(s, slab_addr, obj);
6815
6816 obj = slab_addr + s->size * idx;
6817 obj = fixup_red_left(s, obj);
6818 }
6819
6820 slab_free(s, slab, obj, _RET_IP_);
6821 }
6822
6823 /**
6824 * kfree - free previously allocated memory
6825 * @object: pointer returned by kmalloc() or kmem_cache_alloc()
6826 *
6827 * If @object is NULL, no operation is performed.
6828 */
kfree(const void * object)6829 void kfree(const void *object)
6830 {
6831 struct folio *folio;
6832 struct slab *slab;
6833 struct kmem_cache *s;
6834 void *x = (void *)object;
6835
6836 trace_kfree(_RET_IP_, object);
6837
6838 if (unlikely(ZERO_OR_NULL_PTR(object)))
6839 return;
6840
6841 folio = virt_to_folio(object);
6842 if (unlikely(!folio_test_slab(folio))) {
6843 free_large_kmalloc(folio, (void *)object);
6844 return;
6845 }
6846
6847 slab = folio_slab(folio);
6848 s = slab->slab_cache;
6849 slab_free(s, slab, x, _RET_IP_);
6850 }
6851 EXPORT_SYMBOL(kfree);
6852
6853 /*
6854 * Can be called while holding raw_spinlock_t or from IRQ and NMI,
6855 * but ONLY for objects allocated by kmalloc_nolock().
6856 * Debug checks (like kmemleak and kfence) were skipped on allocation,
6857 * hence
6858 * obj = kmalloc(); kfree_nolock(obj);
6859 * will miss kmemleak/kfence book keeping and will cause false positives.
6860 * large_kmalloc is not supported either.
6861 */
kfree_nolock(const void * object)6862 void kfree_nolock(const void *object)
6863 {
6864 struct folio *folio;
6865 struct slab *slab;
6866 struct kmem_cache *s;
6867 void *x = (void *)object;
6868
6869 if (unlikely(ZERO_OR_NULL_PTR(object)))
6870 return;
6871
6872 folio = virt_to_folio(object);
6873 if (unlikely(!folio_test_slab(folio))) {
6874 WARN_ONCE(1, "large_kmalloc is not supported by kfree_nolock()");
6875 return;
6876 }
6877
6878 slab = folio_slab(folio);
6879 s = slab->slab_cache;
6880
6881 memcg_slab_free_hook(s, slab, &x, 1);
6882 alloc_tagging_slab_free_hook(s, slab, &x, 1);
6883 /*
6884 * Unlike slab_free() do NOT call the following:
6885 * kmemleak_free_recursive(x, s->flags);
6886 * debug_check_no_locks_freed(x, s->object_size);
6887 * debug_check_no_obj_freed(x, s->object_size);
6888 * __kcsan_check_access(x, s->object_size, ..);
6889 * kfence_free(x);
6890 * since they take spinlocks or not safe from any context.
6891 */
6892 kmsan_slab_free(s, x);
6893 /*
6894 * If KASAN finds a kernel bug it will do kasan_report_invalid_free()
6895 * which will call raw_spin_lock_irqsave() which is technically
6896 * unsafe from NMI, but take chance and report kernel bug.
6897 * The sequence of
6898 * kasan_report_invalid_free() -> raw_spin_lock_irqsave() -> NMI
6899 * -> kfree_nolock() -> kasan_report_invalid_free() on the same CPU
6900 * is double buggy and deserves to deadlock.
6901 */
6902 if (kasan_slab_pre_free(s, x))
6903 return;
6904 /*
6905 * memcg, kasan_slab_pre_free are done for 'x'.
6906 * The only thing left is kasan_poison without quarantine,
6907 * since kasan quarantine takes locks and not supported from NMI.
6908 */
6909 kasan_slab_free(s, x, false, false, /* skip quarantine */true);
6910 #ifndef CONFIG_SLUB_TINY
6911 do_slab_free(s, slab, x, x, 0, _RET_IP_);
6912 #else
6913 defer_free(s, x);
6914 #endif
6915 }
6916 EXPORT_SYMBOL_GPL(kfree_nolock);
6917
6918 static __always_inline __realloc_size(2) void *
__do_krealloc(const void * p,size_t new_size,unsigned long align,gfp_t flags,int nid)6919 __do_krealloc(const void *p, size_t new_size, unsigned long align, gfp_t flags, int nid)
6920 {
6921 void *ret;
6922 size_t ks = 0;
6923 int orig_size = 0;
6924 struct kmem_cache *s = NULL;
6925
6926 if (unlikely(ZERO_OR_NULL_PTR(p)))
6927 goto alloc_new;
6928
6929 /* Check for double-free. */
6930 if (!kasan_check_byte(p))
6931 return NULL;
6932
6933 /*
6934 * If reallocation is not necessary (e. g. the new size is less
6935 * than the current allocated size), the current allocation will be
6936 * preserved unless __GFP_THISNODE is set. In the latter case a new
6937 * allocation on the requested node will be attempted.
6938 */
6939 if (unlikely(flags & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
6940 nid != page_to_nid(virt_to_page(p)))
6941 goto alloc_new;
6942
6943 if (is_kfence_address(p)) {
6944 ks = orig_size = kfence_ksize(p);
6945 } else {
6946 struct folio *folio;
6947
6948 folio = virt_to_folio(p);
6949 if (unlikely(!folio_test_slab(folio))) {
6950 /* Big kmalloc object */
6951 WARN_ON(folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE);
6952 WARN_ON(p != folio_address(folio));
6953 ks = folio_size(folio);
6954 } else {
6955 s = folio_slab(folio)->slab_cache;
6956 orig_size = get_orig_size(s, (void *)p);
6957 ks = s->object_size;
6958 }
6959 }
6960
6961 /* If the old object doesn't fit, allocate a bigger one */
6962 if (new_size > ks)
6963 goto alloc_new;
6964
6965 /* If the old object doesn't satisfy the new alignment, allocate a new one */
6966 if (!IS_ALIGNED((unsigned long)p, align))
6967 goto alloc_new;
6968
6969 /* Zero out spare memory. */
6970 if (want_init_on_alloc(flags)) {
6971 kasan_disable_current();
6972 if (orig_size && orig_size < new_size)
6973 memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size);
6974 else
6975 memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
6976 kasan_enable_current();
6977 }
6978
6979 /* Setup kmalloc redzone when needed */
6980 if (s && slub_debug_orig_size(s)) {
6981 set_orig_size(s, (void *)p, new_size);
6982 if (s->flags & SLAB_RED_ZONE && new_size < ks)
6983 memset_no_sanitize_memory(kasan_reset_tag(p) + new_size,
6984 SLUB_RED_ACTIVE, ks - new_size);
6985 }
6986
6987 p = kasan_krealloc(p, new_size, flags);
6988 return (void *)p;
6989
6990 alloc_new:
6991 ret = kmalloc_node_track_caller_noprof(new_size, flags, nid, _RET_IP_);
6992 if (ret && p) {
6993 /* Disable KASAN checks as the object's redzone is accessed. */
6994 kasan_disable_current();
6995 memcpy(ret, kasan_reset_tag(p), orig_size ?: ks);
6996 kasan_enable_current();
6997 }
6998
6999 return ret;
7000 }
7001
7002 /**
7003 * krealloc_node_align - reallocate memory. The contents will remain unchanged.
7004 * @p: object to reallocate memory for.
7005 * @new_size: how many bytes of memory are required.
7006 * @align: desired alignment.
7007 * @flags: the type of memory to allocate.
7008 * @nid: NUMA node or NUMA_NO_NODE
7009 *
7010 * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size
7011 * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
7012 *
7013 * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
7014 * Documentation/core-api/memory-allocation.rst for more details.
7015 *
7016 * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
7017 * initial memory allocation, every subsequent call to this API for the same
7018 * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
7019 * __GFP_ZERO is not fully honored by this API.
7020 *
7021 * When slub_debug_orig_size() is off, krealloc() only knows about the bucket
7022 * size of an allocation (but not the exact size it was allocated with) and
7023 * hence implements the following semantics for shrinking and growing buffers
7024 * with __GFP_ZERO::
7025 *
7026 * new bucket
7027 * 0 size size
7028 * |--------|----------------|
7029 * | keep | zero |
7030 *
7031 * Otherwise, the original allocation size 'orig_size' could be used to
7032 * precisely clear the requested size, and the new size will also be stored
7033 * as the new 'orig_size'.
7034 *
7035 * In any case, the contents of the object pointed to are preserved up to the
7036 * lesser of the new and old sizes.
7037 *
7038 * Return: pointer to the allocated memory or %NULL in case of error
7039 */
krealloc_node_align_noprof(const void * p,size_t new_size,unsigned long align,gfp_t flags,int nid)7040 void *krealloc_node_align_noprof(const void *p, size_t new_size, unsigned long align,
7041 gfp_t flags, int nid)
7042 {
7043 void *ret;
7044
7045 if (unlikely(!new_size)) {
7046 kfree(p);
7047 return ZERO_SIZE_PTR;
7048 }
7049
7050 ret = __do_krealloc(p, new_size, align, flags, nid);
7051 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
7052 kfree(p);
7053
7054 return ret;
7055 }
7056 EXPORT_SYMBOL(krealloc_node_align_noprof);
7057
kmalloc_gfp_adjust(gfp_t flags,size_t size)7058 static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
7059 {
7060 /*
7061 * We want to attempt a large physically contiguous block first because
7062 * it is less likely to fragment multiple larger blocks and therefore
7063 * contribute to a long term fragmentation less than vmalloc fallback.
7064 * However make sure that larger requests are not too disruptive - i.e.
7065 * do not direct reclaim unless physically continuous memory is preferred
7066 * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to
7067 * start working in the background
7068 */
7069 if (size > PAGE_SIZE) {
7070 flags |= __GFP_NOWARN;
7071
7072 if (!(flags & __GFP_RETRY_MAYFAIL))
7073 flags &= ~__GFP_DIRECT_RECLAIM;
7074
7075 /* nofail semantic is implemented by the vmalloc fallback */
7076 flags &= ~__GFP_NOFAIL;
7077 }
7078
7079 return flags;
7080 }
7081
7082 /**
7083 * __kvmalloc_node - attempt to allocate physically contiguous memory, but upon
7084 * failure, fall back to non-contiguous (vmalloc) allocation.
7085 * @size: size of the request.
7086 * @b: which set of kmalloc buckets to allocate from.
7087 * @align: desired alignment.
7088 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
7089 * @node: numa node to allocate from
7090 *
7091 * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
7092 * Documentation/core-api/memory-allocation.rst for more details.
7093 *
7094 * Uses kmalloc to get the memory but if the allocation fails then falls back
7095 * to the vmalloc allocator. Use kvfree for freeing the memory.
7096 *
7097 * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier.
7098 * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
7099 * preferable to the vmalloc fallback, due to visible performance drawbacks.
7100 *
7101 * Return: pointer to the allocated memory of %NULL in case of failure
7102 */
__kvmalloc_node_noprof(DECL_BUCKET_PARAMS (size,b),unsigned long align,gfp_t flags,int node)7103 void *__kvmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), unsigned long align,
7104 gfp_t flags, int node)
7105 {
7106 void *ret;
7107
7108 /*
7109 * It doesn't really make sense to fallback to vmalloc for sub page
7110 * requests
7111 */
7112 ret = __do_kmalloc_node(size, PASS_BUCKET_PARAM(b),
7113 kmalloc_gfp_adjust(flags, size),
7114 node, _RET_IP_);
7115 if (ret || size <= PAGE_SIZE)
7116 return ret;
7117
7118 /* non-sleeping allocations are not supported by vmalloc */
7119 if (!gfpflags_allow_blocking(flags))
7120 return NULL;
7121
7122 /* Don't even allow crazy sizes */
7123 if (unlikely(size > INT_MAX)) {
7124 WARN_ON_ONCE(!(flags & __GFP_NOWARN));
7125 return NULL;
7126 }
7127
7128 /*
7129 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP,
7130 * since the callers already cannot assume anything
7131 * about the resulting pointer, and cannot play
7132 * protection games.
7133 */
7134 return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END,
7135 flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
7136 node, __builtin_return_address(0));
7137 }
7138 EXPORT_SYMBOL(__kvmalloc_node_noprof);
7139
7140 /**
7141 * kvfree() - Free memory.
7142 * @addr: Pointer to allocated memory.
7143 *
7144 * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
7145 * It is slightly more efficient to use kfree() or vfree() if you are certain
7146 * that you know which one to use.
7147 *
7148 * Context: Either preemptible task context or not-NMI interrupt.
7149 */
kvfree(const void * addr)7150 void kvfree(const void *addr)
7151 {
7152 if (is_vmalloc_addr(addr))
7153 vfree(addr);
7154 else
7155 kfree(addr);
7156 }
7157 EXPORT_SYMBOL(kvfree);
7158
7159 /**
7160 * kvfree_sensitive - Free a data object containing sensitive information.
7161 * @addr: address of the data object to be freed.
7162 * @len: length of the data object.
7163 *
7164 * Use the special memzero_explicit() function to clear the content of a
7165 * kvmalloc'ed object containing sensitive data to make sure that the
7166 * compiler won't optimize out the data clearing.
7167 */
kvfree_sensitive(const void * addr,size_t len)7168 void kvfree_sensitive(const void *addr, size_t len)
7169 {
7170 if (likely(!ZERO_OR_NULL_PTR(addr))) {
7171 memzero_explicit((void *)addr, len);
7172 kvfree(addr);
7173 }
7174 }
7175 EXPORT_SYMBOL(kvfree_sensitive);
7176
7177 /**
7178 * kvrealloc_node_align - reallocate memory; contents remain unchanged
7179 * @p: object to reallocate memory for
7180 * @size: the size to reallocate
7181 * @align: desired alignment
7182 * @flags: the flags for the page level allocator
7183 * @nid: NUMA node id
7184 *
7185 * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0
7186 * and @p is not a %NULL pointer, the object pointed to is freed.
7187 *
7188 * Only alignments up to those guaranteed by kmalloc() will be honored. Please see
7189 * Documentation/core-api/memory-allocation.rst for more details.
7190 *
7191 * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
7192 * initial memory allocation, every subsequent call to this API for the same
7193 * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
7194 * __GFP_ZERO is not fully honored by this API.
7195 *
7196 * In any case, the contents of the object pointed to are preserved up to the
7197 * lesser of the new and old sizes.
7198 *
7199 * This function must not be called concurrently with itself or kvfree() for the
7200 * same memory allocation.
7201 *
7202 * Return: pointer to the allocated memory or %NULL in case of error
7203 */
kvrealloc_node_align_noprof(const void * p,size_t size,unsigned long align,gfp_t flags,int nid)7204 void *kvrealloc_node_align_noprof(const void *p, size_t size, unsigned long align,
7205 gfp_t flags, int nid)
7206 {
7207 void *n;
7208
7209 if (is_vmalloc_addr(p))
7210 return vrealloc_node_align_noprof(p, size, align, flags, nid);
7211
7212 n = krealloc_node_align_noprof(p, size, align, kmalloc_gfp_adjust(flags, size), nid);
7213 if (!n) {
7214 /* We failed to krealloc(), fall back to kvmalloc(). */
7215 n = kvmalloc_node_align_noprof(size, align, flags, nid);
7216 if (!n)
7217 return NULL;
7218
7219 if (p) {
7220 /* We already know that `p` is not a vmalloc address. */
7221 kasan_disable_current();
7222 memcpy(n, kasan_reset_tag(p), ksize(p));
7223 kasan_enable_current();
7224
7225 kfree(p);
7226 }
7227 }
7228
7229 return n;
7230 }
7231 EXPORT_SYMBOL(kvrealloc_node_align_noprof);
7232
7233 struct detached_freelist {
7234 struct slab *slab;
7235 void *tail;
7236 void *freelist;
7237 int cnt;
7238 struct kmem_cache *s;
7239 };
7240
7241 /*
7242 * This function progressively scans the array with free objects (with
7243 * a limited look ahead) and extract objects belonging to the same
7244 * slab. It builds a detached freelist directly within the given
7245 * slab/objects. This can happen without any need for
7246 * synchronization, because the objects are owned by running process.
7247 * The freelist is build up as a single linked list in the objects.
7248 * The idea is, that this detached freelist can then be bulk
7249 * transferred to the real freelist(s), but only requiring a single
7250 * synchronization primitive. Look ahead in the array is limited due
7251 * to performance reasons.
7252 */
7253 static inline
build_detached_freelist(struct kmem_cache * s,size_t size,void ** p,struct detached_freelist * df)7254 int build_detached_freelist(struct kmem_cache *s, size_t size,
7255 void **p, struct detached_freelist *df)
7256 {
7257 int lookahead = 3;
7258 void *object;
7259 struct folio *folio;
7260 size_t same;
7261
7262 object = p[--size];
7263 folio = virt_to_folio(object);
7264 if (!s) {
7265 /* Handle kalloc'ed objects */
7266 if (unlikely(!folio_test_slab(folio))) {
7267 free_large_kmalloc(folio, object);
7268 df->slab = NULL;
7269 return size;
7270 }
7271 /* Derive kmem_cache from object */
7272 df->slab = folio_slab(folio);
7273 df->s = df->slab->slab_cache;
7274 } else {
7275 df->slab = folio_slab(folio);
7276 df->s = cache_from_obj(s, object); /* Support for memcg */
7277 }
7278
7279 /* Start new detached freelist */
7280 df->tail = object;
7281 df->freelist = object;
7282 df->cnt = 1;
7283
7284 if (is_kfence_address(object))
7285 return size;
7286
7287 set_freepointer(df->s, object, NULL);
7288
7289 same = size;
7290 while (size) {
7291 object = p[--size];
7292 /* df->slab is always set at this point */
7293 if (df->slab == virt_to_slab(object)) {
7294 /* Opportunity build freelist */
7295 set_freepointer(df->s, object, df->freelist);
7296 df->freelist = object;
7297 df->cnt++;
7298 same--;
7299 if (size != same)
7300 swap(p[size], p[same]);
7301 continue;
7302 }
7303
7304 /* Limit look ahead search */
7305 if (!--lookahead)
7306 break;
7307 }
7308
7309 return same;
7310 }
7311
7312 /*
7313 * Internal bulk free of objects that were not initialised by the post alloc
7314 * hooks and thus should not be processed by the free hooks
7315 */
__kmem_cache_free_bulk(struct kmem_cache * s,size_t size,void ** p)7316 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7317 {
7318 if (!size)
7319 return;
7320
7321 do {
7322 struct detached_freelist df;
7323
7324 size = build_detached_freelist(s, size, p, &df);
7325 if (!df.slab)
7326 continue;
7327
7328 if (kfence_free(df.freelist))
7329 continue;
7330
7331 do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
7332 _RET_IP_);
7333 } while (likely(size));
7334 }
7335
7336 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_free_bulk(struct kmem_cache * s,size_t size,void ** p)7337 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
7338 {
7339 if (!size)
7340 return;
7341
7342 /*
7343 * freeing to sheaves is so incompatible with the detached freelist so
7344 * once we go that way, we have to do everything differently
7345 */
7346 if (s && s->cpu_sheaves) {
7347 free_to_pcs_bulk(s, size, p);
7348 return;
7349 }
7350
7351 do {
7352 struct detached_freelist df;
7353
7354 size = build_detached_freelist(s, size, p, &df);
7355 if (!df.slab)
7356 continue;
7357
7358 slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
7359 df.cnt, _RET_IP_);
7360 } while (likely(size));
7361 }
7362 EXPORT_SYMBOL(kmem_cache_free_bulk);
7363
7364 #ifndef CONFIG_SLUB_TINY
7365 static inline
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)7366 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
7367 void **p)
7368 {
7369 struct kmem_cache_cpu *c;
7370 unsigned long irqflags;
7371 int i;
7372
7373 /*
7374 * Drain objects in the per cpu slab, while disabling local
7375 * IRQs, which protects against PREEMPT and interrupts
7376 * handlers invoking normal fastpath.
7377 */
7378 c = slub_get_cpu_ptr(s->cpu_slab);
7379 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
7380
7381 for (i = 0; i < size; i++) {
7382 void *object = kfence_alloc(s, s->object_size, flags);
7383
7384 if (unlikely(object)) {
7385 p[i] = object;
7386 continue;
7387 }
7388
7389 object = c->freelist;
7390 if (unlikely(!object)) {
7391 /*
7392 * We may have removed an object from c->freelist using
7393 * the fastpath in the previous iteration; in that case,
7394 * c->tid has not been bumped yet.
7395 * Since ___slab_alloc() may reenable interrupts while
7396 * allocating memory, we should bump c->tid now.
7397 */
7398 c->tid = next_tid(c->tid);
7399
7400 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
7401
7402 /*
7403 * Invoking slow path likely have side-effect
7404 * of re-populating per CPU c->freelist
7405 */
7406 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
7407 _RET_IP_, c, s->object_size);
7408 if (unlikely(!p[i]))
7409 goto error;
7410
7411 c = this_cpu_ptr(s->cpu_slab);
7412 maybe_wipe_obj_freeptr(s, p[i]);
7413
7414 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
7415
7416 continue; /* goto for-loop */
7417 }
7418 c->freelist = get_freepointer(s, object);
7419 p[i] = object;
7420 maybe_wipe_obj_freeptr(s, p[i]);
7421 stat(s, ALLOC_FASTPATH);
7422 }
7423 c->tid = next_tid(c->tid);
7424 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
7425 slub_put_cpu_ptr(s->cpu_slab);
7426
7427 return i;
7428
7429 error:
7430 slub_put_cpu_ptr(s->cpu_slab);
7431 __kmem_cache_free_bulk(s, i, p);
7432 return 0;
7433
7434 }
7435 #else /* CONFIG_SLUB_TINY */
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)7436 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
7437 size_t size, void **p)
7438 {
7439 int i;
7440
7441 for (i = 0; i < size; i++) {
7442 void *object = kfence_alloc(s, s->object_size, flags);
7443
7444 if (unlikely(object)) {
7445 p[i] = object;
7446 continue;
7447 }
7448
7449 p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE,
7450 _RET_IP_, s->object_size);
7451 if (unlikely(!p[i]))
7452 goto error;
7453
7454 maybe_wipe_obj_freeptr(s, p[i]);
7455 }
7456
7457 return i;
7458
7459 error:
7460 __kmem_cache_free_bulk(s, i, p);
7461 return 0;
7462 }
7463 #endif /* CONFIG_SLUB_TINY */
7464
7465 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_alloc_bulk_noprof(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)7466 int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size,
7467 void **p)
7468 {
7469 unsigned int i = 0;
7470
7471 if (!size)
7472 return 0;
7473
7474 s = slab_pre_alloc_hook(s, flags);
7475 if (unlikely(!s))
7476 return 0;
7477
7478 if (s->cpu_sheaves)
7479 i = alloc_from_pcs_bulk(s, size, p);
7480
7481 if (i < size) {
7482 /*
7483 * If we ran out of memory, don't bother with freeing back to
7484 * the percpu sheaves, we have bigger problems.
7485 */
7486 if (unlikely(__kmem_cache_alloc_bulk(s, flags, size - i, p + i) == 0)) {
7487 if (i > 0)
7488 __kmem_cache_free_bulk(s, i, p);
7489 return 0;
7490 }
7491 }
7492
7493 /*
7494 * memcg and kmem_cache debug support and memory initialization.
7495 * Done outside of the IRQ disabled fastpath loop.
7496 */
7497 if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p,
7498 slab_want_init_on_alloc(flags, s), s->object_size))) {
7499 return 0;
7500 }
7501
7502 return size;
7503 }
7504 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
7505
7506 /*
7507 * Object placement in a slab is made very easy because we always start at
7508 * offset 0. If we tune the size of the object to the alignment then we can
7509 * get the required alignment by putting one properly sized object after
7510 * another.
7511 *
7512 * Notice that the allocation order determines the sizes of the per cpu
7513 * caches. Each processor has always one slab available for allocations.
7514 * Increasing the allocation order reduces the number of times that slabs
7515 * must be moved on and off the partial lists and is therefore a factor in
7516 * locking overhead.
7517 */
7518
7519 /*
7520 * Minimum / Maximum order of slab pages. This influences locking overhead
7521 * and slab fragmentation. A higher order reduces the number of partial slabs
7522 * and increases the number of allocations possible without having to
7523 * take the list_lock.
7524 */
7525 static unsigned int slub_min_order;
7526 static unsigned int slub_max_order =
7527 IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
7528 static unsigned int slub_min_objects;
7529
7530 /*
7531 * Calculate the order of allocation given an slab object size.
7532 *
7533 * The order of allocation has significant impact on performance and other
7534 * system components. Generally order 0 allocations should be preferred since
7535 * order 0 does not cause fragmentation in the page allocator. Larger objects
7536 * be problematic to put into order 0 slabs because there may be too much
7537 * unused space left. We go to a higher order if more than 1/16th of the slab
7538 * would be wasted.
7539 *
7540 * In order to reach satisfactory performance we must ensure that a minimum
7541 * number of objects is in one slab. Otherwise we may generate too much
7542 * activity on the partial lists which requires taking the list_lock. This is
7543 * less a concern for large slabs though which are rarely used.
7544 *
7545 * slab_max_order specifies the order where we begin to stop considering the
7546 * number of objects in a slab as critical. If we reach slab_max_order then
7547 * we try to keep the page order as low as possible. So we accept more waste
7548 * of space in favor of a small page order.
7549 *
7550 * Higher order allocations also allow the placement of more objects in a
7551 * slab and thereby reduce object handling overhead. If the user has
7552 * requested a higher minimum order then we start with that one instead of
7553 * the smallest order which will fit the object.
7554 */
calc_slab_order(unsigned int size,unsigned int min_order,unsigned int max_order,unsigned int fract_leftover)7555 static inline unsigned int calc_slab_order(unsigned int size,
7556 unsigned int min_order, unsigned int max_order,
7557 unsigned int fract_leftover)
7558 {
7559 unsigned int order;
7560
7561 for (order = min_order; order <= max_order; order++) {
7562
7563 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
7564 unsigned int rem;
7565
7566 rem = slab_size % size;
7567
7568 if (rem <= slab_size / fract_leftover)
7569 break;
7570 }
7571
7572 return order;
7573 }
7574
calculate_order(unsigned int size)7575 static inline int calculate_order(unsigned int size)
7576 {
7577 unsigned int order;
7578 unsigned int min_objects;
7579 unsigned int max_objects;
7580 unsigned int min_order;
7581
7582 min_objects = slub_min_objects;
7583 if (!min_objects) {
7584 /*
7585 * Some architectures will only update present cpus when
7586 * onlining them, so don't trust the number if it's just 1. But
7587 * we also don't want to use nr_cpu_ids always, as on some other
7588 * architectures, there can be many possible cpus, but never
7589 * onlined. Here we compromise between trying to avoid too high
7590 * order on systems that appear larger than they are, and too
7591 * low order on systems that appear smaller than they are.
7592 */
7593 unsigned int nr_cpus = num_present_cpus();
7594 if (nr_cpus <= 1)
7595 nr_cpus = nr_cpu_ids;
7596 min_objects = 4 * (fls(nr_cpus) + 1);
7597 }
7598 /* min_objects can't be 0 because get_order(0) is undefined */
7599 max_objects = max(order_objects(slub_max_order, size), 1U);
7600 min_objects = min(min_objects, max_objects);
7601
7602 min_order = max_t(unsigned int, slub_min_order,
7603 get_order(min_objects * size));
7604 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
7605 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
7606
7607 /*
7608 * Attempt to find best configuration for a slab. This works by first
7609 * attempting to generate a layout with the best possible configuration
7610 * and backing off gradually.
7611 *
7612 * We start with accepting at most 1/16 waste and try to find the
7613 * smallest order from min_objects-derived/slab_min_order up to
7614 * slab_max_order that will satisfy the constraint. Note that increasing
7615 * the order can only result in same or less fractional waste, not more.
7616 *
7617 * If that fails, we increase the acceptable fraction of waste and try
7618 * again. The last iteration with fraction of 1/2 would effectively
7619 * accept any waste and give us the order determined by min_objects, as
7620 * long as at least single object fits within slab_max_order.
7621 */
7622 for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
7623 order = calc_slab_order(size, min_order, slub_max_order,
7624 fraction);
7625 if (order <= slub_max_order)
7626 return order;
7627 }
7628
7629 /*
7630 * Doh this slab cannot be placed using slab_max_order.
7631 */
7632 order = get_order(size);
7633 if (order <= MAX_PAGE_ORDER)
7634 return order;
7635 return -ENOSYS;
7636 }
7637
7638 static void
init_kmem_cache_node(struct kmem_cache_node * n,struct node_barn * barn)7639 init_kmem_cache_node(struct kmem_cache_node *n, struct node_barn *barn)
7640 {
7641 n->nr_partial = 0;
7642 spin_lock_init(&n->list_lock);
7643 INIT_LIST_HEAD(&n->partial);
7644 #ifdef CONFIG_SLUB_DEBUG
7645 atomic_long_set(&n->nr_slabs, 0);
7646 atomic_long_set(&n->total_objects, 0);
7647 INIT_LIST_HEAD(&n->full);
7648 #endif
7649 n->barn = barn;
7650 if (barn)
7651 barn_init(barn);
7652 }
7653
7654 #ifndef CONFIG_SLUB_TINY
alloc_kmem_cache_cpus(struct kmem_cache * s)7655 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
7656 {
7657 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
7658 NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
7659 sizeof(struct kmem_cache_cpu));
7660
7661 /*
7662 * Must align to double word boundary for the double cmpxchg
7663 * instructions to work; see __pcpu_double_call_return_bool().
7664 */
7665 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
7666 2 * sizeof(void *));
7667
7668 if (!s->cpu_slab)
7669 return 0;
7670
7671 init_kmem_cache_cpus(s);
7672
7673 return 1;
7674 }
7675 #else
alloc_kmem_cache_cpus(struct kmem_cache * s)7676 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
7677 {
7678 return 1;
7679 }
7680 #endif /* CONFIG_SLUB_TINY */
7681
init_percpu_sheaves(struct kmem_cache * s)7682 static int init_percpu_sheaves(struct kmem_cache *s)
7683 {
7684 int cpu;
7685
7686 for_each_possible_cpu(cpu) {
7687 struct slub_percpu_sheaves *pcs;
7688
7689 pcs = per_cpu_ptr(s->cpu_sheaves, cpu);
7690
7691 local_trylock_init(&pcs->lock);
7692
7693 pcs->main = alloc_empty_sheaf(s, GFP_KERNEL);
7694
7695 if (!pcs->main)
7696 return -ENOMEM;
7697 }
7698
7699 return 0;
7700 }
7701
7702 static struct kmem_cache *kmem_cache_node;
7703
7704 /*
7705 * No kmalloc_node yet so do it by hand. We know that this is the first
7706 * slab on the node for this slabcache. There are no concurrent accesses
7707 * possible.
7708 *
7709 * Note that this function only works on the kmem_cache_node
7710 * when allocating for the kmem_cache_node. This is used for bootstrapping
7711 * memory on a fresh node that has no slab structures yet.
7712 */
early_kmem_cache_node_alloc(int node)7713 static void early_kmem_cache_node_alloc(int node)
7714 {
7715 struct slab *slab;
7716 struct kmem_cache_node *n;
7717
7718 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
7719
7720 slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
7721
7722 BUG_ON(!slab);
7723 if (slab_nid(slab) != node) {
7724 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
7725 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
7726 }
7727
7728 n = slab->freelist;
7729 BUG_ON(!n);
7730 #ifdef CONFIG_SLUB_DEBUG
7731 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
7732 #endif
7733 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
7734 slab->freelist = get_freepointer(kmem_cache_node, n);
7735 slab->inuse = 1;
7736 kmem_cache_node->node[node] = n;
7737 init_kmem_cache_node(n, NULL);
7738 inc_slabs_node(kmem_cache_node, node, slab->objects);
7739
7740 /*
7741 * No locks need to be taken here as it has just been
7742 * initialized and there is no concurrent access.
7743 */
7744 __add_partial(n, slab, DEACTIVATE_TO_HEAD);
7745 }
7746
free_kmem_cache_nodes(struct kmem_cache * s)7747 static void free_kmem_cache_nodes(struct kmem_cache *s)
7748 {
7749 int node;
7750 struct kmem_cache_node *n;
7751
7752 for_each_kmem_cache_node(s, node, n) {
7753 if (n->barn) {
7754 WARN_ON(n->barn->nr_full);
7755 WARN_ON(n->barn->nr_empty);
7756 kfree(n->barn);
7757 n->barn = NULL;
7758 }
7759
7760 s->node[node] = NULL;
7761 kmem_cache_free(kmem_cache_node, n);
7762 }
7763 }
7764
__kmem_cache_release(struct kmem_cache * s)7765 void __kmem_cache_release(struct kmem_cache *s)
7766 {
7767 cache_random_seq_destroy(s);
7768 if (s->cpu_sheaves)
7769 pcs_destroy(s);
7770 #ifndef CONFIG_SLUB_TINY
7771 #ifdef CONFIG_PREEMPT_RT
7772 if (s->cpu_slab)
7773 lockdep_unregister_key(&s->lock_key);
7774 #endif
7775 free_percpu(s->cpu_slab);
7776 #endif
7777 free_kmem_cache_nodes(s);
7778 }
7779
init_kmem_cache_nodes(struct kmem_cache * s)7780 static int init_kmem_cache_nodes(struct kmem_cache *s)
7781 {
7782 int node;
7783
7784 for_each_node_mask(node, slab_nodes) {
7785 struct kmem_cache_node *n;
7786 struct node_barn *barn = NULL;
7787
7788 if (slab_state == DOWN) {
7789 early_kmem_cache_node_alloc(node);
7790 continue;
7791 }
7792
7793 if (s->cpu_sheaves) {
7794 barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, node);
7795
7796 if (!barn)
7797 return 0;
7798 }
7799
7800 n = kmem_cache_alloc_node(kmem_cache_node,
7801 GFP_KERNEL, node);
7802 if (!n) {
7803 kfree(barn);
7804 return 0;
7805 }
7806
7807 init_kmem_cache_node(n, barn);
7808
7809 s->node[node] = n;
7810 }
7811 return 1;
7812 }
7813
set_cpu_partial(struct kmem_cache * s)7814 static void set_cpu_partial(struct kmem_cache *s)
7815 {
7816 #ifdef CONFIG_SLUB_CPU_PARTIAL
7817 unsigned int nr_objects;
7818
7819 /*
7820 * cpu_partial determined the maximum number of objects kept in the
7821 * per cpu partial lists of a processor.
7822 *
7823 * Per cpu partial lists mainly contain slabs that just have one
7824 * object freed. If they are used for allocation then they can be
7825 * filled up again with minimal effort. The slab will never hit the
7826 * per node partial lists and therefore no locking will be required.
7827 *
7828 * For backwards compatibility reasons, this is determined as number
7829 * of objects, even though we now limit maximum number of pages, see
7830 * slub_set_cpu_partial()
7831 */
7832 if (!kmem_cache_has_cpu_partial(s))
7833 nr_objects = 0;
7834 else if (s->size >= PAGE_SIZE)
7835 nr_objects = 6;
7836 else if (s->size >= 1024)
7837 nr_objects = 24;
7838 else if (s->size >= 256)
7839 nr_objects = 52;
7840 else
7841 nr_objects = 120;
7842
7843 slub_set_cpu_partial(s, nr_objects);
7844 #endif
7845 }
7846
7847 /*
7848 * calculate_sizes() determines the order and the distribution of data within
7849 * a slab object.
7850 */
calculate_sizes(struct kmem_cache_args * args,struct kmem_cache * s)7851 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
7852 {
7853 slab_flags_t flags = s->flags;
7854 unsigned int size = s->object_size;
7855 unsigned int order;
7856
7857 /*
7858 * Round up object size to the next word boundary. We can only
7859 * place the free pointer at word boundaries and this determines
7860 * the possible location of the free pointer.
7861 */
7862 size = ALIGN(size, sizeof(void *));
7863
7864 #ifdef CONFIG_SLUB_DEBUG
7865 /*
7866 * Determine if we can poison the object itself. If the user of
7867 * the slab may touch the object after free or before allocation
7868 * then we should never poison the object itself.
7869 */
7870 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
7871 !s->ctor)
7872 s->flags |= __OBJECT_POISON;
7873 else
7874 s->flags &= ~__OBJECT_POISON;
7875
7876
7877 /*
7878 * If we are Redzoning then check if there is some space between the
7879 * end of the object and the free pointer. If not then add an
7880 * additional word to have some bytes to store Redzone information.
7881 */
7882 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
7883 size += sizeof(void *);
7884 #endif
7885
7886 /*
7887 * With that we have determined the number of bytes in actual use
7888 * by the object and redzoning.
7889 */
7890 s->inuse = size;
7891
7892 if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
7893 (flags & SLAB_POISON) || s->ctor ||
7894 ((flags & SLAB_RED_ZONE) &&
7895 (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
7896 /*
7897 * Relocate free pointer after the object if it is not
7898 * permitted to overwrite the first word of the object on
7899 * kmem_cache_free.
7900 *
7901 * This is the case if we do RCU, have a constructor or
7902 * destructor, are poisoning the objects, or are
7903 * redzoning an object smaller than sizeof(void *) or are
7904 * redzoning an object with slub_debug_orig_size() enabled,
7905 * in which case the right redzone may be extended.
7906 *
7907 * The assumption that s->offset >= s->inuse means free
7908 * pointer is outside of the object is used in the
7909 * freeptr_outside_object() function. If that is no
7910 * longer true, the function needs to be modified.
7911 */
7912 s->offset = size;
7913 size += sizeof(void *);
7914 } else if ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) {
7915 s->offset = args->freeptr_offset;
7916 } else {
7917 /*
7918 * Store freelist pointer near middle of object to keep
7919 * it away from the edges of the object to avoid small
7920 * sized over/underflows from neighboring allocations.
7921 */
7922 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
7923 }
7924
7925 #ifdef CONFIG_SLUB_DEBUG
7926 if (flags & SLAB_STORE_USER) {
7927 /*
7928 * Need to store information about allocs and frees after
7929 * the object.
7930 */
7931 size += 2 * sizeof(struct track);
7932
7933 /* Save the original kmalloc request size */
7934 if (flags & SLAB_KMALLOC)
7935 size += sizeof(unsigned int);
7936 }
7937 #endif
7938
7939 kasan_cache_create(s, &size, &s->flags);
7940 #ifdef CONFIG_SLUB_DEBUG
7941 if (flags & SLAB_RED_ZONE) {
7942 /*
7943 * Add some empty padding so that we can catch
7944 * overwrites from earlier objects rather than let
7945 * tracking information or the free pointer be
7946 * corrupted if a user writes before the start
7947 * of the object.
7948 */
7949 size += sizeof(void *);
7950
7951 s->red_left_pad = sizeof(void *);
7952 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
7953 size += s->red_left_pad;
7954 }
7955 #endif
7956
7957 /*
7958 * SLUB stores one object immediately after another beginning from
7959 * offset 0. In order to align the objects we have to simply size
7960 * each object to conform to the alignment.
7961 */
7962 size = ALIGN(size, s->align);
7963 s->size = size;
7964 s->reciprocal_size = reciprocal_value(size);
7965 order = calculate_order(size);
7966
7967 if ((int)order < 0)
7968 return 0;
7969
7970 s->allocflags = __GFP_COMP;
7971
7972 if (s->flags & SLAB_CACHE_DMA)
7973 s->allocflags |= GFP_DMA;
7974
7975 if (s->flags & SLAB_CACHE_DMA32)
7976 s->allocflags |= GFP_DMA32;
7977
7978 if (s->flags & SLAB_RECLAIM_ACCOUNT)
7979 s->allocflags |= __GFP_RECLAIMABLE;
7980
7981 /*
7982 * Determine the number of objects per slab
7983 */
7984 s->oo = oo_make(order, size);
7985 s->min = oo_make(get_order(size), size);
7986
7987 return !!oo_objects(s->oo);
7988 }
7989
list_slab_objects(struct kmem_cache * s,struct slab * slab)7990 static void list_slab_objects(struct kmem_cache *s, struct slab *slab)
7991 {
7992 #ifdef CONFIG_SLUB_DEBUG
7993 void *addr = slab_address(slab);
7994 void *p;
7995
7996 if (!slab_add_kunit_errors())
7997 slab_bug(s, "Objects remaining on __kmem_cache_shutdown()");
7998
7999 spin_lock(&object_map_lock);
8000 __fill_map(object_map, s, slab);
8001
8002 for_each_object(p, s, addr, slab->objects) {
8003
8004 if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
8005 if (slab_add_kunit_errors())
8006 continue;
8007 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
8008 print_tracking(s, p);
8009 }
8010 }
8011 spin_unlock(&object_map_lock);
8012
8013 __slab_err(slab);
8014 #endif
8015 }
8016
8017 /*
8018 * Attempt to free all partial slabs on a node.
8019 * This is called from __kmem_cache_shutdown(). We must take list_lock
8020 * because sysfs file might still access partial list after the shutdowning.
8021 */
free_partial(struct kmem_cache * s,struct kmem_cache_node * n)8022 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
8023 {
8024 LIST_HEAD(discard);
8025 struct slab *slab, *h;
8026
8027 BUG_ON(irqs_disabled());
8028 spin_lock_irq(&n->list_lock);
8029 list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
8030 if (!slab->inuse) {
8031 remove_partial(n, slab);
8032 list_add(&slab->slab_list, &discard);
8033 } else {
8034 list_slab_objects(s, slab);
8035 }
8036 }
8037 spin_unlock_irq(&n->list_lock);
8038
8039 list_for_each_entry_safe(slab, h, &discard, slab_list)
8040 discard_slab(s, slab);
8041 }
8042
__kmem_cache_empty(struct kmem_cache * s)8043 bool __kmem_cache_empty(struct kmem_cache *s)
8044 {
8045 int node;
8046 struct kmem_cache_node *n;
8047
8048 for_each_kmem_cache_node(s, node, n)
8049 if (n->nr_partial || node_nr_slabs(n))
8050 return false;
8051 return true;
8052 }
8053
8054 /*
8055 * Release all resources used by a slab cache.
8056 */
__kmem_cache_shutdown(struct kmem_cache * s)8057 int __kmem_cache_shutdown(struct kmem_cache *s)
8058 {
8059 int node;
8060 struct kmem_cache_node *n;
8061
8062 flush_all_cpus_locked(s);
8063
8064 /* we might have rcu sheaves in flight */
8065 if (s->cpu_sheaves)
8066 rcu_barrier();
8067
8068 /* Attempt to free all objects */
8069 for_each_kmem_cache_node(s, node, n) {
8070 if (n->barn)
8071 barn_shrink(s, n->barn);
8072 free_partial(s, n);
8073 if (n->nr_partial || node_nr_slabs(n))
8074 return 1;
8075 }
8076 return 0;
8077 }
8078
8079 #ifdef CONFIG_PRINTK
__kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct slab * slab)8080 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
8081 {
8082 void *base;
8083 int __maybe_unused i;
8084 unsigned int objnr;
8085 void *objp;
8086 void *objp0;
8087 struct kmem_cache *s = slab->slab_cache;
8088 struct track __maybe_unused *trackp;
8089
8090 kpp->kp_ptr = object;
8091 kpp->kp_slab = slab;
8092 kpp->kp_slab_cache = s;
8093 base = slab_address(slab);
8094 objp0 = kasan_reset_tag(object);
8095 #ifdef CONFIG_SLUB_DEBUG
8096 objp = restore_red_left(s, objp0);
8097 #else
8098 objp = objp0;
8099 #endif
8100 objnr = obj_to_index(s, slab, objp);
8101 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
8102 objp = base + s->size * objnr;
8103 kpp->kp_objp = objp;
8104 if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
8105 || (objp - base) % s->size) ||
8106 !(s->flags & SLAB_STORE_USER))
8107 return;
8108 #ifdef CONFIG_SLUB_DEBUG
8109 objp = fixup_red_left(s, objp);
8110 trackp = get_track(s, objp, TRACK_ALLOC);
8111 kpp->kp_ret = (void *)trackp->addr;
8112 #ifdef CONFIG_STACKDEPOT
8113 {
8114 depot_stack_handle_t handle;
8115 unsigned long *entries;
8116 unsigned int nr_entries;
8117
8118 handle = READ_ONCE(trackp->handle);
8119 if (handle) {
8120 nr_entries = stack_depot_fetch(handle, &entries);
8121 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8122 kpp->kp_stack[i] = (void *)entries[i];
8123 }
8124
8125 trackp = get_track(s, objp, TRACK_FREE);
8126 handle = READ_ONCE(trackp->handle);
8127 if (handle) {
8128 nr_entries = stack_depot_fetch(handle, &entries);
8129 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
8130 kpp->kp_free_stack[i] = (void *)entries[i];
8131 }
8132 }
8133 #endif
8134 #endif
8135 }
8136 #endif
8137
8138 /********************************************************************
8139 * Kmalloc subsystem
8140 *******************************************************************/
8141
setup_slub_min_order(char * str)8142 static int __init setup_slub_min_order(char *str)
8143 {
8144 get_option(&str, (int *)&slub_min_order);
8145
8146 if (slub_min_order > slub_max_order)
8147 slub_max_order = slub_min_order;
8148
8149 return 1;
8150 }
8151
8152 __setup("slab_min_order=", setup_slub_min_order);
8153 __setup_param("slub_min_order=", slub_min_order, setup_slub_min_order, 0);
8154
8155
setup_slub_max_order(char * str)8156 static int __init setup_slub_max_order(char *str)
8157 {
8158 get_option(&str, (int *)&slub_max_order);
8159 slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
8160
8161 if (slub_min_order > slub_max_order)
8162 slub_min_order = slub_max_order;
8163
8164 return 1;
8165 }
8166
8167 __setup("slab_max_order=", setup_slub_max_order);
8168 __setup_param("slub_max_order=", slub_max_order, setup_slub_max_order, 0);
8169
setup_slub_min_objects(char * str)8170 static int __init setup_slub_min_objects(char *str)
8171 {
8172 get_option(&str, (int *)&slub_min_objects);
8173
8174 return 1;
8175 }
8176
8177 __setup("slab_min_objects=", setup_slub_min_objects);
8178 __setup_param("slub_min_objects=", slub_min_objects, setup_slub_min_objects, 0);
8179
8180 #ifdef CONFIG_NUMA
setup_slab_strict_numa(char * str)8181 static int __init setup_slab_strict_numa(char *str)
8182 {
8183 if (nr_node_ids > 1) {
8184 static_branch_enable(&strict_numa);
8185 pr_info("SLUB: Strict NUMA enabled.\n");
8186 } else {
8187 pr_warn("slab_strict_numa parameter set on non NUMA system.\n");
8188 }
8189
8190 return 1;
8191 }
8192
8193 __setup("slab_strict_numa", setup_slab_strict_numa);
8194 #endif
8195
8196
8197 #ifdef CONFIG_HARDENED_USERCOPY
8198 /*
8199 * Rejects incorrectly sized objects and objects that are to be copied
8200 * to/from userspace but do not fall entirely within the containing slab
8201 * cache's usercopy region.
8202 *
8203 * Returns NULL if check passes, otherwise const char * to name of cache
8204 * to indicate an error.
8205 */
__check_heap_object(const void * ptr,unsigned long n,const struct slab * slab,bool to_user)8206 void __check_heap_object(const void *ptr, unsigned long n,
8207 const struct slab *slab, bool to_user)
8208 {
8209 struct kmem_cache *s;
8210 unsigned int offset;
8211 bool is_kfence = is_kfence_address(ptr);
8212
8213 ptr = kasan_reset_tag(ptr);
8214
8215 /* Find object and usable object size. */
8216 s = slab->slab_cache;
8217
8218 /* Reject impossible pointers. */
8219 if (ptr < slab_address(slab))
8220 usercopy_abort("SLUB object not in SLUB page?!", NULL,
8221 to_user, 0, n);
8222
8223 /* Find offset within object. */
8224 if (is_kfence)
8225 offset = ptr - kfence_object_start(ptr);
8226 else
8227 offset = (ptr - slab_address(slab)) % s->size;
8228
8229 /* Adjust for redzone and reject if within the redzone. */
8230 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
8231 if (offset < s->red_left_pad)
8232 usercopy_abort("SLUB object in left red zone",
8233 s->name, to_user, offset, n);
8234 offset -= s->red_left_pad;
8235 }
8236
8237 /* Allow address range falling entirely within usercopy region. */
8238 if (offset >= s->useroffset &&
8239 offset - s->useroffset <= s->usersize &&
8240 n <= s->useroffset - offset + s->usersize)
8241 return;
8242
8243 usercopy_abort("SLUB object", s->name, to_user, offset, n);
8244 }
8245 #endif /* CONFIG_HARDENED_USERCOPY */
8246
8247 #define SHRINK_PROMOTE_MAX 32
8248
8249 /*
8250 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
8251 * up most to the head of the partial lists. New allocations will then
8252 * fill those up and thus they can be removed from the partial lists.
8253 *
8254 * The slabs with the least items are placed last. This results in them
8255 * being allocated from last increasing the chance that the last objects
8256 * are freed in them.
8257 */
__kmem_cache_do_shrink(struct kmem_cache * s)8258 static int __kmem_cache_do_shrink(struct kmem_cache *s)
8259 {
8260 int node;
8261 int i;
8262 struct kmem_cache_node *n;
8263 struct slab *slab;
8264 struct slab *t;
8265 struct list_head discard;
8266 struct list_head promote[SHRINK_PROMOTE_MAX];
8267 unsigned long flags;
8268 int ret = 0;
8269
8270 for_each_kmem_cache_node(s, node, n) {
8271 INIT_LIST_HEAD(&discard);
8272 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
8273 INIT_LIST_HEAD(promote + i);
8274
8275 if (n->barn)
8276 barn_shrink(s, n->barn);
8277
8278 spin_lock_irqsave(&n->list_lock, flags);
8279
8280 /*
8281 * Build lists of slabs to discard or promote.
8282 *
8283 * Note that concurrent frees may occur while we hold the
8284 * list_lock. slab->inuse here is the upper limit.
8285 */
8286 list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
8287 int free = slab->objects - slab->inuse;
8288
8289 /* Do not reread slab->inuse */
8290 barrier();
8291
8292 /* We do not keep full slabs on the list */
8293 BUG_ON(free <= 0);
8294
8295 if (free == slab->objects) {
8296 list_move(&slab->slab_list, &discard);
8297 slab_clear_node_partial(slab);
8298 n->nr_partial--;
8299 dec_slabs_node(s, node, slab->objects);
8300 } else if (free <= SHRINK_PROMOTE_MAX)
8301 list_move(&slab->slab_list, promote + free - 1);
8302 }
8303
8304 /*
8305 * Promote the slabs filled up most to the head of the
8306 * partial list.
8307 */
8308 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
8309 list_splice(promote + i, &n->partial);
8310
8311 spin_unlock_irqrestore(&n->list_lock, flags);
8312
8313 /* Release empty slabs */
8314 list_for_each_entry_safe(slab, t, &discard, slab_list)
8315 free_slab(s, slab);
8316
8317 if (node_nr_slabs(n))
8318 ret = 1;
8319 }
8320
8321 return ret;
8322 }
8323
__kmem_cache_shrink(struct kmem_cache * s)8324 int __kmem_cache_shrink(struct kmem_cache *s)
8325 {
8326 flush_all(s);
8327 return __kmem_cache_do_shrink(s);
8328 }
8329
slab_mem_going_offline_callback(void)8330 static int slab_mem_going_offline_callback(void)
8331 {
8332 struct kmem_cache *s;
8333
8334 mutex_lock(&slab_mutex);
8335 list_for_each_entry(s, &slab_caches, list) {
8336 flush_all_cpus_locked(s);
8337 __kmem_cache_do_shrink(s);
8338 }
8339 mutex_unlock(&slab_mutex);
8340
8341 return 0;
8342 }
8343
slab_mem_going_online_callback(int nid)8344 static int slab_mem_going_online_callback(int nid)
8345 {
8346 struct kmem_cache_node *n;
8347 struct kmem_cache *s;
8348 int ret = 0;
8349
8350 /*
8351 * We are bringing a node online. No memory is available yet. We must
8352 * allocate a kmem_cache_node structure in order to bring the node
8353 * online.
8354 */
8355 mutex_lock(&slab_mutex);
8356 list_for_each_entry(s, &slab_caches, list) {
8357 struct node_barn *barn = NULL;
8358
8359 /*
8360 * The structure may already exist if the node was previously
8361 * onlined and offlined.
8362 */
8363 if (get_node(s, nid))
8364 continue;
8365
8366 if (s->cpu_sheaves) {
8367 barn = kmalloc_node(sizeof(*barn), GFP_KERNEL, nid);
8368
8369 if (!barn) {
8370 ret = -ENOMEM;
8371 goto out;
8372 }
8373 }
8374
8375 /*
8376 * XXX: kmem_cache_alloc_node will fallback to other nodes
8377 * since memory is not yet available from the node that
8378 * is brought up.
8379 */
8380 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
8381 if (!n) {
8382 kfree(barn);
8383 ret = -ENOMEM;
8384 goto out;
8385 }
8386
8387 init_kmem_cache_node(n, barn);
8388
8389 s->node[nid] = n;
8390 }
8391 /*
8392 * Any cache created after this point will also have kmem_cache_node
8393 * initialized for the new node.
8394 */
8395 node_set(nid, slab_nodes);
8396 out:
8397 mutex_unlock(&slab_mutex);
8398 return ret;
8399 }
8400
slab_memory_callback(struct notifier_block * self,unsigned long action,void * arg)8401 static int slab_memory_callback(struct notifier_block *self,
8402 unsigned long action, void *arg)
8403 {
8404 struct node_notify *nn = arg;
8405 int nid = nn->nid;
8406 int ret = 0;
8407
8408 switch (action) {
8409 case NODE_ADDING_FIRST_MEMORY:
8410 ret = slab_mem_going_online_callback(nid);
8411 break;
8412 case NODE_REMOVING_LAST_MEMORY:
8413 ret = slab_mem_going_offline_callback();
8414 break;
8415 }
8416 if (ret)
8417 ret = notifier_from_errno(ret);
8418 else
8419 ret = NOTIFY_OK;
8420 return ret;
8421 }
8422
8423 /********************************************************************
8424 * Basic setup of slabs
8425 *******************************************************************/
8426
8427 /*
8428 * Used for early kmem_cache structures that were allocated using
8429 * the page allocator. Allocate them properly then fix up the pointers
8430 * that may be pointing to the wrong kmem_cache structure.
8431 */
8432
bootstrap(struct kmem_cache * static_cache)8433 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
8434 {
8435 int node;
8436 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
8437 struct kmem_cache_node *n;
8438
8439 memcpy(s, static_cache, kmem_cache->object_size);
8440
8441 /*
8442 * This runs very early, and only the boot processor is supposed to be
8443 * up. Even if it weren't true, IRQs are not up so we couldn't fire
8444 * IPIs around.
8445 */
8446 __flush_cpu_slab(s, smp_processor_id());
8447 for_each_kmem_cache_node(s, node, n) {
8448 struct slab *p;
8449
8450 list_for_each_entry(p, &n->partial, slab_list)
8451 p->slab_cache = s;
8452
8453 #ifdef CONFIG_SLUB_DEBUG
8454 list_for_each_entry(p, &n->full, slab_list)
8455 p->slab_cache = s;
8456 #endif
8457 }
8458 list_add(&s->list, &slab_caches);
8459 return s;
8460 }
8461
kmem_cache_init(void)8462 void __init kmem_cache_init(void)
8463 {
8464 static __initdata struct kmem_cache boot_kmem_cache,
8465 boot_kmem_cache_node;
8466 int node;
8467
8468 if (debug_guardpage_minorder())
8469 slub_max_order = 0;
8470
8471 /* Inform pointer hashing choice about slub debugging state. */
8472 hash_pointers_finalize(__slub_debug_enabled());
8473
8474 kmem_cache_node = &boot_kmem_cache_node;
8475 kmem_cache = &boot_kmem_cache;
8476
8477 /*
8478 * Initialize the nodemask for which we will allocate per node
8479 * structures. Here we don't need taking slab_mutex yet.
8480 */
8481 for_each_node_state(node, N_MEMORY)
8482 node_set(node, slab_nodes);
8483
8484 create_boot_cache(kmem_cache_node, "kmem_cache_node",
8485 sizeof(struct kmem_cache_node),
8486 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
8487
8488 hotplug_node_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
8489
8490 /* Able to allocate the per node structures */
8491 slab_state = PARTIAL;
8492
8493 create_boot_cache(kmem_cache, "kmem_cache",
8494 offsetof(struct kmem_cache, node) +
8495 nr_node_ids * sizeof(struct kmem_cache_node *),
8496 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
8497
8498 kmem_cache = bootstrap(&boot_kmem_cache);
8499 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
8500
8501 /* Now we can use the kmem_cache to allocate kmalloc slabs */
8502 setup_kmalloc_cache_index_table();
8503 create_kmalloc_caches();
8504
8505 /* Setup random freelists for each cache */
8506 init_freelist_randomization();
8507
8508 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
8509 slub_cpu_dead);
8510
8511 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
8512 cache_line_size(),
8513 slub_min_order, slub_max_order, slub_min_objects,
8514 nr_cpu_ids, nr_node_ids);
8515 }
8516
kmem_cache_init_late(void)8517 void __init kmem_cache_init_late(void)
8518 {
8519 #ifndef CONFIG_SLUB_TINY
8520 flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
8521 WARN_ON(!flushwq);
8522 #endif
8523 }
8524
8525 struct kmem_cache *
__kmem_cache_alias(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))8526 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
8527 slab_flags_t flags, void (*ctor)(void *))
8528 {
8529 struct kmem_cache *s;
8530
8531 s = find_mergeable(size, align, flags, name, ctor);
8532 if (s) {
8533 if (sysfs_slab_alias(s, name))
8534 pr_err("SLUB: Unable to add cache alias %s to sysfs\n",
8535 name);
8536
8537 s->refcount++;
8538
8539 /*
8540 * Adjust the object sizes so that we clear
8541 * the complete object on kzalloc.
8542 */
8543 s->object_size = max(s->object_size, size);
8544 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
8545 }
8546
8547 return s;
8548 }
8549
do_kmem_cache_create(struct kmem_cache * s,const char * name,unsigned int size,struct kmem_cache_args * args,slab_flags_t flags)8550 int do_kmem_cache_create(struct kmem_cache *s, const char *name,
8551 unsigned int size, struct kmem_cache_args *args,
8552 slab_flags_t flags)
8553 {
8554 int err = -EINVAL;
8555
8556 s->name = name;
8557 s->size = s->object_size = size;
8558
8559 s->flags = kmem_cache_flags(flags, s->name);
8560 #ifdef CONFIG_SLAB_FREELIST_HARDENED
8561 s->random = get_random_long();
8562 #endif
8563 s->align = args->align;
8564 s->ctor = args->ctor;
8565 #ifdef CONFIG_HARDENED_USERCOPY
8566 s->useroffset = args->useroffset;
8567 s->usersize = args->usersize;
8568 #endif
8569
8570 if (!calculate_sizes(args, s))
8571 goto out;
8572 if (disable_higher_order_debug) {
8573 /*
8574 * Disable debugging flags that store metadata if the min slab
8575 * order increased.
8576 */
8577 if (get_order(s->size) > get_order(s->object_size)) {
8578 s->flags &= ~DEBUG_METADATA_FLAGS;
8579 s->offset = 0;
8580 if (!calculate_sizes(args, s))
8581 goto out;
8582 }
8583 }
8584
8585 #ifdef system_has_freelist_aba
8586 if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
8587 /* Enable fast mode */
8588 s->flags |= __CMPXCHG_DOUBLE;
8589 }
8590 #endif
8591
8592 /*
8593 * The larger the object size is, the more slabs we want on the partial
8594 * list to avoid pounding the page allocator excessively.
8595 */
8596 s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
8597 s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
8598
8599 set_cpu_partial(s);
8600
8601 if (args->sheaf_capacity && !IS_ENABLED(CONFIG_SLUB_TINY)
8602 && !(s->flags & SLAB_DEBUG_FLAGS)) {
8603 s->cpu_sheaves = alloc_percpu(struct slub_percpu_sheaves);
8604 if (!s->cpu_sheaves) {
8605 err = -ENOMEM;
8606 goto out;
8607 }
8608 // TODO: increase capacity to grow slab_sheaf up to next kmalloc size?
8609 s->sheaf_capacity = args->sheaf_capacity;
8610 }
8611
8612 #ifdef CONFIG_NUMA
8613 s->remote_node_defrag_ratio = 1000;
8614 #endif
8615
8616 /* Initialize the pre-computed randomized freelist if slab is up */
8617 if (slab_state >= UP) {
8618 if (init_cache_random_seq(s))
8619 goto out;
8620 }
8621
8622 if (!init_kmem_cache_nodes(s))
8623 goto out;
8624
8625 if (!alloc_kmem_cache_cpus(s))
8626 goto out;
8627
8628 if (s->cpu_sheaves) {
8629 err = init_percpu_sheaves(s);
8630 if (err)
8631 goto out;
8632 }
8633
8634 err = 0;
8635
8636 /* Mutex is not taken during early boot */
8637 if (slab_state <= UP)
8638 goto out;
8639
8640 /*
8641 * Failing to create sysfs files is not critical to SLUB functionality.
8642 * If it fails, proceed with cache creation without these files.
8643 */
8644 if (sysfs_slab_add(s))
8645 pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name);
8646
8647 if (s->flags & SLAB_STORE_USER)
8648 debugfs_slab_add(s);
8649
8650 out:
8651 if (err)
8652 __kmem_cache_release(s);
8653 return err;
8654 }
8655
8656 #ifdef SLAB_SUPPORTS_SYSFS
count_inuse(struct slab * slab)8657 static int count_inuse(struct slab *slab)
8658 {
8659 return slab->inuse;
8660 }
8661
count_total(struct slab * slab)8662 static int count_total(struct slab *slab)
8663 {
8664 return slab->objects;
8665 }
8666 #endif
8667
8668 #ifdef CONFIG_SLUB_DEBUG
validate_slab(struct kmem_cache * s,struct slab * slab,unsigned long * obj_map)8669 static void validate_slab(struct kmem_cache *s, struct slab *slab,
8670 unsigned long *obj_map)
8671 {
8672 void *p;
8673 void *addr = slab_address(slab);
8674
8675 if (!validate_slab_ptr(slab)) {
8676 slab_err(s, slab, "Not a valid slab page");
8677 return;
8678 }
8679
8680 if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
8681 return;
8682
8683 /* Now we know that a valid freelist exists */
8684 __fill_map(obj_map, s, slab);
8685 for_each_object(p, s, addr, slab->objects) {
8686 u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
8687 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
8688
8689 if (!check_object(s, slab, p, val))
8690 break;
8691 }
8692 }
8693
validate_slab_node(struct kmem_cache * s,struct kmem_cache_node * n,unsigned long * obj_map)8694 static int validate_slab_node(struct kmem_cache *s,
8695 struct kmem_cache_node *n, unsigned long *obj_map)
8696 {
8697 unsigned long count = 0;
8698 struct slab *slab;
8699 unsigned long flags;
8700
8701 spin_lock_irqsave(&n->list_lock, flags);
8702
8703 list_for_each_entry(slab, &n->partial, slab_list) {
8704 validate_slab(s, slab, obj_map);
8705 count++;
8706 }
8707 if (count != n->nr_partial) {
8708 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
8709 s->name, count, n->nr_partial);
8710 slab_add_kunit_errors();
8711 }
8712
8713 if (!(s->flags & SLAB_STORE_USER))
8714 goto out;
8715
8716 list_for_each_entry(slab, &n->full, slab_list) {
8717 validate_slab(s, slab, obj_map);
8718 count++;
8719 }
8720 if (count != node_nr_slabs(n)) {
8721 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
8722 s->name, count, node_nr_slabs(n));
8723 slab_add_kunit_errors();
8724 }
8725
8726 out:
8727 spin_unlock_irqrestore(&n->list_lock, flags);
8728 return count;
8729 }
8730
validate_slab_cache(struct kmem_cache * s)8731 long validate_slab_cache(struct kmem_cache *s)
8732 {
8733 int node;
8734 unsigned long count = 0;
8735 struct kmem_cache_node *n;
8736 unsigned long *obj_map;
8737
8738 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
8739 if (!obj_map)
8740 return -ENOMEM;
8741
8742 flush_all(s);
8743 for_each_kmem_cache_node(s, node, n)
8744 count += validate_slab_node(s, n, obj_map);
8745
8746 bitmap_free(obj_map);
8747
8748 return count;
8749 }
8750 EXPORT_SYMBOL(validate_slab_cache);
8751
8752 #ifdef CONFIG_DEBUG_FS
8753 /*
8754 * Generate lists of code addresses where slabcache objects are allocated
8755 * and freed.
8756 */
8757
8758 struct location {
8759 depot_stack_handle_t handle;
8760 unsigned long count;
8761 unsigned long addr;
8762 unsigned long waste;
8763 long long sum_time;
8764 long min_time;
8765 long max_time;
8766 long min_pid;
8767 long max_pid;
8768 DECLARE_BITMAP(cpus, NR_CPUS);
8769 nodemask_t nodes;
8770 };
8771
8772 struct loc_track {
8773 unsigned long max;
8774 unsigned long count;
8775 struct location *loc;
8776 loff_t idx;
8777 };
8778
8779 static struct dentry *slab_debugfs_root;
8780
free_loc_track(struct loc_track * t)8781 static void free_loc_track(struct loc_track *t)
8782 {
8783 if (t->max)
8784 free_pages((unsigned long)t->loc,
8785 get_order(sizeof(struct location) * t->max));
8786 }
8787
alloc_loc_track(struct loc_track * t,unsigned long max,gfp_t flags)8788 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
8789 {
8790 struct location *l;
8791 int order;
8792
8793 order = get_order(sizeof(struct location) * max);
8794
8795 l = (void *)__get_free_pages(flags, order);
8796 if (!l)
8797 return 0;
8798
8799 if (t->count) {
8800 memcpy(l, t->loc, sizeof(struct location) * t->count);
8801 free_loc_track(t);
8802 }
8803 t->max = max;
8804 t->loc = l;
8805 return 1;
8806 }
8807
add_location(struct loc_track * t,struct kmem_cache * s,const struct track * track,unsigned int orig_size)8808 static int add_location(struct loc_track *t, struct kmem_cache *s,
8809 const struct track *track,
8810 unsigned int orig_size)
8811 {
8812 long start, end, pos;
8813 struct location *l;
8814 unsigned long caddr, chandle, cwaste;
8815 unsigned long age = jiffies - track->when;
8816 depot_stack_handle_t handle = 0;
8817 unsigned int waste = s->object_size - orig_size;
8818
8819 #ifdef CONFIG_STACKDEPOT
8820 handle = READ_ONCE(track->handle);
8821 #endif
8822 start = -1;
8823 end = t->count;
8824
8825 for ( ; ; ) {
8826 pos = start + (end - start + 1) / 2;
8827
8828 /*
8829 * There is nothing at "end". If we end up there
8830 * we need to add something to before end.
8831 */
8832 if (pos == end)
8833 break;
8834
8835 l = &t->loc[pos];
8836 caddr = l->addr;
8837 chandle = l->handle;
8838 cwaste = l->waste;
8839 if ((track->addr == caddr) && (handle == chandle) &&
8840 (waste == cwaste)) {
8841
8842 l->count++;
8843 if (track->when) {
8844 l->sum_time += age;
8845 if (age < l->min_time)
8846 l->min_time = age;
8847 if (age > l->max_time)
8848 l->max_time = age;
8849
8850 if (track->pid < l->min_pid)
8851 l->min_pid = track->pid;
8852 if (track->pid > l->max_pid)
8853 l->max_pid = track->pid;
8854
8855 cpumask_set_cpu(track->cpu,
8856 to_cpumask(l->cpus));
8857 }
8858 node_set(page_to_nid(virt_to_page(track)), l->nodes);
8859 return 1;
8860 }
8861
8862 if (track->addr < caddr)
8863 end = pos;
8864 else if (track->addr == caddr && handle < chandle)
8865 end = pos;
8866 else if (track->addr == caddr && handle == chandle &&
8867 waste < cwaste)
8868 end = pos;
8869 else
8870 start = pos;
8871 }
8872
8873 /*
8874 * Not found. Insert new tracking element.
8875 */
8876 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
8877 return 0;
8878
8879 l = t->loc + pos;
8880 if (pos < t->count)
8881 memmove(l + 1, l,
8882 (t->count - pos) * sizeof(struct location));
8883 t->count++;
8884 l->count = 1;
8885 l->addr = track->addr;
8886 l->sum_time = age;
8887 l->min_time = age;
8888 l->max_time = age;
8889 l->min_pid = track->pid;
8890 l->max_pid = track->pid;
8891 l->handle = handle;
8892 l->waste = waste;
8893 cpumask_clear(to_cpumask(l->cpus));
8894 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
8895 nodes_clear(l->nodes);
8896 node_set(page_to_nid(virt_to_page(track)), l->nodes);
8897 return 1;
8898 }
8899
process_slab(struct loc_track * t,struct kmem_cache * s,struct slab * slab,enum track_item alloc,unsigned long * obj_map)8900 static void process_slab(struct loc_track *t, struct kmem_cache *s,
8901 struct slab *slab, enum track_item alloc,
8902 unsigned long *obj_map)
8903 {
8904 void *addr = slab_address(slab);
8905 bool is_alloc = (alloc == TRACK_ALLOC);
8906 void *p;
8907
8908 __fill_map(obj_map, s, slab);
8909
8910 for_each_object(p, s, addr, slab->objects)
8911 if (!test_bit(__obj_to_index(s, addr, p), obj_map))
8912 add_location(t, s, get_track(s, p, alloc),
8913 is_alloc ? get_orig_size(s, p) :
8914 s->object_size);
8915 }
8916 #endif /* CONFIG_DEBUG_FS */
8917 #endif /* CONFIG_SLUB_DEBUG */
8918
8919 #ifdef SLAB_SUPPORTS_SYSFS
8920 enum slab_stat_type {
8921 SL_ALL, /* All slabs */
8922 SL_PARTIAL, /* Only partially allocated slabs */
8923 SL_CPU, /* Only slabs used for cpu caches */
8924 SL_OBJECTS, /* Determine allocated objects not slabs */
8925 SL_TOTAL /* Determine object capacity not slabs */
8926 };
8927
8928 #define SO_ALL (1 << SL_ALL)
8929 #define SO_PARTIAL (1 << SL_PARTIAL)
8930 #define SO_CPU (1 << SL_CPU)
8931 #define SO_OBJECTS (1 << SL_OBJECTS)
8932 #define SO_TOTAL (1 << SL_TOTAL)
8933
show_slab_objects(struct kmem_cache * s,char * buf,unsigned long flags)8934 static ssize_t show_slab_objects(struct kmem_cache *s,
8935 char *buf, unsigned long flags)
8936 {
8937 unsigned long total = 0;
8938 int node;
8939 int x;
8940 unsigned long *nodes;
8941 int len = 0;
8942
8943 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
8944 if (!nodes)
8945 return -ENOMEM;
8946
8947 if (flags & SO_CPU) {
8948 int cpu;
8949
8950 for_each_possible_cpu(cpu) {
8951 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
8952 cpu);
8953 int node;
8954 struct slab *slab;
8955
8956 slab = READ_ONCE(c->slab);
8957 if (!slab)
8958 continue;
8959
8960 node = slab_nid(slab);
8961 if (flags & SO_TOTAL)
8962 x = slab->objects;
8963 else if (flags & SO_OBJECTS)
8964 x = slab->inuse;
8965 else
8966 x = 1;
8967
8968 total += x;
8969 nodes[node] += x;
8970
8971 #ifdef CONFIG_SLUB_CPU_PARTIAL
8972 slab = slub_percpu_partial_read_once(c);
8973 if (slab) {
8974 node = slab_nid(slab);
8975 if (flags & SO_TOTAL)
8976 WARN_ON_ONCE(1);
8977 else if (flags & SO_OBJECTS)
8978 WARN_ON_ONCE(1);
8979 else
8980 x = data_race(slab->slabs);
8981 total += x;
8982 nodes[node] += x;
8983 }
8984 #endif
8985 }
8986 }
8987
8988 /*
8989 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
8990 * already held which will conflict with an existing lock order:
8991 *
8992 * mem_hotplug_lock->slab_mutex->kernfs_mutex
8993 *
8994 * We don't really need mem_hotplug_lock (to hold off
8995 * slab_mem_going_offline_callback) here because slab's memory hot
8996 * unplug code doesn't destroy the kmem_cache->node[] data.
8997 */
8998
8999 #ifdef CONFIG_SLUB_DEBUG
9000 if (flags & SO_ALL) {
9001 struct kmem_cache_node *n;
9002
9003 for_each_kmem_cache_node(s, node, n) {
9004
9005 if (flags & SO_TOTAL)
9006 x = node_nr_objs(n);
9007 else if (flags & SO_OBJECTS)
9008 x = node_nr_objs(n) - count_partial(n, count_free);
9009 else
9010 x = node_nr_slabs(n);
9011 total += x;
9012 nodes[node] += x;
9013 }
9014
9015 } else
9016 #endif
9017 if (flags & SO_PARTIAL) {
9018 struct kmem_cache_node *n;
9019
9020 for_each_kmem_cache_node(s, node, n) {
9021 if (flags & SO_TOTAL)
9022 x = count_partial(n, count_total);
9023 else if (flags & SO_OBJECTS)
9024 x = count_partial(n, count_inuse);
9025 else
9026 x = n->nr_partial;
9027 total += x;
9028 nodes[node] += x;
9029 }
9030 }
9031
9032 len += sysfs_emit_at(buf, len, "%lu", total);
9033 #ifdef CONFIG_NUMA
9034 for (node = 0; node < nr_node_ids; node++) {
9035 if (nodes[node])
9036 len += sysfs_emit_at(buf, len, " N%d=%lu",
9037 node, nodes[node]);
9038 }
9039 #endif
9040 len += sysfs_emit_at(buf, len, "\n");
9041 kfree(nodes);
9042
9043 return len;
9044 }
9045
9046 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
9047 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
9048
9049 struct slab_attribute {
9050 struct attribute attr;
9051 ssize_t (*show)(struct kmem_cache *s, char *buf);
9052 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
9053 };
9054
9055 #define SLAB_ATTR_RO(_name) \
9056 static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
9057
9058 #define SLAB_ATTR(_name) \
9059 static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
9060
slab_size_show(struct kmem_cache * s,char * buf)9061 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
9062 {
9063 return sysfs_emit(buf, "%u\n", s->size);
9064 }
9065 SLAB_ATTR_RO(slab_size);
9066
align_show(struct kmem_cache * s,char * buf)9067 static ssize_t align_show(struct kmem_cache *s, char *buf)
9068 {
9069 return sysfs_emit(buf, "%u\n", s->align);
9070 }
9071 SLAB_ATTR_RO(align);
9072
object_size_show(struct kmem_cache * s,char * buf)9073 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
9074 {
9075 return sysfs_emit(buf, "%u\n", s->object_size);
9076 }
9077 SLAB_ATTR_RO(object_size);
9078
objs_per_slab_show(struct kmem_cache * s,char * buf)9079 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
9080 {
9081 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
9082 }
9083 SLAB_ATTR_RO(objs_per_slab);
9084
order_show(struct kmem_cache * s,char * buf)9085 static ssize_t order_show(struct kmem_cache *s, char *buf)
9086 {
9087 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
9088 }
9089 SLAB_ATTR_RO(order);
9090
sheaf_capacity_show(struct kmem_cache * s,char * buf)9091 static ssize_t sheaf_capacity_show(struct kmem_cache *s, char *buf)
9092 {
9093 return sysfs_emit(buf, "%u\n", s->sheaf_capacity);
9094 }
9095 SLAB_ATTR_RO(sheaf_capacity);
9096
min_partial_show(struct kmem_cache * s,char * buf)9097 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
9098 {
9099 return sysfs_emit(buf, "%lu\n", s->min_partial);
9100 }
9101
min_partial_store(struct kmem_cache * s,const char * buf,size_t length)9102 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
9103 size_t length)
9104 {
9105 unsigned long min;
9106 int err;
9107
9108 err = kstrtoul(buf, 10, &min);
9109 if (err)
9110 return err;
9111
9112 s->min_partial = min;
9113 return length;
9114 }
9115 SLAB_ATTR(min_partial);
9116
cpu_partial_show(struct kmem_cache * s,char * buf)9117 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
9118 {
9119 unsigned int nr_partial = 0;
9120 #ifdef CONFIG_SLUB_CPU_PARTIAL
9121 nr_partial = s->cpu_partial;
9122 #endif
9123
9124 return sysfs_emit(buf, "%u\n", nr_partial);
9125 }
9126
cpu_partial_store(struct kmem_cache * s,const char * buf,size_t length)9127 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
9128 size_t length)
9129 {
9130 unsigned int objects;
9131 int err;
9132
9133 err = kstrtouint(buf, 10, &objects);
9134 if (err)
9135 return err;
9136 if (objects && !kmem_cache_has_cpu_partial(s))
9137 return -EINVAL;
9138
9139 slub_set_cpu_partial(s, objects);
9140 flush_all(s);
9141 return length;
9142 }
9143 SLAB_ATTR(cpu_partial);
9144
ctor_show(struct kmem_cache * s,char * buf)9145 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
9146 {
9147 if (!s->ctor)
9148 return 0;
9149 return sysfs_emit(buf, "%pS\n", s->ctor);
9150 }
9151 SLAB_ATTR_RO(ctor);
9152
aliases_show(struct kmem_cache * s,char * buf)9153 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
9154 {
9155 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
9156 }
9157 SLAB_ATTR_RO(aliases);
9158
partial_show(struct kmem_cache * s,char * buf)9159 static ssize_t partial_show(struct kmem_cache *s, char *buf)
9160 {
9161 return show_slab_objects(s, buf, SO_PARTIAL);
9162 }
9163 SLAB_ATTR_RO(partial);
9164
cpu_slabs_show(struct kmem_cache * s,char * buf)9165 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
9166 {
9167 return show_slab_objects(s, buf, SO_CPU);
9168 }
9169 SLAB_ATTR_RO(cpu_slabs);
9170
objects_partial_show(struct kmem_cache * s,char * buf)9171 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
9172 {
9173 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
9174 }
9175 SLAB_ATTR_RO(objects_partial);
9176
slabs_cpu_partial_show(struct kmem_cache * s,char * buf)9177 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
9178 {
9179 int objects = 0;
9180 int slabs = 0;
9181 int cpu __maybe_unused;
9182 int len = 0;
9183
9184 #ifdef CONFIG_SLUB_CPU_PARTIAL
9185 for_each_online_cpu(cpu) {
9186 struct slab *slab;
9187
9188 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
9189
9190 if (slab)
9191 slabs += data_race(slab->slabs);
9192 }
9193 #endif
9194
9195 /* Approximate half-full slabs, see slub_set_cpu_partial() */
9196 objects = (slabs * oo_objects(s->oo)) / 2;
9197 len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
9198
9199 #ifdef CONFIG_SLUB_CPU_PARTIAL
9200 for_each_online_cpu(cpu) {
9201 struct slab *slab;
9202
9203 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
9204 if (slab) {
9205 slabs = data_race(slab->slabs);
9206 objects = (slabs * oo_objects(s->oo)) / 2;
9207 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
9208 cpu, objects, slabs);
9209 }
9210 }
9211 #endif
9212 len += sysfs_emit_at(buf, len, "\n");
9213
9214 return len;
9215 }
9216 SLAB_ATTR_RO(slabs_cpu_partial);
9217
reclaim_account_show(struct kmem_cache * s,char * buf)9218 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
9219 {
9220 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
9221 }
9222 SLAB_ATTR_RO(reclaim_account);
9223
hwcache_align_show(struct kmem_cache * s,char * buf)9224 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
9225 {
9226 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
9227 }
9228 SLAB_ATTR_RO(hwcache_align);
9229
9230 #ifdef CONFIG_ZONE_DMA
cache_dma_show(struct kmem_cache * s,char * buf)9231 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
9232 {
9233 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
9234 }
9235 SLAB_ATTR_RO(cache_dma);
9236 #endif
9237
9238 #ifdef CONFIG_HARDENED_USERCOPY
usersize_show(struct kmem_cache * s,char * buf)9239 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
9240 {
9241 return sysfs_emit(buf, "%u\n", s->usersize);
9242 }
9243 SLAB_ATTR_RO(usersize);
9244 #endif
9245
destroy_by_rcu_show(struct kmem_cache * s,char * buf)9246 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
9247 {
9248 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
9249 }
9250 SLAB_ATTR_RO(destroy_by_rcu);
9251
9252 #ifdef CONFIG_SLUB_DEBUG
slabs_show(struct kmem_cache * s,char * buf)9253 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
9254 {
9255 return show_slab_objects(s, buf, SO_ALL);
9256 }
9257 SLAB_ATTR_RO(slabs);
9258
total_objects_show(struct kmem_cache * s,char * buf)9259 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
9260 {
9261 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
9262 }
9263 SLAB_ATTR_RO(total_objects);
9264
objects_show(struct kmem_cache * s,char * buf)9265 static ssize_t objects_show(struct kmem_cache *s, char *buf)
9266 {
9267 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
9268 }
9269 SLAB_ATTR_RO(objects);
9270
sanity_checks_show(struct kmem_cache * s,char * buf)9271 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
9272 {
9273 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
9274 }
9275 SLAB_ATTR_RO(sanity_checks);
9276
trace_show(struct kmem_cache * s,char * buf)9277 static ssize_t trace_show(struct kmem_cache *s, char *buf)
9278 {
9279 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
9280 }
9281 SLAB_ATTR_RO(trace);
9282
red_zone_show(struct kmem_cache * s,char * buf)9283 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
9284 {
9285 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
9286 }
9287
9288 SLAB_ATTR_RO(red_zone);
9289
poison_show(struct kmem_cache * s,char * buf)9290 static ssize_t poison_show(struct kmem_cache *s, char *buf)
9291 {
9292 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
9293 }
9294
9295 SLAB_ATTR_RO(poison);
9296
store_user_show(struct kmem_cache * s,char * buf)9297 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
9298 {
9299 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
9300 }
9301
9302 SLAB_ATTR_RO(store_user);
9303
validate_show(struct kmem_cache * s,char * buf)9304 static ssize_t validate_show(struct kmem_cache *s, char *buf)
9305 {
9306 return 0;
9307 }
9308
validate_store(struct kmem_cache * s,const char * buf,size_t length)9309 static ssize_t validate_store(struct kmem_cache *s,
9310 const char *buf, size_t length)
9311 {
9312 int ret = -EINVAL;
9313
9314 if (buf[0] == '1' && kmem_cache_debug(s)) {
9315 ret = validate_slab_cache(s);
9316 if (ret >= 0)
9317 ret = length;
9318 }
9319 return ret;
9320 }
9321 SLAB_ATTR(validate);
9322
9323 #endif /* CONFIG_SLUB_DEBUG */
9324
9325 #ifdef CONFIG_FAILSLAB
failslab_show(struct kmem_cache * s,char * buf)9326 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
9327 {
9328 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
9329 }
9330
failslab_store(struct kmem_cache * s,const char * buf,size_t length)9331 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
9332 size_t length)
9333 {
9334 if (s->refcount > 1)
9335 return -EINVAL;
9336
9337 if (buf[0] == '1')
9338 WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
9339 else
9340 WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
9341
9342 return length;
9343 }
9344 SLAB_ATTR(failslab);
9345 #endif
9346
shrink_show(struct kmem_cache * s,char * buf)9347 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
9348 {
9349 return 0;
9350 }
9351
shrink_store(struct kmem_cache * s,const char * buf,size_t length)9352 static ssize_t shrink_store(struct kmem_cache *s,
9353 const char *buf, size_t length)
9354 {
9355 if (buf[0] == '1')
9356 kmem_cache_shrink(s);
9357 else
9358 return -EINVAL;
9359 return length;
9360 }
9361 SLAB_ATTR(shrink);
9362
9363 #ifdef CONFIG_NUMA
remote_node_defrag_ratio_show(struct kmem_cache * s,char * buf)9364 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
9365 {
9366 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
9367 }
9368
remote_node_defrag_ratio_store(struct kmem_cache * s,const char * buf,size_t length)9369 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
9370 const char *buf, size_t length)
9371 {
9372 unsigned int ratio;
9373 int err;
9374
9375 err = kstrtouint(buf, 10, &ratio);
9376 if (err)
9377 return err;
9378 if (ratio > 100)
9379 return -ERANGE;
9380
9381 s->remote_node_defrag_ratio = ratio * 10;
9382
9383 return length;
9384 }
9385 SLAB_ATTR(remote_node_defrag_ratio);
9386 #endif
9387
9388 #ifdef CONFIG_SLUB_STATS
show_stat(struct kmem_cache * s,char * buf,enum stat_item si)9389 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
9390 {
9391 unsigned long sum = 0;
9392 int cpu;
9393 int len = 0;
9394 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
9395
9396 if (!data)
9397 return -ENOMEM;
9398
9399 for_each_online_cpu(cpu) {
9400 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
9401
9402 data[cpu] = x;
9403 sum += x;
9404 }
9405
9406 len += sysfs_emit_at(buf, len, "%lu", sum);
9407
9408 #ifdef CONFIG_SMP
9409 for_each_online_cpu(cpu) {
9410 if (data[cpu])
9411 len += sysfs_emit_at(buf, len, " C%d=%u",
9412 cpu, data[cpu]);
9413 }
9414 #endif
9415 kfree(data);
9416 len += sysfs_emit_at(buf, len, "\n");
9417
9418 return len;
9419 }
9420
clear_stat(struct kmem_cache * s,enum stat_item si)9421 static void clear_stat(struct kmem_cache *s, enum stat_item si)
9422 {
9423 int cpu;
9424
9425 for_each_online_cpu(cpu)
9426 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
9427 }
9428
9429 #define STAT_ATTR(si, text) \
9430 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
9431 { \
9432 return show_stat(s, buf, si); \
9433 } \
9434 static ssize_t text##_store(struct kmem_cache *s, \
9435 const char *buf, size_t length) \
9436 { \
9437 if (buf[0] != '0') \
9438 return -EINVAL; \
9439 clear_stat(s, si); \
9440 return length; \
9441 } \
9442 SLAB_ATTR(text); \
9443
9444 STAT_ATTR(ALLOC_PCS, alloc_cpu_sheaf);
9445 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
9446 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
9447 STAT_ATTR(FREE_PCS, free_cpu_sheaf);
9448 STAT_ATTR(FREE_RCU_SHEAF, free_rcu_sheaf);
9449 STAT_ATTR(FREE_RCU_SHEAF_FAIL, free_rcu_sheaf_fail);
9450 STAT_ATTR(FREE_FASTPATH, free_fastpath);
9451 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
9452 STAT_ATTR(FREE_FROZEN, free_frozen);
9453 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
9454 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
9455 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
9456 STAT_ATTR(ALLOC_SLAB, alloc_slab);
9457 STAT_ATTR(ALLOC_REFILL, alloc_refill);
9458 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
9459 STAT_ATTR(FREE_SLAB, free_slab);
9460 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
9461 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
9462 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
9463 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
9464 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
9465 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
9466 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
9467 STAT_ATTR(ORDER_FALLBACK, order_fallback);
9468 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
9469 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
9470 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
9471 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
9472 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
9473 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
9474 STAT_ATTR(SHEAF_FLUSH, sheaf_flush);
9475 STAT_ATTR(SHEAF_REFILL, sheaf_refill);
9476 STAT_ATTR(SHEAF_ALLOC, sheaf_alloc);
9477 STAT_ATTR(SHEAF_FREE, sheaf_free);
9478 STAT_ATTR(BARN_GET, barn_get);
9479 STAT_ATTR(BARN_GET_FAIL, barn_get_fail);
9480 STAT_ATTR(BARN_PUT, barn_put);
9481 STAT_ATTR(BARN_PUT_FAIL, barn_put_fail);
9482 STAT_ATTR(SHEAF_PREFILL_FAST, sheaf_prefill_fast);
9483 STAT_ATTR(SHEAF_PREFILL_SLOW, sheaf_prefill_slow);
9484 STAT_ATTR(SHEAF_PREFILL_OVERSIZE, sheaf_prefill_oversize);
9485 STAT_ATTR(SHEAF_RETURN_FAST, sheaf_return_fast);
9486 STAT_ATTR(SHEAF_RETURN_SLOW, sheaf_return_slow);
9487 #endif /* CONFIG_SLUB_STATS */
9488
9489 #ifdef CONFIG_KFENCE
skip_kfence_show(struct kmem_cache * s,char * buf)9490 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
9491 {
9492 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
9493 }
9494
skip_kfence_store(struct kmem_cache * s,const char * buf,size_t length)9495 static ssize_t skip_kfence_store(struct kmem_cache *s,
9496 const char *buf, size_t length)
9497 {
9498 int ret = length;
9499
9500 if (buf[0] == '0')
9501 s->flags &= ~SLAB_SKIP_KFENCE;
9502 else if (buf[0] == '1')
9503 s->flags |= SLAB_SKIP_KFENCE;
9504 else
9505 ret = -EINVAL;
9506
9507 return ret;
9508 }
9509 SLAB_ATTR(skip_kfence);
9510 #endif
9511
9512 static struct attribute *slab_attrs[] = {
9513 &slab_size_attr.attr,
9514 &object_size_attr.attr,
9515 &objs_per_slab_attr.attr,
9516 &order_attr.attr,
9517 &sheaf_capacity_attr.attr,
9518 &min_partial_attr.attr,
9519 &cpu_partial_attr.attr,
9520 &objects_partial_attr.attr,
9521 &partial_attr.attr,
9522 &cpu_slabs_attr.attr,
9523 &ctor_attr.attr,
9524 &aliases_attr.attr,
9525 &align_attr.attr,
9526 &hwcache_align_attr.attr,
9527 &reclaim_account_attr.attr,
9528 &destroy_by_rcu_attr.attr,
9529 &shrink_attr.attr,
9530 &slabs_cpu_partial_attr.attr,
9531 #ifdef CONFIG_SLUB_DEBUG
9532 &total_objects_attr.attr,
9533 &objects_attr.attr,
9534 &slabs_attr.attr,
9535 &sanity_checks_attr.attr,
9536 &trace_attr.attr,
9537 &red_zone_attr.attr,
9538 &poison_attr.attr,
9539 &store_user_attr.attr,
9540 &validate_attr.attr,
9541 #endif
9542 #ifdef CONFIG_ZONE_DMA
9543 &cache_dma_attr.attr,
9544 #endif
9545 #ifdef CONFIG_NUMA
9546 &remote_node_defrag_ratio_attr.attr,
9547 #endif
9548 #ifdef CONFIG_SLUB_STATS
9549 &alloc_cpu_sheaf_attr.attr,
9550 &alloc_fastpath_attr.attr,
9551 &alloc_slowpath_attr.attr,
9552 &free_cpu_sheaf_attr.attr,
9553 &free_rcu_sheaf_attr.attr,
9554 &free_rcu_sheaf_fail_attr.attr,
9555 &free_fastpath_attr.attr,
9556 &free_slowpath_attr.attr,
9557 &free_frozen_attr.attr,
9558 &free_add_partial_attr.attr,
9559 &free_remove_partial_attr.attr,
9560 &alloc_from_partial_attr.attr,
9561 &alloc_slab_attr.attr,
9562 &alloc_refill_attr.attr,
9563 &alloc_node_mismatch_attr.attr,
9564 &free_slab_attr.attr,
9565 &cpuslab_flush_attr.attr,
9566 &deactivate_full_attr.attr,
9567 &deactivate_empty_attr.attr,
9568 &deactivate_to_head_attr.attr,
9569 &deactivate_to_tail_attr.attr,
9570 &deactivate_remote_frees_attr.attr,
9571 &deactivate_bypass_attr.attr,
9572 &order_fallback_attr.attr,
9573 &cmpxchg_double_fail_attr.attr,
9574 &cmpxchg_double_cpu_fail_attr.attr,
9575 &cpu_partial_alloc_attr.attr,
9576 &cpu_partial_free_attr.attr,
9577 &cpu_partial_node_attr.attr,
9578 &cpu_partial_drain_attr.attr,
9579 &sheaf_flush_attr.attr,
9580 &sheaf_refill_attr.attr,
9581 &sheaf_alloc_attr.attr,
9582 &sheaf_free_attr.attr,
9583 &barn_get_attr.attr,
9584 &barn_get_fail_attr.attr,
9585 &barn_put_attr.attr,
9586 &barn_put_fail_attr.attr,
9587 &sheaf_prefill_fast_attr.attr,
9588 &sheaf_prefill_slow_attr.attr,
9589 &sheaf_prefill_oversize_attr.attr,
9590 &sheaf_return_fast_attr.attr,
9591 &sheaf_return_slow_attr.attr,
9592 #endif
9593 #ifdef CONFIG_FAILSLAB
9594 &failslab_attr.attr,
9595 #endif
9596 #ifdef CONFIG_HARDENED_USERCOPY
9597 &usersize_attr.attr,
9598 #endif
9599 #ifdef CONFIG_KFENCE
9600 &skip_kfence_attr.attr,
9601 #endif
9602
9603 NULL
9604 };
9605
9606 static const struct attribute_group slab_attr_group = {
9607 .attrs = slab_attrs,
9608 };
9609
slab_attr_show(struct kobject * kobj,struct attribute * attr,char * buf)9610 static ssize_t slab_attr_show(struct kobject *kobj,
9611 struct attribute *attr,
9612 char *buf)
9613 {
9614 struct slab_attribute *attribute;
9615 struct kmem_cache *s;
9616
9617 attribute = to_slab_attr(attr);
9618 s = to_slab(kobj);
9619
9620 if (!attribute->show)
9621 return -EIO;
9622
9623 return attribute->show(s, buf);
9624 }
9625
slab_attr_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t len)9626 static ssize_t slab_attr_store(struct kobject *kobj,
9627 struct attribute *attr,
9628 const char *buf, size_t len)
9629 {
9630 struct slab_attribute *attribute;
9631 struct kmem_cache *s;
9632
9633 attribute = to_slab_attr(attr);
9634 s = to_slab(kobj);
9635
9636 if (!attribute->store)
9637 return -EIO;
9638
9639 return attribute->store(s, buf, len);
9640 }
9641
kmem_cache_release(struct kobject * k)9642 static void kmem_cache_release(struct kobject *k)
9643 {
9644 slab_kmem_cache_release(to_slab(k));
9645 }
9646
9647 static const struct sysfs_ops slab_sysfs_ops = {
9648 .show = slab_attr_show,
9649 .store = slab_attr_store,
9650 };
9651
9652 static const struct kobj_type slab_ktype = {
9653 .sysfs_ops = &slab_sysfs_ops,
9654 .release = kmem_cache_release,
9655 };
9656
9657 static struct kset *slab_kset;
9658
cache_kset(struct kmem_cache * s)9659 static inline struct kset *cache_kset(struct kmem_cache *s)
9660 {
9661 return slab_kset;
9662 }
9663
9664 #define ID_STR_LENGTH 32
9665
9666 /* Create a unique string id for a slab cache:
9667 *
9668 * Format :[flags-]size
9669 */
create_unique_id(struct kmem_cache * s)9670 static char *create_unique_id(struct kmem_cache *s)
9671 {
9672 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
9673 char *p = name;
9674
9675 if (!name)
9676 return ERR_PTR(-ENOMEM);
9677
9678 *p++ = ':';
9679 /*
9680 * First flags affecting slabcache operations. We will only
9681 * get here for aliasable slabs so we do not need to support
9682 * too many flags. The flags here must cover all flags that
9683 * are matched during merging to guarantee that the id is
9684 * unique.
9685 */
9686 if (s->flags & SLAB_CACHE_DMA)
9687 *p++ = 'd';
9688 if (s->flags & SLAB_CACHE_DMA32)
9689 *p++ = 'D';
9690 if (s->flags & SLAB_RECLAIM_ACCOUNT)
9691 *p++ = 'a';
9692 if (s->flags & SLAB_CONSISTENCY_CHECKS)
9693 *p++ = 'F';
9694 if (s->flags & SLAB_ACCOUNT)
9695 *p++ = 'A';
9696 if (p != name + 1)
9697 *p++ = '-';
9698 p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
9699
9700 if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
9701 kfree(name);
9702 return ERR_PTR(-EINVAL);
9703 }
9704 kmsan_unpoison_memory(name, p - name);
9705 return name;
9706 }
9707
sysfs_slab_add(struct kmem_cache * s)9708 static int sysfs_slab_add(struct kmem_cache *s)
9709 {
9710 int err;
9711 const char *name;
9712 struct kset *kset = cache_kset(s);
9713 int unmergeable = slab_unmergeable(s);
9714
9715 if (!unmergeable && disable_higher_order_debug &&
9716 (slub_debug & DEBUG_METADATA_FLAGS))
9717 unmergeable = 1;
9718
9719 if (unmergeable) {
9720 /*
9721 * Slabcache can never be merged so we can use the name proper.
9722 * This is typically the case for debug situations. In that
9723 * case we can catch duplicate names easily.
9724 */
9725 sysfs_remove_link(&slab_kset->kobj, s->name);
9726 name = s->name;
9727 } else {
9728 /*
9729 * Create a unique name for the slab as a target
9730 * for the symlinks.
9731 */
9732 name = create_unique_id(s);
9733 if (IS_ERR(name))
9734 return PTR_ERR(name);
9735 }
9736
9737 s->kobj.kset = kset;
9738 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
9739 if (err)
9740 goto out;
9741
9742 err = sysfs_create_group(&s->kobj, &slab_attr_group);
9743 if (err)
9744 goto out_del_kobj;
9745
9746 if (!unmergeable) {
9747 /* Setup first alias */
9748 sysfs_slab_alias(s, s->name);
9749 }
9750 out:
9751 if (!unmergeable)
9752 kfree(name);
9753 return err;
9754 out_del_kobj:
9755 kobject_del(&s->kobj);
9756 goto out;
9757 }
9758
sysfs_slab_unlink(struct kmem_cache * s)9759 void sysfs_slab_unlink(struct kmem_cache *s)
9760 {
9761 if (s->kobj.state_in_sysfs)
9762 kobject_del(&s->kobj);
9763 }
9764
sysfs_slab_release(struct kmem_cache * s)9765 void sysfs_slab_release(struct kmem_cache *s)
9766 {
9767 kobject_put(&s->kobj);
9768 }
9769
9770 /*
9771 * Need to buffer aliases during bootup until sysfs becomes
9772 * available lest we lose that information.
9773 */
9774 struct saved_alias {
9775 struct kmem_cache *s;
9776 const char *name;
9777 struct saved_alias *next;
9778 };
9779
9780 static struct saved_alias *alias_list;
9781
sysfs_slab_alias(struct kmem_cache * s,const char * name)9782 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
9783 {
9784 struct saved_alias *al;
9785
9786 if (slab_state == FULL) {
9787 /*
9788 * If we have a leftover link then remove it.
9789 */
9790 sysfs_remove_link(&slab_kset->kobj, name);
9791 /*
9792 * The original cache may have failed to generate sysfs file.
9793 * In that case, sysfs_create_link() returns -ENOENT and
9794 * symbolic link creation is skipped.
9795 */
9796 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
9797 }
9798
9799 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
9800 if (!al)
9801 return -ENOMEM;
9802
9803 al->s = s;
9804 al->name = name;
9805 al->next = alias_list;
9806 alias_list = al;
9807 kmsan_unpoison_memory(al, sizeof(*al));
9808 return 0;
9809 }
9810
slab_sysfs_init(void)9811 static int __init slab_sysfs_init(void)
9812 {
9813 struct kmem_cache *s;
9814 int err;
9815
9816 mutex_lock(&slab_mutex);
9817
9818 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
9819 if (!slab_kset) {
9820 mutex_unlock(&slab_mutex);
9821 pr_err("Cannot register slab subsystem.\n");
9822 return -ENOMEM;
9823 }
9824
9825 slab_state = FULL;
9826
9827 list_for_each_entry(s, &slab_caches, list) {
9828 err = sysfs_slab_add(s);
9829 if (err)
9830 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
9831 s->name);
9832 }
9833
9834 while (alias_list) {
9835 struct saved_alias *al = alias_list;
9836
9837 alias_list = alias_list->next;
9838 err = sysfs_slab_alias(al->s, al->name);
9839 if (err)
9840 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
9841 al->name);
9842 kfree(al);
9843 }
9844
9845 mutex_unlock(&slab_mutex);
9846 return 0;
9847 }
9848 late_initcall(slab_sysfs_init);
9849 #endif /* SLAB_SUPPORTS_SYSFS */
9850
9851 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
slab_debugfs_show(struct seq_file * seq,void * v)9852 static int slab_debugfs_show(struct seq_file *seq, void *v)
9853 {
9854 struct loc_track *t = seq->private;
9855 struct location *l;
9856 unsigned long idx;
9857
9858 idx = (unsigned long) t->idx;
9859 if (idx < t->count) {
9860 l = &t->loc[idx];
9861
9862 seq_printf(seq, "%7ld ", l->count);
9863
9864 if (l->addr)
9865 seq_printf(seq, "%pS", (void *)l->addr);
9866 else
9867 seq_puts(seq, "<not-available>");
9868
9869 if (l->waste)
9870 seq_printf(seq, " waste=%lu/%lu",
9871 l->count * l->waste, l->waste);
9872
9873 if (l->sum_time != l->min_time) {
9874 seq_printf(seq, " age=%ld/%llu/%ld",
9875 l->min_time, div_u64(l->sum_time, l->count),
9876 l->max_time);
9877 } else
9878 seq_printf(seq, " age=%ld", l->min_time);
9879
9880 if (l->min_pid != l->max_pid)
9881 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
9882 else
9883 seq_printf(seq, " pid=%ld",
9884 l->min_pid);
9885
9886 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
9887 seq_printf(seq, " cpus=%*pbl",
9888 cpumask_pr_args(to_cpumask(l->cpus)));
9889
9890 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
9891 seq_printf(seq, " nodes=%*pbl",
9892 nodemask_pr_args(&l->nodes));
9893
9894 #ifdef CONFIG_STACKDEPOT
9895 {
9896 depot_stack_handle_t handle;
9897 unsigned long *entries;
9898 unsigned int nr_entries, j;
9899
9900 handle = READ_ONCE(l->handle);
9901 if (handle) {
9902 nr_entries = stack_depot_fetch(handle, &entries);
9903 seq_puts(seq, "\n");
9904 for (j = 0; j < nr_entries; j++)
9905 seq_printf(seq, " %pS\n", (void *)entries[j]);
9906 }
9907 }
9908 #endif
9909 seq_puts(seq, "\n");
9910 }
9911
9912 if (!idx && !t->count)
9913 seq_puts(seq, "No data\n");
9914
9915 return 0;
9916 }
9917
slab_debugfs_stop(struct seq_file * seq,void * v)9918 static void slab_debugfs_stop(struct seq_file *seq, void *v)
9919 {
9920 }
9921
slab_debugfs_next(struct seq_file * seq,void * v,loff_t * ppos)9922 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
9923 {
9924 struct loc_track *t = seq->private;
9925
9926 t->idx = ++(*ppos);
9927 if (*ppos <= t->count)
9928 return ppos;
9929
9930 return NULL;
9931 }
9932
cmp_loc_by_count(const void * a,const void * b)9933 static int cmp_loc_by_count(const void *a, const void *b)
9934 {
9935 struct location *loc1 = (struct location *)a;
9936 struct location *loc2 = (struct location *)b;
9937
9938 return cmp_int(loc2->count, loc1->count);
9939 }
9940
slab_debugfs_start(struct seq_file * seq,loff_t * ppos)9941 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
9942 {
9943 struct loc_track *t = seq->private;
9944
9945 t->idx = *ppos;
9946 return ppos;
9947 }
9948
9949 static const struct seq_operations slab_debugfs_sops = {
9950 .start = slab_debugfs_start,
9951 .next = slab_debugfs_next,
9952 .stop = slab_debugfs_stop,
9953 .show = slab_debugfs_show,
9954 };
9955
slab_debug_trace_open(struct inode * inode,struct file * filep)9956 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
9957 {
9958
9959 struct kmem_cache_node *n;
9960 enum track_item alloc;
9961 int node;
9962 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
9963 sizeof(struct loc_track));
9964 struct kmem_cache *s = file_inode(filep)->i_private;
9965 unsigned long *obj_map;
9966
9967 if (!t)
9968 return -ENOMEM;
9969
9970 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
9971 if (!obj_map) {
9972 seq_release_private(inode, filep);
9973 return -ENOMEM;
9974 }
9975
9976 alloc = debugfs_get_aux_num(filep);
9977
9978 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
9979 bitmap_free(obj_map);
9980 seq_release_private(inode, filep);
9981 return -ENOMEM;
9982 }
9983
9984 for_each_kmem_cache_node(s, node, n) {
9985 unsigned long flags;
9986 struct slab *slab;
9987
9988 if (!node_nr_slabs(n))
9989 continue;
9990
9991 spin_lock_irqsave(&n->list_lock, flags);
9992 list_for_each_entry(slab, &n->partial, slab_list)
9993 process_slab(t, s, slab, alloc, obj_map);
9994 list_for_each_entry(slab, &n->full, slab_list)
9995 process_slab(t, s, slab, alloc, obj_map);
9996 spin_unlock_irqrestore(&n->list_lock, flags);
9997 }
9998
9999 /* Sort locations by count */
10000 sort(t->loc, t->count, sizeof(struct location),
10001 cmp_loc_by_count, NULL);
10002
10003 bitmap_free(obj_map);
10004 return 0;
10005 }
10006
slab_debug_trace_release(struct inode * inode,struct file * file)10007 static int slab_debug_trace_release(struct inode *inode, struct file *file)
10008 {
10009 struct seq_file *seq = file->private_data;
10010 struct loc_track *t = seq->private;
10011
10012 free_loc_track(t);
10013 return seq_release_private(inode, file);
10014 }
10015
10016 static const struct file_operations slab_debugfs_fops = {
10017 .open = slab_debug_trace_open,
10018 .read = seq_read,
10019 .llseek = seq_lseek,
10020 .release = slab_debug_trace_release,
10021 };
10022
debugfs_slab_add(struct kmem_cache * s)10023 static void debugfs_slab_add(struct kmem_cache *s)
10024 {
10025 struct dentry *slab_cache_dir;
10026
10027 if (unlikely(!slab_debugfs_root))
10028 return;
10029
10030 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
10031
10032 debugfs_create_file_aux_num("alloc_traces", 0400, slab_cache_dir, s,
10033 TRACK_ALLOC, &slab_debugfs_fops);
10034
10035 debugfs_create_file_aux_num("free_traces", 0400, slab_cache_dir, s,
10036 TRACK_FREE, &slab_debugfs_fops);
10037 }
10038
debugfs_slab_release(struct kmem_cache * s)10039 void debugfs_slab_release(struct kmem_cache *s)
10040 {
10041 debugfs_lookup_and_remove(s->name, slab_debugfs_root);
10042 }
10043
slab_debugfs_init(void)10044 static int __init slab_debugfs_init(void)
10045 {
10046 struct kmem_cache *s;
10047
10048 slab_debugfs_root = debugfs_create_dir("slab", NULL);
10049
10050 list_for_each_entry(s, &slab_caches, list)
10051 if (s->flags & SLAB_STORE_USER)
10052 debugfs_slab_add(s);
10053
10054 return 0;
10055
10056 }
10057 __initcall(slab_debugfs_init);
10058 #endif
10059 /*
10060 * The /proc/slabinfo ABI
10061 */
10062 #ifdef CONFIG_SLUB_DEBUG
get_slabinfo(struct kmem_cache * s,struct slabinfo * sinfo)10063 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
10064 {
10065 unsigned long nr_slabs = 0;
10066 unsigned long nr_objs = 0;
10067 unsigned long nr_free = 0;
10068 int node;
10069 struct kmem_cache_node *n;
10070
10071 for_each_kmem_cache_node(s, node, n) {
10072 nr_slabs += node_nr_slabs(n);
10073 nr_objs += node_nr_objs(n);
10074 nr_free += count_partial_free_approx(n);
10075 }
10076
10077 sinfo->active_objs = nr_objs - nr_free;
10078 sinfo->num_objs = nr_objs;
10079 sinfo->active_slabs = nr_slabs;
10080 sinfo->num_slabs = nr_slabs;
10081 sinfo->objects_per_slab = oo_objects(s->oo);
10082 sinfo->cache_order = oo_order(s->oo);
10083 }
10084 #endif /* CONFIG_SLUB_DEBUG */
10085