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