[PATCH] ide: hotplug mark __devinit sl82c105.c
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / slab.c
blob122d031baab2f957bc73abdac853d4195ba78619
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>
95 #include <linux/string.h>
97 #include <asm/uaccess.h>
98 #include <asm/cacheflush.h>
99 #include <asm/tlbflush.h>
100 #include <asm/page.h>
103 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
104 * SLAB_RED_ZONE & SLAB_POISON.
105 * 0 for faster, smaller code (especially in the critical paths).
107 * STATS - 1 to collect stats for /proc/slabinfo.
108 * 0 for faster, smaller code (especially in the critical paths).
110 * 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
133 * Enforce a minimum alignment for the kmalloc caches.
134 * Usually, the kmalloc caches are cache_line_size() aligned, except when
135 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
136 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
137 * alignment larger than BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
138 * Note that this flag disables some debug features.
140 #define ARCH_KMALLOC_MINALIGN 0
141 #endif
143 #ifndef ARCH_SLAB_MINALIGN
145 * Enforce a minimum alignment for all caches.
146 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
147 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
148 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
149 * some debug features.
151 #define ARCH_SLAB_MINALIGN 0
152 #endif
154 #ifndef ARCH_KMALLOC_FLAGS
155 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
156 #endif
158 /* Legal flag mask for kmem_cache_create(). */
159 #if DEBUG
160 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
161 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
162 SLAB_NO_REAP | SLAB_CACHE_DMA | \
163 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
164 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
165 SLAB_DESTROY_BY_RCU)
166 #else
167 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
168 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
169 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
170 SLAB_DESTROY_BY_RCU)
171 #endif
174 * kmem_bufctl_t:
176 * Bufctl's are used for linking objs within a slab
177 * linked offsets.
179 * This implementation relies on "struct page" for locating the cache &
180 * slab an object belongs to.
181 * This allows the bufctl structure to be small (one int), but limits
182 * the number of objects a slab (not a cache) can contain when off-slab
183 * bufctls are used. The limit is the size of the largest general cache
184 * that does not use off-slab slabs.
185 * For 32bit archs with 4 kB pages, is this 56.
186 * This is not serious, as it is only for large objects, when it is unwise
187 * to have too many per slab.
188 * Note: This limit can be raised by introducing a general cache whose size
189 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
192 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
193 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
194 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-2)
196 /* Max number of objs-per-slab for caches which use off-slab slabs.
197 * Needed to avoid a possible looping condition in cache_grow().
199 static unsigned long offslab_limit;
202 * struct slab
204 * Manages the objs in a slab. Placed either at the beginning of mem allocated
205 * for a slab, or allocated from an general cache.
206 * Slabs are chained into three list: fully used, partial, fully free slabs.
208 struct slab {
209 struct list_head list;
210 unsigned long colouroff;
211 void *s_mem; /* including colour offset */
212 unsigned int inuse; /* num of objs active in slab */
213 kmem_bufctl_t free;
217 * struct slab_rcu
219 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
220 * arrange for kmem_freepages to be called via RCU. This is useful if
221 * we need to approach a kernel structure obliquely, from its address
222 * obtained without the usual locking. We can lock the structure to
223 * stabilize it and check it's still at the given address, only if we
224 * can be sure that the memory has not been meanwhile reused for some
225 * other kind of object (which our subsystem's lock might corrupt).
227 * rcu_read_lock before reading the address, then rcu_read_unlock after
228 * taking the spinlock within the structure expected at that address.
230 * We assume struct slab_rcu can overlay struct slab when destroying.
232 struct slab_rcu {
233 struct rcu_head head;
234 kmem_cache_t *cachep;
235 void *addr;
239 * struct array_cache
241 * Per cpu structures
242 * Purpose:
243 * - LIFO ordering, to hand out cache-warm objects from _alloc
244 * - reduce the number of linked list operations
245 * - reduce spinlock operations
247 * The limit is stored in the per-cpu structure to reduce the data cache
248 * footprint.
251 struct array_cache {
252 unsigned int avail;
253 unsigned int limit;
254 unsigned int batchcount;
255 unsigned int touched;
258 /* bootstrap: The caches do not work without cpuarrays anymore,
259 * but the cpuarrays are allocated from the generic caches...
261 #define BOOT_CPUCACHE_ENTRIES 1
262 struct arraycache_init {
263 struct array_cache cache;
264 void * entries[BOOT_CPUCACHE_ENTRIES];
268 * The slab lists of all objects.
269 * Hopefully reduce the internal fragmentation
270 * NUMA: The spinlock could be moved from the kmem_cache_t
271 * into this structure, too. Figure out what causes
272 * fewer cross-node spinlock operations.
274 struct kmem_list3 {
275 struct list_head slabs_partial; /* partial list first, better asm code */
276 struct list_head slabs_full;
277 struct list_head slabs_free;
278 unsigned long free_objects;
279 int free_touched;
280 unsigned long next_reap;
281 struct array_cache *shared;
284 #define LIST3_INIT(parent) \
286 .slabs_full = LIST_HEAD_INIT(parent.slabs_full), \
287 .slabs_partial = LIST_HEAD_INIT(parent.slabs_partial), \
288 .slabs_free = LIST_HEAD_INIT(parent.slabs_free) \
290 #define list3_data(cachep) \
291 (&(cachep)->lists)
293 /* NUMA: per-node */
294 #define list3_data_ptr(cachep, ptr) \
295 list3_data(cachep)
298 * kmem_cache_t
300 * manages a cache.
303 struct kmem_cache_s {
304 /* 1) per-cpu data, touched during every alloc/free */
305 struct array_cache *array[NR_CPUS];
306 unsigned int batchcount;
307 unsigned int limit;
308 /* 2) touched by every alloc & free from the backend */
309 struct kmem_list3 lists;
310 /* NUMA: kmem_3list_t *nodelists[MAX_NUMNODES] */
311 unsigned int objsize;
312 unsigned int flags; /* constant flags */
313 unsigned int num; /* # of objs per slab */
314 unsigned int free_limit; /* upper limit of objects in the lists */
315 spinlock_t spinlock;
317 /* 3) cache_grow/shrink */
318 /* order of pgs per slab (2^n) */
319 unsigned int gfporder;
321 /* force GFP flags, e.g. GFP_DMA */
322 unsigned int gfpflags;
324 size_t colour; /* cache colouring range */
325 unsigned int colour_off; /* colour offset */
326 unsigned int colour_next; /* cache colouring */
327 kmem_cache_t *slabp_cache;
328 unsigned int slab_size;
329 unsigned int dflags; /* dynamic flags */
331 /* constructor func */
332 void (*ctor)(void *, kmem_cache_t *, unsigned long);
334 /* de-constructor func */
335 void (*dtor)(void *, kmem_cache_t *, unsigned long);
337 /* 4) cache creation/removal */
338 const char *name;
339 struct list_head next;
341 /* 5) statistics */
342 #if STATS
343 unsigned long num_active;
344 unsigned long num_allocations;
345 unsigned long high_mark;
346 unsigned long grown;
347 unsigned long reaped;
348 unsigned long errors;
349 unsigned long max_freeable;
350 unsigned long node_allocs;
351 atomic_t allochit;
352 atomic_t allocmiss;
353 atomic_t freehit;
354 atomic_t freemiss;
355 #endif
356 #if DEBUG
357 int dbghead;
358 int reallen;
359 #endif
362 #define CFLGS_OFF_SLAB (0x80000000UL)
363 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
365 #define BATCHREFILL_LIMIT 16
366 /* Optimization question: fewer reaps means less
367 * probability for unnessary cpucache drain/refill cycles.
369 * OTHO the cpuarrays can contain lots of objects,
370 * which could lock up otherwise freeable slabs.
372 #define REAPTIMEOUT_CPUC (2*HZ)
373 #define REAPTIMEOUT_LIST3 (4*HZ)
375 #if STATS
376 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
377 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
378 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
379 #define STATS_INC_GROWN(x) ((x)->grown++)
380 #define STATS_INC_REAPED(x) ((x)->reaped++)
381 #define STATS_SET_HIGH(x) do { if ((x)->num_active > (x)->high_mark) \
382 (x)->high_mark = (x)->num_active; \
383 } while (0)
384 #define STATS_INC_ERR(x) ((x)->errors++)
385 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
386 #define STATS_SET_FREEABLE(x, i) \
387 do { if ((x)->max_freeable < i) \
388 (x)->max_freeable = i; \
389 } while (0)
391 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
392 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
393 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
394 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
395 #else
396 #define STATS_INC_ACTIVE(x) do { } while (0)
397 #define STATS_DEC_ACTIVE(x) do { } while (0)
398 #define STATS_INC_ALLOCED(x) do { } while (0)
399 #define STATS_INC_GROWN(x) do { } while (0)
400 #define STATS_INC_REAPED(x) do { } while (0)
401 #define STATS_SET_HIGH(x) do { } while (0)
402 #define STATS_INC_ERR(x) do { } while (0)
403 #define STATS_INC_NODEALLOCS(x) do { } while (0)
404 #define STATS_SET_FREEABLE(x, i) \
405 do { } while (0)
407 #define STATS_INC_ALLOCHIT(x) do { } while (0)
408 #define STATS_INC_ALLOCMISS(x) do { } while (0)
409 #define STATS_INC_FREEHIT(x) do { } while (0)
410 #define STATS_INC_FREEMISS(x) do { } while (0)
411 #endif
413 #if DEBUG
414 /* Magic nums for obj red zoning.
415 * Placed in the first word before and the first word after an obj.
417 #define RED_INACTIVE 0x5A2CF071UL /* when obj is inactive */
418 #define RED_ACTIVE 0x170FC2A5UL /* when obj is active */
420 /* ...and for poisoning */
421 #define POISON_INUSE 0x5a /* for use-uninitialised poisoning */
422 #define POISON_FREE 0x6b /* for use-after-free poisoning */
423 #define POISON_END 0xa5 /* end-byte of poisoning */
425 /* memory layout of objects:
426 * 0 : objp
427 * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
428 * the end of an object is aligned with the end of the real
429 * allocation. Catches writes behind the end of the allocation.
430 * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
431 * redzone word.
432 * cachep->dbghead: The real object.
433 * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
434 * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
436 static int obj_dbghead(kmem_cache_t *cachep)
438 return cachep->dbghead;
441 static int obj_reallen(kmem_cache_t *cachep)
443 return cachep->reallen;
446 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
448 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
449 return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
452 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
454 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
455 if (cachep->flags & SLAB_STORE_USER)
456 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
457 return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
460 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
462 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
463 return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
466 #else
468 #define obj_dbghead(x) 0
469 #define obj_reallen(cachep) (cachep->objsize)
470 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
471 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
472 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
474 #endif
477 * Maximum size of an obj (in 2^order pages)
478 * and absolute limit for the gfp order.
480 #if defined(CONFIG_LARGE_ALLOCS)
481 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
482 #define MAX_GFP_ORDER 13 /* up to 32Mb */
483 #elif defined(CONFIG_MMU)
484 #define MAX_OBJ_ORDER 5 /* 32 pages */
485 #define MAX_GFP_ORDER 5 /* 32 pages */
486 #else
487 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
488 #define MAX_GFP_ORDER 8 /* up to 1Mb */
489 #endif
492 * Do not go above this order unless 0 objects fit into the slab.
494 #define BREAK_GFP_ORDER_HI 1
495 #define BREAK_GFP_ORDER_LO 0
496 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
498 /* Macros for storing/retrieving the cachep and or slab from the
499 * global 'mem_map'. These are used to find the slab an obj belongs to.
500 * With kfree(), these are used to find the cache which an obj belongs to.
502 #define SET_PAGE_CACHE(pg,x) ((pg)->lru.next = (struct list_head *)(x))
503 #define GET_PAGE_CACHE(pg) ((kmem_cache_t *)(pg)->lru.next)
504 #define SET_PAGE_SLAB(pg,x) ((pg)->lru.prev = (struct list_head *)(x))
505 #define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->lru.prev)
507 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
508 struct cache_sizes malloc_sizes[] = {
509 #define CACHE(x) { .cs_size = (x) },
510 #include <linux/kmalloc_sizes.h>
511 CACHE(ULONG_MAX)
512 #undef CACHE
514 EXPORT_SYMBOL(malloc_sizes);
516 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
517 struct cache_names {
518 char *name;
519 char *name_dma;
522 static struct cache_names __initdata cache_names[] = {
523 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
524 #include <linux/kmalloc_sizes.h>
525 { NULL, }
526 #undef CACHE
529 static struct arraycache_init initarray_cache __initdata =
530 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
531 static struct arraycache_init initarray_generic =
532 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
534 /* internal cache of cache description objs */
535 static kmem_cache_t cache_cache = {
536 .lists = LIST3_INIT(cache_cache.lists),
537 .batchcount = 1,
538 .limit = BOOT_CPUCACHE_ENTRIES,
539 .objsize = sizeof(kmem_cache_t),
540 .flags = SLAB_NO_REAP,
541 .spinlock = SPIN_LOCK_UNLOCKED,
542 .name = "kmem_cache",
543 #if DEBUG
544 .reallen = sizeof(kmem_cache_t),
545 #endif
548 /* Guard access to the cache-chain. */
549 static struct semaphore cache_chain_sem;
550 static struct list_head cache_chain;
553 * vm_enough_memory() looks at this to determine how many
554 * slab-allocated pages are possibly freeable under pressure
556 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
558 atomic_t slab_reclaim_pages;
559 EXPORT_SYMBOL(slab_reclaim_pages);
562 * chicken and egg problem: delay the per-cpu array allocation
563 * until the general caches are up.
565 static enum {
566 NONE,
567 PARTIAL,
568 FULL
569 } g_cpucache_up;
571 static DEFINE_PER_CPU(struct work_struct, reap_work);
573 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
574 static void enable_cpucache (kmem_cache_t *cachep);
575 static void cache_reap (void *unused);
577 static inline void **ac_entry(struct array_cache *ac)
579 return (void**)(ac+1);
582 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
584 return cachep->array[smp_processor_id()];
587 static inline kmem_cache_t *__find_general_cachep(size_t size, int gfpflags)
589 struct cache_sizes *csizep = malloc_sizes;
591 #if DEBUG
592 /* This happens if someone tries to call
593 * kmem_cache_create(), or __kmalloc(), before
594 * the generic caches are initialized.
596 BUG_ON(csizep->cs_cachep == NULL);
597 #endif
598 while (size > csizep->cs_size)
599 csizep++;
602 * Really subtile: The last entry with cs->cs_size==ULONG_MAX
603 * has cs_{dma,}cachep==NULL. Thus no special case
604 * for large kmalloc calls required.
606 if (unlikely(gfpflags & GFP_DMA))
607 return csizep->cs_dmacachep;
608 return csizep->cs_cachep;
611 kmem_cache_t *kmem_find_general_cachep(size_t size, int gfpflags)
613 return __find_general_cachep(size, gfpflags);
615 EXPORT_SYMBOL(kmem_find_general_cachep);
617 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
618 static void cache_estimate(unsigned long gfporder, size_t size, size_t align,
619 int flags, size_t *left_over, unsigned int *num)
621 int i;
622 size_t wastage = PAGE_SIZE<<gfporder;
623 size_t extra = 0;
624 size_t base = 0;
626 if (!(flags & CFLGS_OFF_SLAB)) {
627 base = sizeof(struct slab);
628 extra = sizeof(kmem_bufctl_t);
630 i = 0;
631 while (i*size + ALIGN(base+i*extra, align) <= wastage)
632 i++;
633 if (i > 0)
634 i--;
636 if (i > SLAB_LIMIT)
637 i = SLAB_LIMIT;
639 *num = i;
640 wastage -= i*size;
641 wastage -= ALIGN(base+i*extra, align);
642 *left_over = wastage;
645 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
647 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
649 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
650 function, cachep->name, msg);
651 dump_stack();
655 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
656 * via the workqueue/eventd.
657 * Add the CPU number into the expiration time to minimize the possibility of
658 * the CPUs getting into lockstep and contending for the global cache chain
659 * lock.
661 static void __devinit start_cpu_timer(int cpu)
663 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
666 * When this gets called from do_initcalls via cpucache_init(),
667 * init_workqueues() has already run, so keventd will be setup
668 * at that time.
670 if (keventd_up() && reap_work->func == NULL) {
671 INIT_WORK(reap_work, cache_reap, NULL);
672 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
676 static struct array_cache *alloc_arraycache(int cpu, int entries,
677 int batchcount)
679 int memsize = sizeof(void*)*entries+sizeof(struct array_cache);
680 struct array_cache *nc = NULL;
682 if (cpu == -1)
683 nc = kmalloc(memsize, GFP_KERNEL);
684 else
685 nc = kmalloc_node(memsize, GFP_KERNEL, cpu_to_node(cpu));
687 if (nc) {
688 nc->avail = 0;
689 nc->limit = entries;
690 nc->batchcount = batchcount;
691 nc->touched = 0;
693 return nc;
696 static int __devinit cpuup_callback(struct notifier_block *nfb,
697 unsigned long action, void *hcpu)
699 long cpu = (long)hcpu;
700 kmem_cache_t* cachep;
702 switch (action) {
703 case CPU_UP_PREPARE:
704 down(&cache_chain_sem);
705 list_for_each_entry(cachep, &cache_chain, next) {
706 struct array_cache *nc;
708 nc = alloc_arraycache(cpu, cachep->limit, cachep->batchcount);
709 if (!nc)
710 goto bad;
712 spin_lock_irq(&cachep->spinlock);
713 cachep->array[cpu] = nc;
714 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
715 + cachep->num;
716 spin_unlock_irq(&cachep->spinlock);
719 up(&cache_chain_sem);
720 break;
721 case CPU_ONLINE:
722 start_cpu_timer(cpu);
723 break;
724 #ifdef CONFIG_HOTPLUG_CPU
725 case CPU_DEAD:
726 /* fall thru */
727 case CPU_UP_CANCELED:
728 down(&cache_chain_sem);
730 list_for_each_entry(cachep, &cache_chain, next) {
731 struct array_cache *nc;
733 spin_lock_irq(&cachep->spinlock);
734 /* cpu is dead; no one can alloc from it. */
735 nc = cachep->array[cpu];
736 cachep->array[cpu] = NULL;
737 cachep->free_limit -= cachep->batchcount;
738 free_block(cachep, ac_entry(nc), nc->avail);
739 spin_unlock_irq(&cachep->spinlock);
740 kfree(nc);
742 up(&cache_chain_sem);
743 break;
744 #endif
746 return NOTIFY_OK;
747 bad:
748 up(&cache_chain_sem);
749 return NOTIFY_BAD;
752 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
754 /* Initialisation.
755 * Called after the gfp() functions have been enabled, and before smp_init().
757 void __init kmem_cache_init(void)
759 size_t left_over;
760 struct cache_sizes *sizes;
761 struct cache_names *names;
764 * Fragmentation resistance on low memory - only use bigger
765 * page orders on machines with more than 32MB of memory.
767 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
768 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
771 /* Bootstrap is tricky, because several objects are allocated
772 * from caches that do not exist yet:
773 * 1) initialize the cache_cache cache: it contains the kmem_cache_t
774 * structures of all caches, except cache_cache itself: cache_cache
775 * is statically allocated.
776 * Initially an __init data area is used for the head array, it's
777 * replaced with a kmalloc allocated array at the end of the bootstrap.
778 * 2) Create the first kmalloc cache.
779 * The kmem_cache_t for the new cache is allocated normally. An __init
780 * data area is used for the head array.
781 * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
782 * 4) Replace the __init data head arrays for cache_cache and the first
783 * kmalloc cache with kmalloc allocated arrays.
784 * 5) Resize the head arrays of the kmalloc caches to their final sizes.
787 /* 1) create the cache_cache */
788 init_MUTEX(&cache_chain_sem);
789 INIT_LIST_HEAD(&cache_chain);
790 list_add(&cache_cache.next, &cache_chain);
791 cache_cache.colour_off = cache_line_size();
792 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
794 cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
796 cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
797 &left_over, &cache_cache.num);
798 if (!cache_cache.num)
799 BUG();
801 cache_cache.colour = left_over/cache_cache.colour_off;
802 cache_cache.colour_next = 0;
803 cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
804 sizeof(struct slab), cache_line_size());
806 /* 2+3) create the kmalloc caches */
807 sizes = malloc_sizes;
808 names = cache_names;
810 while (sizes->cs_size != ULONG_MAX) {
811 /* For performance, all the general caches are L1 aligned.
812 * This should be particularly beneficial on SMP boxes, as it
813 * eliminates "false sharing".
814 * Note for systems short on memory removing the alignment will
815 * allow tighter packing of the smaller caches. */
816 sizes->cs_cachep = kmem_cache_create(names->name,
817 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
818 (ARCH_KMALLOC_FLAGS | SLAB_PANIC), NULL, NULL);
820 /* Inc off-slab bufctl limit until the ceiling is hit. */
821 if (!(OFF_SLAB(sizes->cs_cachep))) {
822 offslab_limit = sizes->cs_size-sizeof(struct slab);
823 offslab_limit /= sizeof(kmem_bufctl_t);
826 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
827 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
828 (ARCH_KMALLOC_FLAGS | SLAB_CACHE_DMA | SLAB_PANIC),
829 NULL, NULL);
831 sizes++;
832 names++;
834 /* 4) Replace the bootstrap head arrays */
836 void * ptr;
838 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
839 local_irq_disable();
840 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
841 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
842 cache_cache.array[smp_processor_id()] = ptr;
843 local_irq_enable();
845 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
846 local_irq_disable();
847 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
848 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
849 sizeof(struct arraycache_init));
850 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
851 local_irq_enable();
854 /* 5) resize the head arrays to their final sizes */
856 kmem_cache_t *cachep;
857 down(&cache_chain_sem);
858 list_for_each_entry(cachep, &cache_chain, next)
859 enable_cpucache(cachep);
860 up(&cache_chain_sem);
863 /* Done! */
864 g_cpucache_up = FULL;
866 /* Register a cpu startup notifier callback
867 * that initializes ac_data for all new cpus
869 register_cpu_notifier(&cpucache_notifier);
872 /* The reap timers are started later, with a module init call:
873 * That part of the kernel is not yet operational.
877 static int __init cpucache_init(void)
879 int cpu;
882 * Register the timers that return unneeded
883 * pages to gfp.
885 for (cpu = 0; cpu < NR_CPUS; cpu++) {
886 if (cpu_online(cpu))
887 start_cpu_timer(cpu);
890 return 0;
893 __initcall(cpucache_init);
896 * Interface to system's page allocator. No need to hold the cache-lock.
898 * If we requested dmaable memory, we will get it. Even if we
899 * did not request dmaable memory, we might get it, but that
900 * would be relatively rare and ignorable.
902 static void *kmem_getpages(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
904 struct page *page;
905 void *addr;
906 int i;
908 flags |= cachep->gfpflags;
909 if (likely(nodeid == -1)) {
910 page = alloc_pages(flags, cachep->gfporder);
911 } else {
912 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
914 if (!page)
915 return NULL;
916 addr = page_address(page);
918 i = (1 << cachep->gfporder);
919 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
920 atomic_add(i, &slab_reclaim_pages);
921 add_page_state(nr_slab, i);
922 while (i--) {
923 SetPageSlab(page);
924 page++;
926 return addr;
930 * Interface to system's page release.
932 static void kmem_freepages(kmem_cache_t *cachep, void *addr)
934 unsigned long i = (1<<cachep->gfporder);
935 struct page *page = virt_to_page(addr);
936 const unsigned long nr_freed = i;
938 while (i--) {
939 if (!TestClearPageSlab(page))
940 BUG();
941 page++;
943 sub_page_state(nr_slab, nr_freed);
944 if (current->reclaim_state)
945 current->reclaim_state->reclaimed_slab += nr_freed;
946 free_pages((unsigned long)addr, cachep->gfporder);
947 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
948 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
951 static void kmem_rcu_free(struct rcu_head *head)
953 struct slab_rcu *slab_rcu = (struct slab_rcu *) head;
954 kmem_cache_t *cachep = slab_rcu->cachep;
956 kmem_freepages(cachep, slab_rcu->addr);
957 if (OFF_SLAB(cachep))
958 kmem_cache_free(cachep->slabp_cache, slab_rcu);
961 #if DEBUG
963 #ifdef CONFIG_DEBUG_PAGEALLOC
964 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr,
965 unsigned long caller)
967 int size = obj_reallen(cachep);
969 addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
971 if (size < 5*sizeof(unsigned long))
972 return;
974 *addr++=0x12345678;
975 *addr++=caller;
976 *addr++=smp_processor_id();
977 size -= 3*sizeof(unsigned long);
979 unsigned long *sptr = &caller;
980 unsigned long svalue;
982 while (!kstack_end(sptr)) {
983 svalue = *sptr++;
984 if (kernel_text_address(svalue)) {
985 *addr++=svalue;
986 size -= sizeof(unsigned long);
987 if (size <= sizeof(unsigned long))
988 break;
993 *addr++=0x87654321;
995 #endif
997 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
999 int size = obj_reallen(cachep);
1000 addr = &((char*)addr)[obj_dbghead(cachep)];
1002 memset(addr, val, size);
1003 *(unsigned char *)(addr+size-1) = POISON_END;
1006 static void dump_line(char *data, int offset, int limit)
1008 int i;
1009 printk(KERN_ERR "%03x:", offset);
1010 for (i=0;i<limit;i++) {
1011 printk(" %02x", (unsigned char)data[offset+i]);
1013 printk("\n");
1015 #endif
1017 #if DEBUG
1019 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
1021 int i, size;
1022 char *realobj;
1024 if (cachep->flags & SLAB_RED_ZONE) {
1025 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1026 *dbg_redzone1(cachep, objp),
1027 *dbg_redzone2(cachep, objp));
1030 if (cachep->flags & SLAB_STORE_USER) {
1031 printk(KERN_ERR "Last user: [<%p>]",
1032 *dbg_userword(cachep, objp));
1033 print_symbol("(%s)",
1034 (unsigned long)*dbg_userword(cachep, objp));
1035 printk("\n");
1037 realobj = (char*)objp+obj_dbghead(cachep);
1038 size = obj_reallen(cachep);
1039 for (i=0; i<size && lines;i+=16, lines--) {
1040 int limit;
1041 limit = 16;
1042 if (i+limit > size)
1043 limit = size-i;
1044 dump_line(realobj, i, limit);
1048 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
1050 char *realobj;
1051 int size, i;
1052 int lines = 0;
1054 realobj = (char*)objp+obj_dbghead(cachep);
1055 size = obj_reallen(cachep);
1057 for (i=0;i<size;i++) {
1058 char exp = POISON_FREE;
1059 if (i == size-1)
1060 exp = POISON_END;
1061 if (realobj[i] != exp) {
1062 int limit;
1063 /* Mismatch ! */
1064 /* Print header */
1065 if (lines == 0) {
1066 printk(KERN_ERR "Slab corruption: start=%p, len=%d\n",
1067 realobj, size);
1068 print_objinfo(cachep, objp, 0);
1070 /* Hexdump the affected line */
1071 i = (i/16)*16;
1072 limit = 16;
1073 if (i+limit > size)
1074 limit = size-i;
1075 dump_line(realobj, i, limit);
1076 i += 16;
1077 lines++;
1078 /* Limit to 5 lines */
1079 if (lines > 5)
1080 break;
1083 if (lines != 0) {
1084 /* Print some data about the neighboring objects, if they
1085 * exist:
1087 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1088 int objnr;
1090 objnr = (objp-slabp->s_mem)/cachep->objsize;
1091 if (objnr) {
1092 objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1093 realobj = (char*)objp+obj_dbghead(cachep);
1094 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1095 realobj, size);
1096 print_objinfo(cachep, objp, 2);
1098 if (objnr+1 < cachep->num) {
1099 objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1100 realobj = (char*)objp+obj_dbghead(cachep);
1101 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1102 realobj, size);
1103 print_objinfo(cachep, objp, 2);
1107 #endif
1109 /* Destroy all the objs in a slab, and release the mem back to the system.
1110 * Before calling the slab must have been unlinked from the cache.
1111 * The cache-lock is not held/needed.
1113 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1115 void *addr = slabp->s_mem - slabp->colouroff;
1117 #if DEBUG
1118 int i;
1119 for (i = 0; i < cachep->num; i++) {
1120 void *objp = slabp->s_mem + cachep->objsize * i;
1122 if (cachep->flags & SLAB_POISON) {
1123 #ifdef CONFIG_DEBUG_PAGEALLOC
1124 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1125 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1126 else
1127 check_poison_obj(cachep, objp);
1128 #else
1129 check_poison_obj(cachep, objp);
1130 #endif
1132 if (cachep->flags & SLAB_RED_ZONE) {
1133 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1134 slab_error(cachep, "start of a freed object "
1135 "was overwritten");
1136 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1137 slab_error(cachep, "end of a freed object "
1138 "was overwritten");
1140 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1141 (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1143 #else
1144 if (cachep->dtor) {
1145 int i;
1146 for (i = 0; i < cachep->num; i++) {
1147 void* objp = slabp->s_mem+cachep->objsize*i;
1148 (cachep->dtor)(objp, cachep, 0);
1151 #endif
1153 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1154 struct slab_rcu *slab_rcu;
1156 slab_rcu = (struct slab_rcu *) slabp;
1157 slab_rcu->cachep = cachep;
1158 slab_rcu->addr = addr;
1159 call_rcu(&slab_rcu->head, kmem_rcu_free);
1160 } else {
1161 kmem_freepages(cachep, addr);
1162 if (OFF_SLAB(cachep))
1163 kmem_cache_free(cachep->slabp_cache, slabp);
1168 * kmem_cache_create - Create a cache.
1169 * @name: A string which is used in /proc/slabinfo to identify this cache.
1170 * @size: The size of objects to be created in this cache.
1171 * @align: The required alignment for the objects.
1172 * @flags: SLAB flags
1173 * @ctor: A constructor for the objects.
1174 * @dtor: A destructor for the objects.
1176 * Returns a ptr to the cache on success, NULL on failure.
1177 * Cannot be called within a int, but can be interrupted.
1178 * The @ctor is run when new pages are allocated by the cache
1179 * and the @dtor is run before the pages are handed back.
1181 * @name must be valid until the cache is destroyed. This implies that
1182 * the module calling this has to destroy the cache before getting
1183 * unloaded.
1185 * The flags are
1187 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1188 * to catch references to uninitialised memory.
1190 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1191 * for buffer overruns.
1193 * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1194 * memory pressure.
1196 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1197 * cacheline. This can be beneficial if you're counting cycles as closely
1198 * as davem.
1200 kmem_cache_t *
1201 kmem_cache_create (const char *name, size_t size, size_t align,
1202 unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1203 void (*dtor)(void*, kmem_cache_t *, unsigned long))
1205 size_t left_over, slab_size, ralign;
1206 kmem_cache_t *cachep = NULL;
1209 * Sanity checks... these are all serious usage bugs.
1211 if ((!name) ||
1212 in_interrupt() ||
1213 (size < BYTES_PER_WORD) ||
1214 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1215 (dtor && !ctor)) {
1216 printk(KERN_ERR "%s: Early error in slab %s\n",
1217 __FUNCTION__, name);
1218 BUG();
1221 #if DEBUG
1222 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
1223 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1224 /* No constructor, but inital state check requested */
1225 printk(KERN_ERR "%s: No con, but init state check "
1226 "requested - %s\n", __FUNCTION__, name);
1227 flags &= ~SLAB_DEBUG_INITIAL;
1230 #if FORCED_DEBUG
1232 * Enable redzoning and last user accounting, except for caches with
1233 * large objects, if the increased size would increase the object size
1234 * above the next power of two: caches with object sizes just above a
1235 * power of two have a significant amount of internal fragmentation.
1237 if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1238 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1239 if (!(flags & SLAB_DESTROY_BY_RCU))
1240 flags |= SLAB_POISON;
1241 #endif
1242 if (flags & SLAB_DESTROY_BY_RCU)
1243 BUG_ON(flags & SLAB_POISON);
1244 #endif
1245 if (flags & SLAB_DESTROY_BY_RCU)
1246 BUG_ON(dtor);
1249 * Always checks flags, a caller might be expecting debug
1250 * support which isn't available.
1252 if (flags & ~CREATE_MASK)
1253 BUG();
1255 /* Check that size is in terms of words. This is needed to avoid
1256 * unaligned accesses for some archs when redzoning is used, and makes
1257 * sure any on-slab bufctl's are also correctly aligned.
1259 if (size & (BYTES_PER_WORD-1)) {
1260 size += (BYTES_PER_WORD-1);
1261 size &= ~(BYTES_PER_WORD-1);
1264 /* calculate out the final buffer alignment: */
1265 /* 1) arch recommendation: can be overridden for debug */
1266 if (flags & SLAB_HWCACHE_ALIGN) {
1267 /* Default alignment: as specified by the arch code.
1268 * Except if an object is really small, then squeeze multiple
1269 * objects into one cacheline.
1271 ralign = cache_line_size();
1272 while (size <= ralign/2)
1273 ralign /= 2;
1274 } else {
1275 ralign = BYTES_PER_WORD;
1277 /* 2) arch mandated alignment: disables debug if necessary */
1278 if (ralign < ARCH_SLAB_MINALIGN) {
1279 ralign = ARCH_SLAB_MINALIGN;
1280 if (ralign > BYTES_PER_WORD)
1281 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1283 /* 3) caller mandated alignment: disables debug if necessary */
1284 if (ralign < align) {
1285 ralign = align;
1286 if (ralign > BYTES_PER_WORD)
1287 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1289 /* 4) Store it. Note that the debug code below can reduce
1290 * the alignment to BYTES_PER_WORD.
1292 align = ralign;
1294 /* Get cache's description obj. */
1295 cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1296 if (!cachep)
1297 goto opps;
1298 memset(cachep, 0, sizeof(kmem_cache_t));
1300 #if DEBUG
1301 cachep->reallen = size;
1303 if (flags & SLAB_RED_ZONE) {
1304 /* redzoning only works with word aligned caches */
1305 align = BYTES_PER_WORD;
1307 /* add space for red zone words */
1308 cachep->dbghead += BYTES_PER_WORD;
1309 size += 2*BYTES_PER_WORD;
1311 if (flags & SLAB_STORE_USER) {
1312 /* user store requires word alignment and
1313 * one word storage behind the end of the real
1314 * object.
1316 align = BYTES_PER_WORD;
1317 size += BYTES_PER_WORD;
1319 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1320 if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1321 cachep->dbghead += PAGE_SIZE - size;
1322 size = PAGE_SIZE;
1324 #endif
1325 #endif
1327 /* Determine if the slab management is 'on' or 'off' slab. */
1328 if (size >= (PAGE_SIZE>>3))
1330 * Size is large, assume best to place the slab management obj
1331 * off-slab (should allow better packing of objs).
1333 flags |= CFLGS_OFF_SLAB;
1335 size = ALIGN(size, align);
1337 if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1339 * A VFS-reclaimable slab tends to have most allocations
1340 * as GFP_NOFS and we really don't want to have to be allocating
1341 * higher-order pages when we are unable to shrink dcache.
1343 cachep->gfporder = 0;
1344 cache_estimate(cachep->gfporder, size, align, flags,
1345 &left_over, &cachep->num);
1346 } else {
1348 * Calculate size (in pages) of slabs, and the num of objs per
1349 * slab. This could be made much more intelligent. For now,
1350 * try to avoid using high page-orders for slabs. When the
1351 * gfp() funcs are more friendly towards high-order requests,
1352 * this should be changed.
1354 do {
1355 unsigned int break_flag = 0;
1356 cal_wastage:
1357 cache_estimate(cachep->gfporder, size, align, flags,
1358 &left_over, &cachep->num);
1359 if (break_flag)
1360 break;
1361 if (cachep->gfporder >= MAX_GFP_ORDER)
1362 break;
1363 if (!cachep->num)
1364 goto next;
1365 if (flags & CFLGS_OFF_SLAB &&
1366 cachep->num > offslab_limit) {
1367 /* This num of objs will cause problems. */
1368 cachep->gfporder--;
1369 break_flag++;
1370 goto cal_wastage;
1374 * Large num of objs is good, but v. large slabs are
1375 * currently bad for the gfp()s.
1377 if (cachep->gfporder >= slab_break_gfp_order)
1378 break;
1380 if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1381 break; /* Acceptable internal fragmentation. */
1382 next:
1383 cachep->gfporder++;
1384 } while (1);
1387 if (!cachep->num) {
1388 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1389 kmem_cache_free(&cache_cache, cachep);
1390 cachep = NULL;
1391 goto opps;
1393 slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1394 + sizeof(struct slab), align);
1397 * If the slab has been placed off-slab, and we have enough space then
1398 * move it on-slab. This is at the expense of any extra colouring.
1400 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1401 flags &= ~CFLGS_OFF_SLAB;
1402 left_over -= slab_size;
1405 if (flags & CFLGS_OFF_SLAB) {
1406 /* really off slab. No need for manual alignment */
1407 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1410 cachep->colour_off = cache_line_size();
1411 /* Offset must be a multiple of the alignment. */
1412 if (cachep->colour_off < align)
1413 cachep->colour_off = align;
1414 cachep->colour = left_over/cachep->colour_off;
1415 cachep->slab_size = slab_size;
1416 cachep->flags = flags;
1417 cachep->gfpflags = 0;
1418 if (flags & SLAB_CACHE_DMA)
1419 cachep->gfpflags |= GFP_DMA;
1420 spin_lock_init(&cachep->spinlock);
1421 cachep->objsize = size;
1422 /* NUMA */
1423 INIT_LIST_HEAD(&cachep->lists.slabs_full);
1424 INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1425 INIT_LIST_HEAD(&cachep->lists.slabs_free);
1427 if (flags & CFLGS_OFF_SLAB)
1428 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1429 cachep->ctor = ctor;
1430 cachep->dtor = dtor;
1431 cachep->name = name;
1433 /* Don't let CPUs to come and go */
1434 lock_cpu_hotplug();
1436 if (g_cpucache_up == FULL) {
1437 enable_cpucache(cachep);
1438 } else {
1439 if (g_cpucache_up == NONE) {
1440 /* Note: the first kmem_cache_create must create
1441 * the cache that's used by kmalloc(24), otherwise
1442 * the creation of further caches will BUG().
1444 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1445 g_cpucache_up = PARTIAL;
1446 } else {
1447 cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1449 BUG_ON(!ac_data(cachep));
1450 ac_data(cachep)->avail = 0;
1451 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1452 ac_data(cachep)->batchcount = 1;
1453 ac_data(cachep)->touched = 0;
1454 cachep->batchcount = 1;
1455 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1456 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1457 + cachep->num;
1460 cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1461 ((unsigned long)cachep)%REAPTIMEOUT_LIST3;
1463 /* Need the semaphore to access the chain. */
1464 down(&cache_chain_sem);
1466 struct list_head *p;
1467 mm_segment_t old_fs;
1469 old_fs = get_fs();
1470 set_fs(KERNEL_DS);
1471 list_for_each(p, &cache_chain) {
1472 kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1473 char tmp;
1474 /* This happens when the module gets unloaded and doesn't
1475 destroy its slab cache and noone else reuses the vmalloc
1476 area of the module. Print a warning. */
1477 if (__get_user(tmp,pc->name)) {
1478 printk("SLAB: cache with size %d has lost its name\n",
1479 pc->objsize);
1480 continue;
1482 if (!strcmp(pc->name,name)) {
1483 printk("kmem_cache_create: duplicate cache %s\n",name);
1484 up(&cache_chain_sem);
1485 unlock_cpu_hotplug();
1486 BUG();
1489 set_fs(old_fs);
1492 /* cache setup completed, link it into the list */
1493 list_add(&cachep->next, &cache_chain);
1494 up(&cache_chain_sem);
1495 unlock_cpu_hotplug();
1496 opps:
1497 if (!cachep && (flags & SLAB_PANIC))
1498 panic("kmem_cache_create(): failed to create slab `%s'\n",
1499 name);
1500 return cachep;
1502 EXPORT_SYMBOL(kmem_cache_create);
1504 #if DEBUG
1505 static void check_irq_off(void)
1507 BUG_ON(!irqs_disabled());
1510 static void check_irq_on(void)
1512 BUG_ON(irqs_disabled());
1515 static void check_spinlock_acquired(kmem_cache_t *cachep)
1517 #ifdef CONFIG_SMP
1518 check_irq_off();
1519 BUG_ON(spin_trylock(&cachep->spinlock));
1520 #endif
1522 #else
1523 #define check_irq_off() do { } while(0)
1524 #define check_irq_on() do { } while(0)
1525 #define check_spinlock_acquired(x) do { } while(0)
1526 #endif
1529 * Waits for all CPUs to execute func().
1531 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1533 check_irq_on();
1534 preempt_disable();
1536 local_irq_disable();
1537 func(arg);
1538 local_irq_enable();
1540 if (smp_call_function(func, arg, 1, 1))
1541 BUG();
1543 preempt_enable();
1546 static void drain_array_locked(kmem_cache_t* cachep,
1547 struct array_cache *ac, int force);
1549 static void do_drain(void *arg)
1551 kmem_cache_t *cachep = (kmem_cache_t*)arg;
1552 struct array_cache *ac;
1554 check_irq_off();
1555 ac = ac_data(cachep);
1556 spin_lock(&cachep->spinlock);
1557 free_block(cachep, &ac_entry(ac)[0], ac->avail);
1558 spin_unlock(&cachep->spinlock);
1559 ac->avail = 0;
1562 static void drain_cpu_caches(kmem_cache_t *cachep)
1564 smp_call_function_all_cpus(do_drain, cachep);
1565 check_irq_on();
1566 spin_lock_irq(&cachep->spinlock);
1567 if (cachep->lists.shared)
1568 drain_array_locked(cachep, cachep->lists.shared, 1);
1569 spin_unlock_irq(&cachep->spinlock);
1573 /* NUMA shrink all list3s */
1574 static int __cache_shrink(kmem_cache_t *cachep)
1576 struct slab *slabp;
1577 int ret;
1579 drain_cpu_caches(cachep);
1581 check_irq_on();
1582 spin_lock_irq(&cachep->spinlock);
1584 for(;;) {
1585 struct list_head *p;
1587 p = cachep->lists.slabs_free.prev;
1588 if (p == &cachep->lists.slabs_free)
1589 break;
1591 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1592 #if DEBUG
1593 if (slabp->inuse)
1594 BUG();
1595 #endif
1596 list_del(&slabp->list);
1598 cachep->lists.free_objects -= cachep->num;
1599 spin_unlock_irq(&cachep->spinlock);
1600 slab_destroy(cachep, slabp);
1601 spin_lock_irq(&cachep->spinlock);
1603 ret = !list_empty(&cachep->lists.slabs_full) ||
1604 !list_empty(&cachep->lists.slabs_partial);
1605 spin_unlock_irq(&cachep->spinlock);
1606 return ret;
1610 * kmem_cache_shrink - Shrink a cache.
1611 * @cachep: The cache to shrink.
1613 * Releases as many slabs as possible for a cache.
1614 * To help debugging, a zero exit status indicates all slabs were released.
1616 int kmem_cache_shrink(kmem_cache_t *cachep)
1618 if (!cachep || in_interrupt())
1619 BUG();
1621 return __cache_shrink(cachep);
1623 EXPORT_SYMBOL(kmem_cache_shrink);
1626 * kmem_cache_destroy - delete a cache
1627 * @cachep: the cache to destroy
1629 * Remove a kmem_cache_t object from the slab cache.
1630 * Returns 0 on success.
1632 * It is expected this function will be called by a module when it is
1633 * unloaded. This will remove the cache completely, and avoid a duplicate
1634 * cache being allocated each time a module is loaded and unloaded, if the
1635 * module doesn't have persistent in-kernel storage across loads and unloads.
1637 * The cache must be empty before calling this function.
1639 * The caller must guarantee that noone will allocate memory from the cache
1640 * during the kmem_cache_destroy().
1642 int kmem_cache_destroy(kmem_cache_t * cachep)
1644 int i;
1646 if (!cachep || in_interrupt())
1647 BUG();
1649 /* Don't let CPUs to come and go */
1650 lock_cpu_hotplug();
1652 /* Find the cache in the chain of caches. */
1653 down(&cache_chain_sem);
1655 * the chain is never empty, cache_cache is never destroyed
1657 list_del(&cachep->next);
1658 up(&cache_chain_sem);
1660 if (__cache_shrink(cachep)) {
1661 slab_error(cachep, "Can't free all objects");
1662 down(&cache_chain_sem);
1663 list_add(&cachep->next,&cache_chain);
1664 up(&cache_chain_sem);
1665 unlock_cpu_hotplug();
1666 return 1;
1669 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1670 synchronize_rcu();
1672 /* no cpu_online check required here since we clear the percpu
1673 * array on cpu offline and set this to NULL.
1675 for (i = 0; i < NR_CPUS; i++)
1676 kfree(cachep->array[i]);
1678 /* NUMA: free the list3 structures */
1679 kfree(cachep->lists.shared);
1680 cachep->lists.shared = NULL;
1681 kmem_cache_free(&cache_cache, cachep);
1683 unlock_cpu_hotplug();
1685 return 0;
1687 EXPORT_SYMBOL(kmem_cache_destroy);
1689 /* Get the memory for a slab management obj. */
1690 static struct slab* alloc_slabmgmt(kmem_cache_t *cachep,
1691 void *objp, int colour_off, unsigned int __nocast local_flags)
1693 struct slab *slabp;
1695 if (OFF_SLAB(cachep)) {
1696 /* Slab management obj is off-slab. */
1697 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1698 if (!slabp)
1699 return NULL;
1700 } else {
1701 slabp = objp+colour_off;
1702 colour_off += cachep->slab_size;
1704 slabp->inuse = 0;
1705 slabp->colouroff = colour_off;
1706 slabp->s_mem = objp+colour_off;
1708 return slabp;
1711 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1713 return (kmem_bufctl_t *)(slabp+1);
1716 static void cache_init_objs(kmem_cache_t *cachep,
1717 struct slab *slabp, unsigned long ctor_flags)
1719 int i;
1721 for (i = 0; i < cachep->num; i++) {
1722 void* objp = slabp->s_mem+cachep->objsize*i;
1723 #if DEBUG
1724 /* need to poison the objs? */
1725 if (cachep->flags & SLAB_POISON)
1726 poison_obj(cachep, objp, POISON_FREE);
1727 if (cachep->flags & SLAB_STORE_USER)
1728 *dbg_userword(cachep, objp) = NULL;
1730 if (cachep->flags & SLAB_RED_ZONE) {
1731 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1732 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1735 * Constructors are not allowed to allocate memory from
1736 * the same cache which they are a constructor for.
1737 * Otherwise, deadlock. They must also be threaded.
1739 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1740 cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1742 if (cachep->flags & SLAB_RED_ZONE) {
1743 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1744 slab_error(cachep, "constructor overwrote the"
1745 " end of an object");
1746 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1747 slab_error(cachep, "constructor overwrote the"
1748 " start of an object");
1750 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1751 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1752 #else
1753 if (cachep->ctor)
1754 cachep->ctor(objp, cachep, ctor_flags);
1755 #endif
1756 slab_bufctl(slabp)[i] = i+1;
1758 slab_bufctl(slabp)[i-1] = BUFCTL_END;
1759 slabp->free = 0;
1762 static void kmem_flagcheck(kmem_cache_t *cachep, unsigned int flags)
1764 if (flags & SLAB_DMA) {
1765 if (!(cachep->gfpflags & GFP_DMA))
1766 BUG();
1767 } else {
1768 if (cachep->gfpflags & GFP_DMA)
1769 BUG();
1773 static void set_slab_attr(kmem_cache_t *cachep, struct slab *slabp, void *objp)
1775 int i;
1776 struct page *page;
1778 /* Nasty!!!!!! I hope this is OK. */
1779 i = 1 << cachep->gfporder;
1780 page = virt_to_page(objp);
1781 do {
1782 SET_PAGE_CACHE(page, cachep);
1783 SET_PAGE_SLAB(page, slabp);
1784 page++;
1785 } while (--i);
1789 * Grow (by 1) the number of slabs within a cache. This is called by
1790 * kmem_cache_alloc() when there are no active objs left in a cache.
1792 static int cache_grow(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
1794 struct slab *slabp;
1795 void *objp;
1796 size_t offset;
1797 unsigned int local_flags;
1798 unsigned long ctor_flags;
1800 /* Be lazy and only check for valid flags here,
1801 * keeping it out of the critical path in kmem_cache_alloc().
1803 if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1804 BUG();
1805 if (flags & SLAB_NO_GROW)
1806 return 0;
1808 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1809 local_flags = (flags & SLAB_LEVEL_MASK);
1810 if (!(local_flags & __GFP_WAIT))
1812 * Not allowed to sleep. Need to tell a constructor about
1813 * this - it might need to know...
1815 ctor_flags |= SLAB_CTOR_ATOMIC;
1817 /* About to mess with non-constant members - lock. */
1818 check_irq_off();
1819 spin_lock(&cachep->spinlock);
1821 /* Get colour for the slab, and cal the next value. */
1822 offset = cachep->colour_next;
1823 cachep->colour_next++;
1824 if (cachep->colour_next >= cachep->colour)
1825 cachep->colour_next = 0;
1826 offset *= cachep->colour_off;
1828 spin_unlock(&cachep->spinlock);
1830 if (local_flags & __GFP_WAIT)
1831 local_irq_enable();
1834 * The test for missing atomic flag is performed here, rather than
1835 * the more obvious place, simply to reduce the critical path length
1836 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1837 * will eventually be caught here (where it matters).
1839 kmem_flagcheck(cachep, flags);
1842 /* Get mem for the objs. */
1843 if (!(objp = kmem_getpages(cachep, flags, nodeid)))
1844 goto failed;
1846 /* Get slab management. */
1847 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1848 goto opps1;
1850 set_slab_attr(cachep, slabp, objp);
1852 cache_init_objs(cachep, slabp, ctor_flags);
1854 if (local_flags & __GFP_WAIT)
1855 local_irq_disable();
1856 check_irq_off();
1857 spin_lock(&cachep->spinlock);
1859 /* Make slab active. */
1860 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1861 STATS_INC_GROWN(cachep);
1862 list3_data(cachep)->free_objects += cachep->num;
1863 spin_unlock(&cachep->spinlock);
1864 return 1;
1865 opps1:
1866 kmem_freepages(cachep, objp);
1867 failed:
1868 if (local_flags & __GFP_WAIT)
1869 local_irq_disable();
1870 return 0;
1873 #if DEBUG
1876 * Perform extra freeing checks:
1877 * - detect bad pointers.
1878 * - POISON/RED_ZONE checking
1879 * - destructor calls, for caches with POISON+dtor
1881 static void kfree_debugcheck(const void *objp)
1883 struct page *page;
1885 if (!virt_addr_valid(objp)) {
1886 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1887 (unsigned long)objp);
1888 BUG();
1890 page = virt_to_page(objp);
1891 if (!PageSlab(page)) {
1892 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1893 BUG();
1897 static void *cache_free_debugcheck(kmem_cache_t *cachep, void *objp,
1898 void *caller)
1900 struct page *page;
1901 unsigned int objnr;
1902 struct slab *slabp;
1904 objp -= obj_dbghead(cachep);
1905 kfree_debugcheck(objp);
1906 page = virt_to_page(objp);
1908 if (GET_PAGE_CACHE(page) != cachep) {
1909 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1910 GET_PAGE_CACHE(page),cachep);
1911 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1912 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1913 WARN_ON(1);
1915 slabp = GET_PAGE_SLAB(page);
1917 if (cachep->flags & SLAB_RED_ZONE) {
1918 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1919 slab_error(cachep, "double free, or memory outside"
1920 " object was overwritten");
1921 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1922 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1924 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1925 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1927 if (cachep->flags & SLAB_STORE_USER)
1928 *dbg_userword(cachep, objp) = caller;
1930 objnr = (objp-slabp->s_mem)/cachep->objsize;
1932 BUG_ON(objnr >= cachep->num);
1933 BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1935 if (cachep->flags & SLAB_DEBUG_INITIAL) {
1936 /* Need to call the slab's constructor so the
1937 * caller can perform a verify of its state (debugging).
1938 * Called without the cache-lock held.
1940 cachep->ctor(objp+obj_dbghead(cachep),
1941 cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1943 if (cachep->flags & SLAB_POISON && cachep->dtor) {
1944 /* we want to cache poison the object,
1945 * call the destruction callback
1947 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1949 if (cachep->flags & SLAB_POISON) {
1950 #ifdef CONFIG_DEBUG_PAGEALLOC
1951 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1952 store_stackinfo(cachep, objp, (unsigned long)caller);
1953 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1954 } else {
1955 poison_obj(cachep, objp, POISON_FREE);
1957 #else
1958 poison_obj(cachep, objp, POISON_FREE);
1959 #endif
1961 return objp;
1964 static void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
1966 kmem_bufctl_t i;
1967 int entries = 0;
1969 check_spinlock_acquired(cachep);
1970 /* Check slab's freelist to see if this obj is there. */
1971 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
1972 entries++;
1973 if (entries > cachep->num || i >= cachep->num)
1974 goto bad;
1976 if (entries != cachep->num - slabp->inuse) {
1977 bad:
1978 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
1979 cachep->name, cachep->num, slabp, slabp->inuse);
1980 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
1981 if ((i%16)==0)
1982 printk("\n%03x:", i);
1983 printk(" %02x", ((unsigned char*)slabp)[i]);
1985 printk("\n");
1986 BUG();
1989 #else
1990 #define kfree_debugcheck(x) do { } while(0)
1991 #define cache_free_debugcheck(x,objp,z) (objp)
1992 #define check_slabp(x,y) do { } while(0)
1993 #endif
1995 static void *cache_alloc_refill(kmem_cache_t *cachep, unsigned int __nocast flags)
1997 int batchcount;
1998 struct kmem_list3 *l3;
1999 struct array_cache *ac;
2001 check_irq_off();
2002 ac = ac_data(cachep);
2003 retry:
2004 batchcount = ac->batchcount;
2005 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2006 /* if there was little recent activity on this
2007 * cache, then perform only a partial refill.
2008 * Otherwise we could generate refill bouncing.
2010 batchcount = BATCHREFILL_LIMIT;
2012 l3 = list3_data(cachep);
2014 BUG_ON(ac->avail > 0);
2015 spin_lock(&cachep->spinlock);
2016 if (l3->shared) {
2017 struct array_cache *shared_array = l3->shared;
2018 if (shared_array->avail) {
2019 if (batchcount > shared_array->avail)
2020 batchcount = shared_array->avail;
2021 shared_array->avail -= batchcount;
2022 ac->avail = batchcount;
2023 memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
2024 sizeof(void*)*batchcount);
2025 shared_array->touched = 1;
2026 goto alloc_done;
2029 while (batchcount > 0) {
2030 struct list_head *entry;
2031 struct slab *slabp;
2032 /* Get slab alloc is to come from. */
2033 entry = l3->slabs_partial.next;
2034 if (entry == &l3->slabs_partial) {
2035 l3->free_touched = 1;
2036 entry = l3->slabs_free.next;
2037 if (entry == &l3->slabs_free)
2038 goto must_grow;
2041 slabp = list_entry(entry, struct slab, list);
2042 check_slabp(cachep, slabp);
2043 check_spinlock_acquired(cachep);
2044 while (slabp->inuse < cachep->num && batchcount--) {
2045 kmem_bufctl_t next;
2046 STATS_INC_ALLOCED(cachep);
2047 STATS_INC_ACTIVE(cachep);
2048 STATS_SET_HIGH(cachep);
2050 /* get obj pointer */
2051 ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
2053 slabp->inuse++;
2054 next = slab_bufctl(slabp)[slabp->free];
2055 #if DEBUG
2056 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2057 #endif
2058 slabp->free = next;
2060 check_slabp(cachep, slabp);
2062 /* move slabp to correct slabp list: */
2063 list_del(&slabp->list);
2064 if (slabp->free == BUFCTL_END)
2065 list_add(&slabp->list, &l3->slabs_full);
2066 else
2067 list_add(&slabp->list, &l3->slabs_partial);
2070 must_grow:
2071 l3->free_objects -= ac->avail;
2072 alloc_done:
2073 spin_unlock(&cachep->spinlock);
2075 if (unlikely(!ac->avail)) {
2076 int x;
2077 x = cache_grow(cachep, flags, -1);
2079 // cache_grow can reenable interrupts, then ac could change.
2080 ac = ac_data(cachep);
2081 if (!x && ac->avail == 0) // no objects in sight? abort
2082 return NULL;
2084 if (!ac->avail) // objects refilled by interrupt?
2085 goto retry;
2087 ac->touched = 1;
2088 return ac_entry(ac)[--ac->avail];
2091 static inline void
2092 cache_alloc_debugcheck_before(kmem_cache_t *cachep, unsigned int __nocast flags)
2094 might_sleep_if(flags & __GFP_WAIT);
2095 #if DEBUG
2096 kmem_flagcheck(cachep, flags);
2097 #endif
2100 #if DEBUG
2101 static void *
2102 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
2103 unsigned long flags, void *objp, void *caller)
2105 if (!objp)
2106 return objp;
2107 if (cachep->flags & SLAB_POISON) {
2108 #ifdef CONFIG_DEBUG_PAGEALLOC
2109 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2110 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
2111 else
2112 check_poison_obj(cachep, objp);
2113 #else
2114 check_poison_obj(cachep, objp);
2115 #endif
2116 poison_obj(cachep, objp, POISON_INUSE);
2118 if (cachep->flags & SLAB_STORE_USER)
2119 *dbg_userword(cachep, objp) = caller;
2121 if (cachep->flags & SLAB_RED_ZONE) {
2122 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2123 slab_error(cachep, "double free, or memory outside"
2124 " object was overwritten");
2125 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
2126 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2128 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2129 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2131 objp += obj_dbghead(cachep);
2132 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2133 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2135 if (!(flags & __GFP_WAIT))
2136 ctor_flags |= SLAB_CTOR_ATOMIC;
2138 cachep->ctor(objp, cachep, ctor_flags);
2140 return objp;
2142 #else
2143 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2144 #endif
2147 static inline void *__cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2149 unsigned long save_flags;
2150 void* objp;
2151 struct array_cache *ac;
2153 cache_alloc_debugcheck_before(cachep, flags);
2155 local_irq_save(save_flags);
2156 ac = ac_data(cachep);
2157 if (likely(ac->avail)) {
2158 STATS_INC_ALLOCHIT(cachep);
2159 ac->touched = 1;
2160 objp = ac_entry(ac)[--ac->avail];
2161 } else {
2162 STATS_INC_ALLOCMISS(cachep);
2163 objp = cache_alloc_refill(cachep, flags);
2165 local_irq_restore(save_flags);
2166 objp = cache_alloc_debugcheck_after(cachep, flags, objp, __builtin_return_address(0));
2167 return objp;
2171 * NUMA: different approach needed if the spinlock is moved into
2172 * the l3 structure
2175 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2177 int i;
2179 check_spinlock_acquired(cachep);
2181 /* NUMA: move add into loop */
2182 cachep->lists.free_objects += nr_objects;
2184 for (i = 0; i < nr_objects; i++) {
2185 void *objp = objpp[i];
2186 struct slab *slabp;
2187 unsigned int objnr;
2189 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2190 list_del(&slabp->list);
2191 objnr = (objp - slabp->s_mem) / cachep->objsize;
2192 check_slabp(cachep, slabp);
2193 #if DEBUG
2194 if (slab_bufctl(slabp)[objnr] != BUFCTL_FREE) {
2195 printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2196 cachep->name, objp);
2197 BUG();
2199 #endif
2200 slab_bufctl(slabp)[objnr] = slabp->free;
2201 slabp->free = objnr;
2202 STATS_DEC_ACTIVE(cachep);
2203 slabp->inuse--;
2204 check_slabp(cachep, slabp);
2206 /* fixup slab chains */
2207 if (slabp->inuse == 0) {
2208 if (cachep->lists.free_objects > cachep->free_limit) {
2209 cachep->lists.free_objects -= cachep->num;
2210 slab_destroy(cachep, slabp);
2211 } else {
2212 list_add(&slabp->list,
2213 &list3_data_ptr(cachep, objp)->slabs_free);
2215 } else {
2216 /* Unconditionally move a slab to the end of the
2217 * partial list on free - maximum time for the
2218 * other objects to be freed, too.
2220 list_add_tail(&slabp->list,
2221 &list3_data_ptr(cachep, objp)->slabs_partial);
2226 static void cache_flusharray(kmem_cache_t *cachep, struct array_cache *ac)
2228 int batchcount;
2230 batchcount = ac->batchcount;
2231 #if DEBUG
2232 BUG_ON(!batchcount || batchcount > ac->avail);
2233 #endif
2234 check_irq_off();
2235 spin_lock(&cachep->spinlock);
2236 if (cachep->lists.shared) {
2237 struct array_cache *shared_array = cachep->lists.shared;
2238 int max = shared_array->limit-shared_array->avail;
2239 if (max) {
2240 if (batchcount > max)
2241 batchcount = max;
2242 memcpy(&ac_entry(shared_array)[shared_array->avail],
2243 &ac_entry(ac)[0],
2244 sizeof(void*)*batchcount);
2245 shared_array->avail += batchcount;
2246 goto free_done;
2250 free_block(cachep, &ac_entry(ac)[0], batchcount);
2251 free_done:
2252 #if STATS
2254 int i = 0;
2255 struct list_head *p;
2257 p = list3_data(cachep)->slabs_free.next;
2258 while (p != &(list3_data(cachep)->slabs_free)) {
2259 struct slab *slabp;
2261 slabp = list_entry(p, struct slab, list);
2262 BUG_ON(slabp->inuse);
2264 i++;
2265 p = p->next;
2267 STATS_SET_FREEABLE(cachep, i);
2269 #endif
2270 spin_unlock(&cachep->spinlock);
2271 ac->avail -= batchcount;
2272 memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2273 sizeof(void*)*ac->avail);
2277 * __cache_free
2278 * Release an obj back to its cache. If the obj has a constructed
2279 * state, it must be in this state _before_ it is released.
2281 * Called with disabled ints.
2283 static inline void __cache_free(kmem_cache_t *cachep, void *objp)
2285 struct array_cache *ac = ac_data(cachep);
2287 check_irq_off();
2288 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2290 if (likely(ac->avail < ac->limit)) {
2291 STATS_INC_FREEHIT(cachep);
2292 ac_entry(ac)[ac->avail++] = objp;
2293 return;
2294 } else {
2295 STATS_INC_FREEMISS(cachep);
2296 cache_flusharray(cachep, ac);
2297 ac_entry(ac)[ac->avail++] = objp;
2302 * kmem_cache_alloc - Allocate an object
2303 * @cachep: The cache to allocate from.
2304 * @flags: See kmalloc().
2306 * Allocate an object from this cache. The flags are only relevant
2307 * if the cache has no available objects.
2309 void *kmem_cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2311 return __cache_alloc(cachep, flags);
2313 EXPORT_SYMBOL(kmem_cache_alloc);
2316 * kmem_ptr_validate - check if an untrusted pointer might
2317 * be a slab entry.
2318 * @cachep: the cache we're checking against
2319 * @ptr: pointer to validate
2321 * This verifies that the untrusted pointer looks sane:
2322 * it is _not_ a guarantee that the pointer is actually
2323 * part of the slab cache in question, but it at least
2324 * validates that the pointer can be dereferenced and
2325 * looks half-way sane.
2327 * Currently only used for dentry validation.
2329 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2331 unsigned long addr = (unsigned long) ptr;
2332 unsigned long min_addr = PAGE_OFFSET;
2333 unsigned long align_mask = BYTES_PER_WORD-1;
2334 unsigned long size = cachep->objsize;
2335 struct page *page;
2337 if (unlikely(addr < min_addr))
2338 goto out;
2339 if (unlikely(addr > (unsigned long)high_memory - size))
2340 goto out;
2341 if (unlikely(addr & align_mask))
2342 goto out;
2343 if (unlikely(!kern_addr_valid(addr)))
2344 goto out;
2345 if (unlikely(!kern_addr_valid(addr + size - 1)))
2346 goto out;
2347 page = virt_to_page(ptr);
2348 if (unlikely(!PageSlab(page)))
2349 goto out;
2350 if (unlikely(GET_PAGE_CACHE(page) != cachep))
2351 goto out;
2352 return 1;
2353 out:
2354 return 0;
2357 #ifdef CONFIG_NUMA
2359 * kmem_cache_alloc_node - Allocate an object on the specified node
2360 * @cachep: The cache to allocate from.
2361 * @flags: See kmalloc().
2362 * @nodeid: node number of the target node.
2364 * Identical to kmem_cache_alloc, except that this function is slow
2365 * and can sleep. And it will allocate memory on the given node, which
2366 * can improve the performance for cpu bound structures.
2368 void *kmem_cache_alloc_node(kmem_cache_t *cachep, int flags, int nodeid)
2370 int loop;
2371 void *objp;
2372 struct slab *slabp;
2373 kmem_bufctl_t next;
2375 for (loop = 0;;loop++) {
2376 struct list_head *q;
2378 objp = NULL;
2379 check_irq_on();
2380 spin_lock_irq(&cachep->spinlock);
2381 /* walk through all partial and empty slab and find one
2382 * from the right node */
2383 list_for_each(q,&cachep->lists.slabs_partial) {
2384 slabp = list_entry(q, struct slab, list);
2386 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2387 loop > 2)
2388 goto got_slabp;
2390 list_for_each(q, &cachep->lists.slabs_free) {
2391 slabp = list_entry(q, struct slab, list);
2393 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2394 loop > 2)
2395 goto got_slabp;
2397 spin_unlock_irq(&cachep->spinlock);
2399 local_irq_disable();
2400 if (!cache_grow(cachep, flags, nodeid)) {
2401 local_irq_enable();
2402 return NULL;
2404 local_irq_enable();
2406 got_slabp:
2407 /* found one: allocate object */
2408 check_slabp(cachep, slabp);
2409 check_spinlock_acquired(cachep);
2411 STATS_INC_ALLOCED(cachep);
2412 STATS_INC_ACTIVE(cachep);
2413 STATS_SET_HIGH(cachep);
2414 STATS_INC_NODEALLOCS(cachep);
2416 objp = slabp->s_mem + slabp->free*cachep->objsize;
2418 slabp->inuse++;
2419 next = slab_bufctl(slabp)[slabp->free];
2420 #if DEBUG
2421 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2422 #endif
2423 slabp->free = next;
2424 check_slabp(cachep, slabp);
2426 /* move slabp to correct slabp list: */
2427 list_del(&slabp->list);
2428 if (slabp->free == BUFCTL_END)
2429 list_add(&slabp->list, &cachep->lists.slabs_full);
2430 else
2431 list_add(&slabp->list, &cachep->lists.slabs_partial);
2433 list3_data(cachep)->free_objects--;
2434 spin_unlock_irq(&cachep->spinlock);
2436 objp = cache_alloc_debugcheck_after(cachep, GFP_KERNEL, objp,
2437 __builtin_return_address(0));
2438 return objp;
2440 EXPORT_SYMBOL(kmem_cache_alloc_node);
2442 void *kmalloc_node(size_t size, int flags, int node)
2444 kmem_cache_t *cachep;
2446 cachep = kmem_find_general_cachep(size, flags);
2447 if (unlikely(cachep == NULL))
2448 return NULL;
2449 return kmem_cache_alloc_node(cachep, flags, node);
2451 EXPORT_SYMBOL(kmalloc_node);
2452 #endif
2455 * kmalloc - allocate memory
2456 * @size: how many bytes of memory are required.
2457 * @flags: the type of memory to allocate.
2459 * kmalloc is the normal method of allocating memory
2460 * in the kernel.
2462 * The @flags argument may be one of:
2464 * %GFP_USER - Allocate memory on behalf of user. May sleep.
2466 * %GFP_KERNEL - Allocate normal kernel ram. May sleep.
2468 * %GFP_ATOMIC - Allocation will not sleep. Use inside interrupt handlers.
2470 * Additionally, the %GFP_DMA flag may be set to indicate the memory
2471 * must be suitable for DMA. This can mean different things on different
2472 * platforms. For example, on i386, it means that the memory must come
2473 * from the first 16MB.
2475 void *__kmalloc(size_t size, unsigned int __nocast flags)
2477 kmem_cache_t *cachep;
2479 /* If you want to save a few bytes .text space: replace
2480 * __ with kmem_.
2481 * Then kmalloc uses the uninlined functions instead of the inline
2482 * functions.
2484 cachep = __find_general_cachep(size, flags);
2485 if (unlikely(cachep == NULL))
2486 return NULL;
2487 return __cache_alloc(cachep, flags);
2489 EXPORT_SYMBOL(__kmalloc);
2491 #ifdef CONFIG_SMP
2493 * __alloc_percpu - allocate one copy of the object for every present
2494 * cpu in the system, zeroing them.
2495 * Objects should be dereferenced using the per_cpu_ptr macro only.
2497 * @size: how many bytes of memory are required.
2498 * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2500 void *__alloc_percpu(size_t size, size_t align)
2502 int i;
2503 struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2505 if (!pdata)
2506 return NULL;
2508 for (i = 0; i < NR_CPUS; i++) {
2509 if (!cpu_possible(i))
2510 continue;
2511 pdata->ptrs[i] = kmalloc_node(size, GFP_KERNEL,
2512 cpu_to_node(i));
2514 if (!pdata->ptrs[i])
2515 goto unwind_oom;
2516 memset(pdata->ptrs[i], 0, size);
2519 /* Catch derefs w/o wrappers */
2520 return (void *) (~(unsigned long) pdata);
2522 unwind_oom:
2523 while (--i >= 0) {
2524 if (!cpu_possible(i))
2525 continue;
2526 kfree(pdata->ptrs[i]);
2528 kfree(pdata);
2529 return NULL;
2531 EXPORT_SYMBOL(__alloc_percpu);
2532 #endif
2535 * kmem_cache_free - Deallocate an object
2536 * @cachep: The cache the allocation was from.
2537 * @objp: The previously allocated object.
2539 * Free an object which was previously allocated from this
2540 * cache.
2542 void kmem_cache_free(kmem_cache_t *cachep, void *objp)
2544 unsigned long flags;
2546 local_irq_save(flags);
2547 __cache_free(cachep, objp);
2548 local_irq_restore(flags);
2550 EXPORT_SYMBOL(kmem_cache_free);
2553 * kcalloc - allocate memory for an array. The memory is set to zero.
2554 * @n: number of elements.
2555 * @size: element size.
2556 * @flags: the type of memory to allocate.
2558 void *kcalloc(size_t n, size_t size, unsigned int __nocast flags)
2560 void *ret = NULL;
2562 if (n != 0 && size > INT_MAX / n)
2563 return ret;
2565 ret = kmalloc(n * size, flags);
2566 if (ret)
2567 memset(ret, 0, n * size);
2568 return ret;
2570 EXPORT_SYMBOL(kcalloc);
2573 * kfree - free previously allocated memory
2574 * @objp: pointer returned by kmalloc.
2576 * Don't free memory not originally allocated by kmalloc()
2577 * or you will run into trouble.
2579 void kfree(const void *objp)
2581 kmem_cache_t *c;
2582 unsigned long flags;
2584 if (unlikely(!objp))
2585 return;
2586 local_irq_save(flags);
2587 kfree_debugcheck(objp);
2588 c = GET_PAGE_CACHE(virt_to_page(objp));
2589 __cache_free(c, (void*)objp);
2590 local_irq_restore(flags);
2592 EXPORT_SYMBOL(kfree);
2594 #ifdef CONFIG_SMP
2596 * free_percpu - free previously allocated percpu memory
2597 * @objp: pointer returned by alloc_percpu.
2599 * Don't free memory not originally allocated by alloc_percpu()
2600 * The complemented objp is to check for that.
2602 void
2603 free_percpu(const void *objp)
2605 int i;
2606 struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2608 for (i = 0; i < NR_CPUS; i++) {
2609 if (!cpu_possible(i))
2610 continue;
2611 kfree(p->ptrs[i]);
2613 kfree(p);
2615 EXPORT_SYMBOL(free_percpu);
2616 #endif
2618 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2620 return obj_reallen(cachep);
2622 EXPORT_SYMBOL(kmem_cache_size);
2624 const char *kmem_cache_name(kmem_cache_t *cachep)
2626 return cachep->name;
2628 EXPORT_SYMBOL_GPL(kmem_cache_name);
2630 struct ccupdate_struct {
2631 kmem_cache_t *cachep;
2632 struct array_cache *new[NR_CPUS];
2635 static void do_ccupdate_local(void *info)
2637 struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2638 struct array_cache *old;
2640 check_irq_off();
2641 old = ac_data(new->cachep);
2643 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2644 new->new[smp_processor_id()] = old;
2648 static int do_tune_cpucache(kmem_cache_t *cachep, int limit, int batchcount,
2649 int shared)
2651 struct ccupdate_struct new;
2652 struct array_cache *new_shared;
2653 int i;
2655 memset(&new.new,0,sizeof(new.new));
2656 for (i = 0; i < NR_CPUS; i++) {
2657 if (cpu_online(i)) {
2658 new.new[i] = alloc_arraycache(i, limit, batchcount);
2659 if (!new.new[i]) {
2660 for (i--; i >= 0; i--) kfree(new.new[i]);
2661 return -ENOMEM;
2663 } else {
2664 new.new[i] = NULL;
2667 new.cachep = cachep;
2669 smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2671 check_irq_on();
2672 spin_lock_irq(&cachep->spinlock);
2673 cachep->batchcount = batchcount;
2674 cachep->limit = limit;
2675 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2676 spin_unlock_irq(&cachep->spinlock);
2678 for (i = 0; i < NR_CPUS; i++) {
2679 struct array_cache *ccold = new.new[i];
2680 if (!ccold)
2681 continue;
2682 spin_lock_irq(&cachep->spinlock);
2683 free_block(cachep, ac_entry(ccold), ccold->avail);
2684 spin_unlock_irq(&cachep->spinlock);
2685 kfree(ccold);
2687 new_shared = alloc_arraycache(-1, batchcount*shared, 0xbaadf00d);
2688 if (new_shared) {
2689 struct array_cache *old;
2691 spin_lock_irq(&cachep->spinlock);
2692 old = cachep->lists.shared;
2693 cachep->lists.shared = new_shared;
2694 if (old)
2695 free_block(cachep, ac_entry(old), old->avail);
2696 spin_unlock_irq(&cachep->spinlock);
2697 kfree(old);
2700 return 0;
2704 static void enable_cpucache(kmem_cache_t *cachep)
2706 int err;
2707 int limit, shared;
2709 /* The head array serves three purposes:
2710 * - create a LIFO ordering, i.e. return objects that are cache-warm
2711 * - reduce the number of spinlock operations.
2712 * - reduce the number of linked list operations on the slab and
2713 * bufctl chains: array operations are cheaper.
2714 * The numbers are guessed, we should auto-tune as described by
2715 * Bonwick.
2717 if (cachep->objsize > 131072)
2718 limit = 1;
2719 else if (cachep->objsize > PAGE_SIZE)
2720 limit = 8;
2721 else if (cachep->objsize > 1024)
2722 limit = 24;
2723 else if (cachep->objsize > 256)
2724 limit = 54;
2725 else
2726 limit = 120;
2728 /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2729 * allocation behaviour: Most allocs on one cpu, most free operations
2730 * on another cpu. For these cases, an efficient object passing between
2731 * cpus is necessary. This is provided by a shared array. The array
2732 * replaces Bonwick's magazine layer.
2733 * On uniprocessor, it's functionally equivalent (but less efficient)
2734 * to a larger limit. Thus disabled by default.
2736 shared = 0;
2737 #ifdef CONFIG_SMP
2738 if (cachep->objsize <= PAGE_SIZE)
2739 shared = 8;
2740 #endif
2742 #if DEBUG
2743 /* With debugging enabled, large batchcount lead to excessively
2744 * long periods with disabled local interrupts. Limit the
2745 * batchcount
2747 if (limit > 32)
2748 limit = 32;
2749 #endif
2750 err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2751 if (err)
2752 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2753 cachep->name, -err);
2756 static void drain_array_locked(kmem_cache_t *cachep,
2757 struct array_cache *ac, int force)
2759 int tofree;
2761 check_spinlock_acquired(cachep);
2762 if (ac->touched && !force) {
2763 ac->touched = 0;
2764 } else if (ac->avail) {
2765 tofree = force ? ac->avail : (ac->limit+4)/5;
2766 if (tofree > ac->avail) {
2767 tofree = (ac->avail+1)/2;
2769 free_block(cachep, ac_entry(ac), tofree);
2770 ac->avail -= tofree;
2771 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2772 sizeof(void*)*ac->avail);
2777 * cache_reap - Reclaim memory from caches.
2779 * Called from workqueue/eventd every few seconds.
2780 * Purpose:
2781 * - clear the per-cpu caches for this CPU.
2782 * - return freeable pages to the main free memory pool.
2784 * If we cannot acquire the cache chain semaphore then just give up - we'll
2785 * try again on the next iteration.
2787 static void cache_reap(void *unused)
2789 struct list_head *walk;
2791 if (down_trylock(&cache_chain_sem)) {
2792 /* Give up. Setup the next iteration. */
2793 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2794 return;
2797 list_for_each(walk, &cache_chain) {
2798 kmem_cache_t *searchp;
2799 struct list_head* p;
2800 int tofree;
2801 struct slab *slabp;
2803 searchp = list_entry(walk, kmem_cache_t, next);
2805 if (searchp->flags & SLAB_NO_REAP)
2806 goto next;
2808 check_irq_on();
2810 spin_lock_irq(&searchp->spinlock);
2812 drain_array_locked(searchp, ac_data(searchp), 0);
2814 if(time_after(searchp->lists.next_reap, jiffies))
2815 goto next_unlock;
2817 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2819 if (searchp->lists.shared)
2820 drain_array_locked(searchp, searchp->lists.shared, 0);
2822 if (searchp->lists.free_touched) {
2823 searchp->lists.free_touched = 0;
2824 goto next_unlock;
2827 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2828 do {
2829 p = list3_data(searchp)->slabs_free.next;
2830 if (p == &(list3_data(searchp)->slabs_free))
2831 break;
2833 slabp = list_entry(p, struct slab, list);
2834 BUG_ON(slabp->inuse);
2835 list_del(&slabp->list);
2836 STATS_INC_REAPED(searchp);
2838 /* Safe to drop the lock. The slab is no longer
2839 * linked to the cache.
2840 * searchp cannot disappear, we hold
2841 * cache_chain_lock
2843 searchp->lists.free_objects -= searchp->num;
2844 spin_unlock_irq(&searchp->spinlock);
2845 slab_destroy(searchp, slabp);
2846 spin_lock_irq(&searchp->spinlock);
2847 } while(--tofree > 0);
2848 next_unlock:
2849 spin_unlock_irq(&searchp->spinlock);
2850 next:
2851 cond_resched();
2853 check_irq_on();
2854 up(&cache_chain_sem);
2855 drain_remote_pages();
2856 /* Setup the next iteration */
2857 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2860 #ifdef CONFIG_PROC_FS
2862 static void *s_start(struct seq_file *m, loff_t *pos)
2864 loff_t n = *pos;
2865 struct list_head *p;
2867 down(&cache_chain_sem);
2868 if (!n) {
2870 * Output format version, so at least we can change it
2871 * without _too_ many complaints.
2873 #if STATS
2874 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
2875 #else
2876 seq_puts(m, "slabinfo - version: 2.1\n");
2877 #endif
2878 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2879 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
2880 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
2881 #if STATS
2882 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped>"
2883 " <error> <maxfreeable> <freelimit> <nodeallocs>");
2884 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
2885 #endif
2886 seq_putc(m, '\n');
2888 p = cache_chain.next;
2889 while (n--) {
2890 p = p->next;
2891 if (p == &cache_chain)
2892 return NULL;
2894 return list_entry(p, kmem_cache_t, next);
2897 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2899 kmem_cache_t *cachep = p;
2900 ++*pos;
2901 return cachep->next.next == &cache_chain ? NULL
2902 : list_entry(cachep->next.next, kmem_cache_t, next);
2905 static void s_stop(struct seq_file *m, void *p)
2907 up(&cache_chain_sem);
2910 static int s_show(struct seq_file *m, void *p)
2912 kmem_cache_t *cachep = p;
2913 struct list_head *q;
2914 struct slab *slabp;
2915 unsigned long active_objs;
2916 unsigned long num_objs;
2917 unsigned long active_slabs = 0;
2918 unsigned long num_slabs;
2919 const char *name;
2920 char *error = NULL;
2922 check_irq_on();
2923 spin_lock_irq(&cachep->spinlock);
2924 active_objs = 0;
2925 num_slabs = 0;
2926 list_for_each(q,&cachep->lists.slabs_full) {
2927 slabp = list_entry(q, struct slab, list);
2928 if (slabp->inuse != cachep->num && !error)
2929 error = "slabs_full accounting error";
2930 active_objs += cachep->num;
2931 active_slabs++;
2933 list_for_each(q,&cachep->lists.slabs_partial) {
2934 slabp = list_entry(q, struct slab, list);
2935 if (slabp->inuse == cachep->num && !error)
2936 error = "slabs_partial inuse accounting error";
2937 if (!slabp->inuse && !error)
2938 error = "slabs_partial/inuse accounting error";
2939 active_objs += slabp->inuse;
2940 active_slabs++;
2942 list_for_each(q,&cachep->lists.slabs_free) {
2943 slabp = list_entry(q, struct slab, list);
2944 if (slabp->inuse && !error)
2945 error = "slabs_free/inuse accounting error";
2946 num_slabs++;
2948 num_slabs+=active_slabs;
2949 num_objs = num_slabs*cachep->num;
2950 if (num_objs - active_objs != cachep->lists.free_objects && !error)
2951 error = "free_objects accounting error";
2953 name = cachep->name;
2954 if (error)
2955 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
2957 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
2958 name, active_objs, num_objs, cachep->objsize,
2959 cachep->num, (1<<cachep->gfporder));
2960 seq_printf(m, " : tunables %4u %4u %4u",
2961 cachep->limit, cachep->batchcount,
2962 cachep->lists.shared->limit/cachep->batchcount);
2963 seq_printf(m, " : slabdata %6lu %6lu %6u",
2964 active_slabs, num_slabs, cachep->lists.shared->avail);
2965 #if STATS
2966 { /* list3 stats */
2967 unsigned long high = cachep->high_mark;
2968 unsigned long allocs = cachep->num_allocations;
2969 unsigned long grown = cachep->grown;
2970 unsigned long reaped = cachep->reaped;
2971 unsigned long errors = cachep->errors;
2972 unsigned long max_freeable = cachep->max_freeable;
2973 unsigned long free_limit = cachep->free_limit;
2974 unsigned long node_allocs = cachep->node_allocs;
2976 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu",
2977 allocs, high, grown, reaped, errors,
2978 max_freeable, free_limit, node_allocs);
2980 /* cpu stats */
2982 unsigned long allochit = atomic_read(&cachep->allochit);
2983 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
2984 unsigned long freehit = atomic_read(&cachep->freehit);
2985 unsigned long freemiss = atomic_read(&cachep->freemiss);
2987 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
2988 allochit, allocmiss, freehit, freemiss);
2990 #endif
2991 seq_putc(m, '\n');
2992 spin_unlock_irq(&cachep->spinlock);
2993 return 0;
2997 * slabinfo_op - iterator that generates /proc/slabinfo
2999 * Output layout:
3000 * cache-name
3001 * num-active-objs
3002 * total-objs
3003 * object size
3004 * num-active-slabs
3005 * total-slabs
3006 * num-pages-per-slab
3007 * + further values on SMP and with statistics enabled
3010 struct seq_operations slabinfo_op = {
3011 .start = s_start,
3012 .next = s_next,
3013 .stop = s_stop,
3014 .show = s_show,
3017 #define MAX_SLABINFO_WRITE 128
3019 * slabinfo_write - Tuning for the slab allocator
3020 * @file: unused
3021 * @buffer: user buffer
3022 * @count: data length
3023 * @ppos: unused
3025 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
3026 size_t count, loff_t *ppos)
3028 char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
3029 int limit, batchcount, shared, res;
3030 struct list_head *p;
3032 if (count > MAX_SLABINFO_WRITE)
3033 return -EINVAL;
3034 if (copy_from_user(&kbuf, buffer, count))
3035 return -EFAULT;
3036 kbuf[MAX_SLABINFO_WRITE] = '\0';
3038 tmp = strchr(kbuf, ' ');
3039 if (!tmp)
3040 return -EINVAL;
3041 *tmp = '\0';
3042 tmp++;
3043 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3044 return -EINVAL;
3046 /* Find the cache in the chain of caches. */
3047 down(&cache_chain_sem);
3048 res = -EINVAL;
3049 list_for_each(p,&cache_chain) {
3050 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
3052 if (!strcmp(cachep->name, kbuf)) {
3053 if (limit < 1 ||
3054 batchcount < 1 ||
3055 batchcount > limit ||
3056 shared < 0) {
3057 res = -EINVAL;
3058 } else {
3059 res = do_tune_cpucache(cachep, limit, batchcount, shared);
3061 break;
3064 up(&cache_chain_sem);
3065 if (res >= 0)
3066 res = count;
3067 return res;
3069 #endif
3071 unsigned int ksize(const void *objp)
3073 kmem_cache_t *c;
3074 unsigned long flags;
3075 unsigned int size = 0;
3077 if (likely(objp != NULL)) {
3078 local_irq_save(flags);
3079 c = GET_PAGE_CACHE(virt_to_page(objp));
3080 size = kmem_cache_size(c);
3081 local_irq_restore(flags);
3084 return size;
3089 * kstrdup - allocate space for and copy an existing string
3091 * @s: the string to duplicate
3092 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
3094 char *kstrdup(const char *s, int gfp)
3096 size_t len;
3097 char *buf;
3099 if (!s)
3100 return NULL;
3102 len = strlen(s) + 1;
3103 buf = kmalloc(len, gfp);
3104 if (buf)
3105 memcpy(buf, s, len);
3106 return buf;
3108 EXPORT_SYMBOL(kstrdup);