Merge branch 'for-4.9' into for-4.10
[linux-2.6-microblaze.git] / mm / slab.c
1 /*
2  * linux/mm/slab.c
3  * Written by Mark Hemment, 1996/97.
4  * (markhe@nextd.demon.co.uk)
5  *
6  * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
7  *
8  * Major cleanup, different bufctl logic, per-cpu arrays
9  *      (c) 2000 Manfred Spraul
10  *
11  * Cleanup, make the head arrays unconditional, preparation for NUMA
12  *      (c) 2002 Manfred Spraul
13  *
14  * An implementation of the Slab Allocator as described in outline in;
15  *      UNIX Internals: The New Frontiers by Uresh Vahalia
16  *      Pub: Prentice Hall      ISBN 0-13-101908-2
17  * or with a little more detail in;
18  *      The Slab Allocator: An Object-Caching Kernel Memory Allocator
19  *      Jeff Bonwick (Sun Microsystems).
20  *      Presented at: USENIX Summer 1994 Technical Conference
21  *
22  * The memory is organized in caches, one cache for each object type.
23  * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24  * Each cache consists out of many slabs (they are small (usually one
25  * page long) and always contiguous), and each slab contains multiple
26  * initialized objects.
27  *
28  * This means, that your constructor is used only for newly allocated
29  * slabs and you must pass objects with the same initializations to
30  * kmem_cache_free.
31  *
32  * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33  * normal). If you need a special memory type, then must create a new
34  * cache for that memory type.
35  *
36  * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37  *   full slabs with 0 free objects
38  *   partial slabs
39  *   empty slabs with no allocated objects
40  *
41  * If partial slabs exist, then new allocations come from these slabs,
42  * otherwise from empty slabs or new slabs are allocated.
43  *
44  * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45  * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
46  *
47  * Each cache has a short per-cpu head array, most allocs
48  * and frees go into that array, and if that array overflows, then 1/2
49  * of the entries in the array are given back into the global cache.
50  * The head array is strictly LIFO and should improve the cache hit rates.
51  * On SMP, it additionally reduces the spinlock operations.
52  *
53  * The c_cpuarray may not be read with enabled local interrupts -
54  * it's changed with a smp_call_function().
55  *
56  * SMP synchronization:
57  *  constructors and destructors are called without any locking.
58  *  Several members in struct kmem_cache and struct slab never change, they
59  *      are accessed without any locking.
60  *  The per-cpu arrays are never accessed from the wrong cpu, no locking,
61  *      and local interrupts are disabled so slab code is preempt-safe.
62  *  The non-constant members are protected with a per-cache irq spinlock.
63  *
64  * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65  * in 2000 - many ideas in the current implementation are derived from
66  * his patch.
67  *
68  * Further notes from the original documentation:
69  *
70  * 11 April '97.  Started multi-threading - markhe
71  *      The global cache-chain is protected by the mutex 'slab_mutex'.
72  *      The sem is only needed when accessing/extending the cache-chain, which
73  *      can never happen inside an interrupt (kmem_cache_create(),
74  *      kmem_cache_shrink() and kmem_cache_reap()).
75  *
76  *      At present, each engine can be growing a cache.  This should be blocked.
77  *
78  * 15 March 2005. NUMA slab allocator.
79  *      Shai Fultheim <shai@scalex86.org>.
80  *      Shobhit Dayal <shobhit@calsoftinc.com>
81  *      Alok N Kataria <alokk@calsoftinc.com>
82  *      Christoph Lameter <christoph@lameter.com>
83  *
84  *      Modified the slab allocator to be node aware on NUMA systems.
85  *      Each node has its own list of partial, free and full slabs.
86  *      All object allocations for a node occur from node specific slab lists.
87  */
88
89 #include        <linux/slab.h>
90 #include        <linux/mm.h>
91 #include        <linux/poison.h>
92 #include        <linux/swap.h>
93 #include        <linux/cache.h>
94 #include        <linux/interrupt.h>
95 #include        <linux/init.h>
96 #include        <linux/compiler.h>
97 #include        <linux/cpuset.h>
98 #include        <linux/proc_fs.h>
99 #include        <linux/seq_file.h>
100 #include        <linux/notifier.h>
101 #include        <linux/kallsyms.h>
102 #include        <linux/cpu.h>
103 #include        <linux/sysctl.h>
104 #include        <linux/module.h>
105 #include        <linux/rcupdate.h>
106 #include        <linux/string.h>
107 #include        <linux/uaccess.h>
108 #include        <linux/nodemask.h>
109 #include        <linux/kmemleak.h>
110 #include        <linux/mempolicy.h>
111 #include        <linux/mutex.h>
112 #include        <linux/fault-inject.h>
113 #include        <linux/rtmutex.h>
114 #include        <linux/reciprocal_div.h>
115 #include        <linux/debugobjects.h>
116 #include        <linux/kmemcheck.h>
117 #include        <linux/memory.h>
118 #include        <linux/prefetch.h>
119
120 #include        <net/sock.h>
121
122 #include        <asm/cacheflush.h>
123 #include        <asm/tlbflush.h>
124 #include        <asm/page.h>
125
126 #include <trace/events/kmem.h>
127
128 #include        "internal.h"
129
130 #include        "slab.h"
131
132 /*
133  * DEBUG        - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
134  *                0 for faster, smaller code (especially in the critical paths).
135  *
136  * STATS        - 1 to collect stats for /proc/slabinfo.
137  *                0 for faster, smaller code (especially in the critical paths).
138  *
139  * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
140  */
141
142 #ifdef CONFIG_DEBUG_SLAB
143 #define DEBUG           1
144 #define STATS           1
145 #define FORCED_DEBUG    1
146 #else
147 #define DEBUG           0
148 #define STATS           0
149 #define FORCED_DEBUG    0
150 #endif
151
152 /* Shouldn't this be in a header file somewhere? */
153 #define BYTES_PER_WORD          sizeof(void *)
154 #define REDZONE_ALIGN           max(BYTES_PER_WORD, __alignof__(unsigned long long))
155
156 #ifndef ARCH_KMALLOC_FLAGS
157 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
158 #endif
159
160 #define FREELIST_BYTE_INDEX (((PAGE_SIZE >> BITS_PER_BYTE) \
161                                 <= SLAB_OBJ_MIN_SIZE) ? 1 : 0)
162
163 #if FREELIST_BYTE_INDEX
164 typedef unsigned char freelist_idx_t;
165 #else
166 typedef unsigned short freelist_idx_t;
167 #endif
168
169 #define SLAB_OBJ_MAX_NUM ((1 << sizeof(freelist_idx_t) * BITS_PER_BYTE) - 1)
170
171 /*
172  * struct array_cache
173  *
174  * Purpose:
175  * - LIFO ordering, to hand out cache-warm objects from _alloc
176  * - reduce the number of linked list operations
177  * - reduce spinlock operations
178  *
179  * The limit is stored in the per-cpu structure to reduce the data cache
180  * footprint.
181  *
182  */
183 struct array_cache {
184         unsigned int avail;
185         unsigned int limit;
186         unsigned int batchcount;
187         unsigned int touched;
188         void *entry[];  /*
189                          * Must have this definition in here for the proper
190                          * alignment of array_cache. Also simplifies accessing
191                          * the entries.
192                          */
193 };
194
195 struct alien_cache {
196         spinlock_t lock;
197         struct array_cache ac;
198 };
199
200 /*
201  * Need this for bootstrapping a per node allocator.
202  */
203 #define NUM_INIT_LISTS (2 * MAX_NUMNODES)
204 static struct kmem_cache_node __initdata init_kmem_cache_node[NUM_INIT_LISTS];
205 #define CACHE_CACHE 0
206 #define SIZE_NODE (MAX_NUMNODES)
207
208 static int drain_freelist(struct kmem_cache *cache,
209                         struct kmem_cache_node *n, int tofree);
210 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
211                         int node, struct list_head *list);
212 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list);
213 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
214 static void cache_reap(struct work_struct *unused);
215
216 static inline void fixup_objfreelist_debug(struct kmem_cache *cachep,
217                                                 void **list);
218 static inline void fixup_slab_list(struct kmem_cache *cachep,
219                                 struct kmem_cache_node *n, struct page *page,
220                                 void **list);
221 static int slab_early_init = 1;
222
223 #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
224
225 static void kmem_cache_node_init(struct kmem_cache_node *parent)
226 {
227         INIT_LIST_HEAD(&parent->slabs_full);
228         INIT_LIST_HEAD(&parent->slabs_partial);
229         INIT_LIST_HEAD(&parent->slabs_free);
230         parent->shared = NULL;
231         parent->alien = NULL;
232         parent->colour_next = 0;
233         spin_lock_init(&parent->list_lock);
234         parent->free_objects = 0;
235         parent->free_touched = 0;
236 }
237
238 #define MAKE_LIST(cachep, listp, slab, nodeid)                          \
239         do {                                                            \
240                 INIT_LIST_HEAD(listp);                                  \
241                 list_splice(&get_node(cachep, nodeid)->slab, listp);    \
242         } while (0)
243
244 #define MAKE_ALL_LISTS(cachep, ptr, nodeid)                             \
245         do {                                                            \
246         MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid);  \
247         MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
248         MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid);  \
249         } while (0)
250
251 #define CFLGS_OBJFREELIST_SLAB  (0x40000000UL)
252 #define CFLGS_OFF_SLAB          (0x80000000UL)
253 #define OBJFREELIST_SLAB(x)     ((x)->flags & CFLGS_OBJFREELIST_SLAB)
254 #define OFF_SLAB(x)     ((x)->flags & CFLGS_OFF_SLAB)
255
256 #define BATCHREFILL_LIMIT       16
257 /*
258  * Optimization question: fewer reaps means less probability for unnessary
259  * cpucache drain/refill cycles.
260  *
261  * OTOH the cpuarrays can contain lots of objects,
262  * which could lock up otherwise freeable slabs.
263  */
264 #define REAPTIMEOUT_AC          (2*HZ)
265 #define REAPTIMEOUT_NODE        (4*HZ)
266
267 #if STATS
268 #define STATS_INC_ACTIVE(x)     ((x)->num_active++)
269 #define STATS_DEC_ACTIVE(x)     ((x)->num_active--)
270 #define STATS_INC_ALLOCED(x)    ((x)->num_allocations++)
271 #define STATS_INC_GROWN(x)      ((x)->grown++)
272 #define STATS_ADD_REAPED(x,y)   ((x)->reaped += (y))
273 #define STATS_SET_HIGH(x)                                               \
274         do {                                                            \
275                 if ((x)->num_active > (x)->high_mark)                   \
276                         (x)->high_mark = (x)->num_active;               \
277         } while (0)
278 #define STATS_INC_ERR(x)        ((x)->errors++)
279 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
280 #define STATS_INC_NODEFREES(x)  ((x)->node_frees++)
281 #define STATS_INC_ACOVERFLOW(x)   ((x)->node_overflow++)
282 #define STATS_SET_FREEABLE(x, i)                                        \
283         do {                                                            \
284                 if ((x)->max_freeable < i)                              \
285                         (x)->max_freeable = i;                          \
286         } while (0)
287 #define STATS_INC_ALLOCHIT(x)   atomic_inc(&(x)->allochit)
288 #define STATS_INC_ALLOCMISS(x)  atomic_inc(&(x)->allocmiss)
289 #define STATS_INC_FREEHIT(x)    atomic_inc(&(x)->freehit)
290 #define STATS_INC_FREEMISS(x)   atomic_inc(&(x)->freemiss)
291 #else
292 #define STATS_INC_ACTIVE(x)     do { } while (0)
293 #define STATS_DEC_ACTIVE(x)     do { } while (0)
294 #define STATS_INC_ALLOCED(x)    do { } while (0)
295 #define STATS_INC_GROWN(x)      do { } while (0)
296 #define STATS_ADD_REAPED(x,y)   do { (void)(y); } while (0)
297 #define STATS_SET_HIGH(x)       do { } while (0)
298 #define STATS_INC_ERR(x)        do { } while (0)
299 #define STATS_INC_NODEALLOCS(x) do { } while (0)
300 #define STATS_INC_NODEFREES(x)  do { } while (0)
301 #define STATS_INC_ACOVERFLOW(x)   do { } while (0)
302 #define STATS_SET_FREEABLE(x, i) do { } while (0)
303 #define STATS_INC_ALLOCHIT(x)   do { } while (0)
304 #define STATS_INC_ALLOCMISS(x)  do { } while (0)
305 #define STATS_INC_FREEHIT(x)    do { } while (0)
306 #define STATS_INC_FREEMISS(x)   do { } while (0)
307 #endif
308
309 #if DEBUG
310
311 /*
312  * memory layout of objects:
313  * 0            : objp
314  * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
315  *              the end of an object is aligned with the end of the real
316  *              allocation. Catches writes behind the end of the allocation.
317  * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
318  *              redzone word.
319  * cachep->obj_offset: The real object.
320  * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
321  * cachep->size - 1* BYTES_PER_WORD: last caller address
322  *                                      [BYTES_PER_WORD long]
323  */
324 static int obj_offset(struct kmem_cache *cachep)
325 {
326         return cachep->obj_offset;
327 }
328
329 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
330 {
331         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
332         return (unsigned long long*) (objp + obj_offset(cachep) -
333                                       sizeof(unsigned long long));
334 }
335
336 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
337 {
338         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
339         if (cachep->flags & SLAB_STORE_USER)
340                 return (unsigned long long *)(objp + cachep->size -
341                                               sizeof(unsigned long long) -
342                                               REDZONE_ALIGN);
343         return (unsigned long long *) (objp + cachep->size -
344                                        sizeof(unsigned long long));
345 }
346
347 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
348 {
349         BUG_ON(!(cachep->flags & SLAB_STORE_USER));
350         return (void **)(objp + cachep->size - BYTES_PER_WORD);
351 }
352
353 #else
354
355 #define obj_offset(x)                   0
356 #define dbg_redzone1(cachep, objp)      ({BUG(); (unsigned long long *)NULL;})
357 #define dbg_redzone2(cachep, objp)      ({BUG(); (unsigned long long *)NULL;})
358 #define dbg_userword(cachep, objp)      ({BUG(); (void **)NULL;})
359
360 #endif
361
362 #ifdef CONFIG_DEBUG_SLAB_LEAK
363
364 static inline bool is_store_user_clean(struct kmem_cache *cachep)
365 {
366         return atomic_read(&cachep->store_user_clean) == 1;
367 }
368
369 static inline void set_store_user_clean(struct kmem_cache *cachep)
370 {
371         atomic_set(&cachep->store_user_clean, 1);
372 }
373
374 static inline void set_store_user_dirty(struct kmem_cache *cachep)
375 {
376         if (is_store_user_clean(cachep))
377                 atomic_set(&cachep->store_user_clean, 0);
378 }
379
380 #else
381 static inline void set_store_user_dirty(struct kmem_cache *cachep) {}
382
383 #endif
384
385 /*
386  * Do not go above this order unless 0 objects fit into the slab or
387  * overridden on the command line.
388  */
389 #define SLAB_MAX_ORDER_HI       1
390 #define SLAB_MAX_ORDER_LO       0
391 static int slab_max_order = SLAB_MAX_ORDER_LO;
392 static bool slab_max_order_set __initdata;
393
394 static inline struct kmem_cache *virt_to_cache(const void *obj)
395 {
396         struct page *page = virt_to_head_page(obj);
397         return page->slab_cache;
398 }
399
400 static inline void *index_to_obj(struct kmem_cache *cache, struct page *page,
401                                  unsigned int idx)
402 {
403         return page->s_mem + cache->size * idx;
404 }
405
406 /*
407  * We want to avoid an expensive divide : (offset / cache->size)
408  *   Using the fact that size is a constant for a particular cache,
409  *   we can replace (offset / cache->size) by
410  *   reciprocal_divide(offset, cache->reciprocal_buffer_size)
411  */
412 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
413                                         const struct page *page, void *obj)
414 {
415         u32 offset = (obj - page->s_mem);
416         return reciprocal_divide(offset, cache->reciprocal_buffer_size);
417 }
418
419 #define BOOT_CPUCACHE_ENTRIES   1
420 /* internal cache of cache description objs */
421 static struct kmem_cache kmem_cache_boot = {
422         .batchcount = 1,
423         .limit = BOOT_CPUCACHE_ENTRIES,
424         .shared = 1,
425         .size = sizeof(struct kmem_cache),
426         .name = "kmem_cache",
427 };
428
429 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
430
431 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
432 {
433         return this_cpu_ptr(cachep->cpu_cache);
434 }
435
436 /*
437  * Calculate the number of objects and left-over bytes for a given buffer size.
438  */
439 static unsigned int cache_estimate(unsigned long gfporder, size_t buffer_size,
440                 unsigned long flags, size_t *left_over)
441 {
442         unsigned int num;
443         size_t slab_size = PAGE_SIZE << gfporder;
444
445         /*
446          * The slab management structure can be either off the slab or
447          * on it. For the latter case, the memory allocated for a
448          * slab is used for:
449          *
450          * - @buffer_size bytes for each object
451          * - One freelist_idx_t for each object
452          *
453          * We don't need to consider alignment of freelist because
454          * freelist will be at the end of slab page. The objects will be
455          * at the correct alignment.
456          *
457          * If the slab management structure is off the slab, then the
458          * alignment will already be calculated into the size. Because
459          * the slabs are all pages aligned, the objects will be at the
460          * correct alignment when allocated.
461          */
462         if (flags & (CFLGS_OBJFREELIST_SLAB | CFLGS_OFF_SLAB)) {
463                 num = slab_size / buffer_size;
464                 *left_over = slab_size % buffer_size;
465         } else {
466                 num = slab_size / (buffer_size + sizeof(freelist_idx_t));
467                 *left_over = slab_size %
468                         (buffer_size + sizeof(freelist_idx_t));
469         }
470
471         return num;
472 }
473
474 #if DEBUG
475 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
476
477 static void __slab_error(const char *function, struct kmem_cache *cachep,
478                         char *msg)
479 {
480         pr_err("slab error in %s(): cache `%s': %s\n",
481                function, cachep->name, msg);
482         dump_stack();
483         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
484 }
485 #endif
486
487 /*
488  * By default on NUMA we use alien caches to stage the freeing of
489  * objects allocated from other nodes. This causes massive memory
490  * inefficiencies when using fake NUMA setup to split memory into a
491  * large number of small nodes, so it can be disabled on the command
492  * line
493   */
494
495 static int use_alien_caches __read_mostly = 1;
496 static int __init noaliencache_setup(char *s)
497 {
498         use_alien_caches = 0;
499         return 1;
500 }
501 __setup("noaliencache", noaliencache_setup);
502
503 static int __init slab_max_order_setup(char *str)
504 {
505         get_option(&str, &slab_max_order);
506         slab_max_order = slab_max_order < 0 ? 0 :
507                                 min(slab_max_order, MAX_ORDER - 1);
508         slab_max_order_set = true;
509
510         return 1;
511 }
512 __setup("slab_max_order=", slab_max_order_setup);
513
514 #ifdef CONFIG_NUMA
515 /*
516  * Special reaping functions for NUMA systems called from cache_reap().
517  * These take care of doing round robin flushing of alien caches (containing
518  * objects freed on different nodes from which they were allocated) and the
519  * flushing of remote pcps by calling drain_node_pages.
520  */
521 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
522
523 static void init_reap_node(int cpu)
524 {
525         per_cpu(slab_reap_node, cpu) = next_node_in(cpu_to_mem(cpu),
526                                                     node_online_map);
527 }
528
529 static void next_reap_node(void)
530 {
531         int node = __this_cpu_read(slab_reap_node);
532
533         node = next_node_in(node, node_online_map);
534         __this_cpu_write(slab_reap_node, node);
535 }
536
537 #else
538 #define init_reap_node(cpu) do { } while (0)
539 #define next_reap_node(void) do { } while (0)
540 #endif
541
542 /*
543  * Initiate the reap timer running on the target CPU.  We run at around 1 to 2Hz
544  * via the workqueue/eventd.
545  * Add the CPU number into the expiration time to minimize the possibility of
546  * the CPUs getting into lockstep and contending for the global cache chain
547  * lock.
548  */
549 static void start_cpu_timer(int cpu)
550 {
551         struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
552
553         if (reap_work->work.func == NULL) {
554                 init_reap_node(cpu);
555                 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
556                 schedule_delayed_work_on(cpu, reap_work,
557                                         __round_jiffies_relative(HZ, cpu));
558         }
559 }
560
561 static void init_arraycache(struct array_cache *ac, int limit, int batch)
562 {
563         /*
564          * The array_cache structures contain pointers to free object.
565          * However, when such objects are allocated or transferred to another
566          * cache the pointers are not cleared and they could be counted as
567          * valid references during a kmemleak scan. Therefore, kmemleak must
568          * not scan such objects.
569          */
570         kmemleak_no_scan(ac);
571         if (ac) {
572                 ac->avail = 0;
573                 ac->limit = limit;
574                 ac->batchcount = batch;
575                 ac->touched = 0;
576         }
577 }
578
579 static struct array_cache *alloc_arraycache(int node, int entries,
580                                             int batchcount, gfp_t gfp)
581 {
582         size_t memsize = sizeof(void *) * entries + sizeof(struct array_cache);
583         struct array_cache *ac = NULL;
584
585         ac = kmalloc_node(memsize, gfp, node);
586         init_arraycache(ac, entries, batchcount);
587         return ac;
588 }
589
590 static noinline void cache_free_pfmemalloc(struct kmem_cache *cachep,
591                                         struct page *page, void *objp)
592 {
593         struct kmem_cache_node *n;
594         int page_node;
595         LIST_HEAD(list);
596
597         page_node = page_to_nid(page);
598         n = get_node(cachep, page_node);
599
600         spin_lock(&n->list_lock);
601         free_block(cachep, &objp, 1, page_node, &list);
602         spin_unlock(&n->list_lock);
603
604         slabs_destroy(cachep, &list);
605 }
606
607 /*
608  * Transfer objects in one arraycache to another.
609  * Locking must be handled by the caller.
610  *
611  * Return the number of entries transferred.
612  */
613 static int transfer_objects(struct array_cache *to,
614                 struct array_cache *from, unsigned int max)
615 {
616         /* Figure out how many entries to transfer */
617         int nr = min3(from->avail, max, to->limit - to->avail);
618
619         if (!nr)
620                 return 0;
621
622         memcpy(to->entry + to->avail, from->entry + from->avail -nr,
623                         sizeof(void *) *nr);
624
625         from->avail -= nr;
626         to->avail += nr;
627         return nr;
628 }
629
630 #ifndef CONFIG_NUMA
631
632 #define drain_alien_cache(cachep, alien) do { } while (0)
633 #define reap_alien(cachep, n) do { } while (0)
634
635 static inline struct alien_cache **alloc_alien_cache(int node,
636                                                 int limit, gfp_t gfp)
637 {
638         return NULL;
639 }
640
641 static inline void free_alien_cache(struct alien_cache **ac_ptr)
642 {
643 }
644
645 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
646 {
647         return 0;
648 }
649
650 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
651                 gfp_t flags)
652 {
653         return NULL;
654 }
655
656 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
657                  gfp_t flags, int nodeid)
658 {
659         return NULL;
660 }
661
662 static inline gfp_t gfp_exact_node(gfp_t flags)
663 {
664         return flags & ~__GFP_NOFAIL;
665 }
666
667 #else   /* CONFIG_NUMA */
668
669 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
670 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
671
672 static struct alien_cache *__alloc_alien_cache(int node, int entries,
673                                                 int batch, gfp_t gfp)
674 {
675         size_t memsize = sizeof(void *) * entries + sizeof(struct alien_cache);
676         struct alien_cache *alc = NULL;
677
678         alc = kmalloc_node(memsize, gfp, node);
679         init_arraycache(&alc->ac, entries, batch);
680         spin_lock_init(&alc->lock);
681         return alc;
682 }
683
684 static struct alien_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
685 {
686         struct alien_cache **alc_ptr;
687         size_t memsize = sizeof(void *) * nr_node_ids;
688         int i;
689
690         if (limit > 1)
691                 limit = 12;
692         alc_ptr = kzalloc_node(memsize, gfp, node);
693         if (!alc_ptr)
694                 return NULL;
695
696         for_each_node(i) {
697                 if (i == node || !node_online(i))
698                         continue;
699                 alc_ptr[i] = __alloc_alien_cache(node, limit, 0xbaadf00d, gfp);
700                 if (!alc_ptr[i]) {
701                         for (i--; i >= 0; i--)
702                                 kfree(alc_ptr[i]);
703                         kfree(alc_ptr);
704                         return NULL;
705                 }
706         }
707         return alc_ptr;
708 }
709
710 static void free_alien_cache(struct alien_cache **alc_ptr)
711 {
712         int i;
713
714         if (!alc_ptr)
715                 return;
716         for_each_node(i)
717             kfree(alc_ptr[i]);
718         kfree(alc_ptr);
719 }
720
721 static void __drain_alien_cache(struct kmem_cache *cachep,
722                                 struct array_cache *ac, int node,
723                                 struct list_head *list)
724 {
725         struct kmem_cache_node *n = get_node(cachep, node);
726
727         if (ac->avail) {
728                 spin_lock(&n->list_lock);
729                 /*
730                  * Stuff objects into the remote nodes shared array first.
731                  * That way we could avoid the overhead of putting the objects
732                  * into the free lists and getting them back later.
733                  */
734                 if (n->shared)
735                         transfer_objects(n->shared, ac, ac->limit);
736
737                 free_block(cachep, ac->entry, ac->avail, node, list);
738                 ac->avail = 0;
739                 spin_unlock(&n->list_lock);
740         }
741 }
742
743 /*
744  * Called from cache_reap() to regularly drain alien caches round robin.
745  */
746 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
747 {
748         int node = __this_cpu_read(slab_reap_node);
749
750         if (n->alien) {
751                 struct alien_cache *alc = n->alien[node];
752                 struct array_cache *ac;
753
754                 if (alc) {
755                         ac = &alc->ac;
756                         if (ac->avail && spin_trylock_irq(&alc->lock)) {
757                                 LIST_HEAD(list);
758
759                                 __drain_alien_cache(cachep, ac, node, &list);
760                                 spin_unlock_irq(&alc->lock);
761                                 slabs_destroy(cachep, &list);
762                         }
763                 }
764         }
765 }
766
767 static void drain_alien_cache(struct kmem_cache *cachep,
768                                 struct alien_cache **alien)
769 {
770         int i = 0;
771         struct alien_cache *alc;
772         struct array_cache *ac;
773         unsigned long flags;
774
775         for_each_online_node(i) {
776                 alc = alien[i];
777                 if (alc) {
778                         LIST_HEAD(list);
779
780                         ac = &alc->ac;
781                         spin_lock_irqsave(&alc->lock, flags);
782                         __drain_alien_cache(cachep, ac, i, &list);
783                         spin_unlock_irqrestore(&alc->lock, flags);
784                         slabs_destroy(cachep, &list);
785                 }
786         }
787 }
788
789 static int __cache_free_alien(struct kmem_cache *cachep, void *objp,
790                                 int node, int page_node)
791 {
792         struct kmem_cache_node *n;
793         struct alien_cache *alien = NULL;
794         struct array_cache *ac;
795         LIST_HEAD(list);
796
797         n = get_node(cachep, node);
798         STATS_INC_NODEFREES(cachep);
799         if (n->alien && n->alien[page_node]) {
800                 alien = n->alien[page_node];
801                 ac = &alien->ac;
802                 spin_lock(&alien->lock);
803                 if (unlikely(ac->avail == ac->limit)) {
804                         STATS_INC_ACOVERFLOW(cachep);
805                         __drain_alien_cache(cachep, ac, page_node, &list);
806                 }
807                 ac->entry[ac->avail++] = objp;
808                 spin_unlock(&alien->lock);
809                 slabs_destroy(cachep, &list);
810         } else {
811                 n = get_node(cachep, page_node);
812                 spin_lock(&n->list_lock);
813                 free_block(cachep, &objp, 1, page_node, &list);
814                 spin_unlock(&n->list_lock);
815                 slabs_destroy(cachep, &list);
816         }
817         return 1;
818 }
819
820 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
821 {
822         int page_node = page_to_nid(virt_to_page(objp));
823         int node = numa_mem_id();
824         /*
825          * Make sure we are not freeing a object from another node to the array
826          * cache on this cpu.
827          */
828         if (likely(node == page_node))
829                 return 0;
830
831         return __cache_free_alien(cachep, objp, node, page_node);
832 }
833
834 /*
835  * Construct gfp mask to allocate from a specific node but do not reclaim or
836  * warn about failures.
837  */
838 static inline gfp_t gfp_exact_node(gfp_t flags)
839 {
840         return (flags | __GFP_THISNODE | __GFP_NOWARN) & ~(__GFP_RECLAIM|__GFP_NOFAIL);
841 }
842 #endif
843
844 static int init_cache_node(struct kmem_cache *cachep, int node, gfp_t gfp)
845 {
846         struct kmem_cache_node *n;
847
848         /*
849          * Set up the kmem_cache_node for cpu before we can
850          * begin anything. Make sure some other cpu on this
851          * node has not already allocated this
852          */
853         n = get_node(cachep, node);
854         if (n) {
855                 spin_lock_irq(&n->list_lock);
856                 n->free_limit = (1 + nr_cpus_node(node)) * cachep->batchcount +
857                                 cachep->num;
858                 spin_unlock_irq(&n->list_lock);
859
860                 return 0;
861         }
862
863         n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
864         if (!n)
865                 return -ENOMEM;
866
867         kmem_cache_node_init(n);
868         n->next_reap = jiffies + REAPTIMEOUT_NODE +
869                     ((unsigned long)cachep) % REAPTIMEOUT_NODE;
870
871         n->free_limit =
872                 (1 + nr_cpus_node(node)) * cachep->batchcount + cachep->num;
873
874         /*
875          * The kmem_cache_nodes don't come and go as CPUs
876          * come and go.  slab_mutex is sufficient
877          * protection here.
878          */
879         cachep->node[node] = n;
880
881         return 0;
882 }
883
884 #if (defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)) || defined(CONFIG_SMP)
885 /*
886  * Allocates and initializes node for a node on each slab cache, used for
887  * either memory or cpu hotplug.  If memory is being hot-added, the kmem_cache_node
888  * will be allocated off-node since memory is not yet online for the new node.
889  * When hotplugging memory or a cpu, existing node are not replaced if
890  * already in use.
891  *
892  * Must hold slab_mutex.
893  */
894 static int init_cache_node_node(int node)
895 {
896         int ret;
897         struct kmem_cache *cachep;
898
899         list_for_each_entry(cachep, &slab_caches, list) {
900                 ret = init_cache_node(cachep, node, GFP_KERNEL);
901                 if (ret)
902                         return ret;
903         }
904
905         return 0;
906 }
907 #endif
908
909 static int setup_kmem_cache_node(struct kmem_cache *cachep,
910                                 int node, gfp_t gfp, bool force_change)
911 {
912         int ret = -ENOMEM;
913         struct kmem_cache_node *n;
914         struct array_cache *old_shared = NULL;
915         struct array_cache *new_shared = NULL;
916         struct alien_cache **new_alien = NULL;
917         LIST_HEAD(list);
918
919         if (use_alien_caches) {
920                 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
921                 if (!new_alien)
922                         goto fail;
923         }
924
925         if (cachep->shared) {
926                 new_shared = alloc_arraycache(node,
927                         cachep->shared * cachep->batchcount, 0xbaadf00d, gfp);
928                 if (!new_shared)
929                         goto fail;
930         }
931
932         ret = init_cache_node(cachep, node, gfp);
933         if (ret)
934                 goto fail;
935
936         n = get_node(cachep, node);
937         spin_lock_irq(&n->list_lock);
938         if (n->shared && force_change) {
939                 free_block(cachep, n->shared->entry,
940                                 n->shared->avail, node, &list);
941                 n->shared->avail = 0;
942         }
943
944         if (!n->shared || force_change) {
945                 old_shared = n->shared;
946                 n->shared = new_shared;
947                 new_shared = NULL;
948         }
949
950         if (!n->alien) {
951                 n->alien = new_alien;
952                 new_alien = NULL;
953         }
954
955         spin_unlock_irq(&n->list_lock);
956         slabs_destroy(cachep, &list);
957
958         /*
959          * To protect lockless access to n->shared during irq disabled context.
960          * If n->shared isn't NULL in irq disabled context, accessing to it is
961          * guaranteed to be valid until irq is re-enabled, because it will be
962          * freed after synchronize_sched().
963          */
964         if (force_change)
965                 synchronize_sched();
966
967 fail:
968         kfree(old_shared);
969         kfree(new_shared);
970         free_alien_cache(new_alien);
971
972         return ret;
973 }
974
975 #ifdef CONFIG_SMP
976
977 static void cpuup_canceled(long cpu)
978 {
979         struct kmem_cache *cachep;
980         struct kmem_cache_node *n = NULL;
981         int node = cpu_to_mem(cpu);
982         const struct cpumask *mask = cpumask_of_node(node);
983
984         list_for_each_entry(cachep, &slab_caches, list) {
985                 struct array_cache *nc;
986                 struct array_cache *shared;
987                 struct alien_cache **alien;
988                 LIST_HEAD(list);
989
990                 n = get_node(cachep, node);
991                 if (!n)
992                         continue;
993
994                 spin_lock_irq(&n->list_lock);
995
996                 /* Free limit for this kmem_cache_node */
997                 n->free_limit -= cachep->batchcount;
998
999                 /* cpu is dead; no one can alloc from it. */
1000                 nc = per_cpu_ptr(cachep->cpu_cache, cpu);
1001                 if (nc) {
1002                         free_block(cachep, nc->entry, nc->avail, node, &list);
1003                         nc->avail = 0;
1004                 }
1005
1006                 if (!cpumask_empty(mask)) {
1007                         spin_unlock_irq(&n->list_lock);
1008                         goto free_slab;
1009                 }
1010
1011                 shared = n->shared;
1012                 if (shared) {
1013                         free_block(cachep, shared->entry,
1014                                    shared->avail, node, &list);
1015                         n->shared = NULL;
1016                 }
1017
1018                 alien = n->alien;
1019                 n->alien = NULL;
1020
1021                 spin_unlock_irq(&n->list_lock);
1022
1023                 kfree(shared);
1024                 if (alien) {
1025                         drain_alien_cache(cachep, alien);
1026                         free_alien_cache(alien);
1027                 }
1028
1029 free_slab:
1030                 slabs_destroy(cachep, &list);
1031         }
1032         /*
1033          * In the previous loop, all the objects were freed to
1034          * the respective cache's slabs,  now we can go ahead and
1035          * shrink each nodelist to its limit.
1036          */
1037         list_for_each_entry(cachep, &slab_caches, list) {
1038                 n = get_node(cachep, node);
1039                 if (!n)
1040                         continue;
1041                 drain_freelist(cachep, n, INT_MAX);
1042         }
1043 }
1044
1045 static int cpuup_prepare(long cpu)
1046 {
1047         struct kmem_cache *cachep;
1048         int node = cpu_to_mem(cpu);
1049         int err;
1050
1051         /*
1052          * We need to do this right in the beginning since
1053          * alloc_arraycache's are going to use this list.
1054          * kmalloc_node allows us to add the slab to the right
1055          * kmem_cache_node and not this cpu's kmem_cache_node
1056          */
1057         err = init_cache_node_node(node);
1058         if (err < 0)
1059                 goto bad;
1060
1061         /*
1062          * Now we can go ahead with allocating the shared arrays and
1063          * array caches
1064          */
1065         list_for_each_entry(cachep, &slab_caches, list) {
1066                 err = setup_kmem_cache_node(cachep, node, GFP_KERNEL, false);
1067                 if (err)
1068                         goto bad;
1069         }
1070
1071         return 0;
1072 bad:
1073         cpuup_canceled(cpu);
1074         return -ENOMEM;
1075 }
1076
1077 int slab_prepare_cpu(unsigned int cpu)
1078 {
1079         int err;
1080
1081         mutex_lock(&slab_mutex);
1082         err = cpuup_prepare(cpu);
1083         mutex_unlock(&slab_mutex);
1084         return err;
1085 }
1086
1087 /*
1088  * This is called for a failed online attempt and for a successful
1089  * offline.
1090  *
1091  * Even if all the cpus of a node are down, we don't free the
1092  * kmem_list3 of any cache. This to avoid a race between cpu_down, and
1093  * a kmalloc allocation from another cpu for memory from the node of
1094  * the cpu going down.  The list3 structure is usually allocated from
1095  * kmem_cache_create() and gets destroyed at kmem_cache_destroy().
1096  */
1097 int slab_dead_cpu(unsigned int cpu)
1098 {
1099         mutex_lock(&slab_mutex);
1100         cpuup_canceled(cpu);
1101         mutex_unlock(&slab_mutex);
1102         return 0;
1103 }
1104 #endif
1105
1106 static int slab_online_cpu(unsigned int cpu)
1107 {
1108         start_cpu_timer(cpu);
1109         return 0;
1110 }
1111
1112 static int slab_offline_cpu(unsigned int cpu)
1113 {
1114         /*
1115          * Shutdown cache reaper. Note that the slab_mutex is held so
1116          * that if cache_reap() is invoked it cannot do anything
1117          * expensive but will only modify reap_work and reschedule the
1118          * timer.
1119          */
1120         cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1121         /* Now the cache_reaper is guaranteed to be not running. */
1122         per_cpu(slab_reap_work, cpu).work.func = NULL;
1123         return 0;
1124 }
1125
1126 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1127 /*
1128  * Drains freelist for a node on each slab cache, used for memory hot-remove.
1129  * Returns -EBUSY if all objects cannot be drained so that the node is not
1130  * removed.
1131  *
1132  * Must hold slab_mutex.
1133  */
1134 static int __meminit drain_cache_node_node(int node)
1135 {
1136         struct kmem_cache *cachep;
1137         int ret = 0;
1138
1139         list_for_each_entry(cachep, &slab_caches, list) {
1140                 struct kmem_cache_node *n;
1141
1142                 n = get_node(cachep, node);
1143                 if (!n)
1144                         continue;
1145
1146                 drain_freelist(cachep, n, INT_MAX);
1147
1148                 if (!list_empty(&n->slabs_full) ||
1149                     !list_empty(&n->slabs_partial)) {
1150                         ret = -EBUSY;
1151                         break;
1152                 }
1153         }
1154         return ret;
1155 }
1156
1157 static int __meminit slab_memory_callback(struct notifier_block *self,
1158                                         unsigned long action, void *arg)
1159 {
1160         struct memory_notify *mnb = arg;
1161         int ret = 0;
1162         int nid;
1163
1164         nid = mnb->status_change_nid;
1165         if (nid < 0)
1166                 goto out;
1167
1168         switch (action) {
1169         case MEM_GOING_ONLINE:
1170                 mutex_lock(&slab_mutex);
1171                 ret = init_cache_node_node(nid);
1172                 mutex_unlock(&slab_mutex);
1173                 break;
1174         case MEM_GOING_OFFLINE:
1175                 mutex_lock(&slab_mutex);
1176                 ret = drain_cache_node_node(nid);
1177                 mutex_unlock(&slab_mutex);
1178                 break;
1179         case MEM_ONLINE:
1180         case MEM_OFFLINE:
1181         case MEM_CANCEL_ONLINE:
1182         case MEM_CANCEL_OFFLINE:
1183                 break;
1184         }
1185 out:
1186         return notifier_from_errno(ret);
1187 }
1188 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1189
1190 /*
1191  * swap the static kmem_cache_node with kmalloced memory
1192  */
1193 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1194                                 int nodeid)
1195 {
1196         struct kmem_cache_node *ptr;
1197
1198         ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1199         BUG_ON(!ptr);
1200
1201         memcpy(ptr, list, sizeof(struct kmem_cache_node));
1202         /*
1203          * Do not assume that spinlocks can be initialized via memcpy:
1204          */
1205         spin_lock_init(&ptr->list_lock);
1206
1207         MAKE_ALL_LISTS(cachep, ptr, nodeid);
1208         cachep->node[nodeid] = ptr;
1209 }
1210
1211 /*
1212  * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1213  * size of kmem_cache_node.
1214  */
1215 static void __init set_up_node(struct kmem_cache *cachep, int index)
1216 {
1217         int node;
1218
1219         for_each_online_node(node) {
1220                 cachep->node[node] = &init_kmem_cache_node[index + node];
1221                 cachep->node[node]->next_reap = jiffies +
1222                     REAPTIMEOUT_NODE +
1223                     ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1224         }
1225 }
1226
1227 /*
1228  * Initialisation.  Called after the page allocator have been initialised and
1229  * before smp_init().
1230  */
1231 void __init kmem_cache_init(void)
1232 {
1233         int i;
1234
1235         BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1236                                         sizeof(struct rcu_head));
1237         kmem_cache = &kmem_cache_boot;
1238
1239         if (!IS_ENABLED(CONFIG_NUMA) || num_possible_nodes() == 1)
1240                 use_alien_caches = 0;
1241
1242         for (i = 0; i < NUM_INIT_LISTS; i++)
1243                 kmem_cache_node_init(&init_kmem_cache_node[i]);
1244
1245         /*
1246          * Fragmentation resistance on low memory - only use bigger
1247          * page orders on machines with more than 32MB of memory if
1248          * not overridden on the command line.
1249          */
1250         if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1251                 slab_max_order = SLAB_MAX_ORDER_HI;
1252
1253         /* Bootstrap is tricky, because several objects are allocated
1254          * from caches that do not exist yet:
1255          * 1) initialize the kmem_cache cache: it contains the struct
1256          *    kmem_cache structures of all caches, except kmem_cache itself:
1257          *    kmem_cache is statically allocated.
1258          *    Initially an __init data area is used for the head array and the
1259          *    kmem_cache_node structures, it's replaced with a kmalloc allocated
1260          *    array at the end of the bootstrap.
1261          * 2) Create the first kmalloc cache.
1262          *    The struct kmem_cache for the new cache is allocated normally.
1263          *    An __init data area is used for the head array.
1264          * 3) Create the remaining kmalloc caches, with minimally sized
1265          *    head arrays.
1266          * 4) Replace the __init data head arrays for kmem_cache and the first
1267          *    kmalloc cache with kmalloc allocated arrays.
1268          * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1269          *    the other cache's with kmalloc allocated memory.
1270          * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1271          */
1272
1273         /* 1) create the kmem_cache */
1274
1275         /*
1276          * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1277          */
1278         create_boot_cache(kmem_cache, "kmem_cache",
1279                 offsetof(struct kmem_cache, node) +
1280                                   nr_node_ids * sizeof(struct kmem_cache_node *),
1281                                   SLAB_HWCACHE_ALIGN);
1282         list_add(&kmem_cache->list, &slab_caches);
1283         slab_state = PARTIAL;
1284
1285         /*
1286          * Initialize the caches that provide memory for the  kmem_cache_node
1287          * structures first.  Without this, further allocations will bug.
1288          */
1289         kmalloc_caches[INDEX_NODE] = create_kmalloc_cache("kmalloc-node",
1290                                 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1291         slab_state = PARTIAL_NODE;
1292         setup_kmalloc_cache_index_table();
1293
1294         slab_early_init = 0;
1295
1296         /* 5) Replace the bootstrap kmem_cache_node */
1297         {
1298                 int nid;
1299
1300                 for_each_online_node(nid) {
1301                         init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1302
1303                         init_list(kmalloc_caches[INDEX_NODE],
1304                                           &init_kmem_cache_node[SIZE_NODE + nid], nid);
1305                 }
1306         }
1307
1308         create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1309 }
1310
1311 void __init kmem_cache_init_late(void)
1312 {
1313         struct kmem_cache *cachep;
1314
1315         slab_state = UP;
1316
1317         /* 6) resize the head arrays to their final sizes */
1318         mutex_lock(&slab_mutex);
1319         list_for_each_entry(cachep, &slab_caches, list)
1320                 if (enable_cpucache(cachep, GFP_NOWAIT))
1321                         BUG();
1322         mutex_unlock(&slab_mutex);
1323
1324         /* Done! */
1325         slab_state = FULL;
1326
1327 #ifdef CONFIG_NUMA
1328         /*
1329          * Register a memory hotplug callback that initializes and frees
1330          * node.
1331          */
1332         hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1333 #endif
1334
1335         /*
1336          * The reap timers are started later, with a module init call: That part
1337          * of the kernel is not yet operational.
1338          */
1339 }
1340
1341 static int __init cpucache_init(void)
1342 {
1343         int ret;
1344
1345         /*
1346          * Register the timers that return unneeded pages to the page allocator
1347          */
1348         ret = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "SLAB online",
1349                                 slab_online_cpu, slab_offline_cpu);
1350         WARN_ON(ret < 0);
1351
1352         /* Done! */
1353         slab_state = FULL;
1354         return 0;
1355 }
1356 __initcall(cpucache_init);
1357
1358 static noinline void
1359 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1360 {
1361 #if DEBUG
1362         struct kmem_cache_node *n;
1363         struct page *page;
1364         unsigned long flags;
1365         int node;
1366         static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1367                                       DEFAULT_RATELIMIT_BURST);
1368
1369         if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1370                 return;
1371
1372         pr_warn("SLAB: Unable to allocate memory on node %d, gfp=%#x(%pGg)\n",
1373                 nodeid, gfpflags, &gfpflags);
1374         pr_warn("  cache: %s, object size: %d, order: %d\n",
1375                 cachep->name, cachep->size, cachep->gfporder);
1376
1377         for_each_kmem_cache_node(cachep, node, n) {
1378                 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1379                 unsigned long active_slabs = 0, num_slabs = 0;
1380
1381                 spin_lock_irqsave(&n->list_lock, flags);
1382                 list_for_each_entry(page, &n->slabs_full, lru) {
1383                         active_objs += cachep->num;
1384                         active_slabs++;
1385                 }
1386                 list_for_each_entry(page, &n->slabs_partial, lru) {
1387                         active_objs += page->active;
1388                         active_slabs++;
1389                 }
1390                 list_for_each_entry(page, &n->slabs_free, lru)
1391                         num_slabs++;
1392
1393                 free_objects += n->free_objects;
1394                 spin_unlock_irqrestore(&n->list_lock, flags);
1395
1396                 num_slabs += active_slabs;
1397                 num_objs = num_slabs * cachep->num;
1398                 pr_warn("  node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1399                         node, active_slabs, num_slabs, active_objs, num_objs,
1400                         free_objects);
1401         }
1402 #endif
1403 }
1404
1405 /*
1406  * Interface to system's page allocator. No need to hold the
1407  * kmem_cache_node ->list_lock.
1408  *
1409  * If we requested dmaable memory, we will get it. Even if we
1410  * did not request dmaable memory, we might get it, but that
1411  * would be relatively rare and ignorable.
1412  */
1413 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1414                                                                 int nodeid)
1415 {
1416         struct page *page;
1417         int nr_pages;
1418
1419         flags |= cachep->allocflags;
1420         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1421                 flags |= __GFP_RECLAIMABLE;
1422
1423         page = __alloc_pages_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1424         if (!page) {
1425                 slab_out_of_memory(cachep, flags, nodeid);
1426                 return NULL;
1427         }
1428
1429         if (memcg_charge_slab(page, flags, cachep->gfporder, cachep)) {
1430                 __free_pages(page, cachep->gfporder);
1431                 return NULL;
1432         }
1433
1434         nr_pages = (1 << cachep->gfporder);
1435         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1436                 add_zone_page_state(page_zone(page),
1437                         NR_SLAB_RECLAIMABLE, nr_pages);
1438         else
1439                 add_zone_page_state(page_zone(page),
1440                         NR_SLAB_UNRECLAIMABLE, nr_pages);
1441
1442         __SetPageSlab(page);
1443         /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1444         if (sk_memalloc_socks() && page_is_pfmemalloc(page))
1445                 SetPageSlabPfmemalloc(page);
1446
1447         if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1448                 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1449
1450                 if (cachep->ctor)
1451                         kmemcheck_mark_uninitialized_pages(page, nr_pages);
1452                 else
1453                         kmemcheck_mark_unallocated_pages(page, nr_pages);
1454         }
1455
1456         return page;
1457 }
1458
1459 /*
1460  * Interface to system's page release.
1461  */
1462 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1463 {
1464         int order = cachep->gfporder;
1465         unsigned long nr_freed = (1 << order);
1466
1467         kmemcheck_free_shadow(page, order);
1468
1469         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1470                 sub_zone_page_state(page_zone(page),
1471                                 NR_SLAB_RECLAIMABLE, nr_freed);
1472         else
1473                 sub_zone_page_state(page_zone(page),
1474                                 NR_SLAB_UNRECLAIMABLE, nr_freed);
1475
1476         BUG_ON(!PageSlab(page));
1477         __ClearPageSlabPfmemalloc(page);
1478         __ClearPageSlab(page);
1479         page_mapcount_reset(page);
1480         page->mapping = NULL;
1481
1482         if (current->reclaim_state)
1483                 current->reclaim_state->reclaimed_slab += nr_freed;
1484         memcg_uncharge_slab(page, order, cachep);
1485         __free_pages(page, order);
1486 }
1487
1488 static void kmem_rcu_free(struct rcu_head *head)
1489 {
1490         struct kmem_cache *cachep;
1491         struct page *page;
1492
1493         page = container_of(head, struct page, rcu_head);
1494         cachep = page->slab_cache;
1495
1496         kmem_freepages(cachep, page);
1497 }
1498
1499 #if DEBUG
1500 static bool is_debug_pagealloc_cache(struct kmem_cache *cachep)
1501 {
1502         if (debug_pagealloc_enabled() && OFF_SLAB(cachep) &&
1503                 (cachep->size % PAGE_SIZE) == 0)
1504                 return true;
1505
1506         return false;
1507 }
1508
1509 #ifdef CONFIG_DEBUG_PAGEALLOC
1510 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1511                             unsigned long caller)
1512 {
1513         int size = cachep->object_size;
1514
1515         addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1516
1517         if (size < 5 * sizeof(unsigned long))
1518                 return;
1519
1520         *addr++ = 0x12345678;
1521         *addr++ = caller;
1522         *addr++ = smp_processor_id();
1523         size -= 3 * sizeof(unsigned long);
1524         {
1525                 unsigned long *sptr = &caller;
1526                 unsigned long svalue;
1527
1528                 while (!kstack_end(sptr)) {
1529                         svalue = *sptr++;
1530                         if (kernel_text_address(svalue)) {
1531                                 *addr++ = svalue;
1532                                 size -= sizeof(unsigned long);
1533                                 if (size <= sizeof(unsigned long))
1534                                         break;
1535                         }
1536                 }
1537
1538         }
1539         *addr++ = 0x87654321;
1540 }
1541
1542 static void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1543                                 int map, unsigned long caller)
1544 {
1545         if (!is_debug_pagealloc_cache(cachep))
1546                 return;
1547
1548         if (caller)
1549                 store_stackinfo(cachep, objp, caller);
1550
1551         kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map);
1552 }
1553
1554 #else
1555 static inline void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1556                                 int map, unsigned long caller) {}
1557
1558 #endif
1559
1560 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1561 {
1562         int size = cachep->object_size;
1563         addr = &((char *)addr)[obj_offset(cachep)];
1564
1565         memset(addr, val, size);
1566         *(unsigned char *)(addr + size - 1) = POISON_END;
1567 }
1568
1569 static void dump_line(char *data, int offset, int limit)
1570 {
1571         int i;
1572         unsigned char error = 0;
1573         int bad_count = 0;
1574
1575         pr_err("%03x: ", offset);
1576         for (i = 0; i < limit; i++) {
1577                 if (data[offset + i] != POISON_FREE) {
1578                         error = data[offset + i];
1579                         bad_count++;
1580                 }
1581         }
1582         print_hex_dump(KERN_CONT, "", 0, 16, 1,
1583                         &data[offset], limit, 1);
1584
1585         if (bad_count == 1) {
1586                 error ^= POISON_FREE;
1587                 if (!(error & (error - 1))) {
1588                         pr_err("Single bit error detected. Probably bad RAM.\n");
1589 #ifdef CONFIG_X86
1590                         pr_err("Run memtest86+ or a similar memory test tool.\n");
1591 #else
1592                         pr_err("Run a memory test tool.\n");
1593 #endif
1594                 }
1595         }
1596 }
1597 #endif
1598
1599 #if DEBUG
1600
1601 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1602 {
1603         int i, size;
1604         char *realobj;
1605
1606         if (cachep->flags & SLAB_RED_ZONE) {
1607                 pr_err("Redzone: 0x%llx/0x%llx\n",
1608                        *dbg_redzone1(cachep, objp),
1609                        *dbg_redzone2(cachep, objp));
1610         }
1611
1612         if (cachep->flags & SLAB_STORE_USER) {
1613                 pr_err("Last user: [<%p>](%pSR)\n",
1614                        *dbg_userword(cachep, objp),
1615                        *dbg_userword(cachep, objp));
1616         }
1617         realobj = (char *)objp + obj_offset(cachep);
1618         size = cachep->object_size;
1619         for (i = 0; i < size && lines; i += 16, lines--) {
1620                 int limit;
1621                 limit = 16;
1622                 if (i + limit > size)
1623                         limit = size - i;
1624                 dump_line(realobj, i, limit);
1625         }
1626 }
1627
1628 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1629 {
1630         char *realobj;
1631         int size, i;
1632         int lines = 0;
1633
1634         if (is_debug_pagealloc_cache(cachep))
1635                 return;
1636
1637         realobj = (char *)objp + obj_offset(cachep);
1638         size = cachep->object_size;
1639
1640         for (i = 0; i < size; i++) {
1641                 char exp = POISON_FREE;
1642                 if (i == size - 1)
1643                         exp = POISON_END;
1644                 if (realobj[i] != exp) {
1645                         int limit;
1646                         /* Mismatch ! */
1647                         /* Print header */
1648                         if (lines == 0) {
1649                                 pr_err("Slab corruption (%s): %s start=%p, len=%d\n",
1650                                        print_tainted(), cachep->name,
1651                                        realobj, size);
1652                                 print_objinfo(cachep, objp, 0);
1653                         }
1654                         /* Hexdump the affected line */
1655                         i = (i / 16) * 16;
1656                         limit = 16;
1657                         if (i + limit > size)
1658                                 limit = size - i;
1659                         dump_line(realobj, i, limit);
1660                         i += 16;
1661                         lines++;
1662                         /* Limit to 5 lines */
1663                         if (lines > 5)
1664                                 break;
1665                 }
1666         }
1667         if (lines != 0) {
1668                 /* Print some data about the neighboring objects, if they
1669                  * exist:
1670                  */
1671                 struct page *page = virt_to_head_page(objp);
1672                 unsigned int objnr;
1673
1674                 objnr = obj_to_index(cachep, page, objp);
1675                 if (objnr) {
1676                         objp = index_to_obj(cachep, page, objnr - 1);
1677                         realobj = (char *)objp + obj_offset(cachep);
1678                         pr_err("Prev obj: start=%p, len=%d\n", realobj, size);
1679                         print_objinfo(cachep, objp, 2);
1680                 }
1681                 if (objnr + 1 < cachep->num) {
1682                         objp = index_to_obj(cachep, page, objnr + 1);
1683                         realobj = (char *)objp + obj_offset(cachep);
1684                         pr_err("Next obj: start=%p, len=%d\n", realobj, size);
1685                         print_objinfo(cachep, objp, 2);
1686                 }
1687         }
1688 }
1689 #endif
1690
1691 #if DEBUG
1692 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1693                                                 struct page *page)
1694 {
1695         int i;
1696
1697         if (OBJFREELIST_SLAB(cachep) && cachep->flags & SLAB_POISON) {
1698                 poison_obj(cachep, page->freelist - obj_offset(cachep),
1699                         POISON_FREE);
1700         }
1701
1702         for (i = 0; i < cachep->num; i++) {
1703                 void *objp = index_to_obj(cachep, page, i);
1704
1705                 if (cachep->flags & SLAB_POISON) {
1706                         check_poison_obj(cachep, objp);
1707                         slab_kernel_map(cachep, objp, 1, 0);
1708                 }
1709                 if (cachep->flags & SLAB_RED_ZONE) {
1710                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1711                                 slab_error(cachep, "start of a freed object was overwritten");
1712                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1713                                 slab_error(cachep, "end of a freed object was overwritten");
1714                 }
1715         }
1716 }
1717 #else
1718 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1719                                                 struct page *page)
1720 {
1721 }
1722 #endif
1723
1724 /**
1725  * slab_destroy - destroy and release all objects in a slab
1726  * @cachep: cache pointer being destroyed
1727  * @page: page pointer being destroyed
1728  *
1729  * Destroy all the objs in a slab page, and release the mem back to the system.
1730  * Before calling the slab page must have been unlinked from the cache. The
1731  * kmem_cache_node ->list_lock is not held/needed.
1732  */
1733 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
1734 {
1735         void *freelist;
1736
1737         freelist = page->freelist;
1738         slab_destroy_debugcheck(cachep, page);
1739         if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1740                 call_rcu(&page->rcu_head, kmem_rcu_free);
1741         else
1742                 kmem_freepages(cachep, page);
1743
1744         /*
1745          * From now on, we don't use freelist
1746          * although actual page can be freed in rcu context
1747          */
1748         if (OFF_SLAB(cachep))
1749                 kmem_cache_free(cachep->freelist_cache, freelist);
1750 }
1751
1752 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
1753 {
1754         struct page *page, *n;
1755
1756         list_for_each_entry_safe(page, n, list, lru) {
1757                 list_del(&page->lru);
1758                 slab_destroy(cachep, page);
1759         }
1760 }
1761
1762 /**
1763  * calculate_slab_order - calculate size (page order) of slabs
1764  * @cachep: pointer to the cache that is being created
1765  * @size: size of objects to be created in this cache.
1766  * @flags: slab allocation flags
1767  *
1768  * Also calculates the number of objects per slab.
1769  *
1770  * This could be made much more intelligent.  For now, try to avoid using
1771  * high order pages for slabs.  When the gfp() functions are more friendly
1772  * towards high-order requests, this should be changed.
1773  */
1774 static size_t calculate_slab_order(struct kmem_cache *cachep,
1775                                 size_t size, unsigned long flags)
1776 {
1777         size_t left_over = 0;
1778         int gfporder;
1779
1780         for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
1781                 unsigned int num;
1782                 size_t remainder;
1783
1784                 num = cache_estimate(gfporder, size, flags, &remainder);
1785                 if (!num)
1786                         continue;
1787
1788                 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
1789                 if (num > SLAB_OBJ_MAX_NUM)
1790                         break;
1791
1792                 if (flags & CFLGS_OFF_SLAB) {
1793                         struct kmem_cache *freelist_cache;
1794                         size_t freelist_size;
1795
1796                         freelist_size = num * sizeof(freelist_idx_t);
1797                         freelist_cache = kmalloc_slab(freelist_size, 0u);
1798                         if (!freelist_cache)
1799                                 continue;
1800
1801                         /*
1802                          * Needed to avoid possible looping condition
1803                          * in cache_grow_begin()
1804                          */
1805                         if (OFF_SLAB(freelist_cache))
1806                                 continue;
1807
1808                         /* check if off slab has enough benefit */
1809                         if (freelist_cache->size > cachep->size / 2)
1810                                 continue;
1811                 }
1812
1813                 /* Found something acceptable - save it away */
1814                 cachep->num = num;
1815                 cachep->gfporder = gfporder;
1816                 left_over = remainder;
1817
1818                 /*
1819                  * A VFS-reclaimable slab tends to have most allocations
1820                  * as GFP_NOFS and we really don't want to have to be allocating
1821                  * higher-order pages when we are unable to shrink dcache.
1822                  */
1823                 if (flags & SLAB_RECLAIM_ACCOUNT)
1824                         break;
1825
1826                 /*
1827                  * Large number of objects is good, but very large slabs are
1828                  * currently bad for the gfp()s.
1829                  */
1830                 if (gfporder >= slab_max_order)
1831                         break;
1832
1833                 /*
1834                  * Acceptable internal fragmentation?
1835                  */
1836                 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1837                         break;
1838         }
1839         return left_over;
1840 }
1841
1842 static struct array_cache __percpu *alloc_kmem_cache_cpus(
1843                 struct kmem_cache *cachep, int entries, int batchcount)
1844 {
1845         int cpu;
1846         size_t size;
1847         struct array_cache __percpu *cpu_cache;
1848
1849         size = sizeof(void *) * entries + sizeof(struct array_cache);
1850         cpu_cache = __alloc_percpu(size, sizeof(void *));
1851
1852         if (!cpu_cache)
1853                 return NULL;
1854
1855         for_each_possible_cpu(cpu) {
1856                 init_arraycache(per_cpu_ptr(cpu_cache, cpu),
1857                                 entries, batchcount);
1858         }
1859
1860         return cpu_cache;
1861 }
1862
1863 static int __ref setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
1864 {
1865         if (slab_state >= FULL)
1866                 return enable_cpucache(cachep, gfp);
1867
1868         cachep->cpu_cache = alloc_kmem_cache_cpus(cachep, 1, 1);
1869         if (!cachep->cpu_cache)
1870                 return 1;
1871
1872         if (slab_state == DOWN) {
1873                 /* Creation of first cache (kmem_cache). */
1874                 set_up_node(kmem_cache, CACHE_CACHE);
1875         } else if (slab_state == PARTIAL) {
1876                 /* For kmem_cache_node */
1877                 set_up_node(cachep, SIZE_NODE);
1878         } else {
1879                 int node;
1880
1881                 for_each_online_node(node) {
1882                         cachep->node[node] = kmalloc_node(
1883                                 sizeof(struct kmem_cache_node), gfp, node);
1884                         BUG_ON(!cachep->node[node]);
1885                         kmem_cache_node_init(cachep->node[node]);
1886                 }
1887         }
1888
1889         cachep->node[numa_mem_id()]->next_reap =
1890                         jiffies + REAPTIMEOUT_NODE +
1891                         ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1892
1893         cpu_cache_get(cachep)->avail = 0;
1894         cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1895         cpu_cache_get(cachep)->batchcount = 1;
1896         cpu_cache_get(cachep)->touched = 0;
1897         cachep->batchcount = 1;
1898         cachep->limit = BOOT_CPUCACHE_ENTRIES;
1899         return 0;
1900 }
1901
1902 unsigned long kmem_cache_flags(unsigned long object_size,
1903         unsigned long flags, const char *name,
1904         void (*ctor)(void *))
1905 {
1906         return flags;
1907 }
1908
1909 struct kmem_cache *
1910 __kmem_cache_alias(const char *name, size_t size, size_t align,
1911                    unsigned long flags, void (*ctor)(void *))
1912 {
1913         struct kmem_cache *cachep;
1914
1915         cachep = find_mergeable(size, align, flags, name, ctor);
1916         if (cachep) {
1917                 cachep->refcount++;
1918
1919                 /*
1920                  * Adjust the object sizes so that we clear
1921                  * the complete object on kzalloc.
1922                  */
1923                 cachep->object_size = max_t(int, cachep->object_size, size);
1924         }
1925         return cachep;
1926 }
1927
1928 static bool set_objfreelist_slab_cache(struct kmem_cache *cachep,
1929                         size_t size, unsigned long flags)
1930 {
1931         size_t left;
1932
1933         cachep->num = 0;
1934
1935         if (cachep->ctor || flags & SLAB_DESTROY_BY_RCU)
1936                 return false;
1937
1938         left = calculate_slab_order(cachep, size,
1939                         flags | CFLGS_OBJFREELIST_SLAB);
1940         if (!cachep->num)
1941                 return false;
1942
1943         if (cachep->num * sizeof(freelist_idx_t) > cachep->object_size)
1944                 return false;
1945
1946         cachep->colour = left / cachep->colour_off;
1947
1948         return true;
1949 }
1950
1951 static bool set_off_slab_cache(struct kmem_cache *cachep,
1952                         size_t size, unsigned long flags)
1953 {
1954         size_t left;
1955
1956         cachep->num = 0;
1957
1958         /*
1959          * Always use on-slab management when SLAB_NOLEAKTRACE
1960          * to avoid recursive calls into kmemleak.
1961          */
1962         if (flags & SLAB_NOLEAKTRACE)
1963                 return false;
1964
1965         /*
1966          * Size is large, assume best to place the slab management obj
1967          * off-slab (should allow better packing of objs).
1968          */
1969         left = calculate_slab_order(cachep, size, flags | CFLGS_OFF_SLAB);
1970         if (!cachep->num)
1971                 return false;
1972
1973         /*
1974          * If the slab has been placed off-slab, and we have enough space then
1975          * move it on-slab. This is at the expense of any extra colouring.
1976          */
1977         if (left >= cachep->num * sizeof(freelist_idx_t))
1978                 return false;
1979
1980         cachep->colour = left / cachep->colour_off;
1981
1982         return true;
1983 }
1984
1985 static bool set_on_slab_cache(struct kmem_cache *cachep,
1986                         size_t size, unsigned long flags)
1987 {
1988         size_t left;
1989
1990         cachep->num = 0;
1991
1992         left = calculate_slab_order(cachep, size, flags);
1993         if (!cachep->num)
1994                 return false;
1995
1996         cachep->colour = left / cachep->colour_off;
1997
1998         return true;
1999 }
2000
2001 /**
2002  * __kmem_cache_create - Create a cache.
2003  * @cachep: cache management descriptor
2004  * @flags: SLAB flags
2005  *
2006  * Returns a ptr to the cache on success, NULL on failure.
2007  * Cannot be called within a int, but can be interrupted.
2008  * The @ctor is run when new pages are allocated by the cache.
2009  *
2010  * The flags are
2011  *
2012  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2013  * to catch references to uninitialised memory.
2014  *
2015  * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2016  * for buffer overruns.
2017  *
2018  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2019  * cacheline.  This can be beneficial if you're counting cycles as closely
2020  * as davem.
2021  */
2022 int
2023 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2024 {
2025         size_t ralign = BYTES_PER_WORD;
2026         gfp_t gfp;
2027         int err;
2028         size_t size = cachep->size;
2029
2030 #if DEBUG
2031 #if FORCED_DEBUG
2032         /*
2033          * Enable redzoning and last user accounting, except for caches with
2034          * large objects, if the increased size would increase the object size
2035          * above the next power of two: caches with object sizes just above a
2036          * power of two have a significant amount of internal fragmentation.
2037          */
2038         if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2039                                                 2 * sizeof(unsigned long long)))
2040                 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2041         if (!(flags & SLAB_DESTROY_BY_RCU))
2042                 flags |= SLAB_POISON;
2043 #endif
2044 #endif
2045
2046         /*
2047          * Check that size is in terms of words.  This is needed to avoid
2048          * unaligned accesses for some archs when redzoning is used, and makes
2049          * sure any on-slab bufctl's are also correctly aligned.
2050          */
2051         if (size & (BYTES_PER_WORD - 1)) {
2052                 size += (BYTES_PER_WORD - 1);
2053                 size &= ~(BYTES_PER_WORD - 1);
2054         }
2055
2056         if (flags & SLAB_RED_ZONE) {
2057                 ralign = REDZONE_ALIGN;
2058                 /* If redzoning, ensure that the second redzone is suitably
2059                  * aligned, by adjusting the object size accordingly. */
2060                 size += REDZONE_ALIGN - 1;
2061                 size &= ~(REDZONE_ALIGN - 1);
2062         }
2063
2064         /* 3) caller mandated alignment */
2065         if (ralign < cachep->align) {
2066                 ralign = cachep->align;
2067         }
2068         /* disable debug if necessary */
2069         if (ralign > __alignof__(unsigned long long))
2070                 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2071         /*
2072          * 4) Store it.
2073          */
2074         cachep->align = ralign;
2075         cachep->colour_off = cache_line_size();
2076         /* Offset must be a multiple of the alignment. */
2077         if (cachep->colour_off < cachep->align)
2078                 cachep->colour_off = cachep->align;
2079
2080         if (slab_is_available())
2081                 gfp = GFP_KERNEL;
2082         else
2083                 gfp = GFP_NOWAIT;
2084
2085 #if DEBUG
2086
2087         /*
2088          * Both debugging options require word-alignment which is calculated
2089          * into align above.
2090          */
2091         if (flags & SLAB_RED_ZONE) {
2092                 /* add space for red zone words */
2093                 cachep->obj_offset += sizeof(unsigned long long);
2094                 size += 2 * sizeof(unsigned long long);
2095         }
2096         if (flags & SLAB_STORE_USER) {
2097                 /* user store requires one word storage behind the end of
2098                  * the real object. But if the second red zone needs to be
2099                  * aligned to 64 bits, we must allow that much space.
2100                  */
2101                 if (flags & SLAB_RED_ZONE)
2102                         size += REDZONE_ALIGN;
2103                 else
2104                         size += BYTES_PER_WORD;
2105         }
2106 #endif
2107
2108         kasan_cache_create(cachep, &size, &flags);
2109
2110         size = ALIGN(size, cachep->align);
2111         /*
2112          * We should restrict the number of objects in a slab to implement
2113          * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
2114          */
2115         if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
2116                 size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
2117
2118 #if DEBUG
2119         /*
2120          * To activate debug pagealloc, off-slab management is necessary
2121          * requirement. In early phase of initialization, small sized slab
2122          * doesn't get initialized so it would not be possible. So, we need
2123          * to check size >= 256. It guarantees that all necessary small
2124          * sized slab is initialized in current slab initialization sequence.
2125          */
2126         if (debug_pagealloc_enabled() && (flags & SLAB_POISON) &&
2127                 size >= 256 && cachep->object_size > cache_line_size()) {
2128                 if (size < PAGE_SIZE || size % PAGE_SIZE == 0) {
2129                         size_t tmp_size = ALIGN(size, PAGE_SIZE);
2130
2131                         if (set_off_slab_cache(cachep, tmp_size, flags)) {
2132                                 flags |= CFLGS_OFF_SLAB;
2133                                 cachep->obj_offset += tmp_size - size;
2134                                 size = tmp_size;
2135                                 goto done;
2136                         }
2137                 }
2138         }
2139 #endif
2140
2141         if (set_objfreelist_slab_cache(cachep, size, flags)) {
2142                 flags |= CFLGS_OBJFREELIST_SLAB;
2143                 goto done;
2144         }
2145
2146         if (set_off_slab_cache(cachep, size, flags)) {
2147                 flags |= CFLGS_OFF_SLAB;
2148                 goto done;
2149         }
2150
2151         if (set_on_slab_cache(cachep, size, flags))
2152                 goto done;
2153
2154         return -E2BIG;
2155
2156 done:
2157         cachep->freelist_size = cachep->num * sizeof(freelist_idx_t);
2158         cachep->flags = flags;
2159         cachep->allocflags = __GFP_COMP;
2160         if (flags & SLAB_CACHE_DMA)
2161                 cachep->allocflags |= GFP_DMA;
2162         cachep->size = size;
2163         cachep->reciprocal_buffer_size = reciprocal_value(size);
2164
2165 #if DEBUG
2166         /*
2167          * If we're going to use the generic kernel_map_pages()
2168          * poisoning, then it's going to smash the contents of
2169          * the redzone and userword anyhow, so switch them off.
2170          */
2171         if (IS_ENABLED(CONFIG_PAGE_POISONING) &&
2172                 (cachep->flags & SLAB_POISON) &&
2173                 is_debug_pagealloc_cache(cachep))
2174                 cachep->flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2175 #endif
2176
2177         if (OFF_SLAB(cachep)) {
2178                 cachep->freelist_cache =
2179                         kmalloc_slab(cachep->freelist_size, 0u);
2180         }
2181
2182         err = setup_cpu_cache(cachep, gfp);
2183         if (err) {
2184                 __kmem_cache_release(cachep);
2185                 return err;
2186         }
2187
2188         return 0;
2189 }
2190
2191 #if DEBUG
2192 static void check_irq_off(void)
2193 {
2194         BUG_ON(!irqs_disabled());
2195 }
2196
2197 static void check_irq_on(void)
2198 {
2199         BUG_ON(irqs_disabled());
2200 }
2201
2202 static void check_mutex_acquired(void)
2203 {
2204         BUG_ON(!mutex_is_locked(&slab_mutex));
2205 }
2206
2207 static void check_spinlock_acquired(struct kmem_cache *cachep)
2208 {
2209 #ifdef CONFIG_SMP
2210         check_irq_off();
2211         assert_spin_locked(&get_node(cachep, numa_mem_id())->list_lock);
2212 #endif
2213 }
2214
2215 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2216 {
2217 #ifdef CONFIG_SMP
2218         check_irq_off();
2219         assert_spin_locked(&get_node(cachep, node)->list_lock);
2220 #endif
2221 }
2222
2223 #else
2224 #define check_irq_off() do { } while(0)
2225 #define check_irq_on()  do { } while(0)
2226 #define check_mutex_acquired()  do { } while(0)
2227 #define check_spinlock_acquired(x) do { } while(0)
2228 #define check_spinlock_acquired_node(x, y) do { } while(0)
2229 #endif
2230
2231 static void drain_array_locked(struct kmem_cache *cachep, struct array_cache *ac,
2232                                 int node, bool free_all, struct list_head *list)
2233 {
2234         int tofree;
2235
2236         if (!ac || !ac->avail)
2237                 return;
2238
2239         tofree = free_all ? ac->avail : (ac->limit + 4) / 5;
2240         if (tofree > ac->avail)
2241                 tofree = (ac->avail + 1) / 2;
2242
2243         free_block(cachep, ac->entry, tofree, node, list);
2244         ac->avail -= tofree;
2245         memmove(ac->entry, &(ac->entry[tofree]), sizeof(void *) * ac->avail);
2246 }
2247
2248 static void do_drain(void *arg)
2249 {
2250         struct kmem_cache *cachep = arg;
2251         struct array_cache *ac;
2252         int node = numa_mem_id();
2253         struct kmem_cache_node *n;
2254         LIST_HEAD(list);
2255
2256         check_irq_off();
2257         ac = cpu_cache_get(cachep);
2258         n = get_node(cachep, node);
2259         spin_lock(&n->list_lock);
2260         free_block(cachep, ac->entry, ac->avail, node, &list);
2261         spin_unlock(&n->list_lock);
2262         slabs_destroy(cachep, &list);
2263         ac->avail = 0;
2264 }
2265
2266 static void drain_cpu_caches(struct kmem_cache *cachep)
2267 {
2268         struct kmem_cache_node *n;
2269         int node;
2270         LIST_HEAD(list);
2271
2272         on_each_cpu(do_drain, cachep, 1);
2273         check_irq_on();
2274         for_each_kmem_cache_node(cachep, node, n)
2275                 if (n->alien)
2276                         drain_alien_cache(cachep, n->alien);
2277
2278         for_each_kmem_cache_node(cachep, node, n) {
2279                 spin_lock_irq(&n->list_lock);
2280                 drain_array_locked(cachep, n->shared, node, true, &list);
2281                 spin_unlock_irq(&n->list_lock);
2282
2283                 slabs_destroy(cachep, &list);
2284         }
2285 }
2286
2287 /*
2288  * Remove slabs from the list of free slabs.
2289  * Specify the number of slabs to drain in tofree.
2290  *
2291  * Returns the actual number of slabs released.
2292  */
2293 static int drain_freelist(struct kmem_cache *cache,
2294                         struct kmem_cache_node *n, int tofree)
2295 {
2296         struct list_head *p;
2297         int nr_freed;
2298         struct page *page;
2299
2300         nr_freed = 0;
2301         while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
2302
2303                 spin_lock_irq(&n->list_lock);
2304                 p = n->slabs_free.prev;
2305                 if (p == &n->slabs_free) {
2306                         spin_unlock_irq(&n->list_lock);
2307                         goto out;
2308                 }
2309
2310                 page = list_entry(p, struct page, lru);
2311                 list_del(&page->lru);
2312                 /*
2313                  * Safe to drop the lock. The slab is no longer linked
2314                  * to the cache.
2315                  */
2316                 n->free_objects -= cache->num;
2317                 spin_unlock_irq(&n->list_lock);
2318                 slab_destroy(cache, page);
2319                 nr_freed++;
2320         }
2321 out:
2322         return nr_freed;
2323 }
2324
2325 int __kmem_cache_shrink(struct kmem_cache *cachep, bool deactivate)
2326 {
2327         int ret = 0;
2328         int node;
2329         struct kmem_cache_node *n;
2330
2331         drain_cpu_caches(cachep);
2332
2333         check_irq_on();
2334         for_each_kmem_cache_node(cachep, node, n) {
2335                 drain_freelist(cachep, n, INT_MAX);
2336
2337                 ret += !list_empty(&n->slabs_full) ||
2338                         !list_empty(&n->slabs_partial);
2339         }
2340         return (ret ? 1 : 0);
2341 }
2342
2343 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2344 {
2345         return __kmem_cache_shrink(cachep, false);
2346 }
2347
2348 void __kmem_cache_release(struct kmem_cache *cachep)
2349 {
2350         int i;
2351         struct kmem_cache_node *n;
2352
2353         cache_random_seq_destroy(cachep);
2354
2355         free_percpu(cachep->cpu_cache);
2356
2357         /* NUMA: free the node structures */
2358         for_each_kmem_cache_node(cachep, i, n) {
2359                 kfree(n->shared);
2360                 free_alien_cache(n->alien);
2361                 kfree(n);
2362                 cachep->node[i] = NULL;
2363         }
2364 }
2365
2366 /*
2367  * Get the memory for a slab management obj.
2368  *
2369  * For a slab cache when the slab descriptor is off-slab, the
2370  * slab descriptor can't come from the same cache which is being created,
2371  * Because if it is the case, that means we defer the creation of
2372  * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
2373  * And we eventually call down to __kmem_cache_create(), which
2374  * in turn looks up in the kmalloc_{dma,}_caches for the disired-size one.
2375  * This is a "chicken-and-egg" problem.
2376  *
2377  * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
2378  * which are all initialized during kmem_cache_init().
2379  */
2380 static void *alloc_slabmgmt(struct kmem_cache *cachep,
2381                                    struct page *page, int colour_off,
2382                                    gfp_t local_flags, int nodeid)
2383 {
2384         void *freelist;
2385         void *addr = page_address(page);
2386
2387         page->s_mem = addr + colour_off;
2388         page->active = 0;
2389
2390         if (OBJFREELIST_SLAB(cachep))
2391                 freelist = NULL;
2392         else if (OFF_SLAB(cachep)) {
2393                 /* Slab management obj is off-slab. */
2394                 freelist = kmem_cache_alloc_node(cachep->freelist_cache,
2395                                               local_flags, nodeid);
2396                 if (!freelist)
2397                         return NULL;
2398         } else {
2399                 /* We will use last bytes at the slab for freelist */
2400                 freelist = addr + (PAGE_SIZE << cachep->gfporder) -
2401                                 cachep->freelist_size;
2402         }
2403
2404         return freelist;
2405 }
2406
2407 static inline freelist_idx_t get_free_obj(struct page *page, unsigned int idx)
2408 {
2409         return ((freelist_idx_t *)page->freelist)[idx];
2410 }
2411
2412 static inline void set_free_obj(struct page *page,
2413                                         unsigned int idx, freelist_idx_t val)
2414 {
2415         ((freelist_idx_t *)(page->freelist))[idx] = val;
2416 }
2417
2418 static void cache_init_objs_debug(struct kmem_cache *cachep, struct page *page)
2419 {
2420 #if DEBUG
2421         int i;
2422
2423         for (i = 0; i < cachep->num; i++) {
2424                 void *objp = index_to_obj(cachep, page, i);
2425
2426                 if (cachep->flags & SLAB_STORE_USER)
2427                         *dbg_userword(cachep, objp) = NULL;
2428
2429                 if (cachep->flags & SLAB_RED_ZONE) {
2430                         *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2431                         *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2432                 }
2433                 /*
2434                  * Constructors are not allowed to allocate memory from the same
2435                  * cache which they are a constructor for.  Otherwise, deadlock.
2436                  * They must also be threaded.
2437                  */
2438                 if (cachep->ctor && !(cachep->flags & SLAB_POISON)) {
2439                         kasan_unpoison_object_data(cachep,
2440                                                    objp + obj_offset(cachep));
2441                         cachep->ctor(objp + obj_offset(cachep));
2442                         kasan_poison_object_data(
2443                                 cachep, objp + obj_offset(cachep));
2444                 }
2445
2446                 if (cachep->flags & SLAB_RED_ZONE) {
2447                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2448                                 slab_error(cachep, "constructor overwrote the end of an object");
2449                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2450                                 slab_error(cachep, "constructor overwrote the start of an object");
2451                 }
2452                 /* need to poison the objs? */
2453                 if (cachep->flags & SLAB_POISON) {
2454                         poison_obj(cachep, objp, POISON_FREE);
2455                         slab_kernel_map(cachep, objp, 0, 0);
2456                 }
2457         }
2458 #endif
2459 }
2460
2461 #ifdef CONFIG_SLAB_FREELIST_RANDOM
2462 /* Hold information during a freelist initialization */
2463 union freelist_init_state {
2464         struct {
2465                 unsigned int pos;
2466                 unsigned int *list;
2467                 unsigned int count;
2468                 unsigned int rand;
2469         };
2470         struct rnd_state rnd_state;
2471 };
2472
2473 /*
2474  * Initialize the state based on the randomization methode available.
2475  * return true if the pre-computed list is available, false otherwize.
2476  */
2477 static bool freelist_state_initialize(union freelist_init_state *state,
2478                                 struct kmem_cache *cachep,
2479                                 unsigned int count)
2480 {
2481         bool ret;
2482         unsigned int rand;
2483
2484         /* Use best entropy available to define a random shift */
2485         rand = get_random_int();
2486
2487         /* Use a random state if the pre-computed list is not available */
2488         if (!cachep->random_seq) {
2489                 prandom_seed_state(&state->rnd_state, rand);
2490                 ret = false;
2491         } else {
2492                 state->list = cachep->random_seq;
2493                 state->count = count;
2494                 state->pos = 0;
2495                 state->rand = rand;
2496                 ret = true;
2497         }
2498         return ret;
2499 }
2500
2501 /* Get the next entry on the list and randomize it using a random shift */
2502 static freelist_idx_t next_random_slot(union freelist_init_state *state)
2503 {
2504         return (state->list[state->pos++] + state->rand) % state->count;
2505 }
2506
2507 /* Swap two freelist entries */
2508 static void swap_free_obj(struct page *page, unsigned int a, unsigned int b)
2509 {
2510         swap(((freelist_idx_t *)page->freelist)[a],
2511                 ((freelist_idx_t *)page->freelist)[b]);
2512 }
2513
2514 /*
2515  * Shuffle the freelist initialization state based on pre-computed lists.
2516  * return true if the list was successfully shuffled, false otherwise.
2517  */
2518 static bool shuffle_freelist(struct kmem_cache *cachep, struct page *page)
2519 {
2520         unsigned int objfreelist = 0, i, rand, count = cachep->num;
2521         union freelist_init_state state;
2522         bool precomputed;
2523
2524         if (count < 2)
2525                 return false;
2526
2527         precomputed = freelist_state_initialize(&state, cachep, count);
2528
2529         /* Take a random entry as the objfreelist */
2530         if (OBJFREELIST_SLAB(cachep)) {
2531                 if (!precomputed)
2532                         objfreelist = count - 1;
2533                 else
2534                         objfreelist = next_random_slot(&state);
2535                 page->freelist = index_to_obj(cachep, page, objfreelist) +
2536                                                 obj_offset(cachep);
2537                 count--;
2538         }
2539
2540         /*
2541          * On early boot, generate the list dynamically.
2542          * Later use a pre-computed list for speed.
2543          */
2544         if (!precomputed) {
2545                 for (i = 0; i < count; i++)
2546                         set_free_obj(page, i, i);
2547
2548                 /* Fisher-Yates shuffle */
2549                 for (i = count - 1; i > 0; i--) {
2550                         rand = prandom_u32_state(&state.rnd_state);
2551                         rand %= (i + 1);
2552                         swap_free_obj(page, i, rand);
2553                 }
2554         } else {
2555                 for (i = 0; i < count; i++)
2556                         set_free_obj(page, i, next_random_slot(&state));
2557         }
2558
2559         if (OBJFREELIST_SLAB(cachep))
2560                 set_free_obj(page, cachep->num - 1, objfreelist);
2561
2562         return true;
2563 }
2564 #else
2565 static inline bool shuffle_freelist(struct kmem_cache *cachep,
2566                                 struct page *page)
2567 {
2568         return false;
2569 }
2570 #endif /* CONFIG_SLAB_FREELIST_RANDOM */
2571
2572 static void cache_init_objs(struct kmem_cache *cachep,
2573                             struct page *page)
2574 {
2575         int i;
2576         void *objp;
2577         bool shuffled;
2578
2579         cache_init_objs_debug(cachep, page);
2580
2581         /* Try to randomize the freelist if enabled */
2582         shuffled = shuffle_freelist(cachep, page);
2583
2584         if (!shuffled && OBJFREELIST_SLAB(cachep)) {
2585                 page->freelist = index_to_obj(cachep, page, cachep->num - 1) +
2586                                                 obj_offset(cachep);
2587         }
2588
2589         for (i = 0; i < cachep->num; i++) {
2590                 objp = index_to_obj(cachep, page, i);
2591                 kasan_init_slab_obj(cachep, objp);
2592
2593                 /* constructor could break poison info */
2594                 if (DEBUG == 0 && cachep->ctor) {
2595                         kasan_unpoison_object_data(cachep, objp);
2596                         cachep->ctor(objp);
2597                         kasan_poison_object_data(cachep, objp);
2598                 }
2599
2600                 if (!shuffled)
2601                         set_free_obj(page, i, i);
2602         }
2603 }
2604
2605 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page)
2606 {
2607         void *objp;
2608
2609         objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2610         page->active++;
2611
2612 #if DEBUG
2613         if (cachep->flags & SLAB_STORE_USER)
2614                 set_store_user_dirty(cachep);
2615 #endif
2616
2617         return objp;
2618 }
2619
2620 static void slab_put_obj(struct kmem_cache *cachep,
2621                         struct page *page, void *objp)
2622 {
2623         unsigned int objnr = obj_to_index(cachep, page, objp);
2624 #if DEBUG
2625         unsigned int i;
2626
2627         /* Verify double free bug */
2628         for (i = page->active; i < cachep->num; i++) {
2629                 if (get_free_obj(page, i) == objnr) {
2630                         pr_err("slab: double free detected in cache '%s', objp %p\n",
2631                                cachep->name, objp);
2632                         BUG();
2633                 }
2634         }
2635 #endif
2636         page->active--;
2637         if (!page->freelist)
2638                 page->freelist = objp + obj_offset(cachep);
2639
2640         set_free_obj(page, page->active, objnr);
2641 }
2642
2643 /*
2644  * Map pages beginning at addr to the given cache and slab. This is required
2645  * for the slab allocator to be able to lookup the cache and slab of a
2646  * virtual address for kfree, ksize, and slab debugging.
2647  */
2648 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2649                            void *freelist)
2650 {
2651         page->slab_cache = cache;
2652         page->freelist = freelist;
2653 }
2654
2655 /*
2656  * Grow (by 1) the number of slabs within a cache.  This is called by
2657  * kmem_cache_alloc() when there are no active objs left in a cache.
2658  */
2659 static struct page *cache_grow_begin(struct kmem_cache *cachep,
2660                                 gfp_t flags, int nodeid)
2661 {
2662         void *freelist;
2663         size_t offset;
2664         gfp_t local_flags;
2665         int page_node;
2666         struct kmem_cache_node *n;
2667         struct page *page;
2668
2669         /*
2670          * Be lazy and only check for valid flags here,  keeping it out of the
2671          * critical path in kmem_cache_alloc().
2672          */
2673         if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
2674                 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK;
2675                 flags &= ~GFP_SLAB_BUG_MASK;
2676                 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
2677                                 invalid_mask, &invalid_mask, flags, &flags);
2678                 dump_stack();
2679         }
2680         local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2681
2682         check_irq_off();
2683         if (gfpflags_allow_blocking(local_flags))
2684                 local_irq_enable();
2685
2686         /*
2687          * Get mem for the objs.  Attempt to allocate a physical page from
2688          * 'nodeid'.
2689          */
2690         page = kmem_getpages(cachep, local_flags, nodeid);
2691         if (!page)
2692                 goto failed;
2693
2694         page_node = page_to_nid(page);
2695         n = get_node(cachep, page_node);
2696
2697         /* Get colour for the slab, and cal the next value. */
2698         n->colour_next++;
2699         if (n->colour_next >= cachep->colour)
2700                 n->colour_next = 0;
2701
2702         offset = n->colour_next;
2703         if (offset >= cachep->colour)
2704                 offset = 0;
2705
2706         offset *= cachep->colour_off;
2707
2708         /* Get slab management. */
2709         freelist = alloc_slabmgmt(cachep, page, offset,
2710                         local_flags & ~GFP_CONSTRAINT_MASK, page_node);
2711         if (OFF_SLAB(cachep) && !freelist)
2712                 goto opps1;
2713
2714         slab_map_pages(cachep, page, freelist);
2715
2716         kasan_poison_slab(page);
2717         cache_init_objs(cachep, page);
2718
2719         if (gfpflags_allow_blocking(local_flags))
2720                 local_irq_disable();
2721
2722         return page;
2723
2724 opps1:
2725         kmem_freepages(cachep, page);
2726 failed:
2727         if (gfpflags_allow_blocking(local_flags))
2728                 local_irq_disable();
2729         return NULL;
2730 }
2731
2732 static void cache_grow_end(struct kmem_cache *cachep, struct page *page)
2733 {
2734         struct kmem_cache_node *n;
2735         void *list = NULL;
2736
2737         check_irq_off();
2738
2739         if (!page)
2740                 return;
2741
2742         INIT_LIST_HEAD(&page->lru);
2743         n = get_node(cachep, page_to_nid(page));
2744
2745         spin_lock(&n->list_lock);
2746         if (!page->active)
2747                 list_add_tail(&page->lru, &(n->slabs_free));
2748         else
2749                 fixup_slab_list(cachep, n, page, &list);
2750         STATS_INC_GROWN(cachep);
2751         n->free_objects += cachep->num - page->active;
2752         spin_unlock(&n->list_lock);
2753
2754         fixup_objfreelist_debug(cachep, &list);
2755 }
2756
2757 #if DEBUG
2758
2759 /*
2760  * Perform extra freeing checks:
2761  * - detect bad pointers.
2762  * - POISON/RED_ZONE checking
2763  */
2764 static void kfree_debugcheck(const void *objp)
2765 {
2766         if (!virt_addr_valid(objp)) {
2767                 pr_err("kfree_debugcheck: out of range ptr %lxh\n",
2768                        (unsigned long)objp);
2769                 BUG();
2770         }
2771 }
2772
2773 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2774 {
2775         unsigned long long redzone1, redzone2;
2776
2777         redzone1 = *dbg_redzone1(cache, obj);
2778         redzone2 = *dbg_redzone2(cache, obj);
2779
2780         /*
2781          * Redzone is ok.
2782          */
2783         if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2784                 return;
2785
2786         if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2787                 slab_error(cache, "double free detected");
2788         else
2789                 slab_error(cache, "memory outside object was overwritten");
2790
2791         pr_err("%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
2792                obj, redzone1, redzone2);
2793 }
2794
2795 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2796                                    unsigned long caller)
2797 {
2798         unsigned int objnr;
2799         struct page *page;
2800
2801         BUG_ON(virt_to_cache(objp) != cachep);
2802
2803         objp -= obj_offset(cachep);
2804         kfree_debugcheck(objp);
2805         page = virt_to_head_page(objp);
2806
2807         if (cachep->flags & SLAB_RED_ZONE) {
2808                 verify_redzone_free(cachep, objp);
2809                 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2810                 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2811         }
2812         if (cachep->flags & SLAB_STORE_USER) {
2813                 set_store_user_dirty(cachep);
2814                 *dbg_userword(cachep, objp) = (void *)caller;
2815         }
2816
2817         objnr = obj_to_index(cachep, page, objp);
2818
2819         BUG_ON(objnr >= cachep->num);
2820         BUG_ON(objp != index_to_obj(cachep, page, objnr));
2821
2822         if (cachep->flags & SLAB_POISON) {
2823                 poison_obj(cachep, objp, POISON_FREE);
2824                 slab_kernel_map(cachep, objp, 0, caller);
2825         }
2826         return objp;
2827 }
2828
2829 #else
2830 #define kfree_debugcheck(x) do { } while(0)
2831 #define cache_free_debugcheck(x,objp,z) (objp)
2832 #endif
2833
2834 static inline void fixup_objfreelist_debug(struct kmem_cache *cachep,
2835                                                 void **list)
2836 {
2837 #if DEBUG
2838         void *next = *list;
2839         void *objp;
2840
2841         while (next) {
2842                 objp = next - obj_offset(cachep);
2843                 next = *(void **)next;
2844                 poison_obj(cachep, objp, POISON_FREE);
2845         }
2846 #endif
2847 }
2848
2849 static inline void fixup_slab_list(struct kmem_cache *cachep,
2850                                 struct kmem_cache_node *n, struct page *page,
2851                                 void **list)
2852 {
2853         /* move slabp to correct slabp list: */
2854         list_del(&page->lru);
2855         if (page->active == cachep->num) {
2856                 list_add(&page->lru, &n->slabs_full);
2857                 if (OBJFREELIST_SLAB(cachep)) {
2858 #if DEBUG
2859                         /* Poisoning will be done without holding the lock */
2860                         if (cachep->flags & SLAB_POISON) {
2861                                 void **objp = page->freelist;
2862
2863                                 *objp = *list;
2864                                 *list = objp;
2865                         }
2866 #endif
2867                         page->freelist = NULL;
2868                 }
2869         } else
2870                 list_add(&page->lru, &n->slabs_partial);
2871 }
2872
2873 /* Try to find non-pfmemalloc slab if needed */
2874 static noinline struct page *get_valid_first_slab(struct kmem_cache_node *n,
2875                                         struct page *page, bool pfmemalloc)
2876 {
2877         if (!page)
2878                 return NULL;
2879
2880         if (pfmemalloc)
2881                 return page;
2882
2883         if (!PageSlabPfmemalloc(page))
2884                 return page;
2885
2886         /* No need to keep pfmemalloc slab if we have enough free objects */
2887         if (n->free_objects > n->free_limit) {
2888                 ClearPageSlabPfmemalloc(page);
2889                 return page;
2890         }
2891
2892         /* Move pfmemalloc slab to the end of list to speed up next search */
2893         list_del(&page->lru);
2894         if (!page->active)
2895                 list_add_tail(&page->lru, &n->slabs_free);
2896         else
2897                 list_add_tail(&page->lru, &n->slabs_partial);
2898
2899         list_for_each_entry(page, &n->slabs_partial, lru) {
2900                 if (!PageSlabPfmemalloc(page))
2901                         return page;
2902         }
2903
2904         list_for_each_entry(page, &n->slabs_free, lru) {
2905                 if (!PageSlabPfmemalloc(page))
2906                         return page;
2907         }
2908
2909         return NULL;
2910 }
2911
2912 static struct page *get_first_slab(struct kmem_cache_node *n, bool pfmemalloc)
2913 {
2914         struct page *page;
2915
2916         page = list_first_entry_or_null(&n->slabs_partial,
2917                         struct page, lru);
2918         if (!page) {
2919                 n->free_touched = 1;
2920                 page = list_first_entry_or_null(&n->slabs_free,
2921                                 struct page, lru);
2922         }
2923
2924         if (sk_memalloc_socks())
2925                 return get_valid_first_slab(n, page, pfmemalloc);
2926
2927         return page;
2928 }
2929
2930 static noinline void *cache_alloc_pfmemalloc(struct kmem_cache *cachep,
2931                                 struct kmem_cache_node *n, gfp_t flags)
2932 {
2933         struct page *page;
2934         void *obj;
2935         void *list = NULL;
2936
2937         if (!gfp_pfmemalloc_allowed(flags))
2938                 return NULL;
2939
2940         spin_lock(&n->list_lock);
2941         page = get_first_slab(n, true);
2942         if (!page) {
2943                 spin_unlock(&n->list_lock);
2944                 return NULL;
2945         }
2946
2947         obj = slab_get_obj(cachep, page);
2948         n->free_objects--;
2949
2950         fixup_slab_list(cachep, n, page, &list);
2951
2952         spin_unlock(&n->list_lock);
2953         fixup_objfreelist_debug(cachep, &list);
2954
2955         return obj;
2956 }
2957
2958 /*
2959  * Slab list should be fixed up by fixup_slab_list() for existing slab
2960  * or cache_grow_end() for new slab
2961  */
2962 static __always_inline int alloc_block(struct kmem_cache *cachep,
2963                 struct array_cache *ac, struct page *page, int batchcount)
2964 {
2965         /*
2966          * There must be at least one object available for
2967          * allocation.
2968          */
2969         BUG_ON(page->active >= cachep->num);
2970
2971         while (page->active < cachep->num && batchcount--) {
2972                 STATS_INC_ALLOCED(cachep);
2973                 STATS_INC_ACTIVE(cachep);
2974                 STATS_SET_HIGH(cachep);
2975
2976                 ac->entry[ac->avail++] = slab_get_obj(cachep, page);
2977         }
2978
2979         return batchcount;
2980 }
2981
2982 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2983 {
2984         int batchcount;
2985         struct kmem_cache_node *n;
2986         struct array_cache *ac, *shared;
2987         int node;
2988         void *list = NULL;
2989         struct page *page;
2990
2991         check_irq_off();
2992         node = numa_mem_id();
2993
2994         ac = cpu_cache_get(cachep);
2995         batchcount = ac->batchcount;
2996         if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2997                 /*
2998                  * If there was little recent activity on this cache, then
2999                  * perform only a partial refill.  Otherwise we could generate
3000                  * refill bouncing.
3001                  */
3002                 batchcount = BATCHREFILL_LIMIT;
3003         }
3004         n = get_node(cachep, node);
3005
3006         BUG_ON(ac->avail > 0 || !n);
3007         shared = READ_ONCE(n->shared);
3008         if (!n->free_objects && (!shared || !shared->avail))
3009                 goto direct_grow;
3010
3011         spin_lock(&n->list_lock);
3012         shared = READ_ONCE(n->shared);
3013
3014         /* See if we can refill from the shared array */
3015         if (shared && transfer_objects(ac, shared, batchcount)) {
3016                 shared->touched = 1;
3017                 goto alloc_done;
3018         }
3019
3020         while (batchcount > 0) {
3021                 /* Get slab alloc is to come from. */
3022                 page = get_first_slab(n, false);
3023                 if (!page)
3024                         goto must_grow;
3025
3026                 check_spinlock_acquired(cachep);
3027
3028                 batchcount = alloc_block(cachep, ac, page, batchcount);
3029                 fixup_slab_list(cachep, n, page, &list);
3030         }
3031
3032 must_grow:
3033         n->free_objects -= ac->avail;
3034 alloc_done:
3035         spin_unlock(&n->list_lock);
3036         fixup_objfreelist_debug(cachep, &list);
3037
3038 direct_grow:
3039         if (unlikely(!ac->avail)) {
3040                 /* Check if we can use obj in pfmemalloc slab */
3041                 if (sk_memalloc_socks()) {
3042                         void *obj = cache_alloc_pfmemalloc(cachep, n, flags);
3043
3044                         if (obj)
3045                                 return obj;
3046                 }
3047
3048                 page = cache_grow_begin(cachep, gfp_exact_node(flags), node);
3049
3050                 /*
3051                  * cache_grow_begin() can reenable interrupts,
3052                  * then ac could change.
3053                  */
3054                 ac = cpu_cache_get(cachep);
3055                 if (!ac->avail && page)
3056                         alloc_block(cachep, ac, page, batchcount);
3057                 cache_grow_end(cachep, page);
3058
3059                 if (!ac->avail)
3060                         return NULL;
3061         }
3062         ac->touched = 1;
3063
3064         return ac->entry[--ac->avail];
3065 }
3066
3067 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3068                                                 gfp_t flags)
3069 {
3070         might_sleep_if(gfpflags_allow_blocking(flags));
3071 }
3072
3073 #if DEBUG
3074 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3075                                 gfp_t flags, void *objp, unsigned long caller)
3076 {
3077         if (!objp)
3078                 return objp;
3079         if (cachep->flags & SLAB_POISON) {
3080                 check_poison_obj(cachep, objp);
3081                 slab_kernel_map(cachep, objp, 1, 0);
3082                 poison_obj(cachep, objp, POISON_INUSE);
3083         }
3084         if (cachep->flags & SLAB_STORE_USER)
3085                 *dbg_userword(cachep, objp) = (void *)caller;
3086
3087         if (cachep->flags & SLAB_RED_ZONE) {
3088                 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3089                                 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3090                         slab_error(cachep, "double free, or memory outside object was overwritten");
3091                         pr_err("%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3092                                objp, *dbg_redzone1(cachep, objp),
3093                                *dbg_redzone2(cachep, objp));
3094                 }
3095                 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3096                 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3097         }
3098
3099         objp += obj_offset(cachep);
3100         if (cachep->ctor && cachep->flags & SLAB_POISON)
3101                 cachep->ctor(objp);
3102         if (ARCH_SLAB_MINALIGN &&
3103             ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3104                 pr_err("0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3105                        objp, (int)ARCH_SLAB_MINALIGN);
3106         }
3107         return objp;
3108 }
3109 #else
3110 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3111 #endif
3112
3113 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3114 {
3115         void *objp;
3116         struct array_cache *ac;
3117
3118         check_irq_off();
3119
3120         ac = cpu_cache_get(cachep);
3121         if (likely(ac->avail)) {
3122                 ac->touched = 1;
3123                 objp = ac->entry[--ac->avail];
3124
3125                 STATS_INC_ALLOCHIT(cachep);
3126                 goto out;
3127         }
3128
3129         STATS_INC_ALLOCMISS(cachep);
3130         objp = cache_alloc_refill(cachep, flags);
3131         /*
3132          * the 'ac' may be updated by cache_alloc_refill(),
3133          * and kmemleak_erase() requires its correct value.
3134          */
3135         ac = cpu_cache_get(cachep);
3136
3137 out:
3138         /*
3139          * To avoid a false negative, if an object that is in one of the
3140          * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3141          * treat the array pointers as a reference to the object.
3142          */
3143         if (objp)
3144                 kmemleak_erase(&ac->entry[ac->avail]);
3145         return objp;
3146 }
3147
3148 #ifdef CONFIG_NUMA
3149 /*
3150  * Try allocating on another node if PFA_SPREAD_SLAB is a mempolicy is set.
3151  *
3152  * If we are in_interrupt, then process context, including cpusets and
3153  * mempolicy, may not apply and should not be used for allocation policy.
3154  */
3155 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3156 {
3157         int nid_alloc, nid_here;
3158
3159         if (in_interrupt() || (flags & __GFP_THISNODE))
3160                 return NULL;
3161         nid_alloc = nid_here = numa_mem_id();
3162         if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3163                 nid_alloc = cpuset_slab_spread_node();
3164         else if (current->mempolicy)
3165                 nid_alloc = mempolicy_slab_node();
3166         if (nid_alloc != nid_here)
3167                 return ____cache_alloc_node(cachep, flags, nid_alloc);
3168         return NULL;
3169 }
3170
3171 /*
3172  * Fallback function if there was no memory available and no objects on a
3173  * certain node and fall back is permitted. First we scan all the
3174  * available node for available objects. If that fails then we
3175  * perform an allocation without specifying a node. This allows the page
3176  * allocator to do its reclaim / fallback magic. We then insert the
3177  * slab into the proper nodelist and then allocate from it.
3178  */
3179 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3180 {
3181         struct zonelist *zonelist;
3182         struct zoneref *z;
3183         struct zone *zone;
3184         enum zone_type high_zoneidx = gfp_zone(flags);
3185         void *obj = NULL;
3186         struct page *page;
3187         int nid;
3188         unsigned int cpuset_mems_cookie;
3189
3190         if (flags & __GFP_THISNODE)
3191                 return NULL;
3192
3193 retry_cpuset:
3194         cpuset_mems_cookie = read_mems_allowed_begin();
3195         zonelist = node_zonelist(mempolicy_slab_node(), flags);
3196
3197 retry:
3198         /*
3199          * Look through allowed nodes for objects available
3200          * from existing per node queues.
3201          */
3202         for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3203                 nid = zone_to_nid(zone);
3204
3205                 if (cpuset_zone_allowed(zone, flags) &&
3206                         get_node(cache, nid) &&
3207                         get_node(cache, nid)->free_objects) {
3208                                 obj = ____cache_alloc_node(cache,
3209                                         gfp_exact_node(flags), nid);
3210                                 if (obj)
3211                                         break;
3212                 }
3213         }
3214
3215         if (!obj) {
3216                 /*
3217                  * This allocation will be performed within the constraints
3218                  * of the current cpuset / memory policy requirements.
3219                  * We may trigger various forms of reclaim on the allowed
3220                  * set and go into memory reserves if necessary.
3221                  */
3222                 page = cache_grow_begin(cache, flags, numa_mem_id());
3223                 cache_grow_end(cache, page);
3224                 if (page) {
3225                         nid = page_to_nid(page);
3226                         obj = ____cache_alloc_node(cache,
3227                                 gfp_exact_node(flags), nid);
3228
3229                         /*
3230                          * Another processor may allocate the objects in
3231                          * the slab since we are not holding any locks.
3232                          */
3233                         if (!obj)
3234                                 goto retry;
3235                 }
3236         }
3237
3238         if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3239                 goto retry_cpuset;
3240         return obj;
3241 }
3242
3243 /*
3244  * A interface to enable slab creation on nodeid
3245  */
3246 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3247                                 int nodeid)
3248 {
3249         struct page *page;
3250         struct kmem_cache_node *n;
3251         void *obj = NULL;
3252         void *list = NULL;
3253
3254         VM_BUG_ON(nodeid < 0 || nodeid >= MAX_NUMNODES);
3255         n = get_node(cachep, nodeid);
3256         BUG_ON(!n);
3257
3258         check_irq_off();
3259         spin_lock(&n->list_lock);
3260         page = get_first_slab(n, false);
3261         if (!page)
3262                 goto must_grow;
3263
3264         check_spinlock_acquired_node(cachep, nodeid);
3265
3266         STATS_INC_NODEALLOCS(cachep);
3267         STATS_INC_ACTIVE(cachep);
3268         STATS_SET_HIGH(cachep);
3269
3270         BUG_ON(page->active == cachep->num);
3271
3272         obj = slab_get_obj(cachep, page);
3273         n->free_objects--;
3274
3275         fixup_slab_list(cachep, n, page, &list);
3276
3277         spin_unlock(&n->list_lock);
3278         fixup_objfreelist_debug(cachep, &list);
3279         return obj;
3280
3281 must_grow:
3282         spin_unlock(&n->list_lock);
3283         page = cache_grow_begin(cachep, gfp_exact_node(flags), nodeid);
3284         if (page) {
3285                 /* This slab isn't counted yet so don't update free_objects */
3286                 obj = slab_get_obj(cachep, page);
3287         }
3288         cache_grow_end(cachep, page);
3289
3290         return obj ? obj : fallback_alloc(cachep, flags);
3291 }
3292
3293 static __always_inline void *
3294 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3295                    unsigned long caller)
3296 {
3297         unsigned long save_flags;
3298         void *ptr;
3299         int slab_node = numa_mem_id();
3300
3301         flags &= gfp_allowed_mask;
3302         cachep = slab_pre_alloc_hook(cachep, flags);
3303         if (unlikely(!cachep))
3304                 return NULL;
3305
3306         cache_alloc_debugcheck_before(cachep, flags);
3307         local_irq_save(save_flags);
3308
3309         if (nodeid == NUMA_NO_NODE)
3310                 nodeid = slab_node;
3311
3312         if (unlikely(!get_node(cachep, nodeid))) {
3313                 /* Node not bootstrapped yet */
3314                 ptr = fallback_alloc(cachep, flags);
3315                 goto out;
3316         }
3317
3318         if (nodeid == slab_node) {
3319                 /*
3320                  * Use the locally cached objects if possible.
3321                  * However ____cache_alloc does not allow fallback
3322                  * to other nodes. It may fail while we still have
3323                  * objects on other nodes available.
3324                  */
3325                 ptr = ____cache_alloc(cachep, flags);
3326                 if (ptr)
3327                         goto out;
3328         }
3329         /* ___cache_alloc_node can fall back to other nodes */
3330         ptr = ____cache_alloc_node(cachep, flags, nodeid);
3331   out:
3332         local_irq_restore(save_flags);
3333         ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3334
3335         if (unlikely(flags & __GFP_ZERO) && ptr)
3336                 memset(ptr, 0, cachep->object_size);
3337
3338         slab_post_alloc_hook(cachep, flags, 1, &ptr);
3339         return ptr;
3340 }
3341
3342 static __always_inline void *
3343 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3344 {
3345         void *objp;
3346
3347         if (current->mempolicy || cpuset_do_slab_mem_spread()) {
3348                 objp = alternate_node_alloc(cache, flags);
3349                 if (objp)
3350                         goto out;
3351         }
3352         objp = ____cache_alloc(cache, flags);
3353
3354         /*
3355          * We may just have run out of memory on the local node.
3356          * ____cache_alloc_node() knows how to locate memory on other nodes
3357          */
3358         if (!objp)
3359                 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3360
3361   out:
3362         return objp;
3363 }
3364 #else
3365
3366 static __always_inline void *
3367 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3368 {
3369         return ____cache_alloc(cachep, flags);
3370 }
3371
3372 #endif /* CONFIG_NUMA */
3373
3374 static __always_inline void *
3375 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3376 {
3377         unsigned long save_flags;
3378         void *objp;
3379
3380         flags &= gfp_allowed_mask;
3381         cachep = slab_pre_alloc_hook(cachep, flags);
3382         if (unlikely(!cachep))
3383                 return NULL;
3384
3385         cache_alloc_debugcheck_before(cachep, flags);
3386         local_irq_save(save_flags);
3387         objp = __do_cache_alloc(cachep, flags);
3388         local_irq_restore(save_flags);
3389         objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3390         prefetchw(objp);
3391
3392         if (unlikely(flags & __GFP_ZERO) && objp)
3393                 memset(objp, 0, cachep->object_size);
3394
3395         slab_post_alloc_hook(cachep, flags, 1, &objp);
3396         return objp;
3397 }
3398
3399 /*
3400  * Caller needs to acquire correct kmem_cache_node's list_lock
3401  * @list: List of detached free slabs should be freed by caller
3402  */
3403 static void free_block(struct kmem_cache *cachep, void **objpp,
3404                         int nr_objects, int node, struct list_head *list)
3405 {
3406         int i;
3407         struct kmem_cache_node *n = get_node(cachep, node);
3408         struct page *page;
3409
3410         n->free_objects += nr_objects;
3411
3412         for (i = 0; i < nr_objects; i++) {
3413                 void *objp;
3414                 struct page *page;
3415
3416                 objp = objpp[i];
3417
3418                 page = virt_to_head_page(objp);
3419                 list_del(&page->lru);
3420                 check_spinlock_acquired_node(cachep, node);
3421                 slab_put_obj(cachep, page, objp);
3422                 STATS_DEC_ACTIVE(cachep);
3423
3424                 /* fixup slab chains */
3425                 if (page->active == 0)
3426                         list_add(&page->lru, &n->slabs_free);
3427                 else {
3428                         /* Unconditionally move a slab to the end of the
3429                          * partial list on free - maximum time for the
3430                          * other objects to be freed, too.
3431                          */
3432                         list_add_tail(&page->lru, &n->slabs_partial);
3433                 }
3434         }
3435
3436         while (n->free_objects > n->free_limit && !list_empty(&n->slabs_free)) {
3437                 n->free_objects -= cachep->num;
3438
3439                 page = list_last_entry(&n->slabs_free, struct page, lru);
3440                 list_move(&page->lru, list);
3441         }
3442 }
3443
3444 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3445 {
3446         int batchcount;
3447         struct kmem_cache_node *n;
3448         int node = numa_mem_id();
3449         LIST_HEAD(list);
3450
3451         batchcount = ac->batchcount;
3452
3453         check_irq_off();
3454         n = get_node(cachep, node);
3455         spin_lock(&n->list_lock);
3456         if (n->shared) {
3457                 struct array_cache *shared_array = n->shared;
3458                 int max = shared_array->limit - shared_array->avail;
3459                 if (max) {
3460                         if (batchcount > max)
3461                                 batchcount = max;
3462                         memcpy(&(shared_array->entry[shared_array->avail]),
3463                                ac->entry, sizeof(void *) * batchcount);
3464                         shared_array->avail += batchcount;
3465                         goto free_done;
3466                 }
3467         }
3468
3469         free_block(cachep, ac->entry, batchcount, node, &list);
3470 free_done:
3471 #if STATS
3472         {
3473                 int i = 0;
3474                 struct page *page;
3475
3476                 list_for_each_entry(page, &n->slabs_free, lru) {
3477                         BUG_ON(page->active);
3478
3479                         i++;
3480                 }
3481                 STATS_SET_FREEABLE(cachep, i);
3482         }
3483 #endif
3484         spin_unlock(&n->list_lock);
3485         slabs_destroy(cachep, &list);
3486         ac->avail -= batchcount;
3487         memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3488 }
3489
3490 /*
3491  * Release an obj back to its cache. If the obj has a constructed state, it must
3492  * be in this state _before_ it is released.  Called with disabled ints.
3493  */
3494 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3495                                 unsigned long caller)
3496 {
3497         /* Put the object into the quarantine, don't touch it for now. */
3498         if (kasan_slab_free(cachep, objp))
3499                 return;
3500
3501         ___cache_free(cachep, objp, caller);
3502 }
3503
3504 void ___cache_free(struct kmem_cache *cachep, void *objp,
3505                 unsigned long caller)
3506 {
3507         struct array_cache *ac = cpu_cache_get(cachep);
3508
3509         check_irq_off();
3510         kmemleak_free_recursive(objp, cachep->flags);
3511         objp = cache_free_debugcheck(cachep, objp, caller);
3512
3513         kmemcheck_slab_free(cachep, objp, cachep->object_size);
3514
3515         /*
3516          * Skip calling cache_free_alien() when the platform is not numa.
3517          * This will avoid cache misses that happen while accessing slabp (which
3518          * is per page memory  reference) to get nodeid. Instead use a global
3519          * variable to skip the call, which is mostly likely to be present in
3520          * the cache.
3521          */
3522         if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3523                 return;
3524
3525         if (ac->avail < ac->limit) {
3526                 STATS_INC_FREEHIT(cachep);
3527         } else {
3528                 STATS_INC_FREEMISS(cachep);
3529                 cache_flusharray(cachep, ac);
3530         }
3531
3532         if (sk_memalloc_socks()) {
3533                 struct page *page = virt_to_head_page(objp);
3534
3535                 if (unlikely(PageSlabPfmemalloc(page))) {
3536                         cache_free_pfmemalloc(cachep, page, objp);
3537                         return;
3538                 }
3539         }
3540
3541         ac->entry[ac->avail++] = objp;
3542 }
3543
3544 /**
3545  * kmem_cache_alloc - Allocate an object
3546  * @cachep: The cache to allocate from.
3547  * @flags: See kmalloc().
3548  *
3549  * Allocate an object from this cache.  The flags are only relevant
3550  * if the cache has no available objects.
3551  */
3552 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3553 {
3554         void *ret = slab_alloc(cachep, flags, _RET_IP_);
3555
3556         kasan_slab_alloc(cachep, ret, flags);
3557         trace_kmem_cache_alloc(_RET_IP_, ret,
3558                                cachep->object_size, cachep->size, flags);
3559
3560         return ret;
3561 }
3562 EXPORT_SYMBOL(kmem_cache_alloc);
3563
3564 static __always_inline void
3565 cache_alloc_debugcheck_after_bulk(struct kmem_cache *s, gfp_t flags,
3566                                   size_t size, void **p, unsigned long caller)
3567 {
3568         size_t i;
3569
3570         for (i = 0; i < size; i++)
3571                 p[i] = cache_alloc_debugcheck_after(s, flags, p[i], caller);
3572 }
3573
3574 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3575                           void **p)
3576 {
3577         size_t i;
3578
3579         s = slab_pre_alloc_hook(s, flags);
3580         if (!s)
3581                 return 0;
3582
3583         cache_alloc_debugcheck_before(s, flags);
3584
3585         local_irq_disable();
3586         for (i = 0; i < size; i++) {
3587                 void *objp = __do_cache_alloc(s, flags);
3588
3589                 if (unlikely(!objp))
3590                         goto error;
3591                 p[i] = objp;
3592         }
3593         local_irq_enable();
3594
3595         cache_alloc_debugcheck_after_bulk(s, flags, size, p, _RET_IP_);
3596
3597         /* Clear memory outside IRQ disabled section */
3598         if (unlikely(flags & __GFP_ZERO))
3599                 for (i = 0; i < size; i++)
3600                         memset(p[i], 0, s->object_size);
3601
3602         slab_post_alloc_hook(s, flags, size, p);
3603         /* FIXME: Trace call missing. Christoph would like a bulk variant */
3604         return size;
3605 error:
3606         local_irq_enable();
3607         cache_alloc_debugcheck_after_bulk(s, flags, i, p, _RET_IP_);
3608         slab_post_alloc_hook(s, flags, i, p);
3609         __kmem_cache_free_bulk(s, i, p);
3610         return 0;
3611 }
3612 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3613
3614 #ifdef CONFIG_TRACING
3615 void *
3616 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3617 {
3618         void *ret;
3619
3620         ret = slab_alloc(cachep, flags, _RET_IP_);
3621
3622         kasan_kmalloc(cachep, ret, size, flags);
3623         trace_kmalloc(_RET_IP_, ret,
3624                       size, cachep->size, flags);
3625         return ret;
3626 }
3627 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3628 #endif
3629
3630 #ifdef CONFIG_NUMA
3631 /**
3632  * kmem_cache_alloc_node - Allocate an object on the specified node
3633  * @cachep: The cache to allocate from.
3634  * @flags: See kmalloc().
3635  * @nodeid: node number of the target node.
3636  *
3637  * Identical to kmem_cache_alloc but it will allocate memory on the given
3638  * node, which can improve the performance for cpu bound structures.
3639  *
3640  * Fallback to other node is possible if __GFP_THISNODE is not set.
3641  */
3642 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3643 {
3644         void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3645
3646         kasan_slab_alloc(cachep, ret, flags);
3647         trace_kmem_cache_alloc_node(_RET_IP_, ret,
3648                                     cachep->object_size, cachep->size,
3649                                     flags, nodeid);
3650
3651         return ret;
3652 }
3653 EXPORT_SYMBOL(kmem_cache_alloc_node);
3654
3655 #ifdef CONFIG_TRACING
3656 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3657                                   gfp_t flags,
3658                                   int nodeid,
3659                                   size_t size)
3660 {
3661         void *ret;
3662
3663         ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3664
3665         kasan_kmalloc(cachep, ret, size, flags);
3666         trace_kmalloc_node(_RET_IP_, ret,
3667                            size, cachep->size,
3668                            flags, nodeid);
3669         return ret;
3670 }
3671 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3672 #endif
3673
3674 static __always_inline void *
3675 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3676 {
3677         struct kmem_cache *cachep;
3678         void *ret;
3679
3680         cachep = kmalloc_slab(size, flags);
3681         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3682                 return cachep;
3683         ret = kmem_cache_alloc_node_trace(cachep, flags, node, size);
3684         kasan_kmalloc(cachep, ret, size, flags);
3685
3686         return ret;
3687 }
3688
3689 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3690 {
3691         return __do_kmalloc_node(size, flags, node, _RET_IP_);
3692 }
3693 EXPORT_SYMBOL(__kmalloc_node);
3694
3695 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3696                 int node, unsigned long caller)
3697 {
3698         return __do_kmalloc_node(size, flags, node, caller);
3699 }
3700 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3701 #endif /* CONFIG_NUMA */
3702
3703 /**
3704  * __do_kmalloc - allocate memory
3705  * @size: how many bytes of memory are required.
3706  * @flags: the type of memory to allocate (see kmalloc).
3707  * @caller: function caller for debug tracking of the caller
3708  */
3709 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3710                                           unsigned long caller)
3711 {
3712         struct kmem_cache *cachep;
3713         void *ret;
3714
3715         cachep = kmalloc_slab(size, flags);
3716         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3717                 return cachep;
3718         ret = slab_alloc(cachep, flags, caller);
3719
3720         kasan_kmalloc(cachep, ret, size, flags);
3721         trace_kmalloc(caller, ret,
3722                       size, cachep->size, flags);
3723
3724         return ret;
3725 }
3726
3727 void *__kmalloc(size_t size, gfp_t flags)
3728 {
3729         return __do_kmalloc(size, flags, _RET_IP_);
3730 }
3731 EXPORT_SYMBOL(__kmalloc);
3732
3733 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3734 {
3735         return __do_kmalloc(size, flags, caller);
3736 }
3737 EXPORT_SYMBOL(__kmalloc_track_caller);
3738
3739 /**
3740  * kmem_cache_free - Deallocate an object
3741  * @cachep: The cache the allocation was from.
3742  * @objp: The previously allocated object.
3743  *
3744  * Free an object which was previously allocated from this
3745  * cache.
3746  */
3747 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3748 {
3749         unsigned long flags;
3750         cachep = cache_from_obj(cachep, objp);
3751         if (!cachep)
3752                 return;
3753
3754         local_irq_save(flags);
3755         debug_check_no_locks_freed(objp, cachep->object_size);
3756         if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3757                 debug_check_no_obj_freed(objp, cachep->object_size);
3758         __cache_free(cachep, objp, _RET_IP_);
3759         local_irq_restore(flags);
3760
3761         trace_kmem_cache_free(_RET_IP_, objp);
3762 }
3763 EXPORT_SYMBOL(kmem_cache_free);
3764
3765 void kmem_cache_free_bulk(struct kmem_cache *orig_s, size_t size, void **p)
3766 {
3767         struct kmem_cache *s;
3768         size_t i;
3769
3770         local_irq_disable();
3771         for (i = 0; i < size; i++) {
3772                 void *objp = p[i];
3773
3774                 if (!orig_s) /* called via kfree_bulk */
3775                         s = virt_to_cache(objp);
3776                 else
3777                         s = cache_from_obj(orig_s, objp);
3778
3779                 debug_check_no_locks_freed(objp, s->object_size);
3780                 if (!(s->flags & SLAB_DEBUG_OBJECTS))
3781                         debug_check_no_obj_freed(objp, s->object_size);
3782
3783                 __cache_free(s, objp, _RET_IP_);
3784         }
3785         local_irq_enable();
3786
3787         /* FIXME: add tracing */
3788 }
3789 EXPORT_SYMBOL(kmem_cache_free_bulk);
3790
3791 /**
3792  * kfree - free previously allocated memory
3793  * @objp: pointer returned by kmalloc.
3794  *
3795  * If @objp is NULL, no operation is performed.
3796  *
3797  * Don't free memory not originally allocated by kmalloc()
3798  * or you will run into trouble.
3799  */
3800 void kfree(const void *objp)
3801 {
3802         struct kmem_cache *c;
3803         unsigned long flags;
3804
3805         trace_kfree(_RET_IP_, objp);
3806
3807         if (unlikely(ZERO_OR_NULL_PTR(objp)))
3808                 return;
3809         local_irq_save(flags);
3810         kfree_debugcheck(objp);
3811         c = virt_to_cache(objp);
3812         debug_check_no_locks_freed(objp, c->object_size);
3813
3814         debug_check_no_obj_freed(objp, c->object_size);
3815         __cache_free(c, (void *)objp, _RET_IP_);
3816         local_irq_restore(flags);
3817 }
3818 EXPORT_SYMBOL(kfree);
3819
3820 /*
3821  * This initializes kmem_cache_node or resizes various caches for all nodes.
3822  */
3823 static int setup_kmem_cache_nodes(struct kmem_cache *cachep, gfp_t gfp)
3824 {
3825         int ret;
3826         int node;
3827         struct kmem_cache_node *n;
3828
3829         for_each_online_node(node) {
3830                 ret = setup_kmem_cache_node(cachep, node, gfp, true);
3831                 if (ret)
3832                         goto fail;
3833
3834         }
3835
3836         return 0;
3837
3838 fail:
3839         if (!cachep->list.next) {
3840                 /* Cache is not active yet. Roll back what we did */
3841                 node--;
3842                 while (node >= 0) {
3843                         n = get_node(cachep, node);
3844                         if (n) {
3845                                 kfree(n->shared);
3846                                 free_alien_cache(n->alien);
3847                                 kfree(n);
3848                                 cachep->node[node] = NULL;
3849                         }
3850                         node--;
3851                 }
3852         }
3853         return -ENOMEM;
3854 }
3855
3856 /* Always called with the slab_mutex held */
3857 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3858                                 int batchcount, int shared, gfp_t gfp)
3859 {
3860         struct array_cache __percpu *cpu_cache, *prev;
3861         int cpu;
3862
3863         cpu_cache = alloc_kmem_cache_cpus(cachep, limit, batchcount);
3864         if (!cpu_cache)
3865                 return -ENOMEM;
3866
3867         prev = cachep->cpu_cache;
3868         cachep->cpu_cache = cpu_cache;
3869         kick_all_cpus_sync();
3870
3871         check_irq_on();
3872         cachep->batchcount = batchcount;
3873         cachep->limit = limit;
3874         cachep->shared = shared;
3875
3876         if (!prev)
3877                 goto setup_node;
3878
3879         for_each_online_cpu(cpu) {
3880                 LIST_HEAD(list);
3881                 int node;
3882                 struct kmem_cache_node *n;
3883                 struct array_cache *ac = per_cpu_ptr(prev, cpu);
3884
3885                 node = cpu_to_mem(cpu);
3886                 n = get_node(cachep, node);
3887                 spin_lock_irq(&n->list_lock);
3888                 free_block(cachep, ac->entry, ac->avail, node, &list);
3889                 spin_unlock_irq(&n->list_lock);
3890                 slabs_destroy(cachep, &list);
3891         }
3892         free_percpu(prev);
3893
3894 setup_node:
3895         return setup_kmem_cache_nodes(cachep, gfp);
3896 }
3897
3898 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3899                                 int batchcount, int shared, gfp_t gfp)
3900 {
3901         int ret;
3902         struct kmem_cache *c;
3903
3904         ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3905
3906         if (slab_state < FULL)
3907                 return ret;
3908
3909         if ((ret < 0) || !is_root_cache(cachep))
3910                 return ret;
3911
3912         lockdep_assert_held(&slab_mutex);
3913         for_each_memcg_cache(c, cachep) {
3914                 /* return value determined by the root cache only */
3915                 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3916         }
3917
3918         return ret;
3919 }
3920
3921 /* Called with slab_mutex held always */
3922 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3923 {
3924         int err;
3925         int limit = 0;
3926         int shared = 0;
3927         int batchcount = 0;
3928
3929         err = cache_random_seq_create(cachep, cachep->num, gfp);
3930         if (err)
3931                 goto end;
3932
3933         if (!is_root_cache(cachep)) {
3934                 struct kmem_cache *root = memcg_root_cache(cachep);
3935                 limit = root->limit;
3936                 shared = root->shared;
3937                 batchcount = root->batchcount;
3938         }
3939
3940         if (limit && shared && batchcount)
3941                 goto skip_setup;
3942         /*
3943          * The head array serves three purposes:
3944          * - create a LIFO ordering, i.e. return objects that are cache-warm
3945          * - reduce the number of spinlock operations.
3946          * - reduce the number of linked list operations on the slab and
3947          *   bufctl chains: array operations are cheaper.
3948          * The numbers are guessed, we should auto-tune as described by
3949          * Bonwick.
3950          */
3951         if (cachep->size > 131072)
3952                 limit = 1;
3953         else if (cachep->size > PAGE_SIZE)
3954                 limit = 8;
3955         else if (cachep->size > 1024)
3956                 limit = 24;
3957         else if (cachep->size > 256)
3958                 limit = 54;
3959         else
3960                 limit = 120;
3961
3962         /*
3963          * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3964          * allocation behaviour: Most allocs on one cpu, most free operations
3965          * on another cpu. For these cases, an efficient object passing between
3966          * cpus is necessary. This is provided by a shared array. The array
3967          * replaces Bonwick's magazine layer.
3968          * On uniprocessor, it's functionally equivalent (but less efficient)
3969          * to a larger limit. Thus disabled by default.
3970          */
3971         shared = 0;
3972         if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
3973                 shared = 8;
3974
3975 #if DEBUG
3976         /*
3977          * With debugging enabled, large batchcount lead to excessively long
3978          * periods with disabled local interrupts. Limit the batchcount
3979          */
3980         if (limit > 32)
3981                 limit = 32;
3982 #endif
3983         batchcount = (limit + 1) / 2;
3984 skip_setup:
3985         err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3986 end:
3987         if (err)
3988                 pr_err("enable_cpucache failed for %s, error %d\n",
3989                        cachep->name, -err);
3990         return err;
3991 }
3992
3993 /*
3994  * Drain an array if it contains any elements taking the node lock only if
3995  * necessary. Note that the node listlock also protects the array_cache
3996  * if drain_array() is used on the shared array.
3997  */
3998 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
3999                          struct array_cache *ac, int node)
4000 {
4001         LIST_HEAD(list);
4002
4003         /* ac from n->shared can be freed if we don't hold the slab_mutex. */
4004         check_mutex_acquired();
4005
4006         if (!ac || !ac->avail)
4007                 return;
4008
4009         if (ac->touched) {
4010                 ac->touched = 0;
4011                 return;
4012         }
4013
4014         spin_lock_irq(&n->list_lock);
4015         drain_array_locked(cachep, ac, node, false, &list);
4016         spin_unlock_irq(&n->list_lock);
4017
4018         slabs_destroy(cachep, &list);
4019 }
4020
4021 /**
4022  * cache_reap - Reclaim memory from caches.
4023  * @w: work descriptor
4024  *
4025  * Called from workqueue/eventd every few seconds.
4026  * Purpose:
4027  * - clear the per-cpu caches for this CPU.
4028  * - return freeable pages to the main free memory pool.
4029  *
4030  * If we cannot acquire the cache chain mutex then just give up - we'll try
4031  * again on the next iteration.
4032  */
4033 static void cache_reap(struct work_struct *w)
4034 {
4035         struct kmem_cache *searchp;
4036         struct kmem_cache_node *n;
4037         int node = numa_mem_id();
4038         struct delayed_work *work = to_delayed_work(w);
4039
4040         if (!mutex_trylock(&slab_mutex))
4041                 /* Give up. Setup the next iteration. */
4042                 goto out;
4043
4044         list_for_each_entry(searchp, &slab_caches, list) {
4045                 check_irq_on();
4046
4047                 /*
4048                  * We only take the node lock if absolutely necessary and we
4049                  * have established with reasonable certainty that
4050                  * we can do some work if the lock was obtained.
4051                  */
4052                 n = get_node(searchp, node);
4053
4054                 reap_alien(searchp, n);
4055
4056                 drain_array(searchp, n, cpu_cache_get(searchp), node);
4057
4058                 /*
4059                  * These are racy checks but it does not matter
4060                  * if we skip one check or scan twice.
4061                  */
4062                 if (time_after(n->next_reap, jiffies))
4063                         goto next;
4064
4065                 n->next_reap = jiffies + REAPTIMEOUT_NODE;
4066
4067                 drain_array(searchp, n, n->shared, node);
4068
4069                 if (n->free_touched)
4070                         n->free_touched = 0;
4071                 else {
4072                         int freed;
4073
4074                         freed = drain_freelist(searchp, n, (n->free_limit +
4075                                 5 * searchp->num - 1) / (5 * searchp->num));
4076                         STATS_ADD_REAPED(searchp, freed);
4077                 }
4078 next:
4079                 cond_resched();
4080         }
4081         check_irq_on();
4082         mutex_unlock(&slab_mutex);
4083         next_reap_node();
4084 out:
4085         /* Set up the next iteration */
4086         schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
4087 }
4088
4089 #ifdef CONFIG_SLABINFO
4090 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4091 {
4092         struct page *page;
4093         unsigned long active_objs;
4094         unsigned long num_objs;
4095         unsigned long active_slabs = 0;
4096         unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4097         const char *name;
4098         char *error = NULL;
4099         int node;
4100         struct kmem_cache_node *n;
4101
4102         active_objs = 0;
4103         num_slabs = 0;
4104         for_each_kmem_cache_node(cachep, node, n) {
4105
4106                 check_irq_on();
4107                 spin_lock_irq(&n->list_lock);
4108
4109                 list_for_each_entry(page, &n->slabs_full, lru) {
4110                         if (page->active != cachep->num && !error)
4111                                 error = "slabs_full accounting error";
4112                         active_objs += cachep->num;
4113                         active_slabs++;
4114                 }
4115                 list_for_each_entry(page, &n->slabs_partial, lru) {
4116                         if (page->active == cachep->num && !error)
4117                                 error = "slabs_partial accounting error";
4118                         if (!page->active && !error)
4119                                 error = "slabs_partial accounting error";
4120                         active_objs += page->active;
4121                         active_slabs++;
4122                 }
4123                 list_for_each_entry(page, &n->slabs_free, lru) {
4124                         if (page->active && !error)
4125                                 error = "slabs_free accounting error";
4126                         num_slabs++;
4127                 }
4128                 free_objects += n->free_objects;
4129                 if (n->shared)
4130                         shared_avail += n->shared->avail;
4131
4132                 spin_unlock_irq(&n->list_lock);
4133         }
4134         num_slabs += active_slabs;
4135         num_objs = num_slabs * cachep->num;
4136         if (num_objs - active_objs != free_objects && !error)
4137                 error = "free_objects accounting error";
4138
4139         name = cachep->name;
4140         if (error)
4141                 pr_err("slab: cache %s error: %s\n", name, error);
4142
4143         sinfo->active_objs = active_objs;
4144         sinfo->num_objs = num_objs;
4145         sinfo->active_slabs = active_slabs;
4146         sinfo->num_slabs = num_slabs;
4147         sinfo->shared_avail = shared_avail;
4148         sinfo->limit = cachep->limit;
4149         sinfo->batchcount = cachep->batchcount;
4150         sinfo->shared = cachep->shared;
4151         sinfo->objects_per_slab = cachep->num;
4152         sinfo->cache_order = cachep->gfporder;
4153 }
4154
4155 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4156 {
4157 #if STATS
4158         {                       /* node stats */
4159                 unsigned long high = cachep->high_mark;
4160                 unsigned long allocs = cachep->num_allocations;
4161                 unsigned long grown = cachep->grown;
4162                 unsigned long reaped = cachep->reaped;
4163                 unsigned long errors = cachep->errors;
4164                 unsigned long max_freeable = cachep->max_freeable;
4165                 unsigned long node_allocs = cachep->node_allocs;
4166                 unsigned long node_frees = cachep->node_frees;
4167                 unsigned long overflows = cachep->node_overflow;
4168
4169                 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu %4lu",
4170                            allocs, high, grown,
4171                            reaped, errors, max_freeable, node_allocs,
4172                            node_frees, overflows);
4173         }
4174         /* cpu stats */
4175         {
4176                 unsigned long allochit = atomic_read(&cachep->allochit);
4177                 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4178                 unsigned long freehit = atomic_read(&cachep->freehit);
4179                 unsigned long freemiss = atomic_read(&cachep->freemiss);
4180
4181                 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4182                            allochit, allocmiss, freehit, freemiss);
4183         }
4184 #endif
4185 }
4186
4187 #define MAX_SLABINFO_WRITE 128
4188 /**
4189  * slabinfo_write - Tuning for the slab allocator
4190  * @file: unused
4191  * @buffer: user buffer
4192  * @count: data length
4193  * @ppos: unused
4194  */
4195 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4196                        size_t count, loff_t *ppos)
4197 {
4198         char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4199         int limit, batchcount, shared, res;
4200         struct kmem_cache *cachep;
4201
4202         if (count > MAX_SLABINFO_WRITE)
4203                 return -EINVAL;
4204         if (copy_from_user(&kbuf, buffer, count))
4205                 return -EFAULT;
4206         kbuf[MAX_SLABINFO_WRITE] = '\0';
4207
4208         tmp = strchr(kbuf, ' ');
4209         if (!tmp)
4210                 return -EINVAL;
4211         *tmp = '\0';
4212         tmp++;
4213         if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4214                 return -EINVAL;
4215
4216         /* Find the cache in the chain of caches. */
4217         mutex_lock(&slab_mutex);
4218         res = -EINVAL;
4219         list_for_each_entry(cachep, &slab_caches, list) {
4220                 if (!strcmp(cachep->name, kbuf)) {
4221                         if (limit < 1 || batchcount < 1 ||
4222                                         batchcount > limit || shared < 0) {
4223                                 res = 0;
4224                         } else {
4225                                 res = do_tune_cpucache(cachep, limit,
4226                                                        batchcount, shared,
4227                                                        GFP_KERNEL);
4228                         }
4229                         break;
4230                 }
4231         }
4232         mutex_unlock(&slab_mutex);
4233         if (res >= 0)
4234                 res = count;
4235         return res;
4236 }
4237
4238 #ifdef CONFIG_DEBUG_SLAB_LEAK
4239
4240 static inline int add_caller(unsigned long *n, unsigned long v)
4241 {
4242         unsigned long *p;
4243         int l;
4244         if (!v)
4245                 return 1;
4246         l = n[1];
4247         p = n + 2;
4248         while (l) {
4249                 int i = l/2;
4250                 unsigned long *q = p + 2 * i;
4251                 if (*q == v) {
4252                         q[1]++;
4253                         return 1;
4254                 }
4255                 if (*q > v) {
4256                         l = i;
4257                 } else {
4258                         p = q + 2;
4259                         l -= i + 1;
4260                 }
4261         }
4262         if (++n[1] == n[0])
4263                 return 0;
4264         memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4265         p[0] = v;
4266         p[1] = 1;
4267         return 1;
4268 }
4269
4270 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4271                                                 struct page *page)
4272 {
4273         void *p;
4274         int i, j;
4275         unsigned long v;
4276
4277         if (n[0] == n[1])
4278                 return;
4279         for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4280                 bool active = true;
4281
4282                 for (j = page->active; j < c->num; j++) {
4283                         if (get_free_obj(page, j) == i) {
4284                                 active = false;
4285                                 break;
4286                         }
4287                 }
4288
4289                 if (!active)
4290                         continue;
4291
4292                 /*
4293                  * probe_kernel_read() is used for DEBUG_PAGEALLOC. page table
4294                  * mapping is established when actual object allocation and
4295                  * we could mistakenly access the unmapped object in the cpu
4296                  * cache.
4297                  */
4298                 if (probe_kernel_read(&v, dbg_userword(c, p), sizeof(v)))
4299                         continue;
4300
4301                 if (!add_caller(n, v))
4302                         return;
4303         }
4304 }
4305
4306 static void show_symbol(struct seq_file *m, unsigned long address)
4307 {
4308 #ifdef CONFIG_KALLSYMS
4309         unsigned long offset, size;
4310         char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4311
4312         if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4313                 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4314                 if (modname[0])
4315                         seq_printf(m, " [%s]", modname);
4316                 return;
4317         }
4318 #endif
4319         seq_printf(m, "%p", (void *)address);
4320 }
4321
4322 static int leaks_show(struct seq_file *m, void *p)
4323 {
4324         struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4325         struct page *page;
4326         struct kmem_cache_node *n;
4327         const char *name;
4328         unsigned long *x = m->private;
4329         int node;
4330         int i;
4331
4332         if (!(cachep->flags & SLAB_STORE_USER))
4333                 return 0;
4334         if (!(cachep->flags & SLAB_RED_ZONE))
4335                 return 0;
4336
4337         /*
4338          * Set store_user_clean and start to grab stored user information
4339          * for all objects on this cache. If some alloc/free requests comes
4340          * during the processing, information would be wrong so restart
4341          * whole processing.
4342          */
4343         do {
4344                 set_store_user_clean(cachep);
4345                 drain_cpu_caches(cachep);
4346
4347                 x[1] = 0;
4348
4349                 for_each_kmem_cache_node(cachep, node, n) {
4350
4351                         check_irq_on();
4352                         spin_lock_irq(&n->list_lock);
4353
4354                         list_for_each_entry(page, &n->slabs_full, lru)
4355                                 handle_slab(x, cachep, page);
4356                         list_for_each_entry(page, &n->slabs_partial, lru)
4357                                 handle_slab(x, cachep, page);
4358                         spin_unlock_irq(&n->list_lock);
4359                 }
4360         } while (!is_store_user_clean(cachep));
4361
4362         name = cachep->name;
4363         if (x[0] == x[1]) {
4364                 /* Increase the buffer size */
4365                 mutex_unlock(&slab_mutex);
4366                 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4367                 if (!m->private) {
4368                         /* Too bad, we are really out */
4369                         m->private = x;
4370                         mutex_lock(&slab_mutex);
4371                         return -ENOMEM;
4372                 }
4373                 *(unsigned long *)m->private = x[0] * 2;
4374                 kfree(x);
4375                 mutex_lock(&slab_mutex);
4376                 /* Now make sure this entry will be retried */
4377                 m->count = m->size;
4378                 return 0;
4379         }
4380         for (i = 0; i < x[1]; i++) {
4381                 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4382                 show_symbol(m, x[2*i+2]);
4383                 seq_putc(m, '\n');
4384         }
4385
4386         return 0;
4387 }
4388
4389 static const struct seq_operations slabstats_op = {
4390         .start = slab_start,
4391         .next = slab_next,
4392         .stop = slab_stop,
4393         .show = leaks_show,
4394 };
4395
4396 static int slabstats_open(struct inode *inode, struct file *file)
4397 {
4398         unsigned long *n;
4399
4400         n = __seq_open_private(file, &slabstats_op, PAGE_SIZE);
4401         if (!n)
4402                 return -ENOMEM;
4403
4404         *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4405
4406         return 0;
4407 }
4408
4409 static const struct file_operations proc_slabstats_operations = {
4410         .open           = slabstats_open,
4411         .read           = seq_read,
4412         .llseek         = seq_lseek,
4413         .release        = seq_release_private,
4414 };
4415 #endif
4416
4417 static int __init slab_proc_init(void)
4418 {
4419 #ifdef CONFIG_DEBUG_SLAB_LEAK
4420         proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4421 #endif
4422         return 0;
4423 }
4424 module_init(slab_proc_init);
4425 #endif
4426
4427 #ifdef CONFIG_HARDENED_USERCOPY
4428 /*
4429  * Rejects objects that are incorrectly sized.
4430  *
4431  * Returns NULL if check passes, otherwise const char * to name of cache
4432  * to indicate an error.
4433  */
4434 const char *__check_heap_object(const void *ptr, unsigned long n,
4435                                 struct page *page)
4436 {
4437         struct kmem_cache *cachep;
4438         unsigned int objnr;
4439         unsigned long offset;
4440
4441         /* Find and validate object. */
4442         cachep = page->slab_cache;
4443         objnr = obj_to_index(cachep, page, (void *)ptr);
4444         BUG_ON(objnr >= cachep->num);
4445
4446         /* Find offset within object. */
4447         offset = ptr - index_to_obj(cachep, page, objnr) - obj_offset(cachep);
4448
4449         /* Allow address range falling entirely within object size. */
4450         if (offset <= cachep->object_size && n <= cachep->object_size - offset)
4451                 return NULL;
4452
4453         return cachep->name;
4454 }
4455 #endif /* CONFIG_HARDENED_USERCOPY */
4456
4457 /**
4458  * ksize - get the actual amount of memory allocated for a given object
4459  * @objp: Pointer to the object
4460  *
4461  * kmalloc may internally round up allocations and return more memory
4462  * than requested. ksize() can be used to determine the actual amount of
4463  * memory allocated. The caller may use this additional memory, even though
4464  * a smaller amount of memory was initially specified with the kmalloc call.
4465  * The caller must guarantee that objp points to a valid object previously
4466  * allocated with either kmalloc() or kmem_cache_alloc(). The object
4467  * must not be freed during the duration of the call.
4468  */
4469 size_t ksize(const void *objp)
4470 {
4471         size_t size;
4472
4473         BUG_ON(!objp);
4474         if (unlikely(objp == ZERO_SIZE_PTR))
4475                 return 0;
4476
4477         size = virt_to_cache(objp)->object_size;
4478         /* We assume that ksize callers could use the whole allocated area,
4479          * so we need to unpoison this area.
4480          */
4481         kasan_unpoison_shadow(objp, size);
4482
4483         return size;
4484 }
4485 EXPORT_SYMBOL(ksize);