OSDN Git Service

UPSTREAM: mm/slab: align cache size first before determination of OFF_SLAB candidate
[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         init_arraycache(&alc->ac, entries, batch);
863         spin_lock_init(&alc->lock);
864         return alc;
865 }
866
867 static struct alien_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
868 {
869         struct alien_cache **alc_ptr;
870         size_t memsize = sizeof(void *) * nr_node_ids;
871         int i;
872
873         if (limit > 1)
874                 limit = 12;
875         alc_ptr = kzalloc_node(memsize, gfp, node);
876         if (!alc_ptr)
877                 return NULL;
878
879         for_each_node(i) {
880                 if (i == node || !node_online(i))
881                         continue;
882                 alc_ptr[i] = __alloc_alien_cache(node, limit, 0xbaadf00d, gfp);
883                 if (!alc_ptr[i]) {
884                         for (i--; i >= 0; i--)
885                                 kfree(alc_ptr[i]);
886                         kfree(alc_ptr);
887                         return NULL;
888                 }
889         }
890         return alc_ptr;
891 }
892
893 static void free_alien_cache(struct alien_cache **alc_ptr)
894 {
895         int i;
896
897         if (!alc_ptr)
898                 return;
899         for_each_node(i)
900             kfree(alc_ptr[i]);
901         kfree(alc_ptr);
902 }
903
904 static void __drain_alien_cache(struct kmem_cache *cachep,
905                                 struct array_cache *ac, int node,
906                                 struct list_head *list)
907 {
908         struct kmem_cache_node *n = get_node(cachep, node);
909
910         if (ac->avail) {
911                 spin_lock(&n->list_lock);
912                 /*
913                  * Stuff objects into the remote nodes shared array first.
914                  * That way we could avoid the overhead of putting the objects
915                  * into the free lists and getting them back later.
916                  */
917                 if (n->shared)
918                         transfer_objects(n->shared, ac, ac->limit);
919
920                 free_block(cachep, ac->entry, ac->avail, node, list);
921                 ac->avail = 0;
922                 spin_unlock(&n->list_lock);
923         }
924 }
925
926 /*
927  * Called from cache_reap() to regularly drain alien caches round robin.
928  */
929 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
930 {
931         int node = __this_cpu_read(slab_reap_node);
932
933         if (n->alien) {
934                 struct alien_cache *alc = n->alien[node];
935                 struct array_cache *ac;
936
937                 if (alc) {
938                         ac = &alc->ac;
939                         if (ac->avail && spin_trylock_irq(&alc->lock)) {
940                                 LIST_HEAD(list);
941
942                                 __drain_alien_cache(cachep, ac, node, &list);
943                                 spin_unlock_irq(&alc->lock);
944                                 slabs_destroy(cachep, &list);
945                         }
946                 }
947         }
948 }
949
950 static void drain_alien_cache(struct kmem_cache *cachep,
951                                 struct alien_cache **alien)
952 {
953         int i = 0;
954         struct alien_cache *alc;
955         struct array_cache *ac;
956         unsigned long flags;
957
958         for_each_online_node(i) {
959                 alc = alien[i];
960                 if (alc) {
961                         LIST_HEAD(list);
962
963                         ac = &alc->ac;
964                         spin_lock_irqsave(&alc->lock, flags);
965                         __drain_alien_cache(cachep, ac, i, &list);
966                         spin_unlock_irqrestore(&alc->lock, flags);
967                         slabs_destroy(cachep, &list);
968                 }
969         }
970 }
971
972 static int __cache_free_alien(struct kmem_cache *cachep, void *objp,
973                                 int node, int page_node)
974 {
975         struct kmem_cache_node *n;
976         struct alien_cache *alien = NULL;
977         struct array_cache *ac;
978         LIST_HEAD(list);
979
980         n = get_node(cachep, node);
981         STATS_INC_NODEFREES(cachep);
982         if (n->alien && n->alien[page_node]) {
983                 alien = n->alien[page_node];
984                 ac = &alien->ac;
985                 spin_lock(&alien->lock);
986                 if (unlikely(ac->avail == ac->limit)) {
987                         STATS_INC_ACOVERFLOW(cachep);
988                         __drain_alien_cache(cachep, ac, page_node, &list);
989                 }
990                 ac_put_obj(cachep, ac, objp);
991                 spin_unlock(&alien->lock);
992                 slabs_destroy(cachep, &list);
993         } else {
994                 n = get_node(cachep, page_node);
995                 spin_lock(&n->list_lock);
996                 free_block(cachep, &objp, 1, page_node, &list);
997                 spin_unlock(&n->list_lock);
998                 slabs_destroy(cachep, &list);
999         }
1000         return 1;
1001 }
1002
1003 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1004 {
1005         int page_node = page_to_nid(virt_to_page(objp));
1006         int node = numa_mem_id();
1007         /*
1008          * Make sure we are not freeing a object from another node to the array
1009          * cache on this cpu.
1010          */
1011         if (likely(node == page_node))
1012                 return 0;
1013
1014         return __cache_free_alien(cachep, objp, node, page_node);
1015 }
1016
1017 /*
1018  * Construct gfp mask to allocate from a specific node but do not direct reclaim
1019  * or warn about failures. kswapd may still wake to reclaim in the background.
1020  */
1021 static inline gfp_t gfp_exact_node(gfp_t flags)
1022 {
1023         return (flags | __GFP_THISNODE | __GFP_NOWARN) & ~__GFP_DIRECT_RECLAIM;
1024 }
1025 #endif
1026
1027 /*
1028  * Allocates and initializes node for a node on each slab cache, used for
1029  * either memory or cpu hotplug.  If memory is being hot-added, the kmem_cache_node
1030  * will be allocated off-node since memory is not yet online for the new node.
1031  * When hotplugging memory or a cpu, existing node are not replaced if
1032  * already in use.
1033  *
1034  * Must hold slab_mutex.
1035  */
1036 static int init_cache_node_node(int node)
1037 {
1038         struct kmem_cache *cachep;
1039         struct kmem_cache_node *n;
1040         const size_t memsize = sizeof(struct kmem_cache_node);
1041
1042         list_for_each_entry(cachep, &slab_caches, list) {
1043                 /*
1044                  * Set up the kmem_cache_node for cpu before we can
1045                  * begin anything. Make sure some other cpu on this
1046                  * node has not already allocated this
1047                  */
1048                 n = get_node(cachep, node);
1049                 if (!n) {
1050                         n = kmalloc_node(memsize, GFP_KERNEL, node);
1051                         if (!n)
1052                                 return -ENOMEM;
1053                         kmem_cache_node_init(n);
1054                         n->next_reap = jiffies + REAPTIMEOUT_NODE +
1055                             ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1056
1057                         /*
1058                          * The kmem_cache_nodes don't come and go as CPUs
1059                          * come and go.  slab_mutex is sufficient
1060                          * protection here.
1061                          */
1062                         cachep->node[node] = n;
1063                 }
1064
1065                 spin_lock_irq(&n->list_lock);
1066                 n->free_limit =
1067                         (1 + nr_cpus_node(node)) *
1068                         cachep->batchcount + cachep->num;
1069                 spin_unlock_irq(&n->list_lock);
1070         }
1071         return 0;
1072 }
1073
1074 static inline int slabs_tofree(struct kmem_cache *cachep,
1075                                                 struct kmem_cache_node *n)
1076 {
1077         return (n->free_objects + cachep->num - 1) / cachep->num;
1078 }
1079
1080 static void cpuup_canceled(long cpu)
1081 {
1082         struct kmem_cache *cachep;
1083         struct kmem_cache_node *n = NULL;
1084         int node = cpu_to_mem(cpu);
1085         const struct cpumask *mask = cpumask_of_node(node);
1086
1087         list_for_each_entry(cachep, &slab_caches, list) {
1088                 struct array_cache *nc;
1089                 struct array_cache *shared;
1090                 struct alien_cache **alien;
1091                 LIST_HEAD(list);
1092
1093                 n = get_node(cachep, node);
1094                 if (!n)
1095                         continue;
1096
1097                 spin_lock_irq(&n->list_lock);
1098
1099                 /* Free limit for this kmem_cache_node */
1100                 n->free_limit -= cachep->batchcount;
1101
1102                 /* cpu is dead; no one can alloc from it. */
1103                 nc = per_cpu_ptr(cachep->cpu_cache, cpu);
1104                 if (nc) {
1105                         free_block(cachep, nc->entry, nc->avail, node, &list);
1106                         nc->avail = 0;
1107                 }
1108
1109                 if (!cpumask_empty(mask)) {
1110                         spin_unlock_irq(&n->list_lock);
1111                         goto free_slab;
1112                 }
1113
1114                 shared = n->shared;
1115                 if (shared) {
1116                         free_block(cachep, shared->entry,
1117                                    shared->avail, node, &list);
1118                         n->shared = NULL;
1119                 }
1120
1121                 alien = n->alien;
1122                 n->alien = NULL;
1123
1124                 spin_unlock_irq(&n->list_lock);
1125
1126                 kfree(shared);
1127                 if (alien) {
1128                         drain_alien_cache(cachep, alien);
1129                         free_alien_cache(alien);
1130                 }
1131
1132 free_slab:
1133                 slabs_destroy(cachep, &list);
1134         }
1135         /*
1136          * In the previous loop, all the objects were freed to
1137          * the respective cache's slabs,  now we can go ahead and
1138          * shrink each nodelist to its limit.
1139          */
1140         list_for_each_entry(cachep, &slab_caches, list) {
1141                 n = get_node(cachep, node);
1142                 if (!n)
1143                         continue;
1144                 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1145         }
1146 }
1147
1148 static int cpuup_prepare(long cpu)
1149 {
1150         struct kmem_cache *cachep;
1151         struct kmem_cache_node *n = NULL;
1152         int node = cpu_to_mem(cpu);
1153         int err;
1154
1155         /*
1156          * We need to do this right in the beginning since
1157          * alloc_arraycache's are going to use this list.
1158          * kmalloc_node allows us to add the slab to the right
1159          * kmem_cache_node and not this cpu's kmem_cache_node
1160          */
1161         err = init_cache_node_node(node);
1162         if (err < 0)
1163                 goto bad;
1164
1165         /*
1166          * Now we can go ahead with allocating the shared arrays and
1167          * array caches
1168          */
1169         list_for_each_entry(cachep, &slab_caches, list) {
1170                 struct array_cache *shared = NULL;
1171                 struct alien_cache **alien = NULL;
1172
1173                 if (cachep->shared) {
1174                         shared = alloc_arraycache(node,
1175                                 cachep->shared * cachep->batchcount,
1176                                 0xbaadf00d, GFP_KERNEL);
1177                         if (!shared)
1178                                 goto bad;
1179                 }
1180                 if (use_alien_caches) {
1181                         alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1182                         if (!alien) {
1183                                 kfree(shared);
1184                                 goto bad;
1185                         }
1186                 }
1187                 n = get_node(cachep, node);
1188                 BUG_ON(!n);
1189
1190                 spin_lock_irq(&n->list_lock);
1191                 if (!n->shared) {
1192                         /*
1193                          * We are serialised from CPU_DEAD or
1194                          * CPU_UP_CANCELLED by the cpucontrol lock
1195                          */
1196                         n->shared = shared;
1197                         shared = NULL;
1198                 }
1199 #ifdef CONFIG_NUMA
1200                 if (!n->alien) {
1201                         n->alien = alien;
1202                         alien = NULL;
1203                 }
1204 #endif
1205                 spin_unlock_irq(&n->list_lock);
1206                 kfree(shared);
1207                 free_alien_cache(alien);
1208         }
1209
1210         return 0;
1211 bad:
1212         cpuup_canceled(cpu);
1213         return -ENOMEM;
1214 }
1215
1216 static int cpuup_callback(struct notifier_block *nfb,
1217                                     unsigned long action, void *hcpu)
1218 {
1219         long cpu = (long)hcpu;
1220         int err = 0;
1221
1222         switch (action) {
1223         case CPU_UP_PREPARE:
1224         case CPU_UP_PREPARE_FROZEN:
1225                 mutex_lock(&slab_mutex);
1226                 err = cpuup_prepare(cpu);
1227                 mutex_unlock(&slab_mutex);
1228                 break;
1229         case CPU_ONLINE:
1230         case CPU_ONLINE_FROZEN:
1231                 start_cpu_timer(cpu);
1232                 break;
1233 #ifdef CONFIG_HOTPLUG_CPU
1234         case CPU_DOWN_PREPARE:
1235         case CPU_DOWN_PREPARE_FROZEN:
1236                 /*
1237                  * Shutdown cache reaper. Note that the slab_mutex is
1238                  * held so that if cache_reap() is invoked it cannot do
1239                  * anything expensive but will only modify reap_work
1240                  * and reschedule the timer.
1241                 */
1242                 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1243                 /* Now the cache_reaper is guaranteed to be not running. */
1244                 per_cpu(slab_reap_work, cpu).work.func = NULL;
1245                 break;
1246         case CPU_DOWN_FAILED:
1247         case CPU_DOWN_FAILED_FROZEN:
1248                 start_cpu_timer(cpu);
1249                 break;
1250         case CPU_DEAD:
1251         case CPU_DEAD_FROZEN:
1252                 /*
1253                  * Even if all the cpus of a node are down, we don't free the
1254                  * kmem_cache_node of any cache. This to avoid a race between
1255                  * cpu_down, and a kmalloc allocation from another cpu for
1256                  * memory from the node of the cpu going down.  The node
1257                  * structure is usually allocated from kmem_cache_create() and
1258                  * gets destroyed at kmem_cache_destroy().
1259                  */
1260                 /* fall through */
1261 #endif
1262         case CPU_UP_CANCELED:
1263         case CPU_UP_CANCELED_FROZEN:
1264                 mutex_lock(&slab_mutex);
1265                 cpuup_canceled(cpu);
1266                 mutex_unlock(&slab_mutex);
1267                 break;
1268         }
1269         return notifier_from_errno(err);
1270 }
1271
1272 static struct notifier_block cpucache_notifier = {
1273         &cpuup_callback, NULL, 0
1274 };
1275
1276 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1277 /*
1278  * Drains freelist for a node on each slab cache, used for memory hot-remove.
1279  * Returns -EBUSY if all objects cannot be drained so that the node is not
1280  * removed.
1281  *
1282  * Must hold slab_mutex.
1283  */
1284 static int __meminit drain_cache_node_node(int node)
1285 {
1286         struct kmem_cache *cachep;
1287         int ret = 0;
1288
1289         list_for_each_entry(cachep, &slab_caches, list) {
1290                 struct kmem_cache_node *n;
1291
1292                 n = get_node(cachep, node);
1293                 if (!n)
1294                         continue;
1295
1296                 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1297
1298                 if (!list_empty(&n->slabs_full) ||
1299                     !list_empty(&n->slabs_partial)) {
1300                         ret = -EBUSY;
1301                         break;
1302                 }
1303         }
1304         return ret;
1305 }
1306
1307 static int __meminit slab_memory_callback(struct notifier_block *self,
1308                                         unsigned long action, void *arg)
1309 {
1310         struct memory_notify *mnb = arg;
1311         int ret = 0;
1312         int nid;
1313
1314         nid = mnb->status_change_nid;
1315         if (nid < 0)
1316                 goto out;
1317
1318         switch (action) {
1319         case MEM_GOING_ONLINE:
1320                 mutex_lock(&slab_mutex);
1321                 ret = init_cache_node_node(nid);
1322                 mutex_unlock(&slab_mutex);
1323                 break;
1324         case MEM_GOING_OFFLINE:
1325                 mutex_lock(&slab_mutex);
1326                 ret = drain_cache_node_node(nid);
1327                 mutex_unlock(&slab_mutex);
1328                 break;
1329         case MEM_ONLINE:
1330         case MEM_OFFLINE:
1331         case MEM_CANCEL_ONLINE:
1332         case MEM_CANCEL_OFFLINE:
1333                 break;
1334         }
1335 out:
1336         return notifier_from_errno(ret);
1337 }
1338 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1339
1340 /*
1341  * swap the static kmem_cache_node with kmalloced memory
1342  */
1343 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1344                                 int nodeid)
1345 {
1346         struct kmem_cache_node *ptr;
1347
1348         ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1349         BUG_ON(!ptr);
1350
1351         memcpy(ptr, list, sizeof(struct kmem_cache_node));
1352         /*
1353          * Do not assume that spinlocks can be initialized via memcpy:
1354          */
1355         spin_lock_init(&ptr->list_lock);
1356
1357         MAKE_ALL_LISTS(cachep, ptr, nodeid);
1358         cachep->node[nodeid] = ptr;
1359 }
1360
1361 /*
1362  * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1363  * size of kmem_cache_node.
1364  */
1365 static void __init set_up_node(struct kmem_cache *cachep, int index)
1366 {
1367         int node;
1368
1369         for_each_online_node(node) {
1370                 cachep->node[node] = &init_kmem_cache_node[index + node];
1371                 cachep->node[node]->next_reap = jiffies +
1372                     REAPTIMEOUT_NODE +
1373                     ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1374         }
1375 }
1376
1377 /*
1378  * Initialisation.  Called after the page allocator have been initialised and
1379  * before smp_init().
1380  */
1381 void __init kmem_cache_init(void)
1382 {
1383         int i;
1384
1385         BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1386                                         sizeof(struct rcu_head));
1387         kmem_cache = &kmem_cache_boot;
1388
1389         if (num_possible_nodes() == 1)
1390                 use_alien_caches = 0;
1391
1392         for (i = 0; i < NUM_INIT_LISTS; i++)
1393                 kmem_cache_node_init(&init_kmem_cache_node[i]);
1394
1395         /*
1396          * Fragmentation resistance on low memory - only use bigger
1397          * page orders on machines with more than 32MB of memory if
1398          * not overridden on the command line.
1399          */
1400         if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1401                 slab_max_order = SLAB_MAX_ORDER_HI;
1402
1403         /* Bootstrap is tricky, because several objects are allocated
1404          * from caches that do not exist yet:
1405          * 1) initialize the kmem_cache cache: it contains the struct
1406          *    kmem_cache structures of all caches, except kmem_cache itself:
1407          *    kmem_cache is statically allocated.
1408          *    Initially an __init data area is used for the head array and the
1409          *    kmem_cache_node structures, it's replaced with a kmalloc allocated
1410          *    array at the end of the bootstrap.
1411          * 2) Create the first kmalloc cache.
1412          *    The struct kmem_cache for the new cache is allocated normally.
1413          *    An __init data area is used for the head array.
1414          * 3) Create the remaining kmalloc caches, with minimally sized
1415          *    head arrays.
1416          * 4) Replace the __init data head arrays for kmem_cache and the first
1417          *    kmalloc cache with kmalloc allocated arrays.
1418          * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1419          *    the other cache's with kmalloc allocated memory.
1420          * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1421          */
1422
1423         /* 1) create the kmem_cache */
1424
1425         /*
1426          * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1427          */
1428         create_boot_cache(kmem_cache, "kmem_cache",
1429                 offsetof(struct kmem_cache, node) +
1430                                   nr_node_ids * sizeof(struct kmem_cache_node *),
1431                                   SLAB_HWCACHE_ALIGN);
1432         list_add(&kmem_cache->list, &slab_caches);
1433         slab_state = PARTIAL;
1434
1435         /*
1436          * Initialize the caches that provide memory for the  kmem_cache_node
1437          * structures first.  Without this, further allocations will bug.
1438          */
1439         kmalloc_caches[INDEX_NODE] = create_kmalloc_cache("kmalloc-node",
1440                                 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1441         slab_state = PARTIAL_NODE;
1442         setup_kmalloc_cache_index_table();
1443
1444         slab_early_init = 0;
1445
1446         /* 5) Replace the bootstrap kmem_cache_node */
1447         {
1448                 int nid;
1449
1450                 for_each_online_node(nid) {
1451                         init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1452
1453                         init_list(kmalloc_caches[INDEX_NODE],
1454                                           &init_kmem_cache_node[SIZE_NODE + nid], nid);
1455                 }
1456         }
1457
1458         create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1459 }
1460
1461 void __init kmem_cache_init_late(void)
1462 {
1463         struct kmem_cache *cachep;
1464
1465         slab_state = UP;
1466
1467         /* 6) resize the head arrays to their final sizes */
1468         mutex_lock(&slab_mutex);
1469         list_for_each_entry(cachep, &slab_caches, list)
1470                 if (enable_cpucache(cachep, GFP_NOWAIT))
1471                         BUG();
1472         mutex_unlock(&slab_mutex);
1473
1474         /* Done! */
1475         slab_state = FULL;
1476
1477         /*
1478          * Register a cpu startup notifier callback that initializes
1479          * cpu_cache_get for all new cpus
1480          */
1481         register_cpu_notifier(&cpucache_notifier);
1482
1483 #ifdef CONFIG_NUMA
1484         /*
1485          * Register a memory hotplug callback that initializes and frees
1486          * node.
1487          */
1488         hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1489 #endif
1490
1491         /*
1492          * The reap timers are started later, with a module init call: That part
1493          * of the kernel is not yet operational.
1494          */
1495 }
1496
1497 static int __init cpucache_init(void)
1498 {
1499         int cpu;
1500
1501         /*
1502          * Register the timers that return unneeded pages to the page allocator
1503          */
1504         for_each_online_cpu(cpu)
1505                 start_cpu_timer(cpu);
1506
1507         /* Done! */
1508         slab_state = FULL;
1509         return 0;
1510 }
1511 __initcall(cpucache_init);
1512
1513 static noinline void
1514 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1515 {
1516 #if DEBUG
1517         struct kmem_cache_node *n;
1518         struct page *page;
1519         unsigned long flags;
1520         int node;
1521         static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1522                                       DEFAULT_RATELIMIT_BURST);
1523
1524         if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1525                 return;
1526
1527         printk(KERN_WARNING
1528                 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1529                 nodeid, gfpflags);
1530         printk(KERN_WARNING "  cache: %s, object size: %d, order: %d\n",
1531                 cachep->name, cachep->size, cachep->gfporder);
1532
1533         for_each_kmem_cache_node(cachep, node, n) {
1534                 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1535                 unsigned long active_slabs = 0, num_slabs = 0;
1536
1537                 spin_lock_irqsave(&n->list_lock, flags);
1538                 list_for_each_entry(page, &n->slabs_full, lru) {
1539                         active_objs += cachep->num;
1540                         active_slabs++;
1541                 }
1542                 list_for_each_entry(page, &n->slabs_partial, lru) {
1543                         active_objs += page->active;
1544                         active_slabs++;
1545                 }
1546                 list_for_each_entry(page, &n->slabs_free, lru)
1547                         num_slabs++;
1548
1549                 free_objects += n->free_objects;
1550                 spin_unlock_irqrestore(&n->list_lock, flags);
1551
1552                 num_slabs += active_slabs;
1553                 num_objs = num_slabs * cachep->num;
1554                 printk(KERN_WARNING
1555                         "  node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1556                         node, active_slabs, num_slabs, active_objs, num_objs,
1557                         free_objects);
1558         }
1559 #endif
1560 }
1561
1562 /*
1563  * Interface to system's page allocator. No need to hold the
1564  * kmem_cache_node ->list_lock.
1565  *
1566  * If we requested dmaable memory, we will get it. Even if we
1567  * did not request dmaable memory, we might get it, but that
1568  * would be relatively rare and ignorable.
1569  */
1570 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1571                                                                 int nodeid)
1572 {
1573         struct page *page;
1574         int nr_pages;
1575
1576         flags |= cachep->allocflags;
1577         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1578                 flags |= __GFP_RECLAIMABLE;
1579
1580         page = __alloc_pages_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1581         if (!page) {
1582                 slab_out_of_memory(cachep, flags, nodeid);
1583                 return NULL;
1584         }
1585
1586         if (memcg_charge_slab(page, flags, cachep->gfporder, cachep)) {
1587                 __free_pages(page, cachep->gfporder);
1588                 return NULL;
1589         }
1590
1591         /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1592         if (page_is_pfmemalloc(page))
1593                 pfmemalloc_active = true;
1594
1595         nr_pages = (1 << cachep->gfporder);
1596         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1597                 add_zone_page_state(page_zone(page),
1598                         NR_SLAB_RECLAIMABLE, nr_pages);
1599         else
1600                 add_zone_page_state(page_zone(page),
1601                         NR_SLAB_UNRECLAIMABLE, nr_pages);
1602         __SetPageSlab(page);
1603         if (page_is_pfmemalloc(page))
1604                 SetPageSlabPfmemalloc(page);
1605
1606         if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1607                 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1608
1609                 if (cachep->ctor)
1610                         kmemcheck_mark_uninitialized_pages(page, nr_pages);
1611                 else
1612                         kmemcheck_mark_unallocated_pages(page, nr_pages);
1613         }
1614
1615         return page;
1616 }
1617
1618 /*
1619  * Interface to system's page release.
1620  */
1621 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1622 {
1623         const unsigned long nr_freed = (1 << cachep->gfporder);
1624
1625         kmemcheck_free_shadow(page, cachep->gfporder);
1626
1627         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1628                 sub_zone_page_state(page_zone(page),
1629                                 NR_SLAB_RECLAIMABLE, nr_freed);
1630         else
1631                 sub_zone_page_state(page_zone(page),
1632                                 NR_SLAB_UNRECLAIMABLE, nr_freed);
1633
1634         BUG_ON(!PageSlab(page));
1635         __ClearPageSlabPfmemalloc(page);
1636         __ClearPageSlab(page);
1637         page_mapcount_reset(page);
1638         page->mapping = NULL;
1639
1640         if (current->reclaim_state)
1641                 current->reclaim_state->reclaimed_slab += nr_freed;
1642         __free_kmem_pages(page, cachep->gfporder);
1643 }
1644
1645 static void kmem_rcu_free(struct rcu_head *head)
1646 {
1647         struct kmem_cache *cachep;
1648         struct page *page;
1649
1650         page = container_of(head, struct page, rcu_head);
1651         cachep = page->slab_cache;
1652
1653         kmem_freepages(cachep, page);
1654 }
1655
1656 #if DEBUG
1657 static bool is_debug_pagealloc_cache(struct kmem_cache *cachep)
1658 {
1659         if (debug_pagealloc_enabled() && OFF_SLAB(cachep) &&
1660                 (cachep->size % PAGE_SIZE) == 0)
1661                 return true;
1662
1663         return false;
1664 }
1665
1666 #ifdef CONFIG_DEBUG_PAGEALLOC
1667 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1668                             unsigned long caller)
1669 {
1670         int size = cachep->object_size;
1671
1672         addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1673
1674         if (size < 5 * sizeof(unsigned long))
1675                 return;
1676
1677         *addr++ = 0x12345678;
1678         *addr++ = caller;
1679         *addr++ = smp_processor_id();
1680         size -= 3 * sizeof(unsigned long);
1681         {
1682                 unsigned long *sptr = &caller;
1683                 unsigned long svalue;
1684
1685                 while (!kstack_end(sptr)) {
1686                         svalue = *sptr++;
1687                         if (kernel_text_address(svalue)) {
1688                                 *addr++ = svalue;
1689                                 size -= sizeof(unsigned long);
1690                                 if (size <= sizeof(unsigned long))
1691                                         break;
1692                         }
1693                 }
1694
1695         }
1696         *addr++ = 0x87654321;
1697 }
1698
1699 static void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1700                                 int map, unsigned long caller)
1701 {
1702         if (!is_debug_pagealloc_cache(cachep))
1703                 return;
1704
1705         if (caller)
1706                 store_stackinfo(cachep, objp, caller);
1707
1708         kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map);
1709 }
1710
1711 #else
1712 static inline void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1713                                 int map, unsigned long caller) {}
1714
1715 #endif
1716
1717 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1718 {
1719         int size = cachep->object_size;
1720         addr = &((char *)addr)[obj_offset(cachep)];
1721
1722         memset(addr, val, size);
1723         *(unsigned char *)(addr + size - 1) = POISON_END;
1724 }
1725
1726 static void dump_line(char *data, int offset, int limit)
1727 {
1728         int i;
1729         unsigned char error = 0;
1730         int bad_count = 0;
1731
1732         printk(KERN_ERR "%03x: ", offset);
1733         for (i = 0; i < limit; i++) {
1734                 if (data[offset + i] != POISON_FREE) {
1735                         error = data[offset + i];
1736                         bad_count++;
1737                 }
1738         }
1739         print_hex_dump(KERN_CONT, "", 0, 16, 1,
1740                         &data[offset], limit, 1);
1741
1742         if (bad_count == 1) {
1743                 error ^= POISON_FREE;
1744                 if (!(error & (error - 1))) {
1745                         printk(KERN_ERR "Single bit error detected. Probably "
1746                                         "bad RAM.\n");
1747 #ifdef CONFIG_X86
1748                         printk(KERN_ERR "Run memtest86+ or a similar memory "
1749                                         "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 "
1867                                            "was overwritten");
1868                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1869                                 slab_error(cachep, "end of a freed object "
1870                                            "was overwritten");
1871                 }
1872         }
1873 }
1874 #else
1875 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1876                                                 struct page *page)
1877 {
1878 }
1879 #endif
1880
1881 /**
1882  * slab_destroy - destroy and release all objects in a slab
1883  * @cachep: cache pointer being destroyed
1884  * @page: page pointer being destroyed
1885  *
1886  * Destroy all the objs in a slab page, and release the mem back to the system.
1887  * Before calling the slab page must have been unlinked from the cache. The
1888  * kmem_cache_node ->list_lock is not held/needed.
1889  */
1890 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
1891 {
1892         void *freelist;
1893
1894         freelist = page->freelist;
1895         slab_destroy_debugcheck(cachep, page);
1896         if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1897                 call_rcu(&page->rcu_head, kmem_rcu_free);
1898         else
1899                 kmem_freepages(cachep, page);
1900
1901         /*
1902          * From now on, we don't use freelist
1903          * although actual page can be freed in rcu context
1904          */
1905         if (OFF_SLAB(cachep))
1906                 kmem_cache_free(cachep->freelist_cache, freelist);
1907 }
1908
1909 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
1910 {
1911         struct page *page, *n;
1912
1913         list_for_each_entry_safe(page, n, list, lru) {
1914                 list_del(&page->lru);
1915                 slab_destroy(cachep, page);
1916         }
1917 }
1918
1919 /**
1920  * calculate_slab_order - calculate size (page order) of slabs
1921  * @cachep: pointer to the cache that is being created
1922  * @size: size of objects to be created in this cache.
1923  * @align: required alignment for the objects.
1924  * @flags: slab allocation flags
1925  *
1926  * Also calculates the number of objects per slab.
1927  *
1928  * This could be made much more intelligent.  For now, try to avoid using
1929  * high order pages for slabs.  When the gfp() functions are more friendly
1930  * towards high-order requests, this should be changed.
1931  */
1932 static size_t calculate_slab_order(struct kmem_cache *cachep,
1933                         size_t size, size_t align, unsigned long flags)
1934 {
1935         unsigned long offslab_limit;
1936         size_t left_over = 0;
1937         int gfporder;
1938
1939         for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
1940                 unsigned int num;
1941                 size_t remainder;
1942
1943                 cache_estimate(gfporder, size, align, flags, &remainder, &num);
1944                 if (!num)
1945                         continue;
1946
1947                 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
1948                 if (num > SLAB_OBJ_MAX_NUM)
1949                         break;
1950
1951                 if (flags & CFLGS_OFF_SLAB) {
1952                         /*
1953                          * Max number of objs-per-slab for caches which
1954                          * use off-slab slabs. Needed to avoid a possible
1955                          * looping condition in cache_grow().
1956                          */
1957                         offslab_limit = size;
1958                         offslab_limit /= sizeof(freelist_idx_t);
1959
1960                         if (num > offslab_limit)
1961                                 break;
1962                 }
1963
1964                 /* Found something acceptable - save it away */
1965                 cachep->num = num;
1966                 cachep->gfporder = gfporder;
1967                 left_over = remainder;
1968
1969                 /*
1970                  * A VFS-reclaimable slab tends to have most allocations
1971                  * as GFP_NOFS and we really don't want to have to be allocating
1972                  * higher-order pages when we are unable to shrink dcache.
1973                  */
1974                 if (flags & SLAB_RECLAIM_ACCOUNT)
1975                         break;
1976
1977                 /*
1978                  * Large number of objects is good, but very large slabs are
1979                  * currently bad for the gfp()s.
1980                  */
1981                 if (gfporder >= slab_max_order)
1982                         break;
1983
1984                 /*
1985                  * Acceptable internal fragmentation?
1986                  */
1987                 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1988                         break;
1989         }
1990         return left_over;
1991 }
1992
1993 static struct array_cache __percpu *alloc_kmem_cache_cpus(
1994                 struct kmem_cache *cachep, int entries, int batchcount)
1995 {
1996         int cpu;
1997         size_t size;
1998         struct array_cache __percpu *cpu_cache;
1999
2000         size = sizeof(void *) * entries + sizeof(struct array_cache);
2001         cpu_cache = __alloc_percpu(size, sizeof(void *));
2002
2003         if (!cpu_cache)
2004                 return NULL;
2005
2006         for_each_possible_cpu(cpu) {
2007                 init_arraycache(per_cpu_ptr(cpu_cache, cpu),
2008                                 entries, batchcount);
2009         }
2010
2011         return cpu_cache;
2012 }
2013
2014 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2015 {
2016         if (slab_state >= FULL)
2017                 return enable_cpucache(cachep, gfp);
2018
2019         cachep->cpu_cache = alloc_kmem_cache_cpus(cachep, 1, 1);
2020         if (!cachep->cpu_cache)
2021                 return 1;
2022
2023         if (slab_state == DOWN) {
2024                 /* Creation of first cache (kmem_cache). */
2025                 set_up_node(kmem_cache, CACHE_CACHE);
2026         } else if (slab_state == PARTIAL) {
2027                 /* For kmem_cache_node */
2028                 set_up_node(cachep, SIZE_NODE);
2029         } else {
2030                 int node;
2031
2032                 for_each_online_node(node) {
2033                         cachep->node[node] = kmalloc_node(
2034                                 sizeof(struct kmem_cache_node), gfp, node);
2035                         BUG_ON(!cachep->node[node]);
2036                         kmem_cache_node_init(cachep->node[node]);
2037                 }
2038         }
2039
2040         cachep->node[numa_mem_id()]->next_reap =
2041                         jiffies + REAPTIMEOUT_NODE +
2042                         ((unsigned long)cachep) % REAPTIMEOUT_NODE;
2043
2044         cpu_cache_get(cachep)->avail = 0;
2045         cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2046         cpu_cache_get(cachep)->batchcount = 1;
2047         cpu_cache_get(cachep)->touched = 0;
2048         cachep->batchcount = 1;
2049         cachep->limit = BOOT_CPUCACHE_ENTRIES;
2050         return 0;
2051 }
2052
2053 unsigned long kmem_cache_flags(unsigned long object_size,
2054         unsigned long flags, const char *name,
2055         void (*ctor)(void *))
2056 {
2057         return flags;
2058 }
2059
2060 struct kmem_cache *
2061 __kmem_cache_alias(const char *name, size_t size, size_t align,
2062                    unsigned long flags, void (*ctor)(void *))
2063 {
2064         struct kmem_cache *cachep;
2065
2066         cachep = find_mergeable(size, align, flags, name, ctor);
2067         if (cachep) {
2068                 cachep->refcount++;
2069
2070                 /*
2071                  * Adjust the object sizes so that we clear
2072                  * the complete object on kzalloc.
2073                  */
2074                 cachep->object_size = max_t(int, cachep->object_size, size);
2075         }
2076         return cachep;
2077 }
2078
2079 /**
2080  * __kmem_cache_create - Create a cache.
2081  * @cachep: cache management descriptor
2082  * @flags: SLAB flags
2083  *
2084  * Returns a ptr to the cache on success, NULL on failure.
2085  * Cannot be called within a int, but can be interrupted.
2086  * The @ctor is run when new pages are allocated by the cache.
2087  *
2088  * The flags are
2089  *
2090  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2091  * to catch references to uninitialised memory.
2092  *
2093  * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2094  * for buffer overruns.
2095  *
2096  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2097  * cacheline.  This can be beneficial if you're counting cycles as closely
2098  * as davem.
2099  */
2100 int
2101 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2102 {
2103         size_t left_over, freelist_size;
2104         size_t ralign = BYTES_PER_WORD;
2105         gfp_t gfp;
2106         int err;
2107         size_t size = cachep->size;
2108
2109 #if DEBUG
2110 #if FORCED_DEBUG
2111         /*
2112          * Enable redzoning and last user accounting, except for caches with
2113          * large objects, if the increased size would increase the object size
2114          * above the next power of two: caches with object sizes just above a
2115          * power of two have a significant amount of internal fragmentation.
2116          */
2117         if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2118                                                 2 * sizeof(unsigned long long)))
2119                 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2120         if (!(flags & SLAB_DESTROY_BY_RCU))
2121                 flags |= SLAB_POISON;
2122 #endif
2123         if (flags & SLAB_DESTROY_BY_RCU)
2124                 BUG_ON(flags & SLAB_POISON);
2125 #endif
2126
2127         /*
2128          * Check that size is in terms of words.  This is needed to avoid
2129          * unaligned accesses for some archs when redzoning is used, and makes
2130          * sure any on-slab bufctl's are also correctly aligned.
2131          */
2132         if (size & (BYTES_PER_WORD - 1)) {
2133                 size += (BYTES_PER_WORD - 1);
2134                 size &= ~(BYTES_PER_WORD - 1);
2135         }
2136
2137         if (flags & SLAB_RED_ZONE) {
2138                 ralign = REDZONE_ALIGN;
2139                 /* If redzoning, ensure that the second redzone is suitably
2140                  * aligned, by adjusting the object size accordingly. */
2141                 size += REDZONE_ALIGN - 1;
2142                 size &= ~(REDZONE_ALIGN - 1);
2143         }
2144
2145         /* 3) caller mandated alignment */
2146         if (ralign < cachep->align) {
2147                 ralign = cachep->align;
2148         }
2149         /* disable debug if necessary */
2150         if (ralign > __alignof__(unsigned long long))
2151                 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2152         /*
2153          * 4) Store it.
2154          */
2155         cachep->align = ralign;
2156
2157         if (slab_is_available())
2158                 gfp = GFP_KERNEL;
2159         else
2160                 gfp = GFP_NOWAIT;
2161
2162 #if DEBUG
2163
2164         /*
2165          * Both debugging options require word-alignment which is calculated
2166          * into align above.
2167          */
2168         if (flags & SLAB_RED_ZONE) {
2169                 /* add space for red zone words */
2170                 cachep->obj_offset += sizeof(unsigned long long);
2171                 size += 2 * sizeof(unsigned long long);
2172         }
2173         if (flags & SLAB_STORE_USER) {
2174                 /* user store requires one word storage behind the end of
2175                  * the real object. But if the second red zone needs to be
2176                  * aligned to 64 bits, we must allow that much space.
2177                  */
2178                 if (flags & SLAB_RED_ZONE)
2179                         size += REDZONE_ALIGN;
2180                 else
2181                         size += BYTES_PER_WORD;
2182         }
2183 #endif
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
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                         cachep->ctor(objp + obj_offset(cachep));
2512
2513                 if (cachep->flags & SLAB_RED_ZONE) {
2514                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2515                                 slab_error(cachep, "constructor overwrote the"
2516                                            " end of an object");
2517                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2518                                 slab_error(cachep, "constructor overwrote the"
2519                                            " start of an object");
2520                 }
2521                 /* need to poison the objs? */
2522                 if (cachep->flags & SLAB_POISON) {
2523                         poison_obj(cachep, objp, POISON_FREE);
2524                         slab_kernel_map(cachep, objp, 0, 0);
2525                 }
2526         }
2527 #endif
2528 }
2529
2530 static void cache_init_objs(struct kmem_cache *cachep,
2531                             struct page *page)
2532 {
2533         int i;
2534
2535         cache_init_objs_debug(cachep, page);
2536
2537         for (i = 0; i < cachep->num; i++) {
2538                 /* constructor could break poison info */
2539                 if (DEBUG == 0 && cachep->ctor)
2540                         cachep->ctor(index_to_obj(cachep, page, i));
2541
2542                 set_free_obj(page, i, i);
2543         }
2544 }
2545
2546 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2547 {
2548         if (CONFIG_ZONE_DMA_FLAG) {
2549                 if (flags & GFP_DMA)
2550                         BUG_ON(!(cachep->allocflags & GFP_DMA));
2551                 else
2552                         BUG_ON(cachep->allocflags & GFP_DMA);
2553         }
2554 }
2555
2556 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page,
2557                                 int nodeid)
2558 {
2559         void *objp;
2560
2561         objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2562         page->active++;
2563 #if DEBUG
2564         WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2565 #endif
2566
2567 #if DEBUG
2568         if (cachep->flags & SLAB_STORE_USER)
2569                 set_store_user_dirty(cachep);
2570 #endif
2571
2572         return objp;
2573 }
2574
2575 static void slab_put_obj(struct kmem_cache *cachep, struct page *page,
2576                                 void *objp, int nodeid)
2577 {
2578         unsigned int objnr = obj_to_index(cachep, page, objp);
2579 #if DEBUG
2580         unsigned int i;
2581
2582         /* Verify that the slab belongs to the intended node */
2583         WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2584
2585         /* Verify double free bug */
2586         for (i = page->active; i < cachep->num; i++) {
2587                 if (get_free_obj(page, i) == objnr) {
2588                         printk(KERN_ERR "slab: double free detected in cache "
2589                                         "'%s', objp %p\n", cachep->name, objp);
2590                         BUG();
2591                 }
2592         }
2593 #endif
2594         page->active--;
2595         set_free_obj(page, page->active, objnr);
2596 }
2597
2598 /*
2599  * Map pages beginning at addr to the given cache and slab. This is required
2600  * for the slab allocator to be able to lookup the cache and slab of a
2601  * virtual address for kfree, ksize, and slab debugging.
2602  */
2603 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2604                            void *freelist)
2605 {
2606         page->slab_cache = cache;
2607         page->freelist = freelist;
2608 }
2609
2610 /*
2611  * Grow (by 1) the number of slabs within a cache.  This is called by
2612  * kmem_cache_alloc() when there are no active objs left in a cache.
2613  */
2614 static int cache_grow(struct kmem_cache *cachep,
2615                 gfp_t flags, int nodeid, struct page *page)
2616 {
2617         void *freelist;
2618         size_t offset;
2619         gfp_t local_flags;
2620         struct kmem_cache_node *n;
2621
2622         /*
2623          * Be lazy and only check for valid flags here,  keeping it out of the
2624          * critical path in kmem_cache_alloc().
2625          */
2626         if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
2627                 pr_emerg("gfp: %u\n", flags & GFP_SLAB_BUG_MASK);
2628                 BUG();
2629         }
2630         local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2631
2632         /* Take the node list lock to change the colour_next on this node */
2633         check_irq_off();
2634         n = get_node(cachep, nodeid);
2635         spin_lock(&n->list_lock);
2636
2637         /* Get colour for the slab, and cal the next value. */
2638         offset = n->colour_next;
2639         n->colour_next++;
2640         if (n->colour_next >= cachep->colour)
2641                 n->colour_next = 0;
2642         spin_unlock(&n->list_lock);
2643
2644         offset *= cachep->colour_off;
2645
2646         if (gfpflags_allow_blocking(local_flags))
2647                 local_irq_enable();
2648
2649         /*
2650          * The test for missing atomic flag is performed here, rather than
2651          * the more obvious place, simply to reduce the critical path length
2652          * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2653          * will eventually be caught here (where it matters).
2654          */
2655         kmem_flagcheck(cachep, flags);
2656
2657         /*
2658          * Get mem for the objs.  Attempt to allocate a physical page from
2659          * 'nodeid'.
2660          */
2661         if (!page)
2662                 page = kmem_getpages(cachep, local_flags, nodeid);
2663         if (!page)
2664                 goto failed;
2665
2666         /* Get slab management. */
2667         freelist = alloc_slabmgmt(cachep, page, offset,
2668                         local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2669         if (!freelist)
2670                 goto opps1;
2671
2672         slab_map_pages(cachep, page, freelist);
2673
2674         cache_init_objs(cachep, page);
2675
2676         if (gfpflags_allow_blocking(local_flags))
2677                 local_irq_disable();
2678         check_irq_off();
2679         spin_lock(&n->list_lock);
2680
2681         /* Make slab active. */
2682         list_add_tail(&page->lru, &(n->slabs_free));
2683         STATS_INC_GROWN(cachep);
2684         n->free_objects += cachep->num;
2685         spin_unlock(&n->list_lock);
2686         return 1;
2687 opps1:
2688         kmem_freepages(cachep, page);
2689 failed:
2690         if (gfpflags_allow_blocking(local_flags))
2691                 local_irq_disable();
2692         return 0;
2693 }
2694
2695 #if DEBUG
2696
2697 /*
2698  * Perform extra freeing checks:
2699  * - detect bad pointers.
2700  * - POISON/RED_ZONE checking
2701  */
2702 static void kfree_debugcheck(const void *objp)
2703 {
2704         if (!virt_addr_valid(objp)) {
2705                 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2706                        (unsigned long)objp);
2707                 BUG();
2708         }
2709 }
2710
2711 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2712 {
2713         unsigned long long redzone1, redzone2;
2714
2715         redzone1 = *dbg_redzone1(cache, obj);
2716         redzone2 = *dbg_redzone2(cache, obj);
2717
2718         /*
2719          * Redzone is ok.
2720          */
2721         if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2722                 return;
2723
2724         if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2725                 slab_error(cache, "double free detected");
2726         else
2727                 slab_error(cache, "memory outside object was overwritten");
2728
2729         printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2730                         obj, redzone1, redzone2);
2731 }
2732
2733 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2734                                    unsigned long caller)
2735 {
2736         unsigned int objnr;
2737         struct page *page;
2738
2739         BUG_ON(virt_to_cache(objp) != cachep);
2740
2741         objp -= obj_offset(cachep);
2742         kfree_debugcheck(objp);
2743         page = virt_to_head_page(objp);
2744
2745         if (cachep->flags & SLAB_RED_ZONE) {
2746                 verify_redzone_free(cachep, objp);
2747                 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2748                 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2749         }
2750         if (cachep->flags & SLAB_STORE_USER) {
2751                 set_store_user_dirty(cachep);
2752                 *dbg_userword(cachep, objp) = (void *)caller;
2753         }
2754
2755         objnr = obj_to_index(cachep, page, objp);
2756
2757         BUG_ON(objnr >= cachep->num);
2758         BUG_ON(objp != index_to_obj(cachep, page, objnr));
2759
2760         if (cachep->flags & SLAB_POISON) {
2761                 poison_obj(cachep, objp, POISON_FREE);
2762                 slab_kernel_map(cachep, objp, 0, caller);
2763         }
2764         return objp;
2765 }
2766
2767 #else
2768 #define kfree_debugcheck(x) do { } while(0)
2769 #define cache_free_debugcheck(x,objp,z) (objp)
2770 #endif
2771
2772 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
2773                                                         bool force_refill)
2774 {
2775         int batchcount;
2776         struct kmem_cache_node *n;
2777         struct array_cache *ac;
2778         int node;
2779
2780         check_irq_off();
2781         node = numa_mem_id();
2782         if (unlikely(force_refill))
2783                 goto force_grow;
2784 retry:
2785         ac = cpu_cache_get(cachep);
2786         batchcount = ac->batchcount;
2787         if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2788                 /*
2789                  * If there was little recent activity on this cache, then
2790                  * perform only a partial refill.  Otherwise we could generate
2791                  * refill bouncing.
2792                  */
2793                 batchcount = BATCHREFILL_LIMIT;
2794         }
2795         n = get_node(cachep, node);
2796
2797         BUG_ON(ac->avail > 0 || !n);
2798         spin_lock(&n->list_lock);
2799
2800         /* See if we can refill from the shared array */
2801         if (n->shared && transfer_objects(ac, n->shared, batchcount)) {
2802                 n->shared->touched = 1;
2803                 goto alloc_done;
2804         }
2805
2806         while (batchcount > 0) {
2807                 struct list_head *entry;
2808                 struct page *page;
2809                 /* Get slab alloc is to come from. */
2810                 entry = n->slabs_partial.next;
2811                 if (entry == &n->slabs_partial) {
2812                         n->free_touched = 1;
2813                         entry = n->slabs_free.next;
2814                         if (entry == &n->slabs_free)
2815                                 goto must_grow;
2816                 }
2817
2818                 page = list_entry(entry, struct page, lru);
2819                 check_spinlock_acquired(cachep);
2820
2821                 /*
2822                  * The slab was either on partial or free list so
2823                  * there must be at least one object available for
2824                  * allocation.
2825                  */
2826                 BUG_ON(page->active >= cachep->num);
2827
2828                 while (page->active < cachep->num && batchcount--) {
2829                         STATS_INC_ALLOCED(cachep);
2830                         STATS_INC_ACTIVE(cachep);
2831                         STATS_SET_HIGH(cachep);
2832
2833                         ac_put_obj(cachep, ac, slab_get_obj(cachep, page,
2834                                                                         node));
2835                 }
2836
2837                 /* move slabp to correct slabp list: */
2838                 list_del(&page->lru);
2839                 if (page->active == cachep->num)
2840                         list_add(&page->lru, &n->slabs_full);
2841                 else
2842                         list_add(&page->lru, &n->slabs_partial);
2843         }
2844
2845 must_grow:
2846         n->free_objects -= ac->avail;
2847 alloc_done:
2848         spin_unlock(&n->list_lock);
2849
2850         if (unlikely(!ac->avail)) {
2851                 int x;
2852 force_grow:
2853                 x = cache_grow(cachep, gfp_exact_node(flags), node, NULL);
2854
2855                 /* cache_grow can reenable interrupts, then ac could change. */
2856                 ac = cpu_cache_get(cachep);
2857                 node = numa_mem_id();
2858
2859                 /* no objects in sight? abort */
2860                 if (!x && (ac->avail == 0 || force_refill))
2861                         return NULL;
2862
2863                 if (!ac->avail)         /* objects refilled by interrupt? */
2864                         goto retry;
2865         }
2866         ac->touched = 1;
2867
2868         return ac_get_obj(cachep, ac, flags, force_refill);
2869 }
2870
2871 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2872                                                 gfp_t flags)
2873 {
2874         might_sleep_if(gfpflags_allow_blocking(flags));
2875 #if DEBUG
2876         kmem_flagcheck(cachep, flags);
2877 #endif
2878 }
2879
2880 #if DEBUG
2881 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
2882                                 gfp_t flags, void *objp, unsigned long caller)
2883 {
2884         if (!objp)
2885                 return objp;
2886         if (cachep->flags & SLAB_POISON) {
2887                 check_poison_obj(cachep, objp);
2888                 slab_kernel_map(cachep, objp, 1, 0);
2889                 poison_obj(cachep, objp, POISON_INUSE);
2890         }
2891         if (cachep->flags & SLAB_STORE_USER)
2892                 *dbg_userword(cachep, objp) = (void *)caller;
2893
2894         if (cachep->flags & SLAB_RED_ZONE) {
2895                 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
2896                                 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2897                         slab_error(cachep, "double free, or memory outside"
2898                                                 " object was overwritten");
2899                         printk(KERN_ERR
2900                                 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
2901                                 objp, *dbg_redzone1(cachep, objp),
2902                                 *dbg_redzone2(cachep, objp));
2903                 }
2904                 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2905                 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2906         }
2907
2908         objp += obj_offset(cachep);
2909         if (cachep->ctor && cachep->flags & SLAB_POISON)
2910                 cachep->ctor(objp);
2911         if (ARCH_SLAB_MINALIGN &&
2912             ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
2913                 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
2914                        objp, (int)ARCH_SLAB_MINALIGN);
2915         }
2916         return objp;
2917 }
2918 #else
2919 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2920 #endif
2921
2922 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
2923 {
2924         if (unlikely(cachep == kmem_cache))
2925                 return false;
2926
2927         return should_failslab(cachep->object_size, flags, cachep->flags);
2928 }
2929
2930 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
2931 {
2932         void *objp;
2933         struct array_cache *ac;
2934         bool force_refill = false;
2935
2936         check_irq_off();
2937
2938         ac = cpu_cache_get(cachep);
2939         if (likely(ac->avail)) {
2940                 ac->touched = 1;
2941                 objp = ac_get_obj(cachep, ac, flags, false);
2942
2943                 /*
2944                  * Allow for the possibility all avail objects are not allowed
2945                  * by the current flags
2946                  */
2947                 if (objp) {
2948                         STATS_INC_ALLOCHIT(cachep);
2949                         goto out;
2950                 }
2951                 force_refill = true;
2952         }
2953
2954         STATS_INC_ALLOCMISS(cachep);
2955         objp = cache_alloc_refill(cachep, flags, force_refill);
2956         /*
2957          * the 'ac' may be updated by cache_alloc_refill(),
2958          * and kmemleak_erase() requires its correct value.
2959          */
2960         ac = cpu_cache_get(cachep);
2961
2962 out:
2963         /*
2964          * To avoid a false negative, if an object that is in one of the
2965          * per-CPU caches is leaked, we need to make sure kmemleak doesn't
2966          * treat the array pointers as a reference to the object.
2967          */
2968         if (objp)
2969                 kmemleak_erase(&ac->entry[ac->avail]);
2970         return objp;
2971 }
2972
2973 #ifdef CONFIG_NUMA
2974 /*
2975  * Try allocating on another node if PFA_SPREAD_SLAB is a mempolicy is set.
2976  *
2977  * If we are in_interrupt, then process context, including cpusets and
2978  * mempolicy, may not apply and should not be used for allocation policy.
2979  */
2980 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
2981 {
2982         int nid_alloc, nid_here;
2983
2984         if (in_interrupt() || (flags & __GFP_THISNODE))
2985                 return NULL;
2986         nid_alloc = nid_here = numa_mem_id();
2987         if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
2988                 nid_alloc = cpuset_slab_spread_node();
2989         else if (current->mempolicy)
2990                 nid_alloc = mempolicy_slab_node();
2991         if (nid_alloc != nid_here)
2992                 return ____cache_alloc_node(cachep, flags, nid_alloc);
2993         return NULL;
2994 }
2995
2996 /*
2997  * Fallback function if there was no memory available and no objects on a
2998  * certain node and fall back is permitted. First we scan all the
2999  * available node for available objects. If that fails then we
3000  * perform an allocation without specifying a node. This allows the page
3001  * allocator to do its reclaim / fallback magic. We then insert the
3002  * slab into the proper nodelist and then allocate from it.
3003  */
3004 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3005 {
3006         struct zonelist *zonelist;
3007         gfp_t local_flags;
3008         struct zoneref *z;
3009         struct zone *zone;
3010         enum zone_type high_zoneidx = gfp_zone(flags);
3011         void *obj = NULL;
3012         int nid;
3013         unsigned int cpuset_mems_cookie;
3014
3015         if (flags & __GFP_THISNODE)
3016                 return NULL;
3017
3018         local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3019
3020 retry_cpuset:
3021         cpuset_mems_cookie = read_mems_allowed_begin();
3022         zonelist = node_zonelist(mempolicy_slab_node(), flags);
3023
3024 retry:
3025         /*
3026          * Look through allowed nodes for objects available
3027          * from existing per node queues.
3028          */
3029         for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3030                 nid = zone_to_nid(zone);
3031
3032                 if (cpuset_zone_allowed(zone, flags) &&
3033                         get_node(cache, nid) &&
3034                         get_node(cache, nid)->free_objects) {
3035                                 obj = ____cache_alloc_node(cache,
3036                                         gfp_exact_node(flags), nid);
3037                                 if (obj)
3038                                         break;
3039                 }
3040         }
3041
3042         if (!obj) {
3043                 /*
3044                  * This allocation will be performed within the constraints
3045                  * of the current cpuset / memory policy requirements.
3046                  * We may trigger various forms of reclaim on the allowed
3047                  * set and go into memory reserves if necessary.
3048                  */
3049                 struct page *page;
3050
3051                 if (gfpflags_allow_blocking(local_flags))
3052                         local_irq_enable();
3053                 kmem_flagcheck(cache, flags);
3054                 page = kmem_getpages(cache, local_flags, numa_mem_id());
3055                 if (gfpflags_allow_blocking(local_flags))
3056                         local_irq_disable();
3057                 if (page) {
3058                         /*
3059                          * Insert into the appropriate per node queues
3060                          */
3061                         nid = page_to_nid(page);
3062                         if (cache_grow(cache, flags, nid, page)) {
3063                                 obj = ____cache_alloc_node(cache,
3064                                         gfp_exact_node(flags), nid);
3065                                 if (!obj)
3066                                         /*
3067                                          * Another processor may allocate the
3068                                          * objects in the slab since we are
3069                                          * not holding any locks.
3070                                          */
3071                                         goto retry;
3072                         } else {
3073                                 /* cache_grow already freed obj */
3074                                 obj = NULL;
3075                         }
3076                 }
3077         }
3078
3079         if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3080                 goto retry_cpuset;
3081         return obj;
3082 }
3083
3084 /*
3085  * A interface to enable slab creation on nodeid
3086  */
3087 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3088                                 int nodeid)
3089 {
3090         struct list_head *entry;
3091         struct page *page;
3092         struct kmem_cache_node *n;
3093         void *obj;
3094         int x;
3095
3096         VM_BUG_ON(nodeid < 0 || nodeid >= MAX_NUMNODES);
3097         n = get_node(cachep, nodeid);
3098         BUG_ON(!n);
3099
3100 retry:
3101         check_irq_off();
3102         spin_lock(&n->list_lock);
3103         entry = n->slabs_partial.next;
3104         if (entry == &n->slabs_partial) {
3105                 n->free_touched = 1;
3106                 entry = n->slabs_free.next;
3107                 if (entry == &n->slabs_free)
3108                         goto must_grow;
3109         }
3110
3111         page = list_entry(entry, struct page, lru);
3112         check_spinlock_acquired_node(cachep, nodeid);
3113
3114         STATS_INC_NODEALLOCS(cachep);
3115         STATS_INC_ACTIVE(cachep);
3116         STATS_SET_HIGH(cachep);
3117
3118         BUG_ON(page->active == cachep->num);
3119
3120         obj = slab_get_obj(cachep, page, nodeid);
3121         n->free_objects--;
3122         /* move slabp to correct slabp list: */
3123         list_del(&page->lru);
3124
3125         if (page->active == cachep->num)
3126                 list_add(&page->lru, &n->slabs_full);
3127         else
3128                 list_add(&page->lru, &n->slabs_partial);
3129
3130         spin_unlock(&n->list_lock);
3131         goto done;
3132
3133 must_grow:
3134         spin_unlock(&n->list_lock);
3135         x = cache_grow(cachep, gfp_exact_node(flags), nodeid, NULL);
3136         if (x)
3137                 goto retry;
3138
3139         return fallback_alloc(cachep, flags);
3140
3141 done:
3142         return obj;
3143 }
3144
3145 static __always_inline void *
3146 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3147                    unsigned long caller)
3148 {
3149         unsigned long save_flags;
3150         void *ptr;
3151         int slab_node = numa_mem_id();
3152
3153         flags &= gfp_allowed_mask;
3154
3155         lockdep_trace_alloc(flags);
3156
3157         if (slab_should_failslab(cachep, flags))
3158                 return NULL;
3159
3160         cachep = memcg_kmem_get_cache(cachep, flags);
3161
3162         cache_alloc_debugcheck_before(cachep, flags);
3163         local_irq_save(save_flags);
3164
3165         if (nodeid == NUMA_NO_NODE)
3166                 nodeid = slab_node;
3167
3168         if (unlikely(!get_node(cachep, nodeid))) {
3169                 /* Node not bootstrapped yet */
3170                 ptr = fallback_alloc(cachep, flags);
3171                 goto out;
3172         }
3173
3174         if (nodeid == slab_node) {
3175                 /*
3176                  * Use the locally cached objects if possible.
3177                  * However ____cache_alloc does not allow fallback
3178                  * to other nodes. It may fail while we still have
3179                  * objects on other nodes available.
3180                  */
3181                 ptr = ____cache_alloc(cachep, flags);
3182                 if (ptr)
3183                         goto out;
3184         }
3185         /* ___cache_alloc_node can fall back to other nodes */
3186         ptr = ____cache_alloc_node(cachep, flags, nodeid);
3187   out:
3188         local_irq_restore(save_flags);
3189         ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3190         kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3191                                  flags);
3192
3193         if (likely(ptr)) {
3194                 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3195                 if (unlikely(flags & __GFP_ZERO))
3196                         memset(ptr, 0, cachep->object_size);
3197         }
3198
3199         memcg_kmem_put_cache(cachep);
3200         return ptr;
3201 }
3202
3203 static __always_inline void *
3204 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3205 {
3206         void *objp;
3207
3208         if (current->mempolicy || cpuset_do_slab_mem_spread()) {
3209                 objp = alternate_node_alloc(cache, flags);
3210                 if (objp)
3211                         goto out;
3212         }
3213         objp = ____cache_alloc(cache, flags);
3214
3215         /*
3216          * We may just have run out of memory on the local node.
3217          * ____cache_alloc_node() knows how to locate memory on other nodes
3218          */
3219         if (!objp)
3220                 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3221
3222   out:
3223         return objp;
3224 }
3225 #else
3226
3227 static __always_inline void *
3228 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3229 {
3230         return ____cache_alloc(cachep, flags);
3231 }
3232
3233 #endif /* CONFIG_NUMA */
3234
3235 static __always_inline void *
3236 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3237 {
3238         unsigned long save_flags;
3239         void *objp;
3240
3241         flags &= gfp_allowed_mask;
3242
3243         lockdep_trace_alloc(flags);
3244
3245         if (slab_should_failslab(cachep, flags))
3246                 return NULL;
3247
3248         cachep = memcg_kmem_get_cache(cachep, flags);
3249
3250         cache_alloc_debugcheck_before(cachep, flags);
3251         local_irq_save(save_flags);
3252         objp = __do_cache_alloc(cachep, flags);
3253         local_irq_restore(save_flags);
3254         objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3255         kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3256                                  flags);
3257         prefetchw(objp);
3258
3259         if (likely(objp)) {
3260                 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3261                 if (unlikely(flags & __GFP_ZERO))
3262                         memset(objp, 0, cachep->object_size);
3263         }
3264
3265         memcg_kmem_put_cache(cachep);
3266         return objp;
3267 }
3268
3269 /*
3270  * Caller needs to acquire correct kmem_cache_node's list_lock
3271  * @list: List of detached free slabs should be freed by caller
3272  */
3273 static void free_block(struct kmem_cache *cachep, void **objpp,
3274                         int nr_objects, int node, struct list_head *list)
3275 {
3276         int i;
3277         struct kmem_cache_node *n = get_node(cachep, node);
3278
3279         for (i = 0; i < nr_objects; i++) {
3280                 void *objp;
3281                 struct page *page;
3282
3283                 clear_obj_pfmemalloc(&objpp[i]);
3284                 objp = objpp[i];
3285
3286                 page = virt_to_head_page(objp);
3287                 list_del(&page->lru);
3288                 check_spinlock_acquired_node(cachep, node);
3289                 slab_put_obj(cachep, page, objp, node);
3290                 STATS_DEC_ACTIVE(cachep);
3291                 n->free_objects++;
3292
3293                 /* fixup slab chains */
3294                 if (page->active == 0) {
3295                         if (n->free_objects > n->free_limit) {
3296                                 n->free_objects -= cachep->num;
3297                                 list_add_tail(&page->lru, list);
3298                         } else {
3299                                 list_add(&page->lru, &n->slabs_free);
3300                         }
3301                 } else {
3302                         /* Unconditionally move a slab to the end of the
3303                          * partial list on free - maximum time for the
3304                          * other objects to be freed, too.
3305                          */
3306                         list_add_tail(&page->lru, &n->slabs_partial);
3307                 }
3308         }
3309 }
3310
3311 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3312 {
3313         int batchcount;
3314         struct kmem_cache_node *n;
3315         int node = numa_mem_id();
3316         LIST_HEAD(list);
3317
3318         batchcount = ac->batchcount;
3319 #if DEBUG
3320         BUG_ON(!batchcount || batchcount > ac->avail);
3321 #endif
3322         check_irq_off();
3323         n = get_node(cachep, node);
3324         spin_lock(&n->list_lock);
3325         if (n->shared) {
3326                 struct array_cache *shared_array = n->shared;
3327                 int max = shared_array->limit - shared_array->avail;
3328                 if (max) {
3329                         if (batchcount > max)
3330                                 batchcount = max;
3331                         memcpy(&(shared_array->entry[shared_array->avail]),
3332                                ac->entry, sizeof(void *) * batchcount);
3333                         shared_array->avail += batchcount;
3334                         goto free_done;
3335                 }
3336         }
3337
3338         free_block(cachep, ac->entry, batchcount, node, &list);
3339 free_done:
3340 #if STATS
3341         {
3342                 int i = 0;
3343                 struct list_head *p;
3344
3345                 p = n->slabs_free.next;
3346                 while (p != &(n->slabs_free)) {
3347                         struct page *page;
3348
3349                         page = list_entry(p, struct page, lru);
3350                         BUG_ON(page->active);
3351
3352                         i++;
3353                         p = p->next;
3354                 }
3355                 STATS_SET_FREEABLE(cachep, i);
3356         }
3357 #endif
3358         spin_unlock(&n->list_lock);
3359         slabs_destroy(cachep, &list);
3360         ac->avail -= batchcount;
3361         memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3362 }
3363
3364 /*
3365  * Release an obj back to its cache. If the obj has a constructed state, it must
3366  * be in this state _before_ it is released.  Called with disabled ints.
3367  */
3368 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3369                                 unsigned long caller)
3370 {
3371         struct array_cache *ac = cpu_cache_get(cachep);
3372
3373         check_irq_off();
3374         kmemleak_free_recursive(objp, cachep->flags);
3375         objp = cache_free_debugcheck(cachep, objp, caller);
3376
3377         kmemcheck_slab_free(cachep, objp, cachep->object_size);
3378
3379         /*
3380          * Skip calling cache_free_alien() when the platform is not numa.
3381          * This will avoid cache misses that happen while accessing slabp (which
3382          * is per page memory  reference) to get nodeid. Instead use a global
3383          * variable to skip the call, which is mostly likely to be present in
3384          * the cache.
3385          */
3386         if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3387                 return;
3388
3389         if (ac->avail < ac->limit) {
3390                 STATS_INC_FREEHIT(cachep);
3391         } else {
3392                 STATS_INC_FREEMISS(cachep);
3393                 cache_flusharray(cachep, ac);
3394         }
3395
3396         ac_put_obj(cachep, ac, objp);
3397 }
3398
3399 /**
3400  * kmem_cache_alloc - Allocate an object
3401  * @cachep: The cache to allocate from.
3402  * @flags: See kmalloc().
3403  *
3404  * Allocate an object from this cache.  The flags are only relevant
3405  * if the cache has no available objects.
3406  */
3407 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3408 {
3409         void *ret = slab_alloc(cachep, flags, _RET_IP_);
3410
3411         trace_kmem_cache_alloc(_RET_IP_, ret,
3412                                cachep->object_size, cachep->size, flags);
3413
3414         return ret;
3415 }
3416 EXPORT_SYMBOL(kmem_cache_alloc);
3417
3418 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
3419 {
3420         __kmem_cache_free_bulk(s, size, p);
3421 }
3422 EXPORT_SYMBOL(kmem_cache_free_bulk);
3423
3424 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3425                                                                 void **p)
3426 {
3427         return __kmem_cache_alloc_bulk(s, flags, size, p);
3428 }
3429 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3430
3431 #ifdef CONFIG_TRACING
3432 void *
3433 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3434 {
3435         void *ret;
3436
3437         ret = slab_alloc(cachep, flags, _RET_IP_);
3438
3439         trace_kmalloc(_RET_IP_, ret,
3440                       size, cachep->size, flags);
3441         return ret;
3442 }
3443 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3444 #endif
3445
3446 #ifdef CONFIG_NUMA
3447 /**
3448  * kmem_cache_alloc_node - Allocate an object on the specified node
3449  * @cachep: The cache to allocate from.
3450  * @flags: See kmalloc().
3451  * @nodeid: node number of the target node.
3452  *
3453  * Identical to kmem_cache_alloc but it will allocate memory on the given
3454  * node, which can improve the performance for cpu bound structures.
3455  *
3456  * Fallback to other node is possible if __GFP_THISNODE is not set.
3457  */
3458 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3459 {
3460         void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3461
3462         trace_kmem_cache_alloc_node(_RET_IP_, ret,
3463                                     cachep->object_size, cachep->size,
3464                                     flags, nodeid);
3465
3466         return ret;
3467 }
3468 EXPORT_SYMBOL(kmem_cache_alloc_node);
3469
3470 #ifdef CONFIG_TRACING
3471 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3472                                   gfp_t flags,
3473                                   int nodeid,
3474                                   size_t size)
3475 {
3476         void *ret;
3477
3478         ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3479
3480         trace_kmalloc_node(_RET_IP_, ret,
3481                            size, cachep->size,
3482                            flags, nodeid);
3483         return ret;
3484 }
3485 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3486 #endif
3487
3488 static __always_inline void *
3489 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3490 {
3491         struct kmem_cache *cachep;
3492
3493         cachep = kmalloc_slab(size, flags);
3494         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3495                 return cachep;
3496         return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3497 }
3498
3499 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3500 {
3501         return __do_kmalloc_node(size, flags, node, _RET_IP_);
3502 }
3503 EXPORT_SYMBOL(__kmalloc_node);
3504
3505 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3506                 int node, unsigned long caller)
3507 {
3508         return __do_kmalloc_node(size, flags, node, caller);
3509 }
3510 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3511 #endif /* CONFIG_NUMA */
3512
3513 /**
3514  * __do_kmalloc - allocate memory
3515  * @size: how many bytes of memory are required.
3516  * @flags: the type of memory to allocate (see kmalloc).
3517  * @caller: function caller for debug tracking of the caller
3518  */
3519 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3520                                           unsigned long caller)
3521 {
3522         struct kmem_cache *cachep;
3523         void *ret;
3524
3525         cachep = kmalloc_slab(size, flags);
3526         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3527                 return cachep;
3528         ret = slab_alloc(cachep, flags, caller);
3529
3530         trace_kmalloc(caller, ret,
3531                       size, cachep->size, flags);
3532
3533         return ret;
3534 }
3535
3536 void *__kmalloc(size_t size, gfp_t flags)
3537 {
3538         return __do_kmalloc(size, flags, _RET_IP_);
3539 }
3540 EXPORT_SYMBOL(__kmalloc);
3541
3542 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3543 {
3544         return __do_kmalloc(size, flags, caller);
3545 }
3546 EXPORT_SYMBOL(__kmalloc_track_caller);
3547
3548 /**
3549  * kmem_cache_free - Deallocate an object
3550  * @cachep: The cache the allocation was from.
3551  * @objp: The previously allocated object.
3552  *
3553  * Free an object which was previously allocated from this
3554  * cache.
3555  */
3556 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3557 {
3558         unsigned long flags;
3559         cachep = cache_from_obj(cachep, objp);
3560         if (!cachep)
3561                 return;
3562
3563         local_irq_save(flags);
3564         debug_check_no_locks_freed(objp, cachep->object_size);
3565         if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3566                 debug_check_no_obj_freed(objp, cachep->object_size);
3567         __cache_free(cachep, objp, _RET_IP_);
3568         local_irq_restore(flags);
3569
3570         trace_kmem_cache_free(_RET_IP_, objp);
3571 }
3572 EXPORT_SYMBOL(kmem_cache_free);
3573
3574 /**
3575  * kfree - free previously allocated memory
3576  * @objp: pointer returned by kmalloc.
3577  *
3578  * If @objp is NULL, no operation is performed.
3579  *
3580  * Don't free memory not originally allocated by kmalloc()
3581  * or you will run into trouble.
3582  */
3583 void kfree(const void *objp)
3584 {
3585         struct kmem_cache *c;
3586         unsigned long flags;
3587
3588         trace_kfree(_RET_IP_, objp);
3589
3590         if (unlikely(ZERO_OR_NULL_PTR(objp)))
3591                 return;
3592         local_irq_save(flags);
3593         kfree_debugcheck(objp);
3594         c = virt_to_cache(objp);
3595         debug_check_no_locks_freed(objp, c->object_size);
3596
3597         debug_check_no_obj_freed(objp, c->object_size);
3598         __cache_free(c, (void *)objp, _RET_IP_);
3599         local_irq_restore(flags);
3600 }
3601 EXPORT_SYMBOL(kfree);
3602
3603 /*
3604  * This initializes kmem_cache_node or resizes various caches for all nodes.
3605  */
3606 static int alloc_kmem_cache_node(struct kmem_cache *cachep, gfp_t gfp)
3607 {
3608         int node;
3609         struct kmem_cache_node *n;
3610         struct array_cache *new_shared;
3611         struct alien_cache **new_alien = NULL;
3612
3613         for_each_online_node(node) {
3614
3615                 if (use_alien_caches) {
3616                         new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3617                         if (!new_alien)
3618                                 goto fail;
3619                 }
3620
3621                 new_shared = NULL;
3622                 if (cachep->shared) {
3623                         new_shared = alloc_arraycache(node,
3624                                 cachep->shared*cachep->batchcount,
3625                                         0xbaadf00d, gfp);
3626                         if (!new_shared) {
3627                                 free_alien_cache(new_alien);
3628                                 goto fail;
3629                         }
3630                 }
3631
3632                 n = get_node(cachep, node);
3633                 if (n) {
3634                         struct array_cache *shared = n->shared;
3635                         LIST_HEAD(list);
3636
3637                         spin_lock_irq(&n->list_lock);
3638
3639                         if (shared)
3640                                 free_block(cachep, shared->entry,
3641                                                 shared->avail, node, &list);
3642
3643                         n->shared = new_shared;
3644                         if (!n->alien) {
3645                                 n->alien = new_alien;
3646                                 new_alien = NULL;
3647                         }
3648                         n->free_limit = (1 + nr_cpus_node(node)) *
3649                                         cachep->batchcount + cachep->num;
3650                         spin_unlock_irq(&n->list_lock);
3651                         slabs_destroy(cachep, &list);
3652                         kfree(shared);
3653                         free_alien_cache(new_alien);
3654                         continue;
3655                 }
3656                 n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
3657                 if (!n) {
3658                         free_alien_cache(new_alien);
3659                         kfree(new_shared);
3660                         goto fail;
3661                 }
3662
3663                 kmem_cache_node_init(n);
3664                 n->next_reap = jiffies + REAPTIMEOUT_NODE +
3665                                 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
3666                 n->shared = new_shared;
3667                 n->alien = new_alien;
3668                 n->free_limit = (1 + nr_cpus_node(node)) *
3669                                         cachep->batchcount + cachep->num;
3670                 cachep->node[node] = n;
3671         }
3672         return 0;
3673
3674 fail:
3675         if (!cachep->list.next) {
3676                 /* Cache is not active yet. Roll back what we did */
3677                 node--;
3678                 while (node >= 0) {
3679                         n = get_node(cachep, node);
3680                         if (n) {
3681                                 kfree(n->shared);
3682                                 free_alien_cache(n->alien);
3683                                 kfree(n);
3684                                 cachep->node[node] = NULL;
3685                         }
3686                         node--;
3687                 }
3688         }
3689         return -ENOMEM;
3690 }
3691
3692 /* Always called with the slab_mutex held */
3693 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3694                                 int batchcount, int shared, gfp_t gfp)
3695 {
3696         struct array_cache __percpu *cpu_cache, *prev;
3697         int cpu;
3698
3699         cpu_cache = alloc_kmem_cache_cpus(cachep, limit, batchcount);
3700         if (!cpu_cache)
3701                 return -ENOMEM;
3702
3703         prev = cachep->cpu_cache;
3704         cachep->cpu_cache = cpu_cache;
3705         kick_all_cpus_sync();
3706
3707         check_irq_on();
3708         cachep->batchcount = batchcount;
3709         cachep->limit = limit;
3710         cachep->shared = shared;
3711
3712         if (!prev)
3713                 goto alloc_node;
3714
3715         for_each_online_cpu(cpu) {
3716                 LIST_HEAD(list);
3717                 int node;
3718                 struct kmem_cache_node *n;
3719                 struct array_cache *ac = per_cpu_ptr(prev, cpu);
3720
3721                 node = cpu_to_mem(cpu);
3722                 n = get_node(cachep, node);
3723                 spin_lock_irq(&n->list_lock);
3724                 free_block(cachep, ac->entry, ac->avail, node, &list);
3725                 spin_unlock_irq(&n->list_lock);
3726                 slabs_destroy(cachep, &list);
3727         }
3728         free_percpu(prev);
3729
3730 alloc_node:
3731         return alloc_kmem_cache_node(cachep, gfp);
3732 }
3733
3734 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3735                                 int batchcount, int shared, gfp_t gfp)
3736 {
3737         int ret;
3738         struct kmem_cache *c;
3739
3740         ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3741
3742         if (slab_state < FULL)
3743                 return ret;
3744
3745         if ((ret < 0) || !is_root_cache(cachep))
3746                 return ret;
3747
3748         lockdep_assert_held(&slab_mutex);
3749         for_each_memcg_cache(c, cachep) {
3750                 /* return value determined by the root cache only */
3751                 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3752         }
3753
3754         return ret;
3755 }
3756
3757 /* Called with slab_mutex held always */
3758 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3759 {
3760         int err;
3761         int limit = 0;
3762         int shared = 0;
3763         int batchcount = 0;
3764
3765         if (!is_root_cache(cachep)) {
3766                 struct kmem_cache *root = memcg_root_cache(cachep);
3767                 limit = root->limit;
3768                 shared = root->shared;
3769                 batchcount = root->batchcount;
3770         }
3771
3772         if (limit && shared && batchcount)
3773                 goto skip_setup;
3774         /*
3775          * The head array serves three purposes:
3776          * - create a LIFO ordering, i.e. return objects that are cache-warm
3777          * - reduce the number of spinlock operations.
3778          * - reduce the number of linked list operations on the slab and
3779          *   bufctl chains: array operations are cheaper.
3780          * The numbers are guessed, we should auto-tune as described by
3781          * Bonwick.
3782          */
3783         if (cachep->size > 131072)
3784                 limit = 1;
3785         else if (cachep->size > PAGE_SIZE)
3786                 limit = 8;
3787         else if (cachep->size > 1024)
3788                 limit = 24;
3789         else if (cachep->size > 256)
3790                 limit = 54;
3791         else
3792                 limit = 120;
3793
3794         /*
3795          * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3796          * allocation behaviour: Most allocs on one cpu, most free operations
3797          * on another cpu. For these cases, an efficient object passing between
3798          * cpus is necessary. This is provided by a shared array. The array
3799          * replaces Bonwick's magazine layer.
3800          * On uniprocessor, it's functionally equivalent (but less efficient)
3801          * to a larger limit. Thus disabled by default.
3802          */
3803         shared = 0;
3804         if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
3805                 shared = 8;
3806
3807 #if DEBUG
3808         /*
3809          * With debugging enabled, large batchcount lead to excessively long
3810          * periods with disabled local interrupts. Limit the batchcount
3811          */
3812         if (limit > 32)
3813                 limit = 32;
3814 #endif
3815         batchcount = (limit + 1) / 2;
3816 skip_setup:
3817         err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3818         if (err)
3819                 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3820                        cachep->name, -err);
3821         return err;
3822 }
3823
3824 /*
3825  * Drain an array if it contains any elements taking the node lock only if
3826  * necessary. Note that the node listlock also protects the array_cache
3827  * if drain_array() is used on the shared array.
3828  */
3829 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
3830                          struct array_cache *ac, int force, int node)
3831 {
3832         LIST_HEAD(list);
3833         int tofree;
3834
3835         if (!ac || !ac->avail)
3836                 return;
3837         if (ac->touched && !force) {
3838                 ac->touched = 0;
3839         } else {
3840                 spin_lock_irq(&n->list_lock);
3841                 if (ac->avail) {
3842                         tofree = force ? ac->avail : (ac->limit + 4) / 5;
3843                         if (tofree > ac->avail)
3844                                 tofree = (ac->avail + 1) / 2;
3845                         free_block(cachep, ac->entry, tofree, node, &list);
3846                         ac->avail -= tofree;
3847                         memmove(ac->entry, &(ac->entry[tofree]),
3848                                 sizeof(void *) * ac->avail);
3849                 }
3850                 spin_unlock_irq(&n->list_lock);
3851                 slabs_destroy(cachep, &list);
3852         }
3853 }
3854
3855 /**
3856  * cache_reap - Reclaim memory from caches.
3857  * @w: work descriptor
3858  *
3859  * Called from workqueue/eventd every few seconds.
3860  * Purpose:
3861  * - clear the per-cpu caches for this CPU.
3862  * - return freeable pages to the main free memory pool.
3863  *
3864  * If we cannot acquire the cache chain mutex then just give up - we'll try
3865  * again on the next iteration.
3866  */
3867 static void cache_reap(struct work_struct *w)
3868 {
3869         struct kmem_cache *searchp;
3870         struct kmem_cache_node *n;
3871         int node = numa_mem_id();
3872         struct delayed_work *work = to_delayed_work(w);
3873
3874         if (!mutex_trylock(&slab_mutex))
3875                 /* Give up. Setup the next iteration. */
3876                 goto out;
3877
3878         list_for_each_entry(searchp, &slab_caches, list) {
3879                 check_irq_on();
3880
3881                 /*
3882                  * We only take the node lock if absolutely necessary and we
3883                  * have established with reasonable certainty that
3884                  * we can do some work if the lock was obtained.
3885                  */
3886                 n = get_node(searchp, node);
3887
3888                 reap_alien(searchp, n);
3889
3890                 drain_array(searchp, n, cpu_cache_get(searchp), 0, node);
3891
3892                 /*
3893                  * These are racy checks but it does not matter
3894                  * if we skip one check or scan twice.
3895                  */
3896                 if (time_after(n->next_reap, jiffies))
3897                         goto next;
3898
3899                 n->next_reap = jiffies + REAPTIMEOUT_NODE;
3900
3901                 drain_array(searchp, n, n->shared, 0, node);
3902
3903                 if (n->free_touched)
3904                         n->free_touched = 0;
3905                 else {
3906                         int freed;
3907
3908                         freed = drain_freelist(searchp, n, (n->free_limit +
3909                                 5 * searchp->num - 1) / (5 * searchp->num));
3910                         STATS_ADD_REAPED(searchp, freed);
3911                 }
3912 next:
3913                 cond_resched();
3914         }
3915         check_irq_on();
3916         mutex_unlock(&slab_mutex);
3917         next_reap_node();
3918 out:
3919         /* Set up the next iteration */
3920         schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
3921 }
3922
3923 #ifdef CONFIG_SLABINFO
3924 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
3925 {
3926         struct page *page;
3927         unsigned long active_objs;
3928         unsigned long num_objs;
3929         unsigned long active_slabs = 0;
3930         unsigned long num_slabs, free_objects = 0, shared_avail = 0;
3931         const char *name;
3932         char *error = NULL;
3933         int node;
3934         struct kmem_cache_node *n;
3935
3936         active_objs = 0;
3937         num_slabs = 0;
3938         for_each_kmem_cache_node(cachep, node, n) {
3939
3940                 check_irq_on();
3941                 spin_lock_irq(&n->list_lock);
3942
3943                 list_for_each_entry(page, &n->slabs_full, lru) {
3944                         if (page->active != cachep->num && !error)
3945                                 error = "slabs_full accounting error";
3946                         active_objs += cachep->num;
3947                         active_slabs++;
3948                 }
3949                 list_for_each_entry(page, &n->slabs_partial, lru) {
3950                         if (page->active == cachep->num && !error)
3951                                 error = "slabs_partial accounting error";
3952                         if (!page->active && !error)
3953                                 error = "slabs_partial accounting error";
3954                         active_objs += page->active;
3955                         active_slabs++;
3956                 }
3957                 list_for_each_entry(page, &n->slabs_free, lru) {
3958                         if (page->active && !error)
3959                                 error = "slabs_free accounting error";
3960                         num_slabs++;
3961                 }
3962                 free_objects += n->free_objects;
3963                 if (n->shared)
3964                         shared_avail += n->shared->avail;
3965
3966                 spin_unlock_irq(&n->list_lock);
3967         }
3968         num_slabs += active_slabs;
3969         num_objs = num_slabs * cachep->num;
3970         if (num_objs - active_objs != free_objects && !error)
3971                 error = "free_objects accounting error";
3972
3973         name = cachep->name;
3974         if (error)
3975                 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3976
3977         sinfo->active_objs = active_objs;
3978         sinfo->num_objs = num_objs;
3979         sinfo->active_slabs = active_slabs;
3980         sinfo->num_slabs = num_slabs;
3981         sinfo->shared_avail = shared_avail;
3982         sinfo->limit = cachep->limit;
3983         sinfo->batchcount = cachep->batchcount;
3984         sinfo->shared = cachep->shared;
3985         sinfo->objects_per_slab = cachep->num;
3986         sinfo->cache_order = cachep->gfporder;
3987 }
3988
3989 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
3990 {
3991 #if STATS
3992         {                       /* node stats */
3993                 unsigned long high = cachep->high_mark;
3994                 unsigned long allocs = cachep->num_allocations;
3995                 unsigned long grown = cachep->grown;
3996                 unsigned long reaped = cachep->reaped;
3997                 unsigned long errors = cachep->errors;
3998                 unsigned long max_freeable = cachep->max_freeable;
3999                 unsigned long node_allocs = cachep->node_allocs;
4000                 unsigned long node_frees = cachep->node_frees;
4001                 unsigned long overflows = cachep->node_overflow;
4002
4003                 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4004                            "%4lu %4lu %4lu %4lu %4lu",
4005                            allocs, high, grown,
4006                            reaped, errors, max_freeable, node_allocs,
4007                            node_frees, overflows);
4008         }
4009         /* cpu stats */
4010         {
4011                 unsigned long allochit = atomic_read(&cachep->allochit);
4012                 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4013                 unsigned long freehit = atomic_read(&cachep->freehit);
4014                 unsigned long freemiss = atomic_read(&cachep->freemiss);
4015
4016                 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4017                            allochit, allocmiss, freehit, freemiss);
4018         }
4019 #endif
4020 }
4021
4022 #define MAX_SLABINFO_WRITE 128
4023 /**
4024  * slabinfo_write - Tuning for the slab allocator
4025  * @file: unused
4026  * @buffer: user buffer
4027  * @count: data length
4028  * @ppos: unused
4029  */
4030 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4031                        size_t count, loff_t *ppos)
4032 {
4033         char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4034         int limit, batchcount, shared, res;
4035         struct kmem_cache *cachep;
4036
4037         if (count > MAX_SLABINFO_WRITE)
4038                 return -EINVAL;
4039         if (copy_from_user(&kbuf, buffer, count))
4040                 return -EFAULT;
4041         kbuf[MAX_SLABINFO_WRITE] = '\0';
4042
4043         tmp = strchr(kbuf, ' ');
4044         if (!tmp)
4045                 return -EINVAL;
4046         *tmp = '\0';
4047         tmp++;
4048         if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4049                 return -EINVAL;
4050
4051         /* Find the cache in the chain of caches. */
4052         mutex_lock(&slab_mutex);
4053         res = -EINVAL;
4054         list_for_each_entry(cachep, &slab_caches, list) {
4055                 if (!strcmp(cachep->name, kbuf)) {
4056                         if (limit < 1 || batchcount < 1 ||
4057                                         batchcount > limit || shared < 0) {
4058                                 res = 0;
4059                         } else {
4060                                 res = do_tune_cpucache(cachep, limit,
4061                                                        batchcount, shared,
4062                                                        GFP_KERNEL);
4063                         }
4064                         break;
4065                 }
4066         }
4067         mutex_unlock(&slab_mutex);
4068         if (res >= 0)
4069                 res = count;
4070         return res;
4071 }
4072
4073 #ifdef CONFIG_DEBUG_SLAB_LEAK
4074
4075 static inline int add_caller(unsigned long *n, unsigned long v)
4076 {
4077         unsigned long *p;
4078         int l;
4079         if (!v)
4080                 return 1;
4081         l = n[1];
4082         p = n + 2;
4083         while (l) {
4084                 int i = l/2;
4085                 unsigned long *q = p + 2 * i;
4086                 if (*q == v) {
4087                         q[1]++;
4088                         return 1;
4089                 }
4090                 if (*q > v) {
4091                         l = i;
4092                 } else {
4093                         p = q + 2;
4094                         l -= i + 1;
4095                 }
4096         }
4097         if (++n[1] == n[0])
4098                 return 0;
4099         memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4100         p[0] = v;
4101         p[1] = 1;
4102         return 1;
4103 }
4104
4105 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4106                                                 struct page *page)
4107 {
4108         void *p;
4109         int i, j;
4110         unsigned long v;
4111
4112         if (n[0] == n[1])
4113                 return;
4114         for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4115                 bool active = true;
4116
4117                 for (j = page->active; j < c->num; j++) {
4118                         if (get_free_obj(page, j) == i) {
4119                                 active = false;
4120                                 break;
4121                         }
4122                 }
4123
4124                 if (!active)
4125                         continue;
4126
4127                 /*
4128                  * probe_kernel_read() is used for DEBUG_PAGEALLOC. page table
4129                  * mapping is established when actual object allocation and
4130                  * we could mistakenly access the unmapped object in the cpu
4131                  * cache.
4132                  */
4133                 if (probe_kernel_read(&v, dbg_userword(c, p), sizeof(v)))
4134                         continue;
4135
4136                 if (!add_caller(n, v))
4137                         return;
4138         }
4139 }
4140
4141 static void show_symbol(struct seq_file *m, unsigned long address)
4142 {
4143 #ifdef CONFIG_KALLSYMS
4144         unsigned long offset, size;
4145         char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4146
4147         if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4148                 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4149                 if (modname[0])
4150                         seq_printf(m, " [%s]", modname);
4151                 return;
4152         }
4153 #endif
4154         seq_printf(m, "%p", (void *)address);
4155 }
4156
4157 static int leaks_show(struct seq_file *m, void *p)
4158 {
4159         struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4160         struct page *page;
4161         struct kmem_cache_node *n;
4162         const char *name;
4163         unsigned long *x = m->private;
4164         int node;
4165         int i;
4166
4167         if (!(cachep->flags & SLAB_STORE_USER))
4168                 return 0;
4169         if (!(cachep->flags & SLAB_RED_ZONE))
4170                 return 0;
4171
4172         /*
4173          * Set store_user_clean and start to grab stored user information
4174          * for all objects on this cache. If some alloc/free requests comes
4175          * during the processing, information would be wrong so restart
4176          * whole processing.
4177          */
4178         do {
4179                 set_store_user_clean(cachep);
4180                 drain_cpu_caches(cachep);
4181
4182                 x[1] = 0;
4183
4184                 for_each_kmem_cache_node(cachep, node, n) {
4185
4186                         check_irq_on();
4187                         spin_lock_irq(&n->list_lock);
4188
4189                         list_for_each_entry(page, &n->slabs_full, lru)
4190                                 handle_slab(x, cachep, page);
4191                         list_for_each_entry(page, &n->slabs_partial, lru)
4192                                 handle_slab(x, cachep, page);
4193                         spin_unlock_irq(&n->list_lock);
4194                 }
4195         } while (!is_store_user_clean(cachep));
4196
4197         name = cachep->name;
4198         if (x[0] == x[1]) {
4199                 /* Increase the buffer size */
4200                 mutex_unlock(&slab_mutex);
4201                 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4202                 if (!m->private) {
4203                         /* Too bad, we are really out */
4204                         m->private = x;
4205                         mutex_lock(&slab_mutex);
4206                         return -ENOMEM;
4207                 }
4208                 *(unsigned long *)m->private = x[0] * 2;
4209                 kfree(x);
4210                 mutex_lock(&slab_mutex);
4211                 /* Now make sure this entry will be retried */
4212                 m->count = m->size;
4213                 return 0;
4214         }
4215         for (i = 0; i < x[1]; i++) {
4216                 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4217                 show_symbol(m, x[2*i+2]);
4218                 seq_putc(m, '\n');
4219         }
4220
4221         return 0;
4222 }
4223
4224 static const struct seq_operations slabstats_op = {
4225         .start = slab_start,
4226         .next = slab_next,
4227         .stop = slab_stop,
4228         .show = leaks_show,
4229 };
4230
4231 static int slabstats_open(struct inode *inode, struct file *file)
4232 {
4233         unsigned long *n;
4234
4235         n = __seq_open_private(file, &slabstats_op, PAGE_SIZE);
4236         if (!n)
4237                 return -ENOMEM;
4238
4239         *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4240
4241         return 0;
4242 }
4243
4244 static const struct file_operations proc_slabstats_operations = {
4245         .open           = slabstats_open,
4246         .read           = seq_read,
4247         .llseek         = seq_lseek,
4248         .release        = seq_release_private,
4249 };
4250 #endif
4251
4252 static int __init slab_proc_init(void)
4253 {
4254 #ifdef CONFIG_DEBUG_SLAB_LEAK
4255         proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4256 #endif
4257         return 0;
4258 }
4259 module_init(slab_proc_init);
4260 #endif
4261
4262 #ifdef CONFIG_HARDENED_USERCOPY
4263 /*
4264  * Rejects objects that are incorrectly sized.
4265  *
4266  * Returns NULL if check passes, otherwise const char * to name of cache
4267  * to indicate an error.
4268  */
4269 const char *__check_heap_object(const void *ptr, unsigned long n,
4270                                 struct page *page)
4271 {
4272         struct kmem_cache *cachep;
4273         unsigned int objnr;
4274         unsigned long offset;
4275
4276         /* Find and validate object. */
4277         cachep = page->slab_cache;
4278         objnr = obj_to_index(cachep, page, (void *)ptr);
4279         BUG_ON(objnr >= cachep->num);
4280
4281         /* Find offset within object. */
4282         offset = ptr - index_to_obj(cachep, page, objnr) - obj_offset(cachep);
4283
4284         /* Allow address range falling entirely within object size. */
4285         if (offset <= cachep->object_size && n <= cachep->object_size - offset)
4286                 return NULL;
4287
4288         return cachep->name;
4289 }
4290 #endif /* CONFIG_HARDENED_USERCOPY */
4291
4292 /**
4293  * ksize - get the actual amount of memory allocated for a given object
4294  * @objp: Pointer to the object
4295  *
4296  * kmalloc may internally round up allocations and return more memory
4297  * than requested. ksize() can be used to determine the actual amount of
4298  * memory allocated. The caller may use this additional memory, even though
4299  * a smaller amount of memory was initially specified with the kmalloc call.
4300  * The caller must guarantee that objp points to a valid object previously
4301  * allocated with either kmalloc() or kmem_cache_alloc(). The object
4302  * must not be freed during the duration of the call.
4303  */
4304 size_t ksize(const void *objp)
4305 {
4306         BUG_ON(!objp);
4307         if (unlikely(objp == ZERO_SIZE_PTR))
4308                 return 0;
4309
4310         return virt_to_cache(objp)->object_size;
4311 }
4312 EXPORT_SYMBOL(ksize);