1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * SLUB: A slab allocator that limits cache line use instead of queuing
4 * objects in per cpu and per node lists.
5 *
6 * The allocator synchronizes using per slab locks or atomic operations
7 * and only uses a centralized lock to manage a pool of partial slabs.
8 *
9 * (C) 2007 SGI, Christoph Lameter
10 * (C) 2011 Linux Foundation, Christoph Lameter
11 */
12
13 #include <linux/mm.h>
14 #include <linux/swap.h> /* mm_account_reclaimed_pages() */
15 #include <linux/module.h>
16 #include <linux/bit_spinlock.h>
17 #include <linux/interrupt.h>
18 #include <linux/swab.h>
19 #include <linux/bitops.h>
20 #include <linux/slab.h>
21 #include "slab.h"
22 #include <linux/proc_fs.h>
23 #include <linux/seq_file.h>
24 #include <linux/kasan.h>
25 #include <linux/kmsan.h>
26 #include <linux/cpu.h>
27 #include <linux/cpuset.h>
28 #include <linux/mempolicy.h>
29 #include <linux/ctype.h>
30 #include <linux/debugobjects.h>
31 #include <linux/kallsyms.h>
32 #include <linux/kfence.h>
33 #include <linux/memory.h>
34 #include <linux/math64.h>
35 #include <linux/fault-inject.h>
36 #include <linux/kmemleak.h>
37 #include <linux/stacktrace.h>
38 #include <linux/prefetch.h>
39 #include <linux/memcontrol.h>
40 #include <linux/random.h>
41 #include <kunit/test.h>
42 #include <kunit/test-bug.h>
43 #include <linux/sort.h>
44
45 #include <linux/debugfs.h>
46 #include <trace/events/kmem.h>
47 #include <trace/hooks/mm.h>
48
49 #include "internal.h"
50
51 /*
52 * Lock order:
53 * 1. slab_mutex (Global Mutex)
54 * 2. node->list_lock (Spinlock)
55 * 3. kmem_cache->cpu_slab->lock (Local lock)
56 * 4. slab_lock(slab) (Only on some arches)
57 * 5. object_map_lock (Only for debugging)
58 *
59 * slab_mutex
60 *
61 * The role of the slab_mutex is to protect the list of all the slabs
62 * and to synchronize major metadata changes to slab cache structures.
63 * Also synchronizes memory hotplug callbacks.
64 *
65 * slab_lock
66 *
67 * The slab_lock is a wrapper around the page lock, thus it is a bit
68 * spinlock.
69 *
70 * The slab_lock is only used on arches that do not have the ability
71 * to do a cmpxchg_double. It only protects:
72 *
73 * A. slab->freelist -> List of free objects in a slab
74 * B. slab->inuse -> Number of objects in use
75 * C. slab->objects -> Number of objects in slab
76 * D. slab->frozen -> frozen state
77 *
78 * Frozen slabs
79 *
80 * If a slab is frozen then it is exempt from list management. It is
81 * the cpu slab which is actively allocated from by the processor that
82 * froze it and it is not on any list. The processor that froze the
83 * slab is the one who can perform list operations on the slab. Other
84 * processors may put objects onto the freelist but the processor that
85 * froze the slab is the only one that can retrieve the objects from the
86 * slab's freelist.
87 *
88 * CPU partial slabs
89 *
90 * The partially empty slabs cached on the CPU partial list are used
91 * for performance reasons, which speeds up the allocation process.
92 * These slabs are not frozen, but are also exempt from list management,
93 * by clearing the PG_workingset flag when moving out of the node
94 * partial list. Please see __slab_free() for more details.
95 *
96 * To sum up, the current scheme is:
97 * - node partial slab: PG_Workingset && !frozen
98 * - cpu partial slab: !PG_Workingset && !frozen
99 * - cpu slab: !PG_Workingset && frozen
100 * - full slab: !PG_Workingset && !frozen
101 *
102 * list_lock
103 *
104 * The list_lock protects the partial and full list on each node and
105 * the partial slab counter. If taken then no new slabs may be added or
106 * removed from the lists nor make the number of partial slabs be modified.
107 * (Note that the total number of slabs is an atomic value that may be
108 * modified without taking the list lock).
109 *
110 * The list_lock is a centralized lock and thus we avoid taking it as
111 * much as possible. As long as SLUB does not have to handle partial
112 * slabs, operations can continue without any centralized lock. F.e.
113 * allocating a long series of objects that fill up slabs does not require
114 * the list lock.
115 *
116 * For debug caches, all allocations are forced to go through a list_lock
117 * protected region to serialize against concurrent validation.
118 *
119 * cpu_slab->lock local lock
120 *
121 * This locks protect slowpath manipulation of all kmem_cache_cpu fields
122 * except the stat counters. This is a percpu structure manipulated only by
123 * the local cpu, so the lock protects against being preempted or interrupted
124 * by an irq. Fast path operations rely on lockless operations instead.
125 *
126 * On PREEMPT_RT, the local lock neither disables interrupts nor preemption
127 * which means the lockless fastpath cannot be used as it might interfere with
128 * an in-progress slow path operations. In this case the local lock is always
129 * taken but it still utilizes the freelist for the common operations.
130 *
131 * lockless fastpaths
132 *
133 * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free())
134 * are fully lockless when satisfied from the percpu slab (and when
135 * cmpxchg_double is possible to use, otherwise slab_lock is taken).
136 * They also don't disable preemption or migration or irqs. They rely on
137 * the transaction id (tid) field to detect being preempted or moved to
138 * another cpu.
139 *
140 * irq, preemption, migration considerations
141 *
142 * Interrupts are disabled as part of list_lock or local_lock operations, or
143 * around the slab_lock operation, in order to make the slab allocator safe
144 * to use in the context of an irq.
145 *
146 * In addition, preemption (or migration on PREEMPT_RT) is disabled in the
147 * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the
148 * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer
149 * doesn't have to be revalidated in each section protected by the local lock.
150 *
151 * SLUB assigns one slab for allocation to each processor.
152 * Allocations only occur from these slabs called cpu slabs.
153 *
154 * Slabs with free elements are kept on a partial list and during regular
155 * operations no list for full slabs is used. If an object in a full slab is
156 * freed then the slab will show up again on the partial lists.
157 * We track full slabs for debugging purposes though because otherwise we
158 * cannot scan all objects.
159 *
160 * Slabs are freed when they become empty. Teardown and setup is
161 * minimal so we rely on the page allocators per cpu caches for
162 * fast frees and allocs.
163 *
164 * slab->frozen The slab is frozen and exempt from list processing.
165 * This means that the slab is dedicated to a purpose
166 * such as satisfying allocations for a specific
167 * processor. Objects may be freed in the slab while
168 * it is frozen but slab_free will then skip the usual
169 * list operations. It is up to the processor holding
170 * the slab to integrate the slab into the slab lists
171 * when the slab is no longer needed.
172 *
173 * One use of this flag is to mark slabs that are
174 * used for allocations. Then such a slab becomes a cpu
175 * slab. The cpu slab may be equipped with an additional
176 * freelist that allows lockless access to
177 * free objects in addition to the regular freelist
178 * that requires the slab lock.
179 *
180 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug
181 * options set. This moves slab handling out of
182 * the fast path and disables lockless freelists.
183 */
184
185 /*
186 * We could simply use migrate_disable()/enable() but as long as it's a
187 * function call even on !PREEMPT_RT, use inline preempt_disable() there.
188 */
189 #ifndef CONFIG_PREEMPT_RT
190 #define slub_get_cpu_ptr(var) get_cpu_ptr(var)
191 #define slub_put_cpu_ptr(var) put_cpu_ptr(var)
192 #define USE_LOCKLESS_FAST_PATH() (true)
193 #else
194 #define slub_get_cpu_ptr(var) \
195 ({ \
196 migrate_disable(); \
197 this_cpu_ptr(var); \
198 })
199 #define slub_put_cpu_ptr(var) \
200 do { \
201 (void)(var); \
202 migrate_enable(); \
203 } while (0)
204 #define USE_LOCKLESS_FAST_PATH() (false)
205 #endif
206
207 #ifndef CONFIG_SLUB_TINY
208 #define __fastpath_inline __always_inline
209 #else
210 #define __fastpath_inline
211 #endif
212
213 #ifdef CONFIG_SLUB_DEBUG
214 #ifdef CONFIG_SLUB_DEBUG_ON
215 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled);
216 #else
217 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled);
218 #endif
219 #endif /* CONFIG_SLUB_DEBUG */
220
221 /* Structure holding parameters for get_partial() call chain */
222 struct partial_context {
223 gfp_t flags;
224 unsigned int orig_size;
225 void *object;
226 };
227
kmem_cache_debug(struct kmem_cache * s)228 static inline bool kmem_cache_debug(struct kmem_cache *s)
229 {
230 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS);
231 }
232
slub_debug_orig_size(struct kmem_cache * s)233 static inline bool slub_debug_orig_size(struct kmem_cache *s)
234 {
235 return (kmem_cache_debug_flags(s, SLAB_STORE_USER) &&
236 (s->flags & SLAB_KMALLOC));
237 }
238
fixup_red_left(struct kmem_cache * s,void * p)239 void *fixup_red_left(struct kmem_cache *s, void *p)
240 {
241 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE))
242 p += s->red_left_pad;
243
244 return p;
245 }
246
kmem_cache_has_cpu_partial(struct kmem_cache * s)247 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s)
248 {
249 #ifdef CONFIG_SLUB_CPU_PARTIAL
250 return !kmem_cache_debug(s);
251 #else
252 return false;
253 #endif
254 }
255
256 /*
257 * Issues still to be resolved:
258 *
259 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
260 *
261 * - Variable sizing of the per node arrays
262 */
263
264 /* Enable to log cmpxchg failures */
265 #undef SLUB_DEBUG_CMPXCHG
266
267 #ifndef CONFIG_SLUB_TINY
268 /*
269 * Minimum number of partial slabs. These will be left on the partial
270 * lists even if they are empty. kmem_cache_shrink may reclaim them.
271 */
272 #define MIN_PARTIAL 5
273
274 /*
275 * Maximum number of desirable partial slabs.
276 * The existence of more partial slabs makes kmem_cache_shrink
277 * sort the partial list by the number of objects in use.
278 */
279 #define MAX_PARTIAL 10
280 #else
281 #define MIN_PARTIAL 0
282 #define MAX_PARTIAL 0
283 #endif
284
285 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \
286 SLAB_POISON | SLAB_STORE_USER)
287
288 /*
289 * These debug flags cannot use CMPXCHG because there might be consistency
290 * issues when checking or reading debug information
291 */
292 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
293 SLAB_TRACE)
294
295
296 /*
297 * Debugging flags that require metadata to be stored in the slab. These get
298 * disabled when slab_debug=O is used and a cache's min order increases with
299 * metadata.
300 */
301 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
302
303 #define OO_SHIFT 16
304 #define OO_MASK ((1 << OO_SHIFT) - 1)
305 #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
306
307 /* Internal SLUB flags */
308 /* Poison object */
309 #define __OBJECT_POISON __SLAB_FLAG_BIT(_SLAB_OBJECT_POISON)
310 /* Use cmpxchg_double */
311
312 #ifdef system_has_freelist_aba
313 #define __CMPXCHG_DOUBLE __SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE)
314 #else
315 #define __CMPXCHG_DOUBLE __SLAB_FLAG_UNUSED
316 #endif
317
318 #ifdef SLAB_SUPPORTS_SYSFS
319 static int sysfs_slab_add(struct kmem_cache *);
320 static int sysfs_slab_alias(struct kmem_cache *, const char *);
321 #else
sysfs_slab_add(struct kmem_cache * s)322 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
sysfs_slab_alias(struct kmem_cache * s,const char * p)323 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
324 { 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 stat_item {
334 ALLOC_FASTPATH, /* Allocation from cpu slab */
335 ALLOC_SLOWPATH, /* Allocation by getting a new cpu slab */
336 FREE_FASTPATH, /* Free to cpu slab */
337 FREE_SLOWPATH, /* Freeing not to cpu slab */
338 FREE_FROZEN, /* Freeing to frozen slab */
339 FREE_ADD_PARTIAL, /* Freeing moves slab to partial list */
340 FREE_REMOVE_PARTIAL, /* Freeing removes last object */
341 ALLOC_FROM_PARTIAL, /* Cpu slab acquired from node partial list */
342 ALLOC_SLAB, /* Cpu slab acquired from page allocator */
343 ALLOC_REFILL, /* Refill cpu slab from slab freelist */
344 ALLOC_NODE_MISMATCH, /* Switching cpu slab */
345 FREE_SLAB, /* Slab freed to the page allocator */
346 CPUSLAB_FLUSH, /* Abandoning of the cpu slab */
347 DEACTIVATE_FULL, /* Cpu slab was full when deactivated */
348 DEACTIVATE_EMPTY, /* Cpu slab was empty when deactivated */
349 DEACTIVATE_TO_HEAD, /* Cpu slab was moved to the head of partials */
350 DEACTIVATE_TO_TAIL, /* Cpu slab was moved to the tail of partials */
351 DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */
352 DEACTIVATE_BYPASS, /* Implicit deactivation */
353 ORDER_FALLBACK, /* Number of times fallback was necessary */
354 CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */
355 CMPXCHG_DOUBLE_FAIL, /* Failures of slab freelist update */
356 CPU_PARTIAL_ALLOC, /* Used cpu partial on alloc */
357 CPU_PARTIAL_FREE, /* Refill cpu partial on free */
358 CPU_PARTIAL_NODE, /* Refill cpu partial from node partial */
359 CPU_PARTIAL_DRAIN, /* Drain cpu partial to node partial */
360 NR_SLUB_STAT_ITEMS
361 };
362
363 #ifndef CONFIG_SLUB_TINY
364 /*
365 * When changing the layout, make sure freelist and tid are still compatible
366 * with this_cpu_cmpxchg_double() alignment requirements.
367 */
368 struct kmem_cache_cpu {
369 union {
370 struct {
371 void **freelist; /* Pointer to next available object */
372 unsigned long tid; /* Globally unique transaction id */
373 };
374 freelist_aba_t freelist_tid;
375 };
376 struct slab *slab; /* The slab from which we are allocating */
377 #ifdef CONFIG_SLUB_CPU_PARTIAL
378 struct slab *partial; /* Partially allocated slabs */
379 #endif
380 local_lock_t lock; /* Protects the fields above */
381 #ifdef CONFIG_SLUB_STATS
382 unsigned int stat[NR_SLUB_STAT_ITEMS];
383 #endif
384 };
385 #endif /* CONFIG_SLUB_TINY */
386
stat(const struct kmem_cache * s,enum stat_item si)387 static inline void stat(const struct kmem_cache *s, enum stat_item si)
388 {
389 #ifdef CONFIG_SLUB_STATS
390 /*
391 * The rmw is racy on a preemptible kernel but this is acceptable, so
392 * avoid this_cpu_add()'s irq-disable overhead.
393 */
394 raw_cpu_inc(s->cpu_slab->stat[si]);
395 #endif
396 }
397
398 static inline
stat_add(const struct kmem_cache * s,enum stat_item si,int v)399 void stat_add(const struct kmem_cache *s, enum stat_item si, int v)
400 {
401 #ifdef CONFIG_SLUB_STATS
402 raw_cpu_add(s->cpu_slab->stat[si], v);
403 #endif
404 }
405
406 /*
407 * The slab lists for all objects.
408 */
409 struct kmem_cache_node {
410 spinlock_t list_lock;
411 unsigned long nr_partial;
412 struct list_head partial;
413 #ifdef CONFIG_SLUB_DEBUG
414 atomic_long_t nr_slabs;
415 atomic_long_t total_objects;
416 struct list_head full;
417 #endif
418 };
419
get_node(struct kmem_cache * s,int node)420 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
421 {
422 return s->node[node];
423 }
424
425 /*
426 * Iterator over all nodes. The body will be executed for each node that has
427 * a kmem_cache_node structure allocated (which is true for all online nodes)
428 */
429 #define for_each_kmem_cache_node(__s, __node, __n) \
430 for (__node = 0; __node < nr_node_ids; __node++) \
431 if ((__n = get_node(__s, __node)))
432
433 /*
434 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated.
435 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily
436 * differ during memory hotplug/hotremove operations.
437 * Protected by slab_mutex.
438 */
439 static nodemask_t slab_nodes;
440
441 #ifndef CONFIG_SLUB_TINY
442 /*
443 * Workqueue used for flush_cpu_slab().
444 */
445 static struct workqueue_struct *flushwq;
446 #endif
447
448 /********************************************************************
449 * Core slab cache functions
450 *******************************************************************/
451
452 /*
453 * Returns freelist pointer (ptr). With hardening, this is obfuscated
454 * with an XOR of the address where the pointer is held and a per-cache
455 * random number.
456 */
freelist_ptr_encode(const struct kmem_cache * s,void * ptr,unsigned long ptr_addr)457 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s,
458 void *ptr, unsigned long ptr_addr)
459 {
460 unsigned long encoded;
461
462 #ifdef CONFIG_SLAB_FREELIST_HARDENED
463 encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr);
464 #else
465 encoded = (unsigned long)ptr;
466 #endif
467 return (freeptr_t){.v = encoded};
468 }
469
freelist_ptr_decode(const struct kmem_cache * s,freeptr_t ptr,unsigned long ptr_addr)470 static inline void *freelist_ptr_decode(const struct kmem_cache *s,
471 freeptr_t ptr, unsigned long ptr_addr)
472 {
473 void *decoded;
474
475 #ifdef CONFIG_SLAB_FREELIST_HARDENED
476 decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr));
477 #else
478 decoded = (void *)ptr.v;
479 #endif
480 return decoded;
481 }
482
get_freepointer(struct kmem_cache * s,void * object)483 static inline void *get_freepointer(struct kmem_cache *s, void *object)
484 {
485 unsigned long ptr_addr;
486 freeptr_t p;
487
488 object = kasan_reset_tag(object);
489 ptr_addr = (unsigned long)object + s->offset;
490 p = *(freeptr_t *)(ptr_addr);
491 return freelist_ptr_decode(s, p, ptr_addr);
492 }
493
494 #ifndef CONFIG_SLUB_TINY
prefetch_freepointer(const struct kmem_cache * s,void * object)495 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
496 {
497 prefetchw(object + s->offset);
498 }
499 #endif
500
501 /*
502 * When running under KMSAN, get_freepointer_safe() may return an uninitialized
503 * pointer value in the case the current thread loses the race for the next
504 * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in
505 * slab_alloc_node() will fail, so the uninitialized value won't be used, but
506 * KMSAN will still check all arguments of cmpxchg because of imperfect
507 * handling of inline assembly.
508 * To work around this problem, we apply __no_kmsan_checks to ensure that
509 * get_freepointer_safe() returns initialized memory.
510 */
511 __no_kmsan_checks
get_freepointer_safe(struct kmem_cache * s,void * object)512 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
513 {
514 unsigned long freepointer_addr;
515 freeptr_t p;
516
517 if (!debug_pagealloc_enabled_static())
518 return get_freepointer(s, object);
519
520 object = kasan_reset_tag(object);
521 freepointer_addr = (unsigned long)object + s->offset;
522 copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p));
523 return freelist_ptr_decode(s, p, freepointer_addr);
524 }
525
set_freepointer(struct kmem_cache * s,void * object,void * fp)526 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
527 {
528 unsigned long freeptr_addr = (unsigned long)object + s->offset;
529
530 #ifdef CONFIG_SLAB_FREELIST_HARDENED
531 BUG_ON(object == fp); /* naive detection of double free or corruption */
532 #endif
533
534 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr);
535 *(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr);
536 }
537
538 /*
539 * See comment in calculate_sizes().
540 */
freeptr_outside_object(struct kmem_cache * s)541 static inline bool freeptr_outside_object(struct kmem_cache *s)
542 {
543 return s->offset >= s->inuse;
544 }
545
546 /*
547 * Return offset of the end of info block which is inuse + free pointer if
548 * not overlapping with object.
549 */
get_info_end(struct kmem_cache * s)550 static inline unsigned int get_info_end(struct kmem_cache *s)
551 {
552 if (freeptr_outside_object(s))
553 return s->inuse + sizeof(void *);
554 else
555 return s->inuse;
556 }
557
558 /* Loop over all objects in a slab */
559 #define for_each_object(__p, __s, __addr, __objects) \
560 for (__p = fixup_red_left(__s, __addr); \
561 __p < (__addr) + (__objects) * (__s)->size; \
562 __p += (__s)->size)
563
order_objects(unsigned int order,unsigned int size)564 static inline unsigned int order_objects(unsigned int order, unsigned int size)
565 {
566 return ((unsigned int)PAGE_SIZE << order) / size;
567 }
568
oo_make(unsigned int order,unsigned int size)569 static inline struct kmem_cache_order_objects oo_make(unsigned int order,
570 unsigned int size)
571 {
572 struct kmem_cache_order_objects x = {
573 (order << OO_SHIFT) + order_objects(order, size)
574 };
575
576 return x;
577 }
578
oo_order(struct kmem_cache_order_objects x)579 static inline unsigned int oo_order(struct kmem_cache_order_objects x)
580 {
581 return x.x >> OO_SHIFT;
582 }
583
oo_objects(struct kmem_cache_order_objects x)584 static inline unsigned int oo_objects(struct kmem_cache_order_objects x)
585 {
586 return x.x & OO_MASK;
587 }
588
589 #ifdef CONFIG_SLUB_CPU_PARTIAL
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)590 static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
591 {
592 unsigned int nr_slabs;
593
594 s->cpu_partial = nr_objects;
595
596 /*
597 * We take the number of objects but actually limit the number of
598 * slabs on the per cpu partial list, in order to limit excessive
599 * growth of the list. For simplicity we assume that the slabs will
600 * be half-full.
601 */
602 nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
603 s->cpu_partial_slabs = nr_slabs;
604 }
605
slub_get_cpu_partial(struct kmem_cache * s)606 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
607 {
608 return s->cpu_partial_slabs;
609 }
610 #else
611 static inline void
slub_set_cpu_partial(struct kmem_cache * s,unsigned int nr_objects)612 slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects)
613 {
614 }
615
slub_get_cpu_partial(struct kmem_cache * s)616 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s)
617 {
618 return 0;
619 }
620 #endif /* CONFIG_SLUB_CPU_PARTIAL */
621
622 /*
623 * Per slab locking using the pagelock
624 */
slab_lock(struct slab * slab)625 static __always_inline void slab_lock(struct slab *slab)
626 {
627 bit_spin_lock(PG_locked, &slab->__page_flags);
628 }
629
slab_unlock(struct slab * slab)630 static __always_inline void slab_unlock(struct slab *slab)
631 {
632 bit_spin_unlock(PG_locked, &slab->__page_flags);
633 }
634
635 static inline bool
__update_freelist_fast(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)636 __update_freelist_fast(struct slab *slab,
637 void *freelist_old, unsigned long counters_old,
638 void *freelist_new, unsigned long counters_new)
639 {
640 #ifdef system_has_freelist_aba
641 freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old };
642 freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new };
643
644 return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full);
645 #else
646 return false;
647 #endif
648 }
649
650 static inline bool
__update_freelist_slow(struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new)651 __update_freelist_slow(struct slab *slab,
652 void *freelist_old, unsigned long counters_old,
653 void *freelist_new, unsigned long counters_new)
654 {
655 bool ret = false;
656
657 slab_lock(slab);
658 if (slab->freelist == freelist_old &&
659 slab->counters == counters_old) {
660 slab->freelist = freelist_new;
661 slab->counters = counters_new;
662 ret = true;
663 }
664 slab_unlock(slab);
665
666 return ret;
667 }
668
669 /*
670 * Interrupts must be disabled (for the fallback code to work right), typically
671 * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is
672 * part of bit_spin_lock(), is sufficient because the policy is not to allow any
673 * allocation/ free operation in hardirq context. Therefore nothing can
674 * interrupt the operation.
675 */
__slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)676 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab,
677 void *freelist_old, unsigned long counters_old,
678 void *freelist_new, unsigned long counters_new,
679 const char *n)
680 {
681 bool ret;
682
683 if (USE_LOCKLESS_FAST_PATH())
684 lockdep_assert_irqs_disabled();
685
686 if (s->flags & __CMPXCHG_DOUBLE) {
687 ret = __update_freelist_fast(slab, freelist_old, counters_old,
688 freelist_new, counters_new);
689 } else {
690 ret = __update_freelist_slow(slab, freelist_old, counters_old,
691 freelist_new, counters_new);
692 }
693 if (likely(ret))
694 return true;
695
696 cpu_relax();
697 stat(s, CMPXCHG_DOUBLE_FAIL);
698
699 #ifdef SLUB_DEBUG_CMPXCHG
700 pr_info("%s %s: cmpxchg double redo ", n, s->name);
701 #endif
702
703 return false;
704 }
705
slab_update_freelist(struct kmem_cache * s,struct slab * slab,void * freelist_old,unsigned long counters_old,void * freelist_new,unsigned long counters_new,const char * n)706 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab,
707 void *freelist_old, unsigned long counters_old,
708 void *freelist_new, unsigned long counters_new,
709 const char *n)
710 {
711 bool ret;
712
713 if (s->flags & __CMPXCHG_DOUBLE) {
714 ret = __update_freelist_fast(slab, freelist_old, counters_old,
715 freelist_new, counters_new);
716 } else {
717 unsigned long flags;
718
719 local_irq_save(flags);
720 ret = __update_freelist_slow(slab, freelist_old, counters_old,
721 freelist_new, counters_new);
722 local_irq_restore(flags);
723 }
724 if (likely(ret))
725 return true;
726
727 cpu_relax();
728 stat(s, CMPXCHG_DOUBLE_FAIL);
729
730 #ifdef SLUB_DEBUG_CMPXCHG
731 pr_info("%s %s: cmpxchg double redo ", n, s->name);
732 #endif
733
734 return false;
735 }
736
737 /*
738 * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API
739 * family will round up the real request size to these fixed ones, so
740 * there could be an extra area than what is requested. Save the original
741 * request size in the meta data area, for better debug and sanity check.
742 */
set_orig_size(struct kmem_cache * s,void * object,unsigned int orig_size)743 static inline void set_orig_size(struct kmem_cache *s,
744 void *object, unsigned int orig_size)
745 {
746 void *p = kasan_reset_tag(object);
747 unsigned int kasan_meta_size;
748
749 if (!slub_debug_orig_size(s))
750 return;
751
752 /*
753 * KASAN can save its free meta data inside of the object at offset 0.
754 * If this meta data size is larger than 'orig_size', it will overlap
755 * the data redzone in [orig_size+1, object_size]. Thus, we adjust
756 * 'orig_size' to be as at least as big as KASAN's meta data.
757 */
758 kasan_meta_size = kasan_metadata_size(s, true);
759 if (kasan_meta_size > orig_size)
760 orig_size = kasan_meta_size;
761
762 p += get_info_end(s);
763 p += sizeof(struct track) * 2;
764
765 *(unsigned int *)p = orig_size;
766 }
767
get_orig_size(struct kmem_cache * s,void * object)768 static inline unsigned int get_orig_size(struct kmem_cache *s, void *object)
769 {
770 void *p = kasan_reset_tag(object);
771
772 if (!slub_debug_orig_size(s))
773 return s->object_size;
774
775 p += get_info_end(s);
776 p += sizeof(struct track) * 2;
777
778 return *(unsigned int *)p;
779 }
780
781 #ifdef CONFIG_SLUB_DEBUG
782 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)];
783 static DEFINE_SPINLOCK(object_map_lock);
784
__fill_map(unsigned long * obj_map,struct kmem_cache * s,struct slab * slab)785 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s,
786 struct slab *slab)
787 {
788 void *addr = slab_address(slab);
789 void *p;
790
791 bitmap_zero(obj_map, slab->objects);
792
793 for (p = slab->freelist; p; p = get_freepointer(s, p))
794 set_bit(__obj_to_index(s, addr, p), obj_map);
795 }
796
797 #if IS_ENABLED(CONFIG_KUNIT)
slab_add_kunit_errors(void)798 static bool slab_add_kunit_errors(void)
799 {
800 struct kunit_resource *resource;
801
802 if (!kunit_get_current_test())
803 return false;
804
805 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
806 if (!resource)
807 return false;
808
809 (*(int *)resource->data)++;
810 kunit_put_resource(resource);
811 return true;
812 }
813
slab_in_kunit_test(void)814 bool slab_in_kunit_test(void)
815 {
816 struct kunit_resource *resource;
817
818 if (!kunit_get_current_test())
819 return false;
820
821 resource = kunit_find_named_resource(current->kunit_test, "slab_errors");
822 if (!resource)
823 return false;
824
825 kunit_put_resource(resource);
826 return true;
827 }
828 #else
slab_add_kunit_errors(void)829 static inline bool slab_add_kunit_errors(void) { return false; }
830 #endif
831
size_from_object(struct kmem_cache * s)832 static inline unsigned int size_from_object(struct kmem_cache *s)
833 {
834 if (s->flags & SLAB_RED_ZONE)
835 return s->size - s->red_left_pad;
836
837 return s->size;
838 }
839
restore_red_left(struct kmem_cache * s,void * p)840 static inline void *restore_red_left(struct kmem_cache *s, void *p)
841 {
842 if (s->flags & SLAB_RED_ZONE)
843 p -= s->red_left_pad;
844
845 return p;
846 }
847
848 /*
849 * Debug settings:
850 */
851 #if defined(CONFIG_SLUB_DEBUG_ON)
852 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS;
853 #else
854 static slab_flags_t slub_debug;
855 #endif
856
857 static char *slub_debug_string;
858 static int disable_higher_order_debug;
859
860 /*
861 * slub is about to manipulate internal object metadata. This memory lies
862 * outside the range of the allocated object, so accessing it would normally
863 * be reported by kasan as a bounds error. metadata_access_enable() is used
864 * to tell kasan that these accesses are OK.
865 */
metadata_access_enable(void)866 static inline void metadata_access_enable(void)
867 {
868 kasan_disable_current();
869 kmsan_disable_current();
870 }
871
metadata_access_disable(void)872 static inline void metadata_access_disable(void)
873 {
874 kmsan_enable_current();
875 kasan_enable_current();
876 }
877
878 /*
879 * Object debugging
880 */
881
882 /* 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)883 static inline int check_valid_pointer(struct kmem_cache *s,
884 struct slab *slab, void *object)
885 {
886 void *base;
887
888 if (!object)
889 return 1;
890
891 base = slab_address(slab);
892 object = kasan_reset_tag(object);
893 object = restore_red_left(s, object);
894 if (object < base || object >= base + slab->objects * s->size ||
895 (object - base) % s->size) {
896 return 0;
897 }
898
899 return 1;
900 }
901
print_section(char * level,char * text,u8 * addr,unsigned int length)902 static void print_section(char *level, char *text, u8 *addr,
903 unsigned int length)
904 {
905 metadata_access_enable();
906 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS,
907 16, 1, kasan_reset_tag((void *)addr), length, 1);
908 metadata_access_disable();
909 }
910
get_track(struct kmem_cache * s,void * object,enum track_item alloc)911 struct track *get_track(struct kmem_cache *s, void *object,
912 enum track_item alloc)
913 {
914 struct track *p;
915
916 p = object + get_info_end(s);
917
918 return kasan_reset_tag(p + alloc);
919 }
920 EXPORT_SYMBOL(get_track);
921
922 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n);
923
get_each_kmemcache_object(struct kmem_cache * s,int (* fn)(struct kmem_cache *,void *,void *),void * private)924 unsigned long get_each_kmemcache_object(struct kmem_cache *s,
925 int (*fn)(struct kmem_cache *, void *, void *),
926 void *private)
927 {
928 int node;
929 unsigned long ret = 0;
930 struct kmem_cache_node *n;
931
932 for_each_kmem_cache_node(s, node, n) {
933 unsigned long flags;
934 struct slab *slab;
935 void *p;
936
937 if (!node_nr_slabs(n))
938 continue;
939
940 spin_lock_irqsave(&n->list_lock, flags);
941 list_for_each_entry(slab, &n->partial, slab_list) {
942 for_each_object(p, s, slab_address(slab), slab->objects) {
943 metadata_access_enable();
944 ret = fn(s, p, private);
945 metadata_access_disable();
946 if (ret) {
947 spin_unlock_irqrestore(&n->list_lock, flags);
948 return ret;
949 }
950 }
951 }
952 #ifdef CONFIG_SLUB_DEBUG
953 list_for_each_entry(slab, &n->full, slab_list) {
954 for_each_object(p, s, slab_address(slab), slab->objects) {
955 metadata_access_enable();
956 ret = fn(s, p, private);
957 metadata_access_disable();
958 if (ret) {
959 spin_unlock_irqrestore(&n->list_lock, flags);
960 return ret;
961 }
962 }
963 }
964 #endif
965 spin_unlock_irqrestore(&n->list_lock, flags);
966 }
967 return ret;
968 }
969 EXPORT_SYMBOL_NS_GPL(get_each_kmemcache_object, MINIDUMP);
970
971 #ifdef CONFIG_STACKDEPOT
set_track_prepare(gfp_t gfp_flags)972 static noinline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
973 {
974 depot_stack_handle_t handle;
975 unsigned long entries[TRACK_ADDRS_COUNT];
976 unsigned int nr_entries;
977
978 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3);
979 handle = stack_depot_save(entries, nr_entries, gfp_flags);
980
981 return handle;
982 }
983 #else
set_track_prepare(gfp_t gfp_flags)984 static inline depot_stack_handle_t set_track_prepare(gfp_t gfp_flags)
985 {
986 return 0;
987 }
988 #endif
989
set_track_update(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,depot_stack_handle_t handle)990 static void set_track_update(struct kmem_cache *s, void *object,
991 enum track_item alloc, unsigned long addr,
992 depot_stack_handle_t handle)
993 {
994 struct track *p = get_track(s, object, alloc);
995
996 #ifdef CONFIG_STACKDEPOT
997 p->handle = handle;
998 #endif
999 p->addr = addr;
1000 p->cpu = smp_processor_id();
1001 p->pid = current->pid;
1002 p->when = jiffies;
1003 trace_android_vh_save_track_hash(alloc == TRACK_ALLOC, p);
1004 }
1005
set_track(struct kmem_cache * s,void * object,enum track_item alloc,unsigned long addr,gfp_t gfp_flags)1006 static __always_inline void set_track(struct kmem_cache *s, void *object,
1007 enum track_item alloc, unsigned long addr, gfp_t gfp_flags)
1008 {
1009 depot_stack_handle_t handle = set_track_prepare(gfp_flags);
1010
1011 set_track_update(s, object, alloc, addr, handle);
1012 }
1013
init_tracking(struct kmem_cache * s,void * object)1014 static void init_tracking(struct kmem_cache *s, void *object)
1015 {
1016 struct track *p;
1017
1018 if (!(s->flags & SLAB_STORE_USER))
1019 return;
1020
1021 p = get_track(s, object, TRACK_ALLOC);
1022 memset(p, 0, 2*sizeof(struct track));
1023 }
1024
print_track(const char * s,struct track * t,unsigned long pr_time)1025 static void print_track(const char *s, struct track *t, unsigned long pr_time)
1026 {
1027 depot_stack_handle_t handle __maybe_unused;
1028
1029 if (!t->addr)
1030 return;
1031
1032 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n",
1033 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid);
1034 #ifdef CONFIG_STACKDEPOT
1035 handle = READ_ONCE(t->handle);
1036 if (handle)
1037 stack_depot_print(handle);
1038 else
1039 pr_err("object allocation/free stack trace missing\n");
1040 #endif
1041 }
1042
print_tracking(struct kmem_cache * s,void * object)1043 void print_tracking(struct kmem_cache *s, void *object)
1044 {
1045 unsigned long pr_time = jiffies;
1046 if (!(s->flags & SLAB_STORE_USER))
1047 return;
1048
1049 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time);
1050 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time);
1051 }
1052
print_slab_info(const struct slab * slab)1053 static void print_slab_info(const struct slab *slab)
1054 {
1055 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n",
1056 slab, slab->objects, slab->inuse, slab->freelist,
1057 &slab->__page_flags);
1058 }
1059
skip_orig_size_check(struct kmem_cache * s,const void * object)1060 void skip_orig_size_check(struct kmem_cache *s, const void *object)
1061 {
1062 set_orig_size(s, (void *)object, s->object_size);
1063 }
1064
__slab_bug(struct kmem_cache * s,const char * fmt,va_list argsp)1065 static void __slab_bug(struct kmem_cache *s, const char *fmt, va_list argsp)
1066 {
1067 struct va_format vaf;
1068 va_list args;
1069
1070 va_copy(args, argsp);
1071 vaf.fmt = fmt;
1072 vaf.va = &args;
1073 pr_err("=============================================================================\n");
1074 pr_err("BUG %s (%s): %pV\n", s ? s->name : "<unknown>", print_tainted(), &vaf);
1075 pr_err("-----------------------------------------------------------------------------\n\n");
1076 va_end(args);
1077 }
1078
slab_bug(struct kmem_cache * s,const char * fmt,...)1079 static void slab_bug(struct kmem_cache *s, const char *fmt, ...)
1080 {
1081 va_list args;
1082
1083 va_start(args, fmt);
1084 __slab_bug(s, fmt, args);
1085 va_end(args);
1086 }
1087
1088 __printf(2, 3)
slab_fix(struct kmem_cache * s,const char * fmt,...)1089 static void slab_fix(struct kmem_cache *s, const char *fmt, ...)
1090 {
1091 struct va_format vaf;
1092 va_list args;
1093
1094 if (slab_add_kunit_errors())
1095 return;
1096
1097 va_start(args, fmt);
1098 vaf.fmt = fmt;
1099 vaf.va = &args;
1100 pr_err("FIX %s: %pV\n", s->name, &vaf);
1101 va_end(args);
1102 }
1103
print_trailer(struct kmem_cache * s,struct slab * slab,u8 * p)1104 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p)
1105 {
1106 unsigned int off; /* Offset of last byte */
1107 u8 *addr = slab_address(slab);
1108
1109 print_tracking(s, p);
1110
1111 print_slab_info(slab);
1112
1113 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
1114 p, p - addr, get_freepointer(s, p));
1115
1116 if (s->flags & SLAB_RED_ZONE)
1117 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
1118 s->red_left_pad);
1119 else if (p > addr + 16)
1120 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
1121
1122 print_section(KERN_ERR, "Object ", p,
1123 min_t(unsigned int, s->object_size, PAGE_SIZE));
1124 if (s->flags & SLAB_RED_ZONE)
1125 print_section(KERN_ERR, "Redzone ", p + s->object_size,
1126 s->inuse - s->object_size);
1127
1128 off = get_info_end(s);
1129
1130 if (s->flags & SLAB_STORE_USER)
1131 off += 2 * sizeof(struct track);
1132
1133 if (slub_debug_orig_size(s))
1134 off += sizeof(unsigned int);
1135
1136 off += kasan_metadata_size(s, false);
1137
1138 if (off != size_from_object(s))
1139 /* Beginning of the filler is the free pointer */
1140 print_section(KERN_ERR, "Padding ", p + off,
1141 size_from_object(s) - off);
1142 }
1143
object_err(struct kmem_cache * s,struct slab * slab,u8 * object,const char * reason)1144 static void object_err(struct kmem_cache *s, struct slab *slab,
1145 u8 *object, const char *reason)
1146 {
1147 if (slab_add_kunit_errors())
1148 return;
1149
1150 slab_bug(s, reason);
1151 if (!object || !check_valid_pointer(s, slab, object)) {
1152 print_slab_info(slab);
1153 pr_err("Invalid pointer 0x%p\n", object);
1154 } else {
1155 print_trailer(s, slab, object);
1156 }
1157 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1158
1159 WARN_ON(1);
1160 }
1161
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)1162 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1163 void **freelist, void *nextfree)
1164 {
1165 if ((s->flags & SLAB_CONSISTENCY_CHECKS) &&
1166 !check_valid_pointer(s, slab, nextfree) && freelist) {
1167 object_err(s, slab, *freelist, "Freechain corrupt");
1168 *freelist = NULL;
1169 slab_fix(s, "Isolate corrupted freechain");
1170 return true;
1171 }
1172
1173 return false;
1174 }
1175
__slab_err(struct slab * slab)1176 static void __slab_err(struct slab *slab)
1177 {
1178 if (slab_in_kunit_test())
1179 return;
1180
1181 print_slab_info(slab);
1182 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
1183
1184 WARN_ON(1);
1185 }
1186
slab_err(struct kmem_cache * s,struct slab * slab,const char * fmt,...)1187 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab,
1188 const char *fmt, ...)
1189 {
1190 va_list args;
1191
1192 if (slab_add_kunit_errors())
1193 return;
1194
1195 va_start(args, fmt);
1196 __slab_bug(s, fmt, args);
1197 va_end(args);
1198
1199 __slab_err(slab);
1200 }
1201
init_object(struct kmem_cache * s,void * object,u8 val)1202 static void init_object(struct kmem_cache *s, void *object, u8 val)
1203 {
1204 u8 *p = kasan_reset_tag(object);
1205 unsigned int poison_size = s->object_size;
1206
1207 if (s->flags & SLAB_RED_ZONE) {
1208 /*
1209 * Here and below, avoid overwriting the KMSAN shadow. Keeping
1210 * the shadow makes it possible to distinguish uninit-value
1211 * from use-after-free.
1212 */
1213 memset_no_sanitize_memory(p - s->red_left_pad, val,
1214 s->red_left_pad);
1215
1216 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1217 /*
1218 * Redzone the extra allocated space by kmalloc than
1219 * requested, and the poison size will be limited to
1220 * the original request size accordingly.
1221 */
1222 poison_size = get_orig_size(s, object);
1223 }
1224 }
1225
1226 if (s->flags & __OBJECT_POISON) {
1227 memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1);
1228 memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1);
1229 }
1230
1231 if (s->flags & SLAB_RED_ZONE)
1232 memset_no_sanitize_memory(p + poison_size, val,
1233 s->inuse - poison_size);
1234 }
1235
restore_bytes(struct kmem_cache * s,const char * message,u8 data,void * from,void * to)1236 static void restore_bytes(struct kmem_cache *s, const char *message, u8 data,
1237 void *from, void *to)
1238 {
1239 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data);
1240 memset(from, data, to - from);
1241 }
1242
1243 #ifdef CONFIG_KMSAN
1244 #define pad_check_attributes noinline __no_kmsan_checks
1245 #else
1246 #define pad_check_attributes
1247 #endif
1248
1249 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)1250 check_bytes_and_report(struct kmem_cache *s, struct slab *slab,
1251 u8 *object, const char *what, u8 *start, unsigned int value,
1252 unsigned int bytes, bool slab_obj_print)
1253 {
1254 u8 *fault;
1255 u8 *end;
1256 u8 *addr = slab_address(slab);
1257
1258 metadata_access_enable();
1259 fault = memchr_inv(kasan_reset_tag(start), value, bytes);
1260 metadata_access_disable();
1261 if (!fault)
1262 return 1;
1263
1264 end = start + bytes;
1265 while (end > fault && end[-1] == value)
1266 end--;
1267
1268 if (slab_add_kunit_errors())
1269 goto skip_bug_print;
1270
1271 pr_err("[%s overwritten] 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n",
1272 what, fault, end - 1, fault - addr, fault[0], value);
1273
1274 if (slab_obj_print)
1275 object_err(s, slab, object, "Object corrupt");
1276
1277 skip_bug_print:
1278 restore_bytes(s, what, value, fault, end);
1279 return 0;
1280 }
1281
1282 /*
1283 * Object layout:
1284 *
1285 * object address
1286 * Bytes of the object to be managed.
1287 * If the freepointer may overlay the object then the free
1288 * pointer is at the middle of the object.
1289 *
1290 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
1291 * 0xa5 (POISON_END)
1292 *
1293 * object + s->object_size
1294 * Padding to reach word boundary. This is also used for Redzoning.
1295 * Padding is extended by another word if Redzoning is enabled and
1296 * object_size == inuse.
1297 *
1298 * We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with
1299 * 0xcc (SLUB_RED_ACTIVE) for objects in use.
1300 *
1301 * object + s->inuse
1302 * Meta data starts here.
1303 *
1304 * A. Free pointer (if we cannot overwrite object on free)
1305 * B. Tracking data for SLAB_STORE_USER
1306 * C. Original request size for kmalloc object (SLAB_STORE_USER enabled)
1307 * D. Padding to reach required alignment boundary or at minimum
1308 * one word if debugging is on to be able to detect writes
1309 * before the word boundary.
1310 *
1311 * Padding is done using 0x5a (POISON_INUSE)
1312 *
1313 * object + s->size
1314 * Nothing is used beyond s->size.
1315 *
1316 * If slabcaches are merged then the object_size and inuse boundaries are mostly
1317 * ignored. And therefore no slab options that rely on these boundaries
1318 * may be used with merged slabcaches.
1319 */
1320
check_pad_bytes(struct kmem_cache * s,struct slab * slab,u8 * p)1321 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
1322 {
1323 unsigned long off = get_info_end(s); /* The end of info */
1324
1325 if (s->flags & SLAB_STORE_USER) {
1326 /* We also have user information there */
1327 off += 2 * sizeof(struct track);
1328
1329 if (s->flags & SLAB_KMALLOC)
1330 off += sizeof(unsigned int);
1331 }
1332
1333 off += kasan_metadata_size(s, false);
1334
1335 if (size_from_object(s) == off)
1336 return 1;
1337
1338 return check_bytes_and_report(s, slab, p, "Object padding",
1339 p + off, POISON_INUSE, size_from_object(s) - off, true);
1340 }
1341
1342 /* Check the pad bytes at the end of a slab page */
1343 static pad_check_attributes void
slab_pad_check(struct kmem_cache * s,struct slab * slab)1344 slab_pad_check(struct kmem_cache *s, struct slab *slab)
1345 {
1346 u8 *start;
1347 u8 *fault;
1348 u8 *end;
1349 u8 *pad;
1350 int length;
1351 int remainder;
1352
1353 if (!(s->flags & SLAB_POISON))
1354 return;
1355
1356 start = slab_address(slab);
1357 length = slab_size(slab);
1358 end = start + length;
1359 remainder = length % s->size;
1360 if (!remainder)
1361 return;
1362
1363 pad = end - remainder;
1364 metadata_access_enable();
1365 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
1366 metadata_access_disable();
1367 if (!fault)
1368 return;
1369 while (end > fault && end[-1] == POISON_INUSE)
1370 end--;
1371
1372 slab_bug(s, "Padding overwritten. 0x%p-0x%p @offset=%tu",
1373 fault, end - 1, fault - start);
1374 print_section(KERN_ERR, "Padding ", pad, remainder);
1375 __slab_err(slab);
1376
1377 restore_bytes(s, "slab padding", POISON_INUSE, fault, end);
1378 }
1379
check_object(struct kmem_cache * s,struct slab * slab,void * object,u8 val)1380 static int check_object(struct kmem_cache *s, struct slab *slab,
1381 void *object, u8 val)
1382 {
1383 u8 *p = object;
1384 u8 *endobject = object + s->object_size;
1385 unsigned int orig_size, kasan_meta_size;
1386 int ret = 1;
1387
1388 if (s->flags & SLAB_RED_ZONE) {
1389 if (!check_bytes_and_report(s, slab, object, "Left Redzone",
1390 object - s->red_left_pad, val, s->red_left_pad, ret))
1391 ret = 0;
1392
1393 if (!check_bytes_and_report(s, slab, object, "Right Redzone",
1394 endobject, val, s->inuse - s->object_size, ret))
1395 ret = 0;
1396
1397 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
1398 orig_size = get_orig_size(s, object);
1399
1400 if (s->object_size > orig_size &&
1401 !check_bytes_and_report(s, slab, object,
1402 "kmalloc Redzone", p + orig_size,
1403 val, s->object_size - orig_size, ret)) {
1404 ret = 0;
1405 }
1406 }
1407 } else {
1408 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
1409 if (!check_bytes_and_report(s, slab, p, "Alignment padding",
1410 endobject, POISON_INUSE,
1411 s->inuse - s->object_size, ret))
1412 ret = 0;
1413 }
1414 }
1415
1416 if (s->flags & SLAB_POISON) {
1417 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) {
1418 /*
1419 * KASAN can save its free meta data inside of the
1420 * object at offset 0. Thus, skip checking the part of
1421 * the redzone that overlaps with the meta data.
1422 */
1423 kasan_meta_size = kasan_metadata_size(s, true);
1424 if (kasan_meta_size < s->object_size - 1 &&
1425 !check_bytes_and_report(s, slab, p, "Poison",
1426 p + kasan_meta_size, POISON_FREE,
1427 s->object_size - kasan_meta_size - 1, ret))
1428 ret = 0;
1429 if (kasan_meta_size < s->object_size &&
1430 !check_bytes_and_report(s, slab, p, "End Poison",
1431 p + s->object_size - 1, POISON_END, 1, ret))
1432 ret = 0;
1433 }
1434 /*
1435 * check_pad_bytes cleans up on its own.
1436 */
1437 if (!check_pad_bytes(s, slab, p))
1438 ret = 0;
1439 }
1440
1441 /*
1442 * Cannot check freepointer while object is allocated if
1443 * object and freepointer overlap.
1444 */
1445 if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
1446 !check_valid_pointer(s, slab, get_freepointer(s, p))) {
1447 object_err(s, slab, p, "Freepointer corrupt");
1448 /*
1449 * No choice but to zap it and thus lose the remainder
1450 * of the free objects in this slab. May cause
1451 * another error because the object count is now wrong.
1452 */
1453 set_freepointer(s, p, NULL);
1454 ret = 0;
1455 }
1456
1457 return ret;
1458 }
1459
check_slab(struct kmem_cache * s,struct slab * slab)1460 static int check_slab(struct kmem_cache *s, struct slab *slab)
1461 {
1462 int maxobj;
1463
1464 if (!folio_test_slab(slab_folio(slab))) {
1465 slab_err(s, slab, "Not a valid slab page");
1466 return 0;
1467 }
1468
1469 maxobj = order_objects(slab_order(slab), s->size);
1470 if (slab->objects > maxobj) {
1471 slab_err(s, slab, "objects %u > max %u",
1472 slab->objects, maxobj);
1473 return 0;
1474 }
1475 if (slab->inuse > slab->objects) {
1476 slab_err(s, slab, "inuse %u > max %u",
1477 slab->inuse, slab->objects);
1478 return 0;
1479 }
1480 if (slab->frozen) {
1481 slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed");
1482 return 0;
1483 }
1484
1485 /* Slab_pad_check fixes things up after itself */
1486 slab_pad_check(s, slab);
1487 return 1;
1488 }
1489
1490 /*
1491 * Determine if a certain object in a slab is on the freelist. Must hold the
1492 * slab lock to guarantee that the chains are in a consistent state.
1493 */
on_freelist(struct kmem_cache * s,struct slab * slab,void * search)1494 static int on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
1495 {
1496 int nr = 0;
1497 void *fp;
1498 void *object = NULL;
1499 int max_objects;
1500
1501 fp = slab->freelist;
1502 while (fp && nr <= slab->objects) {
1503 if (fp == search)
1504 return 1;
1505 if (!check_valid_pointer(s, slab, fp)) {
1506 if (object) {
1507 object_err(s, slab, object,
1508 "Freechain corrupt");
1509 set_freepointer(s, object, NULL);
1510 } else {
1511 slab_err(s, slab, "Freepointer corrupt");
1512 slab->freelist = NULL;
1513 slab->inuse = slab->objects;
1514 slab_fix(s, "Freelist cleared");
1515 return 0;
1516 }
1517 break;
1518 }
1519 object = fp;
1520 fp = get_freepointer(s, object);
1521 nr++;
1522 }
1523
1524 max_objects = order_objects(slab_order(slab), s->size);
1525 if (max_objects > MAX_OBJS_PER_PAGE)
1526 max_objects = MAX_OBJS_PER_PAGE;
1527
1528 if (slab->objects != max_objects) {
1529 slab_err(s, slab, "Wrong number of objects. Found %d but should be %d",
1530 slab->objects, max_objects);
1531 slab->objects = max_objects;
1532 slab_fix(s, "Number of objects adjusted");
1533 }
1534 if (slab->inuse != slab->objects - nr) {
1535 slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d",
1536 slab->inuse, slab->objects - nr);
1537 slab->inuse = slab->objects - nr;
1538 slab_fix(s, "Object count adjusted");
1539 }
1540 return search == NULL;
1541 }
1542
trace(struct kmem_cache * s,struct slab * slab,void * object,int alloc)1543 static void trace(struct kmem_cache *s, struct slab *slab, void *object,
1544 int alloc)
1545 {
1546 if (s->flags & SLAB_TRACE) {
1547 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
1548 s->name,
1549 alloc ? "alloc" : "free",
1550 object, slab->inuse,
1551 slab->freelist);
1552
1553 if (!alloc)
1554 print_section(KERN_INFO, "Object ", (void *)object,
1555 s->object_size);
1556
1557 dump_stack();
1558 }
1559 }
1560
1561 /*
1562 * Tracking of fully allocated slabs for debugging purposes.
1563 */
add_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1564 static void add_full(struct kmem_cache *s,
1565 struct kmem_cache_node *n, struct slab *slab)
1566 {
1567 if (!(s->flags & SLAB_STORE_USER))
1568 return;
1569
1570 lockdep_assert_held(&n->list_lock);
1571 list_add(&slab->slab_list, &n->full);
1572 }
1573
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1574 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab)
1575 {
1576 if (!(s->flags & SLAB_STORE_USER))
1577 return;
1578
1579 lockdep_assert_held(&n->list_lock);
1580 list_del(&slab->slab_list);
1581 }
1582
node_nr_slabs(struct kmem_cache_node * n)1583 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1584 {
1585 return atomic_long_read(&n->nr_slabs);
1586 }
1587
inc_slabs_node(struct kmem_cache * s,int node,int objects)1588 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1589 {
1590 struct kmem_cache_node *n = get_node(s, node);
1591
1592 atomic_long_inc(&n->nr_slabs);
1593 atomic_long_add(objects, &n->total_objects);
1594 }
dec_slabs_node(struct kmem_cache * s,int node,int objects)1595 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1596 {
1597 struct kmem_cache_node *n = get_node(s, node);
1598
1599 atomic_long_dec(&n->nr_slabs);
1600 atomic_long_sub(objects, &n->total_objects);
1601 }
1602
1603 /* Object debug checks for alloc/free paths */
setup_object_debug(struct kmem_cache * s,void * object)1604 static void setup_object_debug(struct kmem_cache *s, void *object)
1605 {
1606 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON))
1607 return;
1608
1609 init_object(s, object, SLUB_RED_INACTIVE);
1610 init_tracking(s, object);
1611 }
1612
1613 static
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1614 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr)
1615 {
1616 if (!kmem_cache_debug_flags(s, SLAB_POISON))
1617 return;
1618
1619 metadata_access_enable();
1620 memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab));
1621 metadata_access_disable();
1622 }
1623
alloc_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object)1624 static inline int alloc_consistency_checks(struct kmem_cache *s,
1625 struct slab *slab, void *object)
1626 {
1627 if (!check_slab(s, slab))
1628 return 0;
1629
1630 if (!check_valid_pointer(s, slab, object)) {
1631 object_err(s, slab, object, "Freelist Pointer check fails");
1632 return 0;
1633 }
1634
1635 if (!check_object(s, slab, object, SLUB_RED_INACTIVE))
1636 return 0;
1637
1638 return 1;
1639 }
1640
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1641 static noinline bool alloc_debug_processing(struct kmem_cache *s,
1642 struct slab *slab, void *object, int orig_size)
1643 {
1644 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
1645 if (!alloc_consistency_checks(s, slab, object))
1646 goto bad;
1647 }
1648
1649 /* Success. Perform special debug activities for allocs */
1650 trace(s, slab, object, 1);
1651 set_orig_size(s, object, orig_size);
1652 init_object(s, object, SLUB_RED_ACTIVE);
1653 return true;
1654
1655 bad:
1656 if (folio_test_slab(slab_folio(slab))) {
1657 /*
1658 * If this is a slab page then lets do the best we can
1659 * to avoid issues in the future. Marking all objects
1660 * as used avoids touching the remaining objects.
1661 */
1662 slab_fix(s, "Marking all objects used");
1663 slab->inuse = slab->objects;
1664 slab->freelist = NULL;
1665 slab->frozen = 1; /* mark consistency-failed slab as frozen */
1666 }
1667 return false;
1668 }
1669
free_consistency_checks(struct kmem_cache * s,struct slab * slab,void * object,unsigned long addr)1670 static inline int free_consistency_checks(struct kmem_cache *s,
1671 struct slab *slab, void *object, unsigned long addr)
1672 {
1673 if (!check_valid_pointer(s, slab, object)) {
1674 slab_err(s, slab, "Invalid object pointer 0x%p", object);
1675 return 0;
1676 }
1677
1678 if (on_freelist(s, slab, object)) {
1679 object_err(s, slab, object, "Object already free");
1680 return 0;
1681 }
1682
1683 if (!check_object(s, slab, object, SLUB_RED_ACTIVE))
1684 return 0;
1685
1686 if (unlikely(s != slab->slab_cache)) {
1687 if (!folio_test_slab(slab_folio(slab))) {
1688 slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
1689 object);
1690 } else if (!slab->slab_cache) {
1691 slab_err(NULL, slab, "No slab cache for object 0x%p",
1692 object);
1693 } else {
1694 object_err(s, slab, object,
1695 "page slab pointer corrupt.");
1696 }
1697 return 0;
1698 }
1699 return 1;
1700 }
1701
1702 /*
1703 * Parse a block of slab_debug options. Blocks are delimited by ';'
1704 *
1705 * @str: start of block
1706 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified
1707 * @slabs: return start of list of slabs, or NULL when there's no list
1708 * @init: assume this is initial parsing and not per-kmem-create parsing
1709 *
1710 * returns the start of next block if there's any, or NULL
1711 */
1712 static char *
parse_slub_debug_flags(char * str,slab_flags_t * flags,char ** slabs,bool init)1713 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
1714 {
1715 bool higher_order_disable = false;
1716
1717 /* Skip any completely empty blocks */
1718 while (*str && *str == ';')
1719 str++;
1720
1721 if (*str == ',') {
1722 /*
1723 * No options but restriction on slabs. This means full
1724 * debugging for slabs matching a pattern.
1725 */
1726 *flags = DEBUG_DEFAULT_FLAGS;
1727 goto check_slabs;
1728 }
1729 *flags = 0;
1730
1731 /* Determine which debug features should be switched on */
1732 for (; *str && *str != ',' && *str != ';'; str++) {
1733 switch (tolower(*str)) {
1734 case '-':
1735 *flags = 0;
1736 break;
1737 case 'f':
1738 *flags |= SLAB_CONSISTENCY_CHECKS;
1739 break;
1740 case 'z':
1741 *flags |= SLAB_RED_ZONE;
1742 break;
1743 case 'p':
1744 *flags |= SLAB_POISON;
1745 break;
1746 case 'u':
1747 *flags |= SLAB_STORE_USER;
1748 break;
1749 case 't':
1750 *flags |= SLAB_TRACE;
1751 break;
1752 case 'a':
1753 *flags |= SLAB_FAILSLAB;
1754 break;
1755 case 'o':
1756 /*
1757 * Avoid enabling debugging on caches if its minimum
1758 * order would increase as a result.
1759 */
1760 higher_order_disable = true;
1761 break;
1762 default:
1763 if (init)
1764 pr_err("slab_debug option '%c' unknown. skipped\n", *str);
1765 }
1766 }
1767 check_slabs:
1768 if (*str == ',')
1769 *slabs = ++str;
1770 else
1771 *slabs = NULL;
1772
1773 /* Skip over the slab list */
1774 while (*str && *str != ';')
1775 str++;
1776
1777 /* Skip any completely empty blocks */
1778 while (*str && *str == ';')
1779 str++;
1780
1781 if (init && higher_order_disable)
1782 disable_higher_order_debug = 1;
1783
1784 if (*str)
1785 return str;
1786 else
1787 return NULL;
1788 }
1789
setup_slub_debug(char * str)1790 static int __init setup_slub_debug(char *str)
1791 {
1792 slab_flags_t flags;
1793 slab_flags_t global_flags;
1794 char *saved_str;
1795 char *slab_list;
1796 bool global_slub_debug_changed = false;
1797 bool slab_list_specified = false;
1798
1799 global_flags = DEBUG_DEFAULT_FLAGS;
1800 if (*str++ != '=' || !*str)
1801 /*
1802 * No options specified. Switch on full debugging.
1803 */
1804 goto out;
1805
1806 saved_str = str;
1807 while (str) {
1808 str = parse_slub_debug_flags(str, &flags, &slab_list, true);
1809
1810 if (!slab_list) {
1811 global_flags = flags;
1812 global_slub_debug_changed = true;
1813 } else {
1814 slab_list_specified = true;
1815 if (flags & SLAB_STORE_USER)
1816 stack_depot_request_early_init();
1817 }
1818 }
1819
1820 /*
1821 * For backwards compatibility, a single list of flags with list of
1822 * slabs means debugging is only changed for those slabs, so the global
1823 * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending
1824 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as
1825 * long as there is no option specifying flags without a slab list.
1826 */
1827 if (slab_list_specified) {
1828 if (!global_slub_debug_changed)
1829 global_flags = slub_debug;
1830 slub_debug_string = saved_str;
1831 }
1832 out:
1833 slub_debug = global_flags;
1834 if (slub_debug & SLAB_STORE_USER)
1835 stack_depot_request_early_init();
1836 if (slub_debug != 0 || slub_debug_string)
1837 static_branch_enable(&slub_debug_enabled);
1838 else
1839 static_branch_disable(&slub_debug_enabled);
1840 if ((static_branch_unlikely(&init_on_alloc) ||
1841 static_branch_unlikely(&init_on_free)) &&
1842 (slub_debug & SLAB_POISON))
1843 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n");
1844 return 1;
1845 }
1846
1847 __setup("slab_debug", setup_slub_debug);
1848 __setup_param("slub_debug", slub_debug, setup_slub_debug, 0);
1849
1850 /*
1851 * kmem_cache_flags - apply debugging options to the cache
1852 * @flags: flags to set
1853 * @name: name of the cache
1854 *
1855 * Debug option(s) are applied to @flags. In addition to the debug
1856 * option(s), if a slab name (or multiple) is specified i.e.
1857 * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ...
1858 * then only the select slabs will receive the debug option(s).
1859 */
kmem_cache_flags(slab_flags_t flags,const char * name)1860 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1861 {
1862 char *iter;
1863 size_t len;
1864 char *next_block;
1865 slab_flags_t block_flags;
1866 slab_flags_t slub_debug_local = slub_debug;
1867
1868 if (flags & SLAB_NO_USER_FLAGS)
1869 return flags;
1870
1871 /*
1872 * If the slab cache is for debugging (e.g. kmemleak) then
1873 * don't store user (stack trace) information by default,
1874 * but let the user enable it via the command line below.
1875 */
1876 if (flags & SLAB_NOLEAKTRACE)
1877 slub_debug_local &= ~SLAB_STORE_USER;
1878
1879 len = strlen(name);
1880 next_block = slub_debug_string;
1881 /* Go through all blocks of debug options, see if any matches our slab's name */
1882 while (next_block) {
1883 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false);
1884 if (!iter)
1885 continue;
1886 /* Found a block that has a slab list, search it */
1887 while (*iter) {
1888 char *end, *glob;
1889 size_t cmplen;
1890
1891 end = strchrnul(iter, ',');
1892 if (next_block && next_block < end)
1893 end = next_block - 1;
1894
1895 glob = strnchr(iter, end - iter, '*');
1896 if (glob)
1897 cmplen = glob - iter;
1898 else
1899 cmplen = max_t(size_t, len, (end - iter));
1900
1901 if (!strncmp(name, iter, cmplen)) {
1902 flags |= block_flags;
1903 return flags;
1904 }
1905
1906 if (!*end || *end == ';')
1907 break;
1908 iter = end + 1;
1909 }
1910 }
1911
1912 return flags | slub_debug_local;
1913 }
1914 #else /* !CONFIG_SLUB_DEBUG */
setup_object_debug(struct kmem_cache * s,void * object)1915 static inline void setup_object_debug(struct kmem_cache *s, void *object) {}
1916 static inline
setup_slab_debug(struct kmem_cache * s,struct slab * slab,void * addr)1917 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {}
1918
alloc_debug_processing(struct kmem_cache * s,struct slab * slab,void * object,int orig_size)1919 static inline bool alloc_debug_processing(struct kmem_cache *s,
1920 struct slab *slab, void *object, int orig_size) { return true; }
1921
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)1922 static inline bool free_debug_processing(struct kmem_cache *s,
1923 struct slab *slab, void *head, void *tail, int *bulk_cnt,
1924 unsigned long addr, depot_stack_handle_t handle) { return true; }
1925
slab_pad_check(struct kmem_cache * s,struct slab * slab)1926 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)1927 static inline int check_object(struct kmem_cache *s, struct slab *slab,
1928 void *object, u8 val) { return 1; }
set_track_prepare(gfp_t gfp_flags)1929 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)1930 static inline void set_track(struct kmem_cache *s, void *object,
1931 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)1932 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1933 struct slab *slab) {}
remove_full(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab)1934 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n,
1935 struct slab *slab) {}
kmem_cache_flags(slab_flags_t flags,const char * name)1936 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name)
1937 {
1938 return flags;
1939 }
1940 #define slub_debug 0
1941
1942 #define disable_higher_order_debug 0
1943
node_nr_slabs(struct kmem_cache_node * n)1944 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1945 { return 0; }
inc_slabs_node(struct kmem_cache * s,int node,int objects)1946 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1947 int objects) {}
dec_slabs_node(struct kmem_cache * s,int node,int objects)1948 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1949 int objects) {}
1950 #ifndef CONFIG_SLUB_TINY
freelist_corrupted(struct kmem_cache * s,struct slab * slab,void ** freelist,void * nextfree)1951 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab,
1952 void **freelist, void *nextfree)
1953 {
1954 return false;
1955 }
1956 #endif
1957 #endif /* CONFIG_SLUB_DEBUG */
1958
1959 #ifdef CONFIG_SLAB_OBJ_EXT
1960
1961 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG
1962
mark_objexts_empty(struct slabobj_ext * obj_exts)1963 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts)
1964 {
1965 struct slabobj_ext *slab_exts;
1966 struct slab *obj_exts_slab;
1967
1968 obj_exts_slab = virt_to_slab(obj_exts);
1969 slab_exts = slab_obj_exts(obj_exts_slab);
1970 if (slab_exts) {
1971 unsigned int offs = obj_to_index(obj_exts_slab->slab_cache,
1972 obj_exts_slab, obj_exts);
1973 /* codetag should be NULL */
1974 WARN_ON(slab_exts[offs].ref.ct);
1975 set_codetag_empty(&slab_exts[offs].ref);
1976 }
1977 }
1978
mark_failed_objexts_alloc(struct slab * slab)1979 static inline void mark_failed_objexts_alloc(struct slab *slab)
1980 {
1981 slab->obj_exts = OBJEXTS_ALLOC_FAIL;
1982 }
1983
handle_failed_objexts_alloc(unsigned long obj_exts,struct slabobj_ext * vec,unsigned int objects)1984 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
1985 struct slabobj_ext *vec, unsigned int objects)
1986 {
1987 /*
1988 * If vector previously failed to allocate then we have live
1989 * objects with no tag reference. Mark all references in this
1990 * vector as empty to avoid warnings later on.
1991 */
1992 if (obj_exts & OBJEXTS_ALLOC_FAIL) {
1993 unsigned int i;
1994
1995 for (i = 0; i < objects; i++)
1996 set_codetag_empty(&vec[i].ref);
1997 }
1998 }
1999
2000 #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2001
mark_objexts_empty(struct slabobj_ext * obj_exts)2002 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) {}
mark_failed_objexts_alloc(struct slab * slab)2003 static inline void mark_failed_objexts_alloc(struct slab *slab) {}
handle_failed_objexts_alloc(unsigned long obj_exts,struct slabobj_ext * vec,unsigned int objects)2004 static inline void handle_failed_objexts_alloc(unsigned long obj_exts,
2005 struct slabobj_ext *vec, unsigned int objects) {}
2006
2007 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */
2008
2009 /*
2010 * The allocated objcg pointers array is not accounted directly.
2011 * Moreover, it should not come from DMA buffer and is not readily
2012 * reclaimable. So those GFP bits should be masked off.
2013 */
2014 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
2015 __GFP_ACCOUNT | __GFP_NOFAIL)
2016
init_slab_obj_exts(struct slab * slab)2017 static inline void init_slab_obj_exts(struct slab *slab)
2018 {
2019 slab->obj_exts = 0;
2020 }
2021
alloc_slab_obj_exts(struct slab * slab,struct kmem_cache * s,gfp_t gfp,bool new_slab)2022 int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2023 gfp_t gfp, bool new_slab)
2024 {
2025 unsigned int objects = objs_per_slab(s, slab);
2026 unsigned long new_exts;
2027 unsigned long old_exts;
2028 struct slabobj_ext *vec;
2029
2030 gfp &= ~OBJCGS_CLEAR_MASK;
2031 /* Prevent recursive extension vector allocation */
2032 gfp |= __GFP_NO_OBJ_EXT;
2033 vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp,
2034 slab_nid(slab));
2035 if (!vec) {
2036 /* Mark vectors which failed to allocate */
2037 if (new_slab)
2038 mark_failed_objexts_alloc(slab);
2039
2040 return -ENOMEM;
2041 }
2042
2043 new_exts = (unsigned long)vec;
2044 #ifdef CONFIG_MEMCG
2045 new_exts |= MEMCG_DATA_OBJEXTS;
2046 #endif
2047 old_exts = READ_ONCE(slab->obj_exts);
2048 handle_failed_objexts_alloc(old_exts, vec, objects);
2049 if (new_slab) {
2050 /*
2051 * If the slab is brand new and nobody can yet access its
2052 * obj_exts, no synchronization is required and obj_exts can
2053 * be simply assigned.
2054 */
2055 slab->obj_exts = new_exts;
2056 } else if ((old_exts & ~OBJEXTS_FLAGS_MASK) ||
2057 cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) {
2058 /*
2059 * If the slab is already in use, somebody can allocate and
2060 * assign slabobj_exts in parallel. In this case the existing
2061 * objcg vector should be reused.
2062 */
2063 mark_objexts_empty(vec);
2064 kfree(vec);
2065 return 0;
2066 }
2067
2068 kmemleak_not_leak(vec);
2069 return 0;
2070 }
2071
2072 /* Should be called only if mem_alloc_profiling_enabled() */
free_slab_obj_exts(struct slab * slab)2073 static noinline void free_slab_obj_exts(struct slab *slab)
2074 {
2075 struct slabobj_ext *obj_exts;
2076
2077 obj_exts = slab_obj_exts(slab);
2078 if (!obj_exts)
2079 return;
2080
2081 /*
2082 * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its
2083 * corresponding extension will be NULL. alloc_tag_sub() will throw a
2084 * warning if slab has extensions but the extension of an object is
2085 * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that
2086 * the extension for obj_exts is expected to be NULL.
2087 */
2088 mark_objexts_empty(obj_exts);
2089 kfree(obj_exts);
2090 slab->obj_exts = 0;
2091 }
2092
2093 #else /* CONFIG_SLAB_OBJ_EXT */
2094
init_slab_obj_exts(struct slab * slab)2095 static inline void init_slab_obj_exts(struct slab *slab)
2096 {
2097 }
2098
alloc_slab_obj_exts(struct slab * slab,struct kmem_cache * s,gfp_t gfp,bool new_slab)2099 static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s,
2100 gfp_t gfp, bool new_slab)
2101 {
2102 return 0;
2103 }
2104
free_slab_obj_exts(struct slab * slab)2105 static inline void free_slab_obj_exts(struct slab *slab)
2106 {
2107 }
2108
2109 #endif /* CONFIG_SLAB_OBJ_EXT */
2110
2111 #ifdef CONFIG_MEM_ALLOC_PROFILING
2112
2113 static inline struct slabobj_ext *
prepare_slab_obj_exts_hook(struct kmem_cache * s,gfp_t flags,void * p)2114 prepare_slab_obj_exts_hook(struct kmem_cache *s, gfp_t flags, void *p)
2115 {
2116 struct slab *slab;
2117
2118 if (!p)
2119 return NULL;
2120
2121 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2122 return NULL;
2123
2124 if (flags & __GFP_NO_OBJ_EXT)
2125 return NULL;
2126
2127 slab = virt_to_slab(p);
2128 if (!slab_obj_exts(slab) &&
2129 alloc_slab_obj_exts(slab, s, flags, false)) {
2130 pr_warn_once("%s, %s: Failed to create slab extension vector!\n",
2131 __func__, s->name);
2132 return NULL;
2133 }
2134
2135 return slab_obj_exts(slab) + obj_to_index(s, slab, p);
2136 }
2137
2138 /* Should be called only if mem_alloc_profiling_enabled() */
2139 static noinline void
__alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2140 __alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2141 {
2142 struct slabobj_ext *obj_exts;
2143
2144 obj_exts = prepare_slab_obj_exts_hook(s, flags, object);
2145 /*
2146 * Currently obj_exts is used only for allocation profiling.
2147 * If other users appear then mem_alloc_profiling_enabled()
2148 * check should be added before alloc_tag_add().
2149 */
2150 if (likely(obj_exts))
2151 alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size);
2152 }
2153
2154 static inline void
alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2155 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2156 {
2157 if (mem_alloc_profiling_enabled())
2158 __alloc_tagging_slab_alloc_hook(s, object, flags);
2159 }
2160
2161 /* Should be called only if mem_alloc_profiling_enabled() */
2162 static noinline void
__alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2163 __alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2164 int objects)
2165 {
2166 struct slabobj_ext *obj_exts;
2167 int i;
2168
2169 /* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */
2170 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE))
2171 return;
2172
2173 obj_exts = slab_obj_exts(slab);
2174 if (!obj_exts)
2175 return;
2176
2177 for (i = 0; i < objects; i++) {
2178 unsigned int off = obj_to_index(s, slab, p[i]);
2179
2180 alloc_tag_sub(&obj_exts[off].ref, s->size);
2181 }
2182 }
2183
2184 static inline void
alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2185 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2186 int objects)
2187 {
2188 if (mem_alloc_profiling_enabled())
2189 __alloc_tagging_slab_free_hook(s, slab, p, objects);
2190 }
2191
2192 #else /* CONFIG_MEM_ALLOC_PROFILING */
2193
2194 static inline void
alloc_tagging_slab_alloc_hook(struct kmem_cache * s,void * object,gfp_t flags)2195 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
2196 {
2197 }
2198
2199 static inline void
alloc_tagging_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2200 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2201 int objects)
2202 {
2203 }
2204
2205 #endif /* CONFIG_MEM_ALLOC_PROFILING */
2206
2207
2208 #ifdef CONFIG_MEMCG
2209
2210 static void memcg_alloc_abort_single(struct kmem_cache *s, void *object);
2211
2212 static __fastpath_inline
memcg_slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p)2213 bool memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
2214 gfp_t flags, size_t size, void **p)
2215 {
2216 if (likely(!memcg_kmem_online()))
2217 return true;
2218
2219 if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT)))
2220 return true;
2221
2222 if (likely(__memcg_slab_post_alloc_hook(s, lru, flags, size, p)))
2223 return true;
2224
2225 if (likely(size == 1)) {
2226 memcg_alloc_abort_single(s, *p);
2227 *p = NULL;
2228 } else {
2229 kmem_cache_free_bulk(s, size, p);
2230 }
2231
2232 return false;
2233 }
2234
2235 static __fastpath_inline
memcg_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2236 void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p,
2237 int objects)
2238 {
2239 struct slabobj_ext *obj_exts;
2240
2241 if (!memcg_kmem_online())
2242 return;
2243
2244 obj_exts = slab_obj_exts(slab);
2245 if (likely(!obj_exts))
2246 return;
2247
2248 __memcg_slab_free_hook(s, slab, p, objects, obj_exts);
2249 }
2250
2251 static __fastpath_inline
memcg_slab_post_charge(void * p,gfp_t flags)2252 bool memcg_slab_post_charge(void *p, gfp_t flags)
2253 {
2254 struct slabobj_ext *slab_exts;
2255 struct kmem_cache *s;
2256 struct folio *folio;
2257 struct slab *slab;
2258 unsigned long off;
2259
2260 folio = virt_to_folio(p);
2261 if (!folio_test_slab(folio)) {
2262 int size;
2263
2264 if (folio_memcg_kmem(folio))
2265 return true;
2266
2267 if (__memcg_kmem_charge_page(folio_page(folio, 0), flags,
2268 folio_order(folio)))
2269 return false;
2270
2271 /*
2272 * This folio has already been accounted in the global stats but
2273 * not in the memcg stats. So, subtract from the global and use
2274 * the interface which adds to both global and memcg stats.
2275 */
2276 size = folio_size(folio);
2277 node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size);
2278 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size);
2279 return true;
2280 }
2281
2282 slab = folio_slab(folio);
2283 s = slab->slab_cache;
2284
2285 /*
2286 * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency
2287 * of slab_obj_exts being allocated from the same slab and thus the slab
2288 * becoming effectively unfreeable.
2289 */
2290 if (is_kmalloc_normal(s))
2291 return true;
2292
2293 /* Ignore already charged objects. */
2294 slab_exts = slab_obj_exts(slab);
2295 if (slab_exts) {
2296 off = obj_to_index(s, slab, p);
2297 if (unlikely(slab_exts[off].objcg))
2298 return true;
2299 }
2300
2301 return __memcg_slab_post_alloc_hook(s, NULL, flags, 1, &p);
2302 }
2303
2304 #else /* CONFIG_MEMCG */
memcg_slab_post_alloc_hook(struct kmem_cache * s,struct list_lru * lru,gfp_t flags,size_t size,void ** p)2305 static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s,
2306 struct list_lru *lru,
2307 gfp_t flags, size_t size,
2308 void **p)
2309 {
2310 return true;
2311 }
2312
memcg_slab_free_hook(struct kmem_cache * s,struct slab * slab,void ** p,int objects)2313 static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab,
2314 void **p, int objects)
2315 {
2316 }
2317
memcg_slab_post_charge(void * p,gfp_t flags)2318 static inline bool memcg_slab_post_charge(void *p, gfp_t flags)
2319 {
2320 return true;
2321 }
2322 #endif /* CONFIG_MEMCG */
2323
2324 #ifdef CONFIG_SLUB_RCU_DEBUG
2325 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head);
2326
2327 struct rcu_delayed_free {
2328 struct rcu_head head;
2329 void *object;
2330 };
2331 #endif
2332
2333 /*
2334 * Hooks for other subsystems that check memory allocations. In a typical
2335 * production configuration these hooks all should produce no code at all.
2336 *
2337 * Returns true if freeing of the object can proceed, false if its reuse
2338 * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned
2339 * to KFENCE.
2340 */
2341 static __always_inline
slab_free_hook(struct kmem_cache * s,void * x,bool init,bool after_rcu_delay)2342 bool slab_free_hook(struct kmem_cache *s, void *x, bool init,
2343 bool after_rcu_delay)
2344 {
2345 /* Are the object contents still accessible? */
2346 bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
2347
2348 kmemleak_free_recursive(x, s->flags);
2349 kmsan_slab_free(s, x);
2350
2351 debug_check_no_locks_freed(x, s->object_size);
2352
2353 if (!(s->flags & SLAB_DEBUG_OBJECTS))
2354 debug_check_no_obj_freed(x, s->object_size);
2355
2356 /* Use KCSAN to help debug racy use-after-free. */
2357 if (!still_accessible)
2358 __kcsan_check_access(x, s->object_size,
2359 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
2360
2361 if (kfence_free(x))
2362 return false;
2363
2364 /*
2365 * Give KASAN a chance to notice an invalid free operation before we
2366 * modify the object.
2367 */
2368 if (kasan_slab_pre_free(s, x))
2369 return false;
2370
2371 #ifdef CONFIG_SLUB_RCU_DEBUG
2372 if (still_accessible) {
2373 struct rcu_delayed_free *delayed_free;
2374
2375 delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT);
2376 if (delayed_free) {
2377 /*
2378 * Let KASAN track our call stack as a "related work
2379 * creation", just like if the object had been freed
2380 * normally via kfree_rcu().
2381 * We have to do this manually because the rcu_head is
2382 * not located inside the object.
2383 */
2384 kasan_record_aux_stack_noalloc(x);
2385
2386 delayed_free->object = x;
2387 call_rcu(&delayed_free->head, slab_free_after_rcu_debug);
2388 return false;
2389 }
2390 }
2391 #endif /* CONFIG_SLUB_RCU_DEBUG */
2392
2393 /*
2394 * As memory initialization might be integrated into KASAN,
2395 * kasan_slab_free and initialization memset's must be
2396 * kept together to avoid discrepancies in behavior.
2397 *
2398 * The initialization memset's clear the object and the metadata,
2399 * but don't touch the SLAB redzone.
2400 *
2401 * The object's freepointer is also avoided if stored outside the
2402 * object.
2403 */
2404 if (unlikely(init)) {
2405 int rsize;
2406 unsigned int inuse, orig_size;
2407
2408 inuse = get_info_end(s);
2409 orig_size = get_orig_size(s, x);
2410 if (!kasan_has_integrated_init())
2411 memset(kasan_reset_tag(x), 0, orig_size);
2412 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0;
2413 memset((char *)kasan_reset_tag(x) + inuse, 0,
2414 s->size - inuse - rsize);
2415 /*
2416 * Restore orig_size, otherwize kmalloc redzone overwritten
2417 * would be reported
2418 */
2419 set_orig_size(s, x, orig_size);
2420
2421 }
2422 /* KASAN might put x into memory quarantine, delaying its reuse. */
2423 return !kasan_slab_free(s, x, init, still_accessible);
2424 }
2425
2426 static __fastpath_inline
slab_free_freelist_hook(struct kmem_cache * s,void ** head,void ** tail,int * cnt)2427 bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail,
2428 int *cnt)
2429 {
2430
2431 void *object;
2432 void *next = *head;
2433 void *old_tail = *tail;
2434 bool init;
2435
2436 if (is_kfence_address(next)) {
2437 slab_free_hook(s, next, false, false);
2438 return false;
2439 }
2440
2441 /* Head and tail of the reconstructed freelist */
2442 *head = NULL;
2443 *tail = NULL;
2444
2445 init = slab_want_init_on_free(s);
2446
2447 do {
2448 object = next;
2449 next = get_freepointer(s, object);
2450
2451 /* If object's reuse doesn't have to be delayed */
2452 if (likely(slab_free_hook(s, object, init, false))) {
2453 /* Move object to the new freelist */
2454 set_freepointer(s, object, *head);
2455 *head = object;
2456 if (!*tail)
2457 *tail = object;
2458 } else {
2459 /*
2460 * Adjust the reconstructed freelist depth
2461 * accordingly if object's reuse is delayed.
2462 */
2463 --(*cnt);
2464 }
2465 } while (object != old_tail);
2466
2467 return *head != NULL;
2468 }
2469
setup_object(struct kmem_cache * s,void * object)2470 static void *setup_object(struct kmem_cache *s, void *object)
2471 {
2472 setup_object_debug(s, object);
2473 object = kasan_init_slab_obj(s, object);
2474 if (unlikely(s->ctor)) {
2475 kasan_unpoison_new_object(s, object);
2476 s->ctor(object);
2477 kasan_poison_new_object(s, object);
2478 }
2479 return object;
2480 }
2481
2482 /*
2483 * Slab allocation and freeing
2484 */
alloc_slab_page(gfp_t flags,int node,struct kmem_cache_order_objects oo)2485 static inline struct slab *alloc_slab_page(gfp_t flags, int node,
2486 struct kmem_cache_order_objects oo)
2487 {
2488 struct folio *folio;
2489 struct slab *slab;
2490 unsigned int order = oo_order(oo);
2491
2492 if (node == NUMA_NO_NODE)
2493 folio = (struct folio *)alloc_pages(flags, order);
2494 else
2495 folio = (struct folio *)__alloc_pages_node(node, flags, order);
2496
2497 if (!folio)
2498 return NULL;
2499
2500 slab = folio_slab(folio);
2501 __folio_set_slab(folio);
2502 /* Make the flag visible before any changes to folio->mapping */
2503 smp_wmb();
2504 if (folio_is_pfmemalloc(folio))
2505 slab_set_pfmemalloc(slab);
2506
2507 trace_android_vh_slab_folio_alloced(order, flags);
2508
2509 return slab;
2510 }
2511
2512 #ifdef CONFIG_SLAB_FREELIST_RANDOM
2513 /* Pre-initialize the random sequence cache */
init_cache_random_seq(struct kmem_cache * s)2514 static int init_cache_random_seq(struct kmem_cache *s)
2515 {
2516 unsigned int count = oo_objects(s->oo);
2517 int err;
2518
2519 /* Bailout if already initialised */
2520 if (s->random_seq)
2521 return 0;
2522
2523 err = cache_random_seq_create(s, count, GFP_KERNEL);
2524 if (err) {
2525 pr_err("SLUB: Unable to initialize free list for %s\n",
2526 s->name);
2527 return err;
2528 }
2529
2530 /* Transform to an offset on the set of pages */
2531 if (s->random_seq) {
2532 unsigned int i;
2533
2534 for (i = 0; i < count; i++)
2535 s->random_seq[i] *= s->size;
2536 }
2537 return 0;
2538 }
2539
2540 /* Initialize each random sequence freelist per cache */
init_freelist_randomization(void)2541 static void __init init_freelist_randomization(void)
2542 {
2543 struct kmem_cache *s;
2544
2545 mutex_lock(&slab_mutex);
2546
2547 list_for_each_entry(s, &slab_caches, list)
2548 init_cache_random_seq(s);
2549
2550 mutex_unlock(&slab_mutex);
2551 }
2552
2553 /* 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)2554 static void *next_freelist_entry(struct kmem_cache *s,
2555 unsigned long *pos, void *start,
2556 unsigned long page_limit,
2557 unsigned long freelist_count)
2558 {
2559 unsigned int idx;
2560
2561 /*
2562 * If the target page allocation failed, the number of objects on the
2563 * page might be smaller than the usual size defined by the cache.
2564 */
2565 do {
2566 idx = s->random_seq[*pos];
2567 *pos += 1;
2568 if (*pos >= freelist_count)
2569 *pos = 0;
2570 } while (unlikely(idx >= page_limit));
2571
2572 return (char *)start + idx;
2573 }
2574
2575 /* Shuffle the single linked freelist based on a random pre-computed sequence */
shuffle_freelist(struct kmem_cache * s,struct slab * slab)2576 static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
2577 {
2578 void *start;
2579 void *cur;
2580 void *next;
2581 unsigned long idx, pos, page_limit, freelist_count;
2582
2583 if (slab->objects < 2 || !s->random_seq)
2584 return false;
2585
2586 freelist_count = oo_objects(s->oo);
2587 pos = get_random_u32_below(freelist_count);
2588
2589 page_limit = slab->objects * s->size;
2590 start = fixup_red_left(s, slab_address(slab));
2591
2592 /* First entry is used as the base of the freelist */
2593 cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count);
2594 cur = setup_object(s, cur);
2595 slab->freelist = cur;
2596
2597 for (idx = 1; idx < slab->objects; idx++) {
2598 next = next_freelist_entry(s, &pos, start, page_limit,
2599 freelist_count);
2600 next = setup_object(s, next);
2601 set_freepointer(s, cur, next);
2602 cur = next;
2603 }
2604 set_freepointer(s, cur, NULL);
2605
2606 return true;
2607 }
2608 #else
init_cache_random_seq(struct kmem_cache * s)2609 static inline int init_cache_random_seq(struct kmem_cache *s)
2610 {
2611 return 0;
2612 }
init_freelist_randomization(void)2613 static inline void init_freelist_randomization(void) { }
shuffle_freelist(struct kmem_cache * s,struct slab * slab)2614 static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
2615 {
2616 return false;
2617 }
2618 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
2619
account_slab(struct slab * slab,int order,struct kmem_cache * s,gfp_t gfp)2620 static __always_inline void account_slab(struct slab *slab, int order,
2621 struct kmem_cache *s, gfp_t gfp)
2622 {
2623 if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT))
2624 alloc_slab_obj_exts(slab, s, gfp, true);
2625
2626 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
2627 PAGE_SIZE << order);
2628 }
2629
unaccount_slab(struct slab * slab,int order,struct kmem_cache * s)2630 static __always_inline void unaccount_slab(struct slab *slab, int order,
2631 struct kmem_cache *s)
2632 {
2633 /*
2634 * The slab object extensions should now be freed regardless of
2635 * whether mem_alloc_profiling_enabled() or not because profiling
2636 * might have been disabled after slab->obj_exts got allocated.
2637 */
2638 free_slab_obj_exts(slab);
2639
2640 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s),
2641 -(PAGE_SIZE << order));
2642 }
2643
allocate_slab(struct kmem_cache * s,gfp_t flags,int node)2644 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
2645 {
2646 struct slab *slab;
2647 struct kmem_cache_order_objects oo = s->oo;
2648 gfp_t alloc_gfp;
2649 void *start, *p, *next;
2650 int idx;
2651 bool shuffle;
2652
2653 flags &= gfp_allowed_mask;
2654
2655 flags |= s->allocflags;
2656
2657 /*
2658 * Let the initial higher-order allocation fail under memory pressure
2659 * so we fall-back to the minimum order allocation.
2660 */
2661 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
2662 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
2663 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
2664
2665 slab = alloc_slab_page(alloc_gfp, node, oo);
2666 if (unlikely(!slab)) {
2667 oo = s->min;
2668 alloc_gfp = flags;
2669 /*
2670 * Allocation may have failed due to fragmentation.
2671 * Try a lower order alloc if possible
2672 */
2673 slab = alloc_slab_page(alloc_gfp, node, oo);
2674 if (unlikely(!slab))
2675 return NULL;
2676 stat(s, ORDER_FALLBACK);
2677 }
2678
2679 slab->objects = oo_objects(oo);
2680 slab->inuse = 0;
2681 slab->frozen = 0;
2682 init_slab_obj_exts(slab);
2683
2684 account_slab(slab, oo_order(oo), s, flags);
2685
2686 slab->slab_cache = s;
2687
2688 kasan_poison_slab(slab);
2689
2690 start = slab_address(slab);
2691
2692 setup_slab_debug(s, slab, start);
2693
2694 shuffle = shuffle_freelist(s, slab);
2695
2696 if (!shuffle) {
2697 start = fixup_red_left(s, start);
2698 start = setup_object(s, start);
2699 slab->freelist = start;
2700 for (idx = 0, p = start; idx < slab->objects - 1; idx++) {
2701 next = p + s->size;
2702 next = setup_object(s, next);
2703 set_freepointer(s, p, next);
2704 p = next;
2705 }
2706 set_freepointer(s, p, NULL);
2707 }
2708
2709 return slab;
2710 }
2711
new_slab(struct kmem_cache * s,gfp_t flags,int node)2712 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node)
2713 {
2714 if (unlikely(flags & GFP_SLAB_BUG_MASK))
2715 flags = kmalloc_fix_flags(flags);
2716
2717 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO));
2718
2719 return allocate_slab(s,
2720 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
2721 }
2722
__free_slab(struct kmem_cache * s,struct slab * slab)2723 static void __free_slab(struct kmem_cache *s, struct slab *slab)
2724 {
2725 struct folio *folio = slab_folio(slab);
2726 int order = folio_order(folio);
2727 int pages = 1 << order;
2728
2729 __slab_clear_pfmemalloc(slab);
2730 folio->mapping = NULL;
2731 /* Make the mapping reset visible before clearing the flag */
2732 smp_wmb();
2733 __folio_clear_slab(folio);
2734 mm_account_reclaimed_pages(pages);
2735 unaccount_slab(slab, order, s);
2736 __free_pages(&folio->page, order);
2737 }
2738
rcu_free_slab(struct rcu_head * h)2739 static void rcu_free_slab(struct rcu_head *h)
2740 {
2741 struct slab *slab = container_of(h, struct slab, rcu_head);
2742
2743 __free_slab(slab->slab_cache, slab);
2744 }
2745
free_slab(struct kmem_cache * s,struct slab * slab)2746 static void free_slab(struct kmem_cache *s, struct slab *slab)
2747 {
2748 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) {
2749 void *p;
2750
2751 slab_pad_check(s, slab);
2752 for_each_object(p, s, slab_address(slab), slab->objects)
2753 check_object(s, slab, p, SLUB_RED_INACTIVE);
2754 }
2755
2756 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU))
2757 call_rcu(&slab->rcu_head, rcu_free_slab);
2758 else
2759 __free_slab(s, slab);
2760 }
2761
discard_slab(struct kmem_cache * s,struct slab * slab)2762 static void discard_slab(struct kmem_cache *s, struct slab *slab)
2763 {
2764 dec_slabs_node(s, slab_nid(slab), slab->objects);
2765 free_slab(s, slab);
2766 }
2767
2768 /*
2769 * SLUB reuses PG_workingset bit to keep track of whether it's on
2770 * the per-node partial list.
2771 */
slab_test_node_partial(const struct slab * slab)2772 static inline bool slab_test_node_partial(const struct slab *slab)
2773 {
2774 return folio_test_workingset(slab_folio(slab));
2775 }
2776
slab_set_node_partial(struct slab * slab)2777 static inline void slab_set_node_partial(struct slab *slab)
2778 {
2779 set_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
2780 }
2781
slab_clear_node_partial(struct slab * slab)2782 static inline void slab_clear_node_partial(struct slab *slab)
2783 {
2784 clear_bit(PG_workingset, folio_flags(slab_folio(slab), 0));
2785 }
2786
2787 /*
2788 * Management of partially allocated slabs.
2789 */
2790 static inline void
__add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)2791 __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail)
2792 {
2793 n->nr_partial++;
2794 if (tail == DEACTIVATE_TO_TAIL)
2795 list_add_tail(&slab->slab_list, &n->partial);
2796 else
2797 list_add(&slab->slab_list, &n->partial);
2798 slab_set_node_partial(slab);
2799 }
2800
add_partial(struct kmem_cache_node * n,struct slab * slab,int tail)2801 static inline void add_partial(struct kmem_cache_node *n,
2802 struct slab *slab, int tail)
2803 {
2804 lockdep_assert_held(&n->list_lock);
2805 __add_partial(n, slab, tail);
2806 }
2807
remove_partial(struct kmem_cache_node * n,struct slab * slab)2808 static inline void remove_partial(struct kmem_cache_node *n,
2809 struct slab *slab)
2810 {
2811 lockdep_assert_held(&n->list_lock);
2812 list_del(&slab->slab_list);
2813 slab_clear_node_partial(slab);
2814 n->nr_partial--;
2815 }
2816
2817 /*
2818 * Called only for kmem_cache_debug() caches instead of remove_partial(), with a
2819 * slab from the n->partial list. Remove only a single object from the slab, do
2820 * the alloc_debug_processing() checks and leave the slab on the list, or move
2821 * it to full list if it was the last free object.
2822 */
alloc_single_from_partial(struct kmem_cache * s,struct kmem_cache_node * n,struct slab * slab,int orig_size)2823 static void *alloc_single_from_partial(struct kmem_cache *s,
2824 struct kmem_cache_node *n, struct slab *slab, int orig_size)
2825 {
2826 void *object;
2827
2828 lockdep_assert_held(&n->list_lock);
2829
2830 object = slab->freelist;
2831 slab->freelist = get_freepointer(s, object);
2832 slab->inuse++;
2833
2834 if (!alloc_debug_processing(s, slab, object, orig_size)) {
2835 if (folio_test_slab(slab_folio(slab)))
2836 remove_partial(n, slab);
2837 return NULL;
2838 }
2839
2840 if (slab->inuse == slab->objects) {
2841 remove_partial(n, slab);
2842 add_full(s, n, slab);
2843 }
2844
2845 return object;
2846 }
2847
2848 /*
2849 * Called only for kmem_cache_debug() caches to allocate from a freshly
2850 * allocated slab. Allocate a single object instead of whole freelist
2851 * and put the slab to the partial (or full) list.
2852 */
alloc_single_from_new_slab(struct kmem_cache * s,struct slab * slab,int orig_size)2853 static void *alloc_single_from_new_slab(struct kmem_cache *s,
2854 struct slab *slab, int orig_size)
2855 {
2856 int nid = slab_nid(slab);
2857 struct kmem_cache_node *n = get_node(s, nid);
2858 unsigned long flags;
2859 void *object;
2860
2861
2862 object = slab->freelist;
2863 slab->freelist = get_freepointer(s, object);
2864 slab->inuse = 1;
2865
2866 if (!alloc_debug_processing(s, slab, object, orig_size))
2867 /*
2868 * It's not really expected that this would fail on a
2869 * freshly allocated slab, but a concurrent memory
2870 * corruption in theory could cause that.
2871 */
2872 return NULL;
2873
2874 spin_lock_irqsave(&n->list_lock, flags);
2875
2876 if (slab->inuse == slab->objects)
2877 add_full(s, n, slab);
2878 else
2879 add_partial(n, slab, DEACTIVATE_TO_HEAD);
2880
2881 inc_slabs_node(s, nid, slab->objects);
2882 spin_unlock_irqrestore(&n->list_lock, flags);
2883
2884 return object;
2885 }
2886
2887 #ifdef CONFIG_SLUB_CPU_PARTIAL
2888 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain);
2889 #else
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)2890 static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab,
2891 int drain) { }
2892 #endif
2893 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags);
2894
2895 /*
2896 * Try to allocate a partial slab from a specific node.
2897 */
get_partial_node(struct kmem_cache * s,struct kmem_cache_node * n,struct partial_context * pc)2898 static struct slab *get_partial_node(struct kmem_cache *s,
2899 struct kmem_cache_node *n,
2900 struct partial_context *pc)
2901 {
2902 struct slab *slab, *slab2, *partial = NULL;
2903 unsigned long flags;
2904 unsigned int partial_slabs = 0;
2905
2906 /*
2907 * Racy check. If we mistakenly see no partial slabs then we
2908 * just allocate an empty slab. If we mistakenly try to get a
2909 * partial slab and there is none available then get_partial()
2910 * will return NULL.
2911 */
2912 if (!n || !n->nr_partial)
2913 return NULL;
2914
2915 spin_lock_irqsave(&n->list_lock, flags);
2916 list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) {
2917 if (!pfmemalloc_match(slab, pc->flags))
2918 continue;
2919
2920 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
2921 void *object = alloc_single_from_partial(s, n, slab,
2922 pc->orig_size);
2923 if (object) {
2924 partial = slab;
2925 pc->object = object;
2926 break;
2927 }
2928 continue;
2929 }
2930
2931 remove_partial(n, slab);
2932
2933 if (!partial) {
2934 partial = slab;
2935 stat(s, ALLOC_FROM_PARTIAL);
2936
2937 if ((slub_get_cpu_partial(s) == 0)) {
2938 break;
2939 }
2940 } else {
2941 put_cpu_partial(s, slab, 0);
2942 stat(s, CPU_PARTIAL_NODE);
2943
2944 if (++partial_slabs > slub_get_cpu_partial(s) / 2) {
2945 break;
2946 }
2947 }
2948 }
2949 spin_unlock_irqrestore(&n->list_lock, flags);
2950 return partial;
2951 }
2952
2953 /*
2954 * Get a slab from somewhere. Search in increasing NUMA distances.
2955 */
get_any_partial(struct kmem_cache * s,struct partial_context * pc)2956 static struct slab *get_any_partial(struct kmem_cache *s,
2957 struct partial_context *pc)
2958 {
2959 #ifdef CONFIG_NUMA
2960 struct zonelist *zonelist;
2961 struct zoneref *z;
2962 struct zone *zone;
2963 enum zone_type highest_zoneidx = gfp_zone(pc->flags);
2964 struct slab *slab;
2965 unsigned int cpuset_mems_cookie;
2966
2967 /*
2968 * The defrag ratio allows a configuration of the tradeoffs between
2969 * inter node defragmentation and node local allocations. A lower
2970 * defrag_ratio increases the tendency to do local allocations
2971 * instead of attempting to obtain partial slabs from other nodes.
2972 *
2973 * If the defrag_ratio is set to 0 then kmalloc() always
2974 * returns node local objects. If the ratio is higher then kmalloc()
2975 * may return off node objects because partial slabs are obtained
2976 * from other nodes and filled up.
2977 *
2978 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100
2979 * (which makes defrag_ratio = 1000) then every (well almost)
2980 * allocation will first attempt to defrag slab caches on other nodes.
2981 * This means scanning over all nodes to look for partial slabs which
2982 * may be expensive if we do it every time we are trying to find a slab
2983 * with available objects.
2984 */
2985 if (!s->remote_node_defrag_ratio ||
2986 get_cycles() % 1024 > s->remote_node_defrag_ratio)
2987 return NULL;
2988
2989 do {
2990 cpuset_mems_cookie = read_mems_allowed_begin();
2991 zonelist = node_zonelist(mempolicy_slab_node(), pc->flags);
2992 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) {
2993 struct kmem_cache_node *n;
2994
2995 n = get_node(s, zone_to_nid(zone));
2996
2997 if (n && cpuset_zone_allowed(zone, pc->flags) &&
2998 n->nr_partial > s->min_partial) {
2999 slab = get_partial_node(s, n, pc);
3000 if (slab) {
3001 /*
3002 * Don't check read_mems_allowed_retry()
3003 * here - if mems_allowed was updated in
3004 * parallel, that was a harmless race
3005 * between allocation and the cpuset
3006 * update
3007 */
3008 return slab;
3009 }
3010 }
3011 }
3012 } while (read_mems_allowed_retry(cpuset_mems_cookie));
3013 #endif /* CONFIG_NUMA */
3014 return NULL;
3015 }
3016
3017 /*
3018 * Get a partial slab, lock it and return it.
3019 */
get_partial(struct kmem_cache * s,int node,struct partial_context * pc)3020 static struct slab *get_partial(struct kmem_cache *s, int node,
3021 struct partial_context *pc)
3022 {
3023 struct slab *slab;
3024 int searchnode = node;
3025
3026 if (node == NUMA_NO_NODE)
3027 searchnode = numa_mem_id();
3028
3029 slab = get_partial_node(s, get_node(s, searchnode), pc);
3030 if (slab || (node != NUMA_NO_NODE && (pc->flags & __GFP_THISNODE)))
3031 return slab;
3032
3033 return get_any_partial(s, pc);
3034 }
3035
3036 #ifndef CONFIG_SLUB_TINY
3037
3038 #ifdef CONFIG_PREEMPTION
3039 /*
3040 * Calculate the next globally unique transaction for disambiguation
3041 * during cmpxchg. The transactions start with the cpu number and are then
3042 * incremented by CONFIG_NR_CPUS.
3043 */
3044 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
3045 #else
3046 /*
3047 * No preemption supported therefore also no need to check for
3048 * different cpus.
3049 */
3050 #define TID_STEP 1
3051 #endif /* CONFIG_PREEMPTION */
3052
next_tid(unsigned long tid)3053 static inline unsigned long next_tid(unsigned long tid)
3054 {
3055 return tid + TID_STEP;
3056 }
3057
3058 #ifdef SLUB_DEBUG_CMPXCHG
tid_to_cpu(unsigned long tid)3059 static inline unsigned int tid_to_cpu(unsigned long tid)
3060 {
3061 return tid % TID_STEP;
3062 }
3063
tid_to_event(unsigned long tid)3064 static inline unsigned long tid_to_event(unsigned long tid)
3065 {
3066 return tid / TID_STEP;
3067 }
3068 #endif
3069
init_tid(int cpu)3070 static inline unsigned int init_tid(int cpu)
3071 {
3072 return cpu;
3073 }
3074
note_cmpxchg_failure(const char * n,const struct kmem_cache * s,unsigned long tid)3075 static inline void note_cmpxchg_failure(const char *n,
3076 const struct kmem_cache *s, unsigned long tid)
3077 {
3078 #ifdef SLUB_DEBUG_CMPXCHG
3079 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
3080
3081 pr_info("%s %s: cmpxchg redo ", n, s->name);
3082
3083 #ifdef CONFIG_PREEMPTION
3084 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
3085 pr_warn("due to cpu change %d -> %d\n",
3086 tid_to_cpu(tid), tid_to_cpu(actual_tid));
3087 else
3088 #endif
3089 if (tid_to_event(tid) != tid_to_event(actual_tid))
3090 pr_warn("due to cpu running other code. Event %ld->%ld\n",
3091 tid_to_event(tid), tid_to_event(actual_tid));
3092 else
3093 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n",
3094 actual_tid, tid, next_tid(tid));
3095 #endif
3096 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
3097 }
3098
init_kmem_cache_cpus(struct kmem_cache * s)3099 static void init_kmem_cache_cpus(struct kmem_cache *s)
3100 {
3101 int cpu;
3102 struct kmem_cache_cpu *c;
3103
3104 for_each_possible_cpu(cpu) {
3105 c = per_cpu_ptr(s->cpu_slab, cpu);
3106 local_lock_init(&c->lock);
3107 c->tid = init_tid(cpu);
3108 }
3109 }
3110
3111 /*
3112 * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist,
3113 * unfreezes the slabs and puts it on the proper list.
3114 * Assumes the slab has been already safely taken away from kmem_cache_cpu
3115 * by the caller.
3116 */
deactivate_slab(struct kmem_cache * s,struct slab * slab,void * freelist)3117 static void deactivate_slab(struct kmem_cache *s, struct slab *slab,
3118 void *freelist)
3119 {
3120 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
3121 int free_delta = 0;
3122 void *nextfree, *freelist_iter, *freelist_tail;
3123 int tail = DEACTIVATE_TO_HEAD;
3124 unsigned long flags = 0;
3125 struct slab new;
3126 struct slab old;
3127
3128 if (READ_ONCE(slab->freelist)) {
3129 stat(s, DEACTIVATE_REMOTE_FREES);
3130 tail = DEACTIVATE_TO_TAIL;
3131 }
3132
3133 /*
3134 * Stage one: Count the objects on cpu's freelist as free_delta and
3135 * remember the last object in freelist_tail for later splicing.
3136 */
3137 freelist_tail = NULL;
3138 freelist_iter = freelist;
3139 while (freelist_iter) {
3140 nextfree = get_freepointer(s, freelist_iter);
3141
3142 /*
3143 * If 'nextfree' is invalid, it is possible that the object at
3144 * 'freelist_iter' is already corrupted. So isolate all objects
3145 * starting at 'freelist_iter' by skipping them.
3146 */
3147 if (freelist_corrupted(s, slab, &freelist_iter, nextfree))
3148 break;
3149
3150 freelist_tail = freelist_iter;
3151 free_delta++;
3152
3153 freelist_iter = nextfree;
3154 }
3155
3156 /*
3157 * Stage two: Unfreeze the slab while splicing the per-cpu
3158 * freelist to the head of slab's freelist.
3159 */
3160 do {
3161 old.freelist = READ_ONCE(slab->freelist);
3162 old.counters = READ_ONCE(slab->counters);
3163 VM_BUG_ON(!old.frozen);
3164
3165 /* Determine target state of the slab */
3166 new.counters = old.counters;
3167 new.frozen = 0;
3168 if (freelist_tail) {
3169 new.inuse -= free_delta;
3170 set_freepointer(s, freelist_tail, old.freelist);
3171 new.freelist = freelist;
3172 } else {
3173 new.freelist = old.freelist;
3174 }
3175 } while (!slab_update_freelist(s, slab,
3176 old.freelist, old.counters,
3177 new.freelist, new.counters,
3178 "unfreezing slab"));
3179
3180 /*
3181 * Stage three: Manipulate the slab list based on the updated state.
3182 */
3183 if (!new.inuse && n->nr_partial >= s->min_partial) {
3184 stat(s, DEACTIVATE_EMPTY);
3185 discard_slab(s, slab);
3186 stat(s, FREE_SLAB);
3187 } else if (new.freelist) {
3188 spin_lock_irqsave(&n->list_lock, flags);
3189 add_partial(n, slab, tail);
3190 spin_unlock_irqrestore(&n->list_lock, flags);
3191 stat(s, tail);
3192 } else {
3193 stat(s, DEACTIVATE_FULL);
3194 }
3195 }
3196
3197 #ifdef CONFIG_SLUB_CPU_PARTIAL
__put_partials(struct kmem_cache * s,struct slab * partial_slab)3198 static void __put_partials(struct kmem_cache *s, struct slab *partial_slab)
3199 {
3200 struct kmem_cache_node *n = NULL, *n2 = NULL;
3201 struct slab *slab, *slab_to_discard = NULL;
3202 unsigned long flags = 0;
3203
3204 while (partial_slab) {
3205 slab = partial_slab;
3206 partial_slab = slab->next;
3207
3208 n2 = get_node(s, slab_nid(slab));
3209 if (n != n2) {
3210 if (n)
3211 spin_unlock_irqrestore(&n->list_lock, flags);
3212
3213 n = n2;
3214 spin_lock_irqsave(&n->list_lock, flags);
3215 }
3216
3217 if (unlikely(!slab->inuse && n->nr_partial >= s->min_partial)) {
3218 slab->next = slab_to_discard;
3219 slab_to_discard = slab;
3220 } else {
3221 add_partial(n, slab, DEACTIVATE_TO_TAIL);
3222 stat(s, FREE_ADD_PARTIAL);
3223 }
3224 }
3225
3226 if (n)
3227 spin_unlock_irqrestore(&n->list_lock, flags);
3228
3229 while (slab_to_discard) {
3230 slab = slab_to_discard;
3231 slab_to_discard = slab_to_discard->next;
3232
3233 stat(s, DEACTIVATE_EMPTY);
3234 discard_slab(s, slab);
3235 stat(s, FREE_SLAB);
3236 }
3237 }
3238
3239 /*
3240 * Put all the cpu partial slabs to the node partial list.
3241 */
put_partials(struct kmem_cache * s)3242 static void put_partials(struct kmem_cache *s)
3243 {
3244 struct slab *partial_slab;
3245 unsigned long flags;
3246
3247 local_lock_irqsave(&s->cpu_slab->lock, flags);
3248 partial_slab = this_cpu_read(s->cpu_slab->partial);
3249 this_cpu_write(s->cpu_slab->partial, NULL);
3250 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3251
3252 if (partial_slab)
3253 __put_partials(s, partial_slab);
3254 }
3255
put_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)3256 static void put_partials_cpu(struct kmem_cache *s,
3257 struct kmem_cache_cpu *c)
3258 {
3259 struct slab *partial_slab;
3260
3261 partial_slab = slub_percpu_partial(c);
3262 c->partial = NULL;
3263
3264 if (partial_slab)
3265 __put_partials(s, partial_slab);
3266 }
3267
3268 /*
3269 * Put a slab into a partial slab slot if available.
3270 *
3271 * If we did not find a slot then simply move all the partials to the
3272 * per node partial list.
3273 */
put_cpu_partial(struct kmem_cache * s,struct slab * slab,int drain)3274 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
3275 {
3276 struct slab *oldslab;
3277 struct slab *slab_to_put = NULL;
3278 unsigned long flags;
3279 int slabs = 0;
3280
3281 local_lock_irqsave(&s->cpu_slab->lock, flags);
3282
3283 oldslab = this_cpu_read(s->cpu_slab->partial);
3284
3285 if (oldslab) {
3286 if (drain && oldslab->slabs >= s->cpu_partial_slabs) {
3287 /*
3288 * Partial array is full. Move the existing set to the
3289 * per node partial list. Postpone the actual unfreezing
3290 * outside of the critical section.
3291 */
3292 slab_to_put = oldslab;
3293 oldslab = NULL;
3294 } else {
3295 slabs = oldslab->slabs;
3296 }
3297 }
3298
3299 slabs++;
3300
3301 slab->slabs = slabs;
3302 slab->next = oldslab;
3303
3304 this_cpu_write(s->cpu_slab->partial, slab);
3305
3306 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3307
3308 if (slab_to_put) {
3309 __put_partials(s, slab_to_put);
3310 stat(s, CPU_PARTIAL_DRAIN);
3311 }
3312 }
3313
3314 #else /* CONFIG_SLUB_CPU_PARTIAL */
3315
put_partials(struct kmem_cache * s)3316 static inline void put_partials(struct kmem_cache *s) { }
put_partials_cpu(struct kmem_cache * s,struct kmem_cache_cpu * c)3317 static inline void put_partials_cpu(struct kmem_cache *s,
3318 struct kmem_cache_cpu *c) { }
3319
3320 #endif /* CONFIG_SLUB_CPU_PARTIAL */
3321
flush_slab(struct kmem_cache * s,struct kmem_cache_cpu * c)3322 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
3323 {
3324 unsigned long flags;
3325 struct slab *slab;
3326 void *freelist;
3327
3328 local_lock_irqsave(&s->cpu_slab->lock, flags);
3329
3330 slab = c->slab;
3331 freelist = c->freelist;
3332
3333 c->slab = NULL;
3334 c->freelist = NULL;
3335 c->tid = next_tid(c->tid);
3336
3337 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3338
3339 if (slab) {
3340 deactivate_slab(s, slab, freelist);
3341 stat(s, CPUSLAB_FLUSH);
3342 }
3343 }
3344
__flush_cpu_slab(struct kmem_cache * s,int cpu)3345 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
3346 {
3347 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
3348 void *freelist = c->freelist;
3349 struct slab *slab = c->slab;
3350
3351 c->slab = NULL;
3352 c->freelist = NULL;
3353 c->tid = next_tid(c->tid);
3354
3355 if (slab) {
3356 deactivate_slab(s, slab, freelist);
3357 stat(s, CPUSLAB_FLUSH);
3358 }
3359
3360 put_partials_cpu(s, c);
3361 }
3362
3363 struct slub_flush_work {
3364 struct work_struct work;
3365 struct kmem_cache *s;
3366 bool skip;
3367 };
3368
3369 /*
3370 * Flush cpu slab.
3371 *
3372 * Called from CPU work handler with migration disabled.
3373 */
flush_cpu_slab(struct work_struct * w)3374 static void flush_cpu_slab(struct work_struct *w)
3375 {
3376 struct kmem_cache *s;
3377 struct kmem_cache_cpu *c;
3378 struct slub_flush_work *sfw;
3379
3380 sfw = container_of(w, struct slub_flush_work, work);
3381
3382 s = sfw->s;
3383 c = this_cpu_ptr(s->cpu_slab);
3384
3385 if (c->slab)
3386 flush_slab(s, c);
3387
3388 put_partials(s);
3389 }
3390
has_cpu_slab(int cpu,struct kmem_cache * s)3391 static bool has_cpu_slab(int cpu, struct kmem_cache *s)
3392 {
3393 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
3394
3395 return c->slab || slub_percpu_partial(c);
3396 }
3397
3398 static DEFINE_MUTEX(flush_lock);
3399 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush);
3400
flush_all_cpus_locked(struct kmem_cache * s)3401 static void flush_all_cpus_locked(struct kmem_cache *s)
3402 {
3403 struct slub_flush_work *sfw;
3404 unsigned int cpu;
3405
3406 lockdep_assert_cpus_held();
3407 mutex_lock(&flush_lock);
3408
3409 for_each_online_cpu(cpu) {
3410 sfw = &per_cpu(slub_flush, cpu);
3411 if (!has_cpu_slab(cpu, s)) {
3412 sfw->skip = true;
3413 continue;
3414 }
3415 INIT_WORK(&sfw->work, flush_cpu_slab);
3416 sfw->skip = false;
3417 sfw->s = s;
3418 queue_work_on(cpu, flushwq, &sfw->work);
3419 }
3420
3421 for_each_online_cpu(cpu) {
3422 sfw = &per_cpu(slub_flush, cpu);
3423 if (sfw->skip)
3424 continue;
3425 flush_work(&sfw->work);
3426 }
3427
3428 mutex_unlock(&flush_lock);
3429 }
3430
flush_all(struct kmem_cache * s)3431 static void flush_all(struct kmem_cache *s)
3432 {
3433 cpus_read_lock();
3434 flush_all_cpus_locked(s);
3435 cpus_read_unlock();
3436 }
3437
3438 /*
3439 * Use the cpu notifier to insure that the cpu slabs are flushed when
3440 * necessary.
3441 */
slub_cpu_dead(unsigned int cpu)3442 static int slub_cpu_dead(unsigned int cpu)
3443 {
3444 struct kmem_cache *s;
3445
3446 mutex_lock(&slab_mutex);
3447 list_for_each_entry(s, &slab_caches, list)
3448 __flush_cpu_slab(s, cpu);
3449 mutex_unlock(&slab_mutex);
3450 return 0;
3451 }
3452
3453 #else /* CONFIG_SLUB_TINY */
flush_all_cpus_locked(struct kmem_cache * s)3454 static inline void flush_all_cpus_locked(struct kmem_cache *s) { }
flush_all(struct kmem_cache * s)3455 static inline void flush_all(struct kmem_cache *s) { }
__flush_cpu_slab(struct kmem_cache * s,int cpu)3456 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { }
slub_cpu_dead(unsigned int cpu)3457 static inline int slub_cpu_dead(unsigned int cpu) { return 0; }
3458 #endif /* CONFIG_SLUB_TINY */
3459
3460 /*
3461 * Check if the objects in a per cpu structure fit numa
3462 * locality expectations.
3463 */
node_match(struct slab * slab,int node)3464 static inline int node_match(struct slab *slab, int node)
3465 {
3466 #ifdef CONFIG_NUMA
3467 if (node != NUMA_NO_NODE && slab_nid(slab) != node)
3468 return 0;
3469 #endif
3470 return 1;
3471 }
3472
3473 #ifdef CONFIG_SLUB_DEBUG
count_free(struct slab * slab)3474 static int count_free(struct slab *slab)
3475 {
3476 return slab->objects - slab->inuse;
3477 }
3478
node_nr_objs(struct kmem_cache_node * n)3479 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
3480 {
3481 return atomic_long_read(&n->total_objects);
3482 }
3483
3484 /* 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)3485 static inline bool free_debug_processing(struct kmem_cache *s,
3486 struct slab *slab, void *head, void *tail, int *bulk_cnt,
3487 unsigned long addr, depot_stack_handle_t handle)
3488 {
3489 bool checks_ok = false;
3490 void *object = head;
3491 int cnt = 0;
3492
3493 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3494 if (!check_slab(s, slab))
3495 goto out;
3496 }
3497
3498 if (slab->inuse < *bulk_cnt) {
3499 slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n",
3500 slab->inuse, *bulk_cnt);
3501 goto out;
3502 }
3503
3504 next_object:
3505
3506 if (++cnt > *bulk_cnt)
3507 goto out_cnt;
3508
3509 if (s->flags & SLAB_CONSISTENCY_CHECKS) {
3510 if (!free_consistency_checks(s, slab, object, addr))
3511 goto out;
3512 }
3513
3514 if (s->flags & SLAB_STORE_USER)
3515 set_track_update(s, object, TRACK_FREE, addr, handle);
3516 trace(s, slab, object, 0);
3517 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */
3518 init_object(s, object, SLUB_RED_INACTIVE);
3519
3520 /* Reached end of constructed freelist yet? */
3521 if (object != tail) {
3522 object = get_freepointer(s, object);
3523 goto next_object;
3524 }
3525 checks_ok = true;
3526
3527 out_cnt:
3528 if (cnt != *bulk_cnt) {
3529 slab_err(s, slab, "Bulk free expected %d objects but found %d\n",
3530 *bulk_cnt, cnt);
3531 *bulk_cnt = cnt;
3532 }
3533
3534 out:
3535
3536 if (!checks_ok)
3537 slab_fix(s, "Object at 0x%p not freed", object);
3538
3539 return checks_ok;
3540 }
3541 #endif /* CONFIG_SLUB_DEBUG */
3542
3543 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS)
count_partial(struct kmem_cache_node * n,int (* get_count)(struct slab *))3544 static unsigned long count_partial(struct kmem_cache_node *n,
3545 int (*get_count)(struct slab *))
3546 {
3547 unsigned long flags;
3548 unsigned long x = 0;
3549 struct slab *slab;
3550
3551 spin_lock_irqsave(&n->list_lock, flags);
3552 list_for_each_entry(slab, &n->partial, slab_list)
3553 x += get_count(slab);
3554 spin_unlock_irqrestore(&n->list_lock, flags);
3555 return x;
3556 }
3557 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */
3558
3559 #ifdef CONFIG_SLUB_DEBUG
3560 #define MAX_PARTIAL_TO_SCAN 10000
3561
count_partial_free_approx(struct kmem_cache_node * n)3562 static unsigned long count_partial_free_approx(struct kmem_cache_node *n)
3563 {
3564 unsigned long flags;
3565 unsigned long x = 0;
3566 struct slab *slab;
3567
3568 spin_lock_irqsave(&n->list_lock, flags);
3569 if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
3570 list_for_each_entry(slab, &n->partial, slab_list)
3571 x += slab->objects - slab->inuse;
3572 } else {
3573 /*
3574 * For a long list, approximate the total count of objects in
3575 * it to meet the limit on the number of slabs to scan.
3576 * Scan from both the list's head and tail for better accuracy.
3577 */
3578 unsigned long scanned = 0;
3579
3580 list_for_each_entry(slab, &n->partial, slab_list) {
3581 x += slab->objects - slab->inuse;
3582 if (++scanned == MAX_PARTIAL_TO_SCAN / 2)
3583 break;
3584 }
3585 list_for_each_entry_reverse(slab, &n->partial, slab_list) {
3586 x += slab->objects - slab->inuse;
3587 if (++scanned == MAX_PARTIAL_TO_SCAN)
3588 break;
3589 }
3590 x = mult_frac(x, n->nr_partial, scanned);
3591 x = min(x, node_nr_objs(n));
3592 }
3593 spin_unlock_irqrestore(&n->list_lock, flags);
3594 return x;
3595 }
3596
3597 static noinline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)3598 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
3599 {
3600 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
3601 DEFAULT_RATELIMIT_BURST);
3602 int cpu = raw_smp_processor_id();
3603 int node;
3604 struct kmem_cache_node *n;
3605
3606 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs))
3607 return;
3608
3609 pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
3610 cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
3611 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
3612 s->name, s->object_size, s->size, oo_order(s->oo),
3613 oo_order(s->min));
3614
3615 if (oo_order(s->min) > get_order(s->object_size))
3616 pr_warn(" %s debugging increased min order, use slab_debug=O to disable.\n",
3617 s->name);
3618
3619 for_each_kmem_cache_node(s, node, n) {
3620 unsigned long nr_slabs;
3621 unsigned long nr_objs;
3622 unsigned long nr_free;
3623
3624 nr_free = count_partial_free_approx(n);
3625 nr_slabs = node_nr_slabs(n);
3626 nr_objs = node_nr_objs(n);
3627
3628 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n",
3629 node, nr_slabs, nr_objs, nr_free);
3630 }
3631 }
3632 #else /* CONFIG_SLUB_DEBUG */
3633 static inline void
slab_out_of_memory(struct kmem_cache * s,gfp_t gfpflags,int nid)3634 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { }
3635 #endif
3636
pfmemalloc_match(struct slab * slab,gfp_t gfpflags)3637 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags)
3638 {
3639 if (unlikely(slab_test_pfmemalloc(slab)))
3640 return gfp_pfmemalloc_allowed(gfpflags);
3641
3642 return true;
3643 }
3644
3645 #ifndef CONFIG_SLUB_TINY
3646 static inline bool
__update_cpu_freelist_fast(struct kmem_cache * s,void * freelist_old,void * freelist_new,unsigned long tid)3647 __update_cpu_freelist_fast(struct kmem_cache *s,
3648 void *freelist_old, void *freelist_new,
3649 unsigned long tid)
3650 {
3651 freelist_aba_t old = { .freelist = freelist_old, .counter = tid };
3652 freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) };
3653
3654 return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full,
3655 &old.full, new.full);
3656 }
3657
3658 /*
3659 * Check the slab->freelist and either transfer the freelist to the
3660 * per cpu freelist or deactivate the slab.
3661 *
3662 * The slab is still frozen if the return value is not NULL.
3663 *
3664 * If this function returns NULL then the slab has been unfrozen.
3665 */
get_freelist(struct kmem_cache * s,struct slab * slab)3666 static inline void *get_freelist(struct kmem_cache *s, struct slab *slab)
3667 {
3668 struct slab new;
3669 unsigned long counters;
3670 void *freelist;
3671
3672 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3673
3674 do {
3675 freelist = slab->freelist;
3676 counters = slab->counters;
3677
3678 new.counters = counters;
3679
3680 new.inuse = slab->objects;
3681 new.frozen = freelist != NULL;
3682
3683 } while (!__slab_update_freelist(s, slab,
3684 freelist, counters,
3685 NULL, new.counters,
3686 "get_freelist"));
3687
3688 return freelist;
3689 }
3690
3691 /*
3692 * Freeze the partial slab and return the pointer to the freelist.
3693 */
freeze_slab(struct kmem_cache * s,struct slab * slab)3694 static inline void *freeze_slab(struct kmem_cache *s, struct slab *slab)
3695 {
3696 struct slab new;
3697 unsigned long counters;
3698 void *freelist;
3699
3700 do {
3701 freelist = slab->freelist;
3702 counters = slab->counters;
3703
3704 new.counters = counters;
3705 VM_BUG_ON(new.frozen);
3706
3707 new.inuse = slab->objects;
3708 new.frozen = 1;
3709
3710 } while (!slab_update_freelist(s, slab,
3711 freelist, counters,
3712 NULL, new.counters,
3713 "freeze_slab"));
3714
3715 return freelist;
3716 }
3717
3718 /*
3719 * Slow path. The lockless freelist is empty or we need to perform
3720 * debugging duties.
3721 *
3722 * Processing is still very fast if new objects have been freed to the
3723 * regular freelist. In that case we simply take over the regular freelist
3724 * as the lockless freelist and zap the regular freelist.
3725 *
3726 * If that is not working then we fall back to the partial lists. We take the
3727 * first element of the freelist as the object to allocate now and move the
3728 * rest of the freelist to the lockless freelist.
3729 *
3730 * And if we were unable to get a new slab from the partial slab lists then
3731 * we need to allocate a new slab. This is the slowest path since it involves
3732 * a call to the page allocator and the setup of a new slab.
3733 *
3734 * Version of __slab_alloc to use when we know that preemption is
3735 * already disabled (which is the case for bulk allocation).
3736 */
___slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)3737 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3738 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3739 {
3740 void *freelist;
3741 struct slab *slab;
3742 unsigned long flags;
3743 struct partial_context pc;
3744 bool try_thisnode = true;
3745
3746 stat(s, ALLOC_SLOWPATH);
3747
3748 reread_slab:
3749
3750 slab = READ_ONCE(c->slab);
3751 if (!slab) {
3752 /*
3753 * if the node is not online or has no normal memory, just
3754 * ignore the node constraint
3755 */
3756 if (unlikely(node != NUMA_NO_NODE &&
3757 !node_isset(node, slab_nodes)))
3758 node = NUMA_NO_NODE;
3759 goto new_slab;
3760 }
3761
3762 if (unlikely(!node_match(slab, node))) {
3763 /*
3764 * same as above but node_match() being false already
3765 * implies node != NUMA_NO_NODE
3766 */
3767 if (!node_isset(node, slab_nodes)) {
3768 node = NUMA_NO_NODE;
3769 } else {
3770 stat(s, ALLOC_NODE_MISMATCH);
3771 goto deactivate_slab;
3772 }
3773 }
3774
3775 /*
3776 * By rights, we should be searching for a slab page that was
3777 * PFMEMALLOC but right now, we are losing the pfmemalloc
3778 * information when the page leaves the per-cpu allocator
3779 */
3780 if (unlikely(!pfmemalloc_match(slab, gfpflags)))
3781 goto deactivate_slab;
3782
3783 /* must check again c->slab in case we got preempted and it changed */
3784 local_lock_irqsave(&s->cpu_slab->lock, flags);
3785 if (unlikely(slab != c->slab)) {
3786 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3787 goto reread_slab;
3788 }
3789 freelist = c->freelist;
3790 if (freelist)
3791 goto load_freelist;
3792
3793 freelist = get_freelist(s, slab);
3794
3795 if (!freelist) {
3796 c->slab = NULL;
3797 c->tid = next_tid(c->tid);
3798 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3799 stat(s, DEACTIVATE_BYPASS);
3800 goto new_slab;
3801 }
3802
3803 stat(s, ALLOC_REFILL);
3804
3805 load_freelist:
3806
3807 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock));
3808
3809 /*
3810 * freelist is pointing to the list of objects to be used.
3811 * slab is pointing to the slab from which the objects are obtained.
3812 * That slab must be frozen for per cpu allocations to work.
3813 */
3814 VM_BUG_ON(!c->slab->frozen);
3815 c->freelist = get_freepointer(s, freelist);
3816 c->tid = next_tid(c->tid);
3817 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3818 return freelist;
3819
3820 deactivate_slab:
3821
3822 local_lock_irqsave(&s->cpu_slab->lock, flags);
3823 if (slab != c->slab) {
3824 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3825 goto reread_slab;
3826 }
3827 freelist = c->freelist;
3828 c->slab = NULL;
3829 c->freelist = NULL;
3830 c->tid = next_tid(c->tid);
3831 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3832 deactivate_slab(s, slab, freelist);
3833
3834 new_slab:
3835
3836 #ifdef CONFIG_SLUB_CPU_PARTIAL
3837 while (slub_percpu_partial(c)) {
3838 local_lock_irqsave(&s->cpu_slab->lock, flags);
3839 if (unlikely(c->slab)) {
3840 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3841 goto reread_slab;
3842 }
3843 if (unlikely(!slub_percpu_partial(c))) {
3844 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3845 /* we were preempted and partial list got empty */
3846 goto new_objects;
3847 }
3848
3849 slab = slub_percpu_partial(c);
3850 slub_set_percpu_partial(c, slab);
3851
3852 if (likely(node_match(slab, node) &&
3853 pfmemalloc_match(slab, gfpflags))) {
3854 c->slab = slab;
3855 freelist = get_freelist(s, slab);
3856 VM_BUG_ON(!freelist);
3857 stat(s, CPU_PARTIAL_ALLOC);
3858 goto load_freelist;
3859 }
3860
3861 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3862
3863 slab->next = NULL;
3864 __put_partials(s, slab);
3865 }
3866 #endif
3867
3868 new_objects:
3869
3870 pc.flags = gfpflags;
3871 /*
3872 * When a preferred node is indicated but no __GFP_THISNODE
3873 *
3874 * 1) try to get a partial slab from target node only by having
3875 * __GFP_THISNODE in pc.flags for get_partial()
3876 * 2) if 1) failed, try to allocate a new slab from target node with
3877 * GPF_NOWAIT | __GFP_THISNODE opportunistically
3878 * 3) if 2) failed, retry with original gfpflags which will allow
3879 * get_partial() try partial lists of other nodes before potentially
3880 * allocating new page from other nodes
3881 */
3882 if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
3883 && try_thisnode))
3884 pc.flags = GFP_NOWAIT | __GFP_THISNODE;
3885
3886 pc.orig_size = orig_size;
3887 slab = get_partial(s, node, &pc);
3888 if (slab) {
3889 if (kmem_cache_debug(s)) {
3890 freelist = pc.object;
3891 /*
3892 * For debug caches here we had to go through
3893 * alloc_single_from_partial() so just store the
3894 * tracking info and return the object.
3895 *
3896 * Due to disabled preemption we need to disallow
3897 * blocking. The flags are further adjusted by
3898 * gfp_nested_mask() in stack_depot itself.
3899 */
3900 if (s->flags & SLAB_STORE_USER)
3901 set_track(s, freelist, TRACK_ALLOC, addr,
3902 gfpflags & ~(__GFP_DIRECT_RECLAIM));
3903
3904 return freelist;
3905 }
3906
3907 freelist = freeze_slab(s, slab);
3908 goto retry_load_slab;
3909 }
3910
3911 slub_put_cpu_ptr(s->cpu_slab);
3912 slab = new_slab(s, pc.flags, node);
3913 c = slub_get_cpu_ptr(s->cpu_slab);
3914
3915 if (unlikely(!slab)) {
3916 if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
3917 && try_thisnode) {
3918 try_thisnode = false;
3919 goto new_objects;
3920 }
3921 slab_out_of_memory(s, gfpflags, node);
3922 return NULL;
3923 }
3924
3925 stat(s, ALLOC_SLAB);
3926
3927 if (kmem_cache_debug(s)) {
3928 freelist = alloc_single_from_new_slab(s, slab, orig_size);
3929
3930 if (unlikely(!freelist))
3931 goto new_objects;
3932
3933 if (s->flags & SLAB_STORE_USER)
3934 set_track(s, freelist, TRACK_ALLOC, addr,
3935 gfpflags & ~(__GFP_DIRECT_RECLAIM));
3936
3937 return freelist;
3938 }
3939
3940 /*
3941 * No other reference to the slab yet so we can
3942 * muck around with it freely without cmpxchg
3943 */
3944 freelist = slab->freelist;
3945 slab->freelist = NULL;
3946 slab->inuse = slab->objects;
3947 slab->frozen = 1;
3948
3949 inc_slabs_node(s, slab_nid(slab), slab->objects);
3950
3951 if (unlikely(!pfmemalloc_match(slab, gfpflags))) {
3952 /*
3953 * For !pfmemalloc_match() case we don't load freelist so that
3954 * we don't make further mismatched allocations easier.
3955 */
3956 deactivate_slab(s, slab, get_freepointer(s, freelist));
3957 return freelist;
3958 }
3959
3960 retry_load_slab:
3961
3962 local_lock_irqsave(&s->cpu_slab->lock, flags);
3963 if (unlikely(c->slab)) {
3964 void *flush_freelist = c->freelist;
3965 struct slab *flush_slab = c->slab;
3966
3967 c->slab = NULL;
3968 c->freelist = NULL;
3969 c->tid = next_tid(c->tid);
3970
3971 local_unlock_irqrestore(&s->cpu_slab->lock, flags);
3972
3973 deactivate_slab(s, flush_slab, flush_freelist);
3974
3975 stat(s, CPUSLAB_FLUSH);
3976
3977 goto retry_load_slab;
3978 }
3979 c->slab = slab;
3980
3981 goto load_freelist;
3982 }
3983
3984 /*
3985 * A wrapper for ___slab_alloc() for contexts where preemption is not yet
3986 * disabled. Compensates for possible cpu changes by refetching the per cpu area
3987 * pointer.
3988 */
__slab_alloc(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,struct kmem_cache_cpu * c,unsigned int orig_size)3989 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
3990 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size)
3991 {
3992 void *p;
3993
3994 #ifdef CONFIG_PREEMPT_COUNT
3995 /*
3996 * We may have been preempted and rescheduled on a different
3997 * cpu before disabling preemption. Need to reload cpu area
3998 * pointer.
3999 */
4000 c = slub_get_cpu_ptr(s->cpu_slab);
4001 #endif
4002
4003 p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size);
4004 #ifdef CONFIG_PREEMPT_COUNT
4005 slub_put_cpu_ptr(s->cpu_slab);
4006 #endif
4007 return p;
4008 }
4009
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)4010 static __always_inline void *__slab_alloc_node(struct kmem_cache *s,
4011 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4012 {
4013 struct kmem_cache_cpu *c;
4014 struct slab *slab;
4015 unsigned long tid;
4016 void *object;
4017
4018 redo:
4019 /*
4020 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
4021 * enabled. We may switch back and forth between cpus while
4022 * reading from one cpu area. That does not matter as long
4023 * as we end up on the original cpu again when doing the cmpxchg.
4024 *
4025 * We must guarantee that tid and kmem_cache_cpu are retrieved on the
4026 * same cpu. We read first the kmem_cache_cpu pointer and use it to read
4027 * the tid. If we are preempted and switched to another cpu between the
4028 * two reads, it's OK as the two are still associated with the same cpu
4029 * and cmpxchg later will validate the cpu.
4030 */
4031 c = raw_cpu_ptr(s->cpu_slab);
4032 tid = READ_ONCE(c->tid);
4033
4034 /*
4035 * Irqless object alloc/free algorithm used here depends on sequence
4036 * of fetching cpu_slab's data. tid should be fetched before anything
4037 * on c to guarantee that object and slab associated with previous tid
4038 * won't be used with current tid. If we fetch tid first, object and
4039 * slab could be one associated with next tid and our alloc/free
4040 * request will be failed. In this case, we will retry. So, no problem.
4041 */
4042 barrier();
4043
4044 /*
4045 * The transaction ids are globally unique per cpu and per operation on
4046 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
4047 * occurs on the right processor and that there was no operation on the
4048 * linked list in between.
4049 */
4050
4051 object = c->freelist;
4052 slab = c->slab;
4053
4054 if (!USE_LOCKLESS_FAST_PATH() ||
4055 unlikely(!object || !slab || !node_match(slab, node))) {
4056 object = __slab_alloc(s, gfpflags, node, addr, c, orig_size);
4057 } else {
4058 void *next_object = get_freepointer_safe(s, object);
4059
4060 /*
4061 * The cmpxchg will only match if there was no additional
4062 * operation and if we are on the right processor.
4063 *
4064 * The cmpxchg does the following atomically (without lock
4065 * semantics!)
4066 * 1. Relocate first pointer to the current per cpu area.
4067 * 2. Verify that tid and freelist have not been changed
4068 * 3. If they were not changed replace tid and freelist
4069 *
4070 * Since this is without lock semantics the protection is only
4071 * against code executing on this cpu *not* from access by
4072 * other cpus.
4073 */
4074 if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
4075 note_cmpxchg_failure("slab_alloc", s, tid);
4076 goto redo;
4077 }
4078 prefetch_freepointer(s, next_object);
4079 stat(s, ALLOC_FASTPATH);
4080 }
4081
4082 return object;
4083 }
4084 #else /* CONFIG_SLUB_TINY */
__slab_alloc_node(struct kmem_cache * s,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)4085 static void *__slab_alloc_node(struct kmem_cache *s,
4086 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4087 {
4088 struct partial_context pc;
4089 struct slab *slab;
4090 void *object;
4091
4092 pc.flags = gfpflags;
4093 pc.orig_size = orig_size;
4094 slab = get_partial(s, node, &pc);
4095
4096 if (slab)
4097 return pc.object;
4098
4099 slab = new_slab(s, gfpflags, node);
4100 if (unlikely(!slab)) {
4101 slab_out_of_memory(s, gfpflags, node);
4102 return NULL;
4103 }
4104
4105 object = alloc_single_from_new_slab(s, slab, orig_size);
4106
4107 return object;
4108 }
4109 #endif /* CONFIG_SLUB_TINY */
4110
4111 /*
4112 * If the object has been wiped upon free, make sure it's fully initialized by
4113 * zeroing out freelist pointer.
4114 *
4115 * Note that we also wipe custom freelist pointers.
4116 */
maybe_wipe_obj_freeptr(struct kmem_cache * s,void * obj)4117 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s,
4118 void *obj)
4119 {
4120 if (unlikely(slab_want_init_on_free(s)) && obj &&
4121 !freeptr_outside_object(s))
4122 memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
4123 0, sizeof(void *));
4124 }
4125
4126 static __fastpath_inline
slab_pre_alloc_hook(struct kmem_cache * s,gfp_t flags)4127 struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
4128 {
4129 flags &= gfp_allowed_mask;
4130
4131 might_alloc(flags);
4132
4133 if (unlikely(should_failslab(s, flags)))
4134 return NULL;
4135
4136 return s;
4137 }
4138
4139 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)4140 bool slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru,
4141 gfp_t flags, size_t size, void **p, bool init,
4142 unsigned int orig_size)
4143 {
4144 unsigned int zero_size = s->object_size;
4145 bool kasan_init = init;
4146 size_t i;
4147 gfp_t init_flags = flags & gfp_allowed_mask;
4148
4149 /*
4150 * For kmalloc object, the allocated memory size(object_size) is likely
4151 * larger than the requested size(orig_size). If redzone check is
4152 * enabled for the extra space, don't zero it, as it will be redzoned
4153 * soon. The redzone operation for this extra space could be seen as a
4154 * replacement of current poisoning under certain debug option, and
4155 * won't break other sanity checks.
4156 */
4157 if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) &&
4158 (s->flags & SLAB_KMALLOC))
4159 zero_size = orig_size;
4160
4161 /*
4162 * When slab_debug is enabled, avoid memory initialization integrated
4163 * into KASAN and instead zero out the memory via the memset below with
4164 * the proper size. Otherwise, KASAN might overwrite SLUB redzones and
4165 * cause false-positive reports. This does not lead to a performance
4166 * penalty on production builds, as slab_debug is not intended to be
4167 * enabled there.
4168 */
4169 if (__slub_debug_enabled())
4170 kasan_init = false;
4171
4172 /*
4173 * As memory initialization might be integrated into KASAN,
4174 * kasan_slab_alloc and initialization memset must be
4175 * kept together to avoid discrepancies in behavior.
4176 *
4177 * As p[i] might get tagged, memset and kmemleak hook come after KASAN.
4178 */
4179 for (i = 0; i < size; i++) {
4180 p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init);
4181 if (p[i] && init && (!kasan_init ||
4182 !kasan_has_integrated_init()))
4183 memset(p[i], 0, zero_size);
4184 kmemleak_alloc_recursive(p[i], s->object_size, 1,
4185 s->flags, init_flags);
4186 kmsan_slab_alloc(s, p[i], init_flags);
4187 alloc_tagging_slab_alloc_hook(s, p[i], flags);
4188 }
4189
4190 return memcg_slab_post_alloc_hook(s, lru, flags, size, p);
4191 }
4192
4193 /*
4194 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
4195 * have the fastpath folded into their functions. So no function call
4196 * overhead for requests that can be satisfied on the fastpath.
4197 *
4198 * The fastpath works by first checking if the lockless freelist can be used.
4199 * If not then __slab_alloc is called for slow processing.
4200 *
4201 * Otherwise we can simply pick the next object from the lockless free list.
4202 */
slab_alloc_node(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags,int node,unsigned long addr,size_t orig_size)4203 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
4204 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size)
4205 {
4206 void *object;
4207 bool init = false;
4208
4209 s = slab_pre_alloc_hook(s, gfpflags);
4210 if (unlikely(!s))
4211 return NULL;
4212
4213 object = kfence_alloc(s, orig_size, gfpflags);
4214 if (unlikely(object))
4215 goto out;
4216
4217 object = __slab_alloc_node(s, gfpflags, node, addr, orig_size);
4218
4219 maybe_wipe_obj_freeptr(s, object);
4220 init = slab_want_init_on_alloc(gfpflags, s);
4221
4222 out:
4223 /*
4224 * When init equals 'true', like for kzalloc() family, only
4225 * @orig_size bytes might be zeroed instead of s->object_size
4226 * In case this fails due to memcg_slab_post_alloc_hook(),
4227 * object is set to NULL
4228 */
4229 slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size);
4230
4231 trace_android_vh_slab_alloc_node(object, addr, s);
4232
4233 return object;
4234 }
4235
kmem_cache_alloc_noprof(struct kmem_cache * s,gfp_t gfpflags)4236 void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags)
4237 {
4238 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, _RET_IP_,
4239 s->object_size);
4240
4241 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4242
4243 return ret;
4244 }
4245 EXPORT_SYMBOL(kmem_cache_alloc_noprof);
4246
kmem_cache_alloc_lru_noprof(struct kmem_cache * s,struct list_lru * lru,gfp_t gfpflags)4247 void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru,
4248 gfp_t gfpflags)
4249 {
4250 void *ret = slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, _RET_IP_,
4251 s->object_size);
4252
4253 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE);
4254
4255 return ret;
4256 }
4257 EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof);
4258
kmem_cache_charge(void * objp,gfp_t gfpflags)4259 bool kmem_cache_charge(void *objp, gfp_t gfpflags)
4260 {
4261 if (!memcg_kmem_online())
4262 return true;
4263
4264 return memcg_slab_post_charge(objp, gfpflags);
4265 }
4266 EXPORT_SYMBOL(kmem_cache_charge);
4267
4268 /**
4269 * kmem_cache_alloc_node - Allocate an object on the specified node
4270 * @s: The cache to allocate from.
4271 * @gfpflags: See kmalloc().
4272 * @node: node number of the target node.
4273 *
4274 * Identical to kmem_cache_alloc but it will allocate memory on the given
4275 * node, which can improve the performance for cpu bound structures.
4276 *
4277 * Fallback to other node is possible if __GFP_THISNODE is not set.
4278 *
4279 * Return: pointer to the new object or %NULL in case of error
4280 */
kmem_cache_alloc_node_noprof(struct kmem_cache * s,gfp_t gfpflags,int node)4281 void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
4282 {
4283 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
4284
4285 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node);
4286
4287 return ret;
4288 }
4289 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
4290
4291 /*
4292 * To avoid unnecessary overhead, we pass through large allocation requests
4293 * directly to the page allocator. We use __GFP_COMP, because we will need to
4294 * know the allocation order to free the pages properly in kfree.
4295 */
___kmalloc_large_node(size_t size,gfp_t flags,int node)4296 static void *___kmalloc_large_node(size_t size, gfp_t flags, int node)
4297 {
4298 struct folio *folio;
4299 void *ptr = NULL;
4300 unsigned int order = get_order(size);
4301 bool bypass = false;
4302
4303 if (unlikely(flags & GFP_SLAB_BUG_MASK))
4304 flags = kmalloc_fix_flags(flags);
4305
4306 trace_android_vh_kmalloc_large_node_bypass(size, flags, node, &ptr, &bypass);
4307 if (bypass)
4308 return ptr;
4309
4310 flags |= __GFP_COMP;
4311
4312 if (node == NUMA_NO_NODE)
4313 folio = (struct folio *)alloc_pages_noprof(flags, order);
4314 else
4315 folio = (struct folio *)__alloc_pages_noprof(flags, order, node, NULL);
4316
4317 if (folio) {
4318 ptr = folio_address(folio);
4319 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
4320 PAGE_SIZE << order);
4321 }
4322
4323 trace_android_vh_kmalloc_large_alloced(folio, order, flags);
4324
4325 ptr = kasan_kmalloc_large(ptr, size, flags);
4326 /* As ptr might get tagged, call kmemleak hook after KASAN. */
4327 kmemleak_alloc(ptr, size, 1, flags);
4328 kmsan_kmalloc_large(ptr, size, flags);
4329
4330 return ptr;
4331 }
4332
__kmalloc_large_noprof(size_t size,gfp_t flags)4333 void *__kmalloc_large_noprof(size_t size, gfp_t flags)
4334 {
4335 void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE);
4336
4337 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
4338 flags, NUMA_NO_NODE);
4339 return ret;
4340 }
4341 EXPORT_SYMBOL(__kmalloc_large_noprof);
4342
__kmalloc_large_node_noprof(size_t size,gfp_t flags,int node)4343 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node)
4344 {
4345 void *ret = ___kmalloc_large_node(size, flags, node);
4346
4347 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size),
4348 flags, node);
4349 return ret;
4350 }
4351 EXPORT_SYMBOL(__kmalloc_large_node_noprof);
4352
4353 static __always_inline
__do_kmalloc_node(size_t size,kmem_buckets * b,gfp_t flags,int node,unsigned long caller)4354 void *__do_kmalloc_node(size_t size, kmem_buckets *b, gfp_t flags, int node,
4355 unsigned long caller)
4356 {
4357 struct kmem_cache *s;
4358 void *ret;
4359
4360 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) {
4361 ret = __kmalloc_large_node_noprof(size, flags, node);
4362 trace_kmalloc(caller, ret, size,
4363 PAGE_SIZE << get_order(size), flags, node);
4364 return ret;
4365 }
4366
4367 if (unlikely(!size))
4368 return ZERO_SIZE_PTR;
4369
4370 s = kmalloc_slab(size, b, flags, caller);
4371
4372 ret = slab_alloc_node(s, NULL, flags, node, caller, size);
4373 ret = kasan_kmalloc(s, ret, size, flags);
4374 trace_kmalloc(caller, ret, size, s->size, flags, node);
4375 return ret;
4376 }
__kmalloc_node_noprof(DECL_BUCKET_PARAMS (size,b),gfp_t flags,int node)4377 void *__kmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
4378 {
4379 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, _RET_IP_);
4380 }
4381 EXPORT_SYMBOL(__kmalloc_node_noprof);
4382
__kmalloc_noprof(size_t size,gfp_t flags)4383 void *__kmalloc_noprof(size_t size, gfp_t flags)
4384 {
4385 return __do_kmalloc_node(size, NULL, flags, NUMA_NO_NODE, _RET_IP_);
4386 }
4387 EXPORT_SYMBOL(__kmalloc_noprof);
4388
__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS (size,b),gfp_t flags,int node,unsigned long caller)4389 void *__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags,
4390 int node, unsigned long caller)
4391 {
4392 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, caller);
4393
4394 }
4395 EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof);
4396
__kmalloc_cache_noprof(struct kmem_cache * s,gfp_t gfpflags,size_t size)4397 void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size)
4398 {
4399 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE,
4400 _RET_IP_, size);
4401
4402 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE);
4403
4404 ret = kasan_kmalloc(s, ret, size, gfpflags);
4405 return ret;
4406 }
4407 EXPORT_SYMBOL(__kmalloc_cache_noprof);
4408
__kmalloc_cache_node_noprof(struct kmem_cache * s,gfp_t gfpflags,int node,size_t size)4409 void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags,
4410 int node, size_t size)
4411 {
4412 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, size);
4413
4414 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node);
4415
4416 ret = kasan_kmalloc(s, ret, size, gfpflags);
4417 return ret;
4418 }
4419 EXPORT_SYMBOL(__kmalloc_cache_node_noprof);
4420
free_to_partial_list(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int bulk_cnt,unsigned long addr)4421 static noinline void free_to_partial_list(
4422 struct kmem_cache *s, struct slab *slab,
4423 void *head, void *tail, int bulk_cnt,
4424 unsigned long addr)
4425 {
4426 struct kmem_cache_node *n = get_node(s, slab_nid(slab));
4427 struct slab *slab_free = NULL;
4428 int cnt = bulk_cnt;
4429 unsigned long flags;
4430 depot_stack_handle_t handle = 0;
4431
4432 /*
4433 * We cannot use GFP_NOWAIT as there are callsites where waking up
4434 * kswapd could deadlock
4435 */
4436 if (s->flags & SLAB_STORE_USER)
4437 handle = set_track_prepare(__GFP_NOWARN);
4438
4439 spin_lock_irqsave(&n->list_lock, flags);
4440
4441 if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) {
4442 void *prior = slab->freelist;
4443
4444 /* Perform the actual freeing while we still hold the locks */
4445 slab->inuse -= cnt;
4446 set_freepointer(s, tail, prior);
4447 slab->freelist = head;
4448
4449 /*
4450 * If the slab is empty, and node's partial list is full,
4451 * it should be discarded anyway no matter it's on full or
4452 * partial list.
4453 */
4454 if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
4455 slab_free = slab;
4456
4457 if (!prior) {
4458 /* was on full list */
4459 remove_full(s, n, slab);
4460 if (!slab_free) {
4461 add_partial(n, slab, DEACTIVATE_TO_TAIL);
4462 stat(s, FREE_ADD_PARTIAL);
4463 }
4464 } else if (slab_free) {
4465 remove_partial(n, slab);
4466 stat(s, FREE_REMOVE_PARTIAL);
4467 }
4468 }
4469
4470 if (slab_free) {
4471 /*
4472 * Update the counters while still holding n->list_lock to
4473 * prevent spurious validation warnings
4474 */
4475 dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
4476 }
4477
4478 spin_unlock_irqrestore(&n->list_lock, flags);
4479
4480 if (slab_free) {
4481 stat(s, FREE_SLAB);
4482 free_slab(s, slab_free);
4483 }
4484 }
4485
4486 /*
4487 * Slow path handling. This may still be called frequently since objects
4488 * have a longer lifetime than the cpu slabs in most processing loads.
4489 *
4490 * So we still attempt to reduce cache line usage. Just take the slab
4491 * lock and free the item. If there is no additional partial slab
4492 * handling required then we can return immediately.
4493 */
__slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)4494 static void __slab_free(struct kmem_cache *s, struct slab *slab,
4495 void *head, void *tail, int cnt,
4496 unsigned long addr)
4497
4498 {
4499 void *prior;
4500 int was_frozen;
4501 struct slab new;
4502 unsigned long counters;
4503 struct kmem_cache_node *n = NULL;
4504 unsigned long flags;
4505 bool on_node_partial;
4506
4507 stat(s, FREE_SLOWPATH);
4508
4509 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) {
4510 free_to_partial_list(s, slab, head, tail, cnt, addr);
4511 return;
4512 }
4513
4514 do {
4515 if (unlikely(n)) {
4516 spin_unlock_irqrestore(&n->list_lock, flags);
4517 n = NULL;
4518 }
4519 prior = slab->freelist;
4520 counters = slab->counters;
4521 set_freepointer(s, tail, prior);
4522 new.counters = counters;
4523 was_frozen = new.frozen;
4524 new.inuse -= cnt;
4525 if ((!new.inuse || !prior) && !was_frozen) {
4526 /* Needs to be taken off a list */
4527 if (!kmem_cache_has_cpu_partial(s) || prior) {
4528
4529 n = get_node(s, slab_nid(slab));
4530 /*
4531 * Speculatively acquire the list_lock.
4532 * If the cmpxchg does not succeed then we may
4533 * drop the list_lock without any processing.
4534 *
4535 * Otherwise the list_lock will synchronize with
4536 * other processors updating the list of slabs.
4537 */
4538 spin_lock_irqsave(&n->list_lock, flags);
4539
4540 on_node_partial = slab_test_node_partial(slab);
4541 }
4542 }
4543
4544 } while (!slab_update_freelist(s, slab,
4545 prior, counters,
4546 head, new.counters,
4547 "__slab_free"));
4548
4549 if (likely(!n)) {
4550
4551 if (likely(was_frozen)) {
4552 /*
4553 * The list lock was not taken therefore no list
4554 * activity can be necessary.
4555 */
4556 stat(s, FREE_FROZEN);
4557 } else if (kmem_cache_has_cpu_partial(s) && !prior) {
4558 /*
4559 * If we started with a full slab then put it onto the
4560 * per cpu partial list.
4561 */
4562 put_cpu_partial(s, slab, 1);
4563 stat(s, CPU_PARTIAL_FREE);
4564 }
4565
4566 return;
4567 }
4568
4569 /*
4570 * This slab was partially empty but not on the per-node partial list,
4571 * in which case we shouldn't manipulate its list, just return.
4572 */
4573 if (prior && !on_node_partial) {
4574 spin_unlock_irqrestore(&n->list_lock, flags);
4575 return;
4576 }
4577
4578 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial))
4579 goto slab_empty;
4580
4581 /*
4582 * Objects left in the slab. If it was not on the partial list before
4583 * then add it.
4584 */
4585 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
4586 add_partial(n, slab, DEACTIVATE_TO_TAIL);
4587 stat(s, FREE_ADD_PARTIAL);
4588 }
4589 spin_unlock_irqrestore(&n->list_lock, flags);
4590 return;
4591
4592 slab_empty:
4593 if (prior) {
4594 /*
4595 * Slab on the partial list.
4596 */
4597 remove_partial(n, slab);
4598 stat(s, FREE_REMOVE_PARTIAL);
4599 }
4600
4601 spin_unlock_irqrestore(&n->list_lock, flags);
4602 stat(s, FREE_SLAB);
4603 discard_slab(s, slab);
4604 }
4605
4606 #ifndef CONFIG_SLUB_TINY
4607 /*
4608 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
4609 * can perform fastpath freeing without additional function calls.
4610 *
4611 * The fastpath is only possible if we are freeing to the current cpu slab
4612 * of this processor. This typically the case if we have just allocated
4613 * the item before.
4614 *
4615 * If fastpath is not possible then fall back to __slab_free where we deal
4616 * with all sorts of special processing.
4617 *
4618 * Bulk free of a freelist with several objects (all pointing to the
4619 * same slab) possible by specifying head and tail ptr, plus objects
4620 * count (cnt). Bulk free indicated by tail pointer being set.
4621 */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)4622 static __always_inline void do_slab_free(struct kmem_cache *s,
4623 struct slab *slab, void *head, void *tail,
4624 int cnt, unsigned long addr)
4625 {
4626 struct kmem_cache_cpu *c;
4627 unsigned long tid;
4628 void **freelist;
4629
4630 redo:
4631 /*
4632 * Determine the currently cpus per cpu slab.
4633 * The cpu may change afterward. However that does not matter since
4634 * data is retrieved via this pointer. If we are on the same cpu
4635 * during the cmpxchg then the free will succeed.
4636 */
4637 c = raw_cpu_ptr(s->cpu_slab);
4638 tid = READ_ONCE(c->tid);
4639
4640 /* Same with comment on barrier() in __slab_alloc_node() */
4641 barrier();
4642
4643 if (unlikely(slab != c->slab)) {
4644 __slab_free(s, slab, head, tail, cnt, addr);
4645 return;
4646 }
4647
4648 if (USE_LOCKLESS_FAST_PATH()) {
4649 freelist = READ_ONCE(c->freelist);
4650
4651 set_freepointer(s, tail, freelist);
4652
4653 if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
4654 note_cmpxchg_failure("slab_free", s, tid);
4655 goto redo;
4656 }
4657 } else {
4658 /* Update the free list under the local lock */
4659 local_lock(&s->cpu_slab->lock);
4660 c = this_cpu_ptr(s->cpu_slab);
4661 if (unlikely(slab != c->slab)) {
4662 local_unlock(&s->cpu_slab->lock);
4663 goto redo;
4664 }
4665 tid = c->tid;
4666 freelist = c->freelist;
4667
4668 set_freepointer(s, tail, freelist);
4669 c->freelist = head;
4670 c->tid = next_tid(tid);
4671
4672 local_unlock(&s->cpu_slab->lock);
4673 }
4674 stat_add(s, FREE_FASTPATH, cnt);
4675 }
4676 #else /* CONFIG_SLUB_TINY */
do_slab_free(struct kmem_cache * s,struct slab * slab,void * head,void * tail,int cnt,unsigned long addr)4677 static void do_slab_free(struct kmem_cache *s,
4678 struct slab *slab, void *head, void *tail,
4679 int cnt, unsigned long addr)
4680 {
4681 __slab_free(s, slab, head, tail, cnt, addr);
4682 }
4683 #endif /* CONFIG_SLUB_TINY */
4684
4685 static __fastpath_inline
slab_free(struct kmem_cache * s,struct slab * slab,void * object,unsigned long addr)4686 void slab_free(struct kmem_cache *s, struct slab *slab, void *object,
4687 unsigned long addr)
4688 {
4689 memcg_slab_free_hook(s, slab, &object, 1);
4690 alloc_tagging_slab_free_hook(s, slab, &object, 1);
4691
4692 if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
4693 do_slab_free(s, slab, object, object, 1, addr);
4694
4695 trace_android_vh_slab_free(addr, s);
4696 }
4697
4698 #ifdef CONFIG_MEMCG
4699 /* Do not inline the rare memcg charging failed path into the allocation path */
4700 static noinline
memcg_alloc_abort_single(struct kmem_cache * s,void * object)4701 void memcg_alloc_abort_single(struct kmem_cache *s, void *object)
4702 {
4703 if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false)))
4704 do_slab_free(s, virt_to_slab(object), object, object, 1, _RET_IP_);
4705 }
4706 #endif
4707
4708 static __fastpath_inline
slab_free_bulk(struct kmem_cache * s,struct slab * slab,void * head,void * tail,void ** p,int cnt,unsigned long addr)4709 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head,
4710 void *tail, void **p, int cnt, unsigned long addr)
4711 {
4712 memcg_slab_free_hook(s, slab, p, cnt);
4713 alloc_tagging_slab_free_hook(s, slab, p, cnt);
4714 /*
4715 * With KASAN enabled slab_free_freelist_hook modifies the freelist
4716 * to remove objects, whose reuse must be delayed.
4717 */
4718 if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt)))
4719 do_slab_free(s, slab, head, tail, cnt, addr);
4720
4721 trace_android_vh_slab_free(addr, s);
4722
4723 }
4724
4725 #ifdef CONFIG_SLUB_RCU_DEBUG
slab_free_after_rcu_debug(struct rcu_head * rcu_head)4726 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head)
4727 {
4728 struct rcu_delayed_free *delayed_free =
4729 container_of(rcu_head, struct rcu_delayed_free, head);
4730 void *object = delayed_free->object;
4731 struct slab *slab = virt_to_slab(object);
4732 struct kmem_cache *s;
4733
4734 kfree(delayed_free);
4735
4736 if (WARN_ON(is_kfence_address(object)))
4737 return;
4738
4739 /* find the object and the cache again */
4740 if (WARN_ON(!slab))
4741 return;
4742 s = slab->slab_cache;
4743 if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU)))
4744 return;
4745
4746 /* resume freeing */
4747 if (slab_free_hook(s, object, slab_want_init_on_free(s), true))
4748 do_slab_free(s, slab, object, object, 1, _THIS_IP_);
4749 }
4750 #endif /* CONFIG_SLUB_RCU_DEBUG */
4751
4752 #ifdef CONFIG_KASAN_GENERIC
___cache_free(struct kmem_cache * cache,void * x,unsigned long addr)4753 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr)
4754 {
4755 do_slab_free(cache, virt_to_slab(x), x, x, 1, addr);
4756 }
4757 #endif
4758
virt_to_cache(const void * obj)4759 static inline struct kmem_cache *virt_to_cache(const void *obj)
4760 {
4761 struct slab *slab;
4762
4763 slab = virt_to_slab(obj);
4764 if (WARN_ONCE(!slab, "%s: Object is not a Slab page!\n", __func__))
4765 return NULL;
4766 return slab->slab_cache;
4767 }
4768
cache_from_obj(struct kmem_cache * s,void * x)4769 static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x)
4770 {
4771 struct kmem_cache *cachep;
4772
4773 if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
4774 !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS))
4775 return s;
4776
4777 cachep = virt_to_cache(x);
4778 if (WARN(cachep && cachep != s,
4779 "%s: Wrong slab cache. %s but object is from %s\n",
4780 __func__, s->name, cachep->name))
4781 print_tracking(cachep, x);
4782 return cachep;
4783 }
4784
4785 /**
4786 * kmem_cache_free - Deallocate an object
4787 * @s: The cache the allocation was from.
4788 * @x: The previously allocated object.
4789 *
4790 * Free an object which was previously allocated from this
4791 * cache.
4792 */
kmem_cache_free(struct kmem_cache * s,void * x)4793 void kmem_cache_free(struct kmem_cache *s, void *x)
4794 {
4795 s = cache_from_obj(s, x);
4796 if (!s)
4797 return;
4798 trace_kmem_cache_free(_RET_IP_, x, s);
4799 slab_free(s, virt_to_slab(x), x, _RET_IP_);
4800 }
4801 EXPORT_SYMBOL(kmem_cache_free);
4802
free_large_kmalloc(struct folio * folio,void * object)4803 static void free_large_kmalloc(struct folio *folio, void *object)
4804 {
4805 unsigned int order = folio_order(folio);
4806
4807 if (WARN_ON_ONCE(order == 0))
4808 pr_warn_once("object pointer: 0x%p\n", object);
4809
4810 kmemleak_free(object);
4811 kasan_kfree_large(object);
4812 kmsan_kfree_large(object);
4813
4814 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B,
4815 -(PAGE_SIZE << order));
4816 folio_put(folio);
4817 }
4818
4819 /**
4820 * kfree - free previously allocated memory
4821 * @object: pointer returned by kmalloc() or kmem_cache_alloc()
4822 *
4823 * If @object is NULL, no operation is performed.
4824 */
kfree(const void * object)4825 void kfree(const void *object)
4826 {
4827 struct folio *folio;
4828 struct slab *slab;
4829 struct kmem_cache *s;
4830 void *x = (void *)object;
4831 bool bypass = false;
4832
4833 trace_kfree(_RET_IP_, object);
4834
4835 if (unlikely(ZERO_OR_NULL_PTR(object)))
4836 return;
4837
4838 folio = virt_to_folio(object);
4839 if (unlikely(!folio_test_slab(folio))) {
4840 trace_android_vh_kfree_bypass(folio, object, &bypass);
4841 if (bypass)
4842 return;
4843 free_large_kmalloc(folio, (void *)object);
4844 return;
4845 }
4846
4847 slab = folio_slab(folio);
4848 s = slab->slab_cache;
4849 slab_free(s, slab, x, _RET_IP_);
4850 }
4851 EXPORT_SYMBOL(kfree);
4852
4853 struct detached_freelist {
4854 struct slab *slab;
4855 void *tail;
4856 void *freelist;
4857 int cnt;
4858 struct kmem_cache *s;
4859 };
4860
4861 /*
4862 * This function progressively scans the array with free objects (with
4863 * a limited look ahead) and extract objects belonging to the same
4864 * slab. It builds a detached freelist directly within the given
4865 * slab/objects. This can happen without any need for
4866 * synchronization, because the objects are owned by running process.
4867 * The freelist is build up as a single linked list in the objects.
4868 * The idea is, that this detached freelist can then be bulk
4869 * transferred to the real freelist(s), but only requiring a single
4870 * synchronization primitive. Look ahead in the array is limited due
4871 * to performance reasons.
4872 */
4873 static inline
build_detached_freelist(struct kmem_cache * s,size_t size,void ** p,struct detached_freelist * df)4874 int build_detached_freelist(struct kmem_cache *s, size_t size,
4875 void **p, struct detached_freelist *df)
4876 {
4877 int lookahead = 3;
4878 void *object;
4879 struct folio *folio;
4880 size_t same;
4881
4882 object = p[--size];
4883 folio = virt_to_folio(object);
4884 if (!s) {
4885 /* Handle kalloc'ed objects */
4886 if (unlikely(!folio_test_slab(folio))) {
4887 free_large_kmalloc(folio, object);
4888 df->slab = NULL;
4889 return size;
4890 }
4891 /* Derive kmem_cache from object */
4892 df->slab = folio_slab(folio);
4893 df->s = df->slab->slab_cache;
4894 } else {
4895 df->slab = folio_slab(folio);
4896 df->s = cache_from_obj(s, object); /* Support for memcg */
4897 }
4898
4899 /* Start new detached freelist */
4900 df->tail = object;
4901 df->freelist = object;
4902 df->cnt = 1;
4903
4904 if (is_kfence_address(object))
4905 return size;
4906
4907 set_freepointer(df->s, object, NULL);
4908
4909 same = size;
4910 while (size) {
4911 object = p[--size];
4912 /* df->slab is always set at this point */
4913 if (df->slab == virt_to_slab(object)) {
4914 /* Opportunity build freelist */
4915 set_freepointer(df->s, object, df->freelist);
4916 df->freelist = object;
4917 df->cnt++;
4918 same--;
4919 if (size != same)
4920 swap(p[size], p[same]);
4921 continue;
4922 }
4923
4924 /* Limit look ahead search */
4925 if (!--lookahead)
4926 break;
4927 }
4928
4929 return same;
4930 }
4931
4932 /*
4933 * Internal bulk free of objects that were not initialised by the post alloc
4934 * hooks and thus should not be processed by the free hooks
4935 */
__kmem_cache_free_bulk(struct kmem_cache * s,size_t size,void ** p)4936 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
4937 {
4938 if (!size)
4939 return;
4940
4941 do {
4942 struct detached_freelist df;
4943
4944 size = build_detached_freelist(s, size, p, &df);
4945 if (!df.slab)
4946 continue;
4947
4948 if (kfence_free(df.freelist))
4949 continue;
4950
4951 do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
4952 _RET_IP_);
4953 } while (likely(size));
4954 }
4955
4956 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_free_bulk(struct kmem_cache * s,size_t size,void ** p)4957 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
4958 {
4959 if (!size)
4960 return;
4961
4962 do {
4963 struct detached_freelist df;
4964
4965 size = build_detached_freelist(s, size, p, &df);
4966 if (!df.slab)
4967 continue;
4968
4969 slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size],
4970 df.cnt, _RET_IP_);
4971 } while (likely(size));
4972 }
4973 EXPORT_SYMBOL(kmem_cache_free_bulk);
4974
4975 #ifndef CONFIG_SLUB_TINY
4976 static inline
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)4977 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
4978 void **p)
4979 {
4980 struct kmem_cache_cpu *c;
4981 unsigned long irqflags;
4982 int i;
4983
4984 /*
4985 * Drain objects in the per cpu slab, while disabling local
4986 * IRQs, which protects against PREEMPT and interrupts
4987 * handlers invoking normal fastpath.
4988 */
4989 c = slub_get_cpu_ptr(s->cpu_slab);
4990 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
4991
4992 for (i = 0; i < size; i++) {
4993 void *object = kfence_alloc(s, s->object_size, flags);
4994
4995 if (unlikely(object)) {
4996 p[i] = object;
4997 continue;
4998 }
4999
5000 object = c->freelist;
5001 if (unlikely(!object)) {
5002 /*
5003 * We may have removed an object from c->freelist using
5004 * the fastpath in the previous iteration; in that case,
5005 * c->tid has not been bumped yet.
5006 * Since ___slab_alloc() may reenable interrupts while
5007 * allocating memory, we should bump c->tid now.
5008 */
5009 c->tid = next_tid(c->tid);
5010
5011 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
5012
5013 /*
5014 * Invoking slow path likely have side-effect
5015 * of re-populating per CPU c->freelist
5016 */
5017 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE,
5018 _RET_IP_, c, s->object_size);
5019 if (unlikely(!p[i]))
5020 goto error;
5021
5022 c = this_cpu_ptr(s->cpu_slab);
5023 maybe_wipe_obj_freeptr(s, p[i]);
5024
5025 local_lock_irqsave(&s->cpu_slab->lock, irqflags);
5026
5027 continue; /* goto for-loop */
5028 }
5029 c->freelist = get_freepointer(s, object);
5030 p[i] = object;
5031 maybe_wipe_obj_freeptr(s, p[i]);
5032 stat(s, ALLOC_FASTPATH);
5033 }
5034 c->tid = next_tid(c->tid);
5035 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags);
5036 slub_put_cpu_ptr(s->cpu_slab);
5037
5038 return i;
5039
5040 error:
5041 slub_put_cpu_ptr(s->cpu_slab);
5042 __kmem_cache_free_bulk(s, i, p);
5043 return 0;
5044
5045 }
5046 #else /* CONFIG_SLUB_TINY */
__kmem_cache_alloc_bulk(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)5047 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags,
5048 size_t size, void **p)
5049 {
5050 int i;
5051
5052 for (i = 0; i < size; i++) {
5053 void *object = kfence_alloc(s, s->object_size, flags);
5054
5055 if (unlikely(object)) {
5056 p[i] = object;
5057 continue;
5058 }
5059
5060 p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE,
5061 _RET_IP_, s->object_size);
5062 if (unlikely(!p[i]))
5063 goto error;
5064
5065 maybe_wipe_obj_freeptr(s, p[i]);
5066 }
5067
5068 return i;
5069
5070 error:
5071 __kmem_cache_free_bulk(s, i, p);
5072 return 0;
5073 }
5074 #endif /* CONFIG_SLUB_TINY */
5075
5076 /* Note that interrupts must be enabled when calling this function. */
kmem_cache_alloc_bulk_noprof(struct kmem_cache * s,gfp_t flags,size_t size,void ** p)5077 int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size,
5078 void **p)
5079 {
5080 int i;
5081
5082 if (!size)
5083 return 0;
5084
5085 s = slab_pre_alloc_hook(s, flags);
5086 if (unlikely(!s))
5087 return 0;
5088
5089 i = __kmem_cache_alloc_bulk(s, flags, size, p);
5090 if (unlikely(i == 0))
5091 return 0;
5092
5093 /*
5094 * memcg and kmem_cache debug support and memory initialization.
5095 * Done outside of the IRQ disabled fastpath loop.
5096 */
5097 if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p,
5098 slab_want_init_on_alloc(flags, s), s->object_size))) {
5099 return 0;
5100 }
5101 return i;
5102 }
5103 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
5104
5105
5106 /*
5107 * Object placement in a slab is made very easy because we always start at
5108 * offset 0. If we tune the size of the object to the alignment then we can
5109 * get the required alignment by putting one properly sized object after
5110 * another.
5111 *
5112 * Notice that the allocation order determines the sizes of the per cpu
5113 * caches. Each processor has always one slab available for allocations.
5114 * Increasing the allocation order reduces the number of times that slabs
5115 * must be moved on and off the partial lists and is therefore a factor in
5116 * locking overhead.
5117 */
5118
5119 /*
5120 * Minimum / Maximum order of slab pages. This influences locking overhead
5121 * and slab fragmentation. A higher order reduces the number of partial slabs
5122 * and increases the number of allocations possible without having to
5123 * take the list_lock.
5124 */
5125 static unsigned int slub_min_order;
5126 static unsigned int slub_max_order =
5127 IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER;
5128 static unsigned int slub_min_objects;
5129
5130 /*
5131 * Calculate the order of allocation given an slab object size.
5132 *
5133 * The order of allocation has significant impact on performance and other
5134 * system components. Generally order 0 allocations should be preferred since
5135 * order 0 does not cause fragmentation in the page allocator. Larger objects
5136 * be problematic to put into order 0 slabs because there may be too much
5137 * unused space left. We go to a higher order if more than 1/16th of the slab
5138 * would be wasted.
5139 *
5140 * In order to reach satisfactory performance we must ensure that a minimum
5141 * number of objects is in one slab. Otherwise we may generate too much
5142 * activity on the partial lists which requires taking the list_lock. This is
5143 * less a concern for large slabs though which are rarely used.
5144 *
5145 * slab_max_order specifies the order where we begin to stop considering the
5146 * number of objects in a slab as critical. If we reach slab_max_order then
5147 * we try to keep the page order as low as possible. So we accept more waste
5148 * of space in favor of a small page order.
5149 *
5150 * Higher order allocations also allow the placement of more objects in a
5151 * slab and thereby reduce object handling overhead. If the user has
5152 * requested a higher minimum order then we start with that one instead of
5153 * the smallest order which will fit the object.
5154 */
calc_slab_order(unsigned int size,unsigned int min_order,unsigned int max_order,unsigned int fract_leftover)5155 static inline unsigned int calc_slab_order(unsigned int size,
5156 unsigned int min_order, unsigned int max_order,
5157 unsigned int fract_leftover)
5158 {
5159 unsigned int order;
5160
5161 for (order = min_order; order <= max_order; order++) {
5162
5163 unsigned int slab_size = (unsigned int)PAGE_SIZE << order;
5164 unsigned int rem;
5165
5166 rem = slab_size % size;
5167
5168 if (rem <= slab_size / fract_leftover)
5169 break;
5170 }
5171
5172 return order;
5173 }
5174
calculate_order(unsigned int size)5175 static inline int calculate_order(unsigned int size)
5176 {
5177 unsigned int order;
5178 unsigned int min_objects;
5179 unsigned int max_objects;
5180 unsigned int min_order;
5181
5182 min_objects = slub_min_objects;
5183 if (!min_objects) {
5184 /*
5185 * Some architectures will only update present cpus when
5186 * onlining them, so don't trust the number if it's just 1. But
5187 * we also don't want to use nr_cpu_ids always, as on some other
5188 * architectures, there can be many possible cpus, but never
5189 * onlined. Here we compromise between trying to avoid too high
5190 * order on systems that appear larger than they are, and too
5191 * low order on systems that appear smaller than they are.
5192 */
5193 unsigned int nr_cpus = num_present_cpus();
5194 if (nr_cpus <= 1)
5195 nr_cpus = nr_cpu_ids;
5196 min_objects = 4 * (fls(nr_cpus) + 1);
5197 }
5198 /* min_objects can't be 0 because get_order(0) is undefined */
5199 max_objects = max(order_objects(slub_max_order, size), 1U);
5200 min_objects = min(min_objects, max_objects);
5201
5202 min_order = max_t(unsigned int, slub_min_order,
5203 get_order(min_objects * size));
5204 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE)
5205 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
5206
5207 /*
5208 * Attempt to find best configuration for a slab. This works by first
5209 * attempting to generate a layout with the best possible configuration
5210 * and backing off gradually.
5211 *
5212 * We start with accepting at most 1/16 waste and try to find the
5213 * smallest order from min_objects-derived/slab_min_order up to
5214 * slab_max_order that will satisfy the constraint. Note that increasing
5215 * the order can only result in same or less fractional waste, not more.
5216 *
5217 * If that fails, we increase the acceptable fraction of waste and try
5218 * again. The last iteration with fraction of 1/2 would effectively
5219 * accept any waste and give us the order determined by min_objects, as
5220 * long as at least single object fits within slab_max_order.
5221 */
5222 for (unsigned int fraction = 16; fraction > 1; fraction /= 2) {
5223 order = calc_slab_order(size, min_order, slub_max_order,
5224 fraction);
5225 if (order <= slub_max_order)
5226 return order;
5227 }
5228
5229 /*
5230 * Doh this slab cannot be placed using slab_max_order.
5231 */
5232 order = get_order(size);
5233 if (order <= MAX_PAGE_ORDER)
5234 return order;
5235 return -ENOSYS;
5236 }
5237
5238 static void
init_kmem_cache_node(struct kmem_cache_node * n)5239 init_kmem_cache_node(struct kmem_cache_node *n)
5240 {
5241 n->nr_partial = 0;
5242 spin_lock_init(&n->list_lock);
5243 INIT_LIST_HEAD(&n->partial);
5244 #ifdef CONFIG_SLUB_DEBUG
5245 atomic_long_set(&n->nr_slabs, 0);
5246 atomic_long_set(&n->total_objects, 0);
5247 INIT_LIST_HEAD(&n->full);
5248 #endif
5249 }
5250
5251 #ifndef CONFIG_SLUB_TINY
alloc_kmem_cache_cpus(struct kmem_cache * s)5252 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
5253 {
5254 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
5255 NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH *
5256 sizeof(struct kmem_cache_cpu));
5257
5258 /*
5259 * Must align to double word boundary for the double cmpxchg
5260 * instructions to work; see __pcpu_double_call_return_bool().
5261 */
5262 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
5263 2 * sizeof(void *));
5264
5265 if (!s->cpu_slab)
5266 return 0;
5267
5268 init_kmem_cache_cpus(s);
5269
5270 return 1;
5271 }
5272 #else
alloc_kmem_cache_cpus(struct kmem_cache * s)5273 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
5274 {
5275 return 1;
5276 }
5277 #endif /* CONFIG_SLUB_TINY */
5278
5279 static struct kmem_cache *kmem_cache_node;
5280
5281 /*
5282 * No kmalloc_node yet so do it by hand. We know that this is the first
5283 * slab on the node for this slabcache. There are no concurrent accesses
5284 * possible.
5285 *
5286 * Note that this function only works on the kmem_cache_node
5287 * when allocating for the kmem_cache_node. This is used for bootstrapping
5288 * memory on a fresh node that has no slab structures yet.
5289 */
early_kmem_cache_node_alloc(int node)5290 static void early_kmem_cache_node_alloc(int node)
5291 {
5292 struct slab *slab;
5293 struct kmem_cache_node *n;
5294
5295 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
5296
5297 slab = new_slab(kmem_cache_node, GFP_NOWAIT, node);
5298
5299 BUG_ON(!slab);
5300 if (slab_nid(slab) != node) {
5301 pr_err("SLUB: Unable to allocate memory from node %d\n", node);
5302 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
5303 }
5304
5305 n = slab->freelist;
5306 BUG_ON(!n);
5307 #ifdef CONFIG_SLUB_DEBUG
5308 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
5309 #endif
5310 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
5311 slab->freelist = get_freepointer(kmem_cache_node, n);
5312 slab->inuse = 1;
5313 kmem_cache_node->node[node] = n;
5314 init_kmem_cache_node(n);
5315 inc_slabs_node(kmem_cache_node, node, slab->objects);
5316
5317 /*
5318 * No locks need to be taken here as it has just been
5319 * initialized and there is no concurrent access.
5320 */
5321 __add_partial(n, slab, DEACTIVATE_TO_HEAD);
5322 }
5323
free_kmem_cache_nodes(struct kmem_cache * s)5324 static void free_kmem_cache_nodes(struct kmem_cache *s)
5325 {
5326 int node;
5327 struct kmem_cache_node *n;
5328
5329 for_each_kmem_cache_node(s, node, n) {
5330 s->node[node] = NULL;
5331 kmem_cache_free(kmem_cache_node, n);
5332 }
5333 }
5334
__kmem_cache_release(struct kmem_cache * s)5335 void __kmem_cache_release(struct kmem_cache *s)
5336 {
5337 cache_random_seq_destroy(s);
5338 #ifndef CONFIG_SLUB_TINY
5339 free_percpu(s->cpu_slab);
5340 #endif
5341 free_kmem_cache_nodes(s);
5342 }
5343
init_kmem_cache_nodes(struct kmem_cache * s)5344 static int init_kmem_cache_nodes(struct kmem_cache *s)
5345 {
5346 int node;
5347
5348 for_each_node_mask(node, slab_nodes) {
5349 struct kmem_cache_node *n;
5350
5351 if (slab_state == DOWN) {
5352 early_kmem_cache_node_alloc(node);
5353 continue;
5354 }
5355 n = kmem_cache_alloc_node(kmem_cache_node,
5356 GFP_KERNEL, node);
5357
5358 if (!n) {
5359 free_kmem_cache_nodes(s);
5360 return 0;
5361 }
5362
5363 init_kmem_cache_node(n);
5364 s->node[node] = n;
5365 }
5366 return 1;
5367 }
5368
set_cpu_partial(struct kmem_cache * s)5369 static void set_cpu_partial(struct kmem_cache *s)
5370 {
5371 #ifdef CONFIG_SLUB_CPU_PARTIAL
5372 unsigned int nr_objects;
5373
5374 /*
5375 * cpu_partial determined the maximum number of objects kept in the
5376 * per cpu partial lists of a processor.
5377 *
5378 * Per cpu partial lists mainly contain slabs that just have one
5379 * object freed. If they are used for allocation then they can be
5380 * filled up again with minimal effort. The slab will never hit the
5381 * per node partial lists and therefore no locking will be required.
5382 *
5383 * For backwards compatibility reasons, this is determined as number
5384 * of objects, even though we now limit maximum number of pages, see
5385 * slub_set_cpu_partial()
5386 */
5387 if (!kmem_cache_has_cpu_partial(s))
5388 nr_objects = 0;
5389 else if (s->size >= PAGE_SIZE)
5390 nr_objects = 6;
5391 else if (s->size >= 1024)
5392 nr_objects = 24;
5393 else if (s->size >= 256)
5394 nr_objects = 52;
5395 else
5396 nr_objects = 120;
5397
5398 slub_set_cpu_partial(s, nr_objects);
5399 #endif
5400 }
5401
5402 /*
5403 * calculate_sizes() determines the order and the distribution of data within
5404 * a slab object.
5405 */
calculate_sizes(struct kmem_cache_args * args,struct kmem_cache * s)5406 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
5407 {
5408 slab_flags_t flags = s->flags;
5409 unsigned int size = s->object_size;
5410 unsigned int order;
5411
5412 /*
5413 * Round up object size to the next word boundary. We can only
5414 * place the free pointer at word boundaries and this determines
5415 * the possible location of the free pointer.
5416 */
5417 size = ALIGN(size, sizeof(void *));
5418
5419 #ifdef CONFIG_SLUB_DEBUG
5420 /*
5421 * Determine if we can poison the object itself. If the user of
5422 * the slab may touch the object after free or before allocation
5423 * then we should never poison the object itself.
5424 */
5425 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
5426 !s->ctor)
5427 s->flags |= __OBJECT_POISON;
5428 else
5429 s->flags &= ~__OBJECT_POISON;
5430
5431
5432 /*
5433 * If we are Redzoning then check if there is some space between the
5434 * end of the object and the free pointer. If not then add an
5435 * additional word to have some bytes to store Redzone information.
5436 */
5437 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
5438 size += sizeof(void *);
5439 #endif
5440
5441 /*
5442 * With that we have determined the number of bytes in actual use
5443 * by the object and redzoning.
5444 */
5445 s->inuse = size;
5446
5447 if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
5448 (flags & SLAB_POISON) || s->ctor ||
5449 ((flags & SLAB_RED_ZONE) &&
5450 (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) {
5451 /*
5452 * Relocate free pointer after the object if it is not
5453 * permitted to overwrite the first word of the object on
5454 * kmem_cache_free.
5455 *
5456 * This is the case if we do RCU, have a constructor or
5457 * destructor, are poisoning the objects, or are
5458 * redzoning an object smaller than sizeof(void *) or are
5459 * redzoning an object with slub_debug_orig_size() enabled,
5460 * in which case the right redzone may be extended.
5461 *
5462 * The assumption that s->offset >= s->inuse means free
5463 * pointer is outside of the object is used in the
5464 * freeptr_outside_object() function. If that is no
5465 * longer true, the function needs to be modified.
5466 */
5467 s->offset = size;
5468 size += sizeof(void *);
5469 } else if ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) {
5470 s->offset = args->freeptr_offset;
5471 } else {
5472 /*
5473 * Store freelist pointer near middle of object to keep
5474 * it away from the edges of the object to avoid small
5475 * sized over/underflows from neighboring allocations.
5476 */
5477 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
5478 }
5479
5480 #ifdef CONFIG_SLUB_DEBUG
5481 if (flags & SLAB_STORE_USER) {
5482 /*
5483 * Need to store information about allocs and frees after
5484 * the object.
5485 */
5486 size += 2 * sizeof(struct track);
5487
5488 /* Save the original kmalloc request size */
5489 if (flags & SLAB_KMALLOC)
5490 size += sizeof(unsigned int);
5491 }
5492 #endif
5493
5494 kasan_cache_create(s, &size, &s->flags);
5495 #ifdef CONFIG_SLUB_DEBUG
5496 if (flags & SLAB_RED_ZONE) {
5497 /*
5498 * Add some empty padding so that we can catch
5499 * overwrites from earlier objects rather than let
5500 * tracking information or the free pointer be
5501 * corrupted if a user writes before the start
5502 * of the object.
5503 */
5504 size += sizeof(void *);
5505
5506 s->red_left_pad = sizeof(void *);
5507 s->red_left_pad = ALIGN(s->red_left_pad, s->align);
5508 size += s->red_left_pad;
5509 }
5510 #endif
5511
5512 /*
5513 * SLUB stores one object immediately after another beginning from
5514 * offset 0. In order to align the objects we have to simply size
5515 * each object to conform to the alignment.
5516 */
5517 size = ALIGN(size, s->align);
5518 s->size = size;
5519 s->reciprocal_size = reciprocal_value(size);
5520 order = calculate_order(size);
5521
5522 if ((int)order < 0)
5523 return 0;
5524
5525 s->allocflags = __GFP_COMP;
5526
5527 if (s->flags & SLAB_CACHE_DMA)
5528 s->allocflags |= GFP_DMA;
5529
5530 if (s->flags & SLAB_CACHE_DMA32)
5531 s->allocflags |= GFP_DMA32;
5532
5533 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5534 s->allocflags |= __GFP_RECLAIMABLE;
5535
5536 /*
5537 * Determine the number of objects per slab
5538 */
5539 s->oo = oo_make(order, size);
5540 s->min = oo_make(get_order(size), size);
5541
5542 return !!oo_objects(s->oo);
5543 }
5544
list_slab_objects(struct kmem_cache * s,struct slab * slab)5545 static void list_slab_objects(struct kmem_cache *s, struct slab *slab)
5546 {
5547 #ifdef CONFIG_SLUB_DEBUG
5548 void *addr = slab_address(slab);
5549 void *p;
5550
5551 if (!slab_add_kunit_errors())
5552 slab_bug(s, "Objects remaining on __kmem_cache_shutdown()");
5553
5554 spin_lock(&object_map_lock);
5555 __fill_map(object_map, s, slab);
5556
5557 for_each_object(p, s, addr, slab->objects) {
5558
5559 if (!test_bit(__obj_to_index(s, addr, p), object_map)) {
5560 if (slab_add_kunit_errors())
5561 continue;
5562 pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
5563 print_tracking(s, p);
5564 }
5565 }
5566 spin_unlock(&object_map_lock);
5567
5568 __slab_err(slab);
5569 #endif
5570 }
5571
5572 /*
5573 * Attempt to free all partial slabs on a node.
5574 * This is called from __kmem_cache_shutdown(). We must take list_lock
5575 * because sysfs file might still access partial list after the shutdowning.
5576 */
free_partial(struct kmem_cache * s,struct kmem_cache_node * n)5577 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
5578 {
5579 LIST_HEAD(discard);
5580 struct slab *slab, *h;
5581
5582 BUG_ON(irqs_disabled());
5583 spin_lock_irq(&n->list_lock);
5584 list_for_each_entry_safe(slab, h, &n->partial, slab_list) {
5585 if (!slab->inuse) {
5586 remove_partial(n, slab);
5587 list_add(&slab->slab_list, &discard);
5588 } else {
5589 list_slab_objects(s, slab);
5590 }
5591 }
5592 spin_unlock_irq(&n->list_lock);
5593
5594 list_for_each_entry_safe(slab, h, &discard, slab_list)
5595 discard_slab(s, slab);
5596 }
5597
__kmem_cache_empty(struct kmem_cache * s)5598 bool __kmem_cache_empty(struct kmem_cache *s)
5599 {
5600 int node;
5601 struct kmem_cache_node *n;
5602
5603 for_each_kmem_cache_node(s, node, n)
5604 if (n->nr_partial || node_nr_slabs(n))
5605 return false;
5606 return true;
5607 }
5608
5609 /*
5610 * Release all resources used by a slab cache.
5611 */
__kmem_cache_shutdown(struct kmem_cache * s)5612 int __kmem_cache_shutdown(struct kmem_cache *s)
5613 {
5614 int node;
5615 struct kmem_cache_node *n;
5616
5617 flush_all_cpus_locked(s);
5618 /* Attempt to free all objects */
5619 for_each_kmem_cache_node(s, node, n) {
5620 free_partial(s, n);
5621 if (n->nr_partial || node_nr_slabs(n))
5622 return 1;
5623 }
5624 return 0;
5625 }
5626
5627 #ifdef CONFIG_PRINTK
__kmem_obj_info(struct kmem_obj_info * kpp,void * object,struct slab * slab)5628 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
5629 {
5630 void *base;
5631 int __maybe_unused i;
5632 unsigned int objnr;
5633 void *objp;
5634 void *objp0;
5635 struct kmem_cache *s = slab->slab_cache;
5636 struct track __maybe_unused *trackp;
5637
5638 kpp->kp_ptr = object;
5639 kpp->kp_slab = slab;
5640 kpp->kp_slab_cache = s;
5641 base = slab_address(slab);
5642 objp0 = kasan_reset_tag(object);
5643 #ifdef CONFIG_SLUB_DEBUG
5644 objp = restore_red_left(s, objp0);
5645 #else
5646 objp = objp0;
5647 #endif
5648 objnr = obj_to_index(s, slab, objp);
5649 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp);
5650 objp = base + s->size * objnr;
5651 kpp->kp_objp = objp;
5652 if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size
5653 || (objp - base) % s->size) ||
5654 !(s->flags & SLAB_STORE_USER))
5655 return;
5656 #ifdef CONFIG_SLUB_DEBUG
5657 objp = fixup_red_left(s, objp);
5658 trackp = get_track(s, objp, TRACK_ALLOC);
5659 kpp->kp_ret = (void *)trackp->addr;
5660 #ifdef CONFIG_STACKDEPOT
5661 {
5662 depot_stack_handle_t handle;
5663 unsigned long *entries;
5664 unsigned int nr_entries;
5665
5666 handle = READ_ONCE(trackp->handle);
5667 if (handle) {
5668 nr_entries = stack_depot_fetch(handle, &entries);
5669 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
5670 kpp->kp_stack[i] = (void *)entries[i];
5671 }
5672
5673 trackp = get_track(s, objp, TRACK_FREE);
5674 handle = READ_ONCE(trackp->handle);
5675 if (handle) {
5676 nr_entries = stack_depot_fetch(handle, &entries);
5677 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++)
5678 kpp->kp_free_stack[i] = (void *)entries[i];
5679 }
5680 }
5681 #endif
5682 #endif
5683 }
5684 #endif
5685
5686 /********************************************************************
5687 * Kmalloc subsystem
5688 *******************************************************************/
5689
setup_slub_min_order(char * str)5690 static int __init setup_slub_min_order(char *str)
5691 {
5692 get_option(&str, (int *)&slub_min_order);
5693
5694 if (slub_min_order > slub_max_order)
5695 slub_max_order = slub_min_order;
5696
5697 return 1;
5698 }
5699
5700 __setup("slab_min_order=", setup_slub_min_order);
5701 __setup_param("slub_min_order=", slub_min_order, setup_slub_min_order, 0);
5702
5703
setup_slub_max_order(char * str)5704 static int __init setup_slub_max_order(char *str)
5705 {
5706 get_option(&str, (int *)&slub_max_order);
5707 slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER);
5708
5709 if (slub_min_order > slub_max_order)
5710 slub_min_order = slub_max_order;
5711
5712 return 1;
5713 }
5714
5715 __setup("slab_max_order=", setup_slub_max_order);
5716 __setup_param("slub_max_order=", slub_max_order, setup_slub_max_order, 0);
5717
setup_slub_min_objects(char * str)5718 static int __init setup_slub_min_objects(char *str)
5719 {
5720 get_option(&str, (int *)&slub_min_objects);
5721
5722 return 1;
5723 }
5724
5725 __setup("slab_min_objects=", setup_slub_min_objects);
5726 __setup_param("slub_min_objects=", slub_min_objects, setup_slub_min_objects, 0);
5727
5728 #ifdef CONFIG_HARDENED_USERCOPY
5729 /*
5730 * Rejects incorrectly sized objects and objects that are to be copied
5731 * to/from userspace but do not fall entirely within the containing slab
5732 * cache's usercopy region.
5733 *
5734 * Returns NULL if check passes, otherwise const char * to name of cache
5735 * to indicate an error.
5736 */
__check_heap_object(const void * ptr,unsigned long n,const struct slab * slab,bool to_user)5737 void __check_heap_object(const void *ptr, unsigned long n,
5738 const struct slab *slab, bool to_user)
5739 {
5740 struct kmem_cache *s;
5741 unsigned int offset;
5742 bool is_kfence = is_kfence_address(ptr);
5743
5744 ptr = kasan_reset_tag(ptr);
5745
5746 /* Find object and usable object size. */
5747 s = slab->slab_cache;
5748
5749 /* Reject impossible pointers. */
5750 if (ptr < slab_address(slab))
5751 usercopy_abort("SLUB object not in SLUB page?!", NULL,
5752 to_user, 0, n);
5753
5754 /* Find offset within object. */
5755 if (is_kfence)
5756 offset = ptr - kfence_object_start(ptr);
5757 else
5758 offset = (ptr - slab_address(slab)) % s->size;
5759
5760 /* Adjust for redzone and reject if within the redzone. */
5761 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) {
5762 if (offset < s->red_left_pad)
5763 usercopy_abort("SLUB object in left red zone",
5764 s->name, to_user, offset, n);
5765 offset -= s->red_left_pad;
5766 }
5767
5768 /* Allow address range falling entirely within usercopy region. */
5769 if (offset >= s->useroffset &&
5770 offset - s->useroffset <= s->usersize &&
5771 n <= s->useroffset - offset + s->usersize)
5772 return;
5773
5774 usercopy_abort("SLUB object", s->name, to_user, offset, n);
5775 }
5776 #endif /* CONFIG_HARDENED_USERCOPY */
5777
5778 #define SHRINK_PROMOTE_MAX 32
5779
5780 /*
5781 * kmem_cache_shrink discards empty slabs and promotes the slabs filled
5782 * up most to the head of the partial lists. New allocations will then
5783 * fill those up and thus they can be removed from the partial lists.
5784 *
5785 * The slabs with the least items are placed last. This results in them
5786 * being allocated from last increasing the chance that the last objects
5787 * are freed in them.
5788 */
__kmem_cache_do_shrink(struct kmem_cache * s)5789 static int __kmem_cache_do_shrink(struct kmem_cache *s)
5790 {
5791 int node;
5792 int i;
5793 struct kmem_cache_node *n;
5794 struct slab *slab;
5795 struct slab *t;
5796 struct list_head discard;
5797 struct list_head promote[SHRINK_PROMOTE_MAX];
5798 unsigned long flags;
5799 int ret = 0;
5800
5801 for_each_kmem_cache_node(s, node, n) {
5802 INIT_LIST_HEAD(&discard);
5803 for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
5804 INIT_LIST_HEAD(promote + i);
5805
5806 spin_lock_irqsave(&n->list_lock, flags);
5807
5808 /*
5809 * Build lists of slabs to discard or promote.
5810 *
5811 * Note that concurrent frees may occur while we hold the
5812 * list_lock. slab->inuse here is the upper limit.
5813 */
5814 list_for_each_entry_safe(slab, t, &n->partial, slab_list) {
5815 int free = slab->objects - slab->inuse;
5816
5817 /* Do not reread slab->inuse */
5818 barrier();
5819
5820 /* We do not keep full slabs on the list */
5821 BUG_ON(free <= 0);
5822
5823 if (free == slab->objects) {
5824 list_move(&slab->slab_list, &discard);
5825 slab_clear_node_partial(slab);
5826 n->nr_partial--;
5827 dec_slabs_node(s, node, slab->objects);
5828 } else if (free <= SHRINK_PROMOTE_MAX)
5829 list_move(&slab->slab_list, promote + free - 1);
5830 }
5831
5832 /*
5833 * Promote the slabs filled up most to the head of the
5834 * partial list.
5835 */
5836 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
5837 list_splice(promote + i, &n->partial);
5838
5839 spin_unlock_irqrestore(&n->list_lock, flags);
5840
5841 /* Release empty slabs */
5842 list_for_each_entry_safe(slab, t, &discard, slab_list)
5843 free_slab(s, slab);
5844
5845 if (node_nr_slabs(n))
5846 ret = 1;
5847 }
5848
5849 return ret;
5850 }
5851
__kmem_cache_shrink(struct kmem_cache * s)5852 int __kmem_cache_shrink(struct kmem_cache *s)
5853 {
5854 flush_all(s);
5855 return __kmem_cache_do_shrink(s);
5856 }
5857
slab_mem_going_offline_callback(void * arg)5858 static int slab_mem_going_offline_callback(void *arg)
5859 {
5860 struct kmem_cache *s;
5861
5862 mutex_lock(&slab_mutex);
5863 list_for_each_entry(s, &slab_caches, list) {
5864 flush_all_cpus_locked(s);
5865 __kmem_cache_do_shrink(s);
5866 }
5867 mutex_unlock(&slab_mutex);
5868
5869 return 0;
5870 }
5871
slab_mem_offline_callback(void * arg)5872 static void slab_mem_offline_callback(void *arg)
5873 {
5874 struct memory_notify *marg = arg;
5875 int offline_node;
5876
5877 offline_node = marg->status_change_nid_normal;
5878
5879 /*
5880 * If the node still has available memory. we need kmem_cache_node
5881 * for it yet.
5882 */
5883 if (offline_node < 0)
5884 return;
5885
5886 mutex_lock(&slab_mutex);
5887 node_clear(offline_node, slab_nodes);
5888 /*
5889 * We no longer free kmem_cache_node structures here, as it would be
5890 * racy with all get_node() users, and infeasible to protect them with
5891 * slab_mutex.
5892 */
5893 mutex_unlock(&slab_mutex);
5894 }
5895
slab_mem_going_online_callback(void * arg)5896 static int slab_mem_going_online_callback(void *arg)
5897 {
5898 struct kmem_cache_node *n;
5899 struct kmem_cache *s;
5900 struct memory_notify *marg = arg;
5901 int nid = marg->status_change_nid_normal;
5902 int ret = 0;
5903
5904 /*
5905 * If the node's memory is already available, then kmem_cache_node is
5906 * already created. Nothing to do.
5907 */
5908 if (nid < 0)
5909 return 0;
5910
5911 /*
5912 * We are bringing a node online. No memory is available yet. We must
5913 * allocate a kmem_cache_node structure in order to bring the node
5914 * online.
5915 */
5916 mutex_lock(&slab_mutex);
5917 list_for_each_entry(s, &slab_caches, list) {
5918 /*
5919 * The structure may already exist if the node was previously
5920 * onlined and offlined.
5921 */
5922 if (get_node(s, nid))
5923 continue;
5924 /*
5925 * XXX: kmem_cache_alloc_node will fallback to other nodes
5926 * since memory is not yet available from the node that
5927 * is brought up.
5928 */
5929 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
5930 if (!n) {
5931 ret = -ENOMEM;
5932 goto out;
5933 }
5934 init_kmem_cache_node(n);
5935 s->node[nid] = n;
5936 }
5937 /*
5938 * Any cache created after this point will also have kmem_cache_node
5939 * initialized for the new node.
5940 */
5941 node_set(nid, slab_nodes);
5942 out:
5943 mutex_unlock(&slab_mutex);
5944 return ret;
5945 }
5946
slab_memory_callback(struct notifier_block * self,unsigned long action,void * arg)5947 static int slab_memory_callback(struct notifier_block *self,
5948 unsigned long action, void *arg)
5949 {
5950 int ret = 0;
5951
5952 switch (action) {
5953 case MEM_GOING_ONLINE:
5954 ret = slab_mem_going_online_callback(arg);
5955 break;
5956 case MEM_GOING_OFFLINE:
5957 ret = slab_mem_going_offline_callback(arg);
5958 break;
5959 case MEM_OFFLINE:
5960 case MEM_CANCEL_ONLINE:
5961 slab_mem_offline_callback(arg);
5962 break;
5963 case MEM_ONLINE:
5964 case MEM_CANCEL_OFFLINE:
5965 break;
5966 }
5967 if (ret)
5968 ret = notifier_from_errno(ret);
5969 else
5970 ret = NOTIFY_OK;
5971 return ret;
5972 }
5973
5974 /********************************************************************
5975 * Basic setup of slabs
5976 *******************************************************************/
5977
5978 /*
5979 * Used for early kmem_cache structures that were allocated using
5980 * the page allocator. Allocate them properly then fix up the pointers
5981 * that may be pointing to the wrong kmem_cache structure.
5982 */
5983
bootstrap(struct kmem_cache * static_cache)5984 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache)
5985 {
5986 int node;
5987 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT);
5988 struct kmem_cache_node *n;
5989
5990 memcpy(s, static_cache, kmem_cache->object_size);
5991
5992 /*
5993 * This runs very early, and only the boot processor is supposed to be
5994 * up. Even if it weren't true, IRQs are not up so we couldn't fire
5995 * IPIs around.
5996 */
5997 __flush_cpu_slab(s, smp_processor_id());
5998 for_each_kmem_cache_node(s, node, n) {
5999 struct slab *p;
6000
6001 list_for_each_entry(p, &n->partial, slab_list)
6002 p->slab_cache = s;
6003
6004 #ifdef CONFIG_SLUB_DEBUG
6005 list_for_each_entry(p, &n->full, slab_list)
6006 p->slab_cache = s;
6007 #endif
6008 }
6009 list_add(&s->list, &slab_caches);
6010 return s;
6011 }
6012
kmem_cache_init(void)6013 void __init kmem_cache_init(void)
6014 {
6015 static __initdata struct kmem_cache boot_kmem_cache,
6016 boot_kmem_cache_node;
6017 int node;
6018
6019 if (debug_guardpage_minorder())
6020 slub_max_order = 0;
6021
6022 /* Print slub debugging pointers without hashing */
6023 if (__slub_debug_enabled())
6024 no_hash_pointers_enable(NULL);
6025
6026 kmem_cache_node = &boot_kmem_cache_node;
6027 kmem_cache = &boot_kmem_cache;
6028
6029 /*
6030 * Initialize the nodemask for which we will allocate per node
6031 * structures. Here we don't need taking slab_mutex yet.
6032 */
6033 for_each_node_state(node, N_NORMAL_MEMORY)
6034 node_set(node, slab_nodes);
6035
6036 create_boot_cache(kmem_cache_node, "kmem_cache_node",
6037 sizeof(struct kmem_cache_node),
6038 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
6039
6040 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
6041
6042 /* Able to allocate the per node structures */
6043 slab_state = PARTIAL;
6044
6045 create_boot_cache(kmem_cache, "kmem_cache",
6046 offsetof(struct kmem_cache, node) +
6047 nr_node_ids * sizeof(struct kmem_cache_node *),
6048 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0);
6049
6050 kmem_cache = bootstrap(&boot_kmem_cache);
6051 kmem_cache_node = bootstrap(&boot_kmem_cache_node);
6052
6053 /* Now we can use the kmem_cache to allocate kmalloc slabs */
6054 setup_kmalloc_cache_index_table();
6055 create_kmalloc_caches();
6056
6057 /* Setup random freelists for each cache */
6058 init_freelist_randomization();
6059
6060 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL,
6061 slub_cpu_dead);
6062
6063 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n",
6064 cache_line_size(),
6065 slub_min_order, slub_max_order, slub_min_objects,
6066 nr_cpu_ids, nr_node_ids);
6067 }
6068
kmem_cache_init_late(void)6069 void __init kmem_cache_init_late(void)
6070 {
6071 #ifndef CONFIG_SLUB_TINY
6072 flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0);
6073 WARN_ON(!flushwq);
6074 #endif
6075 }
6076
6077 struct kmem_cache *
__kmem_cache_alias(const char * name,unsigned int size,unsigned int align,slab_flags_t flags,void (* ctor)(void *))6078 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align,
6079 slab_flags_t flags, void (*ctor)(void *))
6080 {
6081 struct kmem_cache *s;
6082
6083 s = find_mergeable(size, align, flags, name, ctor);
6084 if (s) {
6085 if (sysfs_slab_alias(s, name))
6086 return NULL;
6087
6088 s->refcount++;
6089
6090 /*
6091 * Adjust the object sizes so that we clear
6092 * the complete object on kzalloc.
6093 */
6094 s->object_size = max(s->object_size, size);
6095 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
6096 }
6097
6098 return s;
6099 }
6100
do_kmem_cache_create(struct kmem_cache * s,const char * name,unsigned int size,struct kmem_cache_args * args,slab_flags_t flags)6101 int do_kmem_cache_create(struct kmem_cache *s, const char *name,
6102 unsigned int size, struct kmem_cache_args *args,
6103 slab_flags_t flags)
6104 {
6105 int err = -EINVAL;
6106
6107 s->name = name;
6108 s->size = s->object_size = size;
6109
6110 s->flags = kmem_cache_flags(flags, s->name);
6111 #ifdef CONFIG_SLAB_FREELIST_HARDENED
6112 s->random = get_random_long();
6113 #endif
6114 s->align = args->align;
6115 s->ctor = args->ctor;
6116 #ifdef CONFIG_HARDENED_USERCOPY
6117 s->useroffset = args->useroffset;
6118 s->usersize = args->usersize;
6119 #endif
6120
6121 if (!calculate_sizes(args, s))
6122 goto out;
6123 if (disable_higher_order_debug) {
6124 /*
6125 * Disable debugging flags that store metadata if the min slab
6126 * order increased.
6127 */
6128 if (get_order(s->size) > get_order(s->object_size)) {
6129 s->flags &= ~DEBUG_METADATA_FLAGS;
6130 s->offset = 0;
6131 if (!calculate_sizes(args, s))
6132 goto out;
6133 }
6134 }
6135
6136 #ifdef system_has_freelist_aba
6137 if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) {
6138 /* Enable fast mode */
6139 s->flags |= __CMPXCHG_DOUBLE;
6140 }
6141 #endif
6142
6143 /*
6144 * The larger the object size is, the more slabs we want on the partial
6145 * list to avoid pounding the page allocator excessively.
6146 */
6147 s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2);
6148 s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial);
6149
6150 set_cpu_partial(s);
6151
6152 #ifdef CONFIG_NUMA
6153 s->remote_node_defrag_ratio = 1000;
6154 #endif
6155
6156 /* Initialize the pre-computed randomized freelist if slab is up */
6157 if (slab_state >= UP) {
6158 if (init_cache_random_seq(s))
6159 goto out;
6160 }
6161
6162 if (!init_kmem_cache_nodes(s))
6163 goto out;
6164
6165 if (!alloc_kmem_cache_cpus(s))
6166 goto out;
6167
6168 /* Mutex is not taken during early boot */
6169 if (slab_state <= UP) {
6170 err = 0;
6171 goto out;
6172 }
6173
6174 err = sysfs_slab_add(s);
6175 if (err)
6176 goto out;
6177
6178 if (s->flags & SLAB_STORE_USER)
6179 debugfs_slab_add(s);
6180
6181 out:
6182 if (err)
6183 __kmem_cache_release(s);
6184 return err;
6185 }
6186
6187 #ifdef SLAB_SUPPORTS_SYSFS
count_inuse(struct slab * slab)6188 static int count_inuse(struct slab *slab)
6189 {
6190 return slab->inuse;
6191 }
6192
count_total(struct slab * slab)6193 static int count_total(struct slab *slab)
6194 {
6195 return slab->objects;
6196 }
6197 #endif
6198
6199 #ifdef CONFIG_SLUB_DEBUG
validate_slab(struct kmem_cache * s,struct slab * slab,unsigned long * obj_map)6200 static void validate_slab(struct kmem_cache *s, struct slab *slab,
6201 unsigned long *obj_map)
6202 {
6203 void *p;
6204 void *addr = slab_address(slab);
6205
6206 if (!check_slab(s, slab) || !on_freelist(s, slab, NULL))
6207 return;
6208
6209 /* Now we know that a valid freelist exists */
6210 __fill_map(obj_map, s, slab);
6211 for_each_object(p, s, addr, slab->objects) {
6212 u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ?
6213 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE;
6214
6215 if (!check_object(s, slab, p, val))
6216 break;
6217 }
6218 }
6219
validate_slab_node(struct kmem_cache * s,struct kmem_cache_node * n,unsigned long * obj_map)6220 static int validate_slab_node(struct kmem_cache *s,
6221 struct kmem_cache_node *n, unsigned long *obj_map)
6222 {
6223 unsigned long count = 0;
6224 struct slab *slab;
6225 unsigned long flags;
6226
6227 spin_lock_irqsave(&n->list_lock, flags);
6228
6229 list_for_each_entry(slab, &n->partial, slab_list) {
6230 validate_slab(s, slab, obj_map);
6231 count++;
6232 }
6233 if (count != n->nr_partial) {
6234 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n",
6235 s->name, count, n->nr_partial);
6236 slab_add_kunit_errors();
6237 }
6238
6239 if (!(s->flags & SLAB_STORE_USER))
6240 goto out;
6241
6242 list_for_each_entry(slab, &n->full, slab_list) {
6243 validate_slab(s, slab, obj_map);
6244 count++;
6245 }
6246 if (count != node_nr_slabs(n)) {
6247 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n",
6248 s->name, count, node_nr_slabs(n));
6249 slab_add_kunit_errors();
6250 }
6251
6252 out:
6253 spin_unlock_irqrestore(&n->list_lock, flags);
6254 return count;
6255 }
6256
validate_slab_cache(struct kmem_cache * s)6257 long validate_slab_cache(struct kmem_cache *s)
6258 {
6259 int node;
6260 unsigned long count = 0;
6261 struct kmem_cache_node *n;
6262 unsigned long *obj_map;
6263
6264 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
6265 if (!obj_map)
6266 return -ENOMEM;
6267
6268 flush_all(s);
6269 for_each_kmem_cache_node(s, node, n)
6270 count += validate_slab_node(s, n, obj_map);
6271
6272 bitmap_free(obj_map);
6273
6274 return count;
6275 }
6276 EXPORT_SYMBOL(validate_slab_cache);
6277
6278 #ifdef CONFIG_DEBUG_FS
6279 /*
6280 * Generate lists of code addresses where slabcache objects are allocated
6281 * and freed.
6282 */
6283
6284 struct location {
6285 depot_stack_handle_t handle;
6286 unsigned long count;
6287 unsigned long addr;
6288 unsigned long waste;
6289 long long sum_time;
6290 long min_time;
6291 long max_time;
6292 long min_pid;
6293 long max_pid;
6294 DECLARE_BITMAP(cpus, NR_CPUS);
6295 nodemask_t nodes;
6296 };
6297
6298 struct loc_track {
6299 unsigned long max;
6300 unsigned long count;
6301 struct location *loc;
6302 loff_t idx;
6303 };
6304
6305 static struct dentry *slab_debugfs_root;
6306
free_loc_track(struct loc_track * t)6307 static void free_loc_track(struct loc_track *t)
6308 {
6309 if (t->max)
6310 free_pages((unsigned long)t->loc,
6311 get_order(sizeof(struct location) * t->max));
6312 }
6313
alloc_loc_track(struct loc_track * t,unsigned long max,gfp_t flags)6314 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
6315 {
6316 struct location *l;
6317 int order;
6318
6319 order = get_order(sizeof(struct location) * max);
6320
6321 l = (void *)__get_free_pages(flags, order);
6322 if (!l)
6323 return 0;
6324
6325 if (t->count) {
6326 memcpy(l, t->loc, sizeof(struct location) * t->count);
6327 free_loc_track(t);
6328 }
6329 t->max = max;
6330 t->loc = l;
6331 return 1;
6332 }
6333
add_location(struct loc_track * t,struct kmem_cache * s,const struct track * track,unsigned int orig_size)6334 static int add_location(struct loc_track *t, struct kmem_cache *s,
6335 const struct track *track,
6336 unsigned int orig_size)
6337 {
6338 long start, end, pos;
6339 struct location *l;
6340 unsigned long caddr, chandle, cwaste;
6341 unsigned long age = jiffies - track->when;
6342 depot_stack_handle_t handle = 0;
6343 unsigned int waste = s->object_size - orig_size;
6344
6345 #ifdef CONFIG_STACKDEPOT
6346 handle = READ_ONCE(track->handle);
6347 #endif
6348 start = -1;
6349 end = t->count;
6350
6351 for ( ; ; ) {
6352 pos = start + (end - start + 1) / 2;
6353
6354 /*
6355 * There is nothing at "end". If we end up there
6356 * we need to add something to before end.
6357 */
6358 if (pos == end)
6359 break;
6360
6361 l = &t->loc[pos];
6362 caddr = l->addr;
6363 chandle = l->handle;
6364 cwaste = l->waste;
6365 if ((track->addr == caddr) && (handle == chandle) &&
6366 (waste == cwaste)) {
6367
6368 l->count++;
6369 if (track->when) {
6370 l->sum_time += age;
6371 if (age < l->min_time)
6372 l->min_time = age;
6373 if (age > l->max_time)
6374 l->max_time = age;
6375
6376 if (track->pid < l->min_pid)
6377 l->min_pid = track->pid;
6378 if (track->pid > l->max_pid)
6379 l->max_pid = track->pid;
6380
6381 cpumask_set_cpu(track->cpu,
6382 to_cpumask(l->cpus));
6383 }
6384 node_set(page_to_nid(virt_to_page(track)), l->nodes);
6385 return 1;
6386 }
6387
6388 if (track->addr < caddr)
6389 end = pos;
6390 else if (track->addr == caddr && handle < chandle)
6391 end = pos;
6392 else if (track->addr == caddr && handle == chandle &&
6393 waste < cwaste)
6394 end = pos;
6395 else
6396 start = pos;
6397 }
6398
6399 /*
6400 * Not found. Insert new tracking element.
6401 */
6402 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
6403 return 0;
6404
6405 l = t->loc + pos;
6406 if (pos < t->count)
6407 memmove(l + 1, l,
6408 (t->count - pos) * sizeof(struct location));
6409 t->count++;
6410 l->count = 1;
6411 l->addr = track->addr;
6412 l->sum_time = age;
6413 l->min_time = age;
6414 l->max_time = age;
6415 l->min_pid = track->pid;
6416 l->max_pid = track->pid;
6417 l->handle = handle;
6418 l->waste = waste;
6419 cpumask_clear(to_cpumask(l->cpus));
6420 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
6421 nodes_clear(l->nodes);
6422 node_set(page_to_nid(virt_to_page(track)), l->nodes);
6423 return 1;
6424 }
6425
process_slab(struct loc_track * t,struct kmem_cache * s,struct slab * slab,enum track_item alloc,unsigned long * obj_map)6426 static void process_slab(struct loc_track *t, struct kmem_cache *s,
6427 struct slab *slab, enum track_item alloc,
6428 unsigned long *obj_map)
6429 {
6430 void *addr = slab_address(slab);
6431 bool is_alloc = (alloc == TRACK_ALLOC);
6432 void *p;
6433
6434 __fill_map(obj_map, s, slab);
6435
6436 for_each_object(p, s, addr, slab->objects)
6437 if (!test_bit(__obj_to_index(s, addr, p), obj_map))
6438 add_location(t, s, get_track(s, p, alloc),
6439 is_alloc ? get_orig_size(s, p) :
6440 s->object_size);
6441 }
6442 #endif /* CONFIG_DEBUG_FS */
6443 #endif /* CONFIG_SLUB_DEBUG */
6444
6445 #ifdef SLAB_SUPPORTS_SYSFS
6446 enum slab_stat_type {
6447 SL_ALL, /* All slabs */
6448 SL_PARTIAL, /* Only partially allocated slabs */
6449 SL_CPU, /* Only slabs used for cpu caches */
6450 SL_OBJECTS, /* Determine allocated objects not slabs */
6451 SL_TOTAL /* Determine object capacity not slabs */
6452 };
6453
6454 #define SO_ALL (1 << SL_ALL)
6455 #define SO_PARTIAL (1 << SL_PARTIAL)
6456 #define SO_CPU (1 << SL_CPU)
6457 #define SO_OBJECTS (1 << SL_OBJECTS)
6458 #define SO_TOTAL (1 << SL_TOTAL)
6459
show_slab_objects(struct kmem_cache * s,char * buf,unsigned long flags)6460 static ssize_t show_slab_objects(struct kmem_cache *s,
6461 char *buf, unsigned long flags)
6462 {
6463 unsigned long total = 0;
6464 int node;
6465 int x;
6466 unsigned long *nodes;
6467 int len = 0;
6468
6469 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL);
6470 if (!nodes)
6471 return -ENOMEM;
6472
6473 if (flags & SO_CPU) {
6474 int cpu;
6475
6476 for_each_possible_cpu(cpu) {
6477 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab,
6478 cpu);
6479 int node;
6480 struct slab *slab;
6481
6482 slab = READ_ONCE(c->slab);
6483 if (!slab)
6484 continue;
6485
6486 node = slab_nid(slab);
6487 if (flags & SO_TOTAL)
6488 x = slab->objects;
6489 else if (flags & SO_OBJECTS)
6490 x = slab->inuse;
6491 else
6492 x = 1;
6493
6494 total += x;
6495 nodes[node] += x;
6496
6497 #ifdef CONFIG_SLUB_CPU_PARTIAL
6498 slab = slub_percpu_partial_read_once(c);
6499 if (slab) {
6500 node = slab_nid(slab);
6501 if (flags & SO_TOTAL)
6502 WARN_ON_ONCE(1);
6503 else if (flags & SO_OBJECTS)
6504 WARN_ON_ONCE(1);
6505 else
6506 x = data_race(slab->slabs);
6507 total += x;
6508 nodes[node] += x;
6509 }
6510 #endif
6511 }
6512 }
6513
6514 /*
6515 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex"
6516 * already held which will conflict with an existing lock order:
6517 *
6518 * mem_hotplug_lock->slab_mutex->kernfs_mutex
6519 *
6520 * We don't really need mem_hotplug_lock (to hold off
6521 * slab_mem_going_offline_callback) here because slab's memory hot
6522 * unplug code doesn't destroy the kmem_cache->node[] data.
6523 */
6524
6525 #ifdef CONFIG_SLUB_DEBUG
6526 if (flags & SO_ALL) {
6527 struct kmem_cache_node *n;
6528
6529 for_each_kmem_cache_node(s, node, n) {
6530
6531 if (flags & SO_TOTAL)
6532 x = node_nr_objs(n);
6533 else if (flags & SO_OBJECTS)
6534 x = node_nr_objs(n) - count_partial(n, count_free);
6535 else
6536 x = node_nr_slabs(n);
6537 total += x;
6538 nodes[node] += x;
6539 }
6540
6541 } else
6542 #endif
6543 if (flags & SO_PARTIAL) {
6544 struct kmem_cache_node *n;
6545
6546 for_each_kmem_cache_node(s, node, n) {
6547 if (flags & SO_TOTAL)
6548 x = count_partial(n, count_total);
6549 else if (flags & SO_OBJECTS)
6550 x = count_partial(n, count_inuse);
6551 else
6552 x = n->nr_partial;
6553 total += x;
6554 nodes[node] += x;
6555 }
6556 }
6557
6558 len += sysfs_emit_at(buf, len, "%lu", total);
6559 #ifdef CONFIG_NUMA
6560 for (node = 0; node < nr_node_ids; node++) {
6561 if (nodes[node])
6562 len += sysfs_emit_at(buf, len, " N%d=%lu",
6563 node, nodes[node]);
6564 }
6565 #endif
6566 len += sysfs_emit_at(buf, len, "\n");
6567 kfree(nodes);
6568
6569 return len;
6570 }
6571
6572 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
6573 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
6574
6575 struct slab_attribute {
6576 struct attribute attr;
6577 ssize_t (*show)(struct kmem_cache *s, char *buf);
6578 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
6579 };
6580
6581 #define SLAB_ATTR_RO(_name) \
6582 static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400)
6583
6584 #define SLAB_ATTR(_name) \
6585 static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600)
6586
slab_size_show(struct kmem_cache * s,char * buf)6587 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
6588 {
6589 return sysfs_emit(buf, "%u\n", s->size);
6590 }
6591 SLAB_ATTR_RO(slab_size);
6592
align_show(struct kmem_cache * s,char * buf)6593 static ssize_t align_show(struct kmem_cache *s, char *buf)
6594 {
6595 return sysfs_emit(buf, "%u\n", s->align);
6596 }
6597 SLAB_ATTR_RO(align);
6598
object_size_show(struct kmem_cache * s,char * buf)6599 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
6600 {
6601 return sysfs_emit(buf, "%u\n", s->object_size);
6602 }
6603 SLAB_ATTR_RO(object_size);
6604
objs_per_slab_show(struct kmem_cache * s,char * buf)6605 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
6606 {
6607 return sysfs_emit(buf, "%u\n", oo_objects(s->oo));
6608 }
6609 SLAB_ATTR_RO(objs_per_slab);
6610
order_show(struct kmem_cache * s,char * buf)6611 static ssize_t order_show(struct kmem_cache *s, char *buf)
6612 {
6613 return sysfs_emit(buf, "%u\n", oo_order(s->oo));
6614 }
6615 SLAB_ATTR_RO(order);
6616
min_partial_show(struct kmem_cache * s,char * buf)6617 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
6618 {
6619 return sysfs_emit(buf, "%lu\n", s->min_partial);
6620 }
6621
min_partial_store(struct kmem_cache * s,const char * buf,size_t length)6622 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
6623 size_t length)
6624 {
6625 unsigned long min;
6626 int err;
6627
6628 err = kstrtoul(buf, 10, &min);
6629 if (err)
6630 return err;
6631
6632 s->min_partial = min;
6633 return length;
6634 }
6635 SLAB_ATTR(min_partial);
6636
cpu_partial_show(struct kmem_cache * s,char * buf)6637 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
6638 {
6639 unsigned int nr_partial = 0;
6640 #ifdef CONFIG_SLUB_CPU_PARTIAL
6641 nr_partial = s->cpu_partial;
6642 #endif
6643
6644 return sysfs_emit(buf, "%u\n", nr_partial);
6645 }
6646
cpu_partial_store(struct kmem_cache * s,const char * buf,size_t length)6647 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
6648 size_t length)
6649 {
6650 unsigned int objects;
6651 int err;
6652
6653 err = kstrtouint(buf, 10, &objects);
6654 if (err)
6655 return err;
6656 if (objects && !kmem_cache_has_cpu_partial(s))
6657 return -EINVAL;
6658
6659 slub_set_cpu_partial(s, objects);
6660 flush_all(s);
6661 return length;
6662 }
6663 SLAB_ATTR(cpu_partial);
6664
ctor_show(struct kmem_cache * s,char * buf)6665 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
6666 {
6667 if (!s->ctor)
6668 return 0;
6669 return sysfs_emit(buf, "%pS\n", s->ctor);
6670 }
6671 SLAB_ATTR_RO(ctor);
6672
aliases_show(struct kmem_cache * s,char * buf)6673 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
6674 {
6675 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1);
6676 }
6677 SLAB_ATTR_RO(aliases);
6678
partial_show(struct kmem_cache * s,char * buf)6679 static ssize_t partial_show(struct kmem_cache *s, char *buf)
6680 {
6681 return show_slab_objects(s, buf, SO_PARTIAL);
6682 }
6683 SLAB_ATTR_RO(partial);
6684
cpu_slabs_show(struct kmem_cache * s,char * buf)6685 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
6686 {
6687 return show_slab_objects(s, buf, SO_CPU);
6688 }
6689 SLAB_ATTR_RO(cpu_slabs);
6690
objects_partial_show(struct kmem_cache * s,char * buf)6691 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
6692 {
6693 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
6694 }
6695 SLAB_ATTR_RO(objects_partial);
6696
slabs_cpu_partial_show(struct kmem_cache * s,char * buf)6697 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
6698 {
6699 int objects = 0;
6700 int slabs = 0;
6701 int cpu __maybe_unused;
6702 int len = 0;
6703
6704 #ifdef CONFIG_SLUB_CPU_PARTIAL
6705 for_each_online_cpu(cpu) {
6706 struct slab *slab;
6707
6708 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
6709
6710 if (slab)
6711 slabs += data_race(slab->slabs);
6712 }
6713 #endif
6714
6715 /* Approximate half-full slabs, see slub_set_cpu_partial() */
6716 objects = (slabs * oo_objects(s->oo)) / 2;
6717 len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs);
6718
6719 #ifdef CONFIG_SLUB_CPU_PARTIAL
6720 for_each_online_cpu(cpu) {
6721 struct slab *slab;
6722
6723 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu));
6724 if (slab) {
6725 slabs = data_race(slab->slabs);
6726 objects = (slabs * oo_objects(s->oo)) / 2;
6727 len += sysfs_emit_at(buf, len, " C%d=%d(%d)",
6728 cpu, objects, slabs);
6729 }
6730 }
6731 #endif
6732 len += sysfs_emit_at(buf, len, "\n");
6733
6734 return len;
6735 }
6736 SLAB_ATTR_RO(slabs_cpu_partial);
6737
reclaim_account_show(struct kmem_cache * s,char * buf)6738 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
6739 {
6740 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
6741 }
6742 SLAB_ATTR_RO(reclaim_account);
6743
hwcache_align_show(struct kmem_cache * s,char * buf)6744 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
6745 {
6746 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
6747 }
6748 SLAB_ATTR_RO(hwcache_align);
6749
6750 #ifdef CONFIG_ZONE_DMA
cache_dma_show(struct kmem_cache * s,char * buf)6751 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
6752 {
6753 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
6754 }
6755 SLAB_ATTR_RO(cache_dma);
6756 #endif
6757
6758 #ifdef CONFIG_HARDENED_USERCOPY
usersize_show(struct kmem_cache * s,char * buf)6759 static ssize_t usersize_show(struct kmem_cache *s, char *buf)
6760 {
6761 return sysfs_emit(buf, "%u\n", s->usersize);
6762 }
6763 SLAB_ATTR_RO(usersize);
6764 #endif
6765
destroy_by_rcu_show(struct kmem_cache * s,char * buf)6766 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
6767 {
6768 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU));
6769 }
6770 SLAB_ATTR_RO(destroy_by_rcu);
6771
6772 #ifdef CONFIG_SLUB_DEBUG
slabs_show(struct kmem_cache * s,char * buf)6773 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
6774 {
6775 return show_slab_objects(s, buf, SO_ALL);
6776 }
6777 SLAB_ATTR_RO(slabs);
6778
total_objects_show(struct kmem_cache * s,char * buf)6779 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
6780 {
6781 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
6782 }
6783 SLAB_ATTR_RO(total_objects);
6784
objects_show(struct kmem_cache * s,char * buf)6785 static ssize_t objects_show(struct kmem_cache *s, char *buf)
6786 {
6787 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
6788 }
6789 SLAB_ATTR_RO(objects);
6790
sanity_checks_show(struct kmem_cache * s,char * buf)6791 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
6792 {
6793 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS));
6794 }
6795 SLAB_ATTR_RO(sanity_checks);
6796
trace_show(struct kmem_cache * s,char * buf)6797 static ssize_t trace_show(struct kmem_cache *s, char *buf)
6798 {
6799 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE));
6800 }
6801 SLAB_ATTR_RO(trace);
6802
red_zone_show(struct kmem_cache * s,char * buf)6803 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
6804 {
6805 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
6806 }
6807
6808 SLAB_ATTR_RO(red_zone);
6809
poison_show(struct kmem_cache * s,char * buf)6810 static ssize_t poison_show(struct kmem_cache *s, char *buf)
6811 {
6812 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON));
6813 }
6814
6815 SLAB_ATTR_RO(poison);
6816
store_user_show(struct kmem_cache * s,char * buf)6817 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
6818 {
6819 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
6820 }
6821
6822 SLAB_ATTR_RO(store_user);
6823
validate_show(struct kmem_cache * s,char * buf)6824 static ssize_t validate_show(struct kmem_cache *s, char *buf)
6825 {
6826 return 0;
6827 }
6828
validate_store(struct kmem_cache * s,const char * buf,size_t length)6829 static ssize_t validate_store(struct kmem_cache *s,
6830 const char *buf, size_t length)
6831 {
6832 int ret = -EINVAL;
6833
6834 if (buf[0] == '1' && kmem_cache_debug(s)) {
6835 ret = validate_slab_cache(s);
6836 if (ret >= 0)
6837 ret = length;
6838 }
6839 return ret;
6840 }
6841 SLAB_ATTR(validate);
6842
6843 #endif /* CONFIG_SLUB_DEBUG */
6844
6845 #ifdef CONFIG_FAILSLAB
failslab_show(struct kmem_cache * s,char * buf)6846 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
6847 {
6848 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
6849 }
6850
failslab_store(struct kmem_cache * s,const char * buf,size_t length)6851 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
6852 size_t length)
6853 {
6854 if (s->refcount > 1)
6855 return -EINVAL;
6856
6857 if (buf[0] == '1')
6858 WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB);
6859 else
6860 WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB);
6861
6862 return length;
6863 }
6864 SLAB_ATTR(failslab);
6865 #endif
6866
shrink_show(struct kmem_cache * s,char * buf)6867 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
6868 {
6869 return 0;
6870 }
6871
shrink_store(struct kmem_cache * s,const char * buf,size_t length)6872 static ssize_t shrink_store(struct kmem_cache *s,
6873 const char *buf, size_t length)
6874 {
6875 if (buf[0] == '1')
6876 kmem_cache_shrink(s);
6877 else
6878 return -EINVAL;
6879 return length;
6880 }
6881 SLAB_ATTR(shrink);
6882
6883 #ifdef CONFIG_NUMA
remote_node_defrag_ratio_show(struct kmem_cache * s,char * buf)6884 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
6885 {
6886 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10);
6887 }
6888
remote_node_defrag_ratio_store(struct kmem_cache * s,const char * buf,size_t length)6889 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
6890 const char *buf, size_t length)
6891 {
6892 unsigned int ratio;
6893 int err;
6894
6895 err = kstrtouint(buf, 10, &ratio);
6896 if (err)
6897 return err;
6898 if (ratio > 100)
6899 return -ERANGE;
6900
6901 s->remote_node_defrag_ratio = ratio * 10;
6902
6903 return length;
6904 }
6905 SLAB_ATTR(remote_node_defrag_ratio);
6906 #endif
6907
6908 #ifdef CONFIG_SLUB_STATS
show_stat(struct kmem_cache * s,char * buf,enum stat_item si)6909 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
6910 {
6911 unsigned long sum = 0;
6912 int cpu;
6913 int len = 0;
6914 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL);
6915
6916 if (!data)
6917 return -ENOMEM;
6918
6919 for_each_online_cpu(cpu) {
6920 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
6921
6922 data[cpu] = x;
6923 sum += x;
6924 }
6925
6926 len += sysfs_emit_at(buf, len, "%lu", sum);
6927
6928 #ifdef CONFIG_SMP
6929 for_each_online_cpu(cpu) {
6930 if (data[cpu])
6931 len += sysfs_emit_at(buf, len, " C%d=%u",
6932 cpu, data[cpu]);
6933 }
6934 #endif
6935 kfree(data);
6936 len += sysfs_emit_at(buf, len, "\n");
6937
6938 return len;
6939 }
6940
clear_stat(struct kmem_cache * s,enum stat_item si)6941 static void clear_stat(struct kmem_cache *s, enum stat_item si)
6942 {
6943 int cpu;
6944
6945 for_each_online_cpu(cpu)
6946 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
6947 }
6948
6949 #define STAT_ATTR(si, text) \
6950 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
6951 { \
6952 return show_stat(s, buf, si); \
6953 } \
6954 static ssize_t text##_store(struct kmem_cache *s, \
6955 const char *buf, size_t length) \
6956 { \
6957 if (buf[0] != '0') \
6958 return -EINVAL; \
6959 clear_stat(s, si); \
6960 return length; \
6961 } \
6962 SLAB_ATTR(text); \
6963
6964 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
6965 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
6966 STAT_ATTR(FREE_FASTPATH, free_fastpath);
6967 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
6968 STAT_ATTR(FREE_FROZEN, free_frozen);
6969 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
6970 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
6971 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
6972 STAT_ATTR(ALLOC_SLAB, alloc_slab);
6973 STAT_ATTR(ALLOC_REFILL, alloc_refill);
6974 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
6975 STAT_ATTR(FREE_SLAB, free_slab);
6976 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
6977 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
6978 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
6979 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
6980 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
6981 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
6982 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
6983 STAT_ATTR(ORDER_FALLBACK, order_fallback);
6984 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
6985 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
6986 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
6987 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
6988 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
6989 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
6990 #endif /* CONFIG_SLUB_STATS */
6991
6992 #ifdef CONFIG_KFENCE
skip_kfence_show(struct kmem_cache * s,char * buf)6993 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf)
6994 {
6995 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE));
6996 }
6997
skip_kfence_store(struct kmem_cache * s,const char * buf,size_t length)6998 static ssize_t skip_kfence_store(struct kmem_cache *s,
6999 const char *buf, size_t length)
7000 {
7001 int ret = length;
7002
7003 if (buf[0] == '0')
7004 s->flags &= ~SLAB_SKIP_KFENCE;
7005 else if (buf[0] == '1')
7006 s->flags |= SLAB_SKIP_KFENCE;
7007 else
7008 ret = -EINVAL;
7009
7010 return ret;
7011 }
7012 SLAB_ATTR(skip_kfence);
7013 #endif
7014
7015 static struct attribute *slab_attrs[] = {
7016 &slab_size_attr.attr,
7017 &object_size_attr.attr,
7018 &objs_per_slab_attr.attr,
7019 &order_attr.attr,
7020 &min_partial_attr.attr,
7021 &cpu_partial_attr.attr,
7022 &objects_partial_attr.attr,
7023 &partial_attr.attr,
7024 &cpu_slabs_attr.attr,
7025 &ctor_attr.attr,
7026 &aliases_attr.attr,
7027 &align_attr.attr,
7028 &hwcache_align_attr.attr,
7029 &reclaim_account_attr.attr,
7030 &destroy_by_rcu_attr.attr,
7031 &shrink_attr.attr,
7032 &slabs_cpu_partial_attr.attr,
7033 #ifdef CONFIG_SLUB_DEBUG
7034 &total_objects_attr.attr,
7035 &objects_attr.attr,
7036 &slabs_attr.attr,
7037 &sanity_checks_attr.attr,
7038 &trace_attr.attr,
7039 &red_zone_attr.attr,
7040 &poison_attr.attr,
7041 &store_user_attr.attr,
7042 &validate_attr.attr,
7043 #endif
7044 #ifdef CONFIG_ZONE_DMA
7045 &cache_dma_attr.attr,
7046 #endif
7047 #ifdef CONFIG_NUMA
7048 &remote_node_defrag_ratio_attr.attr,
7049 #endif
7050 #ifdef CONFIG_SLUB_STATS
7051 &alloc_fastpath_attr.attr,
7052 &alloc_slowpath_attr.attr,
7053 &free_fastpath_attr.attr,
7054 &free_slowpath_attr.attr,
7055 &free_frozen_attr.attr,
7056 &free_add_partial_attr.attr,
7057 &free_remove_partial_attr.attr,
7058 &alloc_from_partial_attr.attr,
7059 &alloc_slab_attr.attr,
7060 &alloc_refill_attr.attr,
7061 &alloc_node_mismatch_attr.attr,
7062 &free_slab_attr.attr,
7063 &cpuslab_flush_attr.attr,
7064 &deactivate_full_attr.attr,
7065 &deactivate_empty_attr.attr,
7066 &deactivate_to_head_attr.attr,
7067 &deactivate_to_tail_attr.attr,
7068 &deactivate_remote_frees_attr.attr,
7069 &deactivate_bypass_attr.attr,
7070 &order_fallback_attr.attr,
7071 &cmpxchg_double_fail_attr.attr,
7072 &cmpxchg_double_cpu_fail_attr.attr,
7073 &cpu_partial_alloc_attr.attr,
7074 &cpu_partial_free_attr.attr,
7075 &cpu_partial_node_attr.attr,
7076 &cpu_partial_drain_attr.attr,
7077 #endif
7078 #ifdef CONFIG_FAILSLAB
7079 &failslab_attr.attr,
7080 #endif
7081 #ifdef CONFIG_HARDENED_USERCOPY
7082 &usersize_attr.attr,
7083 #endif
7084 #ifdef CONFIG_KFENCE
7085 &skip_kfence_attr.attr,
7086 #endif
7087
7088 NULL
7089 };
7090
7091 static const struct attribute_group slab_attr_group = {
7092 .attrs = slab_attrs,
7093 };
7094
slab_attr_show(struct kobject * kobj,struct attribute * attr,char * buf)7095 static ssize_t slab_attr_show(struct kobject *kobj,
7096 struct attribute *attr,
7097 char *buf)
7098 {
7099 struct slab_attribute *attribute;
7100 struct kmem_cache *s;
7101
7102 attribute = to_slab_attr(attr);
7103 s = to_slab(kobj);
7104
7105 if (!attribute->show)
7106 return -EIO;
7107
7108 return attribute->show(s, buf);
7109 }
7110
slab_attr_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t len)7111 static ssize_t slab_attr_store(struct kobject *kobj,
7112 struct attribute *attr,
7113 const char *buf, size_t len)
7114 {
7115 struct slab_attribute *attribute;
7116 struct kmem_cache *s;
7117
7118 attribute = to_slab_attr(attr);
7119 s = to_slab(kobj);
7120
7121 if (!attribute->store)
7122 return -EIO;
7123
7124 return attribute->store(s, buf, len);
7125 }
7126
kmem_cache_release(struct kobject * k)7127 static void kmem_cache_release(struct kobject *k)
7128 {
7129 slab_kmem_cache_release(to_slab(k));
7130 }
7131
7132 static const struct sysfs_ops slab_sysfs_ops = {
7133 .show = slab_attr_show,
7134 .store = slab_attr_store,
7135 };
7136
7137 static const struct kobj_type slab_ktype = {
7138 .sysfs_ops = &slab_sysfs_ops,
7139 .release = kmem_cache_release,
7140 };
7141
7142 static struct kset *slab_kset;
7143
cache_kset(struct kmem_cache * s)7144 static inline struct kset *cache_kset(struct kmem_cache *s)
7145 {
7146 return slab_kset;
7147 }
7148
7149 #define ID_STR_LENGTH 32
7150
7151 /* Create a unique string id for a slab cache:
7152 *
7153 * Format :[flags-]size
7154 */
create_unique_id(struct kmem_cache * s)7155 static char *create_unique_id(struct kmem_cache *s)
7156 {
7157 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
7158 char *p = name;
7159
7160 if (!name)
7161 return ERR_PTR(-ENOMEM);
7162
7163 *p++ = ':';
7164 /*
7165 * First flags affecting slabcache operations. We will only
7166 * get here for aliasable slabs so we do not need to support
7167 * too many flags. The flags here must cover all flags that
7168 * are matched during merging to guarantee that the id is
7169 * unique.
7170 */
7171 if (s->flags & SLAB_CACHE_DMA)
7172 *p++ = 'd';
7173 if (s->flags & SLAB_CACHE_DMA32)
7174 *p++ = 'D';
7175 if (s->flags & SLAB_RECLAIM_ACCOUNT)
7176 *p++ = 'a';
7177 if (s->flags & SLAB_CONSISTENCY_CHECKS)
7178 *p++ = 'F';
7179 if (s->flags & SLAB_ACCOUNT)
7180 *p++ = 'A';
7181 if (p != name + 1)
7182 *p++ = '-';
7183 p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
7184
7185 if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
7186 kfree(name);
7187 return ERR_PTR(-EINVAL);
7188 }
7189 kmsan_unpoison_memory(name, p - name);
7190 return name;
7191 }
7192
sysfs_slab_add(struct kmem_cache * s)7193 static int sysfs_slab_add(struct kmem_cache *s)
7194 {
7195 int err;
7196 const char *name;
7197 struct kset *kset = cache_kset(s);
7198 int unmergeable = slab_unmergeable(s);
7199
7200 if (!unmergeable && disable_higher_order_debug &&
7201 (slub_debug & DEBUG_METADATA_FLAGS))
7202 unmergeable = 1;
7203
7204 if (unmergeable) {
7205 /*
7206 * Slabcache can never be merged so we can use the name proper.
7207 * This is typically the case for debug situations. In that
7208 * case we can catch duplicate names easily.
7209 */
7210 sysfs_remove_link(&slab_kset->kobj, s->name);
7211 name = s->name;
7212 } else {
7213 /*
7214 * Create a unique name for the slab as a target
7215 * for the symlinks.
7216 */
7217 name = create_unique_id(s);
7218 if (IS_ERR(name))
7219 return PTR_ERR(name);
7220 }
7221
7222 s->kobj.kset = kset;
7223 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name);
7224 if (err)
7225 goto out;
7226
7227 err = sysfs_create_group(&s->kobj, &slab_attr_group);
7228 if (err)
7229 goto out_del_kobj;
7230
7231 if (!unmergeable) {
7232 /* Setup first alias */
7233 sysfs_slab_alias(s, s->name);
7234 }
7235 out:
7236 if (!unmergeable)
7237 kfree(name);
7238 return err;
7239 out_del_kobj:
7240 kobject_del(&s->kobj);
7241 goto out;
7242 }
7243
sysfs_slab_unlink(struct kmem_cache * s)7244 void sysfs_slab_unlink(struct kmem_cache *s)
7245 {
7246 kobject_del(&s->kobj);
7247 }
7248
sysfs_slab_release(struct kmem_cache * s)7249 void sysfs_slab_release(struct kmem_cache *s)
7250 {
7251 kobject_put(&s->kobj);
7252 }
7253
7254 /*
7255 * Need to buffer aliases during bootup until sysfs becomes
7256 * available lest we lose that information.
7257 */
7258 struct saved_alias {
7259 struct kmem_cache *s;
7260 const char *name;
7261 struct saved_alias *next;
7262 };
7263
7264 static struct saved_alias *alias_list;
7265
sysfs_slab_alias(struct kmem_cache * s,const char * name)7266 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
7267 {
7268 struct saved_alias *al;
7269
7270 if (slab_state == FULL) {
7271 /*
7272 * If we have a leftover link then remove it.
7273 */
7274 sysfs_remove_link(&slab_kset->kobj, name);
7275 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
7276 }
7277
7278 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
7279 if (!al)
7280 return -ENOMEM;
7281
7282 al->s = s;
7283 al->name = name;
7284 al->next = alias_list;
7285 alias_list = al;
7286 kmsan_unpoison_memory(al, sizeof(*al));
7287 return 0;
7288 }
7289
slab_sysfs_init(void)7290 static int __init slab_sysfs_init(void)
7291 {
7292 struct kmem_cache *s;
7293 int err;
7294
7295 mutex_lock(&slab_mutex);
7296
7297 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj);
7298 if (!slab_kset) {
7299 mutex_unlock(&slab_mutex);
7300 pr_err("Cannot register slab subsystem.\n");
7301 return -ENOMEM;
7302 }
7303
7304 slab_state = FULL;
7305
7306 list_for_each_entry(s, &slab_caches, list) {
7307 err = sysfs_slab_add(s);
7308 if (err)
7309 pr_err("SLUB: Unable to add boot slab %s to sysfs\n",
7310 s->name);
7311 }
7312
7313 while (alias_list) {
7314 struct saved_alias *al = alias_list;
7315
7316 alias_list = alias_list->next;
7317 err = sysfs_slab_alias(al->s, al->name);
7318 if (err)
7319 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n",
7320 al->name);
7321 kfree(al);
7322 }
7323
7324 mutex_unlock(&slab_mutex);
7325 return 0;
7326 }
7327 late_initcall(slab_sysfs_init);
7328 #endif /* SLAB_SUPPORTS_SYSFS */
7329
7330 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS)
slab_debugfs_show(struct seq_file * seq,void * v)7331 static int slab_debugfs_show(struct seq_file *seq, void *v)
7332 {
7333 struct loc_track *t = seq->private;
7334 struct location *l;
7335 unsigned long idx;
7336
7337 idx = (unsigned long) t->idx;
7338 if (idx < t->count) {
7339 l = &t->loc[idx];
7340
7341 seq_printf(seq, "%7ld ", l->count);
7342
7343 if (l->addr)
7344 seq_printf(seq, "%pS", (void *)l->addr);
7345 else
7346 seq_puts(seq, "<not-available>");
7347
7348 if (l->waste)
7349 seq_printf(seq, " waste=%lu/%lu",
7350 l->count * l->waste, l->waste);
7351
7352 if (l->sum_time != l->min_time) {
7353 seq_printf(seq, " age=%ld/%llu/%ld",
7354 l->min_time, div_u64(l->sum_time, l->count),
7355 l->max_time);
7356 } else
7357 seq_printf(seq, " age=%ld", l->min_time);
7358
7359 if (l->min_pid != l->max_pid)
7360 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid);
7361 else
7362 seq_printf(seq, " pid=%ld",
7363 l->min_pid);
7364
7365 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus)))
7366 seq_printf(seq, " cpus=%*pbl",
7367 cpumask_pr_args(to_cpumask(l->cpus)));
7368
7369 if (nr_online_nodes > 1 && !nodes_empty(l->nodes))
7370 seq_printf(seq, " nodes=%*pbl",
7371 nodemask_pr_args(&l->nodes));
7372
7373 #ifdef CONFIG_STACKDEPOT
7374 {
7375 depot_stack_handle_t handle;
7376 unsigned long *entries;
7377 unsigned int nr_entries, j;
7378
7379 handle = READ_ONCE(l->handle);
7380 if (handle) {
7381 nr_entries = stack_depot_fetch(handle, &entries);
7382 seq_puts(seq, "\n");
7383 for (j = 0; j < nr_entries; j++)
7384 seq_printf(seq, " %pS\n", (void *)entries[j]);
7385 }
7386 }
7387 #endif
7388 seq_puts(seq, "\n");
7389 }
7390
7391 if (!idx && !t->count)
7392 seq_puts(seq, "No data\n");
7393
7394 return 0;
7395 }
7396
slab_debugfs_stop(struct seq_file * seq,void * v)7397 static void slab_debugfs_stop(struct seq_file *seq, void *v)
7398 {
7399 }
7400
slab_debugfs_next(struct seq_file * seq,void * v,loff_t * ppos)7401 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos)
7402 {
7403 struct loc_track *t = seq->private;
7404
7405 t->idx = ++(*ppos);
7406 if (*ppos <= t->count)
7407 return ppos;
7408
7409 return NULL;
7410 }
7411
cmp_loc_by_count(const void * a,const void * b,const void * data)7412 static int cmp_loc_by_count(const void *a, const void *b, const void *data)
7413 {
7414 struct location *loc1 = (struct location *)a;
7415 struct location *loc2 = (struct location *)b;
7416
7417 if (loc1->count > loc2->count)
7418 return -1;
7419 else
7420 return 1;
7421 }
7422
slab_debugfs_start(struct seq_file * seq,loff_t * ppos)7423 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos)
7424 {
7425 struct loc_track *t = seq->private;
7426
7427 t->idx = *ppos;
7428 return ppos;
7429 }
7430
7431 static const struct seq_operations slab_debugfs_sops = {
7432 .start = slab_debugfs_start,
7433 .next = slab_debugfs_next,
7434 .stop = slab_debugfs_stop,
7435 .show = slab_debugfs_show,
7436 };
7437
slab_debug_trace_open(struct inode * inode,struct file * filep)7438 static int slab_debug_trace_open(struct inode *inode, struct file *filep)
7439 {
7440
7441 struct kmem_cache_node *n;
7442 enum track_item alloc;
7443 int node;
7444 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops,
7445 sizeof(struct loc_track));
7446 struct kmem_cache *s = file_inode(filep)->i_private;
7447 unsigned long *obj_map;
7448
7449 if (!t)
7450 return -ENOMEM;
7451
7452 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL);
7453 if (!obj_map) {
7454 seq_release_private(inode, filep);
7455 return -ENOMEM;
7456 }
7457
7458 if (strcmp(filep->f_path.dentry->d_name.name, "alloc_traces") == 0)
7459 alloc = TRACK_ALLOC;
7460 else
7461 alloc = TRACK_FREE;
7462
7463 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) {
7464 bitmap_free(obj_map);
7465 seq_release_private(inode, filep);
7466 return -ENOMEM;
7467 }
7468
7469 for_each_kmem_cache_node(s, node, n) {
7470 unsigned long flags;
7471 struct slab *slab;
7472
7473 if (!node_nr_slabs(n))
7474 continue;
7475
7476 spin_lock_irqsave(&n->list_lock, flags);
7477 list_for_each_entry(slab, &n->partial, slab_list)
7478 process_slab(t, s, slab, alloc, obj_map);
7479 list_for_each_entry(slab, &n->full, slab_list)
7480 process_slab(t, s, slab, alloc, obj_map);
7481 spin_unlock_irqrestore(&n->list_lock, flags);
7482 }
7483
7484 /* Sort locations by count */
7485 sort_r(t->loc, t->count, sizeof(struct location),
7486 cmp_loc_by_count, NULL, NULL);
7487
7488 bitmap_free(obj_map);
7489 return 0;
7490 }
7491
slab_debug_trace_release(struct inode * inode,struct file * file)7492 static int slab_debug_trace_release(struct inode *inode, struct file *file)
7493 {
7494 struct seq_file *seq = file->private_data;
7495 struct loc_track *t = seq->private;
7496
7497 free_loc_track(t);
7498 return seq_release_private(inode, file);
7499 }
7500
7501 static const struct file_operations slab_debugfs_fops = {
7502 .open = slab_debug_trace_open,
7503 .read = seq_read,
7504 .llseek = seq_lseek,
7505 .release = slab_debug_trace_release,
7506 };
7507
debugfs_slab_add(struct kmem_cache * s)7508 static void debugfs_slab_add(struct kmem_cache *s)
7509 {
7510 struct dentry *slab_cache_dir;
7511
7512 if (unlikely(!slab_debugfs_root))
7513 return;
7514
7515 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root);
7516
7517 debugfs_create_file("alloc_traces", 0400,
7518 slab_cache_dir, s, &slab_debugfs_fops);
7519
7520 debugfs_create_file("free_traces", 0400,
7521 slab_cache_dir, s, &slab_debugfs_fops);
7522 }
7523
debugfs_slab_release(struct kmem_cache * s)7524 void debugfs_slab_release(struct kmem_cache *s)
7525 {
7526 debugfs_lookup_and_remove(s->name, slab_debugfs_root);
7527 }
7528
slab_debugfs_init(void)7529 static int __init slab_debugfs_init(void)
7530 {
7531 struct kmem_cache *s;
7532
7533 slab_debugfs_root = debugfs_create_dir("slab", NULL);
7534
7535 list_for_each_entry(s, &slab_caches, list)
7536 if (s->flags & SLAB_STORE_USER)
7537 debugfs_slab_add(s);
7538
7539 return 0;
7540
7541 }
7542 __initcall(slab_debugfs_init);
7543 #endif
7544 /*
7545 * The /proc/slabinfo ABI
7546 */
7547 #ifdef CONFIG_SLUB_DEBUG
get_slabinfo(struct kmem_cache * s,struct slabinfo * sinfo)7548 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo)
7549 {
7550 unsigned long nr_slabs = 0;
7551 unsigned long nr_objs = 0;
7552 unsigned long nr_free = 0;
7553 int node;
7554 struct kmem_cache_node *n;
7555
7556 for_each_kmem_cache_node(s, node, n) {
7557 nr_slabs += node_nr_slabs(n);
7558 nr_objs += node_nr_objs(n);
7559 nr_free += count_partial_free_approx(n);
7560 }
7561
7562 sinfo->active_objs = nr_objs - nr_free;
7563 sinfo->num_objs = nr_objs;
7564 sinfo->active_slabs = nr_slabs;
7565 sinfo->num_slabs = nr_slabs;
7566 sinfo->objects_per_slab = oo_objects(s->oo);
7567 sinfo->cache_order = oo_order(s->oo);
7568 }
7569 EXPORT_SYMBOL_NS_GPL(get_slabinfo, MINIDUMP);
7570
7571 #endif /* CONFIG_SLUB_DEBUG */
7572