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
131 #define ARCH_KMALLOC_MINALIGN 0
134 #ifndef ARCH_KMALLOC_FLAGS
135 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
138 /* Legal flag mask for kmem_cache_create(). */
140 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
141 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
142 SLAB_NO_REAP | SLAB_CACHE_DMA | \
143 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
144 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
147 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
148 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
149 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
156 * Bufctl's are used for linking objs within a slab
159 * This implementation relies on "struct page" for locating the cache &
160 * slab an object belongs to.
161 * This allows the bufctl structure to be small (one int), but limits
162 * the number of objects a slab (not a cache) can contain when off-slab
163 * bufctls are used. The limit is the size of the largest general cache
164 * that does not use off-slab slabs.
165 * For 32bit archs with 4 kB pages, is this 56.
166 * This is not serious, as it is only for large objects, when it is unwise
167 * to have too many per slab.
168 * Note: This limit can be raised by introducing a general cache whose size
169 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
172 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
173 #define BUFCTL_ALLOC (((kmem_bufctl_t)(~0U))-1)
174 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-2)
176 /* Max number of objs-per-slab for caches which use off-slab slabs.
177 * Needed to avoid a possible looping condition in cache_grow().
179 static unsigned long offslab_limit;
184 * Manages the objs in a slab. Placed either at the beginning of mem allocated
185 * for a slab, or allocated from an general cache.
186 * Slabs are chained into three list: fully used, partial, fully free slabs.
189 struct list_head list;
190 unsigned long colouroff;
191 void *s_mem; /* including colour offset */
192 unsigned int inuse; /* num of objs active in slab */
199 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
200 * arrange for kmem_freepages to be called via RCU. This is useful if
201 * we need to approach a kernel structure obliquely, from its address
202 * obtained without the usual locking. We can lock the structure to
203 * stabilize it and check it's still at the given address, only if we
204 * can be sure that the memory has not been meanwhile reused for some
205 * other kind of object (which our subsystem's lock might corrupt).
207 * rcu_read_lock before reading the address, then rcu_read_unlock after
208 * taking the spinlock within the structure expected at that address.
210 * We assume struct slab_rcu can overlay struct slab when destroying.
213 struct rcu_head head;
214 kmem_cache_t *cachep;
223 * - LIFO ordering, to hand out cache-warm objects from _alloc
224 * - reduce the number of linked list operations
225 * - reduce spinlock operations
227 * The limit is stored in the per-cpu structure to reduce the data cache
234 unsigned int batchcount;
235 unsigned int touched;
238 /* bootstrap: The caches do not work without cpuarrays anymore,
239 * but the cpuarrays are allocated from the generic caches...
241 #define BOOT_CPUCACHE_ENTRIES 1
242 struct arraycache_init {
243 struct array_cache cache;
244 void * entries[BOOT_CPUCACHE_ENTRIES];
248 * The slab lists of all objects.
249 * Hopefully reduce the internal fragmentation
250 * NUMA: The spinlock could be moved from the kmem_cache_t
251 * into this structure, too. Figure out what causes
252 * fewer cross-node spinlock operations.
255 struct list_head slabs_partial; /* partial list first, better asm code */
256 struct list_head slabs_full;
257 struct list_head slabs_free;
258 unsigned long free_objects;
260 unsigned long next_reap;
261 struct array_cache *shared;
264 #define LIST3_INIT(parent) \
266 .slabs_full = LIST_HEAD_INIT(parent.slabs_full), \
267 .slabs_partial = LIST_HEAD_INIT(parent.slabs_partial), \
268 .slabs_free = LIST_HEAD_INIT(parent.slabs_free) \
270 #define list3_data(cachep) \
274 #define list3_data_ptr(cachep, ptr) \
283 struct kmem_cache_s {
284 /* 1) per-cpu data, touched during every alloc/free */
285 struct array_cache *array[NR_CPUS];
286 unsigned int batchcount;
288 /* 2) touched by every alloc & free from the backend */
289 struct kmem_list3 lists;
290 /* NUMA: kmem_3list_t *nodelists[MAX_NUMNODES] */
291 unsigned int objsize;
292 unsigned int flags; /* constant flags */
293 unsigned int num; /* # of objs per slab */
294 unsigned int free_limit; /* upper limit of objects in the lists */
297 /* 3) cache_grow/shrink */
298 /* order of pgs per slab (2^n) */
299 unsigned int gfporder;
301 /* force GFP flags, e.g. GFP_DMA */
302 unsigned int gfpflags;
304 size_t colour; /* cache colouring range */
305 unsigned int colour_off; /* colour offset */
306 unsigned int colour_next; /* cache colouring */
307 kmem_cache_t *slabp_cache;
308 unsigned int slab_size;
309 unsigned int dflags; /* dynamic flags */
311 /* constructor func */
312 void (*ctor)(void *, kmem_cache_t *, unsigned long);
314 /* de-constructor func */
315 void (*dtor)(void *, kmem_cache_t *, unsigned long);
317 /* 4) cache creation/removal */
319 struct list_head next;
323 unsigned long num_active;
324 unsigned long num_allocations;
325 unsigned long high_mark;
327 unsigned long reaped;
328 unsigned long errors;
329 unsigned long max_freeable;
330 unsigned long node_allocs;
339 unsigned long redzonetest;
343 #define CFLGS_OFF_SLAB (0x80000000UL)
344 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
346 #define BATCHREFILL_LIMIT 16
347 /* Optimization question: fewer reaps means less
348 * probability for unnessary cpucache drain/refill cycles.
350 * OTHO the cpuarrays can contain lots of objects,
351 * which could lock up otherwise freeable slabs.
353 #define REAPTIMEOUT_CPUC (2*HZ)
354 #define REAPTIMEOUT_LIST3 (4*HZ)
355 #define REDZONETIMEOUT (300*HZ)
358 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
359 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
360 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
361 #define STATS_INC_GROWN(x) ((x)->grown++)
362 #define STATS_INC_REAPED(x) ((x)->reaped++)
363 #define STATS_SET_HIGH(x) do { if ((x)->num_active > (x)->high_mark) \
364 (x)->high_mark = (x)->num_active; \
366 #define STATS_INC_ERR(x) ((x)->errors++)
367 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
368 #define STATS_SET_FREEABLE(x, i) \
369 do { if ((x)->max_freeable < i) \
370 (x)->max_freeable = i; \
373 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
374 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
375 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
376 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
378 #define STATS_INC_ACTIVE(x) do { } while (0)
379 #define STATS_DEC_ACTIVE(x) do { } while (0)
380 #define STATS_INC_ALLOCED(x) do { } while (0)
381 #define STATS_INC_GROWN(x) do { } while (0)
382 #define STATS_INC_REAPED(x) do { } while (0)
383 #define STATS_SET_HIGH(x) do { } while (0)
384 #define STATS_INC_ERR(x) do { } while (0)
385 #define STATS_INC_NODEALLOCS(x) do { } while (0)
386 #define STATS_SET_FREEABLE(x, i) \
389 #define STATS_INC_ALLOCHIT(x) do { } while (0)
390 #define STATS_INC_ALLOCMISS(x) do { } while (0)
391 #define STATS_INC_FREEHIT(x) do { } while (0)
392 #define STATS_INC_FREEMISS(x) do { } while (0)
396 /* Magic nums for obj red zoning.
397 * Placed in the first word before and the first word after an obj.
399 #define RED_INACTIVE 0x5A2CF071UL /* when obj is inactive */
400 #define RED_ACTIVE 0x170FC2A5UL /* when obj is active */
402 /* ...and for poisoning */
403 #define POISON_INUSE 0x5a /* for use-uninitialised poisoning */
404 #define POISON_FREE 0x6b /* for use-after-free poisoning */
405 #define POISON_END 0xa5 /* end-byte of poisoning */
407 /* memory layout of objects:
409 * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
410 * the end of an object is aligned with the end of the real
411 * allocation. Catches writes behind the end of the allocation.
412 * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
414 * cachep->dbghead: The real object.
415 * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
416 * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
418 static int obj_dbghead(kmem_cache_t *cachep)
420 return cachep->dbghead;
423 static int obj_reallen(kmem_cache_t *cachep)
425 return cachep->reallen;
428 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
430 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
431 return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
434 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
436 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
437 if (cachep->flags & SLAB_STORE_USER)
438 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
439 return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
442 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
444 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
445 return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
450 #define obj_dbghead(x) 0
451 #define obj_reallen(cachep) (cachep->objsize)
452 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
453 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
454 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
459 * Maximum size of an obj (in 2^order pages)
460 * and absolute limit for the gfp order.
462 #if defined(CONFIG_LARGE_ALLOCS)
463 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
464 #define MAX_GFP_ORDER 13 /* up to 32Mb */
465 #elif defined(CONFIG_MMU)
466 #define MAX_OBJ_ORDER 5 /* 32 pages */
467 #define MAX_GFP_ORDER 5 /* 32 pages */
469 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
470 #define MAX_GFP_ORDER 8 /* up to 1Mb */
474 * Do not go above this order unless 0 objects fit into the slab.
476 #define BREAK_GFP_ORDER_HI 1
477 #define BREAK_GFP_ORDER_LO 0
478 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
480 /* Macros for storing/retrieving the cachep and or slab from the
481 * global 'mem_map'. These are used to find the slab an obj belongs to.
482 * With kfree(), these are used to find the cache which an obj belongs to.
484 #define SET_PAGE_CACHE(pg,x) ((pg)->lru.next = (struct list_head *)(x))
485 #define GET_PAGE_CACHE(pg) ((kmem_cache_t *)(pg)->lru.next)
486 #define SET_PAGE_SLAB(pg,x) ((pg)->lru.prev = (struct list_head *)(x))
487 #define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->lru.prev)
489 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
490 struct cache_sizes malloc_sizes[] = {
491 #define CACHE(x) { .cs_size = (x) },
492 #include <linux/kmalloc_sizes.h>
497 EXPORT_SYMBOL(malloc_sizes);
499 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
505 static struct cache_names __initdata cache_names[] = {
506 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
507 #include <linux/kmalloc_sizes.h>
512 static struct arraycache_init initarray_cache __initdata =
513 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
514 static struct arraycache_init initarray_generic =
515 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
517 /* internal cache of cache description objs */
518 static kmem_cache_t cache_cache = {
519 .lists = LIST3_INIT(cache_cache.lists),
521 .limit = BOOT_CPUCACHE_ENTRIES,
522 .objsize = sizeof(kmem_cache_t),
523 .flags = SLAB_NO_REAP,
524 .spinlock = SPIN_LOCK_UNLOCKED,
525 .name = "kmem_cache",
527 .reallen = sizeof(kmem_cache_t),
531 /* Guard access to the cache-chain. */
532 static struct semaphore cache_chain_sem;
533 static struct list_head cache_chain;
536 * vm_enough_memory() looks at this to determine how many
537 * slab-allocated pages are possibly freeable under pressure
539 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
541 atomic_t slab_reclaim_pages;
542 EXPORT_SYMBOL(slab_reclaim_pages);
545 * chicken and egg problem: delay the per-cpu array allocation
546 * until the general caches are up.
554 static DEFINE_PER_CPU(struct work_struct, reap_work);
556 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
557 static void enable_cpucache (kmem_cache_t *cachep);
558 static void cache_reap (void *unused);
560 static inline void ** ac_entry(struct array_cache *ac)
562 return (void**)(ac+1);
565 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
567 return cachep->array[smp_processor_id()];
570 static kmem_cache_t * kmem_find_general_cachep (size_t size, int gfpflags)
572 struct cache_sizes *csizep = malloc_sizes;
574 /* This function could be moved to the header file, and
575 * made inline so consumers can quickly determine what
576 * cache pointer they require.
578 for ( ; csizep->cs_size; csizep++) {
579 if (size > csizep->cs_size)
583 return (gfpflags & GFP_DMA) ? csizep->cs_dmacachep : csizep->cs_cachep;
586 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
587 static void cache_estimate (unsigned long gfporder, size_t size, size_t align,
588 int flags, size_t *left_over, unsigned int *num)
591 size_t wastage = PAGE_SIZE<<gfporder;
595 if (!(flags & CFLGS_OFF_SLAB)) {
596 base = sizeof(struct slab);
597 extra = sizeof(kmem_bufctl_t);
600 while (i*size + ALIGN(base+i*extra, align) <= wastage)
610 wastage -= ALIGN(base+i*extra, align);
611 *left_over = wastage;
614 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
616 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
618 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
619 function, cachep->name, msg);
624 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
625 * via the workqueue/eventd.
626 * Add the CPU number into the expiration time to minimize the possibility of
627 * the CPUs getting into lockstep and contending for the global cache chain
630 static void __devinit start_cpu_timer(int cpu)
632 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
635 * When this gets called from do_initcalls via cpucache_init(),
636 * init_workqueues() has already run, so keventd will be setup
639 if (keventd_up() && reap_work->func == NULL) {
640 INIT_WORK(reap_work, cache_reap, NULL);
641 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
645 static struct array_cache *alloc_arraycache(int cpu, int entries, int batchcount)
647 int memsize = sizeof(void*)*entries+sizeof(struct array_cache);
648 struct array_cache *nc = NULL;
651 nc = kmem_cache_alloc_node(kmem_find_general_cachep(memsize,
652 GFP_KERNEL), cpu_to_node(cpu));
655 nc = kmalloc(memsize, GFP_KERNEL);
659 nc->batchcount = batchcount;
665 static int __devinit cpuup_callback(struct notifier_block *nfb,
666 unsigned long action,
669 long cpu = (long)hcpu;
670 kmem_cache_t* cachep;
674 down(&cache_chain_sem);
675 list_for_each_entry(cachep, &cache_chain, next) {
676 struct array_cache *nc;
678 nc = alloc_arraycache(cpu, cachep->limit, cachep->batchcount);
682 spin_lock_irq(&cachep->spinlock);
683 cachep->array[cpu] = nc;
684 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
686 spin_unlock_irq(&cachep->spinlock);
689 up(&cache_chain_sem);
692 start_cpu_timer(cpu);
694 #ifdef CONFIG_HOTPLUG_CPU
697 case CPU_UP_CANCELED:
698 down(&cache_chain_sem);
700 list_for_each_entry(cachep, &cache_chain, next) {
701 struct array_cache *nc;
703 spin_lock_irq(&cachep->spinlock);
704 /* cpu is dead; no one can alloc from it. */
705 nc = cachep->array[cpu];
706 cachep->array[cpu] = NULL;
707 cachep->free_limit -= cachep->batchcount;
708 free_block(cachep, ac_entry(nc), nc->avail);
709 spin_unlock_irq(&cachep->spinlock);
712 up(&cache_chain_sem);
718 up(&cache_chain_sem);
722 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
725 * Called after the gfp() functions have been enabled, and before smp_init().
727 void __init kmem_cache_init(void)
730 struct cache_sizes *sizes;
731 struct cache_names *names;
734 * Fragmentation resistance on low memory - only use bigger
735 * page orders on machines with more than 32MB of memory.
737 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
738 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
741 /* Bootstrap is tricky, because several objects are allocated
742 * from caches that do not exist yet:
743 * 1) initialize the cache_cache cache: it contains the kmem_cache_t
744 * structures of all caches, except cache_cache itself: cache_cache
745 * is statically allocated.
746 * Initially an __init data area is used for the head array, it's
747 * replaced with a kmalloc allocated array at the end of the bootstrap.
748 * 2) Create the first kmalloc cache.
749 * The kmem_cache_t for the new cache is allocated normally. An __init
750 * data area is used for the head array.
751 * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
752 * 4) Replace the __init data head arrays for cache_cache and the first
753 * kmalloc cache with kmalloc allocated arrays.
754 * 5) Resize the head arrays of the kmalloc caches to their final sizes.
757 /* 1) create the cache_cache */
758 init_MUTEX(&cache_chain_sem);
759 INIT_LIST_HEAD(&cache_chain);
760 list_add(&cache_cache.next, &cache_chain);
761 cache_cache.colour_off = cache_line_size();
762 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
764 cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
766 cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
767 &left_over, &cache_cache.num);
768 if (!cache_cache.num)
771 cache_cache.colour = left_over/cache_cache.colour_off;
772 cache_cache.colour_next = 0;
773 cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
774 sizeof(struct slab), cache_line_size());
776 /* 2+3) create the kmalloc caches */
777 sizes = malloc_sizes;
780 while (sizes->cs_size) {
781 /* For performance, all the general caches are L1 aligned.
782 * This should be particularly beneficial on SMP boxes, as it
783 * eliminates "false sharing".
784 * Note for systems short on memory removing the alignment will
785 * allow tighter packing of the smaller caches. */
786 sizes->cs_cachep = kmem_cache_create(names->name,
787 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
788 (ARCH_KMALLOC_FLAGS | SLAB_PANIC), NULL, NULL);
790 /* Inc off-slab bufctl limit until the ceiling is hit. */
791 if (!(OFF_SLAB(sizes->cs_cachep))) {
792 offslab_limit = sizes->cs_size-sizeof(struct slab);
793 offslab_limit /= sizeof(kmem_bufctl_t);
796 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
797 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
798 (ARCH_KMALLOC_FLAGS | SLAB_CACHE_DMA | SLAB_PANIC),
804 /* 4) Replace the bootstrap head arrays */
808 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
810 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
811 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
812 cache_cache.array[smp_processor_id()] = ptr;
815 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
817 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
818 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
819 sizeof(struct arraycache_init));
820 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
824 /* 5) resize the head arrays to their final sizes */
826 kmem_cache_t *cachep;
827 down(&cache_chain_sem);
828 list_for_each_entry(cachep, &cache_chain, next)
829 enable_cpucache(cachep);
830 up(&cache_chain_sem);
834 g_cpucache_up = FULL;
836 /* Register a cpu startup notifier callback
837 * that initializes ac_data for all new cpus
839 register_cpu_notifier(&cpucache_notifier);
842 /* The reap timers are started later, with a module init call:
843 * That part of the kernel is not yet operational.
847 static int __init cpucache_init(void)
852 * Register the timers that return unneeded
855 for (cpu = 0; cpu < NR_CPUS; cpu++) {
857 start_cpu_timer(cpu);
863 __initcall(cpucache_init);
866 * Interface to system's page allocator. No need to hold the cache-lock.
868 * If we requested dmaable memory, we will get it. Even if we
869 * did not request dmaable memory, we might get it, but that
870 * would be relatively rare and ignorable.
872 static void *kmem_getpages(kmem_cache_t *cachep, int flags, int nodeid)
878 flags |= cachep->gfpflags;
879 if (likely(nodeid == -1)) {
880 addr = (void*)__get_free_pages(flags, cachep->gfporder);
883 page = virt_to_page(addr);
885 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
888 addr = page_address(page);
891 i = (1 << cachep->gfporder);
892 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
893 atomic_add(i, &slab_reclaim_pages);
894 add_page_state(nr_slab, i);
903 * Interface to system's page release.
905 static void kmem_freepages(kmem_cache_t *cachep, void *addr)
907 unsigned long i = (1<<cachep->gfporder);
908 struct page *page = virt_to_page(addr);
909 const unsigned long nr_freed = i;
912 if (!TestClearPageSlab(page))
916 sub_page_state(nr_slab, nr_freed);
917 if (current->reclaim_state)
918 current->reclaim_state->reclaimed_slab += nr_freed;
919 free_pages((unsigned long)addr, cachep->gfporder);
920 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
921 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
924 static void kmem_rcu_free(struct rcu_head *head)
926 struct slab_rcu *slab_rcu = (struct slab_rcu *) head;
927 kmem_cache_t *cachep = slab_rcu->cachep;
929 kmem_freepages(cachep, slab_rcu->addr);
930 if (OFF_SLAB(cachep))
931 kmem_cache_free(cachep->slabp_cache, slab_rcu);
936 #ifdef CONFIG_DEBUG_PAGEALLOC
937 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr, unsigned long caller)
939 int size = obj_reallen(cachep);
941 addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
943 if (size < 5*sizeof(unsigned long))
948 *addr++=smp_processor_id();
949 size -= 3*sizeof(unsigned long);
951 unsigned long *sptr = &caller;
952 unsigned long svalue;
954 while (!kstack_end(sptr)) {
956 if (kernel_text_address(svalue)) {
958 size -= sizeof(unsigned long);
959 if (size <= sizeof(unsigned long))
969 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
971 int size = obj_reallen(cachep);
972 addr = &((char*)addr)[obj_dbghead(cachep)];
974 memset(addr, val, size);
975 *(unsigned char *)(addr+size-1) = POISON_END;
978 static void dump_line(char *data, int offset, int limit)
981 printk(KERN_ERR "%03x:", offset);
982 for (i=0;i<limit;i++) {
983 printk(" %02x", (unsigned char)data[offset+i]);
991 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
996 if (cachep->flags & SLAB_RED_ZONE) {
997 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
998 *dbg_redzone1(cachep, objp),
999 *dbg_redzone2(cachep, objp));
1002 if (cachep->flags & SLAB_STORE_USER) {
1003 printk(KERN_ERR "Last user: [<%p>]",
1004 *dbg_userword(cachep, objp));
1005 print_symbol("(%s)",
1006 (unsigned long)*dbg_userword(cachep, objp));
1009 realobj = (char*)objp+obj_dbghead(cachep);
1010 size = obj_reallen(cachep);
1011 for (i=0; i<size && lines;i+=16, lines--) {
1016 dump_line(realobj, i, limit);
1020 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
1026 realobj = (char*)objp+obj_dbghead(cachep);
1027 size = obj_reallen(cachep);
1029 for (i=0;i<size;i++) {
1030 char exp = POISON_FREE;
1033 if (realobj[i] != exp) {
1038 printk(KERN_ERR "Slab corruption: (%s) start=%p, len=%d\n",
1039 print_tainted(), realobj, size);
1040 print_objinfo(cachep, objp, 0);
1042 /* Hexdump the affected line */
1047 dump_line(realobj, i, limit);
1050 /* Limit to 5 lines */
1056 /* Print some data about the neighboring objects, if they
1059 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1062 objnr = (objp-slabp->s_mem)/cachep->objsize;
1064 objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1065 realobj = (char*)objp+obj_dbghead(cachep);
1066 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1068 print_objinfo(cachep, objp, 2);
1070 if (objnr+1 < cachep->num) {
1071 objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1072 realobj = (char*)objp+obj_dbghead(cachep);
1073 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1075 print_objinfo(cachep, objp, 2);
1081 /* Destroy all the objs in a slab, and release the mem back to the system.
1082 * Before calling the slab must have been unlinked from the cache.
1083 * The cache-lock is not held/needed.
1085 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1087 void *addr = slabp->s_mem - slabp->colouroff;
1091 for (i = 0; i < cachep->num; i++) {
1092 void *objp = slabp->s_mem + cachep->objsize * i;
1094 if (cachep->flags & SLAB_POISON) {
1095 #ifdef CONFIG_DEBUG_PAGEALLOC
1096 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1097 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1099 check_poison_obj(cachep, objp);
1101 check_poison_obj(cachep, objp);
1104 if (cachep->flags & SLAB_RED_ZONE) {
1105 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1106 slab_error(cachep, "start of a freed object "
1108 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1109 slab_error(cachep, "end of a freed object "
1112 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1113 (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1118 for (i = 0; i < cachep->num; i++) {
1119 void* objp = slabp->s_mem+cachep->objsize*i;
1120 (cachep->dtor)(objp, cachep, 0);
1125 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1126 struct slab_rcu *slab_rcu;
1128 slab_rcu = (struct slab_rcu *) slabp;
1129 slab_rcu->cachep = cachep;
1130 slab_rcu->addr = addr;
1131 call_rcu(&slab_rcu->head, kmem_rcu_free);
1133 kmem_freepages(cachep, addr);
1134 if (OFF_SLAB(cachep))
1135 kmem_cache_free(cachep->slabp_cache, slabp);
1140 * kmem_cache_create - Create a cache.
1141 * @name: A string which is used in /proc/slabinfo to identify this cache.
1142 * @size: The size of objects to be created in this cache.
1143 * @align: The required alignment for the objects.
1144 * @flags: SLAB flags
1145 * @ctor: A constructor for the objects.
1146 * @dtor: A destructor for the objects.
1148 * Returns a ptr to the cache on success, NULL on failure.
1149 * Cannot be called within a int, but can be interrupted.
1150 * The @ctor is run when new pages are allocated by the cache
1151 * and the @dtor is run before the pages are handed back.
1153 * @name must be valid until the cache is destroyed. This implies that
1154 * the module calling this has to destroy the cache before getting
1159 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1160 * to catch references to uninitialised memory.
1162 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1163 * for buffer overruns.
1165 * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1168 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1169 * cacheline. This can be beneficial if you're counting cycles as closely
1173 kmem_cache_create (const char *name, size_t size, size_t align,
1174 unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1175 void (*dtor)(void*, kmem_cache_t *, unsigned long))
1177 size_t left_over, slab_size;
1178 kmem_cache_t *cachep = NULL;
1181 * Sanity checks... these are all serious usage bugs.
1185 (size < BYTES_PER_WORD) ||
1186 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1188 printk(KERN_ERR "%s: Early error in slab %s\n",
1189 __FUNCTION__, name);
1194 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
1195 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1196 /* No constructor, but inital state check requested */
1197 printk(KERN_ERR "%s: No con, but init state check "
1198 "requested - %s\n", __FUNCTION__, name);
1199 flags &= ~SLAB_DEBUG_INITIAL;
1204 * Enable redzoning and last user accounting, except for caches with
1205 * large objects, if the increased size would increase the object size
1206 * above the next power of two: caches with object sizes just above a
1207 * power of two have a significant amount of internal fragmentation.
1209 if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1210 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1211 if (!(flags & SLAB_DESTROY_BY_RCU))
1212 flags |= SLAB_POISON;
1214 if (flags & SLAB_DESTROY_BY_RCU)
1215 BUG_ON(flags & SLAB_POISON);
1217 if (flags & SLAB_DESTROY_BY_RCU)
1221 * Always checks flags, a caller might be expecting debug
1222 * support which isn't available.
1224 if (flags & ~CREATE_MASK)
1228 /* combinations of forced alignment and advanced debugging is
1229 * not yet implemented.
1231 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1233 if (flags & SLAB_HWCACHE_ALIGN) {
1234 /* Default alignment: as specified by the arch code.
1235 * Except if an object is really small, then squeeze multiple
1236 * into one cacheline.
1238 align = cache_line_size();
1239 while (size <= align/2)
1242 align = BYTES_PER_WORD;
1246 /* Get cache's description obj. */
1247 cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1250 memset(cachep, 0, sizeof(kmem_cache_t));
1252 /* Check that size is in terms of words. This is needed to avoid
1253 * unaligned accesses for some archs when redzoning is used, and makes
1254 * sure any on-slab bufctl's are also correctly aligned.
1256 if (size & (BYTES_PER_WORD-1)) {
1257 size += (BYTES_PER_WORD-1);
1258 size &= ~(BYTES_PER_WORD-1);
1262 cachep->reallen = size;
1264 if (flags & SLAB_RED_ZONE) {
1265 /* redzoning only works with word aligned caches */
1266 align = BYTES_PER_WORD;
1268 /* add space for red zone words */
1269 cachep->dbghead += BYTES_PER_WORD;
1270 size += 2*BYTES_PER_WORD;
1272 if (flags & SLAB_STORE_USER) {
1273 /* user store requires word alignment and
1274 * one word storage behind the end of the real
1277 align = BYTES_PER_WORD;
1278 size += BYTES_PER_WORD;
1280 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1281 if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1282 cachep->dbghead += PAGE_SIZE - size;
1288 /* Determine if the slab management is 'on' or 'off' slab. */
1289 if (size >= (PAGE_SIZE>>3))
1291 * Size is large, assume best to place the slab management obj
1292 * off-slab (should allow better packing of objs).
1294 flags |= CFLGS_OFF_SLAB;
1296 size = ALIGN(size, align);
1298 if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1300 * A VFS-reclaimable slab tends to have most allocations
1301 * as GFP_NOFS and we really don't want to have to be allocating
1302 * higher-order pages when we are unable to shrink dcache.
1304 cachep->gfporder = 0;
1305 cache_estimate(cachep->gfporder, size, align, flags,
1306 &left_over, &cachep->num);
1309 * Calculate size (in pages) of slabs, and the num of objs per
1310 * slab. This could be made much more intelligent. For now,
1311 * try to avoid using high page-orders for slabs. When the
1312 * gfp() funcs are more friendly towards high-order requests,
1313 * this should be changed.
1316 unsigned int break_flag = 0;
1318 cache_estimate(cachep->gfporder, size, align, flags,
1319 &left_over, &cachep->num);
1322 if (cachep->gfporder >= MAX_GFP_ORDER)
1326 if (flags & CFLGS_OFF_SLAB &&
1327 cachep->num > offslab_limit) {
1328 /* This num of objs will cause problems. */
1335 * Large num of objs is good, but v. large slabs are
1336 * currently bad for the gfp()s.
1338 if (cachep->gfporder >= slab_break_gfp_order)
1341 if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1342 break; /* Acceptable internal fragmentation. */
1349 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1350 kmem_cache_free(&cache_cache, cachep);
1354 slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1355 + sizeof(struct slab), align);
1358 * If the slab has been placed off-slab, and we have enough space then
1359 * move it on-slab. This is at the expense of any extra colouring.
1361 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1362 flags &= ~CFLGS_OFF_SLAB;
1363 left_over -= slab_size;
1366 if (flags & CFLGS_OFF_SLAB) {
1367 /* really off slab. No need for manual alignment */
1368 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1371 cachep->colour_off = cache_line_size();
1372 /* Offset must be a multiple of the alignment. */
1373 if (cachep->colour_off < align)
1374 cachep->colour_off = align;
1375 cachep->colour = left_over/cachep->colour_off;
1376 cachep->slab_size = slab_size;
1377 cachep->flags = flags;
1378 cachep->gfpflags = 0;
1379 if (flags & SLAB_CACHE_DMA)
1380 cachep->gfpflags |= GFP_DMA;
1381 spin_lock_init(&cachep->spinlock);
1382 cachep->objsize = size;
1384 INIT_LIST_HEAD(&cachep->lists.slabs_full);
1385 INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1386 INIT_LIST_HEAD(&cachep->lists.slabs_free);
1388 if (flags & CFLGS_OFF_SLAB)
1389 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1390 cachep->ctor = ctor;
1391 cachep->dtor = dtor;
1392 cachep->name = name;
1394 /* Don't let CPUs to come and go */
1397 if (g_cpucache_up == FULL) {
1398 enable_cpucache(cachep);
1400 if (g_cpucache_up == NONE) {
1401 /* Note: the first kmem_cache_create must create
1402 * the cache that's used by kmalloc(24), otherwise
1403 * the creation of further caches will BUG().
1405 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1406 g_cpucache_up = PARTIAL;
1408 cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1410 BUG_ON(!ac_data(cachep));
1411 ac_data(cachep)->avail = 0;
1412 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1413 ac_data(cachep)->batchcount = 1;
1414 ac_data(cachep)->touched = 0;
1415 cachep->batchcount = 1;
1416 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1417 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1421 cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1422 ((unsigned long)cachep/L1_CACHE_BYTES)%REAPTIMEOUT_LIST3;
1424 cachep->redzonetest = jiffies + REDZONETIMEOUT +
1425 ((unsigned long)cachep/L1_CACHE_BYTES)%REDZONETIMEOUT;
1428 /* Need the semaphore to access the chain. */
1429 down(&cache_chain_sem);
1431 struct list_head *p;
1432 mm_segment_t old_fs;
1436 list_for_each(p, &cache_chain) {
1437 kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1439 /* This happens when the module gets unloaded and doesn't
1440 destroy its slab cache and noone else reuses the vmalloc
1441 area of the module. Print a warning. */
1442 if (__get_user(tmp,pc->name)) {
1443 printk("SLAB: cache with size %d has lost its name\n",
1447 if (!strcmp(pc->name,name)) {
1448 printk("kmem_cache_create: duplicate cache %s\n",name);
1449 up(&cache_chain_sem);
1450 unlock_cpu_hotplug();
1457 /* cache setup completed, link it into the list */
1458 list_add(&cachep->next, &cache_chain);
1459 up(&cache_chain_sem);
1460 unlock_cpu_hotplug();
1462 if (!cachep && (flags & SLAB_PANIC))
1463 panic("kmem_cache_create(): failed to create slab `%s'\n",
1467 EXPORT_SYMBOL(kmem_cache_create);
1470 static void check_irq_off(void)
1472 BUG_ON(!irqs_disabled());
1475 static void check_irq_on(void)
1477 BUG_ON(irqs_disabled());
1480 static void check_spinlock_acquired(kmem_cache_t *cachep)
1484 BUG_ON(spin_trylock(&cachep->spinlock));
1488 #define check_irq_off() do { } while(0)
1489 #define check_irq_on() do { } while(0)
1490 #define check_spinlock_acquired(x) do { } while(0)
1494 * Waits for all CPUs to execute func().
1496 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1501 local_irq_disable();
1505 if (smp_call_function(func, arg, 1, 1))
1511 static void drain_array_locked(kmem_cache_t* cachep,
1512 struct array_cache *ac, int force);
1514 static void do_drain(void *arg)
1516 kmem_cache_t *cachep = (kmem_cache_t*)arg;
1517 struct array_cache *ac;
1520 ac = ac_data(cachep);
1521 spin_lock(&cachep->spinlock);
1522 free_block(cachep, &ac_entry(ac)[0], ac->avail);
1523 spin_unlock(&cachep->spinlock);
1527 static void drain_cpu_caches(kmem_cache_t *cachep)
1529 smp_call_function_all_cpus(do_drain, cachep);
1531 spin_lock_irq(&cachep->spinlock);
1532 if (cachep->lists.shared)
1533 drain_array_locked(cachep, cachep->lists.shared, 1);
1534 spin_unlock_irq(&cachep->spinlock);
1538 /* NUMA shrink all list3s */
1539 static int __cache_shrink(kmem_cache_t *cachep)
1544 drain_cpu_caches(cachep);
1547 spin_lock_irq(&cachep->spinlock);
1550 struct list_head *p;
1552 p = cachep->lists.slabs_free.prev;
1553 if (p == &cachep->lists.slabs_free)
1556 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1561 list_del(&slabp->list);
1563 cachep->lists.free_objects -= cachep->num;
1564 spin_unlock_irq(&cachep->spinlock);
1565 slab_destroy(cachep, slabp);
1566 spin_lock_irq(&cachep->spinlock);
1568 ret = !list_empty(&cachep->lists.slabs_full) ||
1569 !list_empty(&cachep->lists.slabs_partial);
1570 spin_unlock_irq(&cachep->spinlock);
1575 * kmem_cache_shrink - Shrink a cache.
1576 * @cachep: The cache to shrink.
1578 * Releases as many slabs as possible for a cache.
1579 * To help debugging, a zero exit status indicates all slabs were released.
1581 int kmem_cache_shrink(kmem_cache_t *cachep)
1583 if (!cachep || in_interrupt())
1586 return __cache_shrink(cachep);
1589 EXPORT_SYMBOL(kmem_cache_shrink);
1592 * kmem_cache_destroy - delete a cache
1593 * @cachep: the cache to destroy
1595 * Remove a kmem_cache_t object from the slab cache.
1596 * Returns 0 on success.
1598 * It is expected this function will be called by a module when it is
1599 * unloaded. This will remove the cache completely, and avoid a duplicate
1600 * cache being allocated each time a module is loaded and unloaded, if the
1601 * module doesn't have persistent in-kernel storage across loads and unloads.
1603 * The cache must be empty before calling this function.
1605 * The caller must guarantee that noone will allocate memory from the cache
1606 * during the kmem_cache_destroy().
1608 int kmem_cache_destroy (kmem_cache_t * cachep)
1612 if (!cachep || in_interrupt())
1615 /* Don't let CPUs to come and go */
1618 /* Find the cache in the chain of caches. */
1619 down(&cache_chain_sem);
1621 * the chain is never empty, cache_cache is never destroyed
1623 list_del(&cachep->next);
1624 up(&cache_chain_sem);
1626 if (__cache_shrink(cachep)) {
1627 slab_error(cachep, "Can't free all objects");
1628 down(&cache_chain_sem);
1629 list_add(&cachep->next,&cache_chain);
1630 up(&cache_chain_sem);
1631 unlock_cpu_hotplug();
1635 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1636 synchronize_kernel();
1638 /* no cpu_online check required here since we clear the percpu
1639 * array on cpu offline and set this to NULL.
1641 for (i = 0; i < NR_CPUS; i++)
1642 kfree(cachep->array[i]);
1644 /* NUMA: free the list3 structures */
1645 kfree(cachep->lists.shared);
1646 cachep->lists.shared = NULL;
1647 kmem_cache_free(&cache_cache, cachep);
1649 unlock_cpu_hotplug();
1654 EXPORT_SYMBOL(kmem_cache_destroy);
1656 /* Get the memory for a slab management obj. */
1657 static struct slab* alloc_slabmgmt (kmem_cache_t *cachep,
1658 void *objp, int colour_off, int local_flags)
1662 if (OFF_SLAB(cachep)) {
1663 /* Slab management obj is off-slab. */
1664 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1668 slabp = objp+colour_off;
1669 colour_off += cachep->slab_size;
1672 slabp->colouroff = colour_off;
1673 slabp->s_mem = objp+colour_off;
1678 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1680 return (kmem_bufctl_t *)(slabp+1);
1683 static void cache_init_objs (kmem_cache_t * cachep,
1684 struct slab * slabp, unsigned long ctor_flags)
1688 for (i = 0; i < cachep->num; i++) {
1689 void* objp = slabp->s_mem+cachep->objsize*i;
1691 /* need to poison the objs? */
1692 if (cachep->flags & SLAB_POISON)
1693 poison_obj(cachep, objp, POISON_FREE);
1694 if (cachep->flags & SLAB_STORE_USER)
1695 *dbg_userword(cachep, objp) = NULL;
1697 if (cachep->flags & SLAB_RED_ZONE) {
1698 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1699 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1702 * Constructors are not allowed to allocate memory from
1703 * the same cache which they are a constructor for.
1704 * Otherwise, deadlock. They must also be threaded.
1706 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1707 cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1709 if (cachep->flags & SLAB_RED_ZONE) {
1710 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1711 slab_error(cachep, "constructor overwrote the"
1712 " end of an object");
1713 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1714 slab_error(cachep, "constructor overwrote the"
1715 " start of an object");
1717 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1718 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1721 cachep->ctor(objp, cachep, ctor_flags);
1723 slab_bufctl(slabp)[i] = i+1;
1725 slab_bufctl(slabp)[i-1] = BUFCTL_END;
1729 static void kmem_flagcheck(kmem_cache_t *cachep, int flags)
1731 if (flags & SLAB_DMA) {
1732 if (!(cachep->gfpflags & GFP_DMA))
1735 if (cachep->gfpflags & GFP_DMA)
1740 static void set_slab_attr(kmem_cache_t *cachep, struct slab *slabp, void *objp)
1745 /* Nasty!!!!!! I hope this is OK. */
1746 i = 1 << cachep->gfporder;
1747 page = virt_to_page(objp);
1749 SET_PAGE_CACHE(page, cachep);
1750 SET_PAGE_SLAB(page, slabp);
1756 * Grow (by 1) the number of slabs within a cache. This is called by
1757 * kmem_cache_alloc() when there are no active objs left in a cache.
1759 static int cache_grow (kmem_cache_t * cachep, int flags, int nodeid)
1765 unsigned long ctor_flags;
1767 /* Be lazy and only check for valid flags here,
1768 * keeping it out of the critical path in kmem_cache_alloc().
1770 if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1772 if (flags & SLAB_NO_GROW)
1775 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1776 local_flags = (flags & SLAB_LEVEL_MASK);
1777 if (!(local_flags & __GFP_WAIT))
1779 * Not allowed to sleep. Need to tell a constructor about
1780 * this - it might need to know...
1782 ctor_flags |= SLAB_CTOR_ATOMIC;
1784 /* About to mess with non-constant members - lock. */
1786 spin_lock(&cachep->spinlock);
1788 /* Get colour for the slab, and cal the next value. */
1789 offset = cachep->colour_next;
1790 cachep->colour_next++;
1791 if (cachep->colour_next >= cachep->colour)
1792 cachep->colour_next = 0;
1793 offset *= cachep->colour_off;
1795 spin_unlock(&cachep->spinlock);
1797 if (local_flags & __GFP_WAIT)
1801 * The test for missing atomic flag is performed here, rather than
1802 * the more obvious place, simply to reduce the critical path length
1803 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1804 * will eventually be caught here (where it matters).
1806 kmem_flagcheck(cachep, flags);
1809 /* Get mem for the objs. */
1810 if (!(objp = kmem_getpages(cachep, flags, nodeid)))
1813 /* Get slab management. */
1814 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1817 set_slab_attr(cachep, slabp, objp);
1819 cache_init_objs(cachep, slabp, ctor_flags);
1821 if (local_flags & __GFP_WAIT)
1822 local_irq_disable();
1824 spin_lock(&cachep->spinlock);
1826 /* Make slab active. */
1827 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1828 STATS_INC_GROWN(cachep);
1829 list3_data(cachep)->free_objects += cachep->num;
1830 spin_unlock(&cachep->spinlock);
1833 kmem_freepages(cachep, objp);
1835 if (local_flags & __GFP_WAIT)
1836 local_irq_disable();
1843 * Perform extra freeing checks:
1844 * - detect bad pointers.
1845 * - POISON/RED_ZONE checking
1846 * - destructor calls, for caches with POISON+dtor
1848 static void kfree_debugcheck(const void *objp)
1852 if (!virt_addr_valid(objp)) {
1853 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1854 (unsigned long)objp);
1857 page = virt_to_page(objp);
1858 if (!PageSlab(page)) {
1859 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1864 static void *cache_free_debugcheck (kmem_cache_t * cachep, void * objp, void *caller)
1870 objp -= obj_dbghead(cachep);
1871 kfree_debugcheck(objp);
1872 page = virt_to_page(objp);
1874 if (GET_PAGE_CACHE(page) != cachep) {
1875 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1876 GET_PAGE_CACHE(page),cachep);
1877 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1878 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1881 slabp = GET_PAGE_SLAB(page);
1883 if (cachep->flags & SLAB_RED_ZONE) {
1884 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1885 slab_error(cachep, "double free, or memory outside"
1886 " object was overwritten");
1887 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1888 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1890 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1891 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1893 if (cachep->flags & SLAB_STORE_USER)
1894 *dbg_userword(cachep, objp) = caller;
1896 objnr = (objp-slabp->s_mem)/cachep->objsize;
1898 BUG_ON(objnr >= cachep->num);
1899 BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1901 if (cachep->flags & SLAB_DEBUG_INITIAL) {
1902 /* Need to call the slab's constructor so the
1903 * caller can perform a verify of its state (debugging).
1904 * Called without the cache-lock held.
1906 cachep->ctor(objp+obj_dbghead(cachep),
1907 cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1909 if (cachep->flags & SLAB_POISON && cachep->dtor) {
1910 /* we want to cache poison the object,
1911 * call the destruction callback
1913 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1915 if (cachep->flags & SLAB_POISON) {
1916 #ifdef CONFIG_DEBUG_PAGEALLOC
1917 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1918 store_stackinfo(cachep, objp, (unsigned long)caller);
1919 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1921 poison_obj(cachep, objp, POISON_FREE);
1924 poison_obj(cachep, objp, POISON_FREE);
1930 static void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
1935 check_spinlock_acquired(cachep);
1936 /* Check slab's freelist to see if this obj is there. */
1937 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
1939 if (entries > cachep->num || i < 0 || i >= cachep->num)
1942 if (entries != cachep->num - slabp->inuse) {
1945 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
1946 cachep->name, cachep->num, slabp, slabp->inuse);
1947 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
1949 printk("\n%03x:", i);
1950 printk(" %02x", ((unsigned char*)slabp)[i]);
1957 #define kfree_debugcheck(x) do { } while(0)
1958 #define cache_free_debugcheck(x,objp,z) (objp)
1959 #define check_slabp(x,y) do { } while(0)
1962 static void* cache_alloc_refill(kmem_cache_t* cachep, int flags)
1965 struct kmem_list3 *l3;
1966 struct array_cache *ac;
1969 ac = ac_data(cachep);
1971 batchcount = ac->batchcount;
1972 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
1973 /* if there was little recent activity on this
1974 * cache, then perform only a partial refill.
1975 * Otherwise we could generate refill bouncing.
1977 batchcount = BATCHREFILL_LIMIT;
1979 l3 = list3_data(cachep);
1981 BUG_ON(ac->avail > 0);
1982 spin_lock(&cachep->spinlock);
1984 struct array_cache *shared_array = l3->shared;
1985 if (shared_array->avail) {
1986 if (batchcount > shared_array->avail)
1987 batchcount = shared_array->avail;
1988 shared_array->avail -= batchcount;
1989 ac->avail = batchcount;
1990 memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
1991 sizeof(void*)*batchcount);
1992 shared_array->touched = 1;
1996 while (batchcount > 0) {
1997 struct list_head *entry;
1999 /* Get slab alloc is to come from. */
2000 entry = l3->slabs_partial.next;
2001 if (entry == &l3->slabs_partial) {
2002 l3->free_touched = 1;
2003 entry = l3->slabs_free.next;
2004 if (entry == &l3->slabs_free)
2008 slabp = list_entry(entry, struct slab, list);
2009 check_slabp(cachep, slabp);
2010 check_spinlock_acquired(cachep);
2011 while (slabp->inuse < cachep->num && batchcount--) {
2013 STATS_INC_ALLOCED(cachep);
2014 STATS_INC_ACTIVE(cachep);
2015 STATS_SET_HIGH(cachep);
2017 /* get obj pointer */
2018 ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
2021 next = slab_bufctl(slabp)[slabp->free];
2023 slab_bufctl(slabp)[slabp->free] = BUFCTL_ALLOC;
2027 check_slabp(cachep, slabp);
2029 /* move slabp to correct slabp list: */
2030 list_del(&slabp->list);
2031 if (slabp->free == BUFCTL_END)
2032 list_add(&slabp->list, &l3->slabs_full);
2034 list_add(&slabp->list, &l3->slabs_partial);
2038 l3->free_objects -= ac->avail;
2040 spin_unlock(&cachep->spinlock);
2042 if (unlikely(!ac->avail)) {
2044 x = cache_grow(cachep, flags, -1);
2046 // cache_grow can reenable interrupts, then ac could change.
2047 ac = ac_data(cachep);
2048 if (!x && ac->avail == 0) // no objects in sight? abort
2051 if (!ac->avail) // objects refilled by interrupt?
2055 return ac_entry(ac)[--ac->avail];
2059 cache_alloc_debugcheck_before(kmem_cache_t *cachep, int flags)
2061 might_sleep_if(flags & __GFP_WAIT);
2063 kmem_flagcheck(cachep, flags);
2069 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
2070 unsigned long flags, void *objp, void *caller)
2074 if (cachep->flags & SLAB_POISON) {
2075 #ifdef CONFIG_DEBUG_PAGEALLOC
2076 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2077 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
2079 check_poison_obj(cachep, objp);
2081 check_poison_obj(cachep, objp);
2083 poison_obj(cachep, objp, POISON_INUSE);
2085 if (cachep->flags & SLAB_STORE_USER)
2086 *dbg_userword(cachep, objp) = caller;
2088 if (cachep->flags & SLAB_RED_ZONE) {
2089 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2090 slab_error(cachep, "double free, or memory outside"
2091 " object was overwritten");
2092 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
2093 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2095 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2096 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2098 objp += obj_dbghead(cachep);
2099 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2100 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2102 if (!(flags & __GFP_WAIT))
2103 ctor_flags |= SLAB_CTOR_ATOMIC;
2105 cachep->ctor(objp, cachep, ctor_flags);
2110 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2114 static inline void * __cache_alloc (kmem_cache_t *cachep, int flags)
2116 unsigned long save_flags;
2118 struct array_cache *ac;
2120 cache_alloc_debugcheck_before(cachep, flags);
2122 local_irq_save(save_flags);
2123 ac = ac_data(cachep);
2124 if (likely(ac->avail)) {
2125 STATS_INC_ALLOCHIT(cachep);
2127 objp = ac_entry(ac)[--ac->avail];
2129 STATS_INC_ALLOCMISS(cachep);
2130 objp = cache_alloc_refill(cachep, flags);
2132 local_irq_restore(save_flags);
2133 objp = cache_alloc_debugcheck_after(cachep, flags, objp, __builtin_return_address(0));
2138 * NUMA: different approach needed if the spinlock is moved into
2142 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2146 check_spinlock_acquired(cachep);
2148 /* NUMA: move add into loop */
2149 cachep->lists.free_objects += nr_objects;
2151 for (i = 0; i < nr_objects; i++) {
2152 void *objp = objpp[i];
2156 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2157 list_del(&slabp->list);
2158 objnr = (objp - slabp->s_mem) / cachep->objsize;
2159 check_slabp(cachep, slabp);
2161 if (slab_bufctl(slabp)[objnr] != BUFCTL_ALLOC) {
2162 printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2163 cachep->name, objp);
2167 slab_bufctl(slabp)[objnr] = slabp->free;
2168 slabp->free = objnr;
2169 STATS_DEC_ACTIVE(cachep);
2171 check_slabp(cachep, slabp);
2173 /* fixup slab chains */
2174 if (slabp->inuse == 0) {
2175 if (cachep->lists.free_objects > cachep->free_limit) {
2176 cachep->lists.free_objects -= cachep->num;
2177 slab_destroy(cachep, slabp);
2179 list_add(&slabp->list,
2180 &list3_data_ptr(cachep, objp)->slabs_free);
2183 /* Unconditionally move a slab to the end of the
2184 * partial list on free - maximum time for the
2185 * other objects to be freed, too.
2187 list_add_tail(&slabp->list,
2188 &list3_data_ptr(cachep, objp)->slabs_partial);
2193 static void cache_flusharray (kmem_cache_t* cachep, struct array_cache *ac)
2197 batchcount = ac->batchcount;
2199 BUG_ON(!batchcount || batchcount > ac->avail);
2202 spin_lock(&cachep->spinlock);
2203 if (cachep->lists.shared) {
2204 struct array_cache *shared_array = cachep->lists.shared;
2205 int max = shared_array->limit-shared_array->avail;
2207 if (batchcount > max)
2209 memcpy(&ac_entry(shared_array)[shared_array->avail],
2211 sizeof(void*)*batchcount);
2212 shared_array->avail += batchcount;
2217 free_block(cachep, &ac_entry(ac)[0], batchcount);
2222 struct list_head *p;
2224 p = list3_data(cachep)->slabs_free.next;
2225 while (p != &(list3_data(cachep)->slabs_free)) {
2228 slabp = list_entry(p, struct slab, list);
2229 BUG_ON(slabp->inuse);
2234 STATS_SET_FREEABLE(cachep, i);
2237 spin_unlock(&cachep->spinlock);
2238 ac->avail -= batchcount;
2239 memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2240 sizeof(void*)*ac->avail);
2245 * Release an obj back to its cache. If the obj has a constructed
2246 * state, it must be in this state _before_ it is released.
2248 * Called with disabled ints.
2250 static inline void __cache_free (kmem_cache_t *cachep, void* objp)
2252 struct array_cache *ac = ac_data(cachep);
2255 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2257 if (likely(ac->avail < ac->limit)) {
2258 STATS_INC_FREEHIT(cachep);
2259 ac_entry(ac)[ac->avail++] = objp;
2262 STATS_INC_FREEMISS(cachep);
2263 cache_flusharray(cachep, ac);
2264 ac_entry(ac)[ac->avail++] = objp;
2269 * kmem_cache_alloc - Allocate an object
2270 * @cachep: The cache to allocate from.
2271 * @flags: See kmalloc().
2273 * Allocate an object from this cache. The flags are only relevant
2274 * if the cache has no available objects.
2276 void * kmem_cache_alloc (kmem_cache_t *cachep, int flags)
2278 return __cache_alloc(cachep, flags);
2281 EXPORT_SYMBOL(kmem_cache_alloc);
2284 * kmem_ptr_validate - check if an untrusted pointer might
2286 * @cachep: the cache we're checking against
2287 * @ptr: pointer to validate
2289 * This verifies that the untrusted pointer looks sane:
2290 * it is _not_ a guarantee that the pointer is actually
2291 * part of the slab cache in question, but it at least
2292 * validates that the pointer can be dereferenced and
2293 * looks half-way sane.
2295 * Currently only used for dentry validation.
2297 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2299 unsigned long addr = (unsigned long) ptr;
2300 unsigned long min_addr = PAGE_OFFSET;
2301 unsigned long align_mask = BYTES_PER_WORD-1;
2302 unsigned long size = cachep->objsize;
2305 if (unlikely(addr < min_addr))
2307 if (unlikely(addr > (unsigned long)high_memory - size))
2309 if (unlikely(addr & align_mask))
2311 if (unlikely(!kern_addr_valid(addr)))
2313 if (unlikely(!kern_addr_valid(addr + size - 1)))
2315 page = virt_to_page(ptr);
2316 if (unlikely(!PageSlab(page)))
2318 if (unlikely(GET_PAGE_CACHE(page) != cachep))
2327 * kmem_cache_alloc_node - Allocate an object on the specified node
2328 * @cachep: The cache to allocate from.
2329 * @flags: See kmalloc().
2330 * @nodeid: node number of the target node.
2332 * Identical to kmem_cache_alloc, except that this function is slow
2333 * and can sleep. And it will allocate memory on the given node, which
2334 * can improve the performance for cpu bound structures.
2336 void *kmem_cache_alloc_node(kmem_cache_t *cachep, int nodeid)
2343 for (loop = 0;;loop++) {
2344 struct list_head *q;
2348 spin_lock_irq(&cachep->spinlock);
2349 /* walk through all partial and empty slab and find one
2350 * from the right node */
2351 list_for_each(q,&cachep->lists.slabs_partial) {
2352 slabp = list_entry(q, struct slab, list);
2354 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2358 list_for_each(q, &cachep->lists.slabs_free) {
2359 slabp = list_entry(q, struct slab, list);
2361 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2365 spin_unlock_irq(&cachep->spinlock);
2367 local_irq_disable();
2368 if (!cache_grow(cachep, GFP_KERNEL, nodeid)) {
2375 /* found one: allocate object */
2376 check_slabp(cachep, slabp);
2377 check_spinlock_acquired(cachep);
2379 STATS_INC_ALLOCED(cachep);
2380 STATS_INC_ACTIVE(cachep);
2381 STATS_SET_HIGH(cachep);
2382 STATS_INC_NODEALLOCS(cachep);
2384 objp = slabp->s_mem + slabp->free*cachep->objsize;
2387 next = slab_bufctl(slabp)[slabp->free];
2389 slab_bufctl(slabp)[slabp->free] = BUFCTL_ALLOC;
2392 check_slabp(cachep, slabp);
2394 /* move slabp to correct slabp list: */
2395 list_del(&slabp->list);
2396 if (slabp->free == BUFCTL_END)
2397 list_add(&slabp->list, &cachep->lists.slabs_full);
2399 list_add(&slabp->list, &cachep->lists.slabs_partial);
2401 list3_data(cachep)->free_objects--;
2402 spin_unlock_irq(&cachep->spinlock);
2404 objp = cache_alloc_debugcheck_after(cachep, GFP_KERNEL, objp,
2405 __builtin_return_address(0));
2408 EXPORT_SYMBOL(kmem_cache_alloc_node);
2413 * kmalloc - allocate memory
2414 * @size: how many bytes of memory are required.
2415 * @flags: the type of memory to allocate.
2417 * kmalloc is the normal method of allocating memory
2420 * The @flags argument may be one of:
2422 * %GFP_USER - Allocate memory on behalf of user. May sleep.
2424 * %GFP_KERNEL - Allocate normal kernel ram. May sleep.
2426 * %GFP_ATOMIC - Allocation will not sleep. Use inside interrupt handlers.
2428 * Additionally, the %GFP_DMA flag may be set to indicate the memory
2429 * must be suitable for DMA. This can mean different things on different
2430 * platforms. For example, on i386, it means that the memory must come
2431 * from the first 16MB.
2433 void * __kmalloc (size_t size, int flags)
2435 struct cache_sizes *csizep = malloc_sizes;
2437 for (; csizep->cs_size; csizep++) {
2438 if (size > csizep->cs_size)
2441 /* This happens if someone tries to call
2442 * kmem_cache_create(), or kmalloc(), before
2443 * the generic caches are initialized.
2445 BUG_ON(csizep->cs_cachep == NULL);
2447 return __cache_alloc(flags & GFP_DMA ?
2448 csizep->cs_dmacachep : csizep->cs_cachep, flags);
2453 EXPORT_SYMBOL(__kmalloc);
2457 * __alloc_percpu - allocate one copy of the object for every present
2458 * cpu in the system, zeroing them.
2459 * Objects should be dereferenced using the per_cpu_ptr macro only.
2461 * @size: how many bytes of memory are required.
2462 * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2464 void *__alloc_percpu(size_t size, size_t align)
2467 struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2472 for (i = 0; i < NR_CPUS; i++) {
2473 if (!cpu_possible(i))
2475 pdata->ptrs[i] = kmem_cache_alloc_node(
2476 kmem_find_general_cachep(size, GFP_KERNEL),
2479 if (!pdata->ptrs[i])
2481 memset(pdata->ptrs[i], 0, size);
2484 /* Catch derefs w/o wrappers */
2485 return (void *) (~(unsigned long) pdata);
2489 if (!cpu_possible(i))
2491 kfree(pdata->ptrs[i]);
2497 EXPORT_SYMBOL(__alloc_percpu);
2501 * kmem_cache_free - Deallocate an object
2502 * @cachep: The cache the allocation was from.
2503 * @objp: The previously allocated object.
2505 * Free an object which was previously allocated from this
2508 void kmem_cache_free (kmem_cache_t *cachep, void *objp)
2510 unsigned long flags;
2512 local_irq_save(flags);
2513 __cache_free(cachep, objp);
2514 local_irq_restore(flags);
2517 EXPORT_SYMBOL(kmem_cache_free);
2520 * kcalloc - allocate memory for an array. The memory is set to zero.
2521 * @n: number of elements.
2522 * @size: element size.
2523 * @flags: the type of memory to allocate.
2525 void *kcalloc(size_t n, size_t size, int flags)
2529 if (n != 0 && size > INT_MAX / n)
2532 ret = kmalloc(n * size, flags);
2534 memset(ret, 0, n * size);
2538 EXPORT_SYMBOL(kcalloc);
2541 * kfree - free previously allocated memory
2542 * @objp: pointer returned by kmalloc.
2544 * Don't free memory not originally allocated by kmalloc()
2545 * or you will run into trouble.
2547 void kfree (const void *objp)
2550 unsigned long flags;
2554 local_irq_save(flags);
2555 kfree_debugcheck(objp);
2556 c = GET_PAGE_CACHE(virt_to_page(objp));
2557 __cache_free(c, (void*)objp);
2558 local_irq_restore(flags);
2561 EXPORT_SYMBOL(kfree);
2565 * free_percpu - free previously allocated percpu memory
2566 * @objp: pointer returned by alloc_percpu.
2568 * Don't free memory not originally allocated by alloc_percpu()
2569 * The complemented objp is to check for that.
2572 free_percpu(const void *objp)
2575 struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2577 for (i = 0; i < NR_CPUS; i++) {
2578 if (!cpu_possible(i))
2585 EXPORT_SYMBOL(free_percpu);
2588 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2590 return obj_reallen(cachep);
2593 EXPORT_SYMBOL(kmem_cache_size);
2596 static void check_slabuse(kmem_cache_t *cachep, struct slab *slabp)
2600 if (!(cachep->flags & SLAB_RED_ZONE))
2601 return; /* no redzone data to check */
2603 for (i=0;i<cachep->num;i++) {
2604 void *objp = slabp->s_mem + cachep->objsize * i;
2605 unsigned long red1, red2;
2607 red1 = *dbg_redzone1(cachep, objp);
2608 red2 = *dbg_redzone2(cachep, objp);
2610 /* simplest case: marked as inactive */
2611 if (red1 == RED_INACTIVE && red2 == RED_INACTIVE)
2614 /* tricky case: if the bufctl value is BUFCTL_ALLOC, then
2615 * the object is either allocated or somewhere in a cpu
2616 * cache. The cpu caches are lockless and there might be
2617 * a concurrent alloc/free call, thus we must accept random
2618 * combinations of RED_ACTIVE and _INACTIVE
2620 if (slab_bufctl(slabp)[i] == BUFCTL_ALLOC &&
2621 (red1 == RED_INACTIVE || red1 == RED_ACTIVE) &&
2622 (red2 == RED_INACTIVE || red2 == RED_ACTIVE))
2625 printk(KERN_ERR "slab %s: redzone mismatch in slabp %p, objp %p, bufctl 0x%x\n",
2626 cachep->name, slabp, objp, slab_bufctl(slabp)[i]);
2627 print_objinfo(cachep, objp, 2);
2632 * Perform a self test on all slabs from a cache
2634 static void check_redzone(kmem_cache_t *cachep)
2636 struct list_head *q;
2639 check_spinlock_acquired(cachep);
2641 list_for_each(q,&cachep->lists.slabs_full) {
2642 slabp = list_entry(q, struct slab, list);
2644 if (slabp->inuse != cachep->num) {
2645 printk(KERN_INFO "slab %s: wrong slabp found in full slab chain at %p (%d/%d).\n",
2646 cachep->name, slabp, slabp->inuse, cachep->num);
2648 check_slabp(cachep, slabp);
2649 check_slabuse(cachep, slabp);
2651 list_for_each(q,&cachep->lists.slabs_partial) {
2652 slabp = list_entry(q, struct slab, list);
2654 if (slabp->inuse == cachep->num || slabp->inuse == 0) {
2655 printk(KERN_INFO "slab %s: wrong slab found in partial chain at %p (%d/%d).\n",
2656 cachep->name, slabp, slabp->inuse, cachep->num);
2658 check_slabp(cachep, slabp);
2659 check_slabuse(cachep, slabp);
2661 list_for_each(q,&cachep->lists.slabs_free) {
2662 slabp = list_entry(q, struct slab, list);
2664 if (slabp->inuse != 0) {
2665 printk(KERN_INFO "slab %s: wrong slab found in free chain at %p (%d/%d).\n",
2666 cachep->name, slabp, slabp->inuse, cachep->num);
2668 check_slabp(cachep, slabp);
2669 check_slabuse(cachep, slabp);
2675 struct ccupdate_struct {
2676 kmem_cache_t *cachep;
2677 struct array_cache *new[NR_CPUS];
2680 static void do_ccupdate_local(void *info)
2682 struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2683 struct array_cache *old;
2686 old = ac_data(new->cachep);
2688 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2689 new->new[smp_processor_id()] = old;
2693 static int do_tune_cpucache (kmem_cache_t* cachep, int limit, int batchcount, int shared)
2695 struct ccupdate_struct new;
2696 struct array_cache *new_shared;
2699 memset(&new.new,0,sizeof(new.new));
2700 for (i = 0; i < NR_CPUS; i++) {
2701 if (cpu_online(i)) {
2702 new.new[i] = alloc_arraycache(i, limit, batchcount);
2704 for (i--; i >= 0; i--) kfree(new.new[i]);
2711 new.cachep = cachep;
2713 smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2716 spin_lock_irq(&cachep->spinlock);
2717 cachep->batchcount = batchcount;
2718 cachep->limit = limit;
2719 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2720 spin_unlock_irq(&cachep->spinlock);
2722 for (i = 0; i < NR_CPUS; i++) {
2723 struct array_cache *ccold = new.new[i];
2726 spin_lock_irq(&cachep->spinlock);
2727 free_block(cachep, ac_entry(ccold), ccold->avail);
2728 spin_unlock_irq(&cachep->spinlock);
2731 new_shared = alloc_arraycache(-1, batchcount*shared, 0xbaadf00d);
2733 struct array_cache *old;
2735 spin_lock_irq(&cachep->spinlock);
2736 old = cachep->lists.shared;
2737 cachep->lists.shared = new_shared;
2739 free_block(cachep, ac_entry(old), old->avail);
2740 spin_unlock_irq(&cachep->spinlock);
2748 static void enable_cpucache (kmem_cache_t *cachep)
2753 /* The head array serves three purposes:
2754 * - create a LIFO ordering, i.e. return objects that are cache-warm
2755 * - reduce the number of spinlock operations.
2756 * - reduce the number of linked list operations on the slab and
2757 * bufctl chains: array operations are cheaper.
2758 * The numbers are guessed, we should auto-tune as described by
2761 if (cachep->objsize > 131072)
2763 else if (cachep->objsize > PAGE_SIZE)
2765 else if (cachep->objsize > 1024)
2767 else if (cachep->objsize > 256)
2772 /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2773 * allocation behaviour: Most allocs on one cpu, most free operations
2774 * on another cpu. For these cases, an efficient object passing between
2775 * cpus is necessary. This is provided by a shared array. The array
2776 * replaces Bonwick's magazine layer.
2777 * On uniprocessor, it's functionally equivalent (but less efficient)
2778 * to a larger limit. Thus disabled by default.
2782 if (cachep->objsize <= PAGE_SIZE)
2787 /* With debugging enabled, large batchcount lead to excessively
2788 * long periods with disabled local interrupts. Limit the
2794 err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2796 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2797 cachep->name, -err);
2800 static void drain_array_locked(kmem_cache_t *cachep,
2801 struct array_cache *ac, int force)
2805 check_spinlock_acquired(cachep);
2806 if (ac->touched && !force) {
2808 } else if (ac->avail) {
2809 tofree = force ? ac->avail : (ac->limit+4)/5;
2810 if (tofree > ac->avail) {
2811 tofree = (ac->avail+1)/2;
2813 free_block(cachep, ac_entry(ac), tofree);
2814 ac->avail -= tofree;
2815 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2816 sizeof(void*)*ac->avail);
2821 * cache_reap - Reclaim memory from caches.
2823 * Called from workqueue/eventd every few seconds.
2825 * - clear the per-cpu caches for this CPU.
2826 * - return freeable pages to the main free memory pool.
2828 * If we cannot acquire the cache chain semaphore then just give up - we'll
2829 * try again on the next iteration.
2831 static void cache_reap(void *unused)
2833 struct list_head *walk;
2835 if (down_trylock(&cache_chain_sem)) {
2836 /* Give up. Setup the next iteration. */
2837 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2841 list_for_each(walk, &cache_chain) {
2842 kmem_cache_t *searchp;
2843 struct list_head* p;
2847 searchp = list_entry(walk, kmem_cache_t, next);
2849 if (searchp->flags & SLAB_NO_REAP)
2854 spin_lock_irq(&searchp->spinlock);
2856 drain_array_locked(searchp, ac_data(searchp), 0);
2859 if(time_before(searchp->redzonetest, jiffies)) {
2860 searchp->redzonetest = jiffies + REDZONETIMEOUT;
2861 check_redzone(searchp);
2864 if(time_after(searchp->lists.next_reap, jiffies))
2867 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2869 if (searchp->lists.shared)
2870 drain_array_locked(searchp, searchp->lists.shared, 0);
2872 if (searchp->lists.free_touched) {
2873 searchp->lists.free_touched = 0;
2877 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2879 p = list3_data(searchp)->slabs_free.next;
2880 if (p == &(list3_data(searchp)->slabs_free))
2883 slabp = list_entry(p, struct slab, list);
2884 BUG_ON(slabp->inuse);
2885 list_del(&slabp->list);
2886 STATS_INC_REAPED(searchp);
2888 /* Safe to drop the lock. The slab is no longer
2889 * linked to the cache.
2890 * searchp cannot disappear, we hold
2893 searchp->lists.free_objects -= searchp->num;
2894 spin_unlock_irq(&searchp->spinlock);
2895 slab_destroy(searchp, slabp);
2896 spin_lock_irq(&searchp->spinlock);
2897 } while(--tofree > 0);
2899 spin_unlock_irq(&searchp->spinlock);
2904 up(&cache_chain_sem);
2905 /* Setup the next iteration */
2906 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2909 #ifdef CONFIG_PROC_FS
2911 static void *s_start(struct seq_file *m, loff_t *pos)
2914 struct list_head *p;
2916 down(&cache_chain_sem);
2919 * Output format version, so at least we can change it
2920 * without _too_ many complaints.
2923 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
2925 seq_puts(m, "slabinfo - version: 2.1\n");
2927 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2928 seq_puts(m, " : tunables <batchcount> <limit> <sharedfactor>");
2929 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
2931 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped>"
2932 " <error> <maxfreeable> <freelimit> <nodeallocs>");
2933 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
2937 p = cache_chain.next;
2940 if (p == &cache_chain)
2943 return list_entry(p, kmem_cache_t, next);
2946 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2948 kmem_cache_t *cachep = p;
2950 return cachep->next.next == &cache_chain ? NULL
2951 : list_entry(cachep->next.next, kmem_cache_t, next);
2954 static void s_stop(struct seq_file *m, void *p)
2956 up(&cache_chain_sem);
2959 static int s_show(struct seq_file *m, void *p)
2961 kmem_cache_t *cachep = p;
2962 struct list_head *q;
2964 unsigned long active_objs;
2965 unsigned long num_objs;
2966 unsigned long active_slabs = 0;
2967 unsigned long num_slabs;
2972 spin_lock_irq(&cachep->spinlock);
2975 list_for_each(q,&cachep->lists.slabs_full) {
2976 slabp = list_entry(q, struct slab, list);
2977 if (slabp->inuse != cachep->num && !error)
2978 error = "slabs_full accounting error";
2979 active_objs += cachep->num;
2982 list_for_each(q,&cachep->lists.slabs_partial) {
2983 slabp = list_entry(q, struct slab, list);
2984 if (slabp->inuse == cachep->num && !error)
2985 error = "slabs_partial inuse accounting error";
2986 if (!slabp->inuse && !error)
2987 error = "slabs_partial/inuse accounting error";
2988 active_objs += slabp->inuse;
2991 list_for_each(q,&cachep->lists.slabs_free) {
2992 slabp = list_entry(q, struct slab, list);
2993 if (slabp->inuse && !error)
2994 error = "slabs_free/inuse accounting error";
2997 num_slabs+=active_slabs;
2998 num_objs = num_slabs*cachep->num;
2999 if (num_objs - active_objs != cachep->lists.free_objects && !error)
3000 error = "free_objects accounting error";
3002 name = cachep->name;
3004 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3006 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
3007 name, active_objs, num_objs, cachep->objsize,
3008 cachep->num, (1<<cachep->gfporder));
3009 seq_printf(m, " : tunables %4u %4u %4u",
3010 cachep->limit, cachep->batchcount,
3011 cachep->lists.shared->limit/cachep->batchcount);
3012 seq_printf(m, " : slabdata %6lu %6lu %6u",
3013 active_slabs, num_slabs, cachep->lists.shared->avail);
3016 unsigned long high = cachep->high_mark;
3017 unsigned long allocs = cachep->num_allocations;
3018 unsigned long grown = cachep->grown;
3019 unsigned long reaped = cachep->reaped;
3020 unsigned long errors = cachep->errors;
3021 unsigned long max_freeable = cachep->max_freeable;
3022 unsigned long free_limit = cachep->free_limit;
3023 unsigned long node_allocs = cachep->node_allocs;
3025 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu",
3026 allocs, high, grown, reaped, errors,
3027 max_freeable, free_limit, node_allocs);
3031 unsigned long allochit = atomic_read(&cachep->allochit);
3032 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
3033 unsigned long freehit = atomic_read(&cachep->freehit);
3034 unsigned long freemiss = atomic_read(&cachep->freemiss);
3036 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
3037 allochit, allocmiss, freehit, freemiss);
3041 spin_unlock_irq(&cachep->spinlock);
3046 * slabinfo_op - iterator that generates /proc/slabinfo
3055 * num-pages-per-slab
3056 * + further values on SMP and with statistics enabled
3059 struct seq_operations slabinfo_op = {
3066 #define MAX_SLABINFO_WRITE 128
3068 * slabinfo_write - Tuning for the slab allocator
3070 * @buffer: user buffer
3071 * @count: data length
3074 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
3075 size_t count, loff_t *ppos)
3077 char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
3078 int limit, batchcount, shared, res;
3079 struct list_head *p;
3081 if (count > MAX_SLABINFO_WRITE)
3083 if (copy_from_user(&kbuf, buffer, count))
3085 kbuf[MAX_SLABINFO_WRITE] = '\0';
3087 tmp = strchr(kbuf, ' ');
3092 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3095 /* Find the cache in the chain of caches. */
3096 down(&cache_chain_sem);
3098 list_for_each(p,&cache_chain) {
3099 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
3101 if (!strcmp(cachep->name, kbuf)) {
3104 batchcount > limit ||
3108 res = do_tune_cpucache(cachep, limit, batchcount, shared);
3113 up(&cache_chain_sem);
3120 unsigned int ksize(const void *objp)
3123 unsigned long flags;
3124 unsigned int size = 0;
3126 if (likely(objp != NULL)) {
3127 local_irq_save(flags);
3128 c = GET_PAGE_CACHE(virt_to_page(objp));
3129 size = kmem_cache_size(c);
3130 local_irq_restore(flags);