3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
14 * An implementation of the Slab Allocator as described in outline in;
15 * UNIX Internals: The New Frontiers by Uresh Vahalia
16 * Pub: Prentice Hall ISBN 0-13-101908-2
17 * or with a little more detail in;
18 * The Slab Allocator: An Object-Caching Kernel Memory Allocator
19 * Jeff Bonwick (Sun Microsystems).
20 * Presented at: USENIX Summer 1994 Technical Conference
22 * The memory is organized in caches, one cache for each object type.
23 * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24 * Each cache consists out of many slabs (they are small (usually one
25 * page long) and always contiguous), and each slab contains multiple
26 * initialized objects.
28 * This means, that your constructor is used only for newly allocated
29 * slabs and you must pass objects with the same initializations to
32 * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33 * normal). If you need a special memory type, then must create a new
34 * cache for that memory type.
36 * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37 * full slabs with 0 free objects
39 * empty slabs with no allocated objects
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
44 * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45 * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
47 * Each cache has a short per-cpu head array, most allocs
48 * and frees go into that array, and if that array overflows, then 1/2
49 * of the entries in the array are given back into the global cache.
50 * The head array is strictly LIFO and should improve the cache hit rates.
51 * On SMP, it additionally reduces the spinlock operations.
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
56 * SMP synchronization:
57 * constructors and destructors are called without any locking.
58 * Several members in struct kmem_cache and struct slab never change, they
59 * are accessed without any locking.
60 * The per-cpu arrays are never accessed from the wrong cpu, no locking,
61 * and local interrupts are disabled so slab code is preempt-safe.
62 * The non-constant members are protected with a per-cache irq spinlock.
64 * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65 * in 2000 - many ideas in the current implementation are derived from
68 * Further notes from the original documentation:
70 * 11 April '97. Started multi-threading - markhe
71 * The global cache-chain is protected by the mutex 'slab_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>
92 #include <linux/poison.h>
93 #include <linux/swap.h>
94 #include <linux/cache.h>
95 #include <linux/interrupt.h>
96 #include <linux/init.h>
97 #include <linux/compiler.h>
98 #include <linux/cpuset.h>
99 #include <linux/proc_fs.h>
100 #include <linux/seq_file.h>
101 #include <linux/notifier.h>
102 #include <linux/kallsyms.h>
103 #include <linux/cpu.h>
104 #include <linux/sysctl.h>
105 #include <linux/module.h>
106 #include <linux/rcupdate.h>
107 #include <linux/string.h>
108 #include <linux/uaccess.h>
109 #include <linux/nodemask.h>
110 #include <linux/kmemleak.h>
111 #include <linux/mempolicy.h>
112 #include <linux/mutex.h>
113 #include <linux/fault-inject.h>
114 #include <linux/rtmutex.h>
115 #include <linux/reciprocal_div.h>
116 #include <linux/debugobjects.h>
117 #include <linux/kmemcheck.h>
118 #include <linux/memory.h>
119 #include <linux/prefetch.h>
121 #include <net/sock.h>
123 #include <asm/cacheflush.h>
124 #include <asm/tlbflush.h>
125 #include <asm/page.h>
127 #include <trace/events/kmem.h>
129 #include "internal.h"
132 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
133 * 0 for faster, smaller code (especially in the critical paths).
135 * STATS - 1 to collect stats for /proc/slabinfo.
136 * 0 for faster, smaller code (especially in the critical paths).
138 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
141 #ifdef CONFIG_DEBUG_SLAB
144 #define FORCED_DEBUG 1
148 #define FORCED_DEBUG 0
151 /* Shouldn't this be in a header file somewhere? */
152 #define BYTES_PER_WORD sizeof(void *)
153 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
155 #ifndef ARCH_KMALLOC_FLAGS
156 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
160 * true if a page was allocated from pfmemalloc reserves for network-based
163 static bool pfmemalloc_active __read_mostly;
168 * Bufctl's are used for linking objs within a slab
171 * This implementation relies on "struct page" for locating the cache &
172 * slab an object belongs to.
173 * This allows the bufctl structure to be small (one int), but limits
174 * the number of objects a slab (not a cache) can contain when off-slab
175 * bufctls are used. The limit is the size of the largest general cache
176 * that does not use off-slab slabs.
177 * For 32bit archs with 4 kB pages, is this 56.
178 * This is not serious, as it is only for large objects, when it is unwise
179 * to have too many per slab.
180 * Note: This limit can be raised by introducing a general cache whose size
181 * is less than 512 (PAGE_SIZE<<3), but greater than 256.
184 typedef unsigned int kmem_bufctl_t;
185 #define BUFCTL_END (((kmem_bufctl_t)(~0U))-0)
186 #define BUFCTL_FREE (((kmem_bufctl_t)(~0U))-1)
187 #define BUFCTL_ACTIVE (((kmem_bufctl_t)(~0U))-2)
188 #define SLAB_LIMIT (((kmem_bufctl_t)(~0U))-3)
193 * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
194 * arrange for kmem_freepages to be called via RCU. This is useful if
195 * we need to approach a kernel structure obliquely, from its address
196 * obtained without the usual locking. We can lock the structure to
197 * stabilize it and check it's still at the given address, only if we
198 * can be sure that the memory has not been meanwhile reused for some
199 * other kind of object (which our subsystem's lock might corrupt).
201 * rcu_read_lock before reading the address, then rcu_read_unlock after
202 * taking the spinlock within the structure expected at that address.
205 struct rcu_head head;
206 struct kmem_cache *cachep;
213 * Manages the objs in a slab. Placed either at the beginning of mem allocated
214 * for a slab, or allocated from an general cache.
215 * Slabs are chained into three list: fully used, partial, fully free slabs.
220 struct list_head list;
221 unsigned long colouroff;
222 void *s_mem; /* including colour offset */
223 unsigned int inuse; /* num of objs active in slab */
225 unsigned short nodeid;
227 struct slab_rcu __slab_cover_slab_rcu;
235 * - LIFO ordering, to hand out cache-warm objects from _alloc
236 * - reduce the number of linked list operations
237 * - reduce spinlock operations
239 * The limit is stored in the per-cpu structure to reduce the data cache
246 unsigned int batchcount;
247 unsigned int touched;
250 * Must have this definition in here for the proper
251 * alignment of array_cache. Also simplifies accessing
254 * Entries should not be directly dereferenced as
255 * entries belonging to slabs marked pfmemalloc will
256 * have the lower bits set SLAB_OBJ_PFMEMALLOC
260 #define SLAB_OBJ_PFMEMALLOC 1
261 static inline bool is_obj_pfmemalloc(void *objp)
263 return (unsigned long)objp & SLAB_OBJ_PFMEMALLOC;
266 static inline void set_obj_pfmemalloc(void **objp)
268 *objp = (void *)((unsigned long)*objp | SLAB_OBJ_PFMEMALLOC);
272 static inline void clear_obj_pfmemalloc(void **objp)
274 *objp = (void *)((unsigned long)*objp & ~SLAB_OBJ_PFMEMALLOC);
278 * bootstrap: The caches do not work without cpuarrays anymore, but the
279 * cpuarrays are allocated from the generic caches...
281 #define BOOT_CPUCACHE_ENTRIES 1
282 struct arraycache_init {
283 struct array_cache cache;
284 void *entries[BOOT_CPUCACHE_ENTRIES];
288 * The slab lists for all objects.
291 struct list_head slabs_partial; /* partial list first, better asm code */
292 struct list_head slabs_full;
293 struct list_head slabs_free;
294 unsigned long free_objects;
295 unsigned int free_limit;
296 unsigned int colour_next; /* Per-node cache coloring */
297 spinlock_t list_lock;
298 struct array_cache *shared; /* shared per node */
299 struct array_cache **alien; /* on other nodes */
300 unsigned long next_reap; /* updated without locking */
301 int free_touched; /* updated without locking */
305 * Need this for bootstrapping a per node allocator.
307 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
308 static struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
309 #define CACHE_CACHE 0
310 #define SIZE_AC MAX_NUMNODES
311 #define SIZE_L3 (2 * MAX_NUMNODES)
313 static int drain_freelist(struct kmem_cache *cache,
314 struct kmem_list3 *l3, int tofree);
315 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
317 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
318 static void cache_reap(struct work_struct *unused);
321 * This function must be completely optimized away if a constant is passed to
322 * it. Mostly the same as what is in linux/slab.h except it returns an index.
324 static __always_inline int index_of(const size_t size)
326 extern void __bad_size(void);
328 if (__builtin_constant_p(size)) {
336 #include <linux/kmalloc_sizes.h>
344 static int slab_early_init = 1;
346 #define INDEX_AC index_of(sizeof(struct arraycache_init))
347 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
349 static void kmem_list3_init(struct kmem_list3 *parent)
351 INIT_LIST_HEAD(&parent->slabs_full);
352 INIT_LIST_HEAD(&parent->slabs_partial);
353 INIT_LIST_HEAD(&parent->slabs_free);
354 parent->shared = NULL;
355 parent->alien = NULL;
356 parent->colour_next = 0;
357 spin_lock_init(&parent->list_lock);
358 parent->free_objects = 0;
359 parent->free_touched = 0;
362 #define MAKE_LIST(cachep, listp, slab, nodeid) \
364 INIT_LIST_HEAD(listp); \
365 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
368 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
370 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
371 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
372 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
375 #define CFLGS_OFF_SLAB (0x80000000UL)
376 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
378 #define BATCHREFILL_LIMIT 16
380 * Optimization question: fewer reaps means less probability for unnessary
381 * cpucache drain/refill cycles.
383 * OTOH the cpuarrays can contain lots of objects,
384 * which could lock up otherwise freeable slabs.
386 #define REAPTIMEOUT_CPUC (2*HZ)
387 #define REAPTIMEOUT_LIST3 (4*HZ)
390 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
391 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
392 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
393 #define STATS_INC_GROWN(x) ((x)->grown++)
394 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
395 #define STATS_SET_HIGH(x) \
397 if ((x)->num_active > (x)->high_mark) \
398 (x)->high_mark = (x)->num_active; \
400 #define STATS_INC_ERR(x) ((x)->errors++)
401 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
402 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
403 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
404 #define STATS_SET_FREEABLE(x, i) \
406 if ((x)->max_freeable < i) \
407 (x)->max_freeable = i; \
409 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
410 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
411 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
412 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
414 #define STATS_INC_ACTIVE(x) do { } while (0)
415 #define STATS_DEC_ACTIVE(x) do { } while (0)
416 #define STATS_INC_ALLOCED(x) do { } while (0)
417 #define STATS_INC_GROWN(x) do { } while (0)
418 #define STATS_ADD_REAPED(x,y) do { (void)(y); } while (0)
419 #define STATS_SET_HIGH(x) do { } while (0)
420 #define STATS_INC_ERR(x) do { } while (0)
421 #define STATS_INC_NODEALLOCS(x) do { } while (0)
422 #define STATS_INC_NODEFREES(x) do { } while (0)
423 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
424 #define STATS_SET_FREEABLE(x, i) do { } while (0)
425 #define STATS_INC_ALLOCHIT(x) do { } while (0)
426 #define STATS_INC_ALLOCMISS(x) do { } while (0)
427 #define STATS_INC_FREEHIT(x) do { } while (0)
428 #define STATS_INC_FREEMISS(x) do { } while (0)
434 * memory layout of objects:
436 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
437 * the end of an object is aligned with the end of the real
438 * allocation. Catches writes behind the end of the allocation.
439 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
441 * cachep->obj_offset: The real object.
442 * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
443 * cachep->size - 1* BYTES_PER_WORD: last caller address
444 * [BYTES_PER_WORD long]
446 static int obj_offset(struct kmem_cache *cachep)
448 return cachep->obj_offset;
451 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
453 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
454 return (unsigned long long*) (objp + obj_offset(cachep) -
455 sizeof(unsigned long long));
458 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
460 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
461 if (cachep->flags & SLAB_STORE_USER)
462 return (unsigned long long *)(objp + cachep->size -
463 sizeof(unsigned long long) -
465 return (unsigned long long *) (objp + cachep->size -
466 sizeof(unsigned long long));
469 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
471 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
472 return (void **)(objp + cachep->size - BYTES_PER_WORD);
477 #define obj_offset(x) 0
478 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
479 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
480 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
485 * Do not go above this order unless 0 objects fit into the slab or
486 * overridden on the command line.
488 #define SLAB_MAX_ORDER_HI 1
489 #define SLAB_MAX_ORDER_LO 0
490 static int slab_max_order = SLAB_MAX_ORDER_LO;
491 static bool slab_max_order_set __initdata;
493 static inline struct kmem_cache *virt_to_cache(const void *obj)
495 struct page *page = virt_to_head_page(obj);
496 return page->slab_cache;
499 static inline struct slab *virt_to_slab(const void *obj)
501 struct page *page = virt_to_head_page(obj);
503 VM_BUG_ON(!PageSlab(page));
504 return page->slab_page;
507 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
510 return slab->s_mem + cache->size * idx;
514 * We want to avoid an expensive divide : (offset / cache->size)
515 * Using the fact that size is a constant for a particular cache,
516 * we can replace (offset / cache->size) by
517 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
519 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
520 const struct slab *slab, void *obj)
522 u32 offset = (obj - slab->s_mem);
523 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
527 * These are the default caches for kmalloc. Custom caches can have other sizes.
529 struct cache_sizes malloc_sizes[] = {
530 #define CACHE(x) { .cs_size = (x) },
531 #include <linux/kmalloc_sizes.h>
535 EXPORT_SYMBOL(malloc_sizes);
537 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
543 static struct cache_names __initdata cache_names[] = {
544 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
545 #include <linux/kmalloc_sizes.h>
550 static struct arraycache_init initarray_generic =
551 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
553 /* internal cache of cache description objs */
554 static struct kmem_cache kmem_cache_boot = {
556 .limit = BOOT_CPUCACHE_ENTRIES,
558 .size = sizeof(struct kmem_cache),
559 .name = "kmem_cache",
562 #define BAD_ALIEN_MAGIC 0x01020304ul
564 #ifdef CONFIG_LOCKDEP
567 * Slab sometimes uses the kmalloc slabs to store the slab headers
568 * for other slabs "off slab".
569 * The locking for this is tricky in that it nests within the locks
570 * of all other slabs in a few places; to deal with this special
571 * locking we put on-slab caches into a separate lock-class.
573 * We set lock class for alien array caches which are up during init.
574 * The lock annotation will be lost if all cpus of a node goes down and
575 * then comes back up during hotplug
577 static struct lock_class_key on_slab_l3_key;
578 static struct lock_class_key on_slab_alc_key;
580 static struct lock_class_key debugobj_l3_key;
581 static struct lock_class_key debugobj_alc_key;
583 static void slab_set_lock_classes(struct kmem_cache *cachep,
584 struct lock_class_key *l3_key, struct lock_class_key *alc_key,
587 struct array_cache **alc;
588 struct kmem_list3 *l3;
591 l3 = cachep->nodelists[q];
595 lockdep_set_class(&l3->list_lock, l3_key);
598 * FIXME: This check for BAD_ALIEN_MAGIC
599 * should go away when common slab code is taught to
600 * work even without alien caches.
601 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
602 * for alloc_alien_cache,
604 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
608 lockdep_set_class(&alc[r]->lock, alc_key);
612 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
614 slab_set_lock_classes(cachep, &debugobj_l3_key, &debugobj_alc_key, node);
617 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
621 for_each_online_node(node)
622 slab_set_debugobj_lock_classes_node(cachep, node);
625 static void init_node_lock_keys(int q)
627 struct cache_sizes *s = malloc_sizes;
632 for (s = malloc_sizes; s->cs_size != ULONG_MAX; s++) {
633 struct kmem_list3 *l3;
635 l3 = s->cs_cachep->nodelists[q];
636 if (!l3 || OFF_SLAB(s->cs_cachep))
639 slab_set_lock_classes(s->cs_cachep, &on_slab_l3_key,
640 &on_slab_alc_key, q);
644 static inline void init_lock_keys(void)
649 init_node_lock_keys(node);
652 static void init_node_lock_keys(int q)
656 static inline void init_lock_keys(void)
660 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
664 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
669 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
671 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
673 return cachep->array[smp_processor_id()];
676 static inline struct kmem_cache *__find_general_cachep(size_t size,
679 struct cache_sizes *csizep = malloc_sizes;
682 /* This happens if someone tries to call
683 * kmem_cache_create(), or __kmalloc(), before
684 * the generic caches are initialized.
686 BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
689 return ZERO_SIZE_PTR;
691 while (size > csizep->cs_size)
695 * Really subtle: The last entry with cs->cs_size==ULONG_MAX
696 * has cs_{dma,}cachep==NULL. Thus no special case
697 * for large kmalloc calls required.
699 #ifdef CONFIG_ZONE_DMA
700 if (unlikely(gfpflags & GFP_DMA))
701 return csizep->cs_dmacachep;
703 return csizep->cs_cachep;
706 static struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
708 return __find_general_cachep(size, gfpflags);
711 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
713 return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
717 * Calculate the number of objects and left-over bytes for a given buffer size.
719 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
720 size_t align, int flags, size_t *left_over,
725 size_t slab_size = PAGE_SIZE << gfporder;
728 * The slab management structure can be either off the slab or
729 * on it. For the latter case, the memory allocated for a
733 * - One kmem_bufctl_t for each object
734 * - Padding to respect alignment of @align
735 * - @buffer_size bytes for each object
737 * If the slab management structure is off the slab, then the
738 * alignment will already be calculated into the size. Because
739 * the slabs are all pages aligned, the objects will be at the
740 * correct alignment when allocated.
742 if (flags & CFLGS_OFF_SLAB) {
744 nr_objs = slab_size / buffer_size;
746 if (nr_objs > SLAB_LIMIT)
747 nr_objs = SLAB_LIMIT;
750 * Ignore padding for the initial guess. The padding
751 * is at most @align-1 bytes, and @buffer_size is at
752 * least @align. In the worst case, this result will
753 * be one greater than the number of objects that fit
754 * into the memory allocation when taking the padding
757 nr_objs = (slab_size - sizeof(struct slab)) /
758 (buffer_size + sizeof(kmem_bufctl_t));
761 * This calculated number will be either the right
762 * amount, or one greater than what we want.
764 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
768 if (nr_objs > SLAB_LIMIT)
769 nr_objs = SLAB_LIMIT;
771 mgmt_size = slab_mgmt_size(nr_objs, align);
774 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
778 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
780 static void __slab_error(const char *function, struct kmem_cache *cachep,
783 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
784 function, cachep->name, msg);
786 add_taint(TAINT_BAD_PAGE);
791 * By default on NUMA we use alien caches to stage the freeing of
792 * objects allocated from other nodes. This causes massive memory
793 * inefficiencies when using fake NUMA setup to split memory into a
794 * large number of small nodes, so it can be disabled on the command
798 static int use_alien_caches __read_mostly = 1;
799 static int __init noaliencache_setup(char *s)
801 use_alien_caches = 0;
804 __setup("noaliencache", noaliencache_setup);
806 static int __init slab_max_order_setup(char *str)
808 get_option(&str, &slab_max_order);
809 slab_max_order = slab_max_order < 0 ? 0 :
810 min(slab_max_order, MAX_ORDER - 1);
811 slab_max_order_set = true;
815 __setup("slab_max_order=", slab_max_order_setup);
819 * Special reaping functions for NUMA systems called from cache_reap().
820 * These take care of doing round robin flushing of alien caches (containing
821 * objects freed on different nodes from which they were allocated) and the
822 * flushing of remote pcps by calling drain_node_pages.
824 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
826 static void init_reap_node(int cpu)
830 node = next_node(cpu_to_mem(cpu), node_online_map);
831 if (node == MAX_NUMNODES)
832 node = first_node(node_online_map);
834 per_cpu(slab_reap_node, cpu) = node;
837 static void next_reap_node(void)
839 int node = __this_cpu_read(slab_reap_node);
841 node = next_node(node, node_online_map);
842 if (unlikely(node >= MAX_NUMNODES))
843 node = first_node(node_online_map);
844 __this_cpu_write(slab_reap_node, node);
848 #define init_reap_node(cpu) do { } while (0)
849 #define next_reap_node(void) do { } while (0)
853 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
854 * via the workqueue/eventd.
855 * Add the CPU number into the expiration time to minimize the possibility of
856 * the CPUs getting into lockstep and contending for the global cache chain
859 static void __cpuinit start_cpu_timer(int cpu)
861 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
864 * When this gets called from do_initcalls via cpucache_init(),
865 * init_workqueues() has already run, so keventd will be setup
868 if (keventd_up() && reap_work->work.func == NULL) {
870 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
871 schedule_delayed_work_on(cpu, reap_work,
872 __round_jiffies_relative(HZ, cpu));
876 static struct array_cache *alloc_arraycache(int node, int entries,
877 int batchcount, gfp_t gfp)
879 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
880 struct array_cache *nc = NULL;
882 nc = kmalloc_node(memsize, gfp, node);
884 * The array_cache structures contain pointers to free object.
885 * However, when such objects are allocated or transferred to another
886 * cache the pointers are not cleared and they could be counted as
887 * valid references during a kmemleak scan. Therefore, kmemleak must
888 * not scan such objects.
890 kmemleak_no_scan(nc);
894 nc->batchcount = batchcount;
896 spin_lock_init(&nc->lock);
901 static inline bool is_slab_pfmemalloc(struct slab *slabp)
903 struct page *page = virt_to_page(slabp->s_mem);
905 return PageSlabPfmemalloc(page);
908 /* Clears pfmemalloc_active if no slabs have pfmalloc set */
909 static void recheck_pfmemalloc_active(struct kmem_cache *cachep,
910 struct array_cache *ac)
912 struct kmem_list3 *l3 = cachep->nodelists[numa_mem_id()];
916 if (!pfmemalloc_active)
919 spin_lock_irqsave(&l3->list_lock, flags);
920 list_for_each_entry(slabp, &l3->slabs_full, list)
921 if (is_slab_pfmemalloc(slabp))
924 list_for_each_entry(slabp, &l3->slabs_partial, list)
925 if (is_slab_pfmemalloc(slabp))
928 list_for_each_entry(slabp, &l3->slabs_free, list)
929 if (is_slab_pfmemalloc(slabp))
932 pfmemalloc_active = false;
934 spin_unlock_irqrestore(&l3->list_lock, flags);
937 static void *__ac_get_obj(struct kmem_cache *cachep, struct array_cache *ac,
938 gfp_t flags, bool force_refill)
941 void *objp = ac->entry[--ac->avail];
943 /* Ensure the caller is allowed to use objects from PFMEMALLOC slab */
944 if (unlikely(is_obj_pfmemalloc(objp))) {
945 struct kmem_list3 *l3;
947 if (gfp_pfmemalloc_allowed(flags)) {
948 clear_obj_pfmemalloc(&objp);
952 /* The caller cannot use PFMEMALLOC objects, find another one */
953 for (i = 0; i < ac->avail; i++) {
954 /* If a !PFMEMALLOC object is found, swap them */
955 if (!is_obj_pfmemalloc(ac->entry[i])) {
957 ac->entry[i] = ac->entry[ac->avail];
958 ac->entry[ac->avail] = objp;
964 * If there are empty slabs on the slabs_free list and we are
965 * being forced to refill the cache, mark this one !pfmemalloc.
967 l3 = cachep->nodelists[numa_mem_id()];
968 if (!list_empty(&l3->slabs_free) && force_refill) {
969 struct slab *slabp = virt_to_slab(objp);
970 ClearPageSlabPfmemalloc(virt_to_head_page(slabp->s_mem));
971 clear_obj_pfmemalloc(&objp);
972 recheck_pfmemalloc_active(cachep, ac);
976 /* No !PFMEMALLOC objects available */
984 static inline void *ac_get_obj(struct kmem_cache *cachep,
985 struct array_cache *ac, gfp_t flags, bool force_refill)
989 if (unlikely(sk_memalloc_socks()))
990 objp = __ac_get_obj(cachep, ac, flags, force_refill);
992 objp = ac->entry[--ac->avail];
997 static void *__ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
1000 if (unlikely(pfmemalloc_active)) {
1001 /* Some pfmemalloc slabs exist, check if this is one */
1002 struct page *page = virt_to_head_page(objp);
1003 if (PageSlabPfmemalloc(page))
1004 set_obj_pfmemalloc(&objp);
1010 static inline void ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
1013 if (unlikely(sk_memalloc_socks()))
1014 objp = __ac_put_obj(cachep, ac, objp);
1016 ac->entry[ac->avail++] = objp;
1020 * Transfer objects in one arraycache to another.
1021 * Locking must be handled by the caller.
1023 * Return the number of entries transferred.
1025 static int transfer_objects(struct array_cache *to,
1026 struct array_cache *from, unsigned int max)
1028 /* Figure out how many entries to transfer */
1029 int nr = min3(from->avail, max, to->limit - to->avail);
1034 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
1035 sizeof(void *) *nr);
1044 #define drain_alien_cache(cachep, alien) do { } while (0)
1045 #define reap_alien(cachep, l3) do { } while (0)
1047 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
1049 return (struct array_cache **)BAD_ALIEN_MAGIC;
1052 static inline void free_alien_cache(struct array_cache **ac_ptr)
1056 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1061 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
1067 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
1068 gfp_t flags, int nodeid)
1073 #else /* CONFIG_NUMA */
1075 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
1076 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1078 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
1080 struct array_cache **ac_ptr;
1081 int memsize = sizeof(void *) * nr_node_ids;
1086 ac_ptr = kzalloc_node(memsize, gfp, node);
1089 if (i == node || !node_online(i))
1091 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
1093 for (i--; i >= 0; i--)
1103 static void free_alien_cache(struct array_cache **ac_ptr)
1114 static void __drain_alien_cache(struct kmem_cache *cachep,
1115 struct array_cache *ac, int node)
1117 struct kmem_list3 *rl3 = cachep->nodelists[node];
1120 spin_lock(&rl3->list_lock);
1122 * Stuff objects into the remote nodes shared array first.
1123 * That way we could avoid the overhead of putting the objects
1124 * into the free lists and getting them back later.
1127 transfer_objects(rl3->shared, ac, ac->limit);
1129 free_block(cachep, ac->entry, ac->avail, node);
1131 spin_unlock(&rl3->list_lock);
1136 * Called from cache_reap() to regularly drain alien caches round robin.
1138 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
1140 int node = __this_cpu_read(slab_reap_node);
1143 struct array_cache *ac = l3->alien[node];
1145 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1146 __drain_alien_cache(cachep, ac, node);
1147 spin_unlock_irq(&ac->lock);
1152 static void drain_alien_cache(struct kmem_cache *cachep,
1153 struct array_cache **alien)
1156 struct array_cache *ac;
1157 unsigned long flags;
1159 for_each_online_node(i) {
1162 spin_lock_irqsave(&ac->lock, flags);
1163 __drain_alien_cache(cachep, ac, i);
1164 spin_unlock_irqrestore(&ac->lock, flags);
1169 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1171 struct slab *slabp = virt_to_slab(objp);
1172 int nodeid = slabp->nodeid;
1173 struct kmem_list3 *l3;
1174 struct array_cache *alien = NULL;
1177 node = numa_mem_id();
1180 * Make sure we are not freeing a object from another node to the array
1181 * cache on this cpu.
1183 if (likely(slabp->nodeid == node))
1186 l3 = cachep->nodelists[node];
1187 STATS_INC_NODEFREES(cachep);
1188 if (l3->alien && l3->alien[nodeid]) {
1189 alien = l3->alien[nodeid];
1190 spin_lock(&alien->lock);
1191 if (unlikely(alien->avail == alien->limit)) {
1192 STATS_INC_ACOVERFLOW(cachep);
1193 __drain_alien_cache(cachep, alien, nodeid);
1195 ac_put_obj(cachep, alien, objp);
1196 spin_unlock(&alien->lock);
1198 spin_lock(&(cachep->nodelists[nodeid])->list_lock);
1199 free_block(cachep, &objp, 1, nodeid);
1200 spin_unlock(&(cachep->nodelists[nodeid])->list_lock);
1207 * Allocates and initializes nodelists for a node on each slab cache, used for
1208 * either memory or cpu hotplug. If memory is being hot-added, the kmem_list3
1209 * will be allocated off-node since memory is not yet online for the new node.
1210 * When hotplugging memory or a cpu, existing nodelists are not replaced if
1213 * Must hold slab_mutex.
1215 static int init_cache_nodelists_node(int node)
1217 struct kmem_cache *cachep;
1218 struct kmem_list3 *l3;
1219 const int memsize = sizeof(struct kmem_list3);
1221 list_for_each_entry(cachep, &slab_caches, list) {
1223 * Set up the size64 kmemlist for cpu before we can
1224 * begin anything. Make sure some other cpu on this
1225 * node has not already allocated this
1227 if (!cachep->nodelists[node]) {
1228 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1231 kmem_list3_init(l3);
1232 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1233 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1236 * The l3s don't come and go as CPUs come and
1237 * go. slab_mutex is sufficient
1240 cachep->nodelists[node] = l3;
1243 spin_lock_irq(&cachep->nodelists[node]->list_lock);
1244 cachep->nodelists[node]->free_limit =
1245 (1 + nr_cpus_node(node)) *
1246 cachep->batchcount + cachep->num;
1247 spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1252 static void __cpuinit cpuup_canceled(long cpu)
1254 struct kmem_cache *cachep;
1255 struct kmem_list3 *l3 = NULL;
1256 int node = cpu_to_mem(cpu);
1257 const struct cpumask *mask = cpumask_of_node(node);
1259 list_for_each_entry(cachep, &slab_caches, list) {
1260 struct array_cache *nc;
1261 struct array_cache *shared;
1262 struct array_cache **alien;
1264 /* cpu is dead; no one can alloc from it. */
1265 nc = cachep->array[cpu];
1266 cachep->array[cpu] = NULL;
1267 l3 = cachep->nodelists[node];
1270 goto free_array_cache;
1272 spin_lock_irq(&l3->list_lock);
1274 /* Free limit for this kmem_list3 */
1275 l3->free_limit -= cachep->batchcount;
1277 free_block(cachep, nc->entry, nc->avail, node);
1279 if (!cpumask_empty(mask)) {
1280 spin_unlock_irq(&l3->list_lock);
1281 goto free_array_cache;
1284 shared = l3->shared;
1286 free_block(cachep, shared->entry,
1287 shared->avail, node);
1294 spin_unlock_irq(&l3->list_lock);
1298 drain_alien_cache(cachep, alien);
1299 free_alien_cache(alien);
1305 * In the previous loop, all the objects were freed to
1306 * the respective cache's slabs, now we can go ahead and
1307 * shrink each nodelist to its limit.
1309 list_for_each_entry(cachep, &slab_caches, list) {
1310 l3 = cachep->nodelists[node];
1313 drain_freelist(cachep, l3, l3->free_objects);
1317 static int __cpuinit cpuup_prepare(long cpu)
1319 struct kmem_cache *cachep;
1320 struct kmem_list3 *l3 = NULL;
1321 int node = cpu_to_mem(cpu);
1325 * We need to do this right in the beginning since
1326 * alloc_arraycache's are going to use this list.
1327 * kmalloc_node allows us to add the slab to the right
1328 * kmem_list3 and not this cpu's kmem_list3
1330 err = init_cache_nodelists_node(node);
1335 * Now we can go ahead with allocating the shared arrays and
1338 list_for_each_entry(cachep, &slab_caches, list) {
1339 struct array_cache *nc;
1340 struct array_cache *shared = NULL;
1341 struct array_cache **alien = NULL;
1343 nc = alloc_arraycache(node, cachep->limit,
1344 cachep->batchcount, GFP_KERNEL);
1347 if (cachep->shared) {
1348 shared = alloc_arraycache(node,
1349 cachep->shared * cachep->batchcount,
1350 0xbaadf00d, GFP_KERNEL);
1356 if (use_alien_caches) {
1357 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1364 cachep->array[cpu] = nc;
1365 l3 = cachep->nodelists[node];
1368 spin_lock_irq(&l3->list_lock);
1371 * We are serialised from CPU_DEAD or
1372 * CPU_UP_CANCELLED by the cpucontrol lock
1374 l3->shared = shared;
1383 spin_unlock_irq(&l3->list_lock);
1385 free_alien_cache(alien);
1386 if (cachep->flags & SLAB_DEBUG_OBJECTS)
1387 slab_set_debugobj_lock_classes_node(cachep, node);
1389 init_node_lock_keys(node);
1393 cpuup_canceled(cpu);
1397 static int __cpuinit cpuup_callback(struct notifier_block *nfb,
1398 unsigned long action, void *hcpu)
1400 long cpu = (long)hcpu;
1404 case CPU_UP_PREPARE:
1405 case CPU_UP_PREPARE_FROZEN:
1406 mutex_lock(&slab_mutex);
1407 err = cpuup_prepare(cpu);
1408 mutex_unlock(&slab_mutex);
1411 case CPU_ONLINE_FROZEN:
1412 start_cpu_timer(cpu);
1414 #ifdef CONFIG_HOTPLUG_CPU
1415 case CPU_DOWN_PREPARE:
1416 case CPU_DOWN_PREPARE_FROZEN:
1418 * Shutdown cache reaper. Note that the slab_mutex is
1419 * held so that if cache_reap() is invoked it cannot do
1420 * anything expensive but will only modify reap_work
1421 * and reschedule the timer.
1423 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1424 /* Now the cache_reaper is guaranteed to be not running. */
1425 per_cpu(slab_reap_work, cpu).work.func = NULL;
1427 case CPU_DOWN_FAILED:
1428 case CPU_DOWN_FAILED_FROZEN:
1429 start_cpu_timer(cpu);
1432 case CPU_DEAD_FROZEN:
1434 * Even if all the cpus of a node are down, we don't free the
1435 * kmem_list3 of any cache. This to avoid a race between
1436 * cpu_down, and a kmalloc allocation from another cpu for
1437 * memory from the node of the cpu going down. The list3
1438 * structure is usually allocated from kmem_cache_create() and
1439 * gets destroyed at kmem_cache_destroy().
1443 case CPU_UP_CANCELED:
1444 case CPU_UP_CANCELED_FROZEN:
1445 mutex_lock(&slab_mutex);
1446 cpuup_canceled(cpu);
1447 mutex_unlock(&slab_mutex);
1450 return notifier_from_errno(err);
1453 static struct notifier_block __cpuinitdata cpucache_notifier = {
1454 &cpuup_callback, NULL, 0
1457 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1459 * Drains freelist for a node on each slab cache, used for memory hot-remove.
1460 * Returns -EBUSY if all objects cannot be drained so that the node is not
1463 * Must hold slab_mutex.
1465 static int __meminit drain_cache_nodelists_node(int node)
1467 struct kmem_cache *cachep;
1470 list_for_each_entry(cachep, &slab_caches, list) {
1471 struct kmem_list3 *l3;
1473 l3 = cachep->nodelists[node];
1477 drain_freelist(cachep, l3, l3->free_objects);
1479 if (!list_empty(&l3->slabs_full) ||
1480 !list_empty(&l3->slabs_partial)) {
1488 static int __meminit slab_memory_callback(struct notifier_block *self,
1489 unsigned long action, void *arg)
1491 struct memory_notify *mnb = arg;
1495 nid = mnb->status_change_nid;
1500 case MEM_GOING_ONLINE:
1501 mutex_lock(&slab_mutex);
1502 ret = init_cache_nodelists_node(nid);
1503 mutex_unlock(&slab_mutex);
1505 case MEM_GOING_OFFLINE:
1506 mutex_lock(&slab_mutex);
1507 ret = drain_cache_nodelists_node(nid);
1508 mutex_unlock(&slab_mutex);
1512 case MEM_CANCEL_ONLINE:
1513 case MEM_CANCEL_OFFLINE:
1517 return notifier_from_errno(ret);
1519 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1522 * swap the static kmem_list3 with kmalloced memory
1524 static void __init init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1527 struct kmem_list3 *ptr;
1529 ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_NOWAIT, nodeid);
1532 memcpy(ptr, list, sizeof(struct kmem_list3));
1534 * Do not assume that spinlocks can be initialized via memcpy:
1536 spin_lock_init(&ptr->list_lock);
1538 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1539 cachep->nodelists[nodeid] = ptr;
1543 * For setting up all the kmem_list3s for cache whose buffer_size is same as
1544 * size of kmem_list3.
1546 static void __init set_up_list3s(struct kmem_cache *cachep, int index)
1550 for_each_online_node(node) {
1551 cachep->nodelists[node] = &initkmem_list3[index + node];
1552 cachep->nodelists[node]->next_reap = jiffies +
1554 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1559 * The memory after the last cpu cache pointer is used for the
1560 * the nodelists pointer.
1562 static void setup_nodelists_pointer(struct kmem_cache *cachep)
1564 cachep->nodelists = (struct kmem_list3 **)&cachep->array[nr_cpu_ids];
1568 * Initialisation. Called after the page allocator have been initialised and
1569 * before smp_init().
1571 void __init kmem_cache_init(void)
1573 struct cache_sizes *sizes;
1574 struct cache_names *names;
1577 kmem_cache = &kmem_cache_boot;
1578 setup_nodelists_pointer(kmem_cache);
1580 if (num_possible_nodes() == 1)
1581 use_alien_caches = 0;
1583 for (i = 0; i < NUM_INIT_LISTS; i++)
1584 kmem_list3_init(&initkmem_list3[i]);
1586 set_up_list3s(kmem_cache, CACHE_CACHE);
1589 * Fragmentation resistance on low memory - only use bigger
1590 * page orders on machines with more than 32MB of memory if
1591 * not overridden on the command line.
1593 if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1594 slab_max_order = SLAB_MAX_ORDER_HI;
1596 /* Bootstrap is tricky, because several objects are allocated
1597 * from caches that do not exist yet:
1598 * 1) initialize the kmem_cache cache: it contains the struct
1599 * kmem_cache structures of all caches, except kmem_cache itself:
1600 * kmem_cache is statically allocated.
1601 * Initially an __init data area is used for the head array and the
1602 * kmem_list3 structures, it's replaced with a kmalloc allocated
1603 * array at the end of the bootstrap.
1604 * 2) Create the first kmalloc cache.
1605 * The struct kmem_cache for the new cache is allocated normally.
1606 * An __init data area is used for the head array.
1607 * 3) Create the remaining kmalloc caches, with minimally sized
1609 * 4) Replace the __init data head arrays for kmem_cache and the first
1610 * kmalloc cache with kmalloc allocated arrays.
1611 * 5) Replace the __init data for kmem_list3 for kmem_cache and
1612 * the other cache's with kmalloc allocated memory.
1613 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1616 /* 1) create the kmem_cache */
1619 * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1621 create_boot_cache(kmem_cache, "kmem_cache",
1622 offsetof(struct kmem_cache, array[nr_cpu_ids]) +
1623 nr_node_ids * sizeof(struct kmem_list3 *),
1624 SLAB_HWCACHE_ALIGN);
1625 list_add(&kmem_cache->list, &slab_caches);
1627 /* 2+3) create the kmalloc caches */
1628 sizes = malloc_sizes;
1629 names = cache_names;
1632 * Initialize the caches that provide memory for the array cache and the
1633 * kmem_list3 structures first. Without this, further allocations will
1637 sizes[INDEX_AC].cs_cachep = create_kmalloc_cache(names[INDEX_AC].name,
1638 sizes[INDEX_AC].cs_size, ARCH_KMALLOC_FLAGS);
1640 if (INDEX_AC != INDEX_L3)
1641 sizes[INDEX_L3].cs_cachep =
1642 create_kmalloc_cache(names[INDEX_L3].name,
1643 sizes[INDEX_L3].cs_size, ARCH_KMALLOC_FLAGS);
1645 slab_early_init = 0;
1647 while (sizes->cs_size != ULONG_MAX) {
1649 * For performance, all the general caches are L1 aligned.
1650 * This should be particularly beneficial on SMP boxes, as it
1651 * eliminates "false sharing".
1652 * Note for systems short on memory removing the alignment will
1653 * allow tighter packing of the smaller caches.
1655 if (!sizes->cs_cachep)
1656 sizes->cs_cachep = create_kmalloc_cache(names->name,
1657 sizes->cs_size, ARCH_KMALLOC_FLAGS);
1659 #ifdef CONFIG_ZONE_DMA
1660 sizes->cs_dmacachep = create_kmalloc_cache(
1661 names->name_dma, sizes->cs_size,
1662 SLAB_CACHE_DMA|ARCH_KMALLOC_FLAGS);
1667 /* 4) Replace the bootstrap head arrays */
1669 struct array_cache *ptr;
1671 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1673 memcpy(ptr, cpu_cache_get(kmem_cache),
1674 sizeof(struct arraycache_init));
1676 * Do not assume that spinlocks can be initialized via memcpy:
1678 spin_lock_init(&ptr->lock);
1680 kmem_cache->array[smp_processor_id()] = ptr;
1682 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1684 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1685 != &initarray_generic.cache);
1686 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1687 sizeof(struct arraycache_init));
1689 * Do not assume that spinlocks can be initialized via memcpy:
1691 spin_lock_init(&ptr->lock);
1693 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1696 /* 5) Replace the bootstrap kmem_list3's */
1700 for_each_online_node(nid) {
1701 init_list(kmem_cache, &initkmem_list3[CACHE_CACHE + nid], nid);
1703 init_list(malloc_sizes[INDEX_AC].cs_cachep,
1704 &initkmem_list3[SIZE_AC + nid], nid);
1706 if (INDEX_AC != INDEX_L3) {
1707 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1708 &initkmem_list3[SIZE_L3 + nid], nid);
1716 void __init kmem_cache_init_late(void)
1718 struct kmem_cache *cachep;
1722 /* 6) resize the head arrays to their final sizes */
1723 mutex_lock(&slab_mutex);
1724 list_for_each_entry(cachep, &slab_caches, list)
1725 if (enable_cpucache(cachep, GFP_NOWAIT))
1727 mutex_unlock(&slab_mutex);
1729 /* Annotate slab for lockdep -- annotate the malloc caches */
1736 * Register a cpu startup notifier callback that initializes
1737 * cpu_cache_get for all new cpus
1739 register_cpu_notifier(&cpucache_notifier);
1743 * Register a memory hotplug callback that initializes and frees
1746 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1750 * The reap timers are started later, with a module init call: That part
1751 * of the kernel is not yet operational.
1755 static int __init cpucache_init(void)
1760 * Register the timers that return unneeded pages to the page allocator
1762 for_each_online_cpu(cpu)
1763 start_cpu_timer(cpu);
1769 __initcall(cpucache_init);
1771 static noinline void
1772 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1774 struct kmem_list3 *l3;
1776 unsigned long flags;
1780 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1782 printk(KERN_WARNING " cache: %s, object size: %d, order: %d\n",
1783 cachep->name, cachep->size, cachep->gfporder);
1785 for_each_online_node(node) {
1786 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1787 unsigned long active_slabs = 0, num_slabs = 0;
1789 l3 = cachep->nodelists[node];
1793 spin_lock_irqsave(&l3->list_lock, flags);
1794 list_for_each_entry(slabp, &l3->slabs_full, list) {
1795 active_objs += cachep->num;
1798 list_for_each_entry(slabp, &l3->slabs_partial, list) {
1799 active_objs += slabp->inuse;
1802 list_for_each_entry(slabp, &l3->slabs_free, list)
1805 free_objects += l3->free_objects;
1806 spin_unlock_irqrestore(&l3->list_lock, flags);
1808 num_slabs += active_slabs;
1809 num_objs = num_slabs * cachep->num;
1811 " node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1812 node, active_slabs, num_slabs, active_objs, num_objs,
1818 * Interface to system's page allocator. No need to hold the cache-lock.
1820 * If we requested dmaable memory, we will get it. Even if we
1821 * did not request dmaable memory, we might get it, but that
1822 * would be relatively rare and ignorable.
1824 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1832 * Nommu uses slab's for process anonymous memory allocations, and thus
1833 * requires __GFP_COMP to properly refcount higher order allocations
1835 flags |= __GFP_COMP;
1838 flags |= cachep->allocflags;
1839 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1840 flags |= __GFP_RECLAIMABLE;
1842 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1844 if (!(flags & __GFP_NOWARN) && printk_ratelimit())
1845 slab_out_of_memory(cachep, flags, nodeid);
1849 /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1850 if (unlikely(page->pfmemalloc))
1851 pfmemalloc_active = true;
1853 nr_pages = (1 << cachep->gfporder);
1854 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1855 add_zone_page_state(page_zone(page),
1856 NR_SLAB_RECLAIMABLE, nr_pages);
1858 add_zone_page_state(page_zone(page),
1859 NR_SLAB_UNRECLAIMABLE, nr_pages);
1860 for (i = 0; i < nr_pages; i++) {
1861 __SetPageSlab(page + i);
1863 if (page->pfmemalloc)
1864 SetPageSlabPfmemalloc(page + i);
1867 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1868 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1871 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1873 kmemcheck_mark_unallocated_pages(page, nr_pages);
1876 return page_address(page);
1880 * Interface to system's page release.
1882 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1884 unsigned long i = (1 << cachep->gfporder);
1885 struct page *page = virt_to_page(addr);
1886 const unsigned long nr_freed = i;
1888 kmemcheck_free_shadow(page, cachep->gfporder);
1890 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1891 sub_zone_page_state(page_zone(page),
1892 NR_SLAB_RECLAIMABLE, nr_freed);
1894 sub_zone_page_state(page_zone(page),
1895 NR_SLAB_UNRECLAIMABLE, nr_freed);
1897 BUG_ON(!PageSlab(page));
1898 __ClearPageSlabPfmemalloc(page);
1899 __ClearPageSlab(page);
1902 if (current->reclaim_state)
1903 current->reclaim_state->reclaimed_slab += nr_freed;
1904 free_pages((unsigned long)addr, cachep->gfporder);
1907 static void kmem_rcu_free(struct rcu_head *head)
1909 struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1910 struct kmem_cache *cachep = slab_rcu->cachep;
1912 kmem_freepages(cachep, slab_rcu->addr);
1913 if (OFF_SLAB(cachep))
1914 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1919 #ifdef CONFIG_DEBUG_PAGEALLOC
1920 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1921 unsigned long caller)
1923 int size = cachep->object_size;
1925 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1927 if (size < 5 * sizeof(unsigned long))
1930 *addr++ = 0x12345678;
1932 *addr++ = smp_processor_id();
1933 size -= 3 * sizeof(unsigned long);
1935 unsigned long *sptr = &caller;
1936 unsigned long svalue;
1938 while (!kstack_end(sptr)) {
1940 if (kernel_text_address(svalue)) {
1942 size -= sizeof(unsigned long);
1943 if (size <= sizeof(unsigned long))
1949 *addr++ = 0x87654321;
1953 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1955 int size = cachep->object_size;
1956 addr = &((char *)addr)[obj_offset(cachep)];
1958 memset(addr, val, size);
1959 *(unsigned char *)(addr + size - 1) = POISON_END;
1962 static void dump_line(char *data, int offset, int limit)
1965 unsigned char error = 0;
1968 printk(KERN_ERR "%03x: ", offset);
1969 for (i = 0; i < limit; i++) {
1970 if (data[offset + i] != POISON_FREE) {
1971 error = data[offset + i];
1975 print_hex_dump(KERN_CONT, "", 0, 16, 1,
1976 &data[offset], limit, 1);
1978 if (bad_count == 1) {
1979 error ^= POISON_FREE;
1980 if (!(error & (error - 1))) {
1981 printk(KERN_ERR "Single bit error detected. Probably "
1984 printk(KERN_ERR "Run memtest86+ or a similar memory "
1987 printk(KERN_ERR "Run a memory test tool.\n");
1996 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
2001 if (cachep->flags & SLAB_RED_ZONE) {
2002 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
2003 *dbg_redzone1(cachep, objp),
2004 *dbg_redzone2(cachep, objp));
2007 if (cachep->flags & SLAB_STORE_USER) {
2008 printk(KERN_ERR "Last user: [<%p>]",
2009 *dbg_userword(cachep, objp));
2010 print_symbol("(%s)",
2011 (unsigned long)*dbg_userword(cachep, objp));
2014 realobj = (char *)objp + obj_offset(cachep);
2015 size = cachep->object_size;
2016 for (i = 0; i < size && lines; i += 16, lines--) {
2019 if (i + limit > size)
2021 dump_line(realobj, i, limit);
2025 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
2031 realobj = (char *)objp + obj_offset(cachep);
2032 size = cachep->object_size;
2034 for (i = 0; i < size; i++) {
2035 char exp = POISON_FREE;
2038 if (realobj[i] != exp) {
2044 "Slab corruption (%s): %s start=%p, len=%d\n",
2045 print_tainted(), cachep->name, realobj, size);
2046 print_objinfo(cachep, objp, 0);
2048 /* Hexdump the affected line */
2051 if (i + limit > size)
2053 dump_line(realobj, i, limit);
2056 /* Limit to 5 lines */
2062 /* Print some data about the neighboring objects, if they
2065 struct slab *slabp = virt_to_slab(objp);
2068 objnr = obj_to_index(cachep, slabp, objp);
2070 objp = index_to_obj(cachep, slabp, objnr - 1);
2071 realobj = (char *)objp + obj_offset(cachep);
2072 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
2074 print_objinfo(cachep, objp, 2);
2076 if (objnr + 1 < cachep->num) {
2077 objp = index_to_obj(cachep, slabp, objnr + 1);
2078 realobj = (char *)objp + obj_offset(cachep);
2079 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
2081 print_objinfo(cachep, objp, 2);
2088 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
2091 for (i = 0; i < cachep->num; i++) {
2092 void *objp = index_to_obj(cachep, slabp, i);
2094 if (cachep->flags & SLAB_POISON) {
2095 #ifdef CONFIG_DEBUG_PAGEALLOC
2096 if (cachep->size % PAGE_SIZE == 0 &&
2098 kernel_map_pages(virt_to_page(objp),
2099 cachep->size / PAGE_SIZE, 1);
2101 check_poison_obj(cachep, objp);
2103 check_poison_obj(cachep, objp);
2106 if (cachep->flags & SLAB_RED_ZONE) {
2107 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2108 slab_error(cachep, "start of a freed object "
2110 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2111 slab_error(cachep, "end of a freed object "
2117 static void slab_destroy_debugcheck(struct kmem_cache *cachep, struct slab *slabp)
2123 * slab_destroy - destroy and release all objects in a slab
2124 * @cachep: cache pointer being destroyed
2125 * @slabp: slab pointer being destroyed
2127 * Destroy all the objs in a slab, and release the mem back to the system.
2128 * Before calling the slab must have been unlinked from the cache. The
2129 * cache-lock is not held/needed.
2131 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
2133 void *addr = slabp->s_mem - slabp->colouroff;
2135 slab_destroy_debugcheck(cachep, slabp);
2136 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2137 struct slab_rcu *slab_rcu;
2139 slab_rcu = (struct slab_rcu *)slabp;
2140 slab_rcu->cachep = cachep;
2141 slab_rcu->addr = addr;
2142 call_rcu(&slab_rcu->head, kmem_rcu_free);
2144 kmem_freepages(cachep, addr);
2145 if (OFF_SLAB(cachep))
2146 kmem_cache_free(cachep->slabp_cache, slabp);
2151 * calculate_slab_order - calculate size (page order) of slabs
2152 * @cachep: pointer to the cache that is being created
2153 * @size: size of objects to be created in this cache.
2154 * @align: required alignment for the objects.
2155 * @flags: slab allocation flags
2157 * Also calculates the number of objects per slab.
2159 * This could be made much more intelligent. For now, try to avoid using
2160 * high order pages for slabs. When the gfp() functions are more friendly
2161 * towards high-order requests, this should be changed.
2163 static size_t calculate_slab_order(struct kmem_cache *cachep,
2164 size_t size, size_t align, unsigned long flags)
2166 unsigned long offslab_limit;
2167 size_t left_over = 0;
2170 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2174 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2178 if (flags & CFLGS_OFF_SLAB) {
2180 * Max number of objs-per-slab for caches which
2181 * use off-slab slabs. Needed to avoid a possible
2182 * looping condition in cache_grow().
2184 offslab_limit = size - sizeof(struct slab);
2185 offslab_limit /= sizeof(kmem_bufctl_t);
2187 if (num > offslab_limit)
2191 /* Found something acceptable - save it away */
2193 cachep->gfporder = gfporder;
2194 left_over = remainder;
2197 * A VFS-reclaimable slab tends to have most allocations
2198 * as GFP_NOFS and we really don't want to have to be allocating
2199 * higher-order pages when we are unable to shrink dcache.
2201 if (flags & SLAB_RECLAIM_ACCOUNT)
2205 * Large number of objects is good, but very large slabs are
2206 * currently bad for the gfp()s.
2208 if (gfporder >= slab_max_order)
2212 * Acceptable internal fragmentation?
2214 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2220 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2222 if (slab_state >= FULL)
2223 return enable_cpucache(cachep, gfp);
2225 if (slab_state == DOWN) {
2227 * Note: Creation of first cache (kmem_cache).
2228 * The setup_list3s is taken care
2229 * of by the caller of __kmem_cache_create
2231 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2232 slab_state = PARTIAL;
2233 } else if (slab_state == PARTIAL) {
2235 * Note: the second kmem_cache_create must create the cache
2236 * that's used by kmalloc(24), otherwise the creation of
2237 * further caches will BUG().
2239 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2242 * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
2243 * the second cache, then we need to set up all its list3s,
2244 * otherwise the creation of further caches will BUG().
2246 set_up_list3s(cachep, SIZE_AC);
2247 if (INDEX_AC == INDEX_L3)
2248 slab_state = PARTIAL_L3;
2250 slab_state = PARTIAL_ARRAYCACHE;
2252 /* Remaining boot caches */
2253 cachep->array[smp_processor_id()] =
2254 kmalloc(sizeof(struct arraycache_init), gfp);
2256 if (slab_state == PARTIAL_ARRAYCACHE) {
2257 set_up_list3s(cachep, SIZE_L3);
2258 slab_state = PARTIAL_L3;
2261 for_each_online_node(node) {
2262 cachep->nodelists[node] =
2263 kmalloc_node(sizeof(struct kmem_list3),
2265 BUG_ON(!cachep->nodelists[node]);
2266 kmem_list3_init(cachep->nodelists[node]);
2270 cachep->nodelists[numa_mem_id()]->next_reap =
2271 jiffies + REAPTIMEOUT_LIST3 +
2272 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
2274 cpu_cache_get(cachep)->avail = 0;
2275 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2276 cpu_cache_get(cachep)->batchcount = 1;
2277 cpu_cache_get(cachep)->touched = 0;
2278 cachep->batchcount = 1;
2279 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2284 * __kmem_cache_create - Create a cache.
2285 * @cachep: cache management descriptor
2286 * @flags: SLAB flags
2288 * Returns a ptr to the cache on success, NULL on failure.
2289 * Cannot be called within a int, but can be interrupted.
2290 * The @ctor is run when new pages are allocated by the cache.
2294 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2295 * to catch references to uninitialised memory.
2297 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2298 * for buffer overruns.
2300 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2301 * cacheline. This can be beneficial if you're counting cycles as closely
2305 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2307 size_t left_over, slab_size, ralign;
2310 size_t size = cachep->size;
2315 * Enable redzoning and last user accounting, except for caches with
2316 * large objects, if the increased size would increase the object size
2317 * above the next power of two: caches with object sizes just above a
2318 * power of two have a significant amount of internal fragmentation.
2320 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2321 2 * sizeof(unsigned long long)))
2322 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2323 if (!(flags & SLAB_DESTROY_BY_RCU))
2324 flags |= SLAB_POISON;
2326 if (flags & SLAB_DESTROY_BY_RCU)
2327 BUG_ON(flags & SLAB_POISON);
2331 * Check that size is in terms of words. This is needed to avoid
2332 * unaligned accesses for some archs when redzoning is used, and makes
2333 * sure any on-slab bufctl's are also correctly aligned.
2335 if (size & (BYTES_PER_WORD - 1)) {
2336 size += (BYTES_PER_WORD - 1);
2337 size &= ~(BYTES_PER_WORD - 1);
2340 /* calculate the final buffer alignment: */
2342 /* 1) arch recommendation: can be overridden for debug */
2343 if (flags & SLAB_HWCACHE_ALIGN) {
2345 * Default alignment: as specified by the arch code. Except if
2346 * an object is really small, then squeeze multiple objects into
2349 ralign = cache_line_size();
2350 while (size <= ralign / 2)
2353 ralign = BYTES_PER_WORD;
2357 * Redzoning and user store require word alignment or possibly larger.
2358 * Note this will be overridden by architecture or caller mandated
2359 * alignment if either is greater than BYTES_PER_WORD.
2361 if (flags & SLAB_STORE_USER)
2362 ralign = BYTES_PER_WORD;
2364 if (flags & SLAB_RED_ZONE) {
2365 ralign = REDZONE_ALIGN;
2366 /* If redzoning, ensure that the second redzone is suitably
2367 * aligned, by adjusting the object size accordingly. */
2368 size += REDZONE_ALIGN - 1;
2369 size &= ~(REDZONE_ALIGN - 1);
2372 /* 2) arch mandated alignment */
2373 if (ralign < ARCH_SLAB_MINALIGN) {
2374 ralign = ARCH_SLAB_MINALIGN;
2376 /* 3) caller mandated alignment */
2377 if (ralign < cachep->align) {
2378 ralign = cachep->align;
2380 /* disable debug if necessary */
2381 if (ralign > __alignof__(unsigned long long))
2382 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2386 cachep->align = ralign;
2388 if (slab_is_available())
2393 setup_nodelists_pointer(cachep);
2397 * Both debugging options require word-alignment which is calculated
2400 if (flags & SLAB_RED_ZONE) {
2401 /* add space for red zone words */
2402 cachep->obj_offset += sizeof(unsigned long long);
2403 size += 2 * sizeof(unsigned long long);
2405 if (flags & SLAB_STORE_USER) {
2406 /* user store requires one word storage behind the end of
2407 * the real object. But if the second red zone needs to be
2408 * aligned to 64 bits, we must allow that much space.
2410 if (flags & SLAB_RED_ZONE)
2411 size += REDZONE_ALIGN;
2413 size += BYTES_PER_WORD;
2415 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2416 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2417 && cachep->object_size > cache_line_size()
2418 && ALIGN(size, cachep->align) < PAGE_SIZE) {
2419 cachep->obj_offset += PAGE_SIZE - ALIGN(size, cachep->align);
2426 * Determine if the slab management is 'on' or 'off' slab.
2427 * (bootstrapping cannot cope with offslab caches so don't do
2428 * it too early on. Always use on-slab management when
2429 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2431 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init &&
2432 !(flags & SLAB_NOLEAKTRACE))
2434 * Size is large, assume best to place the slab management obj
2435 * off-slab (should allow better packing of objs).
2437 flags |= CFLGS_OFF_SLAB;
2439 size = ALIGN(size, cachep->align);
2441 left_over = calculate_slab_order(cachep, size, cachep->align, flags);
2446 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2447 + sizeof(struct slab), cachep->align);
2450 * If the slab has been placed off-slab, and we have enough space then
2451 * move it on-slab. This is at the expense of any extra colouring.
2453 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2454 flags &= ~CFLGS_OFF_SLAB;
2455 left_over -= slab_size;
2458 if (flags & CFLGS_OFF_SLAB) {
2459 /* really off slab. No need for manual alignment */
2461 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2463 #ifdef CONFIG_PAGE_POISONING
2464 /* If we're going to use the generic kernel_map_pages()
2465 * poisoning, then it's going to smash the contents of
2466 * the redzone and userword anyhow, so switch them off.
2468 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2469 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2473 cachep->colour_off = cache_line_size();
2474 /* Offset must be a multiple of the alignment. */
2475 if (cachep->colour_off < cachep->align)
2476 cachep->colour_off = cachep->align;
2477 cachep->colour = left_over / cachep->colour_off;
2478 cachep->slab_size = slab_size;
2479 cachep->flags = flags;
2480 cachep->allocflags = 0;
2481 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2482 cachep->allocflags |= GFP_DMA;
2483 cachep->size = size;
2484 cachep->reciprocal_buffer_size = reciprocal_value(size);
2486 if (flags & CFLGS_OFF_SLAB) {
2487 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2489 * This is a possibility for one of the malloc_sizes caches.
2490 * But since we go off slab only for object size greater than
2491 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2492 * this should not happen at all.
2493 * But leave a BUG_ON for some lucky dude.
2495 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2498 err = setup_cpu_cache(cachep, gfp);
2500 __kmem_cache_shutdown(cachep);
2504 if (flags & SLAB_DEBUG_OBJECTS) {
2506 * Would deadlock through slab_destroy()->call_rcu()->
2507 * debug_object_activate()->kmem_cache_alloc().
2509 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2511 slab_set_debugobj_lock_classes(cachep);
2518 static void check_irq_off(void)
2520 BUG_ON(!irqs_disabled());
2523 static void check_irq_on(void)
2525 BUG_ON(irqs_disabled());
2528 static void check_spinlock_acquired(struct kmem_cache *cachep)
2532 assert_spin_locked(&cachep->nodelists[numa_mem_id()]->list_lock);
2536 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2540 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2545 #define check_irq_off() do { } while(0)
2546 #define check_irq_on() do { } while(0)
2547 #define check_spinlock_acquired(x) do { } while(0)
2548 #define check_spinlock_acquired_node(x, y) do { } while(0)
2551 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2552 struct array_cache *ac,
2553 int force, int node);
2555 static void do_drain(void *arg)
2557 struct kmem_cache *cachep = arg;
2558 struct array_cache *ac;
2559 int node = numa_mem_id();
2562 ac = cpu_cache_get(cachep);
2563 spin_lock(&cachep->nodelists[node]->list_lock);
2564 free_block(cachep, ac->entry, ac->avail, node);
2565 spin_unlock(&cachep->nodelists[node]->list_lock);
2569 static void drain_cpu_caches(struct kmem_cache *cachep)
2571 struct kmem_list3 *l3;
2574 on_each_cpu(do_drain, cachep, 1);
2576 for_each_online_node(node) {
2577 l3 = cachep->nodelists[node];
2578 if (l3 && l3->alien)
2579 drain_alien_cache(cachep, l3->alien);
2582 for_each_online_node(node) {
2583 l3 = cachep->nodelists[node];
2585 drain_array(cachep, l3, l3->shared, 1, node);
2590 * Remove slabs from the list of free slabs.
2591 * Specify the number of slabs to drain in tofree.
2593 * Returns the actual number of slabs released.
2595 static int drain_freelist(struct kmem_cache *cache,
2596 struct kmem_list3 *l3, int tofree)
2598 struct list_head *p;
2603 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2605 spin_lock_irq(&l3->list_lock);
2606 p = l3->slabs_free.prev;
2607 if (p == &l3->slabs_free) {
2608 spin_unlock_irq(&l3->list_lock);
2612 slabp = list_entry(p, struct slab, list);
2614 BUG_ON(slabp->inuse);
2616 list_del(&slabp->list);
2618 * Safe to drop the lock. The slab is no longer linked
2621 l3->free_objects -= cache->num;
2622 spin_unlock_irq(&l3->list_lock);
2623 slab_destroy(cache, slabp);
2630 /* Called with slab_mutex held to protect against cpu hotplug */
2631 static int __cache_shrink(struct kmem_cache *cachep)
2634 struct kmem_list3 *l3;
2636 drain_cpu_caches(cachep);
2639 for_each_online_node(i) {
2640 l3 = cachep->nodelists[i];
2644 drain_freelist(cachep, l3, l3->free_objects);
2646 ret += !list_empty(&l3->slabs_full) ||
2647 !list_empty(&l3->slabs_partial);
2649 return (ret ? 1 : 0);
2653 * kmem_cache_shrink - Shrink a cache.
2654 * @cachep: The cache to shrink.
2656 * Releases as many slabs as possible for a cache.
2657 * To help debugging, a zero exit status indicates all slabs were released.
2659 int kmem_cache_shrink(struct kmem_cache *cachep)
2662 BUG_ON(!cachep || in_interrupt());
2665 mutex_lock(&slab_mutex);
2666 ret = __cache_shrink(cachep);
2667 mutex_unlock(&slab_mutex);
2671 EXPORT_SYMBOL(kmem_cache_shrink);
2673 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2676 struct kmem_list3 *l3;
2677 int rc = __cache_shrink(cachep);
2682 for_each_online_cpu(i)
2683 kfree(cachep->array[i]);
2685 /* NUMA: free the list3 structures */
2686 for_each_online_node(i) {
2687 l3 = cachep->nodelists[i];
2690 free_alien_cache(l3->alien);
2698 * Get the memory for a slab management obj.
2699 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2700 * always come from malloc_sizes caches. The slab descriptor cannot
2701 * come from the same cache which is getting created because,
2702 * when we are searching for an appropriate cache for these
2703 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2704 * If we are creating a malloc_sizes cache here it would not be visible to
2705 * kmem_find_general_cachep till the initialization is complete.
2706 * Hence we cannot have slabp_cache same as the original cache.
2708 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2709 int colour_off, gfp_t local_flags,
2714 if (OFF_SLAB(cachep)) {
2715 /* Slab management obj is off-slab. */
2716 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2717 local_flags, nodeid);
2719 * If the first object in the slab is leaked (it's allocated
2720 * but no one has a reference to it), we want to make sure
2721 * kmemleak does not treat the ->s_mem pointer as a reference
2722 * to the object. Otherwise we will not report the leak.
2724 kmemleak_scan_area(&slabp->list, sizeof(struct list_head),
2729 slabp = objp + colour_off;
2730 colour_off += cachep->slab_size;
2733 slabp->colouroff = colour_off;
2734 slabp->s_mem = objp + colour_off;
2735 slabp->nodeid = nodeid;
2740 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2742 return (kmem_bufctl_t *) (slabp + 1);
2745 static void cache_init_objs(struct kmem_cache *cachep,
2750 for (i = 0; i < cachep->num; i++) {
2751 void *objp = index_to_obj(cachep, slabp, i);
2753 /* need to poison the objs? */
2754 if (cachep->flags & SLAB_POISON)
2755 poison_obj(cachep, objp, POISON_FREE);
2756 if (cachep->flags & SLAB_STORE_USER)
2757 *dbg_userword(cachep, objp) = NULL;
2759 if (cachep->flags & SLAB_RED_ZONE) {
2760 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2761 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2764 * Constructors are not allowed to allocate memory from the same
2765 * cache which they are a constructor for. Otherwise, deadlock.
2766 * They must also be threaded.
2768 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2769 cachep->ctor(objp + obj_offset(cachep));
2771 if (cachep->flags & SLAB_RED_ZONE) {
2772 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2773 slab_error(cachep, "constructor overwrote the"
2774 " end of an object");
2775 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2776 slab_error(cachep, "constructor overwrote the"
2777 " start of an object");
2779 if ((cachep->size % PAGE_SIZE) == 0 &&
2780 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2781 kernel_map_pages(virt_to_page(objp),
2782 cachep->size / PAGE_SIZE, 0);
2787 slab_bufctl(slabp)[i] = i + 1;
2789 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2792 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2794 if (CONFIG_ZONE_DMA_FLAG) {
2795 if (flags & GFP_DMA)
2796 BUG_ON(!(cachep->allocflags & GFP_DMA));
2798 BUG_ON(cachep->allocflags & GFP_DMA);
2802 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2805 void *objp = index_to_obj(cachep, slabp, slabp->free);
2809 next = slab_bufctl(slabp)[slabp->free];
2811 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2812 WARN_ON(slabp->nodeid != nodeid);
2819 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2820 void *objp, int nodeid)
2822 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2825 /* Verify that the slab belongs to the intended node */
2826 WARN_ON(slabp->nodeid != nodeid);
2828 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2829 printk(KERN_ERR "slab: double free detected in cache "
2830 "'%s', objp %p\n", cachep->name, objp);
2834 slab_bufctl(slabp)[objnr] = slabp->free;
2835 slabp->free = objnr;
2840 * Map pages beginning at addr to the given cache and slab. This is required
2841 * for the slab allocator to be able to lookup the cache and slab of a
2842 * virtual address for kfree, ksize, and slab debugging.
2844 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2850 page = virt_to_page(addr);
2853 if (likely(!PageCompound(page)))
2854 nr_pages <<= cache->gfporder;
2857 page->slab_cache = cache;
2858 page->slab_page = slab;
2860 } while (--nr_pages);
2864 * Grow (by 1) the number of slabs within a cache. This is called by
2865 * kmem_cache_alloc() when there are no active objs left in a cache.
2867 static int cache_grow(struct kmem_cache *cachep,
2868 gfp_t flags, int nodeid, void *objp)
2873 struct kmem_list3 *l3;
2876 * Be lazy and only check for valid flags here, keeping it out of the
2877 * critical path in kmem_cache_alloc().
2879 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2880 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2882 /* Take the l3 list lock to change the colour_next on this node */
2884 l3 = cachep->nodelists[nodeid];
2885 spin_lock(&l3->list_lock);
2887 /* Get colour for the slab, and cal the next value. */
2888 offset = l3->colour_next;
2890 if (l3->colour_next >= cachep->colour)
2891 l3->colour_next = 0;
2892 spin_unlock(&l3->list_lock);
2894 offset *= cachep->colour_off;
2896 if (local_flags & __GFP_WAIT)
2900 * The test for missing atomic flag is performed here, rather than
2901 * the more obvious place, simply to reduce the critical path length
2902 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2903 * will eventually be caught here (where it matters).
2905 kmem_flagcheck(cachep, flags);
2908 * Get mem for the objs. Attempt to allocate a physical page from
2912 objp = kmem_getpages(cachep, local_flags, nodeid);
2916 /* Get slab management. */
2917 slabp = alloc_slabmgmt(cachep, objp, offset,
2918 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2922 slab_map_pages(cachep, slabp, objp);
2924 cache_init_objs(cachep, slabp);
2926 if (local_flags & __GFP_WAIT)
2927 local_irq_disable();
2929 spin_lock(&l3->list_lock);
2931 /* Make slab active. */
2932 list_add_tail(&slabp->list, &(l3->slabs_free));
2933 STATS_INC_GROWN(cachep);
2934 l3->free_objects += cachep->num;
2935 spin_unlock(&l3->list_lock);
2938 kmem_freepages(cachep, objp);
2940 if (local_flags & __GFP_WAIT)
2941 local_irq_disable();
2948 * Perform extra freeing checks:
2949 * - detect bad pointers.
2950 * - POISON/RED_ZONE checking
2952 static void kfree_debugcheck(const void *objp)
2954 if (!virt_addr_valid(objp)) {
2955 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2956 (unsigned long)objp);
2961 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2963 unsigned long long redzone1, redzone2;
2965 redzone1 = *dbg_redzone1(cache, obj);
2966 redzone2 = *dbg_redzone2(cache, obj);
2971 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2974 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2975 slab_error(cache, "double free detected");
2977 slab_error(cache, "memory outside object was overwritten");
2979 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2980 obj, redzone1, redzone2);
2983 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2984 unsigned long caller)
2990 BUG_ON(virt_to_cache(objp) != cachep);
2992 objp -= obj_offset(cachep);
2993 kfree_debugcheck(objp);
2994 page = virt_to_head_page(objp);
2996 slabp = page->slab_page;
2998 if (cachep->flags & SLAB_RED_ZONE) {
2999 verify_redzone_free(cachep, objp);
3000 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
3001 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
3003 if (cachep->flags & SLAB_STORE_USER)
3004 *dbg_userword(cachep, objp) = (void *)caller;
3006 objnr = obj_to_index(cachep, slabp, objp);
3008 BUG_ON(objnr >= cachep->num);
3009 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
3011 #ifdef CONFIG_DEBUG_SLAB_LEAK
3012 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
3014 if (cachep->flags & SLAB_POISON) {
3015 #ifdef CONFIG_DEBUG_PAGEALLOC
3016 if ((cachep->size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
3017 store_stackinfo(cachep, objp, caller);
3018 kernel_map_pages(virt_to_page(objp),
3019 cachep->size / PAGE_SIZE, 0);
3021 poison_obj(cachep, objp, POISON_FREE);
3024 poison_obj(cachep, objp, POISON_FREE);
3030 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
3035 /* Check slab's freelist to see if this obj is there. */
3036 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
3038 if (entries > cachep->num || i >= cachep->num)
3041 if (entries != cachep->num - slabp->inuse) {
3043 printk(KERN_ERR "slab: Internal list corruption detected in "
3044 "cache '%s'(%d), slabp %p(%d). Tainted(%s). Hexdump:\n",
3045 cachep->name, cachep->num, slabp, slabp->inuse,
3047 print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 16, 1, slabp,
3048 sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t),
3054 #define kfree_debugcheck(x) do { } while(0)
3055 #define cache_free_debugcheck(x,objp,z) (objp)
3056 #define check_slabp(x,y) do { } while(0)
3059 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
3063 struct kmem_list3 *l3;
3064 struct array_cache *ac;
3068 node = numa_mem_id();
3069 if (unlikely(force_refill))
3072 ac = cpu_cache_get(cachep);
3073 batchcount = ac->batchcount;
3074 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
3076 * If there was little recent activity on this cache, then
3077 * perform only a partial refill. Otherwise we could generate
3080 batchcount = BATCHREFILL_LIMIT;
3082 l3 = cachep->nodelists[node];
3084 BUG_ON(ac->avail > 0 || !l3);
3085 spin_lock(&l3->list_lock);
3087 /* See if we can refill from the shared array */
3088 if (l3->shared && transfer_objects(ac, l3->shared, batchcount)) {
3089 l3->shared->touched = 1;
3093 while (batchcount > 0) {
3094 struct list_head *entry;
3096 /* Get slab alloc is to come from. */
3097 entry = l3->slabs_partial.next;
3098 if (entry == &l3->slabs_partial) {
3099 l3->free_touched = 1;
3100 entry = l3->slabs_free.next;
3101 if (entry == &l3->slabs_free)
3105 slabp = list_entry(entry, struct slab, list);
3106 check_slabp(cachep, slabp);
3107 check_spinlock_acquired(cachep);
3110 * The slab was either on partial or free list so
3111 * there must be at least one object available for
3114 BUG_ON(slabp->inuse >= cachep->num);
3116 while (slabp->inuse < cachep->num && batchcount--) {
3117 STATS_INC_ALLOCED(cachep);
3118 STATS_INC_ACTIVE(cachep);
3119 STATS_SET_HIGH(cachep);
3121 ac_put_obj(cachep, ac, slab_get_obj(cachep, slabp,
3124 check_slabp(cachep, slabp);
3126 /* move slabp to correct slabp list: */
3127 list_del(&slabp->list);
3128 if (slabp->free == BUFCTL_END)
3129 list_add(&slabp->list, &l3->slabs_full);
3131 list_add(&slabp->list, &l3->slabs_partial);
3135 l3->free_objects -= ac->avail;
3137 spin_unlock(&l3->list_lock);
3139 if (unlikely(!ac->avail)) {
3142 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3144 /* cache_grow can reenable interrupts, then ac could change. */
3145 ac = cpu_cache_get(cachep);
3146 node = numa_mem_id();
3148 /* no objects in sight? abort */
3149 if (!x && (ac->avail == 0 || force_refill))
3152 if (!ac->avail) /* objects refilled by interrupt? */
3157 return ac_get_obj(cachep, ac, flags, force_refill);
3160 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3163 might_sleep_if(flags & __GFP_WAIT);
3165 kmem_flagcheck(cachep, flags);
3170 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3171 gfp_t flags, void *objp, unsigned long caller)
3175 if (cachep->flags & SLAB_POISON) {
3176 #ifdef CONFIG_DEBUG_PAGEALLOC
3177 if ((cachep->size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3178 kernel_map_pages(virt_to_page(objp),
3179 cachep->size / PAGE_SIZE, 1);
3181 check_poison_obj(cachep, objp);
3183 check_poison_obj(cachep, objp);
3185 poison_obj(cachep, objp, POISON_INUSE);
3187 if (cachep->flags & SLAB_STORE_USER)
3188 *dbg_userword(cachep, objp) = (void *)caller;
3190 if (cachep->flags & SLAB_RED_ZONE) {
3191 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3192 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3193 slab_error(cachep, "double free, or memory outside"
3194 " object was overwritten");
3196 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3197 objp, *dbg_redzone1(cachep, objp),
3198 *dbg_redzone2(cachep, objp));
3200 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3201 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3203 #ifdef CONFIG_DEBUG_SLAB_LEAK
3208 slabp = virt_to_head_page(objp)->slab_page;
3209 objnr = (unsigned)(objp - slabp->s_mem) / cachep->size;
3210 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3213 objp += obj_offset(cachep);
3214 if (cachep->ctor && cachep->flags & SLAB_POISON)
3216 if (ARCH_SLAB_MINALIGN &&
3217 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3218 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3219 objp, (int)ARCH_SLAB_MINALIGN);
3224 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3227 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3229 if (cachep == kmem_cache)
3232 return should_failslab(cachep->object_size, flags, cachep->flags);
3235 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3238 struct array_cache *ac;
3239 bool force_refill = false;
3243 ac = cpu_cache_get(cachep);
3244 if (likely(ac->avail)) {
3246 objp = ac_get_obj(cachep, ac, flags, false);
3249 * Allow for the possibility all avail objects are not allowed
3250 * by the current flags
3253 STATS_INC_ALLOCHIT(cachep);
3256 force_refill = true;
3259 STATS_INC_ALLOCMISS(cachep);
3260 objp = cache_alloc_refill(cachep, flags, force_refill);
3262 * the 'ac' may be updated by cache_alloc_refill(),
3263 * and kmemleak_erase() requires its correct value.
3265 ac = cpu_cache_get(cachep);
3269 * To avoid a false negative, if an object that is in one of the
3270 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3271 * treat the array pointers as a reference to the object.
3274 kmemleak_erase(&ac->entry[ac->avail]);
3280 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3282 * If we are in_interrupt, then process context, including cpusets and
3283 * mempolicy, may not apply and should not be used for allocation policy.
3285 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3287 int nid_alloc, nid_here;
3289 if (in_interrupt() || (flags & __GFP_THISNODE))
3291 nid_alloc = nid_here = numa_mem_id();
3292 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3293 nid_alloc = cpuset_slab_spread_node();
3294 else if (current->mempolicy)
3295 nid_alloc = slab_node();
3296 if (nid_alloc != nid_here)
3297 return ____cache_alloc_node(cachep, flags, nid_alloc);
3302 * Fallback function if there was no memory available and no objects on a
3303 * certain node and fall back is permitted. First we scan all the
3304 * available nodelists for available objects. If that fails then we
3305 * perform an allocation without specifying a node. This allows the page
3306 * allocator to do its reclaim / fallback magic. We then insert the
3307 * slab into the proper nodelist and then allocate from it.
3309 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3311 struct zonelist *zonelist;
3315 enum zone_type high_zoneidx = gfp_zone(flags);
3318 unsigned int cpuset_mems_cookie;
3320 if (flags & __GFP_THISNODE)
3323 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3326 cpuset_mems_cookie = get_mems_allowed();
3327 zonelist = node_zonelist(slab_node(), flags);
3331 * Look through allowed nodes for objects available
3332 * from existing per node queues.
3334 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3335 nid = zone_to_nid(zone);
3337 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3338 cache->nodelists[nid] &&
3339 cache->nodelists[nid]->free_objects) {
3340 obj = ____cache_alloc_node(cache,
3341 flags | GFP_THISNODE, nid);
3349 * This allocation will be performed within the constraints
3350 * of the current cpuset / memory policy requirements.
3351 * We may trigger various forms of reclaim on the allowed
3352 * set and go into memory reserves if necessary.
3354 if (local_flags & __GFP_WAIT)
3356 kmem_flagcheck(cache, flags);
3357 obj = kmem_getpages(cache, local_flags, numa_mem_id());
3358 if (local_flags & __GFP_WAIT)
3359 local_irq_disable();
3362 * Insert into the appropriate per node queues
3364 nid = page_to_nid(virt_to_page(obj));
3365 if (cache_grow(cache, flags, nid, obj)) {
3366 obj = ____cache_alloc_node(cache,
3367 flags | GFP_THISNODE, nid);
3370 * Another processor may allocate the
3371 * objects in the slab since we are
3372 * not holding any locks.
3376 /* cache_grow already freed obj */
3382 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !obj))
3388 * A interface to enable slab creation on nodeid
3390 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3393 struct list_head *entry;
3395 struct kmem_list3 *l3;
3399 l3 = cachep->nodelists[nodeid];
3404 spin_lock(&l3->list_lock);
3405 entry = l3->slabs_partial.next;
3406 if (entry == &l3->slabs_partial) {
3407 l3->free_touched = 1;
3408 entry = l3->slabs_free.next;
3409 if (entry == &l3->slabs_free)
3413 slabp = list_entry(entry, struct slab, list);
3414 check_spinlock_acquired_node(cachep, nodeid);
3415 check_slabp(cachep, slabp);
3417 STATS_INC_NODEALLOCS(cachep);
3418 STATS_INC_ACTIVE(cachep);
3419 STATS_SET_HIGH(cachep);
3421 BUG_ON(slabp->inuse == cachep->num);
3423 obj = slab_get_obj(cachep, slabp, nodeid);
3424 check_slabp(cachep, slabp);
3426 /* move slabp to correct slabp list: */
3427 list_del(&slabp->list);
3429 if (slabp->free == BUFCTL_END)
3430 list_add(&slabp->list, &l3->slabs_full);
3432 list_add(&slabp->list, &l3->slabs_partial);
3434 spin_unlock(&l3->list_lock);
3438 spin_unlock(&l3->list_lock);
3439 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3443 return fallback_alloc(cachep, flags);
3450 * kmem_cache_alloc_node - Allocate an object on the specified node
3451 * @cachep: The cache to allocate from.
3452 * @flags: See kmalloc().
3453 * @nodeid: node number of the target node.
3454 * @caller: return address of caller, used for debug information
3456 * Identical to kmem_cache_alloc but it will allocate memory on the given
3457 * node, which can improve the performance for cpu bound structures.
3459 * Fallback to other node is possible if __GFP_THISNODE is not set.
3461 static __always_inline void *
3462 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3463 unsigned long caller)
3465 unsigned long save_flags;
3467 int slab_node = numa_mem_id();
3469 flags &= gfp_allowed_mask;
3471 lockdep_trace_alloc(flags);
3473 if (slab_should_failslab(cachep, flags))
3476 cache_alloc_debugcheck_before(cachep, flags);
3477 local_irq_save(save_flags);
3479 if (nodeid == NUMA_NO_NODE)
3482 if (unlikely(!cachep->nodelists[nodeid])) {
3483 /* Node not bootstrapped yet */
3484 ptr = fallback_alloc(cachep, flags);
3488 if (nodeid == slab_node) {
3490 * Use the locally cached objects if possible.
3491 * However ____cache_alloc does not allow fallback
3492 * to other nodes. It may fail while we still have
3493 * objects on other nodes available.
3495 ptr = ____cache_alloc(cachep, flags);
3499 /* ___cache_alloc_node can fall back to other nodes */
3500 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3502 local_irq_restore(save_flags);
3503 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3504 kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3508 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3510 if (unlikely((flags & __GFP_ZERO) && ptr))
3511 memset(ptr, 0, cachep->object_size);
3516 static __always_inline void *
3517 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3521 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3522 objp = alternate_node_alloc(cache, flags);
3526 objp = ____cache_alloc(cache, flags);
3529 * We may just have run out of memory on the local node.
3530 * ____cache_alloc_node() knows how to locate memory on other nodes
3533 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3540 static __always_inline void *
3541 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3543 return ____cache_alloc(cachep, flags);
3546 #endif /* CONFIG_NUMA */
3548 static __always_inline void *
3549 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3551 unsigned long save_flags;
3554 flags &= gfp_allowed_mask;
3556 lockdep_trace_alloc(flags);
3558 if (slab_should_failslab(cachep, flags))
3561 cache_alloc_debugcheck_before(cachep, flags);
3562 local_irq_save(save_flags);
3563 objp = __do_cache_alloc(cachep, flags);
3564 local_irq_restore(save_flags);
3565 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3566 kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3571 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3573 if (unlikely((flags & __GFP_ZERO) && objp))
3574 memset(objp, 0, cachep->object_size);
3580 * Caller needs to acquire correct kmem_list's list_lock
3582 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3586 struct kmem_list3 *l3;
3588 for (i = 0; i < nr_objects; i++) {
3592 clear_obj_pfmemalloc(&objpp[i]);
3595 slabp = virt_to_slab(objp);
3596 l3 = cachep->nodelists[node];
3597 list_del(&slabp->list);
3598 check_spinlock_acquired_node(cachep, node);
3599 check_slabp(cachep, slabp);
3600 slab_put_obj(cachep, slabp, objp, node);
3601 STATS_DEC_ACTIVE(cachep);
3603 check_slabp(cachep, slabp);
3605 /* fixup slab chains */
3606 if (slabp->inuse == 0) {
3607 if (l3->free_objects > l3->free_limit) {
3608 l3->free_objects -= cachep->num;
3609 /* No need to drop any previously held
3610 * lock here, even if we have a off-slab slab
3611 * descriptor it is guaranteed to come from
3612 * a different cache, refer to comments before
3615 slab_destroy(cachep, slabp);
3617 list_add(&slabp->list, &l3->slabs_free);
3620 /* Unconditionally move a slab to the end of the
3621 * partial list on free - maximum time for the
3622 * other objects to be freed, too.
3624 list_add_tail(&slabp->list, &l3->slabs_partial);
3629 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3632 struct kmem_list3 *l3;
3633 int node = numa_mem_id();
3635 batchcount = ac->batchcount;
3637 BUG_ON(!batchcount || batchcount > ac->avail);
3640 l3 = cachep->nodelists[node];
3641 spin_lock(&l3->list_lock);
3643 struct array_cache *shared_array = l3->shared;
3644 int max = shared_array->limit - shared_array->avail;
3646 if (batchcount > max)
3648 memcpy(&(shared_array->entry[shared_array->avail]),
3649 ac->entry, sizeof(void *) * batchcount);
3650 shared_array->avail += batchcount;
3655 free_block(cachep, ac->entry, batchcount, node);
3660 struct list_head *p;
3662 p = l3->slabs_free.next;
3663 while (p != &(l3->slabs_free)) {
3666 slabp = list_entry(p, struct slab, list);
3667 BUG_ON(slabp->inuse);
3672 STATS_SET_FREEABLE(cachep, i);
3675 spin_unlock(&l3->list_lock);
3676 ac->avail -= batchcount;
3677 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3681 * Release an obj back to its cache. If the obj has a constructed state, it must
3682 * be in this state _before_ it is released. Called with disabled ints.
3684 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3685 unsigned long caller)
3687 struct array_cache *ac = cpu_cache_get(cachep);
3690 kmemleak_free_recursive(objp, cachep->flags);
3691 objp = cache_free_debugcheck(cachep, objp, caller);
3693 kmemcheck_slab_free(cachep, objp, cachep->object_size);
3696 * Skip calling cache_free_alien() when the platform is not numa.
3697 * This will avoid cache misses that happen while accessing slabp (which
3698 * is per page memory reference) to get nodeid. Instead use a global
3699 * variable to skip the call, which is mostly likely to be present in
3702 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3705 if (likely(ac->avail < ac->limit)) {
3706 STATS_INC_FREEHIT(cachep);
3708 STATS_INC_FREEMISS(cachep);
3709 cache_flusharray(cachep, ac);
3712 ac_put_obj(cachep, ac, objp);
3716 * kmem_cache_alloc - Allocate an object
3717 * @cachep: The cache to allocate from.
3718 * @flags: See kmalloc().
3720 * Allocate an object from this cache. The flags are only relevant
3721 * if the cache has no available objects.
3723 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3725 void *ret = slab_alloc(cachep, flags, _RET_IP_);
3727 trace_kmem_cache_alloc(_RET_IP_, ret,
3728 cachep->object_size, cachep->size, flags);
3732 EXPORT_SYMBOL(kmem_cache_alloc);
3734 #ifdef CONFIG_TRACING
3736 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3740 ret = slab_alloc(cachep, flags, _RET_IP_);
3742 trace_kmalloc(_RET_IP_, ret,
3743 size, cachep->size, flags);
3746 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3750 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3752 void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3754 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3755 cachep->object_size, cachep->size,
3760 EXPORT_SYMBOL(kmem_cache_alloc_node);
3762 #ifdef CONFIG_TRACING
3763 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3770 ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3772 trace_kmalloc_node(_RET_IP_, ret,
3777 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3780 static __always_inline void *
3781 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3783 struct kmem_cache *cachep;
3785 cachep = kmem_find_general_cachep(size, flags);
3786 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3788 return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3791 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3792 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3794 return __do_kmalloc_node(size, flags, node, _RET_IP_);
3796 EXPORT_SYMBOL(__kmalloc_node);
3798 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3799 int node, unsigned long caller)
3801 return __do_kmalloc_node(size, flags, node, caller);
3803 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3805 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3807 return __do_kmalloc_node(size, flags, node, 0);
3809 EXPORT_SYMBOL(__kmalloc_node);
3810 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3811 #endif /* CONFIG_NUMA */
3814 * __do_kmalloc - allocate memory
3815 * @size: how many bytes of memory are required.
3816 * @flags: the type of memory to allocate (see kmalloc).
3817 * @caller: function caller for debug tracking of the caller
3819 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3820 unsigned long caller)
3822 struct kmem_cache *cachep;
3825 /* If you want to save a few bytes .text space: replace
3827 * Then kmalloc uses the uninlined functions instead of the inline
3830 cachep = __find_general_cachep(size, flags);
3831 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3833 ret = slab_alloc(cachep, flags, caller);
3835 trace_kmalloc(caller, ret,
3836 size, cachep->size, flags);
3842 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3843 void *__kmalloc(size_t size, gfp_t flags)
3845 return __do_kmalloc(size, flags, _RET_IP_);
3847 EXPORT_SYMBOL(__kmalloc);
3849 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3851 return __do_kmalloc(size, flags, caller);
3853 EXPORT_SYMBOL(__kmalloc_track_caller);
3856 void *__kmalloc(size_t size, gfp_t flags)
3858 return __do_kmalloc(size, flags, 0);
3860 EXPORT_SYMBOL(__kmalloc);
3864 * kmem_cache_free - Deallocate an object
3865 * @cachep: The cache the allocation was from.
3866 * @objp: The previously allocated object.
3868 * Free an object which was previously allocated from this
3871 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3873 unsigned long flags;
3875 local_irq_save(flags);
3876 debug_check_no_locks_freed(objp, cachep->object_size);
3877 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3878 debug_check_no_obj_freed(objp, cachep->object_size);
3879 __cache_free(cachep, objp, _RET_IP_);
3880 local_irq_restore(flags);
3882 trace_kmem_cache_free(_RET_IP_, objp);
3884 EXPORT_SYMBOL(kmem_cache_free);
3887 * kfree - free previously allocated memory
3888 * @objp: pointer returned by kmalloc.
3890 * If @objp is NULL, no operation is performed.
3892 * Don't free memory not originally allocated by kmalloc()
3893 * or you will run into trouble.
3895 void kfree(const void *objp)
3897 struct kmem_cache *c;
3898 unsigned long flags;
3900 trace_kfree(_RET_IP_, objp);
3902 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3904 local_irq_save(flags);
3905 kfree_debugcheck(objp);
3906 c = virt_to_cache(objp);
3907 debug_check_no_locks_freed(objp, c->object_size);
3909 debug_check_no_obj_freed(objp, c->object_size);
3910 __cache_free(c, (void *)objp, _RET_IP_);
3911 local_irq_restore(flags);
3913 EXPORT_SYMBOL(kfree);
3916 * This initializes kmem_list3 or resizes various caches for all nodes.
3918 static int alloc_kmemlist(struct kmem_cache *cachep, gfp_t gfp)
3921 struct kmem_list3 *l3;
3922 struct array_cache *new_shared;
3923 struct array_cache **new_alien = NULL;
3925 for_each_online_node(node) {
3927 if (use_alien_caches) {
3928 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3934 if (cachep->shared) {
3935 new_shared = alloc_arraycache(node,
3936 cachep->shared*cachep->batchcount,
3939 free_alien_cache(new_alien);
3944 l3 = cachep->nodelists[node];
3946 struct array_cache *shared = l3->shared;
3948 spin_lock_irq(&l3->list_lock);
3951 free_block(cachep, shared->entry,
3952 shared->avail, node);
3954 l3->shared = new_shared;
3956 l3->alien = new_alien;
3959 l3->free_limit = (1 + nr_cpus_node(node)) *
3960 cachep->batchcount + cachep->num;
3961 spin_unlock_irq(&l3->list_lock);
3963 free_alien_cache(new_alien);
3966 l3 = kmalloc_node(sizeof(struct kmem_list3), gfp, node);
3968 free_alien_cache(new_alien);
3973 kmem_list3_init(l3);
3974 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3975 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3976 l3->shared = new_shared;
3977 l3->alien = new_alien;
3978 l3->free_limit = (1 + nr_cpus_node(node)) *
3979 cachep->batchcount + cachep->num;
3980 cachep->nodelists[node] = l3;
3985 if (!cachep->list.next) {
3986 /* Cache is not active yet. Roll back what we did */
3989 if (cachep->nodelists[node]) {
3990 l3 = cachep->nodelists[node];
3993 free_alien_cache(l3->alien);
3995 cachep->nodelists[node] = NULL;
4003 struct ccupdate_struct {
4004 struct kmem_cache *cachep;
4005 struct array_cache *new[0];
4008 static void do_ccupdate_local(void *info)
4010 struct ccupdate_struct *new = info;
4011 struct array_cache *old;
4014 old = cpu_cache_get(new->cachep);
4016 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
4017 new->new[smp_processor_id()] = old;
4020 /* Always called with the slab_mutex held */
4021 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
4022 int batchcount, int shared, gfp_t gfp)
4024 struct ccupdate_struct *new;
4027 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
4032 for_each_online_cpu(i) {
4033 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
4036 for (i--; i >= 0; i--)
4042 new->cachep = cachep;
4044 on_each_cpu(do_ccupdate_local, (void *)new, 1);
4047 cachep->batchcount = batchcount;
4048 cachep->limit = limit;
4049 cachep->shared = shared;
4051 for_each_online_cpu(i) {
4052 struct array_cache *ccold = new->new[i];
4055 spin_lock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4056 free_block(cachep, ccold->entry, ccold->avail, cpu_to_mem(i));
4057 spin_unlock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4061 return alloc_kmemlist(cachep, gfp);
4064 /* Called with slab_mutex held always */
4065 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
4071 * The head array serves three purposes:
4072 * - create a LIFO ordering, i.e. return objects that are cache-warm
4073 * - reduce the number of spinlock operations.
4074 * - reduce the number of linked list operations on the slab and
4075 * bufctl chains: array operations are cheaper.
4076 * The numbers are guessed, we should auto-tune as described by
4079 if (cachep->size > 131072)
4081 else if (cachep->size > PAGE_SIZE)
4083 else if (cachep->size > 1024)
4085 else if (cachep->size > 256)
4091 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4092 * allocation behaviour: Most allocs on one cpu, most free operations
4093 * on another cpu. For these cases, an efficient object passing between
4094 * cpus is necessary. This is provided by a shared array. The array
4095 * replaces Bonwick's magazine layer.
4096 * On uniprocessor, it's functionally equivalent (but less efficient)
4097 * to a larger limit. Thus disabled by default.
4100 if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
4105 * With debugging enabled, large batchcount lead to excessively long
4106 * periods with disabled local interrupts. Limit the batchcount
4111 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared, gfp);
4113 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4114 cachep->name, -err);
4119 * Drain an array if it contains any elements taking the l3 lock only if
4120 * necessary. Note that the l3 listlock also protects the array_cache
4121 * if drain_array() is used on the shared array.
4123 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
4124 struct array_cache *ac, int force, int node)
4128 if (!ac || !ac->avail)
4130 if (ac->touched && !force) {
4133 spin_lock_irq(&l3->list_lock);
4135 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4136 if (tofree > ac->avail)
4137 tofree = (ac->avail + 1) / 2;
4138 free_block(cachep, ac->entry, tofree, node);
4139 ac->avail -= tofree;
4140 memmove(ac->entry, &(ac->entry[tofree]),
4141 sizeof(void *) * ac->avail);
4143 spin_unlock_irq(&l3->list_lock);
4148 * cache_reap - Reclaim memory from caches.
4149 * @w: work descriptor
4151 * Called from workqueue/eventd every few seconds.
4153 * - clear the per-cpu caches for this CPU.
4154 * - return freeable pages to the main free memory pool.
4156 * If we cannot acquire the cache chain mutex then just give up - we'll try
4157 * again on the next iteration.
4159 static void cache_reap(struct work_struct *w)
4161 struct kmem_cache *searchp;
4162 struct kmem_list3 *l3;
4163 int node = numa_mem_id();
4164 struct delayed_work *work = to_delayed_work(w);
4166 if (!mutex_trylock(&slab_mutex))
4167 /* Give up. Setup the next iteration. */
4170 list_for_each_entry(searchp, &slab_caches, list) {
4174 * We only take the l3 lock if absolutely necessary and we
4175 * have established with reasonable certainty that
4176 * we can do some work if the lock was obtained.
4178 l3 = searchp->nodelists[node];
4180 reap_alien(searchp, l3);
4182 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4185 * These are racy checks but it does not matter
4186 * if we skip one check or scan twice.
4188 if (time_after(l3->next_reap, jiffies))
4191 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4193 drain_array(searchp, l3, l3->shared, 0, node);
4195 if (l3->free_touched)
4196 l3->free_touched = 0;
4200 freed = drain_freelist(searchp, l3, (l3->free_limit +
4201 5 * searchp->num - 1) / (5 * searchp->num));
4202 STATS_ADD_REAPED(searchp, freed);
4208 mutex_unlock(&slab_mutex);
4211 /* Set up the next iteration */
4212 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4215 #ifdef CONFIG_SLABINFO
4216 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4219 unsigned long active_objs;
4220 unsigned long num_objs;
4221 unsigned long active_slabs = 0;
4222 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4226 struct kmem_list3 *l3;
4230 for_each_online_node(node) {
4231 l3 = cachep->nodelists[node];
4236 spin_lock_irq(&l3->list_lock);
4238 list_for_each_entry(slabp, &l3->slabs_full, list) {
4239 if (slabp->inuse != cachep->num && !error)
4240 error = "slabs_full accounting error";
4241 active_objs += cachep->num;
4244 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4245 if (slabp->inuse == cachep->num && !error)
4246 error = "slabs_partial inuse accounting error";
4247 if (!slabp->inuse && !error)
4248 error = "slabs_partial/inuse accounting error";
4249 active_objs += slabp->inuse;
4252 list_for_each_entry(slabp, &l3->slabs_free, list) {
4253 if (slabp->inuse && !error)
4254 error = "slabs_free/inuse accounting error";
4257 free_objects += l3->free_objects;
4259 shared_avail += l3->shared->avail;
4261 spin_unlock_irq(&l3->list_lock);
4263 num_slabs += active_slabs;
4264 num_objs = num_slabs * cachep->num;
4265 if (num_objs - active_objs != free_objects && !error)
4266 error = "free_objects accounting error";
4268 name = cachep->name;
4270 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4272 sinfo->active_objs = active_objs;
4273 sinfo->num_objs = num_objs;
4274 sinfo->active_slabs = active_slabs;
4275 sinfo->num_slabs = num_slabs;
4276 sinfo->shared_avail = shared_avail;
4277 sinfo->limit = cachep->limit;
4278 sinfo->batchcount = cachep->batchcount;
4279 sinfo->shared = cachep->shared;
4280 sinfo->objects_per_slab = cachep->num;
4281 sinfo->cache_order = cachep->gfporder;
4284 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4288 unsigned long high = cachep->high_mark;
4289 unsigned long allocs = cachep->num_allocations;
4290 unsigned long grown = cachep->grown;
4291 unsigned long reaped = cachep->reaped;
4292 unsigned long errors = cachep->errors;
4293 unsigned long max_freeable = cachep->max_freeable;
4294 unsigned long node_allocs = cachep->node_allocs;
4295 unsigned long node_frees = cachep->node_frees;
4296 unsigned long overflows = cachep->node_overflow;
4298 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4299 "%4lu %4lu %4lu %4lu %4lu",
4300 allocs, high, grown,
4301 reaped, errors, max_freeable, node_allocs,
4302 node_frees, overflows);
4306 unsigned long allochit = atomic_read(&cachep->allochit);
4307 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4308 unsigned long freehit = atomic_read(&cachep->freehit);
4309 unsigned long freemiss = atomic_read(&cachep->freemiss);
4311 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4312 allochit, allocmiss, freehit, freemiss);
4317 #define MAX_SLABINFO_WRITE 128
4319 * slabinfo_write - Tuning for the slab allocator
4321 * @buffer: user buffer
4322 * @count: data length
4325 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4326 size_t count, loff_t *ppos)
4328 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4329 int limit, batchcount, shared, res;
4330 struct kmem_cache *cachep;
4332 if (count > MAX_SLABINFO_WRITE)
4334 if (copy_from_user(&kbuf, buffer, count))
4336 kbuf[MAX_SLABINFO_WRITE] = '\0';
4338 tmp = strchr(kbuf, ' ');
4343 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4346 /* Find the cache in the chain of caches. */
4347 mutex_lock(&slab_mutex);
4349 list_for_each_entry(cachep, &slab_caches, list) {
4350 if (!strcmp(cachep->name, kbuf)) {
4351 if (limit < 1 || batchcount < 1 ||
4352 batchcount > limit || shared < 0) {
4355 res = do_tune_cpucache(cachep, limit,
4362 mutex_unlock(&slab_mutex);
4368 #ifdef CONFIG_DEBUG_SLAB_LEAK
4370 static void *leaks_start(struct seq_file *m, loff_t *pos)
4372 mutex_lock(&slab_mutex);
4373 return seq_list_start(&slab_caches, *pos);
4376 static inline int add_caller(unsigned long *n, unsigned long v)
4386 unsigned long *q = p + 2 * i;
4400 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4406 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4412 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->size) {
4413 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4415 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4420 static void show_symbol(struct seq_file *m, unsigned long address)
4422 #ifdef CONFIG_KALLSYMS
4423 unsigned long offset, size;
4424 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4426 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4427 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4429 seq_printf(m, " [%s]", modname);
4433 seq_printf(m, "%p", (void *)address);
4436 static int leaks_show(struct seq_file *m, void *p)
4438 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4440 struct kmem_list3 *l3;
4442 unsigned long *n = m->private;
4446 if (!(cachep->flags & SLAB_STORE_USER))
4448 if (!(cachep->flags & SLAB_RED_ZONE))
4451 /* OK, we can do it */
4455 for_each_online_node(node) {
4456 l3 = cachep->nodelists[node];
4461 spin_lock_irq(&l3->list_lock);
4463 list_for_each_entry(slabp, &l3->slabs_full, list)
4464 handle_slab(n, cachep, slabp);
4465 list_for_each_entry(slabp, &l3->slabs_partial, list)
4466 handle_slab(n, cachep, slabp);
4467 spin_unlock_irq(&l3->list_lock);
4469 name = cachep->name;
4471 /* Increase the buffer size */
4472 mutex_unlock(&slab_mutex);
4473 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4475 /* Too bad, we are really out */
4477 mutex_lock(&slab_mutex);
4480 *(unsigned long *)m->private = n[0] * 2;
4482 mutex_lock(&slab_mutex);
4483 /* Now make sure this entry will be retried */
4487 for (i = 0; i < n[1]; i++) {
4488 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4489 show_symbol(m, n[2*i+2]);
4496 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4498 return seq_list_next(p, &slab_caches, pos);
4501 static void s_stop(struct seq_file *m, void *p)
4503 mutex_unlock(&slab_mutex);
4506 static const struct seq_operations slabstats_op = {
4507 .start = leaks_start,
4513 static int slabstats_open(struct inode *inode, struct file *file)
4515 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4518 ret = seq_open(file, &slabstats_op);
4520 struct seq_file *m = file->private_data;
4521 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4530 static const struct file_operations proc_slabstats_operations = {
4531 .open = slabstats_open,
4533 .llseek = seq_lseek,
4534 .release = seq_release_private,
4538 static int __init slab_proc_init(void)
4540 #ifdef CONFIG_DEBUG_SLAB_LEAK
4541 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4545 module_init(slab_proc_init);
4549 * ksize - get the actual amount of memory allocated for a given object
4550 * @objp: Pointer to the object
4552 * kmalloc may internally round up allocations and return more memory
4553 * than requested. ksize() can be used to determine the actual amount of
4554 * memory allocated. The caller may use this additional memory, even though
4555 * a smaller amount of memory was initially specified with the kmalloc call.
4556 * The caller must guarantee that objp points to a valid object previously
4557 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4558 * must not be freed during the duration of the call.
4560 size_t ksize(const void *objp)
4563 if (unlikely(objp == ZERO_SIZE_PTR))
4566 return virt_to_cache(objp)->object_size;
4568 EXPORT_SYMBOL(ksize);