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