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