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