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