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