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