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