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