ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.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  */
79
80 #include        <linux/config.h>
81 #include        <linux/slab.h>
82 #include        <linux/mm.h>
83 #include        <linux/swap.h>
84 #include        <linux/cache.h>
85 #include        <linux/interrupt.h>
86 #include        <linux/init.h>
87 #include        <linux/compiler.h>
88 #include        <linux/seq_file.h>
89 #include        <linux/notifier.h>
90 #include        <linux/kallsyms.h>
91 #include        <linux/cpu.h>
92 #include        <linux/sysctl.h>
93 #include        <linux/module.h>
94
95 #include        <asm/uaccess.h>
96 #include        <asm/cacheflush.h>
97 #include        <asm/tlbflush.h>
98
99 /*
100  * DEBUG        - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
101  *                SLAB_RED_ZONE & SLAB_POISON.
102  *                0 for faster, smaller code (especially in the critical paths).
103  *
104  * STATS        - 1 to collect stats for /proc/slabinfo.
105  *                0 for faster, smaller code (especially in the critical paths).
106  *
107  * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
108  */
109
110 #ifdef CONFIG_DEBUG_SLAB
111 #define DEBUG           1
112 #define STATS           1
113 #define FORCED_DEBUG    1
114 #else
115 #define DEBUG           0
116 #define STATS           0
117 #define FORCED_DEBUG    0
118 #endif
119
120
121 /* Shouldn't this be in a header file somewhere? */
122 #define BYTES_PER_WORD          sizeof(void *)
123
124 #ifndef cache_line_size
125 #define cache_line_size()       L1_CACHE_BYTES
126 #endif
127
128 #ifndef ARCH_KMALLOC_MINALIGN
129 #define ARCH_KMALLOC_MINALIGN 0
130 #endif
131
132 /* Legal flag mask for kmem_cache_create(). */
133 #if DEBUG
134 # define CREATE_MASK    (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
135                          SLAB_POISON | SLAB_HWCACHE_ALIGN | \
136                          SLAB_NO_REAP | SLAB_CACHE_DMA | \
137                          SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
138                          SLAB_RECLAIM_ACCOUNT )
139 #else
140 # define CREATE_MASK    (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
141                          SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
142                          SLAB_RECLAIM_ACCOUNT)
143 #endif
144
145 /*
146  * kmem_bufctl_t:
147  *
148  * Bufctl's are used for linking objs within a slab
149  * linked offsets.
150  *
151  * This implementation relies on "struct page" for locating the cache &
152  * slab an object belongs to.
153  * This allows the bufctl structure to be small (one int), but limits
154  * the number of objects a slab (not a cache) can contain when off-slab
155  * bufctls are used. The limit is the size of the largest general cache
156  * that does not use off-slab slabs.
157  * For 32bit archs with 4 kB pages, is this 56.
158  * This is not serious, as it is only for large objects, when it is unwise
159  * to have too many per slab.
160  * Note: This limit can be raised by introducing a general cache whose size
161  * is less than 512 (PAGE_SIZE<<3), but greater than 256.
162  */
163
164 #define BUFCTL_END      0xffffFFFF
165 #define BUFCTL_FREE     0xffffFFFE
166 #define SLAB_LIMIT      0xffffFFFD
167 typedef unsigned int kmem_bufctl_t;
168
169 /* Max number of objs-per-slab for caches which use off-slab slabs.
170  * Needed to avoid a possible looping condition in cache_grow().
171  */
172 static unsigned long offslab_limit;
173
174 /*
175  * struct slab
176  *
177  * Manages the objs in a slab. Placed either at the beginning of mem allocated
178  * for a slab, or allocated from an general cache.
179  * Slabs are chained into three list: fully used, partial, fully free slabs.
180  */
181 struct slab {
182         struct list_head        list;
183         unsigned long           colouroff;
184         void                    *s_mem;         /* including colour offset */
185         unsigned int            inuse;          /* num of objs active in slab */
186         kmem_bufctl_t           free;
187 };
188
189 /*
190  * struct array_cache
191  *
192  * Per cpu structures
193  * Purpose:
194  * - LIFO ordering, to hand out cache-warm objects from _alloc
195  * - reduce the number of linked list operations
196  * - reduce spinlock operations
197  *
198  * The limit is stored in the per-cpu structure to reduce the data cache
199  * footprint.
200  *
201  */
202 struct array_cache {
203         unsigned int avail;
204         unsigned int limit;
205         unsigned int batchcount;
206         unsigned int touched;
207 };
208
209 /* bootstrap: The caches do not work without cpuarrays anymore,
210  * but the cpuarrays are allocated from the generic caches...
211  */
212 #define BOOT_CPUCACHE_ENTRIES   1
213 struct arraycache_init {
214         struct array_cache cache;
215         void * entries[BOOT_CPUCACHE_ENTRIES];
216 };
217
218 /*
219  * The slab lists of all objects.
220  * Hopefully reduce the internal fragmentation
221  * NUMA: The spinlock could be moved from the kmem_cache_t
222  * into this structure, too. Figure out what causes
223  * fewer cross-node spinlock operations.
224  */
225 struct kmem_list3 {
226         struct list_head        slabs_partial;  /* partial list first, better asm code */
227         struct list_head        slabs_full;
228         struct list_head        slabs_free;
229         unsigned long   free_objects;
230         int             free_touched;
231         unsigned long   next_reap;
232         struct array_cache      *shared;
233 };
234
235 #define LIST3_INIT(parent) \
236         { \
237                 .slabs_full     = LIST_HEAD_INIT(parent.slabs_full), \
238                 .slabs_partial  = LIST_HEAD_INIT(parent.slabs_partial), \
239                 .slabs_free     = LIST_HEAD_INIT(parent.slabs_free) \
240         }
241 #define list3_data(cachep) \
242         (&(cachep)->lists)
243
244 /* NUMA: per-node */
245 #define list3_data_ptr(cachep, ptr) \
246                 list3_data(cachep)
247
248 /*
249  * kmem_cache_t
250  *
251  * manages a cache.
252  */
253         
254 struct kmem_cache_s {
255 /* 1) per-cpu data, touched during every alloc/free */
256         struct array_cache      *array[NR_CPUS];
257         unsigned int            batchcount;
258         unsigned int            limit;
259 /* 2) touched by every alloc & free from the backend */
260         struct kmem_list3       lists;
261         /* NUMA: kmem_3list_t   *nodelists[MAX_NUMNODES] */
262         unsigned int            objsize;
263         unsigned int            flags;  /* constant flags */
264         unsigned int            num;    /* # of objs per slab */
265         unsigned int            free_limit; /* upper limit of objects in the lists */
266         spinlock_t              spinlock;
267
268 /* 3) cache_grow/shrink */
269         /* order of pgs per slab (2^n) */
270         unsigned int            gfporder;
271
272         /* force GFP flags, e.g. GFP_DMA */
273         unsigned int            gfpflags;
274
275         size_t                  colour;         /* cache colouring range */
276         unsigned int            colour_off;     /* colour offset */
277         unsigned int            colour_next;    /* cache colouring */
278         kmem_cache_t            *slabp_cache;
279         unsigned int            slab_size;
280         unsigned int            dflags;         /* dynamic flags */
281
282         /* constructor func */
283         void (*ctor)(void *, kmem_cache_t *, unsigned long);
284
285         /* de-constructor func */
286         void (*dtor)(void *, kmem_cache_t *, unsigned long);
287
288 /* 4) cache creation/removal */
289         const char              *name;
290         struct list_head        next;
291
292 /* 5) statistics */
293 #if STATS
294         unsigned long           num_active;
295         unsigned long           num_allocations;
296         unsigned long           high_mark;
297         unsigned long           grown;
298         unsigned long           reaped;
299         unsigned long           errors;
300         unsigned long           max_freeable;
301         atomic_t                allochit;
302         atomic_t                allocmiss;
303         atomic_t                freehit;
304         atomic_t                freemiss;
305 #endif
306 #if DEBUG
307         int                     dbghead;
308         int                     reallen;
309 #endif
310 };
311
312 #define CFLGS_OFF_SLAB          (0x80000000UL)
313 #define OFF_SLAB(x)     ((x)->flags & CFLGS_OFF_SLAB)
314
315 #define BATCHREFILL_LIMIT       16
316 /* Optimization question: fewer reaps means less 
317  * probability for unnessary cpucache drain/refill cycles.
318  *
319  * OTHO the cpuarrays can contain lots of objects,
320  * which could lock up otherwise freeable slabs.
321  */
322 #define REAPTIMEOUT_CPUC        (2*HZ)
323 #define REAPTIMEOUT_LIST3       (4*HZ)
324
325 #if STATS
326 #define STATS_INC_ACTIVE(x)     ((x)->num_active++)
327 #define STATS_DEC_ACTIVE(x)     ((x)->num_active--)
328 #define STATS_INC_ALLOCED(x)    ((x)->num_allocations++)
329 #define STATS_INC_GROWN(x)      ((x)->grown++)
330 #define STATS_INC_REAPED(x)     ((x)->reaped++)
331 #define STATS_SET_HIGH(x)       do { if ((x)->num_active > (x)->high_mark) \
332                                         (x)->high_mark = (x)->num_active; \
333                                 } while (0)
334 #define STATS_INC_ERR(x)        ((x)->errors++)
335 #define STATS_SET_FREEABLE(x, i) \
336                                 do { if ((x)->max_freeable < i) \
337                                         (x)->max_freeable = i; \
338                                 } while (0)
339
340 #define STATS_INC_ALLOCHIT(x)   atomic_inc(&(x)->allochit)
341 #define STATS_INC_ALLOCMISS(x)  atomic_inc(&(x)->allocmiss)
342 #define STATS_INC_FREEHIT(x)    atomic_inc(&(x)->freehit)
343 #define STATS_INC_FREEMISS(x)   atomic_inc(&(x)->freemiss)
344 #else
345 #define STATS_INC_ACTIVE(x)     do { } while (0)
346 #define STATS_DEC_ACTIVE(x)     do { } while (0)
347 #define STATS_INC_ALLOCED(x)    do { } while (0)
348 #define STATS_INC_GROWN(x)      do { } while (0)
349 #define STATS_INC_REAPED(x)     do { } while (0)
350 #define STATS_SET_HIGH(x)       do { } while (0)
351 #define STATS_INC_ERR(x)        do { } while (0)
352 #define STATS_SET_FREEABLE(x, i) \
353                                 do { } while (0)
354
355 #define STATS_INC_ALLOCHIT(x)   do { } while (0)
356 #define STATS_INC_ALLOCMISS(x)  do { } while (0)
357 #define STATS_INC_FREEHIT(x)    do { } while (0)
358 #define STATS_INC_FREEMISS(x)   do { } while (0)
359 #endif
360
361 #if DEBUG
362 /* Magic nums for obj red zoning.
363  * Placed in the first word before and the first word after an obj.
364  */
365 #define RED_INACTIVE    0x5A2CF071UL    /* when obj is inactive */
366 #define RED_ACTIVE      0x170FC2A5UL    /* when obj is active */
367
368 /* ...and for poisoning */
369 #define POISON_INUSE    0x5a    /* for use-uninitialised poisoning */
370 #define POISON_FREE     0x6b    /* for use-after-free poisoning */
371 #define POISON_END      0xa5    /* end-byte of poisoning */
372
373 /* memory layout of objects:
374  * 0            : objp
375  * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
376  *              the end of an object is aligned with the end of the real
377  *              allocation. Catches writes behind the end of the allocation.
378  * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
379  *              redzone word.
380  * cachep->dbghead: The real object.
381  * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
382  * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
383  */
384 static inline int obj_dbghead(kmem_cache_t *cachep)
385 {
386         return cachep->dbghead;
387 }
388
389 static inline int obj_reallen(kmem_cache_t *cachep)
390 {
391         return cachep->reallen;
392 }
393
394 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
395 {
396         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
397         return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
398 }
399
400 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
401 {
402         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
403         if (cachep->flags & SLAB_STORE_USER)
404                 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
405         return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
406 }
407
408 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
409 {
410         BUG_ON(!(cachep->flags & SLAB_STORE_USER));
411         return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
412 }
413 #else
414 static inline int obj_dbghead(kmem_cache_t *cachep)
415 {
416         return 0;
417 }
418 static inline int obj_reallen(kmem_cache_t *cachep)
419 {
420         return cachep->objsize;
421 }
422 static inline unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
423 {
424         BUG();
425         return 0;
426 }
427 static inline unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
428 {
429         BUG();
430         return 0;
431 }
432 static inline void **dbg_userword(kmem_cache_t *cachep, void *objp)
433 {
434         BUG();
435         return 0;
436 }
437 #endif
438
439 /*
440  * Maximum size of an obj (in 2^order pages)
441  * and absolute limit for the gfp order.
442  */
443 #if defined(CONFIG_LARGE_ALLOCS)
444 #define MAX_OBJ_ORDER   13      /* up to 32Mb */
445 #define MAX_GFP_ORDER   13      /* up to 32Mb */
446 #elif defined(CONFIG_MMU)
447 #define MAX_OBJ_ORDER   5       /* 32 pages */
448 #define MAX_GFP_ORDER   5       /* 32 pages */
449 #else
450 #define MAX_OBJ_ORDER   8       /* up to 1Mb */
451 #define MAX_GFP_ORDER   8       /* up to 1Mb */
452 #endif
453
454 /*
455  * Do not go above this order unless 0 objects fit into the slab.
456  */
457 #define BREAK_GFP_ORDER_HI      1
458 #define BREAK_GFP_ORDER_LO      0
459 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
460
461 /* Macros for storing/retrieving the cachep and or slab from the
462  * global 'mem_map'. These are used to find the slab an obj belongs to.
463  * With kfree(), these are used to find the cache which an obj belongs to.
464  */
465 #define SET_PAGE_CACHE(pg,x)  ((pg)->lru.next = (struct list_head *)(x))
466 #define GET_PAGE_CACHE(pg)    ((kmem_cache_t *)(pg)->lru.next)
467 #define SET_PAGE_SLAB(pg,x)   ((pg)->lru.prev = (struct list_head *)(x))
468 #define GET_PAGE_SLAB(pg)     ((struct slab *)(pg)->lru.prev)
469
470 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
471 struct cache_sizes malloc_sizes[] = {
472 #define CACHE(x) { .cs_size = (x) },
473 #include <linux/kmalloc_sizes.h>
474         { 0, }
475 #undef CACHE
476 };
477
478 EXPORT_SYMBOL(malloc_sizes);
479
480 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
481 static struct cache_names {
482         char *name;
483         char *name_dma;
484 } cache_names[] = {
485 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
486 #include <linux/kmalloc_sizes.h>
487         { 0, }
488 #undef CACHE
489 };
490
491 struct arraycache_init initarray_cache __initdata = { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
492 struct arraycache_init initarray_generic __initdata = { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
493
494 /* internal cache of cache description objs */
495 static kmem_cache_t cache_cache = {
496         .lists          = LIST3_INIT(cache_cache.lists),
497         .batchcount     = 1,
498         .limit          = BOOT_CPUCACHE_ENTRIES,
499         .objsize        = sizeof(kmem_cache_t),
500         .flags          = SLAB_NO_REAP,
501         .spinlock       = SPIN_LOCK_UNLOCKED,
502         .name           = "kmem_cache",
503 #if DEBUG
504         .reallen        = sizeof(kmem_cache_t),
505 #endif
506 };
507
508 /* Guard access to the cache-chain. */
509 static struct semaphore cache_chain_sem;
510
511 struct list_head cache_chain;
512
513 /*
514  * vm_enough_memory() looks at this to determine how many
515  * slab-allocated pages are possibly freeable under pressure
516  *
517  * SLAB_RECLAIM_ACCOUNT turns this on per-slab
518  */
519 atomic_t slab_reclaim_pages;
520 EXPORT_SYMBOL(slab_reclaim_pages);
521
522 /*
523  * chicken and egg problem: delay the per-cpu array allocation
524  * until the general caches are up.
525  */
526 enum {
527         NONE,
528         PARTIAL,
529         FULL
530 } g_cpucache_up;
531
532 static DEFINE_PER_CPU(struct timer_list, reap_timers);
533
534 static void reap_timer_fnc(unsigned long data);
535 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
536 static void enable_cpucache (kmem_cache_t *cachep);
537
538 static inline void ** ac_entry(struct array_cache *ac)
539 {
540         return (void**)(ac+1);
541 }
542
543 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
544 {
545         return cachep->array[smp_processor_id()];
546 }
547
548 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
549 static void cache_estimate (unsigned long gfporder, size_t size, size_t align,
550                  int flags, size_t *left_over, unsigned int *num)
551 {
552         int i;
553         size_t wastage = PAGE_SIZE<<gfporder;
554         size_t extra = 0;
555         size_t base = 0;
556
557         if (!(flags & CFLGS_OFF_SLAB)) {
558                 base = sizeof(struct slab);
559                 extra = sizeof(kmem_bufctl_t);
560         }
561         i = 0;
562         while (i*size + ALIGN(base+i*extra, align) <= wastage)
563                 i++;
564         if (i > 0)
565                 i--;
566
567         if (i > SLAB_LIMIT)
568                 i = SLAB_LIMIT;
569
570         *num = i;
571         wastage -= i*size;
572         wastage -= ALIGN(base+i*extra, align);
573         *left_over = wastage;
574 }
575
576 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
577
578 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
579 {
580         printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
581                 function, cachep->name, msg);
582         dump_stack();
583 }
584
585 /*
586  * Start the reap timer running on the target CPU.  We run at around 1 to 2Hz.
587  * Add the CPU number into the expiry time to minimize the possibility of the
588  * CPUs getting into lockstep and contending for the global cache chain lock.
589  */
590 static void __devinit start_cpu_timer(int cpu)
591 {
592         struct timer_list *rt = &per_cpu(reap_timers, cpu);
593
594         if (rt->function == NULL) {
595                 init_timer(rt);
596                 rt->expires = jiffies + HZ + 3*cpu;
597                 rt->data = cpu;
598                 rt->function = reap_timer_fnc;
599                 add_timer_on(rt, cpu);
600         }
601 }
602
603 #ifdef CONFIG_HOTPLUG_CPU
604 static void stop_cpu_timer(int cpu)
605 {
606         struct timer_list *rt = &per_cpu(reap_timers, cpu);
607
608         if (rt->function) {
609                 del_timer_sync(rt);
610                 WARN_ON(timer_pending(rt));
611                 rt->function = NULL;
612         }
613 }
614 #endif
615
616 static int __devinit cpuup_callback(struct notifier_block *nfb,
617                                   unsigned long action,
618                                   void *hcpu)
619 {
620         long cpu = (long)hcpu;
621         kmem_cache_t* cachep;
622
623         switch (action) {
624         case CPU_UP_PREPARE:
625                 down(&cache_chain_sem);
626                 list_for_each_entry(cachep, &cache_chain, next) {
627                         int memsize;
628                         struct array_cache *nc;
629
630                         memsize = sizeof(void*)*cachep->limit+sizeof(struct array_cache);
631                         nc = kmalloc(memsize, GFP_KERNEL);
632                         if (!nc)
633                                 goto bad;
634                         nc->avail = 0;
635                         nc->limit = cachep->limit;
636                         nc->batchcount = cachep->batchcount;
637                         nc->touched = 0;
638
639                         spin_lock_irq(&cachep->spinlock);
640                         cachep->array[cpu] = nc;
641                         cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
642                                                 + cachep->num;
643                         spin_unlock_irq(&cachep->spinlock);
644
645                 }
646                 up(&cache_chain_sem);
647                 break;
648         case CPU_ONLINE:
649                 start_cpu_timer(cpu);
650                 break;
651 #ifdef CONFIG_HOTPLUG_CPU
652         case CPU_DEAD:
653                 stop_cpu_timer(cpu);
654                 /* fall thru */
655         case CPU_UP_CANCELED:
656                 down(&cache_chain_sem);
657
658                 list_for_each_entry(cachep, &cache_chain, next) {
659                         struct array_cache *nc;
660
661                         spin_lock_irq(&cachep->spinlock);
662                         /* cpu is dead; no one can alloc from it. */
663                         nc = cachep->array[cpu];
664                         cachep->array[cpu] = NULL;
665                         cachep->free_limit -= cachep->batchcount;
666                         free_block(cachep, ac_entry(nc), nc->avail);
667                         spin_unlock_irq(&cachep->spinlock);
668                         kfree(nc);
669                 }
670                 up(&cache_chain_sem);
671                 break;
672 #endif
673         }
674         return NOTIFY_OK;
675 bad:
676         up(&cache_chain_sem);
677         return NOTIFY_BAD;
678 }
679
680 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
681
682 /* Initialisation.
683  * Called after the gfp() functions have been enabled, and before smp_init().
684  */
685 void __init kmem_cache_init(void)
686 {
687         size_t left_over;
688         struct cache_sizes *sizes;
689         struct cache_names *names;
690
691         /*
692          * Fragmentation resistance on low memory - only use bigger
693          * page orders on machines with more than 32MB of memory.
694          */
695         if (num_physpages > (32 << 20) >> PAGE_SHIFT)
696                 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
697
698         
699         /* Bootstrap is tricky, because several objects are allocated
700          * from caches that do not exist yet:
701          * 1) initialize the cache_cache cache: it contains the kmem_cache_t
702          *    structures of all caches, except cache_cache itself: cache_cache
703          *    is statically allocated.
704          *    Initially an __init data area is used for the head array, it's
705          *    replaced with a kmalloc allocated array at the end of the bootstrap.
706          * 2) Create the first kmalloc cache.
707          *    The kmem_cache_t for the new cache is allocated normally. An __init
708          *    data area is used for the head array.
709          * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
710          * 4) Replace the __init data head arrays for cache_cache and the first
711          *    kmalloc cache with kmalloc allocated arrays.
712          * 5) Resize the head arrays of the kmalloc caches to their final sizes.
713          */
714
715         /* 1) create the cache_cache */
716         init_MUTEX(&cache_chain_sem);
717         INIT_LIST_HEAD(&cache_chain);
718         list_add(&cache_cache.next, &cache_chain);
719         cache_cache.colour_off = cache_line_size();
720         cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
721
722         cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
723
724         cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
725                                 &left_over, &cache_cache.num);
726         if (!cache_cache.num)
727                 BUG();
728
729         cache_cache.colour = left_over/cache_cache.colour_off;
730         cache_cache.colour_next = 0;
731         cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
732                                 sizeof(struct slab), cache_line_size());
733
734         /* 2+3) create the kmalloc caches */
735         sizes = malloc_sizes;
736         names = cache_names;
737
738         while (sizes->cs_size) {
739                 /* For performance, all the general caches are L1 aligned.
740                  * This should be particularly beneficial on SMP boxes, as it
741                  * eliminates "false sharing".
742                  * Note for systems short on memory removing the alignment will
743                  * allow tighter packing of the smaller caches. */
744                 sizes->cs_cachep = kmem_cache_create(
745                         names->name, sizes->cs_size,
746                         ARCH_KMALLOC_MINALIGN, 0, NULL, NULL);
747                 if (!sizes->cs_cachep)
748                         BUG();
749
750                 /* Inc off-slab bufctl limit until the ceiling is hit. */
751                 if (!(OFF_SLAB(sizes->cs_cachep))) {
752                         offslab_limit = sizes->cs_size-sizeof(struct slab);
753                         offslab_limit /= sizeof(kmem_bufctl_t);
754                 }
755
756                 sizes->cs_dmacachep = kmem_cache_create(
757                         names->name_dma, sizes->cs_size,
758                         ARCH_KMALLOC_MINALIGN, SLAB_CACHE_DMA, NULL, NULL);
759                 if (!sizes->cs_dmacachep)
760                         BUG();
761
762                 sizes++;
763                 names++;
764         }
765         /* 4) Replace the bootstrap head arrays */
766         {
767                 void * ptr;
768                 
769                 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
770                 local_irq_disable();
771                 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
772                 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
773                 cache_cache.array[smp_processor_id()] = ptr;
774                 local_irq_enable();
775         
776                 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
777                 local_irq_disable();
778                 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
779                 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
780                                 sizeof(struct arraycache_init));
781                 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
782                 local_irq_enable();
783         }
784
785         /* 5) resize the head arrays to their final sizes */
786         {
787                 kmem_cache_t *cachep;
788                 down(&cache_chain_sem);
789                 list_for_each_entry(cachep, &cache_chain, next)
790                         enable_cpucache(cachep);
791                 up(&cache_chain_sem);
792         }
793
794         /* Done! */
795         g_cpucache_up = FULL;
796
797         /* Register a cpu startup notifier callback
798          * that initializes ac_data for all new cpus
799          */
800         register_cpu_notifier(&cpucache_notifier);
801         
802
803         /* The reap timers are started later, with a module init call:
804          * That part of the kernel is not yet operational.
805          */
806 }
807
808 int __init cpucache_init(void)
809 {
810         int cpu;
811
812         /* 
813          * Register the timers that return unneeded
814          * pages to gfp.
815          */
816         for (cpu = 0; cpu < NR_CPUS; cpu++) {
817                 if (cpu_online(cpu))
818                         start_cpu_timer(cpu);
819         }
820
821         return 0;
822 }
823
824 __initcall(cpucache_init);
825
826 /*
827  * Interface to system's page allocator. No need to hold the cache-lock.
828  *
829  * If we requested dmaable memory, we will get it. Even if we
830  * did not request dmaable memory, we might get it, but that
831  * would be relatively rare and ignorable.
832  */
833 static inline void *kmem_getpages(kmem_cache_t *cachep, unsigned long flags)
834 {
835         void *addr;
836
837         flags |= cachep->gfpflags;
838         addr = (void*)__get_free_pages(flags, cachep->gfporder);
839         if (addr) {
840                 int i = (1 << cachep->gfporder);
841                 struct page *page = virt_to_page(addr);
842
843                 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
844                         atomic_add(i, &slab_reclaim_pages);
845                 add_page_state(nr_slab, i);
846                 while (i--) {
847                         SetPageSlab(page);
848                         page++;
849                 }
850         }
851         return addr;
852 }
853
854 /*
855  * Interface to system's page release.
856  */
857 static inline void kmem_freepages(kmem_cache_t *cachep, void *addr)
858 {
859         unsigned long i = (1<<cachep->gfporder);
860         struct page *page = virt_to_page(addr);
861         const unsigned long nr_freed = i;
862
863         while (i--) {
864                 if (!TestClearPageSlab(page))
865                         BUG();
866                 page++;
867         }
868         sub_page_state(nr_slab, nr_freed);
869         if (current->reclaim_state)
870                 current->reclaim_state->reclaimed_slab += nr_freed;
871         free_pages((unsigned long)addr, cachep->gfporder);
872         if (cachep->flags & SLAB_RECLAIM_ACCOUNT) 
873                 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
874 }
875
876 #if DEBUG
877
878 #ifdef CONFIG_DEBUG_PAGEALLOC
879 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr, unsigned long caller)
880 {
881         int size = obj_reallen(cachep);
882
883         addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
884
885         if (size < 5*sizeof(unsigned long))
886                 return;
887
888         *addr++=0x12345678;
889         *addr++=caller;
890         *addr++=smp_processor_id();
891         size -= 3*sizeof(unsigned long);
892         {
893                 unsigned long *sptr = &caller;
894                 unsigned long svalue;
895
896                 while (!kstack_end(sptr)) {
897                         svalue = *sptr++;
898                         if (kernel_text_address(svalue)) {
899                                 *addr++=svalue;
900                                 size -= sizeof(unsigned long);
901                                 if (size <= sizeof(unsigned long))
902                                         break;
903                         }
904                 }
905
906         }
907         *addr++=0x87654321;
908 }
909 #endif
910
911 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
912 {
913         int size = obj_reallen(cachep);
914         addr = &((char*)addr)[obj_dbghead(cachep)];
915
916         memset(addr, val, size);
917         *(unsigned char *)(addr+size-1) = POISON_END;
918 }
919
920 static void dump_line(char *data, int offset, int limit)
921 {
922         int i;
923         printk(KERN_ERR "%03x:", offset);
924         for (i=0;i<limit;i++) {
925                 printk(" %02x", (unsigned char)data[offset+i]);
926         }
927         printk("\n");
928 }
929 #endif
930
931 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
932 {
933 #if DEBUG
934         int i, size;
935         char *realobj;
936
937         if (cachep->flags & SLAB_RED_ZONE) {
938                 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
939                         *dbg_redzone1(cachep, objp),
940                         *dbg_redzone2(cachep, objp));
941         }
942
943         if (cachep->flags & SLAB_STORE_USER) {
944                 printk(KERN_ERR "Last user: [<%p>]", *dbg_userword(cachep, objp));
945                 print_symbol("(%s)", (unsigned long)*dbg_userword(cachep, objp));
946                 printk("\n");
947         }
948         realobj = (char*)objp+obj_dbghead(cachep);
949         size = obj_reallen(cachep);
950         for (i=0; i<size && lines;i+=16, lines--) {
951                 int limit;
952                 limit = 16;
953                 if (i+limit > size)
954                         limit = size-i;
955                 dump_line(realobj, i, limit);
956         }
957 #endif
958 }
959
960 #if DEBUG
961
962 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
963 {
964         char *realobj;
965         int size, i;
966         int lines = 0;
967
968         realobj = (char*)objp+obj_dbghead(cachep);
969         size = obj_reallen(cachep);
970
971         for (i=0;i<size;i++) {
972                 char exp = POISON_FREE;
973                 if (i == size-1)
974                         exp = POISON_END;
975                 if (realobj[i] != exp) {
976                         int limit;
977                         /* Mismatch ! */
978                         /* Print header */
979                         if (lines == 0) {
980                                 printk(KERN_ERR "Slab corruption: start=%p, len=%d\n",
981                                                 realobj, size);
982                                 print_objinfo(cachep, objp, 0);
983                         }
984                         /* Hexdump the affected line */
985                         i = (i/16)*16;
986                         limit = 16;
987                         if (i+limit > size)
988                                 limit = size-i;
989                         dump_line(realobj, i, limit);
990                         i += 16;
991                         lines++;
992                         /* Limit to 5 lines */
993                         if (lines > 5)
994                                 break;
995                 }
996         }
997         if (lines != 0) {
998                 /* Print some data about the neighboring objects, if they
999                  * exist:
1000                  */
1001                 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1002                 int objnr;
1003
1004                 objnr = (objp-slabp->s_mem)/cachep->objsize;
1005                 if (objnr) {
1006                         objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1007                         realobj = (char*)objp+obj_dbghead(cachep);
1008                         printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1009                                                 realobj, size);
1010                         print_objinfo(cachep, objp, 2);
1011                 }
1012                 if (objnr+1 < cachep->num) {
1013                         objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1014                         realobj = (char*)objp+obj_dbghead(cachep);
1015                         printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1016                                                 realobj, size);
1017                         print_objinfo(cachep, objp, 2);
1018                 }
1019         }
1020 }
1021 #endif
1022
1023 /* Destroy all the objs in a slab, and release the mem back to the system.
1024  * Before calling the slab must have been unlinked from the cache.
1025  * The cache-lock is not held/needed.
1026  */
1027 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1028 {
1029 #if DEBUG
1030         int i;
1031         for (i = 0; i < cachep->num; i++) {
1032                 void *objp = slabp->s_mem + cachep->objsize * i;
1033
1034                 if (cachep->flags & SLAB_POISON) {
1035 #ifdef CONFIG_DEBUG_PAGEALLOC
1036                         if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1037                                 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1038                         else
1039                                 check_poison_obj(cachep, objp);
1040 #else
1041                         check_poison_obj(cachep, objp);
1042 #endif
1043                 }
1044                 if (cachep->flags & SLAB_RED_ZONE) {
1045                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1046                                 slab_error(cachep, "start of a freed object "
1047                                                         "was overwritten");
1048                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1049                                 slab_error(cachep, "end of a freed object "
1050                                                         "was overwritten");
1051                 }
1052                 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1053                         (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1054         }
1055 #else
1056         if (cachep->dtor) {
1057                 int i;
1058                 for (i = 0; i < cachep->num; i++) {
1059                         void* objp = slabp->s_mem+cachep->objsize*i;
1060                         (cachep->dtor)(objp, cachep, 0);
1061                 }
1062         }
1063 #endif
1064         
1065         kmem_freepages(cachep, slabp->s_mem-slabp->colouroff);
1066         if (OFF_SLAB(cachep))
1067                 kmem_cache_free(cachep->slabp_cache, slabp);
1068 }
1069
1070 /**
1071  * kmem_cache_create - Create a cache.
1072  * @name: A string which is used in /proc/slabinfo to identify this cache.
1073  * @size: The size of objects to be created in this cache.
1074  * @align: The required alignment for the objects.
1075  * @flags: SLAB flags
1076  * @ctor: A constructor for the objects.
1077  * @dtor: A destructor for the objects.
1078  *
1079  * Returns a ptr to the cache on success, NULL on failure.
1080  * Cannot be called within a int, but can be interrupted.
1081  * The @ctor is run when new pages are allocated by the cache
1082  * and the @dtor is run before the pages are handed back.
1083  *
1084  * @name must be valid until the cache is destroyed. This implies that
1085  * the module calling this has to destroy the cache before getting 
1086  * unloaded.
1087  * 
1088  * The flags are
1089  *
1090  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1091  * to catch references to uninitialised memory.
1092  *
1093  * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1094  * for buffer overruns.
1095  *
1096  * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1097  * memory pressure.
1098  *
1099  * %SLAB_HWCACHE_ALIGN - This flag has no effect and will be removed soon.
1100  *
1101  */
1102 kmem_cache_t *
1103 kmem_cache_create (const char *name, size_t size, size_t align,
1104         unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1105         void (*dtor)(void*, kmem_cache_t *, unsigned long))
1106 {
1107         size_t left_over, slab_size;
1108         kmem_cache_t *cachep = NULL;
1109
1110         /*
1111          * Sanity checks... these are all serious usage bugs.
1112          */
1113         if ((!name) ||
1114                 in_interrupt() ||
1115                 (size < BYTES_PER_WORD) ||
1116                 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1117                 (dtor && !ctor) ||
1118                 (align < 0)) {
1119                         printk(KERN_ERR "%s: Early error in slab %s\n",
1120                                         __FUNCTION__, name);
1121                         BUG();
1122                 }
1123
1124 #if DEBUG
1125         WARN_ON(strchr(name, ' '));     /* It confuses parsers */
1126         if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1127                 /* No constructor, but inital state check requested */
1128                 printk(KERN_ERR "%s: No con, but init state check "
1129                                 "requested - %s\n", __FUNCTION__, name);
1130                 flags &= ~SLAB_DEBUG_INITIAL;
1131         }
1132
1133 #if FORCED_DEBUG
1134         /*
1135          * Enable redzoning and last user accounting, except for caches with
1136          * large objects, if the increased size would increase the object size
1137          * above the next power of two: caches with object sizes just above a
1138          * power of two have a significant amount of internal fragmentation.
1139          */
1140         if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1141                 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1142         flags |= SLAB_POISON;
1143 #endif
1144 #endif
1145         /*
1146          * Always checks flags, a caller might be expecting debug
1147          * support which isn't available.
1148          */
1149         if (flags & ~CREATE_MASK)
1150                 BUG();
1151
1152         if (align) {
1153                 /* combinations of forced alignment and advanced debugging is
1154                  * not yet implemented.
1155                  */
1156                 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1157         } else {
1158                 if (flags & SLAB_HWCACHE_ALIGN) {
1159                         /* Default alignment: as specified by the arch code.
1160                          * Except if an object is really small, then squeeze multiple
1161                          * into one cacheline.
1162                          */
1163                         align = cache_line_size();
1164                         while (size <= align/2)
1165                                 align /= 2;
1166                 } else {
1167                         align = BYTES_PER_WORD;
1168                 }
1169         }
1170
1171         /* Get cache's description obj. */
1172         cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1173         if (!cachep)
1174                 goto opps;
1175         memset(cachep, 0, sizeof(kmem_cache_t));
1176
1177         /* Check that size is in terms of words.  This is needed to avoid
1178          * unaligned accesses for some archs when redzoning is used, and makes
1179          * sure any on-slab bufctl's are also correctly aligned.
1180          */
1181         if (size & (BYTES_PER_WORD-1)) {
1182                 size += (BYTES_PER_WORD-1);
1183                 size &= ~(BYTES_PER_WORD-1);
1184         }
1185         
1186 #if DEBUG
1187         cachep->reallen = size;
1188
1189         if (flags & SLAB_RED_ZONE) {
1190                 /* redzoning only works with word aligned caches */
1191                 align = BYTES_PER_WORD;
1192
1193                 /* add space for red zone words */
1194                 cachep->dbghead += BYTES_PER_WORD;
1195                 size += 2*BYTES_PER_WORD;
1196         }
1197         if (flags & SLAB_STORE_USER) {
1198                 /* user store requires word alignment and
1199                  * one word storage behind the end of the real
1200                  * object.
1201                  */
1202                 align = BYTES_PER_WORD;
1203                 size += BYTES_PER_WORD;
1204         }
1205 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1206         if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1207                 cachep->dbghead += PAGE_SIZE - size;
1208                 size = PAGE_SIZE;
1209         }
1210 #endif
1211 #endif
1212
1213         /* Determine if the slab management is 'on' or 'off' slab. */
1214         if (size >= (PAGE_SIZE>>3))
1215                 /*
1216                  * Size is large, assume best to place the slab management obj
1217                  * off-slab (should allow better packing of objs).
1218                  */
1219                 flags |= CFLGS_OFF_SLAB;
1220
1221         size = ALIGN(size, align);
1222
1223         if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1224                 /*
1225                  * A VFS-reclaimable slab tends to have most allocations
1226                  * as GFP_NOFS and we really don't want to have to be allocating
1227                  * higher-order pages when we are unable to shrink dcache.
1228                  */
1229                 cachep->gfporder = 0;
1230                 cache_estimate(cachep->gfporder, size, align, flags,
1231                                         &left_over, &cachep->num);
1232         } else {
1233                 /*
1234                  * Calculate size (in pages) of slabs, and the num of objs per
1235                  * slab.  This could be made much more intelligent.  For now,
1236                  * try to avoid using high page-orders for slabs.  When the
1237                  * gfp() funcs are more friendly towards high-order requests,
1238                  * this should be changed.
1239                  */
1240                 do {
1241                         unsigned int break_flag = 0;
1242 cal_wastage:
1243                         cache_estimate(cachep->gfporder, size, align, flags,
1244                                                 &left_over, &cachep->num);
1245                         if (break_flag)
1246                                 break;
1247                         if (cachep->gfporder >= MAX_GFP_ORDER)
1248                                 break;
1249                         if (!cachep->num)
1250                                 goto next;
1251                         if (flags & CFLGS_OFF_SLAB &&
1252                                         cachep->num > offslab_limit) {
1253                                 /* This num of objs will cause problems. */
1254                                 cachep->gfporder--;
1255                                 break_flag++;
1256                                 goto cal_wastage;
1257                         }
1258
1259                         /*
1260                          * Large num of objs is good, but v. large slabs are
1261                          * currently bad for the gfp()s.
1262                          */
1263                         if (cachep->gfporder >= slab_break_gfp_order)
1264                                 break;
1265
1266                         if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1267                                 break;  /* Acceptable internal fragmentation. */
1268 next:
1269                         cachep->gfporder++;
1270                 } while (1);
1271         }
1272
1273         if (!cachep->num) {
1274                 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1275                 kmem_cache_free(&cache_cache, cachep);
1276                 cachep = NULL;
1277                 goto opps;
1278         }
1279         slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1280                                 + sizeof(struct slab), align);
1281
1282         /*
1283          * If the slab has been placed off-slab, and we have enough space then
1284          * move it on-slab. This is at the expense of any extra colouring.
1285          */
1286         if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1287                 flags &= ~CFLGS_OFF_SLAB;
1288                 left_over -= slab_size;
1289         }
1290
1291         if (flags & CFLGS_OFF_SLAB) {
1292                 /* really off slab. No need for manual alignment */
1293                 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1294         }
1295
1296         cachep->colour_off = cache_line_size();
1297         /* Offset must be a multiple of the alignment. */
1298         if (cachep->colour_off < align)
1299                 cachep->colour_off = align;
1300         cachep->colour = left_over/cachep->colour_off;
1301         cachep->slab_size = slab_size;
1302         cachep->flags = flags;
1303         cachep->gfpflags = 0;
1304         if (flags & SLAB_CACHE_DMA)
1305                 cachep->gfpflags |= GFP_DMA;
1306         spin_lock_init(&cachep->spinlock);
1307         cachep->objsize = size;
1308         /* NUMA */
1309         INIT_LIST_HEAD(&cachep->lists.slabs_full);
1310         INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1311         INIT_LIST_HEAD(&cachep->lists.slabs_free);
1312
1313         if (flags & CFLGS_OFF_SLAB)
1314                 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1315         cachep->ctor = ctor;
1316         cachep->dtor = dtor;
1317         cachep->name = name;
1318
1319         /* Don't let CPUs to come and go */
1320         lock_cpu_hotplug();
1321
1322         if (g_cpucache_up == FULL) {
1323                 enable_cpucache(cachep);
1324         } else {
1325                 if (g_cpucache_up == NONE) {
1326                         /* Note: the first kmem_cache_create must create
1327                          * the cache that's used by kmalloc(24), otherwise
1328                          * the creation of further caches will BUG().
1329                          */
1330                         cachep->array[smp_processor_id()] = &initarray_generic.cache;
1331                         g_cpucache_up = PARTIAL;
1332                 } else {
1333                         cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1334                 }
1335                 BUG_ON(!ac_data(cachep));
1336                 ac_data(cachep)->avail = 0;
1337                 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1338                 ac_data(cachep)->batchcount = 1;
1339                 ac_data(cachep)->touched = 0;
1340                 cachep->batchcount = 1;
1341                 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1342                 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1343                                         + cachep->num;
1344         } 
1345
1346         cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1347                                         ((unsigned long)cachep)%REAPTIMEOUT_LIST3;
1348
1349         /* Need the semaphore to access the chain. */
1350         down(&cache_chain_sem);
1351         {
1352                 struct list_head *p;
1353                 mm_segment_t old_fs;
1354
1355                 old_fs = get_fs();
1356                 set_fs(KERNEL_DS);
1357                 list_for_each(p, &cache_chain) {
1358                         kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1359                         char tmp;
1360                         /* This happens when the module gets unloaded and doesn't
1361                            destroy its slab cache and noone else reuses the vmalloc
1362                            area of the module. Print a warning. */
1363                         if (__get_user(tmp,pc->name)) { 
1364                                 printk("SLAB: cache with size %d has lost its name\n", 
1365                                         pc->objsize); 
1366                                 continue; 
1367                         }       
1368                         if (!strcmp(pc->name,name)) { 
1369                                 printk("kmem_cache_create: duplicate cache %s\n",name); 
1370                                 up(&cache_chain_sem); 
1371                                 unlock_cpu_hotplug();
1372                                 BUG(); 
1373                         }       
1374                 }
1375                 set_fs(old_fs);
1376         }
1377
1378         /* cache setup completed, link it into the list */
1379         list_add(&cachep->next, &cache_chain);
1380         up(&cache_chain_sem);
1381         unlock_cpu_hotplug();
1382 opps:
1383         return cachep;
1384 }
1385
1386 EXPORT_SYMBOL(kmem_cache_create);
1387
1388 static inline void check_irq_off(void)
1389 {
1390 #if DEBUG
1391         BUG_ON(!irqs_disabled());
1392 #endif
1393 }
1394
1395 static inline void check_irq_on(void)
1396 {
1397 #if DEBUG
1398         BUG_ON(irqs_disabled());
1399 #endif
1400 }
1401
1402 static inline void check_spinlock_acquired(kmem_cache_t *cachep)
1403 {
1404 #ifdef CONFIG_SMP
1405         check_irq_off();
1406         BUG_ON(spin_trylock(&cachep->spinlock));
1407 #endif
1408 }
1409
1410 /*
1411  * Waits for all CPUs to execute func().
1412  */
1413 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1414 {
1415         check_irq_on();
1416         preempt_disable();
1417
1418         local_irq_disable();
1419         func(arg);
1420         local_irq_enable();
1421
1422         if (smp_call_function(func, arg, 1, 1))
1423                 BUG();
1424
1425         preempt_enable();
1426 }
1427
1428 static void drain_array_locked(kmem_cache_t* cachep,
1429                                 struct array_cache *ac, int force);
1430
1431 static void do_drain(void *arg)
1432 {
1433         kmem_cache_t *cachep = (kmem_cache_t*)arg;
1434         struct array_cache *ac;
1435
1436         check_irq_off();
1437         ac = ac_data(cachep);
1438         spin_lock(&cachep->spinlock);
1439         free_block(cachep, &ac_entry(ac)[0], ac->avail);
1440         spin_unlock(&cachep->spinlock);
1441         ac->avail = 0;
1442 }
1443
1444 static void drain_cpu_caches(kmem_cache_t *cachep)
1445 {
1446         smp_call_function_all_cpus(do_drain, cachep);
1447         check_irq_on();
1448         spin_lock_irq(&cachep->spinlock);
1449         if (cachep->lists.shared)
1450                 drain_array_locked(cachep, cachep->lists.shared, 1);
1451         spin_unlock_irq(&cachep->spinlock);
1452 }
1453
1454
1455 /* NUMA shrink all list3s */
1456 static int __cache_shrink(kmem_cache_t *cachep)
1457 {
1458         struct slab *slabp;
1459         int ret;
1460
1461         drain_cpu_caches(cachep);
1462
1463         check_irq_on();
1464         spin_lock_irq(&cachep->spinlock);
1465
1466         for(;;) {
1467                 struct list_head *p;
1468
1469                 p = cachep->lists.slabs_free.prev;
1470                 if (p == &cachep->lists.slabs_free)
1471                         break;
1472
1473                 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1474 #if DEBUG
1475                 if (slabp->inuse)
1476                         BUG();
1477 #endif
1478                 list_del(&slabp->list);
1479
1480                 cachep->lists.free_objects -= cachep->num;
1481                 spin_unlock_irq(&cachep->spinlock);
1482                 slab_destroy(cachep, slabp);
1483                 spin_lock_irq(&cachep->spinlock);
1484         }
1485         ret = !list_empty(&cachep->lists.slabs_full) ||
1486                 !list_empty(&cachep->lists.slabs_partial);
1487         spin_unlock_irq(&cachep->spinlock);
1488         return ret;
1489 }
1490
1491 /**
1492  * kmem_cache_shrink - Shrink a cache.
1493  * @cachep: The cache to shrink.
1494  *
1495  * Releases as many slabs as possible for a cache.
1496  * To help debugging, a zero exit status indicates all slabs were released.
1497  */
1498 int kmem_cache_shrink(kmem_cache_t *cachep)
1499 {
1500         if (!cachep || in_interrupt())
1501                 BUG();
1502
1503         return __cache_shrink(cachep);
1504 }
1505
1506 EXPORT_SYMBOL(kmem_cache_shrink);
1507
1508 /**
1509  * kmem_cache_destroy - delete a cache
1510  * @cachep: the cache to destroy
1511  *
1512  * Remove a kmem_cache_t object from the slab cache.
1513  * Returns 0 on success.
1514  *
1515  * It is expected this function will be called by a module when it is
1516  * unloaded.  This will remove the cache completely, and avoid a duplicate
1517  * cache being allocated each time a module is loaded and unloaded, if the
1518  * module doesn't have persistent in-kernel storage across loads and unloads.
1519  *
1520  * The cache must be empty before calling this function.
1521  *
1522  * The caller must guarantee that noone will allocate memory from the cache
1523  * during the kmem_cache_destroy().
1524  */
1525 int kmem_cache_destroy (kmem_cache_t * cachep)
1526 {
1527         int i;
1528
1529         if (!cachep || in_interrupt())
1530                 BUG();
1531
1532         /* Don't let CPUs to come and go */
1533         lock_cpu_hotplug();
1534
1535         /* Find the cache in the chain of caches. */
1536         down(&cache_chain_sem);
1537         /*
1538          * the chain is never empty, cache_cache is never destroyed
1539          */
1540         list_del(&cachep->next);
1541         up(&cache_chain_sem);
1542
1543         if (__cache_shrink(cachep)) {
1544                 slab_error(cachep, "Can't free all objects");
1545                 down(&cache_chain_sem);
1546                 list_add(&cachep->next,&cache_chain);
1547                 up(&cache_chain_sem);
1548                 unlock_cpu_hotplug();
1549                 return 1;
1550         }
1551
1552         /* no cpu_online check required here since we clear the percpu
1553          * array on cpu offline and set this to NULL.
1554          */
1555         for (i = 0; i < NR_CPUS; i++)
1556                 kfree(cachep->array[i]);
1557
1558         /* NUMA: free the list3 structures */
1559         kfree(cachep->lists.shared);
1560         cachep->lists.shared = NULL;
1561         kmem_cache_free(&cache_cache, cachep);
1562
1563         unlock_cpu_hotplug();
1564
1565         return 0;
1566 }
1567
1568 EXPORT_SYMBOL(kmem_cache_destroy);
1569
1570 /* Get the memory for a slab management obj. */
1571 static inline struct slab* alloc_slabmgmt (kmem_cache_t *cachep,
1572                         void *objp, int colour_off, int local_flags)
1573 {
1574         struct slab *slabp;
1575         
1576         if (OFF_SLAB(cachep)) {
1577                 /* Slab management obj is off-slab. */
1578                 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1579                 if (!slabp)
1580                         return NULL;
1581         } else {
1582                 slabp = objp+colour_off;
1583                 colour_off += cachep->slab_size;
1584         }
1585         slabp->inuse = 0;
1586         slabp->colouroff = colour_off;
1587         slabp->s_mem = objp+colour_off;
1588
1589         return slabp;
1590 }
1591
1592 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1593 {
1594         return (kmem_bufctl_t *)(slabp+1);
1595 }
1596
1597 static void cache_init_objs (kmem_cache_t * cachep,
1598                         struct slab * slabp, unsigned long ctor_flags)
1599 {
1600         int i;
1601
1602         for (i = 0; i < cachep->num; i++) {
1603                 void* objp = slabp->s_mem+cachep->objsize*i;
1604 #if DEBUG
1605                 /* need to poison the objs? */
1606                 if (cachep->flags & SLAB_POISON)
1607                         poison_obj(cachep, objp, POISON_FREE);
1608                 if (cachep->flags & SLAB_STORE_USER)
1609                         *dbg_userword(cachep, objp) = NULL;
1610
1611                 if (cachep->flags & SLAB_RED_ZONE) {
1612                         *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1613                         *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1614                 }
1615                 /*
1616                  * Constructors are not allowed to allocate memory from
1617                  * the same cache which they are a constructor for.
1618                  * Otherwise, deadlock. They must also be threaded.
1619                  */
1620                 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1621                         cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1622
1623                 if (cachep->flags & SLAB_RED_ZONE) {
1624                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1625                                 slab_error(cachep, "constructor overwrote the"
1626                                                         " end of an object");
1627                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1628                                 slab_error(cachep, "constructor overwrote the"
1629                                                         " start of an object");
1630                 }
1631                 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1632                         kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1633 #else
1634                 if (cachep->ctor)
1635                         cachep->ctor(objp, cachep, ctor_flags);
1636 #endif
1637                 slab_bufctl(slabp)[i] = i+1;
1638         }
1639         slab_bufctl(slabp)[i-1] = BUFCTL_END;
1640         slabp->free = 0;
1641 }
1642
1643 static void kmem_flagcheck(kmem_cache_t *cachep, int flags)
1644 {
1645         if (flags & SLAB_DMA) {
1646                 if (!(cachep->gfpflags & GFP_DMA))
1647                         BUG();
1648         } else {
1649                 if (cachep->gfpflags & GFP_DMA)
1650                         BUG();
1651         }
1652 }
1653
1654 /*
1655  * Grow (by 1) the number of slabs within a cache.  This is called by
1656  * kmem_cache_alloc() when there are no active objs left in a cache.
1657  */
1658 static int cache_grow (kmem_cache_t * cachep, int flags)
1659 {
1660         struct slab     *slabp;
1661         struct page     *page;
1662         void            *objp;
1663         size_t           offset;
1664         unsigned int     i, local_flags;
1665         unsigned long    ctor_flags;
1666
1667         /* Be lazy and only check for valid flags here,
1668          * keeping it out of the critical path in kmem_cache_alloc().
1669          */
1670         if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1671                 BUG();
1672         if (flags & SLAB_NO_GROW)
1673                 return 0;
1674
1675         ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1676         local_flags = (flags & SLAB_LEVEL_MASK);
1677         if (!(local_flags & __GFP_WAIT))
1678                 /*
1679                  * Not allowed to sleep.  Need to tell a constructor about
1680                  * this - it might need to know...
1681                  */
1682                 ctor_flags |= SLAB_CTOR_ATOMIC;
1683
1684         /* About to mess with non-constant members - lock. */
1685         check_irq_off();
1686         spin_lock(&cachep->spinlock);
1687
1688         /* Get colour for the slab, and cal the next value. */
1689         offset = cachep->colour_next;
1690         cachep->colour_next++;
1691         if (cachep->colour_next >= cachep->colour)
1692                 cachep->colour_next = 0;
1693         offset *= cachep->colour_off;
1694
1695         spin_unlock(&cachep->spinlock);
1696
1697         if (local_flags & __GFP_WAIT)
1698                 local_irq_enable();
1699
1700         /*
1701          * The test for missing atomic flag is performed here, rather than
1702          * the more obvious place, simply to reduce the critical path length
1703          * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1704          * will eventually be caught here (where it matters).
1705          */
1706         kmem_flagcheck(cachep, flags);
1707
1708
1709         /* Get mem for the objs. */
1710         if (!(objp = kmem_getpages(cachep, flags)))
1711                 goto failed;
1712
1713         /* Get slab management. */
1714         if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1715                 goto opps1;
1716
1717         /* Nasty!!!!!! I hope this is OK. */
1718         i = 1 << cachep->gfporder;
1719         page = virt_to_page(objp);
1720         do {
1721                 SET_PAGE_CACHE(page, cachep);
1722                 SET_PAGE_SLAB(page, slabp);
1723                 page++;
1724         } while (--i);
1725
1726         cache_init_objs(cachep, slabp, ctor_flags);
1727
1728         if (local_flags & __GFP_WAIT)
1729                 local_irq_disable();
1730         check_irq_off();
1731         spin_lock(&cachep->spinlock);
1732
1733         /* Make slab active. */
1734         list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1735         STATS_INC_GROWN(cachep);
1736         list3_data(cachep)->free_objects += cachep->num;
1737         spin_unlock(&cachep->spinlock);
1738         return 1;
1739 opps1:
1740         kmem_freepages(cachep, objp);
1741 failed:
1742         if (local_flags & __GFP_WAIT)
1743                 local_irq_disable();
1744         return 0;
1745 }
1746
1747 /*
1748  * Perform extra freeing checks:
1749  * - detect bad pointers.
1750  * - POISON/RED_ZONE checking
1751  * - destructor calls, for caches with POISON+dtor
1752  */
1753 static inline void kfree_debugcheck(const void *objp)
1754 {
1755 #if DEBUG
1756         struct page *page;
1757
1758         if (!virt_addr_valid(objp)) {
1759                 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1760                         (unsigned long)objp);   
1761                 BUG();  
1762         }
1763         page = virt_to_page(objp);
1764         if (!PageSlab(page)) {
1765                 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1766                 BUG();
1767         }
1768 #endif 
1769 }
1770
1771 static inline void *cache_free_debugcheck (kmem_cache_t * cachep, void * objp, void *caller)
1772 {
1773 #if DEBUG
1774         struct page *page;
1775         unsigned int objnr;
1776         struct slab *slabp;
1777
1778         objp -= obj_dbghead(cachep);
1779         kfree_debugcheck(objp);
1780         page = virt_to_page(objp);
1781
1782         if (GET_PAGE_CACHE(page) != cachep) {
1783                 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1784                                 GET_PAGE_CACHE(page),cachep);
1785                 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1786                 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1787                 WARN_ON(1);
1788         }
1789         slabp = GET_PAGE_SLAB(page);
1790
1791         if (cachep->flags & SLAB_RED_ZONE) {
1792                 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1793                         slab_error(cachep, "double free, or memory outside"
1794                                                 " object was overwritten");
1795                         printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1796                                         objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1797                 }
1798                 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1799                 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1800         }
1801         if (cachep->flags & SLAB_STORE_USER)
1802                 *dbg_userword(cachep, objp) = caller;
1803
1804         objnr = (objp-slabp->s_mem)/cachep->objsize;
1805
1806         BUG_ON(objnr >= cachep->num);
1807         BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1808
1809         if (cachep->flags & SLAB_DEBUG_INITIAL) {
1810                 /* Need to call the slab's constructor so the
1811                  * caller can perform a verify of its state (debugging).
1812                  * Called without the cache-lock held.
1813                  */
1814                 cachep->ctor(objp+obj_dbghead(cachep),
1815                                         cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1816         }
1817         if (cachep->flags & SLAB_POISON && cachep->dtor) {
1818                 /* we want to cache poison the object,
1819                  * call the destruction callback
1820                  */
1821                 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1822         }
1823         if (cachep->flags & SLAB_POISON) {
1824 #ifdef CONFIG_DEBUG_PAGEALLOC
1825                 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1826                         store_stackinfo(cachep, objp, (unsigned long)caller);
1827                         kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1828                 } else {
1829                         poison_obj(cachep, objp, POISON_FREE);
1830                 }
1831 #else
1832                 poison_obj(cachep, objp, POISON_FREE);
1833 #endif
1834         }
1835 #endif
1836         return objp;
1837 }
1838
1839 static inline void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
1840 {
1841 #if DEBUG
1842         int i;
1843         int entries = 0;
1844         
1845         check_spinlock_acquired(cachep);
1846         /* Check slab's freelist to see if this obj is there. */
1847         for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
1848                 entries++;
1849                 if (entries > cachep->num || i < 0 || i >= cachep->num)
1850                         goto bad;
1851         }
1852         if (entries != cachep->num - slabp->inuse) {
1853                 int i;
1854 bad:
1855                 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
1856                                 cachep->name, cachep->num, slabp, slabp->inuse);
1857                 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
1858                         if ((i%16)==0)
1859                                 printk("\n%03x:", i);
1860                         printk(" %02x", ((unsigned char*)slabp)[i]);
1861                 }
1862                 printk("\n");
1863                 BUG();
1864         }
1865 #endif
1866 }
1867
1868 static void* cache_alloc_refill(kmem_cache_t* cachep, int flags)
1869 {
1870         int batchcount;
1871         struct kmem_list3 *l3;
1872         struct array_cache *ac;
1873
1874         check_irq_off();
1875         ac = ac_data(cachep);
1876 retry:
1877         batchcount = ac->batchcount;
1878         if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
1879                 /* if there was little recent activity on this
1880                  * cache, then perform only a partial refill.
1881                  * Otherwise we could generate refill bouncing.
1882                  */
1883                 batchcount = BATCHREFILL_LIMIT;
1884         }
1885         l3 = list3_data(cachep);
1886
1887         BUG_ON(ac->avail > 0);
1888         spin_lock(&cachep->spinlock);
1889         if (l3->shared) {
1890                 struct array_cache *shared_array = l3->shared;
1891                 if (shared_array->avail) {
1892                         if (batchcount > shared_array->avail)
1893                                 batchcount = shared_array->avail;
1894                         shared_array->avail -= batchcount;
1895                         ac->avail = batchcount;
1896                         memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
1897                                         sizeof(void*)*batchcount);
1898                         shared_array->touched = 1;
1899                         goto alloc_done;
1900                 }
1901         }
1902         while (batchcount > 0) {
1903                 struct list_head *entry;
1904                 struct slab *slabp;
1905                 /* Get slab alloc is to come from. */
1906                 entry = l3->slabs_partial.next;
1907                 if (entry == &l3->slabs_partial) {
1908                         l3->free_touched = 1;
1909                         entry = l3->slabs_free.next;
1910                         if (entry == &l3->slabs_free)
1911                                 goto must_grow;
1912                 }
1913
1914                 slabp = list_entry(entry, struct slab, list);
1915                 check_slabp(cachep, slabp);
1916                 check_spinlock_acquired(cachep);
1917                 while (slabp->inuse < cachep->num && batchcount--) {
1918                         kmem_bufctl_t next;
1919                         STATS_INC_ALLOCED(cachep);
1920                         STATS_INC_ACTIVE(cachep);
1921                         STATS_SET_HIGH(cachep);
1922
1923                         /* get obj pointer */
1924                         ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
1925
1926                         slabp->inuse++;
1927                         next = slab_bufctl(slabp)[slabp->free];
1928 #if DEBUG
1929                         slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
1930 #endif
1931                         slabp->free = next;
1932                 }
1933                 check_slabp(cachep, slabp);
1934
1935                 /* move slabp to correct slabp list: */
1936                 list_del(&slabp->list);
1937                 if (slabp->free == BUFCTL_END)
1938                         list_add(&slabp->list, &l3->slabs_full);
1939                 else
1940                         list_add(&slabp->list, &l3->slabs_partial);
1941         }
1942
1943 must_grow:
1944         l3->free_objects -= ac->avail;
1945 alloc_done:
1946         spin_unlock(&cachep->spinlock);
1947
1948         if (unlikely(!ac->avail)) {
1949                 int x;
1950                 x = cache_grow(cachep, flags);
1951                 
1952                 // cache_grow can reenable interrupts, then ac could change.
1953                 ac = ac_data(cachep);
1954                 if (!x && ac->avail == 0)       // no objects in sight? abort
1955                         return NULL;
1956
1957                 if (!ac->avail)         // objects refilled by interrupt?
1958                         goto retry;
1959         }
1960         ac->touched = 1;
1961         return ac_entry(ac)[--ac->avail];
1962 }
1963
1964 static inline void
1965 cache_alloc_debugcheck_before(kmem_cache_t *cachep, int flags)
1966 {
1967         might_sleep_if(flags & __GFP_WAIT);
1968 #if DEBUG
1969         kmem_flagcheck(cachep, flags);
1970 #endif
1971 }
1972
1973 static inline void *
1974 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
1975                         unsigned long flags, void *objp, void *caller)
1976 {
1977 #if DEBUG
1978         if (!objp)      
1979                 return objp;
1980         if (cachep->flags & SLAB_POISON) {
1981 #ifdef CONFIG_DEBUG_PAGEALLOC
1982                 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
1983                         kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
1984                 else
1985                         check_poison_obj(cachep, objp);
1986 #else
1987                 check_poison_obj(cachep, objp);
1988 #endif
1989                 poison_obj(cachep, objp, POISON_INUSE);
1990         }
1991         if (cachep->flags & SLAB_STORE_USER)
1992                 *dbg_userword(cachep, objp) = caller;
1993
1994         if (cachep->flags & SLAB_RED_ZONE) {
1995                 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
1996                         slab_error(cachep, "double free, or memory outside"
1997                                                 " object was overwritten");
1998                         printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1999                                         objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2000                 }
2001                 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2002                 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2003         }
2004         objp += obj_dbghead(cachep);
2005         if (cachep->ctor && cachep->flags & SLAB_POISON) {
2006                 unsigned long   ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2007
2008                 if (!(flags & __GFP_WAIT))
2009                         ctor_flags |= SLAB_CTOR_ATOMIC;
2010
2011                 cachep->ctor(objp, cachep, ctor_flags);
2012         }       
2013 #endif
2014         return objp;
2015 }
2016
2017
2018 static inline void * __cache_alloc (kmem_cache_t *cachep, int flags)
2019 {
2020         unsigned long save_flags;
2021         void* objp;
2022         struct array_cache *ac;
2023
2024         cache_alloc_debugcheck_before(cachep, flags);
2025
2026         local_irq_save(save_flags);
2027         ac = ac_data(cachep);
2028         if (likely(ac->avail)) {
2029                 STATS_INC_ALLOCHIT(cachep);
2030                 ac->touched = 1;
2031                 objp = ac_entry(ac)[--ac->avail];
2032         } else {
2033                 STATS_INC_ALLOCMISS(cachep);
2034                 objp = cache_alloc_refill(cachep, flags);
2035         }
2036         local_irq_restore(save_flags);
2037         objp = cache_alloc_debugcheck_after(cachep, flags, objp, __builtin_return_address(0));
2038         return objp;
2039 }
2040
2041 /* 
2042  * NUMA: different approach needed if the spinlock is moved into
2043  * the l3 structure
2044  */
2045
2046 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2047 {
2048         int i;
2049
2050         check_spinlock_acquired(cachep);
2051
2052         /* NUMA: move add into loop */
2053         cachep->lists.free_objects += nr_objects;
2054
2055         for (i = 0; i < nr_objects; i++) {
2056                 void *objp = objpp[i];
2057                 struct slab *slabp;
2058                 unsigned int objnr;
2059
2060                 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2061                 list_del(&slabp->list);
2062                 objnr = (objp - slabp->s_mem) / cachep->objsize;
2063                 check_slabp(cachep, slabp);
2064 #if DEBUG
2065                 if (slab_bufctl(slabp)[objnr] != BUFCTL_FREE) {
2066                         printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2067                                                 cachep->name, objp);
2068                         BUG();
2069                 }
2070 #endif
2071                 slab_bufctl(slabp)[objnr] = slabp->free;
2072                 slabp->free = objnr;
2073                 STATS_DEC_ACTIVE(cachep);
2074                 slabp->inuse--;
2075                 check_slabp(cachep, slabp);
2076
2077                 /* fixup slab chains */
2078                 if (slabp->inuse == 0) {
2079                         if (cachep->lists.free_objects > cachep->free_limit) {
2080                                 cachep->lists.free_objects -= cachep->num;
2081                                 slab_destroy(cachep, slabp);
2082                         } else {
2083                                 list_add(&slabp->list,
2084                                 &list3_data_ptr(cachep, objp)->slabs_free);
2085                         }
2086                 } else {
2087                         /* Unconditionally move a slab to the end of the
2088                          * partial list on free - maximum time for the
2089                          * other objects to be freed, too.
2090                          */
2091                         list_add_tail(&slabp->list,
2092                                 &list3_data_ptr(cachep, objp)->slabs_partial);
2093                 }
2094         }
2095 }
2096
2097 static void cache_flusharray (kmem_cache_t* cachep, struct array_cache *ac)
2098 {
2099         int batchcount;
2100
2101         batchcount = ac->batchcount;
2102 #if DEBUG
2103         BUG_ON(!batchcount || batchcount > ac->avail);
2104 #endif
2105         check_irq_off();
2106         spin_lock(&cachep->spinlock);
2107         if (cachep->lists.shared) {
2108                 struct array_cache *shared_array = cachep->lists.shared;
2109                 int max = shared_array->limit-shared_array->avail;
2110                 if (max) {
2111                         if (batchcount > max)
2112                                 batchcount = max;
2113                         memcpy(&ac_entry(shared_array)[shared_array->avail],
2114                                         &ac_entry(ac)[0],
2115                                         sizeof(void*)*batchcount);
2116                         shared_array->avail += batchcount;
2117                         goto free_done;
2118                 }
2119         }
2120
2121         free_block(cachep, &ac_entry(ac)[0], batchcount);
2122 free_done:
2123 #if STATS
2124         {
2125                 int i = 0;
2126                 struct list_head *p;
2127
2128                 p = list3_data(cachep)->slabs_free.next;
2129                 while (p != &(list3_data(cachep)->slabs_free)) {
2130                         struct slab *slabp;
2131
2132                         slabp = list_entry(p, struct slab, list);
2133                         BUG_ON(slabp->inuse);
2134
2135                         i++;
2136                         p = p->next;
2137                 }
2138                 STATS_SET_FREEABLE(cachep, i);
2139         }
2140 #endif
2141         spin_unlock(&cachep->spinlock);
2142         ac->avail -= batchcount;
2143         memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2144                         sizeof(void*)*ac->avail);
2145 }
2146
2147 /*
2148  * __cache_free
2149  * Release an obj back to its cache. If the obj has a constructed
2150  * state, it must be in this state _before_ it is released.
2151  *
2152  * Called with disabled ints.
2153  */
2154 static inline void __cache_free (kmem_cache_t *cachep, void* objp)
2155 {
2156         struct array_cache *ac = ac_data(cachep);
2157
2158         check_irq_off();
2159         objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2160
2161         if (likely(ac->avail < ac->limit)) {
2162                 STATS_INC_FREEHIT(cachep);
2163                 ac_entry(ac)[ac->avail++] = objp;
2164                 return;
2165         } else {
2166                 STATS_INC_FREEMISS(cachep);
2167                 cache_flusharray(cachep, ac);
2168                 ac_entry(ac)[ac->avail++] = objp;
2169         }
2170 }
2171
2172 /**
2173  * kmem_cache_alloc - Allocate an object
2174  * @cachep: The cache to allocate from.
2175  * @flags: See kmalloc().
2176  *
2177  * Allocate an object from this cache.  The flags are only relevant
2178  * if the cache has no available objects.
2179  */
2180 void * kmem_cache_alloc (kmem_cache_t *cachep, int flags)
2181 {
2182         return __cache_alloc(cachep, flags);
2183 }
2184
2185 EXPORT_SYMBOL(kmem_cache_alloc);
2186
2187 /**
2188  * kmem_ptr_validate - check if an untrusted pointer might
2189  *      be a slab entry.
2190  * @cachep: the cache we're checking against
2191  * @ptr: pointer to validate
2192  *
2193  * This verifies that the untrusted pointer looks sane:
2194  * it is _not_ a guarantee that the pointer is actually
2195  * part of the slab cache in question, but it at least
2196  * validates that the pointer can be dereferenced and
2197  * looks half-way sane.
2198  *
2199  * Currently only used for dentry validation.
2200  */
2201 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2202 {
2203         unsigned long addr = (unsigned long) ptr;
2204         unsigned long min_addr = PAGE_OFFSET;
2205         unsigned long align_mask = BYTES_PER_WORD-1;
2206         unsigned long size = cachep->objsize;
2207         struct page *page;
2208
2209         if (unlikely(addr < min_addr))
2210                 goto out;
2211         if (unlikely(addr > (unsigned long)high_memory - size))
2212                 goto out;
2213         if (unlikely(addr & align_mask))
2214                 goto out;
2215         if (unlikely(!kern_addr_valid(addr)))
2216                 goto out;
2217         if (unlikely(!kern_addr_valid(addr + size - 1)))
2218                 goto out;
2219         page = virt_to_page(ptr);
2220         if (unlikely(!PageSlab(page)))
2221                 goto out;
2222         if (unlikely(GET_PAGE_CACHE(page) != cachep))
2223                 goto out;
2224         return 1;
2225 out:
2226         return 0;
2227 }
2228
2229 /**
2230  * kmalloc - allocate memory
2231  * @size: how many bytes of memory are required.
2232  * @flags: the type of memory to allocate.
2233  *
2234  * kmalloc is the normal method of allocating memory
2235  * in the kernel.
2236  *
2237  * The @flags argument may be one of:
2238  *
2239  * %GFP_USER - Allocate memory on behalf of user.  May sleep.
2240  *
2241  * %GFP_KERNEL - Allocate normal kernel ram.  May sleep.
2242  *
2243  * %GFP_ATOMIC - Allocation will not sleep.  Use inside interrupt handlers.
2244  *
2245  * Additionally, the %GFP_DMA flag may be set to indicate the memory
2246  * must be suitable for DMA.  This can mean different things on different
2247  * platforms.  For example, on i386, it means that the memory must come
2248  * from the first 16MB.
2249  */
2250 void * __kmalloc (size_t size, int flags)
2251 {
2252         struct cache_sizes *csizep = malloc_sizes;
2253
2254         for (; csizep->cs_size; csizep++) {
2255                 if (size > csizep->cs_size)
2256                         continue;
2257 #if DEBUG
2258                 /* This happens if someone tries to call
2259                  * kmem_cache_create(), or kmalloc(), before
2260                  * the generic caches are initialized.
2261                  */
2262                 BUG_ON(csizep->cs_cachep == NULL);
2263 #endif
2264                 return __cache_alloc(flags & GFP_DMA ?
2265                          csizep->cs_dmacachep : csizep->cs_cachep, flags);
2266         }
2267         return NULL;
2268 }
2269
2270 EXPORT_SYMBOL(__kmalloc);
2271
2272 #ifdef CONFIG_SMP
2273 /**
2274  * __alloc_percpu - allocate one copy of the object for every present
2275  * cpu in the system, zeroing them.
2276  * Objects should be dereferenced using per_cpu_ptr/get_cpu_ptr
2277  * macros only.
2278  *
2279  * @size: how many bytes of memory are required.
2280  * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2281  */
2282 void *__alloc_percpu(size_t size, size_t align)
2283 {
2284         int i;
2285         struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2286
2287         if (!pdata)
2288                 return NULL;
2289
2290         for (i = 0; i < NR_CPUS; i++) {
2291                 if (!cpu_possible(i))
2292                         continue;
2293                 pdata->ptrs[i] = kmalloc(size, GFP_KERNEL);
2294                 if (!pdata->ptrs[i])
2295                         goto unwind_oom;
2296                 memset(pdata->ptrs[i], 0, size);
2297         }
2298
2299         /* Catch derefs w/o wrappers */
2300         return (void *) (~(unsigned long) pdata);
2301
2302 unwind_oom:
2303         while (--i >= 0) {
2304                 if (!cpu_possible(i))
2305                         continue;
2306                 kfree(pdata->ptrs[i]);
2307         }
2308         kfree(pdata);
2309         return NULL;
2310 }
2311
2312 EXPORT_SYMBOL(__alloc_percpu);
2313 #endif
2314
2315 /**
2316  * kmem_cache_free - Deallocate an object
2317  * @cachep: The cache the allocation was from.
2318  * @objp: The previously allocated object.
2319  *
2320  * Free an object which was previously allocated from this
2321  * cache.
2322  */
2323 void kmem_cache_free (kmem_cache_t *cachep, void *objp)
2324 {
2325         unsigned long flags;
2326
2327         local_irq_save(flags);
2328         __cache_free(cachep, objp);
2329         local_irq_restore(flags);
2330 }
2331
2332 EXPORT_SYMBOL(kmem_cache_free);
2333
2334 /**
2335  * kfree - free previously allocated memory
2336  * @objp: pointer returned by kmalloc.
2337  *
2338  * Don't free memory not originally allocated by kmalloc()
2339  * or you will run into trouble.
2340  */
2341 void kfree (const void *objp)
2342 {
2343         kmem_cache_t *c;
2344         unsigned long flags;
2345
2346         if (!objp)
2347                 return;
2348         local_irq_save(flags);
2349         kfree_debugcheck(objp);
2350         c = GET_PAGE_CACHE(virt_to_page(objp));
2351         __cache_free(c, (void*)objp);
2352         local_irq_restore(flags);
2353 }
2354
2355 EXPORT_SYMBOL(kfree);
2356
2357 #ifdef CONFIG_SMP
2358 /**
2359  * free_percpu - free previously allocated percpu memory
2360  * @objp: pointer returned by alloc_percpu.
2361  *
2362  * Don't free memory not originally allocated by alloc_percpu()
2363  * The complemented objp is to check for that.
2364  */
2365 void
2366 free_percpu(const void *objp)
2367 {
2368         int i;
2369         struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2370
2371         for (i = 0; i < NR_CPUS; i++) {
2372                 if (!cpu_possible(i))
2373                         continue;
2374                 kfree(p->ptrs[i]);
2375         }
2376 }
2377
2378 EXPORT_SYMBOL(free_percpu);
2379 #endif
2380
2381 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2382 {
2383         return obj_reallen(cachep);
2384 }
2385
2386 EXPORT_SYMBOL(kmem_cache_size);
2387
2388 kmem_cache_t * kmem_find_general_cachep (size_t size, int gfpflags)
2389 {
2390         struct cache_sizes *csizep = malloc_sizes;
2391
2392         /* This function could be moved to the header file, and
2393          * made inline so consumers can quickly determine what
2394          * cache pointer they require.
2395          */
2396         for ( ; csizep->cs_size; csizep++) {
2397                 if (size > csizep->cs_size)
2398                         continue;
2399                 break;
2400         }
2401         return (gfpflags & GFP_DMA) ? csizep->cs_dmacachep : csizep->cs_cachep;
2402 }
2403
2404 EXPORT_SYMBOL(kmem_find_general_cachep);
2405
2406 struct ccupdate_struct {
2407         kmem_cache_t *cachep;
2408         struct array_cache *new[NR_CPUS];
2409 };
2410
2411 static void do_ccupdate_local(void *info)
2412 {
2413         struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2414         struct array_cache *old;
2415
2416         check_irq_off();
2417         old = ac_data(new->cachep);
2418         
2419         new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2420         new->new[smp_processor_id()] = old;
2421 }
2422
2423
2424 static int do_tune_cpucache (kmem_cache_t* cachep, int limit, int batchcount, int shared)
2425 {
2426         struct ccupdate_struct new;
2427         struct array_cache *new_shared;
2428         int i;
2429
2430         memset(&new.new,0,sizeof(new.new));
2431         for (i = 0; i < NR_CPUS; i++) {
2432                 struct array_cache *ccnew;
2433
2434                 ccnew = kmalloc(sizeof(void*)*limit+
2435                                 sizeof(struct array_cache), GFP_KERNEL);
2436                 if (!ccnew) {
2437                         for (i--; i >= 0; i--) kfree(new.new[i]);
2438                         return -ENOMEM;
2439                 }
2440                 ccnew->avail = 0;
2441                 ccnew->limit = limit;
2442                 ccnew->batchcount = batchcount;
2443                 ccnew->touched = 0;
2444                 new.new[i] = ccnew;
2445         }
2446         new.cachep = cachep;
2447
2448         smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2449         
2450         check_irq_on();
2451         spin_lock_irq(&cachep->spinlock);
2452         cachep->batchcount = batchcount;
2453         cachep->limit = limit;
2454         cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2455         spin_unlock_irq(&cachep->spinlock);
2456
2457         for (i = 0; i < NR_CPUS; i++) {
2458                 struct array_cache *ccold = new.new[i];
2459                 if (!ccold)
2460                         continue;
2461                 spin_lock_irq(&cachep->spinlock);
2462                 free_block(cachep, ac_entry(ccold), ccold->avail);
2463                 spin_unlock_irq(&cachep->spinlock);
2464                 kfree(ccold);
2465         }
2466         new_shared = kmalloc(sizeof(void*)*batchcount*shared+
2467                                 sizeof(struct array_cache), GFP_KERNEL);
2468         if (new_shared) {
2469                 struct array_cache *old;
2470                 new_shared->avail = 0;
2471                 new_shared->limit = batchcount*shared;
2472                 new_shared->batchcount = 0xbaadf00d;
2473                 new_shared->touched = 0;
2474
2475                 spin_lock_irq(&cachep->spinlock);
2476                 old = cachep->lists.shared;
2477                 cachep->lists.shared = new_shared;
2478                 if (old)
2479                         free_block(cachep, ac_entry(old), old->avail);
2480                 spin_unlock_irq(&cachep->spinlock);
2481                 kfree(old);
2482         }
2483
2484         return 0;
2485 }
2486
2487
2488 static void enable_cpucache (kmem_cache_t *cachep)
2489 {
2490         int err;
2491         int limit, shared;
2492
2493         /* The head array serves three purposes:
2494          * - create a LIFO ordering, i.e. return objects that are cache-warm
2495          * - reduce the number of spinlock operations.
2496          * - reduce the number of linked list operations on the slab and 
2497          *   bufctl chains: array operations are cheaper.
2498          * The numbers are guessed, we should auto-tune as described by
2499          * Bonwick.
2500          */
2501         if (cachep->objsize > 131072)
2502                 limit = 1;
2503         else if (cachep->objsize > PAGE_SIZE)
2504                 limit = 8;
2505         else if (cachep->objsize > 1024)
2506                 limit = 24;
2507         else if (cachep->objsize > 256)
2508                 limit = 54;
2509         else
2510                 limit = 120;
2511
2512         /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2513          * allocation behaviour: Most allocs on one cpu, most free operations
2514          * on another cpu. For these cases, an efficient object passing between
2515          * cpus is necessary. This is provided by a shared array. The array
2516          * replaces Bonwick's magazine layer.
2517          * On uniprocessor, it's functionally equivalent (but less efficient)
2518          * to a larger limit. Thus disabled by default.
2519          */
2520         shared = 0;
2521 #ifdef CONFIG_SMP
2522         if (cachep->objsize <= PAGE_SIZE)
2523                 shared = 8;
2524 #endif
2525
2526 #if DEBUG
2527         /* With debugging enabled, large batchcount lead to excessively
2528          * long periods with disabled local interrupts. Limit the 
2529          * batchcount
2530          */
2531         if (limit > 32)
2532                 limit = 32;
2533 #endif
2534         err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2535         if (err)
2536                 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2537                                         cachep->name, -err);
2538 }
2539
2540 static void drain_array(kmem_cache_t *cachep, struct array_cache *ac)
2541 {
2542         int tofree;
2543
2544         check_irq_off();
2545         if (ac->touched) {
2546                 ac->touched = 0;
2547         } else if (ac->avail) {
2548                 tofree = (ac->limit+4)/5;
2549                 if (tofree > ac->avail) {
2550                         tofree = (ac->avail+1)/2;
2551                 }
2552                 spin_lock(&cachep->spinlock);
2553                 free_block(cachep, ac_entry(ac), tofree);
2554                 spin_unlock(&cachep->spinlock);
2555                 ac->avail -= tofree;
2556                 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2557                                         sizeof(void*)*ac->avail);
2558         }
2559 }
2560
2561 static void drain_array_locked(kmem_cache_t *cachep,
2562                                 struct array_cache *ac, int force)
2563 {
2564         int tofree;
2565
2566         check_spinlock_acquired(cachep);
2567         if (ac->touched && !force) {
2568                 ac->touched = 0;
2569         } else if (ac->avail) {
2570                 tofree = force ? ac->avail : (ac->limit+4)/5;
2571                 if (tofree > ac->avail) {
2572                         tofree = (ac->avail+1)/2;
2573                 }
2574                 free_block(cachep, ac_entry(ac), tofree);
2575                 ac->avail -= tofree;
2576                 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2577                                         sizeof(void*)*ac->avail);
2578         }
2579 }
2580
2581 /**
2582  * cache_reap - Reclaim memory from caches.
2583  *
2584  * Called from a timer, every few seconds
2585  * Purpose:
2586  * - clear the per-cpu caches for this CPU.
2587  * - return freeable pages to the main free memory pool.
2588  *
2589  * If we cannot acquire the cache chain semaphore then just give up - we'll
2590  * try again next timer interrupt.
2591  */
2592 static inline void cache_reap (void)
2593 {
2594         struct list_head *walk;
2595
2596 #if DEBUG
2597         BUG_ON(!in_interrupt());
2598         BUG_ON(in_irq());
2599 #endif
2600         if (down_trylock(&cache_chain_sem))
2601                 return;
2602
2603         list_for_each(walk, &cache_chain) {
2604                 kmem_cache_t *searchp;
2605                 struct list_head* p;
2606                 int tofree;
2607                 struct slab *slabp;
2608
2609                 searchp = list_entry(walk, kmem_cache_t, next);
2610
2611                 if (searchp->flags & SLAB_NO_REAP)
2612                         goto next;
2613
2614                 check_irq_on();
2615                 local_irq_disable();
2616                 drain_array(searchp, ac_data(searchp));
2617
2618                 if(time_after(searchp->lists.next_reap, jiffies))
2619                         goto next_irqon;
2620
2621                 spin_lock(&searchp->spinlock);
2622                 if(time_after(searchp->lists.next_reap, jiffies)) {
2623                         goto next_unlock;
2624                 }
2625                 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2626
2627                 if (searchp->lists.shared)
2628                         drain_array_locked(searchp, searchp->lists.shared, 0);
2629
2630                 if (searchp->lists.free_touched) {
2631                         searchp->lists.free_touched = 0;
2632                         goto next_unlock;
2633                 }
2634
2635                 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2636                 do {
2637                         p = list3_data(searchp)->slabs_free.next;
2638                         if (p == &(list3_data(searchp)->slabs_free))
2639                                 break;
2640
2641                         slabp = list_entry(p, struct slab, list);
2642                         BUG_ON(slabp->inuse);
2643                         list_del(&slabp->list);
2644                         STATS_INC_REAPED(searchp);
2645
2646                         /* Safe to drop the lock. The slab is no longer
2647                          * linked to the cache.
2648                          * searchp cannot disappear, we hold
2649                          * cache_chain_lock
2650                          */
2651                         searchp->lists.free_objects -= searchp->num;
2652                         spin_unlock_irq(&searchp->spinlock);
2653                         slab_destroy(searchp, slabp);
2654                         spin_lock_irq(&searchp->spinlock);
2655                 } while(--tofree > 0);
2656 next_unlock:
2657                 spin_unlock(&searchp->spinlock);
2658 next_irqon:
2659                 local_irq_enable();
2660 next:
2661                 ;
2662         }
2663         check_irq_on();
2664         up(&cache_chain_sem);
2665 }
2666
2667 /*
2668  * This is a timer handler.  There is one per CPU.  It is called periodially
2669  * to shrink this CPU's caches.  Otherwise there could be memory tied up
2670  * for long periods (or for ever) due to load changes.
2671  */
2672 static void reap_timer_fnc(unsigned long cpu)
2673 {
2674         struct timer_list *rt = &__get_cpu_var(reap_timers);
2675
2676         /* CPU hotplug can drag us off cpu: don't run on wrong CPU */
2677         if (!cpu_is_offline(cpu)) {
2678                 cache_reap();
2679                 mod_timer(rt, jiffies + REAPTIMEOUT_CPUC + cpu);
2680         }
2681 }
2682
2683 #ifdef CONFIG_PROC_FS
2684
2685 static void *s_start(struct seq_file *m, loff_t *pos)
2686 {
2687         loff_t n = *pos;
2688         struct list_head *p;
2689
2690         down(&cache_chain_sem);
2691         if (!n) {
2692                 /*
2693                  * Output format version, so at least we can change it
2694                  * without _too_ many complaints.
2695                  */
2696 #if STATS
2697                 seq_puts(m, "slabinfo - version: 2.0 (statistics)\n");
2698 #else
2699                 seq_puts(m, "slabinfo - version: 2.0\n");
2700 #endif
2701                 seq_puts(m, "# name            <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2702                 seq_puts(m, " : tunables <batchcount> <limit> <sharedfactor>");
2703                 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
2704 #if STATS
2705                 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <freelimit>");
2706                 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
2707 #endif
2708                 seq_putc(m, '\n');
2709         }
2710         p = cache_chain.next;
2711         while (n--) {
2712                 p = p->next;
2713                 if (p == &cache_chain)
2714                         return NULL;
2715         }
2716         return list_entry(p, kmem_cache_t, next);
2717 }
2718
2719 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2720 {
2721         kmem_cache_t *cachep = p;
2722         ++*pos;
2723         return cachep->next.next == &cache_chain ? NULL
2724                 : list_entry(cachep->next.next, kmem_cache_t, next);
2725 }
2726
2727 static void s_stop(struct seq_file *m, void *p)
2728 {
2729         up(&cache_chain_sem);
2730 }
2731
2732 static int s_show(struct seq_file *m, void *p)
2733 {
2734         kmem_cache_t *cachep = p;
2735         struct list_head *q;
2736         struct slab     *slabp;
2737         unsigned long   active_objs;
2738         unsigned long   num_objs;
2739         unsigned long   active_slabs = 0;
2740         unsigned long   num_slabs;
2741         const char *name; 
2742         char *error = NULL;
2743         mm_segment_t old_fs;
2744         char tmp; 
2745
2746         check_irq_on();
2747         spin_lock_irq(&cachep->spinlock);
2748         active_objs = 0;
2749         num_slabs = 0;
2750         list_for_each(q,&cachep->lists.slabs_full) {
2751                 slabp = list_entry(q, struct slab, list);
2752                 if (slabp->inuse != cachep->num && !error)
2753                         error = "slabs_full accounting error";
2754                 active_objs += cachep->num;
2755                 active_slabs++;
2756         }
2757         list_for_each(q,&cachep->lists.slabs_partial) {
2758                 slabp = list_entry(q, struct slab, list);
2759                 if (slabp->inuse == cachep->num && !error)
2760                         error = "slabs_partial inuse accounting error";
2761                 if (!slabp->inuse && !error)
2762                         error = "slabs_partial/inuse accounting error";
2763                 active_objs += slabp->inuse;
2764                 active_slabs++;
2765         }
2766         list_for_each(q,&cachep->lists.slabs_free) {
2767                 slabp = list_entry(q, struct slab, list);
2768                 if (slabp->inuse && !error)
2769                         error = "slabs_free/inuse accounting error";
2770                 num_slabs++;
2771         }
2772         num_slabs+=active_slabs;
2773         num_objs = num_slabs*cachep->num;
2774         if (num_objs - active_objs != cachep->lists.free_objects && !error)
2775                 error = "free_objects accounting error";
2776
2777         name = cachep->name; 
2778
2779         /*
2780          * Check to see if `name' resides inside a module which has been
2781          * unloaded (someone forgot to destroy their cache)
2782          */
2783         old_fs = get_fs();
2784         set_fs(KERNEL_DS);
2785         if (__get_user(tmp, name)) 
2786                 name = "broken"; 
2787         set_fs(old_fs);
2788
2789         if (error)
2790                 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
2791
2792         seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
2793                 name, active_objs, num_objs, cachep->objsize,
2794                 cachep->num, (1<<cachep->gfporder));
2795         seq_printf(m, " : tunables %4u %4u %4u",
2796                         cachep->limit, cachep->batchcount,
2797                         cachep->lists.shared->limit/cachep->batchcount);
2798         seq_printf(m, " : slabdata %6lu %6lu %6u",
2799                         active_slabs, num_slabs, cachep->lists.shared->avail);
2800 #if STATS
2801         {       /* list3 stats */
2802                 unsigned long high = cachep->high_mark;
2803                 unsigned long allocs = cachep->num_allocations;
2804                 unsigned long grown = cachep->grown;
2805                 unsigned long reaped = cachep->reaped;
2806                 unsigned long errors = cachep->errors;
2807                 unsigned long max_freeable = cachep->max_freeable;
2808                 unsigned long free_limit = cachep->free_limit;
2809
2810                 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu",
2811                                 allocs, high, grown, reaped, errors, 
2812                                 max_freeable, free_limit);
2813         }
2814         /* cpu stats */
2815         {
2816                 unsigned long allochit = atomic_read(&cachep->allochit);
2817                 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
2818                 unsigned long freehit = atomic_read(&cachep->freehit);
2819                 unsigned long freemiss = atomic_read(&cachep->freemiss);
2820
2821                 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
2822                         allochit, allocmiss, freehit, freemiss);
2823         }
2824 #endif
2825         seq_putc(m, '\n');
2826         spin_unlock_irq(&cachep->spinlock);
2827         return 0;
2828 }
2829
2830 /*
2831  * slabinfo_op - iterator that generates /proc/slabinfo
2832  *
2833  * Output layout:
2834  * cache-name
2835  * num-active-objs
2836  * total-objs
2837  * object size
2838  * num-active-slabs
2839  * total-slabs
2840  * num-pages-per-slab
2841  * + further values on SMP and with statistics enabled
2842  */
2843
2844 struct seq_operations slabinfo_op = {
2845         .start  = s_start,
2846         .next   = s_next,
2847         .stop   = s_stop,
2848         .show   = s_show,
2849 };
2850
2851 #define MAX_SLABINFO_WRITE 128
2852 /**
2853  * slabinfo_write - Tuning for the slab allocator
2854  * @file: unused
2855  * @buffer: user buffer
2856  * @count: data length
2857  * @ppos: unused
2858  */
2859 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
2860                                 size_t count, loff_t *ppos)
2861 {
2862         char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
2863         int limit, batchcount, shared, res;
2864         struct list_head *p;
2865         
2866         if (count > MAX_SLABINFO_WRITE)
2867                 return -EINVAL;
2868         if (copy_from_user(&kbuf, buffer, count))
2869                 return -EFAULT;
2870         kbuf[MAX_SLABINFO_WRITE] = '\0'; 
2871
2872         tmp = strchr(kbuf, ' ');
2873         if (!tmp)
2874                 return -EINVAL;
2875         *tmp = '\0';
2876         tmp++;
2877         if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
2878                 return -EINVAL;
2879
2880         /* Find the cache in the chain of caches. */
2881         down(&cache_chain_sem);
2882         res = -EINVAL;
2883         list_for_each(p,&cache_chain) {
2884                 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
2885
2886                 if (!strcmp(cachep->name, kbuf)) {
2887                         if (limit < 1 ||
2888                             batchcount < 1 ||
2889                             batchcount > limit ||
2890                             shared < 0) {
2891                                 res = -EINVAL;
2892                         } else {
2893                                 res = do_tune_cpucache(cachep, limit, batchcount, shared);
2894                         }
2895                         break;
2896                 }
2897         }
2898         up(&cache_chain_sem);
2899         if (res >= 0)
2900                 res = count;
2901         return res;
2902 }
2903 #endif
2904
2905 unsigned int ksize(const void *objp)
2906 {
2907         kmem_cache_t *c;
2908         unsigned long flags;
2909         unsigned int size = 0;
2910
2911         if (likely(objp != NULL)) {
2912                 local_irq_save(flags);
2913                 c = GET_PAGE_CACHE(virt_to_page(objp));
2914                 size = kmem_cache_size(c);
2915                 local_irq_restore(flags);
2916         }
2917
2918         return size;
2919 }
2920
2921 void ptrinfo(unsigned long addr)
2922 {
2923         struct page *page;
2924
2925         printk("Dumping data about address %p.\n", (void*)addr);
2926         if (!virt_addr_valid((void*)addr)) {
2927                 printk("virt addr invalid.\n");
2928                 return;
2929         }
2930 #ifdef CONFIG_MMU
2931         do {
2932                 pgd_t *pgd = pgd_offset_k(addr);
2933                 pmd_t *pmd;
2934                 if (pgd_none(*pgd)) {
2935                         printk("No pgd.\n");
2936                         break;
2937                 }
2938                 pmd = pmd_offset(pgd, addr);
2939                 if (pmd_none(*pmd)) {
2940                         printk("No pmd.\n");
2941                         break;
2942                 }
2943 #ifdef CONFIG_X86
2944                 if (pmd_large(*pmd)) {
2945                         printk("Large page.\n");
2946                         break;
2947                 }
2948 #endif
2949                 printk("normal page, pte_val 0x%llx\n",
2950                   (unsigned long long)pte_val(*pte_offset_kernel(pmd, addr)));
2951         } while(0);
2952 #endif
2953
2954         page = virt_to_page((void*)addr);
2955         printk("struct page at %p, flags %08lx\n",
2956                         page, (unsigned long)page->flags);
2957         if (PageSlab(page)) {
2958                 kmem_cache_t *c;
2959                 struct slab *s;
2960                 unsigned long flags;
2961                 int objnr;
2962                 void *objp;
2963
2964                 c = GET_PAGE_CACHE(page);
2965                 printk("belongs to cache %s.\n",c->name);
2966
2967                 spin_lock_irqsave(&c->spinlock, flags);
2968                 s = GET_PAGE_SLAB(page);
2969                 printk("slabp %p with %d inuse objects (from %d).\n",
2970                         s, s->inuse, c->num);
2971                 check_slabp(c,s);
2972
2973                 objnr = (addr-(unsigned long)s->s_mem)/c->objsize;
2974                 objp = s->s_mem+c->objsize*objnr;
2975                 printk("points into object no %d, starting at %p, len %d.\n",
2976                         objnr, objp, c->objsize);
2977                 if (objnr >= c->num) {
2978                         printk("Bad obj number.\n");
2979                 } else {
2980                         kernel_map_pages(virt_to_page(objp),
2981                                         c->objsize/PAGE_SIZE, 1);
2982
2983                         print_objinfo(c, objp, 2);
2984                 }
2985                 spin_unlock_irqrestore(&c->spinlock, flags);
2986
2987         }
2988 }