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