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