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