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
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
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
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>
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>
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)
112 #ifdef CONFIG_DEBUG_SLAB
115 #define FORCED_DEBUG 1
119 #define FORCED_DEBUG 0
123 /* Shouldn't this be in a header file somewhere? */
124 #define BYTES_PER_WORD sizeof(void *)
126 #ifndef cache_line_size
127 #define cache_line_size() L1_CACHE_BYTES
130 #ifndef ARCH_KMALLOC_MINALIGN
132 * Enforce a minimum alignment for the kmalloc caches.
133 * Usually, the kmalloc caches are cache_line_size() aligned, except when
134 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
135 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
136 * alignment larger than BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
137 * Note that this flag disables some debug features.
139 #define ARCH_KMALLOC_MINALIGN 0
142 #ifndef ARCH_SLAB_MINALIGN
144 * Enforce a minimum alignment for all caches.
145 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
146 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
147 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
148 * some debug features.
150 #define ARCH_SLAB_MINALIGN 0
153 #ifndef ARCH_KMALLOC_FLAGS
154 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
157 /* Legal flag mask for kmem_cache_create(). */
159 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
160 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
161 SLAB_NO_REAP | SLAB_CACHE_DMA | \
162 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
163 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
166 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
167 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
168 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
175 * Bufctl's are used for linking objs within a slab
178 * This implementation relies on "struct page" for locating the cache &
179 * slab an object belongs to.
180 * This allows the bufctl structure to be small (one int), but limits
181 * the number of objects a slab (not a cache) can contain when off-slab
182 * bufctls are used. The limit is the size of the largest general cache
183 * that does not use off-slab slabs.
184 * For 32bit archs with 4 kB pages, is this 56.
185 * This is not serious, as it is only for large objects, when it is unwise
186 * to have too many per slab.
187 * Note: This limit can be raised by introducing a general cache whose size
188 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
191 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
192 #define BUFCTL_ALLOC (((kmem_bufctl_t)(~0U))-1)
193 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-2)
195 /* Max number of objs-per-slab for caches which use off-slab slabs.
196 * Needed to avoid a possible looping condition in cache_grow().
198 static unsigned long offslab_limit;
203 * Manages the objs in a slab. Placed either at the beginning of mem allocated
204 * for a slab, or allocated from an general cache.
205 * Slabs are chained into three list: fully used, partial, fully free slabs.
208 struct list_head list;
209 unsigned long colouroff;
210 void *s_mem; /* including colour offset */
211 unsigned int inuse; /* num of objs active in slab */
218 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
219 * arrange for kmem_freepages to be called via RCU. This is useful if
220 * we need to approach a kernel structure obliquely, from its address
221 * obtained without the usual locking. We can lock the structure to
222 * stabilize it and check it's still at the given address, only if we
223 * can be sure that the memory has not been meanwhile reused for some
224 * other kind of object (which our subsystem's lock might corrupt).
226 * rcu_read_lock before reading the address, then rcu_read_unlock after
227 * taking the spinlock within the structure expected at that address.
229 * We assume struct slab_rcu can overlay struct slab when destroying.
232 struct rcu_head head;
233 kmem_cache_t *cachep;
242 * - LIFO ordering, to hand out cache-warm objects from _alloc
243 * - reduce the number of linked list operations
244 * - reduce spinlock operations
246 * The limit is stored in the per-cpu structure to reduce the data cache
253 unsigned int batchcount;
254 unsigned int touched;
257 /* bootstrap: The caches do not work without cpuarrays anymore,
258 * but the cpuarrays are allocated from the generic caches...
260 #define BOOT_CPUCACHE_ENTRIES 1
261 struct arraycache_init {
262 struct array_cache cache;
263 void * entries[BOOT_CPUCACHE_ENTRIES];
267 * The slab lists of all objects.
268 * Hopefully reduce the internal fragmentation
269 * NUMA: The spinlock could be moved from the kmem_cache_t
270 * into this structure, too. Figure out what causes
271 * fewer cross-node spinlock operations.
274 struct list_head slabs_partial; /* partial list first, better asm code */
275 struct list_head slabs_full;
276 struct list_head slabs_free;
277 unsigned long free_objects;
279 unsigned long next_reap;
280 struct array_cache *shared;
283 #define LIST3_INIT(parent) \
285 .slabs_full = LIST_HEAD_INIT(parent.slabs_full), \
286 .slabs_partial = LIST_HEAD_INIT(parent.slabs_partial), \
287 .slabs_free = LIST_HEAD_INIT(parent.slabs_free) \
289 #define list3_data(cachep) \
293 #define list3_data_ptr(cachep, ptr) \
302 struct kmem_cache_s {
303 /* 1) per-cpu data, touched during every alloc/free */
304 struct array_cache *array[NR_CPUS];
305 unsigned int batchcount;
307 /* 2) touched by every alloc & free from the backend */
308 struct kmem_list3 lists;
309 /* NUMA: kmem_3list_t *nodelists[MAX_NUMNODES] */
310 unsigned int objsize;
311 unsigned int flags; /* constant flags */
312 unsigned int num; /* # of objs per slab */
313 unsigned int free_limit; /* upper limit of objects in the lists */
316 /* 3) cache_grow/shrink */
317 /* order of pgs per slab (2^n) */
318 unsigned int gfporder;
320 /* force GFP flags, e.g. GFP_DMA */
321 unsigned int gfpflags;
323 size_t colour; /* cache colouring range */
324 unsigned int colour_off; /* colour offset */
325 unsigned int colour_next; /* cache colouring */
326 kmem_cache_t *slabp_cache;
327 unsigned int slab_size;
328 unsigned int dflags; /* dynamic flags */
330 /* constructor func */
331 void (*ctor)(void *, kmem_cache_t *, unsigned long);
333 /* de-constructor func */
334 void (*dtor)(void *, kmem_cache_t *, unsigned long);
336 /* 4) cache creation/removal */
338 struct list_head next;
342 unsigned long num_active;
343 unsigned long num_allocations;
344 unsigned long high_mark;
346 unsigned long reaped;
347 unsigned long errors;
348 unsigned long max_freeable;
349 unsigned long node_allocs;
358 unsigned long redzonetest;
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)
374 #define REDZONETIMEOUT (300*HZ)
377 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
378 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
379 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
380 #define STATS_INC_GROWN(x) ((x)->grown++)
381 #define STATS_INC_REAPED(x) ((x)->reaped++)
382 #define STATS_SET_HIGH(x) do { if ((x)->num_active > (x)->high_mark) \
383 (x)->high_mark = (x)->num_active; \
385 #define STATS_INC_ERR(x) ((x)->errors++)
386 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
387 #define STATS_SET_FREEABLE(x, i) \
388 do { if ((x)->max_freeable < i) \
389 (x)->max_freeable = i; \
392 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
393 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
394 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
395 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
397 #define STATS_INC_ACTIVE(x) do { } while (0)
398 #define STATS_DEC_ACTIVE(x) do { } while (0)
399 #define STATS_INC_ALLOCED(x) do { } while (0)
400 #define STATS_INC_GROWN(x) do { } while (0)
401 #define STATS_INC_REAPED(x) do { } while (0)
402 #define STATS_SET_HIGH(x) do { } while (0)
403 #define STATS_INC_ERR(x) do { } while (0)
404 #define STATS_INC_NODEALLOCS(x) do { } while (0)
405 #define STATS_SET_FREEABLE(x, i) \
408 #define STATS_INC_ALLOCHIT(x) do { } while (0)
409 #define STATS_INC_ALLOCMISS(x) do { } while (0)
410 #define STATS_INC_FREEHIT(x) do { } while (0)
411 #define STATS_INC_FREEMISS(x) do { } while (0)
415 /* Magic nums for obj red zoning.
416 * Placed in the first word before and the first word after an obj.
418 #define RED_INACTIVE 0x5A2CF071UL /* when obj is inactive */
419 #define RED_ACTIVE 0x170FC2A5UL /* when obj is active */
421 /* ...and for poisoning */
422 #define POISON_INUSE 0x5a /* for use-uninitialised poisoning */
423 #define POISON_FREE 0x6b /* for use-after-free poisoning */
424 #define POISON_END 0xa5 /* end-byte of poisoning */
426 /* memory layout of objects:
428 * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
429 * the end of an object is aligned with the end of the real
430 * allocation. Catches writes behind the end of the allocation.
431 * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
433 * cachep->dbghead: The real object.
434 * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
435 * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
437 static int obj_dbghead(kmem_cache_t *cachep)
439 return cachep->dbghead;
442 static int obj_reallen(kmem_cache_t *cachep)
444 return cachep->reallen;
447 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
449 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
450 return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
453 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
455 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
456 if (cachep->flags & SLAB_STORE_USER)
457 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
458 return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
461 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
463 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
464 return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
469 #define obj_dbghead(x) 0
470 #define obj_reallen(cachep) (cachep->objsize)
471 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
472 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
473 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
478 * Maximum size of an obj (in 2^order pages)
479 * and absolute limit for the gfp order.
481 #if defined(CONFIG_LARGE_ALLOCS)
482 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
483 #define MAX_GFP_ORDER 13 /* up to 32Mb */
484 #elif defined(CONFIG_MMU)
485 #define MAX_OBJ_ORDER 5 /* 32 pages */
486 #define MAX_GFP_ORDER 5 /* 32 pages */
488 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
489 #define MAX_GFP_ORDER 8 /* up to 1Mb */
493 * Do not go above this order unless 0 objects fit into the slab.
495 #define BREAK_GFP_ORDER_HI 1
496 #define BREAK_GFP_ORDER_LO 0
497 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
499 /* Macros for storing/retrieving the cachep and or slab from the
500 * global 'mem_map'. These are used to find the slab an obj belongs to.
501 * With kfree(), these are used to find the cache which an obj belongs to.
503 #define SET_PAGE_CACHE(pg,x) ((pg)->lru.next = (struct list_head *)(x))
504 #define GET_PAGE_CACHE(pg) ((kmem_cache_t *)(pg)->lru.next)
505 #define SET_PAGE_SLAB(pg,x) ((pg)->lru.prev = (struct list_head *)(x))
506 #define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->lru.prev)
508 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
509 struct cache_sizes malloc_sizes[] = {
510 #define CACHE(x) { .cs_size = (x) },
511 #include <linux/kmalloc_sizes.h>
515 EXPORT_SYMBOL(malloc_sizes);
517 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
523 static struct cache_names __initdata cache_names[] = {
524 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
525 #include <linux/kmalloc_sizes.h>
530 static struct arraycache_init initarray_cache __initdata =
531 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
532 static struct arraycache_init initarray_generic =
533 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
535 /* internal cache of cache description objs */
536 static kmem_cache_t cache_cache = {
537 .lists = LIST3_INIT(cache_cache.lists),
539 .limit = BOOT_CPUCACHE_ENTRIES,
540 .objsize = sizeof(kmem_cache_t),
541 .flags = SLAB_NO_REAP,
542 .spinlock = SPIN_LOCK_UNLOCKED,
543 .name = "kmem_cache",
545 .reallen = sizeof(kmem_cache_t),
549 /* Guard access to the cache-chain. */
550 static struct semaphore cache_chain_sem;
551 static struct list_head cache_chain;
554 * vm_enough_memory() looks at this to determine how many
555 * slab-allocated pages are possibly freeable under pressure
557 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
559 atomic_t slab_reclaim_pages;
560 EXPORT_SYMBOL(slab_reclaim_pages);
563 * chicken and egg problem: delay the per-cpu array allocation
564 * until the general caches are up.
572 static DEFINE_PER_CPU(struct work_struct, reap_work);
574 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
575 static void enable_cpucache (kmem_cache_t *cachep);
576 static void cache_reap (void *unused);
578 static inline void **ac_entry(struct array_cache *ac)
580 return (void**)(ac+1);
583 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
585 return cachep->array[smp_processor_id()];
588 static inline kmem_cache_t *__find_general_cachep(size_t size, int gfpflags)
590 struct cache_sizes *csizep = malloc_sizes;
593 /* This happens if someone tries to call
594 * kmem_cache_create(), or __kmalloc(), before
595 * the generic caches are initialized.
597 BUG_ON(csizep->cs_cachep == NULL);
599 while (size > csizep->cs_size)
603 * Really subtile: The last entry with cs->cs_size==ULONG_MAX
604 * has cs_{dma,}cachep==NULL. Thus no special case
605 * for large kmalloc calls required.
607 if (unlikely(gfpflags & GFP_DMA))
608 return csizep->cs_dmacachep;
609 return csizep->cs_cachep;
612 kmem_cache_t *kmem_find_general_cachep(size_t size, int gfpflags)
614 return __find_general_cachep(size, gfpflags);
616 EXPORT_SYMBOL(kmem_find_general_cachep);
618 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
619 static void cache_estimate(unsigned long gfporder, size_t size, size_t align,
620 int flags, size_t *left_over, unsigned int *num)
623 size_t wastage = PAGE_SIZE<<gfporder;
627 if (!(flags & CFLGS_OFF_SLAB)) {
628 base = sizeof(struct slab);
629 extra = sizeof(kmem_bufctl_t);
632 while (i*size + ALIGN(base+i*extra, align) <= wastage)
642 wastage -= ALIGN(base+i*extra, align);
643 *left_over = wastage;
646 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
648 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
650 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
651 function, cachep->name, msg);
656 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
657 * via the workqueue/eventd.
658 * Add the CPU number into the expiration time to minimize the possibility of
659 * the CPUs getting into lockstep and contending for the global cache chain
662 static void __devinit start_cpu_timer(int cpu)
664 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
667 * When this gets called from do_initcalls via cpucache_init(),
668 * init_workqueues() has already run, so keventd will be setup
671 if (keventd_up() && reap_work->func == NULL) {
672 INIT_WORK(reap_work, cache_reap, NULL);
673 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
677 static struct array_cache *alloc_arraycache(int cpu, int entries,
680 int memsize = sizeof(void*)*entries+sizeof(struct array_cache);
681 struct array_cache *nc = NULL;
684 nc = kmalloc(memsize, GFP_KERNEL);
686 nc = kmalloc_node(memsize, GFP_KERNEL, cpu_to_node(cpu));
691 nc->batchcount = batchcount;
697 static int __devinit cpuup_callback(struct notifier_block *nfb,
698 unsigned long action, void *hcpu)
700 long cpu = (long)hcpu;
701 kmem_cache_t* cachep;
705 down(&cache_chain_sem);
706 list_for_each_entry(cachep, &cache_chain, next) {
707 struct array_cache *nc;
709 nc = alloc_arraycache(cpu, cachep->limit, cachep->batchcount);
713 spin_lock_irq(&cachep->spinlock);
714 cachep->array[cpu] = nc;
715 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
717 spin_unlock_irq(&cachep->spinlock);
720 up(&cache_chain_sem);
723 start_cpu_timer(cpu);
725 #ifdef CONFIG_HOTPLUG_CPU
728 case CPU_UP_CANCELED:
729 down(&cache_chain_sem);
731 list_for_each_entry(cachep, &cache_chain, next) {
732 struct array_cache *nc;
734 spin_lock_irq(&cachep->spinlock);
735 /* cpu is dead; no one can alloc from it. */
736 nc = cachep->array[cpu];
737 cachep->array[cpu] = NULL;
738 cachep->free_limit -= cachep->batchcount;
739 free_block(cachep, ac_entry(nc), nc->avail);
740 spin_unlock_irq(&cachep->spinlock);
743 up(&cache_chain_sem);
749 up(&cache_chain_sem);
753 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
756 * Called after the gfp() functions have been enabled, and before smp_init().
758 void __init kmem_cache_init(void)
761 struct cache_sizes *sizes;
762 struct cache_names *names;
765 * Fragmentation resistance on low memory - only use bigger
766 * page orders on machines with more than 32MB of memory.
768 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
769 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
772 /* Bootstrap is tricky, because several objects are allocated
773 * from caches that do not exist yet:
774 * 1) initialize the cache_cache cache: it contains the kmem_cache_t
775 * structures of all caches, except cache_cache itself: cache_cache
776 * is statically allocated.
777 * Initially an __init data area is used for the head array, it's
778 * replaced with a kmalloc allocated array at the end of the bootstrap.
779 * 2) Create the first kmalloc cache.
780 * The kmem_cache_t for the new cache is allocated normally. An __init
781 * data area is used for the head array.
782 * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
783 * 4) Replace the __init data head arrays for cache_cache and the first
784 * kmalloc cache with kmalloc allocated arrays.
785 * 5) Resize the head arrays of the kmalloc caches to their final sizes.
788 /* 1) create the cache_cache */
789 init_MUTEX(&cache_chain_sem);
790 INIT_LIST_HEAD(&cache_chain);
791 list_add(&cache_cache.next, &cache_chain);
792 cache_cache.colour_off = cache_line_size();
793 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
795 cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
797 cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
798 &left_over, &cache_cache.num);
799 if (!cache_cache.num)
802 cache_cache.colour = left_over/cache_cache.colour_off;
803 cache_cache.colour_next = 0;
804 cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
805 sizeof(struct slab), cache_line_size());
807 /* 2+3) create the kmalloc caches */
808 sizes = malloc_sizes;
811 while (sizes->cs_size != ULONG_MAX) {
812 /* For performance, all the general caches are L1 aligned.
813 * This should be particularly beneficial on SMP boxes, as it
814 * eliminates "false sharing".
815 * Note for systems short on memory removing the alignment will
816 * allow tighter packing of the smaller caches. */
817 sizes->cs_cachep = kmem_cache_create(names->name,
818 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
819 (ARCH_KMALLOC_FLAGS | SLAB_PANIC), NULL, NULL);
821 /* Inc off-slab bufctl limit until the ceiling is hit. */
822 if (!(OFF_SLAB(sizes->cs_cachep))) {
823 offslab_limit = sizes->cs_size-sizeof(struct slab);
824 offslab_limit /= sizeof(kmem_bufctl_t);
827 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
828 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
829 (ARCH_KMALLOC_FLAGS | SLAB_CACHE_DMA | SLAB_PANIC),
835 /* 4) Replace the bootstrap head arrays */
839 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
841 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
842 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
843 cache_cache.array[smp_processor_id()] = ptr;
846 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
848 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
849 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
850 sizeof(struct arraycache_init));
851 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
855 /* 5) resize the head arrays to their final sizes */
857 kmem_cache_t *cachep;
858 down(&cache_chain_sem);
859 list_for_each_entry(cachep, &cache_chain, next)
860 enable_cpucache(cachep);
861 up(&cache_chain_sem);
865 g_cpucache_up = FULL;
867 /* Register a cpu startup notifier callback
868 * that initializes ac_data for all new cpus
870 register_cpu_notifier(&cpucache_notifier);
873 /* The reap timers are started later, with a module init call:
874 * That part of the kernel is not yet operational.
878 static int __init cpucache_init(void)
883 * Register the timers that return unneeded
886 for (cpu = 0; cpu < NR_CPUS; cpu++) {
888 start_cpu_timer(cpu);
894 __initcall(cpucache_init);
897 * Interface to system's page allocator. No need to hold the cache-lock.
899 * If we requested dmaable memory, we will get it. Even if we
900 * did not request dmaable memory, we might get it, but that
901 * would be relatively rare and ignorable.
903 static void *kmem_getpages(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
909 flags |= cachep->gfpflags;
910 if (likely(nodeid == -1)) {
911 page = alloc_pages(flags, cachep->gfporder);
913 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
917 addr = page_address(page);
919 i = (1 << cachep->gfporder);
920 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
921 atomic_add(i, &slab_reclaim_pages);
922 add_page_state(nr_slab, i);
931 * Interface to system's page release.
933 static void kmem_freepages(kmem_cache_t *cachep, void *addr)
935 unsigned long i = (1<<cachep->gfporder);
936 struct page *page = virt_to_page(addr);
937 const unsigned long nr_freed = i;
940 if (!TestClearPageSlab(page))
944 sub_page_state(nr_slab, nr_freed);
945 if (current->reclaim_state)
946 current->reclaim_state->reclaimed_slab += nr_freed;
947 free_pages((unsigned long)addr, cachep->gfporder);
948 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
949 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
952 static void kmem_rcu_free(struct rcu_head *head)
954 struct slab_rcu *slab_rcu = (struct slab_rcu *) head;
955 kmem_cache_t *cachep = slab_rcu->cachep;
957 kmem_freepages(cachep, slab_rcu->addr);
958 if (OFF_SLAB(cachep))
959 kmem_cache_free(cachep->slabp_cache, slab_rcu);
964 #ifdef CONFIG_DEBUG_PAGEALLOC
965 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr,
966 unsigned long caller)
968 int size = obj_reallen(cachep);
970 addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
972 if (size < 5*sizeof(unsigned long))
977 *addr++=smp_processor_id();
978 size -= 3*sizeof(unsigned long);
980 unsigned long *sptr = &caller;
981 unsigned long svalue;
983 while (!kstack_end(sptr)) {
985 if (kernel_text_address(svalue)) {
987 size -= sizeof(unsigned long);
988 if (size <= sizeof(unsigned long))
998 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
1000 int size = obj_reallen(cachep);
1001 addr = &((char*)addr)[obj_dbghead(cachep)];
1003 memset(addr, val, size);
1004 *(unsigned char *)(addr+size-1) = POISON_END;
1007 static void dump_line(char *data, int offset, int limit)
1010 unsigned char total=0;
1012 printk(KERN_ERR "%03x:", offset);
1013 for (i=0;i<limit;i++) {
1014 if (data[offset+i] != POISON_FREE)
1015 total += data[offset+i];
1016 if (check_tainted() == 0)
1017 printk(" %02x", (unsigned char)data[offset+i]);
1020 case 0: printk(" f3 3d");
1024 printk(" %02x", (unsigned char)data[offset+i]);
1038 printk (KERN_ERR "Single bit error detected. Possibly bad RAM. Run memtest86.\n");
1046 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
1051 if (cachep->flags & SLAB_RED_ZONE) {
1052 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1053 *dbg_redzone1(cachep, objp),
1054 *dbg_redzone2(cachep, objp));
1057 if (cachep->flags & SLAB_STORE_USER) {
1058 printk(KERN_ERR "Last user: [<%p>]",
1059 *dbg_userword(cachep, objp));
1060 print_symbol("(%s)",
1061 (unsigned long)*dbg_userword(cachep, objp));
1064 realobj = (char*)objp+obj_dbghead(cachep);
1065 size = obj_reallen(cachep);
1066 for (i=0; i<size && lines;i+=16, lines--) {
1071 dump_line(realobj, i, limit);
1075 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
1081 realobj = (char*)objp+obj_dbghead(cachep);
1082 size = obj_reallen(cachep);
1084 for (i=0;i<size;i++) {
1085 char exp = POISON_FREE;
1088 if (realobj[i] != exp) {
1093 printk(KERN_ERR "Slab corruption: (%s) start=%p, len=%d\n",
1094 print_tainted(), realobj, size);
1095 print_objinfo(cachep, objp, 0);
1098 /* Hexdump the affected line */
1103 dump_line(realobj, i, limit);
1106 /* Limit to 5 lines */
1112 /* Print some data about the neighboring objects, if they
1115 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1118 objnr = (objp-slabp->s_mem)/cachep->objsize;
1120 objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1121 realobj = (char*)objp+obj_dbghead(cachep);
1122 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1124 print_objinfo(cachep, objp, 2);
1126 if (objnr+1 < cachep->num) {
1127 objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1128 realobj = (char*)objp+obj_dbghead(cachep);
1129 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1131 print_objinfo(cachep, objp, 2);
1137 /* Destroy all the objs in a slab, and release the mem back to the system.
1138 * Before calling the slab must have been unlinked from the cache.
1139 * The cache-lock is not held/needed.
1141 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1143 void *addr = slabp->s_mem - slabp->colouroff;
1147 for (i = 0; i < cachep->num; i++) {
1148 void *objp = slabp->s_mem + cachep->objsize * i;
1150 if (cachep->flags & SLAB_POISON) {
1151 #ifdef CONFIG_DEBUG_PAGEALLOC
1152 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1153 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1155 check_poison_obj(cachep, objp);
1157 check_poison_obj(cachep, objp);
1160 if (cachep->flags & SLAB_RED_ZONE) {
1161 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1162 slab_error(cachep, "start of a freed object "
1164 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1165 slab_error(cachep, "end of a freed object "
1168 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1169 (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1174 for (i = 0; i < cachep->num; i++) {
1175 void* objp = slabp->s_mem+cachep->objsize*i;
1176 (cachep->dtor)(objp, cachep, 0);
1181 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1182 struct slab_rcu *slab_rcu;
1184 slab_rcu = (struct slab_rcu *) slabp;
1185 slab_rcu->cachep = cachep;
1186 slab_rcu->addr = addr;
1187 call_rcu(&slab_rcu->head, kmem_rcu_free);
1189 kmem_freepages(cachep, addr);
1190 if (OFF_SLAB(cachep))
1191 kmem_cache_free(cachep->slabp_cache, slabp);
1196 * kmem_cache_create - Create a cache.
1197 * @name: A string which is used in /proc/slabinfo to identify this cache.
1198 * @size: The size of objects to be created in this cache.
1199 * @align: The required alignment for the objects.
1200 * @flags: SLAB flags
1201 * @ctor: A constructor for the objects.
1202 * @dtor: A destructor for the objects.
1204 * Returns a ptr to the cache on success, NULL on failure.
1205 * Cannot be called within a int, but can be interrupted.
1206 * The @ctor is run when new pages are allocated by the cache
1207 * and the @dtor is run before the pages are handed back.
1209 * @name must be valid until the cache is destroyed. This implies that
1210 * the module calling this has to destroy the cache before getting
1215 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1216 * to catch references to uninitialised memory.
1218 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1219 * for buffer overruns.
1221 * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1224 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1225 * cacheline. This can be beneficial if you're counting cycles as closely
1229 kmem_cache_create (const char *name, size_t size, size_t align,
1230 unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1231 void (*dtor)(void*, kmem_cache_t *, unsigned long))
1233 size_t left_over, slab_size, ralign;
1234 kmem_cache_t *cachep = NULL;
1237 * Sanity checks... these are all serious usage bugs.
1241 (size < BYTES_PER_WORD) ||
1242 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1244 printk(KERN_ERR "%s: Early error in slab %s\n",
1245 __FUNCTION__, name);
1250 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
1251 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1252 /* No constructor, but inital state check requested */
1253 printk(KERN_ERR "%s: No con, but init state check "
1254 "requested - %s\n", __FUNCTION__, name);
1255 flags &= ~SLAB_DEBUG_INITIAL;
1260 * Enable redzoning and last user accounting, except for caches with
1261 * large objects, if the increased size would increase the object size
1262 * above the next power of two: caches with object sizes just above a
1263 * power of two have a significant amount of internal fragmentation.
1265 if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1266 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1267 if (!(flags & SLAB_DESTROY_BY_RCU))
1268 flags |= SLAB_POISON;
1270 if (flags & SLAB_DESTROY_BY_RCU)
1271 BUG_ON(flags & SLAB_POISON);
1273 if (flags & SLAB_DESTROY_BY_RCU)
1277 * Always checks flags, a caller might be expecting debug
1278 * support which isn't available.
1280 if (flags & ~CREATE_MASK)
1283 /* Check that size is in terms of words. This is needed to avoid
1284 * unaligned accesses for some archs when redzoning is used, and makes
1285 * sure any on-slab bufctl's are also correctly aligned.
1287 if (size & (BYTES_PER_WORD-1)) {
1288 size += (BYTES_PER_WORD-1);
1289 size &= ~(BYTES_PER_WORD-1);
1292 /* calculate out the final buffer alignment: */
1293 /* 1) arch recommendation: can be overridden for debug */
1294 if (flags & SLAB_HWCACHE_ALIGN) {
1295 /* Default alignment: as specified by the arch code.
1296 * Except if an object is really small, then squeeze multiple
1297 * objects into one cacheline.
1299 ralign = cache_line_size();
1300 while (size <= ralign/2)
1303 ralign = BYTES_PER_WORD;
1305 /* 2) arch mandated alignment: disables debug if necessary */
1306 if (ralign < ARCH_SLAB_MINALIGN) {
1307 ralign = ARCH_SLAB_MINALIGN;
1308 if (ralign > BYTES_PER_WORD)
1309 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1311 /* 3) caller mandated alignment: disables debug if necessary */
1312 if (ralign < align) {
1314 if (ralign > BYTES_PER_WORD)
1315 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1317 /* 4) Store it. Note that the debug code below can reduce
1318 * the alignment to BYTES_PER_WORD.
1322 /* Get cache's description obj. */
1323 cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1326 memset(cachep, 0, sizeof(kmem_cache_t));
1329 cachep->reallen = size;
1331 if (flags & SLAB_RED_ZONE) {
1332 /* redzoning only works with word aligned caches */
1333 align = BYTES_PER_WORD;
1335 /* add space for red zone words */
1336 cachep->dbghead += BYTES_PER_WORD;
1337 size += 2*BYTES_PER_WORD;
1339 if (flags & SLAB_STORE_USER) {
1340 /* user store requires word alignment and
1341 * one word storage behind the end of the real
1344 align = BYTES_PER_WORD;
1345 size += BYTES_PER_WORD;
1347 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1348 if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1349 cachep->dbghead += PAGE_SIZE - size;
1355 /* Determine if the slab management is 'on' or 'off' slab. */
1356 if (size >= (PAGE_SIZE>>3))
1358 * Size is large, assume best to place the slab management obj
1359 * off-slab (should allow better packing of objs).
1361 flags |= CFLGS_OFF_SLAB;
1363 size = ALIGN(size, align);
1365 if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1367 * A VFS-reclaimable slab tends to have most allocations
1368 * as GFP_NOFS and we really don't want to have to be allocating
1369 * higher-order pages when we are unable to shrink dcache.
1371 cachep->gfporder = 0;
1372 cache_estimate(cachep->gfporder, size, align, flags,
1373 &left_over, &cachep->num);
1376 * Calculate size (in pages) of slabs, and the num of objs per
1377 * slab. This could be made much more intelligent. For now,
1378 * try to avoid using high page-orders for slabs. When the
1379 * gfp() funcs are more friendly towards high-order requests,
1380 * this should be changed.
1383 unsigned int break_flag = 0;
1385 cache_estimate(cachep->gfporder, size, align, flags,
1386 &left_over, &cachep->num);
1389 if (cachep->gfporder >= MAX_GFP_ORDER)
1393 if (flags & CFLGS_OFF_SLAB &&
1394 cachep->num > offslab_limit) {
1395 /* This num of objs will cause problems. */
1402 * Large num of objs is good, but v. large slabs are
1403 * currently bad for the gfp()s.
1405 if (cachep->gfporder >= slab_break_gfp_order)
1408 if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1409 break; /* Acceptable internal fragmentation. */
1416 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1417 kmem_cache_free(&cache_cache, cachep);
1421 slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1422 + sizeof(struct slab), align);
1425 * If the slab has been placed off-slab, and we have enough space then
1426 * move it on-slab. This is at the expense of any extra colouring.
1428 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1429 flags &= ~CFLGS_OFF_SLAB;
1430 left_over -= slab_size;
1433 if (flags & CFLGS_OFF_SLAB) {
1434 /* really off slab. No need for manual alignment */
1435 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1438 cachep->colour_off = cache_line_size();
1439 /* Offset must be a multiple of the alignment. */
1440 if (cachep->colour_off < align)
1441 cachep->colour_off = align;
1442 cachep->colour = left_over/cachep->colour_off;
1443 cachep->slab_size = slab_size;
1444 cachep->flags = flags;
1445 cachep->gfpflags = 0;
1446 if (flags & SLAB_CACHE_DMA)
1447 cachep->gfpflags |= GFP_DMA;
1448 spin_lock_init(&cachep->spinlock);
1449 cachep->objsize = size;
1451 INIT_LIST_HEAD(&cachep->lists.slabs_full);
1452 INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1453 INIT_LIST_HEAD(&cachep->lists.slabs_free);
1455 if (flags & CFLGS_OFF_SLAB)
1456 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1457 cachep->ctor = ctor;
1458 cachep->dtor = dtor;
1459 cachep->name = name;
1461 /* Don't let CPUs to come and go */
1464 if (g_cpucache_up == FULL) {
1465 enable_cpucache(cachep);
1467 if (g_cpucache_up == NONE) {
1468 /* Note: the first kmem_cache_create must create
1469 * the cache that's used by kmalloc(24), otherwise
1470 * the creation of further caches will BUG().
1472 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1473 g_cpucache_up = PARTIAL;
1475 cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1477 BUG_ON(!ac_data(cachep));
1478 ac_data(cachep)->avail = 0;
1479 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1480 ac_data(cachep)->batchcount = 1;
1481 ac_data(cachep)->touched = 0;
1482 cachep->batchcount = 1;
1483 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1484 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1488 cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1489 ((unsigned long)cachep/L1_CACHE_BYTES)%REAPTIMEOUT_LIST3;
1491 cachep->redzonetest = jiffies + REDZONETIMEOUT +
1492 ((unsigned long)cachep/L1_CACHE_BYTES)%REDZONETIMEOUT;
1495 /* Need the semaphore to access the chain. */
1496 down(&cache_chain_sem);
1498 struct list_head *p;
1499 mm_segment_t old_fs;
1503 list_for_each(p, &cache_chain) {
1504 kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1506 /* This happens when the module gets unloaded and doesn't
1507 destroy its slab cache and noone else reuses the vmalloc
1508 area of the module. Print a warning. */
1509 if (__get_user(tmp,pc->name)) {
1510 printk("SLAB: cache with size %d has lost its name\n",
1514 if (!strcmp(pc->name,name)) {
1515 printk("kmem_cache_create: duplicate cache %s\n",name);
1516 up(&cache_chain_sem);
1517 unlock_cpu_hotplug();
1524 /* cache setup completed, link it into the list */
1525 list_add(&cachep->next, &cache_chain);
1526 up(&cache_chain_sem);
1527 unlock_cpu_hotplug();
1529 if (!cachep && (flags & SLAB_PANIC))
1530 panic("kmem_cache_create(): failed to create slab `%s'\n",
1534 EXPORT_SYMBOL(kmem_cache_create);
1537 static void check_irq_off(void)
1539 BUG_ON(!irqs_disabled());
1542 static void check_irq_on(void)
1544 BUG_ON(irqs_disabled());
1547 static void check_spinlock_acquired(kmem_cache_t *cachep)
1551 BUG_ON(spin_trylock(&cachep->spinlock));
1555 #define check_irq_off() do { } while(0)
1556 #define check_irq_on() do { } while(0)
1557 #define check_spinlock_acquired(x) do { } while(0)
1561 * Waits for all CPUs to execute func().
1563 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1568 local_irq_disable();
1572 if (smp_call_function(func, arg, 1, 1))
1578 static void drain_array_locked(kmem_cache_t* cachep,
1579 struct array_cache *ac, int force);
1581 static void do_drain(void *arg)
1583 kmem_cache_t *cachep = (kmem_cache_t*)arg;
1584 struct array_cache *ac;
1587 ac = ac_data(cachep);
1588 spin_lock(&cachep->spinlock);
1589 free_block(cachep, &ac_entry(ac)[0], ac->avail);
1590 spin_unlock(&cachep->spinlock);
1594 static void drain_cpu_caches(kmem_cache_t *cachep)
1596 smp_call_function_all_cpus(do_drain, cachep);
1598 spin_lock_irq(&cachep->spinlock);
1599 if (cachep->lists.shared)
1600 drain_array_locked(cachep, cachep->lists.shared, 1);
1601 spin_unlock_irq(&cachep->spinlock);
1605 /* NUMA shrink all list3s */
1606 static int __cache_shrink(kmem_cache_t *cachep)
1611 drain_cpu_caches(cachep);
1614 spin_lock_irq(&cachep->spinlock);
1617 struct list_head *p;
1619 p = cachep->lists.slabs_free.prev;
1620 if (p == &cachep->lists.slabs_free)
1623 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1628 list_del(&slabp->list);
1630 cachep->lists.free_objects -= cachep->num;
1631 spin_unlock_irq(&cachep->spinlock);
1632 slab_destroy(cachep, slabp);
1633 spin_lock_irq(&cachep->spinlock);
1635 ret = !list_empty(&cachep->lists.slabs_full) ||
1636 !list_empty(&cachep->lists.slabs_partial);
1637 spin_unlock_irq(&cachep->spinlock);
1642 * kmem_cache_shrink - Shrink a cache.
1643 * @cachep: The cache to shrink.
1645 * Releases as many slabs as possible for a cache.
1646 * To help debugging, a zero exit status indicates all slabs were released.
1648 int kmem_cache_shrink(kmem_cache_t *cachep)
1650 if (!cachep || in_interrupt())
1653 return __cache_shrink(cachep);
1655 EXPORT_SYMBOL(kmem_cache_shrink);
1658 * kmem_cache_destroy - delete a cache
1659 * @cachep: the cache to destroy
1661 * Remove a kmem_cache_t object from the slab cache.
1662 * Returns 0 on success.
1664 * It is expected this function will be called by a module when it is
1665 * unloaded. This will remove the cache completely, and avoid a duplicate
1666 * cache being allocated each time a module is loaded and unloaded, if the
1667 * module doesn't have persistent in-kernel storage across loads and unloads.
1669 * The cache must be empty before calling this function.
1671 * The caller must guarantee that noone will allocate memory from the cache
1672 * during the kmem_cache_destroy().
1674 int kmem_cache_destroy(kmem_cache_t * cachep)
1678 if (!cachep || in_interrupt())
1681 /* Don't let CPUs to come and go */
1684 /* Find the cache in the chain of caches. */
1685 down(&cache_chain_sem);
1687 * the chain is never empty, cache_cache is never destroyed
1689 list_del(&cachep->next);
1690 up(&cache_chain_sem);
1692 if (__cache_shrink(cachep)) {
1693 slab_error(cachep, "Can't free all objects");
1694 down(&cache_chain_sem);
1695 list_add(&cachep->next,&cache_chain);
1696 up(&cache_chain_sem);
1697 unlock_cpu_hotplug();
1701 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1704 /* no cpu_online check required here since we clear the percpu
1705 * array on cpu offline and set this to NULL.
1707 for (i = 0; i < NR_CPUS; i++)
1708 kfree(cachep->array[i]);
1710 /* NUMA: free the list3 structures */
1711 kfree(cachep->lists.shared);
1712 cachep->lists.shared = NULL;
1713 kmem_cache_free(&cache_cache, cachep);
1715 unlock_cpu_hotplug();
1719 EXPORT_SYMBOL(kmem_cache_destroy);
1721 /* Get the memory for a slab management obj. */
1722 static struct slab* alloc_slabmgmt(kmem_cache_t *cachep,
1723 void *objp, int colour_off, unsigned int __nocast local_flags)
1727 if (OFF_SLAB(cachep)) {
1728 /* Slab management obj is off-slab. */
1729 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1733 slabp = objp+colour_off;
1734 colour_off += cachep->slab_size;
1737 slabp->colouroff = colour_off;
1738 slabp->s_mem = objp+colour_off;
1743 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1745 return (kmem_bufctl_t *)(slabp+1);
1748 static void cache_init_objs(kmem_cache_t *cachep,
1749 struct slab *slabp, unsigned long ctor_flags)
1753 for (i = 0; i < cachep->num; i++) {
1754 void* objp = slabp->s_mem+cachep->objsize*i;
1756 /* need to poison the objs? */
1757 if (cachep->flags & SLAB_POISON)
1758 poison_obj(cachep, objp, POISON_FREE);
1759 if (cachep->flags & SLAB_STORE_USER)
1760 *dbg_userword(cachep, objp) = NULL;
1762 if (cachep->flags & SLAB_RED_ZONE) {
1763 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1764 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1767 * Constructors are not allowed to allocate memory from
1768 * the same cache which they are a constructor for.
1769 * Otherwise, deadlock. They must also be threaded.
1771 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1772 cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1774 if (cachep->flags & SLAB_RED_ZONE) {
1775 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1776 slab_error(cachep, "constructor overwrote the"
1777 " end of an object");
1778 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1779 slab_error(cachep, "constructor overwrote the"
1780 " start of an object");
1782 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1783 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1786 cachep->ctor(objp, cachep, ctor_flags);
1788 slab_bufctl(slabp)[i] = i+1;
1790 slab_bufctl(slabp)[i-1] = BUFCTL_END;
1794 static void kmem_flagcheck(kmem_cache_t *cachep, unsigned int flags)
1796 if (flags & SLAB_DMA) {
1797 if (!(cachep->gfpflags & GFP_DMA))
1800 if (cachep->gfpflags & GFP_DMA)
1805 static void set_slab_attr(kmem_cache_t *cachep, struct slab *slabp, void *objp)
1810 /* Nasty!!!!!! I hope this is OK. */
1811 i = 1 << cachep->gfporder;
1812 page = virt_to_page(objp);
1814 SET_PAGE_CACHE(page, cachep);
1815 SET_PAGE_SLAB(page, slabp);
1821 * Grow (by 1) the number of slabs within a cache. This is called by
1822 * kmem_cache_alloc() when there are no active objs left in a cache.
1824 static int cache_grow(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
1829 unsigned int local_flags;
1830 unsigned long ctor_flags;
1832 /* Be lazy and only check for valid flags here,
1833 * keeping it out of the critical path in kmem_cache_alloc().
1835 if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1837 if (flags & SLAB_NO_GROW)
1840 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1841 local_flags = (flags & SLAB_LEVEL_MASK);
1842 if (!(local_flags & __GFP_WAIT))
1844 * Not allowed to sleep. Need to tell a constructor about
1845 * this - it might need to know...
1847 ctor_flags |= SLAB_CTOR_ATOMIC;
1849 /* About to mess with non-constant members - lock. */
1851 spin_lock(&cachep->spinlock);
1853 /* Get colour for the slab, and cal the next value. */
1854 offset = cachep->colour_next;
1855 cachep->colour_next++;
1856 if (cachep->colour_next >= cachep->colour)
1857 cachep->colour_next = 0;
1858 offset *= cachep->colour_off;
1860 spin_unlock(&cachep->spinlock);
1862 if (local_flags & __GFP_WAIT)
1866 * The test for missing atomic flag is performed here, rather than
1867 * the more obvious place, simply to reduce the critical path length
1868 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1869 * will eventually be caught here (where it matters).
1871 kmem_flagcheck(cachep, flags);
1874 /* Get mem for the objs. */
1875 if (!(objp = kmem_getpages(cachep, flags, nodeid)))
1878 /* Get slab management. */
1879 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1882 set_slab_attr(cachep, slabp, objp);
1884 cache_init_objs(cachep, slabp, ctor_flags);
1886 if (local_flags & __GFP_WAIT)
1887 local_irq_disable();
1889 spin_lock(&cachep->spinlock);
1891 /* Make slab active. */
1892 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1893 STATS_INC_GROWN(cachep);
1894 list3_data(cachep)->free_objects += cachep->num;
1895 spin_unlock(&cachep->spinlock);
1898 kmem_freepages(cachep, objp);
1900 if (local_flags & __GFP_WAIT)
1901 local_irq_disable();
1908 * Perform extra freeing checks:
1909 * - detect bad pointers.
1910 * - POISON/RED_ZONE checking
1911 * - destructor calls, for caches with POISON+dtor
1913 static void kfree_debugcheck(const void *objp)
1917 if (!virt_addr_valid(objp)) {
1918 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1919 (unsigned long)objp);
1922 page = virt_to_page(objp);
1923 if (!PageSlab(page)) {
1924 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1929 static void *cache_free_debugcheck(kmem_cache_t *cachep, void *objp,
1936 objp -= obj_dbghead(cachep);
1937 kfree_debugcheck(objp);
1938 page = virt_to_page(objp);
1940 if (GET_PAGE_CACHE(page) != cachep) {
1941 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1942 GET_PAGE_CACHE(page),cachep);
1943 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1944 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1947 slabp = GET_PAGE_SLAB(page);
1949 if (cachep->flags & SLAB_RED_ZONE) {
1950 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1951 slab_error(cachep, "double free, or memory outside"
1952 " object was overwritten");
1953 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1954 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1956 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1957 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1959 if (cachep->flags & SLAB_STORE_USER)
1960 *dbg_userword(cachep, objp) = caller;
1962 objnr = (objp-slabp->s_mem)/cachep->objsize;
1964 BUG_ON(objnr >= cachep->num);
1965 BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1967 if (cachep->flags & SLAB_DEBUG_INITIAL) {
1968 /* Need to call the slab's constructor so the
1969 * caller can perform a verify of its state (debugging).
1970 * Called without the cache-lock held.
1972 cachep->ctor(objp+obj_dbghead(cachep),
1973 cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1975 if (cachep->flags & SLAB_POISON && cachep->dtor) {
1976 /* we want to cache poison the object,
1977 * call the destruction callback
1979 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1981 if (cachep->flags & SLAB_POISON) {
1982 #ifdef CONFIG_DEBUG_PAGEALLOC
1983 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1984 store_stackinfo(cachep, objp, (unsigned long)caller);
1985 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1987 poison_obj(cachep, objp, POISON_FREE);
1990 poison_obj(cachep, objp, POISON_FREE);
1996 static void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
2001 check_spinlock_acquired(cachep);
2002 /* Check slab's freelist to see if this obj is there. */
2003 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2005 if (entries > cachep->num || i >= cachep->num)
2008 if (entries != cachep->num - slabp->inuse) {
2010 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2011 cachep->name, cachep->num, slabp, slabp->inuse);
2012 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
2014 printk("\n%03x:", i);
2015 printk(" %02x", ((unsigned char*)slabp)[i]);
2022 #define kfree_debugcheck(x) do { } while(0)
2023 #define cache_free_debugcheck(x,objp,z) (objp)
2024 #define check_slabp(x,y) do { } while(0)
2027 static void *cache_alloc_refill(kmem_cache_t *cachep, unsigned int __nocast flags)
2030 struct kmem_list3 *l3;
2031 struct array_cache *ac;
2034 ac = ac_data(cachep);
2036 batchcount = ac->batchcount;
2037 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2038 /* if there was little recent activity on this
2039 * cache, then perform only a partial refill.
2040 * Otherwise we could generate refill bouncing.
2042 batchcount = BATCHREFILL_LIMIT;
2044 l3 = list3_data(cachep);
2046 BUG_ON(ac->avail > 0);
2047 spin_lock(&cachep->spinlock);
2049 struct array_cache *shared_array = l3->shared;
2050 if (shared_array->avail) {
2051 if (batchcount > shared_array->avail)
2052 batchcount = shared_array->avail;
2053 shared_array->avail -= batchcount;
2054 ac->avail = batchcount;
2055 memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
2056 sizeof(void*)*batchcount);
2057 shared_array->touched = 1;
2061 while (batchcount > 0) {
2062 struct list_head *entry;
2064 /* Get slab alloc is to come from. */
2065 entry = l3->slabs_partial.next;
2066 if (entry == &l3->slabs_partial) {
2067 l3->free_touched = 1;
2068 entry = l3->slabs_free.next;
2069 if (entry == &l3->slabs_free)
2073 slabp = list_entry(entry, struct slab, list);
2074 check_slabp(cachep, slabp);
2075 check_spinlock_acquired(cachep);
2076 while (slabp->inuse < cachep->num && batchcount--) {
2078 STATS_INC_ALLOCED(cachep);
2079 STATS_INC_ACTIVE(cachep);
2080 STATS_SET_HIGH(cachep);
2082 /* get obj pointer */
2083 ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
2086 next = slab_bufctl(slabp)[slabp->free];
2088 slab_bufctl(slabp)[slabp->free] = BUFCTL_ALLOC;
2092 check_slabp(cachep, slabp);
2094 /* move slabp to correct slabp list: */
2095 list_del(&slabp->list);
2096 if (slabp->free == BUFCTL_END)
2097 list_add(&slabp->list, &l3->slabs_full);
2099 list_add(&slabp->list, &l3->slabs_partial);
2103 l3->free_objects -= ac->avail;
2105 spin_unlock(&cachep->spinlock);
2107 if (unlikely(!ac->avail)) {
2109 x = cache_grow(cachep, flags, -1);
2111 // cache_grow can reenable interrupts, then ac could change.
2112 ac = ac_data(cachep);
2113 if (!x && ac->avail == 0) // no objects in sight? abort
2116 if (!ac->avail) // objects refilled by interrupt?
2120 return ac_entry(ac)[--ac->avail];
2124 cache_alloc_debugcheck_before(kmem_cache_t *cachep, unsigned int __nocast flags)
2126 might_sleep_if(flags & __GFP_WAIT);
2128 kmem_flagcheck(cachep, flags);
2134 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
2135 unsigned long flags, void *objp, void *caller)
2139 if (cachep->flags & SLAB_POISON) {
2140 #ifdef CONFIG_DEBUG_PAGEALLOC
2141 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2142 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
2144 check_poison_obj(cachep, objp);
2146 check_poison_obj(cachep, objp);
2148 poison_obj(cachep, objp, POISON_INUSE);
2150 if (cachep->flags & SLAB_STORE_USER)
2151 *dbg_userword(cachep, objp) = caller;
2153 if (cachep->flags & SLAB_RED_ZONE) {
2154 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2155 slab_error(cachep, "double free, or memory outside"
2156 " object was overwritten");
2157 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
2158 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2160 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2161 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2163 objp += obj_dbghead(cachep);
2164 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2165 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2167 if (!(flags & __GFP_WAIT))
2168 ctor_flags |= SLAB_CTOR_ATOMIC;
2170 cachep->ctor(objp, cachep, ctor_flags);
2175 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2179 static inline void *__cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2181 unsigned long save_flags;
2183 struct array_cache *ac;
2185 cache_alloc_debugcheck_before(cachep, flags);
2187 local_irq_save(save_flags);
2188 ac = ac_data(cachep);
2189 if (likely(ac->avail)) {
2190 STATS_INC_ALLOCHIT(cachep);
2192 objp = ac_entry(ac)[--ac->avail];
2194 STATS_INC_ALLOCMISS(cachep);
2195 objp = cache_alloc_refill(cachep, flags);
2197 local_irq_restore(save_flags);
2198 objp = cache_alloc_debugcheck_after(cachep, flags, objp, __builtin_return_address(0));
2203 * NUMA: different approach needed if the spinlock is moved into
2207 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2211 check_spinlock_acquired(cachep);
2213 /* NUMA: move add into loop */
2214 cachep->lists.free_objects += nr_objects;
2216 for (i = 0; i < nr_objects; i++) {
2217 void *objp = objpp[i];
2221 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2222 list_del(&slabp->list);
2223 objnr = (objp - slabp->s_mem) / cachep->objsize;
2224 check_slabp(cachep, slabp);
2226 if (slab_bufctl(slabp)[objnr] != BUFCTL_ALLOC) {
2227 printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2228 cachep->name, objp);
2232 slab_bufctl(slabp)[objnr] = slabp->free;
2233 slabp->free = objnr;
2234 STATS_DEC_ACTIVE(cachep);
2236 check_slabp(cachep, slabp);
2238 /* fixup slab chains */
2239 if (slabp->inuse == 0) {
2240 if (cachep->lists.free_objects > cachep->free_limit) {
2241 cachep->lists.free_objects -= cachep->num;
2242 slab_destroy(cachep, slabp);
2244 list_add(&slabp->list,
2245 &list3_data_ptr(cachep, objp)->slabs_free);
2248 /* Unconditionally move a slab to the end of the
2249 * partial list on free - maximum time for the
2250 * other objects to be freed, too.
2252 list_add_tail(&slabp->list,
2253 &list3_data_ptr(cachep, objp)->slabs_partial);
2258 static void cache_flusharray(kmem_cache_t *cachep, struct array_cache *ac)
2262 batchcount = ac->batchcount;
2264 BUG_ON(!batchcount || batchcount > ac->avail);
2267 spin_lock(&cachep->spinlock);
2268 if (cachep->lists.shared) {
2269 struct array_cache *shared_array = cachep->lists.shared;
2270 int max = shared_array->limit-shared_array->avail;
2272 if (batchcount > max)
2274 memcpy(&ac_entry(shared_array)[shared_array->avail],
2276 sizeof(void*)*batchcount);
2277 shared_array->avail += batchcount;
2282 free_block(cachep, &ac_entry(ac)[0], batchcount);
2287 struct list_head *p;
2289 p = list3_data(cachep)->slabs_free.next;
2290 while (p != &(list3_data(cachep)->slabs_free)) {
2293 slabp = list_entry(p, struct slab, list);
2294 BUG_ON(slabp->inuse);
2299 STATS_SET_FREEABLE(cachep, i);
2302 spin_unlock(&cachep->spinlock);
2303 ac->avail -= batchcount;
2304 memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2305 sizeof(void*)*ac->avail);
2310 * Release an obj back to its cache. If the obj has a constructed
2311 * state, it must be in this state _before_ it is released.
2313 * Called with disabled ints.
2315 static inline void __cache_free(kmem_cache_t *cachep, void *objp)
2317 struct array_cache *ac = ac_data(cachep);
2320 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2322 if (likely(ac->avail < ac->limit)) {
2323 STATS_INC_FREEHIT(cachep);
2324 ac_entry(ac)[ac->avail++] = objp;
2327 STATS_INC_FREEMISS(cachep);
2328 cache_flusharray(cachep, ac);
2329 ac_entry(ac)[ac->avail++] = objp;
2334 * kmem_cache_alloc - Allocate an object
2335 * @cachep: The cache to allocate from.
2336 * @flags: See kmalloc().
2338 * Allocate an object from this cache. The flags are only relevant
2339 * if the cache has no available objects.
2341 void *kmem_cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2343 return __cache_alloc(cachep, flags);
2345 EXPORT_SYMBOL(kmem_cache_alloc);
2348 * kmem_ptr_validate - check if an untrusted pointer might
2350 * @cachep: the cache we're checking against
2351 * @ptr: pointer to validate
2353 * This verifies that the untrusted pointer looks sane:
2354 * it is _not_ a guarantee that the pointer is actually
2355 * part of the slab cache in question, but it at least
2356 * validates that the pointer can be dereferenced and
2357 * looks half-way sane.
2359 * Currently only used for dentry validation.
2361 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2363 unsigned long addr = (unsigned long) ptr;
2364 unsigned long min_addr = PAGE_OFFSET;
2365 unsigned long align_mask = BYTES_PER_WORD-1;
2366 unsigned long size = cachep->objsize;
2369 if (unlikely(addr < min_addr))
2371 if (unlikely(addr > (unsigned long)high_memory - size))
2373 if (unlikely(addr & align_mask))
2375 if (unlikely(!kern_addr_valid(addr)))
2377 if (unlikely(!kern_addr_valid(addr + size - 1)))
2379 page = virt_to_page(ptr);
2380 if (unlikely(!PageSlab(page)))
2382 if (unlikely(GET_PAGE_CACHE(page) != cachep))
2391 * kmem_cache_alloc_node - Allocate an object on the specified node
2392 * @cachep: The cache to allocate from.
2393 * @flags: See kmalloc().
2394 * @nodeid: node number of the target node.
2396 * Identical to kmem_cache_alloc, except that this function is slow
2397 * and can sleep. And it will allocate memory on the given node, which
2398 * can improve the performance for cpu bound structures.
2400 void *kmem_cache_alloc_node(kmem_cache_t *cachep, int flags, int nodeid)
2407 for (loop = 0;;loop++) {
2408 struct list_head *q;
2412 spin_lock_irq(&cachep->spinlock);
2413 /* walk through all partial and empty slab and find one
2414 * from the right node */
2415 list_for_each(q,&cachep->lists.slabs_partial) {
2416 slabp = list_entry(q, struct slab, list);
2418 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2422 list_for_each(q, &cachep->lists.slabs_free) {
2423 slabp = list_entry(q, struct slab, list);
2425 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2429 spin_unlock_irq(&cachep->spinlock);
2431 local_irq_disable();
2432 if (!cache_grow(cachep, flags, nodeid)) {
2439 /* found one: allocate object */
2440 check_slabp(cachep, slabp);
2441 check_spinlock_acquired(cachep);
2443 STATS_INC_ALLOCED(cachep);
2444 STATS_INC_ACTIVE(cachep);
2445 STATS_SET_HIGH(cachep);
2446 STATS_INC_NODEALLOCS(cachep);
2448 objp = slabp->s_mem + slabp->free*cachep->objsize;
2451 next = slab_bufctl(slabp)[slabp->free];
2453 slab_bufctl(slabp)[slabp->free] = BUFCTL_ALLOC;
2456 check_slabp(cachep, slabp);
2458 /* move slabp to correct slabp list: */
2459 list_del(&slabp->list);
2460 if (slabp->free == BUFCTL_END)
2461 list_add(&slabp->list, &cachep->lists.slabs_full);
2463 list_add(&slabp->list, &cachep->lists.slabs_partial);
2465 list3_data(cachep)->free_objects--;
2466 spin_unlock_irq(&cachep->spinlock);
2468 objp = cache_alloc_debugcheck_after(cachep, GFP_KERNEL, objp,
2469 __builtin_return_address(0));
2472 EXPORT_SYMBOL(kmem_cache_alloc_node);
2474 void *kmalloc_node(size_t size, int flags, int node)
2476 kmem_cache_t *cachep;
2478 cachep = kmem_find_general_cachep(size, flags);
2479 if (unlikely(cachep == NULL))
2481 return kmem_cache_alloc_node(cachep, flags, node);
2483 EXPORT_SYMBOL(kmalloc_node);
2487 * kmalloc - allocate memory
2488 * @size: how many bytes of memory are required.
2489 * @flags: the type of memory to allocate.
2491 * kmalloc is the normal method of allocating memory
2494 * The @flags argument may be one of:
2496 * %GFP_USER - Allocate memory on behalf of user. May sleep.
2498 * %GFP_KERNEL - Allocate normal kernel ram. May sleep.
2500 * %GFP_ATOMIC - Allocation will not sleep. Use inside interrupt handlers.
2502 * Additionally, the %GFP_DMA flag may be set to indicate the memory
2503 * must be suitable for DMA. This can mean different things on different
2504 * platforms. For example, on i386, it means that the memory must come
2505 * from the first 16MB.
2507 void *__kmalloc(size_t size, unsigned int __nocast flags)
2509 kmem_cache_t *cachep;
2511 /* If you want to save a few bytes .text space: replace
2513 * Then kmalloc uses the uninlined functions instead of the inline
2516 cachep = __find_general_cachep(size, flags);
2517 if (unlikely(cachep == NULL))
2519 return __cache_alloc(cachep, flags);
2521 EXPORT_SYMBOL(__kmalloc);
2525 * __alloc_percpu - allocate one copy of the object for every present
2526 * cpu in the system, zeroing them.
2527 * Objects should be dereferenced using the per_cpu_ptr macro only.
2529 * @size: how many bytes of memory are required.
2530 * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2532 void *__alloc_percpu(size_t size, size_t align)
2535 struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2540 for (i = 0; i < NR_CPUS; i++) {
2541 if (!cpu_possible(i))
2543 pdata->ptrs[i] = kmalloc_node(size, GFP_KERNEL,
2546 if (!pdata->ptrs[i])
2548 memset(pdata->ptrs[i], 0, size);
2551 /* Catch derefs w/o wrappers */
2552 return (void *) (~(unsigned long) pdata);
2556 if (!cpu_possible(i))
2558 kfree(pdata->ptrs[i]);
2563 EXPORT_SYMBOL(__alloc_percpu);
2567 * kmem_cache_free - Deallocate an object
2568 * @cachep: The cache the allocation was from.
2569 * @objp: The previously allocated object.
2571 * Free an object which was previously allocated from this
2574 void kmem_cache_free(kmem_cache_t *cachep, void *objp)
2576 unsigned long flags;
2578 local_irq_save(flags);
2579 __cache_free(cachep, objp);
2580 local_irq_restore(flags);
2582 EXPORT_SYMBOL(kmem_cache_free);
2585 * kcalloc - allocate memory for an array. The memory is set to zero.
2586 * @n: number of elements.
2587 * @size: element size.
2588 * @flags: the type of memory to allocate.
2590 void *kcalloc(size_t n, size_t size, unsigned int __nocast flags)
2594 if (n != 0 && size > INT_MAX / n)
2597 ret = kmalloc(n * size, flags);
2599 memset(ret, 0, n * size);
2602 EXPORT_SYMBOL(kcalloc);
2605 * kfree - free previously allocated memory
2606 * @objp: pointer returned by kmalloc.
2608 * Don't free memory not originally allocated by kmalloc()
2609 * or you will run into trouble.
2611 void kfree(const void *objp)
2614 unsigned long flags;
2616 if (unlikely(!objp))
2618 local_irq_save(flags);
2619 kfree_debugcheck(objp);
2620 c = GET_PAGE_CACHE(virt_to_page(objp));
2621 __cache_free(c, (void*)objp);
2622 local_irq_restore(flags);
2624 EXPORT_SYMBOL(kfree);
2628 * free_percpu - free previously allocated percpu memory
2629 * @objp: pointer returned by alloc_percpu.
2631 * Don't free memory not originally allocated by alloc_percpu()
2632 * The complemented objp is to check for that.
2635 free_percpu(const void *objp)
2638 struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2640 for (i = 0; i < NR_CPUS; i++) {
2641 if (!cpu_possible(i))
2647 EXPORT_SYMBOL(free_percpu);
2650 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2652 return obj_reallen(cachep);
2654 EXPORT_SYMBOL(kmem_cache_size);
2657 static void check_slabuse(kmem_cache_t *cachep, struct slab *slabp)
2661 if (!(cachep->flags & SLAB_RED_ZONE))
2662 return; /* no redzone data to check */
2664 #if CONFIG_DEBUG_PAGEALLOC
2665 /* Page alloc debugging on for this cache. Mapping & Unmapping happens
2666 * without any locking, thus parallel checks are impossible.
2668 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
2672 for (i=0;i<cachep->num;i++) {
2673 void *objp = slabp->s_mem + cachep->objsize * i;
2674 unsigned long red1, red2;
2676 red1 = *dbg_redzone1(cachep, objp);
2677 red2 = *dbg_redzone2(cachep, objp);
2679 /* simplest case: marked as inactive */
2680 if (red1 == RED_INACTIVE && red2 == RED_INACTIVE)
2683 /* tricky case: if the bufctl value is BUFCTL_ALLOC, then
2684 * the object is either allocated or somewhere in a cpu
2685 * cache. The cpu caches are lockless and there might be
2686 * a concurrent alloc/free call, thus we must accept random
2687 * combinations of RED_ACTIVE and _INACTIVE
2689 if (slab_bufctl(slabp)[i] == BUFCTL_ALLOC &&
2690 (red1 == RED_INACTIVE || red1 == RED_ACTIVE) &&
2691 (red2 == RED_INACTIVE || red2 == RED_ACTIVE))
2694 printk(KERN_ERR "slab %s: redzone mismatch in slabp %p, objp %p, bufctl 0x%x\n",
2695 cachep->name, slabp, objp, slab_bufctl(slabp)[i]);
2696 print_objinfo(cachep, objp, 2);
2701 * Perform a self test on all slabs from a cache
2703 static void check_redzone(kmem_cache_t *cachep)
2705 struct list_head *q;
2708 check_spinlock_acquired(cachep);
2710 list_for_each(q,&cachep->lists.slabs_full) {
2711 slabp = list_entry(q, struct slab, list);
2713 if (slabp->inuse != cachep->num) {
2714 printk(KERN_INFO "slab %s: wrong slabp found in full slab chain at %p (%d/%d).\n",
2715 cachep->name, slabp, slabp->inuse, cachep->num);
2717 check_slabp(cachep, slabp);
2718 check_slabuse(cachep, slabp);
2720 list_for_each(q,&cachep->lists.slabs_partial) {
2721 slabp = list_entry(q, struct slab, list);
2723 if (slabp->inuse == cachep->num || slabp->inuse == 0) {
2724 printk(KERN_INFO "slab %s: wrong slab found in partial chain at %p (%d/%d).\n",
2725 cachep->name, slabp, slabp->inuse, cachep->num);
2727 check_slabp(cachep, slabp);
2728 check_slabuse(cachep, slabp);
2730 list_for_each(q,&cachep->lists.slabs_free) {
2731 slabp = list_entry(q, struct slab, list);
2733 if (slabp->inuse != 0) {
2734 printk(KERN_INFO "slab %s: wrong slab found in free chain at %p (%d/%d).\n",
2735 cachep->name, slabp, slabp->inuse, cachep->num);
2737 check_slabp(cachep, slabp);
2738 check_slabuse(cachep, slabp);
2744 struct ccupdate_struct {
2745 kmem_cache_t *cachep;
2746 struct array_cache *new[NR_CPUS];
2749 static void do_ccupdate_local(void *info)
2751 struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2752 struct array_cache *old;
2755 old = ac_data(new->cachep);
2757 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2758 new->new[smp_processor_id()] = old;
2762 static int do_tune_cpucache(kmem_cache_t *cachep, int limit, int batchcount,
2765 struct ccupdate_struct new;
2766 struct array_cache *new_shared;
2769 memset(&new.new,0,sizeof(new.new));
2770 for (i = 0; i < NR_CPUS; i++) {
2771 if (cpu_online(i)) {
2772 new.new[i] = alloc_arraycache(i, limit, batchcount);
2774 for (i--; i >= 0; i--) kfree(new.new[i]);
2781 new.cachep = cachep;
2783 smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2786 spin_lock_irq(&cachep->spinlock);
2787 cachep->batchcount = batchcount;
2788 cachep->limit = limit;
2789 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2790 spin_unlock_irq(&cachep->spinlock);
2792 for (i = 0; i < NR_CPUS; i++) {
2793 struct array_cache *ccold = new.new[i];
2796 spin_lock_irq(&cachep->spinlock);
2797 free_block(cachep, ac_entry(ccold), ccold->avail);
2798 spin_unlock_irq(&cachep->spinlock);
2801 new_shared = alloc_arraycache(-1, batchcount*shared, 0xbaadf00d);
2803 struct array_cache *old;
2805 spin_lock_irq(&cachep->spinlock);
2806 old = cachep->lists.shared;
2807 cachep->lists.shared = new_shared;
2809 free_block(cachep, ac_entry(old), old->avail);
2810 spin_unlock_irq(&cachep->spinlock);
2818 static void enable_cpucache(kmem_cache_t *cachep)
2823 /* The head array serves three purposes:
2824 * - create a LIFO ordering, i.e. return objects that are cache-warm
2825 * - reduce the number of spinlock operations.
2826 * - reduce the number of linked list operations on the slab and
2827 * bufctl chains: array operations are cheaper.
2828 * The numbers are guessed, we should auto-tune as described by
2831 if (cachep->objsize > 131072)
2833 else if (cachep->objsize > PAGE_SIZE)
2835 else if (cachep->objsize > 1024)
2837 else if (cachep->objsize > 256)
2842 /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2843 * allocation behaviour: Most allocs on one cpu, most free operations
2844 * on another cpu. For these cases, an efficient object passing between
2845 * cpus is necessary. This is provided by a shared array. The array
2846 * replaces Bonwick's magazine layer.
2847 * On uniprocessor, it's functionally equivalent (but less efficient)
2848 * to a larger limit. Thus disabled by default.
2852 if (cachep->objsize <= PAGE_SIZE)
2857 /* With debugging enabled, large batchcount lead to excessively
2858 * long periods with disabled local interrupts. Limit the
2864 err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2866 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2867 cachep->name, -err);
2870 static void drain_array_locked(kmem_cache_t *cachep,
2871 struct array_cache *ac, int force)
2875 check_spinlock_acquired(cachep);
2876 if (ac->touched && !force) {
2878 } else if (ac->avail) {
2879 tofree = force ? ac->avail : (ac->limit+4)/5;
2880 if (tofree > ac->avail) {
2881 tofree = (ac->avail+1)/2;
2883 free_block(cachep, ac_entry(ac), tofree);
2884 ac->avail -= tofree;
2885 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2886 sizeof(void*)*ac->avail);
2891 * cache_reap - Reclaim memory from caches.
2893 * Called from workqueue/eventd every few seconds.
2895 * - clear the per-cpu caches for this CPU.
2896 * - return freeable pages to the main free memory pool.
2898 * If we cannot acquire the cache chain semaphore then just give up - we'll
2899 * try again on the next iteration.
2901 static void cache_reap(void *unused)
2903 struct list_head *walk;
2905 if (down_trylock(&cache_chain_sem)) {
2906 /* Give up. Setup the next iteration. */
2907 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2911 list_for_each(walk, &cache_chain) {
2912 kmem_cache_t *searchp;
2913 struct list_head* p;
2917 searchp = list_entry(walk, kmem_cache_t, next);
2919 if (searchp->flags & SLAB_NO_REAP)
2924 spin_lock_irq(&searchp->spinlock);
2926 drain_array_locked(searchp, ac_data(searchp), 0);
2929 if(time_before(searchp->redzonetest, jiffies)) {
2930 searchp->redzonetest = jiffies + REDZONETIMEOUT;
2931 check_redzone(searchp);
2934 if(time_after(searchp->lists.next_reap, jiffies))
2937 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2939 if (searchp->lists.shared)
2940 drain_array_locked(searchp, searchp->lists.shared, 0);
2942 if (searchp->lists.free_touched) {
2943 searchp->lists.free_touched = 0;
2947 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2949 p = list3_data(searchp)->slabs_free.next;
2950 if (p == &(list3_data(searchp)->slabs_free))
2953 slabp = list_entry(p, struct slab, list);
2954 BUG_ON(slabp->inuse);
2955 list_del(&slabp->list);
2956 STATS_INC_REAPED(searchp);
2958 /* Safe to drop the lock. The slab is no longer
2959 * linked to the cache.
2960 * searchp cannot disappear, we hold
2963 searchp->lists.free_objects -= searchp->num;
2964 spin_unlock_irq(&searchp->spinlock);
2965 slab_destroy(searchp, slabp);
2966 spin_lock_irq(&searchp->spinlock);
2967 } while(--tofree > 0);
2969 spin_unlock_irq(&searchp->spinlock);
2974 up(&cache_chain_sem);
2975 /* Setup the next iteration */
2976 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2979 #ifdef CONFIG_PROC_FS
2981 static void *s_start(struct seq_file *m, loff_t *pos)
2984 struct list_head *p;
2986 down(&cache_chain_sem);
2989 * Output format version, so at least we can change it
2990 * without _too_ many complaints.
2993 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
2995 seq_puts(m, "slabinfo - version: 2.1\n");
2997 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2998 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
2999 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
3001 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped>"
3002 " <error> <maxfreeable> <freelimit> <nodeallocs>");
3003 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
3007 p = cache_chain.next;
3010 if (p == &cache_chain)
3013 return list_entry(p, kmem_cache_t, next);
3016 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3018 kmem_cache_t *cachep = p;
3020 return cachep->next.next == &cache_chain ? NULL
3021 : list_entry(cachep->next.next, kmem_cache_t, next);
3024 static void s_stop(struct seq_file *m, void *p)
3026 up(&cache_chain_sem);
3029 static int s_show(struct seq_file *m, void *p)
3031 kmem_cache_t *cachep = p;
3032 struct list_head *q;
3034 unsigned long active_objs;
3035 unsigned long num_objs;
3036 unsigned long active_slabs = 0;
3037 unsigned long num_slabs;
3042 spin_lock_irq(&cachep->spinlock);
3045 list_for_each(q,&cachep->lists.slabs_full) {
3046 slabp = list_entry(q, struct slab, list);
3047 if (slabp->inuse != cachep->num && !error)
3048 error = "slabs_full accounting error";
3049 active_objs += cachep->num;
3052 list_for_each(q,&cachep->lists.slabs_partial) {
3053 slabp = list_entry(q, struct slab, list);
3054 if (slabp->inuse == cachep->num && !error)
3055 error = "slabs_partial inuse accounting error";
3056 if (!slabp->inuse && !error)
3057 error = "slabs_partial/inuse accounting error";
3058 active_objs += slabp->inuse;
3061 list_for_each(q,&cachep->lists.slabs_free) {
3062 slabp = list_entry(q, struct slab, list);
3063 if (slabp->inuse && !error)
3064 error = "slabs_free/inuse accounting error";
3067 num_slabs+=active_slabs;
3068 num_objs = num_slabs*cachep->num;
3069 if (num_objs - active_objs != cachep->lists.free_objects && !error)
3070 error = "free_objects accounting error";
3072 name = cachep->name;
3074 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3076 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
3077 name, active_objs, num_objs, cachep->objsize,
3078 cachep->num, (1<<cachep->gfporder));
3079 seq_printf(m, " : tunables %4u %4u %4u",
3080 cachep->limit, cachep->batchcount,
3081 cachep->lists.shared->limit/cachep->batchcount);
3082 seq_printf(m, " : slabdata %6lu %6lu %6u",
3083 active_slabs, num_slabs, cachep->lists.shared->avail);
3086 unsigned long high = cachep->high_mark;
3087 unsigned long allocs = cachep->num_allocations;
3088 unsigned long grown = cachep->grown;
3089 unsigned long reaped = cachep->reaped;
3090 unsigned long errors = cachep->errors;
3091 unsigned long max_freeable = cachep->max_freeable;
3092 unsigned long free_limit = cachep->free_limit;
3093 unsigned long node_allocs = cachep->node_allocs;
3095 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu",
3096 allocs, high, grown, reaped, errors,
3097 max_freeable, free_limit, node_allocs);
3101 unsigned long allochit = atomic_read(&cachep->allochit);
3102 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
3103 unsigned long freehit = atomic_read(&cachep->freehit);
3104 unsigned long freemiss = atomic_read(&cachep->freemiss);
3106 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
3107 allochit, allocmiss, freehit, freemiss);
3111 spin_unlock_irq(&cachep->spinlock);
3116 * slabinfo_op - iterator that generates /proc/slabinfo
3125 * num-pages-per-slab
3126 * + further values on SMP and with statistics enabled
3129 struct seq_operations slabinfo_op = {
3136 #define MAX_SLABINFO_WRITE 128
3138 * slabinfo_write - Tuning for the slab allocator
3140 * @buffer: user buffer
3141 * @count: data length
3144 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
3145 size_t count, loff_t *ppos)
3147 char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
3148 int limit, batchcount, shared, res;
3149 struct list_head *p;
3151 if (count > MAX_SLABINFO_WRITE)
3153 if (copy_from_user(&kbuf, buffer, count))
3155 kbuf[MAX_SLABINFO_WRITE] = '\0';
3157 tmp = strchr(kbuf, ' ');
3162 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3165 /* Find the cache in the chain of caches. */
3166 down(&cache_chain_sem);
3168 list_for_each(p,&cache_chain) {
3169 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
3171 if (!strcmp(cachep->name, kbuf)) {
3174 batchcount > limit ||
3178 res = do_tune_cpucache(cachep, limit, batchcount, shared);
3183 up(&cache_chain_sem);
3190 unsigned int ksize(const void *objp)
3193 unsigned long flags;
3194 unsigned int size = 0;
3196 if (likely(objp != NULL)) {
3197 local_irq_save(flags);
3198 c = GET_PAGE_CACHE(virt_to_page(objp));
3199 size = kmem_cache_size(c);
3200 local_irq_restore(flags);