OSDN Git Service

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