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