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