OSDN Git Service

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