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_FREE (((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;
341 #define CFLGS_OFF_SLAB (0x80000000UL)
342 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
344 #define BATCHREFILL_LIMIT 16
345 /* Optimization question: fewer reaps means less
346 * probability for unnessary cpucache drain/refill cycles.
348 * OTHO the cpuarrays can contain lots of objects,
349 * which could lock up otherwise freeable slabs.
351 #define REAPTIMEOUT_CPUC (2*HZ)
352 #define REAPTIMEOUT_LIST3 (4*HZ)
355 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
356 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
357 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
358 #define STATS_INC_GROWN(x) ((x)->grown++)
359 #define STATS_INC_REAPED(x) ((x)->reaped++)
360 #define STATS_SET_HIGH(x) do { if ((x)->num_active > (x)->high_mark) \
361 (x)->high_mark = (x)->num_active; \
363 #define STATS_INC_ERR(x) ((x)->errors++)
364 #define STATS_SET_FREEABLE(x, i) \
365 do { if ((x)->max_freeable < i) \
366 (x)->max_freeable = i; \
369 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
370 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
371 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
372 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
374 #define STATS_INC_ACTIVE(x) do { } while (0)
375 #define STATS_DEC_ACTIVE(x) do { } while (0)
376 #define STATS_INC_ALLOCED(x) do { } while (0)
377 #define STATS_INC_GROWN(x) do { } while (0)
378 #define STATS_INC_REAPED(x) do { } while (0)
379 #define STATS_SET_HIGH(x) do { } while (0)
380 #define STATS_INC_ERR(x) do { } while (0)
381 #define STATS_SET_FREEABLE(x, i) \
384 #define STATS_INC_ALLOCHIT(x) do { } while (0)
385 #define STATS_INC_ALLOCMISS(x) do { } while (0)
386 #define STATS_INC_FREEHIT(x) do { } while (0)
387 #define STATS_INC_FREEMISS(x) do { } while (0)
391 /* Magic nums for obj red zoning.
392 * Placed in the first word before and the first word after an obj.
394 #define RED_INACTIVE 0x5A2CF071UL /* when obj is inactive */
395 #define RED_ACTIVE 0x170FC2A5UL /* when obj is active */
397 /* ...and for poisoning */
398 #define POISON_INUSE 0x5a /* for use-uninitialised poisoning */
399 #define POISON_FREE 0x6b /* for use-after-free poisoning */
400 #define POISON_END 0xa5 /* end-byte of poisoning */
402 /* memory layout of objects:
404 * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
405 * the end of an object is aligned with the end of the real
406 * allocation. Catches writes behind the end of the allocation.
407 * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
409 * cachep->dbghead: The real object.
410 * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
411 * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
413 static int obj_dbghead(kmem_cache_t *cachep)
415 return cachep->dbghead;
418 static int obj_reallen(kmem_cache_t *cachep)
420 return cachep->reallen;
423 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
425 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
426 return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
429 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
431 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
432 if (cachep->flags & SLAB_STORE_USER)
433 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
434 return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
437 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
439 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
440 return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
445 #define obj_dbghead(x) 0
446 #define obj_reallen(cachep) (cachep->objsize)
447 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
448 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
449 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
454 * Maximum size of an obj (in 2^order pages)
455 * and absolute limit for the gfp order.
457 #if defined(CONFIG_LARGE_ALLOCS)
458 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
459 #define MAX_GFP_ORDER 13 /* up to 32Mb */
460 #elif defined(CONFIG_MMU)
461 #define MAX_OBJ_ORDER 5 /* 32 pages */
462 #define MAX_GFP_ORDER 5 /* 32 pages */
464 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
465 #define MAX_GFP_ORDER 8 /* up to 1Mb */
469 * Do not go above this order unless 0 objects fit into the slab.
471 #define BREAK_GFP_ORDER_HI 1
472 #define BREAK_GFP_ORDER_LO 0
473 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
475 /* Macros for storing/retrieving the cachep and or slab from the
476 * global 'mem_map'. These are used to find the slab an obj belongs to.
477 * With kfree(), these are used to find the cache which an obj belongs to.
479 #define SET_PAGE_CACHE(pg,x) ((pg)->lru.next = (struct list_head *)(x))
480 #define GET_PAGE_CACHE(pg) ((kmem_cache_t *)(pg)->lru.next)
481 #define SET_PAGE_SLAB(pg,x) ((pg)->lru.prev = (struct list_head *)(x))
482 #define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->lru.prev)
484 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
485 struct cache_sizes malloc_sizes[] = {
486 #define CACHE(x) { .cs_size = (x) },
487 #include <linux/kmalloc_sizes.h>
492 EXPORT_SYMBOL(malloc_sizes);
494 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
500 static struct cache_names __initdata cache_names[] = {
501 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
502 #include <linux/kmalloc_sizes.h>
507 static struct arraycache_init initarray_cache __initdata =
508 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
509 static struct arraycache_init initarray_generic __initdata =
510 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
512 /* internal cache of cache description objs */
513 static kmem_cache_t cache_cache = {
514 .lists = LIST3_INIT(cache_cache.lists),
516 .limit = BOOT_CPUCACHE_ENTRIES,
517 .objsize = sizeof(kmem_cache_t),
518 .flags = SLAB_NO_REAP,
519 .spinlock = SPIN_LOCK_UNLOCKED,
520 .name = "kmem_cache",
522 .reallen = sizeof(kmem_cache_t),
526 /* Guard access to the cache-chain. */
527 static struct semaphore cache_chain_sem;
528 static struct list_head cache_chain;
531 * vm_enough_memory() looks at this to determine how many
532 * slab-allocated pages are possibly freeable under pressure
534 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
536 atomic_t slab_reclaim_pages;
537 EXPORT_SYMBOL(slab_reclaim_pages);
540 * chicken and egg problem: delay the per-cpu array allocation
541 * until the general caches are up.
549 static DEFINE_PER_CPU(struct work_struct, reap_work);
551 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
552 static void enable_cpucache (kmem_cache_t *cachep);
553 static void cache_reap (void *unused);
555 static inline void ** ac_entry(struct array_cache *ac)
557 return (void**)(ac+1);
560 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
562 return cachep->array[smp_processor_id()];
565 static kmem_cache_t * kmem_find_general_cachep (size_t size, int gfpflags)
567 struct cache_sizes *csizep = malloc_sizes;
569 /* This function could be moved to the header file, and
570 * made inline so consumers can quickly determine what
571 * cache pointer they require.
573 for ( ; csizep->cs_size; csizep++) {
574 if (size > csizep->cs_size)
578 return (gfpflags & GFP_DMA) ? csizep->cs_dmacachep : csizep->cs_cachep;
581 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
582 static void cache_estimate (unsigned long gfporder, size_t size, size_t align,
583 int flags, size_t *left_over, unsigned int *num)
586 size_t wastage = PAGE_SIZE<<gfporder;
590 if (!(flags & CFLGS_OFF_SLAB)) {
591 base = sizeof(struct slab);
592 extra = sizeof(kmem_bufctl_t);
595 while (i*size + ALIGN(base+i*extra, align) <= wastage)
605 wastage -= ALIGN(base+i*extra, align);
606 *left_over = wastage;
609 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
611 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
613 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
614 function, cachep->name, msg);
619 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
620 * via the workqueue/eventd.
621 * Add the CPU number into the expiration time to minimize the possibility of
622 * the CPUs getting into lockstep and contending for the global cache chain
625 static void __devinit start_cpu_timer(int cpu)
627 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
630 * When this gets called from do_initcalls via cpucache_init(),
631 * init_workqueues() has already run, so keventd will be setup
634 if (keventd_up() && reap_work->func == NULL) {
635 INIT_WORK(reap_work, cache_reap, NULL);
636 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
640 static struct array_cache *alloc_arraycache(int cpu, int entries, int batchcount)
642 int memsize = sizeof(void*)*entries+sizeof(struct array_cache);
643 struct array_cache *nc = NULL;
646 nc = kmem_cache_alloc_node(kmem_find_general_cachep(memsize,
647 GFP_KERNEL), cpu_to_node(cpu));
650 nc = kmalloc(memsize, GFP_KERNEL);
654 nc->batchcount = batchcount;
660 static int __devinit cpuup_callback(struct notifier_block *nfb,
661 unsigned long action,
664 long cpu = (long)hcpu;
665 kmem_cache_t* cachep;
669 down(&cache_chain_sem);
670 list_for_each_entry(cachep, &cache_chain, next) {
671 struct array_cache *nc;
673 nc = alloc_arraycache(cpu, cachep->limit, cachep->batchcount);
677 spin_lock_irq(&cachep->spinlock);
678 cachep->array[cpu] = nc;
679 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
681 spin_unlock_irq(&cachep->spinlock);
684 up(&cache_chain_sem);
687 start_cpu_timer(cpu);
689 #ifdef CONFIG_HOTPLUG_CPU
692 case CPU_UP_CANCELED:
693 down(&cache_chain_sem);
695 list_for_each_entry(cachep, &cache_chain, next) {
696 struct array_cache *nc;
698 spin_lock_irq(&cachep->spinlock);
699 /* cpu is dead; no one can alloc from it. */
700 nc = cachep->array[cpu];
701 cachep->array[cpu] = NULL;
702 cachep->free_limit -= cachep->batchcount;
703 free_block(cachep, ac_entry(nc), nc->avail);
704 spin_unlock_irq(&cachep->spinlock);
707 up(&cache_chain_sem);
713 up(&cache_chain_sem);
717 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
720 * Called after the gfp() functions have been enabled, and before smp_init().
722 void __init kmem_cache_init(void)
725 struct cache_sizes *sizes;
726 struct cache_names *names;
729 * Fragmentation resistance on low memory - only use bigger
730 * page orders on machines with more than 32MB of memory.
732 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
733 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
736 /* Bootstrap is tricky, because several objects are allocated
737 * from caches that do not exist yet:
738 * 1) initialize the cache_cache cache: it contains the kmem_cache_t
739 * structures of all caches, except cache_cache itself: cache_cache
740 * is statically allocated.
741 * Initially an __init data area is used for the head array, it's
742 * replaced with a kmalloc allocated array at the end of the bootstrap.
743 * 2) Create the first kmalloc cache.
744 * The kmem_cache_t for the new cache is allocated normally. An __init
745 * data area is used for the head array.
746 * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
747 * 4) Replace the __init data head arrays for cache_cache and the first
748 * kmalloc cache with kmalloc allocated arrays.
749 * 5) Resize the head arrays of the kmalloc caches to their final sizes.
752 /* 1) create the cache_cache */
753 init_MUTEX(&cache_chain_sem);
754 INIT_LIST_HEAD(&cache_chain);
755 list_add(&cache_cache.next, &cache_chain);
756 cache_cache.colour_off = cache_line_size();
757 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
759 cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
761 cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
762 &left_over, &cache_cache.num);
763 if (!cache_cache.num)
766 cache_cache.colour = left_over/cache_cache.colour_off;
767 cache_cache.colour_next = 0;
768 cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
769 sizeof(struct slab), cache_line_size());
771 /* 2+3) create the kmalloc caches */
772 sizes = malloc_sizes;
775 while (sizes->cs_size) {
776 /* For performance, all the general caches are L1 aligned.
777 * This should be particularly beneficial on SMP boxes, as it
778 * eliminates "false sharing".
779 * Note for systems short on memory removing the alignment will
780 * allow tighter packing of the smaller caches. */
781 sizes->cs_cachep = kmem_cache_create(names->name,
782 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
783 (ARCH_KMALLOC_FLAGS | SLAB_PANIC), NULL, NULL);
785 /* Inc off-slab bufctl limit until the ceiling is hit. */
786 if (!(OFF_SLAB(sizes->cs_cachep))) {
787 offslab_limit = sizes->cs_size-sizeof(struct slab);
788 offslab_limit /= sizeof(kmem_bufctl_t);
791 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
792 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
793 (ARCH_KMALLOC_FLAGS | SLAB_CACHE_DMA | SLAB_PANIC),
799 /* 4) Replace the bootstrap head arrays */
803 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
805 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
806 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
807 cache_cache.array[smp_processor_id()] = ptr;
810 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
812 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
813 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
814 sizeof(struct arraycache_init));
815 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
819 /* 5) resize the head arrays to their final sizes */
821 kmem_cache_t *cachep;
822 down(&cache_chain_sem);
823 list_for_each_entry(cachep, &cache_chain, next)
824 enable_cpucache(cachep);
825 up(&cache_chain_sem);
829 g_cpucache_up = FULL;
831 /* Register a cpu startup notifier callback
832 * that initializes ac_data for all new cpus
834 register_cpu_notifier(&cpucache_notifier);
837 /* The reap timers are started later, with a module init call:
838 * That part of the kernel is not yet operational.
842 static int __init cpucache_init(void)
847 * Register the timers that return unneeded
850 for (cpu = 0; cpu < NR_CPUS; cpu++) {
852 start_cpu_timer(cpu);
858 __initcall(cpucache_init);
861 * Interface to system's page allocator. No need to hold the cache-lock.
863 * If we requested dmaable memory, we will get it. Even if we
864 * did not request dmaable memory, we might get it, but that
865 * would be relatively rare and ignorable.
867 static void *kmem_getpages(kmem_cache_t *cachep, int flags, int nodeid)
873 flags |= cachep->gfpflags;
874 if (likely(nodeid == -1)) {
875 addr = (void*)__get_free_pages(flags, cachep->gfporder);
878 page = virt_to_page(addr);
880 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
883 addr = page_address(page);
886 i = (1 << cachep->gfporder);
887 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
888 atomic_add(i, &slab_reclaim_pages);
889 add_page_state(nr_slab, i);
898 * Interface to system's page release.
900 static void kmem_freepages(kmem_cache_t *cachep, void *addr)
902 unsigned long i = (1<<cachep->gfporder);
903 struct page *page = virt_to_page(addr);
904 const unsigned long nr_freed = i;
907 if (!TestClearPageSlab(page))
911 sub_page_state(nr_slab, nr_freed);
912 if (current->reclaim_state)
913 current->reclaim_state->reclaimed_slab += nr_freed;
914 free_pages((unsigned long)addr, cachep->gfporder);
915 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
916 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
919 static void kmem_rcu_free(struct rcu_head *head)
921 struct slab_rcu *slab_rcu = (struct slab_rcu *) head;
922 kmem_cache_t *cachep = slab_rcu->cachep;
924 kmem_freepages(cachep, slab_rcu->addr);
925 if (OFF_SLAB(cachep))
926 kmem_cache_free(cachep->slabp_cache, slab_rcu);
931 #ifdef CONFIG_DEBUG_PAGEALLOC
932 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr, unsigned long caller)
934 int size = obj_reallen(cachep);
936 addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
938 if (size < 5*sizeof(unsigned long))
943 *addr++=smp_processor_id();
944 size -= 3*sizeof(unsigned long);
946 unsigned long *sptr = &caller;
947 unsigned long svalue;
949 while (!kstack_end(sptr)) {
951 if (kernel_text_address(svalue)) {
953 size -= sizeof(unsigned long);
954 if (size <= sizeof(unsigned long))
964 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
966 int size = obj_reallen(cachep);
967 addr = &((char*)addr)[obj_dbghead(cachep)];
969 memset(addr, val, size);
970 *(unsigned char *)(addr+size-1) = POISON_END;
973 static void dump_line(char *data, int offset, int limit)
976 printk(KERN_ERR "%03x:", offset);
977 for (i=0;i<limit;i++) {
978 printk(" %02x", (unsigned char)data[offset+i]);
986 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
991 if (cachep->flags & SLAB_RED_ZONE) {
992 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
993 *dbg_redzone1(cachep, objp),
994 *dbg_redzone2(cachep, objp));
997 if (cachep->flags & SLAB_STORE_USER) {
998 printk(KERN_ERR "Last user: [<%p>]",
999 *dbg_userword(cachep, objp));
1000 print_symbol("(%s)",
1001 (unsigned long)*dbg_userword(cachep, objp));
1004 realobj = (char*)objp+obj_dbghead(cachep);
1005 size = obj_reallen(cachep);
1006 for (i=0; i<size && lines;i+=16, lines--) {
1011 dump_line(realobj, i, limit);
1015 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
1021 realobj = (char*)objp+obj_dbghead(cachep);
1022 size = obj_reallen(cachep);
1024 for (i=0;i<size;i++) {
1025 char exp = POISON_FREE;
1028 if (realobj[i] != exp) {
1033 printk(KERN_ERR "Slab corruption: start=%p, len=%d\n",
1035 print_objinfo(cachep, objp, 0);
1037 /* Hexdump the affected line */
1042 dump_line(realobj, i, limit);
1045 /* Limit to 5 lines */
1051 /* Print some data about the neighboring objects, if they
1054 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1057 objnr = (objp-slabp->s_mem)/cachep->objsize;
1059 objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1060 realobj = (char*)objp+obj_dbghead(cachep);
1061 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1063 print_objinfo(cachep, objp, 2);
1065 if (objnr+1 < cachep->num) {
1066 objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1067 realobj = (char*)objp+obj_dbghead(cachep);
1068 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1070 print_objinfo(cachep, objp, 2);
1076 /* Destroy all the objs in a slab, and release the mem back to the system.
1077 * Before calling the slab must have been unlinked from the cache.
1078 * The cache-lock is not held/needed.
1080 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1082 void *addr = slabp->s_mem - slabp->colouroff;
1086 for (i = 0; i < cachep->num; i++) {
1087 void *objp = slabp->s_mem + cachep->objsize * i;
1089 if (cachep->flags & SLAB_POISON) {
1090 #ifdef CONFIG_DEBUG_PAGEALLOC
1091 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1092 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1094 check_poison_obj(cachep, objp);
1096 check_poison_obj(cachep, objp);
1099 if (cachep->flags & SLAB_RED_ZONE) {
1100 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1101 slab_error(cachep, "start of a freed object "
1103 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1104 slab_error(cachep, "end of a freed object "
1107 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1108 (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1113 for (i = 0; i < cachep->num; i++) {
1114 void* objp = slabp->s_mem+cachep->objsize*i;
1115 (cachep->dtor)(objp, cachep, 0);
1120 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1121 struct slab_rcu *slab_rcu;
1123 slab_rcu = (struct slab_rcu *) slabp;
1124 slab_rcu->cachep = cachep;
1125 slab_rcu->addr = addr;
1126 call_rcu(&slab_rcu->head, kmem_rcu_free);
1128 kmem_freepages(cachep, addr);
1129 if (OFF_SLAB(cachep))
1130 kmem_cache_free(cachep->slabp_cache, slabp);
1135 * kmem_cache_create - Create a cache.
1136 * @name: A string which is used in /proc/slabinfo to identify this cache.
1137 * @size: The size of objects to be created in this cache.
1138 * @align: The required alignment for the objects.
1139 * @flags: SLAB flags
1140 * @ctor: A constructor for the objects.
1141 * @dtor: A destructor for the objects.
1143 * Returns a ptr to the cache on success, NULL on failure.
1144 * Cannot be called within a int, but can be interrupted.
1145 * The @ctor is run when new pages are allocated by the cache
1146 * and the @dtor is run before the pages are handed back.
1148 * @name must be valid until the cache is destroyed. This implies that
1149 * the module calling this has to destroy the cache before getting
1154 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1155 * to catch references to uninitialised memory.
1157 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1158 * for buffer overruns.
1160 * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1163 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1164 * cacheline. This can be beneficial if you're counting cycles as closely
1168 kmem_cache_create (const char *name, size_t size, size_t align,
1169 unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1170 void (*dtor)(void*, kmem_cache_t *, unsigned long))
1172 size_t left_over, slab_size;
1173 kmem_cache_t *cachep = NULL;
1176 * Sanity checks... these are all serious usage bugs.
1180 (size < BYTES_PER_WORD) ||
1181 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1183 printk(KERN_ERR "%s: Early error in slab %s\n",
1184 __FUNCTION__, name);
1189 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
1190 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1191 /* No constructor, but inital state check requested */
1192 printk(KERN_ERR "%s: No con, but init state check "
1193 "requested - %s\n", __FUNCTION__, name);
1194 flags &= ~SLAB_DEBUG_INITIAL;
1199 * Enable redzoning and last user accounting, except for caches with
1200 * large objects, if the increased size would increase the object size
1201 * above the next power of two: caches with object sizes just above a
1202 * power of two have a significant amount of internal fragmentation.
1204 if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1205 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1206 if (!(flags & SLAB_DESTROY_BY_RCU))
1207 flags |= SLAB_POISON;
1209 if (flags & SLAB_DESTROY_BY_RCU)
1210 BUG_ON(flags & SLAB_POISON);
1212 if (flags & SLAB_DESTROY_BY_RCU)
1216 * Always checks flags, a caller might be expecting debug
1217 * support which isn't available.
1219 if (flags & ~CREATE_MASK)
1223 /* combinations of forced alignment and advanced debugging is
1224 * not yet implemented.
1226 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1228 if (flags & SLAB_HWCACHE_ALIGN) {
1229 /* Default alignment: as specified by the arch code.
1230 * Except if an object is really small, then squeeze multiple
1231 * into one cacheline.
1233 align = cache_line_size();
1234 while (size <= align/2)
1237 align = BYTES_PER_WORD;
1241 /* Get cache's description obj. */
1242 cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1245 memset(cachep, 0, sizeof(kmem_cache_t));
1247 /* Check that size is in terms of words. This is needed to avoid
1248 * unaligned accesses for some archs when redzoning is used, and makes
1249 * sure any on-slab bufctl's are also correctly aligned.
1251 if (size & (BYTES_PER_WORD-1)) {
1252 size += (BYTES_PER_WORD-1);
1253 size &= ~(BYTES_PER_WORD-1);
1257 cachep->reallen = size;
1259 if (flags & SLAB_RED_ZONE) {
1260 /* redzoning only works with word aligned caches */
1261 align = BYTES_PER_WORD;
1263 /* add space for red zone words */
1264 cachep->dbghead += BYTES_PER_WORD;
1265 size += 2*BYTES_PER_WORD;
1267 if (flags & SLAB_STORE_USER) {
1268 /* user store requires word alignment and
1269 * one word storage behind the end of the real
1272 align = BYTES_PER_WORD;
1273 size += BYTES_PER_WORD;
1275 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1276 if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1277 cachep->dbghead += PAGE_SIZE - size;
1283 /* Determine if the slab management is 'on' or 'off' slab. */
1284 if (size >= (PAGE_SIZE>>3))
1286 * Size is large, assume best to place the slab management obj
1287 * off-slab (should allow better packing of objs).
1289 flags |= CFLGS_OFF_SLAB;
1291 size = ALIGN(size, align);
1293 if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1295 * A VFS-reclaimable slab tends to have most allocations
1296 * as GFP_NOFS and we really don't want to have to be allocating
1297 * higher-order pages when we are unable to shrink dcache.
1299 cachep->gfporder = 0;
1300 cache_estimate(cachep->gfporder, size, align, flags,
1301 &left_over, &cachep->num);
1304 * Calculate size (in pages) of slabs, and the num of objs per
1305 * slab. This could be made much more intelligent. For now,
1306 * try to avoid using high page-orders for slabs. When the
1307 * gfp() funcs are more friendly towards high-order requests,
1308 * this should be changed.
1311 unsigned int break_flag = 0;
1313 cache_estimate(cachep->gfporder, size, align, flags,
1314 &left_over, &cachep->num);
1317 if (cachep->gfporder >= MAX_GFP_ORDER)
1321 if (flags & CFLGS_OFF_SLAB &&
1322 cachep->num > offslab_limit) {
1323 /* This num of objs will cause problems. */
1330 * Large num of objs is good, but v. large slabs are
1331 * currently bad for the gfp()s.
1333 if (cachep->gfporder >= slab_break_gfp_order)
1336 if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1337 break; /* Acceptable internal fragmentation. */
1344 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1345 kmem_cache_free(&cache_cache, cachep);
1349 slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1350 + sizeof(struct slab), align);
1353 * If the slab has been placed off-slab, and we have enough space then
1354 * move it on-slab. This is at the expense of any extra colouring.
1356 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1357 flags &= ~CFLGS_OFF_SLAB;
1358 left_over -= slab_size;
1361 if (flags & CFLGS_OFF_SLAB) {
1362 /* really off slab. No need for manual alignment */
1363 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1366 cachep->colour_off = cache_line_size();
1367 /* Offset must be a multiple of the alignment. */
1368 if (cachep->colour_off < align)
1369 cachep->colour_off = align;
1370 cachep->colour = left_over/cachep->colour_off;
1371 cachep->slab_size = slab_size;
1372 cachep->flags = flags;
1373 cachep->gfpflags = 0;
1374 if (flags & SLAB_CACHE_DMA)
1375 cachep->gfpflags |= GFP_DMA;
1376 spin_lock_init(&cachep->spinlock);
1377 cachep->objsize = size;
1379 INIT_LIST_HEAD(&cachep->lists.slabs_full);
1380 INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1381 INIT_LIST_HEAD(&cachep->lists.slabs_free);
1383 if (flags & CFLGS_OFF_SLAB)
1384 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1385 cachep->ctor = ctor;
1386 cachep->dtor = dtor;
1387 cachep->name = name;
1389 /* Don't let CPUs to come and go */
1392 if (g_cpucache_up == FULL) {
1393 enable_cpucache(cachep);
1395 if (g_cpucache_up == NONE) {
1396 /* Note: the first kmem_cache_create must create
1397 * the cache that's used by kmalloc(24), otherwise
1398 * the creation of further caches will BUG().
1400 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1401 g_cpucache_up = PARTIAL;
1403 cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1405 BUG_ON(!ac_data(cachep));
1406 ac_data(cachep)->avail = 0;
1407 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1408 ac_data(cachep)->batchcount = 1;
1409 ac_data(cachep)->touched = 0;
1410 cachep->batchcount = 1;
1411 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1412 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1416 cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1417 ((unsigned long)cachep)%REAPTIMEOUT_LIST3;
1419 /* Need the semaphore to access the chain. */
1420 down(&cache_chain_sem);
1422 struct list_head *p;
1423 mm_segment_t old_fs;
1427 list_for_each(p, &cache_chain) {
1428 kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1430 /* This happens when the module gets unloaded and doesn't
1431 destroy its slab cache and noone else reuses the vmalloc
1432 area of the module. Print a warning. */
1433 if (__get_user(tmp,pc->name)) {
1434 printk("SLAB: cache with size %d has lost its name\n",
1438 if (!strcmp(pc->name,name)) {
1439 printk("kmem_cache_create: duplicate cache %s\n",name);
1440 up(&cache_chain_sem);
1441 unlock_cpu_hotplug();
1448 /* cache setup completed, link it into the list */
1449 list_add(&cachep->next, &cache_chain);
1450 up(&cache_chain_sem);
1451 unlock_cpu_hotplug();
1453 if (!cachep && (flags & SLAB_PANIC))
1454 panic("kmem_cache_create(): failed to create slab `%s'\n",
1458 EXPORT_SYMBOL(kmem_cache_create);
1461 static void check_irq_off(void)
1463 BUG_ON(!irqs_disabled());
1466 static void check_irq_on(void)
1468 BUG_ON(irqs_disabled());
1471 static void check_spinlock_acquired(kmem_cache_t *cachep)
1475 BUG_ON(spin_trylock(&cachep->spinlock));
1479 #define check_irq_off() do { } while(0)
1480 #define check_irq_on() do { } while(0)
1481 #define check_spinlock_acquired(x) do { } while(0)
1485 * Waits for all CPUs to execute func().
1487 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1492 local_irq_disable();
1496 if (smp_call_function(func, arg, 1, 1))
1502 static void drain_array_locked(kmem_cache_t* cachep,
1503 struct array_cache *ac, int force);
1505 static void do_drain(void *arg)
1507 kmem_cache_t *cachep = (kmem_cache_t*)arg;
1508 struct array_cache *ac;
1511 ac = ac_data(cachep);
1512 spin_lock(&cachep->spinlock);
1513 free_block(cachep, &ac_entry(ac)[0], ac->avail);
1514 spin_unlock(&cachep->spinlock);
1518 static void drain_cpu_caches(kmem_cache_t *cachep)
1520 smp_call_function_all_cpus(do_drain, cachep);
1522 spin_lock_irq(&cachep->spinlock);
1523 if (cachep->lists.shared)
1524 drain_array_locked(cachep, cachep->lists.shared, 1);
1525 spin_unlock_irq(&cachep->spinlock);
1529 /* NUMA shrink all list3s */
1530 static int __cache_shrink(kmem_cache_t *cachep)
1535 drain_cpu_caches(cachep);
1538 spin_lock_irq(&cachep->spinlock);
1541 struct list_head *p;
1543 p = cachep->lists.slabs_free.prev;
1544 if (p == &cachep->lists.slabs_free)
1547 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1552 list_del(&slabp->list);
1554 cachep->lists.free_objects -= cachep->num;
1555 spin_unlock_irq(&cachep->spinlock);
1556 slab_destroy(cachep, slabp);
1557 spin_lock_irq(&cachep->spinlock);
1559 ret = !list_empty(&cachep->lists.slabs_full) ||
1560 !list_empty(&cachep->lists.slabs_partial);
1561 spin_unlock_irq(&cachep->spinlock);
1566 * kmem_cache_shrink - Shrink a cache.
1567 * @cachep: The cache to shrink.
1569 * Releases as many slabs as possible for a cache.
1570 * To help debugging, a zero exit status indicates all slabs were released.
1572 int kmem_cache_shrink(kmem_cache_t *cachep)
1574 if (!cachep || in_interrupt())
1577 return __cache_shrink(cachep);
1580 EXPORT_SYMBOL(kmem_cache_shrink);
1583 * kmem_cache_destroy - delete a cache
1584 * @cachep: the cache to destroy
1586 * Remove a kmem_cache_t object from the slab cache.
1587 * Returns 0 on success.
1589 * It is expected this function will be called by a module when it is
1590 * unloaded. This will remove the cache completely, and avoid a duplicate
1591 * cache being allocated each time a module is loaded and unloaded, if the
1592 * module doesn't have persistent in-kernel storage across loads and unloads.
1594 * The cache must be empty before calling this function.
1596 * The caller must guarantee that noone will allocate memory from the cache
1597 * during the kmem_cache_destroy().
1599 int kmem_cache_destroy (kmem_cache_t * cachep)
1603 if (!cachep || in_interrupt())
1606 /* Don't let CPUs to come and go */
1609 /* Find the cache in the chain of caches. */
1610 down(&cache_chain_sem);
1612 * the chain is never empty, cache_cache is never destroyed
1614 list_del(&cachep->next);
1615 up(&cache_chain_sem);
1617 if (__cache_shrink(cachep)) {
1618 slab_error(cachep, "Can't free all objects");
1619 down(&cache_chain_sem);
1620 list_add(&cachep->next,&cache_chain);
1621 up(&cache_chain_sem);
1622 unlock_cpu_hotplug();
1626 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1627 synchronize_kernel();
1629 /* no cpu_online check required here since we clear the percpu
1630 * array on cpu offline and set this to NULL.
1632 for (i = 0; i < NR_CPUS; i++)
1633 kfree(cachep->array[i]);
1635 /* NUMA: free the list3 structures */
1636 kfree(cachep->lists.shared);
1637 cachep->lists.shared = NULL;
1638 kmem_cache_free(&cache_cache, cachep);
1640 unlock_cpu_hotplug();
1645 EXPORT_SYMBOL(kmem_cache_destroy);
1647 /* Get the memory for a slab management obj. */
1648 static struct slab* alloc_slabmgmt (kmem_cache_t *cachep,
1649 void *objp, int colour_off, int local_flags)
1653 if (OFF_SLAB(cachep)) {
1654 /* Slab management obj is off-slab. */
1655 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1659 slabp = objp+colour_off;
1660 colour_off += cachep->slab_size;
1663 slabp->colouroff = colour_off;
1664 slabp->s_mem = objp+colour_off;
1669 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1671 return (kmem_bufctl_t *)(slabp+1);
1674 static void cache_init_objs (kmem_cache_t * cachep,
1675 struct slab * slabp, unsigned long ctor_flags)
1679 for (i = 0; i < cachep->num; i++) {
1680 void* objp = slabp->s_mem+cachep->objsize*i;
1682 /* need to poison the objs? */
1683 if (cachep->flags & SLAB_POISON)
1684 poison_obj(cachep, objp, POISON_FREE);
1685 if (cachep->flags & SLAB_STORE_USER)
1686 *dbg_userword(cachep, objp) = NULL;
1688 if (cachep->flags & SLAB_RED_ZONE) {
1689 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1690 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1693 * Constructors are not allowed to allocate memory from
1694 * the same cache which they are a constructor for.
1695 * Otherwise, deadlock. They must also be threaded.
1697 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1698 cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1700 if (cachep->flags & SLAB_RED_ZONE) {
1701 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1702 slab_error(cachep, "constructor overwrote the"
1703 " end of an object");
1704 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1705 slab_error(cachep, "constructor overwrote the"
1706 " start of an object");
1708 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1709 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1712 cachep->ctor(objp, cachep, ctor_flags);
1714 slab_bufctl(slabp)[i] = i+1;
1716 slab_bufctl(slabp)[i-1] = BUFCTL_END;
1720 static void kmem_flagcheck(kmem_cache_t *cachep, int flags)
1722 if (flags & SLAB_DMA) {
1723 if (!(cachep->gfpflags & GFP_DMA))
1726 if (cachep->gfpflags & GFP_DMA)
1731 static void set_slab_attr(kmem_cache_t *cachep, struct slab *slabp, void *objp)
1736 /* Nasty!!!!!! I hope this is OK. */
1737 i = 1 << cachep->gfporder;
1738 page = virt_to_page(objp);
1740 SET_PAGE_CACHE(page, cachep);
1741 SET_PAGE_SLAB(page, slabp);
1747 * Grow (by 1) the number of slabs within a cache. This is called by
1748 * kmem_cache_alloc() when there are no active objs left in a cache.
1750 static int cache_grow (kmem_cache_t * cachep, int flags)
1756 unsigned long ctor_flags;
1758 /* Be lazy and only check for valid flags here,
1759 * keeping it out of the critical path in kmem_cache_alloc().
1761 if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1763 if (flags & SLAB_NO_GROW)
1766 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1767 local_flags = (flags & SLAB_LEVEL_MASK);
1768 if (!(local_flags & __GFP_WAIT))
1770 * Not allowed to sleep. Need to tell a constructor about
1771 * this - it might need to know...
1773 ctor_flags |= SLAB_CTOR_ATOMIC;
1775 /* About to mess with non-constant members - lock. */
1777 spin_lock(&cachep->spinlock);
1779 /* Get colour for the slab, and cal the next value. */
1780 offset = cachep->colour_next;
1781 cachep->colour_next++;
1782 if (cachep->colour_next >= cachep->colour)
1783 cachep->colour_next = 0;
1784 offset *= cachep->colour_off;
1786 spin_unlock(&cachep->spinlock);
1788 if (local_flags & __GFP_WAIT)
1792 * The test for missing atomic flag is performed here, rather than
1793 * the more obvious place, simply to reduce the critical path length
1794 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1795 * will eventually be caught here (where it matters).
1797 kmem_flagcheck(cachep, flags);
1800 /* Get mem for the objs. */
1801 if (!(objp = kmem_getpages(cachep, flags, -1)))
1804 /* Get slab management. */
1805 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1808 set_slab_attr(cachep, slabp, objp);
1810 cache_init_objs(cachep, slabp, ctor_flags);
1812 if (local_flags & __GFP_WAIT)
1813 local_irq_disable();
1815 spin_lock(&cachep->spinlock);
1817 /* Make slab active. */
1818 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1819 STATS_INC_GROWN(cachep);
1820 list3_data(cachep)->free_objects += cachep->num;
1821 spin_unlock(&cachep->spinlock);
1824 kmem_freepages(cachep, objp);
1826 if (local_flags & __GFP_WAIT)
1827 local_irq_disable();
1834 * Perform extra freeing checks:
1835 * - detect bad pointers.
1836 * - POISON/RED_ZONE checking
1837 * - destructor calls, for caches with POISON+dtor
1839 static void kfree_debugcheck(const void *objp)
1843 if (!virt_addr_valid(objp)) {
1844 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1845 (unsigned long)objp);
1848 page = virt_to_page(objp);
1849 if (!PageSlab(page)) {
1850 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1855 static void *cache_free_debugcheck (kmem_cache_t * cachep, void * objp, void *caller)
1861 objp -= obj_dbghead(cachep);
1862 kfree_debugcheck(objp);
1863 page = virt_to_page(objp);
1865 if (GET_PAGE_CACHE(page) != cachep) {
1866 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1867 GET_PAGE_CACHE(page),cachep);
1868 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1869 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1872 slabp = GET_PAGE_SLAB(page);
1874 if (cachep->flags & SLAB_RED_ZONE) {
1875 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1876 slab_error(cachep, "double free, or memory outside"
1877 " object was overwritten");
1878 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1879 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1881 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1882 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1884 if (cachep->flags & SLAB_STORE_USER)
1885 *dbg_userword(cachep, objp) = caller;
1887 objnr = (objp-slabp->s_mem)/cachep->objsize;
1889 BUG_ON(objnr >= cachep->num);
1890 BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1892 if (cachep->flags & SLAB_DEBUG_INITIAL) {
1893 /* Need to call the slab's constructor so the
1894 * caller can perform a verify of its state (debugging).
1895 * Called without the cache-lock held.
1897 cachep->ctor(objp+obj_dbghead(cachep),
1898 cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1900 if (cachep->flags & SLAB_POISON && cachep->dtor) {
1901 /* we want to cache poison the object,
1902 * call the destruction callback
1904 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1906 if (cachep->flags & SLAB_POISON) {
1907 #ifdef CONFIG_DEBUG_PAGEALLOC
1908 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1909 store_stackinfo(cachep, objp, (unsigned long)caller);
1910 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1912 poison_obj(cachep, objp, POISON_FREE);
1915 poison_obj(cachep, objp, POISON_FREE);
1921 static void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
1926 check_spinlock_acquired(cachep);
1927 /* Check slab's freelist to see if this obj is there. */
1928 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
1930 if (entries > cachep->num || i < 0 || i >= cachep->num)
1933 if (entries != cachep->num - slabp->inuse) {
1936 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
1937 cachep->name, cachep->num, slabp, slabp->inuse);
1938 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
1940 printk("\n%03x:", i);
1941 printk(" %02x", ((unsigned char*)slabp)[i]);
1948 #define kfree_debugcheck(x) do { } while(0)
1949 #define cache_free_debugcheck(x,objp,z) (objp)
1950 #define check_slabp(x,y) do { } while(0)
1953 static void* cache_alloc_refill(kmem_cache_t* cachep, int flags)
1956 struct kmem_list3 *l3;
1957 struct array_cache *ac;
1960 ac = ac_data(cachep);
1962 batchcount = ac->batchcount;
1963 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
1964 /* if there was little recent activity on this
1965 * cache, then perform only a partial refill.
1966 * Otherwise we could generate refill bouncing.
1968 batchcount = BATCHREFILL_LIMIT;
1970 l3 = list3_data(cachep);
1972 BUG_ON(ac->avail > 0);
1973 spin_lock(&cachep->spinlock);
1975 struct array_cache *shared_array = l3->shared;
1976 if (shared_array->avail) {
1977 if (batchcount > shared_array->avail)
1978 batchcount = shared_array->avail;
1979 shared_array->avail -= batchcount;
1980 ac->avail = batchcount;
1981 memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
1982 sizeof(void*)*batchcount);
1983 shared_array->touched = 1;
1987 while (batchcount > 0) {
1988 struct list_head *entry;
1990 /* Get slab alloc is to come from. */
1991 entry = l3->slabs_partial.next;
1992 if (entry == &l3->slabs_partial) {
1993 l3->free_touched = 1;
1994 entry = l3->slabs_free.next;
1995 if (entry == &l3->slabs_free)
1999 slabp = list_entry(entry, struct slab, list);
2000 check_slabp(cachep, slabp);
2001 check_spinlock_acquired(cachep);
2002 while (slabp->inuse < cachep->num && batchcount--) {
2004 STATS_INC_ALLOCED(cachep);
2005 STATS_INC_ACTIVE(cachep);
2006 STATS_SET_HIGH(cachep);
2008 /* get obj pointer */
2009 ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
2012 next = slab_bufctl(slabp)[slabp->free];
2014 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2018 check_slabp(cachep, slabp);
2020 /* move slabp to correct slabp list: */
2021 list_del(&slabp->list);
2022 if (slabp->free == BUFCTL_END)
2023 list_add(&slabp->list, &l3->slabs_full);
2025 list_add(&slabp->list, &l3->slabs_partial);
2029 l3->free_objects -= ac->avail;
2031 spin_unlock(&cachep->spinlock);
2033 if (unlikely(!ac->avail)) {
2035 x = cache_grow(cachep, flags);
2037 // cache_grow can reenable interrupts, then ac could change.
2038 ac = ac_data(cachep);
2039 if (!x && ac->avail == 0) // no objects in sight? abort
2042 if (!ac->avail) // objects refilled by interrupt?
2046 return ac_entry(ac)[--ac->avail];
2050 cache_alloc_debugcheck_before(kmem_cache_t *cachep, int flags)
2052 might_sleep_if(flags & __GFP_WAIT);
2054 kmem_flagcheck(cachep, flags);
2060 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
2061 unsigned long flags, void *objp, void *caller)
2065 if (cachep->flags & SLAB_POISON) {
2066 #ifdef CONFIG_DEBUG_PAGEALLOC
2067 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2068 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
2070 check_poison_obj(cachep, objp);
2072 check_poison_obj(cachep, objp);
2074 poison_obj(cachep, objp, POISON_INUSE);
2076 if (cachep->flags & SLAB_STORE_USER)
2077 *dbg_userword(cachep, objp) = caller;
2079 if (cachep->flags & SLAB_RED_ZONE) {
2080 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2081 slab_error(cachep, "double free, or memory outside"
2082 " object was overwritten");
2083 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
2084 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2086 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2087 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2089 objp += obj_dbghead(cachep);
2090 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2091 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2093 if (!(flags & __GFP_WAIT))
2094 ctor_flags |= SLAB_CTOR_ATOMIC;
2096 cachep->ctor(objp, cachep, ctor_flags);
2101 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2105 static inline void * __cache_alloc (kmem_cache_t *cachep, int flags)
2107 unsigned long save_flags;
2109 struct array_cache *ac;
2111 cache_alloc_debugcheck_before(cachep, flags);
2113 local_irq_save(save_flags);
2114 ac = ac_data(cachep);
2115 if (likely(ac->avail)) {
2116 STATS_INC_ALLOCHIT(cachep);
2118 objp = ac_entry(ac)[--ac->avail];
2120 STATS_INC_ALLOCMISS(cachep);
2121 objp = cache_alloc_refill(cachep, flags);
2123 local_irq_restore(save_flags);
2124 objp = cache_alloc_debugcheck_after(cachep, flags, objp, __builtin_return_address(0));
2129 * NUMA: different approach needed if the spinlock is moved into
2133 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2137 check_spinlock_acquired(cachep);
2139 /* NUMA: move add into loop */
2140 cachep->lists.free_objects += nr_objects;
2142 for (i = 0; i < nr_objects; i++) {
2143 void *objp = objpp[i];
2147 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2148 list_del(&slabp->list);
2149 objnr = (objp - slabp->s_mem) / cachep->objsize;
2150 check_slabp(cachep, slabp);
2152 if (slab_bufctl(slabp)[objnr] != BUFCTL_FREE) {
2153 printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2154 cachep->name, objp);
2158 slab_bufctl(slabp)[objnr] = slabp->free;
2159 slabp->free = objnr;
2160 STATS_DEC_ACTIVE(cachep);
2162 check_slabp(cachep, slabp);
2164 /* fixup slab chains */
2165 if (slabp->inuse == 0) {
2166 if (cachep->lists.free_objects > cachep->free_limit) {
2167 cachep->lists.free_objects -= cachep->num;
2168 slab_destroy(cachep, slabp);
2170 list_add(&slabp->list,
2171 &list3_data_ptr(cachep, objp)->slabs_free);
2174 /* Unconditionally move a slab to the end of the
2175 * partial list on free - maximum time for the
2176 * other objects to be freed, too.
2178 list_add_tail(&slabp->list,
2179 &list3_data_ptr(cachep, objp)->slabs_partial);
2184 static void cache_flusharray (kmem_cache_t* cachep, struct array_cache *ac)
2188 batchcount = ac->batchcount;
2190 BUG_ON(!batchcount || batchcount > ac->avail);
2193 spin_lock(&cachep->spinlock);
2194 if (cachep->lists.shared) {
2195 struct array_cache *shared_array = cachep->lists.shared;
2196 int max = shared_array->limit-shared_array->avail;
2198 if (batchcount > max)
2200 memcpy(&ac_entry(shared_array)[shared_array->avail],
2202 sizeof(void*)*batchcount);
2203 shared_array->avail += batchcount;
2208 free_block(cachep, &ac_entry(ac)[0], batchcount);
2213 struct list_head *p;
2215 p = list3_data(cachep)->slabs_free.next;
2216 while (p != &(list3_data(cachep)->slabs_free)) {
2219 slabp = list_entry(p, struct slab, list);
2220 BUG_ON(slabp->inuse);
2225 STATS_SET_FREEABLE(cachep, i);
2228 spin_unlock(&cachep->spinlock);
2229 ac->avail -= batchcount;
2230 memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2231 sizeof(void*)*ac->avail);
2236 * Release an obj back to its cache. If the obj has a constructed
2237 * state, it must be in this state _before_ it is released.
2239 * Called with disabled ints.
2241 static inline void __cache_free (kmem_cache_t *cachep, void* objp)
2243 struct array_cache *ac = ac_data(cachep);
2246 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2248 if (likely(ac->avail < ac->limit)) {
2249 STATS_INC_FREEHIT(cachep);
2250 ac_entry(ac)[ac->avail++] = objp;
2253 STATS_INC_FREEMISS(cachep);
2254 cache_flusharray(cachep, ac);
2255 ac_entry(ac)[ac->avail++] = objp;
2260 * kmem_cache_alloc - Allocate an object
2261 * @cachep: The cache to allocate from.
2262 * @flags: See kmalloc().
2264 * Allocate an object from this cache. The flags are only relevant
2265 * if the cache has no available objects.
2267 void * kmem_cache_alloc (kmem_cache_t *cachep, int flags)
2269 return __cache_alloc(cachep, flags);
2272 EXPORT_SYMBOL(kmem_cache_alloc);
2275 * kmem_ptr_validate - check if an untrusted pointer might
2277 * @cachep: the cache we're checking against
2278 * @ptr: pointer to validate
2280 * This verifies that the untrusted pointer looks sane:
2281 * it is _not_ a guarantee that the pointer is actually
2282 * part of the slab cache in question, but it at least
2283 * validates that the pointer can be dereferenced and
2284 * looks half-way sane.
2286 * Currently only used for dentry validation.
2288 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2290 unsigned long addr = (unsigned long) ptr;
2291 unsigned long min_addr = PAGE_OFFSET;
2292 unsigned long align_mask = BYTES_PER_WORD-1;
2293 unsigned long size = cachep->objsize;
2296 if (unlikely(addr < min_addr))
2298 if (unlikely(addr > (unsigned long)high_memory - size))
2300 if (unlikely(addr & align_mask))
2302 if (unlikely(!kern_addr_valid(addr)))
2304 if (unlikely(!kern_addr_valid(addr + size - 1)))
2306 page = virt_to_page(ptr);
2307 if (unlikely(!PageSlab(page)))
2309 if (unlikely(GET_PAGE_CACHE(page) != cachep))
2317 * kmem_cache_alloc_node - Allocate an object on the specified node
2318 * @cachep: The cache to allocate from.
2319 * @flags: See kmalloc().
2320 * @nodeid: node number of the target node.
2322 * Identical to kmem_cache_alloc, except that this function is slow
2323 * and can sleep. And it will allocate memory on the given node, which
2324 * can improve the performance for cpu bound structures.
2326 void *kmem_cache_alloc_node(kmem_cache_t *cachep, int nodeid)
2333 /* The main algorithms are not node aware, thus we have to cheat:
2334 * We bypass all caches and allocate a new slab.
2335 * The following code is a streamlined copy of cache_grow().
2338 /* Get colour for the slab, and update the next value. */
2339 spin_lock_irq(&cachep->spinlock);
2340 offset = cachep->colour_next;
2341 cachep->colour_next++;
2342 if (cachep->colour_next >= cachep->colour)
2343 cachep->colour_next = 0;
2344 offset *= cachep->colour_off;
2345 spin_unlock_irq(&cachep->spinlock);
2347 /* Get mem for the objs. */
2348 if (!(objp = kmem_getpages(cachep, GFP_KERNEL, nodeid)))
2351 /* Get slab management. */
2352 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, GFP_KERNEL)))
2355 set_slab_attr(cachep, slabp, objp);
2356 cache_init_objs(cachep, slabp, SLAB_CTOR_CONSTRUCTOR);
2358 /* The first object is ours: */
2359 objp = slabp->s_mem + slabp->free*cachep->objsize;
2361 next = slab_bufctl(slabp)[slabp->free];
2363 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2367 /* add the remaining objects into the cache */
2368 spin_lock_irq(&cachep->spinlock);
2369 check_slabp(cachep, slabp);
2370 STATS_INC_GROWN(cachep);
2371 /* Make slab active. */
2372 if (slabp->free == BUFCTL_END) {
2373 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_full));
2375 list_add_tail(&slabp->list,
2376 &(list3_data(cachep)->slabs_partial));
2377 list3_data(cachep)->free_objects += cachep->num-1;
2379 spin_unlock_irq(&cachep->spinlock);
2380 objp = cache_alloc_debugcheck_after(cachep, GFP_KERNEL, objp,
2381 __builtin_return_address(0));
2384 kmem_freepages(cachep, objp);
2389 EXPORT_SYMBOL(kmem_cache_alloc_node);
2392 * kmalloc - allocate memory
2393 * @size: how many bytes of memory are required.
2394 * @flags: the type of memory to allocate.
2396 * kmalloc is the normal method of allocating memory
2399 * The @flags argument may be one of:
2401 * %GFP_USER - Allocate memory on behalf of user. May sleep.
2403 * %GFP_KERNEL - Allocate normal kernel ram. May sleep.
2405 * %GFP_ATOMIC - Allocation will not sleep. Use inside interrupt handlers.
2407 * Additionally, the %GFP_DMA flag may be set to indicate the memory
2408 * must be suitable for DMA. This can mean different things on different
2409 * platforms. For example, on i386, it means that the memory must come
2410 * from the first 16MB.
2412 void * __kmalloc (size_t size, int flags)
2414 struct cache_sizes *csizep = malloc_sizes;
2416 for (; csizep->cs_size; csizep++) {
2417 if (size > csizep->cs_size)
2420 /* This happens if someone tries to call
2421 * kmem_cache_create(), or kmalloc(), before
2422 * the generic caches are initialized.
2424 BUG_ON(csizep->cs_cachep == NULL);
2426 return __cache_alloc(flags & GFP_DMA ?
2427 csizep->cs_dmacachep : csizep->cs_cachep, flags);
2432 EXPORT_SYMBOL(__kmalloc);
2436 * __alloc_percpu - allocate one copy of the object for every present
2437 * cpu in the system, zeroing them.
2438 * Objects should be dereferenced using the per_cpu_ptr macro only.
2440 * @size: how many bytes of memory are required.
2441 * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2443 void *__alloc_percpu(size_t size, size_t align)
2446 struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2451 for (i = 0; i < NR_CPUS; i++) {
2452 if (!cpu_possible(i))
2454 pdata->ptrs[i] = kmem_cache_alloc_node(
2455 kmem_find_general_cachep(size, GFP_KERNEL),
2458 if (!pdata->ptrs[i])
2460 memset(pdata->ptrs[i], 0, size);
2463 /* Catch derefs w/o wrappers */
2464 return (void *) (~(unsigned long) pdata);
2468 if (!cpu_possible(i))
2470 kfree(pdata->ptrs[i]);
2476 EXPORT_SYMBOL(__alloc_percpu);
2480 * kmem_cache_free - Deallocate an object
2481 * @cachep: The cache the allocation was from.
2482 * @objp: The previously allocated object.
2484 * Free an object which was previously allocated from this
2487 void kmem_cache_free (kmem_cache_t *cachep, void *objp)
2489 unsigned long flags;
2491 local_irq_save(flags);
2492 __cache_free(cachep, objp);
2493 local_irq_restore(flags);
2496 EXPORT_SYMBOL(kmem_cache_free);
2499 * kcalloc - allocate memory for an array. The memory is set to zero.
2500 * @n: number of elements.
2501 * @size: element size.
2502 * @flags: the type of memory to allocate.
2504 void *kcalloc(size_t n, size_t size, int flags)
2508 if (n != 0 && size > INT_MAX / n)
2511 ret = kmalloc(n * size, flags);
2513 memset(ret, 0, n * size);
2517 EXPORT_SYMBOL(kcalloc);
2520 * kfree - free previously allocated memory
2521 * @objp: pointer returned by kmalloc.
2523 * Don't free memory not originally allocated by kmalloc()
2524 * or you will run into trouble.
2526 void kfree (const void *objp)
2529 unsigned long flags;
2533 local_irq_save(flags);
2534 kfree_debugcheck(objp);
2535 c = GET_PAGE_CACHE(virt_to_page(objp));
2536 __cache_free(c, (void*)objp);
2537 local_irq_restore(flags);
2540 EXPORT_SYMBOL(kfree);
2544 * free_percpu - free previously allocated percpu memory
2545 * @objp: pointer returned by alloc_percpu.
2547 * Don't free memory not originally allocated by alloc_percpu()
2548 * The complemented objp is to check for that.
2551 free_percpu(const void *objp)
2554 struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2556 for (i = 0; i < NR_CPUS; i++) {
2557 if (!cpu_possible(i))
2563 EXPORT_SYMBOL(free_percpu);
2566 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2568 return obj_reallen(cachep);
2571 EXPORT_SYMBOL(kmem_cache_size);
2573 struct ccupdate_struct {
2574 kmem_cache_t *cachep;
2575 struct array_cache *new[NR_CPUS];
2578 static void do_ccupdate_local(void *info)
2580 struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2581 struct array_cache *old;
2584 old = ac_data(new->cachep);
2586 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2587 new->new[smp_processor_id()] = old;
2591 static int do_tune_cpucache (kmem_cache_t* cachep, int limit, int batchcount, int shared)
2593 struct ccupdate_struct new;
2594 struct array_cache *new_shared;
2597 memset(&new.new,0,sizeof(new.new));
2598 for (i = 0; i < NR_CPUS; i++) {
2599 if (cpu_online(i)) {
2600 new.new[i] = alloc_arraycache(i, limit, batchcount);
2602 for (i--; i >= 0; i--) kfree(new.new[i]);
2609 new.cachep = cachep;
2611 smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2614 spin_lock_irq(&cachep->spinlock);
2615 cachep->batchcount = batchcount;
2616 cachep->limit = limit;
2617 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2618 spin_unlock_irq(&cachep->spinlock);
2620 for (i = 0; i < NR_CPUS; i++) {
2621 struct array_cache *ccold = new.new[i];
2624 spin_lock_irq(&cachep->spinlock);
2625 free_block(cachep, ac_entry(ccold), ccold->avail);
2626 spin_unlock_irq(&cachep->spinlock);
2629 new_shared = alloc_arraycache(-1, batchcount*shared, 0xbaadf00d);
2631 struct array_cache *old;
2633 spin_lock_irq(&cachep->spinlock);
2634 old = cachep->lists.shared;
2635 cachep->lists.shared = new_shared;
2637 free_block(cachep, ac_entry(old), old->avail);
2638 spin_unlock_irq(&cachep->spinlock);
2646 static void enable_cpucache (kmem_cache_t *cachep)
2651 /* The head array serves three purposes:
2652 * - create a LIFO ordering, i.e. return objects that are cache-warm
2653 * - reduce the number of spinlock operations.
2654 * - reduce the number of linked list operations on the slab and
2655 * bufctl chains: array operations are cheaper.
2656 * The numbers are guessed, we should auto-tune as described by
2659 if (cachep->objsize > 131072)
2661 else if (cachep->objsize > PAGE_SIZE)
2663 else if (cachep->objsize > 1024)
2665 else if (cachep->objsize > 256)
2670 /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2671 * allocation behaviour: Most allocs on one cpu, most free operations
2672 * on another cpu. For these cases, an efficient object passing between
2673 * cpus is necessary. This is provided by a shared array. The array
2674 * replaces Bonwick's magazine layer.
2675 * On uniprocessor, it's functionally equivalent (but less efficient)
2676 * to a larger limit. Thus disabled by default.
2680 if (cachep->objsize <= PAGE_SIZE)
2685 /* With debugging enabled, large batchcount lead to excessively
2686 * long periods with disabled local interrupts. Limit the
2692 err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2694 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2695 cachep->name, -err);
2698 static void drain_array_locked(kmem_cache_t *cachep,
2699 struct array_cache *ac, int force)
2703 check_spinlock_acquired(cachep);
2704 if (ac->touched && !force) {
2706 } else if (ac->avail) {
2707 tofree = force ? ac->avail : (ac->limit+4)/5;
2708 if (tofree > ac->avail) {
2709 tofree = (ac->avail+1)/2;
2711 free_block(cachep, ac_entry(ac), tofree);
2712 ac->avail -= tofree;
2713 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2714 sizeof(void*)*ac->avail);
2719 * cache_reap - Reclaim memory from caches.
2721 * Called from workqueue/eventd every few seconds.
2723 * - clear the per-cpu caches for this CPU.
2724 * - return freeable pages to the main free memory pool.
2726 * If we cannot acquire the cache chain semaphore then just give up - we'll
2727 * try again on the next iteration.
2729 static void cache_reap(void *unused)
2731 struct list_head *walk;
2733 if (down_trylock(&cache_chain_sem)) {
2734 /* Give up. Setup the next iteration. */
2735 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2739 list_for_each(walk, &cache_chain) {
2740 kmem_cache_t *searchp;
2741 struct list_head* p;
2745 searchp = list_entry(walk, kmem_cache_t, next);
2747 if (searchp->flags & SLAB_NO_REAP)
2752 spin_lock_irq(&searchp->spinlock);
2754 drain_array_locked(searchp, ac_data(searchp), 0);
2756 if(time_after(searchp->lists.next_reap, jiffies))
2759 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2761 if (searchp->lists.shared)
2762 drain_array_locked(searchp, searchp->lists.shared, 0);
2764 if (searchp->lists.free_touched) {
2765 searchp->lists.free_touched = 0;
2769 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2771 p = list3_data(searchp)->slabs_free.next;
2772 if (p == &(list3_data(searchp)->slabs_free))
2775 slabp = list_entry(p, struct slab, list);
2776 BUG_ON(slabp->inuse);
2777 list_del(&slabp->list);
2778 STATS_INC_REAPED(searchp);
2780 /* Safe to drop the lock. The slab is no longer
2781 * linked to the cache.
2782 * searchp cannot disappear, we hold
2785 searchp->lists.free_objects -= searchp->num;
2786 spin_unlock_irq(&searchp->spinlock);
2787 slab_destroy(searchp, slabp);
2788 spin_lock_irq(&searchp->spinlock);
2789 } while(--tofree > 0);
2791 spin_unlock_irq(&searchp->spinlock);
2796 up(&cache_chain_sem);
2797 /* Setup the next iteration */
2798 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2801 #ifdef CONFIG_PROC_FS
2803 static void *s_start(struct seq_file *m, loff_t *pos)
2806 struct list_head *p;
2808 down(&cache_chain_sem);
2811 * Output format version, so at least we can change it
2812 * without _too_ many complaints.
2815 seq_puts(m, "slabinfo - version: 2.0 (statistics)\n");
2817 seq_puts(m, "slabinfo - version: 2.0\n");
2819 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2820 seq_puts(m, " : tunables <batchcount> <limit> <sharedfactor>");
2821 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
2823 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> <error> <maxfreeable> <freelimit>");
2824 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
2828 p = cache_chain.next;
2831 if (p == &cache_chain)
2834 return list_entry(p, kmem_cache_t, next);
2837 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2839 kmem_cache_t *cachep = p;
2841 return cachep->next.next == &cache_chain ? NULL
2842 : list_entry(cachep->next.next, kmem_cache_t, next);
2845 static void s_stop(struct seq_file *m, void *p)
2847 up(&cache_chain_sem);
2850 static int s_show(struct seq_file *m, void *p)
2852 kmem_cache_t *cachep = p;
2853 struct list_head *q;
2855 unsigned long active_objs;
2856 unsigned long num_objs;
2857 unsigned long active_slabs = 0;
2858 unsigned long num_slabs;
2863 spin_lock_irq(&cachep->spinlock);
2866 list_for_each(q,&cachep->lists.slabs_full) {
2867 slabp = list_entry(q, struct slab, list);
2868 if (slabp->inuse != cachep->num && !error)
2869 error = "slabs_full accounting error";
2870 active_objs += cachep->num;
2873 list_for_each(q,&cachep->lists.slabs_partial) {
2874 slabp = list_entry(q, struct slab, list);
2875 if (slabp->inuse == cachep->num && !error)
2876 error = "slabs_partial inuse accounting error";
2877 if (!slabp->inuse && !error)
2878 error = "slabs_partial/inuse accounting error";
2879 active_objs += slabp->inuse;
2882 list_for_each(q,&cachep->lists.slabs_free) {
2883 slabp = list_entry(q, struct slab, list);
2884 if (slabp->inuse && !error)
2885 error = "slabs_free/inuse accounting error";
2888 num_slabs+=active_slabs;
2889 num_objs = num_slabs*cachep->num;
2890 if (num_objs - active_objs != cachep->lists.free_objects && !error)
2891 error = "free_objects accounting error";
2893 name = cachep->name;
2895 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
2897 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
2898 name, active_objs, num_objs, cachep->objsize,
2899 cachep->num, (1<<cachep->gfporder));
2900 seq_printf(m, " : tunables %4u %4u %4u",
2901 cachep->limit, cachep->batchcount,
2902 cachep->lists.shared->limit/cachep->batchcount);
2903 seq_printf(m, " : slabdata %6lu %6lu %6u",
2904 active_slabs, num_slabs, cachep->lists.shared->avail);
2907 unsigned long high = cachep->high_mark;
2908 unsigned long allocs = cachep->num_allocations;
2909 unsigned long grown = cachep->grown;
2910 unsigned long reaped = cachep->reaped;
2911 unsigned long errors = cachep->errors;
2912 unsigned long max_freeable = cachep->max_freeable;
2913 unsigned long free_limit = cachep->free_limit;
2915 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu",
2916 allocs, high, grown, reaped, errors,
2917 max_freeable, free_limit);
2921 unsigned long allochit = atomic_read(&cachep->allochit);
2922 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
2923 unsigned long freehit = atomic_read(&cachep->freehit);
2924 unsigned long freemiss = atomic_read(&cachep->freemiss);
2926 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
2927 allochit, allocmiss, freehit, freemiss);
2931 spin_unlock_irq(&cachep->spinlock);
2936 * slabinfo_op - iterator that generates /proc/slabinfo
2945 * num-pages-per-slab
2946 * + further values on SMP and with statistics enabled
2949 struct seq_operations slabinfo_op = {
2956 #define MAX_SLABINFO_WRITE 128
2958 * slabinfo_write - Tuning for the slab allocator
2960 * @buffer: user buffer
2961 * @count: data length
2964 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
2965 size_t count, loff_t *ppos)
2967 char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
2968 int limit, batchcount, shared, res;
2969 struct list_head *p;
2971 if (count > MAX_SLABINFO_WRITE)
2973 if (copy_from_user(&kbuf, buffer, count))
2975 kbuf[MAX_SLABINFO_WRITE] = '\0';
2977 tmp = strchr(kbuf, ' ');
2982 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
2985 /* Find the cache in the chain of caches. */
2986 down(&cache_chain_sem);
2988 list_for_each(p,&cache_chain) {
2989 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
2991 if (!strcmp(cachep->name, kbuf)) {
2994 batchcount > limit ||
2998 res = do_tune_cpucache(cachep, limit, batchcount, shared);
3003 up(&cache_chain_sem);
3010 unsigned int ksize(const void *objp)
3013 unsigned long flags;
3014 unsigned int size = 0;
3016 if (likely(objp != NULL)) {
3017 local_irq_save(flags);
3018 c = GET_PAGE_CACHE(virt_to_page(objp));
3019 size = kmem_cache_size(c);
3020 local_irq_restore(flags);