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