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