3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
14 * An implementation of the Slab Allocator as described in outline in;
15 * UNIX Internals: The New Frontiers by Uresh Vahalia
16 * Pub: Prentice Hall ISBN 0-13-101908-2
17 * or with a little more detail in;
18 * The Slab Allocator: An Object-Caching Kernel Memory Allocator
19 * Jeff Bonwick (Sun Microsystems).
20 * Presented at: USENIX Summer 1994 Technical Conference
22 * The memory is organized in caches, one cache for each object type.
23 * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24 * Each cache consists out of many slabs (they are small (usually one
25 * page long) and always contiguous), and each slab contains multiple
26 * initialized objects.
28 * This means, that your constructor is used only for newly allocated
29 * slabs and you must pass objects with the same initializations to
32 * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33 * normal). If you need a special memory type, then must create a new
34 * cache for that memory type.
36 * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37 * full slabs with 0 free objects
39 * empty slabs with no allocated objects
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
44 * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45 * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
47 * Each cache has a short per-cpu head array, most allocs
48 * and frees go into that array, and if that array overflows, then 1/2
49 * of the entries in the array are given back into the global cache.
50 * The head array is strictly LIFO and should improve the cache hit rates.
51 * On SMP, it additionally reduces the spinlock operations.
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
56 * SMP synchronization:
57 * constructors and destructors are called without any locking.
58 * Several members in struct kmem_cache and struct slab never change, they
59 * are accessed without any locking.
60 * The per-cpu arrays are never accessed from the wrong cpu, no locking,
61 * and local interrupts are disabled so slab code is preempt-safe.
62 * The non-constant members are protected with a per-cache irq spinlock.
64 * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65 * in 2000 - many ideas in the current implementation are derived from
68 * Further notes from the original documentation:
70 * 11 April '97. Started multi-threading - markhe
71 * The global cache-chain is protected by the mutex 'cache_chain_mutex'.
72 * The sem is only needed when accessing/extending the cache-chain, which
73 * can never happen inside an interrupt (kmem_cache_create(),
74 * kmem_cache_shrink() and kmem_cache_reap()).
76 * At present, each engine can be growing a cache. This should be blocked.
78 * 15 March 2005. NUMA slab allocator.
79 * Shai Fultheim <shai@scalex86.org>.
80 * Shobhit Dayal <shobhit@calsoftinc.com>
81 * Alok N Kataria <alokk@calsoftinc.com>
82 * Christoph Lameter <christoph@lameter.com>
84 * Modified the slab allocator to be node aware on NUMA systems.
85 * Each node has its own list of partial, free and full slabs.
86 * All object allocations for a node occur from node specific slab lists.
89 #include <linux/slab.h>
91 #include <linux/poison.h>
92 #include <linux/swap.h>
93 #include <linux/cache.h>
94 #include <linux/interrupt.h>
95 #include <linux/init.h>
96 #include <linux/compiler.h>
97 #include <linux/cpuset.h>
98 #include <linux/proc_fs.h>
99 #include <linux/seq_file.h>
100 #include <linux/notifier.h>
101 #include <linux/kallsyms.h>
102 #include <linux/cpu.h>
103 #include <linux/sysctl.h>
104 #include <linux/module.h>
105 #include <linux/kmemtrace.h>
106 #include <linux/rcupdate.h>
107 #include <linux/string.h>
108 #include <linux/uaccess.h>
109 #include <linux/nodemask.h>
110 #include <linux/kmemleak.h>
111 #include <linux/mempolicy.h>
112 #include <linux/mutex.h>
113 #include <linux/fault-inject.h>
114 #include <linux/rtmutex.h>
115 #include <linux/reciprocal_div.h>
116 #include <linux/debugobjects.h>
118 #include <asm/cacheflush.h>
119 #include <asm/tlbflush.h>
120 #include <asm/page.h>
123 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
124 * 0 for faster, smaller code (especially in the critical paths).
126 * STATS - 1 to collect stats for /proc/slabinfo.
127 * 0 for faster, smaller code (especially in the critical paths).
129 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
132 #ifdef CONFIG_DEBUG_SLAB
135 #define FORCED_DEBUG 1
139 #define FORCED_DEBUG 0
142 /* Shouldn't this be in a header file somewhere? */
143 #define BYTES_PER_WORD sizeof(void *)
144 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
146 #ifndef ARCH_KMALLOC_MINALIGN
148 * Enforce a minimum alignment for the kmalloc caches.
149 * Usually, the kmalloc caches are cache_line_size() aligned, except when
150 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
151 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
152 * alignment larger than the alignment of a 64-bit integer.
153 * ARCH_KMALLOC_MINALIGN allows that.
154 * Note that increasing this value may disable some debug features.
156 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
159 #ifndef ARCH_SLAB_MINALIGN
161 * Enforce a minimum alignment for all caches.
162 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
163 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
164 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
165 * some debug features.
167 #define ARCH_SLAB_MINALIGN 0
170 #ifndef ARCH_KMALLOC_FLAGS
171 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
174 /* Legal flag mask for kmem_cache_create(). */
176 # define CREATE_MASK (SLAB_RED_ZONE | \
177 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
180 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
181 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
182 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE)
184 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
186 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
187 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
188 SLAB_DEBUG_OBJECTS | SLAB_NOLEAKTRACE)
194 * Bufctl's are used for linking objs within a slab
197 * This implementation relies on "struct page" for locating the cache &
198 * slab an object belongs to.
199 * This allows the bufctl structure to be small (one int), but limits
200 * the number of objects a slab (not a cache) can contain when off-slab
201 * bufctls are used. The limit is the size of the largest general cache
202 * that does not use off-slab slabs.
203 * For 32bit archs with 4 kB pages, is this 56.
204 * This is not serious, as it is only for large objects, when it is unwise
205 * to have too many per slab.
206 * Note: This limit can be raised by introducing a general cache whose size
207 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
210 typedef unsigned int kmem_bufctl_t;
211 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
212 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
213 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
214 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
219 * Manages the objs in a slab. Placed either at the beginning of mem allocated
220 * for a slab, or allocated from an general cache.
221 * 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;
235 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
236 * arrange for kmem_freepages to be called via RCU. This is useful if
237 * we need to approach a kernel structure obliquely, from its address
238 * obtained without the usual locking. We can lock the structure to
239 * stabilize it and check it's still at the given address, only if we
240 * can be sure that the memory has not been meanwhile reused for some
241 * other kind of object (which our subsystem's lock might corrupt).
243 * rcu_read_lock before reading the address, then rcu_read_unlock after
244 * taking the spinlock within the structure expected at that address.
246 * We assume struct slab_rcu can overlay struct slab when destroying.
249 struct rcu_head head;
250 struct kmem_cache *cachep;
258 * - LIFO ordering, to hand out cache-warm objects from _alloc
259 * - reduce the number of linked list operations
260 * - reduce spinlock operations
262 * The limit is stored in the per-cpu structure to reduce the data cache
269 unsigned int batchcount;
270 unsigned int touched;
273 * Must have this definition in here for the proper
274 * alignment of array_cache. Also simplifies accessing
280 * bootstrap: The caches do not work without cpuarrays anymore, but the
281 * cpuarrays are allocated from the generic caches...
283 #define BOOT_CPUCACHE_ENTRIES 1
284 struct arraycache_init {
285 struct array_cache cache;
286 void *entries[BOOT_CPUCACHE_ENTRIES];
290 * The slab lists for all objects.
293 struct list_head slabs_partial; /* partial list first, better asm code */
294 struct list_head slabs_full;
295 struct list_head slabs_free;
296 unsigned long free_objects;
297 unsigned int free_limit;
298 unsigned int colour_next; /* Per-node cache coloring */
299 spinlock_t list_lock;
300 struct array_cache *shared; /* shared per node */
301 struct array_cache **alien; /* on other nodes */
302 unsigned long next_reap; /* updated without locking */
303 int free_touched; /* updated without locking */
307 * Need this for bootstrapping a per node allocator.
309 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
310 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
311 #define CACHE_CACHE 0
312 #define SIZE_AC MAX_NUMNODES
313 #define SIZE_L3 (2 * MAX_NUMNODES)
315 static int drain_freelist(struct kmem_cache *cache,
316 struct kmem_list3 *l3, int tofree);
317 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
319 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
320 static void cache_reap(struct work_struct *unused);
323 * This function must be completely optimized away if a constant is passed to
324 * it. Mostly the same as what is in linux/slab.h except it returns an index.
326 static __always_inline int index_of(const size_t size)
328 extern void __bad_size(void);
330 if (__builtin_constant_p(size)) {
338 #include <linux/kmalloc_sizes.h>
346 static int slab_early_init = 1;
348 #define INDEX_AC index_of(sizeof(struct arraycache_init))
349 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
351 static void kmem_list3_init(struct kmem_list3 *parent)
353 INIT_LIST_HEAD(&parent->slabs_full);
354 INIT_LIST_HEAD(&parent->slabs_partial);
355 INIT_LIST_HEAD(&parent->slabs_free);
356 parent->shared = NULL;
357 parent->alien = NULL;
358 parent->colour_next = 0;
359 spin_lock_init(&parent->list_lock);
360 parent->free_objects = 0;
361 parent->free_touched = 0;
364 #define MAKE_LIST(cachep, listp, slab, nodeid) \
366 INIT_LIST_HEAD(listp); \
367 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
370 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
372 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
373 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
374 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
377 #define CFLGS_OFF_SLAB (0x80000000UL)
378 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
380 #define BATCHREFILL_LIMIT 16
382 * Optimization question: fewer reaps means less probability for unnessary
383 * cpucache drain/refill cycles.
385 * OTOH the cpuarrays can contain lots of objects,
386 * which could lock up otherwise freeable slabs.
388 #define REAPTIMEOUT_CPUC (2*HZ)
389 #define REAPTIMEOUT_LIST3 (4*HZ)
392 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
393 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
394 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
395 #define STATS_INC_GROWN(x) ((x)->grown++)
396 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
397 #define STATS_SET_HIGH(x) \
399 if ((x)->num_active > (x)->high_mark) \
400 (x)->high_mark = (x)->num_active; \
402 #define STATS_INC_ERR(x) ((x)->errors++)
403 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
404 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
405 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
406 #define STATS_SET_FREEABLE(x, i) \
408 if ((x)->max_freeable < i) \
409 (x)->max_freeable = i; \
411 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
412 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
413 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
414 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
416 #define STATS_INC_ACTIVE(x) do { } while (0)
417 #define STATS_DEC_ACTIVE(x) do { } while (0)
418 #define STATS_INC_ALLOCED(x) do { } while (0)
419 #define STATS_INC_GROWN(x) do { } while (0)
420 #define STATS_ADD_REAPED(x,y) do { } while (0)
421 #define STATS_SET_HIGH(x) do { } while (0)
422 #define STATS_INC_ERR(x) do { } while (0)
423 #define STATS_INC_NODEALLOCS(x) do { } while (0)
424 #define STATS_INC_NODEFREES(x) do { } while (0)
425 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
426 #define STATS_SET_FREEABLE(x, i) do { } while (0)
427 #define STATS_INC_ALLOCHIT(x) do { } while (0)
428 #define STATS_INC_ALLOCMISS(x) do { } while (0)
429 #define STATS_INC_FREEHIT(x) do { } while (0)
430 #define STATS_INC_FREEMISS(x) do { } while (0)
436 * memory layout of objects:
438 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
439 * the end of an object is aligned with the end of the real
440 * allocation. Catches writes behind the end of the allocation.
441 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
443 * cachep->obj_offset: The real object.
444 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
445 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
446 * [BYTES_PER_WORD long]
448 static int obj_offset(struct kmem_cache *cachep)
450 return cachep->obj_offset;
453 static int obj_size(struct kmem_cache *cachep)
455 return cachep->obj_size;
458 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
460 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
461 return (unsigned long long*) (objp + obj_offset(cachep) -
462 sizeof(unsigned long long));
465 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
467 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
468 if (cachep->flags & SLAB_STORE_USER)
469 return (unsigned long long *)(objp + cachep->buffer_size -
470 sizeof(unsigned long long) -
472 return (unsigned long long *) (objp + cachep->buffer_size -
473 sizeof(unsigned long long));
476 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
478 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
479 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
484 #define obj_offset(x) 0
485 #define obj_size(cachep) (cachep->buffer_size)
486 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
487 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
488 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
492 #ifdef CONFIG_KMEMTRACE
493 size_t slab_buffer_size(struct kmem_cache *cachep)
495 return cachep->buffer_size;
497 EXPORT_SYMBOL(slab_buffer_size);
501 * Do not go above this order unless 0 objects fit into the slab.
503 #define BREAK_GFP_ORDER_HI 1
504 #define BREAK_GFP_ORDER_LO 0
505 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
508 * Functions for storing/retrieving the cachep and or slab from the page
509 * allocator. These are used to find the slab an obj belongs to. With kfree(),
510 * these are used to find the cache which an obj belongs to.
512 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
514 page->lru.next = (struct list_head *)cache;
517 static inline struct kmem_cache *page_get_cache(struct page *page)
519 page = compound_head(page);
520 BUG_ON(!PageSlab(page));
521 return (struct kmem_cache *)page->lru.next;
524 static inline void page_set_slab(struct page *page, struct slab *slab)
526 page->lru.prev = (struct list_head *)slab;
529 static inline struct slab *page_get_slab(struct page *page)
531 BUG_ON(!PageSlab(page));
532 return (struct slab *)page->lru.prev;
535 static inline struct kmem_cache *virt_to_cache(const void *obj)
537 struct page *page = virt_to_head_page(obj);
538 return page_get_cache(page);
541 static inline struct slab *virt_to_slab(const void *obj)
543 struct page *page = virt_to_head_page(obj);
544 return page_get_slab(page);
547 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
550 return slab->s_mem + cache->buffer_size * idx;
554 * We want to avoid an expensive divide : (offset / cache->buffer_size)
555 * Using the fact that buffer_size is a constant for a particular cache,
556 * we can replace (offset / cache->buffer_size) by
557 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
559 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
560 const struct slab *slab, void *obj)
562 u32 offset = (obj - slab->s_mem);
563 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
567 * These are the default caches for kmalloc. Custom caches can have other sizes.
569 struct cache_sizes malloc_sizes[] = {
570 #define CACHE(x) { .cs_size = (x) },
571 #include <linux/kmalloc_sizes.h>
575 EXPORT_SYMBOL(malloc_sizes);
577 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
583 static struct cache_names __initdata cache_names[] = {
584 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
585 #include <linux/kmalloc_sizes.h>
590 static struct arraycache_init initarray_cache __initdata =
591 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
592 static struct arraycache_init initarray_generic =
593 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
595 /* internal cache of cache description objs */
596 static struct kmem_cache cache_cache = {
598 .limit = BOOT_CPUCACHE_ENTRIES,
600 .buffer_size = sizeof(struct kmem_cache),
601 .name = "kmem_cache",
604 #define BAD_ALIEN_MAGIC 0x01020304ul
606 #ifdef CONFIG_LOCKDEP
609 * Slab sometimes uses the kmalloc slabs to store the slab headers
610 * for other slabs "off slab".
611 * The locking for this is tricky in that it nests within the locks
612 * of all other slabs in a few places; to deal with this special
613 * locking we put on-slab caches into a separate lock-class.
615 * We set lock class for alien array caches which are up during init.
616 * The lock annotation will be lost if all cpus of a node goes down and
617 * then comes back up during hotplug
619 static struct lock_class_key on_slab_l3_key;
620 static struct lock_class_key on_slab_alc_key;
622 static inline void init_lock_keys(void)
626 struct cache_sizes *s = malloc_sizes;
628 while (s->cs_size != ULONG_MAX) {
630 struct array_cache **alc;
632 struct kmem_list3 *l3 = s->cs_cachep->nodelists[q];
633 if (!l3 || OFF_SLAB(s->cs_cachep))
635 lockdep_set_class(&l3->list_lock, &on_slab_l3_key);
638 * FIXME: This check for BAD_ALIEN_MAGIC
639 * should go away when common slab code is taught to
640 * work even without alien caches.
641 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
642 * for alloc_alien_cache,
644 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
648 lockdep_set_class(&alc[r]->lock,
656 static inline void init_lock_keys(void)
662 * Guard access to the cache-chain.
664 static DEFINE_MUTEX(cache_chain_mutex);
665 static struct list_head cache_chain;
668 * chicken and egg problem: delay the per-cpu array allocation
669 * until the general caches are up.
679 * used by boot code to determine if it can use slab based allocator
681 int slab_is_available(void)
683 return g_cpucache_up == FULL;
686 static DEFINE_PER_CPU(struct delayed_work, reap_work);
688 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
690 return cachep->array[smp_processor_id()];
693 static inline struct kmem_cache *__find_general_cachep(size_t size,
696 struct cache_sizes *csizep = malloc_sizes;
699 /* This happens if someone tries to call
700 * kmem_cache_create(), or __kmalloc(), before
701 * the generic caches are initialized.
703 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
706 return ZERO_SIZE_PTR;
708 while (size > csizep->cs_size)
712 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
713 * has cs_{dma,}cachep==NULL. Thus no special case
714 * for large kmalloc calls required.
716 #ifdef CONFIG_ZONE_DMA
717 if (unlikely(gfpflags & GFP_DMA))
718 return csizep->cs_dmacachep;
720 return csizep->cs_cachep;
723 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
725 return __find_general_cachep(size, gfpflags);
728 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
730 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
734 * Calculate the number of objects and left-over bytes for a given buffer size.
736 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
737 size_t align, int flags, size_t *left_over,
742 size_t slab_size = PAGE_SIZE << gfporder;
745 * The slab management structure can be either off the slab or
746 * on it. For the latter case, the memory allocated for a
750 * - One kmem_bufctl_t for each object
751 * - Padding to respect alignment of @align
752 * - @buffer_size bytes for each object
754 * If the slab management structure is off the slab, then the
755 * alignment will already be calculated into the size. Because
756 * the slabs are all pages aligned, the objects will be at the
757 * correct alignment when allocated.
759 if (flags & CFLGS_OFF_SLAB) {
761 nr_objs = slab_size / buffer_size;
763 if (nr_objs > SLAB_LIMIT)
764 nr_objs = SLAB_LIMIT;
767 * Ignore padding for the initial guess. The padding
768 * is at most @align-1 bytes, and @buffer_size is at
769 * least @align. In the worst case, this result will
770 * be one greater than the number of objects that fit
771 * into the memory allocation when taking the padding
774 nr_objs = (slab_size - sizeof(struct slab)) /
775 (buffer_size + sizeof(kmem_bufctl_t));
778 * This calculated number will be either the right
779 * amount, or one greater than what we want.
781 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
785 if (nr_objs > SLAB_LIMIT)
786 nr_objs = SLAB_LIMIT;
788 mgmt_size = slab_mgmt_size(nr_objs, align);
791 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
794 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
796 static void __slab_error(const char *function, struct kmem_cache *cachep,
799 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
800 function, cachep->name, msg);
805 * By default on NUMA we use alien caches to stage the freeing of
806 * objects allocated from other nodes. This causes massive memory
807 * inefficiencies when using fake NUMA setup to split memory into a
808 * large number of small nodes, so it can be disabled on the command
812 static int use_alien_caches __read_mostly = 1;
813 static int numa_platform __read_mostly = 1;
814 static int __init noaliencache_setup(char *s)
816 use_alien_caches = 0;
819 __setup("noaliencache", noaliencache_setup);
823 * Special reaping functions for NUMA systems called from cache_reap().
824 * These take care of doing round robin flushing of alien caches (containing
825 * objects freed on different nodes from which they were allocated) and the
826 * flushing of remote pcps by calling drain_node_pages.
828 static DEFINE_PER_CPU(unsigned long, reap_node);
830 static void init_reap_node(int cpu)
834 node = next_node(cpu_to_node(cpu), node_online_map);
835 if (node == MAX_NUMNODES)
836 node = first_node(node_online_map);
838 per_cpu(reap_node, cpu) = node;
841 static void next_reap_node(void)
843 int node = __get_cpu_var(reap_node);
845 node = next_node(node, node_online_map);
846 if (unlikely(node >= MAX_NUMNODES))
847 node = first_node(node_online_map);
848 __get_cpu_var(reap_node) = node;
852 #define init_reap_node(cpu) do { } while (0)
853 #define next_reap_node(void) do { } while (0)
857 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
858 * via the workqueue/eventd.
859 * Add the CPU number into the expiration time to minimize the possibility of
860 * the CPUs getting into lockstep and contending for the global cache chain
863 static void __cpuinit start_cpu_timer(int cpu)
865 struct delayed_work *reap_work = &per_cpu(reap_work, cpu);
868 * When this gets called from do_initcalls via cpucache_init(),
869 * init_workqueues() has already run, so keventd will be setup
872 if (keventd_up() && reap_work->work.func == NULL) {
874 INIT_DELAYED_WORK(reap_work, cache_reap);
875 schedule_delayed_work_on(cpu, reap_work,
876 __round_jiffies_relative(HZ, cpu));
880 static struct array_cache *alloc_arraycache(int node, int entries,
881 int batchcount, gfp_t gfp)
883 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
884 struct array_cache *nc = NULL;
886 nc = kmalloc_node(memsize, gfp, node);
888 * The array_cache structures contain pointers to free object.
889 * However, when such objects are allocated or transfered to another
890 * cache the pointers are not cleared and they could be counted as
891 * valid references during a kmemleak scan. Therefore, kmemleak must
892 * not scan such objects.
894 kmemleak_no_scan(nc);
898 nc->batchcount = batchcount;
900 spin_lock_init(&nc->lock);
906 * Transfer objects in one arraycache to another.
907 * Locking must be handled by the caller.
909 * Return the number of entries transferred.
911 static int transfer_objects(struct array_cache *to,
912 struct array_cache *from, unsigned int max)
914 /* Figure out how many entries to transfer */
915 int nr = min(min(from->avail, max), to->limit - to->avail);
920 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
931 #define drain_alien_cache(cachep, alien) do { } while (0)
932 #define reap_alien(cachep, l3) do { } while (0)
934 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
936 return (struct array_cache **)BAD_ALIEN_MAGIC;
939 static inline void free_alien_cache(struct array_cache **ac_ptr)
943 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
948 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
954 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
955 gfp_t flags, int nodeid)
960 #else /* CONFIG_NUMA */
962 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
963 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
965 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
967 struct array_cache **ac_ptr;
968 int memsize = sizeof(void *) * nr_node_ids;
973 ac_ptr = kmalloc_node(memsize, gfp, node);
976 if (i == node || !node_online(i)) {
980 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
982 for (i--; i >= 0; i--)
992 static void free_alien_cache(struct array_cache **ac_ptr)
1003 static void __drain_alien_cache(struct kmem_cache *cachep,
1004 struct array_cache *ac, int node)
1006 struct kmem_list3 *rl3 = cachep->nodelists[node];
1009 spin_lock(&rl3->list_lock);
1011 * Stuff objects into the remote nodes shared array first.
1012 * That way we could avoid the overhead of putting the objects
1013 * into the free lists and getting them back later.
1016 transfer_objects(rl3->shared, ac, ac->limit);
1018 free_block(cachep, ac->entry, ac->avail, node);
1020 spin_unlock(&rl3->list_lock);
1025 * Called from cache_reap() to regularly drain alien caches round robin.
1027 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1029 int node = __get_cpu_var(reap_node);
1032 struct array_cache *ac = l3->alien[node];
1034 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1035 __drain_alien_cache(cachep, ac, node);
1036 spin_unlock_irq(&ac->lock);
1041 static void drain_alien_cache(struct kmem_cache *cachep,
1042 struct array_cache **alien)
1045 struct array_cache *ac;
1046 unsigned long flags;
1048 for_each_online_node(i) {
1051 spin_lock_irqsave(&ac->lock, flags);
1052 __drain_alien_cache(cachep, ac, i);
1053 spin_unlock_irqrestore(&ac->lock, flags);
1058 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1060 struct slab *slabp = virt_to_slab(objp);
1061 int nodeid = slabp->nodeid;
1062 struct kmem_list3 *l3;
1063 struct array_cache *alien = NULL;
1066 node = numa_node_id();
1069 * Make sure we are not freeing a object from another node to the array
1070 * cache on this cpu.
1072 if (likely(slabp->nodeid == node))
1075 l3 = cachep->nodelists[node];
1076 STATS_INC_NODEFREES(cachep);
1077 if (l3->alien && l3->alien[nodeid]) {
1078 alien = l3->alien[nodeid];
1079 spin_lock(&alien->lock);
1080 if (unlikely(alien->avail == alien->limit)) {
1081 STATS_INC_ACOVERFLOW(cachep);
1082 __drain_alien_cache(cachep, alien, nodeid);
1084 alien->entry[alien->avail++] = objp;
1085 spin_unlock(&alien->lock);
1087 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1088 free_block(cachep, &objp, 1, nodeid);
1089 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1095 static void __cpuinit cpuup_canceled(long cpu)
1097 struct kmem_cache *cachep;
1098 struct kmem_list3 *l3 = NULL;
1099 int node = cpu_to_node(cpu);
1100 const struct cpumask *mask = cpumask_of_node(node);
1102 list_for_each_entry(cachep, &cache_chain, next) {
1103 struct array_cache *nc;
1104 struct array_cache *shared;
1105 struct array_cache **alien;
1107 /* cpu is dead; no one can alloc from it. */
1108 nc = cachep->array[cpu];
1109 cachep->array[cpu] = NULL;
1110 l3 = cachep->nodelists[node];
1113 goto free_array_cache;
1115 spin_lock_irq(&l3->list_lock);
1117 /* Free limit for this kmem_list3 */
1118 l3->free_limit -= cachep->batchcount;
1120 free_block(cachep, nc->entry, nc->avail, node);
1122 if (!cpus_empty(*mask)) {
1123 spin_unlock_irq(&l3->list_lock);
1124 goto free_array_cache;
1127 shared = l3->shared;
1129 free_block(cachep, shared->entry,
1130 shared->avail, node);
1137 spin_unlock_irq(&l3->list_lock);
1141 drain_alien_cache(cachep, alien);
1142 free_alien_cache(alien);
1148 * In the previous loop, all the objects were freed to
1149 * the respective cache's slabs, now we can go ahead and
1150 * shrink each nodelist to its limit.
1152 list_for_each_entry(cachep, &cache_chain, next) {
1153 l3 = cachep->nodelists[node];
1156 drain_freelist(cachep, l3, l3->free_objects);
1160 static int __cpuinit cpuup_prepare(long cpu)
1162 struct kmem_cache *cachep;
1163 struct kmem_list3 *l3 = NULL;
1164 int node = cpu_to_node(cpu);
1165 const int memsize = sizeof(struct kmem_list3);
1168 * We need to do this right in the beginning since
1169 * alloc_arraycache's are going to use this list.
1170 * kmalloc_node allows us to add the slab to the right
1171 * kmem_list3 and not this cpu's kmem_list3
1174 list_for_each_entry(cachep, &cache_chain, next) {
1176 * Set up the size64 kmemlist for cpu before we can
1177 * begin anything. Make sure some other cpu on this
1178 * node has not already allocated this
1180 if (!cachep->nodelists[node]) {
1181 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1184 kmem_list3_init(l3);
1185 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1186 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1189 * The l3s don't come and go as CPUs come and
1190 * go. cache_chain_mutex is sufficient
1193 cachep->nodelists[node] = l3;
1196 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1197 cachep->nodelists[node]->free_limit =
1198 (1 + nr_cpus_node(node)) *
1199 cachep->batchcount + cachep->num;
1200 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1204 * Now we can go ahead with allocating the shared arrays and
1207 list_for_each_entry(cachep, &cache_chain, next) {
1208 struct array_cache *nc;
1209 struct array_cache *shared = NULL;
1210 struct array_cache **alien = NULL;
1212 nc = alloc_arraycache(node, cachep->limit,
1213 cachep->batchcount, GFP_KERNEL);
1216 if (cachep->shared) {
1217 shared = alloc_arraycache(node,
1218 cachep->shared * cachep->batchcount,
1219 0xbaadf00d, GFP_KERNEL);
1225 if (use_alien_caches) {
1226 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1233 cachep->array[cpu] = nc;
1234 l3 = cachep->nodelists[node];
1237 spin_lock_irq(&l3->list_lock);
1240 * We are serialised from CPU_DEAD or
1241 * CPU_UP_CANCELLED by the cpucontrol lock
1243 l3->shared = shared;
1252 spin_unlock_irq(&l3->list_lock);
1254 free_alien_cache(alien);
1258 cpuup_canceled(cpu);
1262 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1263 unsigned long action, void *hcpu)
1265 long cpu = (long)hcpu;
1269 case CPU_UP_PREPARE:
1270 case CPU_UP_PREPARE_FROZEN:
1271 mutex_lock(&cache_chain_mutex);
1272 err = cpuup_prepare(cpu);
1273 mutex_unlock(&cache_chain_mutex);
1276 case CPU_ONLINE_FROZEN:
1277 start_cpu_timer(cpu);
1279 #ifdef CONFIG_HOTPLUG_CPU
1280 case CPU_DOWN_PREPARE:
1281 case CPU_DOWN_PREPARE_FROZEN:
1283 * Shutdown cache reaper. Note that the cache_chain_mutex is
1284 * held so that if cache_reap() is invoked it cannot do
1285 * anything expensive but will only modify reap_work
1286 * and reschedule the timer.
1288 cancel_rearming_delayed_work(&per_cpu(reap_work, cpu));
1289 /* Now the cache_reaper is guaranteed to be not running. */
1290 per_cpu(reap_work, cpu).work.func = NULL;
1292 case CPU_DOWN_FAILED:
1293 case CPU_DOWN_FAILED_FROZEN:
1294 start_cpu_timer(cpu);
1297 case CPU_DEAD_FROZEN:
1299 * Even if all the cpus of a node are down, we don't free the
1300 * kmem_list3 of any cache. This to avoid a race between
1301 * cpu_down, and a kmalloc allocation from another cpu for
1302 * memory from the node of the cpu going down. The list3
1303 * structure is usually allocated from kmem_cache_create() and
1304 * gets destroyed at kmem_cache_destroy().
1308 case CPU_UP_CANCELED:
1309 case CPU_UP_CANCELED_FROZEN:
1310 mutex_lock(&cache_chain_mutex);
1311 cpuup_canceled(cpu);
1312 mutex_unlock(&cache_chain_mutex);
1315 return err ? NOTIFY_BAD : NOTIFY_OK;
1318 static struct notifier_block __cpuinitdata cpucache_notifier = {
1319 &cpuup_callback, NULL, 0
1323 * swap the static kmem_list3 with kmalloced memory
1325 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1328 struct kmem_list3 *ptr;
1330 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_NOWAIT, nodeid);
1333 memcpy(ptr, list, sizeof(struct kmem_list3));
1335 * Do not assume that spinlocks can be initialized via memcpy:
1337 spin_lock_init(&ptr->list_lock);
1339 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1340 cachep->nodelists[nodeid] = ptr;
1344 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1345 * size of kmem_list3.
1347 static void __init set_up_list3s(struct kmem_cache *cachep, int index)
1351 for_each_online_node(node) {
1352 cachep->nodelists[node] = &initkmem_list3[index + node];
1353 cachep->nodelists[node]->next_reap = jiffies +
1355 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1360 * Initialisation. Called after the page allocator have been initialised and
1361 * before smp_init().
1363 void __init kmem_cache_init(void)
1366 struct cache_sizes *sizes;
1367 struct cache_names *names;
1372 if (num_possible_nodes() == 1) {
1373 use_alien_caches = 0;
1377 for (i = 0; i < NUM_INIT_LISTS; i++) {
1378 kmem_list3_init(&initkmem_list3[i]);
1379 if (i < MAX_NUMNODES)
1380 cache_cache.nodelists[i] = NULL;
1382 set_up_list3s(&cache_cache, CACHE_CACHE);
1385 * Fragmentation resistance on low memory - only use bigger
1386 * page orders on machines with more than 32MB of memory.
1388 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
1389 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1391 /* Bootstrap is tricky, because several objects are allocated
1392 * from caches that do not exist yet:
1393 * 1) initialize the cache_cache cache: it contains the struct
1394 * kmem_cache structures of all caches, except cache_cache itself:
1395 * cache_cache is statically allocated.
1396 * Initially an __init data area is used for the head array and the
1397 * kmem_list3 structures, it's replaced with a kmalloc allocated
1398 * array at the end of the bootstrap.
1399 * 2) Create the first kmalloc cache.
1400 * The struct kmem_cache for the new cache is allocated normally.
1401 * An __init data area is used for the head array.
1402 * 3) Create the remaining kmalloc caches, with minimally sized
1404 * 4) Replace the __init data head arrays for cache_cache and the first
1405 * kmalloc cache with kmalloc allocated arrays.
1406 * 5) Replace the __init data for kmem_list3 for cache_cache and
1407 * the other cache's with kmalloc allocated memory.
1408 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1411 node = numa_node_id();
1413 /* 1) create the cache_cache */
1414 INIT_LIST_HEAD(&cache_chain);
1415 list_add(&cache_cache.next, &cache_chain);
1416 cache_cache.colour_off = cache_line_size();
1417 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1418 cache_cache.nodelists[node] = &initkmem_list3[CACHE_CACHE + node];
1421 * struct kmem_cache size depends on nr_node_ids, which
1422 * can be less than MAX_NUMNODES.
1424 cache_cache.buffer_size = offsetof(struct kmem_cache, nodelists) +
1425 nr_node_ids * sizeof(struct kmem_list3 *);
1427 cache_cache.obj_size = cache_cache.buffer_size;
1429 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1431 cache_cache.reciprocal_buffer_size =
1432 reciprocal_value(cache_cache.buffer_size);
1434 for (order = 0; order < MAX_ORDER; order++) {
1435 cache_estimate(order, cache_cache.buffer_size,
1436 cache_line_size(), 0, &left_over, &cache_cache.num);
1437 if (cache_cache.num)
1440 BUG_ON(!cache_cache.num);
1441 cache_cache.gfporder = order;
1442 cache_cache.colour = left_over / cache_cache.colour_off;
1443 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1444 sizeof(struct slab), cache_line_size());
1446 /* 2+3) create the kmalloc caches */
1447 sizes = malloc_sizes;
1448 names = cache_names;
1451 * Initialize the caches that provide memory for the array cache and the
1452 * kmem_list3 structures first. Without this, further allocations will
1456 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1457 sizes[INDEX_AC].cs_size,
1458 ARCH_KMALLOC_MINALIGN,
1459 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1462 if (INDEX_AC != INDEX_L3) {
1463 sizes[INDEX_L3].cs_cachep =
1464 kmem_cache_create(names[INDEX_L3].name,
1465 sizes[INDEX_L3].cs_size,
1466 ARCH_KMALLOC_MINALIGN,
1467 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1471 slab_early_init = 0;
1473 while (sizes->cs_size != ULONG_MAX) {
1475 * For performance, all the general caches are L1 aligned.
1476 * This should be particularly beneficial on SMP boxes, as it
1477 * eliminates "false sharing".
1478 * Note for systems short on memory removing the alignment will
1479 * allow tighter packing of the smaller caches.
1481 if (!sizes->cs_cachep) {
1482 sizes->cs_cachep = kmem_cache_create(names->name,
1484 ARCH_KMALLOC_MINALIGN,
1485 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1488 #ifdef CONFIG_ZONE_DMA
1489 sizes->cs_dmacachep = kmem_cache_create(
1492 ARCH_KMALLOC_MINALIGN,
1493 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1500 /* 4) Replace the bootstrap head arrays */
1502 struct array_cache *ptr;
1504 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1506 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1507 memcpy(ptr, cpu_cache_get(&cache_cache),
1508 sizeof(struct arraycache_init));
1510 * Do not assume that spinlocks can be initialized via memcpy:
1512 spin_lock_init(&ptr->lock);
1514 cache_cache.array[smp_processor_id()] = ptr;
1516 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1518 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1519 != &initarray_generic.cache);
1520 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1521 sizeof(struct arraycache_init));
1523 * Do not assume that spinlocks can be initialized via memcpy:
1525 spin_lock_init(&ptr->lock);
1527 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1530 /* 5) Replace the bootstrap kmem_list3's */
1534 for_each_online_node(nid) {
1535 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE + nid], nid);
1537 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1538 &initkmem_list3[SIZE_AC + nid], nid);
1540 if (INDEX_AC != INDEX_L3) {
1541 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1542 &initkmem_list3[SIZE_L3 + nid], nid);
1547 /* 6) resize the head arrays to their final sizes */
1549 struct kmem_cache *cachep;
1550 mutex_lock(&cache_chain_mutex);
1551 list_for_each_entry(cachep, &cache_chain, next)
1552 if (enable_cpucache(cachep, GFP_NOWAIT))
1554 mutex_unlock(&cache_chain_mutex);
1557 /* Annotate slab for lockdep -- annotate the malloc caches */
1562 g_cpucache_up = FULL;
1565 * Register a cpu startup notifier callback that initializes
1566 * cpu_cache_get for all new cpus
1568 register_cpu_notifier(&cpucache_notifier);
1571 * The reap timers are started later, with a module init call: That part
1572 * of the kernel is not yet operational.
1576 static int __init cpucache_init(void)
1581 * Register the timers that return unneeded pages to the page allocator
1583 for_each_online_cpu(cpu)
1584 start_cpu_timer(cpu);
1587 __initcall(cpucache_init);
1590 * Interface to system's page allocator. No need to hold the cache-lock.
1592 * If we requested dmaable memory, we will get it. Even if we
1593 * did not request dmaable memory, we might get it, but that
1594 * would be relatively rare and ignorable.
1596 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1604 * Nommu uses slab's for process anonymous memory allocations, and thus
1605 * requires __GFP_COMP to properly refcount higher order allocations
1607 flags |= __GFP_COMP;
1610 flags |= cachep->gfpflags;
1611 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1612 flags |= __GFP_RECLAIMABLE;
1614 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
1618 nr_pages = (1 << cachep->gfporder);
1619 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1620 add_zone_page_state(page_zone(page),
1621 NR_SLAB_RECLAIMABLE, nr_pages);
1623 add_zone_page_state(page_zone(page),
1624 NR_SLAB_UNRECLAIMABLE, nr_pages);
1625 for (i = 0; i < nr_pages; i++)
1626 __SetPageSlab(page + i);
1627 return page_address(page);
1631 * Interface to system's page release.
1633 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1635 unsigned long i = (1 << cachep->gfporder);
1636 struct page *page = virt_to_page(addr);
1637 const unsigned long nr_freed = i;
1639 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1640 sub_zone_page_state(page_zone(page),
1641 NR_SLAB_RECLAIMABLE, nr_freed);
1643 sub_zone_page_state(page_zone(page),
1644 NR_SLAB_UNRECLAIMABLE, nr_freed);
1646 BUG_ON(!PageSlab(page));
1647 __ClearPageSlab(page);
1650 if (current->reclaim_state)
1651 current->reclaim_state->reclaimed_slab += nr_freed;
1652 free_pages((unsigned long)addr, cachep->gfporder);
1655 static void kmem_rcu_free(struct rcu_head *head)
1657 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1658 struct kmem_cache *cachep = slab_rcu->cachep;
1660 kmem_freepages(cachep, slab_rcu->addr);
1661 if (OFF_SLAB(cachep))
1662 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1667 #ifdef CONFIG_DEBUG_PAGEALLOC
1668 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1669 unsigned long caller)
1671 int size = obj_size(cachep);
1673 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1675 if (size < 5 * sizeof(unsigned long))
1678 *addr++ = 0x12345678;
1680 *addr++ = smp_processor_id();
1681 size -= 3 * sizeof(unsigned long);
1683 unsigned long *sptr = &caller;
1684 unsigned long svalue;
1686 while (!kstack_end(sptr)) {
1688 if (kernel_text_address(svalue)) {
1690 size -= sizeof(unsigned long);
1691 if (size <= sizeof(unsigned long))
1697 *addr++ = 0x87654321;
1701 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1703 int size = obj_size(cachep);
1704 addr = &((char *)addr)[obj_offset(cachep)];
1706 memset(addr, val, size);
1707 *(unsigned char *)(addr + size - 1) = POISON_END;
1710 static void dump_line(char *data, int offset, int limit)
1713 unsigned char error = 0;
1716 printk(KERN_ERR "%03x:", offset);
1717 for (i = 0; i < limit; i++) {
1718 if (data[offset + i] != POISON_FREE) {
1719 error = data[offset + i];
1722 printk(" %02x", (unsigned char)data[offset + i]);
1726 if (bad_count == 1) {
1727 error ^= POISON_FREE;
1728 if (!(error & (error - 1))) {
1729 printk(KERN_ERR "Single bit error detected. Probably "
1732 printk(KERN_ERR "Run memtest86+ or a similar memory "
1735 printk(KERN_ERR "Run a memory test tool.\n");
1744 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1749 if (cachep->flags & SLAB_RED_ZONE) {
1750 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1751 *dbg_redzone1(cachep, objp),
1752 *dbg_redzone2(cachep, objp));
1755 if (cachep->flags & SLAB_STORE_USER) {
1756 printk(KERN_ERR "Last user: [<%p>]",
1757 *dbg_userword(cachep, objp));
1758 print_symbol("(%s)",
1759 (unsigned long)*dbg_userword(cachep, objp));
1762 realobj = (char *)objp + obj_offset(cachep);
1763 size = obj_size(cachep);
1764 for (i = 0; i < size && lines; i += 16, lines--) {
1767 if (i + limit > size)
1769 dump_line(realobj, i, limit);
1773 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1779 realobj = (char *)objp + obj_offset(cachep);
1780 size = obj_size(cachep);
1782 for (i = 0; i < size; i++) {
1783 char exp = POISON_FREE;
1786 if (realobj[i] != exp) {
1792 "Slab corruption: %s start=%p, len=%d\n",
1793 cachep->name, realobj, size);
1794 print_objinfo(cachep, objp, 0);
1796 /* Hexdump the affected line */
1799 if (i + limit > size)
1801 dump_line(realobj, i, limit);
1804 /* Limit to 5 lines */
1810 /* Print some data about the neighboring objects, if they
1813 struct slab *slabp = virt_to_slab(objp);
1816 objnr = obj_to_index(cachep, slabp, objp);
1818 objp = index_to_obj(cachep, slabp, objnr - 1);
1819 realobj = (char *)objp + obj_offset(cachep);
1820 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1822 print_objinfo(cachep, objp, 2);
1824 if (objnr + 1 < cachep->num) {
1825 objp = index_to_obj(cachep, slabp, objnr + 1);
1826 realobj = (char *)objp + obj_offset(cachep);
1827 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1829 print_objinfo(cachep, objp, 2);
1836 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
1839 for (i = 0; i < cachep->num; i++) {
1840 void *objp = index_to_obj(cachep, slabp, i);
1842 if (cachep->flags & SLAB_POISON) {
1843 #ifdef CONFIG_DEBUG_PAGEALLOC
1844 if (cachep->buffer_size % PAGE_SIZE == 0 &&
1846 kernel_map_pages(virt_to_page(objp),
1847 cachep->buffer_size / PAGE_SIZE, 1);
1849 check_poison_obj(cachep, objp);
1851 check_poison_obj(cachep, objp);
1854 if (cachep->flags & SLAB_RED_ZONE) {
1855 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1856 slab_error(cachep, "start of a freed object "
1858 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1859 slab_error(cachep, "end of a freed object "
1865 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
1871 * slab_destroy - destroy and release all objects in a slab
1872 * @cachep: cache pointer being destroyed
1873 * @slabp: slab pointer being destroyed
1875 * Destroy all the objs in a slab, and release the mem back to the system.
1876 * Before calling the slab must have been unlinked from the cache. The
1877 * cache-lock is not held/needed.
1879 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1881 void *addr = slabp->s_mem - slabp->colouroff;
1883 slab_destroy_debugcheck(cachep, slabp);
1884 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1885 struct slab_rcu *slab_rcu;
1887 slab_rcu = (struct slab_rcu *)slabp;
1888 slab_rcu->cachep = cachep;
1889 slab_rcu->addr = addr;
1890 call_rcu(&slab_rcu->head, kmem_rcu_free);
1892 kmem_freepages(cachep, addr);
1893 if (OFF_SLAB(cachep))
1894 kmem_cache_free(cachep->slabp_cache, slabp);
1898 static void __kmem_cache_destroy(struct kmem_cache *cachep)
1901 struct kmem_list3 *l3;
1903 for_each_online_cpu(i)
1904 kfree(cachep->array[i]);
1906 /* NUMA: free the list3 structures */
1907 for_each_online_node(i) {
1908 l3 = cachep->nodelists[i];
1911 free_alien_cache(l3->alien);
1915 kmem_cache_free(&cache_cache, cachep);
1920 * calculate_slab_order - calculate size (page order) of slabs
1921 * @cachep: pointer to the cache that is being created
1922 * @size: size of objects to be created in this cache.
1923 * @align: required alignment for the objects.
1924 * @flags: slab allocation flags
1926 * Also calculates the number of objects per slab.
1928 * This could be made much more intelligent. For now, try to avoid using
1929 * high order pages for slabs. When the gfp() functions are more friendly
1930 * towards high-order requests, this should be changed.
1932 static size_t calculate_slab_order(struct kmem_cache *cachep,
1933 size_t size, size_t align, unsigned long flags)
1935 unsigned long offslab_limit;
1936 size_t left_over = 0;
1939 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
1943 cache_estimate(gfporder, size, align, flags, &remainder, &num);
1947 if (flags & CFLGS_OFF_SLAB) {
1949 * Max number of objs-per-slab for caches which
1950 * use off-slab slabs. Needed to avoid a possible
1951 * looping condition in cache_grow().
1953 offslab_limit = size - sizeof(struct slab);
1954 offslab_limit /= sizeof(kmem_bufctl_t);
1956 if (num > offslab_limit)
1960 /* Found something acceptable - save it away */
1962 cachep->gfporder = gfporder;
1963 left_over = remainder;
1966 * A VFS-reclaimable slab tends to have most allocations
1967 * as GFP_NOFS and we really don't want to have to be allocating
1968 * higher-order pages when we are unable to shrink dcache.
1970 if (flags & SLAB_RECLAIM_ACCOUNT)
1974 * Large number of objects is good, but very large slabs are
1975 * currently bad for the gfp()s.
1977 if (gfporder >= slab_break_gfp_order)
1981 * Acceptable internal fragmentation?
1983 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1989 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
1991 if (g_cpucache_up == FULL)
1992 return enable_cpucache(cachep, gfp);
1994 if (g_cpucache_up == NONE) {
1996 * Note: the first kmem_cache_create must create the cache
1997 * that's used by kmalloc(24), otherwise the creation of
1998 * further caches will BUG().
2000 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2003 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2004 * the first cache, then we need to set up all its list3s,
2005 * otherwise the creation of further caches will BUG().
2007 set_up_list3s(cachep, SIZE_AC);
2008 if (INDEX_AC == INDEX_L3)
2009 g_cpucache_up = PARTIAL_L3;
2011 g_cpucache_up = PARTIAL_AC;
2013 cachep->array[smp_processor_id()] =
2014 kmalloc(sizeof(struct arraycache_init), gfp);
2016 if (g_cpucache_up == PARTIAL_AC) {
2017 set_up_list3s(cachep, SIZE_L3);
2018 g_cpucache_up = PARTIAL_L3;
2021 for_each_online_node(node) {
2022 cachep->nodelists[node] =
2023 kmalloc_node(sizeof(struct kmem_list3),
2025 BUG_ON(!cachep->nodelists[node]);
2026 kmem_list3_init(cachep->nodelists[node]);
2030 cachep->nodelists[numa_node_id()]->next_reap =
2031 jiffies + REAPTIMEOUT_LIST3 +
2032 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2034 cpu_cache_get(cachep)->avail = 0;
2035 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2036 cpu_cache_get(cachep)->batchcount = 1;
2037 cpu_cache_get(cachep)->touched = 0;
2038 cachep->batchcount = 1;
2039 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2044 * kmem_cache_create - Create a cache.
2045 * @name: A string which is used in /proc/slabinfo to identify this cache.
2046 * @size: The size of objects to be created in this cache.
2047 * @align: The required alignment for the objects.
2048 * @flags: SLAB flags
2049 * @ctor: A constructor for the objects.
2051 * Returns a ptr to the cache on success, NULL on failure.
2052 * Cannot be called within a int, but can be interrupted.
2053 * The @ctor is run when new pages are allocated by the cache.
2055 * @name must be valid until the cache is destroyed. This implies that
2056 * the module calling this has to destroy the cache before getting unloaded.
2057 * Note that kmem_cache_name() is not guaranteed to return the same pointer,
2058 * therefore applications must manage it themselves.
2062 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2063 * to catch references to uninitialised memory.
2065 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2066 * for buffer overruns.
2068 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2069 * cacheline. This can be beneficial if you're counting cycles as closely
2073 kmem_cache_create (const char *name, size_t size, size_t align,
2074 unsigned long flags, void (*ctor)(void *))
2076 size_t left_over, slab_size, ralign;
2077 struct kmem_cache *cachep = NULL, *pc;
2081 * Sanity checks... these are all serious usage bugs.
2083 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
2084 size > KMALLOC_MAX_SIZE) {
2085 printk(KERN_ERR "%s: Early error in slab %s\n", __func__,
2091 * We use cache_chain_mutex to ensure a consistent view of
2092 * cpu_online_mask as well. Please see cpuup_callback
2094 if (slab_is_available()) {
2096 mutex_lock(&cache_chain_mutex);
2099 list_for_each_entry(pc, &cache_chain, next) {
2104 * This happens when the module gets unloaded and doesn't
2105 * destroy its slab cache and no-one else reuses the vmalloc
2106 * area of the module. Print a warning.
2108 res = probe_kernel_address(pc->name, tmp);
2111 "SLAB: cache with size %d has lost its name\n",
2116 if (!strcmp(pc->name, name)) {
2118 "kmem_cache_create: duplicate cache %s\n", name);
2125 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2128 * Enable redzoning and last user accounting, except for caches with
2129 * large objects, if the increased size would increase the object size
2130 * above the next power of two: caches with object sizes just above a
2131 * power of two have a significant amount of internal fragmentation.
2133 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2134 2 * sizeof(unsigned long long)))
2135 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2136 if (!(flags & SLAB_DESTROY_BY_RCU))
2137 flags |= SLAB_POISON;
2139 if (flags & SLAB_DESTROY_BY_RCU)
2140 BUG_ON(flags & SLAB_POISON);
2143 * Always checks flags, a caller might be expecting debug support which
2146 BUG_ON(flags & ~CREATE_MASK);
2149 * Check that size is in terms of words. This is needed to avoid
2150 * unaligned accesses for some archs when redzoning is used, and makes
2151 * sure any on-slab bufctl's are also correctly aligned.
2153 if (size & (BYTES_PER_WORD - 1)) {
2154 size += (BYTES_PER_WORD - 1);
2155 size &= ~(BYTES_PER_WORD - 1);
2158 /* calculate the final buffer alignment: */
2160 /* 1) arch recommendation: can be overridden for debug */
2161 if (flags & SLAB_HWCACHE_ALIGN) {
2163 * Default alignment: as specified by the arch code. Except if
2164 * an object is really small, then squeeze multiple objects into
2167 ralign = cache_line_size();
2168 while (size <= ralign / 2)
2171 ralign = BYTES_PER_WORD;
2175 * Redzoning and user store require word alignment or possibly larger.
2176 * Note this will be overridden by architecture or caller mandated
2177 * alignment if either is greater than BYTES_PER_WORD.
2179 if (flags & SLAB_STORE_USER)
2180 ralign = BYTES_PER_WORD;
2182 if (flags & SLAB_RED_ZONE) {
2183 ralign = REDZONE_ALIGN;
2184 /* If redzoning, ensure that the second redzone is suitably
2185 * aligned, by adjusting the object size accordingly. */
2186 size += REDZONE_ALIGN - 1;
2187 size &= ~(REDZONE_ALIGN - 1);
2190 /* 2) arch mandated alignment */
2191 if (ralign < ARCH_SLAB_MINALIGN) {
2192 ralign = ARCH_SLAB_MINALIGN;
2194 /* 3) caller mandated alignment */
2195 if (ralign < align) {
2198 /* disable debug if necessary */
2199 if (ralign > __alignof__(unsigned long long))
2200 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2206 if (slab_is_available())
2211 /* Get cache's description obj. */
2212 cachep = kmem_cache_zalloc(&cache_cache, gfp);
2217 cachep->obj_size = size;
2220 * Both debugging options require word-alignment which is calculated
2223 if (flags & SLAB_RED_ZONE) {
2224 /* add space for red zone words */
2225 cachep->obj_offset += sizeof(unsigned long long);
2226 size += 2 * sizeof(unsigned long long);
2228 if (flags & SLAB_STORE_USER) {
2229 /* user store requires one word storage behind the end of
2230 * the real object. But if the second red zone needs to be
2231 * aligned to 64 bits, we must allow that much space.
2233 if (flags & SLAB_RED_ZONE)
2234 size += REDZONE_ALIGN;
2236 size += BYTES_PER_WORD;
2238 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2239 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2240 && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2241 cachep->obj_offset += PAGE_SIZE - size;
2248 * Determine if the slab management is 'on' or 'off' slab.
2249 * (bootstrapping cannot cope with offslab caches so don't do
2252 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init)
2254 * Size is large, assume best to place the slab management obj
2255 * off-slab (should allow better packing of objs).
2257 flags |= CFLGS_OFF_SLAB;
2259 size = ALIGN(size, align);
2261 left_over = calculate_slab_order(cachep, size, align, flags);
2265 "kmem_cache_create: couldn't create cache %s.\n", name);
2266 kmem_cache_free(&cache_cache, cachep);
2270 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2271 + sizeof(struct slab), align);
2274 * If the slab has been placed off-slab, and we have enough space then
2275 * move it on-slab. This is at the expense of any extra colouring.
2277 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2278 flags &= ~CFLGS_OFF_SLAB;
2279 left_over -= slab_size;
2282 if (flags & CFLGS_OFF_SLAB) {
2283 /* really off slab. No need for manual alignment */
2285 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2288 cachep->colour_off = cache_line_size();
2289 /* Offset must be a multiple of the alignment. */
2290 if (cachep->colour_off < align)
2291 cachep->colour_off = align;
2292 cachep->colour = left_over / cachep->colour_off;
2293 cachep->slab_size = slab_size;
2294 cachep->flags = flags;
2295 cachep->gfpflags = 0;
2296 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2297 cachep->gfpflags |= GFP_DMA;
2298 cachep->buffer_size = size;
2299 cachep->reciprocal_buffer_size = reciprocal_value(size);
2301 if (flags & CFLGS_OFF_SLAB) {
2302 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2304 * This is a possibility for one of the malloc_sizes caches.
2305 * But since we go off slab only for object size greater than
2306 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2307 * this should not happen at all.
2308 * But leave a BUG_ON for some lucky dude.
2310 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2312 cachep->ctor = ctor;
2313 cachep->name = name;
2315 if (setup_cpu_cache(cachep, gfp)) {
2316 __kmem_cache_destroy(cachep);
2321 /* cache setup completed, link it into the list */
2322 list_add(&cachep->next, &cache_chain);
2324 if (!cachep && (flags & SLAB_PANIC))
2325 panic("kmem_cache_create(): failed to create slab `%s'\n",
2327 if (slab_is_available()) {
2328 mutex_unlock(&cache_chain_mutex);
2333 EXPORT_SYMBOL(kmem_cache_create);
2336 static void check_irq_off(void)
2338 BUG_ON(!irqs_disabled());
2341 static void check_irq_on(void)
2343 BUG_ON(irqs_disabled());
2346 static void check_spinlock_acquired(struct kmem_cache *cachep)
2350 assert_spin_locked(&cachep->nodelists[numa_node_id()]->list_lock);
2354 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2358 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2363 #define check_irq_off() do { } while(0)
2364 #define check_irq_on() do { } while(0)
2365 #define check_spinlock_acquired(x) do { } while(0)
2366 #define check_spinlock_acquired_node(x, y) do { } while(0)
2369 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2370 struct array_cache *ac,
2371 int force, int node);
2373 static void do_drain(void *arg)
2375 struct kmem_cache *cachep = arg;
2376 struct array_cache *ac;
2377 int node = numa_node_id();
2380 ac = cpu_cache_get(cachep);
2381 spin_lock(&cachep->nodelists[node]->list_lock);
2382 free_block(cachep, ac->entry, ac->avail, node);
2383 spin_unlock(&cachep->nodelists[node]->list_lock);
2387 static void drain_cpu_caches(struct kmem_cache *cachep)
2389 struct kmem_list3 *l3;
2392 on_each_cpu(do_drain, cachep, 1);
2394 for_each_online_node(node) {
2395 l3 = cachep->nodelists[node];
2396 if (l3 && l3->alien)
2397 drain_alien_cache(cachep, l3->alien);
2400 for_each_online_node(node) {
2401 l3 = cachep->nodelists[node];
2403 drain_array(cachep, l3, l3->shared, 1, node);
2408 * Remove slabs from the list of free slabs.
2409 * Specify the number of slabs to drain in tofree.
2411 * Returns the actual number of slabs released.
2413 static int drain_freelist(struct kmem_cache *cache,
2414 struct kmem_list3 *l3, int tofree)
2416 struct list_head *p;
2421 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2423 spin_lock_irq(&l3->list_lock);
2424 p = l3->slabs_free.prev;
2425 if (p == &l3->slabs_free) {
2426 spin_unlock_irq(&l3->list_lock);
2430 slabp = list_entry(p, struct slab, list);
2432 BUG_ON(slabp->inuse);
2434 list_del(&slabp->list);
2436 * Safe to drop the lock. The slab is no longer linked
2439 l3->free_objects -= cache->num;
2440 spin_unlock_irq(&l3->list_lock);
2441 slab_destroy(cache, slabp);
2448 /* Called with cache_chain_mutex held to protect against cpu hotplug */
2449 static int __cache_shrink(struct kmem_cache *cachep)
2452 struct kmem_list3 *l3;
2454 drain_cpu_caches(cachep);
2457 for_each_online_node(i) {
2458 l3 = cachep->nodelists[i];
2462 drain_freelist(cachep, l3, l3->free_objects);
2464 ret += !list_empty(&l3->slabs_full) ||
2465 !list_empty(&l3->slabs_partial);
2467 return (ret ? 1 : 0);
2471 * kmem_cache_shrink - Shrink a cache.
2472 * @cachep: The cache to shrink.
2474 * Releases as many slabs as possible for a cache.
2475 * To help debugging, a zero exit status indicates all slabs were released.
2477 int kmem_cache_shrink(struct kmem_cache *cachep)
2480 BUG_ON(!cachep || in_interrupt());
2483 mutex_lock(&cache_chain_mutex);
2484 ret = __cache_shrink(cachep);
2485 mutex_unlock(&cache_chain_mutex);
2489 EXPORT_SYMBOL(kmem_cache_shrink);
2492 * kmem_cache_destroy - delete a cache
2493 * @cachep: the cache to destroy
2495 * Remove a &struct kmem_cache object from the slab cache.
2497 * It is expected this function will be called by a module when it is
2498 * unloaded. This will remove the cache completely, and avoid a duplicate
2499 * cache being allocated each time a module is loaded and unloaded, if the
2500 * module doesn't have persistent in-kernel storage across loads and unloads.
2502 * The cache must be empty before calling this function.
2504 * The caller must guarantee that noone will allocate memory from the cache
2505 * during the kmem_cache_destroy().
2507 void kmem_cache_destroy(struct kmem_cache *cachep)
2509 BUG_ON(!cachep || in_interrupt());
2511 /* Find the cache in the chain of caches. */
2513 mutex_lock(&cache_chain_mutex);
2515 * the chain is never empty, cache_cache is never destroyed
2517 list_del(&cachep->next);
2518 if (__cache_shrink(cachep)) {
2519 slab_error(cachep, "Can't free all objects");
2520 list_add(&cachep->next, &cache_chain);
2521 mutex_unlock(&cache_chain_mutex);
2526 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2529 __kmem_cache_destroy(cachep);
2530 mutex_unlock(&cache_chain_mutex);
2533 EXPORT_SYMBOL(kmem_cache_destroy);
2536 * Get the memory for a slab management obj.
2537 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2538 * always come from malloc_sizes caches. The slab descriptor cannot
2539 * come from the same cache which is getting created because,
2540 * when we are searching for an appropriate cache for these
2541 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2542 * If we are creating a malloc_sizes cache here it would not be visible to
2543 * kmem_find_general_cachep till the initialization is complete.
2544 * Hence we cannot have slabp_cache same as the original cache.
2546 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2547 int colour_off, gfp_t local_flags,
2552 if (OFF_SLAB(cachep)) {
2553 /* Slab management obj is off-slab. */
2554 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2555 local_flags, nodeid);
2557 * If the first object in the slab is leaked (it's allocated
2558 * but no one has a reference to it), we want to make sure
2559 * kmemleak does not treat the ->s_mem pointer as a reference
2560 * to the object. Otherwise we will not report the leak.
2562 kmemleak_scan_area(slabp, offsetof(struct slab, list),
2563 sizeof(struct list_head), local_flags);
2567 slabp = objp + colour_off;
2568 colour_off += cachep->slab_size;
2571 slabp->colouroff = colour_off;
2572 slabp->s_mem = objp + colour_off;
2573 slabp->nodeid = nodeid;
2578 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2580 return (kmem_bufctl_t *) (slabp + 1);
2583 static void cache_init_objs(struct kmem_cache *cachep,
2588 for (i = 0; i < cachep->num; i++) {
2589 void *objp = index_to_obj(cachep, slabp, i);
2591 /* need to poison the objs? */
2592 if (cachep->flags & SLAB_POISON)
2593 poison_obj(cachep, objp, POISON_FREE);
2594 if (cachep->flags & SLAB_STORE_USER)
2595 *dbg_userword(cachep, objp) = NULL;
2597 if (cachep->flags & SLAB_RED_ZONE) {
2598 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2599 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2602 * Constructors are not allowed to allocate memory from the same
2603 * cache which they are a constructor for. Otherwise, deadlock.
2604 * They must also be threaded.
2606 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2607 cachep->ctor(objp + obj_offset(cachep));
2609 if (cachep->flags & SLAB_RED_ZONE) {
2610 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2611 slab_error(cachep, "constructor overwrote the"
2612 " end of an object");
2613 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2614 slab_error(cachep, "constructor overwrote the"
2615 " start of an object");
2617 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2618 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2619 kernel_map_pages(virt_to_page(objp),
2620 cachep->buffer_size / PAGE_SIZE, 0);
2625 slab_bufctl(slabp)[i] = i + 1;
2627 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2630 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2632 if (CONFIG_ZONE_DMA_FLAG) {
2633 if (flags & GFP_DMA)
2634 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2636 BUG_ON(cachep->gfpflags & GFP_DMA);
2640 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2643 void *objp = index_to_obj(cachep, slabp, slabp->free);
2647 next = slab_bufctl(slabp)[slabp->free];
2649 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2650 WARN_ON(slabp->nodeid != nodeid);
2657 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2658 void *objp, int nodeid)
2660 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2663 /* Verify that the slab belongs to the intended node */
2664 WARN_ON(slabp->nodeid != nodeid);
2666 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2667 printk(KERN_ERR "slab: double free detected in cache "
2668 "'%s', objp %p\n", cachep->name, objp);
2672 slab_bufctl(slabp)[objnr] = slabp->free;
2673 slabp->free = objnr;
2678 * Map pages beginning at addr to the given cache and slab. This is required
2679 * for the slab allocator to be able to lookup the cache and slab of a
2680 * virtual address for kfree, ksize, kmem_ptr_validate, and slab debugging.
2682 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2688 page = virt_to_page(addr);
2691 if (likely(!PageCompound(page)))
2692 nr_pages <<= cache->gfporder;
2695 page_set_cache(page, cache);
2696 page_set_slab(page, slab);
2698 } while (--nr_pages);
2702 * Grow (by 1) the number of slabs within a cache. This is called by
2703 * kmem_cache_alloc() when there are no active objs left in a cache.
2705 static int cache_grow(struct kmem_cache *cachep,
2706 gfp_t flags, int nodeid, void *objp)
2711 struct kmem_list3 *l3;
2714 * Be lazy and only check for valid flags here, keeping it out of the
2715 * critical path in kmem_cache_alloc().
2717 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2718 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2720 /* Take the l3 list lock to change the colour_next on this node */
2722 l3 = cachep->nodelists[nodeid];
2723 spin_lock(&l3->list_lock);
2725 /* Get colour for the slab, and cal the next value. */
2726 offset = l3->colour_next;
2728 if (l3->colour_next >= cachep->colour)
2729 l3->colour_next = 0;
2730 spin_unlock(&l3->list_lock);
2732 offset *= cachep->colour_off;
2734 if (local_flags & __GFP_WAIT)
2738 * The test for missing atomic flag is performed here, rather than
2739 * the more obvious place, simply to reduce the critical path length
2740 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2741 * will eventually be caught here (where it matters).
2743 kmem_flagcheck(cachep, flags);
2746 * Get mem for the objs. Attempt to allocate a physical page from
2750 objp = kmem_getpages(cachep, local_flags, nodeid);
2754 /* Get slab management. */
2755 slabp = alloc_slabmgmt(cachep, objp, offset,
2756 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2760 slab_map_pages(cachep, slabp, objp);
2762 cache_init_objs(cachep, slabp);
2764 if (local_flags & __GFP_WAIT)
2765 local_irq_disable();
2767 spin_lock(&l3->list_lock);
2769 /* Make slab active. */
2770 list_add_tail(&slabp->list, &(l3->slabs_free));
2771 STATS_INC_GROWN(cachep);
2772 l3->free_objects += cachep->num;
2773 spin_unlock(&l3->list_lock);
2776 kmem_freepages(cachep, objp);
2778 if (local_flags & __GFP_WAIT)
2779 local_irq_disable();
2786 * Perform extra freeing checks:
2787 * - detect bad pointers.
2788 * - POISON/RED_ZONE checking
2790 static void kfree_debugcheck(const void *objp)
2792 if (!virt_addr_valid(objp)) {
2793 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2794 (unsigned long)objp);
2799 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2801 unsigned long long redzone1, redzone2;
2803 redzone1 = *dbg_redzone1(cache, obj);
2804 redzone2 = *dbg_redzone2(cache, obj);
2809 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2812 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2813 slab_error(cache, "double free detected");
2815 slab_error(cache, "memory outside object was overwritten");
2817 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2818 obj, redzone1, redzone2);
2821 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2828 BUG_ON(virt_to_cache(objp) != cachep);
2830 objp -= obj_offset(cachep);
2831 kfree_debugcheck(objp);
2832 page = virt_to_head_page(objp);
2834 slabp = page_get_slab(page);
2836 if (cachep->flags & SLAB_RED_ZONE) {
2837 verify_redzone_free(cachep, objp);
2838 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2839 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2841 if (cachep->flags & SLAB_STORE_USER)
2842 *dbg_userword(cachep, objp) = caller;
2844 objnr = obj_to_index(cachep, slabp, objp);
2846 BUG_ON(objnr >= cachep->num);
2847 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2849 #ifdef CONFIG_DEBUG_SLAB_LEAK
2850 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2852 if (cachep->flags & SLAB_POISON) {
2853 #ifdef CONFIG_DEBUG_PAGEALLOC
2854 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2855 store_stackinfo(cachep, objp, (unsigned long)caller);
2856 kernel_map_pages(virt_to_page(objp),
2857 cachep->buffer_size / PAGE_SIZE, 0);
2859 poison_obj(cachep, objp, POISON_FREE);
2862 poison_obj(cachep, objp, POISON_FREE);
2868 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
2873 /* Check slab's freelist to see if this obj is there. */
2874 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2876 if (entries > cachep->num || i >= cachep->num)
2879 if (entries != cachep->num - slabp->inuse) {
2881 printk(KERN_ERR "slab: Internal list corruption detected in "
2882 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2883 cachep->name, cachep->num, slabp, slabp->inuse);
2885 i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
2888 printk("\n%03x:", i);
2889 printk(" %02x", ((unsigned char *)slabp)[i]);
2896 #define kfree_debugcheck(x) do { } while(0)
2897 #define cache_free_debugcheck(x,objp,z) (objp)
2898 #define check_slabp(x,y) do { } while(0)
2901 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2904 struct kmem_list3 *l3;
2905 struct array_cache *ac;
2910 node = numa_node_id();
2911 ac = cpu_cache_get(cachep);
2912 batchcount = ac->batchcount;
2913 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2915 * If there was little recent activity on this cache, then
2916 * perform only a partial refill. Otherwise we could generate
2919 batchcount = BATCHREFILL_LIMIT;
2921 l3 = cachep->nodelists[node];
2923 BUG_ON(ac->avail > 0 || !l3);
2924 spin_lock(&l3->list_lock);
2926 /* See if we can refill from the shared array */
2927 if (l3->shared && transfer_objects(ac, l3->shared, batchcount))
2930 while (batchcount > 0) {
2931 struct list_head *entry;
2933 /* Get slab alloc is to come from. */
2934 entry = l3->slabs_partial.next;
2935 if (entry == &l3->slabs_partial) {
2936 l3->free_touched = 1;
2937 entry = l3->slabs_free.next;
2938 if (entry == &l3->slabs_free)
2942 slabp = list_entry(entry, struct slab, list);
2943 check_slabp(cachep, slabp);
2944 check_spinlock_acquired(cachep);
2947 * The slab was either on partial or free list so
2948 * there must be at least one object available for
2951 BUG_ON(slabp->inuse >= cachep->num);
2953 while (slabp->inuse < cachep->num && batchcount--) {
2954 STATS_INC_ALLOCED(cachep);
2955 STATS_INC_ACTIVE(cachep);
2956 STATS_SET_HIGH(cachep);
2958 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
2961 check_slabp(cachep, slabp);
2963 /* move slabp to correct slabp list: */
2964 list_del(&slabp->list);
2965 if (slabp->free == BUFCTL_END)
2966 list_add(&slabp->list, &l3->slabs_full);
2968 list_add(&slabp->list, &l3->slabs_partial);
2972 l3->free_objects -= ac->avail;
2974 spin_unlock(&l3->list_lock);
2976 if (unlikely(!ac->avail)) {
2978 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
2980 /* cache_grow can reenable interrupts, then ac could change. */
2981 ac = cpu_cache_get(cachep);
2982 if (!x && ac->avail == 0) /* no objects in sight? abort */
2985 if (!ac->avail) /* objects refilled by interrupt? */
2989 return ac->entry[--ac->avail];
2992 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2995 might_sleep_if(flags & __GFP_WAIT);
2997 kmem_flagcheck(cachep, flags);
3002 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3003 gfp_t flags, void *objp, void *caller)
3007 if (cachep->flags & SLAB_POISON) {
3008 #ifdef CONFIG_DEBUG_PAGEALLOC
3009 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3010 kernel_map_pages(virt_to_page(objp),
3011 cachep->buffer_size / PAGE_SIZE, 1);
3013 check_poison_obj(cachep, objp);
3015 check_poison_obj(cachep, objp);
3017 poison_obj(cachep, objp, POISON_INUSE);
3019 if (cachep->flags & SLAB_STORE_USER)
3020 *dbg_userword(cachep, objp) = caller;
3022 if (cachep->flags & SLAB_RED_ZONE) {
3023 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3024 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3025 slab_error(cachep, "double free, or memory outside"
3026 " object was overwritten");
3028 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3029 objp, *dbg_redzone1(cachep, objp),
3030 *dbg_redzone2(cachep, objp));
3032 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3033 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3035 #ifdef CONFIG_DEBUG_SLAB_LEAK
3040 slabp = page_get_slab(virt_to_head_page(objp));
3041 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
3042 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3045 objp += obj_offset(cachep);
3046 if (cachep->ctor && cachep->flags & SLAB_POISON)
3048 #if ARCH_SLAB_MINALIGN
3049 if ((u32)objp & (ARCH_SLAB_MINALIGN-1)) {
3050 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3051 objp, ARCH_SLAB_MINALIGN);
3057 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3060 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3062 if (cachep == &cache_cache)
3065 return should_failslab(obj_size(cachep), flags);
3068 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3071 struct array_cache *ac;
3075 ac = cpu_cache_get(cachep);
3076 if (likely(ac->avail)) {
3077 STATS_INC_ALLOCHIT(cachep);
3079 objp = ac->entry[--ac->avail];
3081 STATS_INC_ALLOCMISS(cachep);
3082 objp = cache_alloc_refill(cachep, flags);
3085 * To avoid a false negative, if an object that is in one of the
3086 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3087 * treat the array pointers as a reference to the object.
3089 kmemleak_erase(&ac->entry[ac->avail]);
3095 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3097 * If we are in_interrupt, then process context, including cpusets and
3098 * mempolicy, may not apply and should not be used for allocation policy.
3100 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3102 int nid_alloc, nid_here;
3104 if (in_interrupt() || (flags & __GFP_THISNODE))
3106 nid_alloc = nid_here = numa_node_id();
3107 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3108 nid_alloc = cpuset_mem_spread_node();
3109 else if (current->mempolicy)
3110 nid_alloc = slab_node(current->mempolicy);
3111 if (nid_alloc != nid_here)
3112 return ____cache_alloc_node(cachep, flags, nid_alloc);
3117 * Fallback function if there was no memory available and no objects on a
3118 * certain node and fall back is permitted. First we scan all the
3119 * available nodelists for available objects. If that fails then we
3120 * perform an allocation without specifying a node. This allows the page
3121 * allocator to do its reclaim / fallback magic. We then insert the
3122 * slab into the proper nodelist and then allocate from it.
3124 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3126 struct zonelist *zonelist;
3130 enum zone_type high_zoneidx = gfp_zone(flags);
3134 if (flags & __GFP_THISNODE)
3137 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
3138 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3142 * Look through allowed nodes for objects available
3143 * from existing per node queues.
3145 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3146 nid = zone_to_nid(zone);
3148 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3149 cache->nodelists[nid] &&
3150 cache->nodelists[nid]->free_objects) {
3151 obj = ____cache_alloc_node(cache,
3152 flags | GFP_THISNODE, nid);
3160 * This allocation will be performed within the constraints
3161 * of the current cpuset / memory policy requirements.
3162 * We may trigger various forms of reclaim on the allowed
3163 * set and go into memory reserves if necessary.
3165 if (local_flags & __GFP_WAIT)
3167 kmem_flagcheck(cache, flags);
3168 obj = kmem_getpages(cache, local_flags, -1);
3169 if (local_flags & __GFP_WAIT)
3170 local_irq_disable();
3173 * Insert into the appropriate per node queues
3175 nid = page_to_nid(virt_to_page(obj));
3176 if (cache_grow(cache, flags, nid, obj)) {
3177 obj = ____cache_alloc_node(cache,
3178 flags | GFP_THISNODE, nid);
3181 * Another processor may allocate the
3182 * objects in the slab since we are
3183 * not holding any locks.
3187 /* cache_grow already freed obj */
3196 * A interface to enable slab creation on nodeid
3198 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3201 struct list_head *entry;
3203 struct kmem_list3 *l3;
3207 l3 = cachep->nodelists[nodeid];
3212 spin_lock(&l3->list_lock);
3213 entry = l3->slabs_partial.next;
3214 if (entry == &l3->slabs_partial) {
3215 l3->free_touched = 1;
3216 entry = l3->slabs_free.next;
3217 if (entry == &l3->slabs_free)
3221 slabp = list_entry(entry, struct slab, list);
3222 check_spinlock_acquired_node(cachep, nodeid);
3223 check_slabp(cachep, slabp);
3225 STATS_INC_NODEALLOCS(cachep);
3226 STATS_INC_ACTIVE(cachep);
3227 STATS_SET_HIGH(cachep);
3229 BUG_ON(slabp->inuse == cachep->num);
3231 obj = slab_get_obj(cachep, slabp, nodeid);
3232 check_slabp(cachep, slabp);
3234 /* move slabp to correct slabp list: */
3235 list_del(&slabp->list);
3237 if (slabp->free == BUFCTL_END)
3238 list_add(&slabp->list, &l3->slabs_full);
3240 list_add(&slabp->list, &l3->slabs_partial);
3242 spin_unlock(&l3->list_lock);
3246 spin_unlock(&l3->list_lock);
3247 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3251 return fallback_alloc(cachep, flags);
3258 * kmem_cache_alloc_node - Allocate an object on the specified node
3259 * @cachep: The cache to allocate from.
3260 * @flags: See kmalloc().
3261 * @nodeid: node number of the target node.
3262 * @caller: return address of caller, used for debug information
3264 * Identical to kmem_cache_alloc but it will allocate memory on the given
3265 * node, which can improve the performance for cpu bound structures.
3267 * Fallback to other node is possible if __GFP_THISNODE is not set.
3269 static __always_inline void *
3270 __cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3273 unsigned long save_flags;
3276 lockdep_trace_alloc(flags);
3278 if (slab_should_failslab(cachep, flags))
3281 cache_alloc_debugcheck_before(cachep, flags);
3282 local_irq_save(save_flags);
3284 if (unlikely(nodeid == -1))
3285 nodeid = numa_node_id();
3287 if (unlikely(!cachep->nodelists[nodeid])) {
3288 /* Node not bootstrapped yet */
3289 ptr = fallback_alloc(cachep, flags);
3293 if (nodeid == numa_node_id()) {
3295 * Use the locally cached objects if possible.
3296 * However ____cache_alloc does not allow fallback
3297 * to other nodes. It may fail while we still have
3298 * objects on other nodes available.
3300 ptr = ____cache_alloc(cachep, flags);
3304 /* ___cache_alloc_node can fall back to other nodes */
3305 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3307 local_irq_restore(save_flags);
3308 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3309 kmemleak_alloc_recursive(ptr, obj_size(cachep), 1, cachep->flags,
3312 if (unlikely((flags & __GFP_ZERO) && ptr))
3313 memset(ptr, 0, obj_size(cachep));
3318 static __always_inline void *
3319 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3323 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3324 objp = alternate_node_alloc(cache, flags);
3328 objp = ____cache_alloc(cache, flags);
3331 * We may just have run out of memory on the local node.
3332 * ____cache_alloc_node() knows how to locate memory on other nodes
3335 objp = ____cache_alloc_node(cache, flags, numa_node_id());
3342 static __always_inline void *
3343 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3345 return ____cache_alloc(cachep, flags);
3348 #endif /* CONFIG_NUMA */
3350 static __always_inline void *
3351 __cache_alloc(struct kmem_cache *cachep, gfp_t flags, void *caller)
3353 unsigned long save_flags;
3356 lockdep_trace_alloc(flags);
3358 if (slab_should_failslab(cachep, flags))
3361 cache_alloc_debugcheck_before(cachep, flags);
3362 local_irq_save(save_flags);
3363 objp = __do_cache_alloc(cachep, flags);
3364 local_irq_restore(save_flags);
3365 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3366 kmemleak_alloc_recursive(objp, obj_size(cachep), 1, cachep->flags,
3370 if (unlikely((flags & __GFP_ZERO) && objp))
3371 memset(objp, 0, obj_size(cachep));
3377 * Caller needs to acquire correct kmem_list's list_lock
3379 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3383 struct kmem_list3 *l3;
3385 for (i = 0; i < nr_objects; i++) {
3386 void *objp = objpp[i];
3389 slabp = virt_to_slab(objp);
3390 l3 = cachep->nodelists[node];
3391 list_del(&slabp->list);
3392 check_spinlock_acquired_node(cachep, node);
3393 check_slabp(cachep, slabp);
3394 slab_put_obj(cachep, slabp, objp, node);
3395 STATS_DEC_ACTIVE(cachep);
3397 check_slabp(cachep, slabp);
3399 /* fixup slab chains */
3400 if (slabp->inuse == 0) {
3401 if (l3->free_objects > l3->free_limit) {
3402 l3->free_objects -= cachep->num;
3403 /* No need to drop any previously held
3404 * lock here, even if we have a off-slab slab
3405 * descriptor it is guaranteed to come from
3406 * a different cache, refer to comments before
3409 slab_destroy(cachep, slabp);
3411 list_add(&slabp->list, &l3->slabs_free);
3414 /* Unconditionally move a slab to the end of the
3415 * partial list on free - maximum time for the
3416 * other objects to be freed, too.
3418 list_add_tail(&slabp->list, &l3->slabs_partial);
3423 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3426 struct kmem_list3 *l3;
3427 int node = numa_node_id();
3429 batchcount = ac->batchcount;
3431 BUG_ON(!batchcount || batchcount > ac->avail);
3434 l3 = cachep->nodelists[node];
3435 spin_lock(&l3->list_lock);
3437 struct array_cache *shared_array = l3->shared;
3438 int max = shared_array->limit - shared_array->avail;
3440 if (batchcount > max)
3442 memcpy(&(shared_array->entry[shared_array->avail]),
3443 ac->entry, sizeof(void *) * batchcount);
3444 shared_array->avail += batchcount;
3449 free_block(cachep, ac->entry, batchcount, node);
3454 struct list_head *p;
3456 p = l3->slabs_free.next;
3457 while (p != &(l3->slabs_free)) {
3460 slabp = list_entry(p, struct slab, list);
3461 BUG_ON(slabp->inuse);
3466 STATS_SET_FREEABLE(cachep, i);
3469 spin_unlock(&l3->list_lock);
3470 ac->avail -= batchcount;
3471 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3475 * Release an obj back to its cache. If the obj has a constructed state, it must
3476 * be in this state _before_ it is released. Called with disabled ints.
3478 static inline void __cache_free(struct kmem_cache *cachep, void *objp)
3480 struct array_cache *ac = cpu_cache_get(cachep);
3483 kmemleak_free_recursive(objp, cachep->flags);
3484 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3487 * Skip calling cache_free_alien() when the platform is not numa.
3488 * This will avoid cache misses that happen while accessing slabp (which
3489 * is per page memory reference) to get nodeid. Instead use a global
3490 * variable to skip the call, which is mostly likely to be present in
3493 if (numa_platform && cache_free_alien(cachep, objp))
3496 if (likely(ac->avail < ac->limit)) {
3497 STATS_INC_FREEHIT(cachep);
3498 ac->entry[ac->avail++] = objp;
3501 STATS_INC_FREEMISS(cachep);
3502 cache_flusharray(cachep, ac);
3503 ac->entry[ac->avail++] = objp;
3508 * kmem_cache_alloc - Allocate an object
3509 * @cachep: The cache to allocate from.
3510 * @flags: See kmalloc().
3512 * Allocate an object from this cache. The flags are only relevant
3513 * if the cache has no available objects.
3515 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3517 void *ret = __cache_alloc(cachep, flags, __builtin_return_address(0));
3519 trace_kmem_cache_alloc(_RET_IP_, ret,
3520 obj_size(cachep), cachep->buffer_size, flags);
3524 EXPORT_SYMBOL(kmem_cache_alloc);
3526 #ifdef CONFIG_KMEMTRACE
3527 void *kmem_cache_alloc_notrace(struct kmem_cache *cachep, gfp_t flags)
3529 return __cache_alloc(cachep, flags, __builtin_return_address(0));
3531 EXPORT_SYMBOL(kmem_cache_alloc_notrace);
3535 * kmem_ptr_validate - check if an untrusted pointer might be a slab entry.
3536 * @cachep: the cache we're checking against
3537 * @ptr: pointer to validate
3539 * This verifies that the untrusted pointer looks sane;
3540 * it is _not_ a guarantee that the pointer is actually
3541 * part of the slab cache in question, but it at least
3542 * validates that the pointer can be dereferenced and
3543 * looks half-way sane.
3545 * Currently only used for dentry validation.
3547 int kmem_ptr_validate(struct kmem_cache *cachep, const void *ptr)
3549 unsigned long addr = (unsigned long)ptr;
3550 unsigned long min_addr = PAGE_OFFSET;
3551 unsigned long align_mask = BYTES_PER_WORD - 1;
3552 unsigned long size = cachep->buffer_size;
3555 if (unlikely(addr < min_addr))
3557 if (unlikely(addr > (unsigned long)high_memory - size))
3559 if (unlikely(addr & align_mask))
3561 if (unlikely(!kern_addr_valid(addr)))
3563 if (unlikely(!kern_addr_valid(addr + size - 1)))
3565 page = virt_to_page(ptr);
3566 if (unlikely(!PageSlab(page)))
3568 if (unlikely(page_get_cache(page) != cachep))
3576 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3578 void *ret = __cache_alloc_node(cachep, flags, nodeid,
3579 __builtin_return_address(0));
3581 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3582 obj_size(cachep), cachep->buffer_size,
3587 EXPORT_SYMBOL(kmem_cache_alloc_node);
3589 #ifdef CONFIG_KMEMTRACE
3590 void *kmem_cache_alloc_node_notrace(struct kmem_cache *cachep,
3594 return __cache_alloc_node(cachep, flags, nodeid,
3595 __builtin_return_address(0));
3597 EXPORT_SYMBOL(kmem_cache_alloc_node_notrace);
3600 static __always_inline void *
3601 __do_kmalloc_node(size_t size, gfp_t flags, int node, void *caller)
3603 struct kmem_cache *cachep;
3606 cachep = kmem_find_general_cachep(size, flags);
3607 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3609 ret = kmem_cache_alloc_node_notrace(cachep, flags, node);
3611 trace_kmalloc_node((unsigned long) caller, ret,
3612 size, cachep->buffer_size, flags, node);
3617 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_KMEMTRACE)
3618 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3620 return __do_kmalloc_node(size, flags, node,
3621 __builtin_return_address(0));
3623 EXPORT_SYMBOL(__kmalloc_node);
3625 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3626 int node, unsigned long caller)
3628 return __do_kmalloc_node(size, flags, node, (void *)caller);
3630 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3632 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3634 return __do_kmalloc_node(size, flags, node, NULL);
3636 EXPORT_SYMBOL(__kmalloc_node);
3637 #endif /* CONFIG_DEBUG_SLAB */
3638 #endif /* CONFIG_NUMA */
3641 * __do_kmalloc - allocate memory
3642 * @size: how many bytes of memory are required.
3643 * @flags: the type of memory to allocate (see kmalloc).
3644 * @caller: function caller for debug tracking of the caller
3646 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3649 struct kmem_cache *cachep;
3652 /* If you want to save a few bytes .text space: replace
3654 * Then kmalloc uses the uninlined functions instead of the inline
3657 cachep = __find_general_cachep(size, flags);
3658 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3660 ret = __cache_alloc(cachep, flags, caller);
3662 trace_kmalloc((unsigned long) caller, ret,
3663 size, cachep->buffer_size, flags);
3669 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_KMEMTRACE)
3670 void *__kmalloc(size_t size, gfp_t flags)
3672 return __do_kmalloc(size, flags, __builtin_return_address(0));
3674 EXPORT_SYMBOL(__kmalloc);
3676 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3678 return __do_kmalloc(size, flags, (void *)caller);
3680 EXPORT_SYMBOL(__kmalloc_track_caller);
3683 void *__kmalloc(size_t size, gfp_t flags)
3685 return __do_kmalloc(size, flags, NULL);
3687 EXPORT_SYMBOL(__kmalloc);
3691 * kmem_cache_free - Deallocate an object
3692 * @cachep: The cache the allocation was from.
3693 * @objp: The previously allocated object.
3695 * Free an object which was previously allocated from this
3698 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3700 unsigned long flags;
3702 local_irq_save(flags);
3703 debug_check_no_locks_freed(objp, obj_size(cachep));
3704 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3705 debug_check_no_obj_freed(objp, obj_size(cachep));
3706 __cache_free(cachep, objp);
3707 local_irq_restore(flags);
3709 trace_kmem_cache_free(_RET_IP_, objp);
3711 EXPORT_SYMBOL(kmem_cache_free);
3714 * kfree - free previously allocated memory
3715 * @objp: pointer returned by kmalloc.
3717 * If @objp is NULL, no operation is performed.
3719 * Don't free memory not originally allocated by kmalloc()
3720 * or you will run into trouble.
3722 void kfree(const void *objp)
3724 struct kmem_cache *c;
3725 unsigned long flags;
3727 trace_kfree(_RET_IP_, objp);
3729 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3731 local_irq_save(flags);
3732 kfree_debugcheck(objp);
3733 c = virt_to_cache(objp);
3734 debug_check_no_locks_freed(objp, obj_size(c));
3735 debug_check_no_obj_freed(objp, obj_size(c));
3736 __cache_free(c, (void *)objp);
3737 local_irq_restore(flags);
3739 EXPORT_SYMBOL(kfree);
3741 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3743 return obj_size(cachep);
3745 EXPORT_SYMBOL(kmem_cache_size);
3747 const char *kmem_cache_name(struct kmem_cache *cachep)
3749 return cachep->name;
3751 EXPORT_SYMBOL_GPL(kmem_cache_name);
3754 * This initializes kmem_list3 or resizes various caches for all nodes.
3756 static int alloc_kmemlist(struct kmem_cache *cachep, gfp_t gfp)
3759 struct kmem_list3 *l3;
3760 struct array_cache *new_shared;
3761 struct array_cache **new_alien = NULL;
3763 for_each_online_node(node) {
3765 if (use_alien_caches) {
3766 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3772 if (cachep->shared) {
3773 new_shared = alloc_arraycache(node,
3774 cachep->shared*cachep->batchcount,
3777 free_alien_cache(new_alien);
3782 l3 = cachep->nodelists[node];
3784 struct array_cache *shared = l3->shared;
3786 spin_lock_irq(&l3->list_lock);
3789 free_block(cachep, shared->entry,
3790 shared->avail, node);
3792 l3->shared = new_shared;
3794 l3->alien = new_alien;
3797 l3->free_limit = (1 + nr_cpus_node(node)) *
3798 cachep->batchcount + cachep->num;
3799 spin_unlock_irq(&l3->list_lock);
3801 free_alien_cache(new_alien);
3804 l3 = kmalloc_node(sizeof(struct kmem_list3), gfp, node);
3806 free_alien_cache(new_alien);
3811 kmem_list3_init(l3);
3812 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3813 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3814 l3->shared = new_shared;
3815 l3->alien = new_alien;
3816 l3->free_limit = (1 + nr_cpus_node(node)) *
3817 cachep->batchcount + cachep->num;
3818 cachep->nodelists[node] = l3;
3823 if (!cachep->next.next) {
3824 /* Cache is not active yet. Roll back what we did */
3827 if (cachep->nodelists[node]) {
3828 l3 = cachep->nodelists[node];
3831 free_alien_cache(l3->alien);
3833 cachep->nodelists[node] = NULL;
3841 struct ccupdate_struct {
3842 struct kmem_cache *cachep;
3843 struct array_cache *new[NR_CPUS];
3846 static void do_ccupdate_local(void *info)
3848 struct ccupdate_struct *new = info;
3849 struct array_cache *old;
3852 old = cpu_cache_get(new->cachep);
3854 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3855 new->new[smp_processor_id()] = old;
3858 /* Always called with the cache_chain_mutex held */
3859 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3860 int batchcount, int shared, gfp_t gfp)
3862 struct ccupdate_struct *new;
3865 new = kzalloc(sizeof(*new), gfp);
3869 for_each_online_cpu(i) {
3870 new->new[i] = alloc_arraycache(cpu_to_node(i), limit,
3873 for (i--; i >= 0; i--)
3879 new->cachep = cachep;
3881 on_each_cpu(do_ccupdate_local, (void *)new, 1);
3884 cachep->batchcount = batchcount;
3885 cachep->limit = limit;
3886 cachep->shared = shared;
3888 for_each_online_cpu(i) {
3889 struct array_cache *ccold = new->new[i];
3892 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3893 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
3894 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3898 return alloc_kmemlist(cachep, gfp);
3901 /* Called with cache_chain_mutex held always */
3902 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3908 * The head array serves three purposes:
3909 * - create a LIFO ordering, i.e. return objects that are cache-warm
3910 * - reduce the number of spinlock operations.
3911 * - reduce the number of linked list operations on the slab and
3912 * bufctl chains: array operations are cheaper.
3913 * The numbers are guessed, we should auto-tune as described by
3916 if (cachep->buffer_size > 131072)
3918 else if (cachep->buffer_size > PAGE_SIZE)
3920 else if (cachep->buffer_size > 1024)
3922 else if (cachep->buffer_size > 256)
3928 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3929 * allocation behaviour: Most allocs on one cpu, most free operations
3930 * on another cpu. For these cases, an efficient object passing between
3931 * cpus is necessary. This is provided by a shared array. The array
3932 * replaces Bonwick's magazine layer.
3933 * On uniprocessor, it's functionally equivalent (but less efficient)
3934 * to a larger limit. Thus disabled by default.
3937 if (cachep->buffer_size <= PAGE_SIZE && num_possible_cpus() > 1)
3942 * With debugging enabled, large batchcount lead to excessively long
3943 * periods with disabled local interrupts. Limit the batchcount
3948 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared, gfp);
3950 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3951 cachep->name, -err);
3956 * Drain an array if it contains any elements taking the l3 lock only if
3957 * necessary. Note that the l3 listlock also protects the array_cache
3958 * if drain_array() is used on the shared array.
3960 void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
3961 struct array_cache *ac, int force, int node)
3965 if (!ac || !ac->avail)
3967 if (ac->touched && !force) {
3970 spin_lock_irq(&l3->list_lock);
3972 tofree = force ? ac->avail : (ac->limit + 4) / 5;
3973 if (tofree > ac->avail)
3974 tofree = (ac->avail + 1) / 2;
3975 free_block(cachep, ac->entry, tofree, node);
3976 ac->avail -= tofree;
3977 memmove(ac->entry, &(ac->entry[tofree]),
3978 sizeof(void *) * ac->avail);
3980 spin_unlock_irq(&l3->list_lock);
3985 * cache_reap - Reclaim memory from caches.
3986 * @w: work descriptor
3988 * Called from workqueue/eventd every few seconds.
3990 * - clear the per-cpu caches for this CPU.
3991 * - return freeable pages to the main free memory pool.
3993 * If we cannot acquire the cache chain mutex then just give up - we'll try
3994 * again on the next iteration.
3996 static void cache_reap(struct work_struct *w)
3998 struct kmem_cache *searchp;
3999 struct kmem_list3 *l3;
4000 int node = numa_node_id();
4001 struct delayed_work *work = to_delayed_work(w);
4003 if (!mutex_trylock(&cache_chain_mutex))
4004 /* Give up. Setup the next iteration. */
4007 list_for_each_entry(searchp, &cache_chain, next) {
4011 * We only take the l3 lock if absolutely necessary and we
4012 * have established with reasonable certainty that
4013 * we can do some work if the lock was obtained.
4015 l3 = searchp->nodelists[node];
4017 reap_alien(searchp, l3);
4019 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4022 * These are racy checks but it does not matter
4023 * if we skip one check or scan twice.
4025 if (time_after(l3->next_reap, jiffies))
4028 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4030 drain_array(searchp, l3, l3->shared, 0, node);
4032 if (l3->free_touched)
4033 l3->free_touched = 0;
4037 freed = drain_freelist(searchp, l3, (l3->free_limit +
4038 5 * searchp->num - 1) / (5 * searchp->num));
4039 STATS_ADD_REAPED(searchp, freed);
4045 mutex_unlock(&cache_chain_mutex);
4048 /* Set up the next iteration */
4049 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4052 #ifdef CONFIG_SLABINFO
4054 static void print_slabinfo_header(struct seq_file *m)
4057 * Output format version, so at least we can change it
4058 * without _too_ many complaints.
4061 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
4063 seq_puts(m, "slabinfo - version: 2.1\n");
4065 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4066 "<objperslab> <pagesperslab>");
4067 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4068 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4070 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
4071 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
4072 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
4077 static void *s_start(struct seq_file *m, loff_t *pos)
4081 mutex_lock(&cache_chain_mutex);
4083 print_slabinfo_header(m);
4085 return seq_list_start(&cache_chain, *pos);
4088 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4090 return seq_list_next(p, &cache_chain, pos);
4093 static void s_stop(struct seq_file *m, void *p)
4095 mutex_unlock(&cache_chain_mutex);
4098 static int s_show(struct seq_file *m, void *p)
4100 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4102 unsigned long active_objs;
4103 unsigned long num_objs;
4104 unsigned long active_slabs = 0;
4105 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4109 struct kmem_list3 *l3;
4113 for_each_online_node(node) {
4114 l3 = cachep->nodelists[node];
4119 spin_lock_irq(&l3->list_lock);
4121 list_for_each_entry(slabp, &l3->slabs_full, list) {
4122 if (slabp->inuse != cachep->num && !error)
4123 error = "slabs_full accounting error";
4124 active_objs += cachep->num;
4127 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4128 if (slabp->inuse == cachep->num && !error)
4129 error = "slabs_partial inuse accounting error";
4130 if (!slabp->inuse && !error)
4131 error = "slabs_partial/inuse accounting error";
4132 active_objs += slabp->inuse;
4135 list_for_each_entry(slabp, &l3->slabs_free, list) {
4136 if (slabp->inuse && !error)
4137 error = "slabs_free/inuse accounting error";
4140 free_objects += l3->free_objects;
4142 shared_avail += l3->shared->avail;
4144 spin_unlock_irq(&l3->list_lock);
4146 num_slabs += active_slabs;
4147 num_objs = num_slabs * cachep->num;
4148 if (num_objs - active_objs != free_objects && !error)
4149 error = "free_objects accounting error";
4151 name = cachep->name;
4153 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4155 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
4156 name, active_objs, num_objs, cachep->buffer_size,
4157 cachep->num, (1 << cachep->gfporder));
4158 seq_printf(m, " : tunables %4u %4u %4u",
4159 cachep->limit, cachep->batchcount, cachep->shared);
4160 seq_printf(m, " : slabdata %6lu %6lu %6lu",
4161 active_slabs, num_slabs, shared_avail);
4164 unsigned long high = cachep->high_mark;
4165 unsigned long allocs = cachep->num_allocations;
4166 unsigned long grown = cachep->grown;
4167 unsigned long reaped = cachep->reaped;
4168 unsigned long errors = cachep->errors;
4169 unsigned long max_freeable = cachep->max_freeable;
4170 unsigned long node_allocs = cachep->node_allocs;
4171 unsigned long node_frees = cachep->node_frees;
4172 unsigned long overflows = cachep->node_overflow;
4174 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
4175 %4lu %4lu %4lu %4lu %4lu", allocs, high, grown,
4176 reaped, errors, max_freeable, node_allocs,
4177 node_frees, overflows);
4181 unsigned long allochit = atomic_read(&cachep->allochit);
4182 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4183 unsigned long freehit = atomic_read(&cachep->freehit);
4184 unsigned long freemiss = atomic_read(&cachep->freemiss);
4186 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4187 allochit, allocmiss, freehit, freemiss);
4195 * slabinfo_op - iterator that generates /proc/slabinfo
4204 * num-pages-per-slab
4205 * + further values on SMP and with statistics enabled
4208 static const struct seq_operations slabinfo_op = {
4215 #define MAX_SLABINFO_WRITE 128
4217 * slabinfo_write - Tuning for the slab allocator
4219 * @buffer: user buffer
4220 * @count: data length
4223 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4224 size_t count, loff_t *ppos)
4226 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4227 int limit, batchcount, shared, res;
4228 struct kmem_cache *cachep;
4230 if (count > MAX_SLABINFO_WRITE)
4232 if (copy_from_user(&kbuf, buffer, count))
4234 kbuf[MAX_SLABINFO_WRITE] = '\0';
4236 tmp = strchr(kbuf, ' ');
4241 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4244 /* Find the cache in the chain of caches. */
4245 mutex_lock(&cache_chain_mutex);
4247 list_for_each_entry(cachep, &cache_chain, next) {
4248 if (!strcmp(cachep->name, kbuf)) {
4249 if (limit < 1 || batchcount < 1 ||
4250 batchcount > limit || shared < 0) {
4253 res = do_tune_cpucache(cachep, limit,
4260 mutex_unlock(&cache_chain_mutex);
4266 static int slabinfo_open(struct inode *inode, struct file *file)
4268 return seq_open(file, &slabinfo_op);
4271 static const struct file_operations proc_slabinfo_operations = {
4272 .open = slabinfo_open,
4274 .write = slabinfo_write,
4275 .llseek = seq_lseek,
4276 .release = seq_release,
4279 #ifdef CONFIG_DEBUG_SLAB_LEAK
4281 static void *leaks_start(struct seq_file *m, loff_t *pos)
4283 mutex_lock(&cache_chain_mutex);
4284 return seq_list_start(&cache_chain, *pos);
4287 static inline int add_caller(unsigned long *n, unsigned long v)
4297 unsigned long *q = p + 2 * i;
4311 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4317 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4323 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4324 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4326 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4331 static void show_symbol(struct seq_file *m, unsigned long address)
4333 #ifdef CONFIG_KALLSYMS
4334 unsigned long offset, size;
4335 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4337 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4338 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4340 seq_printf(m, " [%s]", modname);
4344 seq_printf(m, "%p", (void *)address);
4347 static int leaks_show(struct seq_file *m, void *p)
4349 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4351 struct kmem_list3 *l3;
4353 unsigned long *n = m->private;
4357 if (!(cachep->flags & SLAB_STORE_USER))
4359 if (!(cachep->flags & SLAB_RED_ZONE))
4362 /* OK, we can do it */
4366 for_each_online_node(node) {
4367 l3 = cachep->nodelists[node];
4372 spin_lock_irq(&l3->list_lock);
4374 list_for_each_entry(slabp, &l3->slabs_full, list)
4375 handle_slab(n, cachep, slabp);
4376 list_for_each_entry(slabp, &l3->slabs_partial, list)
4377 handle_slab(n, cachep, slabp);
4378 spin_unlock_irq(&l3->list_lock);
4380 name = cachep->name;
4382 /* Increase the buffer size */
4383 mutex_unlock(&cache_chain_mutex);
4384 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4386 /* Too bad, we are really out */
4388 mutex_lock(&cache_chain_mutex);
4391 *(unsigned long *)m->private = n[0] * 2;
4393 mutex_lock(&cache_chain_mutex);
4394 /* Now make sure this entry will be retried */
4398 for (i = 0; i < n[1]; i++) {
4399 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4400 show_symbol(m, n[2*i+2]);
4407 static const struct seq_operations slabstats_op = {
4408 .start = leaks_start,
4414 static int slabstats_open(struct inode *inode, struct file *file)
4416 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4419 ret = seq_open(file, &slabstats_op);
4421 struct seq_file *m = file->private_data;
4422 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4431 static const struct file_operations proc_slabstats_operations = {
4432 .open = slabstats_open,
4434 .llseek = seq_lseek,
4435 .release = seq_release_private,
4439 static int __init slab_proc_init(void)
4441 proc_create("slabinfo",S_IWUSR|S_IRUGO,NULL,&proc_slabinfo_operations);
4442 #ifdef CONFIG_DEBUG_SLAB_LEAK
4443 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4447 module_init(slab_proc_init);
4451 * ksize - get the actual amount of memory allocated for a given object
4452 * @objp: Pointer to the object
4454 * kmalloc may internally round up allocations and return more memory
4455 * than requested. ksize() can be used to determine the actual amount of
4456 * memory allocated. The caller may use this additional memory, even though
4457 * a smaller amount of memory was initially specified with the kmalloc call.
4458 * The caller must guarantee that objp points to a valid object previously
4459 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4460 * must not be freed during the duration of the call.
4462 size_t ksize(const void *objp)
4465 if (unlikely(objp == ZERO_SIZE_PTR))
4468 return obj_size(virt_to_cache(objp));
4470 EXPORT_SYMBOL(ksize);