[PATCH] orinoco: Fix memory leak on error in processing hostscan frames.
[linux/fpc-iii.git] / mm / slab.c
bloba9ff4f7f9860b2f1f37891fe4fe8c50a5caa637d
1 /*
2 * linux/mm/slab.c
3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
14 * An implementation of the Slab Allocator as described in outline in;
15 * UNIX Internals: The New Frontiers by Uresh Vahalia
16 * Pub: Prentice Hall ISBN 0-13-101908-2
17 * or with a little more detail in;
18 * The Slab Allocator: An Object-Caching Kernel Memory Allocator
19 * Jeff Bonwick (Sun Microsystems).
20 * Presented at: USENIX Summer 1994 Technical Conference
22 * The memory is organized in caches, one cache for each object type.
23 * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24 * Each cache consists out of many slabs (they are small (usually one
25 * page long) and always contiguous), and each slab contains multiple
26 * initialized objects.
28 * This means, that your constructor is used only for newly allocated
29 * slabs and you must pass objects with the same intializations to
30 * kmem_cache_free.
32 * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33 * normal). If you need a special memory type, then must create a new
34 * cache for that memory type.
36 * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37 * full slabs with 0 free objects
38 * partial slabs
39 * empty slabs with no allocated objects
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
44 * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45 * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
47 * Each cache has a short per-cpu head array, most allocs
48 * and frees go into that array, and if that array overflows, then 1/2
49 * of the entries in the array are given back into the global cache.
50 * The head array is strictly LIFO and should improve the cache hit rates.
51 * On SMP, it additionally reduces the spinlock operations.
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
56 * SMP synchronization:
57 * constructors and destructors are called without any locking.
58 * Several members in kmem_cache_t and struct slab never change, they
59 * are accessed without any locking.
60 * The per-cpu arrays are never accessed from the wrong cpu, no locking,
61 * and local interrupts are disabled so slab code is preempt-safe.
62 * The non-constant members are protected with a per-cache irq spinlock.
64 * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65 * in 2000 - many ideas in the current implementation are derived from
66 * his patch.
68 * Further notes from the original documentation:
70 * 11 April '97. Started multi-threading - markhe
71 * The global cache-chain is protected by the semaphore 'cache_chain_sem'.
72 * The sem is only needed when accessing/extending the cache-chain, which
73 * can never happen inside an interrupt (kmem_cache_create(),
74 * kmem_cache_shrink() and kmem_cache_reap()).
76 * At present, each engine can be growing a cache. This should be blocked.
80 #include <linux/config.h>
81 #include <linux/slab.h>
82 #include <linux/mm.h>
83 #include <linux/swap.h>
84 #include <linux/cache.h>
85 #include <linux/interrupt.h>
86 #include <linux/init.h>
87 #include <linux/compiler.h>
88 #include <linux/seq_file.h>
89 #include <linux/notifier.h>
90 #include <linux/kallsyms.h>
91 #include <linux/cpu.h>
92 #include <linux/sysctl.h>
93 #include <linux/module.h>
94 #include <linux/rcupdate.h>
95 #include <linux/string.h>
97 #include <asm/uaccess.h>
98 #include <asm/cacheflush.h>
99 #include <asm/tlbflush.h>
100 #include <asm/page.h>
103 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
104 * SLAB_RED_ZONE & SLAB_POISON.
105 * 0 for faster, smaller code (especially in the critical paths).
107 * STATS - 1 to collect stats for /proc/slabinfo.
108 * 0 for faster, smaller code (especially in the critical paths).
110 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
113 #ifdef CONFIG_DEBUG_SLAB
114 #define DEBUG 1
115 #define STATS 1
116 #define FORCED_DEBUG 1
117 #else
118 #define DEBUG 0
119 #define STATS 0
120 #define FORCED_DEBUG 0
121 #endif
124 /* Shouldn't this be in a header file somewhere? */
125 #define BYTES_PER_WORD sizeof(void *)
127 #ifndef cache_line_size
128 #define cache_line_size() L1_CACHE_BYTES
129 #endif
131 #ifndef ARCH_KMALLOC_MINALIGN
133 * Enforce a minimum alignment for the kmalloc caches.
134 * Usually, the kmalloc caches are cache_line_size() aligned, except when
135 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
136 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
137 * alignment larger than BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
138 * Note that this flag disables some debug features.
140 #define ARCH_KMALLOC_MINALIGN 0
141 #endif
143 #ifndef ARCH_SLAB_MINALIGN
145 * Enforce a minimum alignment for all caches.
146 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
147 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
148 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
149 * some debug features.
151 #define ARCH_SLAB_MINALIGN 0
152 #endif
154 #ifndef ARCH_KMALLOC_FLAGS
155 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
156 #endif
158 /* Legal flag mask for kmem_cache_create(). */
159 #if DEBUG
160 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
161 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
162 SLAB_NO_REAP | SLAB_CACHE_DMA | \
163 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
164 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
165 SLAB_DESTROY_BY_RCU)
166 #else
167 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
168 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
169 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
170 SLAB_DESTROY_BY_RCU)
171 #endif
174 * kmem_bufctl_t:
176 * Bufctl's are used for linking objs within a slab
177 * linked offsets.
179 * This implementation relies on "struct page" for locating the cache &
180 * slab an object belongs to.
181 * This allows the bufctl structure to be small (one int), but limits
182 * the number of objects a slab (not a cache) can contain when off-slab
183 * bufctls are used. The limit is the size of the largest general cache
184 * that does not use off-slab slabs.
185 * For 32bit archs with 4 kB pages, is this 56.
186 * This is not serious, as it is only for large objects, when it is unwise
187 * to have too many per slab.
188 * Note: This limit can be raised by introducing a general cache whose size
189 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
192 typedef unsigned int kmem_bufctl_t;
193 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
194 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
195 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-2)
197 /* Max number of objs-per-slab for caches which use off-slab slabs.
198 * Needed to avoid a possible looping condition in cache_grow().
200 static unsigned long offslab_limit;
203 * struct slab
205 * Manages the objs in a slab. Placed either at the beginning of mem allocated
206 * for a slab, or allocated from an general cache.
207 * Slabs are chained into three list: fully used, partial, fully free slabs.
209 struct slab {
210 struct list_head list;
211 unsigned long colouroff;
212 void *s_mem; /* including colour offset */
213 unsigned int inuse; /* num of objs active in slab */
214 kmem_bufctl_t free;
218 * struct slab_rcu
220 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
221 * arrange for kmem_freepages to be called via RCU. This is useful if
222 * we need to approach a kernel structure obliquely, from its address
223 * obtained without the usual locking. We can lock the structure to
224 * stabilize it and check it's still at the given address, only if we
225 * can be sure that the memory has not been meanwhile reused for some
226 * other kind of object (which our subsystem's lock might corrupt).
228 * rcu_read_lock before reading the address, then rcu_read_unlock after
229 * taking the spinlock within the structure expected at that address.
231 * We assume struct slab_rcu can overlay struct slab when destroying.
233 struct slab_rcu {
234 struct rcu_head head;
235 kmem_cache_t *cachep;
236 void *addr;
240 * struct array_cache
242 * Per cpu structures
243 * Purpose:
244 * - LIFO ordering, to hand out cache-warm objects from _alloc
245 * - reduce the number of linked list operations
246 * - reduce spinlock operations
248 * The limit is stored in the per-cpu structure to reduce the data cache
249 * footprint.
252 struct array_cache {
253 unsigned int avail;
254 unsigned int limit;
255 unsigned int batchcount;
256 unsigned int touched;
259 /* bootstrap: The caches do not work without cpuarrays anymore,
260 * but the cpuarrays are allocated from the generic caches...
262 #define BOOT_CPUCACHE_ENTRIES 1
263 struct arraycache_init {
264 struct array_cache cache;
265 void * entries[BOOT_CPUCACHE_ENTRIES];
269 * The slab lists of all objects.
270 * Hopefully reduce the internal fragmentation
271 * NUMA: The spinlock could be moved from the kmem_cache_t
272 * into this structure, too. Figure out what causes
273 * fewer cross-node spinlock operations.
275 struct kmem_list3 {
276 struct list_head slabs_partial; /* partial list first, better asm code */
277 struct list_head slabs_full;
278 struct list_head slabs_free;
279 unsigned long free_objects;
280 int free_touched;
281 unsigned long next_reap;
282 struct array_cache *shared;
285 #define LIST3_INIT(parent) \
287 .slabs_full = LIST_HEAD_INIT(parent.slabs_full), \
288 .slabs_partial = LIST_HEAD_INIT(parent.slabs_partial), \
289 .slabs_free = LIST_HEAD_INIT(parent.slabs_free) \
291 #define list3_data(cachep) \
292 (&(cachep)->lists)
294 /* NUMA: per-node */
295 #define list3_data_ptr(cachep, ptr) \
296 list3_data(cachep)
299 * kmem_cache_t
301 * manages a cache.
304 struct kmem_cache_s {
305 /* 1) per-cpu data, touched during every alloc/free */
306 struct array_cache *array[NR_CPUS];
307 unsigned int batchcount;
308 unsigned int limit;
309 /* 2) touched by every alloc & free from the backend */
310 struct kmem_list3 lists;
311 /* NUMA: kmem_3list_t *nodelists[MAX_NUMNODES] */
312 unsigned int objsize;
313 unsigned int flags; /* constant flags */
314 unsigned int num; /* # of objs per slab */
315 unsigned int free_limit; /* upper limit of objects in the lists */
316 spinlock_t spinlock;
318 /* 3) cache_grow/shrink */
319 /* order of pgs per slab (2^n) */
320 unsigned int gfporder;
322 /* force GFP flags, e.g. GFP_DMA */
323 unsigned int gfpflags;
325 size_t colour; /* cache colouring range */
326 unsigned int colour_off; /* colour offset */
327 unsigned int colour_next; /* cache colouring */
328 kmem_cache_t *slabp_cache;
329 unsigned int slab_size;
330 unsigned int dflags; /* dynamic flags */
332 /* constructor func */
333 void (*ctor)(void *, kmem_cache_t *, unsigned long);
335 /* de-constructor func */
336 void (*dtor)(void *, kmem_cache_t *, unsigned long);
338 /* 4) cache creation/removal */
339 const char *name;
340 struct list_head next;
342 /* 5) statistics */
343 #if STATS
344 unsigned long num_active;
345 unsigned long num_allocations;
346 unsigned long high_mark;
347 unsigned long grown;
348 unsigned long reaped;
349 unsigned long errors;
350 unsigned long max_freeable;
351 unsigned long node_allocs;
352 atomic_t allochit;
353 atomic_t allocmiss;
354 atomic_t freehit;
355 atomic_t freemiss;
356 #endif
357 #if DEBUG
358 int dbghead;
359 int reallen;
360 #endif
363 #define CFLGS_OFF_SLAB (0x80000000UL)
364 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
366 #define BATCHREFILL_LIMIT 16
367 /* Optimization question: fewer reaps means less
368 * probability for unnessary cpucache drain/refill cycles.
370 * OTHO the cpuarrays can contain lots of objects,
371 * which could lock up otherwise freeable slabs.
373 #define REAPTIMEOUT_CPUC (2*HZ)
374 #define REAPTIMEOUT_LIST3 (4*HZ)
376 #if STATS
377 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
378 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
379 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
380 #define STATS_INC_GROWN(x) ((x)->grown++)
381 #define STATS_INC_REAPED(x) ((x)->reaped++)
382 #define STATS_SET_HIGH(x) do { if ((x)->num_active > (x)->high_mark) \
383 (x)->high_mark = (x)->num_active; \
384 } while (0)
385 #define STATS_INC_ERR(x) ((x)->errors++)
386 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
387 #define STATS_SET_FREEABLE(x, i) \
388 do { if ((x)->max_freeable < i) \
389 (x)->max_freeable = i; \
390 } while (0)
392 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
393 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
394 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
395 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
396 #else
397 #define STATS_INC_ACTIVE(x) do { } while (0)
398 #define STATS_DEC_ACTIVE(x) do { } while (0)
399 #define STATS_INC_ALLOCED(x) do { } while (0)
400 #define STATS_INC_GROWN(x) do { } while (0)
401 #define STATS_INC_REAPED(x) do { } while (0)
402 #define STATS_SET_HIGH(x) do { } while (0)
403 #define STATS_INC_ERR(x) do { } while (0)
404 #define STATS_INC_NODEALLOCS(x) do { } while (0)
405 #define STATS_SET_FREEABLE(x, i) \
406 do { } while (0)
408 #define STATS_INC_ALLOCHIT(x) do { } while (0)
409 #define STATS_INC_ALLOCMISS(x) do { } while (0)
410 #define STATS_INC_FREEHIT(x) do { } while (0)
411 #define STATS_INC_FREEMISS(x) do { } while (0)
412 #endif
414 #if DEBUG
415 /* Magic nums for obj red zoning.
416 * Placed in the first word before and the first word after an obj.
418 #define RED_INACTIVE 0x5A2CF071UL /* when obj is inactive */
419 #define RED_ACTIVE 0x170FC2A5UL /* when obj is active */
421 /* ...and for poisoning */
422 #define POISON_INUSE 0x5a /* for use-uninitialised poisoning */
423 #define POISON_FREE 0x6b /* for use-after-free poisoning */
424 #define POISON_END 0xa5 /* end-byte of poisoning */
426 /* memory layout of objects:
427 * 0 : objp
428 * 0 .. cachep->dbghead - BYTES_PER_WORD - 1: padding. This ensures that
429 * the end of an object is aligned with the end of the real
430 * allocation. Catches writes behind the end of the allocation.
431 * cachep->dbghead - BYTES_PER_WORD .. cachep->dbghead - 1:
432 * redzone word.
433 * cachep->dbghead: The real object.
434 * cachep->objsize - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
435 * cachep->objsize - 1* BYTES_PER_WORD: last caller address [BYTES_PER_WORD long]
437 static int obj_dbghead(kmem_cache_t *cachep)
439 return cachep->dbghead;
442 static int obj_reallen(kmem_cache_t *cachep)
444 return cachep->reallen;
447 static unsigned long *dbg_redzone1(kmem_cache_t *cachep, void *objp)
449 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
450 return (unsigned long*) (objp+obj_dbghead(cachep)-BYTES_PER_WORD);
453 static unsigned long *dbg_redzone2(kmem_cache_t *cachep, void *objp)
455 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
456 if (cachep->flags & SLAB_STORE_USER)
457 return (unsigned long*) (objp+cachep->objsize-2*BYTES_PER_WORD);
458 return (unsigned long*) (objp+cachep->objsize-BYTES_PER_WORD);
461 static void **dbg_userword(kmem_cache_t *cachep, void *objp)
463 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
464 return (void**)(objp+cachep->objsize-BYTES_PER_WORD);
467 #else
469 #define obj_dbghead(x) 0
470 #define obj_reallen(cachep) (cachep->objsize)
471 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
472 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
473 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
475 #endif
478 * Maximum size of an obj (in 2^order pages)
479 * and absolute limit for the gfp order.
481 #if defined(CONFIG_LARGE_ALLOCS)
482 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
483 #define MAX_GFP_ORDER 13 /* up to 32Mb */
484 #elif defined(CONFIG_MMU)
485 #define MAX_OBJ_ORDER 5 /* 32 pages */
486 #define MAX_GFP_ORDER 5 /* 32 pages */
487 #else
488 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
489 #define MAX_GFP_ORDER 8 /* up to 1Mb */
490 #endif
493 * Do not go above this order unless 0 objects fit into the slab.
495 #define BREAK_GFP_ORDER_HI 1
496 #define BREAK_GFP_ORDER_LO 0
497 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
499 /* Macros for storing/retrieving the cachep and or slab from the
500 * global 'mem_map'. These are used to find the slab an obj belongs to.
501 * With kfree(), these are used to find the cache which an obj belongs to.
503 #define SET_PAGE_CACHE(pg,x) ((pg)->lru.next = (struct list_head *)(x))
504 #define GET_PAGE_CACHE(pg) ((kmem_cache_t *)(pg)->lru.next)
505 #define SET_PAGE_SLAB(pg,x) ((pg)->lru.prev = (struct list_head *)(x))
506 #define GET_PAGE_SLAB(pg) ((struct slab *)(pg)->lru.prev)
508 /* These are the default caches for kmalloc. Custom caches can have other sizes. */
509 struct cache_sizes malloc_sizes[] = {
510 #define CACHE(x) { .cs_size = (x) },
511 #include <linux/kmalloc_sizes.h>
512 CACHE(ULONG_MAX)
513 #undef CACHE
515 EXPORT_SYMBOL(malloc_sizes);
517 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
518 struct cache_names {
519 char *name;
520 char *name_dma;
523 static struct cache_names __initdata cache_names[] = {
524 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
525 #include <linux/kmalloc_sizes.h>
526 { NULL, }
527 #undef CACHE
530 static struct arraycache_init initarray_cache __initdata =
531 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
532 static struct arraycache_init initarray_generic =
533 { { 0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
535 /* internal cache of cache description objs */
536 static kmem_cache_t cache_cache = {
537 .lists = LIST3_INIT(cache_cache.lists),
538 .batchcount = 1,
539 .limit = BOOT_CPUCACHE_ENTRIES,
540 .objsize = sizeof(kmem_cache_t),
541 .flags = SLAB_NO_REAP,
542 .spinlock = SPIN_LOCK_UNLOCKED,
543 .name = "kmem_cache",
544 #if DEBUG
545 .reallen = sizeof(kmem_cache_t),
546 #endif
549 /* Guard access to the cache-chain. */
550 static struct semaphore cache_chain_sem;
551 static struct list_head cache_chain;
554 * vm_enough_memory() looks at this to determine how many
555 * slab-allocated pages are possibly freeable under pressure
557 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
559 atomic_t slab_reclaim_pages;
560 EXPORT_SYMBOL(slab_reclaim_pages);
563 * chicken and egg problem: delay the per-cpu array allocation
564 * until the general caches are up.
566 static enum {
567 NONE,
568 PARTIAL,
569 FULL
570 } g_cpucache_up;
572 static DEFINE_PER_CPU(struct work_struct, reap_work);
574 static void free_block(kmem_cache_t* cachep, void** objpp, int len);
575 static void enable_cpucache (kmem_cache_t *cachep);
576 static void cache_reap (void *unused);
578 static inline void **ac_entry(struct array_cache *ac)
580 return (void**)(ac+1);
583 static inline struct array_cache *ac_data(kmem_cache_t *cachep)
585 return cachep->array[smp_processor_id()];
588 static inline kmem_cache_t *__find_general_cachep(size_t size,
589 unsigned int __nocast gfpflags)
591 struct cache_sizes *csizep = malloc_sizes;
593 #if DEBUG
594 /* This happens if someone tries to call
595 * kmem_cache_create(), or __kmalloc(), before
596 * the generic caches are initialized.
598 BUG_ON(csizep->cs_cachep == NULL);
599 #endif
600 while (size > csizep->cs_size)
601 csizep++;
604 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
605 * has cs_{dma,}cachep==NULL. Thus no special case
606 * for large kmalloc calls required.
608 if (unlikely(gfpflags & GFP_DMA))
609 return csizep->cs_dmacachep;
610 return csizep->cs_cachep;
613 kmem_cache_t *kmem_find_general_cachep(size_t size,
614 unsigned int __nocast gfpflags)
616 return __find_general_cachep(size, gfpflags);
618 EXPORT_SYMBOL(kmem_find_general_cachep);
620 /* Cal the num objs, wastage, and bytes left over for a given slab size. */
621 static void cache_estimate(unsigned long gfporder, size_t size, size_t align,
622 int flags, size_t *left_over, unsigned int *num)
624 int i;
625 size_t wastage = PAGE_SIZE<<gfporder;
626 size_t extra = 0;
627 size_t base = 0;
629 if (!(flags & CFLGS_OFF_SLAB)) {
630 base = sizeof(struct slab);
631 extra = sizeof(kmem_bufctl_t);
633 i = 0;
634 while (i*size + ALIGN(base+i*extra, align) <= wastage)
635 i++;
636 if (i > 0)
637 i--;
639 if (i > SLAB_LIMIT)
640 i = SLAB_LIMIT;
642 *num = i;
643 wastage -= i*size;
644 wastage -= ALIGN(base+i*extra, align);
645 *left_over = wastage;
648 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
650 static void __slab_error(const char *function, kmem_cache_t *cachep, char *msg)
652 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
653 function, cachep->name, msg);
654 dump_stack();
658 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
659 * via the workqueue/eventd.
660 * Add the CPU number into the expiration time to minimize the possibility of
661 * the CPUs getting into lockstep and contending for the global cache chain
662 * lock.
664 static void __devinit start_cpu_timer(int cpu)
666 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
669 * When this gets called from do_initcalls via cpucache_init(),
670 * init_workqueues() has already run, so keventd will be setup
671 * at that time.
673 if (keventd_up() && reap_work->func == NULL) {
674 INIT_WORK(reap_work, cache_reap, NULL);
675 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
679 static struct array_cache *alloc_arraycache(int cpu, int entries,
680 int batchcount)
682 int memsize = sizeof(void*)*entries+sizeof(struct array_cache);
683 struct array_cache *nc = NULL;
685 if (cpu == -1)
686 nc = kmalloc(memsize, GFP_KERNEL);
687 else
688 nc = kmalloc_node(memsize, GFP_KERNEL, cpu_to_node(cpu));
690 if (nc) {
691 nc->avail = 0;
692 nc->limit = entries;
693 nc->batchcount = batchcount;
694 nc->touched = 0;
696 return nc;
699 static int __devinit cpuup_callback(struct notifier_block *nfb,
700 unsigned long action, void *hcpu)
702 long cpu = (long)hcpu;
703 kmem_cache_t* cachep;
705 switch (action) {
706 case CPU_UP_PREPARE:
707 down(&cache_chain_sem);
708 list_for_each_entry(cachep, &cache_chain, next) {
709 struct array_cache *nc;
711 nc = alloc_arraycache(cpu, cachep->limit, cachep->batchcount);
712 if (!nc)
713 goto bad;
715 spin_lock_irq(&cachep->spinlock);
716 cachep->array[cpu] = nc;
717 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
718 + cachep->num;
719 spin_unlock_irq(&cachep->spinlock);
722 up(&cache_chain_sem);
723 break;
724 case CPU_ONLINE:
725 start_cpu_timer(cpu);
726 break;
727 #ifdef CONFIG_HOTPLUG_CPU
728 case CPU_DEAD:
729 /* fall thru */
730 case CPU_UP_CANCELED:
731 down(&cache_chain_sem);
733 list_for_each_entry(cachep, &cache_chain, next) {
734 struct array_cache *nc;
736 spin_lock_irq(&cachep->spinlock);
737 /* cpu is dead; no one can alloc from it. */
738 nc = cachep->array[cpu];
739 cachep->array[cpu] = NULL;
740 cachep->free_limit -= cachep->batchcount;
741 free_block(cachep, ac_entry(nc), nc->avail);
742 spin_unlock_irq(&cachep->spinlock);
743 kfree(nc);
745 up(&cache_chain_sem);
746 break;
747 #endif
749 return NOTIFY_OK;
750 bad:
751 up(&cache_chain_sem);
752 return NOTIFY_BAD;
755 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
757 /* Initialisation.
758 * Called after the gfp() functions have been enabled, and before smp_init().
760 void __init kmem_cache_init(void)
762 size_t left_over;
763 struct cache_sizes *sizes;
764 struct cache_names *names;
767 * Fragmentation resistance on low memory - only use bigger
768 * page orders on machines with more than 32MB of memory.
770 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
771 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
774 /* Bootstrap is tricky, because several objects are allocated
775 * from caches that do not exist yet:
776 * 1) initialize the cache_cache cache: it contains the kmem_cache_t
777 * structures of all caches, except cache_cache itself: cache_cache
778 * is statically allocated.
779 * Initially an __init data area is used for the head array, it's
780 * replaced with a kmalloc allocated array at the end of the bootstrap.
781 * 2) Create the first kmalloc cache.
782 * The kmem_cache_t for the new cache is allocated normally. An __init
783 * data area is used for the head array.
784 * 3) Create the remaining kmalloc caches, with minimally sized head arrays.
785 * 4) Replace the __init data head arrays for cache_cache and the first
786 * kmalloc cache with kmalloc allocated arrays.
787 * 5) Resize the head arrays of the kmalloc caches to their final sizes.
790 /* 1) create the cache_cache */
791 init_MUTEX(&cache_chain_sem);
792 INIT_LIST_HEAD(&cache_chain);
793 list_add(&cache_cache.next, &cache_chain);
794 cache_cache.colour_off = cache_line_size();
795 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
797 cache_cache.objsize = ALIGN(cache_cache.objsize, cache_line_size());
799 cache_estimate(0, cache_cache.objsize, cache_line_size(), 0,
800 &left_over, &cache_cache.num);
801 if (!cache_cache.num)
802 BUG();
804 cache_cache.colour = left_over/cache_cache.colour_off;
805 cache_cache.colour_next = 0;
806 cache_cache.slab_size = ALIGN(cache_cache.num*sizeof(kmem_bufctl_t) +
807 sizeof(struct slab), cache_line_size());
809 /* 2+3) create the kmalloc caches */
810 sizes = malloc_sizes;
811 names = cache_names;
813 while (sizes->cs_size != ULONG_MAX) {
814 /* For performance, all the general caches are L1 aligned.
815 * This should be particularly beneficial on SMP boxes, as it
816 * eliminates "false sharing".
817 * Note for systems short on memory removing the alignment will
818 * allow tighter packing of the smaller caches. */
819 sizes->cs_cachep = kmem_cache_create(names->name,
820 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
821 (ARCH_KMALLOC_FLAGS | SLAB_PANIC), NULL, NULL);
823 /* Inc off-slab bufctl limit until the ceiling is hit. */
824 if (!(OFF_SLAB(sizes->cs_cachep))) {
825 offslab_limit = sizes->cs_size-sizeof(struct slab);
826 offslab_limit /= sizeof(kmem_bufctl_t);
829 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
830 sizes->cs_size, ARCH_KMALLOC_MINALIGN,
831 (ARCH_KMALLOC_FLAGS | SLAB_CACHE_DMA | SLAB_PANIC),
832 NULL, NULL);
834 sizes++;
835 names++;
837 /* 4) Replace the bootstrap head arrays */
839 void * ptr;
841 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
842 local_irq_disable();
843 BUG_ON(ac_data(&cache_cache) != &initarray_cache.cache);
844 memcpy(ptr, ac_data(&cache_cache), sizeof(struct arraycache_init));
845 cache_cache.array[smp_processor_id()] = ptr;
846 local_irq_enable();
848 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
849 local_irq_disable();
850 BUG_ON(ac_data(malloc_sizes[0].cs_cachep) != &initarray_generic.cache);
851 memcpy(ptr, ac_data(malloc_sizes[0].cs_cachep),
852 sizeof(struct arraycache_init));
853 malloc_sizes[0].cs_cachep->array[smp_processor_id()] = ptr;
854 local_irq_enable();
857 /* 5) resize the head arrays to their final sizes */
859 kmem_cache_t *cachep;
860 down(&cache_chain_sem);
861 list_for_each_entry(cachep, &cache_chain, next)
862 enable_cpucache(cachep);
863 up(&cache_chain_sem);
866 /* Done! */
867 g_cpucache_up = FULL;
869 /* Register a cpu startup notifier callback
870 * that initializes ac_data for all new cpus
872 register_cpu_notifier(&cpucache_notifier);
875 /* The reap timers are started later, with a module init call:
876 * That part of the kernel is not yet operational.
880 static int __init cpucache_init(void)
882 int cpu;
885 * Register the timers that return unneeded
886 * pages to gfp.
888 for (cpu = 0; cpu < NR_CPUS; cpu++) {
889 if (cpu_online(cpu))
890 start_cpu_timer(cpu);
893 return 0;
896 __initcall(cpucache_init);
899 * Interface to system's page allocator. No need to hold the cache-lock.
901 * If we requested dmaable memory, we will get it. Even if we
902 * did not request dmaable memory, we might get it, but that
903 * would be relatively rare and ignorable.
905 static void *kmem_getpages(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
907 struct page *page;
908 void *addr;
909 int i;
911 flags |= cachep->gfpflags;
912 if (likely(nodeid == -1)) {
913 page = alloc_pages(flags, cachep->gfporder);
914 } else {
915 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
917 if (!page)
918 return NULL;
919 addr = page_address(page);
921 i = (1 << cachep->gfporder);
922 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
923 atomic_add(i, &slab_reclaim_pages);
924 add_page_state(nr_slab, i);
925 while (i--) {
926 SetPageSlab(page);
927 page++;
929 return addr;
933 * Interface to system's page release.
935 static void kmem_freepages(kmem_cache_t *cachep, void *addr)
937 unsigned long i = (1<<cachep->gfporder);
938 struct page *page = virt_to_page(addr);
939 const unsigned long nr_freed = i;
941 while (i--) {
942 if (!TestClearPageSlab(page))
943 BUG();
944 page++;
946 sub_page_state(nr_slab, nr_freed);
947 if (current->reclaim_state)
948 current->reclaim_state->reclaimed_slab += nr_freed;
949 free_pages((unsigned long)addr, cachep->gfporder);
950 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
951 atomic_sub(1<<cachep->gfporder, &slab_reclaim_pages);
954 static void kmem_rcu_free(struct rcu_head *head)
956 struct slab_rcu *slab_rcu = (struct slab_rcu *) head;
957 kmem_cache_t *cachep = slab_rcu->cachep;
959 kmem_freepages(cachep, slab_rcu->addr);
960 if (OFF_SLAB(cachep))
961 kmem_cache_free(cachep->slabp_cache, slab_rcu);
964 #if DEBUG
966 #ifdef CONFIG_DEBUG_PAGEALLOC
967 static void store_stackinfo(kmem_cache_t *cachep, unsigned long *addr,
968 unsigned long caller)
970 int size = obj_reallen(cachep);
972 addr = (unsigned long *)&((char*)addr)[obj_dbghead(cachep)];
974 if (size < 5*sizeof(unsigned long))
975 return;
977 *addr++=0x12345678;
978 *addr++=caller;
979 *addr++=smp_processor_id();
980 size -= 3*sizeof(unsigned long);
982 unsigned long *sptr = &caller;
983 unsigned long svalue;
985 while (!kstack_end(sptr)) {
986 svalue = *sptr++;
987 if (kernel_text_address(svalue)) {
988 *addr++=svalue;
989 size -= sizeof(unsigned long);
990 if (size <= sizeof(unsigned long))
991 break;
996 *addr++=0x87654321;
998 #endif
1000 static void poison_obj(kmem_cache_t *cachep, void *addr, unsigned char val)
1002 int size = obj_reallen(cachep);
1003 addr = &((char*)addr)[obj_dbghead(cachep)];
1005 memset(addr, val, size);
1006 *(unsigned char *)(addr+size-1) = POISON_END;
1009 static void dump_line(char *data, int offset, int limit)
1011 int i;
1012 printk(KERN_ERR "%03x:", offset);
1013 for (i=0;i<limit;i++) {
1014 printk(" %02x", (unsigned char)data[offset+i]);
1016 printk("\n");
1018 #endif
1020 #if DEBUG
1022 static void print_objinfo(kmem_cache_t *cachep, void *objp, int lines)
1024 int i, size;
1025 char *realobj;
1027 if (cachep->flags & SLAB_RED_ZONE) {
1028 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1029 *dbg_redzone1(cachep, objp),
1030 *dbg_redzone2(cachep, objp));
1033 if (cachep->flags & SLAB_STORE_USER) {
1034 printk(KERN_ERR "Last user: [<%p>]",
1035 *dbg_userword(cachep, objp));
1036 print_symbol("(%s)",
1037 (unsigned long)*dbg_userword(cachep, objp));
1038 printk("\n");
1040 realobj = (char*)objp+obj_dbghead(cachep);
1041 size = obj_reallen(cachep);
1042 for (i=0; i<size && lines;i+=16, lines--) {
1043 int limit;
1044 limit = 16;
1045 if (i+limit > size)
1046 limit = size-i;
1047 dump_line(realobj, i, limit);
1051 static void check_poison_obj(kmem_cache_t *cachep, void *objp)
1053 char *realobj;
1054 int size, i;
1055 int lines = 0;
1057 realobj = (char*)objp+obj_dbghead(cachep);
1058 size = obj_reallen(cachep);
1060 for (i=0;i<size;i++) {
1061 char exp = POISON_FREE;
1062 if (i == size-1)
1063 exp = POISON_END;
1064 if (realobj[i] != exp) {
1065 int limit;
1066 /* Mismatch ! */
1067 /* Print header */
1068 if (lines == 0) {
1069 printk(KERN_ERR "Slab corruption: start=%p, len=%d\n",
1070 realobj, size);
1071 print_objinfo(cachep, objp, 0);
1073 /* Hexdump the affected line */
1074 i = (i/16)*16;
1075 limit = 16;
1076 if (i+limit > size)
1077 limit = size-i;
1078 dump_line(realobj, i, limit);
1079 i += 16;
1080 lines++;
1081 /* Limit to 5 lines */
1082 if (lines > 5)
1083 break;
1086 if (lines != 0) {
1087 /* Print some data about the neighboring objects, if they
1088 * exist:
1090 struct slab *slabp = GET_PAGE_SLAB(virt_to_page(objp));
1091 int objnr;
1093 objnr = (objp-slabp->s_mem)/cachep->objsize;
1094 if (objnr) {
1095 objp = slabp->s_mem+(objnr-1)*cachep->objsize;
1096 realobj = (char*)objp+obj_dbghead(cachep);
1097 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1098 realobj, size);
1099 print_objinfo(cachep, objp, 2);
1101 if (objnr+1 < cachep->num) {
1102 objp = slabp->s_mem+(objnr+1)*cachep->objsize;
1103 realobj = (char*)objp+obj_dbghead(cachep);
1104 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1105 realobj, size);
1106 print_objinfo(cachep, objp, 2);
1110 #endif
1112 /* Destroy all the objs in a slab, and release the mem back to the system.
1113 * Before calling the slab must have been unlinked from the cache.
1114 * The cache-lock is not held/needed.
1116 static void slab_destroy (kmem_cache_t *cachep, struct slab *slabp)
1118 void *addr = slabp->s_mem - slabp->colouroff;
1120 #if DEBUG
1121 int i;
1122 for (i = 0; i < cachep->num; i++) {
1123 void *objp = slabp->s_mem + cachep->objsize * i;
1125 if (cachep->flags & SLAB_POISON) {
1126 #ifdef CONFIG_DEBUG_PAGEALLOC
1127 if ((cachep->objsize%PAGE_SIZE)==0 && OFF_SLAB(cachep))
1128 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE,1);
1129 else
1130 check_poison_obj(cachep, objp);
1131 #else
1132 check_poison_obj(cachep, objp);
1133 #endif
1135 if (cachep->flags & SLAB_RED_ZONE) {
1136 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1137 slab_error(cachep, "start of a freed object "
1138 "was overwritten");
1139 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1140 slab_error(cachep, "end of a freed object "
1141 "was overwritten");
1143 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1144 (cachep->dtor)(objp+obj_dbghead(cachep), cachep, 0);
1146 #else
1147 if (cachep->dtor) {
1148 int i;
1149 for (i = 0; i < cachep->num; i++) {
1150 void* objp = slabp->s_mem+cachep->objsize*i;
1151 (cachep->dtor)(objp, cachep, 0);
1154 #endif
1156 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1157 struct slab_rcu *slab_rcu;
1159 slab_rcu = (struct slab_rcu *) slabp;
1160 slab_rcu->cachep = cachep;
1161 slab_rcu->addr = addr;
1162 call_rcu(&slab_rcu->head, kmem_rcu_free);
1163 } else {
1164 kmem_freepages(cachep, addr);
1165 if (OFF_SLAB(cachep))
1166 kmem_cache_free(cachep->slabp_cache, slabp);
1171 * kmem_cache_create - Create a cache.
1172 * @name: A string which is used in /proc/slabinfo to identify this cache.
1173 * @size: The size of objects to be created in this cache.
1174 * @align: The required alignment for the objects.
1175 * @flags: SLAB flags
1176 * @ctor: A constructor for the objects.
1177 * @dtor: A destructor for the objects.
1179 * Returns a ptr to the cache on success, NULL on failure.
1180 * Cannot be called within a int, but can be interrupted.
1181 * The @ctor is run when new pages are allocated by the cache
1182 * and the @dtor is run before the pages are handed back.
1184 * @name must be valid until the cache is destroyed. This implies that
1185 * the module calling this has to destroy the cache before getting
1186 * unloaded.
1188 * The flags are
1190 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1191 * to catch references to uninitialised memory.
1193 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1194 * for buffer overruns.
1196 * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1197 * memory pressure.
1199 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1200 * cacheline. This can be beneficial if you're counting cycles as closely
1201 * as davem.
1203 kmem_cache_t *
1204 kmem_cache_create (const char *name, size_t size, size_t align,
1205 unsigned long flags, void (*ctor)(void*, kmem_cache_t *, unsigned long),
1206 void (*dtor)(void*, kmem_cache_t *, unsigned long))
1208 size_t left_over, slab_size, ralign;
1209 kmem_cache_t *cachep = NULL;
1212 * Sanity checks... these are all serious usage bugs.
1214 if ((!name) ||
1215 in_interrupt() ||
1216 (size < BYTES_PER_WORD) ||
1217 (size > (1<<MAX_OBJ_ORDER)*PAGE_SIZE) ||
1218 (dtor && !ctor)) {
1219 printk(KERN_ERR "%s: Early error in slab %s\n",
1220 __FUNCTION__, name);
1221 BUG();
1224 #if DEBUG
1225 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
1226 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1227 /* No constructor, but inital state check requested */
1228 printk(KERN_ERR "%s: No con, but init state check "
1229 "requested - %s\n", __FUNCTION__, name);
1230 flags &= ~SLAB_DEBUG_INITIAL;
1233 #if FORCED_DEBUG
1235 * Enable redzoning and last user accounting, except for caches with
1236 * large objects, if the increased size would increase the object size
1237 * above the next power of two: caches with object sizes just above a
1238 * power of two have a significant amount of internal fragmentation.
1240 if ((size < 4096 || fls(size-1) == fls(size-1+3*BYTES_PER_WORD)))
1241 flags |= SLAB_RED_ZONE|SLAB_STORE_USER;
1242 if (!(flags & SLAB_DESTROY_BY_RCU))
1243 flags |= SLAB_POISON;
1244 #endif
1245 if (flags & SLAB_DESTROY_BY_RCU)
1246 BUG_ON(flags & SLAB_POISON);
1247 #endif
1248 if (flags & SLAB_DESTROY_BY_RCU)
1249 BUG_ON(dtor);
1252 * Always checks flags, a caller might be expecting debug
1253 * support which isn't available.
1255 if (flags & ~CREATE_MASK)
1256 BUG();
1258 /* Check that size is in terms of words. This is needed to avoid
1259 * unaligned accesses for some archs when redzoning is used, and makes
1260 * sure any on-slab bufctl's are also correctly aligned.
1262 if (size & (BYTES_PER_WORD-1)) {
1263 size += (BYTES_PER_WORD-1);
1264 size &= ~(BYTES_PER_WORD-1);
1267 /* calculate out the final buffer alignment: */
1268 /* 1) arch recommendation: can be overridden for debug */
1269 if (flags & SLAB_HWCACHE_ALIGN) {
1270 /* Default alignment: as specified by the arch code.
1271 * Except if an object is really small, then squeeze multiple
1272 * objects into one cacheline.
1274 ralign = cache_line_size();
1275 while (size <= ralign/2)
1276 ralign /= 2;
1277 } else {
1278 ralign = BYTES_PER_WORD;
1280 /* 2) arch mandated alignment: disables debug if necessary */
1281 if (ralign < ARCH_SLAB_MINALIGN) {
1282 ralign = ARCH_SLAB_MINALIGN;
1283 if (ralign > BYTES_PER_WORD)
1284 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1286 /* 3) caller mandated alignment: disables debug if necessary */
1287 if (ralign < align) {
1288 ralign = align;
1289 if (ralign > BYTES_PER_WORD)
1290 flags &= ~(SLAB_RED_ZONE|SLAB_STORE_USER);
1292 /* 4) Store it. Note that the debug code below can reduce
1293 * the alignment to BYTES_PER_WORD.
1295 align = ralign;
1297 /* Get cache's description obj. */
1298 cachep = (kmem_cache_t *) kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1299 if (!cachep)
1300 goto opps;
1301 memset(cachep, 0, sizeof(kmem_cache_t));
1303 #if DEBUG
1304 cachep->reallen = size;
1306 if (flags & SLAB_RED_ZONE) {
1307 /* redzoning only works with word aligned caches */
1308 align = BYTES_PER_WORD;
1310 /* add space for red zone words */
1311 cachep->dbghead += BYTES_PER_WORD;
1312 size += 2*BYTES_PER_WORD;
1314 if (flags & SLAB_STORE_USER) {
1315 /* user store requires word alignment and
1316 * one word storage behind the end of the real
1317 * object.
1319 align = BYTES_PER_WORD;
1320 size += BYTES_PER_WORD;
1322 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
1323 if (size > 128 && cachep->reallen > cache_line_size() && size < PAGE_SIZE) {
1324 cachep->dbghead += PAGE_SIZE - size;
1325 size = PAGE_SIZE;
1327 #endif
1328 #endif
1330 /* Determine if the slab management is 'on' or 'off' slab. */
1331 if (size >= (PAGE_SIZE>>3))
1333 * Size is large, assume best to place the slab management obj
1334 * off-slab (should allow better packing of objs).
1336 flags |= CFLGS_OFF_SLAB;
1338 size = ALIGN(size, align);
1340 if ((flags & SLAB_RECLAIM_ACCOUNT) && size <= PAGE_SIZE) {
1342 * A VFS-reclaimable slab tends to have most allocations
1343 * as GFP_NOFS and we really don't want to have to be allocating
1344 * higher-order pages when we are unable to shrink dcache.
1346 cachep->gfporder = 0;
1347 cache_estimate(cachep->gfporder, size, align, flags,
1348 &left_over, &cachep->num);
1349 } else {
1351 * Calculate size (in pages) of slabs, and the num of objs per
1352 * slab. This could be made much more intelligent. For now,
1353 * try to avoid using high page-orders for slabs. When the
1354 * gfp() funcs are more friendly towards high-order requests,
1355 * this should be changed.
1357 do {
1358 unsigned int break_flag = 0;
1359 cal_wastage:
1360 cache_estimate(cachep->gfporder, size, align, flags,
1361 &left_over, &cachep->num);
1362 if (break_flag)
1363 break;
1364 if (cachep->gfporder >= MAX_GFP_ORDER)
1365 break;
1366 if (!cachep->num)
1367 goto next;
1368 if (flags & CFLGS_OFF_SLAB &&
1369 cachep->num > offslab_limit) {
1370 /* This num of objs will cause problems. */
1371 cachep->gfporder--;
1372 break_flag++;
1373 goto cal_wastage;
1377 * Large num of objs is good, but v. large slabs are
1378 * currently bad for the gfp()s.
1380 if (cachep->gfporder >= slab_break_gfp_order)
1381 break;
1383 if ((left_over*8) <= (PAGE_SIZE<<cachep->gfporder))
1384 break; /* Acceptable internal fragmentation. */
1385 next:
1386 cachep->gfporder++;
1387 } while (1);
1390 if (!cachep->num) {
1391 printk("kmem_cache_create: couldn't create cache %s.\n", name);
1392 kmem_cache_free(&cache_cache, cachep);
1393 cachep = NULL;
1394 goto opps;
1396 slab_size = ALIGN(cachep->num*sizeof(kmem_bufctl_t)
1397 + sizeof(struct slab), align);
1400 * If the slab has been placed off-slab, and we have enough space then
1401 * move it on-slab. This is at the expense of any extra colouring.
1403 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
1404 flags &= ~CFLGS_OFF_SLAB;
1405 left_over -= slab_size;
1408 if (flags & CFLGS_OFF_SLAB) {
1409 /* really off slab. No need for manual alignment */
1410 slab_size = cachep->num*sizeof(kmem_bufctl_t)+sizeof(struct slab);
1413 cachep->colour_off = cache_line_size();
1414 /* Offset must be a multiple of the alignment. */
1415 if (cachep->colour_off < align)
1416 cachep->colour_off = align;
1417 cachep->colour = left_over/cachep->colour_off;
1418 cachep->slab_size = slab_size;
1419 cachep->flags = flags;
1420 cachep->gfpflags = 0;
1421 if (flags & SLAB_CACHE_DMA)
1422 cachep->gfpflags |= GFP_DMA;
1423 spin_lock_init(&cachep->spinlock);
1424 cachep->objsize = size;
1425 /* NUMA */
1426 INIT_LIST_HEAD(&cachep->lists.slabs_full);
1427 INIT_LIST_HEAD(&cachep->lists.slabs_partial);
1428 INIT_LIST_HEAD(&cachep->lists.slabs_free);
1430 if (flags & CFLGS_OFF_SLAB)
1431 cachep->slabp_cache = kmem_find_general_cachep(slab_size,0);
1432 cachep->ctor = ctor;
1433 cachep->dtor = dtor;
1434 cachep->name = name;
1436 /* Don't let CPUs to come and go */
1437 lock_cpu_hotplug();
1439 if (g_cpucache_up == FULL) {
1440 enable_cpucache(cachep);
1441 } else {
1442 if (g_cpucache_up == NONE) {
1443 /* Note: the first kmem_cache_create must create
1444 * the cache that's used by kmalloc(24), otherwise
1445 * the creation of further caches will BUG().
1447 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1448 g_cpucache_up = PARTIAL;
1449 } else {
1450 cachep->array[smp_processor_id()] = kmalloc(sizeof(struct arraycache_init),GFP_KERNEL);
1452 BUG_ON(!ac_data(cachep));
1453 ac_data(cachep)->avail = 0;
1454 ac_data(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1455 ac_data(cachep)->batchcount = 1;
1456 ac_data(cachep)->touched = 0;
1457 cachep->batchcount = 1;
1458 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1459 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount
1460 + cachep->num;
1463 cachep->lists.next_reap = jiffies + REAPTIMEOUT_LIST3 +
1464 ((unsigned long)cachep)%REAPTIMEOUT_LIST3;
1466 /* Need the semaphore to access the chain. */
1467 down(&cache_chain_sem);
1469 struct list_head *p;
1470 mm_segment_t old_fs;
1472 old_fs = get_fs();
1473 set_fs(KERNEL_DS);
1474 list_for_each(p, &cache_chain) {
1475 kmem_cache_t *pc = list_entry(p, kmem_cache_t, next);
1476 char tmp;
1477 /* This happens when the module gets unloaded and doesn't
1478 destroy its slab cache and noone else reuses the vmalloc
1479 area of the module. Print a warning. */
1480 if (__get_user(tmp,pc->name)) {
1481 printk("SLAB: cache with size %d has lost its name\n",
1482 pc->objsize);
1483 continue;
1485 if (!strcmp(pc->name,name)) {
1486 printk("kmem_cache_create: duplicate cache %s\n",name);
1487 up(&cache_chain_sem);
1488 unlock_cpu_hotplug();
1489 BUG();
1492 set_fs(old_fs);
1495 /* cache setup completed, link it into the list */
1496 list_add(&cachep->next, &cache_chain);
1497 up(&cache_chain_sem);
1498 unlock_cpu_hotplug();
1499 opps:
1500 if (!cachep && (flags & SLAB_PANIC))
1501 panic("kmem_cache_create(): failed to create slab `%s'\n",
1502 name);
1503 return cachep;
1505 EXPORT_SYMBOL(kmem_cache_create);
1507 #if DEBUG
1508 static void check_irq_off(void)
1510 BUG_ON(!irqs_disabled());
1513 static void check_irq_on(void)
1515 BUG_ON(irqs_disabled());
1518 static void check_spinlock_acquired(kmem_cache_t *cachep)
1520 #ifdef CONFIG_SMP
1521 check_irq_off();
1522 BUG_ON(spin_trylock(&cachep->spinlock));
1523 #endif
1525 #else
1526 #define check_irq_off() do { } while(0)
1527 #define check_irq_on() do { } while(0)
1528 #define check_spinlock_acquired(x) do { } while(0)
1529 #endif
1532 * Waits for all CPUs to execute func().
1534 static void smp_call_function_all_cpus(void (*func) (void *arg), void *arg)
1536 check_irq_on();
1537 preempt_disable();
1539 local_irq_disable();
1540 func(arg);
1541 local_irq_enable();
1543 if (smp_call_function(func, arg, 1, 1))
1544 BUG();
1546 preempt_enable();
1549 static void drain_array_locked(kmem_cache_t* cachep,
1550 struct array_cache *ac, int force);
1552 static void do_drain(void *arg)
1554 kmem_cache_t *cachep = (kmem_cache_t*)arg;
1555 struct array_cache *ac;
1557 check_irq_off();
1558 ac = ac_data(cachep);
1559 spin_lock(&cachep->spinlock);
1560 free_block(cachep, &ac_entry(ac)[0], ac->avail);
1561 spin_unlock(&cachep->spinlock);
1562 ac->avail = 0;
1565 static void drain_cpu_caches(kmem_cache_t *cachep)
1567 smp_call_function_all_cpus(do_drain, cachep);
1568 check_irq_on();
1569 spin_lock_irq(&cachep->spinlock);
1570 if (cachep->lists.shared)
1571 drain_array_locked(cachep, cachep->lists.shared, 1);
1572 spin_unlock_irq(&cachep->spinlock);
1576 /* NUMA shrink all list3s */
1577 static int __cache_shrink(kmem_cache_t *cachep)
1579 struct slab *slabp;
1580 int ret;
1582 drain_cpu_caches(cachep);
1584 check_irq_on();
1585 spin_lock_irq(&cachep->spinlock);
1587 for(;;) {
1588 struct list_head *p;
1590 p = cachep->lists.slabs_free.prev;
1591 if (p == &cachep->lists.slabs_free)
1592 break;
1594 slabp = list_entry(cachep->lists.slabs_free.prev, struct slab, list);
1595 #if DEBUG
1596 if (slabp->inuse)
1597 BUG();
1598 #endif
1599 list_del(&slabp->list);
1601 cachep->lists.free_objects -= cachep->num;
1602 spin_unlock_irq(&cachep->spinlock);
1603 slab_destroy(cachep, slabp);
1604 spin_lock_irq(&cachep->spinlock);
1606 ret = !list_empty(&cachep->lists.slabs_full) ||
1607 !list_empty(&cachep->lists.slabs_partial);
1608 spin_unlock_irq(&cachep->spinlock);
1609 return ret;
1613 * kmem_cache_shrink - Shrink a cache.
1614 * @cachep: The cache to shrink.
1616 * Releases as many slabs as possible for a cache.
1617 * To help debugging, a zero exit status indicates all slabs were released.
1619 int kmem_cache_shrink(kmem_cache_t *cachep)
1621 if (!cachep || in_interrupt())
1622 BUG();
1624 return __cache_shrink(cachep);
1626 EXPORT_SYMBOL(kmem_cache_shrink);
1629 * kmem_cache_destroy - delete a cache
1630 * @cachep: the cache to destroy
1632 * Remove a kmem_cache_t object from the slab cache.
1633 * Returns 0 on success.
1635 * It is expected this function will be called by a module when it is
1636 * unloaded. This will remove the cache completely, and avoid a duplicate
1637 * cache being allocated each time a module is loaded and unloaded, if the
1638 * module doesn't have persistent in-kernel storage across loads and unloads.
1640 * The cache must be empty before calling this function.
1642 * The caller must guarantee that noone will allocate memory from the cache
1643 * during the kmem_cache_destroy().
1645 int kmem_cache_destroy(kmem_cache_t * cachep)
1647 int i;
1649 if (!cachep || in_interrupt())
1650 BUG();
1652 /* Don't let CPUs to come and go */
1653 lock_cpu_hotplug();
1655 /* Find the cache in the chain of caches. */
1656 down(&cache_chain_sem);
1658 * the chain is never empty, cache_cache is never destroyed
1660 list_del(&cachep->next);
1661 up(&cache_chain_sem);
1663 if (__cache_shrink(cachep)) {
1664 slab_error(cachep, "Can't free all objects");
1665 down(&cache_chain_sem);
1666 list_add(&cachep->next,&cache_chain);
1667 up(&cache_chain_sem);
1668 unlock_cpu_hotplug();
1669 return 1;
1672 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1673 synchronize_rcu();
1675 /* no cpu_online check required here since we clear the percpu
1676 * array on cpu offline and set this to NULL.
1678 for (i = 0; i < NR_CPUS; i++)
1679 kfree(cachep->array[i]);
1681 /* NUMA: free the list3 structures */
1682 kfree(cachep->lists.shared);
1683 cachep->lists.shared = NULL;
1684 kmem_cache_free(&cache_cache, cachep);
1686 unlock_cpu_hotplug();
1688 return 0;
1690 EXPORT_SYMBOL(kmem_cache_destroy);
1692 /* Get the memory for a slab management obj. */
1693 static struct slab* alloc_slabmgmt(kmem_cache_t *cachep,
1694 void *objp, int colour_off, unsigned int __nocast local_flags)
1696 struct slab *slabp;
1698 if (OFF_SLAB(cachep)) {
1699 /* Slab management obj is off-slab. */
1700 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
1701 if (!slabp)
1702 return NULL;
1703 } else {
1704 slabp = objp+colour_off;
1705 colour_off += cachep->slab_size;
1707 slabp->inuse = 0;
1708 slabp->colouroff = colour_off;
1709 slabp->s_mem = objp+colour_off;
1711 return slabp;
1714 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
1716 return (kmem_bufctl_t *)(slabp+1);
1719 static void cache_init_objs(kmem_cache_t *cachep,
1720 struct slab *slabp, unsigned long ctor_flags)
1722 int i;
1724 for (i = 0; i < cachep->num; i++) {
1725 void* objp = slabp->s_mem+cachep->objsize*i;
1726 #if DEBUG
1727 /* need to poison the objs? */
1728 if (cachep->flags & SLAB_POISON)
1729 poison_obj(cachep, objp, POISON_FREE);
1730 if (cachep->flags & SLAB_STORE_USER)
1731 *dbg_userword(cachep, objp) = NULL;
1733 if (cachep->flags & SLAB_RED_ZONE) {
1734 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1735 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1738 * Constructors are not allowed to allocate memory from
1739 * the same cache which they are a constructor for.
1740 * Otherwise, deadlock. They must also be threaded.
1742 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
1743 cachep->ctor(objp+obj_dbghead(cachep), cachep, ctor_flags);
1745 if (cachep->flags & SLAB_RED_ZONE) {
1746 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1747 slab_error(cachep, "constructor overwrote the"
1748 " end of an object");
1749 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1750 slab_error(cachep, "constructor overwrote the"
1751 " start of an object");
1753 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
1754 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1755 #else
1756 if (cachep->ctor)
1757 cachep->ctor(objp, cachep, ctor_flags);
1758 #endif
1759 slab_bufctl(slabp)[i] = i+1;
1761 slab_bufctl(slabp)[i-1] = BUFCTL_END;
1762 slabp->free = 0;
1765 static void kmem_flagcheck(kmem_cache_t *cachep, unsigned int flags)
1767 if (flags & SLAB_DMA) {
1768 if (!(cachep->gfpflags & GFP_DMA))
1769 BUG();
1770 } else {
1771 if (cachep->gfpflags & GFP_DMA)
1772 BUG();
1776 static void set_slab_attr(kmem_cache_t *cachep, struct slab *slabp, void *objp)
1778 int i;
1779 struct page *page;
1781 /* Nasty!!!!!! I hope this is OK. */
1782 i = 1 << cachep->gfporder;
1783 page = virt_to_page(objp);
1784 do {
1785 SET_PAGE_CACHE(page, cachep);
1786 SET_PAGE_SLAB(page, slabp);
1787 page++;
1788 } while (--i);
1792 * Grow (by 1) the number of slabs within a cache. This is called by
1793 * kmem_cache_alloc() when there are no active objs left in a cache.
1795 static int cache_grow(kmem_cache_t *cachep, unsigned int __nocast flags, int nodeid)
1797 struct slab *slabp;
1798 void *objp;
1799 size_t offset;
1800 unsigned int local_flags;
1801 unsigned long ctor_flags;
1803 /* Be lazy and only check for valid flags here,
1804 * keeping it out of the critical path in kmem_cache_alloc().
1806 if (flags & ~(SLAB_DMA|SLAB_LEVEL_MASK|SLAB_NO_GROW))
1807 BUG();
1808 if (flags & SLAB_NO_GROW)
1809 return 0;
1811 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
1812 local_flags = (flags & SLAB_LEVEL_MASK);
1813 if (!(local_flags & __GFP_WAIT))
1815 * Not allowed to sleep. Need to tell a constructor about
1816 * this - it might need to know...
1818 ctor_flags |= SLAB_CTOR_ATOMIC;
1820 /* About to mess with non-constant members - lock. */
1821 check_irq_off();
1822 spin_lock(&cachep->spinlock);
1824 /* Get colour for the slab, and cal the next value. */
1825 offset = cachep->colour_next;
1826 cachep->colour_next++;
1827 if (cachep->colour_next >= cachep->colour)
1828 cachep->colour_next = 0;
1829 offset *= cachep->colour_off;
1831 spin_unlock(&cachep->spinlock);
1833 if (local_flags & __GFP_WAIT)
1834 local_irq_enable();
1837 * The test for missing atomic flag is performed here, rather than
1838 * the more obvious place, simply to reduce the critical path length
1839 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
1840 * will eventually be caught here (where it matters).
1842 kmem_flagcheck(cachep, flags);
1845 /* Get mem for the objs. */
1846 if (!(objp = kmem_getpages(cachep, flags, nodeid)))
1847 goto failed;
1849 /* Get slab management. */
1850 if (!(slabp = alloc_slabmgmt(cachep, objp, offset, local_flags)))
1851 goto opps1;
1853 set_slab_attr(cachep, slabp, objp);
1855 cache_init_objs(cachep, slabp, ctor_flags);
1857 if (local_flags & __GFP_WAIT)
1858 local_irq_disable();
1859 check_irq_off();
1860 spin_lock(&cachep->spinlock);
1862 /* Make slab active. */
1863 list_add_tail(&slabp->list, &(list3_data(cachep)->slabs_free));
1864 STATS_INC_GROWN(cachep);
1865 list3_data(cachep)->free_objects += cachep->num;
1866 spin_unlock(&cachep->spinlock);
1867 return 1;
1868 opps1:
1869 kmem_freepages(cachep, objp);
1870 failed:
1871 if (local_flags & __GFP_WAIT)
1872 local_irq_disable();
1873 return 0;
1876 #if DEBUG
1879 * Perform extra freeing checks:
1880 * - detect bad pointers.
1881 * - POISON/RED_ZONE checking
1882 * - destructor calls, for caches with POISON+dtor
1884 static void kfree_debugcheck(const void *objp)
1886 struct page *page;
1888 if (!virt_addr_valid(objp)) {
1889 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
1890 (unsigned long)objp);
1891 BUG();
1893 page = virt_to_page(objp);
1894 if (!PageSlab(page)) {
1895 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n", (unsigned long)objp);
1896 BUG();
1900 static void *cache_free_debugcheck(kmem_cache_t *cachep, void *objp,
1901 void *caller)
1903 struct page *page;
1904 unsigned int objnr;
1905 struct slab *slabp;
1907 objp -= obj_dbghead(cachep);
1908 kfree_debugcheck(objp);
1909 page = virt_to_page(objp);
1911 if (GET_PAGE_CACHE(page) != cachep) {
1912 printk(KERN_ERR "mismatch in kmem_cache_free: expected cache %p, got %p\n",
1913 GET_PAGE_CACHE(page),cachep);
1914 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
1915 printk(KERN_ERR "%p is %s.\n", GET_PAGE_CACHE(page), GET_PAGE_CACHE(page)->name);
1916 WARN_ON(1);
1918 slabp = GET_PAGE_SLAB(page);
1920 if (cachep->flags & SLAB_RED_ZONE) {
1921 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE || *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
1922 slab_error(cachep, "double free, or memory outside"
1923 " object was overwritten");
1924 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
1925 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
1927 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
1928 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
1930 if (cachep->flags & SLAB_STORE_USER)
1931 *dbg_userword(cachep, objp) = caller;
1933 objnr = (objp-slabp->s_mem)/cachep->objsize;
1935 BUG_ON(objnr >= cachep->num);
1936 BUG_ON(objp != slabp->s_mem + objnr*cachep->objsize);
1938 if (cachep->flags & SLAB_DEBUG_INITIAL) {
1939 /* Need to call the slab's constructor so the
1940 * caller can perform a verify of its state (debugging).
1941 * Called without the cache-lock held.
1943 cachep->ctor(objp+obj_dbghead(cachep),
1944 cachep, SLAB_CTOR_CONSTRUCTOR|SLAB_CTOR_VERIFY);
1946 if (cachep->flags & SLAB_POISON && cachep->dtor) {
1947 /* we want to cache poison the object,
1948 * call the destruction callback
1950 cachep->dtor(objp+obj_dbghead(cachep), cachep, 0);
1952 if (cachep->flags & SLAB_POISON) {
1953 #ifdef CONFIG_DEBUG_PAGEALLOC
1954 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep)) {
1955 store_stackinfo(cachep, objp, (unsigned long)caller);
1956 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 0);
1957 } else {
1958 poison_obj(cachep, objp, POISON_FREE);
1960 #else
1961 poison_obj(cachep, objp, POISON_FREE);
1962 #endif
1964 return objp;
1967 static void check_slabp(kmem_cache_t *cachep, struct slab *slabp)
1969 kmem_bufctl_t i;
1970 int entries = 0;
1972 check_spinlock_acquired(cachep);
1973 /* Check slab's freelist to see if this obj is there. */
1974 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
1975 entries++;
1976 if (entries > cachep->num || i >= cachep->num)
1977 goto bad;
1979 if (entries != cachep->num - slabp->inuse) {
1980 bad:
1981 printk(KERN_ERR "slab: Internal list corruption detected in cache '%s'(%d), slabp %p(%d). Hexdump:\n",
1982 cachep->name, cachep->num, slabp, slabp->inuse);
1983 for (i=0;i<sizeof(slabp)+cachep->num*sizeof(kmem_bufctl_t);i++) {
1984 if ((i%16)==0)
1985 printk("\n%03x:", i);
1986 printk(" %02x", ((unsigned char*)slabp)[i]);
1988 printk("\n");
1989 BUG();
1992 #else
1993 #define kfree_debugcheck(x) do { } while(0)
1994 #define cache_free_debugcheck(x,objp,z) (objp)
1995 #define check_slabp(x,y) do { } while(0)
1996 #endif
1998 static void *cache_alloc_refill(kmem_cache_t *cachep, unsigned int __nocast flags)
2000 int batchcount;
2001 struct kmem_list3 *l3;
2002 struct array_cache *ac;
2004 check_irq_off();
2005 ac = ac_data(cachep);
2006 retry:
2007 batchcount = ac->batchcount;
2008 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2009 /* if there was little recent activity on this
2010 * cache, then perform only a partial refill.
2011 * Otherwise we could generate refill bouncing.
2013 batchcount = BATCHREFILL_LIMIT;
2015 l3 = list3_data(cachep);
2017 BUG_ON(ac->avail > 0);
2018 spin_lock(&cachep->spinlock);
2019 if (l3->shared) {
2020 struct array_cache *shared_array = l3->shared;
2021 if (shared_array->avail) {
2022 if (batchcount > shared_array->avail)
2023 batchcount = shared_array->avail;
2024 shared_array->avail -= batchcount;
2025 ac->avail = batchcount;
2026 memcpy(ac_entry(ac), &ac_entry(shared_array)[shared_array->avail],
2027 sizeof(void*)*batchcount);
2028 shared_array->touched = 1;
2029 goto alloc_done;
2032 while (batchcount > 0) {
2033 struct list_head *entry;
2034 struct slab *slabp;
2035 /* Get slab alloc is to come from. */
2036 entry = l3->slabs_partial.next;
2037 if (entry == &l3->slabs_partial) {
2038 l3->free_touched = 1;
2039 entry = l3->slabs_free.next;
2040 if (entry == &l3->slabs_free)
2041 goto must_grow;
2044 slabp = list_entry(entry, struct slab, list);
2045 check_slabp(cachep, slabp);
2046 check_spinlock_acquired(cachep);
2047 while (slabp->inuse < cachep->num && batchcount--) {
2048 kmem_bufctl_t next;
2049 STATS_INC_ALLOCED(cachep);
2050 STATS_INC_ACTIVE(cachep);
2051 STATS_SET_HIGH(cachep);
2053 /* get obj pointer */
2054 ac_entry(ac)[ac->avail++] = slabp->s_mem + slabp->free*cachep->objsize;
2056 slabp->inuse++;
2057 next = slab_bufctl(slabp)[slabp->free];
2058 #if DEBUG
2059 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2060 #endif
2061 slabp->free = next;
2063 check_slabp(cachep, slabp);
2065 /* move slabp to correct slabp list: */
2066 list_del(&slabp->list);
2067 if (slabp->free == BUFCTL_END)
2068 list_add(&slabp->list, &l3->slabs_full);
2069 else
2070 list_add(&slabp->list, &l3->slabs_partial);
2073 must_grow:
2074 l3->free_objects -= ac->avail;
2075 alloc_done:
2076 spin_unlock(&cachep->spinlock);
2078 if (unlikely(!ac->avail)) {
2079 int x;
2080 x = cache_grow(cachep, flags, -1);
2082 // cache_grow can reenable interrupts, then ac could change.
2083 ac = ac_data(cachep);
2084 if (!x && ac->avail == 0) // no objects in sight? abort
2085 return NULL;
2087 if (!ac->avail) // objects refilled by interrupt?
2088 goto retry;
2090 ac->touched = 1;
2091 return ac_entry(ac)[--ac->avail];
2094 static inline void
2095 cache_alloc_debugcheck_before(kmem_cache_t *cachep, unsigned int __nocast flags)
2097 might_sleep_if(flags & __GFP_WAIT);
2098 #if DEBUG
2099 kmem_flagcheck(cachep, flags);
2100 #endif
2103 #if DEBUG
2104 static void *
2105 cache_alloc_debugcheck_after(kmem_cache_t *cachep,
2106 unsigned int __nocast flags, void *objp, void *caller)
2108 if (!objp)
2109 return objp;
2110 if (cachep->flags & SLAB_POISON) {
2111 #ifdef CONFIG_DEBUG_PAGEALLOC
2112 if ((cachep->objsize % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2113 kernel_map_pages(virt_to_page(objp), cachep->objsize/PAGE_SIZE, 1);
2114 else
2115 check_poison_obj(cachep, objp);
2116 #else
2117 check_poison_obj(cachep, objp);
2118 #endif
2119 poison_obj(cachep, objp, POISON_INUSE);
2121 if (cachep->flags & SLAB_STORE_USER)
2122 *dbg_userword(cachep, objp) = caller;
2124 if (cachep->flags & SLAB_RED_ZONE) {
2125 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE || *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2126 slab_error(cachep, "double free, or memory outside"
2127 " object was overwritten");
2128 printk(KERN_ERR "%p: redzone 1: 0x%lx, redzone 2: 0x%lx.\n",
2129 objp, *dbg_redzone1(cachep, objp), *dbg_redzone2(cachep, objp));
2131 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2132 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2134 objp += obj_dbghead(cachep);
2135 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2136 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2138 if (!(flags & __GFP_WAIT))
2139 ctor_flags |= SLAB_CTOR_ATOMIC;
2141 cachep->ctor(objp, cachep, ctor_flags);
2143 return objp;
2145 #else
2146 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2147 #endif
2150 static inline void *__cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2152 unsigned long save_flags;
2153 void* objp;
2154 struct array_cache *ac;
2156 cache_alloc_debugcheck_before(cachep, flags);
2158 local_irq_save(save_flags);
2159 ac = ac_data(cachep);
2160 if (likely(ac->avail)) {
2161 STATS_INC_ALLOCHIT(cachep);
2162 ac->touched = 1;
2163 objp = ac_entry(ac)[--ac->avail];
2164 } else {
2165 STATS_INC_ALLOCMISS(cachep);
2166 objp = cache_alloc_refill(cachep, flags);
2168 local_irq_restore(save_flags);
2169 objp = cache_alloc_debugcheck_after(cachep, flags, objp,
2170 __builtin_return_address(0));
2171 prefetchw(objp);
2172 return objp;
2176 * NUMA: different approach needed if the spinlock is moved into
2177 * the l3 structure
2180 static void free_block(kmem_cache_t *cachep, void **objpp, int nr_objects)
2182 int i;
2184 check_spinlock_acquired(cachep);
2186 /* NUMA: move add into loop */
2187 cachep->lists.free_objects += nr_objects;
2189 for (i = 0; i < nr_objects; i++) {
2190 void *objp = objpp[i];
2191 struct slab *slabp;
2192 unsigned int objnr;
2194 slabp = GET_PAGE_SLAB(virt_to_page(objp));
2195 list_del(&slabp->list);
2196 objnr = (objp - slabp->s_mem) / cachep->objsize;
2197 check_slabp(cachep, slabp);
2198 #if DEBUG
2199 if (slab_bufctl(slabp)[objnr] != BUFCTL_FREE) {
2200 printk(KERN_ERR "slab: double free detected in cache '%s', objp %p.\n",
2201 cachep->name, objp);
2202 BUG();
2204 #endif
2205 slab_bufctl(slabp)[objnr] = slabp->free;
2206 slabp->free = objnr;
2207 STATS_DEC_ACTIVE(cachep);
2208 slabp->inuse--;
2209 check_slabp(cachep, slabp);
2211 /* fixup slab chains */
2212 if (slabp->inuse == 0) {
2213 if (cachep->lists.free_objects > cachep->free_limit) {
2214 cachep->lists.free_objects -= cachep->num;
2215 slab_destroy(cachep, slabp);
2216 } else {
2217 list_add(&slabp->list,
2218 &list3_data_ptr(cachep, objp)->slabs_free);
2220 } else {
2221 /* Unconditionally move a slab to the end of the
2222 * partial list on free - maximum time for the
2223 * other objects to be freed, too.
2225 list_add_tail(&slabp->list,
2226 &list3_data_ptr(cachep, objp)->slabs_partial);
2231 static void cache_flusharray(kmem_cache_t *cachep, struct array_cache *ac)
2233 int batchcount;
2235 batchcount = ac->batchcount;
2236 #if DEBUG
2237 BUG_ON(!batchcount || batchcount > ac->avail);
2238 #endif
2239 check_irq_off();
2240 spin_lock(&cachep->spinlock);
2241 if (cachep->lists.shared) {
2242 struct array_cache *shared_array = cachep->lists.shared;
2243 int max = shared_array->limit-shared_array->avail;
2244 if (max) {
2245 if (batchcount > max)
2246 batchcount = max;
2247 memcpy(&ac_entry(shared_array)[shared_array->avail],
2248 &ac_entry(ac)[0],
2249 sizeof(void*)*batchcount);
2250 shared_array->avail += batchcount;
2251 goto free_done;
2255 free_block(cachep, &ac_entry(ac)[0], batchcount);
2256 free_done:
2257 #if STATS
2259 int i = 0;
2260 struct list_head *p;
2262 p = list3_data(cachep)->slabs_free.next;
2263 while (p != &(list3_data(cachep)->slabs_free)) {
2264 struct slab *slabp;
2266 slabp = list_entry(p, struct slab, list);
2267 BUG_ON(slabp->inuse);
2269 i++;
2270 p = p->next;
2272 STATS_SET_FREEABLE(cachep, i);
2274 #endif
2275 spin_unlock(&cachep->spinlock);
2276 ac->avail -= batchcount;
2277 memmove(&ac_entry(ac)[0], &ac_entry(ac)[batchcount],
2278 sizeof(void*)*ac->avail);
2282 * __cache_free
2283 * Release an obj back to its cache. If the obj has a constructed
2284 * state, it must be in this state _before_ it is released.
2286 * Called with disabled ints.
2288 static inline void __cache_free(kmem_cache_t *cachep, void *objp)
2290 struct array_cache *ac = ac_data(cachep);
2292 check_irq_off();
2293 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
2295 if (likely(ac->avail < ac->limit)) {
2296 STATS_INC_FREEHIT(cachep);
2297 ac_entry(ac)[ac->avail++] = objp;
2298 return;
2299 } else {
2300 STATS_INC_FREEMISS(cachep);
2301 cache_flusharray(cachep, ac);
2302 ac_entry(ac)[ac->avail++] = objp;
2307 * kmem_cache_alloc - Allocate an object
2308 * @cachep: The cache to allocate from.
2309 * @flags: See kmalloc().
2311 * Allocate an object from this cache. The flags are only relevant
2312 * if the cache has no available objects.
2314 void *kmem_cache_alloc(kmem_cache_t *cachep, unsigned int __nocast flags)
2316 return __cache_alloc(cachep, flags);
2318 EXPORT_SYMBOL(kmem_cache_alloc);
2321 * kmem_ptr_validate - check if an untrusted pointer might
2322 * be a slab entry.
2323 * @cachep: the cache we're checking against
2324 * @ptr: pointer to validate
2326 * This verifies that the untrusted pointer looks sane:
2327 * it is _not_ a guarantee that the pointer is actually
2328 * part of the slab cache in question, but it at least
2329 * validates that the pointer can be dereferenced and
2330 * looks half-way sane.
2332 * Currently only used for dentry validation.
2334 int fastcall kmem_ptr_validate(kmem_cache_t *cachep, void *ptr)
2336 unsigned long addr = (unsigned long) ptr;
2337 unsigned long min_addr = PAGE_OFFSET;
2338 unsigned long align_mask = BYTES_PER_WORD-1;
2339 unsigned long size = cachep->objsize;
2340 struct page *page;
2342 if (unlikely(addr < min_addr))
2343 goto out;
2344 if (unlikely(addr > (unsigned long)high_memory - size))
2345 goto out;
2346 if (unlikely(addr & align_mask))
2347 goto out;
2348 if (unlikely(!kern_addr_valid(addr)))
2349 goto out;
2350 if (unlikely(!kern_addr_valid(addr + size - 1)))
2351 goto out;
2352 page = virt_to_page(ptr);
2353 if (unlikely(!PageSlab(page)))
2354 goto out;
2355 if (unlikely(GET_PAGE_CACHE(page) != cachep))
2356 goto out;
2357 return 1;
2358 out:
2359 return 0;
2362 #ifdef CONFIG_NUMA
2364 * kmem_cache_alloc_node - Allocate an object on the specified node
2365 * @cachep: The cache to allocate from.
2366 * @flags: See kmalloc().
2367 * @nodeid: node number of the target node.
2369 * Identical to kmem_cache_alloc, except that this function is slow
2370 * and can sleep. And it will allocate memory on the given node, which
2371 * can improve the performance for cpu bound structures.
2373 void *kmem_cache_alloc_node(kmem_cache_t *cachep, int flags, int nodeid)
2375 int loop;
2376 void *objp;
2377 struct slab *slabp;
2378 kmem_bufctl_t next;
2380 if (nodeid == -1)
2381 return kmem_cache_alloc(cachep, flags);
2383 for (loop = 0;;loop++) {
2384 struct list_head *q;
2386 objp = NULL;
2387 check_irq_on();
2388 spin_lock_irq(&cachep->spinlock);
2389 /* walk through all partial and empty slab and find one
2390 * from the right node */
2391 list_for_each(q,&cachep->lists.slabs_partial) {
2392 slabp = list_entry(q, struct slab, list);
2394 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2395 loop > 2)
2396 goto got_slabp;
2398 list_for_each(q, &cachep->lists.slabs_free) {
2399 slabp = list_entry(q, struct slab, list);
2401 if (page_to_nid(virt_to_page(slabp->s_mem)) == nodeid ||
2402 loop > 2)
2403 goto got_slabp;
2405 spin_unlock_irq(&cachep->spinlock);
2407 local_irq_disable();
2408 if (!cache_grow(cachep, flags, nodeid)) {
2409 local_irq_enable();
2410 return NULL;
2412 local_irq_enable();
2414 got_slabp:
2415 /* found one: allocate object */
2416 check_slabp(cachep, slabp);
2417 check_spinlock_acquired(cachep);
2419 STATS_INC_ALLOCED(cachep);
2420 STATS_INC_ACTIVE(cachep);
2421 STATS_SET_HIGH(cachep);
2422 STATS_INC_NODEALLOCS(cachep);
2424 objp = slabp->s_mem + slabp->free*cachep->objsize;
2426 slabp->inuse++;
2427 next = slab_bufctl(slabp)[slabp->free];
2428 #if DEBUG
2429 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2430 #endif
2431 slabp->free = next;
2432 check_slabp(cachep, slabp);
2434 /* move slabp to correct slabp list: */
2435 list_del(&slabp->list);
2436 if (slabp->free == BUFCTL_END)
2437 list_add(&slabp->list, &cachep->lists.slabs_full);
2438 else
2439 list_add(&slabp->list, &cachep->lists.slabs_partial);
2441 list3_data(cachep)->free_objects--;
2442 spin_unlock_irq(&cachep->spinlock);
2444 objp = cache_alloc_debugcheck_after(cachep, GFP_KERNEL, objp,
2445 __builtin_return_address(0));
2446 return objp;
2448 EXPORT_SYMBOL(kmem_cache_alloc_node);
2450 void *kmalloc_node(size_t size, unsigned int __nocast flags, int node)
2452 kmem_cache_t *cachep;
2454 cachep = kmem_find_general_cachep(size, flags);
2455 if (unlikely(cachep == NULL))
2456 return NULL;
2457 return kmem_cache_alloc_node(cachep, flags, node);
2459 EXPORT_SYMBOL(kmalloc_node);
2460 #endif
2463 * kmalloc - allocate memory
2464 * @size: how many bytes of memory are required.
2465 * @flags: the type of memory to allocate.
2467 * kmalloc is the normal method of allocating memory
2468 * in the kernel.
2470 * The @flags argument may be one of:
2472 * %GFP_USER - Allocate memory on behalf of user. May sleep.
2474 * %GFP_KERNEL - Allocate normal kernel ram. May sleep.
2476 * %GFP_ATOMIC - Allocation will not sleep. Use inside interrupt handlers.
2478 * Additionally, the %GFP_DMA flag may be set to indicate the memory
2479 * must be suitable for DMA. This can mean different things on different
2480 * platforms. For example, on i386, it means that the memory must come
2481 * from the first 16MB.
2483 void *__kmalloc(size_t size, unsigned int __nocast flags)
2485 kmem_cache_t *cachep;
2487 /* If you want to save a few bytes .text space: replace
2488 * __ with kmem_.
2489 * Then kmalloc uses the uninlined functions instead of the inline
2490 * functions.
2492 cachep = __find_general_cachep(size, flags);
2493 if (unlikely(cachep == NULL))
2494 return NULL;
2495 return __cache_alloc(cachep, flags);
2497 EXPORT_SYMBOL(__kmalloc);
2499 #ifdef CONFIG_SMP
2501 * __alloc_percpu - allocate one copy of the object for every present
2502 * cpu in the system, zeroing them.
2503 * Objects should be dereferenced using the per_cpu_ptr macro only.
2505 * @size: how many bytes of memory are required.
2506 * @align: the alignment, which can't be greater than SMP_CACHE_BYTES.
2508 void *__alloc_percpu(size_t size, size_t align)
2510 int i;
2511 struct percpu_data *pdata = kmalloc(sizeof (*pdata), GFP_KERNEL);
2513 if (!pdata)
2514 return NULL;
2516 for (i = 0; i < NR_CPUS; i++) {
2517 if (!cpu_possible(i))
2518 continue;
2519 pdata->ptrs[i] = kmalloc_node(size, GFP_KERNEL,
2520 cpu_to_node(i));
2522 if (!pdata->ptrs[i])
2523 goto unwind_oom;
2524 memset(pdata->ptrs[i], 0, size);
2527 /* Catch derefs w/o wrappers */
2528 return (void *) (~(unsigned long) pdata);
2530 unwind_oom:
2531 while (--i >= 0) {
2532 if (!cpu_possible(i))
2533 continue;
2534 kfree(pdata->ptrs[i]);
2536 kfree(pdata);
2537 return NULL;
2539 EXPORT_SYMBOL(__alloc_percpu);
2540 #endif
2543 * kmem_cache_free - Deallocate an object
2544 * @cachep: The cache the allocation was from.
2545 * @objp: The previously allocated object.
2547 * Free an object which was previously allocated from this
2548 * cache.
2550 void kmem_cache_free(kmem_cache_t *cachep, void *objp)
2552 unsigned long flags;
2554 local_irq_save(flags);
2555 __cache_free(cachep, objp);
2556 local_irq_restore(flags);
2558 EXPORT_SYMBOL(kmem_cache_free);
2561 * kcalloc - allocate memory for an array. The memory is set to zero.
2562 * @n: number of elements.
2563 * @size: element size.
2564 * @flags: the type of memory to allocate.
2566 void *kcalloc(size_t n, size_t size, unsigned int __nocast flags)
2568 void *ret = NULL;
2570 if (n != 0 && size > INT_MAX / n)
2571 return ret;
2573 ret = kmalloc(n * size, flags);
2574 if (ret)
2575 memset(ret, 0, n * size);
2576 return ret;
2578 EXPORT_SYMBOL(kcalloc);
2581 * kfree - free previously allocated memory
2582 * @objp: pointer returned by kmalloc.
2584 * Don't free memory not originally allocated by kmalloc()
2585 * or you will run into trouble.
2587 void kfree(const void *objp)
2589 kmem_cache_t *c;
2590 unsigned long flags;
2592 if (unlikely(!objp))
2593 return;
2594 local_irq_save(flags);
2595 kfree_debugcheck(objp);
2596 c = GET_PAGE_CACHE(virt_to_page(objp));
2597 __cache_free(c, (void*)objp);
2598 local_irq_restore(flags);
2600 EXPORT_SYMBOL(kfree);
2602 #ifdef CONFIG_SMP
2604 * free_percpu - free previously allocated percpu memory
2605 * @objp: pointer returned by alloc_percpu.
2607 * Don't free memory not originally allocated by alloc_percpu()
2608 * The complemented objp is to check for that.
2610 void
2611 free_percpu(const void *objp)
2613 int i;
2614 struct percpu_data *p = (struct percpu_data *) (~(unsigned long) objp);
2616 for (i = 0; i < NR_CPUS; i++) {
2617 if (!cpu_possible(i))
2618 continue;
2619 kfree(p->ptrs[i]);
2621 kfree(p);
2623 EXPORT_SYMBOL(free_percpu);
2624 #endif
2626 unsigned int kmem_cache_size(kmem_cache_t *cachep)
2628 return obj_reallen(cachep);
2630 EXPORT_SYMBOL(kmem_cache_size);
2632 const char *kmem_cache_name(kmem_cache_t *cachep)
2634 return cachep->name;
2636 EXPORT_SYMBOL_GPL(kmem_cache_name);
2638 struct ccupdate_struct {
2639 kmem_cache_t *cachep;
2640 struct array_cache *new[NR_CPUS];
2643 static void do_ccupdate_local(void *info)
2645 struct ccupdate_struct *new = (struct ccupdate_struct *)info;
2646 struct array_cache *old;
2648 check_irq_off();
2649 old = ac_data(new->cachep);
2651 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
2652 new->new[smp_processor_id()] = old;
2656 static int do_tune_cpucache(kmem_cache_t *cachep, int limit, int batchcount,
2657 int shared)
2659 struct ccupdate_struct new;
2660 struct array_cache *new_shared;
2661 int i;
2663 memset(&new.new,0,sizeof(new.new));
2664 for (i = 0; i < NR_CPUS; i++) {
2665 if (cpu_online(i)) {
2666 new.new[i] = alloc_arraycache(i, limit, batchcount);
2667 if (!new.new[i]) {
2668 for (i--; i >= 0; i--) kfree(new.new[i]);
2669 return -ENOMEM;
2671 } else {
2672 new.new[i] = NULL;
2675 new.cachep = cachep;
2677 smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
2679 check_irq_on();
2680 spin_lock_irq(&cachep->spinlock);
2681 cachep->batchcount = batchcount;
2682 cachep->limit = limit;
2683 cachep->free_limit = (1+num_online_cpus())*cachep->batchcount + cachep->num;
2684 spin_unlock_irq(&cachep->spinlock);
2686 for (i = 0; i < NR_CPUS; i++) {
2687 struct array_cache *ccold = new.new[i];
2688 if (!ccold)
2689 continue;
2690 spin_lock_irq(&cachep->spinlock);
2691 free_block(cachep, ac_entry(ccold), ccold->avail);
2692 spin_unlock_irq(&cachep->spinlock);
2693 kfree(ccold);
2695 new_shared = alloc_arraycache(-1, batchcount*shared, 0xbaadf00d);
2696 if (new_shared) {
2697 struct array_cache *old;
2699 spin_lock_irq(&cachep->spinlock);
2700 old = cachep->lists.shared;
2701 cachep->lists.shared = new_shared;
2702 if (old)
2703 free_block(cachep, ac_entry(old), old->avail);
2704 spin_unlock_irq(&cachep->spinlock);
2705 kfree(old);
2708 return 0;
2712 static void enable_cpucache(kmem_cache_t *cachep)
2714 int err;
2715 int limit, shared;
2717 /* The head array serves three purposes:
2718 * - create a LIFO ordering, i.e. return objects that are cache-warm
2719 * - reduce the number of spinlock operations.
2720 * - reduce the number of linked list operations on the slab and
2721 * bufctl chains: array operations are cheaper.
2722 * The numbers are guessed, we should auto-tune as described by
2723 * Bonwick.
2725 if (cachep->objsize > 131072)
2726 limit = 1;
2727 else if (cachep->objsize > PAGE_SIZE)
2728 limit = 8;
2729 else if (cachep->objsize > 1024)
2730 limit = 24;
2731 else if (cachep->objsize > 256)
2732 limit = 54;
2733 else
2734 limit = 120;
2736 /* Cpu bound tasks (e.g. network routing) can exhibit cpu bound
2737 * allocation behaviour: Most allocs on one cpu, most free operations
2738 * on another cpu. For these cases, an efficient object passing between
2739 * cpus is necessary. This is provided by a shared array. The array
2740 * replaces Bonwick's magazine layer.
2741 * On uniprocessor, it's functionally equivalent (but less efficient)
2742 * to a larger limit. Thus disabled by default.
2744 shared = 0;
2745 #ifdef CONFIG_SMP
2746 if (cachep->objsize <= PAGE_SIZE)
2747 shared = 8;
2748 #endif
2750 #if DEBUG
2751 /* With debugging enabled, large batchcount lead to excessively
2752 * long periods with disabled local interrupts. Limit the
2753 * batchcount
2755 if (limit > 32)
2756 limit = 32;
2757 #endif
2758 err = do_tune_cpucache(cachep, limit, (limit+1)/2, shared);
2759 if (err)
2760 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
2761 cachep->name, -err);
2764 static void drain_array_locked(kmem_cache_t *cachep,
2765 struct array_cache *ac, int force)
2767 int tofree;
2769 check_spinlock_acquired(cachep);
2770 if (ac->touched && !force) {
2771 ac->touched = 0;
2772 } else if (ac->avail) {
2773 tofree = force ? ac->avail : (ac->limit+4)/5;
2774 if (tofree > ac->avail) {
2775 tofree = (ac->avail+1)/2;
2777 free_block(cachep, ac_entry(ac), tofree);
2778 ac->avail -= tofree;
2779 memmove(&ac_entry(ac)[0], &ac_entry(ac)[tofree],
2780 sizeof(void*)*ac->avail);
2785 * cache_reap - Reclaim memory from caches.
2787 * Called from workqueue/eventd every few seconds.
2788 * Purpose:
2789 * - clear the per-cpu caches for this CPU.
2790 * - return freeable pages to the main free memory pool.
2792 * If we cannot acquire the cache chain semaphore then just give up - we'll
2793 * try again on the next iteration.
2795 static void cache_reap(void *unused)
2797 struct list_head *walk;
2799 if (down_trylock(&cache_chain_sem)) {
2800 /* Give up. Setup the next iteration. */
2801 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2802 return;
2805 list_for_each(walk, &cache_chain) {
2806 kmem_cache_t *searchp;
2807 struct list_head* p;
2808 int tofree;
2809 struct slab *slabp;
2811 searchp = list_entry(walk, kmem_cache_t, next);
2813 if (searchp->flags & SLAB_NO_REAP)
2814 goto next;
2816 check_irq_on();
2818 spin_lock_irq(&searchp->spinlock);
2820 drain_array_locked(searchp, ac_data(searchp), 0);
2822 if(time_after(searchp->lists.next_reap, jiffies))
2823 goto next_unlock;
2825 searchp->lists.next_reap = jiffies + REAPTIMEOUT_LIST3;
2827 if (searchp->lists.shared)
2828 drain_array_locked(searchp, searchp->lists.shared, 0);
2830 if (searchp->lists.free_touched) {
2831 searchp->lists.free_touched = 0;
2832 goto next_unlock;
2835 tofree = (searchp->free_limit+5*searchp->num-1)/(5*searchp->num);
2836 do {
2837 p = list3_data(searchp)->slabs_free.next;
2838 if (p == &(list3_data(searchp)->slabs_free))
2839 break;
2841 slabp = list_entry(p, struct slab, list);
2842 BUG_ON(slabp->inuse);
2843 list_del(&slabp->list);
2844 STATS_INC_REAPED(searchp);
2846 /* Safe to drop the lock. The slab is no longer
2847 * linked to the cache.
2848 * searchp cannot disappear, we hold
2849 * cache_chain_lock
2851 searchp->lists.free_objects -= searchp->num;
2852 spin_unlock_irq(&searchp->spinlock);
2853 slab_destroy(searchp, slabp);
2854 spin_lock_irq(&searchp->spinlock);
2855 } while(--tofree > 0);
2856 next_unlock:
2857 spin_unlock_irq(&searchp->spinlock);
2858 next:
2859 cond_resched();
2861 check_irq_on();
2862 up(&cache_chain_sem);
2863 drain_remote_pages();
2864 /* Setup the next iteration */
2865 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC + smp_processor_id());
2868 #ifdef CONFIG_PROC_FS
2870 static void *s_start(struct seq_file *m, loff_t *pos)
2872 loff_t n = *pos;
2873 struct list_head *p;
2875 down(&cache_chain_sem);
2876 if (!n) {
2878 * Output format version, so at least we can change it
2879 * without _too_ many complaints.
2881 #if STATS
2882 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
2883 #else
2884 seq_puts(m, "slabinfo - version: 2.1\n");
2885 #endif
2886 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>");
2887 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
2888 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
2889 #if STATS
2890 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped>"
2891 " <error> <maxfreeable> <freelimit> <nodeallocs>");
2892 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
2893 #endif
2894 seq_putc(m, '\n');
2896 p = cache_chain.next;
2897 while (n--) {
2898 p = p->next;
2899 if (p == &cache_chain)
2900 return NULL;
2902 return list_entry(p, kmem_cache_t, next);
2905 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
2907 kmem_cache_t *cachep = p;
2908 ++*pos;
2909 return cachep->next.next == &cache_chain ? NULL
2910 : list_entry(cachep->next.next, kmem_cache_t, next);
2913 static void s_stop(struct seq_file *m, void *p)
2915 up(&cache_chain_sem);
2918 static int s_show(struct seq_file *m, void *p)
2920 kmem_cache_t *cachep = p;
2921 struct list_head *q;
2922 struct slab *slabp;
2923 unsigned long active_objs;
2924 unsigned long num_objs;
2925 unsigned long active_slabs = 0;
2926 unsigned long num_slabs;
2927 const char *name;
2928 char *error = NULL;
2930 check_irq_on();
2931 spin_lock_irq(&cachep->spinlock);
2932 active_objs = 0;
2933 num_slabs = 0;
2934 list_for_each(q,&cachep->lists.slabs_full) {
2935 slabp = list_entry(q, struct slab, list);
2936 if (slabp->inuse != cachep->num && !error)
2937 error = "slabs_full accounting error";
2938 active_objs += cachep->num;
2939 active_slabs++;
2941 list_for_each(q,&cachep->lists.slabs_partial) {
2942 slabp = list_entry(q, struct slab, list);
2943 if (slabp->inuse == cachep->num && !error)
2944 error = "slabs_partial inuse accounting error";
2945 if (!slabp->inuse && !error)
2946 error = "slabs_partial/inuse accounting error";
2947 active_objs += slabp->inuse;
2948 active_slabs++;
2950 list_for_each(q,&cachep->lists.slabs_free) {
2951 slabp = list_entry(q, struct slab, list);
2952 if (slabp->inuse && !error)
2953 error = "slabs_free/inuse accounting error";
2954 num_slabs++;
2956 num_slabs+=active_slabs;
2957 num_objs = num_slabs*cachep->num;
2958 if (num_objs - active_objs != cachep->lists.free_objects && !error)
2959 error = "free_objects accounting error";
2961 name = cachep->name;
2962 if (error)
2963 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
2965 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
2966 name, active_objs, num_objs, cachep->objsize,
2967 cachep->num, (1<<cachep->gfporder));
2968 seq_printf(m, " : tunables %4u %4u %4u",
2969 cachep->limit, cachep->batchcount,
2970 cachep->lists.shared->limit/cachep->batchcount);
2971 seq_printf(m, " : slabdata %6lu %6lu %6u",
2972 active_slabs, num_slabs, cachep->lists.shared->avail);
2973 #if STATS
2974 { /* list3 stats */
2975 unsigned long high = cachep->high_mark;
2976 unsigned long allocs = cachep->num_allocations;
2977 unsigned long grown = cachep->grown;
2978 unsigned long reaped = cachep->reaped;
2979 unsigned long errors = cachep->errors;
2980 unsigned long max_freeable = cachep->max_freeable;
2981 unsigned long free_limit = cachep->free_limit;
2982 unsigned long node_allocs = cachep->node_allocs;
2984 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu %4lu %4lu %4lu %4lu",
2985 allocs, high, grown, reaped, errors,
2986 max_freeable, free_limit, node_allocs);
2988 /* cpu stats */
2990 unsigned long allochit = atomic_read(&cachep->allochit);
2991 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
2992 unsigned long freehit = atomic_read(&cachep->freehit);
2993 unsigned long freemiss = atomic_read(&cachep->freemiss);
2995 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
2996 allochit, allocmiss, freehit, freemiss);
2998 #endif
2999 seq_putc(m, '\n');
3000 spin_unlock_irq(&cachep->spinlock);
3001 return 0;
3005 * slabinfo_op - iterator that generates /proc/slabinfo
3007 * Output layout:
3008 * cache-name
3009 * num-active-objs
3010 * total-objs
3011 * object size
3012 * num-active-slabs
3013 * total-slabs
3014 * num-pages-per-slab
3015 * + further values on SMP and with statistics enabled
3018 struct seq_operations slabinfo_op = {
3019 .start = s_start,
3020 .next = s_next,
3021 .stop = s_stop,
3022 .show = s_show,
3025 #define MAX_SLABINFO_WRITE 128
3027 * slabinfo_write - Tuning for the slab allocator
3028 * @file: unused
3029 * @buffer: user buffer
3030 * @count: data length
3031 * @ppos: unused
3033 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
3034 size_t count, loff_t *ppos)
3036 char kbuf[MAX_SLABINFO_WRITE+1], *tmp;
3037 int limit, batchcount, shared, res;
3038 struct list_head *p;
3040 if (count > MAX_SLABINFO_WRITE)
3041 return -EINVAL;
3042 if (copy_from_user(&kbuf, buffer, count))
3043 return -EFAULT;
3044 kbuf[MAX_SLABINFO_WRITE] = '\0';
3046 tmp = strchr(kbuf, ' ');
3047 if (!tmp)
3048 return -EINVAL;
3049 *tmp = '\0';
3050 tmp++;
3051 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3052 return -EINVAL;
3054 /* Find the cache in the chain of caches. */
3055 down(&cache_chain_sem);
3056 res = -EINVAL;
3057 list_for_each(p,&cache_chain) {
3058 kmem_cache_t *cachep = list_entry(p, kmem_cache_t, next);
3060 if (!strcmp(cachep->name, kbuf)) {
3061 if (limit < 1 ||
3062 batchcount < 1 ||
3063 batchcount > limit ||
3064 shared < 0) {
3065 res = -EINVAL;
3066 } else {
3067 res = do_tune_cpucache(cachep, limit, batchcount, shared);
3069 break;
3072 up(&cache_chain_sem);
3073 if (res >= 0)
3074 res = count;
3075 return res;
3077 #endif
3080 * ksize - get the actual amount of memory allocated for a given object
3081 * @objp: Pointer to the object
3083 * kmalloc may internally round up allocations and return more memory
3084 * than requested. ksize() can be used to determine the actual amount of
3085 * memory allocated. The caller may use this additional memory, even though
3086 * a smaller amount of memory was initially specified with the kmalloc call.
3087 * The caller must guarantee that objp points to a valid object previously
3088 * allocated with either kmalloc() or kmem_cache_alloc(). The object
3089 * must not be freed during the duration of the call.
3091 unsigned int ksize(const void *objp)
3093 if (unlikely(objp == NULL))
3094 return 0;
3096 return obj_reallen(GET_PAGE_CACHE(virt_to_page(objp)));
3101 * kstrdup - allocate space for and copy an existing string
3103 * @s: the string to duplicate
3104 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
3106 char *kstrdup(const char *s, unsigned int __nocast gfp)
3108 size_t len;
3109 char *buf;
3111 if (!s)
3112 return NULL;
3114 len = strlen(s) + 1;
3115 buf = kmalloc(len, gfp);
3116 if (buf)
3117 memcpy(buf, s, len);
3118 return buf;
3120 EXPORT_SYMBOL(kstrdup);