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