kmemtrace: SLOB hooks.
[linux-2.6/kmemtrace.git] / mm / slab.c
blob149696275644f34da88dceaa5044ead9afe1b6dc
1 /*
2 * linux/mm/slab.c
3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
14 * An implementation of the Slab Allocator as described in outline in;
15 * UNIX Internals: The New Frontiers by Uresh Vahalia
16 * Pub: Prentice Hall ISBN 0-13-101908-2
17 * or with a little more detail in;
18 * The Slab Allocator: An Object-Caching Kernel Memory Allocator
19 * Jeff Bonwick (Sun Microsystems).
20 * Presented at: USENIX Summer 1994 Technical Conference
22 * The memory is organized in caches, one cache for each object type.
23 * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24 * Each cache consists out of many slabs (they are small (usually one
25 * page long) and always contiguous), and each slab contains multiple
26 * initialized objects.
28 * This means, that your constructor is used only for newly allocated
29 * slabs and you must pass objects with the same initializations to
30 * kmem_cache_free.
32 * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33 * normal). If you need a special memory type, then must create a new
34 * cache for that memory type.
36 * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37 * full slabs with 0 free objects
38 * partial slabs
39 * empty slabs with no allocated objects
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
44 * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45 * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
47 * Each cache has a short per-cpu head array, most allocs
48 * and frees go into that array, and if that array overflows, then 1/2
49 * of the entries in the array are given back into the global cache.
50 * The head array is strictly LIFO and should improve the cache hit rates.
51 * On SMP, it additionally reduces the spinlock operations.
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
56 * SMP synchronization:
57 * constructors and destructors are called without any locking.
58 * Several members in 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
66 * his patch.
68 * Further notes from the original documentation:
70 * 11 April '97. Started multi-threading - markhe
71 * The global cache-chain is protected by the 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>
90 #include <linux/mm.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/seq_file.h>
99 #include <linux/notifier.h>
100 #include <linux/kallsyms.h>
101 #include <linux/cpu.h>
102 #include <linux/sysctl.h>
103 #include <linux/module.h>
104 #include <linux/rcupdate.h>
105 #include <linux/string.h>
106 #include <linux/uaccess.h>
107 #include <linux/nodemask.h>
108 #include <linux/mempolicy.h>
109 #include <linux/mutex.h>
110 #include <linux/fault-inject.h>
111 #include <linux/rtmutex.h>
112 #include <linux/reciprocal_div.h>
113 #include <linux/debugobjects.h>
114 #include <linux/kmemtrace.h>
116 #include <asm/cacheflush.h>
117 #include <asm/tlbflush.h>
118 #include <asm/page.h>
121 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
122 * 0 for faster, smaller code (especially in the critical paths).
124 * STATS - 1 to collect stats for /proc/slabinfo.
125 * 0 for faster, smaller code (especially in the critical paths).
127 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
130 #ifdef CONFIG_DEBUG_SLAB
131 #define DEBUG 1
132 #define STATS 1
133 #define FORCED_DEBUG 1
134 #else
135 #define DEBUG 0
136 #define STATS 0
137 #define FORCED_DEBUG 0
138 #endif
140 /* Shouldn't this be in a header file somewhere? */
141 #define BYTES_PER_WORD sizeof(void *)
142 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
144 #ifndef ARCH_KMALLOC_MINALIGN
146 * Enforce a minimum alignment for the kmalloc caches.
147 * Usually, the kmalloc caches are cache_line_size() aligned, except when
148 * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
149 * Some archs want to perform DMA into kmalloc caches and need a guaranteed
150 * alignment larger than the alignment of a 64-bit integer.
151 * ARCH_KMALLOC_MINALIGN allows that.
152 * Note that increasing this value may disable some debug features.
154 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
155 #endif
157 #ifndef ARCH_SLAB_MINALIGN
159 * Enforce a minimum alignment for all caches.
160 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
161 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
162 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
163 * some debug features.
165 #define ARCH_SLAB_MINALIGN 0
166 #endif
168 #ifndef ARCH_KMALLOC_FLAGS
169 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
170 #endif
172 /* Legal flag mask for kmem_cache_create(). */
173 #if DEBUG
174 # define CREATE_MASK (SLAB_RED_ZONE | \
175 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
176 SLAB_CACHE_DMA | \
177 SLAB_STORE_USER | \
178 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
179 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
180 SLAB_DEBUG_OBJECTS)
181 #else
182 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
183 SLAB_CACHE_DMA | \
184 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
185 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD | \
186 SLAB_DEBUG_OBJECTS)
187 #endif
190 * kmem_bufctl_t:
192 * Bufctl's are used for linking objs within a slab
193 * linked offsets.
195 * This implementation relies on "struct page" for locating the cache &
196 * slab an object belongs to.
197 * This allows the bufctl structure to be small (one int), but limits
198 * the number of objects a slab (not a cache) can contain when off-slab
199 * bufctls are used. The limit is the size of the largest general cache
200 * that does not use off-slab slabs.
201 * For 32bit archs with 4 kB pages, is this 56.
202 * This is not serious, as it is only for large objects, when it is unwise
203 * to have too many per slab.
204 * Note: This limit can be raised by introducing a general cache whose size
205 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
208 typedef unsigned int kmem_bufctl_t;
209 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
210 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
211 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
212 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
215 * struct slab
217 * Manages the objs in a slab. Placed either at the beginning of mem allocated
218 * for a slab, or allocated from an general cache.
219 * Slabs are chained into three list: fully used, partial, fully free slabs.
221 struct slab {
222 struct list_head list;
223 unsigned long colouroff;
224 void *s_mem; /* including colour offset */
225 unsigned int inuse; /* num of objs active in slab */
226 kmem_bufctl_t free;
227 unsigned short nodeid;
231 * struct slab_rcu
233 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
234 * arrange for kmem_freepages to be called via RCU. This is useful if
235 * we need to approach a kernel structure obliquely, from its address
236 * obtained without the usual locking. We can lock the structure to
237 * stabilize it and check it's still at the given address, only if we
238 * can be sure that the memory has not been meanwhile reused for some
239 * other kind of object (which our subsystem's lock might corrupt).
241 * rcu_read_lock before reading the address, then rcu_read_unlock after
242 * taking the spinlock within the structure expected at that address.
244 * We assume struct slab_rcu can overlay struct slab when destroying.
246 struct slab_rcu {
247 struct rcu_head head;
248 struct kmem_cache *cachep;
249 void *addr;
253 * struct array_cache
255 * Purpose:
256 * - LIFO ordering, to hand out cache-warm objects from _alloc
257 * - reduce the number of linked list operations
258 * - reduce spinlock operations
260 * The limit is stored in the per-cpu structure to reduce the data cache
261 * footprint.
264 struct array_cache {
265 unsigned int avail;
266 unsigned int limit;
267 unsigned int batchcount;
268 unsigned int touched;
269 spinlock_t lock;
270 void *entry[]; /*
271 * Must have this definition in here for the proper
272 * alignment of array_cache. Also simplifies accessing
273 * the entries.
278 * bootstrap: The caches do not work without cpuarrays anymore, but the
279 * cpuarrays are allocated from the generic caches...
281 #define BOOT_CPUCACHE_ENTRIES 1
282 struct arraycache_init {
283 struct array_cache cache;
284 void *entries[BOOT_CPUCACHE_ENTRIES];
288 * The slab lists for all objects.
290 struct kmem_list3 {
291 struct list_head slabs_partial; /* partial list first, better asm code */
292 struct list_head slabs_full;
293 struct list_head slabs_free;
294 unsigned long free_objects;
295 unsigned int free_limit;
296 unsigned int colour_next; /* Per-node cache coloring */
297 spinlock_t list_lock;
298 struct array_cache *shared; /* shared per node */
299 struct array_cache **alien; /* on other nodes */
300 unsigned long next_reap; /* updated without locking */
301 int free_touched; /* updated without locking */
305 * Need this for bootstrapping a per node allocator.
307 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
308 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
309 #define CACHE_CACHE 0
310 #define SIZE_AC MAX_NUMNODES
311 #define SIZE_L3 (2 * MAX_NUMNODES)
313 static int drain_freelist(struct kmem_cache *cache,
314 struct kmem_list3 *l3, int tofree);
315 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
316 int node);
317 static int enable_cpucache(struct kmem_cache *cachep);
318 static void cache_reap(struct work_struct *unused);
321 * This function must be completely optimized away if a constant is passed to
322 * it. Mostly the same as what is in linux/slab.h except it returns an index.
324 static __always_inline int index_of(const size_t size)
326 extern void __bad_size(void);
328 if (__builtin_constant_p(size)) {
329 int i = 0;
331 #define CACHE(x) \
332 if (size <=x) \
333 return i; \
334 else \
335 i++;
336 #include <linux/kmalloc_sizes.h>
337 #undef CACHE
338 __bad_size();
339 } else
340 __bad_size();
341 return 0;
344 static int slab_early_init = 1;
346 #define INDEX_AC index_of(sizeof(struct arraycache_init))
347 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
349 static void kmem_list3_init(struct kmem_list3 *parent)
351 INIT_LIST_HEAD(&parent->slabs_full);
352 INIT_LIST_HEAD(&parent->slabs_partial);
353 INIT_LIST_HEAD(&parent->slabs_free);
354 parent->shared = NULL;
355 parent->alien = NULL;
356 parent->colour_next = 0;
357 spin_lock_init(&parent->list_lock);
358 parent->free_objects = 0;
359 parent->free_touched = 0;
362 #define MAKE_LIST(cachep, listp, slab, nodeid) \
363 do { \
364 INIT_LIST_HEAD(listp); \
365 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
366 } while (0)
368 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
369 do { \
370 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
371 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
372 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
373 } while (0)
376 * struct kmem_cache
378 * manages a cache.
381 struct kmem_cache {
382 /* 1) per-cpu data, touched during every alloc/free */
383 struct array_cache *array[NR_CPUS];
384 /* 2) Cache tunables. Protected by cache_chain_mutex */
385 unsigned int batchcount;
386 unsigned int limit;
387 unsigned int shared;
389 unsigned int buffer_size;
390 u32 reciprocal_buffer_size;
391 /* 3) touched by every alloc & free from the backend */
393 unsigned int flags; /* constant flags */
394 unsigned int num; /* # of objs per slab */
396 /* 4) cache_grow/shrink */
397 /* order of pgs per slab (2^n) */
398 unsigned int gfporder;
400 /* force GFP flags, e.g. GFP_DMA */
401 gfp_t gfpflags;
403 size_t colour; /* cache colouring range */
404 unsigned int colour_off; /* colour offset */
405 struct kmem_cache *slabp_cache;
406 unsigned int slab_size;
407 unsigned int dflags; /* dynamic flags */
409 /* constructor func */
410 void (*ctor)(struct kmem_cache *, void *);
412 /* 5) cache creation/removal */
413 const char *name;
414 struct list_head next;
416 /* 6) statistics */
417 #if STATS
418 unsigned long num_active;
419 unsigned long num_allocations;
420 unsigned long high_mark;
421 unsigned long grown;
422 unsigned long reaped;
423 unsigned long errors;
424 unsigned long max_freeable;
425 unsigned long node_allocs;
426 unsigned long node_frees;
427 unsigned long node_overflow;
428 atomic_t allochit;
429 atomic_t allocmiss;
430 atomic_t freehit;
431 atomic_t freemiss;
432 #endif
433 #if DEBUG
435 * If debugging is enabled, then the allocator can add additional
436 * fields and/or padding to every object. buffer_size contains the total
437 * object size including these internal fields, the following two
438 * variables contain the offset to the user object and its size.
440 int obj_offset;
441 int obj_size;
442 #endif
444 * We put nodelists[] at the end of kmem_cache, because we want to size
445 * this array to nr_node_ids slots instead of MAX_NUMNODES
446 * (see kmem_cache_init())
447 * We still use [MAX_NUMNODES] and not [1] or [0] because cache_cache
448 * is statically defined, so we reserve the max number of nodes.
450 struct kmem_list3 *nodelists[MAX_NUMNODES];
452 * Do not add fields after nodelists[]
456 #define CFLGS_OFF_SLAB (0x80000000UL)
457 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
459 #define BATCHREFILL_LIMIT 16
461 * Optimization question: fewer reaps means less probability for unnessary
462 * cpucache drain/refill cycles.
464 * OTOH the cpuarrays can contain lots of objects,
465 * which could lock up otherwise freeable slabs.
467 #define REAPTIMEOUT_CPUC (2*HZ)
468 #define REAPTIMEOUT_LIST3 (4*HZ)
470 #if STATS
471 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
472 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
473 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
474 #define STATS_INC_GROWN(x) ((x)->grown++)
475 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
476 #define STATS_SET_HIGH(x) \
477 do { \
478 if ((x)->num_active > (x)->high_mark) \
479 (x)->high_mark = (x)->num_active; \
480 } while (0)
481 #define STATS_INC_ERR(x) ((x)->errors++)
482 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
483 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
484 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
485 #define STATS_SET_FREEABLE(x, i) \
486 do { \
487 if ((x)->max_freeable < i) \
488 (x)->max_freeable = i; \
489 } while (0)
490 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
491 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
492 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
493 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
494 #else
495 #define STATS_INC_ACTIVE(x) do { } while (0)
496 #define STATS_DEC_ACTIVE(x) do { } while (0)
497 #define STATS_INC_ALLOCED(x) do { } while (0)
498 #define STATS_INC_GROWN(x) do { } while (0)
499 #define STATS_ADD_REAPED(x,y) do { } while (0)
500 #define STATS_SET_HIGH(x) do { } while (0)
501 #define STATS_INC_ERR(x) do { } while (0)
502 #define STATS_INC_NODEALLOCS(x) do { } while (0)
503 #define STATS_INC_NODEFREES(x) do { } while (0)
504 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
505 #define STATS_SET_FREEABLE(x, i) do { } while (0)
506 #define STATS_INC_ALLOCHIT(x) do { } while (0)
507 #define STATS_INC_ALLOCMISS(x) do { } while (0)
508 #define STATS_INC_FREEHIT(x) do { } while (0)
509 #define STATS_INC_FREEMISS(x) do { } while (0)
510 #endif
512 #if DEBUG
515 * memory layout of objects:
516 * 0 : objp
517 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
518 * the end of an object is aligned with the end of the real
519 * allocation. Catches writes behind the end of the allocation.
520 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
521 * redzone word.
522 * cachep->obj_offset: The real object.
523 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
524 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
525 * [BYTES_PER_WORD long]
527 static int obj_offset(struct kmem_cache *cachep)
529 return cachep->obj_offset;
532 static int obj_size(struct kmem_cache *cachep)
534 return cachep->obj_size;
537 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
539 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
540 return (unsigned long long*) (objp + obj_offset(cachep) -
541 sizeof(unsigned long long));
544 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
546 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
547 if (cachep->flags & SLAB_STORE_USER)
548 return (unsigned long long *)(objp + cachep->buffer_size -
549 sizeof(unsigned long long) -
550 REDZONE_ALIGN);
551 return (unsigned long long *) (objp + cachep->buffer_size -
552 sizeof(unsigned long long));
555 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
557 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
558 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
561 #else
563 #define obj_offset(x) 0
564 #define obj_size(cachep) (cachep->buffer_size)
565 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
566 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
567 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
569 #endif
571 #ifdef CONFIG_KMEMTRACE
572 size_t slab_buffer_size(struct kmem_cache *cachep)
574 return cachep->buffer_size;
576 EXPORT_SYMBOL(slab_buffer_size);
577 #endif
580 * Do not go above this order unless 0 objects fit into the slab.
582 #define BREAK_GFP_ORDER_HI 1
583 #define BREAK_GFP_ORDER_LO 0
584 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
587 * Functions for storing/retrieving the cachep and or slab from the page
588 * allocator. These are used to find the slab an obj belongs to. With kfree(),
589 * these are used to find the cache which an obj belongs to.
591 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
593 page->lru.next = (struct list_head *)cache;
596 static inline struct kmem_cache *page_get_cache(struct page *page)
598 page = compound_head(page);
599 BUG_ON(!PageSlab(page));
600 return (struct kmem_cache *)page->lru.next;
603 static inline void page_set_slab(struct page *page, struct slab *slab)
605 page->lru.prev = (struct list_head *)slab;
608 static inline struct slab *page_get_slab(struct page *page)
610 BUG_ON(!PageSlab(page));
611 return (struct slab *)page->lru.prev;
614 static inline struct kmem_cache *virt_to_cache(const void *obj)
616 struct page *page = virt_to_head_page(obj);
617 return page_get_cache(page);
620 static inline struct slab *virt_to_slab(const void *obj)
622 struct page *page = virt_to_head_page(obj);
623 return page_get_slab(page);
626 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
627 unsigned int idx)
629 return slab->s_mem + cache->buffer_size * idx;
633 * We want to avoid an expensive divide : (offset / cache->buffer_size)
634 * Using the fact that buffer_size is a constant for a particular cache,
635 * we can replace (offset / cache->buffer_size) by
636 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
638 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
639 const struct slab *slab, void *obj)
641 u32 offset = (obj - slab->s_mem);
642 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
646 * These are the default caches for kmalloc. Custom caches can have other sizes.
648 struct cache_sizes malloc_sizes[] = {
649 #define CACHE(x) { .cs_size = (x) },
650 #include <linux/kmalloc_sizes.h>
651 CACHE(ULONG_MAX)
652 #undef CACHE
654 EXPORT_SYMBOL(malloc_sizes);
656 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
657 struct cache_names {
658 char *name;
659 char *name_dma;
662 static struct cache_names __initdata cache_names[] = {
663 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
664 #include <linux/kmalloc_sizes.h>
665 {NULL,}
666 #undef CACHE
669 static struct arraycache_init initarray_cache __initdata =
670 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
671 static struct arraycache_init initarray_generic =
672 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
674 /* internal cache of cache description objs */
675 static struct kmem_cache cache_cache = {
676 .batchcount = 1,
677 .limit = BOOT_CPUCACHE_ENTRIES,
678 .shared = 1,
679 .buffer_size = sizeof(struct kmem_cache),
680 .name = "kmem_cache",
683 #define BAD_ALIEN_MAGIC 0x01020304ul
685 #ifdef CONFIG_LOCKDEP
688 * Slab sometimes uses the kmalloc slabs to store the slab headers
689 * for other slabs "off slab".
690 * The locking for this is tricky in that it nests within the locks
691 * of all other slabs in a few places; to deal with this special
692 * locking we put on-slab caches into a separate lock-class.
694 * We set lock class for alien array caches which are up during init.
695 * The lock annotation will be lost if all cpus of a node goes down and
696 * then comes back up during hotplug
698 static struct lock_class_key on_slab_l3_key;
699 static struct lock_class_key on_slab_alc_key;
701 static inline void init_lock_keys(void)
704 int q;
705 struct cache_sizes *s = malloc_sizes;
707 while (s->cs_size != ULONG_MAX) {
708 for_each_node(q) {
709 struct array_cache **alc;
710 int r;
711 struct kmem_list3 *l3 = s->cs_cachep->nodelists[q];
712 if (!l3 || OFF_SLAB(s->cs_cachep))
713 continue;
714 lockdep_set_class(&l3->list_lock, &on_slab_l3_key);
715 alc = l3->alien;
717 * FIXME: This check for BAD_ALIEN_MAGIC
718 * should go away when common slab code is taught to
719 * work even without alien caches.
720 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
721 * for alloc_alien_cache,
723 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
724 continue;
725 for_each_node(r) {
726 if (alc[r])
727 lockdep_set_class(&alc[r]->lock,
728 &on_slab_alc_key);
731 s++;
734 #else
735 static inline void init_lock_keys(void)
738 #endif
741 * Guard access to the cache-chain.
743 static DEFINE_MUTEX(cache_chain_mutex);
744 static struct list_head cache_chain;
747 * chicken and egg problem: delay the per-cpu array allocation
748 * until the general caches are up.
750 static enum {
751 NONE,
752 PARTIAL_AC,
753 PARTIAL_L3,
754 FULL
755 } g_cpucache_up;
758 * used by boot code to determine if it can use slab based allocator
760 int slab_is_available(void)
762 return g_cpucache_up == FULL;
765 static DEFINE_PER_CPU(struct delayed_work, reap_work);
767 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
769 return cachep->array[smp_processor_id()];
772 static inline struct kmem_cache *__find_general_cachep(size_t size,
773 gfp_t gfpflags)
775 struct cache_sizes *csizep = malloc_sizes;
777 #if DEBUG
778 /* This happens if someone tries to call
779 * kmem_cache_create(), or __kmalloc(), before
780 * the generic caches are initialized.
782 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
783 #endif
784 if (!size)
785 return ZERO_SIZE_PTR;
787 while (size > csizep->cs_size)
788 csizep++;
791 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
792 * has cs_{dma,}cachep==NULL. Thus no special case
793 * for large kmalloc calls required.
795 #ifdef CONFIG_ZONE_DMA
796 if (unlikely(gfpflags & GFP_DMA))
797 return csizep->cs_dmacachep;
798 #endif
799 return csizep->cs_cachep;
802 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
804 return __find_general_cachep(size, gfpflags);
807 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
809 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
813 * Calculate the number of objects and left-over bytes for a given buffer size.
815 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
816 size_t align, int flags, size_t *left_over,
817 unsigned int *num)
819 int nr_objs;
820 size_t mgmt_size;
821 size_t slab_size = PAGE_SIZE << gfporder;
824 * The slab management structure can be either off the slab or
825 * on it. For the latter case, the memory allocated for a
826 * slab is used for:
828 * - The struct slab
829 * - One kmem_bufctl_t for each object
830 * - Padding to respect alignment of @align
831 * - @buffer_size bytes for each object
833 * If the slab management structure is off the slab, then the
834 * alignment will already be calculated into the size. Because
835 * the slabs are all pages aligned, the objects will be at the
836 * correct alignment when allocated.
838 if (flags & CFLGS_OFF_SLAB) {
839 mgmt_size = 0;
840 nr_objs = slab_size / buffer_size;
842 if (nr_objs > SLAB_LIMIT)
843 nr_objs = SLAB_LIMIT;
844 } else {
846 * Ignore padding for the initial guess. The padding
847 * is at most @align-1 bytes, and @buffer_size is at
848 * least @align. In the worst case, this result will
849 * be one greater than the number of objects that fit
850 * into the memory allocation when taking the padding
851 * into account.
853 nr_objs = (slab_size - sizeof(struct slab)) /
854 (buffer_size + sizeof(kmem_bufctl_t));
857 * This calculated number will be either the right
858 * amount, or one greater than what we want.
860 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
861 > slab_size)
862 nr_objs--;
864 if (nr_objs > SLAB_LIMIT)
865 nr_objs = SLAB_LIMIT;
867 mgmt_size = slab_mgmt_size(nr_objs, align);
869 *num = nr_objs;
870 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
873 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
875 static void __slab_error(const char *function, struct kmem_cache *cachep,
876 char *msg)
878 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
879 function, cachep->name, msg);
880 dump_stack();
884 * By default on NUMA we use alien caches to stage the freeing of
885 * objects allocated from other nodes. This causes massive memory
886 * inefficiencies when using fake NUMA setup to split memory into a
887 * large number of small nodes, so it can be disabled on the command
888 * line
891 static int use_alien_caches __read_mostly = 1;
892 static int numa_platform __read_mostly = 1;
893 static int __init noaliencache_setup(char *s)
895 use_alien_caches = 0;
896 return 1;
898 __setup("noaliencache", noaliencache_setup);
900 #ifdef CONFIG_NUMA
902 * Special reaping functions for NUMA systems called from cache_reap().
903 * These take care of doing round robin flushing of alien caches (containing
904 * objects freed on different nodes from which they were allocated) and the
905 * flushing of remote pcps by calling drain_node_pages.
907 static DEFINE_PER_CPU(unsigned long, reap_node);
909 static void init_reap_node(int cpu)
911 int node;
913 node = next_node(cpu_to_node(cpu), node_online_map);
914 if (node == MAX_NUMNODES)
915 node = first_node(node_online_map);
917 per_cpu(reap_node, cpu) = node;
920 static void next_reap_node(void)
922 int node = __get_cpu_var(reap_node);
924 node = next_node(node, node_online_map);
925 if (unlikely(node >= MAX_NUMNODES))
926 node = first_node(node_online_map);
927 __get_cpu_var(reap_node) = node;
930 #else
931 #define init_reap_node(cpu) do { } while (0)
932 #define next_reap_node(void) do { } while (0)
933 #endif
936 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
937 * via the workqueue/eventd.
938 * Add the CPU number into the expiration time to minimize the possibility of
939 * the CPUs getting into lockstep and contending for the global cache chain
940 * lock.
942 static void __cpuinit start_cpu_timer(int cpu)
944 struct delayed_work *reap_work = &per_cpu(reap_work, cpu);
947 * When this gets called from do_initcalls via cpucache_init(),
948 * init_workqueues() has already run, so keventd will be setup
949 * at that time.
951 if (keventd_up() && reap_work->work.func == NULL) {
952 init_reap_node(cpu);
953 INIT_DELAYED_WORK(reap_work, cache_reap);
954 schedule_delayed_work_on(cpu, reap_work,
955 __round_jiffies_relative(HZ, cpu));
959 static struct array_cache *alloc_arraycache(int node, int entries,
960 int batchcount)
962 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
963 struct array_cache *nc = NULL;
965 nc = kmalloc_node(memsize, GFP_KERNEL, node);
966 if (nc) {
967 nc->avail = 0;
968 nc->limit = entries;
969 nc->batchcount = batchcount;
970 nc->touched = 0;
971 spin_lock_init(&nc->lock);
973 return nc;
977 * Transfer objects in one arraycache to another.
978 * Locking must be handled by the caller.
980 * Return the number of entries transferred.
982 static int transfer_objects(struct array_cache *to,
983 struct array_cache *from, unsigned int max)
985 /* Figure out how many entries to transfer */
986 int nr = min(min(from->avail, max), to->limit - to->avail);
988 if (!nr)
989 return 0;
991 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
992 sizeof(void *) *nr);
994 from->avail -= nr;
995 to->avail += nr;
996 to->touched = 1;
997 return nr;
1000 #ifndef CONFIG_NUMA
1002 #define drain_alien_cache(cachep, alien) do { } while (0)
1003 #define reap_alien(cachep, l3) do { } while (0)
1005 static inline struct array_cache **alloc_alien_cache(int node, int limit)
1007 return (struct array_cache **)BAD_ALIEN_MAGIC;
1010 static inline void free_alien_cache(struct array_cache **ac_ptr)
1014 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1016 return 0;
1019 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
1020 gfp_t flags)
1022 return NULL;
1025 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
1026 gfp_t flags, int nodeid)
1028 return NULL;
1031 #else /* CONFIG_NUMA */
1033 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
1034 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1036 static struct array_cache **alloc_alien_cache(int node, int limit)
1038 struct array_cache **ac_ptr;
1039 int memsize = sizeof(void *) * nr_node_ids;
1040 int i;
1042 if (limit > 1)
1043 limit = 12;
1044 ac_ptr = kmalloc_node(memsize, GFP_KERNEL, node);
1045 if (ac_ptr) {
1046 for_each_node(i) {
1047 if (i == node || !node_online(i)) {
1048 ac_ptr[i] = NULL;
1049 continue;
1051 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d);
1052 if (!ac_ptr[i]) {
1053 for (i--; i >= 0; i--)
1054 kfree(ac_ptr[i]);
1055 kfree(ac_ptr);
1056 return NULL;
1060 return ac_ptr;
1063 static void free_alien_cache(struct array_cache **ac_ptr)
1065 int i;
1067 if (!ac_ptr)
1068 return;
1069 for_each_node(i)
1070 kfree(ac_ptr[i]);
1071 kfree(ac_ptr);
1074 static void __drain_alien_cache(struct kmem_cache *cachep,
1075 struct array_cache *ac, int node)
1077 struct kmem_list3 *rl3 = cachep->nodelists[node];
1079 if (ac->avail) {
1080 spin_lock(&rl3->list_lock);
1082 * Stuff objects into the remote nodes shared array first.
1083 * That way we could avoid the overhead of putting the objects
1084 * into the free lists and getting them back later.
1086 if (rl3->shared)
1087 transfer_objects(rl3->shared, ac, ac->limit);
1089 free_block(cachep, ac->entry, ac->avail, node);
1090 ac->avail = 0;
1091 spin_unlock(&rl3->list_lock);
1096 * Called from cache_reap() to regularly drain alien caches round robin.
1098 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1100 int node = __get_cpu_var(reap_node);
1102 if (l3->alien) {
1103 struct array_cache *ac = l3->alien[node];
1105 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1106 __drain_alien_cache(cachep, ac, node);
1107 spin_unlock_irq(&ac->lock);
1112 static void drain_alien_cache(struct kmem_cache *cachep,
1113 struct array_cache **alien)
1115 int i = 0;
1116 struct array_cache *ac;
1117 unsigned long flags;
1119 for_each_online_node(i) {
1120 ac = alien[i];
1121 if (ac) {
1122 spin_lock_irqsave(&ac->lock, flags);
1123 __drain_alien_cache(cachep, ac, i);
1124 spin_unlock_irqrestore(&ac->lock, flags);
1129 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1131 struct slab *slabp = virt_to_slab(objp);
1132 int nodeid = slabp->nodeid;
1133 struct kmem_list3 *l3;
1134 struct array_cache *alien = NULL;
1135 int node;
1137 node = numa_node_id();
1140 * Make sure we are not freeing a object from another node to the array
1141 * cache on this cpu.
1143 if (likely(slabp->nodeid == node))
1144 return 0;
1146 l3 = cachep->nodelists[node];
1147 STATS_INC_NODEFREES(cachep);
1148 if (l3->alien && l3->alien[nodeid]) {
1149 alien = l3->alien[nodeid];
1150 spin_lock(&alien->lock);
1151 if (unlikely(alien->avail == alien->limit)) {
1152 STATS_INC_ACOVERFLOW(cachep);
1153 __drain_alien_cache(cachep, alien, nodeid);
1155 alien->entry[alien->avail++] = objp;
1156 spin_unlock(&alien->lock);
1157 } else {
1158 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1159 free_block(cachep, &objp, 1, nodeid);
1160 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1162 return 1;
1164 #endif
1166 static void __cpuinit cpuup_canceled(long cpu)
1168 struct kmem_cache *cachep;
1169 struct kmem_list3 *l3 = NULL;
1170 int node = cpu_to_node(cpu);
1171 node_to_cpumask_ptr(mask, node);
1173 list_for_each_entry(cachep, &cache_chain, next) {
1174 struct array_cache *nc;
1175 struct array_cache *shared;
1176 struct array_cache **alien;
1178 /* cpu is dead; no one can alloc from it. */
1179 nc = cachep->array[cpu];
1180 cachep->array[cpu] = NULL;
1181 l3 = cachep->nodelists[node];
1183 if (!l3)
1184 goto free_array_cache;
1186 spin_lock_irq(&l3->list_lock);
1188 /* Free limit for this kmem_list3 */
1189 l3->free_limit -= cachep->batchcount;
1190 if (nc)
1191 free_block(cachep, nc->entry, nc->avail, node);
1193 if (!cpus_empty(*mask)) {
1194 spin_unlock_irq(&l3->list_lock);
1195 goto free_array_cache;
1198 shared = l3->shared;
1199 if (shared) {
1200 free_block(cachep, shared->entry,
1201 shared->avail, node);
1202 l3->shared = NULL;
1205 alien = l3->alien;
1206 l3->alien = NULL;
1208 spin_unlock_irq(&l3->list_lock);
1210 kfree(shared);
1211 if (alien) {
1212 drain_alien_cache(cachep, alien);
1213 free_alien_cache(alien);
1215 free_array_cache:
1216 kfree(nc);
1219 * In the previous loop, all the objects were freed to
1220 * the respective cache's slabs, now we can go ahead and
1221 * shrink each nodelist to its limit.
1223 list_for_each_entry(cachep, &cache_chain, next) {
1224 l3 = cachep->nodelists[node];
1225 if (!l3)
1226 continue;
1227 drain_freelist(cachep, l3, l3->free_objects);
1231 static int __cpuinit cpuup_prepare(long cpu)
1233 struct kmem_cache *cachep;
1234 struct kmem_list3 *l3 = NULL;
1235 int node = cpu_to_node(cpu);
1236 const int memsize = sizeof(struct kmem_list3);
1239 * We need to do this right in the beginning since
1240 * alloc_arraycache's are going to use this list.
1241 * kmalloc_node allows us to add the slab to the right
1242 * kmem_list3 and not this cpu's kmem_list3
1245 list_for_each_entry(cachep, &cache_chain, next) {
1247 * Set up the size64 kmemlist for cpu before we can
1248 * begin anything. Make sure some other cpu on this
1249 * node has not already allocated this
1251 if (!cachep->nodelists[node]) {
1252 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1253 if (!l3)
1254 goto bad;
1255 kmem_list3_init(l3);
1256 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1257 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1260 * The l3s don't come and go as CPUs come and
1261 * go. cache_chain_mutex is sufficient
1262 * protection here.
1264 cachep->nodelists[node] = l3;
1267 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1268 cachep->nodelists[node]->free_limit =
1269 (1 + nr_cpus_node(node)) *
1270 cachep->batchcount + cachep->num;
1271 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1275 * Now we can go ahead with allocating the shared arrays and
1276 * array caches
1278 list_for_each_entry(cachep, &cache_chain, next) {
1279 struct array_cache *nc;
1280 struct array_cache *shared = NULL;
1281 struct array_cache **alien = NULL;
1283 nc = alloc_arraycache(node, cachep->limit,
1284 cachep->batchcount);
1285 if (!nc)
1286 goto bad;
1287 if (cachep->shared) {
1288 shared = alloc_arraycache(node,
1289 cachep->shared * cachep->batchcount,
1290 0xbaadf00d);
1291 if (!shared) {
1292 kfree(nc);
1293 goto bad;
1296 if (use_alien_caches) {
1297 alien = alloc_alien_cache(node, cachep->limit);
1298 if (!alien) {
1299 kfree(shared);
1300 kfree(nc);
1301 goto bad;
1304 cachep->array[cpu] = nc;
1305 l3 = cachep->nodelists[node];
1306 BUG_ON(!l3);
1308 spin_lock_irq(&l3->list_lock);
1309 if (!l3->shared) {
1311 * We are serialised from CPU_DEAD or
1312 * CPU_UP_CANCELLED by the cpucontrol lock
1314 l3->shared = shared;
1315 shared = NULL;
1317 #ifdef CONFIG_NUMA
1318 if (!l3->alien) {
1319 l3->alien = alien;
1320 alien = NULL;
1322 #endif
1323 spin_unlock_irq(&l3->list_lock);
1324 kfree(shared);
1325 free_alien_cache(alien);
1327 return 0;
1328 bad:
1329 cpuup_canceled(cpu);
1330 return -ENOMEM;
1333 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1334 unsigned long action, void *hcpu)
1336 long cpu = (long)hcpu;
1337 int err = 0;
1339 switch (action) {
1340 case CPU_UP_PREPARE:
1341 case CPU_UP_PREPARE_FROZEN:
1342 mutex_lock(&cache_chain_mutex);
1343 err = cpuup_prepare(cpu);
1344 mutex_unlock(&cache_chain_mutex);
1345 break;
1346 case CPU_ONLINE:
1347 case CPU_ONLINE_FROZEN:
1348 start_cpu_timer(cpu);
1349 break;
1350 #ifdef CONFIG_HOTPLUG_CPU
1351 case CPU_DOWN_PREPARE:
1352 case CPU_DOWN_PREPARE_FROZEN:
1354 * Shutdown cache reaper. Note that the cache_chain_mutex is
1355 * held so that if cache_reap() is invoked it cannot do
1356 * anything expensive but will only modify reap_work
1357 * and reschedule the timer.
1359 cancel_rearming_delayed_work(&per_cpu(reap_work, cpu));
1360 /* Now the cache_reaper is guaranteed to be not running. */
1361 per_cpu(reap_work, cpu).work.func = NULL;
1362 break;
1363 case CPU_DOWN_FAILED:
1364 case CPU_DOWN_FAILED_FROZEN:
1365 start_cpu_timer(cpu);
1366 break;
1367 case CPU_DEAD:
1368 case CPU_DEAD_FROZEN:
1370 * Even if all the cpus of a node are down, we don't free the
1371 * kmem_list3 of any cache. This to avoid a race between
1372 * cpu_down, and a kmalloc allocation from another cpu for
1373 * memory from the node of the cpu going down. The list3
1374 * structure is usually allocated from kmem_cache_create() and
1375 * gets destroyed at kmem_cache_destroy().
1377 /* fall through */
1378 #endif
1379 case CPU_UP_CANCELED:
1380 case CPU_UP_CANCELED_FROZEN:
1381 mutex_lock(&cache_chain_mutex);
1382 cpuup_canceled(cpu);
1383 mutex_unlock(&cache_chain_mutex);
1384 break;
1386 return err ? NOTIFY_BAD : NOTIFY_OK;
1389 static struct notifier_block __cpuinitdata cpucache_notifier = {
1390 &cpuup_callback, NULL, 0
1394 * swap the static kmem_list3 with kmalloced memory
1396 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1397 int nodeid)
1399 struct kmem_list3 *ptr;
1401 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, nodeid);
1402 BUG_ON(!ptr);
1404 local_irq_disable();
1405 memcpy(ptr, list, sizeof(struct kmem_list3));
1407 * Do not assume that spinlocks can be initialized via memcpy:
1409 spin_lock_init(&ptr->list_lock);
1411 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1412 cachep->nodelists[nodeid] = ptr;
1413 local_irq_enable();
1417 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1418 * size of kmem_list3.
1420 static void __init set_up_list3s(struct kmem_cache *cachep, int index)
1422 int node;
1424 for_each_online_node(node) {
1425 cachep->nodelists[node] = &initkmem_list3[index + node];
1426 cachep->nodelists[node]->next_reap = jiffies +
1427 REAPTIMEOUT_LIST3 +
1428 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1433 * Initialisation. Called after the page allocator have been initialised and
1434 * before smp_init().
1436 void __init kmem_cache_init(void)
1438 size_t left_over;
1439 struct cache_sizes *sizes;
1440 struct cache_names *names;
1441 int i;
1442 int order;
1443 int node;
1445 if (num_possible_nodes() == 1) {
1446 use_alien_caches = 0;
1447 numa_platform = 0;
1450 for (i = 0; i < NUM_INIT_LISTS; i++) {
1451 kmem_list3_init(&initkmem_list3[i]);
1452 if (i < MAX_NUMNODES)
1453 cache_cache.nodelists[i] = NULL;
1455 set_up_list3s(&cache_cache, CACHE_CACHE);
1458 * Fragmentation resistance on low memory - only use bigger
1459 * page orders on machines with more than 32MB of memory.
1461 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
1462 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1464 /* Bootstrap is tricky, because several objects are allocated
1465 * from caches that do not exist yet:
1466 * 1) initialize the cache_cache cache: it contains the struct
1467 * kmem_cache structures of all caches, except cache_cache itself:
1468 * cache_cache is statically allocated.
1469 * Initially an __init data area is used for the head array and the
1470 * kmem_list3 structures, it's replaced with a kmalloc allocated
1471 * array at the end of the bootstrap.
1472 * 2) Create the first kmalloc cache.
1473 * The struct kmem_cache for the new cache is allocated normally.
1474 * An __init data area is used for the head array.
1475 * 3) Create the remaining kmalloc caches, with minimally sized
1476 * head arrays.
1477 * 4) Replace the __init data head arrays for cache_cache and the first
1478 * kmalloc cache with kmalloc allocated arrays.
1479 * 5) Replace the __init data for kmem_list3 for cache_cache and
1480 * the other cache's with kmalloc allocated memory.
1481 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1484 node = numa_node_id();
1486 /* 1) create the cache_cache */
1487 INIT_LIST_HEAD(&cache_chain);
1488 list_add(&cache_cache.next, &cache_chain);
1489 cache_cache.colour_off = cache_line_size();
1490 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1491 cache_cache.nodelists[node] = &initkmem_list3[CACHE_CACHE + node];
1494 * struct kmem_cache size depends on nr_node_ids, which
1495 * can be less than MAX_NUMNODES.
1497 cache_cache.buffer_size = offsetof(struct kmem_cache, nodelists) +
1498 nr_node_ids * sizeof(struct kmem_list3 *);
1499 #if DEBUG
1500 cache_cache.obj_size = cache_cache.buffer_size;
1501 #endif
1502 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1503 cache_line_size());
1504 cache_cache.reciprocal_buffer_size =
1505 reciprocal_value(cache_cache.buffer_size);
1507 for (order = 0; order < MAX_ORDER; order++) {
1508 cache_estimate(order, cache_cache.buffer_size,
1509 cache_line_size(), 0, &left_over, &cache_cache.num);
1510 if (cache_cache.num)
1511 break;
1513 BUG_ON(!cache_cache.num);
1514 cache_cache.gfporder = order;
1515 cache_cache.colour = left_over / cache_cache.colour_off;
1516 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1517 sizeof(struct slab), cache_line_size());
1519 /* 2+3) create the kmalloc caches */
1520 sizes = malloc_sizes;
1521 names = cache_names;
1524 * Initialize the caches that provide memory for the array cache and the
1525 * kmem_list3 structures first. Without this, further allocations will
1526 * bug.
1529 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1530 sizes[INDEX_AC].cs_size,
1531 ARCH_KMALLOC_MINALIGN,
1532 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1533 NULL);
1535 if (INDEX_AC != INDEX_L3) {
1536 sizes[INDEX_L3].cs_cachep =
1537 kmem_cache_create(names[INDEX_L3].name,
1538 sizes[INDEX_L3].cs_size,
1539 ARCH_KMALLOC_MINALIGN,
1540 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1541 NULL);
1544 slab_early_init = 0;
1546 while (sizes->cs_size != ULONG_MAX) {
1548 * For performance, all the general caches are L1 aligned.
1549 * This should be particularly beneficial on SMP boxes, as it
1550 * eliminates "false sharing".
1551 * Note for systems short on memory removing the alignment will
1552 * allow tighter packing of the smaller caches.
1554 if (!sizes->cs_cachep) {
1555 sizes->cs_cachep = kmem_cache_create(names->name,
1556 sizes->cs_size,
1557 ARCH_KMALLOC_MINALIGN,
1558 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1559 NULL);
1561 #ifdef CONFIG_ZONE_DMA
1562 sizes->cs_dmacachep = kmem_cache_create(
1563 names->name_dma,
1564 sizes->cs_size,
1565 ARCH_KMALLOC_MINALIGN,
1566 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1567 SLAB_PANIC,
1568 NULL);
1569 #endif
1570 sizes++;
1571 names++;
1573 /* 4) Replace the bootstrap head arrays */
1575 struct array_cache *ptr;
1577 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1579 local_irq_disable();
1580 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1581 memcpy(ptr, cpu_cache_get(&cache_cache),
1582 sizeof(struct arraycache_init));
1584 * Do not assume that spinlocks can be initialized via memcpy:
1586 spin_lock_init(&ptr->lock);
1588 cache_cache.array[smp_processor_id()] = ptr;
1589 local_irq_enable();
1591 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1593 local_irq_disable();
1594 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1595 != &initarray_generic.cache);
1596 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1597 sizeof(struct arraycache_init));
1599 * Do not assume that spinlocks can be initialized via memcpy:
1601 spin_lock_init(&ptr->lock);
1603 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1604 ptr;
1605 local_irq_enable();
1607 /* 5) Replace the bootstrap kmem_list3's */
1609 int nid;
1611 for_each_online_node(nid) {
1612 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE + nid], nid);
1614 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1615 &initkmem_list3[SIZE_AC + nid], nid);
1617 if (INDEX_AC != INDEX_L3) {
1618 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1619 &initkmem_list3[SIZE_L3 + nid], nid);
1624 /* 6) resize the head arrays to their final sizes */
1626 struct kmem_cache *cachep;
1627 mutex_lock(&cache_chain_mutex);
1628 list_for_each_entry(cachep, &cache_chain, next)
1629 if (enable_cpucache(cachep))
1630 BUG();
1631 mutex_unlock(&cache_chain_mutex);
1634 /* Annotate slab for lockdep -- annotate the malloc caches */
1635 init_lock_keys();
1638 /* Done! */
1639 g_cpucache_up = FULL;
1642 * Register a cpu startup notifier callback that initializes
1643 * cpu_cache_get for all new cpus
1645 register_cpu_notifier(&cpucache_notifier);
1648 * The reap timers are started later, with a module init call: That part
1649 * of the kernel is not yet operational.
1653 static int __init cpucache_init(void)
1655 int cpu;
1658 * Register the timers that return unneeded pages to the page allocator
1660 for_each_online_cpu(cpu)
1661 start_cpu_timer(cpu);
1662 return 0;
1664 __initcall(cpucache_init);
1667 * Interface to system's page allocator. No need to hold the cache-lock.
1669 * If we requested dmaable memory, we will get it. Even if we
1670 * did not request dmaable memory, we might get it, but that
1671 * would be relatively rare and ignorable.
1673 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1675 struct page *page;
1676 int nr_pages;
1677 int i;
1679 #ifndef CONFIG_MMU
1681 * Nommu uses slab's for process anonymous memory allocations, and thus
1682 * requires __GFP_COMP to properly refcount higher order allocations
1684 flags |= __GFP_COMP;
1685 #endif
1687 flags |= cachep->gfpflags;
1688 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1689 flags |= __GFP_RECLAIMABLE;
1691 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
1692 if (!page)
1693 return NULL;
1695 nr_pages = (1 << cachep->gfporder);
1696 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1697 add_zone_page_state(page_zone(page),
1698 NR_SLAB_RECLAIMABLE, nr_pages);
1699 else
1700 add_zone_page_state(page_zone(page),
1701 NR_SLAB_UNRECLAIMABLE, nr_pages);
1702 for (i = 0; i < nr_pages; i++)
1703 __SetPageSlab(page + i);
1704 return page_address(page);
1708 * Interface to system's page release.
1710 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1712 unsigned long i = (1 << cachep->gfporder);
1713 struct page *page = virt_to_page(addr);
1714 const unsigned long nr_freed = i;
1716 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1717 sub_zone_page_state(page_zone(page),
1718 NR_SLAB_RECLAIMABLE, nr_freed);
1719 else
1720 sub_zone_page_state(page_zone(page),
1721 NR_SLAB_UNRECLAIMABLE, nr_freed);
1722 while (i--) {
1723 BUG_ON(!PageSlab(page));
1724 __ClearPageSlab(page);
1725 page++;
1727 if (current->reclaim_state)
1728 current->reclaim_state->reclaimed_slab += nr_freed;
1729 free_pages((unsigned long)addr, cachep->gfporder);
1732 static void kmem_rcu_free(struct rcu_head *head)
1734 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1735 struct kmem_cache *cachep = slab_rcu->cachep;
1737 kmem_freepages(cachep, slab_rcu->addr);
1738 if (OFF_SLAB(cachep))
1739 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1742 #if DEBUG
1744 #ifdef CONFIG_DEBUG_PAGEALLOC
1745 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1746 unsigned long caller)
1748 int size = obj_size(cachep);
1750 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1752 if (size < 5 * sizeof(unsigned long))
1753 return;
1755 *addr++ = 0x12345678;
1756 *addr++ = caller;
1757 *addr++ = smp_processor_id();
1758 size -= 3 * sizeof(unsigned long);
1760 unsigned long *sptr = &caller;
1761 unsigned long svalue;
1763 while (!kstack_end(sptr)) {
1764 svalue = *sptr++;
1765 if (kernel_text_address(svalue)) {
1766 *addr++ = svalue;
1767 size -= sizeof(unsigned long);
1768 if (size <= sizeof(unsigned long))
1769 break;
1774 *addr++ = 0x87654321;
1776 #endif
1778 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1780 int size = obj_size(cachep);
1781 addr = &((char *)addr)[obj_offset(cachep)];
1783 memset(addr, val, size);
1784 *(unsigned char *)(addr + size - 1) = POISON_END;
1787 static void dump_line(char *data, int offset, int limit)
1789 int i;
1790 unsigned char error = 0;
1791 int bad_count = 0;
1793 printk(KERN_ERR "%03x:", offset);
1794 for (i = 0; i < limit; i++) {
1795 if (data[offset + i] != POISON_FREE) {
1796 error = data[offset + i];
1797 bad_count++;
1799 printk(" %02x", (unsigned char)data[offset + i]);
1801 printk("\n");
1803 if (bad_count == 1) {
1804 error ^= POISON_FREE;
1805 if (!(error & (error - 1))) {
1806 printk(KERN_ERR "Single bit error detected. Probably "
1807 "bad RAM.\n");
1808 #ifdef CONFIG_X86
1809 printk(KERN_ERR "Run memtest86+ or a similar memory "
1810 "test tool.\n");
1811 #else
1812 printk(KERN_ERR "Run a memory test tool.\n");
1813 #endif
1817 #endif
1819 #if DEBUG
1821 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1823 int i, size;
1824 char *realobj;
1826 if (cachep->flags & SLAB_RED_ZONE) {
1827 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1828 *dbg_redzone1(cachep, objp),
1829 *dbg_redzone2(cachep, objp));
1832 if (cachep->flags & SLAB_STORE_USER) {
1833 printk(KERN_ERR "Last user: [<%p>]",
1834 *dbg_userword(cachep, objp));
1835 print_symbol("(%s)",
1836 (unsigned long)*dbg_userword(cachep, objp));
1837 printk("\n");
1839 realobj = (char *)objp + obj_offset(cachep);
1840 size = obj_size(cachep);
1841 for (i = 0; i < size && lines; i += 16, lines--) {
1842 int limit;
1843 limit = 16;
1844 if (i + limit > size)
1845 limit = size - i;
1846 dump_line(realobj, i, limit);
1850 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1852 char *realobj;
1853 int size, i;
1854 int lines = 0;
1856 realobj = (char *)objp + obj_offset(cachep);
1857 size = obj_size(cachep);
1859 for (i = 0; i < size; i++) {
1860 char exp = POISON_FREE;
1861 if (i == size - 1)
1862 exp = POISON_END;
1863 if (realobj[i] != exp) {
1864 int limit;
1865 /* Mismatch ! */
1866 /* Print header */
1867 if (lines == 0) {
1868 printk(KERN_ERR
1869 "Slab corruption: %s start=%p, len=%d\n",
1870 cachep->name, realobj, size);
1871 print_objinfo(cachep, objp, 0);
1873 /* Hexdump the affected line */
1874 i = (i / 16) * 16;
1875 limit = 16;
1876 if (i + limit > size)
1877 limit = size - i;
1878 dump_line(realobj, i, limit);
1879 i += 16;
1880 lines++;
1881 /* Limit to 5 lines */
1882 if (lines > 5)
1883 break;
1886 if (lines != 0) {
1887 /* Print some data about the neighboring objects, if they
1888 * exist:
1890 struct slab *slabp = virt_to_slab(objp);
1891 unsigned int objnr;
1893 objnr = obj_to_index(cachep, slabp, objp);
1894 if (objnr) {
1895 objp = index_to_obj(cachep, slabp, objnr - 1);
1896 realobj = (char *)objp + obj_offset(cachep);
1897 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1898 realobj, size);
1899 print_objinfo(cachep, objp, 2);
1901 if (objnr + 1 < cachep->num) {
1902 objp = index_to_obj(cachep, slabp, objnr + 1);
1903 realobj = (char *)objp + obj_offset(cachep);
1904 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1905 realobj, size);
1906 print_objinfo(cachep, objp, 2);
1910 #endif
1912 #if DEBUG
1914 * slab_destroy_objs - destroy a slab and its objects
1915 * @cachep: cache pointer being destroyed
1916 * @slabp: slab pointer being destroyed
1918 * Call the registered destructor for each object in a slab that is being
1919 * destroyed.
1921 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1923 int i;
1924 for (i = 0; i < cachep->num; i++) {
1925 void *objp = index_to_obj(cachep, slabp, i);
1927 if (cachep->flags & SLAB_POISON) {
1928 #ifdef CONFIG_DEBUG_PAGEALLOC
1929 if (cachep->buffer_size % PAGE_SIZE == 0 &&
1930 OFF_SLAB(cachep))
1931 kernel_map_pages(virt_to_page(objp),
1932 cachep->buffer_size / PAGE_SIZE, 1);
1933 else
1934 check_poison_obj(cachep, objp);
1935 #else
1936 check_poison_obj(cachep, objp);
1937 #endif
1939 if (cachep->flags & SLAB_RED_ZONE) {
1940 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1941 slab_error(cachep, "start of a freed object "
1942 "was overwritten");
1943 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1944 slab_error(cachep, "end of a freed object "
1945 "was overwritten");
1949 #else
1950 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1953 #endif
1956 * slab_destroy - destroy and release all objects in a slab
1957 * @cachep: cache pointer being destroyed
1958 * @slabp: slab pointer being destroyed
1960 * Destroy all the objs in a slab, and release the mem back to the system.
1961 * Before calling the slab must have been unlinked from the cache. The
1962 * cache-lock is not held/needed.
1964 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1966 void *addr = slabp->s_mem - slabp->colouroff;
1968 slab_destroy_objs(cachep, slabp);
1969 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1970 struct slab_rcu *slab_rcu;
1972 slab_rcu = (struct slab_rcu *)slabp;
1973 slab_rcu->cachep = cachep;
1974 slab_rcu->addr = addr;
1975 call_rcu(&slab_rcu->head, kmem_rcu_free);
1976 } else {
1977 kmem_freepages(cachep, addr);
1978 if (OFF_SLAB(cachep))
1979 kmem_cache_free(cachep->slabp_cache, slabp);
1983 static void __kmem_cache_destroy(struct kmem_cache *cachep)
1985 int i;
1986 struct kmem_list3 *l3;
1988 for_each_online_cpu(i)
1989 kfree(cachep->array[i]);
1991 /* NUMA: free the list3 structures */
1992 for_each_online_node(i) {
1993 l3 = cachep->nodelists[i];
1994 if (l3) {
1995 kfree(l3->shared);
1996 free_alien_cache(l3->alien);
1997 kfree(l3);
2000 kmem_cache_free(&cache_cache, cachep);
2005 * calculate_slab_order - calculate size (page order) of slabs
2006 * @cachep: pointer to the cache that is being created
2007 * @size: size of objects to be created in this cache.
2008 * @align: required alignment for the objects.
2009 * @flags: slab allocation flags
2011 * Also calculates the number of objects per slab.
2013 * This could be made much more intelligent. For now, try to avoid using
2014 * high order pages for slabs. When the gfp() functions are more friendly
2015 * towards high-order requests, this should be changed.
2017 static size_t calculate_slab_order(struct kmem_cache *cachep,
2018 size_t size, size_t align, unsigned long flags)
2020 unsigned long offslab_limit;
2021 size_t left_over = 0;
2022 int gfporder;
2024 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2025 unsigned int num;
2026 size_t remainder;
2028 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2029 if (!num)
2030 continue;
2032 if (flags & CFLGS_OFF_SLAB) {
2034 * Max number of objs-per-slab for caches which
2035 * use off-slab slabs. Needed to avoid a possible
2036 * looping condition in cache_grow().
2038 offslab_limit = size - sizeof(struct slab);
2039 offslab_limit /= sizeof(kmem_bufctl_t);
2041 if (num > offslab_limit)
2042 break;
2045 /* Found something acceptable - save it away */
2046 cachep->num = num;
2047 cachep->gfporder = gfporder;
2048 left_over = remainder;
2051 * A VFS-reclaimable slab tends to have most allocations
2052 * as GFP_NOFS and we really don't want to have to be allocating
2053 * higher-order pages when we are unable to shrink dcache.
2055 if (flags & SLAB_RECLAIM_ACCOUNT)
2056 break;
2059 * Large number of objects is good, but very large slabs are
2060 * currently bad for the gfp()s.
2062 if (gfporder >= slab_break_gfp_order)
2063 break;
2066 * Acceptable internal fragmentation?
2068 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2069 break;
2071 return left_over;
2074 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep)
2076 if (g_cpucache_up == FULL)
2077 return enable_cpucache(cachep);
2079 if (g_cpucache_up == NONE) {
2081 * Note: the first kmem_cache_create must create the cache
2082 * that's used by kmalloc(24), otherwise the creation of
2083 * further caches will BUG().
2085 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2088 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2089 * the first cache, then we need to set up all its list3s,
2090 * otherwise the creation of further caches will BUG().
2092 set_up_list3s(cachep, SIZE_AC);
2093 if (INDEX_AC == INDEX_L3)
2094 g_cpucache_up = PARTIAL_L3;
2095 else
2096 g_cpucache_up = PARTIAL_AC;
2097 } else {
2098 cachep->array[smp_processor_id()] =
2099 kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
2101 if (g_cpucache_up == PARTIAL_AC) {
2102 set_up_list3s(cachep, SIZE_L3);
2103 g_cpucache_up = PARTIAL_L3;
2104 } else {
2105 int node;
2106 for_each_online_node(node) {
2107 cachep->nodelists[node] =
2108 kmalloc_node(sizeof(struct kmem_list3),
2109 GFP_KERNEL, node);
2110 BUG_ON(!cachep->nodelists[node]);
2111 kmem_list3_init(cachep->nodelists[node]);
2115 cachep->nodelists[numa_node_id()]->next_reap =
2116 jiffies + REAPTIMEOUT_LIST3 +
2117 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2119 cpu_cache_get(cachep)->avail = 0;
2120 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2121 cpu_cache_get(cachep)->batchcount = 1;
2122 cpu_cache_get(cachep)->touched = 0;
2123 cachep->batchcount = 1;
2124 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2125 return 0;
2129 * kmem_cache_create - Create a cache.
2130 * @name: A string which is used in /proc/slabinfo to identify this cache.
2131 * @size: The size of objects to be created in this cache.
2132 * @align: The required alignment for the objects.
2133 * @flags: SLAB flags
2134 * @ctor: A constructor for the objects.
2136 * Returns a ptr to the cache on success, NULL on failure.
2137 * Cannot be called within a int, but can be interrupted.
2138 * The @ctor is run when new pages are allocated by the cache.
2140 * @name must be valid until the cache is destroyed. This implies that
2141 * the module calling this has to destroy the cache before getting unloaded.
2143 * The flags are
2145 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2146 * to catch references to uninitialised memory.
2148 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2149 * for buffer overruns.
2151 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2152 * cacheline. This can be beneficial if you're counting cycles as closely
2153 * as davem.
2155 struct kmem_cache *
2156 kmem_cache_create (const char *name, size_t size, size_t align,
2157 unsigned long flags,
2158 void (*ctor)(struct kmem_cache *, void *))
2160 size_t left_over, slab_size, ralign;
2161 struct kmem_cache *cachep = NULL, *pc;
2164 * Sanity checks... these are all serious usage bugs.
2166 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
2167 size > KMALLOC_MAX_SIZE) {
2168 printk(KERN_ERR "%s: Early error in slab %s\n", __func__,
2169 name);
2170 BUG();
2174 * We use cache_chain_mutex to ensure a consistent view of
2175 * cpu_online_map as well. Please see cpuup_callback
2177 get_online_cpus();
2178 mutex_lock(&cache_chain_mutex);
2180 list_for_each_entry(pc, &cache_chain, next) {
2181 char tmp;
2182 int res;
2185 * This happens when the module gets unloaded and doesn't
2186 * destroy its slab cache and no-one else reuses the vmalloc
2187 * area of the module. Print a warning.
2189 res = probe_kernel_address(pc->name, tmp);
2190 if (res) {
2191 printk(KERN_ERR
2192 "SLAB: cache with size %d has lost its name\n",
2193 pc->buffer_size);
2194 continue;
2197 if (!strcmp(pc->name, name)) {
2198 printk(KERN_ERR
2199 "kmem_cache_create: duplicate cache %s\n", name);
2200 dump_stack();
2201 goto oops;
2205 #if DEBUG
2206 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2207 #if FORCED_DEBUG
2209 * Enable redzoning and last user accounting, except for caches with
2210 * large objects, if the increased size would increase the object size
2211 * above the next power of two: caches with object sizes just above a
2212 * power of two have a significant amount of internal fragmentation.
2214 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2215 2 * sizeof(unsigned long long)))
2216 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2217 if (!(flags & SLAB_DESTROY_BY_RCU))
2218 flags |= SLAB_POISON;
2219 #endif
2220 if (flags & SLAB_DESTROY_BY_RCU)
2221 BUG_ON(flags & SLAB_POISON);
2222 #endif
2224 * Always checks flags, a caller might be expecting debug support which
2225 * isn't available.
2227 BUG_ON(flags & ~CREATE_MASK);
2230 * Check that size is in terms of words. This is needed to avoid
2231 * unaligned accesses for some archs when redzoning is used, and makes
2232 * sure any on-slab bufctl's are also correctly aligned.
2234 if (size & (BYTES_PER_WORD - 1)) {
2235 size += (BYTES_PER_WORD - 1);
2236 size &= ~(BYTES_PER_WORD - 1);
2239 /* calculate the final buffer alignment: */
2241 /* 1) arch recommendation: can be overridden for debug */
2242 if (flags & SLAB_HWCACHE_ALIGN) {
2244 * Default alignment: as specified by the arch code. Except if
2245 * an object is really small, then squeeze multiple objects into
2246 * one cacheline.
2248 ralign = cache_line_size();
2249 while (size <= ralign / 2)
2250 ralign /= 2;
2251 } else {
2252 ralign = BYTES_PER_WORD;
2256 * Redzoning and user store require word alignment or possibly larger.
2257 * Note this will be overridden by architecture or caller mandated
2258 * alignment if either is greater than BYTES_PER_WORD.
2260 if (flags & SLAB_STORE_USER)
2261 ralign = BYTES_PER_WORD;
2263 if (flags & SLAB_RED_ZONE) {
2264 ralign = REDZONE_ALIGN;
2265 /* If redzoning, ensure that the second redzone is suitably
2266 * aligned, by adjusting the object size accordingly. */
2267 size += REDZONE_ALIGN - 1;
2268 size &= ~(REDZONE_ALIGN - 1);
2271 /* 2) arch mandated alignment */
2272 if (ralign < ARCH_SLAB_MINALIGN) {
2273 ralign = ARCH_SLAB_MINALIGN;
2275 /* 3) caller mandated alignment */
2276 if (ralign < align) {
2277 ralign = align;
2279 /* disable debug if necessary */
2280 if (ralign > __alignof__(unsigned long long))
2281 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2283 * 4) Store it.
2285 align = ralign;
2287 /* Get cache's description obj. */
2288 cachep = kmem_cache_zalloc(&cache_cache, GFP_KERNEL);
2289 if (!cachep)
2290 goto oops;
2292 #if DEBUG
2293 cachep->obj_size = size;
2296 * Both debugging options require word-alignment which is calculated
2297 * into align above.
2299 if (flags & SLAB_RED_ZONE) {
2300 /* add space for red zone words */
2301 cachep->obj_offset += sizeof(unsigned long long);
2302 size += 2 * sizeof(unsigned long long);
2304 if (flags & SLAB_STORE_USER) {
2305 /* user store requires one word storage behind the end of
2306 * the real object. But if the second red zone needs to be
2307 * aligned to 64 bits, we must allow that much space.
2309 if (flags & SLAB_RED_ZONE)
2310 size += REDZONE_ALIGN;
2311 else
2312 size += BYTES_PER_WORD;
2314 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2315 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2316 && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2317 cachep->obj_offset += PAGE_SIZE - size;
2318 size = PAGE_SIZE;
2320 #endif
2321 #endif
2324 * Determine if the slab management is 'on' or 'off' slab.
2325 * (bootstrapping cannot cope with offslab caches so don't do
2326 * it too early on.)
2328 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init)
2330 * Size is large, assume best to place the slab management obj
2331 * off-slab (should allow better packing of objs).
2333 flags |= CFLGS_OFF_SLAB;
2335 size = ALIGN(size, align);
2337 left_over = calculate_slab_order(cachep, size, align, flags);
2339 if (!cachep->num) {
2340 printk(KERN_ERR
2341 "kmem_cache_create: couldn't create cache %s.\n", name);
2342 kmem_cache_free(&cache_cache, cachep);
2343 cachep = NULL;
2344 goto oops;
2346 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2347 + sizeof(struct slab), align);
2350 * If the slab has been placed off-slab, and we have enough space then
2351 * move it on-slab. This is at the expense of any extra colouring.
2353 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2354 flags &= ~CFLGS_OFF_SLAB;
2355 left_over -= slab_size;
2358 if (flags & CFLGS_OFF_SLAB) {
2359 /* really off slab. No need for manual alignment */
2360 slab_size =
2361 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2364 cachep->colour_off = cache_line_size();
2365 /* Offset must be a multiple of the alignment. */
2366 if (cachep->colour_off < align)
2367 cachep->colour_off = align;
2368 cachep->colour = left_over / cachep->colour_off;
2369 cachep->slab_size = slab_size;
2370 cachep->flags = flags;
2371 cachep->gfpflags = 0;
2372 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2373 cachep->gfpflags |= GFP_DMA;
2374 cachep->buffer_size = size;
2375 cachep->reciprocal_buffer_size = reciprocal_value(size);
2377 if (flags & CFLGS_OFF_SLAB) {
2378 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2380 * This is a possibility for one of the malloc_sizes caches.
2381 * But since we go off slab only for object size greater than
2382 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2383 * this should not happen at all.
2384 * But leave a BUG_ON for some lucky dude.
2386 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2388 cachep->ctor = ctor;
2389 cachep->name = name;
2391 if (setup_cpu_cache(cachep)) {
2392 __kmem_cache_destroy(cachep);
2393 cachep = NULL;
2394 goto oops;
2397 /* cache setup completed, link it into the list */
2398 list_add(&cachep->next, &cache_chain);
2399 oops:
2400 if (!cachep && (flags & SLAB_PANIC))
2401 panic("kmem_cache_create(): failed to create slab `%s'\n",
2402 name);
2403 mutex_unlock(&cache_chain_mutex);
2404 put_online_cpus();
2405 return cachep;
2407 EXPORT_SYMBOL(kmem_cache_create);
2409 #if DEBUG
2410 static void check_irq_off(void)
2412 BUG_ON(!irqs_disabled());
2415 static void check_irq_on(void)
2417 BUG_ON(irqs_disabled());
2420 static void check_spinlock_acquired(struct kmem_cache *cachep)
2422 #ifdef CONFIG_SMP
2423 check_irq_off();
2424 assert_spin_locked(&cachep->nodelists[numa_node_id()]->list_lock);
2425 #endif
2428 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2430 #ifdef CONFIG_SMP
2431 check_irq_off();
2432 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2433 #endif
2436 #else
2437 #define check_irq_off() do { } while(0)
2438 #define check_irq_on() do { } while(0)
2439 #define check_spinlock_acquired(x) do { } while(0)
2440 #define check_spinlock_acquired_node(x, y) do { } while(0)
2441 #endif
2443 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2444 struct array_cache *ac,
2445 int force, int node);
2447 static void do_drain(void *arg)
2449 struct kmem_cache *cachep = arg;
2450 struct array_cache *ac;
2451 int node = numa_node_id();
2453 check_irq_off();
2454 ac = cpu_cache_get(cachep);
2455 spin_lock(&cachep->nodelists[node]->list_lock);
2456 free_block(cachep, ac->entry, ac->avail, node);
2457 spin_unlock(&cachep->nodelists[node]->list_lock);
2458 ac->avail = 0;
2461 static void drain_cpu_caches(struct kmem_cache *cachep)
2463 struct kmem_list3 *l3;
2464 int node;
2466 on_each_cpu(do_drain, cachep, 1, 1);
2467 check_irq_on();
2468 for_each_online_node(node) {
2469 l3 = cachep->nodelists[node];
2470 if (l3 && l3->alien)
2471 drain_alien_cache(cachep, l3->alien);
2474 for_each_online_node(node) {
2475 l3 = cachep->nodelists[node];
2476 if (l3)
2477 drain_array(cachep, l3, l3->shared, 1, node);
2482 * Remove slabs from the list of free slabs.
2483 * Specify the number of slabs to drain in tofree.
2485 * Returns the actual number of slabs released.
2487 static int drain_freelist(struct kmem_cache *cache,
2488 struct kmem_list3 *l3, int tofree)
2490 struct list_head *p;
2491 int nr_freed;
2492 struct slab *slabp;
2494 nr_freed = 0;
2495 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2497 spin_lock_irq(&l3->list_lock);
2498 p = l3->slabs_free.prev;
2499 if (p == &l3->slabs_free) {
2500 spin_unlock_irq(&l3->list_lock);
2501 goto out;
2504 slabp = list_entry(p, struct slab, list);
2505 #if DEBUG
2506 BUG_ON(slabp->inuse);
2507 #endif
2508 list_del(&slabp->list);
2510 * Safe to drop the lock. The slab is no longer linked
2511 * to the cache.
2513 l3->free_objects -= cache->num;
2514 spin_unlock_irq(&l3->list_lock);
2515 slab_destroy(cache, slabp);
2516 nr_freed++;
2518 out:
2519 return nr_freed;
2522 /* Called with cache_chain_mutex held to protect against cpu hotplug */
2523 static int __cache_shrink(struct kmem_cache *cachep)
2525 int ret = 0, i = 0;
2526 struct kmem_list3 *l3;
2528 drain_cpu_caches(cachep);
2530 check_irq_on();
2531 for_each_online_node(i) {
2532 l3 = cachep->nodelists[i];
2533 if (!l3)
2534 continue;
2536 drain_freelist(cachep, l3, l3->free_objects);
2538 ret += !list_empty(&l3->slabs_full) ||
2539 !list_empty(&l3->slabs_partial);
2541 return (ret ? 1 : 0);
2545 * kmem_cache_shrink - Shrink a cache.
2546 * @cachep: The cache to shrink.
2548 * Releases as many slabs as possible for a cache.
2549 * To help debugging, a zero exit status indicates all slabs were released.
2551 int kmem_cache_shrink(struct kmem_cache *cachep)
2553 int ret;
2554 BUG_ON(!cachep || in_interrupt());
2556 get_online_cpus();
2557 mutex_lock(&cache_chain_mutex);
2558 ret = __cache_shrink(cachep);
2559 mutex_unlock(&cache_chain_mutex);
2560 put_online_cpus();
2561 return ret;
2563 EXPORT_SYMBOL(kmem_cache_shrink);
2566 * kmem_cache_destroy - delete a cache
2567 * @cachep: the cache to destroy
2569 * Remove a &struct kmem_cache object from the slab cache.
2571 * It is expected this function will be called by a module when it is
2572 * unloaded. This will remove the cache completely, and avoid a duplicate
2573 * cache being allocated each time a module is loaded and unloaded, if the
2574 * module doesn't have persistent in-kernel storage across loads and unloads.
2576 * The cache must be empty before calling this function.
2578 * The caller must guarantee that noone will allocate memory from the cache
2579 * during the kmem_cache_destroy().
2581 void kmem_cache_destroy(struct kmem_cache *cachep)
2583 BUG_ON(!cachep || in_interrupt());
2585 /* Find the cache in the chain of caches. */
2586 get_online_cpus();
2587 mutex_lock(&cache_chain_mutex);
2589 * the chain is never empty, cache_cache is never destroyed
2591 list_del(&cachep->next);
2592 if (__cache_shrink(cachep)) {
2593 slab_error(cachep, "Can't free all objects");
2594 list_add(&cachep->next, &cache_chain);
2595 mutex_unlock(&cache_chain_mutex);
2596 put_online_cpus();
2597 return;
2600 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2601 synchronize_rcu();
2603 __kmem_cache_destroy(cachep);
2604 mutex_unlock(&cache_chain_mutex);
2605 put_online_cpus();
2607 EXPORT_SYMBOL(kmem_cache_destroy);
2610 * Get the memory for a slab management obj.
2611 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2612 * always come from malloc_sizes caches. The slab descriptor cannot
2613 * come from the same cache which is getting created because,
2614 * when we are searching for an appropriate cache for these
2615 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2616 * If we are creating a malloc_sizes cache here it would not be visible to
2617 * kmem_find_general_cachep till the initialization is complete.
2618 * Hence we cannot have slabp_cache same as the original cache.
2620 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2621 int colour_off, gfp_t local_flags,
2622 int nodeid)
2624 struct slab *slabp;
2626 if (OFF_SLAB(cachep)) {
2627 /* Slab management obj is off-slab. */
2628 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2629 local_flags & ~GFP_THISNODE, nodeid);
2630 if (!slabp)
2631 return NULL;
2632 } else {
2633 slabp = objp + colour_off;
2634 colour_off += cachep->slab_size;
2636 slabp->inuse = 0;
2637 slabp->colouroff = colour_off;
2638 slabp->s_mem = objp + colour_off;
2639 slabp->nodeid = nodeid;
2640 slabp->free = 0;
2641 return slabp;
2644 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2646 return (kmem_bufctl_t *) (slabp + 1);
2649 static void cache_init_objs(struct kmem_cache *cachep,
2650 struct slab *slabp)
2652 int i;
2654 for (i = 0; i < cachep->num; i++) {
2655 void *objp = index_to_obj(cachep, slabp, i);
2656 #if DEBUG
2657 /* need to poison the objs? */
2658 if (cachep->flags & SLAB_POISON)
2659 poison_obj(cachep, objp, POISON_FREE);
2660 if (cachep->flags & SLAB_STORE_USER)
2661 *dbg_userword(cachep, objp) = NULL;
2663 if (cachep->flags & SLAB_RED_ZONE) {
2664 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2665 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2668 * Constructors are not allowed to allocate memory from the same
2669 * cache which they are a constructor for. Otherwise, deadlock.
2670 * They must also be threaded.
2672 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2673 cachep->ctor(cachep, objp + obj_offset(cachep));
2675 if (cachep->flags & SLAB_RED_ZONE) {
2676 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2677 slab_error(cachep, "constructor overwrote the"
2678 " end of an object");
2679 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2680 slab_error(cachep, "constructor overwrote the"
2681 " start of an object");
2683 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2684 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2685 kernel_map_pages(virt_to_page(objp),
2686 cachep->buffer_size / PAGE_SIZE, 0);
2687 #else
2688 if (cachep->ctor)
2689 cachep->ctor(cachep, objp);
2690 #endif
2691 slab_bufctl(slabp)[i] = i + 1;
2693 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2696 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2698 if (CONFIG_ZONE_DMA_FLAG) {
2699 if (flags & GFP_DMA)
2700 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2701 else
2702 BUG_ON(cachep->gfpflags & GFP_DMA);
2706 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2707 int nodeid)
2709 void *objp = index_to_obj(cachep, slabp, slabp->free);
2710 kmem_bufctl_t next;
2712 slabp->inuse++;
2713 next = slab_bufctl(slabp)[slabp->free];
2714 #if DEBUG
2715 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2716 WARN_ON(slabp->nodeid != nodeid);
2717 #endif
2718 slabp->free = next;
2720 return objp;
2723 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2724 void *objp, int nodeid)
2726 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2728 #if DEBUG
2729 /* Verify that the slab belongs to the intended node */
2730 WARN_ON(slabp->nodeid != nodeid);
2732 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2733 printk(KERN_ERR "slab: double free detected in cache "
2734 "'%s', objp %p\n", cachep->name, objp);
2735 BUG();
2737 #endif
2738 slab_bufctl(slabp)[objnr] = slabp->free;
2739 slabp->free = objnr;
2740 slabp->inuse--;
2744 * Map pages beginning at addr to the given cache and slab. This is required
2745 * for the slab allocator to be able to lookup the cache and slab of a
2746 * virtual address for kfree, ksize, kmem_ptr_validate, and slab debugging.
2748 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2749 void *addr)
2751 int nr_pages;
2752 struct page *page;
2754 page = virt_to_page(addr);
2756 nr_pages = 1;
2757 if (likely(!PageCompound(page)))
2758 nr_pages <<= cache->gfporder;
2760 do {
2761 page_set_cache(page, cache);
2762 page_set_slab(page, slab);
2763 page++;
2764 } while (--nr_pages);
2768 * Grow (by 1) the number of slabs within a cache. This is called by
2769 * kmem_cache_alloc() when there are no active objs left in a cache.
2771 static int cache_grow(struct kmem_cache *cachep,
2772 gfp_t flags, int nodeid, void *objp)
2774 struct slab *slabp;
2775 size_t offset;
2776 gfp_t local_flags;
2777 struct kmem_list3 *l3;
2780 * Be lazy and only check for valid flags here, keeping it out of the
2781 * critical path in kmem_cache_alloc().
2783 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2784 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2786 /* Take the l3 list lock to change the colour_next on this node */
2787 check_irq_off();
2788 l3 = cachep->nodelists[nodeid];
2789 spin_lock(&l3->list_lock);
2791 /* Get colour for the slab, and cal the next value. */
2792 offset = l3->colour_next;
2793 l3->colour_next++;
2794 if (l3->colour_next >= cachep->colour)
2795 l3->colour_next = 0;
2796 spin_unlock(&l3->list_lock);
2798 offset *= cachep->colour_off;
2800 if (local_flags & __GFP_WAIT)
2801 local_irq_enable();
2804 * The test for missing atomic flag is performed here, rather than
2805 * the more obvious place, simply to reduce the critical path length
2806 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2807 * will eventually be caught here (where it matters).
2809 kmem_flagcheck(cachep, flags);
2812 * Get mem for the objs. Attempt to allocate a physical page from
2813 * 'nodeid'.
2815 if (!objp)
2816 objp = kmem_getpages(cachep, local_flags, nodeid);
2817 if (!objp)
2818 goto failed;
2820 /* Get slab management. */
2821 slabp = alloc_slabmgmt(cachep, objp, offset,
2822 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2823 if (!slabp)
2824 goto opps1;
2826 slab_map_pages(cachep, slabp, objp);
2828 cache_init_objs(cachep, slabp);
2830 if (local_flags & __GFP_WAIT)
2831 local_irq_disable();
2832 check_irq_off();
2833 spin_lock(&l3->list_lock);
2835 /* Make slab active. */
2836 list_add_tail(&slabp->list, &(l3->slabs_free));
2837 STATS_INC_GROWN(cachep);
2838 l3->free_objects += cachep->num;
2839 spin_unlock(&l3->list_lock);
2840 return 1;
2841 opps1:
2842 kmem_freepages(cachep, objp);
2843 failed:
2844 if (local_flags & __GFP_WAIT)
2845 local_irq_disable();
2846 return 0;
2849 #if DEBUG
2852 * Perform extra freeing checks:
2853 * - detect bad pointers.
2854 * - POISON/RED_ZONE checking
2856 static void kfree_debugcheck(const void *objp)
2858 if (!virt_addr_valid(objp)) {
2859 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2860 (unsigned long)objp);
2861 BUG();
2865 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2867 unsigned long long redzone1, redzone2;
2869 redzone1 = *dbg_redzone1(cache, obj);
2870 redzone2 = *dbg_redzone2(cache, obj);
2873 * Redzone is ok.
2875 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2876 return;
2878 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2879 slab_error(cache, "double free detected");
2880 else
2881 slab_error(cache, "memory outside object was overwritten");
2883 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2884 obj, redzone1, redzone2);
2887 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2888 void *caller)
2890 struct page *page;
2891 unsigned int objnr;
2892 struct slab *slabp;
2894 BUG_ON(virt_to_cache(objp) != cachep);
2896 objp -= obj_offset(cachep);
2897 kfree_debugcheck(objp);
2898 page = virt_to_head_page(objp);
2900 slabp = page_get_slab(page);
2902 if (cachep->flags & SLAB_RED_ZONE) {
2903 verify_redzone_free(cachep, objp);
2904 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2905 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2907 if (cachep->flags & SLAB_STORE_USER)
2908 *dbg_userword(cachep, objp) = caller;
2910 objnr = obj_to_index(cachep, slabp, objp);
2912 BUG_ON(objnr >= cachep->num);
2913 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2915 #ifdef CONFIG_DEBUG_SLAB_LEAK
2916 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2917 #endif
2918 if (cachep->flags & SLAB_POISON) {
2919 #ifdef CONFIG_DEBUG_PAGEALLOC
2920 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2921 store_stackinfo(cachep, objp, (unsigned long)caller);
2922 kernel_map_pages(virt_to_page(objp),
2923 cachep->buffer_size / PAGE_SIZE, 0);
2924 } else {
2925 poison_obj(cachep, objp, POISON_FREE);
2927 #else
2928 poison_obj(cachep, objp, POISON_FREE);
2929 #endif
2931 return objp;
2934 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
2936 kmem_bufctl_t i;
2937 int entries = 0;
2939 /* Check slab's freelist to see if this obj is there. */
2940 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2941 entries++;
2942 if (entries > cachep->num || i >= cachep->num)
2943 goto bad;
2945 if (entries != cachep->num - slabp->inuse) {
2946 bad:
2947 printk(KERN_ERR "slab: Internal list corruption detected in "
2948 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2949 cachep->name, cachep->num, slabp, slabp->inuse);
2950 for (i = 0;
2951 i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
2952 i++) {
2953 if (i % 16 == 0)
2954 printk("\n%03x:", i);
2955 printk(" %02x", ((unsigned char *)slabp)[i]);
2957 printk("\n");
2958 BUG();
2961 #else
2962 #define kfree_debugcheck(x) do { } while(0)
2963 #define cache_free_debugcheck(x,objp,z) (objp)
2964 #define check_slabp(x,y) do { } while(0)
2965 #endif
2967 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2969 int batchcount;
2970 struct kmem_list3 *l3;
2971 struct array_cache *ac;
2972 int node;
2974 retry:
2975 check_irq_off();
2976 node = numa_node_id();
2977 ac = cpu_cache_get(cachep);
2978 batchcount = ac->batchcount;
2979 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2981 * If there was little recent activity on this cache, then
2982 * perform only a partial refill. Otherwise we could generate
2983 * refill bouncing.
2985 batchcount = BATCHREFILL_LIMIT;
2987 l3 = cachep->nodelists[node];
2989 BUG_ON(ac->avail > 0 || !l3);
2990 spin_lock(&l3->list_lock);
2992 /* See if we can refill from the shared array */
2993 if (l3->shared && transfer_objects(ac, l3->shared, batchcount))
2994 goto alloc_done;
2996 while (batchcount > 0) {
2997 struct list_head *entry;
2998 struct slab *slabp;
2999 /* Get slab alloc is to come from. */
3000 entry = l3->slabs_partial.next;
3001 if (entry == &l3->slabs_partial) {
3002 l3->free_touched = 1;
3003 entry = l3->slabs_free.next;
3004 if (entry == &l3->slabs_free)
3005 goto must_grow;
3008 slabp = list_entry(entry, struct slab, list);
3009 check_slabp(cachep, slabp);
3010 check_spinlock_acquired(cachep);
3013 * The slab was either on partial or free list so
3014 * there must be at least one object available for
3015 * allocation.
3017 BUG_ON(slabp->inuse < 0 || slabp->inuse >= cachep->num);
3019 while (slabp->inuse < cachep->num && batchcount--) {
3020 STATS_INC_ALLOCED(cachep);
3021 STATS_INC_ACTIVE(cachep);
3022 STATS_SET_HIGH(cachep);
3024 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
3025 node);
3027 check_slabp(cachep, slabp);
3029 /* move slabp to correct slabp list: */
3030 list_del(&slabp->list);
3031 if (slabp->free == BUFCTL_END)
3032 list_add(&slabp->list, &l3->slabs_full);
3033 else
3034 list_add(&slabp->list, &l3->slabs_partial);
3037 must_grow:
3038 l3->free_objects -= ac->avail;
3039 alloc_done:
3040 spin_unlock(&l3->list_lock);
3042 if (unlikely(!ac->avail)) {
3043 int x;
3044 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3046 /* cache_grow can reenable interrupts, then ac could change. */
3047 ac = cpu_cache_get(cachep);
3048 if (!x && ac->avail == 0) /* no objects in sight? abort */
3049 return NULL;
3051 if (!ac->avail) /* objects refilled by interrupt? */
3052 goto retry;
3054 ac->touched = 1;
3055 return ac->entry[--ac->avail];
3058 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3059 gfp_t flags)
3061 might_sleep_if(flags & __GFP_WAIT);
3062 #if DEBUG
3063 kmem_flagcheck(cachep, flags);
3064 #endif
3067 #if DEBUG
3068 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3069 gfp_t flags, void *objp, void *caller)
3071 if (!objp)
3072 return objp;
3073 if (cachep->flags & SLAB_POISON) {
3074 #ifdef CONFIG_DEBUG_PAGEALLOC
3075 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3076 kernel_map_pages(virt_to_page(objp),
3077 cachep->buffer_size / PAGE_SIZE, 1);
3078 else
3079 check_poison_obj(cachep, objp);
3080 #else
3081 check_poison_obj(cachep, objp);
3082 #endif
3083 poison_obj(cachep, objp, POISON_INUSE);
3085 if (cachep->flags & SLAB_STORE_USER)
3086 *dbg_userword(cachep, objp) = caller;
3088 if (cachep->flags & SLAB_RED_ZONE) {
3089 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3090 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3091 slab_error(cachep, "double free, or memory outside"
3092 " object was overwritten");
3093 printk(KERN_ERR
3094 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3095 objp, *dbg_redzone1(cachep, objp),
3096 *dbg_redzone2(cachep, objp));
3098 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3099 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3101 #ifdef CONFIG_DEBUG_SLAB_LEAK
3103 struct slab *slabp;
3104 unsigned objnr;
3106 slabp = page_get_slab(virt_to_head_page(objp));
3107 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
3108 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3110 #endif
3111 objp += obj_offset(cachep);
3112 if (cachep->ctor && cachep->flags & SLAB_POISON)
3113 cachep->ctor(cachep, objp);
3114 #if ARCH_SLAB_MINALIGN
3115 if ((u32)objp & (ARCH_SLAB_MINALIGN-1)) {
3116 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3117 objp, ARCH_SLAB_MINALIGN);
3119 #endif
3120 return objp;
3122 #else
3123 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3124 #endif
3126 #ifdef CONFIG_FAILSLAB
3128 static struct failslab_attr {
3130 struct fault_attr attr;
3132 u32 ignore_gfp_wait;
3133 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3134 struct dentry *ignore_gfp_wait_file;
3135 #endif
3137 } failslab = {
3138 .attr = FAULT_ATTR_INITIALIZER,
3139 .ignore_gfp_wait = 1,
3142 static int __init setup_failslab(char *str)
3144 return setup_fault_attr(&failslab.attr, str);
3146 __setup("failslab=", setup_failslab);
3148 static int should_failslab(struct kmem_cache *cachep, gfp_t flags)
3150 if (cachep == &cache_cache)
3151 return 0;
3152 if (flags & __GFP_NOFAIL)
3153 return 0;
3154 if (failslab.ignore_gfp_wait && (flags & __GFP_WAIT))
3155 return 0;
3157 return should_fail(&failslab.attr, obj_size(cachep));
3160 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
3162 static int __init failslab_debugfs(void)
3164 mode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
3165 struct dentry *dir;
3166 int err;
3168 err = init_fault_attr_dentries(&failslab.attr, "failslab");
3169 if (err)
3170 return err;
3171 dir = failslab.attr.dentries.dir;
3173 failslab.ignore_gfp_wait_file =
3174 debugfs_create_bool("ignore-gfp-wait", mode, dir,
3175 &failslab.ignore_gfp_wait);
3177 if (!failslab.ignore_gfp_wait_file) {
3178 err = -ENOMEM;
3179 debugfs_remove(failslab.ignore_gfp_wait_file);
3180 cleanup_fault_attr_dentries(&failslab.attr);
3183 return err;
3186 late_initcall(failslab_debugfs);
3188 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
3190 #else /* CONFIG_FAILSLAB */
3192 static inline int should_failslab(struct kmem_cache *cachep, gfp_t flags)
3194 return 0;
3197 #endif /* CONFIG_FAILSLAB */
3199 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3201 void *objp;
3202 struct array_cache *ac;
3204 check_irq_off();
3206 ac = cpu_cache_get(cachep);
3207 if (likely(ac->avail)) {
3208 STATS_INC_ALLOCHIT(cachep);
3209 ac->touched = 1;
3210 objp = ac->entry[--ac->avail];
3211 } else {
3212 STATS_INC_ALLOCMISS(cachep);
3213 objp = cache_alloc_refill(cachep, flags);
3215 return objp;
3218 #ifdef CONFIG_NUMA
3220 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3222 * If we are in_interrupt, then process context, including cpusets and
3223 * mempolicy, may not apply and should not be used for allocation policy.
3225 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3227 int nid_alloc, nid_here;
3229 if (in_interrupt() || (flags & __GFP_THISNODE))
3230 return NULL;
3231 nid_alloc = nid_here = numa_node_id();
3232 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3233 nid_alloc = cpuset_mem_spread_node();
3234 else if (current->mempolicy)
3235 nid_alloc = slab_node(current->mempolicy);
3236 if (nid_alloc != nid_here)
3237 return ____cache_alloc_node(cachep, flags, nid_alloc);
3238 return NULL;
3242 * Fallback function if there was no memory available and no objects on a
3243 * certain node and fall back is permitted. First we scan all the
3244 * available nodelists for available objects. If that fails then we
3245 * perform an allocation without specifying a node. This allows the page
3246 * allocator to do its reclaim / fallback magic. We then insert the
3247 * slab into the proper nodelist and then allocate from it.
3249 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3251 struct zonelist *zonelist;
3252 gfp_t local_flags;
3253 struct zoneref *z;
3254 struct zone *zone;
3255 enum zone_type high_zoneidx = gfp_zone(flags);
3256 void *obj = NULL;
3257 int nid;
3259 if (flags & __GFP_THISNODE)
3260 return NULL;
3262 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
3263 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3265 retry:
3267 * Look through allowed nodes for objects available
3268 * from existing per node queues.
3270 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3271 nid = zone_to_nid(zone);
3273 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3274 cache->nodelists[nid] &&
3275 cache->nodelists[nid]->free_objects) {
3276 obj = ____cache_alloc_node(cache,
3277 flags | GFP_THISNODE, nid);
3278 if (obj)
3279 break;
3283 if (!obj) {
3285 * This allocation will be performed within the constraints
3286 * of the current cpuset / memory policy requirements.
3287 * We may trigger various forms of reclaim on the allowed
3288 * set and go into memory reserves if necessary.
3290 if (local_flags & __GFP_WAIT)
3291 local_irq_enable();
3292 kmem_flagcheck(cache, flags);
3293 obj = kmem_getpages(cache, local_flags, -1);
3294 if (local_flags & __GFP_WAIT)
3295 local_irq_disable();
3296 if (obj) {
3298 * Insert into the appropriate per node queues
3300 nid = page_to_nid(virt_to_page(obj));
3301 if (cache_grow(cache, flags, nid, obj)) {
3302 obj = ____cache_alloc_node(cache,
3303 flags | GFP_THISNODE, nid);
3304 if (!obj)
3306 * Another processor may allocate the
3307 * objects in the slab since we are
3308 * not holding any locks.
3310 goto retry;
3311 } else {
3312 /* cache_grow already freed obj */
3313 obj = NULL;
3317 return obj;
3321 * A interface to enable slab creation on nodeid
3323 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3324 int nodeid)
3326 struct list_head *entry;
3327 struct slab *slabp;
3328 struct kmem_list3 *l3;
3329 void *obj;
3330 int x;
3332 l3 = cachep->nodelists[nodeid];
3333 BUG_ON(!l3);
3335 retry:
3336 check_irq_off();
3337 spin_lock(&l3->list_lock);
3338 entry = l3->slabs_partial.next;
3339 if (entry == &l3->slabs_partial) {
3340 l3->free_touched = 1;
3341 entry = l3->slabs_free.next;
3342 if (entry == &l3->slabs_free)
3343 goto must_grow;
3346 slabp = list_entry(entry, struct slab, list);
3347 check_spinlock_acquired_node(cachep, nodeid);
3348 check_slabp(cachep, slabp);
3350 STATS_INC_NODEALLOCS(cachep);
3351 STATS_INC_ACTIVE(cachep);
3352 STATS_SET_HIGH(cachep);
3354 BUG_ON(slabp->inuse == cachep->num);
3356 obj = slab_get_obj(cachep, slabp, nodeid);
3357 check_slabp(cachep, slabp);
3358 l3->free_objects--;
3359 /* move slabp to correct slabp list: */
3360 list_del(&slabp->list);
3362 if (slabp->free == BUFCTL_END)
3363 list_add(&slabp->list, &l3->slabs_full);
3364 else
3365 list_add(&slabp->list, &l3->slabs_partial);
3367 spin_unlock(&l3->list_lock);
3368 goto done;
3370 must_grow:
3371 spin_unlock(&l3->list_lock);
3372 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3373 if (x)
3374 goto retry;
3376 return fallback_alloc(cachep, flags);
3378 done:
3379 return obj;
3383 * kmem_cache_alloc_node - Allocate an object on the specified node
3384 * @cachep: The cache to allocate from.
3385 * @flags: See kmalloc().
3386 * @nodeid: node number of the target node.
3387 * @caller: return address of caller, used for debug information
3389 * Identical to kmem_cache_alloc but it will allocate memory on the given
3390 * node, which can improve the performance for cpu bound structures.
3392 * Fallback to other node is possible if __GFP_THISNODE is not set.
3394 static __always_inline void *
3395 __cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3396 void *caller)
3398 unsigned long save_flags;
3399 void *ptr;
3401 if (should_failslab(cachep, flags))
3402 return NULL;
3404 cache_alloc_debugcheck_before(cachep, flags);
3405 local_irq_save(save_flags);
3407 if (unlikely(nodeid == -1))
3408 nodeid = numa_node_id();
3410 if (unlikely(!cachep->nodelists[nodeid])) {
3411 /* Node not bootstrapped yet */
3412 ptr = fallback_alloc(cachep, flags);
3413 goto out;
3416 if (nodeid == numa_node_id()) {
3418 * Use the locally cached objects if possible.
3419 * However ____cache_alloc does not allow fallback
3420 * to other nodes. It may fail while we still have
3421 * objects on other nodes available.
3423 ptr = ____cache_alloc(cachep, flags);
3424 if (ptr)
3425 goto out;
3427 /* ___cache_alloc_node can fall back to other nodes */
3428 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3429 out:
3430 local_irq_restore(save_flags);
3431 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3433 if (unlikely((flags & __GFP_ZERO) && ptr))
3434 memset(ptr, 0, obj_size(cachep));
3436 return ptr;
3439 static __always_inline void *
3440 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3442 void *objp;
3444 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3445 objp = alternate_node_alloc(cache, flags);
3446 if (objp)
3447 goto out;
3449 objp = ____cache_alloc(cache, flags);
3452 * We may just have run out of memory on the local node.
3453 * ____cache_alloc_node() knows how to locate memory on other nodes
3455 if (!objp)
3456 objp = ____cache_alloc_node(cache, flags, numa_node_id());
3458 out:
3459 return objp;
3461 #else
3463 static __always_inline void *
3464 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3466 return ____cache_alloc(cachep, flags);
3469 #endif /* CONFIG_NUMA */
3471 static __always_inline void *
3472 __cache_alloc(struct kmem_cache *cachep, gfp_t flags, void *caller)
3474 unsigned long save_flags;
3475 void *objp;
3477 if (should_failslab(cachep, flags))
3478 return NULL;
3480 cache_alloc_debugcheck_before(cachep, flags);
3481 local_irq_save(save_flags);
3482 objp = __do_cache_alloc(cachep, flags);
3483 local_irq_restore(save_flags);
3484 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3485 prefetchw(objp);
3487 if (unlikely((flags & __GFP_ZERO) && objp))
3488 memset(objp, 0, obj_size(cachep));
3490 return objp;
3494 * Caller needs to acquire correct kmem_list's list_lock
3496 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3497 int node)
3499 int i;
3500 struct kmem_list3 *l3;
3502 for (i = 0; i < nr_objects; i++) {
3503 void *objp = objpp[i];
3504 struct slab *slabp;
3506 slabp = virt_to_slab(objp);
3507 l3 = cachep->nodelists[node];
3508 list_del(&slabp->list);
3509 check_spinlock_acquired_node(cachep, node);
3510 check_slabp(cachep, slabp);
3511 slab_put_obj(cachep, slabp, objp, node);
3512 STATS_DEC_ACTIVE(cachep);
3513 l3->free_objects++;
3514 check_slabp(cachep, slabp);
3516 /* fixup slab chains */
3517 if (slabp->inuse == 0) {
3518 if (l3->free_objects > l3->free_limit) {
3519 l3->free_objects -= cachep->num;
3520 /* No need to drop any previously held
3521 * lock here, even if we have a off-slab slab
3522 * descriptor it is guaranteed to come from
3523 * a different cache, refer to comments before
3524 * alloc_slabmgmt.
3526 slab_destroy(cachep, slabp);
3527 } else {
3528 list_add(&slabp->list, &l3->slabs_free);
3530 } else {
3531 /* Unconditionally move a slab to the end of the
3532 * partial list on free - maximum time for the
3533 * other objects to be freed, too.
3535 list_add_tail(&slabp->list, &l3->slabs_partial);
3540 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3542 int batchcount;
3543 struct kmem_list3 *l3;
3544 int node = numa_node_id();
3546 batchcount = ac->batchcount;
3547 #if DEBUG
3548 BUG_ON(!batchcount || batchcount > ac->avail);
3549 #endif
3550 check_irq_off();
3551 l3 = cachep->nodelists[node];
3552 spin_lock(&l3->list_lock);
3553 if (l3->shared) {
3554 struct array_cache *shared_array = l3->shared;
3555 int max = shared_array->limit - shared_array->avail;
3556 if (max) {
3557 if (batchcount > max)
3558 batchcount = max;
3559 memcpy(&(shared_array->entry[shared_array->avail]),
3560 ac->entry, sizeof(void *) * batchcount);
3561 shared_array->avail += batchcount;
3562 goto free_done;
3566 free_block(cachep, ac->entry, batchcount, node);
3567 free_done:
3568 #if STATS
3570 int i = 0;
3571 struct list_head *p;
3573 p = l3->slabs_free.next;
3574 while (p != &(l3->slabs_free)) {
3575 struct slab *slabp;
3577 slabp = list_entry(p, struct slab, list);
3578 BUG_ON(slabp->inuse);
3580 i++;
3581 p = p->next;
3583 STATS_SET_FREEABLE(cachep, i);
3585 #endif
3586 spin_unlock(&l3->list_lock);
3587 ac->avail -= batchcount;
3588 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3592 * Release an obj back to its cache. If the obj has a constructed state, it must
3593 * be in this state _before_ it is released. Called with disabled ints.
3595 static inline void __cache_free(struct kmem_cache *cachep, void *objp)
3597 struct array_cache *ac = cpu_cache_get(cachep);
3599 check_irq_off();
3600 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3603 * Skip calling cache_free_alien() when the platform is not numa.
3604 * This will avoid cache misses that happen while accessing slabp (which
3605 * is per page memory reference) to get nodeid. Instead use a global
3606 * variable to skip the call, which is mostly likely to be present in
3607 * the cache.
3609 if (numa_platform && cache_free_alien(cachep, objp))
3610 return;
3612 if (likely(ac->avail < ac->limit)) {
3613 STATS_INC_FREEHIT(cachep);
3614 ac->entry[ac->avail++] = objp;
3615 return;
3616 } else {
3617 STATS_INC_FREEMISS(cachep);
3618 cache_flusharray(cachep, ac);
3619 ac->entry[ac->avail++] = objp;
3624 * kmem_cache_alloc - Allocate an object
3625 * @cachep: The cache to allocate from.
3626 * @flags: See kmalloc().
3628 * Allocate an object from this cache. The flags are only relevant
3629 * if the cache has no available objects.
3631 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3633 void *ret = __cache_alloc(cachep, flags, __builtin_return_address(0));
3635 kmemtrace_mark_alloc(KMEMTRACE_TYPE_CACHE, _RET_IP_, ret,
3636 obj_size(cachep), cachep->buffer_size, flags);
3638 return ret;
3640 EXPORT_SYMBOL(kmem_cache_alloc);
3642 #ifdef CONFIG_KMEMTRACE
3643 void *kmem_cache_alloc_notrace(struct kmem_cache *cachep, gfp_t flags)
3645 return __cache_alloc(cachep, flags, __builtin_return_address(0));
3647 EXPORT_SYMBOL(kmem_cache_alloc_notrace);
3648 #endif
3651 * kmem_ptr_validate - check if an untrusted pointer might be a slab entry.
3652 * @cachep: the cache we're checking against
3653 * @ptr: pointer to validate
3655 * This verifies that the untrusted pointer looks sane;
3656 * it is _not_ a guarantee that the pointer is actually
3657 * part of the slab cache in question, but it at least
3658 * validates that the pointer can be dereferenced and
3659 * looks half-way sane.
3661 * Currently only used for dentry validation.
3663 int kmem_ptr_validate(struct kmem_cache *cachep, const void *ptr)
3665 unsigned long addr = (unsigned long)ptr;
3666 unsigned long min_addr = PAGE_OFFSET;
3667 unsigned long align_mask = BYTES_PER_WORD - 1;
3668 unsigned long size = cachep->buffer_size;
3669 struct page *page;
3671 if (unlikely(addr < min_addr))
3672 goto out;
3673 if (unlikely(addr > (unsigned long)high_memory - size))
3674 goto out;
3675 if (unlikely(addr & align_mask))
3676 goto out;
3677 if (unlikely(!kern_addr_valid(addr)))
3678 goto out;
3679 if (unlikely(!kern_addr_valid(addr + size - 1)))
3680 goto out;
3681 page = virt_to_page(ptr);
3682 if (unlikely(!PageSlab(page)))
3683 goto out;
3684 if (unlikely(page_get_cache(page) != cachep))
3685 goto out;
3686 return 1;
3687 out:
3688 return 0;
3691 #ifdef CONFIG_NUMA
3692 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3694 void *ret = __cache_alloc_node(cachep, flags, nodeid,
3695 __builtin_return_address(0));
3697 kmemtrace_mark_alloc_node(KMEMTRACE_TYPE_CACHE, _RET_IP_, ret,
3698 obj_size(cachep), cachep->buffer_size,
3699 flags, nodeid);
3701 return ret;
3703 EXPORT_SYMBOL(kmem_cache_alloc_node);
3705 #ifdef CONFIG_KMEMTRACE
3706 void *kmem_cache_alloc_node_notrace(struct kmem_cache *cachep,
3707 gfp_t flags,
3708 int nodeid)
3710 return __cache_alloc_node(cachep, flags, nodeid,
3711 __builtin_return_address(0));
3713 EXPORT_SYMBOL(kmem_cache_alloc_node_notrace);
3714 #endif
3716 static __always_inline void *
3717 __do_kmalloc_node(size_t size, gfp_t flags, int node, void *caller)
3719 struct kmem_cache *cachep;
3720 void *ret;
3722 cachep = kmem_find_general_cachep(size, flags);
3723 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3724 return cachep;
3725 ret = kmem_cache_alloc_node_notrace(cachep, flags, node);
3727 kmemtrace_mark_alloc_node(KMEMTRACE_TYPE_KMALLOC,
3728 (unsigned long) caller, ret,
3729 size, cachep->buffer_size, flags, node);
3731 return ret;
3734 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_KMEMTRACE)
3735 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3737 return __do_kmalloc_node(size, flags, node,
3738 __builtin_return_address(0));
3740 EXPORT_SYMBOL(__kmalloc_node);
3742 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3743 int node, void *caller)
3745 return __do_kmalloc_node(size, flags, node, caller);
3747 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3748 #else
3749 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3751 return __do_kmalloc_node(size, flags, node, NULL);
3753 EXPORT_SYMBOL(__kmalloc_node);
3754 #endif /* CONFIG_DEBUG_SLAB */
3755 #endif /* CONFIG_NUMA */
3758 * __do_kmalloc - allocate memory
3759 * @size: how many bytes of memory are required.
3760 * @flags: the type of memory to allocate (see kmalloc).
3761 * @caller: function caller for debug tracking of the caller
3763 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3764 void *caller)
3766 struct kmem_cache *cachep;
3767 void *ret;
3769 /* If you want to save a few bytes .text space: replace
3770 * __ with kmem_.
3771 * Then kmalloc uses the uninlined functions instead of the inline
3772 * functions.
3774 cachep = __find_general_cachep(size, flags);
3775 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3776 return cachep;
3777 ret = __cache_alloc(cachep, flags, caller);
3779 kmemtrace_mark_alloc(KMEMTRACE_TYPE_KMALLOC,
3780 (unsigned long) caller, ret,
3781 size, cachep->buffer_size, flags);
3783 return ret;
3787 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_KMEMTRACE)
3788 void *__kmalloc(size_t size, gfp_t flags)
3790 return __do_kmalloc(size, flags, __builtin_return_address(0));
3792 EXPORT_SYMBOL(__kmalloc);
3794 void *__kmalloc_track_caller(size_t size, gfp_t flags, void *caller)
3796 return __do_kmalloc(size, flags, caller);
3798 EXPORT_SYMBOL(__kmalloc_track_caller);
3800 #else
3801 void *__kmalloc(size_t size, gfp_t flags)
3803 return __do_kmalloc(size, flags, NULL);
3805 EXPORT_SYMBOL(__kmalloc);
3806 #endif
3809 * kmem_cache_free - Deallocate an object
3810 * @cachep: The cache the allocation was from.
3811 * @objp: The previously allocated object.
3813 * Free an object which was previously allocated from this
3814 * cache.
3816 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3818 unsigned long flags;
3820 local_irq_save(flags);
3821 debug_check_no_locks_freed(objp, obj_size(cachep));
3822 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3823 debug_check_no_obj_freed(objp, obj_size(cachep));
3824 __cache_free(cachep, objp);
3825 local_irq_restore(flags);
3827 kmemtrace_mark_free(KMEMTRACE_TYPE_CACHE, _RET_IP_, objp);
3829 EXPORT_SYMBOL(kmem_cache_free);
3832 * kfree - free previously allocated memory
3833 * @objp: pointer returned by kmalloc.
3835 * If @objp is NULL, no operation is performed.
3837 * Don't free memory not originally allocated by kmalloc()
3838 * or you will run into trouble.
3840 void kfree(const void *objp)
3842 struct kmem_cache *c;
3843 unsigned long flags;
3845 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3846 return;
3847 local_irq_save(flags);
3848 kfree_debugcheck(objp);
3849 c = virt_to_cache(objp);
3850 debug_check_no_locks_freed(objp, obj_size(c));
3851 debug_check_no_obj_freed(objp, obj_size(c));
3852 __cache_free(c, (void *)objp);
3853 local_irq_restore(flags);
3855 kmemtrace_mark_free(KMEMTRACE_TYPE_KMALLOC, _RET_IP_, objp);
3857 EXPORT_SYMBOL(kfree);
3859 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3861 return obj_size(cachep);
3863 EXPORT_SYMBOL(kmem_cache_size);
3865 const char *kmem_cache_name(struct kmem_cache *cachep)
3867 return cachep->name;
3869 EXPORT_SYMBOL_GPL(kmem_cache_name);
3872 * This initializes kmem_list3 or resizes various caches for all nodes.
3874 static int alloc_kmemlist(struct kmem_cache *cachep)
3876 int node;
3877 struct kmem_list3 *l3;
3878 struct array_cache *new_shared;
3879 struct array_cache **new_alien = NULL;
3881 for_each_online_node(node) {
3883 if (use_alien_caches) {
3884 new_alien = alloc_alien_cache(node, cachep->limit);
3885 if (!new_alien)
3886 goto fail;
3889 new_shared = NULL;
3890 if (cachep->shared) {
3891 new_shared = alloc_arraycache(node,
3892 cachep->shared*cachep->batchcount,
3893 0xbaadf00d);
3894 if (!new_shared) {
3895 free_alien_cache(new_alien);
3896 goto fail;
3900 l3 = cachep->nodelists[node];
3901 if (l3) {
3902 struct array_cache *shared = l3->shared;
3904 spin_lock_irq(&l3->list_lock);
3906 if (shared)
3907 free_block(cachep, shared->entry,
3908 shared->avail, node);
3910 l3->shared = new_shared;
3911 if (!l3->alien) {
3912 l3->alien = new_alien;
3913 new_alien = NULL;
3915 l3->free_limit = (1 + nr_cpus_node(node)) *
3916 cachep->batchcount + cachep->num;
3917 spin_unlock_irq(&l3->list_lock);
3918 kfree(shared);
3919 free_alien_cache(new_alien);
3920 continue;
3922 l3 = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, node);
3923 if (!l3) {
3924 free_alien_cache(new_alien);
3925 kfree(new_shared);
3926 goto fail;
3929 kmem_list3_init(l3);
3930 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3931 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3932 l3->shared = new_shared;
3933 l3->alien = new_alien;
3934 l3->free_limit = (1 + nr_cpus_node(node)) *
3935 cachep->batchcount + cachep->num;
3936 cachep->nodelists[node] = l3;
3938 return 0;
3940 fail:
3941 if (!cachep->next.next) {
3942 /* Cache is not active yet. Roll back what we did */
3943 node--;
3944 while (node >= 0) {
3945 if (cachep->nodelists[node]) {
3946 l3 = cachep->nodelists[node];
3948 kfree(l3->shared);
3949 free_alien_cache(l3->alien);
3950 kfree(l3);
3951 cachep->nodelists[node] = NULL;
3953 node--;
3956 return -ENOMEM;
3959 struct ccupdate_struct {
3960 struct kmem_cache *cachep;
3961 struct array_cache *new[NR_CPUS];
3964 static void do_ccupdate_local(void *info)
3966 struct ccupdate_struct *new = info;
3967 struct array_cache *old;
3969 check_irq_off();
3970 old = cpu_cache_get(new->cachep);
3972 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3973 new->new[smp_processor_id()] = old;
3976 /* Always called with the cache_chain_mutex held */
3977 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3978 int batchcount, int shared)
3980 struct ccupdate_struct *new;
3981 int i;
3983 new = kzalloc(sizeof(*new), GFP_KERNEL);
3984 if (!new)
3985 return -ENOMEM;
3987 for_each_online_cpu(i) {
3988 new->new[i] = alloc_arraycache(cpu_to_node(i), limit,
3989 batchcount);
3990 if (!new->new[i]) {
3991 for (i--; i >= 0; i--)
3992 kfree(new->new[i]);
3993 kfree(new);
3994 return -ENOMEM;
3997 new->cachep = cachep;
3999 on_each_cpu(do_ccupdate_local, (void *)new, 1, 1);
4001 check_irq_on();
4002 cachep->batchcount = batchcount;
4003 cachep->limit = limit;
4004 cachep->shared = shared;
4006 for_each_online_cpu(i) {
4007 struct array_cache *ccold = new->new[i];
4008 if (!ccold)
4009 continue;
4010 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
4011 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
4012 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
4013 kfree(ccold);
4015 kfree(new);
4016 return alloc_kmemlist(cachep);
4019 /* Called with cache_chain_mutex held always */
4020 static int enable_cpucache(struct kmem_cache *cachep)
4022 int err;
4023 int limit, shared;
4026 * The head array serves three purposes:
4027 * - create a LIFO ordering, i.e. return objects that are cache-warm
4028 * - reduce the number of spinlock operations.
4029 * - reduce the number of linked list operations on the slab and
4030 * bufctl chains: array operations are cheaper.
4031 * The numbers are guessed, we should auto-tune as described by
4032 * Bonwick.
4034 if (cachep->buffer_size > 131072)
4035 limit = 1;
4036 else if (cachep->buffer_size > PAGE_SIZE)
4037 limit = 8;
4038 else if (cachep->buffer_size > 1024)
4039 limit = 24;
4040 else if (cachep->buffer_size > 256)
4041 limit = 54;
4042 else
4043 limit = 120;
4046 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4047 * allocation behaviour: Most allocs on one cpu, most free operations
4048 * on another cpu. For these cases, an efficient object passing between
4049 * cpus is necessary. This is provided by a shared array. The array
4050 * replaces Bonwick's magazine layer.
4051 * On uniprocessor, it's functionally equivalent (but less efficient)
4052 * to a larger limit. Thus disabled by default.
4054 shared = 0;
4055 if (cachep->buffer_size <= PAGE_SIZE && num_possible_cpus() > 1)
4056 shared = 8;
4058 #if DEBUG
4060 * With debugging enabled, large batchcount lead to excessively long
4061 * periods with disabled local interrupts. Limit the batchcount
4063 if (limit > 32)
4064 limit = 32;
4065 #endif
4066 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared);
4067 if (err)
4068 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4069 cachep->name, -err);
4070 return err;
4074 * Drain an array if it contains any elements taking the l3 lock only if
4075 * necessary. Note that the l3 listlock also protects the array_cache
4076 * if drain_array() is used on the shared array.
4078 void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
4079 struct array_cache *ac, int force, int node)
4081 int tofree;
4083 if (!ac || !ac->avail)
4084 return;
4085 if (ac->touched && !force) {
4086 ac->touched = 0;
4087 } else {
4088 spin_lock_irq(&l3->list_lock);
4089 if (ac->avail) {
4090 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4091 if (tofree > ac->avail)
4092 tofree = (ac->avail + 1) / 2;
4093 free_block(cachep, ac->entry, tofree, node);
4094 ac->avail -= tofree;
4095 memmove(ac->entry, &(ac->entry[tofree]),
4096 sizeof(void *) * ac->avail);
4098 spin_unlock_irq(&l3->list_lock);
4103 * cache_reap - Reclaim memory from caches.
4104 * @w: work descriptor
4106 * Called from workqueue/eventd every few seconds.
4107 * Purpose:
4108 * - clear the per-cpu caches for this CPU.
4109 * - return freeable pages to the main free memory pool.
4111 * If we cannot acquire the cache chain mutex then just give up - we'll try
4112 * again on the next iteration.
4114 static void cache_reap(struct work_struct *w)
4116 struct kmem_cache *searchp;
4117 struct kmem_list3 *l3;
4118 int node = numa_node_id();
4119 struct delayed_work *work =
4120 container_of(w, struct delayed_work, work);
4122 if (!mutex_trylock(&cache_chain_mutex))
4123 /* Give up. Setup the next iteration. */
4124 goto out;
4126 list_for_each_entry(searchp, &cache_chain, next) {
4127 check_irq_on();
4130 * We only take the l3 lock if absolutely necessary and we
4131 * have established with reasonable certainty that
4132 * we can do some work if the lock was obtained.
4134 l3 = searchp->nodelists[node];
4136 reap_alien(searchp, l3);
4138 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4141 * These are racy checks but it does not matter
4142 * if we skip one check or scan twice.
4144 if (time_after(l3->next_reap, jiffies))
4145 goto next;
4147 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4149 drain_array(searchp, l3, l3->shared, 0, node);
4151 if (l3->free_touched)
4152 l3->free_touched = 0;
4153 else {
4154 int freed;
4156 freed = drain_freelist(searchp, l3, (l3->free_limit +
4157 5 * searchp->num - 1) / (5 * searchp->num));
4158 STATS_ADD_REAPED(searchp, freed);
4160 next:
4161 cond_resched();
4163 check_irq_on();
4164 mutex_unlock(&cache_chain_mutex);
4165 next_reap_node();
4166 out:
4167 /* Set up the next iteration */
4168 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4171 #ifdef CONFIG_SLABINFO
4173 static void print_slabinfo_header(struct seq_file *m)
4176 * Output format version, so at least we can change it
4177 * without _too_ many complaints.
4179 #if STATS
4180 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
4181 #else
4182 seq_puts(m, "slabinfo - version: 2.1\n");
4183 #endif
4184 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4185 "<objperslab> <pagesperslab>");
4186 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4187 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4188 #if STATS
4189 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
4190 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
4191 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
4192 #endif
4193 seq_putc(m, '\n');
4196 static void *s_start(struct seq_file *m, loff_t *pos)
4198 loff_t n = *pos;
4200 mutex_lock(&cache_chain_mutex);
4201 if (!n)
4202 print_slabinfo_header(m);
4204 return seq_list_start(&cache_chain, *pos);
4207 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4209 return seq_list_next(p, &cache_chain, pos);
4212 static void s_stop(struct seq_file *m, void *p)
4214 mutex_unlock(&cache_chain_mutex);
4217 static int s_show(struct seq_file *m, void *p)
4219 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4220 struct slab *slabp;
4221 unsigned long active_objs;
4222 unsigned long num_objs;
4223 unsigned long active_slabs = 0;
4224 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4225 const char *name;
4226 char *error = NULL;
4227 int node;
4228 struct kmem_list3 *l3;
4230 active_objs = 0;
4231 num_slabs = 0;
4232 for_each_online_node(node) {
4233 l3 = cachep->nodelists[node];
4234 if (!l3)
4235 continue;
4237 check_irq_on();
4238 spin_lock_irq(&l3->list_lock);
4240 list_for_each_entry(slabp, &l3->slabs_full, list) {
4241 if (slabp->inuse != cachep->num && !error)
4242 error = "slabs_full accounting error";
4243 active_objs += cachep->num;
4244 active_slabs++;
4246 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4247 if (slabp->inuse == cachep->num && !error)
4248 error = "slabs_partial inuse accounting error";
4249 if (!slabp->inuse && !error)
4250 error = "slabs_partial/inuse accounting error";
4251 active_objs += slabp->inuse;
4252 active_slabs++;
4254 list_for_each_entry(slabp, &l3->slabs_free, list) {
4255 if (slabp->inuse && !error)
4256 error = "slabs_free/inuse accounting error";
4257 num_slabs++;
4259 free_objects += l3->free_objects;
4260 if (l3->shared)
4261 shared_avail += l3->shared->avail;
4263 spin_unlock_irq(&l3->list_lock);
4265 num_slabs += active_slabs;
4266 num_objs = num_slabs * cachep->num;
4267 if (num_objs - active_objs != free_objects && !error)
4268 error = "free_objects accounting error";
4270 name = cachep->name;
4271 if (error)
4272 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4274 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
4275 name, active_objs, num_objs, cachep->buffer_size,
4276 cachep->num, (1 << cachep->gfporder));
4277 seq_printf(m, " : tunables %4u %4u %4u",
4278 cachep->limit, cachep->batchcount, cachep->shared);
4279 seq_printf(m, " : slabdata %6lu %6lu %6lu",
4280 active_slabs, num_slabs, shared_avail);
4281 #if STATS
4282 { /* list3 stats */
4283 unsigned long high = cachep->high_mark;
4284 unsigned long allocs = cachep->num_allocations;
4285 unsigned long grown = cachep->grown;
4286 unsigned long reaped = cachep->reaped;
4287 unsigned long errors = cachep->errors;
4288 unsigned long max_freeable = cachep->max_freeable;
4289 unsigned long node_allocs = cachep->node_allocs;
4290 unsigned long node_frees = cachep->node_frees;
4291 unsigned long overflows = cachep->node_overflow;
4293 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
4294 %4lu %4lu %4lu %4lu %4lu", allocs, high, grown,
4295 reaped, errors, max_freeable, node_allocs,
4296 node_frees, overflows);
4298 /* cpu stats */
4300 unsigned long allochit = atomic_read(&cachep->allochit);
4301 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4302 unsigned long freehit = atomic_read(&cachep->freehit);
4303 unsigned long freemiss = atomic_read(&cachep->freemiss);
4305 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4306 allochit, allocmiss, freehit, freemiss);
4308 #endif
4309 seq_putc(m, '\n');
4310 return 0;
4314 * slabinfo_op - iterator that generates /proc/slabinfo
4316 * Output layout:
4317 * cache-name
4318 * num-active-objs
4319 * total-objs
4320 * object size
4321 * num-active-slabs
4322 * total-slabs
4323 * num-pages-per-slab
4324 * + further values on SMP and with statistics enabled
4327 const struct seq_operations slabinfo_op = {
4328 .start = s_start,
4329 .next = s_next,
4330 .stop = s_stop,
4331 .show = s_show,
4334 #define MAX_SLABINFO_WRITE 128
4336 * slabinfo_write - Tuning for the slab allocator
4337 * @file: unused
4338 * @buffer: user buffer
4339 * @count: data length
4340 * @ppos: unused
4342 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4343 size_t count, loff_t *ppos)
4345 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4346 int limit, batchcount, shared, res;
4347 struct kmem_cache *cachep;
4349 if (count > MAX_SLABINFO_WRITE)
4350 return -EINVAL;
4351 if (copy_from_user(&kbuf, buffer, count))
4352 return -EFAULT;
4353 kbuf[MAX_SLABINFO_WRITE] = '\0';
4355 tmp = strchr(kbuf, ' ');
4356 if (!tmp)
4357 return -EINVAL;
4358 *tmp = '\0';
4359 tmp++;
4360 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4361 return -EINVAL;
4363 /* Find the cache in the chain of caches. */
4364 mutex_lock(&cache_chain_mutex);
4365 res = -EINVAL;
4366 list_for_each_entry(cachep, &cache_chain, next) {
4367 if (!strcmp(cachep->name, kbuf)) {
4368 if (limit < 1 || batchcount < 1 ||
4369 batchcount > limit || shared < 0) {
4370 res = 0;
4371 } else {
4372 res = do_tune_cpucache(cachep, limit,
4373 batchcount, shared);
4375 break;
4378 mutex_unlock(&cache_chain_mutex);
4379 if (res >= 0)
4380 res = count;
4381 return res;
4384 #ifdef CONFIG_DEBUG_SLAB_LEAK
4386 static void *leaks_start(struct seq_file *m, loff_t *pos)
4388 mutex_lock(&cache_chain_mutex);
4389 return seq_list_start(&cache_chain, *pos);
4392 static inline int add_caller(unsigned long *n, unsigned long v)
4394 unsigned long *p;
4395 int l;
4396 if (!v)
4397 return 1;
4398 l = n[1];
4399 p = n + 2;
4400 while (l) {
4401 int i = l/2;
4402 unsigned long *q = p + 2 * i;
4403 if (*q == v) {
4404 q[1]++;
4405 return 1;
4407 if (*q > v) {
4408 l = i;
4409 } else {
4410 p = q + 2;
4411 l -= i + 1;
4414 if (++n[1] == n[0])
4415 return 0;
4416 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4417 p[0] = v;
4418 p[1] = 1;
4419 return 1;
4422 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4424 void *p;
4425 int i;
4426 if (n[0] == n[1])
4427 return;
4428 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4429 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4430 continue;
4431 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4432 return;
4436 static void show_symbol(struct seq_file *m, unsigned long address)
4438 #ifdef CONFIG_KALLSYMS
4439 unsigned long offset, size;
4440 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4442 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4443 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4444 if (modname[0])
4445 seq_printf(m, " [%s]", modname);
4446 return;
4448 #endif
4449 seq_printf(m, "%p", (void *)address);
4452 static int leaks_show(struct seq_file *m, void *p)
4454 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, next);
4455 struct slab *slabp;
4456 struct kmem_list3 *l3;
4457 const char *name;
4458 unsigned long *n = m->private;
4459 int node;
4460 int i;
4462 if (!(cachep->flags & SLAB_STORE_USER))
4463 return 0;
4464 if (!(cachep->flags & SLAB_RED_ZONE))
4465 return 0;
4467 /* OK, we can do it */
4469 n[1] = 0;
4471 for_each_online_node(node) {
4472 l3 = cachep->nodelists[node];
4473 if (!l3)
4474 continue;
4476 check_irq_on();
4477 spin_lock_irq(&l3->list_lock);
4479 list_for_each_entry(slabp, &l3->slabs_full, list)
4480 handle_slab(n, cachep, slabp);
4481 list_for_each_entry(slabp, &l3->slabs_partial, list)
4482 handle_slab(n, cachep, slabp);
4483 spin_unlock_irq(&l3->list_lock);
4485 name = cachep->name;
4486 if (n[0] == n[1]) {
4487 /* Increase the buffer size */
4488 mutex_unlock(&cache_chain_mutex);
4489 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4490 if (!m->private) {
4491 /* Too bad, we are really out */
4492 m->private = n;
4493 mutex_lock(&cache_chain_mutex);
4494 return -ENOMEM;
4496 *(unsigned long *)m->private = n[0] * 2;
4497 kfree(n);
4498 mutex_lock(&cache_chain_mutex);
4499 /* Now make sure this entry will be retried */
4500 m->count = m->size;
4501 return 0;
4503 for (i = 0; i < n[1]; i++) {
4504 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4505 show_symbol(m, n[2*i+2]);
4506 seq_putc(m, '\n');
4509 return 0;
4512 const struct seq_operations slabstats_op = {
4513 .start = leaks_start,
4514 .next = s_next,
4515 .stop = s_stop,
4516 .show = leaks_show,
4518 #endif
4519 #endif
4522 * ksize - get the actual amount of memory allocated for a given object
4523 * @objp: Pointer to the object
4525 * kmalloc may internally round up allocations and return more memory
4526 * than requested. ksize() can be used to determine the actual amount of
4527 * memory allocated. The caller may use this additional memory, even though
4528 * a smaller amount of memory was initially specified with the kmalloc call.
4529 * The caller must guarantee that objp points to a valid object previously
4530 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4531 * must not be freed during the duration of the call.
4533 size_t ksize(const void *objp)
4535 BUG_ON(!objp);
4536 if (unlikely(objp == ZERO_SIZE_PTR))
4537 return 0;
4539 return obj_size(virt_to_cache(objp));
4541 EXPORT_SYMBOL(ksize);