3 * Written by Mark Hemment, 1996/97.
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.
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/rcupdate.h>
106 #include <linux/string.h>
107 #include <linux/uaccess.h>
108 #include <linux/nodemask.h>
109 #include <linux/kmemleak.h>
110 #include <linux/mempolicy.h>
111 #include <linux/mutex.h>
112 #include <linux/fault-inject.h>
113 #include <linux/rtmutex.h>
114 #include <linux/reciprocal_div.h>
115 #include <linux/debugobjects.h>
116 #include <linux/kmemcheck.h>
117 #include <linux/memory.h>
118 #include <linux/prefetch.h>
120 #include <asm/cacheflush.h>
121 #include <asm/tlbflush.h>
122 #include <asm/page.h>
125 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
126 * 0 for faster, smaller code (especially in the critical paths).
128 * STATS - 1 to collect stats for /proc/slabinfo.
129 * 0 for faster, smaller code (especially in the critical paths).
131 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
134 #ifdef CONFIG_DEBUG_SLAB
137 #define FORCED_DEBUG 1
141 #define FORCED_DEBUG 0
144 /* Shouldn't this be in a header file somewhere? */
145 #define BYTES_PER_WORD sizeof(void *)
146 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
148 #ifndef ARCH_KMALLOC_FLAGS
149 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
152 /* Legal flag mask for kmem_cache_create(). */
154 # define CREATE_MASK (SLAB_RED_ZONE | \
155 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
158 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
159 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
160 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE | SLAB_NOTRACK)
162 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
164 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
165 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
166 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE | SLAB_NOTRACK)
172 * Bufctl's are used for linking objs within a slab
175 * This implementation relies on "struct page" for locating the cache &
176 * slab an object belongs to.
177 * This allows the bufctl structure to be small (one int), but limits
178 * the number of objects a slab (not a cache) can contain when off-slab
179 * bufctls are used. The limit is the size of the largest general cache
180 * that does not use off-slab slabs.
181 * For 32bit archs with 4 kB pages, is this 56.
182 * This is not serious, as it is only for large objects, when it is unwise
183 * to have too many per slab.
184 * Note: This limit can be raised by introducing a general cache whose size
185 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
188 typedef unsigned int kmem_bufctl_t;
189 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
190 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
191 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
192 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
197 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
198 * arrange for kmem_freepages to be called via RCU. This is useful if
199 * we need to approach a kernel structure obliquely, from its address
200 * obtained without the usual locking. We can lock the structure to
201 * stabilize it and check it's still at the given address, only if we
202 * can be sure that the memory has not been meanwhile reused for some
203 * other kind of object (which our subsystem's lock might corrupt).
205 * rcu_read_lock before reading the address, then rcu_read_unlock after
206 * taking the spinlock within the structure expected at that address.
209 struct rcu_head head;
210 struct kmem_cache *cachep;
217 * Manages the objs in a slab. Placed either at the beginning of mem allocated
218 * for a slab, or allocated from an general cache.
219 * Slabs are chained into three list: fully used, partial, fully free slabs.
224 struct list_head list;
225 unsigned long colouroff;
226 void *s_mem; /* including colour offset */
227 unsigned int inuse; /* num of objs active in slab */
229 unsigned short nodeid;
231 struct slab_rcu __slab_cover_slab_rcu;
239 * - LIFO ordering, to hand out cache-warm objects from _alloc
240 * - reduce the number of linked list operations
241 * - reduce spinlock operations
243 * The limit is stored in the per-cpu structure to reduce the data cache
250 unsigned int batchcount;
251 unsigned int touched;
254 * Must have this definition in here for the proper
255 * alignment of array_cache. Also simplifies accessing
261 * bootstrap: The caches do not work without cpuarrays anymore, but the
262 * cpuarrays are allocated from the generic caches...
264 #define BOOT_CPUCACHE_ENTRIES 1
265 struct arraycache_init {
266 struct array_cache cache;
267 void *entries[BOOT_CPUCACHE_ENTRIES];
271 * The slab lists for all objects.
274 struct list_head slabs_partial; /* partial list first, better asm code */
275 struct list_head slabs_full;
276 struct list_head slabs_free;
277 unsigned long free_objects;
278 unsigned int free_limit;
279 unsigned int colour_next; /* Per-node cache coloring */
280 spinlock_t list_lock;
281 struct array_cache *shared; /* shared per node */
282 struct array_cache **alien; /* on other nodes */
283 unsigned long next_reap; /* updated without locking */
284 int free_touched; /* updated without locking */
288 * Need this for bootstrapping a per node allocator.
290 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
291 static struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
292 #define CACHE_CACHE 0
293 #define SIZE_AC MAX_NUMNODES
294 #define SIZE_L3 (2 * MAX_NUMNODES)
296 static int drain_freelist(struct kmem_cache *cache,
297 struct kmem_list3 *l3, int tofree);
298 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
300 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
301 static void cache_reap(struct work_struct *unused);
304 * This function must be completely optimized away if a constant is passed to
305 * it. Mostly the same as what is in linux/slab.h except it returns an index.
307 static __always_inline int index_of(const size_t size)
309 extern void __bad_size(void);
311 if (__builtin_constant_p(size)) {
319 #include <linux/kmalloc_sizes.h>
327 static int slab_early_init = 1;
329 #define INDEX_AC index_of(sizeof(struct arraycache_init))
330 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
332 static void kmem_list3_init(struct kmem_list3 *parent)
334 INIT_LIST_HEAD(&parent->slabs_full);
335 INIT_LIST_HEAD(&parent->slabs_partial);
336 INIT_LIST_HEAD(&parent->slabs_free);
337 parent->shared = NULL;
338 parent->alien = NULL;
339 parent->colour_next = 0;
340 spin_lock_init(&parent->list_lock);
341 parent->free_objects = 0;
342 parent->free_touched = 0;
345 #define MAKE_LIST(cachep, listp, slab, nodeid) \
347 INIT_LIST_HEAD(listp); \
348 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
351 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
353 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
354 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
355 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
358 #define CFLGS_OFF_SLAB (0x80000000UL)
359 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
361 #define BATCHREFILL_LIMIT 16
363 * Optimization question: fewer reaps means less probability for unnessary
364 * cpucache drain/refill cycles.
366 * OTOH the cpuarrays can contain lots of objects,
367 * which could lock up otherwise freeable slabs.
369 #define REAPTIMEOUT_CPUC (2*HZ)
370 #define REAPTIMEOUT_LIST3 (4*HZ)
373 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
374 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
375 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
376 #define STATS_INC_GROWN(x) ((x)->grown++)
377 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
378 #define STATS_SET_HIGH(x) \
380 if ((x)->num_active > (x)->high_mark) \
381 (x)->high_mark = (x)->num_active; \
383 #define STATS_INC_ERR(x) ((x)->errors++)
384 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
385 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
386 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
387 #define STATS_SET_FREEABLE(x, i) \
389 if ((x)->max_freeable < i) \
390 (x)->max_freeable = i; \
392 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
393 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
394 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
395 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
397 #define STATS_INC_ACTIVE(x) do { } while (0)
398 #define STATS_DEC_ACTIVE(x) do { } while (0)
399 #define STATS_INC_ALLOCED(x) do { } while (0)
400 #define STATS_INC_GROWN(x) do { } while (0)
401 #define STATS_ADD_REAPED(x,y) do { (void)(y); } while (0)
402 #define STATS_SET_HIGH(x) do { } while (0)
403 #define STATS_INC_ERR(x) do { } while (0)
404 #define STATS_INC_NODEALLOCS(x) do { } while (0)
405 #define STATS_INC_NODEFREES(x) do { } while (0)
406 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
407 #define STATS_SET_FREEABLE(x, i) do { } while (0)
408 #define STATS_INC_ALLOCHIT(x) do { } while (0)
409 #define STATS_INC_ALLOCMISS(x) do { } while (0)
410 #define STATS_INC_FREEHIT(x) do { } while (0)
411 #define STATS_INC_FREEMISS(x) do { } while (0)
417 * memory layout of objects:
419 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
420 * the end of an object is aligned with the end of the real
421 * allocation. Catches writes behind the end of the allocation.
422 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
424 * cachep->obj_offset: The real object.
425 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
426 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
427 * [BYTES_PER_WORD long]
429 static int obj_offset(struct kmem_cache *cachep)
431 return cachep->obj_offset;
434 static int obj_size(struct kmem_cache *cachep)
436 return cachep->obj_size;
439 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
441 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
442 return (unsigned long long*) (objp + obj_offset(cachep) -
443 sizeof(unsigned long long));
446 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
448 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
449 if (cachep->flags & SLAB_STORE_USER)
450 return (unsigned long long *)(objp + cachep->buffer_size -
451 sizeof(unsigned long long) -
453 return (unsigned long long *) (objp + cachep->buffer_size -
454 sizeof(unsigned long long));
457 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
459 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
460 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
465 #define obj_offset(x) 0
466 #define obj_size(cachep) (cachep->buffer_size)
467 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
468 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
469 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
473 #ifdef CONFIG_TRACING
474 size_t slab_buffer_size(struct kmem_cache *cachep)
476 return cachep->buffer_size;
478 EXPORT_SYMBOL(slab_buffer_size);
482 * Do not go above this order unless 0 objects fit into the slab or
483 * overridden on the command line.
485 #define SLAB_MAX_ORDER_HI 1
486 #define SLAB_MAX_ORDER_LO 0
487 static int slab_max_order = SLAB_MAX_ORDER_LO;
488 static bool slab_max_order_set __initdata;
491 * Functions for storing/retrieving the cachep and or slab from the page
492 * allocator. These are used to find the slab an obj belongs to. With kfree(),
493 * these are used to find the cache which an obj belongs to.
495 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
497 page->lru.next = (struct list_head *)cache;
500 static inline struct kmem_cache *page_get_cache(struct page *page)
502 page = compound_head(page);
503 BUG_ON(!PageSlab(page));
504 return (struct kmem_cache *)page->lru.next;
507 static inline void page_set_slab(struct page *page, struct slab *slab)
509 page->lru.prev = (struct list_head *)slab;
512 static inline struct slab *page_get_slab(struct page *page)
514 BUG_ON(!PageSlab(page));
515 return (struct slab *)page->lru.prev;
518 static inline struct kmem_cache *virt_to_cache(const void *obj)
520 struct page *page = virt_to_head_page(obj);
521 return page_get_cache(page);
524 static inline struct slab *virt_to_slab(const void *obj)
526 struct page *page = virt_to_head_page(obj);
527 return page_get_slab(page);
530 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
533 return slab->s_mem + cache->buffer_size * idx;
537 * We want to avoid an expensive divide : (offset / cache->buffer_size)
538 * Using the fact that buffer_size is a constant for a particular cache,
539 * we can replace (offset / cache->buffer_size) by
540 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
542 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
543 const struct slab *slab, void *obj)
545 u32 offset = (obj - slab->s_mem);
546 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
550 * These are the default caches for kmalloc. Custom caches can have other sizes.
552 struct cache_sizes malloc_sizes[] = {
553 #define CACHE(x) { .cs_size = (x) },
554 #include <linux/kmalloc_sizes.h>
558 EXPORT_SYMBOL(malloc_sizes);
560 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
566 static struct cache_names __initdata cache_names[] = {
567 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
568 #include <linux/kmalloc_sizes.h>
573 static struct arraycache_init initarray_cache __initdata =
574 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
575 static struct arraycache_init initarray_generic =
576 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
578 /* internal cache of cache description objs */
579 static struct kmem_list3 *cache_cache_nodelists[MAX_NUMNODES];
580 static struct kmem_cache cache_cache = {
581 .nodelists = cache_cache_nodelists,
583 .limit = BOOT_CPUCACHE_ENTRIES,
585 .buffer_size = sizeof(struct kmem_cache),
586 .name = "kmem_cache",
589 #define BAD_ALIEN_MAGIC 0x01020304ul
592 * chicken and egg problem: delay the per-cpu array allocation
593 * until the general caches are up.
605 * used by boot code to determine if it can use slab based allocator
607 int slab_is_available(void)
609 return g_cpucache_up >= EARLY;
612 #ifdef CONFIG_LOCKDEP
615 * Slab sometimes uses the kmalloc slabs to store the slab headers
616 * for other slabs "off slab".
617 * The locking for this is tricky in that it nests within the locks
618 * of all other slabs in a few places; to deal with this special
619 * locking we put on-slab caches into a separate lock-class.
621 * We set lock class for alien array caches which are up during init.
622 * The lock annotation will be lost if all cpus of a node goes down and
623 * then comes back up during hotplug
625 static struct lock_class_key on_slab_l3_key;
626 static struct lock_class_key on_slab_alc_key;
628 static struct lock_class_key debugobj_l3_key;
629 static struct lock_class_key debugobj_alc_key;
631 static void slab_set_lock_classes(struct kmem_cache *cachep,
632 struct lock_class_key *l3_key, struct lock_class_key *alc_key,
635 struct array_cache **alc;
636 struct kmem_list3 *l3;
639 l3 = cachep->nodelists[q];
643 lockdep_set_class(&l3->list_lock, l3_key);
646 * FIXME: This check for BAD_ALIEN_MAGIC
647 * should go away when common slab code is taught to
648 * work even without alien caches.
649 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
650 * for alloc_alien_cache,
652 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
656 lockdep_set_class(&alc[r]->lock, alc_key);
660 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
662 slab_set_lock_classes(cachep, &debugobj_l3_key, &debugobj_alc_key, node);
665 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
669 for_each_online_node(node)
670 slab_set_debugobj_lock_classes_node(cachep, node);
673 static void init_node_lock_keys(int q)
675 struct cache_sizes *s = malloc_sizes;
677 if (g_cpucache_up < LATE)
680 for (s = malloc_sizes; s->cs_size != ULONG_MAX; s++) {
681 struct kmem_list3 *l3;
683 l3 = s->cs_cachep->nodelists[q];
684 if (!l3 || OFF_SLAB(s->cs_cachep))
687 slab_set_lock_classes(s->cs_cachep, &on_slab_l3_key,
688 &on_slab_alc_key, q);
692 static inline void init_lock_keys(void)
697 init_node_lock_keys(node);
700 static void init_node_lock_keys(int q)
704 static inline void init_lock_keys(void)
708 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
712 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
718 * Guard access to the cache-chain.
720 static DEFINE_MUTEX(cache_chain_mutex);
721 static struct list_head cache_chain;
723 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
725 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
727 return cachep->array[smp_processor_id()];
730 static inline struct kmem_cache *__find_general_cachep(size_t size,
733 struct cache_sizes *csizep = malloc_sizes;
736 /* This happens if someone tries to call
737 * kmem_cache_create(), or __kmalloc(), before
738 * the generic caches are initialized.
740 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
743 return ZERO_SIZE_PTR;
745 while (size > csizep->cs_size)
749 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
750 * has cs_{dma,}cachep==NULL. Thus no special case
751 * for large kmalloc calls required.
753 #ifdef CONFIG_ZONE_DMA
754 if (unlikely(gfpflags & GFP_DMA))
755 return csizep->cs_dmacachep;
757 return csizep->cs_cachep;
760 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
762 return __find_general_cachep(size, gfpflags);
765 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
767 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
771 * Calculate the number of objects and left-over bytes for a given buffer size.
773 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
774 size_t align, int flags, size_t *left_over,
779 size_t slab_size = PAGE_SIZE << gfporder;
782 * The slab management structure can be either off the slab or
783 * on it. For the latter case, the memory allocated for a
787 * - One kmem_bufctl_t for each object
788 * - Padding to respect alignment of @align
789 * - @buffer_size bytes for each object
791 * If the slab management structure is off the slab, then the
792 * alignment will already be calculated into the size. Because
793 * the slabs are all pages aligned, the objects will be at the
794 * correct alignment when allocated.
796 if (flags & CFLGS_OFF_SLAB) {
798 nr_objs = slab_size / buffer_size;
800 if (nr_objs > SLAB_LIMIT)
801 nr_objs = SLAB_LIMIT;
804 * Ignore padding for the initial guess. The padding
805 * is at most @align-1 bytes, and @buffer_size is at
806 * least @align. In the worst case, this result will
807 * be one greater than the number of objects that fit
808 * into the memory allocation when taking the padding
811 nr_objs = (slab_size - sizeof(struct slab)) /
812 (buffer_size + sizeof(kmem_bufctl_t));
815 * This calculated number will be either the right
816 * amount, or one greater than what we want.
818 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
822 if (nr_objs > SLAB_LIMIT)
823 nr_objs = SLAB_LIMIT;
825 mgmt_size = slab_mgmt_size(nr_objs, align);
828 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
831 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
833 static void __slab_error(const char *function, struct kmem_cache *cachep,
836 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
837 function, cachep->name, msg);
842 * By default on NUMA we use alien caches to stage the freeing of
843 * objects allocated from other nodes. This causes massive memory
844 * inefficiencies when using fake NUMA setup to split memory into a
845 * large number of small nodes, so it can be disabled on the command
849 static int use_alien_caches __read_mostly = 1;
850 static int __init noaliencache_setup(char *s)
852 use_alien_caches = 0;
855 __setup("noaliencache", noaliencache_setup);
857 static int __init slab_max_order_setup(char *str)
859 get_option(&str, &slab_max_order);
860 slab_max_order = slab_max_order < 0 ? 0 :
861 min(slab_max_order, MAX_ORDER - 1);
862 slab_max_order_set = true;
866 __setup("slab_max_order=", slab_max_order_setup);
870 * Special reaping functions for NUMA systems called from cache_reap().
871 * These take care of doing round robin flushing of alien caches (containing
872 * objects freed on different nodes from which they were allocated) and the
873 * flushing of remote pcps by calling drain_node_pages.
875 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
877 static void init_reap_node(int cpu)
881 node = next_node(cpu_to_mem(cpu), node_online_map);
882 if (node == MAX_NUMNODES)
883 node = first_node(node_online_map);
885 per_cpu(slab_reap_node, cpu) = node;
888 static void next_reap_node(void)
890 int node = __this_cpu_read(slab_reap_node);
892 node = next_node(node, node_online_map);
893 if (unlikely(node >= MAX_NUMNODES))
894 node = first_node(node_online_map);
895 __this_cpu_write(slab_reap_node, node);
899 #define init_reap_node(cpu) do { } while (0)
900 #define next_reap_node(void) do { } while (0)
904 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
905 * via the workqueue/eventd.
906 * Add the CPU number into the expiration time to minimize the possibility of
907 * the CPUs getting into lockstep and contending for the global cache chain
910 static void __cpuinit start_cpu_timer(int cpu)
912 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
915 * When this gets called from do_initcalls via cpucache_init(),
916 * init_workqueues() has already run, so keventd will be setup
919 if (keventd_up() && reap_work->work.func == NULL) {
921 INIT_DELAYED_WORK_DEFERRABLE(reap_work, cache_reap);
922 schedule_delayed_work_on(cpu, reap_work,
923 __round_jiffies_relative(HZ, cpu));
927 static struct array_cache *alloc_arraycache(int node, int entries,
928 int batchcount, gfp_t gfp)
930 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
931 struct array_cache *nc = NULL;
933 nc = kmalloc_node(memsize, gfp, node);
935 * The array_cache structures contain pointers to free object.
936 * However, when such objects are allocated or transferred to another
937 * cache the pointers are not cleared and they could be counted as
938 * valid references during a kmemleak scan. Therefore, kmemleak must
939 * not scan such objects.
941 kmemleak_no_scan(nc);
945 nc->batchcount = batchcount;
947 spin_lock_init(&nc->lock);
953 * Transfer objects in one arraycache to another.
954 * Locking must be handled by the caller.
956 * Return the number of entries transferred.
958 static int transfer_objects(struct array_cache *to,
959 struct array_cache *from, unsigned int max)
961 /* Figure out how many entries to transfer */
962 int nr = min3(from->avail, max, to->limit - to->avail);
967 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
977 #define drain_alien_cache(cachep, alien) do { } while (0)
978 #define reap_alien(cachep, l3) do { } while (0)
980 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
982 return (struct array_cache **)BAD_ALIEN_MAGIC;
985 static inline void free_alien_cache(struct array_cache **ac_ptr)
989 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
994 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
1000 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
1001 gfp_t flags, int nodeid)
1006 #else /* CONFIG_NUMA */
1008 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
1009 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1011 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
1013 struct array_cache **ac_ptr;
1014 int memsize = sizeof(void *) * nr_node_ids;
1019 ac_ptr = kzalloc_node(memsize, gfp, node);
1022 if (i == node || !node_online(i))
1024 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
1026 for (i--; i >= 0; i--)
1036 static void free_alien_cache(struct array_cache **ac_ptr)
1047 static void __drain_alien_cache(struct kmem_cache *cachep,
1048 struct array_cache *ac, int node)
1050 struct kmem_list3 *rl3 = cachep->nodelists[node];
1053 spin_lock(&rl3->list_lock);
1055 * Stuff objects into the remote nodes shared array first.
1056 * That way we could avoid the overhead of putting the objects
1057 * into the free lists and getting them back later.
1060 transfer_objects(rl3->shared, ac, ac->limit);
1062 free_block(cachep, ac->entry, ac->avail, node);
1064 spin_unlock(&rl3->list_lock);
1069 * Called from cache_reap() to regularly drain alien caches round robin.
1071 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1073 int node = __this_cpu_read(slab_reap_node);
1076 struct array_cache *ac = l3->alien[node];
1078 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1079 __drain_alien_cache(cachep, ac, node);
1080 spin_unlock_irq(&ac->lock);
1085 static void drain_alien_cache(struct kmem_cache *cachep,
1086 struct array_cache **alien)
1089 struct array_cache *ac;
1090 unsigned long flags;
1092 for_each_online_node(i) {
1095 spin_lock_irqsave(&ac->lock, flags);
1096 __drain_alien_cache(cachep, ac, i);
1097 spin_unlock_irqrestore(&ac->lock, flags);
1102 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1104 struct slab *slabp = virt_to_slab(objp);
1105 int nodeid = slabp->nodeid;
1106 struct kmem_list3 *l3;
1107 struct array_cache *alien = NULL;
1110 node = numa_mem_id();
1113 * Make sure we are not freeing a object from another node to the array
1114 * cache on this cpu.
1116 if (likely(slabp->nodeid == node))
1119 l3 = cachep->nodelists[node];
1120 STATS_INC_NODEFREES(cachep);
1121 if (l3->alien && l3->alien[nodeid]) {
1122 alien = l3->alien[nodeid];
1123 spin_lock(&alien->lock);
1124 if (unlikely(alien->avail == alien->limit)) {
1125 STATS_INC_ACOVERFLOW(cachep);
1126 __drain_alien_cache(cachep, alien, nodeid);
1128 alien->entry[alien->avail++] = objp;
1129 spin_unlock(&alien->lock);
1131 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1132 free_block(cachep, &objp, 1, nodeid);
1133 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1140 * Allocates and initializes nodelists for a node on each slab cache, used for
1141 * either memory or cpu hotplug. If memory is being hot-added, the kmem_list3
1142 * will be allocated off-node since memory is not yet online for the new node.
1143 * When hotplugging memory or a cpu, existing nodelists are not replaced if
1146 * Must hold cache_chain_mutex.
1148 static int init_cache_nodelists_node(int node)
1150 struct kmem_cache *cachep;
1151 struct kmem_list3 *l3;
1152 const int memsize = sizeof(struct kmem_list3);
1154 list_for_each_entry(cachep, &cache_chain, next) {
1156 * Set up the size64 kmemlist for cpu before we can
1157 * begin anything. Make sure some other cpu on this
1158 * node has not already allocated this
1160 if (!cachep->nodelists[node]) {
1161 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1164 kmem_list3_init(l3);
1165 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1166 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1169 * The l3s don't come and go as CPUs come and
1170 * go. cache_chain_mutex is sufficient
1173 cachep->nodelists[node] = l3;
1176 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1177 cachep->nodelists[node]->free_limit =
1178 (1 + nr_cpus_node(node)) *
1179 cachep->batchcount + cachep->num;
1180 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1185 static void __cpuinit cpuup_canceled(long cpu)
1187 struct kmem_cache *cachep;
1188 struct kmem_list3 *l3 = NULL;
1189 int node = cpu_to_mem(cpu);
1190 const struct cpumask *mask = cpumask_of_node(node);
1192 list_for_each_entry(cachep, &cache_chain, next) {
1193 struct array_cache *nc;
1194 struct array_cache *shared;
1195 struct array_cache **alien;
1197 /* cpu is dead; no one can alloc from it. */
1198 nc = cachep->array[cpu];
1199 cachep->array[cpu] = NULL;
1200 l3 = cachep->nodelists[node];
1203 goto free_array_cache;
1205 spin_lock_irq(&l3->list_lock);
1207 /* Free limit for this kmem_list3 */
1208 l3->free_limit -= cachep->batchcount;
1210 free_block(cachep, nc->entry, nc->avail, node);
1212 if (!cpumask_empty(mask)) {
1213 spin_unlock_irq(&l3->list_lock);
1214 goto free_array_cache;
1217 shared = l3->shared;
1219 free_block(cachep, shared->entry,
1220 shared->avail, node);
1227 spin_unlock_irq(&l3->list_lock);
1231 drain_alien_cache(cachep, alien);
1232 free_alien_cache(alien);
1238 * In the previous loop, all the objects were freed to
1239 * the respective cache's slabs, now we can go ahead and
1240 * shrink each nodelist to its limit.
1242 list_for_each_entry(cachep, &cache_chain, next) {
1243 l3 = cachep->nodelists[node];
1246 drain_freelist(cachep, l3, l3->free_objects);
1250 static int __cpuinit cpuup_prepare(long cpu)
1252 struct kmem_cache *cachep;
1253 struct kmem_list3 *l3 = NULL;
1254 int node = cpu_to_mem(cpu);
1258 * We need to do this right in the beginning since
1259 * alloc_arraycache's are going to use this list.
1260 * kmalloc_node allows us to add the slab to the right
1261 * kmem_list3 and not this cpu's kmem_list3
1263 err = init_cache_nodelists_node(node);
1268 * Now we can go ahead with allocating the shared arrays and
1271 list_for_each_entry(cachep, &cache_chain, next) {
1272 struct array_cache *nc;
1273 struct array_cache *shared = NULL;
1274 struct array_cache **alien = NULL;
1276 nc = alloc_arraycache(node, cachep->limit,
1277 cachep->batchcount, GFP_KERNEL);
1280 if (cachep->shared) {
1281 shared = alloc_arraycache(node,
1282 cachep->shared * cachep->batchcount,
1283 0xbaadf00d, GFP_KERNEL);
1289 if (use_alien_caches) {
1290 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1297 cachep->array[cpu] = nc;
1298 l3 = cachep->nodelists[node];
1301 spin_lock_irq(&l3->list_lock);
1304 * We are serialised from CPU_DEAD or
1305 * CPU_UP_CANCELLED by the cpucontrol lock
1307 l3->shared = shared;
1316 spin_unlock_irq(&l3->list_lock);
1318 free_alien_cache(alien);
1319 if (cachep->flags & SLAB_DEBUG_OBJECTS)
1320 slab_set_debugobj_lock_classes_node(cachep, node);
1322 init_node_lock_keys(node);
1326 cpuup_canceled(cpu);
1330 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1331 unsigned long action, void *hcpu)
1333 long cpu = (long)hcpu;
1337 case CPU_UP_PREPARE:
1338 case CPU_UP_PREPARE_FROZEN:
1339 mutex_lock(&cache_chain_mutex);
1340 err = cpuup_prepare(cpu);
1341 mutex_unlock(&cache_chain_mutex);
1344 case CPU_ONLINE_FROZEN:
1345 start_cpu_timer(cpu);
1347 #ifdef CONFIG_HOTPLUG_CPU
1348 case CPU_DOWN_PREPARE:
1349 case CPU_DOWN_PREPARE_FROZEN:
1351 * Shutdown cache reaper. Note that the cache_chain_mutex is
1352 * held so that if cache_reap() is invoked it cannot do
1353 * anything expensive but will only modify reap_work
1354 * and reschedule the timer.
1356 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1357 /* Now the cache_reaper is guaranteed to be not running. */
1358 per_cpu(slab_reap_work, cpu).work.func = NULL;
1360 case CPU_DOWN_FAILED:
1361 case CPU_DOWN_FAILED_FROZEN:
1362 start_cpu_timer(cpu);
1365 case CPU_DEAD_FROZEN:
1367 * Even if all the cpus of a node are down, we don't free the
1368 * kmem_list3 of any cache. This to avoid a race between
1369 * cpu_down, and a kmalloc allocation from another cpu for
1370 * memory from the node of the cpu going down. The list3
1371 * structure is usually allocated from kmem_cache_create() and
1372 * gets destroyed at kmem_cache_destroy().
1376 case CPU_UP_CANCELED:
1377 case CPU_UP_CANCELED_FROZEN:
1378 mutex_lock(&cache_chain_mutex);
1379 cpuup_canceled(cpu);
1380 mutex_unlock(&cache_chain_mutex);
1383 return notifier_from_errno(err);
1386 static struct notifier_block __cpuinitdata cpucache_notifier = {
1387 &cpuup_callback, NULL, 0
1390 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1392 * Drains freelist for a node on each slab cache, used for memory hot-remove.
1393 * Returns -EBUSY if all objects cannot be drained so that the node is not
1396 * Must hold cache_chain_mutex.
1398 static int __meminit drain_cache_nodelists_node(int node)
1400 struct kmem_cache *cachep;
1403 list_for_each_entry(cachep, &cache_chain, next) {
1404 struct kmem_list3 *l3;
1406 l3 = cachep->nodelists[node];
1410 drain_freelist(cachep, l3, l3->free_objects);
1412 if (!list_empty(&l3->slabs_full) ||
1413 !list_empty(&l3->slabs_partial)) {
1421 static int __meminit slab_memory_callback(struct notifier_block *self,
1422 unsigned long action, void *arg)
1424 struct memory_notify *mnb = arg;
1428 nid = mnb->status_change_nid;
1433 case MEM_GOING_ONLINE:
1434 mutex_lock(&cache_chain_mutex);
1435 ret = init_cache_nodelists_node(nid);
1436 mutex_unlock(&cache_chain_mutex);
1438 case MEM_GOING_OFFLINE:
1439 mutex_lock(&cache_chain_mutex);
1440 ret = drain_cache_nodelists_node(nid);
1441 mutex_unlock(&cache_chain_mutex);
1445 case MEM_CANCEL_ONLINE:
1446 case MEM_CANCEL_OFFLINE:
1450 return notifier_from_errno(ret);
1452 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1455 * swap the static kmem_list3 with kmalloced memory
1457 static void __init init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1460 struct kmem_list3 *ptr;
1462 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_NOWAIT, nodeid);
1465 memcpy(ptr, list, sizeof(struct kmem_list3));
1467 * Do not assume that spinlocks can be initialized via memcpy:
1469 spin_lock_init(&ptr->list_lock);
1471 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1472 cachep->nodelists[nodeid] = ptr;
1476 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1477 * size of kmem_list3.
1479 static void __init set_up_list3s(struct kmem_cache *cachep, int index)
1483 for_each_online_node(node) {
1484 cachep->nodelists[node] = &initkmem_list3[index + node];
1485 cachep->nodelists[node]->next_reap = jiffies +
1487 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1492 * Initialisation. Called after the page allocator have been initialised and
1493 * before smp_init().
1495 void __init kmem_cache_init(void)
1498 struct cache_sizes *sizes;
1499 struct cache_names *names;
1504 if (num_possible_nodes() == 1)
1505 use_alien_caches = 0;
1507 for (i = 0; i < NUM_INIT_LISTS; i++) {
1508 kmem_list3_init(&initkmem_list3[i]);
1509 if (i < MAX_NUMNODES)
1510 cache_cache.nodelists[i] = NULL;
1512 set_up_list3s(&cache_cache, CACHE_CACHE);
1515 * Fragmentation resistance on low memory - only use bigger
1516 * page orders on machines with more than 32MB of memory if
1517 * not overridden on the command line.
1519 if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1520 slab_max_order = SLAB_MAX_ORDER_HI;
1522 /* Bootstrap is tricky, because several objects are allocated
1523 * from caches that do not exist yet:
1524 * 1) initialize the cache_cache cache: it contains the struct
1525 * kmem_cache structures of all caches, except cache_cache itself:
1526 * cache_cache is statically allocated.
1527 * Initially an __init data area is used for the head array and the
1528 * kmem_list3 structures, it's replaced with a kmalloc allocated
1529 * array at the end of the bootstrap.
1530 * 2) Create the first kmalloc cache.
1531 * The struct kmem_cache for the new cache is allocated normally.
1532 * An __init data area is used for the head array.
1533 * 3) Create the remaining kmalloc caches, with minimally sized
1535 * 4) Replace the __init data head arrays for cache_cache and the first
1536 * kmalloc cache with kmalloc allocated arrays.
1537 * 5) Replace the __init data for kmem_list3 for cache_cache and
1538 * the other cache's with kmalloc allocated memory.
1539 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1542 node = numa_mem_id();
1544 /* 1) create the cache_cache */
1545 INIT_LIST_HEAD(&cache_chain);
1546 list_add(&cache_cache.next, &cache_chain);
1547 cache_cache.colour_off = cache_line_size();
1548 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1549 cache_cache.nodelists[node] = &initkmem_list3[CACHE_CACHE + node];
1552 * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1554 cache_cache.buffer_size = offsetof(struct kmem_cache, array[nr_cpu_ids]) +
1555 nr_node_ids * sizeof(struct kmem_list3 *);
1557 cache_cache.obj_size = cache_cache.buffer_size;
1559 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1561 cache_cache.reciprocal_buffer_size =
1562 reciprocal_value(cache_cache.buffer_size);
1564 for (order = 0; order < MAX_ORDER; order++) {
1565 cache_estimate(order, cache_cache.buffer_size,
1566 cache_line_size(), 0, &left_over, &cache_cache.num);
1567 if (cache_cache.num)
1570 BUG_ON(!cache_cache.num);
1571 cache_cache.gfporder = order;
1572 cache_cache.colour = left_over / cache_cache.colour_off;
1573 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1574 sizeof(struct slab), cache_line_size());
1576 /* 2+3) create the kmalloc caches */
1577 sizes = malloc_sizes;
1578 names = cache_names;
1581 * Initialize the caches that provide memory for the array cache and the
1582 * kmem_list3 structures first. Without this, further allocations will
1586 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1587 sizes[INDEX_AC].cs_size,
1588 ARCH_KMALLOC_MINALIGN,
1589 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1592 if (INDEX_AC != INDEX_L3) {
1593 sizes[INDEX_L3].cs_cachep =
1594 kmem_cache_create(names[INDEX_L3].name,
1595 sizes[INDEX_L3].cs_size,
1596 ARCH_KMALLOC_MINALIGN,
1597 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1601 slab_early_init = 0;
1603 while (sizes->cs_size != ULONG_MAX) {
1605 * For performance, all the general caches are L1 aligned.
1606 * This should be particularly beneficial on SMP boxes, as it
1607 * eliminates "false sharing".
1608 * Note for systems short on memory removing the alignment will
1609 * allow tighter packing of the smaller caches.
1611 if (!sizes->cs_cachep) {
1612 sizes->cs_cachep = kmem_cache_create(names->name,
1614 ARCH_KMALLOC_MINALIGN,
1615 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1618 #ifdef CONFIG_ZONE_DMA
1619 sizes->cs_dmacachep = kmem_cache_create(
1622 ARCH_KMALLOC_MINALIGN,
1623 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1630 /* 4) Replace the bootstrap head arrays */
1632 struct array_cache *ptr;
1634 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1636 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1637 memcpy(ptr, cpu_cache_get(&cache_cache),
1638 sizeof(struct arraycache_init));
1640 * Do not assume that spinlocks can be initialized via memcpy:
1642 spin_lock_init(&ptr->lock);
1644 cache_cache.array[smp_processor_id()] = ptr;
1646 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1648 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1649 != &initarray_generic.cache);
1650 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1651 sizeof(struct arraycache_init));
1653 * Do not assume that spinlocks can be initialized via memcpy:
1655 spin_lock_init(&ptr->lock);
1657 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1660 /* 5) Replace the bootstrap kmem_list3's */
1664 for_each_online_node(nid) {
1665 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE + nid], nid);
1667 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1668 &initkmem_list3[SIZE_AC + nid], nid);
1670 if (INDEX_AC != INDEX_L3) {
1671 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1672 &initkmem_list3[SIZE_L3 + nid], nid);
1677 g_cpucache_up = EARLY;
1680 void __init kmem_cache_init_late(void)
1682 struct kmem_cache *cachep;
1684 g_cpucache_up = LATE;
1686 /* Annotate slab for lockdep -- annotate the malloc caches */
1689 /* 6) resize the head arrays to their final sizes */
1690 mutex_lock(&cache_chain_mutex);
1691 list_for_each_entry(cachep, &cache_chain, next)
1692 if (enable_cpucache(cachep, GFP_NOWAIT))
1694 mutex_unlock(&cache_chain_mutex);
1697 g_cpucache_up = FULL;
1700 * Register a cpu startup notifier callback that initializes
1701 * cpu_cache_get for all new cpus
1703 register_cpu_notifier(&cpucache_notifier);
1707 * Register a memory hotplug callback that initializes and frees
1710 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1714 * The reap timers are started later, with a module init call: That part
1715 * of the kernel is not yet operational.
1719 static int __init cpucache_init(void)
1724 * Register the timers that return unneeded pages to the page allocator
1726 for_each_online_cpu(cpu)
1727 start_cpu_timer(cpu);
1730 __initcall(cpucache_init);
1733 * Interface to system's page allocator. No need to hold the cache-lock.
1735 * If we requested dmaable memory, we will get it. Even if we
1736 * did not request dmaable memory, we might get it, but that
1737 * would be relatively rare and ignorable.
1739 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1747 * Nommu uses slab's for process anonymous memory allocations, and thus
1748 * requires __GFP_COMP to properly refcount higher order allocations
1750 flags |= __GFP_COMP;
1753 flags |= cachep->gfpflags;
1754 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1755 flags |= __GFP_RECLAIMABLE;
1757 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1761 nr_pages = (1 << cachep->gfporder);
1762 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1763 add_zone_page_state(page_zone(page),
1764 NR_SLAB_RECLAIMABLE, nr_pages);
1766 add_zone_page_state(page_zone(page),
1767 NR_SLAB_UNRECLAIMABLE, nr_pages);
1768 for (i = 0; i < nr_pages; i++)
1769 __SetPageSlab(page + i);
1771 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1772 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1775 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1777 kmemcheck_mark_unallocated_pages(page, nr_pages);
1780 return page_address(page);
1784 * Interface to system's page release.
1786 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1788 unsigned long i = (1 << cachep->gfporder);
1789 struct page *page = virt_to_page(addr);
1790 const unsigned long nr_freed = i;
1792 kmemcheck_free_shadow(page, cachep->gfporder);
1794 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1795 sub_zone_page_state(page_zone(page),
1796 NR_SLAB_RECLAIMABLE, nr_freed);
1798 sub_zone_page_state(page_zone(page),
1799 NR_SLAB_UNRECLAIMABLE, nr_freed);
1801 BUG_ON(!PageSlab(page));
1802 __ClearPageSlab(page);
1805 if (current->reclaim_state)
1806 current->reclaim_state->reclaimed_slab += nr_freed;
1807 free_pages((unsigned long)addr, cachep->gfporder);
1810 static void kmem_rcu_free(struct rcu_head *head)
1812 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1813 struct kmem_cache *cachep = slab_rcu->cachep;
1815 kmem_freepages(cachep, slab_rcu->addr);
1816 if (OFF_SLAB(cachep))
1817 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1822 #ifdef CONFIG_DEBUG_PAGEALLOC
1823 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1824 unsigned long caller)
1826 int size = obj_size(cachep);
1828 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1830 if (size < 5 * sizeof(unsigned long))
1833 *addr++ = 0x12345678;
1835 *addr++ = smp_processor_id();
1836 size -= 3 * sizeof(unsigned long);
1838 unsigned long *sptr = &caller;
1839 unsigned long svalue;
1841 while (!kstack_end(sptr)) {
1843 if (kernel_text_address(svalue)) {
1845 size -= sizeof(unsigned long);
1846 if (size <= sizeof(unsigned long))
1852 *addr++ = 0x87654321;
1856 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1858 int size = obj_size(cachep);
1859 addr = &((char *)addr)[obj_offset(cachep)];
1861 memset(addr, val, size);
1862 *(unsigned char *)(addr + size - 1) = POISON_END;
1865 static void dump_line(char *data, int offset, int limit)
1868 unsigned char error = 0;
1871 printk(KERN_ERR "%03x: ", offset);
1872 for (i = 0; i < limit; i++) {
1873 if (data[offset + i] != POISON_FREE) {
1874 error = data[offset + i];
1878 print_hex_dump(KERN_CONT, "", 0, 16, 1,
1879 &data[offset], limit, 1);
1881 if (bad_count == 1) {
1882 error ^= POISON_FREE;
1883 if (!(error & (error - 1))) {
1884 printk(KERN_ERR "Single bit error detected. Probably "
1887 printk(KERN_ERR "Run memtest86+ or a similar memory "
1890 printk(KERN_ERR "Run a memory test tool.\n");
1899 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1904 if (cachep->flags & SLAB_RED_ZONE) {
1905 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1906 *dbg_redzone1(cachep, objp),
1907 *dbg_redzone2(cachep, objp));
1910 if (cachep->flags & SLAB_STORE_USER) {
1911 printk(KERN_ERR "Last user: [<%p>]",
1912 *dbg_userword(cachep, objp));
1913 print_symbol("(%s)",
1914 (unsigned long)*dbg_userword(cachep, objp));
1917 realobj = (char *)objp + obj_offset(cachep);
1918 size = obj_size(cachep);
1919 for (i = 0; i < size && lines; i += 16, lines--) {
1922 if (i + limit > size)
1924 dump_line(realobj, i, limit);
1928 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1934 realobj = (char *)objp + obj_offset(cachep);
1935 size = obj_size(cachep);
1937 for (i = 0; i < size; i++) {
1938 char exp = POISON_FREE;
1941 if (realobj[i] != exp) {
1947 "Slab corruption (%s): %s start=%p, len=%d\n",
1948 print_tainted(), cachep->name, realobj, size);
1949 print_objinfo(cachep, objp, 0);
1951 /* Hexdump the affected line */
1954 if (i + limit > size)
1956 dump_line(realobj, i, limit);
1959 /* Limit to 5 lines */
1965 /* Print some data about the neighboring objects, if they
1968 struct slab *slabp = virt_to_slab(objp);
1971 objnr = obj_to_index(cachep, slabp, objp);
1973 objp = index_to_obj(cachep, slabp, objnr - 1);
1974 realobj = (char *)objp + obj_offset(cachep);
1975 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1977 print_objinfo(cachep, objp, 2);
1979 if (objnr + 1 < cachep->num) {
1980 objp = index_to_obj(cachep, slabp, objnr + 1);
1981 realobj = (char *)objp + obj_offset(cachep);
1982 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1984 print_objinfo(cachep, objp, 2);
1991 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
1994 for (i = 0; i < cachep->num; i++) {
1995 void *objp = index_to_obj(cachep, slabp, i);
1997 if (cachep->flags & SLAB_POISON) {
1998 #ifdef CONFIG_DEBUG_PAGEALLOC
1999 if (cachep->buffer_size % PAGE_SIZE == 0 &&
2001 kernel_map_pages(virt_to_page(objp),
2002 cachep->buffer_size / PAGE_SIZE, 1);
2004 check_poison_obj(cachep, objp);
2006 check_poison_obj(cachep, objp);
2009 if (cachep->flags & SLAB_RED_ZONE) {
2010 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2011 slab_error(cachep, "start of a freed object "
2013 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2014 slab_error(cachep, "end of a freed object "
2020 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
2026 * slab_destroy - destroy and release all objects in a slab
2027 * @cachep: cache pointer being destroyed
2028 * @slabp: slab pointer being destroyed
2030 * Destroy all the objs in a slab, and release the mem back to the system.
2031 * Before calling the slab must have been unlinked from the cache. The
2032 * cache-lock is not held/needed.
2034 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
2036 void *addr = slabp->s_mem - slabp->colouroff;
2038 slab_destroy_debugcheck(cachep, slabp);
2039 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2040 struct slab_rcu *slab_rcu;
2042 slab_rcu = (struct slab_rcu *)slabp;
2043 slab_rcu->cachep = cachep;
2044 slab_rcu->addr = addr;
2045 call_rcu(&slab_rcu->head, kmem_rcu_free);
2047 kmem_freepages(cachep, addr);
2048 if (OFF_SLAB(cachep))
2049 kmem_cache_free(cachep->slabp_cache, slabp);
2053 static void __kmem_cache_destroy(struct kmem_cache *cachep)
2056 struct kmem_list3 *l3;
2058 for_each_online_cpu(i)
2059 kfree(cachep->array[i]);
2061 /* NUMA: free the list3 structures */
2062 for_each_online_node(i) {
2063 l3 = cachep->nodelists[i];
2066 free_alien_cache(l3->alien);
2070 kmem_cache_free(&cache_cache, cachep);
2075 * calculate_slab_order - calculate size (page order) of slabs
2076 * @cachep: pointer to the cache that is being created
2077 * @size: size of objects to be created in this cache.
2078 * @align: required alignment for the objects.
2079 * @flags: slab allocation flags
2081 * Also calculates the number of objects per slab.
2083 * This could be made much more intelligent. For now, try to avoid using
2084 * high order pages for slabs. When the gfp() functions are more friendly
2085 * towards high-order requests, this should be changed.
2087 static size_t calculate_slab_order(struct kmem_cache *cachep,
2088 size_t size, size_t align, unsigned long flags)
2090 unsigned long offslab_limit;
2091 size_t left_over = 0;
2094 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2098 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2102 if (flags & CFLGS_OFF_SLAB) {
2104 * Max number of objs-per-slab for caches which
2105 * use off-slab slabs. Needed to avoid a possible
2106 * looping condition in cache_grow().
2108 offslab_limit = size - sizeof(struct slab);
2109 offslab_limit /= sizeof(kmem_bufctl_t);
2111 if (num > offslab_limit)
2115 /* Found something acceptable - save it away */
2117 cachep->gfporder = gfporder;
2118 left_over = remainder;
2121 * A VFS-reclaimable slab tends to have most allocations
2122 * as GFP_NOFS and we really don't want to have to be allocating
2123 * higher-order pages when we are unable to shrink dcache.
2125 if (flags & SLAB_RECLAIM_ACCOUNT)
2129 * Large number of objects is good, but very large slabs are
2130 * currently bad for the gfp()s.
2132 if (gfporder >= slab_max_order)
2136 * Acceptable internal fragmentation?
2138 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2144 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2146 if (g_cpucache_up == FULL)
2147 return enable_cpucache(cachep, gfp);
2149 if (g_cpucache_up == NONE) {
2151 * Note: the first kmem_cache_create must create the cache
2152 * that's used by kmalloc(24), otherwise the creation of
2153 * further caches will BUG().
2155 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2158 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2159 * the first cache, then we need to set up all its list3s,
2160 * otherwise the creation of further caches will BUG().
2162 set_up_list3s(cachep, SIZE_AC);
2163 if (INDEX_AC == INDEX_L3)
2164 g_cpucache_up = PARTIAL_L3;
2166 g_cpucache_up = PARTIAL_AC;
2168 cachep->array[smp_processor_id()] =
2169 kmalloc(sizeof(struct arraycache_init), gfp);
2171 if (g_cpucache_up == PARTIAL_AC) {
2172 set_up_list3s(cachep, SIZE_L3);
2173 g_cpucache_up = PARTIAL_L3;
2176 for_each_online_node(node) {
2177 cachep->nodelists[node] =
2178 kmalloc_node(sizeof(struct kmem_list3),
2180 BUG_ON(!cachep->nodelists[node]);
2181 kmem_list3_init(cachep->nodelists[node]);
2185 cachep->nodelists[numa_mem_id()]->next_reap =
2186 jiffies + REAPTIMEOUT_LIST3 +
2187 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2189 cpu_cache_get(cachep)->avail = 0;
2190 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2191 cpu_cache_get(cachep)->batchcount = 1;
2192 cpu_cache_get(cachep)->touched = 0;
2193 cachep->batchcount = 1;
2194 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2199 * kmem_cache_create - Create a cache.
2200 * @name: A string which is used in /proc/slabinfo to identify this cache.
2201 * @size: The size of objects to be created in this cache.
2202 * @align: The required alignment for the objects.
2203 * @flags: SLAB flags
2204 * @ctor: A constructor for the objects.
2206 * Returns a ptr to the cache on success, NULL on failure.
2207 * Cannot be called within a int, but can be interrupted.
2208 * The @ctor is run when new pages are allocated by the cache.
2210 * @name must be valid until the cache is destroyed. This implies that
2211 * the module calling this has to destroy the cache before getting unloaded.
2215 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2216 * to catch references to uninitialised memory.
2218 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2219 * for buffer overruns.
2221 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2222 * cacheline. This can be beneficial if you're counting cycles as closely
2226 kmem_cache_create (const char *name, size_t size, size_t align,
2227 unsigned long flags, void (*ctor)(void *))
2229 size_t left_over, slab_size, ralign;
2230 struct kmem_cache *cachep = NULL, *pc;
2234 * Sanity checks... these are all serious usage bugs.
2236 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
2237 size > KMALLOC_MAX_SIZE) {
2238 printk(KERN_ERR "%s: Early error in slab %s\n", __func__,
2244 * We use cache_chain_mutex to ensure a consistent view of
2245 * cpu_online_mask as well. Please see cpuup_callback
2247 if (slab_is_available()) {
2249 mutex_lock(&cache_chain_mutex);
2252 list_for_each_entry(pc, &cache_chain, next) {
2257 * This happens when the module gets unloaded and doesn't
2258 * destroy its slab cache and no-one else reuses the vmalloc
2259 * area of the module. Print a warning.
2261 res = probe_kernel_address(pc->name, tmp);
2264 "SLAB: cache with size %d has lost its name\n",
2269 if (!strcmp(pc->name, name)) {
2271 "kmem_cache_create: duplicate cache %s\n", name);
2278 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2281 * Enable redzoning and last user accounting, except for caches with
2282 * large objects, if the increased size would increase the object size
2283 * above the next power of two: caches with object sizes just above a
2284 * power of two have a significant amount of internal fragmentation.
2286 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2287 2 * sizeof(unsigned long long)))
2288 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2289 if (!(flags & SLAB_DESTROY_BY_RCU))
2290 flags |= SLAB_POISON;
2292 if (flags & SLAB_DESTROY_BY_RCU)
2293 BUG_ON(flags & SLAB_POISON);
2296 * Always checks flags, a caller might be expecting debug support which
2299 BUG_ON(flags & ~CREATE_MASK);
2302 * Check that size is in terms of words. This is needed to avoid
2303 * unaligned accesses for some archs when redzoning is used, and makes
2304 * sure any on-slab bufctl's are also correctly aligned.
2306 if (size & (BYTES_PER_WORD - 1)) {
2307 size += (BYTES_PER_WORD - 1);
2308 size &= ~(BYTES_PER_WORD - 1);
2311 /* calculate the final buffer alignment: */
2313 /* 1) arch recommendation: can be overridden for debug */
2314 if (flags & SLAB_HWCACHE_ALIGN) {
2316 * Default alignment: as specified by the arch code. Except if
2317 * an object is really small, then squeeze multiple objects into
2320 ralign = cache_line_size();
2321 while (size <= ralign / 2)
2324 ralign = BYTES_PER_WORD;
2328 * Redzoning and user store require word alignment or possibly larger.
2329 * Note this will be overridden by architecture or caller mandated
2330 * alignment if either is greater than BYTES_PER_WORD.
2332 if (flags & SLAB_STORE_USER)
2333 ralign = BYTES_PER_WORD;
2335 if (flags & SLAB_RED_ZONE) {
2336 ralign = REDZONE_ALIGN;
2337 /* If redzoning, ensure that the second redzone is suitably
2338 * aligned, by adjusting the object size accordingly. */
2339 size += REDZONE_ALIGN - 1;
2340 size &= ~(REDZONE_ALIGN - 1);
2343 /* 2) arch mandated alignment */
2344 if (ralign < ARCH_SLAB_MINALIGN) {
2345 ralign = ARCH_SLAB_MINALIGN;
2347 /* 3) caller mandated alignment */
2348 if (ralign < align) {
2351 /* disable debug if necessary */
2352 if (ralign > __alignof__(unsigned long long))
2353 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2359 if (slab_is_available())
2364 /* Get cache's description obj. */
2365 cachep = kmem_cache_zalloc(&cache_cache, gfp);
2369 cachep->nodelists = (struct kmem_list3 **)&cachep->array[nr_cpu_ids];
2371 cachep->obj_size = size;
2374 * Both debugging options require word-alignment which is calculated
2377 if (flags & SLAB_RED_ZONE) {
2378 /* add space for red zone words */
2379 cachep->obj_offset += sizeof(unsigned long long);
2380 size += 2 * sizeof(unsigned long long);
2382 if (flags & SLAB_STORE_USER) {
2383 /* user store requires one word storage behind the end of
2384 * the real object. But if the second red zone needs to be
2385 * aligned to 64 bits, we must allow that much space.
2387 if (flags & SLAB_RED_ZONE)
2388 size += REDZONE_ALIGN;
2390 size += BYTES_PER_WORD;
2392 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2393 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2394 && cachep->obj_size > cache_line_size() && ALIGN(size, align) < PAGE_SIZE) {
2395 cachep->obj_offset += PAGE_SIZE - ALIGN(size, align);
2402 * Determine if the slab management is 'on' or 'off' slab.
2403 * (bootstrapping cannot cope with offslab caches so don't do
2404 * it too early on. Always use on-slab management when
2405 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2407 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init &&
2408 !(flags & SLAB_NOLEAKTRACE))
2410 * Size is large, assume best to place the slab management obj
2411 * off-slab (should allow better packing of objs).
2413 flags |= CFLGS_OFF_SLAB;
2415 size = ALIGN(size, align);
2417 left_over = calculate_slab_order(cachep, size, align, flags);
2421 "kmem_cache_create: couldn't create cache %s.\n", name);
2422 kmem_cache_free(&cache_cache, cachep);
2426 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2427 + sizeof(struct slab), align);
2430 * If the slab has been placed off-slab, and we have enough space then
2431 * move it on-slab. This is at the expense of any extra colouring.
2433 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2434 flags &= ~CFLGS_OFF_SLAB;
2435 left_over -= slab_size;
2438 if (flags & CFLGS_OFF_SLAB) {
2439 /* really off slab. No need for manual alignment */
2441 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2443 #ifdef CONFIG_PAGE_POISONING
2444 /* If we're going to use the generic kernel_map_pages()
2445 * poisoning, then it's going to smash the contents of
2446 * the redzone and userword anyhow, so switch them off.
2448 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2449 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2453 cachep->colour_off = cache_line_size();
2454 /* Offset must be a multiple of the alignment. */
2455 if (cachep->colour_off < align)
2456 cachep->colour_off = align;
2457 cachep->colour = left_over / cachep->colour_off;
2458 cachep->slab_size = slab_size;
2459 cachep->flags = flags;
2460 cachep->gfpflags = 0;
2461 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2462 cachep->gfpflags |= GFP_DMA;
2463 cachep->buffer_size = size;
2464 cachep->reciprocal_buffer_size = reciprocal_value(size);
2466 if (flags & CFLGS_OFF_SLAB) {
2467 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2469 * This is a possibility for one of the malloc_sizes caches.
2470 * But since we go off slab only for object size greater than
2471 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2472 * this should not happen at all.
2473 * But leave a BUG_ON for some lucky dude.
2475 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2477 cachep->ctor = ctor;
2478 cachep->name = name;
2480 if (setup_cpu_cache(cachep, gfp)) {
2481 __kmem_cache_destroy(cachep);
2486 if (flags & SLAB_DEBUG_OBJECTS) {
2488 * Would deadlock through slab_destroy()->call_rcu()->
2489 * debug_object_activate()->kmem_cache_alloc().
2491 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2493 slab_set_debugobj_lock_classes(cachep);
2496 /* cache setup completed, link it into the list */
2497 list_add(&cachep->next, &cache_chain);
2499 if (!cachep && (flags & SLAB_PANIC))
2500 panic("kmem_cache_create(): failed to create slab `%s'\n",
2502 if (slab_is_available()) {
2503 mutex_unlock(&cache_chain_mutex);
2508 EXPORT_SYMBOL(kmem_cache_create);
2511 static void check_irq_off(void)
2513 BUG_ON(!irqs_disabled());
2516 static void check_irq_on(void)
2518 BUG_ON(irqs_disabled());
2521 static void check_spinlock_acquired(struct kmem_cache *cachep)
2525 assert_spin_locked(&cachep->nodelists[numa_mem_id()]->list_lock);
2529 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2533 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2538 #define check_irq_off() do { } while(0)
2539 #define check_irq_on() do { } while(0)
2540 #define check_spinlock_acquired(x) do { } while(0)
2541 #define check_spinlock_acquired_node(x, y) do { } while(0)
2544 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2545 struct array_cache *ac,
2546 int force, int node);
2548 static void do_drain(void *arg)
2550 struct kmem_cache *cachep = arg;
2551 struct array_cache *ac;
2552 int node = numa_mem_id();
2555 ac = cpu_cache_get(cachep);
2556 spin_lock(&cachep->nodelists[node]->list_lock);
2557 free_block(cachep, ac->entry, ac->avail, node);
2558 spin_unlock(&cachep->nodelists[node]->list_lock);
2562 static void drain_cpu_caches(struct kmem_cache *cachep)
2564 struct kmem_list3 *l3;
2567 on_each_cpu(do_drain, cachep, 1);
2569 for_each_online_node(node) {
2570 l3 = cachep->nodelists[node];
2571 if (l3 && l3->alien)
2572 drain_alien_cache(cachep, l3->alien);
2575 for_each_online_node(node) {
2576 l3 = cachep->nodelists[node];
2578 drain_array(cachep, l3, l3->shared, 1, node);
2583 * Remove slabs from the list of free slabs.
2584 * Specify the number of slabs to drain in tofree.
2586 * Returns the actual number of slabs released.
2588 static int drain_freelist(struct kmem_cache *cache,
2589 struct kmem_list3 *l3, int tofree)
2591 struct list_head *p;
2596 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2598 spin_lock_irq(&l3->list_lock);
2599 p = l3->slabs_free.prev;
2600 if (p == &l3->slabs_free) {
2601 spin_unlock_irq(&l3->list_lock);
2605 slabp = list_entry(p, struct slab, list);
2607 BUG_ON(slabp->inuse);
2609 list_del(&slabp->list);
2611 * Safe to drop the lock. The slab is no longer linked
2614 l3->free_objects -= cache->num;
2615 spin_unlock_irq(&l3->list_lock);
2616 slab_destroy(cache, slabp);
2623 /* Called with cache_chain_mutex held to protect against cpu hotplug */
2624 static int __cache_shrink(struct kmem_cache *cachep)
2627 struct kmem_list3 *l3;
2629 drain_cpu_caches(cachep);
2632 for_each_online_node(i) {
2633 l3 = cachep->nodelists[i];
2637 drain_freelist(cachep, l3, l3->free_objects);
2639 ret += !list_empty(&l3->slabs_full) ||
2640 !list_empty(&l3->slabs_partial);
2642 return (ret ? 1 : 0);
2646 * kmem_cache_shrink - Shrink a cache.
2647 * @cachep: The cache to shrink.
2649 * Releases as many slabs as possible for a cache.
2650 * To help debugging, a zero exit status indicates all slabs were released.
2652 int kmem_cache_shrink(struct kmem_cache *cachep)
2655 BUG_ON(!cachep || in_interrupt());
2658 mutex_lock(&cache_chain_mutex);
2659 ret = __cache_shrink(cachep);
2660 mutex_unlock(&cache_chain_mutex);
2664 EXPORT_SYMBOL(kmem_cache_shrink);
2667 * kmem_cache_destroy - delete a cache
2668 * @cachep: the cache to destroy
2670 * Remove a &struct kmem_cache object from the slab cache.
2672 * It is expected this function will be called by a module when it is
2673 * unloaded. This will remove the cache completely, and avoid a duplicate
2674 * cache being allocated each time a module is loaded and unloaded, if the
2675 * module doesn't have persistent in-kernel storage across loads and unloads.
2677 * The cache must be empty before calling this function.
2679 * The caller must guarantee that no one will allocate memory from the cache
2680 * during the kmem_cache_destroy().
2682 void kmem_cache_destroy(struct kmem_cache *cachep)
2684 BUG_ON(!cachep || in_interrupt());
2686 /* Find the cache in the chain of caches. */
2688 mutex_lock(&cache_chain_mutex);
2690 * the chain is never empty, cache_cache is never destroyed
2692 list_del(&cachep->next);
2693 if (__cache_shrink(cachep)) {
2694 slab_error(cachep, "Can't free all objects");
2695 list_add(&cachep->next, &cache_chain);
2696 mutex_unlock(&cache_chain_mutex);
2701 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2704 __kmem_cache_destroy(cachep);
2705 mutex_unlock(&cache_chain_mutex);
2708 EXPORT_SYMBOL(kmem_cache_destroy);
2711 * Get the memory for a slab management obj.
2712 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2713 * always come from malloc_sizes caches. The slab descriptor cannot
2714 * come from the same cache which is getting created because,
2715 * when we are searching for an appropriate cache for these
2716 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2717 * If we are creating a malloc_sizes cache here it would not be visible to
2718 * kmem_find_general_cachep till the initialization is complete.
2719 * Hence we cannot have slabp_cache same as the original cache.
2721 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2722 int colour_off, gfp_t local_flags,
2727 if (OFF_SLAB(cachep)) {
2728 /* Slab management obj is off-slab. */
2729 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2730 local_flags, nodeid);
2732 * If the first object in the slab is leaked (it's allocated
2733 * but no one has a reference to it), we want to make sure
2734 * kmemleak does not treat the ->s_mem pointer as a reference
2735 * to the object. Otherwise we will not report the leak.
2737 kmemleak_scan_area(&slabp->list, sizeof(struct list_head),
2742 slabp = objp + colour_off;
2743 colour_off += cachep->slab_size;
2746 slabp->colouroff = colour_off;
2747 slabp->s_mem = objp + colour_off;
2748 slabp->nodeid = nodeid;
2753 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2755 return (kmem_bufctl_t *) (slabp + 1);
2758 static void cache_init_objs(struct kmem_cache *cachep,
2763 for (i = 0; i < cachep->num; i++) {
2764 void *objp = index_to_obj(cachep, slabp, i);
2766 /* need to poison the objs? */
2767 if (cachep->flags & SLAB_POISON)
2768 poison_obj(cachep, objp, POISON_FREE);
2769 if (cachep->flags & SLAB_STORE_USER)
2770 *dbg_userword(cachep, objp) = NULL;
2772 if (cachep->flags & SLAB_RED_ZONE) {
2773 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2774 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2777 * Constructors are not allowed to allocate memory from the same
2778 * cache which they are a constructor for. Otherwise, deadlock.
2779 * They must also be threaded.
2781 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2782 cachep->ctor(objp + obj_offset(cachep));
2784 if (cachep->flags & SLAB_RED_ZONE) {
2785 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2786 slab_error(cachep, "constructor overwrote the"
2787 " end of an object");
2788 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2789 slab_error(cachep, "constructor overwrote the"
2790 " start of an object");
2792 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2793 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2794 kernel_map_pages(virt_to_page(objp),
2795 cachep->buffer_size / PAGE_SIZE, 0);
2800 slab_bufctl(slabp)[i] = i + 1;
2802 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2805 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2807 if (CONFIG_ZONE_DMA_FLAG) {
2808 if (flags & GFP_DMA)
2809 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2811 BUG_ON(cachep->gfpflags & GFP_DMA);
2815 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2818 void *objp = index_to_obj(cachep, slabp, slabp->free);
2822 next = slab_bufctl(slabp)[slabp->free];
2824 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2825 WARN_ON(slabp->nodeid != nodeid);
2832 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2833 void *objp, int nodeid)
2835 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2838 /* Verify that the slab belongs to the intended node */
2839 WARN_ON(slabp->nodeid != nodeid);
2841 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2842 printk(KERN_ERR "slab: double free detected in cache "
2843 "'%s', objp %p\n", cachep->name, objp);
2847 slab_bufctl(slabp)[objnr] = slabp->free;
2848 slabp->free = objnr;
2853 * Map pages beginning at addr to the given cache and slab. This is required
2854 * for the slab allocator to be able to lookup the cache and slab of a
2855 * virtual address for kfree, ksize, and slab debugging.
2857 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2863 page = virt_to_page(addr);
2866 if (likely(!PageCompound(page)))
2867 nr_pages <<= cache->gfporder;
2870 page_set_cache(page, cache);
2871 page_set_slab(page, slab);
2873 } while (--nr_pages);
2877 * Grow (by 1) the number of slabs within a cache. This is called by
2878 * kmem_cache_alloc() when there are no active objs left in a cache.
2880 static int cache_grow(struct kmem_cache *cachep,
2881 gfp_t flags, int nodeid, void *objp)
2886 struct kmem_list3 *l3;
2889 * Be lazy and only check for valid flags here, keeping it out of the
2890 * critical path in kmem_cache_alloc().
2892 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2893 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2895 /* Take the l3 list lock to change the colour_next on this node */
2897 l3 = cachep->nodelists[nodeid];
2898 spin_lock(&l3->list_lock);
2900 /* Get colour for the slab, and cal the next value. */
2901 offset = l3->colour_next;
2903 if (l3->colour_next >= cachep->colour)
2904 l3->colour_next = 0;
2905 spin_unlock(&l3->list_lock);
2907 offset *= cachep->colour_off;
2909 if (local_flags & __GFP_WAIT)
2913 * The test for missing atomic flag is performed here, rather than
2914 * the more obvious place, simply to reduce the critical path length
2915 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2916 * will eventually be caught here (where it matters).
2918 kmem_flagcheck(cachep, flags);
2921 * Get mem for the objs. Attempt to allocate a physical page from
2925 objp = kmem_getpages(cachep, local_flags, nodeid);
2929 /* Get slab management. */
2930 slabp = alloc_slabmgmt(cachep, objp, offset,
2931 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2935 slab_map_pages(cachep, slabp, objp);
2937 cache_init_objs(cachep, slabp);
2939 if (local_flags & __GFP_WAIT)
2940 local_irq_disable();
2942 spin_lock(&l3->list_lock);
2944 /* Make slab active. */
2945 list_add_tail(&slabp->list, &(l3->slabs_free));
2946 STATS_INC_GROWN(cachep);
2947 l3->free_objects += cachep->num;
2948 spin_unlock(&l3->list_lock);
2951 kmem_freepages(cachep, objp);
2953 if (local_flags & __GFP_WAIT)
2954 local_irq_disable();
2961 * Perform extra freeing checks:
2962 * - detect bad pointers.
2963 * - POISON/RED_ZONE checking
2965 static void kfree_debugcheck(const void *objp)
2967 if (!virt_addr_valid(objp)) {
2968 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2969 (unsigned long)objp);
2974 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2976 unsigned long long redzone1, redzone2;
2978 redzone1 = *dbg_redzone1(cache, obj);
2979 redzone2 = *dbg_redzone2(cache, obj);
2984 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2987 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2988 slab_error(cache, "double free detected");
2990 slab_error(cache, "memory outside object was overwritten");
2992 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2993 obj, redzone1, redzone2);
2996 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
3003 BUG_ON(virt_to_cache(objp) != cachep);
3005 objp -= obj_offset(cachep);
3006 kfree_debugcheck(objp);
3007 page = virt_to_head_page(objp);
3009 slabp = page_get_slab(page);
3011 if (cachep->flags & SLAB_RED_ZONE) {
3012 verify_redzone_free(cachep, objp);
3013 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
3014 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
3016 if (cachep->flags & SLAB_STORE_USER)
3017 *dbg_userword(cachep, objp) = caller;
3019 objnr = obj_to_index(cachep, slabp, objp);
3021 BUG_ON(objnr >= cachep->num);
3022 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
3024 #ifdef CONFIG_DEBUG_SLAB_LEAK
3025 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
3027 if (cachep->flags & SLAB_POISON) {
3028 #ifdef CONFIG_DEBUG_PAGEALLOC
3029 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
3030 store_stackinfo(cachep, objp, (unsigned long)caller);
3031 kernel_map_pages(virt_to_page(objp),
3032 cachep->buffer_size / PAGE_SIZE, 0);
3034 poison_obj(cachep, objp, POISON_FREE);
3037 poison_obj(cachep, objp, POISON_FREE);
3043 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
3048 /* Check slab's freelist to see if this obj is there. */
3049 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
3051 if (entries > cachep->num || i >= cachep->num)
3054 if (entries != cachep->num - slabp->inuse) {
3056 printk(KERN_ERR "slab: Internal list corruption detected in "
3057 "cache '%s'(%d), slabp %p(%d). Tainted(%s). Hexdump:\n",
3058 cachep->name, cachep->num, slabp, slabp->inuse,
3060 print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 16, 1, slabp,
3061 sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t),
3067 #define kfree_debugcheck(x) do { } while(0)
3068 #define cache_free_debugcheck(x,objp,z) (objp)
3069 #define check_slabp(x,y) do { } while(0)
3072 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
3075 struct kmem_list3 *l3;
3076 struct array_cache *ac;
3081 node = numa_mem_id();
3082 ac = cpu_cache_get(cachep);
3083 batchcount = ac->batchcount;
3084 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
3086 * If there was little recent activity on this cache, then
3087 * perform only a partial refill. Otherwise we could generate
3090 batchcount = BATCHREFILL_LIMIT;
3092 l3 = cachep->nodelists[node];
3094 BUG_ON(ac->avail > 0 || !l3);
3095 spin_lock(&l3->list_lock);
3097 /* See if we can refill from the shared array */
3098 if (l3->shared && transfer_objects(ac, l3->shared, batchcount)) {
3099 l3->shared->touched = 1;
3103 while (batchcount > 0) {
3104 struct list_head *entry;
3106 /* Get slab alloc is to come from. */
3107 entry = l3->slabs_partial.next;
3108 if (entry == &l3->slabs_partial) {
3109 l3->free_touched = 1;
3110 entry = l3->slabs_free.next;
3111 if (entry == &l3->slabs_free)
3115 slabp = list_entry(entry, struct slab, list);
3116 check_slabp(cachep, slabp);
3117 check_spinlock_acquired(cachep);
3120 * The slab was either on partial or free list so
3121 * there must be at least one object available for
3124 BUG_ON(slabp->inuse >= cachep->num);
3126 while (slabp->inuse < cachep->num && batchcount--) {
3127 STATS_INC_ALLOCED(cachep);
3128 STATS_INC_ACTIVE(cachep);
3129 STATS_SET_HIGH(cachep);
3131 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
3134 check_slabp(cachep, slabp);
3136 /* move slabp to correct slabp list: */
3137 list_del(&slabp->list);
3138 if (slabp->free == BUFCTL_END)
3139 list_add(&slabp->list, &l3->slabs_full);
3141 list_add(&slabp->list, &l3->slabs_partial);
3145 l3->free_objects -= ac->avail;
3147 spin_unlock(&l3->list_lock);
3149 if (unlikely(!ac->avail)) {
3151 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3153 /* cache_grow can reenable interrupts, then ac could change. */
3154 ac = cpu_cache_get(cachep);
3155 if (!x && ac->avail == 0) /* no objects in sight? abort */
3158 if (!ac->avail) /* objects refilled by interrupt? */
3162 return ac->entry[--ac->avail];
3165 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3168 might_sleep_if(flags & __GFP_WAIT);
3170 kmem_flagcheck(cachep, flags);
3175 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3176 gfp_t flags, void *objp, void *caller)
3180 if (cachep->flags & SLAB_POISON) {
3181 #ifdef CONFIG_DEBUG_PAGEALLOC
3182 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3183 kernel_map_pages(virt_to_page(objp),
3184 cachep->buffer_size / PAGE_SIZE, 1);
3186 check_poison_obj(cachep, objp);
3188 check_poison_obj(cachep, objp);
3190 poison_obj(cachep, objp, POISON_INUSE);
3192 if (cachep->flags & SLAB_STORE_USER)
3193 *dbg_userword(cachep, objp) = caller;
3195 if (cachep->flags & SLAB_RED_ZONE) {
3196 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3197 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3198 slab_error(cachep, "double free, or memory outside"
3199 " object was overwritten");
3201 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3202 objp, *dbg_redzone1(cachep, objp),
3203 *dbg_redzone2(cachep, objp));
3205 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3206 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3208 #ifdef CONFIG_DEBUG_SLAB_LEAK
3213 slabp = page_get_slab(virt_to_head_page(objp));
3214 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
3215 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3218 objp += obj_offset(cachep);
3219 if (cachep->ctor && cachep->flags & SLAB_POISON)
3221 if (ARCH_SLAB_MINALIGN &&
3222 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3223 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3224 objp, (int)ARCH_SLAB_MINALIGN);
3229 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3232 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3234 if (cachep == &cache_cache)
3237 return should_failslab(obj_size(cachep), flags, cachep->flags);
3240 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3243 struct array_cache *ac;
3247 ac = cpu_cache_get(cachep);
3248 if (likely(ac->avail)) {
3249 STATS_INC_ALLOCHIT(cachep);
3251 objp = ac->entry[--ac->avail];
3253 STATS_INC_ALLOCMISS(cachep);
3254 objp = cache_alloc_refill(cachep, flags);
3256 * the 'ac' may be updated by cache_alloc_refill(),
3257 * and kmemleak_erase() requires its correct value.
3259 ac = cpu_cache_get(cachep);
3262 * To avoid a false negative, if an object that is in one of the
3263 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3264 * treat the array pointers as a reference to the object.
3267 kmemleak_erase(&ac->entry[ac->avail]);
3273 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3275 * If we are in_interrupt, then process context, including cpusets and
3276 * mempolicy, may not apply and should not be used for allocation policy.
3278 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3280 int nid_alloc, nid_here;
3282 if (in_interrupt() || (flags & __GFP_THISNODE))
3284 nid_alloc = nid_here = numa_mem_id();
3286 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3287 nid_alloc = cpuset_slab_spread_node();
3288 else if (current->mempolicy)
3289 nid_alloc = slab_node(current->mempolicy);
3291 if (nid_alloc != nid_here)
3292 return ____cache_alloc_node(cachep, flags, nid_alloc);
3297 * Fallback function if there was no memory available and no objects on a
3298 * certain node and fall back is permitted. First we scan all the
3299 * available nodelists for available objects. If that fails then we
3300 * perform an allocation without specifying a node. This allows the page
3301 * allocator to do its reclaim / fallback magic. We then insert the
3302 * slab into the proper nodelist and then allocate from it.
3304 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3306 struct zonelist *zonelist;
3310 enum zone_type high_zoneidx = gfp_zone(flags);
3314 if (flags & __GFP_THISNODE)
3318 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
3319 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3323 * Look through allowed nodes for objects available
3324 * from existing per node queues.
3326 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3327 nid = zone_to_nid(zone);
3329 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3330 cache->nodelists[nid] &&
3331 cache->nodelists[nid]->free_objects) {
3332 obj = ____cache_alloc_node(cache,
3333 flags | GFP_THISNODE, nid);
3341 * This allocation will be performed within the constraints
3342 * of the current cpuset / memory policy requirements.
3343 * We may trigger various forms of reclaim on the allowed
3344 * set and go into memory reserves if necessary.
3346 if (local_flags & __GFP_WAIT)
3348 kmem_flagcheck(cache, flags);
3349 obj = kmem_getpages(cache, local_flags, numa_mem_id());
3350 if (local_flags & __GFP_WAIT)
3351 local_irq_disable();
3354 * Insert into the appropriate per node queues
3356 nid = page_to_nid(virt_to_page(obj));
3357 if (cache_grow(cache, flags, nid, obj)) {
3358 obj = ____cache_alloc_node(cache,
3359 flags | GFP_THISNODE, nid);
3362 * Another processor may allocate the
3363 * objects in the slab since we are
3364 * not holding any locks.
3368 /* cache_grow already freed obj */
3378 * A interface to enable slab creation on nodeid
3380 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3383 struct list_head *entry;
3385 struct kmem_list3 *l3;
3389 l3 = cachep->nodelists[nodeid];
3394 spin_lock(&l3->list_lock);
3395 entry = l3->slabs_partial.next;
3396 if (entry == &l3->slabs_partial) {
3397 l3->free_touched = 1;
3398 entry = l3->slabs_free.next;
3399 if (entry == &l3->slabs_free)
3403 slabp = list_entry(entry, struct slab, list);
3404 check_spinlock_acquired_node(cachep, nodeid);
3405 check_slabp(cachep, slabp);
3407 STATS_INC_NODEALLOCS(cachep);
3408 STATS_INC_ACTIVE(cachep);
3409 STATS_SET_HIGH(cachep);
3411 BUG_ON(slabp->inuse == cachep->num);
3413 obj = slab_get_obj(cachep, slabp, nodeid);
3414 check_slabp(cachep, slabp);
3416 /* move slabp to correct slabp list: */
3417 list_del(&slabp->list);
3419 if (slabp->free == BUFCTL_END)
3420 list_add(&slabp->list, &l3->slabs_full);
3422 list_add(&slabp->list, &l3->slabs_partial);
3424 spin_unlock(&l3->list_lock);
3428 spin_unlock(&l3->list_lock);
3429 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3433 return fallback_alloc(cachep, flags);
3440 * kmem_cache_alloc_node - Allocate an object on the specified node
3441 * @cachep: The cache to allocate from.
3442 * @flags: See kmalloc().
3443 * @nodeid: node number of the target node.
3444 * @caller: return address of caller, used for debug information
3446 * Identical to kmem_cache_alloc but it will allocate memory on the given
3447 * node, which can improve the performance for cpu bound structures.
3449 * Fallback to other node is possible if __GFP_THISNODE is not set.
3451 static __always_inline void *
3452 __cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3455 unsigned long save_flags;
3457 int slab_node = numa_mem_id();
3459 flags &= gfp_allowed_mask;
3461 lockdep_trace_alloc(flags);
3463 if (slab_should_failslab(cachep, flags))
3466 cache_alloc_debugcheck_before(cachep, flags);
3467 local_irq_save(save_flags);
3469 if (nodeid == NUMA_NO_NODE)
3472 if (unlikely(!cachep->nodelists[nodeid])) {
3473 /* Node not bootstrapped yet */
3474 ptr = fallback_alloc(cachep, flags);
3478 if (nodeid == slab_node) {
3480 * Use the locally cached objects if possible.
3481 * However ____cache_alloc does not allow fallback
3482 * to other nodes. It may fail while we still have
3483 * objects on other nodes available.
3485 ptr = ____cache_alloc(cachep, flags);
3489 /* ___cache_alloc_node can fall back to other nodes */
3490 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3492 local_irq_restore(save_flags);
3493 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3494 kmemleak_alloc_recursive(ptr, obj_size(cachep), 1, cachep->flags,
3498 kmemcheck_slab_alloc(cachep, flags, ptr, obj_size(cachep));
3500 if (unlikely((flags & __GFP_ZERO) && ptr))
3501 memset(ptr, 0, obj_size(cachep));
3506 static __always_inline void *
3507 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3511 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3512 objp = alternate_node_alloc(cache, flags);
3516 objp = ____cache_alloc(cache, flags);
3519 * We may just have run out of memory on the local node.
3520 * ____cache_alloc_node() knows how to locate memory on other nodes
3523 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3530 static __always_inline void *
3531 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3533 return ____cache_alloc(cachep, flags);
3536 #endif /* CONFIG_NUMA */
3538 static __always_inline void *
3539 __cache_alloc(struct kmem_cache *cachep, gfp_t flags, void *caller)
3541 unsigned long save_flags;
3544 flags &= gfp_allowed_mask;
3546 lockdep_trace_alloc(flags);
3548 if (slab_should_failslab(cachep, flags))
3551 cache_alloc_debugcheck_before(cachep, flags);
3552 local_irq_save(save_flags);
3553 objp = __do_cache_alloc(cachep, flags);
3554 local_irq_restore(save_flags);
3555 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3556 kmemleak_alloc_recursive(objp, obj_size(cachep), 1, cachep->flags,
3561 kmemcheck_slab_alloc(cachep, flags, objp, obj_size(cachep));
3563 if (unlikely((flags & __GFP_ZERO) && objp))
3564 memset(objp, 0, obj_size(cachep));
3570 * Caller needs to acquire correct kmem_list's list_lock
3572 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3576 struct kmem_list3 *l3;
3578 for (i = 0; i < nr_objects; i++) {
3579 void *objp = objpp[i];
3582 slabp = virt_to_slab(objp);
3583 l3 = cachep->nodelists[node];
3584 list_del(&slabp->list);
3585 check_spinlock_acquired_node(cachep, node);
3586 check_slabp(cachep, slabp);
3587 slab_put_obj(cachep, slabp, objp, node);
3588 STATS_DEC_ACTIVE(cachep);
3590 check_slabp(cachep, slabp);
3592 /* fixup slab chains */
3593 if (slabp->inuse == 0) {
3594 if (l3->free_objects > l3->free_limit) {
3595 l3->free_objects -= cachep->num;
3596 /* No need to drop any previously held
3597 * lock here, even if we have a off-slab slab
3598 * descriptor it is guaranteed to come from
3599 * a different cache, refer to comments before
3602 slab_destroy(cachep, slabp);
3604 list_add(&slabp->list, &l3->slabs_free);
3607 /* Unconditionally move a slab to the end of the
3608 * partial list on free - maximum time for the
3609 * other objects to be freed, too.
3611 list_add_tail(&slabp->list, &l3->slabs_partial);
3616 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3619 struct kmem_list3 *l3;
3620 int node = numa_mem_id();
3622 batchcount = ac->batchcount;
3624 BUG_ON(!batchcount || batchcount > ac->avail);
3627 l3 = cachep->nodelists[node];
3628 spin_lock(&l3->list_lock);
3630 struct array_cache *shared_array = l3->shared;
3631 int max = shared_array->limit - shared_array->avail;
3633 if (batchcount > max)
3635 memcpy(&(shared_array->entry[shared_array->avail]),
3636 ac->entry, sizeof(void *) * batchcount);
3637 shared_array->avail += batchcount;
3642 free_block(cachep, ac->entry, batchcount, node);
3647 struct list_head *p;
3649 p = l3->slabs_free.next;
3650 while (p != &(l3->slabs_free)) {
3653 slabp = list_entry(p, struct slab, list);
3654 BUG_ON(slabp->inuse);
3659 STATS_SET_FREEABLE(cachep, i);
3662 spin_unlock(&l3->list_lock);
3663 ac->avail -= batchcount;
3664 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3668 * Release an obj back to its cache. If the obj has a constructed state, it must
3669 * be in this state _before_ it is released. Called with disabled ints.
3671 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3674 struct array_cache *ac = cpu_cache_get(cachep);
3677 kmemleak_free_recursive(objp, cachep->flags);
3678 objp = cache_free_debugcheck(cachep, objp, caller);
3680 kmemcheck_slab_free(cachep, objp, obj_size(cachep));
3683 * Skip calling cache_free_alien() when the platform is not numa.
3684 * This will avoid cache misses that happen while accessing slabp (which
3685 * is per page memory reference) to get nodeid. Instead use a global
3686 * variable to skip the call, which is mostly likely to be present in
3689 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3692 if (likely(ac->avail < ac->limit)) {
3693 STATS_INC_FREEHIT(cachep);
3694 ac->entry[ac->avail++] = objp;
3697 STATS_INC_FREEMISS(cachep);
3698 cache_flusharray(cachep, ac);
3699 ac->entry[ac->avail++] = objp;
3704 * kmem_cache_alloc - Allocate an object
3705 * @cachep: The cache to allocate from.
3706 * @flags: See kmalloc().
3708 * Allocate an object from this cache. The flags are only relevant
3709 * if the cache has no available objects.
3711 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3713 void *ret = __cache_alloc(cachep, flags, __builtin_return_address(0));
3715 trace_kmem_cache_alloc(_RET_IP_, ret,
3716 obj_size(cachep), cachep->buffer_size, flags);
3720 EXPORT_SYMBOL(kmem_cache_alloc);
3722 #ifdef CONFIG_TRACING
3724 kmem_cache_alloc_trace(size_t size, struct kmem_cache *cachep, gfp_t flags)
3728 ret = __cache_alloc(cachep, flags, __builtin_return_address(0));
3730 trace_kmalloc(_RET_IP_, ret,
3731 size, slab_buffer_size(cachep), flags);
3734 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3738 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3740 void *ret = __cache_alloc_node(cachep, flags, nodeid,
3741 __builtin_return_address(0));
3743 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3744 obj_size(cachep), cachep->buffer_size,
3749 EXPORT_SYMBOL(kmem_cache_alloc_node);
3751 #ifdef CONFIG_TRACING
3752 void *kmem_cache_alloc_node_trace(size_t size,
3753 struct kmem_cache *cachep,
3759 ret = __cache_alloc_node(cachep, flags, nodeid,
3760 __builtin_return_address(0));
3761 trace_kmalloc_node(_RET_IP_, ret,
3762 size, slab_buffer_size(cachep),
3766 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3769 static __always_inline void *
3770 __do_kmalloc_node(size_t size, gfp_t flags, int node, void *caller)
3772 struct kmem_cache *cachep;
3774 cachep = kmem_find_general_cachep(size, flags);
3775 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3777 return kmem_cache_alloc_node_trace(size, cachep, flags, node);
3780 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3781 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3783 return __do_kmalloc_node(size, flags, node,
3784 __builtin_return_address(0));
3786 EXPORT_SYMBOL(__kmalloc_node);
3788 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3789 int node, unsigned long caller)
3791 return __do_kmalloc_node(size, flags, node, (void *)caller);
3793 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3795 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3797 return __do_kmalloc_node(size, flags, node, NULL);
3799 EXPORT_SYMBOL(__kmalloc_node);
3800 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3801 #endif /* CONFIG_NUMA */
3804 * __do_kmalloc - allocate memory
3805 * @size: how many bytes of memory are required.
3806 * @flags: the type of memory to allocate (see kmalloc).
3807 * @caller: function caller for debug tracking of the caller
3809 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3812 struct kmem_cache *cachep;
3815 /* If you want to save a few bytes .text space: replace
3817 * Then kmalloc uses the uninlined functions instead of the inline
3820 cachep = __find_general_cachep(size, flags);
3821 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3823 ret = __cache_alloc(cachep, flags, caller);
3825 trace_kmalloc((unsigned long) caller, ret,
3826 size, cachep->buffer_size, flags);
3832 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3833 void *__kmalloc(size_t size, gfp_t flags)
3835 return __do_kmalloc(size, flags, __builtin_return_address(0));
3837 EXPORT_SYMBOL(__kmalloc);
3839 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3841 return __do_kmalloc(size, flags, (void *)caller);
3843 EXPORT_SYMBOL(__kmalloc_track_caller);
3846 void *__kmalloc(size_t size, gfp_t flags)
3848 return __do_kmalloc(size, flags, NULL);
3850 EXPORT_SYMBOL(__kmalloc);
3854 * kmem_cache_free - Deallocate an object
3855 * @cachep: The cache the allocation was from.
3856 * @objp: The previously allocated object.
3858 * Free an object which was previously allocated from this
3861 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3863 unsigned long flags;
3865 local_irq_save(flags);
3866 debug_check_no_locks_freed(objp, obj_size(cachep));
3867 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3868 debug_check_no_obj_freed(objp, obj_size(cachep));
3869 __cache_free(cachep, objp, __builtin_return_address(0));
3870 local_irq_restore(flags);
3872 trace_kmem_cache_free(_RET_IP_, objp);
3874 EXPORT_SYMBOL(kmem_cache_free);
3877 * kfree - free previously allocated memory
3878 * @objp: pointer returned by kmalloc.
3880 * If @objp is NULL, no operation is performed.
3882 * Don't free memory not originally allocated by kmalloc()
3883 * or you will run into trouble.
3885 void kfree(const void *objp)
3887 struct kmem_cache *c;
3888 unsigned long flags;
3890 trace_kfree(_RET_IP_, objp);
3892 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3894 local_irq_save(flags);
3895 kfree_debugcheck(objp);
3896 c = virt_to_cache(objp);
3897 debug_check_no_locks_freed(objp, obj_size(c));
3898 debug_check_no_obj_freed(objp, obj_size(c));
3899 __cache_free(c, (void *)objp, __builtin_return_address(0));
3900 local_irq_restore(flags);
3902 EXPORT_SYMBOL(kfree);
3904 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3906 return obj_size(cachep);
3908 EXPORT_SYMBOL(kmem_cache_size);
3911 * This initializes kmem_list3 or resizes various caches for all nodes.
3913 static int alloc_kmemlist(struct kmem_cache *cachep, gfp_t gfp)
3916 struct kmem_list3 *l3;
3917 struct array_cache *new_shared;
3918 struct array_cache **new_alien = NULL;
3920 for_each_online_node(node) {
3922 if (use_alien_caches) {
3923 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3929 if (cachep->shared) {
3930 new_shared = alloc_arraycache(node,
3931 cachep->shared*cachep->batchcount,
3934 free_alien_cache(new_alien);
3939 l3 = cachep->nodelists[node];
3941 struct array_cache *shared = l3->shared;
3943 spin_lock_irq(&l3->list_lock);
3946 free_block(cachep, shared->entry,
3947 shared->avail, node);
3949 l3->shared = new_shared;
3951 l3->alien = new_alien;
3954 l3->free_limit = (1 + nr_cpus_node(node)) *
3955 cachep->batchcount + cachep->num;
3956 spin_unlock_irq(&l3->list_lock);
3958 free_alien_cache(new_alien);
3961 l3 = kmalloc_node(sizeof(struct kmem_list3), gfp, node);
3963 free_alien_cache(new_alien);
3968 kmem_list3_init(l3);
3969 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3970 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3971 l3->shared = new_shared;
3972 l3->alien = new_alien;
3973 l3->free_limit = (1 + nr_cpus_node(node)) *
3974 cachep->batchcount + cachep->num;
3975 cachep->nodelists[node] = l3;
3980 if (!cachep->next.next) {
3981 /* Cache is not active yet. Roll back what we did */
3984 if (cachep->nodelists[node]) {
3985 l3 = cachep->nodelists[node];
3988 free_alien_cache(l3->alien);
3990 cachep->nodelists[node] = NULL;
3998 struct ccupdate_struct {
3999 struct kmem_cache *cachep;
4000 struct array_cache *new[0];
4003 static void do_ccupdate_local(void *info)
4005 struct ccupdate_struct *new = info;
4006 struct array_cache *old;
4009 old = cpu_cache_get(new->cachep);
4011 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
4012 new->new[smp_processor_id()] = old;
4015 /* Always called with the cache_chain_mutex held */
4016 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
4017 int batchcount, int shared, gfp_t gfp)
4019 struct ccupdate_struct *new;
4022 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
4027 for_each_online_cpu(i) {
4028 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
4031 for (i--; i >= 0; i--)
4037 new->cachep = cachep;
4039 on_each_cpu(do_ccupdate_local, (void *)new, 1);
4042 cachep->batchcount = batchcount;
4043 cachep->limit = limit;
4044 cachep->shared = shared;
4046 for_each_online_cpu(i) {
4047 struct array_cache *ccold = new->new[i];
4050 spin_lock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4051 free_block(cachep, ccold->entry, ccold->avail, cpu_to_mem(i));
4052 spin_unlock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4056 return alloc_kmemlist(cachep, gfp);
4059 /* Called with cache_chain_mutex held always */
4060 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
4066 * The head array serves three purposes:
4067 * - create a LIFO ordering, i.e. return objects that are cache-warm
4068 * - reduce the number of spinlock operations.
4069 * - reduce the number of linked list operations on the slab and
4070 * bufctl chains: array operations are cheaper.
4071 * The numbers are guessed, we should auto-tune as described by
4074 if (cachep->buffer_size > 131072)
4076 else if (cachep->buffer_size > PAGE_SIZE)
4078 else if (cachep->buffer_size > 1024)
4080 else if (cachep->buffer_size > 256)
4086 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4087 * allocation behaviour: Most allocs on one cpu, most free operations
4088 * on another cpu. For these cases, an efficient object passing between
4089 * cpus is necessary. This is provided by a shared array. The array
4090 * replaces Bonwick's magazine layer.
4091 * On uniprocessor, it's functionally equivalent (but less efficient)
4092 * to a larger limit. Thus disabled by default.
4095 if (cachep->buffer_size <= PAGE_SIZE && num_possible_cpus() > 1)
4100 * With debugging enabled, large batchcount lead to excessively long
4101 * periods with disabled local interrupts. Limit the batchcount
4106 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared, gfp);
4108 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4109 cachep->name, -err);
4114 * Drain an array if it contains any elements taking the l3 lock only if
4115 * necessary. Note that the l3 listlock also protects the array_cache
4116 * if drain_array() is used on the shared array.
4118 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
4119 struct array_cache *ac, int force, int node)
4123 if (!ac || !ac->avail)
4125 if (ac->touched && !force) {
4128 spin_lock_irq(&l3->list_lock);
4130 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4131 if (tofree > ac->avail)
4132 tofree = (ac->avail + 1) / 2;
4133 free_block(cachep, ac->entry, tofree, node);
4134 ac->avail -= tofree;
4135 memmove(ac->entry, &(ac->entry[tofree]),
4136 sizeof(void *) * ac->avail);
4138 spin_unlock_irq(&l3->list_lock);
4143 * cache_reap - Reclaim memory from caches.
4144 * @w: work descriptor
4146 * Called from workqueue/eventd every few seconds.
4148 * - clear the per-cpu caches for this CPU.
4149 * - return freeable pages to the main free memory pool.
4151 * If we cannot acquire the cache chain mutex then just give up - we'll try
4152 * again on the next iteration.
4154 static void cache_reap(struct work_struct *w)
4156 struct kmem_cache *searchp;
4157 struct kmem_list3 *l3;
4158 int node = numa_mem_id();
4159 struct delayed_work *work = to_delayed_work(w);
4161 if (!mutex_trylock(&cache_chain_mutex))
4162 /* Give up. Setup the next iteration. */
4165 list_for_each_entry(searchp, &cache_chain, next) {
4169 * We only take the l3 lock if absolutely necessary and we
4170 * have established with reasonable certainty that
4171 * we can do some work if the lock was obtained.
4173 l3 = searchp->nodelists[node];
4175 reap_alien(searchp, l3);
4177 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4180 * These are racy checks but it does not matter
4181 * if we skip one check or scan twice.
4183 if (time_after(l3->next_reap, jiffies))
4186 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4188 drain_array(searchp, l3, l3->shared, 0, node);
4190 if (l3->free_touched)
4191 l3->free_touched = 0;
4195 freed = drain_freelist(searchp, l3, (l3->free_limit +
4196 5 * searchp->num - 1) / (5 * searchp->num));
4197 STATS_ADD_REAPED(searchp, freed);
4203 mutex_unlock(&cache_chain_mutex);
4206 /* Set up the next iteration */
4207 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4210 #ifdef CONFIG_SLABINFO
4212 static void print_slabinfo_header(struct seq_file *m)
4215 * Output format version, so at least we can change it
4216 * without _too_ many complaints.
4219 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
4221 seq_puts(m, "slabinfo - version: 2.1\n");
4223 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4224 "<objperslab> <pagesperslab>");
4225 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4226 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4228 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
4229 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
4230 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
4235 static void *s_start(struct seq_file *m, loff_t *pos)
4239 mutex_lock(&cache_chain_mutex);
4241 print_slabinfo_header(m);
4243 return seq_list_start(&cache_chain, *pos);
4246 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4248 return seq_list_next(p, &cache_chain, pos);
4251 static void s_stop(struct seq_file *m, void *p)
4253 mutex_unlock(&cache_chain_mutex);
4256 static int s_show(struct seq_file *m, void *p)
4258 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4260 unsigned long active_objs;
4261 unsigned long num_objs;
4262 unsigned long active_slabs = 0;
4263 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4267 struct kmem_list3 *l3;
4271 for_each_online_node(node) {
4272 l3 = cachep->nodelists[node];
4277 spin_lock_irq(&l3->list_lock);
4279 list_for_each_entry(slabp, &l3->slabs_full, list) {
4280 if (slabp->inuse != cachep->num && !error)
4281 error = "slabs_full accounting error";
4282 active_objs += cachep->num;
4285 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4286 if (slabp->inuse == cachep->num && !error)
4287 error = "slabs_partial inuse accounting error";
4288 if (!slabp->inuse && !error)
4289 error = "slabs_partial/inuse accounting error";
4290 active_objs += slabp->inuse;
4293 list_for_each_entry(slabp, &l3->slabs_free, list) {
4294 if (slabp->inuse && !error)
4295 error = "slabs_free/inuse accounting error";
4298 free_objects += l3->free_objects;
4300 shared_avail += l3->shared->avail;
4302 spin_unlock_irq(&l3->list_lock);
4304 num_slabs += active_slabs;
4305 num_objs = num_slabs * cachep->num;
4306 if (num_objs - active_objs != free_objects && !error)
4307 error = "free_objects accounting error";
4309 name = cachep->name;
4311 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4313 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
4314 name, active_objs, num_objs, cachep->buffer_size,
4315 cachep->num, (1 << cachep->gfporder));
4316 seq_printf(m, " : tunables %4u %4u %4u",
4317 cachep->limit, cachep->batchcount, cachep->shared);
4318 seq_printf(m, " : slabdata %6lu %6lu %6lu",
4319 active_slabs, num_slabs, shared_avail);
4322 unsigned long high = cachep->high_mark;
4323 unsigned long allocs = cachep->num_allocations;
4324 unsigned long grown = cachep->grown;
4325 unsigned long reaped = cachep->reaped;
4326 unsigned long errors = cachep->errors;
4327 unsigned long max_freeable = cachep->max_freeable;
4328 unsigned long node_allocs = cachep->node_allocs;
4329 unsigned long node_frees = cachep->node_frees;
4330 unsigned long overflows = cachep->node_overflow;
4332 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4333 "%4lu %4lu %4lu %4lu %4lu",
4334 allocs, high, grown,
4335 reaped, errors, max_freeable, node_allocs,
4336 node_frees, overflows);
4340 unsigned long allochit = atomic_read(&cachep->allochit);
4341 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4342 unsigned long freehit = atomic_read(&cachep->freehit);
4343 unsigned long freemiss = atomic_read(&cachep->freemiss);
4345 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4346 allochit, allocmiss, freehit, freemiss);
4354 * slabinfo_op - iterator that generates /proc/slabinfo
4363 * num-pages-per-slab
4364 * + further values on SMP and with statistics enabled
4367 static const struct seq_operations slabinfo_op = {
4374 #define MAX_SLABINFO_WRITE 128
4376 * slabinfo_write - Tuning for the slab allocator
4378 * @buffer: user buffer
4379 * @count: data length
4382 static ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4383 size_t count, loff_t *ppos)
4385 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4386 int limit, batchcount, shared, res;
4387 struct kmem_cache *cachep;
4389 if (count > MAX_SLABINFO_WRITE)
4391 if (copy_from_user(&kbuf, buffer, count))
4393 kbuf[MAX_SLABINFO_WRITE] = '\0';
4395 tmp = strchr(kbuf, ' ');
4400 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4403 /* Find the cache in the chain of caches. */
4404 mutex_lock(&cache_chain_mutex);
4406 list_for_each_entry(cachep, &cache_chain, next) {
4407 if (!strcmp(cachep->name, kbuf)) {
4408 if (limit < 1 || batchcount < 1 ||
4409 batchcount > limit || shared < 0) {
4412 res = do_tune_cpucache(cachep, limit,
4419 mutex_unlock(&cache_chain_mutex);
4425 static int slabinfo_open(struct inode *inode, struct file *file)
4427 return seq_open(file, &slabinfo_op);
4430 static const struct file_operations proc_slabinfo_operations = {
4431 .open = slabinfo_open,
4433 .write = slabinfo_write,
4434 .llseek = seq_lseek,
4435 .release = seq_release,
4438 #ifdef CONFIG_DEBUG_SLAB_LEAK
4440 static void *leaks_start(struct seq_file *m, loff_t *pos)
4442 mutex_lock(&cache_chain_mutex);
4443 return seq_list_start(&cache_chain, *pos);
4446 static inline int add_caller(unsigned long *n, unsigned long v)
4456 unsigned long *q = p + 2 * i;
4470 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4476 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4482 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4483 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4485 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4490 static void show_symbol(struct seq_file *m, unsigned long address)
4492 #ifdef CONFIG_KALLSYMS
4493 unsigned long offset, size;
4494 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4496 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4497 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4499 seq_printf(m, " [%s]", modname);
4503 seq_printf(m, "%p", (void *)address);
4506 static int leaks_show(struct seq_file *m, void *p)
4508 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4510 struct kmem_list3 *l3;
4512 unsigned long *n = m->private;
4516 if (!(cachep->flags & SLAB_STORE_USER))
4518 if (!(cachep->flags & SLAB_RED_ZONE))
4521 /* OK, we can do it */
4525 for_each_online_node(node) {
4526 l3 = cachep->nodelists[node];
4531 spin_lock_irq(&l3->list_lock);
4533 list_for_each_entry(slabp, &l3->slabs_full, list)
4534 handle_slab(n, cachep, slabp);
4535 list_for_each_entry(slabp, &l3->slabs_partial, list)
4536 handle_slab(n, cachep, slabp);
4537 spin_unlock_irq(&l3->list_lock);
4539 name = cachep->name;
4541 /* Increase the buffer size */
4542 mutex_unlock(&cache_chain_mutex);
4543 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4545 /* Too bad, we are really out */
4547 mutex_lock(&cache_chain_mutex);
4550 *(unsigned long *)m->private = n[0] * 2;
4552 mutex_lock(&cache_chain_mutex);
4553 /* Now make sure this entry will be retried */
4557 for (i = 0; i < n[1]; i++) {
4558 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4559 show_symbol(m, n[2*i+2]);
4566 static const struct seq_operations slabstats_op = {
4567 .start = leaks_start,
4573 static int slabstats_open(struct inode *inode, struct file *file)
4575 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4578 ret = seq_open(file, &slabstats_op);
4580 struct seq_file *m = file->private_data;
4581 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4590 static const struct file_operations proc_slabstats_operations = {
4591 .open = slabstats_open,
4593 .llseek = seq_lseek,
4594 .release = seq_release_private,
4598 static int __init slab_proc_init(void)
4600 proc_create("slabinfo",S_IWUSR|S_IRUSR,NULL,&proc_slabinfo_operations);
4601 #ifdef CONFIG_DEBUG_SLAB_LEAK
4602 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4606 module_init(slab_proc_init);
4610 * ksize - get the actual amount of memory allocated for a given object
4611 * @objp: Pointer to the object
4613 * kmalloc may internally round up allocations and return more memory
4614 * than requested. ksize() can be used to determine the actual amount of
4615 * memory allocated. The caller may use this additional memory, even though
4616 * a smaller amount of memory was initially specified with the kmalloc call.
4617 * The caller must guarantee that objp points to a valid object previously
4618 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4619 * must not be freed during the duration of the call.
4621 size_t ksize(const void *objp)
4624 if (unlikely(objp == ZERO_SIZE_PTR))
4627 return obj_size(virt_to_cache(objp));
4629 EXPORT_SYMBOL(ksize);