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