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