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