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