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 initializations 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/slab.h>
91 #include <linux/poison.h>
92 #include <linux/swap.h>
93 #include <linux/cache.h>
94 #include <linux/interrupt.h>
95 #include <linux/init.h>
96 #include <linux/compiler.h>
97 #include <linux/cpuset.h>
98 #include <linux/proc_fs.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/kmemtrace.h>
106 #include <linux/rcupdate.h>
107 #include <linux/string.h>
108 #include <linux/uaccess.h>
109 #include <linux/nodemask.h>
110 #include <linux/kmemleak.h>
111 #include <linux/mempolicy.h>
112 #include <linux/mutex.h>
113 #include <linux/fault-inject.h>
114 #include <linux/rtmutex.h>
115 #include <linux/reciprocal_div.h>
116 #include <linux/debugobjects.h>
117 #include <linux/kmemcheck.h>
119 #include <asm/cacheflush.h>
120 #include <asm/tlbflush.h>
121 #include <asm/page.h>
123 #include "internal.h"
126 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
127 * 0 for faster, smaller code (especially in the critical paths).
129 * STATS - 1 to collect stats for /proc/slabinfo.
130 * 0 for faster, smaller code (especially in the critical paths).
132 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
135 #ifdef CONFIG_DEBUG_SLAB
138 #define FORCED_DEBUG 1
142 #define FORCED_DEBUG 0
145 /* Shouldn't this be in a header file somewhere? */
146 #define BYTES_PER_WORD sizeof(void *)
147 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
149 #ifndef ARCH_KMALLOC_MINALIGN
151 * Enforce a minimum alignment for the kmalloc caches.
152 * Usually, the kmalloc caches are cache_line_size() aligned, except when
153 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
154 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
155 * alignment larger than the alignment of a 64-bit integer.
156 * ARCH_KMALLOC_MINALIGN allows that.
157 * Note that increasing this value may disable some debug features.
159 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
162 #ifndef ARCH_SLAB_MINALIGN
164 * Enforce a minimum alignment for all caches.
165 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
166 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
167 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
168 * some debug features.
170 #define ARCH_SLAB_MINALIGN 0
173 #ifndef ARCH_KMALLOC_FLAGS
174 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
177 /* Legal flag mask for kmem_cache_create(). */
179 # define CREATE_MASK (SLAB_RED_ZONE | \
180 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
183 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
184 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
185 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE | SLAB_NOTRACK)
187 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
189 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
190 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
191 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE | SLAB_NOTRACK)
197 * Bufctl's are used for linking objs within a slab
200 * This implementation relies on "struct page" for locating the cache &
201 * slab an object belongs to.
202 * This allows the bufctl structure to be small (one int), but limits
203 * the number of objects a slab (not a cache) can contain when off-slab
204 * bufctls are used. The limit is the size of the largest general cache
205 * that does not use off-slab slabs.
206 * For 32bit archs with 4 kB pages, is this 56.
207 * This is not serious, as it is only for large objects, when it is unwise
208 * to have too many per slab.
209 * Note: This limit can be raised by introducing a general cache whose size
210 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
213 typedef unsigned int kmem_bufctl_t;
214 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
215 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
216 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
217 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
222 * Manages the objs in a slab. Placed either at the beginning of mem allocated
223 * for a slab, or allocated from an general cache.
224 * Slabs are chained into three list: fully used, partial, fully free slabs.
227 struct list_head list;
228 unsigned long colouroff;
229 void *s_mem; /* including colour offset */
230 unsigned int inuse; /* num of objs active in slab */
232 unsigned short nodeid;
238 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
239 * arrange for kmem_freepages to be called via RCU. This is useful if
240 * we need to approach a kernel structure obliquely, from its address
241 * obtained without the usual locking. We can lock the structure to
242 * stabilize it and check it's still at the given address, only if we
243 * can be sure that the memory has not been meanwhile reused for some
244 * other kind of object (which our subsystem's lock might corrupt).
246 * rcu_read_lock before reading the address, then rcu_read_unlock after
247 * taking the spinlock within the structure expected at that address.
249 * We assume struct slab_rcu can overlay struct slab when destroying.
252 struct rcu_head head;
253 struct kmem_cache *cachep;
261 * - LIFO ordering, to hand out cache-warm objects from _alloc
262 * - reduce the number of linked list operations
263 * - reduce spinlock operations
265 * The limit is stored in the per-cpu structure to reduce the data cache
272 unsigned int batchcount;
273 unsigned int touched:1,
277 * Must have this definition in here for the proper
278 * alignment of array_cache. Also simplifies accessing
284 * bootstrap: The caches do not work without cpuarrays anymore, but the
285 * cpuarrays are allocated from the generic caches...
287 #define BOOT_CPUCACHE_ENTRIES 1
288 struct arraycache_init {
289 struct array_cache cache;
290 void *entries[BOOT_CPUCACHE_ENTRIES];
294 * The slab lists for all objects.
297 struct list_head slabs_partial; /* partial list first, better asm code */
298 struct list_head slabs_full;
299 struct list_head slabs_free;
300 unsigned long free_objects;
301 unsigned int free_limit;
302 unsigned int colour_next; /* Per-node cache coloring */
303 spinlock_t list_lock;
304 struct array_cache *shared; /* shared per node */
305 struct array_cache **alien; /* on other nodes */
306 unsigned long next_reap; /* updated without locking */
307 int free_touched; /* updated without locking */
308 } __attribute__((aligned(sizeof(long))));
311 * Need this for bootstrapping a per node allocator.
313 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
314 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
315 #define CACHE_CACHE 0
316 #define SIZE_AC MAX_NUMNODES
317 #define SIZE_L3 (2 * MAX_NUMNODES)
319 static int drain_freelist(struct kmem_cache *cache,
320 struct kmem_list3 *l3, int tofree);
321 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
323 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
324 static void cache_reap(struct work_struct *unused);
327 * This function must be completely optimized away if a constant is passed to
328 * it. Mostly the same as what is in linux/slab.h except it returns an index.
330 static __always_inline int index_of(const size_t size)
332 extern void __bad_size(void);
334 if (__builtin_constant_p(size)) {
342 #include <linux/kmalloc_sizes.h>
350 static int slab_early_init = 1;
352 #define INDEX_AC index_of(sizeof(struct arraycache_init))
353 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
355 static void kmem_list3_init(struct kmem_list3 *parent)
357 INIT_LIST_HEAD(&parent->slabs_full);
358 INIT_LIST_HEAD(&parent->slabs_partial);
359 INIT_LIST_HEAD(&parent->slabs_free);
360 parent->shared = NULL;
361 parent->alien = NULL;
362 parent->colour_next = 0;
363 spin_lock_init(&parent->list_lock);
364 parent->free_objects = 0;
365 parent->free_touched = 0;
368 #define MAKE_LIST(cachep, listp, slab, nodeid) \
370 INIT_LIST_HEAD(listp); \
371 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
374 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
376 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
377 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
378 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
381 #define CFLGS_OFF_SLAB (0x80000000UL)
382 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
384 #define BATCHREFILL_LIMIT 16
386 * Optimization question: fewer reaps means less probability for unnessary
387 * cpucache drain/refill cycles.
389 * OTOH the cpuarrays can contain lots of objects,
390 * which could lock up otherwise freeable slabs.
392 #define REAPTIMEOUT_CPUC (2*HZ)
393 #define REAPTIMEOUT_LIST3 (4*HZ)
396 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
397 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
398 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
399 #define STATS_INC_GROWN(x) ((x)->grown++)
400 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
401 #define STATS_SET_HIGH(x) \
403 if ((x)->num_active > (x)->high_mark) \
404 (x)->high_mark = (x)->num_active; \
406 #define STATS_INC_ERR(x) ((x)->errors++)
407 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
408 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
409 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
410 #define STATS_SET_FREEABLE(x, i) \
412 if ((x)->max_freeable < i) \
413 (x)->max_freeable = i; \
415 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
416 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
417 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
418 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
420 #define STATS_INC_ACTIVE(x) do { } while (0)
421 #define STATS_DEC_ACTIVE(x) do { } while (0)
422 #define STATS_INC_ALLOCED(x) do { } while (0)
423 #define STATS_INC_GROWN(x) do { } while (0)
424 #define STATS_ADD_REAPED(x,y) do { } while (0)
425 #define STATS_SET_HIGH(x) do { } while (0)
426 #define STATS_INC_ERR(x) do { } while (0)
427 #define STATS_INC_NODEALLOCS(x) do { } while (0)
428 #define STATS_INC_NODEFREES(x) do { } while (0)
429 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
430 #define STATS_SET_FREEABLE(x, i) do { } while (0)
431 #define STATS_INC_ALLOCHIT(x) do { } while (0)
432 #define STATS_INC_ALLOCMISS(x) do { } while (0)
433 #define STATS_INC_FREEHIT(x) do { } while (0)
434 #define STATS_INC_FREEMISS(x) do { } while (0)
440 * memory layout of objects:
442 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
443 * the end of an object is aligned with the end of the real
444 * allocation. Catches writes behind the end of the allocation.
445 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
447 * cachep->obj_offset: The real object.
448 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
449 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
450 * [BYTES_PER_WORD long]
452 static int obj_offset(struct kmem_cache *cachep)
454 return cachep->obj_offset;
457 static int obj_size(struct kmem_cache *cachep)
459 return cachep->obj_size;
462 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
464 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
465 return (unsigned long long*) (objp + obj_offset(cachep) -
466 sizeof(unsigned long long));
469 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
471 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
472 if (cachep->flags & SLAB_STORE_USER)
473 return (unsigned long long *)(objp + cachep->buffer_size -
474 sizeof(unsigned long long) -
476 return (unsigned long long *) (objp + cachep->buffer_size -
477 sizeof(unsigned long long));
480 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
482 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
483 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
488 #define obj_offset(x) 0
489 #define obj_size(cachep) (cachep->buffer_size)
490 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
491 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
492 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
496 #ifdef CONFIG_TRACING
497 size_t slab_buffer_size(struct kmem_cache *cachep)
499 return cachep->buffer_size;
501 EXPORT_SYMBOL(slab_buffer_size);
505 * Do not go above this order unless 0 objects fit into the slab.
507 #define BREAK_GFP_ORDER_HI 1
508 #define BREAK_GFP_ORDER_LO 0
509 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
512 * Functions for storing/retrieving the cachep and or slab from the page
513 * allocator. These are used to find the slab an obj belongs to. With kfree(),
514 * these are used to find the cache which an obj belongs to.
516 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
518 page->lru.next = (struct list_head *)cache;
521 static inline struct kmem_cache *page_get_cache(struct page *page)
523 page = compound_head(page);
524 BUG_ON(!PageSlab(page));
525 return (struct kmem_cache *)page->lru.next;
528 static inline void page_set_slab(struct page *page, struct slab *slab)
530 page->lru.prev = (struct list_head *)slab;
533 static inline struct slab *page_get_slab(struct page *page)
535 BUG_ON(!PageSlab(page));
536 return (struct slab *)page->lru.prev;
539 static inline struct kmem_cache *virt_to_cache(const void *obj)
541 struct page *page = virt_to_head_page(obj);
542 return page_get_cache(page);
545 static inline struct slab *virt_to_slab(const void *obj)
547 struct page *page = virt_to_head_page(obj);
548 return page_get_slab(page);
551 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
554 return slab->s_mem + cache->buffer_size * idx;
558 * We want to avoid an expensive divide : (offset / cache->buffer_size)
559 * Using the fact that buffer_size is a constant for a particular cache,
560 * we can replace (offset / cache->buffer_size) by
561 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
563 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
564 const struct slab *slab, void *obj)
566 u32 offset = (obj - slab->s_mem);
567 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
571 * These are the default caches for kmalloc. Custom caches can have other sizes.
573 struct cache_sizes malloc_sizes[] = {
574 #define CACHE(x) { .cs_size = (x) },
575 #include <linux/kmalloc_sizes.h>
579 EXPORT_SYMBOL(malloc_sizes);
581 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
587 static struct cache_names __initdata cache_names[] = {
588 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
589 #include <linux/kmalloc_sizes.h>
594 static struct arraycache_init initarray_cache __initdata =
595 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
596 static struct arraycache_init initarray_generic =
597 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
599 /* internal cache of cache description objs */
600 static struct kmem_cache cache_cache = {
602 .limit = BOOT_CPUCACHE_ENTRIES,
604 .buffer_size = sizeof(struct kmem_cache),
605 .name = "kmem_cache",
608 #define BAD_ALIEN_MAGIC 0x01020304ul
611 * chicken and egg problem: delay the per-cpu array allocation
612 * until the general caches are up.
623 * used by boot code to determine if it can use slab based allocator
625 int slab_is_available(void)
627 return g_cpucache_up >= EARLY;
630 #ifdef CONFIG_LOCKDEP
633 * Slab sometimes uses the kmalloc slabs to store the slab headers
634 * for other slabs "off slab".
635 * The locking for this is tricky in that it nests within the locks
636 * of all other slabs in a few places; to deal with this special
637 * locking we put on-slab caches into a separate lock-class.
639 * We set lock class for alien array caches which are up during init.
640 * The lock annotation will be lost if all cpus of a node goes down and
641 * then comes back up during hotplug
643 static struct lock_class_key on_slab_l3_key;
644 static struct lock_class_key on_slab_alc_key;
646 static void init_node_lock_keys(int q)
648 struct cache_sizes *s = malloc_sizes;
650 if (g_cpucache_up != FULL)
653 for (s = malloc_sizes; s->cs_size != ULONG_MAX; s++) {
654 struct array_cache **alc;
655 struct kmem_list3 *l3;
658 l3 = s->cs_cachep->nodelists[q];
659 if (!l3 || OFF_SLAB(s->cs_cachep))
661 lockdep_set_class(&l3->list_lock, &on_slab_l3_key);
664 * FIXME: This check for BAD_ALIEN_MAGIC
665 * should go away when common slab code is taught to
666 * work even without alien caches.
667 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
668 * for alloc_alien_cache,
670 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
674 lockdep_set_class(&alc[r]->lock,
680 static inline void init_lock_keys(void)
685 init_node_lock_keys(node);
688 static void init_node_lock_keys(int q)
692 static inline void init_lock_keys(void)
698 * Guard access to the cache-chain.
700 static DEFINE_MUTEX(cache_chain_mutex);
701 static struct list_head cache_chain;
703 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
705 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
707 return cachep->array[smp_processor_id()];
711 * If the last page came from the reserves, and the current allocation context
712 * does not have access to them, force an allocation to test the watermarks.
714 static inline int slab_force_alloc(struct kmem_cache *cachep, gfp_t flags)
716 if (unlikely(cpu_cache_get(cachep)->reserve) &&
717 !(gfp_to_alloc_flags(flags) & ALLOC_NO_WATERMARKS))
723 static inline void slab_set_reserve(struct kmem_cache *cachep, int reserve)
725 struct array_cache *ac = cpu_cache_get(cachep);
727 if (unlikely(ac->reserve != reserve))
728 ac->reserve = reserve;
731 static inline struct kmem_cache *__find_general_cachep(size_t size,
734 struct cache_sizes *csizep = malloc_sizes;
737 /* This happens if someone tries to call
738 * kmem_cache_create(), or __kmalloc(), before
739 * the generic caches are initialized.
741 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
744 return ZERO_SIZE_PTR;
746 while (size > csizep->cs_size)
750 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
751 * has cs_{dma,}cachep==NULL. Thus no special case
752 * for large kmalloc calls required.
754 #ifdef CONFIG_ZONE_DMA
755 if (unlikely(gfpflags & GFP_DMA))
756 return csizep->cs_dmacachep;
758 return csizep->cs_cachep;
761 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
763 return __find_general_cachep(size, gfpflags);
766 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
768 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
772 * Calculate the number of objects and left-over bytes for a given buffer size.
774 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
775 size_t align, int flags, size_t *left_over,
780 size_t slab_size = PAGE_SIZE << gfporder;
783 * The slab management structure can be either off the slab or
784 * on it. For the latter case, the memory allocated for a
788 * - One kmem_bufctl_t for each object
789 * - Padding to respect alignment of @align
790 * - @buffer_size bytes for each object
792 * If the slab management structure is off the slab, then the
793 * alignment will already be calculated into the size. Because
794 * the slabs are all pages aligned, the objects will be at the
795 * correct alignment when allocated.
797 if (flags & CFLGS_OFF_SLAB) {
799 nr_objs = slab_size / buffer_size;
801 if (nr_objs > SLAB_LIMIT)
802 nr_objs = SLAB_LIMIT;
805 * Ignore padding for the initial guess. The padding
806 * is at most @align-1 bytes, and @buffer_size is at
807 * least @align. In the worst case, this result will
808 * be one greater than the number of objects that fit
809 * into the memory allocation when taking the padding
812 nr_objs = (slab_size - sizeof(struct slab)) /
813 (buffer_size + sizeof(kmem_bufctl_t));
816 * This calculated number will be either the right
817 * amount, or one greater than what we want.
819 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
823 if (nr_objs > SLAB_LIMIT)
824 nr_objs = SLAB_LIMIT;
826 mgmt_size = slab_mgmt_size(nr_objs, align);
829 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
832 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
834 static void __slab_error(const char *function, struct kmem_cache *cachep,
837 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
838 function, cachep->name, msg);
843 * By default on NUMA we use alien caches to stage the freeing of
844 * objects allocated from other nodes. This causes massive memory
845 * inefficiencies when using fake NUMA setup to split memory into a
846 * large number of small nodes, so it can be disabled on the command
850 static int use_alien_caches __read_mostly = 1;
851 static int __init noaliencache_setup(char *s)
853 use_alien_caches = 0;
856 __setup("noaliencache", noaliencache_setup);
860 * Special reaping functions for NUMA systems called from cache_reap().
861 * These take care of doing round robin flushing of alien caches (containing
862 * objects freed on different nodes from which they were allocated) and the
863 * flushing of remote pcps by calling drain_node_pages.
865 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
867 static void init_reap_node(int cpu)
871 node = next_node(cpu_to_node(cpu), node_online_map);
872 if (node == MAX_NUMNODES)
873 node = first_node(node_online_map);
875 per_cpu(slab_reap_node, cpu) = node;
878 static void next_reap_node(void)
880 int node = __get_cpu_var(slab_reap_node);
882 node = next_node(node, node_online_map);
883 if (unlikely(node >= MAX_NUMNODES))
884 node = first_node(node_online_map);
885 __get_cpu_var(slab_reap_node) = node;
889 #define init_reap_node(cpu) do { } while (0)
890 #define next_reap_node(void) do { } while (0)
894 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
895 * via the workqueue/eventd.
896 * Add the CPU number into the expiration time to minimize the possibility of
897 * the CPUs getting into lockstep and contending for the global cache chain
900 static void __cpuinit start_cpu_timer(int cpu)
902 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
905 * When this gets called from do_initcalls via cpucache_init(),
906 * init_workqueues() has already run, so keventd will be setup
909 if (keventd_up() && reap_work->work.func == NULL) {
911 INIT_DELAYED_WORK(reap_work, cache_reap);
912 schedule_delayed_work_on(cpu, reap_work,
913 __round_jiffies_relative(HZ, cpu));
917 static struct array_cache *alloc_arraycache(int node, int entries,
918 int batchcount, gfp_t gfp)
920 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
921 struct array_cache *nc = NULL;
923 nc = kmalloc_node(memsize, gfp, node);
925 * The array_cache structures contain pointers to free object.
926 * However, when such objects are allocated or transfered to another
927 * cache the pointers are not cleared and they could be counted as
928 * valid references during a kmemleak scan. Therefore, kmemleak must
929 * not scan such objects.
931 kmemleak_no_scan(nc);
935 nc->batchcount = batchcount;
938 spin_lock_init(&nc->lock);
944 * Transfer objects in one arraycache to another.
945 * Locking must be handled by the caller.
947 * Return the number of entries transferred.
949 static int transfer_objects(struct array_cache *to,
950 struct array_cache *from, unsigned int max)
952 /* Figure out how many entries to transfer */
953 int nr = min(min(from->avail, max), to->limit - to->avail);
958 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
969 #define drain_alien_cache(cachep, alien) do { } while (0)
970 #define reap_alien(cachep, l3) do { } while (0)
972 static inline int numa_slab_nid(struct kmem_cache *cachep, gfp_t flags)
977 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
979 return (struct array_cache **)BAD_ALIEN_MAGIC;
982 static inline void free_alien_cache(struct array_cache **ac_ptr)
986 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
991 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
997 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
998 gfp_t flags, int nodeid)
1003 #else /* CONFIG_NUMA */
1005 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
1006 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1009 * slow path for numa_slab_nid(), below
1011 static noinline int __numa_slab_nid(struct kmem_cache *cachep,
1012 int node, gfp_t flags)
1014 struct zonelist *zonelist;
1016 enum zone_type highest_zoneidx = gfp_zone(flags);
1018 if (likely(node_state(node, N_NORMAL_MEMORY)))
1022 * memoryless node: consult its zonelist.
1023 * Cache the fallback node, if cache pointer provided.
1025 zonelist = &NODE_DATA(node)->node_zonelists[0];
1026 (void)first_zones_zonelist(zonelist, highest_zoneidx,
1030 cachep->nodelists[node] =
1031 (struct kmem_list3 *)((unsigned long)zone->node << 1 | 1);
1036 * "Local" node for slab is first node in zonelist with memory.
1037 * For nodes with memory this will be the actual local node.
1039 * Use nodelist[numa_node_id()] to cache the fallback node for
1040 * memoryless nodes. We'll be loading that member soon anyway,
1041 * or already have, when called for cache refill, ... Use low
1042 * bit of "pointer" as flag for "memoryless_node", indicating
1043 * that the fallback nodes is stored here [<<1].
1045 #define memoryless_node(L3L) ((L3L) & 1)
1046 static inline int numa_slab_nid(struct kmem_cache *cachep, gfp_t flags)
1048 int node = numa_node_id();
1050 if (likely(cachep)){
1051 unsigned long l3l = (unsigned long)cachep->nodelists[node];
1054 if (unlikely(memoryless_node(l3l)))
1055 node = (int)(l3l >> 1);
1061 * !cachep || !l3l - the slow path
1063 return __numa_slab_nid(cachep, node, flags);
1066 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
1068 struct array_cache **ac_ptr;
1069 int memsize = sizeof(void *) * nr_node_ids;
1074 ac_ptr = kmalloc_node(memsize, gfp, node);
1077 if (i == node || !node_online(i)) {
1081 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
1083 for (i--; i >= 0; i--)
1093 static void free_alien_cache(struct array_cache **ac_ptr)
1104 static void __drain_alien_cache(struct kmem_cache *cachep,
1105 struct array_cache *ac, int node)
1107 struct kmem_list3 *rl3 = cachep->nodelists[node];
1110 spin_lock(&rl3->list_lock);
1112 * Stuff objects into the remote nodes shared array first.
1113 * That way we could avoid the overhead of putting the objects
1114 * into the free lists and getting them back later.
1117 transfer_objects(rl3->shared, ac, ac->limit);
1119 free_block(cachep, ac->entry, ac->avail, node);
1121 spin_unlock(&rl3->list_lock);
1126 * Called from cache_reap() to regularly drain alien caches round robin.
1128 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1130 int node = __get_cpu_var(slab_reap_node);
1133 struct array_cache *ac = l3->alien[node];
1135 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1136 __drain_alien_cache(cachep, ac, node);
1137 spin_unlock_irq(&ac->lock);
1142 static void drain_alien_cache(struct kmem_cache *cachep,
1143 struct array_cache **alien)
1146 struct array_cache *ac;
1147 unsigned long flags;
1149 for_each_online_node(i) {
1152 spin_lock_irqsave(&ac->lock, flags);
1153 __drain_alien_cache(cachep, ac, i);
1154 spin_unlock_irqrestore(&ac->lock, flags);
1159 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1161 struct slab *slabp = virt_to_slab(objp);
1162 int nodeid = slabp->nodeid;
1163 struct kmem_list3 *l3;
1164 struct array_cache *alien = NULL;
1167 node = numa_slab_nid(cachep, GFP_KERNEL);
1170 * Make sure we are not freeing a object from another node to the array
1171 * cache on this cpu.
1173 if (likely(slabp->nodeid == node))
1176 l3 = cachep->nodelists[node];
1177 STATS_INC_NODEFREES(cachep);
1178 if (l3->alien && l3->alien[nodeid]) {
1179 alien = l3->alien[nodeid];
1180 spin_lock(&alien->lock);
1181 if (unlikely(alien->avail == alien->limit)) {
1182 STATS_INC_ACOVERFLOW(cachep);
1183 __drain_alien_cache(cachep, alien, nodeid);
1185 alien->entry[alien->avail++] = objp;
1186 spin_unlock(&alien->lock);
1188 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1189 free_block(cachep, &objp, 1, nodeid);
1190 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1196 static void __cpuinit cpuup_canceled(long cpu)
1198 struct kmem_cache *cachep;
1199 struct kmem_list3 *l3 = NULL;
1200 int node = cpu_to_node(cpu);
1201 const struct cpumask *mask = cpumask_of_node(node);
1203 list_for_each_entry(cachep, &cache_chain, next) {
1204 struct array_cache *nc;
1205 struct array_cache *shared;
1206 struct array_cache **alien;
1208 /* cpu is dead; no one can alloc from it. */
1209 nc = cachep->array[cpu];
1210 cachep->array[cpu] = NULL;
1211 l3 = cachep->nodelists[node];
1214 goto free_array_cache;
1216 spin_lock_irq(&l3->list_lock);
1218 /* Free limit for this kmem_list3 */
1219 l3->free_limit -= cachep->batchcount;
1221 free_block(cachep, nc->entry, nc->avail, node);
1223 if (!cpumask_empty(mask)) {
1224 spin_unlock_irq(&l3->list_lock);
1225 goto free_array_cache;
1228 shared = l3->shared;
1230 free_block(cachep, shared->entry,
1231 shared->avail, node);
1238 spin_unlock_irq(&l3->list_lock);
1242 drain_alien_cache(cachep, alien);
1243 free_alien_cache(alien);
1249 * In the previous loop, all the objects were freed to
1250 * the respective cache's slabs, now we can go ahead and
1251 * shrink each nodelist to its limit.
1253 list_for_each_entry(cachep, &cache_chain, next) {
1254 l3 = cachep->nodelists[node];
1257 drain_freelist(cachep, l3, l3->free_objects);
1261 static int __cpuinit cpuup_prepare(long cpu)
1263 struct kmem_cache *cachep;
1264 struct kmem_list3 *l3 = NULL;
1265 int node = cpu_to_node(cpu);
1266 const int memsize = sizeof(struct kmem_list3);
1269 * We need to do this right in the beginning since
1270 * alloc_arraycache's are going to use this list.
1271 * kmalloc_node allows us to add the slab to the right
1272 * kmem_list3 and not this cpu's kmem_list3
1275 list_for_each_entry(cachep, &cache_chain, next) {
1277 * Set up the size64 kmemlist for cpu before we can
1278 * begin anything. Make sure some other cpu on this
1279 * node has not already allocated this
1281 if (!cachep->nodelists[node]) {
1282 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1285 kmem_list3_init(l3);
1286 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1287 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1290 * The l3s don't come and go as CPUs come and
1291 * go. cache_chain_mutex is sufficient
1294 cachep->nodelists[node] = l3;
1297 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1298 cachep->nodelists[node]->free_limit =
1299 (1 + nr_cpus_node(node)) *
1300 cachep->batchcount + cachep->num;
1301 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1305 * Now we can go ahead with allocating the shared arrays and
1308 list_for_each_entry(cachep, &cache_chain, next) {
1309 struct array_cache *nc;
1310 struct array_cache *shared = NULL;
1311 struct array_cache **alien = NULL;
1313 nc = alloc_arraycache(node, cachep->limit,
1314 cachep->batchcount, GFP_KERNEL);
1317 if (cachep->shared) {
1318 shared = alloc_arraycache(node,
1319 cachep->shared * cachep->batchcount,
1320 0xbaadf00d, GFP_KERNEL);
1326 if (use_alien_caches) {
1327 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1334 cachep->array[cpu] = nc;
1335 l3 = cachep->nodelists[node];
1338 spin_lock_irq(&l3->list_lock);
1341 * We are serialised from CPU_DEAD or
1342 * CPU_UP_CANCELLED by the cpucontrol lock
1344 l3->shared = shared;
1353 spin_unlock_irq(&l3->list_lock);
1355 free_alien_cache(alien);
1357 init_node_lock_keys(node);
1361 cpuup_canceled(cpu);
1365 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1366 unsigned long action, void *hcpu)
1368 long cpu = (long)hcpu;
1372 case CPU_UP_PREPARE:
1373 case CPU_UP_PREPARE_FROZEN:
1374 mutex_lock(&cache_chain_mutex);
1375 err = cpuup_prepare(cpu);
1376 mutex_unlock(&cache_chain_mutex);
1379 case CPU_ONLINE_FROZEN:
1380 start_cpu_timer(cpu);
1382 #ifdef CONFIG_HOTPLUG_CPU
1383 case CPU_DOWN_PREPARE:
1384 case CPU_DOWN_PREPARE_FROZEN:
1386 * Shutdown cache reaper. Note that the cache_chain_mutex is
1387 * held so that if cache_reap() is invoked it cannot do
1388 * anything expensive but will only modify reap_work
1389 * and reschedule the timer.
1391 cancel_rearming_delayed_work(&per_cpu(slab_reap_work, cpu));
1392 /* Now the cache_reaper is guaranteed to be not running. */
1393 per_cpu(slab_reap_work, cpu).work.func = NULL;
1395 case CPU_DOWN_FAILED:
1396 case CPU_DOWN_FAILED_FROZEN:
1397 start_cpu_timer(cpu);
1400 case CPU_DEAD_FROZEN:
1402 * Even if all the cpus of a node are down, we don't free the
1403 * kmem_list3 of any cache. This to avoid a race between
1404 * cpu_down, and a kmalloc allocation from another cpu for
1405 * memory from the node of the cpu going down. The list3
1406 * structure is usually allocated from kmem_cache_create() and
1407 * gets destroyed at kmem_cache_destroy().
1411 case CPU_UP_CANCELED:
1412 case CPU_UP_CANCELED_FROZEN:
1413 mutex_lock(&cache_chain_mutex);
1414 cpuup_canceled(cpu);
1415 mutex_unlock(&cache_chain_mutex);
1418 return err ? NOTIFY_BAD : NOTIFY_OK;
1421 static struct notifier_block __cpuinitdata cpucache_notifier = {
1422 &cpuup_callback, NULL, 0
1426 * swap the static kmem_list3 with kmalloced memory
1428 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1431 struct kmem_list3 *ptr;
1433 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_NOWAIT, nodeid);
1436 memcpy(ptr, list, sizeof(struct kmem_list3));
1438 * Do not assume that spinlocks can be initialized via memcpy:
1440 spin_lock_init(&ptr->list_lock);
1442 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1443 cachep->nodelists[nodeid] = ptr;
1447 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1448 * size of kmem_list3.
1450 static void __init set_up_list3s(struct kmem_cache *cachep, int index)
1454 for_each_online_node(node) {
1455 cachep->nodelists[node] = &initkmem_list3[index + node];
1456 cachep->nodelists[node]->next_reap = jiffies +
1458 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1463 * Initialisation. Called after the page allocator have been initialised and
1464 * before smp_init().
1466 void __init kmem_cache_init(void)
1469 struct cache_sizes *sizes;
1470 struct cache_names *names;
1475 if (num_possible_nodes() == 1)
1476 use_alien_caches = 0;
1478 for (i = 0; i < NUM_INIT_LISTS; i++) {
1479 kmem_list3_init(&initkmem_list3[i]);
1480 if (i < MAX_NUMNODES)
1481 cache_cache.nodelists[i] = NULL;
1483 set_up_list3s(&cache_cache, CACHE_CACHE);
1486 * Fragmentation resistance on low memory - only use bigger
1487 * page orders on machines with more than 32MB of memory.
1489 if (totalram_pages > (32 << 20) >> PAGE_SHIFT)
1490 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1492 /* Bootstrap is tricky, because several objects are allocated
1493 * from caches that do not exist yet:
1494 * 1) initialize the cache_cache cache: it contains the struct
1495 * kmem_cache structures of all caches, except cache_cache itself:
1496 * cache_cache is statically allocated.
1497 * Initially an __init data area is used for the head array and the
1498 * kmem_list3 structures, it's replaced with a kmalloc allocated
1499 * array at the end of the bootstrap.
1500 * 2) Create the first kmalloc cache.
1501 * The struct kmem_cache for the new cache is allocated normally.
1502 * An __init data area is used for the head array.
1503 * 3) Create the remaining kmalloc caches, with minimally sized
1505 * 4) Replace the __init data head arrays for cache_cache and the first
1506 * kmalloc cache with kmalloc allocated arrays.
1507 * 5) Replace the __init data for kmem_list3 for cache_cache and
1508 * the other cache's with kmalloc allocated memory.
1509 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1512 node = numa_slab_nid(NULL, GFP_KERNEL);
1514 /* 1) create the cache_cache */
1515 INIT_LIST_HEAD(&cache_chain);
1516 list_add(&cache_cache.next, &cache_chain);
1517 cache_cache.colour_off = cache_line_size();
1518 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1519 cache_cache.nodelists[node] = &initkmem_list3[CACHE_CACHE + node];
1522 * struct kmem_cache size depends on nr_node_ids, which
1523 * can be less than MAX_NUMNODES.
1525 cache_cache.buffer_size = offsetof(struct kmem_cache, nodelists) +
1526 nr_node_ids * sizeof(struct kmem_list3 *);
1528 cache_cache.obj_size = cache_cache.buffer_size;
1530 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1532 cache_cache.reciprocal_buffer_size =
1533 reciprocal_value(cache_cache.buffer_size);
1535 for (order = 0; order < MAX_ORDER; order++) {
1536 cache_estimate(order, cache_cache.buffer_size,
1537 cache_line_size(), 0, &left_over, &cache_cache.num);
1538 if (cache_cache.num)
1541 BUG_ON(!cache_cache.num);
1542 cache_cache.gfporder = order;
1543 cache_cache.colour = left_over / cache_cache.colour_off;
1544 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1545 sizeof(struct slab), cache_line_size());
1547 /* 2+3) create the kmalloc caches */
1548 sizes = malloc_sizes;
1549 names = cache_names;
1552 * Initialize the caches that provide memory for the array cache and the
1553 * kmem_list3 structures first. Without this, further allocations will
1557 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1558 sizes[INDEX_AC].cs_size,
1559 ARCH_KMALLOC_MINALIGN,
1560 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1563 if (INDEX_AC != INDEX_L3) {
1564 sizes[INDEX_L3].cs_cachep =
1565 kmem_cache_create(names[INDEX_L3].name,
1566 sizes[INDEX_L3].cs_size,
1567 ARCH_KMALLOC_MINALIGN,
1568 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1572 slab_early_init = 0;
1574 while (sizes->cs_size != ULONG_MAX) {
1576 * For performance, all the general caches are L1 aligned.
1577 * This should be particularly beneficial on SMP boxes, as it
1578 * eliminates "false sharing".
1579 * Note for systems short on memory removing the alignment will
1580 * allow tighter packing of the smaller caches.
1582 if (!sizes->cs_cachep) {
1583 sizes->cs_cachep = kmem_cache_create(names->name,
1585 ARCH_KMALLOC_MINALIGN,
1586 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1589 #ifdef CONFIG_ZONE_DMA
1590 sizes->cs_dmacachep = kmem_cache_create(
1593 ARCH_KMALLOC_MINALIGN,
1594 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1601 /* 4) Replace the bootstrap head arrays */
1603 struct array_cache *ptr;
1605 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1607 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1608 memcpy(ptr, cpu_cache_get(&cache_cache),
1609 sizeof(struct arraycache_init));
1611 * Do not assume that spinlocks can be initialized via memcpy:
1613 spin_lock_init(&ptr->lock);
1615 cache_cache.array[smp_processor_id()] = ptr;
1617 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1619 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1620 != &initarray_generic.cache);
1621 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1622 sizeof(struct arraycache_init));
1624 * Do not assume that spinlocks can be initialized via memcpy:
1626 spin_lock_init(&ptr->lock);
1628 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1631 /* 5) Replace the bootstrap kmem_list3's */
1635 for_each_online_node(nid) {
1636 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE + nid], nid);
1638 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1639 &initkmem_list3[SIZE_AC + nid], nid);
1641 if (INDEX_AC != INDEX_L3) {
1642 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1643 &initkmem_list3[SIZE_L3 + nid], nid);
1648 g_cpucache_up = EARLY;
1651 void __init kmem_cache_init_late(void)
1653 struct kmem_cache *cachep;
1655 /* 6) resize the head arrays to their final sizes */
1656 mutex_lock(&cache_chain_mutex);
1657 list_for_each_entry(cachep, &cache_chain, next)
1658 if (enable_cpucache(cachep, GFP_NOWAIT))
1660 mutex_unlock(&cache_chain_mutex);
1663 g_cpucache_up = FULL;
1665 /* Annotate slab for lockdep -- annotate the malloc caches */
1669 * Register a cpu startup notifier callback that initializes
1670 * cpu_cache_get for all new cpus
1672 register_cpu_notifier(&cpucache_notifier);
1675 * The reap timers are started later, with a module init call: That part
1676 * of the kernel is not yet operational.
1680 static int __init cpucache_init(void)
1685 * Register the timers that return unneeded pages to the page allocator
1687 for_each_online_cpu(cpu)
1688 start_cpu_timer(cpu);
1691 __initcall(cpucache_init);
1694 * Interface to system's page allocator. No need to hold the cache-lock.
1696 * If we requested dmaable memory, we will get it. Even if we
1697 * did not request dmaable memory, we might get it, but that
1698 * would be relatively rare and ignorable.
1700 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid,
1709 * Nommu uses slab's for process anonymous memory allocations, and thus
1710 * requires __GFP_COMP to properly refcount higher order allocations
1712 flags |= __GFP_COMP;
1715 flags |= cachep->gfpflags;
1716 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1717 flags |= __GFP_RECLAIMABLE;
1719 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1723 *reserve = page->reserve;
1724 nr_pages = (1 << cachep->gfporder);
1725 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1726 add_zone_page_state(page_zone(page),
1727 NR_SLAB_RECLAIMABLE, nr_pages);
1729 add_zone_page_state(page_zone(page),
1730 NR_SLAB_UNRECLAIMABLE, nr_pages);
1731 for (i = 0; i < nr_pages; i++)
1732 __SetPageSlab(page + i);
1734 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1735 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1738 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1740 kmemcheck_mark_unallocated_pages(page, nr_pages);
1743 return page_address(page);
1747 * Interface to system's page release.
1749 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1751 unsigned long i = (1 << cachep->gfporder);
1752 struct page *page = virt_to_page(addr);
1753 const unsigned long nr_freed = i;
1755 kmemcheck_free_shadow(page, cachep->gfporder);
1757 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1758 sub_zone_page_state(page_zone(page),
1759 NR_SLAB_RECLAIMABLE, nr_freed);
1761 sub_zone_page_state(page_zone(page),
1762 NR_SLAB_UNRECLAIMABLE, nr_freed);
1764 BUG_ON(!PageSlab(page));
1765 __ClearPageSlab(page);
1768 if (current->reclaim_state)
1769 current->reclaim_state->reclaimed_slab += nr_freed;
1770 free_pages((unsigned long)addr, cachep->gfporder);
1773 static void kmem_rcu_free(struct rcu_head *head)
1775 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1776 struct kmem_cache *cachep = slab_rcu->cachep;
1778 kmem_freepages(cachep, slab_rcu->addr);
1779 if (OFF_SLAB(cachep))
1780 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1785 #ifdef CONFIG_DEBUG_PAGEALLOC
1786 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1787 unsigned long caller)
1789 int size = obj_size(cachep);
1791 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1793 if (size < 5 * sizeof(unsigned long))
1796 *addr++ = 0x12345678;
1798 *addr++ = smp_processor_id();
1799 size -= 3 * sizeof(unsigned long);
1801 unsigned long *sptr = &caller;
1802 unsigned long svalue;
1804 while (!kstack_end(sptr)) {
1806 if (kernel_text_address(svalue)) {
1808 size -= sizeof(unsigned long);
1809 if (size <= sizeof(unsigned long))
1815 *addr++ = 0x87654321;
1819 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1821 int size = obj_size(cachep);
1822 addr = &((char *)addr)[obj_offset(cachep)];
1824 memset(addr, val, size);
1825 *(unsigned char *)(addr + size - 1) = POISON_END;
1828 static void dump_line(char *data, int offset, int limit)
1831 unsigned char error = 0;
1834 printk(KERN_ERR "%03x:", offset);
1835 for (i = 0; i < limit; i++) {
1836 if (data[offset + i] != POISON_FREE) {
1837 error = data[offset + i];
1840 printk(" %02x", (unsigned char)data[offset + i]);
1844 if (bad_count == 1) {
1845 error ^= POISON_FREE;
1846 if (!(error & (error - 1))) {
1847 printk(KERN_ERR "Single bit error detected. Probably "
1850 printk(KERN_ERR "Run memtest86+ or a similar memory "
1853 printk(KERN_ERR "Run a memory test tool.\n");
1862 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1867 if (cachep->flags & SLAB_RED_ZONE) {
1868 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1869 *dbg_redzone1(cachep, objp),
1870 *dbg_redzone2(cachep, objp));
1873 if (cachep->flags & SLAB_STORE_USER) {
1874 printk(KERN_ERR "Last user: [<%p>]",
1875 *dbg_userword(cachep, objp));
1876 print_symbol("(%s)",
1877 (unsigned long)*dbg_userword(cachep, objp));
1880 realobj = (char *)objp + obj_offset(cachep);
1881 size = obj_size(cachep);
1882 for (i = 0; i < size && lines; i += 16, lines--) {
1885 if (i + limit > size)
1887 dump_line(realobj, i, limit);
1891 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1897 realobj = (char *)objp + obj_offset(cachep);
1898 size = obj_size(cachep);
1900 for (i = 0; i < size; i++) {
1901 char exp = POISON_FREE;
1904 if (realobj[i] != exp) {
1910 "Slab corruption: %s start=%p, len=%d\n",
1911 cachep->name, realobj, size);
1912 print_objinfo(cachep, objp, 0);
1914 /* Hexdump the affected line */
1917 if (i + limit > size)
1919 dump_line(realobj, i, limit);
1922 /* Limit to 5 lines */
1928 /* Print some data about the neighboring objects, if they
1931 struct slab *slabp = virt_to_slab(objp);
1934 objnr = obj_to_index(cachep, slabp, objp);
1936 objp = index_to_obj(cachep, slabp, objnr - 1);
1937 realobj = (char *)objp + obj_offset(cachep);
1938 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1940 print_objinfo(cachep, objp, 2);
1942 if (objnr + 1 < cachep->num) {
1943 objp = index_to_obj(cachep, slabp, objnr + 1);
1944 realobj = (char *)objp + obj_offset(cachep);
1945 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1947 print_objinfo(cachep, objp, 2);
1954 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
1957 for (i = 0; i < cachep->num; i++) {
1958 void *objp = index_to_obj(cachep, slabp, i);
1960 if (cachep->flags & SLAB_POISON) {
1961 #ifdef CONFIG_DEBUG_PAGEALLOC
1962 if (cachep->buffer_size % PAGE_SIZE == 0 &&
1964 kernel_map_pages(virt_to_page(objp),
1965 cachep->buffer_size / PAGE_SIZE, 1);
1967 check_poison_obj(cachep, objp);
1969 check_poison_obj(cachep, objp);
1972 if (cachep->flags & SLAB_RED_ZONE) {
1973 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1974 slab_error(cachep, "start of a freed object "
1976 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1977 slab_error(cachep, "end of a freed object "
1983 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
1989 * slab_destroy - destroy and release all objects in a slab
1990 * @cachep: cache pointer being destroyed
1991 * @slabp: slab pointer being destroyed
1993 * Destroy all the objs in a slab, and release the mem back to the system.
1994 * Before calling the slab must have been unlinked from the cache. The
1995 * cache-lock is not held/needed.
1997 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1999 void *addr = slabp->s_mem - slabp->colouroff;
2001 slab_destroy_debugcheck(cachep, slabp);
2002 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2003 struct slab_rcu *slab_rcu;
2005 slab_rcu = (struct slab_rcu *)slabp;
2006 slab_rcu->cachep = cachep;
2007 slab_rcu->addr = addr;
2008 call_rcu(&slab_rcu->head, kmem_rcu_free);
2010 kmem_freepages(cachep, addr);
2011 if (OFF_SLAB(cachep))
2012 kmem_cache_free(cachep->slabp_cache, slabp);
2016 static void __kmem_cache_destroy(struct kmem_cache *cachep)
2019 struct kmem_list3 *l3;
2021 for_each_online_cpu(i)
2022 kfree(cachep->array[i]);
2024 /* NUMA: free the list3 structures */
2025 for_each_online_node(i) {
2026 l3 = cachep->nodelists[i];
2029 free_alien_cache(l3->alien);
2033 kmem_cache_free(&cache_cache, cachep);
2038 * calculate_slab_order - calculate size (page order) of slabs
2039 * @cachep: pointer to the cache that is being created
2040 * @size: size of objects to be created in this cache.
2041 * @align: required alignment for the objects.
2042 * @flags: slab allocation flags
2044 * Also calculates the number of objects per slab.
2046 * This could be made much more intelligent. For now, try to avoid using
2047 * high order pages for slabs. When the gfp() functions are more friendly
2048 * towards high-order requests, this should be changed.
2050 static size_t calculate_slab_order(struct kmem_cache *cachep,
2051 size_t size, size_t align, unsigned long flags)
2053 unsigned long offslab_limit;
2054 size_t left_over = 0;
2057 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2061 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2065 if (flags & CFLGS_OFF_SLAB) {
2067 * Max number of objs-per-slab for caches which
2068 * use off-slab slabs. Needed to avoid a possible
2069 * looping condition in cache_grow().
2071 offslab_limit = size - sizeof(struct slab);
2072 offslab_limit /= sizeof(kmem_bufctl_t);
2074 if (num > offslab_limit)
2078 /* Found something acceptable - save it away */
2080 cachep->gfporder = gfporder;
2081 left_over = remainder;
2084 * A VFS-reclaimable slab tends to have most allocations
2085 * as GFP_NOFS and we really don't want to have to be allocating
2086 * higher-order pages when we are unable to shrink dcache.
2088 if (flags & SLAB_RECLAIM_ACCOUNT)
2092 * Large number of objects is good, but very large slabs are
2093 * currently bad for the gfp()s.
2095 if (gfporder >= slab_break_gfp_order)
2099 * Acceptable internal fragmentation?
2101 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2107 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2109 if (g_cpucache_up == FULL)
2110 return enable_cpucache(cachep, gfp);
2112 if (g_cpucache_up == NONE) {
2114 * Note: the first kmem_cache_create must create the cache
2115 * that's used by kmalloc(24), otherwise the creation of
2116 * further caches will BUG().
2118 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2121 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2122 * the first cache, then we need to set up all its list3s,
2123 * otherwise the creation of further caches will BUG().
2125 set_up_list3s(cachep, SIZE_AC);
2126 if (INDEX_AC == INDEX_L3)
2127 g_cpucache_up = PARTIAL_L3;
2129 g_cpucache_up = PARTIAL_AC;
2131 cachep->array[smp_processor_id()] =
2132 kmalloc(sizeof(struct arraycache_init), gfp);
2134 if (g_cpucache_up == PARTIAL_AC) {
2135 set_up_list3s(cachep, SIZE_L3);
2136 g_cpucache_up = PARTIAL_L3;
2139 for_each_online_node(node) {
2140 cachep->nodelists[node] =
2141 kmalloc_node(sizeof(struct kmem_list3),
2143 BUG_ON(!cachep->nodelists[node]);
2144 kmem_list3_init(cachep->nodelists[node]);
2148 cachep->nodelists[numa_slab_nid(cachep, GFP_KERNEL)]->next_reap =
2149 jiffies + REAPTIMEOUT_LIST3 +
2150 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2152 cpu_cache_get(cachep)->avail = 0;
2153 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2154 cpu_cache_get(cachep)->batchcount = 1;
2155 cpu_cache_get(cachep)->touched = 0;
2156 cpu_cache_get(cachep)->reserve = 0;
2157 cachep->batchcount = 1;
2158 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2163 * kmem_cache_create - Create a cache.
2164 * @name: A string which is used in /proc/slabinfo to identify this cache.
2165 * @size: The size of objects to be created in this cache.
2166 * @align: The required alignment for the objects.
2167 * @flags: SLAB flags
2168 * @ctor: A constructor for the objects.
2170 * Returns a ptr to the cache on success, NULL on failure.
2171 * Cannot be called within a int, but can be interrupted.
2172 * The @ctor is run when new pages are allocated by the cache.
2174 * @name must be valid until the cache is destroyed. This implies that
2175 * the module calling this has to destroy the cache before getting unloaded.
2176 * Note that kmem_cache_name() is not guaranteed to return the same pointer,
2177 * therefore applications must manage it themselves.
2181 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2182 * to catch references to uninitialised memory.
2184 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2185 * for buffer overruns.
2187 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2188 * cacheline. This can be beneficial if you're counting cycles as closely
2192 kmem_cache_create (const char *name, size_t size, size_t align,
2193 unsigned long flags, void (*ctor)(void *))
2195 size_t left_over, slab_size, ralign;
2196 struct kmem_cache *cachep = NULL, *pc;
2200 * Sanity checks... these are all serious usage bugs.
2202 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
2203 size > KMALLOC_MAX_SIZE) {
2204 printk(KERN_ERR "%s: Early error in slab %s\n", __func__,
2210 * We use cache_chain_mutex to ensure a consistent view of
2211 * cpu_online_mask as well. Please see cpuup_callback
2213 if (slab_is_available()) {
2215 mutex_lock(&cache_chain_mutex);
2218 list_for_each_entry(pc, &cache_chain, next) {
2223 * This happens when the module gets unloaded and doesn't
2224 * destroy its slab cache and no-one else reuses the vmalloc
2225 * area of the module. Print a warning.
2227 res = probe_kernel_address(pc->name, tmp);
2230 "SLAB: cache with size %d has lost its name\n",
2235 if (!strcmp(pc->name, name)) {
2237 "kmem_cache_create: duplicate cache %s\n", name);
2244 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2247 * Enable redzoning and last user accounting, except for caches with
2248 * large objects, if the increased size would increase the object size
2249 * above the next power of two: caches with object sizes just above a
2250 * power of two have a significant amount of internal fragmentation.
2252 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2253 2 * sizeof(unsigned long long)))
2254 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2255 if (!(flags & SLAB_DESTROY_BY_RCU))
2256 flags |= SLAB_POISON;
2258 if (flags & SLAB_DESTROY_BY_RCU)
2259 BUG_ON(flags & SLAB_POISON);
2262 * Always checks flags, a caller might be expecting debug support which
2265 BUG_ON(flags & ~CREATE_MASK);
2268 * Check that size is in terms of words. This is needed to avoid
2269 * unaligned accesses for some archs when redzoning is used, and makes
2270 * sure any on-slab bufctl's are also correctly aligned.
2272 if (size & (BYTES_PER_WORD - 1)) {
2273 size += (BYTES_PER_WORD - 1);
2274 size &= ~(BYTES_PER_WORD - 1);
2277 /* calculate the final buffer alignment: */
2279 /* 1) arch recommendation: can be overridden for debug */
2280 if (flags & SLAB_HWCACHE_ALIGN) {
2282 * Default alignment: as specified by the arch code. Except if
2283 * an object is really small, then squeeze multiple objects into
2286 ralign = cache_line_size();
2287 while (size <= ralign / 2)
2290 ralign = BYTES_PER_WORD;
2294 * Redzoning and user store require word alignment or possibly larger.
2295 * Note this will be overridden by architecture or caller mandated
2296 * alignment if either is greater than BYTES_PER_WORD.
2298 if (flags & SLAB_STORE_USER)
2299 ralign = BYTES_PER_WORD;
2301 if (flags & SLAB_RED_ZONE) {
2302 ralign = REDZONE_ALIGN;
2303 /* If redzoning, ensure that the second redzone is suitably
2304 * aligned, by adjusting the object size accordingly. */
2305 size += REDZONE_ALIGN - 1;
2306 size &= ~(REDZONE_ALIGN - 1);
2309 /* 2) arch mandated alignment */
2310 if (ralign < ARCH_SLAB_MINALIGN) {
2311 ralign = ARCH_SLAB_MINALIGN;
2313 /* 3) caller mandated alignment */
2314 if (ralign < align) {
2317 /* disable debug if necessary */
2318 if (ralign > __alignof__(unsigned long long))
2319 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2325 if (slab_is_available())
2330 /* Get cache's description obj. */
2331 cachep = kmem_cache_zalloc(&cache_cache, gfp);
2336 cachep->obj_size = size;
2339 * Both debugging options require word-alignment which is calculated
2342 if (flags & SLAB_RED_ZONE) {
2343 /* add space for red zone words */
2344 cachep->obj_offset += sizeof(unsigned long long);
2345 size += 2 * sizeof(unsigned long long);
2347 if (flags & SLAB_STORE_USER) {
2348 /* user store requires one word storage behind the end of
2349 * the real object. But if the second red zone needs to be
2350 * aligned to 64 bits, we must allow that much space.
2352 if (flags & SLAB_RED_ZONE)
2353 size += REDZONE_ALIGN;
2355 size += BYTES_PER_WORD;
2357 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2358 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2359 && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2360 cachep->obj_offset += PAGE_SIZE - size;
2367 * Determine if the slab management is 'on' or 'off' slab.
2368 * (bootstrapping cannot cope with offslab caches so don't do
2369 * it too early on. Always use on-slab management when
2370 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2372 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init &&
2373 !(flags & SLAB_NOLEAKTRACE))
2375 * Size is large, assume best to place the slab management obj
2376 * off-slab (should allow better packing of objs).
2378 flags |= CFLGS_OFF_SLAB;
2380 size = ALIGN(size, align);
2382 left_over = calculate_slab_order(cachep, size, align, flags);
2386 "kmem_cache_create: couldn't create cache %s.\n", name);
2387 kmem_cache_free(&cache_cache, cachep);
2391 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2392 + sizeof(struct slab), align);
2395 * If the slab has been placed off-slab, and we have enough space then
2396 * move it on-slab. This is at the expense of any extra colouring.
2398 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2399 flags &= ~CFLGS_OFF_SLAB;
2400 left_over -= slab_size;
2403 if (flags & CFLGS_OFF_SLAB) {
2404 /* really off slab. No need for manual alignment */
2406 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2408 #ifdef CONFIG_PAGE_POISONING
2409 /* If we're going to use the generic kernel_map_pages()
2410 * poisoning, then it's going to smash the contents of
2411 * the redzone and userword anyhow, so switch them off.
2413 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2414 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2418 cachep->colour_off = cache_line_size();
2419 /* Offset must be a multiple of the alignment. */
2420 if (cachep->colour_off < align)
2421 cachep->colour_off = align;
2422 cachep->colour = left_over / cachep->colour_off;
2423 cachep->slab_size = slab_size;
2424 cachep->flags = flags;
2425 cachep->gfpflags = 0;
2426 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2427 cachep->gfpflags |= GFP_DMA;
2428 cachep->buffer_size = size;
2429 cachep->reciprocal_buffer_size = reciprocal_value(size);
2431 if (flags & CFLGS_OFF_SLAB) {
2432 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2434 * This is a possibility for one of the malloc_sizes caches.
2435 * But since we go off slab only for object size greater than
2436 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2437 * this should not happen at all.
2438 * But leave a BUG_ON for some lucky dude.
2440 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2442 cachep->ctor = ctor;
2443 cachep->name = name;
2445 if (setup_cpu_cache(cachep, gfp)) {
2446 __kmem_cache_destroy(cachep);
2451 /* cache setup completed, link it into the list */
2452 list_add(&cachep->next, &cache_chain);
2454 if (!cachep && (flags & SLAB_PANIC))
2455 panic("kmem_cache_create(): failed to create slab `%s'\n",
2457 if (slab_is_available()) {
2458 mutex_unlock(&cache_chain_mutex);
2463 EXPORT_SYMBOL(kmem_cache_create);
2466 static void check_irq_off(void)
2468 BUG_ON(!irqs_disabled());
2471 static void check_irq_on(void)
2473 BUG_ON(irqs_disabled());
2476 static void check_spinlock_acquired(struct kmem_cache *cachep)
2480 assert_spin_locked(&cachep->nodelists[numa_slab_nid(cachep, GFP_KERNEL)]->list_lock);
2484 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2488 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2493 #define check_irq_off() do { } while(0)
2494 #define check_irq_on() do { } while(0)
2495 #define check_spinlock_acquired(x) do { } while(0)
2496 #define check_spinlock_acquired_node(x, y) do { } while(0)
2499 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2500 struct array_cache *ac,
2501 int force, int node);
2503 static void do_drain(void *arg)
2505 struct kmem_cache *cachep = arg;
2506 struct array_cache *ac;
2507 int node = numa_slab_nid(cachep, GFP_KERNEL);
2510 ac = cpu_cache_get(cachep);
2511 spin_lock(&cachep->nodelists[node]->list_lock);
2512 free_block(cachep, ac->entry, ac->avail, node);
2513 spin_unlock(&cachep->nodelists[node]->list_lock);
2517 static void drain_cpu_caches(struct kmem_cache *cachep)
2519 struct kmem_list3 *l3;
2522 on_each_cpu(do_drain, cachep, 1);
2524 for_each_online_node(node) {
2525 l3 = cachep->nodelists[node];
2526 if (l3 && l3->alien)
2527 drain_alien_cache(cachep, l3->alien);
2530 for_each_online_node(node) {
2531 l3 = cachep->nodelists[node];
2533 drain_array(cachep, l3, l3->shared, 1, node);
2538 * Remove slabs from the list of free slabs.
2539 * Specify the number of slabs to drain in tofree.
2541 * Returns the actual number of slabs released.
2543 static int drain_freelist(struct kmem_cache *cache,
2544 struct kmem_list3 *l3, int tofree)
2546 struct list_head *p;
2551 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2553 spin_lock_irq(&l3->list_lock);
2554 p = l3->slabs_free.prev;
2555 if (p == &l3->slabs_free) {
2556 spin_unlock_irq(&l3->list_lock);
2560 slabp = list_entry(p, struct slab, list);
2562 BUG_ON(slabp->inuse);
2564 list_del(&slabp->list);
2566 * Safe to drop the lock. The slab is no longer linked
2569 l3->free_objects -= cache->num;
2570 spin_unlock_irq(&l3->list_lock);
2571 slab_destroy(cache, slabp);
2578 /* Called with cache_chain_mutex held to protect against cpu hotplug */
2579 static int __cache_shrink(struct kmem_cache *cachep)
2582 struct kmem_list3 *l3;
2584 drain_cpu_caches(cachep);
2587 for_each_online_node(i) {
2588 l3 = cachep->nodelists[i];
2592 drain_freelist(cachep, l3, l3->free_objects);
2594 ret += !list_empty(&l3->slabs_full) ||
2595 !list_empty(&l3->slabs_partial);
2597 return (ret ? 1 : 0);
2601 * kmem_cache_shrink - Shrink a cache.
2602 * @cachep: The cache to shrink.
2604 * Releases as many slabs as possible for a cache.
2605 * To help debugging, a zero exit status indicates all slabs were released.
2607 int kmem_cache_shrink(struct kmem_cache *cachep)
2610 BUG_ON(!cachep || in_interrupt());
2613 mutex_lock(&cache_chain_mutex);
2614 ret = __cache_shrink(cachep);
2615 mutex_unlock(&cache_chain_mutex);
2619 EXPORT_SYMBOL(kmem_cache_shrink);
2622 * kmem_cache_destroy - delete a cache
2623 * @cachep: the cache to destroy
2625 * Remove a &struct kmem_cache object from the slab cache.
2627 * It is expected this function will be called by a module when it is
2628 * unloaded. This will remove the cache completely, and avoid a duplicate
2629 * cache being allocated each time a module is loaded and unloaded, if the
2630 * module doesn't have persistent in-kernel storage across loads and unloads.
2632 * The cache must be empty before calling this function.
2634 * The caller must guarantee that noone will allocate memory from the cache
2635 * during the kmem_cache_destroy().
2637 void kmem_cache_destroy(struct kmem_cache *cachep)
2639 BUG_ON(!cachep || in_interrupt());
2641 /* Find the cache in the chain of caches. */
2643 mutex_lock(&cache_chain_mutex);
2645 * the chain is never empty, cache_cache is never destroyed
2647 list_del(&cachep->next);
2648 if (__cache_shrink(cachep)) {
2649 slab_error(cachep, "Can't free all objects");
2650 list_add(&cachep->next, &cache_chain);
2651 mutex_unlock(&cache_chain_mutex);
2656 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2659 __kmem_cache_destroy(cachep);
2660 mutex_unlock(&cache_chain_mutex);
2663 EXPORT_SYMBOL(kmem_cache_destroy);
2666 * Get the memory for a slab management obj.
2667 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2668 * always come from malloc_sizes caches. The slab descriptor cannot
2669 * come from the same cache which is getting created because,
2670 * when we are searching for an appropriate cache for these
2671 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2672 * If we are creating a malloc_sizes cache here it would not be visible to
2673 * kmem_find_general_cachep till the initialization is complete.
2674 * Hence we cannot have slabp_cache same as the original cache.
2676 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2677 int colour_off, gfp_t local_flags,
2682 if (OFF_SLAB(cachep)) {
2683 /* Slab management obj is off-slab. */
2684 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2685 local_flags, nodeid);
2687 * If the first object in the slab is leaked (it's allocated
2688 * but no one has a reference to it), we want to make sure
2689 * kmemleak does not treat the ->s_mem pointer as a reference
2690 * to the object. Otherwise we will not report the leak.
2692 kmemleak_scan_area(&slabp->list, sizeof(struct list_head),
2697 slabp = objp + colour_off;
2698 colour_off += cachep->slab_size;
2701 slabp->colouroff = colour_off;
2702 slabp->s_mem = objp + colour_off;
2703 slabp->nodeid = nodeid;
2708 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2710 return (kmem_bufctl_t *) (slabp + 1);
2713 static void cache_init_objs(struct kmem_cache *cachep,
2718 for (i = 0; i < cachep->num; i++) {
2719 void *objp = index_to_obj(cachep, slabp, i);
2721 /* need to poison the objs? */
2722 if (cachep->flags & SLAB_POISON)
2723 poison_obj(cachep, objp, POISON_FREE);
2724 if (cachep->flags & SLAB_STORE_USER)
2725 *dbg_userword(cachep, objp) = NULL;
2727 if (cachep->flags & SLAB_RED_ZONE) {
2728 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2729 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2732 * Constructors are not allowed to allocate memory from the same
2733 * cache which they are a constructor for. Otherwise, deadlock.
2734 * They must also be threaded.
2736 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2737 cachep->ctor(objp + obj_offset(cachep));
2739 if (cachep->flags & SLAB_RED_ZONE) {
2740 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2741 slab_error(cachep, "constructor overwrote the"
2742 " end of an object");
2743 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2744 slab_error(cachep, "constructor overwrote the"
2745 " start of an object");
2747 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2748 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2749 kernel_map_pages(virt_to_page(objp),
2750 cachep->buffer_size / PAGE_SIZE, 0);
2755 slab_bufctl(slabp)[i] = i + 1;
2757 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2760 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2762 if (CONFIG_ZONE_DMA_FLAG) {
2763 if (flags & GFP_DMA)
2764 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2766 BUG_ON(cachep->gfpflags & GFP_DMA);
2770 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2773 void *objp = index_to_obj(cachep, slabp, slabp->free);
2777 next = slab_bufctl(slabp)[slabp->free];
2779 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2780 WARN_ON(slabp->nodeid != nodeid);
2787 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2788 void *objp, int nodeid)
2790 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2793 /* Verify that the slab belongs to the intended node */
2794 WARN_ON(slabp->nodeid != nodeid);
2796 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2797 printk(KERN_ERR "slab: double free detected in cache "
2798 "'%s', objp %p\n", cachep->name, objp);
2802 slab_bufctl(slabp)[objnr] = slabp->free;
2803 slabp->free = objnr;
2808 * Map pages beginning at addr to the given cache and slab. This is required
2809 * for the slab allocator to be able to lookup the cache and slab of a
2810 * virtual address for kfree, ksize, kmem_ptr_validate, and slab debugging.
2812 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2818 page = virt_to_page(addr);
2821 if (likely(!PageCompound(page)))
2822 nr_pages <<= cache->gfporder;
2825 page_set_cache(page, cache);
2826 page_set_slab(page, slab);
2828 } while (--nr_pages);
2832 * Grow (by 1) the number of slabs within a cache. This is called by
2833 * kmem_cache_alloc() when there are no active objs left in a cache.
2835 static int cache_grow(struct kmem_cache *cachep,
2836 gfp_t flags, int nodeid, void *objp)
2841 struct kmem_list3 *l3;
2845 * Be lazy and only check for valid flags here, keeping it out of the
2846 * critical path in kmem_cache_alloc().
2848 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2849 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2851 /* Take the l3 list lock to change the colour_next on this node */
2853 l3 = cachep->nodelists[nodeid];
2854 spin_lock(&l3->list_lock);
2856 /* Get colour for the slab, and cal the next value. */
2857 offset = l3->colour_next;
2859 if (l3->colour_next >= cachep->colour)
2860 l3->colour_next = 0;
2861 spin_unlock(&l3->list_lock);
2863 offset *= cachep->colour_off;
2865 if (local_flags & __GFP_WAIT)
2869 * The test for missing atomic flag is performed here, rather than
2870 * the more obvious place, simply to reduce the critical path length
2871 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2872 * will eventually be caught here (where it matters).
2874 kmem_flagcheck(cachep, flags);
2877 * Get mem for the objs. Attempt to allocate a physical page from
2881 objp = kmem_getpages(cachep, local_flags, nodeid, &reserve);
2885 /* Get slab management. */
2886 slabp = alloc_slabmgmt(cachep, objp, offset,
2887 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2891 slab_map_pages(cachep, slabp, objp);
2893 cache_init_objs(cachep, slabp);
2895 if (local_flags & __GFP_WAIT)
2896 local_irq_disable();
2899 slab_set_reserve(cachep, reserve);
2900 spin_lock(&l3->list_lock);
2902 /* Make slab active. */
2903 list_add_tail(&slabp->list, &(l3->slabs_free));
2904 STATS_INC_GROWN(cachep);
2905 l3->free_objects += cachep->num;
2906 spin_unlock(&l3->list_lock);
2909 kmem_freepages(cachep, objp);
2911 if (local_flags & __GFP_WAIT)
2912 local_irq_disable();
2919 * Perform extra freeing checks:
2920 * - detect bad pointers.
2921 * - POISON/RED_ZONE checking
2923 static void kfree_debugcheck(const void *objp)
2925 if (!virt_addr_valid(objp)) {
2926 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2927 (unsigned long)objp);
2932 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2934 unsigned long long redzone1, redzone2;
2936 redzone1 = *dbg_redzone1(cache, obj);
2937 redzone2 = *dbg_redzone2(cache, obj);
2942 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2945 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2946 slab_error(cache, "double free detected");
2948 slab_error(cache, "memory outside object was overwritten");
2950 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2951 obj, redzone1, redzone2);
2954 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2961 BUG_ON(virt_to_cache(objp) != cachep);
2963 objp -= obj_offset(cachep);
2964 kfree_debugcheck(objp);
2965 page = virt_to_head_page(objp);
2967 slabp = page_get_slab(page);
2969 if (cachep->flags & SLAB_RED_ZONE) {
2970 verify_redzone_free(cachep, objp);
2971 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2972 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2974 if (cachep->flags & SLAB_STORE_USER)
2975 *dbg_userword(cachep, objp) = caller;
2977 objnr = obj_to_index(cachep, slabp, objp);
2979 BUG_ON(objnr >= cachep->num);
2980 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2982 #ifdef CONFIG_DEBUG_SLAB_LEAK
2983 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2985 if (cachep->flags & SLAB_POISON) {
2986 #ifdef CONFIG_DEBUG_PAGEALLOC
2987 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2988 store_stackinfo(cachep, objp, (unsigned long)caller);
2989 kernel_map_pages(virt_to_page(objp),
2990 cachep->buffer_size / PAGE_SIZE, 0);
2992 poison_obj(cachep, objp, POISON_FREE);
2995 poison_obj(cachep, objp, POISON_FREE);
3001 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
3006 /* Check slab's freelist to see if this obj is there. */
3007 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
3009 if (entries > cachep->num || i >= cachep->num)
3012 if (entries != cachep->num - slabp->inuse) {
3014 printk(KERN_ERR "slab: Internal list corruption detected in "
3015 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
3016 cachep->name, cachep->num, slabp, slabp->inuse);
3018 i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
3021 printk("\n%03x:", i);
3022 printk(" %02x", ((unsigned char *)slabp)[i]);
3029 #define kfree_debugcheck(x) do { } while(0)
3030 #define cache_free_debugcheck(x,objp,z) (objp)
3031 #define check_slabp(x,y) do { } while(0)
3034 static void *cache_alloc_refill(struct kmem_cache *cachep,
3035 gfp_t flags, int must_refill)
3038 struct kmem_list3 *l3;
3039 struct array_cache *ac;
3044 node = numa_slab_nid(cachep, flags);
3045 if (unlikely(must_refill))
3047 ac = cpu_cache_get(cachep);
3048 batchcount = ac->batchcount;
3049 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
3051 * If there was little recent activity on this cache, then
3052 * perform only a partial refill. Otherwise we could generate
3055 batchcount = BATCHREFILL_LIMIT;
3057 l3 = cachep->nodelists[node];
3059 BUG_ON(ac->avail > 0 || !l3);
3060 spin_lock(&l3->list_lock);
3062 /* See if we can refill from the shared array */
3063 if (l3->shared && transfer_objects(ac, l3->shared, batchcount))
3066 while (batchcount > 0) {
3067 struct list_head *entry;
3069 /* Get slab alloc is to come from. */
3070 entry = l3->slabs_partial.next;
3071 if (entry == &l3->slabs_partial) {
3072 l3->free_touched = 1;
3073 entry = l3->slabs_free.next;
3074 if (entry == &l3->slabs_free)
3078 slabp = list_entry(entry, struct slab, list);
3079 check_slabp(cachep, slabp);
3080 check_spinlock_acquired(cachep);
3083 * The slab was either on partial or free list so
3084 * there must be at least one object available for
3087 BUG_ON(slabp->inuse >= cachep->num);
3089 while (slabp->inuse < cachep->num && batchcount--) {
3090 STATS_INC_ALLOCED(cachep);
3091 STATS_INC_ACTIVE(cachep);
3092 STATS_SET_HIGH(cachep);
3094 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
3097 check_slabp(cachep, slabp);
3099 /* move slabp to correct slabp list: */
3100 list_del(&slabp->list);
3101 if (slabp->free == BUFCTL_END)
3102 list_add(&slabp->list, &l3->slabs_full);
3104 list_add(&slabp->list, &l3->slabs_partial);
3108 l3->free_objects -= ac->avail;
3110 spin_unlock(&l3->list_lock);
3112 if (unlikely(!ac->avail)) {
3115 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3117 /* cache_grow can reenable interrupts, then ac could change. */
3118 ac = cpu_cache_get(cachep);
3120 /* no objects in sight? abort */
3121 if (!x && (ac->avail == 0 || must_refill))
3124 if (!ac->avail) /* objects refilled by interrupt? */
3128 return ac->entry[--ac->avail];
3131 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3134 might_sleep_if(flags & __GFP_WAIT);
3136 kmem_flagcheck(cachep, flags);
3141 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3142 gfp_t flags, void *objp, void *caller)
3146 if (cachep->flags & SLAB_POISON) {
3147 #ifdef CONFIG_DEBUG_PAGEALLOC
3148 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3149 kernel_map_pages(virt_to_page(objp),
3150 cachep->buffer_size / PAGE_SIZE, 1);
3152 check_poison_obj(cachep, objp);
3154 check_poison_obj(cachep, objp);
3156 poison_obj(cachep, objp, POISON_INUSE);
3158 if (cachep->flags & SLAB_STORE_USER)
3159 *dbg_userword(cachep, objp) = caller;
3161 if (cachep->flags & SLAB_RED_ZONE) {
3162 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3163 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3164 slab_error(cachep, "double free, or memory outside"
3165 " object was overwritten");
3167 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3168 objp, *dbg_redzone1(cachep, objp),
3169 *dbg_redzone2(cachep, objp));
3171 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3172 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3174 #ifdef CONFIG_DEBUG_SLAB_LEAK
3179 slabp = page_get_slab(virt_to_head_page(objp));
3180 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
3181 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3184 objp += obj_offset(cachep);
3185 if (cachep->ctor && cachep->flags & SLAB_POISON)
3187 #if ARCH_SLAB_MINALIGN
3188 if ((u32)objp & (ARCH_SLAB_MINALIGN-1)) {
3189 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3190 objp, ARCH_SLAB_MINALIGN);
3196 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3199 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3201 if (cachep == &cache_cache)
3204 return should_failslab(obj_size(cachep), flags);
3207 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3210 struct array_cache *ac;
3211 int must_refill = slab_force_alloc(cachep, flags);
3215 ac = cpu_cache_get(cachep);
3216 if (likely(ac->avail && !must_refill)) {
3217 STATS_INC_ALLOCHIT(cachep);
3219 objp = ac->entry[--ac->avail];
3221 STATS_INC_ALLOCMISS(cachep);
3222 objp = cache_alloc_refill(cachep, flags, must_refill);
3224 * the 'ac' may be updated by cache_alloc_refill(),
3225 * and kmemleak_erase() requires its correct value.
3227 ac = cpu_cache_get(cachep);
3230 * To avoid a false negative, if an object that is in one of the
3231 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3232 * treat the array pointers as a reference to the object.
3235 kmemleak_erase(&ac->entry[ac->avail]);
3241 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3243 * If we are in_interrupt, then process context, including cpusets and
3244 * mempolicy, may not apply and should not be used for allocation policy.
3246 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3248 int nid_alloc, nid_here;
3250 if (in_interrupt() || (flags & __GFP_THISNODE))
3252 nid_alloc = nid_here = numa_slab_nid(cachep, flags);
3253 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3254 nid_alloc = cpuset_mem_spread_node();
3255 else if (current->mempolicy)
3256 nid_alloc = slab_node(current->mempolicy);
3257 if (nid_alloc != nid_here)
3258 return ____cache_alloc_node(cachep, flags, nid_alloc);
3263 * Fallback function if there was no memory available and no objects on a
3264 * certain node and fall back is permitted. First we scan all the
3265 * available nodelists for available objects. If that fails then we
3266 * perform an allocation without specifying a node. This allows the page
3267 * allocator to do its reclaim / fallback magic. We then insert the
3268 * slab into the proper nodelist and then allocate from it.
3270 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3272 struct zonelist *zonelist;
3276 enum zone_type high_zoneidx = gfp_zone(flags);
3280 if (flags & __GFP_THISNODE)
3283 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
3284 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3288 * Look through allowed nodes for objects available
3289 * from existing per node queues.
3291 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3292 nid = zone_to_nid(zone);
3294 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3295 cache->nodelists[nid] &&
3296 cache->nodelists[nid]->free_objects) {
3297 obj = ____cache_alloc_node(cache,
3298 flags | GFP_THISNODE, nid);
3306 * This allocation will be performed within the constraints
3307 * of the current cpuset / memory policy requirements.
3308 * We may trigger various forms of reclaim on the allowed
3309 * set and go into memory reserves if necessary.
3311 if (local_flags & __GFP_WAIT)
3313 kmem_flagcheck(cache, flags);
3314 obj = kmem_getpages(cache, local_flags, numa_node_id(),
3316 if (local_flags & __GFP_WAIT)
3317 local_irq_disable();
3319 slab_set_reserve(cache, reserve);
3321 * Insert into the appropriate per node queues
3323 nid = page_to_nid(virt_to_page(obj));
3324 if (cache_grow(cache, flags, nid, obj)) {
3325 obj = ____cache_alloc_node(cache,
3326 flags | GFP_THISNODE, nid);
3329 * Another processor may allocate the
3330 * objects in the slab since we are
3331 * not holding any locks.
3335 /* cache_grow already freed obj */
3344 * A interface to enable slab creation on nodeid
3346 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3349 struct list_head *entry;
3351 struct kmem_list3 *l3;
3355 l3 = cachep->nodelists[nodeid];
3358 if (unlikely(slab_force_alloc(cachep, flags)))
3363 spin_lock(&l3->list_lock);
3364 entry = l3->slabs_partial.next;
3365 if (entry == &l3->slabs_partial) {
3366 l3->free_touched = 1;
3367 entry = l3->slabs_free.next;
3368 if (entry == &l3->slabs_free)
3372 slabp = list_entry(entry, struct slab, list);
3373 check_spinlock_acquired_node(cachep, nodeid);
3374 check_slabp(cachep, slabp);
3376 STATS_INC_NODEALLOCS(cachep);
3377 STATS_INC_ACTIVE(cachep);
3378 STATS_SET_HIGH(cachep);
3380 BUG_ON(slabp->inuse == cachep->num);
3382 obj = slab_get_obj(cachep, slabp, nodeid);
3383 check_slabp(cachep, slabp);
3385 /* move slabp to correct slabp list: */
3386 list_del(&slabp->list);
3388 if (slabp->free == BUFCTL_END)
3389 list_add(&slabp->list, &l3->slabs_full);
3391 list_add(&slabp->list, &l3->slabs_partial);
3393 spin_unlock(&l3->list_lock);
3397 spin_unlock(&l3->list_lock);
3399 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3403 return fallback_alloc(cachep, flags);
3410 * kmem_cache_alloc_node - Allocate an object on the specified node
3411 * @cachep: The cache to allocate from.
3412 * @flags: See kmalloc().
3413 * @nodeid: node number of the target node.
3414 * @caller: return address of caller, used for debug information
3416 * Identical to kmem_cache_alloc but it will allocate memory on the given
3417 * node, which can improve the performance for cpu bound structures.
3419 * Fallback to other node is possible if __GFP_THISNODE is not set.
3421 static __always_inline void *
3422 __cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3425 unsigned long save_flags;
3427 int slab_node = numa_slab_nid(cachep, flags);
3429 flags &= gfp_allowed_mask;
3431 lockdep_trace_alloc(flags);
3433 if (slab_should_failslab(cachep, flags))
3436 cache_alloc_debugcheck_before(cachep, flags);
3437 local_irq_save(save_flags);
3442 if (unlikely(!cachep->nodelists[nodeid])) {
3443 /* Node not bootstrapped yet */
3444 ptr = fallback_alloc(cachep, flags);
3448 if (nodeid == slab_node) {
3450 * Use the locally cached objects if possible.
3451 * However ____cache_alloc does not allow fallback
3452 * to other nodes. It may fail while we still have
3453 * objects on other nodes available.
3455 ptr = ____cache_alloc(cachep, flags);
3459 /* ___cache_alloc_node can fall back to other nodes */
3460 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3462 local_irq_restore(save_flags);
3463 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3464 kmemleak_alloc_recursive(ptr, obj_size(cachep), 1, cachep->flags,
3468 kmemcheck_slab_alloc(cachep, flags, ptr, obj_size(cachep));
3470 if (unlikely((flags & __GFP_ZERO) && ptr))
3471 memset(ptr, 0, obj_size(cachep));
3476 static __always_inline void *
3477 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3481 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3482 objp = alternate_node_alloc(cache, flags);
3486 objp = ____cache_alloc(cache, flags);
3489 * We may just have run out of memory on the local node.
3490 * ____cache_alloc_node() knows how to locate memory on other nodes
3493 objp = ____cache_alloc_node(cache, flags,
3494 numa_slab_nid(cache, flags));
3501 static __always_inline void *
3502 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3504 return ____cache_alloc(cachep, flags);
3507 #endif /* CONFIG_NUMA */
3509 static __always_inline void *
3510 __cache_alloc(struct kmem_cache *cachep, gfp_t flags, void *caller)
3512 unsigned long save_flags;
3515 flags &= gfp_allowed_mask;
3517 lockdep_trace_alloc(flags);
3519 if (slab_should_failslab(cachep, flags))
3522 cache_alloc_debugcheck_before(cachep, flags);
3523 local_irq_save(save_flags);
3524 objp = __do_cache_alloc(cachep, flags);
3525 local_irq_restore(save_flags);
3526 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3527 kmemleak_alloc_recursive(objp, obj_size(cachep), 1, cachep->flags,
3532 kmemcheck_slab_alloc(cachep, flags, objp, obj_size(cachep));
3534 if (unlikely((flags & __GFP_ZERO) && objp))
3535 memset(objp, 0, obj_size(cachep));
3541 * Caller needs to acquire correct kmem_list's list_lock
3543 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3547 struct kmem_list3 *l3;
3549 for (i = 0; i < nr_objects; i++) {
3550 void *objp = objpp[i];
3553 slabp = virt_to_slab(objp);
3554 l3 = cachep->nodelists[node];
3555 list_del(&slabp->list);
3556 check_spinlock_acquired_node(cachep, node);
3557 check_slabp(cachep, slabp);
3558 slab_put_obj(cachep, slabp, objp, node);
3559 STATS_DEC_ACTIVE(cachep);
3561 check_slabp(cachep, slabp);
3563 /* fixup slab chains */
3564 if (slabp->inuse == 0) {
3565 if (l3->free_objects > l3->free_limit) {
3566 l3->free_objects -= cachep->num;
3567 /* No need to drop any previously held
3568 * lock here, even if we have a off-slab slab
3569 * descriptor it is guaranteed to come from
3570 * a different cache, refer to comments before
3573 slab_destroy(cachep, slabp);
3575 list_add(&slabp->list, &l3->slabs_free);
3578 /* Unconditionally move a slab to the end of the
3579 * partial list on free - maximum time for the
3580 * other objects to be freed, too.
3582 list_add_tail(&slabp->list, &l3->slabs_partial);
3587 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3590 struct kmem_list3 *l3;
3591 int node = numa_slab_nid(cachep, GFP_KERNEL);
3593 batchcount = ac->batchcount;
3595 BUG_ON(!batchcount || batchcount > ac->avail);
3598 l3 = cachep->nodelists[node];
3599 spin_lock(&l3->list_lock);
3601 struct array_cache *shared_array = l3->shared;
3602 int max = shared_array->limit - shared_array->avail;
3604 if (batchcount > max)
3606 memcpy(&(shared_array->entry[shared_array->avail]),
3607 ac->entry, sizeof(void *) * batchcount);
3608 shared_array->avail += batchcount;
3613 free_block(cachep, ac->entry, batchcount, node);
3618 struct list_head *p;
3620 p = l3->slabs_free.next;
3621 while (p != &(l3->slabs_free)) {
3624 slabp = list_entry(p, struct slab, list);
3625 BUG_ON(slabp->inuse);
3630 STATS_SET_FREEABLE(cachep, i);
3633 spin_unlock(&l3->list_lock);
3634 ac->avail -= batchcount;
3635 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3639 * Release an obj back to its cache. If the obj has a constructed state, it must
3640 * be in this state _before_ it is released. Called with disabled ints.
3642 static inline void __cache_free(struct kmem_cache *cachep, void *objp)
3644 struct array_cache *ac = cpu_cache_get(cachep);
3647 kmemleak_free_recursive(objp, cachep->flags);
3648 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3650 kmemcheck_slab_free(cachep, objp, obj_size(cachep));
3653 * Skip calling cache_free_alien() when the platform is not numa.
3654 * This will avoid cache misses that happen while accessing slabp (which
3655 * is per page memory reference) to get nodeid. Instead use a global
3656 * variable to skip the call, which is mostly likely to be present in
3659 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3662 if (likely(ac->avail < ac->limit)) {
3663 STATS_INC_FREEHIT(cachep);
3664 ac->entry[ac->avail++] = objp;
3667 STATS_INC_FREEMISS(cachep);
3668 cache_flusharray(cachep, ac);
3669 ac->entry[ac->avail++] = objp;
3674 * kmem_cache_alloc - Allocate an object
3675 * @cachep: The cache to allocate from.
3676 * @flags: See kmalloc().
3678 * Allocate an object from this cache. The flags are only relevant
3679 * if the cache has no available objects.
3681 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3683 void *ret = __cache_alloc(cachep, flags, __builtin_return_address(0));
3685 trace_kmem_cache_alloc(_RET_IP_, ret,
3686 obj_size(cachep), cachep->buffer_size, flags);
3690 EXPORT_SYMBOL(kmem_cache_alloc);
3692 #ifdef CONFIG_TRACING
3693 void *kmem_cache_alloc_notrace(struct kmem_cache *cachep, gfp_t flags)
3695 return __cache_alloc(cachep, flags, __builtin_return_address(0));
3697 EXPORT_SYMBOL(kmem_cache_alloc_notrace);
3701 * kmem_ptr_validate - check if an untrusted pointer might be a slab entry.
3702 * @cachep: the cache we're checking against
3703 * @ptr: pointer to validate
3705 * This verifies that the untrusted pointer looks sane;
3706 * it is _not_ a guarantee that the pointer is actually
3707 * part of the slab cache in question, but it at least
3708 * validates that the pointer can be dereferenced and
3709 * looks half-way sane.
3711 * Currently only used for dentry validation.
3713 int kmem_ptr_validate(struct kmem_cache *cachep, const void *ptr)
3715 unsigned long addr = (unsigned long)ptr;
3716 unsigned long min_addr = PAGE_OFFSET;
3717 unsigned long align_mask = BYTES_PER_WORD - 1;
3718 unsigned long size = cachep->buffer_size;
3721 if (unlikely(addr < min_addr))
3723 if (unlikely(addr > (unsigned long)high_memory - size))
3725 if (unlikely(addr & align_mask))
3727 if (unlikely(!kern_addr_valid(addr)))
3729 if (unlikely(!kern_addr_valid(addr + size - 1)))
3731 page = virt_to_page(ptr);
3732 if (unlikely(!PageSlab(page)))
3734 if (unlikely(page_get_cache(page) != cachep))
3742 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3744 void *ret = __cache_alloc_node(cachep, flags, nodeid,
3745 __builtin_return_address(0));
3747 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3748 obj_size(cachep), cachep->buffer_size,
3753 EXPORT_SYMBOL(kmem_cache_alloc_node);
3755 #ifdef CONFIG_TRACING
3756 void *kmem_cache_alloc_node_notrace(struct kmem_cache *cachep,
3760 return __cache_alloc_node(cachep, flags, nodeid,
3761 __builtin_return_address(0));
3763 EXPORT_SYMBOL(kmem_cache_alloc_node_notrace);
3766 static __always_inline void *
3767 __do_kmalloc_node(size_t size, gfp_t flags, int node, void *caller)
3769 struct kmem_cache *cachep;
3772 cachep = kmem_find_general_cachep(size, flags);
3773 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3775 ret = kmem_cache_alloc_node_notrace(cachep, flags, node);
3777 trace_kmalloc_node((unsigned long) caller, ret,
3778 size, cachep->buffer_size, flags, node);
3783 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3784 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3786 return __do_kmalloc_node(size, flags, node,
3787 __builtin_return_address(0));
3789 EXPORT_SYMBOL(__kmalloc_node);
3791 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3792 int node, unsigned long caller)
3794 return __do_kmalloc_node(size, flags, node, (void *)caller);
3796 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3798 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3800 return __do_kmalloc_node(size, flags, node, NULL);
3802 EXPORT_SYMBOL(__kmalloc_node);
3803 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3804 #endif /* CONFIG_NUMA */
3807 * __do_kmalloc - allocate memory
3808 * @size: how many bytes of memory are required.
3809 * @flags: the type of memory to allocate (see kmalloc).
3810 * @caller: function caller for debug tracking of the caller
3812 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3815 struct kmem_cache *cachep;
3818 /* If you want to save a few bytes .text space: replace
3820 * Then kmalloc uses the uninlined functions instead of the inline
3823 cachep = __find_general_cachep(size, flags);
3824 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3826 ret = __cache_alloc(cachep, flags, caller);
3828 trace_kmalloc((unsigned long) caller, ret,
3829 size, cachep->buffer_size, flags);
3835 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3836 void *__kmalloc(size_t size, gfp_t flags)
3838 return __do_kmalloc(size, flags, __builtin_return_address(0));
3840 EXPORT_SYMBOL(__kmalloc);
3842 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3844 return __do_kmalloc(size, flags, (void *)caller);
3846 EXPORT_SYMBOL(__kmalloc_track_caller);
3849 void *__kmalloc(size_t size, gfp_t flags)
3851 return __do_kmalloc(size, flags, NULL);
3853 EXPORT_SYMBOL(__kmalloc);
3857 * kmem_cache_free - Deallocate an object
3858 * @cachep: The cache the allocation was from.
3859 * @objp: The previously allocated object.
3861 * Free an object which was previously allocated from this
3864 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3866 unsigned long flags;
3868 local_irq_save(flags);
3869 debug_check_no_locks_freed(objp, obj_size(cachep));
3870 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3871 debug_check_no_obj_freed(objp, obj_size(cachep));
3872 __cache_free(cachep, objp);
3873 local_irq_restore(flags);
3875 trace_kmem_cache_free(_RET_IP_, objp);
3877 EXPORT_SYMBOL(kmem_cache_free);
3880 * kfree - free previously allocated memory
3881 * @objp: pointer returned by kmalloc.
3883 * If @objp is NULL, no operation is performed.
3885 * Don't free memory not originally allocated by kmalloc()
3886 * or you will run into trouble.
3888 void kfree(const void *objp)
3890 struct kmem_cache *c;
3891 unsigned long flags;
3893 trace_kfree(_RET_IP_, objp);
3895 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3897 local_irq_save(flags);
3898 kfree_debugcheck(objp);
3899 c = virt_to_cache(objp);
3900 debug_check_no_locks_freed(objp, obj_size(c));
3901 debug_check_no_obj_freed(objp, obj_size(c));
3902 __cache_free(c, (void *)objp);
3903 local_irq_restore(flags);
3905 EXPORT_SYMBOL(kfree);
3907 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3909 return obj_size(cachep);
3911 EXPORT_SYMBOL(kmem_cache_size);
3913 const char *kmem_cache_name(struct kmem_cache *cachep)
3915 return cachep->name;
3917 EXPORT_SYMBOL_GPL(kmem_cache_name);
3920 * Calculate the upper bound of pages required to sequentially allocate
3921 * @objects objects from @cachep.
3923 unsigned kmem_alloc_estimate(struct kmem_cache *cachep,
3924 gfp_t flags, int objects)
3927 * (1) memory for objects,
3929 unsigned nr_slabs = DIV_ROUND_UP(objects, cachep->num);
3930 unsigned nr_pages = nr_slabs << cachep->gfporder;
3933 * (2) memory for each per-cpu queue (nr_cpu_ids),
3934 * (3) memory for each per-node alien queues (nr_cpu_ids), and
3935 * (4) some amount of memory for the slab management structures
3937 * XXX: truely account these
3939 nr_pages += 1 + ilog2(nr_pages);
3945 * Calculate the upper bound of pages required to sequentially allocate
3946 * @count objects of @size bytes from kmalloc given @flags.
3948 unsigned kmalloc_estimate_objs(size_t size, gfp_t flags, int count)
3950 struct kmem_cache *s = kmem_find_general_cachep(size, flags);
3954 return kmem_alloc_estimate(s, flags, count);
3956 EXPORT_SYMBOL_GPL(kmalloc_estimate_objs);
3959 * Calculate the upper bound of pages requires to sequentially allocate @bytes
3960 * from kmalloc in an unspecified number of allocations of nonuniform size.
3962 unsigned kmalloc_estimate_bytes(gfp_t flags, size_t bytes)
3964 unsigned long pages;
3965 struct cache_sizes *csizep = malloc_sizes;
3968 * multiply by two, in order to account the worst case slack space
3969 * due to the power-of-two allocation sizes.
3971 pages = DIV_ROUND_UP(2 * bytes, PAGE_SIZE);
3974 * add the kmem_cache overhead of each possible kmalloc cache
3976 for (csizep = malloc_sizes; csizep->cs_cachep; csizep++) {
3977 struct kmem_cache *s;
3979 #ifdef CONFIG_ZONE_DMA
3980 if (unlikely(flags & __GFP_DMA))
3981 s = csizep->cs_dmacachep;
3984 s = csizep->cs_cachep;
3987 pages += kmem_alloc_estimate(s, flags, 0);
3992 EXPORT_SYMBOL_GPL(kmalloc_estimate_bytes);
3995 * This initializes kmem_list3 or resizes various caches for all nodes.
3997 static int alloc_kmemlist(struct kmem_cache *cachep, gfp_t gfp)
4000 struct kmem_list3 *l3;
4001 struct array_cache *new_shared;
4002 struct array_cache **new_alien = NULL;
4004 for_each_online_node(node) {
4006 if (use_alien_caches) {
4007 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
4013 if (cachep->shared) {
4014 new_shared = alloc_arraycache(node,
4015 cachep->shared*cachep->batchcount,
4018 free_alien_cache(new_alien);
4023 l3 = cachep->nodelists[node];
4025 struct array_cache *shared = l3->shared;
4027 spin_lock_irq(&l3->list_lock);
4030 free_block(cachep, shared->entry,
4031 shared->avail, node);
4033 l3->shared = new_shared;
4035 l3->alien = new_alien;
4038 l3->free_limit = (1 + nr_cpus_node(node)) *
4039 cachep->batchcount + cachep->num;
4040 spin_unlock_irq(&l3->list_lock);
4042 free_alien_cache(new_alien);
4045 l3 = kmalloc_node(sizeof(struct kmem_list3), gfp, node);
4047 free_alien_cache(new_alien);
4052 kmem_list3_init(l3);
4053 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
4054 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
4055 l3->shared = new_shared;
4056 l3->alien = new_alien;
4057 l3->free_limit = (1 + nr_cpus_node(node)) *
4058 cachep->batchcount + cachep->num;
4059 cachep->nodelists[node] = l3;
4064 if (!cachep->next.next) {
4065 /* Cache is not active yet. Roll back what we did */
4068 if (cachep->nodelists[node]) {
4069 l3 = cachep->nodelists[node];
4072 free_alien_cache(l3->alien);
4074 cachep->nodelists[node] = NULL;
4082 struct ccupdate_struct {
4083 struct kmem_cache *cachep;
4084 struct array_cache *new[NR_CPUS];
4087 static void do_ccupdate_local(void *info)
4089 struct ccupdate_struct *new = info;
4090 struct array_cache *old;
4093 old = cpu_cache_get(new->cachep);
4095 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
4096 new->new[smp_processor_id()] = old;
4099 /* Always called with the cache_chain_mutex held */
4100 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
4101 int batchcount, int shared, gfp_t gfp)
4103 struct ccupdate_struct *new;
4106 new = kzalloc(sizeof(*new), gfp);
4110 for_each_online_cpu(i) {
4111 new->new[i] = alloc_arraycache(cpu_to_node(i), limit,
4114 for (i--; i >= 0; i--)
4120 new->cachep = cachep;
4122 on_each_cpu(do_ccupdate_local, (void *)new, 1);
4125 cachep->batchcount = batchcount;
4126 cachep->limit = limit;
4127 cachep->shared = shared;
4129 for_each_online_cpu(i) {
4130 struct array_cache *ccold = new->new[i];
4133 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
4134 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
4135 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
4139 return alloc_kmemlist(cachep, gfp);
4142 /* Called with cache_chain_mutex held always */
4143 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
4149 * The head array serves three purposes:
4150 * - create a LIFO ordering, i.e. return objects that are cache-warm
4151 * - reduce the number of spinlock operations.
4152 * - reduce the number of linked list operations on the slab and
4153 * bufctl chains: array operations are cheaper.
4154 * The numbers are guessed, we should auto-tune as described by
4157 if (cachep->buffer_size > 131072)
4159 else if (cachep->buffer_size > PAGE_SIZE)
4161 else if (cachep->buffer_size > 1024)
4163 else if (cachep->buffer_size > 256)
4169 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4170 * allocation behaviour: Most allocs on one cpu, most free operations
4171 * on another cpu. For these cases, an efficient object passing between
4172 * cpus is necessary. This is provided by a shared array. The array
4173 * replaces Bonwick's magazine layer.
4174 * On uniprocessor, it's functionally equivalent (but less efficient)
4175 * to a larger limit. Thus disabled by default.
4178 if (cachep->buffer_size <= PAGE_SIZE && num_possible_cpus() > 1)
4183 * With debugging enabled, large batchcount lead to excessively long
4184 * periods with disabled local interrupts. Limit the batchcount
4189 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared, gfp);
4191 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4192 cachep->name, -err);
4197 * Drain an array if it contains any elements taking the l3 lock only if
4198 * necessary. Note that the l3 listlock also protects the array_cache
4199 * if drain_array() is used on the shared array.
4201 void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
4202 struct array_cache *ac, int force, int node)
4206 if (!ac || !ac->avail)
4208 if (ac->touched && !force) {
4211 spin_lock_irq(&l3->list_lock);
4213 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4214 if (tofree > ac->avail)
4215 tofree = (ac->avail + 1) / 2;
4216 free_block(cachep, ac->entry, tofree, node);
4217 ac->avail -= tofree;
4218 memmove(ac->entry, &(ac->entry[tofree]),
4219 sizeof(void *) * ac->avail);
4221 spin_unlock_irq(&l3->list_lock);
4226 * cache_reap - Reclaim memory from caches.
4227 * @w: work descriptor
4229 * Called from workqueue/eventd every few seconds.
4231 * - clear the per-cpu caches for this CPU.
4232 * - return freeable pages to the main free memory pool.
4234 * If we cannot acquire the cache chain mutex then just give up - we'll try
4235 * again on the next iteration.
4237 static void cache_reap(struct work_struct *w)
4239 struct kmem_cache *searchp;
4240 struct kmem_list3 *l3;
4241 int node = numa_slab_nid(NULL, GFP_KERNEL);
4242 struct delayed_work *work = to_delayed_work(w);
4244 if (!mutex_trylock(&cache_chain_mutex))
4245 /* Give up. Setup the next iteration. */
4248 list_for_each_entry(searchp, &cache_chain, next) {
4252 * We only take the l3 lock if absolutely necessary and we
4253 * have established with reasonable certainty that
4254 * we can do some work if the lock was obtained.
4256 l3 = searchp->nodelists[node];
4258 reap_alien(searchp, l3);
4260 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4263 * These are racy checks but it does not matter
4264 * if we skip one check or scan twice.
4266 if (time_after(l3->next_reap, jiffies))
4269 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4271 drain_array(searchp, l3, l3->shared, 0, node);
4273 if (l3->free_touched)
4274 l3->free_touched = 0;
4278 freed = drain_freelist(searchp, l3, (l3->free_limit +
4279 5 * searchp->num - 1) / (5 * searchp->num));
4280 STATS_ADD_REAPED(searchp, freed);
4286 mutex_unlock(&cache_chain_mutex);
4289 /* Set up the next iteration */
4290 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4293 #ifdef CONFIG_SLABINFO
4295 static void print_slabinfo_header(struct seq_file *m)
4298 * Output format version, so at least we can change it
4299 * without _too_ many complaints.
4302 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
4304 seq_puts(m, "slabinfo - version: 2.1\n");
4306 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4307 "<objperslab> <pagesperslab>");
4308 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4309 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4311 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
4312 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
4313 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
4318 static void *s_start(struct seq_file *m, loff_t *pos)
4322 mutex_lock(&cache_chain_mutex);
4324 print_slabinfo_header(m);
4326 return seq_list_start(&cache_chain, *pos);
4329 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4331 return seq_list_next(p, &cache_chain, pos);
4334 static void s_stop(struct seq_file *m, void *p)
4336 mutex_unlock(&cache_chain_mutex);
4339 static int s_show(struct seq_file *m, void *p)
4341 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4343 unsigned long active_objs;
4344 unsigned long num_objs;
4345 unsigned long active_slabs = 0;
4346 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4350 struct kmem_list3 *l3;
4354 for_each_online_node(node) {
4355 l3 = cachep->nodelists[node];
4360 spin_lock_irq(&l3->list_lock);
4362 list_for_each_entry(slabp, &l3->slabs_full, list) {
4363 if (slabp->inuse != cachep->num && !error)
4364 error = "slabs_full accounting error";
4365 active_objs += cachep->num;
4368 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4369 if (slabp->inuse == cachep->num && !error)
4370 error = "slabs_partial inuse accounting error";
4371 if (!slabp->inuse && !error)
4372 error = "slabs_partial/inuse accounting error";
4373 active_objs += slabp->inuse;
4376 list_for_each_entry(slabp, &l3->slabs_free, list) {
4377 if (slabp->inuse && !error)
4378 error = "slabs_free/inuse accounting error";
4381 free_objects += l3->free_objects;
4383 shared_avail += l3->shared->avail;
4385 spin_unlock_irq(&l3->list_lock);
4387 num_slabs += active_slabs;
4388 num_objs = num_slabs * cachep->num;
4389 if (num_objs - active_objs != free_objects && !error)
4390 error = "free_objects accounting error";
4392 name = cachep->name;
4394 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4396 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
4397 name, active_objs, num_objs, cachep->buffer_size,
4398 cachep->num, (1 << cachep->gfporder));
4399 seq_printf(m, " : tunables %4u %4u %4u",
4400 cachep->limit, cachep->batchcount, cachep->shared);
4401 seq_printf(m, " : slabdata %6lu %6lu %6lu",
4402 active_slabs, num_slabs, shared_avail);
4405 unsigned long high = cachep->high_mark;
4406 unsigned long allocs = cachep->num_allocations;
4407 unsigned long grown = cachep->grown;
4408 unsigned long reaped = cachep->reaped;
4409 unsigned long errors = cachep->errors;
4410 unsigned long max_freeable = cachep->max_freeable;
4411 unsigned long node_allocs = cachep->node_allocs;
4412 unsigned long node_frees = cachep->node_frees;
4413 unsigned long overflows = cachep->node_overflow;
4415 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
4416 %4lu %4lu %4lu %4lu %4lu", allocs, high, grown,
4417 reaped, errors, max_freeable, node_allocs,
4418 node_frees, overflows);
4422 unsigned long allochit = atomic_read(&cachep->allochit);
4423 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4424 unsigned long freehit = atomic_read(&cachep->freehit);
4425 unsigned long freemiss = atomic_read(&cachep->freemiss);
4427 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4428 allochit, allocmiss, freehit, freemiss);
4436 * slabinfo_op - iterator that generates /proc/slabinfo
4445 * num-pages-per-slab
4446 * + further values on SMP and with statistics enabled
4449 static const struct seq_operations slabinfo_op = {
4456 #define MAX_SLABINFO_WRITE 128
4458 * slabinfo_write - Tuning for the slab allocator
4460 * @buffer: user buffer
4461 * @count: data length
4464 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4465 size_t count, loff_t *ppos)
4467 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4468 int limit, batchcount, shared, res;
4469 struct kmem_cache *cachep;
4471 if (count > MAX_SLABINFO_WRITE)
4473 if (copy_from_user(&kbuf, buffer, count))
4475 kbuf[MAX_SLABINFO_WRITE] = '\0';
4477 tmp = strchr(kbuf, ' ');
4482 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4485 /* Find the cache in the chain of caches. */
4486 mutex_lock(&cache_chain_mutex);
4488 list_for_each_entry(cachep, &cache_chain, next) {
4489 if (!strcmp(cachep->name, kbuf)) {
4490 if (limit < 1 || batchcount < 1 ||
4491 batchcount > limit || shared < 0) {
4494 res = do_tune_cpucache(cachep, limit,
4501 mutex_unlock(&cache_chain_mutex);
4507 static int slabinfo_open(struct inode *inode, struct file *file)
4509 return seq_open(file, &slabinfo_op);
4512 static const struct file_operations proc_slabinfo_operations = {
4513 .open = slabinfo_open,
4515 .write = slabinfo_write,
4516 .llseek = seq_lseek,
4517 .release = seq_release,
4520 #ifdef CONFIG_DEBUG_SLAB_LEAK
4522 static void *leaks_start(struct seq_file *m, loff_t *pos)
4524 mutex_lock(&cache_chain_mutex);
4525 return seq_list_start(&cache_chain, *pos);
4528 static inline int add_caller(unsigned long *n, unsigned long v)
4538 unsigned long *q = p + 2 * i;
4552 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4558 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4564 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4565 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4567 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4572 static void show_symbol(struct seq_file *m, unsigned long address)
4574 #ifdef CONFIG_KALLSYMS
4575 unsigned long offset, size;
4576 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4578 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4579 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4581 seq_printf(m, " [%s]", modname);
4585 seq_printf(m, "%p", (void *)address);
4588 static int leaks_show(struct seq_file *m, void *p)
4590 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4592 struct kmem_list3 *l3;
4594 unsigned long *n = m->private;
4598 if (!(cachep->flags & SLAB_STORE_USER))
4600 if (!(cachep->flags & SLAB_RED_ZONE))
4603 /* OK, we can do it */
4607 for_each_online_node(node) {
4608 l3 = cachep->nodelists[node];
4613 spin_lock_irq(&l3->list_lock);
4615 list_for_each_entry(slabp, &l3->slabs_full, list)
4616 handle_slab(n, cachep, slabp);
4617 list_for_each_entry(slabp, &l3->slabs_partial, list)
4618 handle_slab(n, cachep, slabp);
4619 spin_unlock_irq(&l3->list_lock);
4621 name = cachep->name;
4623 /* Increase the buffer size */
4624 mutex_unlock(&cache_chain_mutex);
4625 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4627 /* Too bad, we are really out */
4629 mutex_lock(&cache_chain_mutex);
4632 *(unsigned long *)m->private = n[0] * 2;
4634 mutex_lock(&cache_chain_mutex);
4635 /* Now make sure this entry will be retried */
4639 for (i = 0; i < n[1]; i++) {
4640 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4641 show_symbol(m, n[2*i+2]);
4648 static const struct seq_operations slabstats_op = {
4649 .start = leaks_start,
4655 static int slabstats_open(struct inode *inode, struct file *file)
4657 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4660 ret = seq_open(file, &slabstats_op);
4662 struct seq_file *m = file->private_data;
4663 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4672 static const struct file_operations proc_slabstats_operations = {
4673 .open = slabstats_open,
4675 .llseek = seq_lseek,
4676 .release = seq_release_private,
4680 static int __init slab_proc_init(void)
4682 proc_create("slabinfo",S_IWUSR|S_IRUGO,NULL,&proc_slabinfo_operations);
4683 #ifdef CONFIG_DEBUG_SLAB_LEAK
4684 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4688 module_init(slab_proc_init);
4692 * ksize - get the actual amount of memory allocated for a given object
4693 * @objp: Pointer to the object
4695 * kmalloc may internally round up allocations and return more memory
4696 * than requested. ksize() can be used to determine the actual amount of
4697 * memory allocated. The caller may use this additional memory, even though
4698 * a smaller amount of memory was initially specified with the kmalloc call.
4699 * The caller must guarantee that objp points to a valid object previously
4700 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4701 * must not be freed during the duration of the call.
4703 size_t ksize(const void *objp)
4706 if (unlikely(objp == ZERO_SIZE_PTR))
4709 return obj_size(virt_to_cache(objp));
4711 EXPORT_SYMBOL(ksize);