[PATCH] mm: slab: eliminate lock_cpu_hotplug from slab
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / slab.c
blob3318252f657f30374e2151a77ca97be68f1bdc12
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 intializations 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/nodemask.h>
107 #include <linux/mempolicy.h>
108 #include <linux/mutex.h>
109 #include <linux/rtmutex.h>
111 #include <asm/uaccess.h>
112 #include <asm/cacheflush.h>
113 #include <asm/tlbflush.h>
114 #include <asm/page.h>
117 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
118 * SLAB_RED_ZONE & SLAB_POISON.
119 * 0 for faster, smaller code (especially in the critical paths).
121 * STATS - 1 to collect stats for /proc/slabinfo.
122 * 0 for faster, smaller code (especially in the critical paths).
124 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
127 #ifdef CONFIG_DEBUG_SLAB
128 #define DEBUG 1
129 #define STATS 1
130 #define FORCED_DEBUG 1
131 #else
132 #define DEBUG 0
133 #define STATS 0
134 #define FORCED_DEBUG 0
135 #endif
137 /* Shouldn't this be in a header file somewhere? */
138 #define BYTES_PER_WORD sizeof(void *)
140 #ifndef cache_line_size
141 #define cache_line_size() L1_CACHE_BYTES
142 #endif
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 BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
151 * Note that this flag disables some debug features.
153 #define ARCH_KMALLOC_MINALIGN 0
154 #endif
156 #ifndef ARCH_SLAB_MINALIGN
158 * Enforce a minimum alignment for all caches.
159 * Intended for archs that get misalignment faults even for BYTES_PER_WORD
160 * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
161 * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
162 * some debug features.
164 #define ARCH_SLAB_MINALIGN 0
165 #endif
167 #ifndef ARCH_KMALLOC_FLAGS
168 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
169 #endif
171 /* Legal flag mask for kmem_cache_create(). */
172 #if DEBUG
173 # define CREATE_MASK (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
174 SLAB_POISON | SLAB_HWCACHE_ALIGN | \
175 SLAB_CACHE_DMA | \
176 SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
177 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
178 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD)
179 #else
180 # define CREATE_MASK (SLAB_HWCACHE_ALIGN | \
181 SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
182 SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
183 SLAB_DESTROY_BY_RCU | SLAB_MEM_SPREAD)
184 #endif
187 * kmem_bufctl_t:
189 * Bufctl's are used for linking objs within a slab
190 * linked offsets.
192 * This implementation relies on "struct page" for locating the cache &
193 * slab an object belongs to.
194 * This allows the bufctl structure to be small (one int), but limits
195 * the number of objects a slab (not a cache) can contain when off-slab
196 * bufctls are used. The limit is the size of the largest general cache
197 * that does not use off-slab slabs.
198 * For 32bit archs with 4 kB pages, is this 56.
199 * This is not serious, as it is only for large objects, when it is unwise
200 * to have too many per slab.
201 * Note: This limit can be raised by introducing a general cache whose size
202 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
205 typedef unsigned int kmem_bufctl_t;
206 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
207 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
208 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
209 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
212 * struct slab
214 * Manages the objs in a slab. Placed either at the beginning of mem allocated
215 * for a slab, or allocated from an general cache.
216 * Slabs are chained into three list: fully used, partial, fully free slabs.
218 struct slab {
219 struct list_head list;
220 unsigned long colouroff;
221 void *s_mem; /* including colour offset */
222 unsigned int inuse; /* num of objs active in slab */
223 kmem_bufctl_t free;
224 unsigned short nodeid;
228 * struct slab_rcu
230 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
231 * arrange for kmem_freepages to be called via RCU. This is useful if
232 * we need to approach a kernel structure obliquely, from its address
233 * obtained without the usual locking. We can lock the structure to
234 * stabilize it and check it's still at the given address, only if we
235 * can be sure that the memory has not been meanwhile reused for some
236 * other kind of object (which our subsystem's lock might corrupt).
238 * rcu_read_lock before reading the address, then rcu_read_unlock after
239 * taking the spinlock within the structure expected at that address.
241 * We assume struct slab_rcu can overlay struct slab when destroying.
243 struct slab_rcu {
244 struct rcu_head head;
245 struct kmem_cache *cachep;
246 void *addr;
250 * struct array_cache
252 * Purpose:
253 * - LIFO ordering, to hand out cache-warm objects from _alloc
254 * - reduce the number of linked list operations
255 * - reduce spinlock operations
257 * The limit is stored in the per-cpu structure to reduce the data cache
258 * footprint.
261 struct array_cache {
262 unsigned int avail;
263 unsigned int limit;
264 unsigned int batchcount;
265 unsigned int touched;
266 spinlock_t lock;
267 void *entry[0]; /*
268 * Must have this definition in here for the proper
269 * alignment of array_cache. Also simplifies accessing
270 * the entries.
271 * [0] is for gcc 2.95. It should really be [].
276 * bootstrap: The caches do not work without cpuarrays anymore, but the
277 * cpuarrays are allocated from the generic caches...
279 #define BOOT_CPUCACHE_ENTRIES 1
280 struct arraycache_init {
281 struct array_cache cache;
282 void *entries[BOOT_CPUCACHE_ENTRIES];
286 * The slab lists for all objects.
288 struct kmem_list3 {
289 struct list_head slabs_partial; /* partial list first, better asm code */
290 struct list_head slabs_full;
291 struct list_head slabs_free;
292 unsigned long free_objects;
293 unsigned int free_limit;
294 unsigned int colour_next; /* Per-node cache coloring */
295 spinlock_t list_lock;
296 struct array_cache *shared; /* shared per node */
297 struct array_cache **alien; /* on other nodes */
298 unsigned long next_reap; /* updated without locking */
299 int free_touched; /* updated without locking */
303 * Need this for bootstrapping a per node allocator.
305 #define NUM_INIT_LISTS (2 * MAX_NUMNODES + 1)
306 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
307 #define CACHE_CACHE 0
308 #define SIZE_AC 1
309 #define SIZE_L3 (1 + MAX_NUMNODES)
311 static int drain_freelist(struct kmem_cache *cache,
312 struct kmem_list3 *l3, int tofree);
313 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
314 int node);
315 static int enable_cpucache(struct kmem_cache *cachep);
316 static void cache_reap(struct work_struct *unused);
319 * This function must be completely optimized away if a constant is passed to
320 * it. Mostly the same as what is in linux/slab.h except it returns an index.
322 static __always_inline int index_of(const size_t size)
324 extern void __bad_size(void);
326 if (__builtin_constant_p(size)) {
327 int i = 0;
329 #define CACHE(x) \
330 if (size <=x) \
331 return i; \
332 else \
333 i++;
334 #include "linux/kmalloc_sizes.h"
335 #undef CACHE
336 __bad_size();
337 } else
338 __bad_size();
339 return 0;
342 static int slab_early_init = 1;
344 #define INDEX_AC index_of(sizeof(struct arraycache_init))
345 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
347 static void kmem_list3_init(struct kmem_list3 *parent)
349 INIT_LIST_HEAD(&parent->slabs_full);
350 INIT_LIST_HEAD(&parent->slabs_partial);
351 INIT_LIST_HEAD(&parent->slabs_free);
352 parent->shared = NULL;
353 parent->alien = NULL;
354 parent->colour_next = 0;
355 spin_lock_init(&parent->list_lock);
356 parent->free_objects = 0;
357 parent->free_touched = 0;
360 #define MAKE_LIST(cachep, listp, slab, nodeid) \
361 do { \
362 INIT_LIST_HEAD(listp); \
363 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
364 } while (0)
366 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
367 do { \
368 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
369 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
370 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
371 } while (0)
374 * struct kmem_cache
376 * manages a cache.
379 struct kmem_cache {
380 /* 1) per-cpu data, touched during every alloc/free */
381 struct array_cache *array[NR_CPUS];
382 /* 2) Cache tunables. Protected by cache_chain_mutex */
383 unsigned int batchcount;
384 unsigned int limit;
385 unsigned int shared;
387 unsigned int buffer_size;
388 /* 3) touched by every alloc & free from the backend */
389 struct kmem_list3 *nodelists[MAX_NUMNODES];
391 unsigned int flags; /* constant flags */
392 unsigned int num; /* # of objs per slab */
394 /* 4) cache_grow/shrink */
395 /* order of pgs per slab (2^n) */
396 unsigned int gfporder;
398 /* force GFP flags, e.g. GFP_DMA */
399 gfp_t gfpflags;
401 size_t colour; /* cache colouring range */
402 unsigned int colour_off; /* colour offset */
403 struct kmem_cache *slabp_cache;
404 unsigned int slab_size;
405 unsigned int dflags; /* dynamic flags */
407 /* constructor func */
408 void (*ctor) (void *, struct kmem_cache *, unsigned long);
410 /* de-constructor func */
411 void (*dtor) (void *, struct kmem_cache *, unsigned long);
413 /* 5) cache creation/removal */
414 const char *name;
415 struct list_head next;
417 /* 6) statistics */
418 #if STATS
419 unsigned long num_active;
420 unsigned long num_allocations;
421 unsigned long high_mark;
422 unsigned long grown;
423 unsigned long reaped;
424 unsigned long errors;
425 unsigned long max_freeable;
426 unsigned long node_allocs;
427 unsigned long node_frees;
428 unsigned long node_overflow;
429 atomic_t allochit;
430 atomic_t allocmiss;
431 atomic_t freehit;
432 atomic_t freemiss;
433 #endif
434 #if DEBUG
436 * If debugging is enabled, then the allocator can add additional
437 * fields and/or padding to every object. buffer_size contains the total
438 * object size including these internal fields, the following two
439 * variables contain the offset to the user object and its size.
441 int obj_offset;
442 int obj_size;
443 #endif
446 #define CFLGS_OFF_SLAB (0x80000000UL)
447 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
449 #define BATCHREFILL_LIMIT 16
451 * Optimization question: fewer reaps means less probability for unnessary
452 * cpucache drain/refill cycles.
454 * OTOH the cpuarrays can contain lots of objects,
455 * which could lock up otherwise freeable slabs.
457 #define REAPTIMEOUT_CPUC (2*HZ)
458 #define REAPTIMEOUT_LIST3 (4*HZ)
460 #if STATS
461 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
462 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
463 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
464 #define STATS_INC_GROWN(x) ((x)->grown++)
465 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
466 #define STATS_SET_HIGH(x) \
467 do { \
468 if ((x)->num_active > (x)->high_mark) \
469 (x)->high_mark = (x)->num_active; \
470 } while (0)
471 #define STATS_INC_ERR(x) ((x)->errors++)
472 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
473 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
474 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
475 #define STATS_SET_FREEABLE(x, i) \
476 do { \
477 if ((x)->max_freeable < i) \
478 (x)->max_freeable = i; \
479 } while (0)
480 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
481 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
482 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
483 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
484 #else
485 #define STATS_INC_ACTIVE(x) do { } while (0)
486 #define STATS_DEC_ACTIVE(x) do { } while (0)
487 #define STATS_INC_ALLOCED(x) do { } while (0)
488 #define STATS_INC_GROWN(x) do { } while (0)
489 #define STATS_ADD_REAPED(x,y) do { } while (0)
490 #define STATS_SET_HIGH(x) do { } while (0)
491 #define STATS_INC_ERR(x) do { } while (0)
492 #define STATS_INC_NODEALLOCS(x) do { } while (0)
493 #define STATS_INC_NODEFREES(x) do { } while (0)
494 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
495 #define STATS_SET_FREEABLE(x, i) do { } while (0)
496 #define STATS_INC_ALLOCHIT(x) do { } while (0)
497 #define STATS_INC_ALLOCMISS(x) do { } while (0)
498 #define STATS_INC_FREEHIT(x) do { } while (0)
499 #define STATS_INC_FREEMISS(x) do { } while (0)
500 #endif
502 #if DEBUG
505 * memory layout of objects:
506 * 0 : objp
507 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
508 * the end of an object is aligned with the end of the real
509 * allocation. Catches writes behind the end of the allocation.
510 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
511 * redzone word.
512 * cachep->obj_offset: The real object.
513 * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
514 * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
515 * [BYTES_PER_WORD long]
517 static int obj_offset(struct kmem_cache *cachep)
519 return cachep->obj_offset;
522 static int obj_size(struct kmem_cache *cachep)
524 return cachep->obj_size;
527 static unsigned long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
529 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
530 return (unsigned long*) (objp+obj_offset(cachep)-BYTES_PER_WORD);
533 static unsigned long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
535 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
536 if (cachep->flags & SLAB_STORE_USER)
537 return (unsigned long *)(objp + cachep->buffer_size -
538 2 * BYTES_PER_WORD);
539 return (unsigned long *)(objp + cachep->buffer_size - BYTES_PER_WORD);
542 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
544 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
545 return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
548 #else
550 #define obj_offset(x) 0
551 #define obj_size(cachep) (cachep->buffer_size)
552 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long *)NULL;})
553 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long *)NULL;})
554 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
556 #endif
559 * Maximum size of an obj (in 2^order pages) and absolute limit for the gfp
560 * order.
562 #if defined(CONFIG_LARGE_ALLOCS)
563 #define MAX_OBJ_ORDER 13 /* up to 32Mb */
564 #define MAX_GFP_ORDER 13 /* up to 32Mb */
565 #elif defined(CONFIG_MMU)
566 #define MAX_OBJ_ORDER 5 /* 32 pages */
567 #define MAX_GFP_ORDER 5 /* 32 pages */
568 #else
569 #define MAX_OBJ_ORDER 8 /* up to 1Mb */
570 #define MAX_GFP_ORDER 8 /* up to 1Mb */
571 #endif
574 * Do not go above this order unless 0 objects fit into the slab.
576 #define BREAK_GFP_ORDER_HI 1
577 #define BREAK_GFP_ORDER_LO 0
578 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
581 * Functions for storing/retrieving the cachep and or slab from the page
582 * allocator. These are used to find the slab an obj belongs to. With kfree(),
583 * these are used to find the cache which an obj belongs to.
585 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
587 page->lru.next = (struct list_head *)cache;
590 static inline struct kmem_cache *page_get_cache(struct page *page)
592 if (unlikely(PageCompound(page)))
593 page = (struct page *)page_private(page);
594 BUG_ON(!PageSlab(page));
595 return (struct kmem_cache *)page->lru.next;
598 static inline void page_set_slab(struct page *page, struct slab *slab)
600 page->lru.prev = (struct list_head *)slab;
603 static inline struct slab *page_get_slab(struct page *page)
605 if (unlikely(PageCompound(page)))
606 page = (struct page *)page_private(page);
607 BUG_ON(!PageSlab(page));
608 return (struct slab *)page->lru.prev;
611 static inline struct kmem_cache *virt_to_cache(const void *obj)
613 struct page *page = virt_to_page(obj);
614 return page_get_cache(page);
617 static inline struct slab *virt_to_slab(const void *obj)
619 struct page *page = virt_to_page(obj);
620 return page_get_slab(page);
623 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
624 unsigned int idx)
626 return slab->s_mem + cache->buffer_size * idx;
629 static inline unsigned int obj_to_index(struct kmem_cache *cache,
630 struct slab *slab, void *obj)
632 return (unsigned)(obj - slab->s_mem) / cache->buffer_size;
636 * These are the default caches for kmalloc. Custom caches can have other sizes.
638 struct cache_sizes malloc_sizes[] = {
639 #define CACHE(x) { .cs_size = (x) },
640 #include <linux/kmalloc_sizes.h>
641 CACHE(ULONG_MAX)
642 #undef CACHE
644 EXPORT_SYMBOL(malloc_sizes);
646 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
647 struct cache_names {
648 char *name;
649 char *name_dma;
652 static struct cache_names __initdata cache_names[] = {
653 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
654 #include <linux/kmalloc_sizes.h>
655 {NULL,}
656 #undef CACHE
659 static struct arraycache_init initarray_cache __initdata =
660 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
661 static struct arraycache_init initarray_generic =
662 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
664 /* internal cache of cache description objs */
665 static struct kmem_cache cache_cache = {
666 .batchcount = 1,
667 .limit = BOOT_CPUCACHE_ENTRIES,
668 .shared = 1,
669 .buffer_size = sizeof(struct kmem_cache),
670 .name = "kmem_cache",
671 #if DEBUG
672 .obj_size = sizeof(struct kmem_cache),
673 #endif
676 #define BAD_ALIEN_MAGIC 0x01020304ul
678 #ifdef CONFIG_LOCKDEP
681 * Slab sometimes uses the kmalloc slabs to store the slab headers
682 * for other slabs "off slab".
683 * The locking for this is tricky in that it nests within the locks
684 * of all other slabs in a few places; to deal with this special
685 * locking we put on-slab caches into a separate lock-class.
687 * We set lock class for alien array caches which are up during init.
688 * The lock annotation will be lost if all cpus of a node goes down and
689 * then comes back up during hotplug
691 static struct lock_class_key on_slab_l3_key;
692 static struct lock_class_key on_slab_alc_key;
694 static inline void init_lock_keys(void)
697 int q;
698 struct cache_sizes *s = malloc_sizes;
700 while (s->cs_size != ULONG_MAX) {
701 for_each_node(q) {
702 struct array_cache **alc;
703 int r;
704 struct kmem_list3 *l3 = s->cs_cachep->nodelists[q];
705 if (!l3 || OFF_SLAB(s->cs_cachep))
706 continue;
707 lockdep_set_class(&l3->list_lock, &on_slab_l3_key);
708 alc = l3->alien;
710 * FIXME: This check for BAD_ALIEN_MAGIC
711 * should go away when common slab code is taught to
712 * work even without alien caches.
713 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
714 * for alloc_alien_cache,
716 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
717 continue;
718 for_each_node(r) {
719 if (alc[r])
720 lockdep_set_class(&alc[r]->lock,
721 &on_slab_alc_key);
724 s++;
727 #else
728 static inline void init_lock_keys(void)
731 #endif
734 * 1. Guard access to the cache-chain.
735 * 2. Protect sanity of cpu_online_map against cpu hotplug events
737 static DEFINE_MUTEX(cache_chain_mutex);
738 static struct list_head cache_chain;
741 * chicken and egg problem: delay the per-cpu array allocation
742 * until the general caches are up.
744 static enum {
745 NONE,
746 PARTIAL_AC,
747 PARTIAL_L3,
748 FULL
749 } g_cpucache_up;
752 * used by boot code to determine if it can use slab based allocator
754 int slab_is_available(void)
756 return g_cpucache_up == FULL;
759 static DEFINE_PER_CPU(struct delayed_work, reap_work);
761 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
763 return cachep->array[smp_processor_id()];
766 static inline struct kmem_cache *__find_general_cachep(size_t size,
767 gfp_t gfpflags)
769 struct cache_sizes *csizep = malloc_sizes;
771 #if DEBUG
772 /* This happens if someone tries to call
773 * kmem_cache_create(), or __kmalloc(), before
774 * the generic caches are initialized.
776 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
777 #endif
778 while (size > csizep->cs_size)
779 csizep++;
782 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
783 * has cs_{dma,}cachep==NULL. Thus no special case
784 * for large kmalloc calls required.
786 if (unlikely(gfpflags & GFP_DMA))
787 return csizep->cs_dmacachep;
788 return csizep->cs_cachep;
791 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
793 return __find_general_cachep(size, gfpflags);
796 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
798 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
802 * Calculate the number of objects and left-over bytes for a given buffer size.
804 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
805 size_t align, int flags, size_t *left_over,
806 unsigned int *num)
808 int nr_objs;
809 size_t mgmt_size;
810 size_t slab_size = PAGE_SIZE << gfporder;
813 * The slab management structure can be either off the slab or
814 * on it. For the latter case, the memory allocated for a
815 * slab is used for:
817 * - The struct slab
818 * - One kmem_bufctl_t for each object
819 * - Padding to respect alignment of @align
820 * - @buffer_size bytes for each object
822 * If the slab management structure is off the slab, then the
823 * alignment will already be calculated into the size. Because
824 * the slabs are all pages aligned, the objects will be at the
825 * correct alignment when allocated.
827 if (flags & CFLGS_OFF_SLAB) {
828 mgmt_size = 0;
829 nr_objs = slab_size / buffer_size;
831 if (nr_objs > SLAB_LIMIT)
832 nr_objs = SLAB_LIMIT;
833 } else {
835 * Ignore padding for the initial guess. The padding
836 * is at most @align-1 bytes, and @buffer_size is at
837 * least @align. In the worst case, this result will
838 * be one greater than the number of objects that fit
839 * into the memory allocation when taking the padding
840 * into account.
842 nr_objs = (slab_size - sizeof(struct slab)) /
843 (buffer_size + sizeof(kmem_bufctl_t));
846 * This calculated number will be either the right
847 * amount, or one greater than what we want.
849 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
850 > slab_size)
851 nr_objs--;
853 if (nr_objs > SLAB_LIMIT)
854 nr_objs = SLAB_LIMIT;
856 mgmt_size = slab_mgmt_size(nr_objs, align);
858 *num = nr_objs;
859 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
862 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
864 static void __slab_error(const char *function, struct kmem_cache *cachep,
865 char *msg)
867 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
868 function, cachep->name, msg);
869 dump_stack();
872 #ifdef CONFIG_NUMA
874 * Special reaping functions for NUMA systems called from cache_reap().
875 * These take care of doing round robin flushing of alien caches (containing
876 * objects freed on different nodes from which they were allocated) and the
877 * flushing of remote pcps by calling drain_node_pages.
879 static DEFINE_PER_CPU(unsigned long, reap_node);
881 static void init_reap_node(int cpu)
883 int node;
885 node = next_node(cpu_to_node(cpu), node_online_map);
886 if (node == MAX_NUMNODES)
887 node = first_node(node_online_map);
889 per_cpu(reap_node, cpu) = node;
892 static void next_reap_node(void)
894 int node = __get_cpu_var(reap_node);
897 * Also drain per cpu pages on remote zones
899 if (node != numa_node_id())
900 drain_node_pages(node);
902 node = next_node(node, node_online_map);
903 if (unlikely(node >= MAX_NUMNODES))
904 node = first_node(node_online_map);
905 __get_cpu_var(reap_node) = node;
908 #else
909 #define init_reap_node(cpu) do { } while (0)
910 #define next_reap_node(void) do { } while (0)
911 #endif
914 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
915 * via the workqueue/eventd.
916 * Add the CPU number into the expiration time to minimize the possibility of
917 * the CPUs getting into lockstep and contending for the global cache chain
918 * lock.
920 static void __devinit start_cpu_timer(int cpu)
922 struct delayed_work *reap_work = &per_cpu(reap_work, cpu);
925 * When this gets called from do_initcalls via cpucache_init(),
926 * init_workqueues() has already run, so keventd will be setup
927 * at that time.
929 if (keventd_up() && reap_work->work.func == NULL) {
930 init_reap_node(cpu);
931 INIT_DELAYED_WORK(reap_work, cache_reap);
932 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
936 static struct array_cache *alloc_arraycache(int node, int entries,
937 int batchcount)
939 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
940 struct array_cache *nc = NULL;
942 nc = kmalloc_node(memsize, GFP_KERNEL, node);
943 if (nc) {
944 nc->avail = 0;
945 nc->limit = entries;
946 nc->batchcount = batchcount;
947 nc->touched = 0;
948 spin_lock_init(&nc->lock);
950 return nc;
954 * Transfer objects in one arraycache to another.
955 * Locking must be handled by the caller.
957 * Return the number of entries transferred.
959 static int transfer_objects(struct array_cache *to,
960 struct array_cache *from, unsigned int max)
962 /* Figure out how many entries to transfer */
963 int nr = min(min(from->avail, max), to->limit - to->avail);
965 if (!nr)
966 return 0;
968 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
969 sizeof(void *) *nr);
971 from->avail -= nr;
972 to->avail += nr;
973 to->touched = 1;
974 return nr;
977 #ifndef CONFIG_NUMA
979 #define drain_alien_cache(cachep, alien) do { } while (0)
980 #define reap_alien(cachep, l3) do { } while (0)
982 static inline struct array_cache **alloc_alien_cache(int node, int limit)
984 return (struct array_cache **)BAD_ALIEN_MAGIC;
987 static inline void free_alien_cache(struct array_cache **ac_ptr)
991 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
993 return 0;
996 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
997 gfp_t flags)
999 return NULL;
1002 static inline void *__cache_alloc_node(struct kmem_cache *cachep,
1003 gfp_t flags, int nodeid)
1005 return NULL;
1008 #else /* CONFIG_NUMA */
1010 static void *__cache_alloc_node(struct kmem_cache *, gfp_t, int);
1011 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1013 static struct array_cache **alloc_alien_cache(int node, int limit)
1015 struct array_cache **ac_ptr;
1016 int memsize = sizeof(void *) * MAX_NUMNODES;
1017 int i;
1019 if (limit > 1)
1020 limit = 12;
1021 ac_ptr = kmalloc_node(memsize, GFP_KERNEL, node);
1022 if (ac_ptr) {
1023 for_each_node(i) {
1024 if (i == node || !node_online(i)) {
1025 ac_ptr[i] = NULL;
1026 continue;
1028 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d);
1029 if (!ac_ptr[i]) {
1030 for (i--; i <= 0; i--)
1031 kfree(ac_ptr[i]);
1032 kfree(ac_ptr);
1033 return NULL;
1037 return ac_ptr;
1040 static void free_alien_cache(struct array_cache **ac_ptr)
1042 int i;
1044 if (!ac_ptr)
1045 return;
1046 for_each_node(i)
1047 kfree(ac_ptr[i]);
1048 kfree(ac_ptr);
1051 static void __drain_alien_cache(struct kmem_cache *cachep,
1052 struct array_cache *ac, int node)
1054 struct kmem_list3 *rl3 = cachep->nodelists[node];
1056 if (ac->avail) {
1057 spin_lock(&rl3->list_lock);
1059 * Stuff objects into the remote nodes shared array first.
1060 * That way we could avoid the overhead of putting the objects
1061 * into the free lists and getting them back later.
1063 if (rl3->shared)
1064 transfer_objects(rl3->shared, ac, ac->limit);
1066 free_block(cachep, ac->entry, ac->avail, node);
1067 ac->avail = 0;
1068 spin_unlock(&rl3->list_lock);
1073 * Called from cache_reap() to regularly drain alien caches round robin.
1075 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1077 int node = __get_cpu_var(reap_node);
1079 if (l3->alien) {
1080 struct array_cache *ac = l3->alien[node];
1082 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1083 __drain_alien_cache(cachep, ac, node);
1084 spin_unlock_irq(&ac->lock);
1089 static void drain_alien_cache(struct kmem_cache *cachep,
1090 struct array_cache **alien)
1092 int i = 0;
1093 struct array_cache *ac;
1094 unsigned long flags;
1096 for_each_online_node(i) {
1097 ac = alien[i];
1098 if (ac) {
1099 spin_lock_irqsave(&ac->lock, flags);
1100 __drain_alien_cache(cachep, ac, i);
1101 spin_unlock_irqrestore(&ac->lock, flags);
1106 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1108 struct slab *slabp = virt_to_slab(objp);
1109 int nodeid = slabp->nodeid;
1110 struct kmem_list3 *l3;
1111 struct array_cache *alien = NULL;
1112 int node;
1114 node = numa_node_id();
1117 * Make sure we are not freeing a object from another node to the array
1118 * cache on this cpu.
1120 if (likely(slabp->nodeid == node))
1121 return 0;
1123 l3 = cachep->nodelists[node];
1124 STATS_INC_NODEFREES(cachep);
1125 if (l3->alien && l3->alien[nodeid]) {
1126 alien = l3->alien[nodeid];
1127 spin_lock(&alien->lock);
1128 if (unlikely(alien->avail == alien->limit)) {
1129 STATS_INC_ACOVERFLOW(cachep);
1130 __drain_alien_cache(cachep, alien, nodeid);
1132 alien->entry[alien->avail++] = objp;
1133 spin_unlock(&alien->lock);
1134 } else {
1135 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1136 free_block(cachep, &objp, 1, nodeid);
1137 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1139 return 1;
1141 #endif
1143 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1144 unsigned long action, void *hcpu)
1146 long cpu = (long)hcpu;
1147 struct kmem_cache *cachep;
1148 struct kmem_list3 *l3 = NULL;
1149 int node = cpu_to_node(cpu);
1150 int memsize = sizeof(struct kmem_list3);
1152 switch (action) {
1153 case CPU_UP_PREPARE:
1154 mutex_lock(&cache_chain_mutex);
1156 * We need to do this right in the beginning since
1157 * alloc_arraycache's are going to use this list.
1158 * kmalloc_node allows us to add the slab to the right
1159 * kmem_list3 and not this cpu's kmem_list3
1162 list_for_each_entry(cachep, &cache_chain, next) {
1164 * Set up the size64 kmemlist for cpu before we can
1165 * begin anything. Make sure some other cpu on this
1166 * node has not already allocated this
1168 if (!cachep->nodelists[node]) {
1169 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1170 if (!l3)
1171 goto bad;
1172 kmem_list3_init(l3);
1173 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1174 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1177 * The l3s don't come and go as CPUs come and
1178 * go. cache_chain_mutex is sufficient
1179 * protection here.
1181 cachep->nodelists[node] = l3;
1184 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1185 cachep->nodelists[node]->free_limit =
1186 (1 + nr_cpus_node(node)) *
1187 cachep->batchcount + cachep->num;
1188 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1192 * Now we can go ahead with allocating the shared arrays and
1193 * array caches
1195 list_for_each_entry(cachep, &cache_chain, next) {
1196 struct array_cache *nc;
1197 struct array_cache *shared;
1198 struct array_cache **alien;
1200 nc = alloc_arraycache(node, cachep->limit,
1201 cachep->batchcount);
1202 if (!nc)
1203 goto bad;
1204 shared = alloc_arraycache(node,
1205 cachep->shared * cachep->batchcount,
1206 0xbaadf00d);
1207 if (!shared)
1208 goto bad;
1210 alien = alloc_alien_cache(node, cachep->limit);
1211 if (!alien)
1212 goto bad;
1213 cachep->array[cpu] = nc;
1214 l3 = cachep->nodelists[node];
1215 BUG_ON(!l3);
1217 spin_lock_irq(&l3->list_lock);
1218 if (!l3->shared) {
1220 * We are serialised from CPU_DEAD or
1221 * CPU_UP_CANCELLED by the cpucontrol lock
1223 l3->shared = shared;
1224 shared = NULL;
1226 #ifdef CONFIG_NUMA
1227 if (!l3->alien) {
1228 l3->alien = alien;
1229 alien = NULL;
1231 #endif
1232 spin_unlock_irq(&l3->list_lock);
1233 kfree(shared);
1234 free_alien_cache(alien);
1236 break;
1237 case CPU_ONLINE:
1238 mutex_unlock(&cache_chain_mutex);
1239 start_cpu_timer(cpu);
1240 break;
1241 #ifdef CONFIG_HOTPLUG_CPU
1242 case CPU_DOWN_PREPARE:
1243 mutex_lock(&cache_chain_mutex);
1244 break;
1245 case CPU_DOWN_FAILED:
1246 mutex_unlock(&cache_chain_mutex);
1247 break;
1248 case CPU_DEAD:
1250 * Even if all the cpus of a node are down, we don't free the
1251 * kmem_list3 of any cache. This to avoid a race between
1252 * cpu_down, and a kmalloc allocation from another cpu for
1253 * memory from the node of the cpu going down. The list3
1254 * structure is usually allocated from kmem_cache_create() and
1255 * gets destroyed at kmem_cache_destroy().
1257 /* fall thru */
1258 #endif
1259 case CPU_UP_CANCELED:
1260 list_for_each_entry(cachep, &cache_chain, next) {
1261 struct array_cache *nc;
1262 struct array_cache *shared;
1263 struct array_cache **alien;
1264 cpumask_t mask;
1266 mask = node_to_cpumask(node);
1267 /* cpu is dead; no one can alloc from it. */
1268 nc = cachep->array[cpu];
1269 cachep->array[cpu] = NULL;
1270 l3 = cachep->nodelists[node];
1272 if (!l3)
1273 goto free_array_cache;
1275 spin_lock_irq(&l3->list_lock);
1277 /* Free limit for this kmem_list3 */
1278 l3->free_limit -= cachep->batchcount;
1279 if (nc)
1280 free_block(cachep, nc->entry, nc->avail, node);
1282 if (!cpus_empty(mask)) {
1283 spin_unlock_irq(&l3->list_lock);
1284 goto free_array_cache;
1287 shared = l3->shared;
1288 if (shared) {
1289 free_block(cachep, l3->shared->entry,
1290 l3->shared->avail, node);
1291 l3->shared = NULL;
1294 alien = l3->alien;
1295 l3->alien = NULL;
1297 spin_unlock_irq(&l3->list_lock);
1299 kfree(shared);
1300 if (alien) {
1301 drain_alien_cache(cachep, alien);
1302 free_alien_cache(alien);
1304 free_array_cache:
1305 kfree(nc);
1308 * In the previous loop, all the objects were freed to
1309 * the respective cache's slabs, now we can go ahead and
1310 * shrink each nodelist to its limit.
1312 list_for_each_entry(cachep, &cache_chain, next) {
1313 l3 = cachep->nodelists[node];
1314 if (!l3)
1315 continue;
1316 drain_freelist(cachep, l3, l3->free_objects);
1318 mutex_unlock(&cache_chain_mutex);
1319 break;
1321 return NOTIFY_OK;
1322 bad:
1323 return NOTIFY_BAD;
1326 static struct notifier_block __cpuinitdata cpucache_notifier = {
1327 &cpuup_callback, NULL, 0
1331 * swap the static kmem_list3 with kmalloced memory
1333 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1334 int nodeid)
1336 struct kmem_list3 *ptr;
1338 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, nodeid);
1339 BUG_ON(!ptr);
1341 local_irq_disable();
1342 memcpy(ptr, list, sizeof(struct kmem_list3));
1344 * Do not assume that spinlocks can be initialized via memcpy:
1346 spin_lock_init(&ptr->list_lock);
1348 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1349 cachep->nodelists[nodeid] = ptr;
1350 local_irq_enable();
1354 * Initialisation. Called after the page allocator have been initialised and
1355 * before smp_init().
1357 void __init kmem_cache_init(void)
1359 size_t left_over;
1360 struct cache_sizes *sizes;
1361 struct cache_names *names;
1362 int i;
1363 int order;
1364 int node;
1366 for (i = 0; i < NUM_INIT_LISTS; i++) {
1367 kmem_list3_init(&initkmem_list3[i]);
1368 if (i < MAX_NUMNODES)
1369 cache_cache.nodelists[i] = NULL;
1373 * Fragmentation resistance on low memory - only use bigger
1374 * page orders on machines with more than 32MB of memory.
1376 if (num_physpages > (32 << 20) >> PAGE_SHIFT)
1377 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1379 /* Bootstrap is tricky, because several objects are allocated
1380 * from caches that do not exist yet:
1381 * 1) initialize the cache_cache cache: it contains the struct
1382 * kmem_cache structures of all caches, except cache_cache itself:
1383 * cache_cache is statically allocated.
1384 * Initially an __init data area is used for the head array and the
1385 * kmem_list3 structures, it's replaced with a kmalloc allocated
1386 * array at the end of the bootstrap.
1387 * 2) Create the first kmalloc cache.
1388 * The struct kmem_cache for the new cache is allocated normally.
1389 * An __init data area is used for the head array.
1390 * 3) Create the remaining kmalloc caches, with minimally sized
1391 * head arrays.
1392 * 4) Replace the __init data head arrays for cache_cache and the first
1393 * kmalloc cache with kmalloc allocated arrays.
1394 * 5) Replace the __init data for kmem_list3 for cache_cache and
1395 * the other cache's with kmalloc allocated memory.
1396 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1399 node = numa_node_id();
1401 /* 1) create the cache_cache */
1402 INIT_LIST_HEAD(&cache_chain);
1403 list_add(&cache_cache.next, &cache_chain);
1404 cache_cache.colour_off = cache_line_size();
1405 cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1406 cache_cache.nodelists[node] = &initkmem_list3[CACHE_CACHE];
1408 cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1409 cache_line_size());
1411 for (order = 0; order < MAX_ORDER; order++) {
1412 cache_estimate(order, cache_cache.buffer_size,
1413 cache_line_size(), 0, &left_over, &cache_cache.num);
1414 if (cache_cache.num)
1415 break;
1417 BUG_ON(!cache_cache.num);
1418 cache_cache.gfporder = order;
1419 cache_cache.colour = left_over / cache_cache.colour_off;
1420 cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1421 sizeof(struct slab), cache_line_size());
1423 /* 2+3) create the kmalloc caches */
1424 sizes = malloc_sizes;
1425 names = cache_names;
1428 * Initialize the caches that provide memory for the array cache and the
1429 * kmem_list3 structures first. Without this, further allocations will
1430 * bug.
1433 sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1434 sizes[INDEX_AC].cs_size,
1435 ARCH_KMALLOC_MINALIGN,
1436 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1437 NULL, NULL);
1439 if (INDEX_AC != INDEX_L3) {
1440 sizes[INDEX_L3].cs_cachep =
1441 kmem_cache_create(names[INDEX_L3].name,
1442 sizes[INDEX_L3].cs_size,
1443 ARCH_KMALLOC_MINALIGN,
1444 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1445 NULL, NULL);
1448 slab_early_init = 0;
1450 while (sizes->cs_size != ULONG_MAX) {
1452 * For performance, all the general caches are L1 aligned.
1453 * This should be particularly beneficial on SMP boxes, as it
1454 * eliminates "false sharing".
1455 * Note for systems short on memory removing the alignment will
1456 * allow tighter packing of the smaller caches.
1458 if (!sizes->cs_cachep) {
1459 sizes->cs_cachep = kmem_cache_create(names->name,
1460 sizes->cs_size,
1461 ARCH_KMALLOC_MINALIGN,
1462 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1463 NULL, NULL);
1466 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
1467 sizes->cs_size,
1468 ARCH_KMALLOC_MINALIGN,
1469 ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1470 SLAB_PANIC,
1471 NULL, NULL);
1472 sizes++;
1473 names++;
1475 /* 4) Replace the bootstrap head arrays */
1477 struct array_cache *ptr;
1479 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1481 local_irq_disable();
1482 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1483 memcpy(ptr, cpu_cache_get(&cache_cache),
1484 sizeof(struct arraycache_init));
1486 * Do not assume that spinlocks can be initialized via memcpy:
1488 spin_lock_init(&ptr->lock);
1490 cache_cache.array[smp_processor_id()] = ptr;
1491 local_irq_enable();
1493 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1495 local_irq_disable();
1496 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1497 != &initarray_generic.cache);
1498 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1499 sizeof(struct arraycache_init));
1501 * Do not assume that spinlocks can be initialized via memcpy:
1503 spin_lock_init(&ptr->lock);
1505 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1506 ptr;
1507 local_irq_enable();
1509 /* 5) Replace the bootstrap kmem_list3's */
1511 int nid;
1513 /* Replace the static kmem_list3 structures for the boot cpu */
1514 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE], node);
1516 for_each_online_node(nid) {
1517 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1518 &initkmem_list3[SIZE_AC + nid], nid);
1520 if (INDEX_AC != INDEX_L3) {
1521 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1522 &initkmem_list3[SIZE_L3 + nid], nid);
1527 /* 6) resize the head arrays to their final sizes */
1529 struct kmem_cache *cachep;
1530 mutex_lock(&cache_chain_mutex);
1531 list_for_each_entry(cachep, &cache_chain, next)
1532 if (enable_cpucache(cachep))
1533 BUG();
1534 mutex_unlock(&cache_chain_mutex);
1537 /* Annotate slab for lockdep -- annotate the malloc caches */
1538 init_lock_keys();
1541 /* Done! */
1542 g_cpucache_up = FULL;
1545 * Register a cpu startup notifier callback that initializes
1546 * cpu_cache_get for all new cpus
1548 register_cpu_notifier(&cpucache_notifier);
1551 * The reap timers are started later, with a module init call: That part
1552 * of the kernel is not yet operational.
1556 static int __init cpucache_init(void)
1558 int cpu;
1561 * Register the timers that return unneeded pages to the page allocator
1563 for_each_online_cpu(cpu)
1564 start_cpu_timer(cpu);
1565 return 0;
1567 __initcall(cpucache_init);
1570 * Interface to system's page allocator. No need to hold the cache-lock.
1572 * If we requested dmaable memory, we will get it. Even if we
1573 * did not request dmaable memory, we might get it, but that
1574 * would be relatively rare and ignorable.
1576 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1578 struct page *page;
1579 int nr_pages;
1580 int i;
1582 #ifndef CONFIG_MMU
1584 * Nommu uses slab's for process anonymous memory allocations, and thus
1585 * requires __GFP_COMP to properly refcount higher order allocations
1587 flags |= __GFP_COMP;
1588 #endif
1591 * Under NUMA we want memory on the indicated node. We will handle
1592 * the needed fallback ourselves since we want to serve from our
1593 * per node object lists first for other nodes.
1595 flags |= cachep->gfpflags | GFP_THISNODE;
1597 page = alloc_pages_node(nodeid, flags, cachep->gfporder);
1598 if (!page)
1599 return NULL;
1601 nr_pages = (1 << cachep->gfporder);
1602 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1603 add_zone_page_state(page_zone(page),
1604 NR_SLAB_RECLAIMABLE, nr_pages);
1605 else
1606 add_zone_page_state(page_zone(page),
1607 NR_SLAB_UNRECLAIMABLE, nr_pages);
1608 for (i = 0; i < nr_pages; i++)
1609 __SetPageSlab(page + i);
1610 return page_address(page);
1614 * Interface to system's page release.
1616 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1618 unsigned long i = (1 << cachep->gfporder);
1619 struct page *page = virt_to_page(addr);
1620 const unsigned long nr_freed = i;
1622 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1623 sub_zone_page_state(page_zone(page),
1624 NR_SLAB_RECLAIMABLE, nr_freed);
1625 else
1626 sub_zone_page_state(page_zone(page),
1627 NR_SLAB_UNRECLAIMABLE, nr_freed);
1628 while (i--) {
1629 BUG_ON(!PageSlab(page));
1630 __ClearPageSlab(page);
1631 page++;
1633 if (current->reclaim_state)
1634 current->reclaim_state->reclaimed_slab += nr_freed;
1635 free_pages((unsigned long)addr, cachep->gfporder);
1638 static void kmem_rcu_free(struct rcu_head *head)
1640 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1641 struct kmem_cache *cachep = slab_rcu->cachep;
1643 kmem_freepages(cachep, slab_rcu->addr);
1644 if (OFF_SLAB(cachep))
1645 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1648 #if DEBUG
1650 #ifdef CONFIG_DEBUG_PAGEALLOC
1651 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1652 unsigned long caller)
1654 int size = obj_size(cachep);
1656 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1658 if (size < 5 * sizeof(unsigned long))
1659 return;
1661 *addr++ = 0x12345678;
1662 *addr++ = caller;
1663 *addr++ = smp_processor_id();
1664 size -= 3 * sizeof(unsigned long);
1666 unsigned long *sptr = &caller;
1667 unsigned long svalue;
1669 while (!kstack_end(sptr)) {
1670 svalue = *sptr++;
1671 if (kernel_text_address(svalue)) {
1672 *addr++ = svalue;
1673 size -= sizeof(unsigned long);
1674 if (size <= sizeof(unsigned long))
1675 break;
1680 *addr++ = 0x87654321;
1682 #endif
1684 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1686 int size = obj_size(cachep);
1687 addr = &((char *)addr)[obj_offset(cachep)];
1689 memset(addr, val, size);
1690 *(unsigned char *)(addr + size - 1) = POISON_END;
1693 static void dump_line(char *data, int offset, int limit)
1695 int i;
1696 unsigned char error = 0;
1697 int bad_count = 0;
1699 printk(KERN_ERR "%03x:", offset);
1700 for (i = 0; i < limit; i++) {
1701 if (data[offset + i] != POISON_FREE) {
1702 error = data[offset + i];
1703 bad_count++;
1705 printk(" %02x", (unsigned char)data[offset + i]);
1707 printk("\n");
1709 if (bad_count == 1) {
1710 error ^= POISON_FREE;
1711 if (!(error & (error - 1))) {
1712 printk(KERN_ERR "Single bit error detected. Probably "
1713 "bad RAM.\n");
1714 #ifdef CONFIG_X86
1715 printk(KERN_ERR "Run memtest86+ or a similar memory "
1716 "test tool.\n");
1717 #else
1718 printk(KERN_ERR "Run a memory test tool.\n");
1719 #endif
1723 #endif
1725 #if DEBUG
1727 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1729 int i, size;
1730 char *realobj;
1732 if (cachep->flags & SLAB_RED_ZONE) {
1733 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1734 *dbg_redzone1(cachep, objp),
1735 *dbg_redzone2(cachep, objp));
1738 if (cachep->flags & SLAB_STORE_USER) {
1739 printk(KERN_ERR "Last user: [<%p>]",
1740 *dbg_userword(cachep, objp));
1741 print_symbol("(%s)",
1742 (unsigned long)*dbg_userword(cachep, objp));
1743 printk("\n");
1745 realobj = (char *)objp + obj_offset(cachep);
1746 size = obj_size(cachep);
1747 for (i = 0; i < size && lines; i += 16, lines--) {
1748 int limit;
1749 limit = 16;
1750 if (i + limit > size)
1751 limit = size - i;
1752 dump_line(realobj, i, limit);
1756 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1758 char *realobj;
1759 int size, i;
1760 int lines = 0;
1762 realobj = (char *)objp + obj_offset(cachep);
1763 size = obj_size(cachep);
1765 for (i = 0; i < size; i++) {
1766 char exp = POISON_FREE;
1767 if (i == size - 1)
1768 exp = POISON_END;
1769 if (realobj[i] != exp) {
1770 int limit;
1771 /* Mismatch ! */
1772 /* Print header */
1773 if (lines == 0) {
1774 printk(KERN_ERR
1775 "Slab corruption: start=%p, len=%d\n",
1776 realobj, size);
1777 print_objinfo(cachep, objp, 0);
1779 /* Hexdump the affected line */
1780 i = (i / 16) * 16;
1781 limit = 16;
1782 if (i + limit > size)
1783 limit = size - i;
1784 dump_line(realobj, i, limit);
1785 i += 16;
1786 lines++;
1787 /* Limit to 5 lines */
1788 if (lines > 5)
1789 break;
1792 if (lines != 0) {
1793 /* Print some data about the neighboring objects, if they
1794 * exist:
1796 struct slab *slabp = virt_to_slab(objp);
1797 unsigned int objnr;
1799 objnr = obj_to_index(cachep, slabp, objp);
1800 if (objnr) {
1801 objp = index_to_obj(cachep, slabp, objnr - 1);
1802 realobj = (char *)objp + obj_offset(cachep);
1803 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1804 realobj, size);
1805 print_objinfo(cachep, objp, 2);
1807 if (objnr + 1 < cachep->num) {
1808 objp = index_to_obj(cachep, slabp, objnr + 1);
1809 realobj = (char *)objp + obj_offset(cachep);
1810 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1811 realobj, size);
1812 print_objinfo(cachep, objp, 2);
1816 #endif
1818 #if DEBUG
1820 * slab_destroy_objs - destroy a slab and its objects
1821 * @cachep: cache pointer being destroyed
1822 * @slabp: slab pointer being destroyed
1824 * Call the registered destructor for each object in a slab that is being
1825 * destroyed.
1827 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1829 int i;
1830 for (i = 0; i < cachep->num; i++) {
1831 void *objp = index_to_obj(cachep, slabp, i);
1833 if (cachep->flags & SLAB_POISON) {
1834 #ifdef CONFIG_DEBUG_PAGEALLOC
1835 if (cachep->buffer_size % PAGE_SIZE == 0 &&
1836 OFF_SLAB(cachep))
1837 kernel_map_pages(virt_to_page(objp),
1838 cachep->buffer_size / PAGE_SIZE, 1);
1839 else
1840 check_poison_obj(cachep, objp);
1841 #else
1842 check_poison_obj(cachep, objp);
1843 #endif
1845 if (cachep->flags & SLAB_RED_ZONE) {
1846 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1847 slab_error(cachep, "start of a freed object "
1848 "was overwritten");
1849 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1850 slab_error(cachep, "end of a freed object "
1851 "was overwritten");
1853 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1854 (cachep->dtor) (objp + obj_offset(cachep), cachep, 0);
1857 #else
1858 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1860 if (cachep->dtor) {
1861 int i;
1862 for (i = 0; i < cachep->num; i++) {
1863 void *objp = index_to_obj(cachep, slabp, i);
1864 (cachep->dtor) (objp, cachep, 0);
1868 #endif
1871 * slab_destroy - destroy and release all objects in a slab
1872 * @cachep: cache pointer being destroyed
1873 * @slabp: slab pointer being destroyed
1875 * Destroy all the objs in a slab, and release the mem back to the system.
1876 * Before calling the slab must have been unlinked from the cache. The
1877 * cache-lock is not held/needed.
1879 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1881 void *addr = slabp->s_mem - slabp->colouroff;
1883 slab_destroy_objs(cachep, slabp);
1884 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1885 struct slab_rcu *slab_rcu;
1887 slab_rcu = (struct slab_rcu *)slabp;
1888 slab_rcu->cachep = cachep;
1889 slab_rcu->addr = addr;
1890 call_rcu(&slab_rcu->head, kmem_rcu_free);
1891 } else {
1892 kmem_freepages(cachep, addr);
1893 if (OFF_SLAB(cachep))
1894 kmem_cache_free(cachep->slabp_cache, slabp);
1899 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1900 * size of kmem_list3.
1902 static void set_up_list3s(struct kmem_cache *cachep, int index)
1904 int node;
1906 for_each_online_node(node) {
1907 cachep->nodelists[node] = &initkmem_list3[index + node];
1908 cachep->nodelists[node]->next_reap = jiffies +
1909 REAPTIMEOUT_LIST3 +
1910 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1914 static void __kmem_cache_destroy(struct kmem_cache *cachep)
1916 int i;
1917 struct kmem_list3 *l3;
1919 for_each_online_cpu(i)
1920 kfree(cachep->array[i]);
1922 /* NUMA: free the list3 structures */
1923 for_each_online_node(i) {
1924 l3 = cachep->nodelists[i];
1925 if (l3) {
1926 kfree(l3->shared);
1927 free_alien_cache(l3->alien);
1928 kfree(l3);
1931 kmem_cache_free(&cache_cache, cachep);
1936 * calculate_slab_order - calculate size (page order) of slabs
1937 * @cachep: pointer to the cache that is being created
1938 * @size: size of objects to be created in this cache.
1939 * @align: required alignment for the objects.
1940 * @flags: slab allocation flags
1942 * Also calculates the number of objects per slab.
1944 * This could be made much more intelligent. For now, try to avoid using
1945 * high order pages for slabs. When the gfp() functions are more friendly
1946 * towards high-order requests, this should be changed.
1948 static size_t calculate_slab_order(struct kmem_cache *cachep,
1949 size_t size, size_t align, unsigned long flags)
1951 unsigned long offslab_limit;
1952 size_t left_over = 0;
1953 int gfporder;
1955 for (gfporder = 0; gfporder <= MAX_GFP_ORDER; gfporder++) {
1956 unsigned int num;
1957 size_t remainder;
1959 cache_estimate(gfporder, size, align, flags, &remainder, &num);
1960 if (!num)
1961 continue;
1963 if (flags & CFLGS_OFF_SLAB) {
1965 * Max number of objs-per-slab for caches which
1966 * use off-slab slabs. Needed to avoid a possible
1967 * looping condition in cache_grow().
1969 offslab_limit = size - sizeof(struct slab);
1970 offslab_limit /= sizeof(kmem_bufctl_t);
1972 if (num > offslab_limit)
1973 break;
1976 /* Found something acceptable - save it away */
1977 cachep->num = num;
1978 cachep->gfporder = gfporder;
1979 left_over = remainder;
1982 * A VFS-reclaimable slab tends to have most allocations
1983 * as GFP_NOFS and we really don't want to have to be allocating
1984 * higher-order pages when we are unable to shrink dcache.
1986 if (flags & SLAB_RECLAIM_ACCOUNT)
1987 break;
1990 * Large number of objects is good, but very large slabs are
1991 * currently bad for the gfp()s.
1993 if (gfporder >= slab_break_gfp_order)
1994 break;
1997 * Acceptable internal fragmentation?
1999 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2000 break;
2002 return left_over;
2005 static int setup_cpu_cache(struct kmem_cache *cachep)
2007 if (g_cpucache_up == FULL)
2008 return enable_cpucache(cachep);
2010 if (g_cpucache_up == NONE) {
2012 * Note: the first kmem_cache_create must create the cache
2013 * that's used by kmalloc(24), otherwise the creation of
2014 * further caches will BUG().
2016 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2019 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2020 * the first cache, then we need to set up all its list3s,
2021 * otherwise the creation of further caches will BUG().
2023 set_up_list3s(cachep, SIZE_AC);
2024 if (INDEX_AC == INDEX_L3)
2025 g_cpucache_up = PARTIAL_L3;
2026 else
2027 g_cpucache_up = PARTIAL_AC;
2028 } else {
2029 cachep->array[smp_processor_id()] =
2030 kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
2032 if (g_cpucache_up == PARTIAL_AC) {
2033 set_up_list3s(cachep, SIZE_L3);
2034 g_cpucache_up = PARTIAL_L3;
2035 } else {
2036 int node;
2037 for_each_online_node(node) {
2038 cachep->nodelists[node] =
2039 kmalloc_node(sizeof(struct kmem_list3),
2040 GFP_KERNEL, node);
2041 BUG_ON(!cachep->nodelists[node]);
2042 kmem_list3_init(cachep->nodelists[node]);
2046 cachep->nodelists[numa_node_id()]->next_reap =
2047 jiffies + REAPTIMEOUT_LIST3 +
2048 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2050 cpu_cache_get(cachep)->avail = 0;
2051 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2052 cpu_cache_get(cachep)->batchcount = 1;
2053 cpu_cache_get(cachep)->touched = 0;
2054 cachep->batchcount = 1;
2055 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2056 return 0;
2060 * kmem_cache_create - Create a cache.
2061 * @name: A string which is used in /proc/slabinfo to identify this cache.
2062 * @size: The size of objects to be created in this cache.
2063 * @align: The required alignment for the objects.
2064 * @flags: SLAB flags
2065 * @ctor: A constructor for the objects.
2066 * @dtor: A destructor for the objects.
2068 * Returns a ptr to the cache on success, NULL on failure.
2069 * Cannot be called within a int, but can be interrupted.
2070 * The @ctor is run when new pages are allocated by the cache
2071 * and the @dtor is run before the pages are handed back.
2073 * @name must be valid until the cache is destroyed. This implies that
2074 * the module calling this has to destroy the cache before getting unloaded.
2076 * The flags are
2078 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2079 * to catch references to uninitialised memory.
2081 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2082 * for buffer overruns.
2084 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2085 * cacheline. This can be beneficial if you're counting cycles as closely
2086 * as davem.
2088 struct kmem_cache *
2089 kmem_cache_create (const char *name, size_t size, size_t align,
2090 unsigned long flags,
2091 void (*ctor)(void*, struct kmem_cache *, unsigned long),
2092 void (*dtor)(void*, struct kmem_cache *, unsigned long))
2094 size_t left_over, slab_size, ralign;
2095 struct kmem_cache *cachep = NULL, *pc;
2098 * Sanity checks... these are all serious usage bugs.
2100 if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
2101 (size > (1 << MAX_OBJ_ORDER) * PAGE_SIZE) || (dtor && !ctor)) {
2102 printk(KERN_ERR "%s: Early error in slab %s\n", __FUNCTION__,
2103 name);
2104 BUG();
2108 * We use cache_chain_mutex to ensure a consistent view of
2109 * cpu_online_map as well. Please see cpuup_callback
2111 mutex_lock(&cache_chain_mutex);
2113 list_for_each_entry(pc, &cache_chain, next) {
2114 mm_segment_t old_fs = get_fs();
2115 char tmp;
2116 int res;
2119 * This happens when the module gets unloaded and doesn't
2120 * destroy its slab cache and no-one else reuses the vmalloc
2121 * area of the module. Print a warning.
2123 set_fs(KERNEL_DS);
2124 res = __get_user(tmp, pc->name);
2125 set_fs(old_fs);
2126 if (res) {
2127 printk("SLAB: cache with size %d has lost its name\n",
2128 pc->buffer_size);
2129 continue;
2132 if (!strcmp(pc->name, name)) {
2133 printk("kmem_cache_create: duplicate cache %s\n", name);
2134 dump_stack();
2135 goto oops;
2139 #if DEBUG
2140 WARN_ON(strchr(name, ' ')); /* It confuses parsers */
2141 if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
2142 /* No constructor, but inital state check requested */
2143 printk(KERN_ERR "%s: No con, but init state check "
2144 "requested - %s\n", __FUNCTION__, name);
2145 flags &= ~SLAB_DEBUG_INITIAL;
2147 #if FORCED_DEBUG
2149 * Enable redzoning and last user accounting, except for caches with
2150 * large objects, if the increased size would increase the object size
2151 * above the next power of two: caches with object sizes just above a
2152 * power of two have a significant amount of internal fragmentation.
2154 if (size < 4096 || fls(size - 1) == fls(size-1 + 3 * BYTES_PER_WORD))
2155 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2156 if (!(flags & SLAB_DESTROY_BY_RCU))
2157 flags |= SLAB_POISON;
2158 #endif
2159 if (flags & SLAB_DESTROY_BY_RCU)
2160 BUG_ON(flags & SLAB_POISON);
2161 #endif
2162 if (flags & SLAB_DESTROY_BY_RCU)
2163 BUG_ON(dtor);
2166 * Always checks flags, a caller might be expecting debug support which
2167 * isn't available.
2169 BUG_ON(flags & ~CREATE_MASK);
2172 * Check that size is in terms of words. This is needed to avoid
2173 * unaligned accesses for some archs when redzoning is used, and makes
2174 * sure any on-slab bufctl's are also correctly aligned.
2176 if (size & (BYTES_PER_WORD - 1)) {
2177 size += (BYTES_PER_WORD - 1);
2178 size &= ~(BYTES_PER_WORD - 1);
2181 /* calculate the final buffer alignment: */
2183 /* 1) arch recommendation: can be overridden for debug */
2184 if (flags & SLAB_HWCACHE_ALIGN) {
2186 * Default alignment: as specified by the arch code. Except if
2187 * an object is really small, then squeeze multiple objects into
2188 * one cacheline.
2190 ralign = cache_line_size();
2191 while (size <= ralign / 2)
2192 ralign /= 2;
2193 } else {
2194 ralign = BYTES_PER_WORD;
2198 * Redzoning and user store require word alignment. Note this will be
2199 * overridden by architecture or caller mandated alignment if either
2200 * is greater than BYTES_PER_WORD.
2202 if (flags & SLAB_RED_ZONE || flags & SLAB_STORE_USER)
2203 ralign = BYTES_PER_WORD;
2205 /* 2) arch mandated alignment */
2206 if (ralign < ARCH_SLAB_MINALIGN) {
2207 ralign = ARCH_SLAB_MINALIGN;
2209 /* 3) caller mandated alignment */
2210 if (ralign < align) {
2211 ralign = align;
2213 /* disable debug if necessary */
2214 if (ralign > BYTES_PER_WORD)
2215 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2217 * 4) Store it.
2219 align = ralign;
2221 /* Get cache's description obj. */
2222 cachep = kmem_cache_zalloc(&cache_cache, SLAB_KERNEL);
2223 if (!cachep)
2224 goto oops;
2226 #if DEBUG
2227 cachep->obj_size = size;
2230 * Both debugging options require word-alignment which is calculated
2231 * into align above.
2233 if (flags & SLAB_RED_ZONE) {
2234 /* add space for red zone words */
2235 cachep->obj_offset += BYTES_PER_WORD;
2236 size += 2 * BYTES_PER_WORD;
2238 if (flags & SLAB_STORE_USER) {
2239 /* user store requires one word storage behind the end of
2240 * the real object.
2242 size += BYTES_PER_WORD;
2244 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2245 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2246 && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2247 cachep->obj_offset += PAGE_SIZE - size;
2248 size = PAGE_SIZE;
2250 #endif
2251 #endif
2254 * Determine if the slab management is 'on' or 'off' slab.
2255 * (bootstrapping cannot cope with offslab caches so don't do
2256 * it too early on.)
2258 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init)
2260 * Size is large, assume best to place the slab management obj
2261 * off-slab (should allow better packing of objs).
2263 flags |= CFLGS_OFF_SLAB;
2265 size = ALIGN(size, align);
2267 left_over = calculate_slab_order(cachep, size, align, flags);
2269 if (!cachep->num) {
2270 printk("kmem_cache_create: couldn't create cache %s.\n", name);
2271 kmem_cache_free(&cache_cache, cachep);
2272 cachep = NULL;
2273 goto oops;
2275 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2276 + sizeof(struct slab), align);
2279 * If the slab has been placed off-slab, and we have enough space then
2280 * move it on-slab. This is at the expense of any extra colouring.
2282 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2283 flags &= ~CFLGS_OFF_SLAB;
2284 left_over -= slab_size;
2287 if (flags & CFLGS_OFF_SLAB) {
2288 /* really off slab. No need for manual alignment */
2289 slab_size =
2290 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2293 cachep->colour_off = cache_line_size();
2294 /* Offset must be a multiple of the alignment. */
2295 if (cachep->colour_off < align)
2296 cachep->colour_off = align;
2297 cachep->colour = left_over / cachep->colour_off;
2298 cachep->slab_size = slab_size;
2299 cachep->flags = flags;
2300 cachep->gfpflags = 0;
2301 if (flags & SLAB_CACHE_DMA)
2302 cachep->gfpflags |= GFP_DMA;
2303 cachep->buffer_size = size;
2305 if (flags & CFLGS_OFF_SLAB) {
2306 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2308 * This is a possibility for one of the malloc_sizes caches.
2309 * But since we go off slab only for object size greater than
2310 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2311 * this should not happen at all.
2312 * But leave a BUG_ON for some lucky dude.
2314 BUG_ON(!cachep->slabp_cache);
2316 cachep->ctor = ctor;
2317 cachep->dtor = dtor;
2318 cachep->name = name;
2320 if (setup_cpu_cache(cachep)) {
2321 __kmem_cache_destroy(cachep);
2322 cachep = NULL;
2323 goto oops;
2326 /* cache setup completed, link it into the list */
2327 list_add(&cachep->next, &cache_chain);
2328 oops:
2329 if (!cachep && (flags & SLAB_PANIC))
2330 panic("kmem_cache_create(): failed to create slab `%s'\n",
2331 name);
2332 mutex_unlock(&cache_chain_mutex);
2333 return cachep;
2335 EXPORT_SYMBOL(kmem_cache_create);
2337 #if DEBUG
2338 static void check_irq_off(void)
2340 BUG_ON(!irqs_disabled());
2343 static void check_irq_on(void)
2345 BUG_ON(irqs_disabled());
2348 static void check_spinlock_acquired(struct kmem_cache *cachep)
2350 #ifdef CONFIG_SMP
2351 check_irq_off();
2352 assert_spin_locked(&cachep->nodelists[numa_node_id()]->list_lock);
2353 #endif
2356 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2358 #ifdef CONFIG_SMP
2359 check_irq_off();
2360 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2361 #endif
2364 #else
2365 #define check_irq_off() do { } while(0)
2366 #define check_irq_on() do { } while(0)
2367 #define check_spinlock_acquired(x) do { } while(0)
2368 #define check_spinlock_acquired_node(x, y) do { } while(0)
2369 #endif
2371 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2372 struct array_cache *ac,
2373 int force, int node);
2375 static void do_drain(void *arg)
2377 struct kmem_cache *cachep = arg;
2378 struct array_cache *ac;
2379 int node = numa_node_id();
2381 check_irq_off();
2382 ac = cpu_cache_get(cachep);
2383 spin_lock(&cachep->nodelists[node]->list_lock);
2384 free_block(cachep, ac->entry, ac->avail, node);
2385 spin_unlock(&cachep->nodelists[node]->list_lock);
2386 ac->avail = 0;
2389 static void drain_cpu_caches(struct kmem_cache *cachep)
2391 struct kmem_list3 *l3;
2392 int node;
2394 on_each_cpu(do_drain, cachep, 1, 1);
2395 check_irq_on();
2396 for_each_online_node(node) {
2397 l3 = cachep->nodelists[node];
2398 if (l3 && l3->alien)
2399 drain_alien_cache(cachep, l3->alien);
2402 for_each_online_node(node) {
2403 l3 = cachep->nodelists[node];
2404 if (l3)
2405 drain_array(cachep, l3, l3->shared, 1, node);
2410 * Remove slabs from the list of free slabs.
2411 * Specify the number of slabs to drain in tofree.
2413 * Returns the actual number of slabs released.
2415 static int drain_freelist(struct kmem_cache *cache,
2416 struct kmem_list3 *l3, int tofree)
2418 struct list_head *p;
2419 int nr_freed;
2420 struct slab *slabp;
2422 nr_freed = 0;
2423 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2425 spin_lock_irq(&l3->list_lock);
2426 p = l3->slabs_free.prev;
2427 if (p == &l3->slabs_free) {
2428 spin_unlock_irq(&l3->list_lock);
2429 goto out;
2432 slabp = list_entry(p, struct slab, list);
2433 #if DEBUG
2434 BUG_ON(slabp->inuse);
2435 #endif
2436 list_del(&slabp->list);
2438 * Safe to drop the lock. The slab is no longer linked
2439 * to the cache.
2441 l3->free_objects -= cache->num;
2442 spin_unlock_irq(&l3->list_lock);
2443 slab_destroy(cache, slabp);
2444 nr_freed++;
2446 out:
2447 return nr_freed;
2450 /* Called with cache_chain_mutex held to protect against cpu hotplug */
2451 static int __cache_shrink(struct kmem_cache *cachep)
2453 int ret = 0, i = 0;
2454 struct kmem_list3 *l3;
2456 drain_cpu_caches(cachep);
2458 check_irq_on();
2459 for_each_online_node(i) {
2460 l3 = cachep->nodelists[i];
2461 if (!l3)
2462 continue;
2464 drain_freelist(cachep, l3, l3->free_objects);
2466 ret += !list_empty(&l3->slabs_full) ||
2467 !list_empty(&l3->slabs_partial);
2469 return (ret ? 1 : 0);
2473 * kmem_cache_shrink - Shrink a cache.
2474 * @cachep: The cache to shrink.
2476 * Releases as many slabs as possible for a cache.
2477 * To help debugging, a zero exit status indicates all slabs were released.
2479 int kmem_cache_shrink(struct kmem_cache *cachep)
2481 int ret;
2482 BUG_ON(!cachep || in_interrupt());
2484 mutex_lock(&cache_chain_mutex);
2485 ret = __cache_shrink(cachep);
2486 mutex_unlock(&cache_chain_mutex);
2487 return ret;
2489 EXPORT_SYMBOL(kmem_cache_shrink);
2492 * kmem_cache_destroy - delete a cache
2493 * @cachep: the cache to destroy
2495 * Remove a struct kmem_cache object from the slab cache.
2497 * It is expected this function will be called by a module when it is
2498 * unloaded. This will remove the cache completely, and avoid a duplicate
2499 * cache being allocated each time a module is loaded and unloaded, if the
2500 * module doesn't have persistent in-kernel storage across loads and unloads.
2502 * The cache must be empty before calling this function.
2504 * The caller must guarantee that noone will allocate memory from the cache
2505 * during the kmem_cache_destroy().
2507 void kmem_cache_destroy(struct kmem_cache *cachep)
2509 BUG_ON(!cachep || in_interrupt());
2511 /* Find the cache in the chain of caches. */
2512 mutex_lock(&cache_chain_mutex);
2514 * the chain is never empty, cache_cache is never destroyed
2516 list_del(&cachep->next);
2517 if (__cache_shrink(cachep)) {
2518 slab_error(cachep, "Can't free all objects");
2519 list_add(&cachep->next, &cache_chain);
2520 mutex_unlock(&cache_chain_mutex);
2521 return;
2524 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2525 synchronize_rcu();
2527 __kmem_cache_destroy(cachep);
2528 mutex_unlock(&cache_chain_mutex);
2530 EXPORT_SYMBOL(kmem_cache_destroy);
2533 * Get the memory for a slab management obj.
2534 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2535 * always come from malloc_sizes caches. The slab descriptor cannot
2536 * come from the same cache which is getting created because,
2537 * when we are searching for an appropriate cache for these
2538 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2539 * If we are creating a malloc_sizes cache here it would not be visible to
2540 * kmem_find_general_cachep till the initialization is complete.
2541 * Hence we cannot have slabp_cache same as the original cache.
2543 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2544 int colour_off, gfp_t local_flags,
2545 int nodeid)
2547 struct slab *slabp;
2549 if (OFF_SLAB(cachep)) {
2550 /* Slab management obj is off-slab. */
2551 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2552 local_flags, nodeid);
2553 if (!slabp)
2554 return NULL;
2555 } else {
2556 slabp = objp + colour_off;
2557 colour_off += cachep->slab_size;
2559 slabp->inuse = 0;
2560 slabp->colouroff = colour_off;
2561 slabp->s_mem = objp + colour_off;
2562 slabp->nodeid = nodeid;
2563 return slabp;
2566 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2568 return (kmem_bufctl_t *) (slabp + 1);
2571 static void cache_init_objs(struct kmem_cache *cachep,
2572 struct slab *slabp, unsigned long ctor_flags)
2574 int i;
2576 for (i = 0; i < cachep->num; i++) {
2577 void *objp = index_to_obj(cachep, slabp, i);
2578 #if DEBUG
2579 /* need to poison the objs? */
2580 if (cachep->flags & SLAB_POISON)
2581 poison_obj(cachep, objp, POISON_FREE);
2582 if (cachep->flags & SLAB_STORE_USER)
2583 *dbg_userword(cachep, objp) = NULL;
2585 if (cachep->flags & SLAB_RED_ZONE) {
2586 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2587 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2590 * Constructors are not allowed to allocate memory from the same
2591 * cache which they are a constructor for. Otherwise, deadlock.
2592 * They must also be threaded.
2594 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2595 cachep->ctor(objp + obj_offset(cachep), cachep,
2596 ctor_flags);
2598 if (cachep->flags & SLAB_RED_ZONE) {
2599 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2600 slab_error(cachep, "constructor overwrote the"
2601 " end of an object");
2602 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2603 slab_error(cachep, "constructor overwrote the"
2604 " start of an object");
2606 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2607 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2608 kernel_map_pages(virt_to_page(objp),
2609 cachep->buffer_size / PAGE_SIZE, 0);
2610 #else
2611 if (cachep->ctor)
2612 cachep->ctor(objp, cachep, ctor_flags);
2613 #endif
2614 slab_bufctl(slabp)[i] = i + 1;
2616 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2617 slabp->free = 0;
2620 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2622 if (flags & SLAB_DMA)
2623 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2624 else
2625 BUG_ON(cachep->gfpflags & GFP_DMA);
2628 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2629 int nodeid)
2631 void *objp = index_to_obj(cachep, slabp, slabp->free);
2632 kmem_bufctl_t next;
2634 slabp->inuse++;
2635 next = slab_bufctl(slabp)[slabp->free];
2636 #if DEBUG
2637 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2638 WARN_ON(slabp->nodeid != nodeid);
2639 #endif
2640 slabp->free = next;
2642 return objp;
2645 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2646 void *objp, int nodeid)
2648 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2650 #if DEBUG
2651 /* Verify that the slab belongs to the intended node */
2652 WARN_ON(slabp->nodeid != nodeid);
2654 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2655 printk(KERN_ERR "slab: double free detected in cache "
2656 "'%s', objp %p\n", cachep->name, objp);
2657 BUG();
2659 #endif
2660 slab_bufctl(slabp)[objnr] = slabp->free;
2661 slabp->free = objnr;
2662 slabp->inuse--;
2666 * Map pages beginning at addr to the given cache and slab. This is required
2667 * for the slab allocator to be able to lookup the cache and slab of a
2668 * virtual address for kfree, ksize, kmem_ptr_validate, and slab debugging.
2670 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2671 void *addr)
2673 int nr_pages;
2674 struct page *page;
2676 page = virt_to_page(addr);
2678 nr_pages = 1;
2679 if (likely(!PageCompound(page)))
2680 nr_pages <<= cache->gfporder;
2682 do {
2683 page_set_cache(page, cache);
2684 page_set_slab(page, slab);
2685 page++;
2686 } while (--nr_pages);
2690 * Grow (by 1) the number of slabs within a cache. This is called by
2691 * kmem_cache_alloc() when there are no active objs left in a cache.
2693 static int cache_grow(struct kmem_cache *cachep, gfp_t flags, int nodeid)
2695 struct slab *slabp;
2696 void *objp;
2697 size_t offset;
2698 gfp_t local_flags;
2699 unsigned long ctor_flags;
2700 struct kmem_list3 *l3;
2703 * Be lazy and only check for valid flags here, keeping it out of the
2704 * critical path in kmem_cache_alloc().
2706 BUG_ON(flags & ~(SLAB_DMA | SLAB_LEVEL_MASK | SLAB_NO_GROW));
2707 if (flags & SLAB_NO_GROW)
2708 return 0;
2710 ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2711 local_flags = (flags & SLAB_LEVEL_MASK);
2712 if (!(local_flags & __GFP_WAIT))
2714 * Not allowed to sleep. Need to tell a constructor about
2715 * this - it might need to know...
2717 ctor_flags |= SLAB_CTOR_ATOMIC;
2719 /* Take the l3 list lock to change the colour_next on this node */
2720 check_irq_off();
2721 l3 = cachep->nodelists[nodeid];
2722 spin_lock(&l3->list_lock);
2724 /* Get colour for the slab, and cal the next value. */
2725 offset = l3->colour_next;
2726 l3->colour_next++;
2727 if (l3->colour_next >= cachep->colour)
2728 l3->colour_next = 0;
2729 spin_unlock(&l3->list_lock);
2731 offset *= cachep->colour_off;
2733 if (local_flags & __GFP_WAIT)
2734 local_irq_enable();
2737 * The test for missing atomic flag is performed here, rather than
2738 * the more obvious place, simply to reduce the critical path length
2739 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2740 * will eventually be caught here (where it matters).
2742 kmem_flagcheck(cachep, flags);
2745 * Get mem for the objs. Attempt to allocate a physical page from
2746 * 'nodeid'.
2748 objp = kmem_getpages(cachep, flags, nodeid);
2749 if (!objp)
2750 goto failed;
2752 /* Get slab management. */
2753 slabp = alloc_slabmgmt(cachep, objp, offset, local_flags, nodeid);
2754 if (!slabp)
2755 goto opps1;
2757 slabp->nodeid = nodeid;
2758 slab_map_pages(cachep, slabp, objp);
2760 cache_init_objs(cachep, slabp, ctor_flags);
2762 if (local_flags & __GFP_WAIT)
2763 local_irq_disable();
2764 check_irq_off();
2765 spin_lock(&l3->list_lock);
2767 /* Make slab active. */
2768 list_add_tail(&slabp->list, &(l3->slabs_free));
2769 STATS_INC_GROWN(cachep);
2770 l3->free_objects += cachep->num;
2771 spin_unlock(&l3->list_lock);
2772 return 1;
2773 opps1:
2774 kmem_freepages(cachep, objp);
2775 failed:
2776 if (local_flags & __GFP_WAIT)
2777 local_irq_disable();
2778 return 0;
2781 #if DEBUG
2784 * Perform extra freeing checks:
2785 * - detect bad pointers.
2786 * - POISON/RED_ZONE checking
2787 * - destructor calls, for caches with POISON+dtor
2789 static void kfree_debugcheck(const void *objp)
2791 struct page *page;
2793 if (!virt_addr_valid(objp)) {
2794 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2795 (unsigned long)objp);
2796 BUG();
2798 page = virt_to_page(objp);
2799 if (!PageSlab(page)) {
2800 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n",
2801 (unsigned long)objp);
2802 BUG();
2806 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2808 unsigned long redzone1, redzone2;
2810 redzone1 = *dbg_redzone1(cache, obj);
2811 redzone2 = *dbg_redzone2(cache, obj);
2814 * Redzone is ok.
2816 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2817 return;
2819 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2820 slab_error(cache, "double free detected");
2821 else
2822 slab_error(cache, "memory outside object was overwritten");
2824 printk(KERN_ERR "%p: redzone 1:0x%lx, redzone 2:0x%lx.\n",
2825 obj, redzone1, redzone2);
2828 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2829 void *caller)
2831 struct page *page;
2832 unsigned int objnr;
2833 struct slab *slabp;
2835 objp -= obj_offset(cachep);
2836 kfree_debugcheck(objp);
2837 page = virt_to_page(objp);
2839 slabp = page_get_slab(page);
2841 if (cachep->flags & SLAB_RED_ZONE) {
2842 verify_redzone_free(cachep, objp);
2843 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2844 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2846 if (cachep->flags & SLAB_STORE_USER)
2847 *dbg_userword(cachep, objp) = caller;
2849 objnr = obj_to_index(cachep, slabp, objp);
2851 BUG_ON(objnr >= cachep->num);
2852 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2854 if (cachep->flags & SLAB_DEBUG_INITIAL) {
2856 * Need to call the slab's constructor so the caller can
2857 * perform a verify of its state (debugging). Called without
2858 * the cache-lock held.
2860 cachep->ctor(objp + obj_offset(cachep),
2861 cachep, SLAB_CTOR_CONSTRUCTOR | SLAB_CTOR_VERIFY);
2863 if (cachep->flags & SLAB_POISON && cachep->dtor) {
2864 /* we want to cache poison the object,
2865 * call the destruction callback
2867 cachep->dtor(objp + obj_offset(cachep), cachep, 0);
2869 #ifdef CONFIG_DEBUG_SLAB_LEAK
2870 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2871 #endif
2872 if (cachep->flags & SLAB_POISON) {
2873 #ifdef CONFIG_DEBUG_PAGEALLOC
2874 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2875 store_stackinfo(cachep, objp, (unsigned long)caller);
2876 kernel_map_pages(virt_to_page(objp),
2877 cachep->buffer_size / PAGE_SIZE, 0);
2878 } else {
2879 poison_obj(cachep, objp, POISON_FREE);
2881 #else
2882 poison_obj(cachep, objp, POISON_FREE);
2883 #endif
2885 return objp;
2888 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
2890 kmem_bufctl_t i;
2891 int entries = 0;
2893 /* Check slab's freelist to see if this obj is there. */
2894 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2895 entries++;
2896 if (entries > cachep->num || i >= cachep->num)
2897 goto bad;
2899 if (entries != cachep->num - slabp->inuse) {
2900 bad:
2901 printk(KERN_ERR "slab: Internal list corruption detected in "
2902 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2903 cachep->name, cachep->num, slabp, slabp->inuse);
2904 for (i = 0;
2905 i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
2906 i++) {
2907 if (i % 16 == 0)
2908 printk("\n%03x:", i);
2909 printk(" %02x", ((unsigned char *)slabp)[i]);
2911 printk("\n");
2912 BUG();
2915 #else
2916 #define kfree_debugcheck(x) do { } while(0)
2917 #define cache_free_debugcheck(x,objp,z) (objp)
2918 #define check_slabp(x,y) do { } while(0)
2919 #endif
2921 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2923 int batchcount;
2924 struct kmem_list3 *l3;
2925 struct array_cache *ac;
2926 int node;
2928 node = numa_node_id();
2930 check_irq_off();
2931 ac = cpu_cache_get(cachep);
2932 retry:
2933 batchcount = ac->batchcount;
2934 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2936 * If there was little recent activity on this cache, then
2937 * perform only a partial refill. Otherwise we could generate
2938 * refill bouncing.
2940 batchcount = BATCHREFILL_LIMIT;
2942 l3 = cachep->nodelists[node];
2944 BUG_ON(ac->avail > 0 || !l3);
2945 spin_lock(&l3->list_lock);
2947 /* See if we can refill from the shared array */
2948 if (l3->shared && transfer_objects(ac, l3->shared, batchcount))
2949 goto alloc_done;
2951 while (batchcount > 0) {
2952 struct list_head *entry;
2953 struct slab *slabp;
2954 /* Get slab alloc is to come from. */
2955 entry = l3->slabs_partial.next;
2956 if (entry == &l3->slabs_partial) {
2957 l3->free_touched = 1;
2958 entry = l3->slabs_free.next;
2959 if (entry == &l3->slabs_free)
2960 goto must_grow;
2963 slabp = list_entry(entry, struct slab, list);
2964 check_slabp(cachep, slabp);
2965 check_spinlock_acquired(cachep);
2966 while (slabp->inuse < cachep->num && batchcount--) {
2967 STATS_INC_ALLOCED(cachep);
2968 STATS_INC_ACTIVE(cachep);
2969 STATS_SET_HIGH(cachep);
2971 ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
2972 node);
2974 check_slabp(cachep, slabp);
2976 /* move slabp to correct slabp list: */
2977 list_del(&slabp->list);
2978 if (slabp->free == BUFCTL_END)
2979 list_add(&slabp->list, &l3->slabs_full);
2980 else
2981 list_add(&slabp->list, &l3->slabs_partial);
2984 must_grow:
2985 l3->free_objects -= ac->avail;
2986 alloc_done:
2987 spin_unlock(&l3->list_lock);
2989 if (unlikely(!ac->avail)) {
2990 int x;
2991 x = cache_grow(cachep, flags, node);
2993 /* cache_grow can reenable interrupts, then ac could change. */
2994 ac = cpu_cache_get(cachep);
2995 if (!x && ac->avail == 0) /* no objects in sight? abort */
2996 return NULL;
2998 if (!ac->avail) /* objects refilled by interrupt? */
2999 goto retry;
3001 ac->touched = 1;
3002 return ac->entry[--ac->avail];
3005 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3006 gfp_t flags)
3008 might_sleep_if(flags & __GFP_WAIT);
3009 #if DEBUG
3010 kmem_flagcheck(cachep, flags);
3011 #endif
3014 #if DEBUG
3015 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3016 gfp_t flags, void *objp, void *caller)
3018 if (!objp)
3019 return objp;
3020 if (cachep->flags & SLAB_POISON) {
3021 #ifdef CONFIG_DEBUG_PAGEALLOC
3022 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3023 kernel_map_pages(virt_to_page(objp),
3024 cachep->buffer_size / PAGE_SIZE, 1);
3025 else
3026 check_poison_obj(cachep, objp);
3027 #else
3028 check_poison_obj(cachep, objp);
3029 #endif
3030 poison_obj(cachep, objp, POISON_INUSE);
3032 if (cachep->flags & SLAB_STORE_USER)
3033 *dbg_userword(cachep, objp) = caller;
3035 if (cachep->flags & SLAB_RED_ZONE) {
3036 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3037 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3038 slab_error(cachep, "double free, or memory outside"
3039 " object was overwritten");
3040 printk(KERN_ERR
3041 "%p: redzone 1:0x%lx, redzone 2:0x%lx\n",
3042 objp, *dbg_redzone1(cachep, objp),
3043 *dbg_redzone2(cachep, objp));
3045 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3046 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3048 #ifdef CONFIG_DEBUG_SLAB_LEAK
3050 struct slab *slabp;
3051 unsigned objnr;
3053 slabp = page_get_slab(virt_to_page(objp));
3054 objnr = (unsigned)(objp - slabp->s_mem) / cachep->buffer_size;
3055 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3057 #endif
3058 objp += obj_offset(cachep);
3059 if (cachep->ctor && cachep->flags & SLAB_POISON) {
3060 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
3062 if (!(flags & __GFP_WAIT))
3063 ctor_flags |= SLAB_CTOR_ATOMIC;
3065 cachep->ctor(objp, cachep, ctor_flags);
3067 #if ARCH_SLAB_MINALIGN
3068 if ((u32)objp & (ARCH_SLAB_MINALIGN-1)) {
3069 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3070 objp, ARCH_SLAB_MINALIGN);
3072 #endif
3073 return objp;
3075 #else
3076 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3077 #endif
3079 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3081 void *objp;
3082 struct array_cache *ac;
3084 check_irq_off();
3085 ac = cpu_cache_get(cachep);
3086 if (likely(ac->avail)) {
3087 STATS_INC_ALLOCHIT(cachep);
3088 ac->touched = 1;
3089 objp = ac->entry[--ac->avail];
3090 } else {
3091 STATS_INC_ALLOCMISS(cachep);
3092 objp = cache_alloc_refill(cachep, flags);
3094 return objp;
3097 static __always_inline void *__cache_alloc(struct kmem_cache *cachep,
3098 gfp_t flags, void *caller)
3100 unsigned long save_flags;
3101 void *objp = NULL;
3103 cache_alloc_debugcheck_before(cachep, flags);
3105 local_irq_save(save_flags);
3107 if (unlikely(NUMA_BUILD &&
3108 current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY)))
3109 objp = alternate_node_alloc(cachep, flags);
3111 if (!objp)
3112 objp = ____cache_alloc(cachep, flags);
3114 * We may just have run out of memory on the local node.
3115 * __cache_alloc_node() knows how to locate memory on other nodes
3117 if (NUMA_BUILD && !objp)
3118 objp = __cache_alloc_node(cachep, flags, numa_node_id());
3119 local_irq_restore(save_flags);
3120 objp = cache_alloc_debugcheck_after(cachep, flags, objp,
3121 caller);
3122 prefetchw(objp);
3123 return objp;
3126 #ifdef CONFIG_NUMA
3128 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3130 * If we are in_interrupt, then process context, including cpusets and
3131 * mempolicy, may not apply and should not be used for allocation policy.
3133 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3135 int nid_alloc, nid_here;
3137 if (in_interrupt() || (flags & __GFP_THISNODE))
3138 return NULL;
3139 nid_alloc = nid_here = numa_node_id();
3140 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3141 nid_alloc = cpuset_mem_spread_node();
3142 else if (current->mempolicy)
3143 nid_alloc = slab_node(current->mempolicy);
3144 if (nid_alloc != nid_here)
3145 return __cache_alloc_node(cachep, flags, nid_alloc);
3146 return NULL;
3150 * Fallback function if there was no memory available and no objects on a
3151 * certain node and we are allowed to fall back. We mimick the behavior of
3152 * the page allocator. We fall back according to a zonelist determined by
3153 * the policy layer while obeying cpuset constraints.
3155 void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3157 struct zonelist *zonelist = &NODE_DATA(slab_node(current->mempolicy))
3158 ->node_zonelists[gfp_zone(flags)];
3159 struct zone **z;
3160 void *obj = NULL;
3162 for (z = zonelist->zones; *z && !obj; z++) {
3163 int nid = zone_to_nid(*z);
3165 if (zone_idx(*z) <= ZONE_NORMAL &&
3166 cpuset_zone_allowed(*z, flags) &&
3167 cache->nodelists[nid])
3168 obj = __cache_alloc_node(cache,
3169 flags | __GFP_THISNODE, nid);
3171 return obj;
3175 * A interface to enable slab creation on nodeid
3177 static void *__cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3178 int nodeid)
3180 struct list_head *entry;
3181 struct slab *slabp;
3182 struct kmem_list3 *l3;
3183 void *obj;
3184 int x;
3186 l3 = cachep->nodelists[nodeid];
3187 BUG_ON(!l3);
3189 retry:
3190 check_irq_off();
3191 spin_lock(&l3->list_lock);
3192 entry = l3->slabs_partial.next;
3193 if (entry == &l3->slabs_partial) {
3194 l3->free_touched = 1;
3195 entry = l3->slabs_free.next;
3196 if (entry == &l3->slabs_free)
3197 goto must_grow;
3200 slabp = list_entry(entry, struct slab, list);
3201 check_spinlock_acquired_node(cachep, nodeid);
3202 check_slabp(cachep, slabp);
3204 STATS_INC_NODEALLOCS(cachep);
3205 STATS_INC_ACTIVE(cachep);
3206 STATS_SET_HIGH(cachep);
3208 BUG_ON(slabp->inuse == cachep->num);
3210 obj = slab_get_obj(cachep, slabp, nodeid);
3211 check_slabp(cachep, slabp);
3212 l3->free_objects--;
3213 /* move slabp to correct slabp list: */
3214 list_del(&slabp->list);
3216 if (slabp->free == BUFCTL_END)
3217 list_add(&slabp->list, &l3->slabs_full);
3218 else
3219 list_add(&slabp->list, &l3->slabs_partial);
3221 spin_unlock(&l3->list_lock);
3222 goto done;
3224 must_grow:
3225 spin_unlock(&l3->list_lock);
3226 x = cache_grow(cachep, flags, nodeid);
3227 if (x)
3228 goto retry;
3230 if (!(flags & __GFP_THISNODE))
3231 /* Unable to grow the cache. Fall back to other nodes. */
3232 return fallback_alloc(cachep, flags);
3234 return NULL;
3236 done:
3237 return obj;
3239 #endif
3242 * Caller needs to acquire correct kmem_list's list_lock
3244 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3245 int node)
3247 int i;
3248 struct kmem_list3 *l3;
3250 for (i = 0; i < nr_objects; i++) {
3251 void *objp = objpp[i];
3252 struct slab *slabp;
3254 slabp = virt_to_slab(objp);
3255 l3 = cachep->nodelists[node];
3256 list_del(&slabp->list);
3257 check_spinlock_acquired_node(cachep, node);
3258 check_slabp(cachep, slabp);
3259 slab_put_obj(cachep, slabp, objp, node);
3260 STATS_DEC_ACTIVE(cachep);
3261 l3->free_objects++;
3262 check_slabp(cachep, slabp);
3264 /* fixup slab chains */
3265 if (slabp->inuse == 0) {
3266 if (l3->free_objects > l3->free_limit) {
3267 l3->free_objects -= cachep->num;
3268 /* No need to drop any previously held
3269 * lock here, even if we have a off-slab slab
3270 * descriptor it is guaranteed to come from
3271 * a different cache, refer to comments before
3272 * alloc_slabmgmt.
3274 slab_destroy(cachep, slabp);
3275 } else {
3276 list_add(&slabp->list, &l3->slabs_free);
3278 } else {
3279 /* Unconditionally move a slab to the end of the
3280 * partial list on free - maximum time for the
3281 * other objects to be freed, too.
3283 list_add_tail(&slabp->list, &l3->slabs_partial);
3288 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3290 int batchcount;
3291 struct kmem_list3 *l3;
3292 int node = numa_node_id();
3294 batchcount = ac->batchcount;
3295 #if DEBUG
3296 BUG_ON(!batchcount || batchcount > ac->avail);
3297 #endif
3298 check_irq_off();
3299 l3 = cachep->nodelists[node];
3300 spin_lock(&l3->list_lock);
3301 if (l3->shared) {
3302 struct array_cache *shared_array = l3->shared;
3303 int max = shared_array->limit - shared_array->avail;
3304 if (max) {
3305 if (batchcount > max)
3306 batchcount = max;
3307 memcpy(&(shared_array->entry[shared_array->avail]),
3308 ac->entry, sizeof(void *) * batchcount);
3309 shared_array->avail += batchcount;
3310 goto free_done;
3314 free_block(cachep, ac->entry, batchcount, node);
3315 free_done:
3316 #if STATS
3318 int i = 0;
3319 struct list_head *p;
3321 p = l3->slabs_free.next;
3322 while (p != &(l3->slabs_free)) {
3323 struct slab *slabp;
3325 slabp = list_entry(p, struct slab, list);
3326 BUG_ON(slabp->inuse);
3328 i++;
3329 p = p->next;
3331 STATS_SET_FREEABLE(cachep, i);
3333 #endif
3334 spin_unlock(&l3->list_lock);
3335 ac->avail -= batchcount;
3336 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3340 * Release an obj back to its cache. If the obj has a constructed state, it must
3341 * be in this state _before_ it is released. Called with disabled ints.
3343 static inline void __cache_free(struct kmem_cache *cachep, void *objp)
3345 struct array_cache *ac = cpu_cache_get(cachep);
3347 check_irq_off();
3348 objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3350 if (cache_free_alien(cachep, objp))
3351 return;
3353 if (likely(ac->avail < ac->limit)) {
3354 STATS_INC_FREEHIT(cachep);
3355 ac->entry[ac->avail++] = objp;
3356 return;
3357 } else {
3358 STATS_INC_FREEMISS(cachep);
3359 cache_flusharray(cachep, ac);
3360 ac->entry[ac->avail++] = objp;
3365 * kmem_cache_alloc - Allocate an object
3366 * @cachep: The cache to allocate from.
3367 * @flags: See kmalloc().
3369 * Allocate an object from this cache. The flags are only relevant
3370 * if the cache has no available objects.
3372 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3374 return __cache_alloc(cachep, flags, __builtin_return_address(0));
3376 EXPORT_SYMBOL(kmem_cache_alloc);
3379 * kmem_cache_zalloc - Allocate an object. The memory is set to zero.
3380 * @cache: The cache to allocate from.
3381 * @flags: See kmalloc().
3383 * Allocate an object from this cache and set the allocated memory to zero.
3384 * The flags are only relevant if the cache has no available objects.
3386 void *kmem_cache_zalloc(struct kmem_cache *cache, gfp_t flags)
3388 void *ret = __cache_alloc(cache, flags, __builtin_return_address(0));
3389 if (ret)
3390 memset(ret, 0, obj_size(cache));
3391 return ret;
3393 EXPORT_SYMBOL(kmem_cache_zalloc);
3396 * kmem_ptr_validate - check if an untrusted pointer might
3397 * be a slab entry.
3398 * @cachep: the cache we're checking against
3399 * @ptr: pointer to validate
3401 * This verifies that the untrusted pointer looks sane:
3402 * it is _not_ a guarantee that the pointer is actually
3403 * part of the slab cache in question, but it at least
3404 * validates that the pointer can be dereferenced and
3405 * looks half-way sane.
3407 * Currently only used for dentry validation.
3409 int fastcall kmem_ptr_validate(struct kmem_cache *cachep, void *ptr)
3411 unsigned long addr = (unsigned long)ptr;
3412 unsigned long min_addr = PAGE_OFFSET;
3413 unsigned long align_mask = BYTES_PER_WORD - 1;
3414 unsigned long size = cachep->buffer_size;
3415 struct page *page;
3417 if (unlikely(addr < min_addr))
3418 goto out;
3419 if (unlikely(addr > (unsigned long)high_memory - size))
3420 goto out;
3421 if (unlikely(addr & align_mask))
3422 goto out;
3423 if (unlikely(!kern_addr_valid(addr)))
3424 goto out;
3425 if (unlikely(!kern_addr_valid(addr + size - 1)))
3426 goto out;
3427 page = virt_to_page(ptr);
3428 if (unlikely(!PageSlab(page)))
3429 goto out;
3430 if (unlikely(page_get_cache(page) != cachep))
3431 goto out;
3432 return 1;
3433 out:
3434 return 0;
3437 #ifdef CONFIG_NUMA
3439 * kmem_cache_alloc_node - Allocate an object on the specified node
3440 * @cachep: The cache to allocate from.
3441 * @flags: See kmalloc().
3442 * @nodeid: node number of the target node.
3444 * Identical to kmem_cache_alloc, except that this function is slow
3445 * and can sleep. And it will allocate memory on the given node, which
3446 * can improve the performance for cpu bound structures.
3447 * New and improved: it will now make sure that the object gets
3448 * put on the correct node list so that there is no false sharing.
3450 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3452 unsigned long save_flags;
3453 void *ptr;
3455 cache_alloc_debugcheck_before(cachep, flags);
3456 local_irq_save(save_flags);
3458 if (nodeid == -1 || nodeid == numa_node_id() ||
3459 !cachep->nodelists[nodeid])
3460 ptr = ____cache_alloc(cachep, flags);
3461 else
3462 ptr = __cache_alloc_node(cachep, flags, nodeid);
3463 local_irq_restore(save_flags);
3465 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr,
3466 __builtin_return_address(0));
3468 return ptr;
3470 EXPORT_SYMBOL(kmem_cache_alloc_node);
3472 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3474 struct kmem_cache *cachep;
3476 cachep = kmem_find_general_cachep(size, flags);
3477 if (unlikely(cachep == NULL))
3478 return NULL;
3479 return kmem_cache_alloc_node(cachep, flags, node);
3481 EXPORT_SYMBOL(__kmalloc_node);
3482 #endif
3485 * __do_kmalloc - allocate memory
3486 * @size: how many bytes of memory are required.
3487 * @flags: the type of memory to allocate (see kmalloc).
3488 * @caller: function caller for debug tracking of the caller
3490 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3491 void *caller)
3493 struct kmem_cache *cachep;
3495 /* If you want to save a few bytes .text space: replace
3496 * __ with kmem_.
3497 * Then kmalloc uses the uninlined functions instead of the inline
3498 * functions.
3500 cachep = __find_general_cachep(size, flags);
3501 if (unlikely(cachep == NULL))
3502 return NULL;
3503 return __cache_alloc(cachep, flags, caller);
3507 #ifdef CONFIG_DEBUG_SLAB
3508 void *__kmalloc(size_t size, gfp_t flags)
3510 return __do_kmalloc(size, flags, __builtin_return_address(0));
3512 EXPORT_SYMBOL(__kmalloc);
3514 void *__kmalloc_track_caller(size_t size, gfp_t flags, void *caller)
3516 return __do_kmalloc(size, flags, caller);
3518 EXPORT_SYMBOL(__kmalloc_track_caller);
3520 #else
3521 void *__kmalloc(size_t size, gfp_t flags)
3523 return __do_kmalloc(size, flags, NULL);
3525 EXPORT_SYMBOL(__kmalloc);
3526 #endif
3529 * kmem_cache_free - Deallocate an object
3530 * @cachep: The cache the allocation was from.
3531 * @objp: The previously allocated object.
3533 * Free an object which was previously allocated from this
3534 * cache.
3536 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3538 unsigned long flags;
3540 BUG_ON(virt_to_cache(objp) != cachep);
3542 local_irq_save(flags);
3543 __cache_free(cachep, objp);
3544 local_irq_restore(flags);
3546 EXPORT_SYMBOL(kmem_cache_free);
3549 * kfree - free previously allocated memory
3550 * @objp: pointer returned by kmalloc.
3552 * If @objp is NULL, no operation is performed.
3554 * Don't free memory not originally allocated by kmalloc()
3555 * or you will run into trouble.
3557 void kfree(const void *objp)
3559 struct kmem_cache *c;
3560 unsigned long flags;
3562 if (unlikely(!objp))
3563 return;
3564 local_irq_save(flags);
3565 kfree_debugcheck(objp);
3566 c = virt_to_cache(objp);
3567 debug_check_no_locks_freed(objp, obj_size(c));
3568 __cache_free(c, (void *)objp);
3569 local_irq_restore(flags);
3571 EXPORT_SYMBOL(kfree);
3573 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3575 return obj_size(cachep);
3577 EXPORT_SYMBOL(kmem_cache_size);
3579 const char *kmem_cache_name(struct kmem_cache *cachep)
3581 return cachep->name;
3583 EXPORT_SYMBOL_GPL(kmem_cache_name);
3586 * This initializes kmem_list3 or resizes varioius caches for all nodes.
3588 static int alloc_kmemlist(struct kmem_cache *cachep)
3590 int node;
3591 struct kmem_list3 *l3;
3592 struct array_cache *new_shared;
3593 struct array_cache **new_alien;
3595 for_each_online_node(node) {
3597 new_alien = alloc_alien_cache(node, cachep->limit);
3598 if (!new_alien)
3599 goto fail;
3601 new_shared = alloc_arraycache(node,
3602 cachep->shared*cachep->batchcount,
3603 0xbaadf00d);
3604 if (!new_shared) {
3605 free_alien_cache(new_alien);
3606 goto fail;
3609 l3 = cachep->nodelists[node];
3610 if (l3) {
3611 struct array_cache *shared = l3->shared;
3613 spin_lock_irq(&l3->list_lock);
3615 if (shared)
3616 free_block(cachep, shared->entry,
3617 shared->avail, node);
3619 l3->shared = new_shared;
3620 if (!l3->alien) {
3621 l3->alien = new_alien;
3622 new_alien = NULL;
3624 l3->free_limit = (1 + nr_cpus_node(node)) *
3625 cachep->batchcount + cachep->num;
3626 spin_unlock_irq(&l3->list_lock);
3627 kfree(shared);
3628 free_alien_cache(new_alien);
3629 continue;
3631 l3 = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, node);
3632 if (!l3) {
3633 free_alien_cache(new_alien);
3634 kfree(new_shared);
3635 goto fail;
3638 kmem_list3_init(l3);
3639 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3640 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3641 l3->shared = new_shared;
3642 l3->alien = new_alien;
3643 l3->free_limit = (1 + nr_cpus_node(node)) *
3644 cachep->batchcount + cachep->num;
3645 cachep->nodelists[node] = l3;
3647 return 0;
3649 fail:
3650 if (!cachep->next.next) {
3651 /* Cache is not active yet. Roll back what we did */
3652 node--;
3653 while (node >= 0) {
3654 if (cachep->nodelists[node]) {
3655 l3 = cachep->nodelists[node];
3657 kfree(l3->shared);
3658 free_alien_cache(l3->alien);
3659 kfree(l3);
3660 cachep->nodelists[node] = NULL;
3662 node--;
3665 return -ENOMEM;
3668 struct ccupdate_struct {
3669 struct kmem_cache *cachep;
3670 struct array_cache *new[NR_CPUS];
3673 static void do_ccupdate_local(void *info)
3675 struct ccupdate_struct *new = info;
3676 struct array_cache *old;
3678 check_irq_off();
3679 old = cpu_cache_get(new->cachep);
3681 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3682 new->new[smp_processor_id()] = old;
3685 /* Always called with the cache_chain_mutex held */
3686 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3687 int batchcount, int shared)
3689 struct ccupdate_struct *new;
3690 int i;
3692 new = kzalloc(sizeof(*new), GFP_KERNEL);
3693 if (!new)
3694 return -ENOMEM;
3696 for_each_online_cpu(i) {
3697 new->new[i] = alloc_arraycache(cpu_to_node(i), limit,
3698 batchcount);
3699 if (!new->new[i]) {
3700 for (i--; i >= 0; i--)
3701 kfree(new->new[i]);
3702 kfree(new);
3703 return -ENOMEM;
3706 new->cachep = cachep;
3708 on_each_cpu(do_ccupdate_local, (void *)new, 1, 1);
3710 check_irq_on();
3711 cachep->batchcount = batchcount;
3712 cachep->limit = limit;
3713 cachep->shared = shared;
3715 for_each_online_cpu(i) {
3716 struct array_cache *ccold = new->new[i];
3717 if (!ccold)
3718 continue;
3719 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3720 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
3721 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3722 kfree(ccold);
3724 kfree(new);
3725 return alloc_kmemlist(cachep);
3728 /* Called with cache_chain_mutex held always */
3729 static int enable_cpucache(struct kmem_cache *cachep)
3731 int err;
3732 int limit, shared;
3735 * The head array serves three purposes:
3736 * - create a LIFO ordering, i.e. return objects that are cache-warm
3737 * - reduce the number of spinlock operations.
3738 * - reduce the number of linked list operations on the slab and
3739 * bufctl chains: array operations are cheaper.
3740 * The numbers are guessed, we should auto-tune as described by
3741 * Bonwick.
3743 if (cachep->buffer_size > 131072)
3744 limit = 1;
3745 else if (cachep->buffer_size > PAGE_SIZE)
3746 limit = 8;
3747 else if (cachep->buffer_size > 1024)
3748 limit = 24;
3749 else if (cachep->buffer_size > 256)
3750 limit = 54;
3751 else
3752 limit = 120;
3755 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3756 * allocation behaviour: Most allocs on one cpu, most free operations
3757 * on another cpu. For these cases, an efficient object passing between
3758 * cpus is necessary. This is provided by a shared array. The array
3759 * replaces Bonwick's magazine layer.
3760 * On uniprocessor, it's functionally equivalent (but less efficient)
3761 * to a larger limit. Thus disabled by default.
3763 shared = 0;
3764 #ifdef CONFIG_SMP
3765 if (cachep->buffer_size <= PAGE_SIZE)
3766 shared = 8;
3767 #endif
3769 #if DEBUG
3771 * With debugging enabled, large batchcount lead to excessively long
3772 * periods with disabled local interrupts. Limit the batchcount
3774 if (limit > 32)
3775 limit = 32;
3776 #endif
3777 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared);
3778 if (err)
3779 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3780 cachep->name, -err);
3781 return err;
3785 * Drain an array if it contains any elements taking the l3 lock only if
3786 * necessary. Note that the l3 listlock also protects the array_cache
3787 * if drain_array() is used on the shared array.
3789 void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
3790 struct array_cache *ac, int force, int node)
3792 int tofree;
3794 if (!ac || !ac->avail)
3795 return;
3796 if (ac->touched && !force) {
3797 ac->touched = 0;
3798 } else {
3799 spin_lock_irq(&l3->list_lock);
3800 if (ac->avail) {
3801 tofree = force ? ac->avail : (ac->limit + 4) / 5;
3802 if (tofree > ac->avail)
3803 tofree = (ac->avail + 1) / 2;
3804 free_block(cachep, ac->entry, tofree, node);
3805 ac->avail -= tofree;
3806 memmove(ac->entry, &(ac->entry[tofree]),
3807 sizeof(void *) * ac->avail);
3809 spin_unlock_irq(&l3->list_lock);
3814 * cache_reap - Reclaim memory from caches.
3815 * @unused: unused parameter
3817 * Called from workqueue/eventd every few seconds.
3818 * Purpose:
3819 * - clear the per-cpu caches for this CPU.
3820 * - return freeable pages to the main free memory pool.
3822 * If we cannot acquire the cache chain mutex then just give up - we'll try
3823 * again on the next iteration.
3825 static void cache_reap(struct work_struct *unused)
3827 struct kmem_cache *searchp;
3828 struct kmem_list3 *l3;
3829 int node = numa_node_id();
3831 if (!mutex_trylock(&cache_chain_mutex)) {
3832 /* Give up. Setup the next iteration. */
3833 schedule_delayed_work(&__get_cpu_var(reap_work),
3834 REAPTIMEOUT_CPUC);
3835 return;
3838 list_for_each_entry(searchp, &cache_chain, next) {
3839 check_irq_on();
3842 * We only take the l3 lock if absolutely necessary and we
3843 * have established with reasonable certainty that
3844 * we can do some work if the lock was obtained.
3846 l3 = searchp->nodelists[node];
3848 reap_alien(searchp, l3);
3850 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
3853 * These are racy checks but it does not matter
3854 * if we skip one check or scan twice.
3856 if (time_after(l3->next_reap, jiffies))
3857 goto next;
3859 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
3861 drain_array(searchp, l3, l3->shared, 0, node);
3863 if (l3->free_touched)
3864 l3->free_touched = 0;
3865 else {
3866 int freed;
3868 freed = drain_freelist(searchp, l3, (l3->free_limit +
3869 5 * searchp->num - 1) / (5 * searchp->num));
3870 STATS_ADD_REAPED(searchp, freed);
3872 next:
3873 cond_resched();
3875 check_irq_on();
3876 mutex_unlock(&cache_chain_mutex);
3877 next_reap_node();
3878 refresh_cpu_vm_stats(smp_processor_id());
3879 /* Set up the next iteration */
3880 schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC);
3883 #ifdef CONFIG_PROC_FS
3885 static void print_slabinfo_header(struct seq_file *m)
3888 * Output format version, so at least we can change it
3889 * without _too_ many complaints.
3891 #if STATS
3892 seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
3893 #else
3894 seq_puts(m, "slabinfo - version: 2.1\n");
3895 #endif
3896 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
3897 "<objperslab> <pagesperslab>");
3898 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
3899 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
3900 #if STATS
3901 seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
3902 "<error> <maxfreeable> <nodeallocs> <remotefrees> <alienoverflow>");
3903 seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
3904 #endif
3905 seq_putc(m, '\n');
3908 static void *s_start(struct seq_file *m, loff_t *pos)
3910 loff_t n = *pos;
3911 struct list_head *p;
3913 mutex_lock(&cache_chain_mutex);
3914 if (!n)
3915 print_slabinfo_header(m);
3916 p = cache_chain.next;
3917 while (n--) {
3918 p = p->next;
3919 if (p == &cache_chain)
3920 return NULL;
3922 return list_entry(p, struct kmem_cache, next);
3925 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3927 struct kmem_cache *cachep = p;
3928 ++*pos;
3929 return cachep->next.next == &cache_chain ?
3930 NULL : list_entry(cachep->next.next, struct kmem_cache, next);
3933 static void s_stop(struct seq_file *m, void *p)
3935 mutex_unlock(&cache_chain_mutex);
3938 static int s_show(struct seq_file *m, void *p)
3940 struct kmem_cache *cachep = p;
3941 struct slab *slabp;
3942 unsigned long active_objs;
3943 unsigned long num_objs;
3944 unsigned long active_slabs = 0;
3945 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
3946 const char *name;
3947 char *error = NULL;
3948 int node;
3949 struct kmem_list3 *l3;
3951 active_objs = 0;
3952 num_slabs = 0;
3953 for_each_online_node(node) {
3954 l3 = cachep->nodelists[node];
3955 if (!l3)
3956 continue;
3958 check_irq_on();
3959 spin_lock_irq(&l3->list_lock);
3961 list_for_each_entry(slabp, &l3->slabs_full, list) {
3962 if (slabp->inuse != cachep->num && !error)
3963 error = "slabs_full accounting error";
3964 active_objs += cachep->num;
3965 active_slabs++;
3967 list_for_each_entry(slabp, &l3->slabs_partial, list) {
3968 if (slabp->inuse == cachep->num && !error)
3969 error = "slabs_partial inuse accounting error";
3970 if (!slabp->inuse && !error)
3971 error = "slabs_partial/inuse accounting error";
3972 active_objs += slabp->inuse;
3973 active_slabs++;
3975 list_for_each_entry(slabp, &l3->slabs_free, list) {
3976 if (slabp->inuse && !error)
3977 error = "slabs_free/inuse accounting error";
3978 num_slabs++;
3980 free_objects += l3->free_objects;
3981 if (l3->shared)
3982 shared_avail += l3->shared->avail;
3984 spin_unlock_irq(&l3->list_lock);
3986 num_slabs += active_slabs;
3987 num_objs = num_slabs * cachep->num;
3988 if (num_objs - active_objs != free_objects && !error)
3989 error = "free_objects accounting error";
3991 name = cachep->name;
3992 if (error)
3993 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3995 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
3996 name, active_objs, num_objs, cachep->buffer_size,
3997 cachep->num, (1 << cachep->gfporder));
3998 seq_printf(m, " : tunables %4u %4u %4u",
3999 cachep->limit, cachep->batchcount, cachep->shared);
4000 seq_printf(m, " : slabdata %6lu %6lu %6lu",
4001 active_slabs, num_slabs, shared_avail);
4002 #if STATS
4003 { /* list3 stats */
4004 unsigned long high = cachep->high_mark;
4005 unsigned long allocs = cachep->num_allocations;
4006 unsigned long grown = cachep->grown;
4007 unsigned long reaped = cachep->reaped;
4008 unsigned long errors = cachep->errors;
4009 unsigned long max_freeable = cachep->max_freeable;
4010 unsigned long node_allocs = cachep->node_allocs;
4011 unsigned long node_frees = cachep->node_frees;
4012 unsigned long overflows = cachep->node_overflow;
4014 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
4015 %4lu %4lu %4lu %4lu %4lu", allocs, high, grown,
4016 reaped, errors, max_freeable, node_allocs,
4017 node_frees, overflows);
4019 /* cpu stats */
4021 unsigned long allochit = atomic_read(&cachep->allochit);
4022 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4023 unsigned long freehit = atomic_read(&cachep->freehit);
4024 unsigned long freemiss = atomic_read(&cachep->freemiss);
4026 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4027 allochit, allocmiss, freehit, freemiss);
4029 #endif
4030 seq_putc(m, '\n');
4031 return 0;
4035 * slabinfo_op - iterator that generates /proc/slabinfo
4037 * Output layout:
4038 * cache-name
4039 * num-active-objs
4040 * total-objs
4041 * object size
4042 * num-active-slabs
4043 * total-slabs
4044 * num-pages-per-slab
4045 * + further values on SMP and with statistics enabled
4048 struct seq_operations slabinfo_op = {
4049 .start = s_start,
4050 .next = s_next,
4051 .stop = s_stop,
4052 .show = s_show,
4055 #define MAX_SLABINFO_WRITE 128
4057 * slabinfo_write - Tuning for the slab allocator
4058 * @file: unused
4059 * @buffer: user buffer
4060 * @count: data length
4061 * @ppos: unused
4063 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4064 size_t count, loff_t *ppos)
4066 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4067 int limit, batchcount, shared, res;
4068 struct kmem_cache *cachep;
4070 if (count > MAX_SLABINFO_WRITE)
4071 return -EINVAL;
4072 if (copy_from_user(&kbuf, buffer, count))
4073 return -EFAULT;
4074 kbuf[MAX_SLABINFO_WRITE] = '\0';
4076 tmp = strchr(kbuf, ' ');
4077 if (!tmp)
4078 return -EINVAL;
4079 *tmp = '\0';
4080 tmp++;
4081 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4082 return -EINVAL;
4084 /* Find the cache in the chain of caches. */
4085 mutex_lock(&cache_chain_mutex);
4086 res = -EINVAL;
4087 list_for_each_entry(cachep, &cache_chain, next) {
4088 if (!strcmp(cachep->name, kbuf)) {
4089 if (limit < 1 || batchcount < 1 ||
4090 batchcount > limit || shared < 0) {
4091 res = 0;
4092 } else {
4093 res = do_tune_cpucache(cachep, limit,
4094 batchcount, shared);
4096 break;
4099 mutex_unlock(&cache_chain_mutex);
4100 if (res >= 0)
4101 res = count;
4102 return res;
4105 #ifdef CONFIG_DEBUG_SLAB_LEAK
4107 static void *leaks_start(struct seq_file *m, loff_t *pos)
4109 loff_t n = *pos;
4110 struct list_head *p;
4112 mutex_lock(&cache_chain_mutex);
4113 p = cache_chain.next;
4114 while (n--) {
4115 p = p->next;
4116 if (p == &cache_chain)
4117 return NULL;
4119 return list_entry(p, struct kmem_cache, next);
4122 static inline int add_caller(unsigned long *n, unsigned long v)
4124 unsigned long *p;
4125 int l;
4126 if (!v)
4127 return 1;
4128 l = n[1];
4129 p = n + 2;
4130 while (l) {
4131 int i = l/2;
4132 unsigned long *q = p + 2 * i;
4133 if (*q == v) {
4134 q[1]++;
4135 return 1;
4137 if (*q > v) {
4138 l = i;
4139 } else {
4140 p = q + 2;
4141 l -= i + 1;
4144 if (++n[1] == n[0])
4145 return 0;
4146 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4147 p[0] = v;
4148 p[1] = 1;
4149 return 1;
4152 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4154 void *p;
4155 int i;
4156 if (n[0] == n[1])
4157 return;
4158 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->buffer_size) {
4159 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4160 continue;
4161 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4162 return;
4166 static void show_symbol(struct seq_file *m, unsigned long address)
4168 #ifdef CONFIG_KALLSYMS
4169 char *modname;
4170 const char *name;
4171 unsigned long offset, size;
4172 char namebuf[KSYM_NAME_LEN+1];
4174 name = kallsyms_lookup(address, &size, &offset, &modname, namebuf);
4176 if (name) {
4177 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4178 if (modname)
4179 seq_printf(m, " [%s]", modname);
4180 return;
4182 #endif
4183 seq_printf(m, "%p", (void *)address);
4186 static int leaks_show(struct seq_file *m, void *p)
4188 struct kmem_cache *cachep = p;
4189 struct slab *slabp;
4190 struct kmem_list3 *l3;
4191 const char *name;
4192 unsigned long *n = m->private;
4193 int node;
4194 int i;
4196 if (!(cachep->flags & SLAB_STORE_USER))
4197 return 0;
4198 if (!(cachep->flags & SLAB_RED_ZONE))
4199 return 0;
4201 /* OK, we can do it */
4203 n[1] = 0;
4205 for_each_online_node(node) {
4206 l3 = cachep->nodelists[node];
4207 if (!l3)
4208 continue;
4210 check_irq_on();
4211 spin_lock_irq(&l3->list_lock);
4213 list_for_each_entry(slabp, &l3->slabs_full, list)
4214 handle_slab(n, cachep, slabp);
4215 list_for_each_entry(slabp, &l3->slabs_partial, list)
4216 handle_slab(n, cachep, slabp);
4217 spin_unlock_irq(&l3->list_lock);
4219 name = cachep->name;
4220 if (n[0] == n[1]) {
4221 /* Increase the buffer size */
4222 mutex_unlock(&cache_chain_mutex);
4223 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4224 if (!m->private) {
4225 /* Too bad, we are really out */
4226 m->private = n;
4227 mutex_lock(&cache_chain_mutex);
4228 return -ENOMEM;
4230 *(unsigned long *)m->private = n[0] * 2;
4231 kfree(n);
4232 mutex_lock(&cache_chain_mutex);
4233 /* Now make sure this entry will be retried */
4234 m->count = m->size;
4235 return 0;
4237 for (i = 0; i < n[1]; i++) {
4238 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4239 show_symbol(m, n[2*i+2]);
4240 seq_putc(m, '\n');
4243 return 0;
4246 struct seq_operations slabstats_op = {
4247 .start = leaks_start,
4248 .next = s_next,
4249 .stop = s_stop,
4250 .show = leaks_show,
4252 #endif
4253 #endif
4256 * ksize - get the actual amount of memory allocated for a given object
4257 * @objp: Pointer to the object
4259 * kmalloc may internally round up allocations and return more memory
4260 * than requested. ksize() can be used to determine the actual amount of
4261 * memory allocated. The caller may use this additional memory, even though
4262 * a smaller amount of memory was initially specified with the kmalloc call.
4263 * The caller must guarantee that objp points to a valid object previously
4264 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4265 * must not be freed during the duration of the call.
4267 unsigned int ksize(const void *objp)
4269 if (unlikely(objp == NULL))
4270 return 0;
4272 return obj_size(virt_to_cache(objp));