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 struct kmem_cache 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 mutex 'cache_chain_mutex'.
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.
78 * 15 March 2005. NUMA slab allocator.
79 * Shai Fultheim <shai@scalex86.org>.
80 * Shobhit Dayal <shobhit@calsoftinc.com>
81 * Alok N Kataria <alokk@calsoftinc.com>
82 * Christoph Lameter <christoph@lameter.com>
84 * Modified the slab allocator to be node aware on NUMA systems.
85 * Each node has its own list of partial, free and full slabs.
86 * All object allocations for a node occur from node specific slab lists.
89 #include <linux/config.h>
90 #include <linux/slab.h>
92 #include <linux/poison.h>
93 #include <linux/swap.h>
94 #include <linux/cache.h>
95 #include <linux/interrupt.h>
96 #include <linux/init.h>
97 #include <linux/compiler.h>
98 #include <linux/cpuset.h>
99 #include <linux/seq_file.h>
100 #include <linux/notifier.h>
101 #include <linux/kallsyms.h>
102 #include <linux/cpu.h>
103 #include <linux/sysctl.h>
104 #include <linux/module.h>
105 #include <linux/rcupdate.h>
106 #include <linux/string.h>
107 #include <linux/nodemask.h>
108 #include <linux/mempolicy.h>
109 #include <linux/mutex.h>
110 #include <linux/rtmutex.h>
112 #include <asm/uaccess.h>
113 #include <asm/cacheflush.h>
114 #include <asm/tlbflush.h>
115 #include <asm/page.h>
118 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
119 * SLAB_RED_ZONE & SLAB_POISON.
120 * 0 for faster, smaller code (especially in the critical paths).
122 * STATS - 1 to collect stats for /proc/slabinfo.
123 * 0 for faster, smaller code (especially in the critical paths).
125 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
128 #ifdef CONFIG_DEBUG_SLAB
131 #define FORCED_DEBUG 1
135 #define FORCED_DEBUG 0
138 /* Shouldn't this be in a header file somewhere? */
139 #define BYTES_PER_WORD sizeof(void *)
141 #ifndef cache_line_size
142 #define cache_line_size() L1_CACHE_BYTES
145 #ifndef ARCH_KMALLOC_MINALIGN
147 * Enforce a minimum alignment for the kmalloc caches.
148 * Usually, the kmalloc caches are cache_line_size() aligned, except when
149 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
150 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
151 * alignment larger than BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
152 * Note that this flag disables some debug features.
154 #define ARCH_KMALLOC_MINALIGN 0
157 #ifndef ARCH_SLAB_MINALIGN
159 * Enforce a minimum alignment for all caches.
160 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
161 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
162 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
163 * some debug features.
165 #define ARCH_SLAB_MINALIGN 0
168 #ifndef ARCH_KMALLOC_FLAGS
169 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
172 /* Legal flag mask for kmem_cache_create(). */
174 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
175 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
177 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
178 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
179 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD)
181 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
182 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
183 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
184 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD)
190 * Bufctl's are used for linking objs within a slab
193 * This implementation relies on "struct page" for locating the cache &
194 * slab an object belongs to.
195 * This allows the bufctl structure to be small (one int), but limits
196 * the number of objects a slab (not a cache) can contain when off-slab
197 * bufctls are used. The limit is the size of the largest general cache
198 * that does not use off-slab slabs.
199 * For 32bit archs with 4 kB pages, is this 56.
200 * This is not serious, as it is only for large objects, when it is unwise
201 * to have too many per slab.
202 * Note: This limit can be raised by introducing a general cache whose size
203 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
206 typedef unsigned int kmem_bufctl_t;
207 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
208 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
209 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
210 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
215 * Manages the objs in a slab. Placed either at the beginning of mem allocated
216 * for a slab, or allocated from an general cache.
217 * Slabs are chained into three list: fully used, partial, fully free slabs.
220 struct list_head list;
221 unsigned long colouroff;
222 void *s_mem; /* including colour offset */
223 unsigned int inuse; /* num of objs active in slab */
225 unsigned short nodeid;
231 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
232 * arrange for kmem_freepages to be called via RCU. This is useful if
233 * we need to approach a kernel structure obliquely, from its address
234 * obtained without the usual locking. We can lock the structure to
235 * stabilize it and check it's still at the given address, only if we
236 * can be sure that the memory has not been meanwhile reused for some
237 * other kind of object (which our subsystem's lock might corrupt).
239 * rcu_read_lock before reading the address, then rcu_read_unlock after
240 * taking the spinlock within the structure expected at that address.
242 * We assume struct slab_rcu can overlay struct slab when destroying.
245 struct rcu_head head;
246 struct kmem_cache *cachep;
254 * - LIFO ordering, to hand out cache-warm objects from _alloc
255 * - reduce the number of linked list operations
256 * - reduce spinlock operations
258 * The limit is stored in the per-cpu structure to reduce the data cache
265 unsigned int batchcount;
266 unsigned int touched;
269 * Must have this definition in here for the proper
270 * alignment of array_cache. Also simplifies accessing
272 * [0] is for gcc 2.95. It should really be [].
277 * bootstrap: The caches do not work without cpuarrays anymore, but the
278 * cpuarrays are allocated from the generic caches...
280 #define BOOT_CPUCACHE_ENTRIES 1
281 struct arraycache_init {
282 struct array_cache cache;
283 void *entries[BOOT_CPUCACHE_ENTRIES];
287 * The slab lists for all objects.
290 struct list_head slabs_partial; /* partial list first, better asm code */
291 struct list_head slabs_full;
292 struct list_head slabs_free;
293 unsigned long free_objects;
294 unsigned int free_limit;
295 unsigned int colour_next; /* Per-node cache coloring */
296 spinlock_t list_lock;
297 struct array_cache *shared; /* shared per node */
298 struct array_cache **alien; /* on other nodes */
299 unsigned long next_reap; /* updated without locking */
300 int free_touched; /* updated without locking */
304 * Need this for bootstrapping a per node allocator.
306 #define NUM_INIT_LISTS (2 * MAX_NUMNODES + 1)
307 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
308 #define CACHE_CACHE 0
310 #define SIZE_L3 (1 + MAX_NUMNODES)
312 static int drain_freelist(struct kmem_cache *cache,
313 struct kmem_list3 *l3, int tofree);
314 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
316 static void enable_cpucache(struct kmem_cache *cachep);
317 static void cache_reap(void *unused);
320 * This function must be completely optimized away if a constant is passed to
321 * it. Mostly the same as what is in linux/slab.h except it returns an index.
323 static __always_inline int index_of(const size_t size)
325 extern void __bad_size(void);
327 if (__builtin_constant_p(size)) {
335 #include "linux/kmalloc_sizes.h"
343 static int slab_early_init = 1;
345 #define INDEX_AC index_of(sizeof(struct arraycache_init))
346 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
348 static void kmem_list3_init(struct kmem_list3 *parent)
350 INIT_LIST_HEAD(&parent->slabs_full);
351 INIT_LIST_HEAD(&parent->slabs_partial);
352 INIT_LIST_HEAD(&parent->slabs_free);
353 parent->shared = NULL;
354 parent->alien = NULL;
355 parent->colour_next = 0;
356 spin_lock_init(&parent->list_lock);
357 parent->free_objects = 0;
358 parent->free_touched = 0;
361 #define MAKE_LIST(cachep, listp, slab, nodeid) \
363 INIT_LIST_HEAD(listp); \
364 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
367 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
369 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
370 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
371 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
381 /* 1) per-cpu data, touched during every alloc/free */
382 struct array_cache *array[NR_CPUS];
383 /* 2) Cache tunables. Protected by cache_chain_mutex */
384 unsigned int batchcount;
388 unsigned int buffer_size;
389 /* 3) touched by every alloc & free from the backend */
390 struct kmem_list3 *nodelists[MAX_NUMNODES];
392 unsigned int flags; /* constant flags */
393 unsigned int num; /* # of objs per slab */
395 /* 4) cache_grow/shrink */
396 /* order of pgs per slab (2^n) */
397 unsigned int gfporder;
399 /* force GFP flags, e.g. GFP_DMA */
402 size_t colour; /* cache colouring range */
403 unsigned int colour_off; /* colour offset */
404 struct kmem_cache *slabp_cache;
405 unsigned int slab_size;
406 unsigned int dflags; /* dynamic flags */
408 /* constructor func */
409 void (*ctor) (void *, struct kmem_cache *, unsigned long);
411 /* de-constructor func */
412 void (*dtor) (void *, struct kmem_cache *, unsigned long);
414 /* 5) cache creation/removal */
416 struct list_head next;
420 unsigned long num_active;
421 unsigned long num_allocations;
422 unsigned long high_mark;
424 unsigned long reaped;
425 unsigned long errors;
426 unsigned long max_freeable;
427 unsigned long node_allocs;
428 unsigned long node_frees;
429 unsigned long node_overflow;
437 * If debugging is enabled, then the allocator can add additional
438 * fields and/or padding to every object. buffer_size contains the total
439 * object size including these internal fields, the following two
440 * variables contain the offset to the user object and its size.
447 #define CFLGS_OFF_SLAB (0x80000000UL)
448 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
450 #define BATCHREFILL_LIMIT 16
452 * Optimization question: fewer reaps means less probability for unnessary
453 * cpucache drain/refill cycles.
455 * OTOH the cpuarrays can contain lots of objects,
456 * which could lock up otherwise freeable slabs.
458 #define REAPTIMEOUT_CPUC (2*HZ)
459 #define REAPTIMEOUT_LIST3 (4*HZ)
462 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
463 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
464 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
465 #define STATS_INC_GROWN(x) ((x)->grown++)
466 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
467 #define STATS_SET_HIGH(x) \
469 if ((x)->num_active > (x)->high_mark) \
470 (x)->high_mark = (x)->num_active; \
472 #define STATS_INC_ERR(x) ((x)->errors++)
473 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
474 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
475 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
476 #define STATS_SET_FREEABLE(x, i) \
478 if ((x)->max_freeable < i) \
479 (x)->max_freeable = i; \
481 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
482 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
483 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
484 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
486 #define STATS_INC_ACTIVE(x) do { } while (0)
487 #define STATS_DEC_ACTIVE(x) do { } while (0)
488 #define STATS_INC_ALLOCED(x) do { } while (0)
489 #define STATS_INC_GROWN(x) do { } while (0)
490 #define STATS_ADD_REAPED(x,y) do { } while (0)
491 #define STATS_SET_HIGH(x) do { } while (0)
492 #define STATS_INC_ERR(x) do { } while (0)
493 #define STATS_INC_NODEALLOCS(x) do { } while (0)
494 #define STATS_INC_NODEFREES(x) do { } while (0)
495 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
496 #define STATS_SET_FREEABLE(x, i) do { } while (0)
497 #define STATS_INC_ALLOCHIT(x) do { } while (0)
498 #define STATS_INC_ALLOCMISS(x) do { } while (0)
499 #define STATS_INC_FREEHIT(x) do { } while (0)
500 #define STATS_INC_FREEMISS(x) do { } while (0)
506 * memory layout of objects:
508 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
509 * the end of an object is aligned with the end of the real
510 * allocation. Catches writes behind the end of the allocation.
511 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
513 * cachep->obj_offset: The real object.
514 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
515 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
516 * [BYTES_PER_WORD long]
518 static int obj_offset(struct kmem_cache *cachep)
520 return cachep->obj_offset;
523 static int obj_size(struct kmem_cache *cachep)
525 return cachep->obj_size;
528 static unsigned long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
530 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
531 return (unsigned long*) (objp+obj_offset(cachep)-BYTES_PER_WORD);
534 static unsigned long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
536 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
537 if (cachep->flags & SLAB_STORE_USER)
538 return (unsigned long *)(objp + cachep->buffer_size -
540 return (unsigned long *)(objp + cachep->buffer_size - BYTES_PER_WORD);
543 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
545 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
546 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
551 #define obj_offset(x) 0
552 #define obj_size(cachep) (cachep->buffer_size)
553 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
554 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
555 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
560 * Maximum size of an obj (in 2^order pages) and absolute limit for the gfp
563 #if defined(CONFIG_LARGE_ALLOCS)
564 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
565 #define MAX_GFP_ORDER 13 /* up to 32Mb */
566 #elif defined(CONFIG_MMU)
567 #define MAX_OBJ_ORDER 5 /* 32 pages */
568 #define MAX_GFP_ORDER 5 /* 32 pages */
570 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
571 #define MAX_GFP_ORDER 8 /* up to 1Mb */
575 * Do not go above this order unless 0 objects fit into the slab.
577 #define BREAK_GFP_ORDER_HI 1
578 #define BREAK_GFP_ORDER_LO 0
579 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
582 * Functions for storing/retrieving the cachep and or slab from the page
583 * allocator. These are used to find the slab an obj belongs to. With kfree(),
584 * these are used to find the cache which an obj belongs to.
586 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
588 page->lru.next = (struct list_head *)cache;
591 static inline struct kmem_cache *page_get_cache(struct page *page)
593 if (unlikely(PageCompound(page)))
594 page = (struct page *)page_private(page);
595 BUG_ON(!PageSlab(page));
596 return (struct kmem_cache *)page->lru.next;
599 static inline void page_set_slab(struct page *page, struct slab *slab)
601 page->lru.prev = (struct list_head *)slab;
604 static inline struct slab *page_get_slab(struct page *page)
606 if (unlikely(PageCompound(page)))
607 page = (struct page *)page_private(page);
608 BUG_ON(!PageSlab(page));
609 return (struct slab *)page->lru.prev;
612 static inline struct kmem_cache *virt_to_cache(const void *obj)
614 struct page *page = virt_to_page(obj);
615 return page_get_cache(page);
618 static inline struct slab *virt_to_slab(const void *obj)
620 struct page *page = virt_to_page(obj);
621 return page_get_slab(page);
624 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
627 return slab->s_mem + cache->buffer_size * idx;
630 static inline unsigned int obj_to_index(struct kmem_cache *cache,
631 struct slab *slab, void *obj)
633 return (unsigned)(obj - slab->s_mem) / cache->buffer_size;
637 * These are the default caches for kmalloc. Custom caches can have other sizes.
639 struct cache_sizes malloc_sizes[] = {
640 #define CACHE(x) { .cs_size = (x) },
641 #include <linux/kmalloc_sizes.h>
645 EXPORT_SYMBOL(malloc_sizes);
647 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
653 static struct cache_names __initdata cache_names[] = {
654 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
655 #include <linux/kmalloc_sizes.h>
660 static struct arraycache_init initarray_cache __initdata =
661 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
662 static struct arraycache_init initarray_generic =
663 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
665 /* internal cache of cache description objs */
666 static struct kmem_cache cache_cache = {
668 .limit = BOOT_CPUCACHE_ENTRIES,
670 .buffer_size = sizeof(struct kmem_cache),
671 .name = "kmem_cache",
673 .obj_size = sizeof(struct kmem_cache),
677 /* Guard access to the cache-chain. */
678 static DEFINE_MUTEX(cache_chain_mutex);
679 static struct list_head cache_chain;
682 * vm_enough_memory() looks at this to determine how many slab-allocated pages
683 * are possibly freeable under pressure
685 * SLAB_RECLAIM_ACCOUNT turns this on per-slab
687 atomic_t slab_reclaim_pages;
690 * chicken and egg problem: delay the per-cpu array allocation
691 * until the general caches are up.
701 * used by boot code to determine if it can use slab based allocator
703 int slab_is_available(void)
705 return g_cpucache_up == FULL;
708 static DEFINE_PER_CPU(struct work_struct, reap_work);
710 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
712 return cachep->array[smp_processor_id()];
715 static inline struct kmem_cache *__find_general_cachep(size_t size,
718 struct cache_sizes *csizep = malloc_sizes;
721 /* This happens if someone tries to call
722 * kmem_cache_create(), or __kmalloc(), before
723 * the generic caches are initialized.
725 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
727 while (size > csizep->cs_size)
731 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
732 * has cs_{dma,}cachep==NULL. Thus no special case
733 * for large kmalloc calls required.
735 if (unlikely(gfpflags & GFP_DMA))
736 return csizep->cs_dmacachep;
737 return csizep->cs_cachep;
740 struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
742 return __find_general_cachep(size, gfpflags);
744 EXPORT_SYMBOL(kmem_find_general_cachep);
746 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
748 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
752 * Calculate the number of objects and left-over bytes for a given buffer size.
754 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
755 size_t align, int flags, size_t *left_over,
760 size_t slab_size = PAGE_SIZE << gfporder;
763 * The slab management structure can be either off the slab or
764 * on it. For the latter case, the memory allocated for a
768 * - One kmem_bufctl_t for each object
769 * - Padding to respect alignment of @align
770 * - @buffer_size bytes for each object
772 * If the slab management structure is off the slab, then the
773 * alignment will already be calculated into the size. Because
774 * the slabs are all pages aligned, the objects will be at the
775 * correct alignment when allocated.
777 if (flags & CFLGS_OFF_SLAB) {
779 nr_objs = slab_size / buffer_size;
781 if (nr_objs > SLAB_LIMIT)
782 nr_objs = SLAB_LIMIT;
785 * Ignore padding for the initial guess. The padding
786 * is at most @align-1 bytes, and @buffer_size is at
787 * least @align. In the worst case, this result will
788 * be one greater than the number of objects that fit
789 * into the memory allocation when taking the padding
792 nr_objs = (slab_size - sizeof(struct slab)) /
793 (buffer_size + sizeof(kmem_bufctl_t));
796 * This calculated number will be either the right
797 * amount, or one greater than what we want.
799 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
803 if (nr_objs > SLAB_LIMIT)
804 nr_objs = SLAB_LIMIT;
806 mgmt_size = slab_mgmt_size(nr_objs, align);
809 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
812 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
814 static void __slab_error(const char *function, struct kmem_cache *cachep,
817 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
818 function, cachep->name, msg);
824 * Special reaping functions for NUMA systems called from cache_reap().
825 * These take care of doing round robin flushing of alien caches (containing
826 * objects freed on different nodes from which they were allocated) and the
827 * flushing of remote pcps by calling drain_node_pages.
829 static DEFINE_PER_CPU(unsigned long, reap_node);
831 static void init_reap_node(int cpu)
835 node = next_node(cpu_to_node(cpu), node_online_map);
836 if (node == MAX_NUMNODES)
837 node = first_node(node_online_map);
839 __get_cpu_var(reap_node) = node;
842 static void next_reap_node(void)
844 int node = __get_cpu_var(reap_node);
847 * Also drain per cpu pages on remote zones
849 if (node != numa_node_id())
850 drain_node_pages(node);
852 node = next_node(node, node_online_map);
853 if (unlikely(node >= MAX_NUMNODES))
854 node = first_node(node_online_map);
855 __get_cpu_var(reap_node) = node;
859 #define init_reap_node(cpu) do { } while (0)
860 #define next_reap_node(void) do { } while (0)
864 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
865 * via the workqueue/eventd.
866 * Add the CPU number into the expiration time to minimize the possibility of
867 * the CPUs getting into lockstep and contending for the global cache chain
870 static void __devinit start_cpu_timer(int cpu)
872 struct work_struct *reap_work = &per_cpu(reap_work, cpu);
875 * When this gets called from do_initcalls via cpucache_init(),
876 * init_workqueues() has already run, so keventd will be setup
879 if (keventd_up() && reap_work->func == NULL) {
881 INIT_WORK(reap_work, cache_reap, NULL);
882 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
886 static struct array_cache *alloc_arraycache(int node, int entries,
889 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
890 struct array_cache *nc = NULL;
892 nc = kmalloc_node(memsize, GFP_KERNEL, node);
896 nc->batchcount = batchcount;
898 spin_lock_init(&nc->lock);
904 * Transfer objects in one arraycache to another.
905 * Locking must be handled by the caller.
907 * Return the number of entries transferred.
909 static int transfer_objects(struct array_cache *to,
910 struct array_cache *from, unsigned int max)
912 /* Figure out how many entries to transfer */
913 int nr = min(min(from->avail, max), to->limit - to->avail);
918 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
928 static void *__cache_alloc_node(struct kmem_cache *, gfp_t, int);
929 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
931 static struct array_cache **alloc_alien_cache(int node, int limit)
933 struct array_cache **ac_ptr;
934 int memsize = sizeof(void *) * MAX_NUMNODES;
939 ac_ptr = kmalloc_node(memsize, GFP_KERNEL, node);
942 if (i == node || !node_online(i)) {
946 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d);
948 for (i--; i <= 0; i--)
958 static void free_alien_cache(struct array_cache **ac_ptr)
969 static void __drain_alien_cache(struct kmem_cache *cachep,
970 struct array_cache *ac, int node)
972 struct kmem_list3 *rl3 = cachep->nodelists[node];
975 spin_lock(&rl3->list_lock);
977 * Stuff objects into the remote nodes shared array first.
978 * That way we could avoid the overhead of putting the objects
979 * into the free lists and getting them back later.
982 transfer_objects(rl3->shared, ac, ac->limit);
984 free_block(cachep, ac->entry, ac->avail, node);
986 spin_unlock(&rl3->list_lock);
991 * Called from cache_reap() to regularly drain alien caches round robin.
993 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
995 int node = __get_cpu_var(reap_node);
998 struct array_cache *ac = l3->alien[node];
1000 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1001 __drain_alien_cache(cachep, ac, node);
1002 spin_unlock_irq(&ac->lock);
1007 static void drain_alien_cache(struct kmem_cache *cachep,
1008 struct array_cache **alien)
1011 struct array_cache *ac;
1012 unsigned long flags;
1014 for_each_online_node(i) {
1017 spin_lock_irqsave(&ac->lock, flags);
1018 __drain_alien_cache(cachep, ac, i);
1019 spin_unlock_irqrestore(&ac->lock, flags);
1024 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp,
1027 struct slab *slabp = virt_to_slab(objp);
1028 int nodeid = slabp->nodeid;
1029 struct kmem_list3 *l3;
1030 struct array_cache *alien = NULL;
1033 * Make sure we are not freeing a object from another node to the array
1034 * cache on this cpu.
1036 if (likely(slabp->nodeid == numa_node_id()))
1039 l3 = cachep->nodelists[numa_node_id()];
1040 STATS_INC_NODEFREES(cachep);
1041 if (l3->alien && l3->alien[nodeid]) {
1042 alien = l3->alien[nodeid];
1043 spin_lock_nested(&alien->lock, nesting);
1044 if (unlikely(alien->avail == alien->limit)) {
1045 STATS_INC_ACOVERFLOW(cachep);
1046 __drain_alien_cache(cachep, alien, nodeid);
1048 alien->entry[alien->avail++] = objp;
1049 spin_unlock(&alien->lock);
1051 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1052 free_block(cachep, &objp, 1, nodeid);
1053 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1060 #define drain_alien_cache(cachep, alien) do { } while (0)
1061 #define reap_alien(cachep, l3) do { } while (0)
1063 static inline struct array_cache **alloc_alien_cache(int node, int limit)
1065 return (struct array_cache **) 0x01020304ul;
1068 static inline void free_alien_cache(struct array_cache **ac_ptr)
1072 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp,
1080 static int __devinit cpuup_callback(struct notifier_block *nfb,
1081 unsigned long action, void *hcpu)
1083 long cpu = (long)hcpu;
1084 struct kmem_cache *cachep;
1085 struct kmem_list3 *l3 = NULL;
1086 int node = cpu_to_node(cpu);
1087 int memsize = sizeof(struct kmem_list3);
1090 case CPU_UP_PREPARE:
1091 mutex_lock(&cache_chain_mutex);
1093 * We need to do this right in the beginning since
1094 * alloc_arraycache's are going to use this list.
1095 * kmalloc_node allows us to add the slab to the right
1096 * kmem_list3 and not this cpu's kmem_list3
1099 list_for_each_entry(cachep, &cache_chain, next) {
1101 * Set up the size64 kmemlist for cpu before we can
1102 * begin anything. Make sure some other cpu on this
1103 * node has not already allocated this
1105 if (!cachep->nodelists[node]) {
1106 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1109 kmem_list3_init(l3);
1110 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1111 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1114 * The l3s don't come and go as CPUs come and
1115 * go. cache_chain_mutex is sufficient
1118 cachep->nodelists[node] = l3;
1121 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1122 cachep->nodelists[node]->free_limit =
1123 (1 + nr_cpus_node(node)) *
1124 cachep->batchcount + cachep->num;
1125 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1129 * Now we can go ahead with allocating the shared arrays and
1132 list_for_each_entry(cachep, &cache_chain, next) {
1133 struct array_cache *nc;
1134 struct array_cache *shared;
1135 struct array_cache **alien;
1137 nc = alloc_arraycache(node, cachep->limit,
1138 cachep->batchcount);
1141 shared = alloc_arraycache(node,
1142 cachep->shared * cachep->batchcount,
1147 alien = alloc_alien_cache(node, cachep->limit);
1150 cachep->array[cpu] = nc;
1151 l3 = cachep->nodelists[node];
1154 spin_lock_irq(&l3->list_lock);
1157 * We are serialised from CPU_DEAD or
1158 * CPU_UP_CANCELLED by the cpucontrol lock
1160 l3->shared = shared;
1169 spin_unlock_irq(&l3->list_lock);
1171 free_alien_cache(alien);
1173 mutex_unlock(&cache_chain_mutex);
1176 start_cpu_timer(cpu);
1178 #ifdef CONFIG_HOTPLUG_CPU
1181 * Even if all the cpus of a node are down, we don't free the
1182 * kmem_list3 of any cache. This to avoid a race between
1183 * cpu_down, and a kmalloc allocation from another cpu for
1184 * memory from the node of the cpu going down. The list3
1185 * structure is usually allocated from kmem_cache_create() and
1186 * gets destroyed at kmem_cache_destroy().
1189 case CPU_UP_CANCELED:
1190 mutex_lock(&cache_chain_mutex);
1191 list_for_each_entry(cachep, &cache_chain, next) {
1192 struct array_cache *nc;
1193 struct array_cache *shared;
1194 struct array_cache **alien;
1197 mask = node_to_cpumask(node);
1198 /* cpu is dead; no one can alloc from it. */
1199 nc = cachep->array[cpu];
1200 cachep->array[cpu] = NULL;
1201 l3 = cachep->nodelists[node];
1204 goto free_array_cache;
1206 spin_lock_irq(&l3->list_lock);
1208 /* Free limit for this kmem_list3 */
1209 l3->free_limit -= cachep->batchcount;
1211 free_block(cachep, nc->entry, nc->avail, node);
1213 if (!cpus_empty(mask)) {
1214 spin_unlock_irq(&l3->list_lock);
1215 goto free_array_cache;
1218 shared = l3->shared;
1220 free_block(cachep, l3->shared->entry,
1221 l3->shared->avail, node);
1228 spin_unlock_irq(&l3->list_lock);
1232 drain_alien_cache(cachep, alien);
1233 free_alien_cache(alien);
1239 * In the previous loop, all the objects were freed to
1240 * the respective cache's slabs, now we can go ahead and
1241 * shrink each nodelist to its limit.
1243 list_for_each_entry(cachep, &cache_chain, next) {
1244 l3 = cachep->nodelists[node];
1247 drain_freelist(cachep, l3, l3->free_objects);
1249 mutex_unlock(&cache_chain_mutex);
1255 mutex_unlock(&cache_chain_mutex);
1259 static struct notifier_block __cpuinitdata cpucache_notifier = {
1260 &cpuup_callback, NULL, 0
1264 * swap the static kmem_list3 with kmalloced memory
1266 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1269 struct kmem_list3 *ptr;
1271 BUG_ON(cachep->nodelists[nodeid] != list);
1272 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, nodeid);
1275 local_irq_disable();
1276 memcpy(ptr, list, sizeof(struct kmem_list3));
1278 * Do not assume that spinlocks can be initialized via memcpy:
1280 spin_lock_init(&ptr->list_lock);
1282 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1283 cachep->nodelists[nodeid] = ptr;
1288 * Initialisation. Called after the page allocator have been initialised and
1289 * before smp_init().
1291 void __init kmem_cache_init(void)
1294 struct cache_sizes *sizes;
1295 struct cache_names *names;
1299 for (i = 0; i < NUM_INIT_LISTS; i++) {
1300 kmem_list3_init(&initkmem_list3[i]);
1301 if (i < MAX_NUMNODES)
1302 cache_cache.nodelists[i] = NULL;
1306 * Fragmentation resistance on low memory - only use bigger
1307 * page orders on machines with more than 32MB of memory.
1309 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
1310 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1312 /* Bootstrap is tricky, because several objects are allocated
1313 * from caches that do not exist yet:
1314 * 1) initialize the cache_cache cache: it contains the struct
1315 * kmem_cache structures of all caches, except cache_cache itself:
1316 * cache_cache is statically allocated.
1317 * Initially an __init data area is used for the head array and the
1318 * kmem_list3 structures, it's replaced with a kmalloc allocated
1319 * array at the end of the bootstrap.
1320 * 2) Create the first kmalloc cache.
1321 * The struct kmem_cache for the new cache is allocated normally.
1322 * An __init data area is used for the head array.
1323 * 3) Create the remaining kmalloc caches, with minimally sized
1325 * 4) Replace the __init data head arrays for cache_cache and the first
1326 * kmalloc cache with kmalloc allocated arrays.
1327 * 5) Replace the __init data for kmem_list3 for cache_cache and
1328 * the other cache's with kmalloc allocated memory.
1329 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1332 /* 1) create the cache_cache */
1333 INIT_LIST_HEAD(&cache_chain);
1334 list_add(&cache_cache.next, &cache_chain);
1335 cache_cache.colour_off = cache_line_size();
1336 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1337 cache_cache.nodelists[numa_node_id()] = &initkmem_list3[CACHE_CACHE];
1339 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1342 for (order = 0; order < MAX_ORDER; order++) {
1343 cache_estimate(order, cache_cache.buffer_size,
1344 cache_line_size(), 0, &left_over, &cache_cache.num);
1345 if (cache_cache.num)
1348 BUG_ON(!cache_cache.num);
1349 cache_cache.gfporder = order;
1350 cache_cache.colour = left_over / cache_cache.colour_off;
1351 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1352 sizeof(struct slab), cache_line_size());
1354 /* 2+3) create the kmalloc caches */
1355 sizes = malloc_sizes;
1356 names = cache_names;
1359 * Initialize the caches that provide memory for the array cache and the
1360 * kmem_list3 structures first. Without this, further allocations will
1364 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1365 sizes[INDEX_AC].cs_size,
1366 ARCH_KMALLOC_MINALIGN,
1367 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1370 if (INDEX_AC != INDEX_L3) {
1371 sizes[INDEX_L3].cs_cachep =
1372 kmem_cache_create(names[INDEX_L3].name,
1373 sizes[INDEX_L3].cs_size,
1374 ARCH_KMALLOC_MINALIGN,
1375 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1379 slab_early_init = 0;
1381 while (sizes->cs_size != ULONG_MAX) {
1383 * For performance, all the general caches are L1 aligned.
1384 * This should be particularly beneficial on SMP boxes, as it
1385 * eliminates "false sharing".
1386 * Note for systems short on memory removing the alignment will
1387 * allow tighter packing of the smaller caches.
1389 if (!sizes->cs_cachep) {
1390 sizes->cs_cachep = kmem_cache_create(names->name,
1392 ARCH_KMALLOC_MINALIGN,
1393 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1397 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
1399 ARCH_KMALLOC_MINALIGN,
1400 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1406 /* 4) Replace the bootstrap head arrays */
1408 struct array_cache *ptr;
1410 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1412 local_irq_disable();
1413 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1414 memcpy(ptr, cpu_cache_get(&cache_cache),
1415 sizeof(struct arraycache_init));
1417 * Do not assume that spinlocks can be initialized via memcpy:
1419 spin_lock_init(&ptr->lock);
1421 cache_cache.array[smp_processor_id()] = ptr;
1424 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1426 local_irq_disable();
1427 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1428 != &initarray_generic.cache);
1429 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1430 sizeof(struct arraycache_init));
1432 * Do not assume that spinlocks can be initialized via memcpy:
1434 spin_lock_init(&ptr->lock);
1436 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1440 /* 5) Replace the bootstrap kmem_list3's */
1443 /* Replace the static kmem_list3 structures for the boot cpu */
1444 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE],
1447 for_each_online_node(node) {
1448 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1449 &initkmem_list3[SIZE_AC + node], node);
1451 if (INDEX_AC != INDEX_L3) {
1452 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1453 &initkmem_list3[SIZE_L3 + node],
1459 /* 6) resize the head arrays to their final sizes */
1461 struct kmem_cache *cachep;
1462 mutex_lock(&cache_chain_mutex);
1463 list_for_each_entry(cachep, &cache_chain, next)
1464 enable_cpucache(cachep);
1465 mutex_unlock(&cache_chain_mutex);
1469 g_cpucache_up = FULL;
1472 * Register a cpu startup notifier callback that initializes
1473 * cpu_cache_get for all new cpus
1475 register_cpu_notifier(&cpucache_notifier);
1478 * The reap timers are started later, with a module init call: That part
1479 * of the kernel is not yet operational.
1483 static int __init cpucache_init(void)
1488 * Register the timers that return unneeded pages to the page allocator
1490 for_each_online_cpu(cpu)
1491 start_cpu_timer(cpu);
1494 __initcall(cpucache_init);
1497 * Interface to system's page allocator. No need to hold the cache-lock.
1499 * If we requested dmaable memory, we will get it. Even if we
1500 * did not request dmaable memory, we might get it, but that
1501 * would be relatively rare and ignorable.
1503 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1511 * Nommu uses slab's for process anonymous memory allocations, and thus
1512 * requires __GFP_COMP to properly refcount higher order allocations
1514 flags |= __GFP_COMP;
1516 flags |= cachep->gfpflags;
1518 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
1522 nr_pages = (1 << cachep->gfporder);
1523 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1524 atomic_add(nr_pages, &slab_reclaim_pages);
1525 add_zone_page_state(page_zone(page), NR_SLAB, nr_pages);
1526 for (i = 0; i < nr_pages; i++)
1527 __SetPageSlab(page + i);
1528 return page_address(page);
1532 * Interface to system's page release.
1534 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1536 unsigned long i = (1 << cachep->gfporder);
1537 struct page *page = virt_to_page(addr);
1538 const unsigned long nr_freed = i;
1540 sub_zone_page_state(page_zone(page), NR_SLAB, nr_freed);
1542 BUG_ON(!PageSlab(page));
1543 __ClearPageSlab(page);
1546 if (current->reclaim_state)
1547 current->reclaim_state->reclaimed_slab += nr_freed;
1548 free_pages((unsigned long)addr, cachep->gfporder);
1549 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1550 atomic_sub(1 << cachep->gfporder, &slab_reclaim_pages);
1553 static void kmem_rcu_free(struct rcu_head *head)
1555 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1556 struct kmem_cache *cachep = slab_rcu->cachep;
1558 kmem_freepages(cachep, slab_rcu->addr);
1559 if (OFF_SLAB(cachep))
1560 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1565 #ifdef CONFIG_DEBUG_PAGEALLOC
1566 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1567 unsigned long caller)
1569 int size = obj_size(cachep);
1571 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1573 if (size < 5 * sizeof(unsigned long))
1576 *addr++ = 0x12345678;
1578 *addr++ = smp_processor_id();
1579 size -= 3 * sizeof(unsigned long);
1581 unsigned long *sptr = &caller;
1582 unsigned long svalue;
1584 while (!kstack_end(sptr)) {
1586 if (kernel_text_address(svalue)) {
1588 size -= sizeof(unsigned long);
1589 if (size <= sizeof(unsigned long))
1595 *addr++ = 0x87654321;
1599 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1601 int size = obj_size(cachep);
1602 addr = &((char *)addr)[obj_offset(cachep)];
1604 memset(addr, val, size);
1605 *(unsigned char *)(addr + size - 1) = POISON_END;
1608 static void dump_line(char *data, int offset, int limit)
1611 printk(KERN_ERR "%03x:", offset);
1612 for (i = 0; i < limit; i++)
1613 printk(" %02x", (unsigned char)data[offset + i]);
1620 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1625 if (cachep->flags & SLAB_RED_ZONE) {
1626 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1627 *dbg_redzone1(cachep, objp),
1628 *dbg_redzone2(cachep, objp));
1631 if (cachep->flags & SLAB_STORE_USER) {
1632 printk(KERN_ERR "Last user: [<%p>]",
1633 *dbg_userword(cachep, objp));
1634 print_symbol("(%s)",
1635 (unsigned long)*dbg_userword(cachep, objp));
1638 realobj = (char *)objp + obj_offset(cachep);
1639 size = obj_size(cachep);
1640 for (i = 0; i < size && lines; i += 16, lines--) {
1643 if (i + limit > size)
1645 dump_line(realobj, i, limit);
1649 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1655 realobj = (char *)objp + obj_offset(cachep);
1656 size = obj_size(cachep);
1658 for (i = 0; i < size; i++) {
1659 char exp = POISON_FREE;
1662 if (realobj[i] != exp) {
1668 "Slab corruption: start=%p, len=%d\n",
1670 print_objinfo(cachep, objp, 0);
1672 /* Hexdump the affected line */
1675 if (i + limit > size)
1677 dump_line(realobj, i, limit);
1680 /* Limit to 5 lines */
1686 /* Print some data about the neighboring objects, if they
1689 struct slab *slabp = virt_to_slab(objp);
1692 objnr = obj_to_index(cachep, slabp, objp);
1694 objp = index_to_obj(cachep, slabp, objnr - 1);
1695 realobj = (char *)objp + obj_offset(cachep);
1696 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1698 print_objinfo(cachep, objp, 2);
1700 if (objnr + 1 < cachep->num) {
1701 objp = index_to_obj(cachep, slabp, objnr + 1);
1702 realobj = (char *)objp + obj_offset(cachep);
1703 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1705 print_objinfo(cachep, objp, 2);
1713 * slab_destroy_objs - destroy a slab and its objects
1714 * @cachep: cache pointer being destroyed
1715 * @slabp: slab pointer being destroyed
1717 * Call the registered destructor for each object in a slab that is being
1720 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1723 for (i = 0; i < cachep->num; i++) {
1724 void *objp = index_to_obj(cachep, slabp, i);
1726 if (cachep->flags & SLAB_POISON) {
1727 #ifdef CONFIG_DEBUG_PAGEALLOC
1728 if (cachep->buffer_size % PAGE_SIZE == 0 &&
1730 kernel_map_pages(virt_to_page(objp),
1731 cachep->buffer_size / PAGE_SIZE, 1);
1733 check_poison_obj(cachep, objp);
1735 check_poison_obj(cachep, objp);
1738 if (cachep->flags & SLAB_RED_ZONE) {
1739 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1740 slab_error(cachep, "start of a freed object "
1742 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1743 slab_error(cachep, "end of a freed object "
1746 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1747 (cachep->dtor) (objp + obj_offset(cachep), cachep, 0);
1751 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1755 for (i = 0; i < cachep->num; i++) {
1756 void *objp = index_to_obj(cachep, slabp, i);
1757 (cachep->dtor) (objp, cachep, 0);
1763 static void __cache_free(struct kmem_cache *cachep, void *objp, int nesting);
1766 * slab_destroy - destroy and release all objects in a slab
1767 * @cachep: cache pointer being destroyed
1768 * @slabp: slab pointer being destroyed
1770 * Destroy all the objs in a slab, and release the mem back to the system.
1771 * Before calling the slab must have been unlinked from the cache. The
1772 * cache-lock is not held/needed.
1774 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1776 void *addr = slabp->s_mem - slabp->colouroff;
1778 slab_destroy_objs(cachep, slabp);
1779 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1780 struct slab_rcu *slab_rcu;
1782 slab_rcu = (struct slab_rcu *)slabp;
1783 slab_rcu->cachep = cachep;
1784 slab_rcu->addr = addr;
1785 call_rcu(&slab_rcu->head, kmem_rcu_free);
1787 kmem_freepages(cachep, addr);
1788 if (OFF_SLAB(cachep)) {
1789 unsigned long flags;
1792 * lockdep: we may nest inside an already held
1793 * ac->lock, so pass in a nesting flag:
1795 local_irq_save(flags);
1796 __cache_free(cachep->slabp_cache, slabp, 1);
1797 local_irq_restore(flags);
1803 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1804 * size of kmem_list3.
1806 static void set_up_list3s(struct kmem_cache *cachep, int index)
1810 for_each_online_node(node) {
1811 cachep->nodelists[node] = &initkmem_list3[index + node];
1812 cachep->nodelists[node]->next_reap = jiffies +
1814 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1819 * calculate_slab_order - calculate size (page order) of slabs
1820 * @cachep: pointer to the cache that is being created
1821 * @size: size of objects to be created in this cache.
1822 * @align: required alignment for the objects.
1823 * @flags: slab allocation flags
1825 * Also calculates the number of objects per slab.
1827 * This could be made much more intelligent. For now, try to avoid using
1828 * high order pages for slabs. When the gfp() functions are more friendly
1829 * towards high-order requests, this should be changed.
1831 static size_t calculate_slab_order(struct kmem_cache *cachep,
1832 size_t size, size_t align, unsigned long flags)
1834 unsigned long offslab_limit;
1835 size_t left_over = 0;
1838 for (gfporder = 0; gfporder <= MAX_GFP_ORDER; gfporder++) {
1842 cache_estimate(gfporder, size, align, flags, &remainder, &num);
1846 if (flags & CFLGS_OFF_SLAB) {
1848 * Max number of objs-per-slab for caches which
1849 * use off-slab slabs. Needed to avoid a possible
1850 * looping condition in cache_grow().
1852 offslab_limit = size - sizeof(struct slab);
1853 offslab_limit /= sizeof(kmem_bufctl_t);
1855 if (num > offslab_limit)
1859 /* Found something acceptable - save it away */
1861 cachep->gfporder = gfporder;
1862 left_over = remainder;
1865 * A VFS-reclaimable slab tends to have most allocations
1866 * as GFP_NOFS and we really don't want to have to be allocating
1867 * higher-order pages when we are unable to shrink dcache.
1869 if (flags & SLAB_RECLAIM_ACCOUNT)
1873 * Large number of objects is good, but very large slabs are
1874 * currently bad for the gfp()s.
1876 if (gfporder >= slab_break_gfp_order)
1880 * Acceptable internal fragmentation?
1882 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1888 static void setup_cpu_cache(struct kmem_cache *cachep)
1890 if (g_cpucache_up == FULL) {
1891 enable_cpucache(cachep);
1894 if (g_cpucache_up == NONE) {
1896 * Note: the first kmem_cache_create must create the cache
1897 * that's used by kmalloc(24), otherwise the creation of
1898 * further caches will BUG().
1900 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1903 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
1904 * the first cache, then we need to set up all its list3s,
1905 * otherwise the creation of further caches will BUG().
1907 set_up_list3s(cachep, SIZE_AC);
1908 if (INDEX_AC == INDEX_L3)
1909 g_cpucache_up = PARTIAL_L3;
1911 g_cpucache_up = PARTIAL_AC;
1913 cachep->array[smp_processor_id()] =
1914 kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1916 if (g_cpucache_up == PARTIAL_AC) {
1917 set_up_list3s(cachep, SIZE_L3);
1918 g_cpucache_up = PARTIAL_L3;
1921 for_each_online_node(node) {
1922 cachep->nodelists[node] =
1923 kmalloc_node(sizeof(struct kmem_list3),
1925 BUG_ON(!cachep->nodelists[node]);
1926 kmem_list3_init(cachep->nodelists[node]);
1930 cachep->nodelists[numa_node_id()]->next_reap =
1931 jiffies + REAPTIMEOUT_LIST3 +
1932 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1934 cpu_cache_get(cachep)->avail = 0;
1935 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1936 cpu_cache_get(cachep)->batchcount = 1;
1937 cpu_cache_get(cachep)->touched = 0;
1938 cachep->batchcount = 1;
1939 cachep->limit = BOOT_CPUCACHE_ENTRIES;
1943 * kmem_cache_create - Create a cache.
1944 * @name: A string which is used in /proc/slabinfo to identify this cache.
1945 * @size: The size of objects to be created in this cache.
1946 * @align: The required alignment for the objects.
1947 * @flags: SLAB flags
1948 * @ctor: A constructor for the objects.
1949 * @dtor: A destructor for the objects.
1951 * Returns a ptr to the cache on success, NULL on failure.
1952 * Cannot be called within a int, but can be interrupted.
1953 * The @ctor is run when new pages are allocated by the cache
1954 * and the @dtor is run before the pages are handed back.
1956 * @name must be valid until the cache is destroyed. This implies that
1957 * the module calling this has to destroy the cache before getting unloaded.
1961 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1962 * to catch references to uninitialised memory.
1964 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1965 * for buffer overruns.
1967 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1968 * cacheline. This can be beneficial if you're counting cycles as closely
1972 kmem_cache_create (const char *name, size_t size, size_t align,
1973 unsigned long flags,
1974 void (*ctor)(void*, struct kmem_cache *, unsigned long),
1975 void (*dtor)(void*, struct kmem_cache *, unsigned long))
1977 size_t left_over, slab_size, ralign;
1978 struct kmem_cache *cachep = NULL, *pc;
1981 * Sanity checks... these are all serious usage bugs.
1983 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
1984 (size > (1 << MAX_OBJ_ORDER) * PAGE_SIZE) || (dtor && !ctor)) {
1985 printk(KERN_ERR "%s: Early error in slab %s\n", __FUNCTION__,
1991 * Prevent CPUs from coming and going.
1992 * lock_cpu_hotplug() nests outside cache_chain_mutex
1996 mutex_lock(&cache_chain_mutex);
1998 list_for_each_entry(pc, &cache_chain, next) {
1999 mm_segment_t old_fs = get_fs();
2004 * This happens when the module gets unloaded and doesn't
2005 * destroy its slab cache and no-one else reuses the vmalloc
2006 * area of the module. Print a warning.
2009 res = __get_user(tmp, pc->name);
2012 printk("SLAB: cache with size %d has lost its name\n",
2017 if (!strcmp(pc->name, name)) {
2018 printk("kmem_cache_create: duplicate cache %s\n", name);
2025 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2026 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
2027 /* No constructor, but inital state check requested */
2028 printk(KERN_ERR "%s: No con, but init state check "
2029 "requested - %s\n", __FUNCTION__, name);
2030 flags &= ~SLAB_DEBUG_INITIAL;
2034 * Enable redzoning and last user accounting, except for caches with
2035 * large objects, if the increased size would increase the object size
2036 * above the next power of two: caches with object sizes just above a
2037 * power of two have a significant amount of internal fragmentation.
2039 if (size < 4096 || fls(size - 1) == fls(size-1 + 3 * BYTES_PER_WORD))
2040 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2041 if (!(flags & SLAB_DESTROY_BY_RCU))
2042 flags |= SLAB_POISON;
2044 if (flags & SLAB_DESTROY_BY_RCU)
2045 BUG_ON(flags & SLAB_POISON);
2047 if (flags & SLAB_DESTROY_BY_RCU)
2051 * Always checks flags, a caller might be expecting debug support which
2054 BUG_ON(flags & ~CREATE_MASK);
2057 * Check that size is in terms of words. This is needed to avoid
2058 * unaligned accesses for some archs when redzoning is used, and makes
2059 * sure any on-slab bufctl's are also correctly aligned.
2061 if (size & (BYTES_PER_WORD - 1)) {
2062 size += (BYTES_PER_WORD - 1);
2063 size &= ~(BYTES_PER_WORD - 1);
2066 /* calculate the final buffer alignment: */
2068 /* 1) arch recommendation: can be overridden for debug */
2069 if (flags & SLAB_HWCACHE_ALIGN) {
2071 * Default alignment: as specified by the arch code. Except if
2072 * an object is really small, then squeeze multiple objects into
2075 ralign = cache_line_size();
2076 while (size <= ralign / 2)
2079 ralign = BYTES_PER_WORD;
2081 /* 2) arch mandated alignment: disables debug if necessary */
2082 if (ralign < ARCH_SLAB_MINALIGN) {
2083 ralign = ARCH_SLAB_MINALIGN;
2084 if (ralign > BYTES_PER_WORD)
2085 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2087 /* 3) caller mandated alignment: disables debug if necessary */
2088 if (ralign < align) {
2090 if (ralign > BYTES_PER_WORD)
2091 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2094 * 4) Store it. Note that the debug code below can reduce
2095 * the alignment to BYTES_PER_WORD.
2099 /* Get cache's description obj. */
2100 cachep = kmem_cache_zalloc(&cache_cache, SLAB_KERNEL);
2105 cachep->obj_size = size;
2107 if (flags & SLAB_RED_ZONE) {
2108 /* redzoning only works with word aligned caches */
2109 align = BYTES_PER_WORD;
2111 /* add space for red zone words */
2112 cachep->obj_offset += BYTES_PER_WORD;
2113 size += 2 * BYTES_PER_WORD;
2115 if (flags & SLAB_STORE_USER) {
2116 /* user store requires word alignment and
2117 * one word storage behind the end of the real
2120 align = BYTES_PER_WORD;
2121 size += BYTES_PER_WORD;
2123 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2124 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2125 && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2126 cachep->obj_offset += PAGE_SIZE - size;
2133 * Determine if the slab management is 'on' or 'off' slab.
2134 * (bootstrapping cannot cope with offslab caches so don't do
2137 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init)
2139 * Size is large, assume best to place the slab management obj
2140 * off-slab (should allow better packing of objs).
2142 flags |= CFLGS_OFF_SLAB;
2144 size = ALIGN(size, align);
2146 left_over = calculate_slab_order(cachep, size, align, flags);
2149 printk("kmem_cache_create: couldn't create cache %s.\n", name);
2150 kmem_cache_free(&cache_cache, cachep);
2154 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2155 + sizeof(struct slab), align);
2158 * If the slab has been placed off-slab, and we have enough space then
2159 * move it on-slab. This is at the expense of any extra colouring.
2161 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2162 flags &= ~CFLGS_OFF_SLAB;
2163 left_over -= slab_size;
2166 if (flags & CFLGS_OFF_SLAB) {
2167 /* really off slab. No need for manual alignment */
2169 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2172 cachep->colour_off = cache_line_size();
2173 /* Offset must be a multiple of the alignment. */
2174 if (cachep->colour_off < align)
2175 cachep->colour_off = align;
2176 cachep->colour = left_over / cachep->colour_off;
2177 cachep->slab_size = slab_size;
2178 cachep->flags = flags;
2179 cachep->gfpflags = 0;
2180 if (flags & SLAB_CACHE_DMA)
2181 cachep->gfpflags |= GFP_DMA;
2182 cachep->buffer_size = size;
2184 if (flags & CFLGS_OFF_SLAB)
2185 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2186 cachep->ctor = ctor;
2187 cachep->dtor = dtor;
2188 cachep->name = name;
2191 setup_cpu_cache(cachep);
2193 /* cache setup completed, link it into the list */
2194 list_add(&cachep->next, &cache_chain);
2196 if (!cachep && (flags & SLAB_PANIC))
2197 panic("kmem_cache_create(): failed to create slab `%s'\n",
2199 mutex_unlock(&cache_chain_mutex);
2200 unlock_cpu_hotplug();
2203 EXPORT_SYMBOL(kmem_cache_create);
2206 static void check_irq_off(void)
2208 BUG_ON(!irqs_disabled());
2211 static void check_irq_on(void)
2213 BUG_ON(irqs_disabled());
2216 static void check_spinlock_acquired(struct kmem_cache *cachep)
2220 assert_spin_locked(&cachep->nodelists[numa_node_id()]->list_lock);
2224 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2228 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2233 #define check_irq_off() do { } while(0)
2234 #define check_irq_on() do { } while(0)
2235 #define check_spinlock_acquired(x) do { } while(0)
2236 #define check_spinlock_acquired_node(x, y) do { } while(0)
2239 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2240 struct array_cache *ac,
2241 int force, int node);
2243 static void do_drain(void *arg)
2245 struct kmem_cache *cachep = arg;
2246 struct array_cache *ac;
2247 int node = numa_node_id();
2250 ac = cpu_cache_get(cachep);
2251 spin_lock(&cachep->nodelists[node]->list_lock);
2252 free_block(cachep, ac->entry, ac->avail, node);
2253 spin_unlock(&cachep->nodelists[node]->list_lock);
2257 static void drain_cpu_caches(struct kmem_cache *cachep)
2259 struct kmem_list3 *l3;
2262 on_each_cpu(do_drain, cachep, 1, 1);
2264 for_each_online_node(node) {
2265 l3 = cachep->nodelists[node];
2266 if (l3 && l3->alien)
2267 drain_alien_cache(cachep, l3->alien);
2270 for_each_online_node(node) {
2271 l3 = cachep->nodelists[node];
2273 drain_array(cachep, l3, l3->shared, 1, node);
2278 * Remove slabs from the list of free slabs.
2279 * Specify the number of slabs to drain in tofree.
2281 * Returns the actual number of slabs released.
2283 static int drain_freelist(struct kmem_cache *cache,
2284 struct kmem_list3 *l3, int tofree)
2286 struct list_head *p;
2291 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2293 spin_lock_irq(&l3->list_lock);
2294 p = l3->slabs_free.prev;
2295 if (p == &l3->slabs_free) {
2296 spin_unlock_irq(&l3->list_lock);
2300 slabp = list_entry(p, struct slab, list);
2302 BUG_ON(slabp->inuse);
2304 list_del(&slabp->list);
2306 * Safe to drop the lock. The slab is no longer linked
2309 l3->free_objects -= cache->num;
2310 spin_unlock_irq(&l3->list_lock);
2311 slab_destroy(cache, slabp);
2318 static int __cache_shrink(struct kmem_cache *cachep)
2321 struct kmem_list3 *l3;
2323 drain_cpu_caches(cachep);
2326 for_each_online_node(i) {
2327 l3 = cachep->nodelists[i];
2331 drain_freelist(cachep, l3, l3->free_objects);
2333 ret += !list_empty(&l3->slabs_full) ||
2334 !list_empty(&l3->slabs_partial);
2336 return (ret ? 1 : 0);
2340 * kmem_cache_shrink - Shrink a cache.
2341 * @cachep: The cache to shrink.
2343 * Releases as many slabs as possible for a cache.
2344 * To help debugging, a zero exit status indicates all slabs were released.
2346 int kmem_cache_shrink(struct kmem_cache *cachep)
2348 BUG_ON(!cachep || in_interrupt());
2350 return __cache_shrink(cachep);
2352 EXPORT_SYMBOL(kmem_cache_shrink);
2355 * kmem_cache_destroy - delete a cache
2356 * @cachep: the cache to destroy
2358 * Remove a struct kmem_cache object from the slab cache.
2359 * Returns 0 on success.
2361 * It is expected this function will be called by a module when it is
2362 * unloaded. This will remove the cache completely, and avoid a duplicate
2363 * cache being allocated each time a module is loaded and unloaded, if the
2364 * module doesn't have persistent in-kernel storage across loads and unloads.
2366 * The cache must be empty before calling this function.
2368 * The caller must guarantee that noone will allocate memory from the cache
2369 * during the kmem_cache_destroy().
2371 int kmem_cache_destroy(struct kmem_cache *cachep)
2374 struct kmem_list3 *l3;
2376 BUG_ON(!cachep || in_interrupt());
2378 /* Don't let CPUs to come and go */
2381 /* Find the cache in the chain of caches. */
2382 mutex_lock(&cache_chain_mutex);
2384 * the chain is never empty, cache_cache is never destroyed
2386 list_del(&cachep->next);
2387 mutex_unlock(&cache_chain_mutex);
2389 if (__cache_shrink(cachep)) {
2390 slab_error(cachep, "Can't free all objects");
2391 mutex_lock(&cache_chain_mutex);
2392 list_add(&cachep->next, &cache_chain);
2393 mutex_unlock(&cache_chain_mutex);
2394 unlock_cpu_hotplug();
2398 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2401 for_each_online_cpu(i)
2402 kfree(cachep->array[i]);
2404 /* NUMA: free the list3 structures */
2405 for_each_online_node(i) {
2406 l3 = cachep->nodelists[i];
2409 free_alien_cache(l3->alien);
2413 kmem_cache_free(&cache_cache, cachep);
2414 unlock_cpu_hotplug();
2417 EXPORT_SYMBOL(kmem_cache_destroy);
2419 /* Get the memory for a slab management obj. */
2420 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2421 int colour_off, gfp_t local_flags,
2426 if (OFF_SLAB(cachep)) {
2427 /* Slab management obj is off-slab. */
2428 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2429 local_flags, nodeid);
2433 slabp = objp + colour_off;
2434 colour_off += cachep->slab_size;
2437 slabp->colouroff = colour_off;
2438 slabp->s_mem = objp + colour_off;
2439 slabp->nodeid = nodeid;
2443 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2445 return (kmem_bufctl_t *) (slabp + 1);
2448 static void cache_init_objs(struct kmem_cache *cachep,
2449 struct slab *slabp, unsigned long ctor_flags)
2453 for (i = 0; i < cachep->num; i++) {
2454 void *objp = index_to_obj(cachep, slabp, i);
2456 /* need to poison the objs? */
2457 if (cachep->flags & SLAB_POISON)
2458 poison_obj(cachep, objp, POISON_FREE);
2459 if (cachep->flags & SLAB_STORE_USER)
2460 *dbg_userword(cachep, objp) = NULL;
2462 if (cachep->flags & SLAB_RED_ZONE) {
2463 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2464 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2467 * Constructors are not allowed to allocate memory from the same
2468 * cache which they are a constructor for. Otherwise, deadlock.
2469 * They must also be threaded.
2471 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2472 cachep->ctor(objp + obj_offset(cachep), cachep,
2475 if (cachep->flags & SLAB_RED_ZONE) {
2476 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2477 slab_error(cachep, "constructor overwrote the"
2478 " end of an object");
2479 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2480 slab_error(cachep, "constructor overwrote the"
2481 " start of an object");
2483 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2484 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2485 kernel_map_pages(virt_to_page(objp),
2486 cachep->buffer_size / PAGE_SIZE, 0);
2489 cachep->ctor(objp, cachep, ctor_flags);
2491 slab_bufctl(slabp)[i] = i + 1;
2493 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2497 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2499 if (flags & SLAB_DMA)
2500 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2502 BUG_ON(cachep->gfpflags & GFP_DMA);
2505 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2508 void *objp = index_to_obj(cachep, slabp, slabp->free);
2512 next = slab_bufctl(slabp)[slabp->free];
2514 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2515 WARN_ON(slabp->nodeid != nodeid);
2522 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2523 void *objp, int nodeid)
2525 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2528 /* Verify that the slab belongs to the intended node */
2529 WARN_ON(slabp->nodeid != nodeid);
2531 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2532 printk(KERN_ERR "slab: double free detected in cache "
2533 "'%s', objp %p\n", cachep->name, objp);
2537 slab_bufctl(slabp)[objnr] = slabp->free;
2538 slabp->free = objnr;
2543 * Map pages beginning at addr to the given cache and slab. This is required
2544 * for the slab allocator to be able to lookup the cache and slab of a
2545 * virtual address for kfree, ksize, kmem_ptr_validate, and slab debugging.
2547 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2553 page = virt_to_page(addr);
2556 if (likely(!PageCompound(page)))
2557 nr_pages <<= cache->gfporder;
2560 page_set_cache(page, cache);
2561 page_set_slab(page, slab);
2563 } while (--nr_pages);
2567 * Grow (by 1) the number of slabs within a cache. This is called by
2568 * kmem_cache_alloc() when there are no active objs left in a cache.
2570 static int cache_grow(struct kmem_cache *cachep, gfp_t flags, int nodeid)
2576 unsigned long ctor_flags;
2577 struct kmem_list3 *l3;
2580 * Be lazy and only check for valid flags here, keeping it out of the
2581 * critical path in kmem_cache_alloc().
2583 BUG_ON(flags & ~(SLAB_DMA | SLAB_LEVEL_MASK | SLAB_NO_GROW));
2584 if (flags & SLAB_NO_GROW)
2587 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2588 local_flags = (flags & SLAB_LEVEL_MASK);
2589 if (!(local_flags & __GFP_WAIT))
2591 * Not allowed to sleep. Need to tell a constructor about
2592 * this - it might need to know...
2594 ctor_flags |= SLAB_CTOR_ATOMIC;
2596 /* Take the l3 list lock to change the colour_next on this node */
2598 l3 = cachep->nodelists[nodeid];
2599 spin_lock(&l3->list_lock);
2601 /* Get colour for the slab, and cal the next value. */
2602 offset = l3->colour_next;
2604 if (l3->colour_next >= cachep->colour)
2605 l3->colour_next = 0;
2606 spin_unlock(&l3->list_lock);
2608 offset *= cachep->colour_off;
2610 if (local_flags & __GFP_WAIT)
2614 * The test for missing atomic flag is performed here, rather than
2615 * the more obvious place, simply to reduce the critical path length
2616 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2617 * will eventually be caught here (where it matters).
2619 kmem_flagcheck(cachep, flags);
2622 * Get mem for the objs. Attempt to allocate a physical page from
2625 objp = kmem_getpages(cachep, flags, nodeid);
2629 /* Get slab management. */
2630 slabp = alloc_slabmgmt(cachep, objp, offset, local_flags, nodeid);
2634 slabp->nodeid = nodeid;
2635 slab_map_pages(cachep, slabp, objp);
2637 cache_init_objs(cachep, slabp, ctor_flags);
2639 if (local_flags & __GFP_WAIT)
2640 local_irq_disable();
2642 spin_lock(&l3->list_lock);
2644 /* Make slab active. */
2645 list_add_tail(&slabp->list, &(l3->slabs_free));
2646 STATS_INC_GROWN(cachep);
2647 l3->free_objects += cachep->num;
2648 spin_unlock(&l3->list_lock);
2651 kmem_freepages(cachep, objp);
2653 if (local_flags & __GFP_WAIT)
2654 local_irq_disable();
2661 * Perform extra freeing checks:
2662 * - detect bad pointers.
2663 * - POISON/RED_ZONE checking
2664 * - destructor calls, for caches with POISON+dtor
2666 static void kfree_debugcheck(const void *objp)
2670 if (!virt_addr_valid(objp)) {
2671 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2672 (unsigned long)objp);
2675 page = virt_to_page(objp);
2676 if (!PageSlab(page)) {
2677 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n",
2678 (unsigned long)objp);
2683 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2685 unsigned long redzone1, redzone2;
2687 redzone1 = *dbg_redzone1(cache, obj);
2688 redzone2 = *dbg_redzone2(cache, obj);
2693 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2696 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2697 slab_error(cache, "double free detected");
2699 slab_error(cache, "memory outside object was overwritten");
2701 printk(KERN_ERR "%p: redzone 1:0x%lx, redzone 2:0x%lx.\n",
2702 obj, redzone1, redzone2);
2705 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2712 objp -= obj_offset(cachep);
2713 kfree_debugcheck(objp);
2714 page = virt_to_page(objp);
2716 slabp = page_get_slab(page);
2718 if (cachep->flags & SLAB_RED_ZONE) {
2719 verify_redzone_free(cachep, objp);
2720 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2721 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2723 if (cachep->flags & SLAB_STORE_USER)
2724 *dbg_userword(cachep, objp) = caller;
2726 objnr = obj_to_index(cachep, slabp, objp);
2728 BUG_ON(objnr >= cachep->num);
2729 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2731 if (cachep->flags & SLAB_DEBUG_INITIAL) {
2733 * Need to call the slab's constructor so the caller can
2734 * perform a verify of its state (debugging). Called without
2735 * the cache-lock held.
2737 cachep->ctor(objp + obj_offset(cachep),
2738 cachep, SLAB_CTOR_CONSTRUCTOR | SLAB_CTOR_VERIFY);
2740 if (cachep->flags & SLAB_POISON && cachep->dtor) {
2741 /* we want to cache poison the object,
2742 * call the destruction callback
2744 cachep->dtor(objp + obj_offset(cachep), cachep, 0);
2746 #ifdef CONFIG_DEBUG_SLAB_LEAK
2747 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2749 if (cachep->flags & SLAB_POISON) {
2750 #ifdef CONFIG_DEBUG_PAGEALLOC
2751 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2752 store_stackinfo(cachep, objp, (unsigned long)caller);
2753 kernel_map_pages(virt_to_page(objp),
2754 cachep->buffer_size / PAGE_SIZE, 0);
2756 poison_obj(cachep, objp, POISON_FREE);
2759 poison_obj(cachep, objp, POISON_FREE);
2765 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
2770 /* Check slab's freelist to see if this obj is there. */
2771 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2773 if (entries > cachep->num || i >= cachep->num)
2776 if (entries != cachep->num - slabp->inuse) {
2778 printk(KERN_ERR "slab: Internal list corruption detected in "
2779 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2780 cachep->name, cachep->num, slabp, slabp->inuse);
2782 i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
2785 printk("\n%03x:", i);
2786 printk(" %02x", ((unsigned char *)slabp)[i]);
2793 #define kfree_debugcheck(x) do { } while(0)
2794 #define cache_free_debugcheck(x,objp,z) (objp)
2795 #define check_slabp(x,y) do { } while(0)
2798 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2801 struct kmem_list3 *l3;
2802 struct array_cache *ac;
2805 ac = cpu_cache_get(cachep);
2807 batchcount = ac->batchcount;
2808 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2810 * If there was little recent activity on this cache, then
2811 * perform only a partial refill. Otherwise we could generate
2814 batchcount = BATCHREFILL_LIMIT;
2816 l3 = cachep->nodelists[numa_node_id()];
2818 BUG_ON(ac->avail > 0 || !l3);
2819 spin_lock(&l3->list_lock);
2821 /* See if we can refill from the shared array */
2822 if (l3->shared && transfer_objects(ac, l3->shared, batchcount))
2825 while (batchcount > 0) {
2826 struct list_head *entry;
2828 /* Get slab alloc is to come from. */
2829 entry = l3->slabs_partial.next;
2830 if (entry == &l3->slabs_partial) {
2831 l3->free_touched = 1;
2832 entry = l3->slabs_free.next;
2833 if (entry == &l3->slabs_free)
2837 slabp = list_entry(entry, struct slab, list);
2838 check_slabp(cachep, slabp);
2839 check_spinlock_acquired(cachep);
2840 while (slabp->inuse < cachep->num && batchcount--) {
2841 STATS_INC_ALLOCED(cachep);
2842 STATS_INC_ACTIVE(cachep);
2843 STATS_SET_HIGH(cachep);
2845 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
2848 check_slabp(cachep, slabp);
2850 /* move slabp to correct slabp list: */
2851 list_del(&slabp->list);
2852 if (slabp->free == BUFCTL_END)
2853 list_add(&slabp->list, &l3->slabs_full);
2855 list_add(&slabp->list, &l3->slabs_partial);
2859 l3->free_objects -= ac->avail;
2861 spin_unlock(&l3->list_lock);
2863 if (unlikely(!ac->avail)) {
2865 x = cache_grow(cachep, flags, numa_node_id());
2867 /* cache_grow can reenable interrupts, then ac could change. */
2868 ac = cpu_cache_get(cachep);
2869 if (!x && ac->avail == 0) /* no objects in sight? abort */
2872 if (!ac->avail) /* objects refilled by interrupt? */
2876 return ac->entry[--ac->avail];
2879 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2882 might_sleep_if(flags & __GFP_WAIT);
2884 kmem_flagcheck(cachep, flags);
2889 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
2890 gfp_t flags, void *objp, void *caller)
2894 if (cachep->flags & SLAB_POISON) {
2895 #ifdef CONFIG_DEBUG_PAGEALLOC
2896 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2897 kernel_map_pages(virt_to_page(objp),
2898 cachep->buffer_size / PAGE_SIZE, 1);
2900 check_poison_obj(cachep, objp);
2902 check_poison_obj(cachep, objp);
2904 poison_obj(cachep, objp, POISON_INUSE);
2906 if (cachep->flags & SLAB_STORE_USER)
2907 *dbg_userword(cachep, objp) = caller;
2909 if (cachep->flags & SLAB_RED_ZONE) {
2910 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
2911 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2912 slab_error(cachep, "double free, or memory outside"
2913 " object was overwritten");
2915 "%p: redzone 1:0x%lx, redzone 2:0x%lx\n",
2916 objp, *dbg_redzone1(cachep, objp),
2917 *dbg_redzone2(cachep, objp));
2919 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2920 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2922 #ifdef CONFIG_DEBUG_SLAB_LEAK
2927 slabp = page_get_slab(virt_to_page(objp));
2928 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
2929 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
2932 objp += obj_offset(cachep);
2933 if (cachep->ctor && cachep->flags & SLAB_POISON) {
2934 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2936 if (!(flags & __GFP_WAIT))
2937 ctor_flags |= SLAB_CTOR_ATOMIC;
2939 cachep->ctor(objp, cachep, ctor_flags);
2944 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2947 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
2950 struct array_cache *ac;
2953 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
2954 objp = alternate_node_alloc(cachep, flags);
2961 ac = cpu_cache_get(cachep);
2962 if (likely(ac->avail)) {
2963 STATS_INC_ALLOCHIT(cachep);
2965 objp = ac->entry[--ac->avail];
2967 STATS_INC_ALLOCMISS(cachep);
2968 objp = cache_alloc_refill(cachep, flags);
2973 static __always_inline void *__cache_alloc(struct kmem_cache *cachep,
2974 gfp_t flags, void *caller)
2976 unsigned long save_flags;
2979 cache_alloc_debugcheck_before(cachep, flags);
2981 local_irq_save(save_flags);
2982 objp = ____cache_alloc(cachep, flags);
2983 local_irq_restore(save_flags);
2984 objp = cache_alloc_debugcheck_after(cachep, flags, objp,
2992 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
2994 * If we are in_interrupt, then process context, including cpusets and
2995 * mempolicy, may not apply and should not be used for allocation policy.
2997 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
2999 int nid_alloc, nid_here;
3003 nid_alloc = nid_here = numa_node_id();
3004 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3005 nid_alloc = cpuset_mem_spread_node();
3006 else if (current->mempolicy)
3007 nid_alloc = slab_node(current->mempolicy);
3008 if (nid_alloc != nid_here)
3009 return __cache_alloc_node(cachep, flags, nid_alloc);
3014 * A interface to enable slab creation on nodeid
3016 static void *__cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3019 struct list_head *entry;
3021 struct kmem_list3 *l3;
3025 l3 = cachep->nodelists[nodeid];
3030 spin_lock(&l3->list_lock);
3031 entry = l3->slabs_partial.next;
3032 if (entry == &l3->slabs_partial) {
3033 l3->free_touched = 1;
3034 entry = l3->slabs_free.next;
3035 if (entry == &l3->slabs_free)
3039 slabp = list_entry(entry, struct slab, list);
3040 check_spinlock_acquired_node(cachep, nodeid);
3041 check_slabp(cachep, slabp);
3043 STATS_INC_NODEALLOCS(cachep);
3044 STATS_INC_ACTIVE(cachep);
3045 STATS_SET_HIGH(cachep);
3047 BUG_ON(slabp->inuse == cachep->num);
3049 obj = slab_get_obj(cachep, slabp, nodeid);
3050 check_slabp(cachep, slabp);
3052 /* move slabp to correct slabp list: */
3053 list_del(&slabp->list);
3055 if (slabp->free == BUFCTL_END)
3056 list_add(&slabp->list, &l3->slabs_full);
3058 list_add(&slabp->list, &l3->slabs_partial);
3060 spin_unlock(&l3->list_lock);
3064 spin_unlock(&l3->list_lock);
3065 x = cache_grow(cachep, flags, nodeid);
3077 * Caller needs to acquire correct kmem_list's list_lock
3079 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3083 struct kmem_list3 *l3;
3085 for (i = 0; i < nr_objects; i++) {
3086 void *objp = objpp[i];
3089 slabp = virt_to_slab(objp);
3090 l3 = cachep->nodelists[node];
3091 list_del(&slabp->list);
3092 check_spinlock_acquired_node(cachep, node);
3093 check_slabp(cachep, slabp);
3094 slab_put_obj(cachep, slabp, objp, node);
3095 STATS_DEC_ACTIVE(cachep);
3097 check_slabp(cachep, slabp);
3099 /* fixup slab chains */
3100 if (slabp->inuse == 0) {
3101 if (l3->free_objects > l3->free_limit) {
3102 l3->free_objects -= cachep->num;
3104 * It is safe to drop the lock. The slab is
3105 * no longer linked to the cache. cachep
3106 * cannot disappear - we are using it and
3107 * all destruction of caches must be
3108 * serialized properly by the user.
3110 spin_unlock(&l3->list_lock);
3111 slab_destroy(cachep, slabp);
3112 spin_lock(&l3->list_lock);
3114 list_add(&slabp->list, &l3->slabs_free);
3117 /* Unconditionally move a slab to the end of the
3118 * partial list on free - maximum time for the
3119 * other objects to be freed, too.
3121 list_add_tail(&slabp->list, &l3->slabs_partial);
3126 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3129 struct kmem_list3 *l3;
3130 int node = numa_node_id();
3132 batchcount = ac->batchcount;
3134 BUG_ON(!batchcount || batchcount > ac->avail);
3137 l3 = cachep->nodelists[node];
3138 spin_lock_nested(&l3->list_lock, SINGLE_DEPTH_NESTING);
3140 struct array_cache *shared_array = l3->shared;
3141 int max = shared_array->limit - shared_array->avail;
3143 if (batchcount > max)
3145 memcpy(&(shared_array->entry[shared_array->avail]),
3146 ac->entry, sizeof(void *) * batchcount);
3147 shared_array->avail += batchcount;
3152 free_block(cachep, ac->entry, batchcount, node);
3157 struct list_head *p;
3159 p = l3->slabs_free.next;
3160 while (p != &(l3->slabs_free)) {
3163 slabp = list_entry(p, struct slab, list);
3164 BUG_ON(slabp->inuse);
3169 STATS_SET_FREEABLE(cachep, i);
3172 spin_unlock(&l3->list_lock);
3173 ac->avail -= batchcount;
3174 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3178 * Release an obj back to its cache. If the obj has a constructed state, it must
3179 * be in this state _before_ it is released. Called with disabled ints.
3181 static void __cache_free(struct kmem_cache *cachep, void *objp, int nesting)
3183 struct array_cache *ac = cpu_cache_get(cachep);
3186 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3188 if (cache_free_alien(cachep, objp, nesting))
3191 if (likely(ac->avail < ac->limit)) {
3192 STATS_INC_FREEHIT(cachep);
3193 ac->entry[ac->avail++] = objp;
3196 STATS_INC_FREEMISS(cachep);
3197 cache_flusharray(cachep, ac);
3198 ac->entry[ac->avail++] = objp;
3203 * kmem_cache_alloc - Allocate an object
3204 * @cachep: The cache to allocate from.
3205 * @flags: See kmalloc().
3207 * Allocate an object from this cache. The flags are only relevant
3208 * if the cache has no available objects.
3210 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3212 return __cache_alloc(cachep, flags, __builtin_return_address(0));
3214 EXPORT_SYMBOL(kmem_cache_alloc);
3217 * kmem_cache_alloc - Allocate an object. The memory is set to zero.
3218 * @cache: The cache to allocate from.
3219 * @flags: See kmalloc().
3221 * Allocate an object from this cache and set the allocated memory to zero.
3222 * The flags are only relevant if the cache has no available objects.
3224 void *kmem_cache_zalloc(struct kmem_cache *cache, gfp_t flags)
3226 void *ret = __cache_alloc(cache, flags, __builtin_return_address(0));
3228 memset(ret, 0, obj_size(cache));
3231 EXPORT_SYMBOL(kmem_cache_zalloc);
3234 * kmem_ptr_validate - check if an untrusted pointer might
3236 * @cachep: the cache we're checking against
3237 * @ptr: pointer to validate
3239 * This verifies that the untrusted pointer looks sane:
3240 * it is _not_ a guarantee that the pointer is actually
3241 * part of the slab cache in question, but it at least
3242 * validates that the pointer can be dereferenced and
3243 * looks half-way sane.
3245 * Currently only used for dentry validation.
3247 int fastcall kmem_ptr_validate(struct kmem_cache *cachep, void *ptr)
3249 unsigned long addr = (unsigned long)ptr;
3250 unsigned long min_addr = PAGE_OFFSET;
3251 unsigned long align_mask = BYTES_PER_WORD - 1;
3252 unsigned long size = cachep->buffer_size;
3255 if (unlikely(addr < min_addr))
3257 if (unlikely(addr > (unsigned long)high_memory - size))
3259 if (unlikely(addr & align_mask))
3261 if (unlikely(!kern_addr_valid(addr)))
3263 if (unlikely(!kern_addr_valid(addr + size - 1)))
3265 page = virt_to_page(ptr);
3266 if (unlikely(!PageSlab(page)))
3268 if (unlikely(page_get_cache(page) != cachep))
3277 * kmem_cache_alloc_node - Allocate an object on the specified node
3278 * @cachep: The cache to allocate from.
3279 * @flags: See kmalloc().
3280 * @nodeid: node number of the target node.
3282 * Identical to kmem_cache_alloc, except that this function is slow
3283 * and can sleep. And it will allocate memory on the given node, which
3284 * can improve the performance for cpu bound structures.
3285 * New and improved: it will now make sure that the object gets
3286 * put on the correct node list so that there is no false sharing.
3288 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3290 unsigned long save_flags;
3293 cache_alloc_debugcheck_before(cachep, flags);
3294 local_irq_save(save_flags);
3296 if (nodeid == -1 || nodeid == numa_node_id() ||
3297 !cachep->nodelists[nodeid])
3298 ptr = ____cache_alloc(cachep, flags);
3300 ptr = __cache_alloc_node(cachep, flags, nodeid);
3301 local_irq_restore(save_flags);
3303 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr,
3304 __builtin_return_address(0));
3308 EXPORT_SYMBOL(kmem_cache_alloc_node);
3310 void *kmalloc_node(size_t size, gfp_t flags, int node)
3312 struct kmem_cache *cachep;
3314 cachep = kmem_find_general_cachep(size, flags);
3315 if (unlikely(cachep == NULL))
3317 return kmem_cache_alloc_node(cachep, flags, node);
3319 EXPORT_SYMBOL(kmalloc_node);
3323 * __do_kmalloc - allocate memory
3324 * @size: how many bytes of memory are required.
3325 * @flags: the type of memory to allocate (see kmalloc).
3326 * @caller: function caller for debug tracking of the caller
3328 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3331 struct kmem_cache *cachep;
3333 /* If you want to save a few bytes .text space: replace
3335 * Then kmalloc uses the uninlined functions instead of the inline
3338 cachep = __find_general_cachep(size, flags);
3339 if (unlikely(cachep == NULL))
3341 return __cache_alloc(cachep, flags, caller);
3345 void *__kmalloc(size_t size, gfp_t flags)
3347 #ifndef CONFIG_DEBUG_SLAB
3348 return __do_kmalloc(size, flags, NULL);
3350 return __do_kmalloc(size, flags, __builtin_return_address(0));
3353 EXPORT_SYMBOL(__kmalloc);
3355 #ifdef CONFIG_DEBUG_SLAB
3356 void *__kmalloc_track_caller(size_t size, gfp_t flags, void *caller)
3358 return __do_kmalloc(size, flags, caller);
3360 EXPORT_SYMBOL(__kmalloc_track_caller);
3365 * __alloc_percpu - allocate one copy of the object for every present
3366 * cpu in the system, zeroing them.
3367 * Objects should be dereferenced using the per_cpu_ptr macro only.
3369 * @size: how many bytes of memory are required.
3371 void *__alloc_percpu(size_t size)
3374 struct percpu_data *pdata = kmalloc(sizeof(*pdata), GFP_KERNEL);
3380 * Cannot use for_each_online_cpu since a cpu may come online
3381 * and we have no way of figuring out how to fix the array
3382 * that we have allocated then....
3384 for_each_possible_cpu(i) {
3385 int node = cpu_to_node(i);
3387 if (node_online(node))
3388 pdata->ptrs[i] = kmalloc_node(size, GFP_KERNEL, node);
3390 pdata->ptrs[i] = kmalloc(size, GFP_KERNEL);
3392 if (!pdata->ptrs[i])
3394 memset(pdata->ptrs[i], 0, size);
3397 /* Catch derefs w/o wrappers */
3398 return (void *)(~(unsigned long)pdata);
3402 if (!cpu_possible(i))
3404 kfree(pdata->ptrs[i]);
3409 EXPORT_SYMBOL(__alloc_percpu);
3413 * kmem_cache_free - Deallocate an object
3414 * @cachep: The cache the allocation was from.
3415 * @objp: The previously allocated object.
3417 * Free an object which was previously allocated from this
3420 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3422 unsigned long flags;
3424 BUG_ON(virt_to_cache(objp) != cachep);
3426 local_irq_save(flags);
3427 __cache_free(cachep, objp, 0);
3428 local_irq_restore(flags);
3430 EXPORT_SYMBOL(kmem_cache_free);
3433 * kfree - free previously allocated memory
3434 * @objp: pointer returned by kmalloc.
3436 * If @objp is NULL, no operation is performed.
3438 * Don't free memory not originally allocated by kmalloc()
3439 * or you will run into trouble.
3441 void kfree(const void *objp)
3443 struct kmem_cache *c;
3444 unsigned long flags;
3446 if (unlikely(!objp))
3448 local_irq_save(flags);
3449 kfree_debugcheck(objp);
3450 c = virt_to_cache(objp);
3451 debug_check_no_locks_freed(objp, obj_size(c));
3452 __cache_free(c, (void *)objp, 0);
3453 local_irq_restore(flags);
3455 EXPORT_SYMBOL(kfree);
3459 * free_percpu - free previously allocated percpu memory
3460 * @objp: pointer returned by alloc_percpu.
3462 * Don't free memory not originally allocated by alloc_percpu()
3463 * The complemented objp is to check for that.
3465 void free_percpu(const void *objp)
3468 struct percpu_data *p = (struct percpu_data *)(~(unsigned long)objp);
3471 * We allocate for all cpus so we cannot use for online cpu here.
3473 for_each_possible_cpu(i)
3477 EXPORT_SYMBOL(free_percpu);
3480 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3482 return obj_size(cachep);
3484 EXPORT_SYMBOL(kmem_cache_size);
3486 const char *kmem_cache_name(struct kmem_cache *cachep)
3488 return cachep->name;
3490 EXPORT_SYMBOL_GPL(kmem_cache_name);
3493 * This initializes kmem_list3 or resizes varioius caches for all nodes.
3495 static int alloc_kmemlist(struct kmem_cache *cachep)
3498 struct kmem_list3 *l3;
3499 struct array_cache *new_shared;
3500 struct array_cache **new_alien;
3502 for_each_online_node(node) {
3504 new_alien = alloc_alien_cache(node, cachep->limit);
3508 new_shared = alloc_arraycache(node,
3509 cachep->shared*cachep->batchcount,
3512 free_alien_cache(new_alien);
3516 l3 = cachep->nodelists[node];
3518 struct array_cache *shared = l3->shared;
3520 spin_lock_irq(&l3->list_lock);
3523 free_block(cachep, shared->entry,
3524 shared->avail, node);
3526 l3->shared = new_shared;
3528 l3->alien = new_alien;
3531 l3->free_limit = (1 + nr_cpus_node(node)) *
3532 cachep->batchcount + cachep->num;
3533 spin_unlock_irq(&l3->list_lock);
3535 free_alien_cache(new_alien);
3538 l3 = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, node);
3540 free_alien_cache(new_alien);
3545 kmem_list3_init(l3);
3546 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3547 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3548 l3->shared = new_shared;
3549 l3->alien = new_alien;
3550 l3->free_limit = (1 + nr_cpus_node(node)) *
3551 cachep->batchcount + cachep->num;
3552 cachep->nodelists[node] = l3;
3557 if (!cachep->next.next) {
3558 /* Cache is not active yet. Roll back what we did */
3561 if (cachep->nodelists[node]) {
3562 l3 = cachep->nodelists[node];
3565 free_alien_cache(l3->alien);
3567 cachep->nodelists[node] = NULL;
3575 struct ccupdate_struct {
3576 struct kmem_cache *cachep;
3577 struct array_cache *new[NR_CPUS];
3580 static void do_ccupdate_local(void *info)
3582 struct ccupdate_struct *new = info;
3583 struct array_cache *old;
3586 old = cpu_cache_get(new->cachep);
3588 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3589 new->new[smp_processor_id()] = old;
3592 /* Always called with the cache_chain_mutex held */
3593 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3594 int batchcount, int shared)
3596 struct ccupdate_struct new;
3599 memset(&new.new, 0, sizeof(new.new));
3600 for_each_online_cpu(i) {
3601 new.new[i] = alloc_arraycache(cpu_to_node(i), limit,
3604 for (i--; i >= 0; i--)
3609 new.cachep = cachep;
3611 on_each_cpu(do_ccupdate_local, (void *)&new, 1, 1);
3614 cachep->batchcount = batchcount;
3615 cachep->limit = limit;
3616 cachep->shared = shared;
3618 for_each_online_cpu(i) {
3619 struct array_cache *ccold = new.new[i];
3622 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3623 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
3624 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3628 err = alloc_kmemlist(cachep);
3630 printk(KERN_ERR "alloc_kmemlist failed for %s, error %d.\n",
3631 cachep->name, -err);
3637 /* Called with cache_chain_mutex held always */
3638 static void enable_cpucache(struct kmem_cache *cachep)
3644 * The head array serves three purposes:
3645 * - create a LIFO ordering, i.e. return objects that are cache-warm
3646 * - reduce the number of spinlock operations.
3647 * - reduce the number of linked list operations on the slab and
3648 * bufctl chains: array operations are cheaper.
3649 * The numbers are guessed, we should auto-tune as described by
3652 if (cachep->buffer_size > 131072)
3654 else if (cachep->buffer_size > PAGE_SIZE)
3656 else if (cachep->buffer_size > 1024)
3658 else if (cachep->buffer_size > 256)
3664 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3665 * allocation behaviour: Most allocs on one cpu, most free operations
3666 * on another cpu. For these cases, an efficient object passing between
3667 * cpus is necessary. This is provided by a shared array. The array
3668 * replaces Bonwick's magazine layer.
3669 * On uniprocessor, it's functionally equivalent (but less efficient)
3670 * to a larger limit. Thus disabled by default.
3674 if (cachep->buffer_size <= PAGE_SIZE)
3680 * With debugging enabled, large batchcount lead to excessively long
3681 * periods with disabled local interrupts. Limit the batchcount
3686 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared);
3688 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3689 cachep->name, -err);
3693 * Drain an array if it contains any elements taking the l3 lock only if
3694 * necessary. Note that the l3 listlock also protects the array_cache
3695 * if drain_array() is used on the shared array.
3697 void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
3698 struct array_cache *ac, int force, int node)
3702 if (!ac || !ac->avail)
3704 if (ac->touched && !force) {
3707 spin_lock_irq(&l3->list_lock);
3709 tofree = force ? ac->avail : (ac->limit + 4) / 5;
3710 if (tofree > ac->avail)
3711 tofree = (ac->avail + 1) / 2;
3712 free_block(cachep, ac->entry, tofree, node);
3713 ac->avail -= tofree;
3714 memmove(ac->entry, &(ac->entry[tofree]),
3715 sizeof(void *) * ac->avail);
3717 spin_unlock_irq(&l3->list_lock);
3722 * cache_reap - Reclaim memory from caches.
3723 * @unused: unused parameter
3725 * Called from workqueue/eventd every few seconds.
3727 * - clear the per-cpu caches for this CPU.
3728 * - return freeable pages to the main free memory pool.
3730 * If we cannot acquire the cache chain mutex then just give up - we'll try
3731 * again on the next iteration.
3733 static void cache_reap(void *unused)
3735 struct kmem_cache *searchp;
3736 struct kmem_list3 *l3;
3737 int node = numa_node_id();
3739 if (!mutex_trylock(&cache_chain_mutex)) {
3740 /* Give up. Setup the next iteration. */
3741 schedule_delayed_work(&__get_cpu_var(reap_work),
3746 list_for_each_entry(searchp, &cache_chain, next) {
3750 * We only take the l3 lock if absolutely necessary and we
3751 * have established with reasonable certainty that
3752 * we can do some work if the lock was obtained.
3754 l3 = searchp->nodelists[node];
3756 reap_alien(searchp, l3);
3758 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
3761 * These are racy checks but it does not matter
3762 * if we skip one check or scan twice.
3764 if (time_after(l3->next_reap, jiffies))
3767 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
3769 drain_array(searchp, l3, l3->shared, 0, node);
3771 if (l3->free_touched)
3772 l3->free_touched = 0;
3776 freed = drain_freelist(searchp, l3, (l3->free_limit +
3777 5 * searchp->num - 1) / (5 * searchp->num));
3778 STATS_ADD_REAPED(searchp, freed);
3784 mutex_unlock(&cache_chain_mutex);
3786 refresh_cpu_vm_stats(smp_processor_id());
3787 /* Set up the next iteration */
3788 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC);
3791 #ifdef CONFIG_PROC_FS
3793 static void print_slabinfo_header(struct seq_file *m)
3796 * Output format version, so at least we can change it
3797 * without _too_ many complaints.
3800 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
3802 seq_puts(m, "slabinfo - version: 2.1\n");
3804 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
3805 "<objperslab> <pagesperslab>");
3806 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
3807 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
3809 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
3810 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
3811 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
3816 static void *s_start(struct seq_file *m, loff_t *pos)
3819 struct list_head *p;
3821 mutex_lock(&cache_chain_mutex);
3823 print_slabinfo_header(m);
3824 p = cache_chain.next;
3827 if (p == &cache_chain)
3830 return list_entry(p, struct kmem_cache, next);
3833 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3835 struct kmem_cache *cachep = p;
3837 return cachep->next.next == &cache_chain ?
3838 NULL : list_entry(cachep->next.next, struct kmem_cache, next);
3841 static void s_stop(struct seq_file *m, void *p)
3843 mutex_unlock(&cache_chain_mutex);
3846 static int s_show(struct seq_file *m, void *p)
3848 struct kmem_cache *cachep = p;
3850 unsigned long active_objs;
3851 unsigned long num_objs;
3852 unsigned long active_slabs = 0;
3853 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
3857 struct kmem_list3 *l3;
3861 for_each_online_node(node) {
3862 l3 = cachep->nodelists[node];
3867 spin_lock_irq(&l3->list_lock);
3869 list_for_each_entry(slabp, &l3->slabs_full, list) {
3870 if (slabp->inuse != cachep->num && !error)
3871 error = "slabs_full accounting error";
3872 active_objs += cachep->num;
3875 list_for_each_entry(slabp, &l3->slabs_partial, list) {
3876 if (slabp->inuse == cachep->num && !error)
3877 error = "slabs_partial inuse accounting error";
3878 if (!slabp->inuse && !error)
3879 error = "slabs_partial/inuse accounting error";
3880 active_objs += slabp->inuse;
3883 list_for_each_entry(slabp, &l3->slabs_free, list) {
3884 if (slabp->inuse && !error)
3885 error = "slabs_free/inuse accounting error";
3888 free_objects += l3->free_objects;
3890 shared_avail += l3->shared->avail;
3892 spin_unlock_irq(&l3->list_lock);
3894 num_slabs += active_slabs;
3895 num_objs = num_slabs * cachep->num;
3896 if (num_objs - active_objs != free_objects && !error)
3897 error = "free_objects accounting error";
3899 name = cachep->name;
3901 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3903 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
3904 name, active_objs, num_objs, cachep->buffer_size,
3905 cachep->num, (1 << cachep->gfporder));
3906 seq_printf(m, " : tunables %4u %4u %4u",
3907 cachep->limit, cachep->batchcount, cachep->shared);
3908 seq_printf(m, " : slabdata %6lu %6lu %6lu",
3909 active_slabs, num_slabs, shared_avail);
3912 unsigned long high = cachep->high_mark;
3913 unsigned long allocs = cachep->num_allocations;
3914 unsigned long grown = cachep->grown;
3915 unsigned long reaped = cachep->reaped;
3916 unsigned long errors = cachep->errors;
3917 unsigned long max_freeable = cachep->max_freeable;
3918 unsigned long node_allocs = cachep->node_allocs;
3919 unsigned long node_frees = cachep->node_frees;
3920 unsigned long overflows = cachep->node_overflow;
3922 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
3923 %4lu %4lu %4lu %4lu %4lu", allocs, high, grown,
3924 reaped, errors, max_freeable, node_allocs,
3925 node_frees, overflows);
3929 unsigned long allochit = atomic_read(&cachep->allochit);
3930 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
3931 unsigned long freehit = atomic_read(&cachep->freehit);
3932 unsigned long freemiss = atomic_read(&cachep->freemiss);
3934 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
3935 allochit, allocmiss, freehit, freemiss);
3943 * slabinfo_op - iterator that generates /proc/slabinfo
3952 * num-pages-per-slab
3953 * + further values on SMP and with statistics enabled
3956 struct seq_operations slabinfo_op = {
3963 #define MAX_SLABINFO_WRITE 128
3965 * slabinfo_write - Tuning for the slab allocator
3967 * @buffer: user buffer
3968 * @count: data length
3971 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
3972 size_t count, loff_t *ppos)
3974 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
3975 int limit, batchcount, shared, res;
3976 struct kmem_cache *cachep;
3978 if (count > MAX_SLABINFO_WRITE)
3980 if (copy_from_user(&kbuf, buffer, count))
3982 kbuf[MAX_SLABINFO_WRITE] = '\0';
3984 tmp = strchr(kbuf, ' ');
3989 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3992 /* Find the cache in the chain of caches. */
3993 mutex_lock(&cache_chain_mutex);
3995 list_for_each_entry(cachep, &cache_chain, next) {
3996 if (!strcmp(cachep->name, kbuf)) {
3997 if (limit < 1 || batchcount < 1 ||
3998 batchcount > limit || shared < 0) {
4001 res = do_tune_cpucache(cachep, limit,
4002 batchcount, shared);
4007 mutex_unlock(&cache_chain_mutex);
4013 #ifdef CONFIG_DEBUG_SLAB_LEAK
4015 static void *leaks_start(struct seq_file *m, loff_t *pos)
4018 struct list_head *p;
4020 mutex_lock(&cache_chain_mutex);
4021 p = cache_chain.next;
4024 if (p == &cache_chain)
4027 return list_entry(p, struct kmem_cache, next);
4030 static inline int add_caller(unsigned long *n, unsigned long v)
4040 unsigned long *q = p + 2 * i;
4054 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4060 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4066 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4067 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4069 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4074 static void show_symbol(struct seq_file *m, unsigned long address)
4076 #ifdef CONFIG_KALLSYMS
4079 unsigned long offset, size;
4080 char namebuf[KSYM_NAME_LEN+1];
4082 name = kallsyms_lookup(address, &size, &offset, &modname, namebuf);
4085 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4087 seq_printf(m, " [%s]", modname);
4091 seq_printf(m, "%p", (void *)address);
4094 static int leaks_show(struct seq_file *m, void *p)
4096 struct kmem_cache *cachep = p;
4098 struct kmem_list3 *l3;
4100 unsigned long *n = m->private;
4104 if (!(cachep->flags & SLAB_STORE_USER))
4106 if (!(cachep->flags & SLAB_RED_ZONE))
4109 /* OK, we can do it */
4113 for_each_online_node(node) {
4114 l3 = cachep->nodelists[node];
4119 spin_lock_irq(&l3->list_lock);
4121 list_for_each_entry(slabp, &l3->slabs_full, list)
4122 handle_slab(n, cachep, slabp);
4123 list_for_each_entry(slabp, &l3->slabs_partial, list)
4124 handle_slab(n, cachep, slabp);
4125 spin_unlock_irq(&l3->list_lock);
4127 name = cachep->name;
4129 /* Increase the buffer size */
4130 mutex_unlock(&cache_chain_mutex);
4131 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4133 /* Too bad, we are really out */
4135 mutex_lock(&cache_chain_mutex);
4138 *(unsigned long *)m->private = n[0] * 2;
4140 mutex_lock(&cache_chain_mutex);
4141 /* Now make sure this entry will be retried */
4145 for (i = 0; i < n[1]; i++) {
4146 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4147 show_symbol(m, n[2*i+2]);
4153 struct seq_operations slabstats_op = {
4154 .start = leaks_start,
4163 * ksize - get the actual amount of memory allocated for a given object
4164 * @objp: Pointer to the object
4166 * kmalloc may internally round up allocations and return more memory
4167 * than requested. ksize() can be used to determine the actual amount of
4168 * memory allocated. The caller may use this additional memory, even though
4169 * a smaller amount of memory was initially specified with the kmalloc call.
4170 * The caller must guarantee that objp points to a valid object previously
4171 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4172 * must not be freed during the duration of the call.
4174 unsigned int ksize(const void *objp)
4176 if (unlikely(objp == NULL))
4179 return obj_size(virt_to_cache(objp));