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