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