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