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