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);
2341 * Redzoning and user store require word alignment or possibly larger.
2342 * Note this will be overridden by architecture or caller mandated
2343 * alignment if either is greater than BYTES_PER_WORD.
2345 if (flags & SLAB_STORE_USER)
2346 ralign = BYTES_PER_WORD;
2348 if (flags & SLAB_RED_ZONE) {
2349 ralign = REDZONE_ALIGN;
2350 /* If redzoning, ensure that the second redzone is suitably
2351 * aligned, by adjusting the object size accordingly. */
2352 size += REDZONE_ALIGN - 1;
2353 size &= ~(REDZONE_ALIGN - 1);
2356 /* 3) caller mandated alignment */
2357 if (ralign < cachep->align) {
2358 ralign = cachep->align;
2360 /* disable debug if necessary */
2361 if (ralign > __alignof__(unsigned long long))
2362 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2366 cachep->align = ralign;
2368 if (slab_is_available())
2373 setup_nodelists_pointer(cachep);
2377 * Both debugging options require word-alignment which is calculated
2380 if (flags & SLAB_RED_ZONE) {
2381 /* add space for red zone words */
2382 cachep->obj_offset += sizeof(unsigned long long);
2383 size += 2 * sizeof(unsigned long long);
2385 if (flags & SLAB_STORE_USER) {
2386 /* user store requires one word storage behind the end of
2387 * the real object. But if the second red zone needs to be
2388 * aligned to 64 bits, we must allow that much space.
2390 if (flags & SLAB_RED_ZONE)
2391 size += REDZONE_ALIGN;
2393 size += BYTES_PER_WORD;
2395 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2396 if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2397 && cachep->object_size > cache_line_size()
2398 && ALIGN(size, cachep->align) < PAGE_SIZE) {
2399 cachep->obj_offset += PAGE_SIZE - ALIGN(size, cachep->align);
2406 * Determine if the slab management is 'on' or 'off' slab.
2407 * (bootstrapping cannot cope with offslab caches so don't do
2408 * it too early on. Always use on-slab management when
2409 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2411 if ((size >= (PAGE_SIZE >> 3)) && !slab_early_init &&
2412 !(flags & SLAB_NOLEAKTRACE))
2414 * Size is large, assume best to place the slab management obj
2415 * off-slab (should allow better packing of objs).
2417 flags |= CFLGS_OFF_SLAB;
2419 size = ALIGN(size, cachep->align);
2421 left_over = calculate_slab_order(cachep, size, cachep->align, flags);
2426 slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2427 + sizeof(struct slab), cachep->align);
2430 * If the slab has been placed off-slab, and we have enough space then
2431 * move it on-slab. This is at the expense of any extra colouring.
2433 if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2434 flags &= ~CFLGS_OFF_SLAB;
2435 left_over -= slab_size;
2438 if (flags & CFLGS_OFF_SLAB) {
2439 /* really off slab. No need for manual alignment */
2441 cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2443 #ifdef CONFIG_PAGE_POISONING
2444 /* If we're going to use the generic kernel_map_pages()
2445 * poisoning, then it's going to smash the contents of
2446 * the redzone and userword anyhow, so switch them off.
2448 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2449 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2453 cachep->colour_off = cache_line_size();
2454 /* Offset must be a multiple of the alignment. */
2455 if (cachep->colour_off < cachep->align)
2456 cachep->colour_off = cachep->align;
2457 cachep->colour = left_over / cachep->colour_off;
2458 cachep->slab_size = slab_size;
2459 cachep->flags = flags;
2460 cachep->allocflags = 0;
2461 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2462 cachep->allocflags |= GFP_DMA;
2463 cachep->size = size;
2464 cachep->reciprocal_buffer_size = reciprocal_value(size);
2466 if (flags & CFLGS_OFF_SLAB) {
2467 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2469 * This is a possibility for one of the malloc_sizes caches.
2470 * But since we go off slab only for object size greater than
2471 * PAGE_SIZE/8, and malloc_sizes gets created in ascending order,
2472 * this should not happen at all.
2473 * But leave a BUG_ON for some lucky dude.
2475 BUG_ON(ZERO_OR_NULL_PTR(cachep->slabp_cache));
2478 err = setup_cpu_cache(cachep, gfp);
2480 __kmem_cache_shutdown(cachep);
2484 if (flags & SLAB_DEBUG_OBJECTS) {
2486 * Would deadlock through slab_destroy()->call_rcu()->
2487 * debug_object_activate()->kmem_cache_alloc().
2489 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2491 slab_set_debugobj_lock_classes(cachep);
2498 static void check_irq_off(void)
2500 BUG_ON(!irqs_disabled());
2503 static void check_irq_on(void)
2505 BUG_ON(irqs_disabled());
2508 static void check_spinlock_acquired(struct kmem_cache *cachep)
2512 assert_spin_locked(&cachep->nodelists[numa_mem_id()]->list_lock);
2516 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2520 assert_spin_locked(&cachep->nodelists[node]->list_lock);
2525 #define check_irq_off() do { } while(0)
2526 #define check_irq_on() do { } while(0)
2527 #define check_spinlock_acquired(x) do { } while(0)
2528 #define check_spinlock_acquired_node(x, y) do { } while(0)
2531 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
2532 struct array_cache *ac,
2533 int force, int node);
2535 static void do_drain(void *arg)
2537 struct kmem_cache *cachep = arg;
2538 struct array_cache *ac;
2539 int node = numa_mem_id();
2542 ac = cpu_cache_get(cachep);
2543 spin_lock(&cachep->nodelists[node]->list_lock);
2544 free_block(cachep, ac->entry, ac->avail, node);
2545 spin_unlock(&cachep->nodelists[node]->list_lock);
2549 static void drain_cpu_caches(struct kmem_cache *cachep)
2551 struct kmem_list3 *l3;
2554 on_each_cpu(do_drain, cachep, 1);
2556 for_each_online_node(node) {
2557 l3 = cachep->nodelists[node];
2558 if (l3 && l3->alien)
2559 drain_alien_cache(cachep, l3->alien);
2562 for_each_online_node(node) {
2563 l3 = cachep->nodelists[node];
2565 drain_array(cachep, l3, l3->shared, 1, node);
2570 * Remove slabs from the list of free slabs.
2571 * Specify the number of slabs to drain in tofree.
2573 * Returns the actual number of slabs released.
2575 static int drain_freelist(struct kmem_cache *cache,
2576 struct kmem_list3 *l3, int tofree)
2578 struct list_head *p;
2583 while (nr_freed < tofree && !list_empty(&l3->slabs_free)) {
2585 spin_lock_irq(&l3->list_lock);
2586 p = l3->slabs_free.prev;
2587 if (p == &l3->slabs_free) {
2588 spin_unlock_irq(&l3->list_lock);
2592 slabp = list_entry(p, struct slab, list);
2594 BUG_ON(slabp->inuse);
2596 list_del(&slabp->list);
2598 * Safe to drop the lock. The slab is no longer linked
2601 l3->free_objects -= cache->num;
2602 spin_unlock_irq(&l3->list_lock);
2603 slab_destroy(cache, slabp);
2610 /* Called with slab_mutex held to protect against cpu hotplug */
2611 static int __cache_shrink(struct kmem_cache *cachep)
2614 struct kmem_list3 *l3;
2616 drain_cpu_caches(cachep);
2619 for_each_online_node(i) {
2620 l3 = cachep->nodelists[i];
2624 drain_freelist(cachep, l3, l3->free_objects);
2626 ret += !list_empty(&l3->slabs_full) ||
2627 !list_empty(&l3->slabs_partial);
2629 return (ret ? 1 : 0);
2633 * kmem_cache_shrink - Shrink a cache.
2634 * @cachep: The cache to shrink.
2636 * Releases as many slabs as possible for a cache.
2637 * To help debugging, a zero exit status indicates all slabs were released.
2639 int kmem_cache_shrink(struct kmem_cache *cachep)
2642 BUG_ON(!cachep || in_interrupt());
2645 mutex_lock(&slab_mutex);
2646 ret = __cache_shrink(cachep);
2647 mutex_unlock(&slab_mutex);
2651 EXPORT_SYMBOL(kmem_cache_shrink);
2653 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2656 struct kmem_list3 *l3;
2657 int rc = __cache_shrink(cachep);
2662 for_each_online_cpu(i)
2663 kfree(cachep->array[i]);
2665 /* NUMA: free the list3 structures */
2666 for_each_online_node(i) {
2667 l3 = cachep->nodelists[i];
2670 free_alien_cache(l3->alien);
2678 * Get the memory for a slab management obj.
2679 * For a slab cache when the slab descriptor is off-slab, slab descriptors
2680 * always come from malloc_sizes caches. The slab descriptor cannot
2681 * come from the same cache which is getting created because,
2682 * when we are searching for an appropriate cache for these
2683 * descriptors in kmem_cache_create, we search through the malloc_sizes array.
2684 * If we are creating a malloc_sizes cache here it would not be visible to
2685 * kmem_find_general_cachep till the initialization is complete.
2686 * Hence we cannot have slabp_cache same as the original cache.
2688 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2689 int colour_off, gfp_t local_flags,
2694 if (OFF_SLAB(cachep)) {
2695 /* Slab management obj is off-slab. */
2696 slabp = kmem_cache_alloc_node(cachep->slabp_cache,
2697 local_flags, nodeid);
2699 * If the first object in the slab is leaked (it's allocated
2700 * but no one has a reference to it), we want to make sure
2701 * kmemleak does not treat the ->s_mem pointer as a reference
2702 * to the object. Otherwise we will not report the leak.
2704 kmemleak_scan_area(&slabp->list, sizeof(struct list_head),
2709 slabp = objp + colour_off;
2710 colour_off += cachep->slab_size;
2713 slabp->colouroff = colour_off;
2714 slabp->s_mem = objp + colour_off;
2715 slabp->nodeid = nodeid;
2720 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2722 return (kmem_bufctl_t *) (slabp + 1);
2725 static void cache_init_objs(struct kmem_cache *cachep,
2730 for (i = 0; i < cachep->num; i++) {
2731 void *objp = index_to_obj(cachep, slabp, i);
2733 /* need to poison the objs? */
2734 if (cachep->flags & SLAB_POISON)
2735 poison_obj(cachep, objp, POISON_FREE);
2736 if (cachep->flags & SLAB_STORE_USER)
2737 *dbg_userword(cachep, objp) = NULL;
2739 if (cachep->flags & SLAB_RED_ZONE) {
2740 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2741 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2744 * Constructors are not allowed to allocate memory from the same
2745 * cache which they are a constructor for. Otherwise, deadlock.
2746 * They must also be threaded.
2748 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2749 cachep->ctor(objp + obj_offset(cachep));
2751 if (cachep->flags & SLAB_RED_ZONE) {
2752 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2753 slab_error(cachep, "constructor overwrote the"
2754 " end of an object");
2755 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2756 slab_error(cachep, "constructor overwrote the"
2757 " start of an object");
2759 if ((cachep->size % PAGE_SIZE) == 0 &&
2760 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2761 kernel_map_pages(virt_to_page(objp),
2762 cachep->size / PAGE_SIZE, 0);
2767 slab_bufctl(slabp)[i] = i + 1;
2769 slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2772 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2774 if (CONFIG_ZONE_DMA_FLAG) {
2775 if (flags & GFP_DMA)
2776 BUG_ON(!(cachep->allocflags & GFP_DMA));
2778 BUG_ON(cachep->allocflags & GFP_DMA);
2782 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2785 void *objp = index_to_obj(cachep, slabp, slabp->free);
2789 next = slab_bufctl(slabp)[slabp->free];
2791 slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2792 WARN_ON(slabp->nodeid != nodeid);
2799 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2800 void *objp, int nodeid)
2802 unsigned int objnr = obj_to_index(cachep, slabp, objp);
2805 /* Verify that the slab belongs to the intended node */
2806 WARN_ON(slabp->nodeid != nodeid);
2808 if (slab_bufctl(slabp)[objnr] + 1 <= SLAB_LIMIT + 1) {
2809 printk(KERN_ERR "slab: double free detected in cache "
2810 "'%s', objp %p\n", cachep->name, objp);
2814 slab_bufctl(slabp)[objnr] = slabp->free;
2815 slabp->free = objnr;
2820 * Map pages beginning at addr to the given cache and slab. This is required
2821 * for the slab allocator to be able to lookup the cache and slab of a
2822 * virtual address for kfree, ksize, and slab debugging.
2824 static void slab_map_pages(struct kmem_cache *cache, struct slab *slab,
2830 page = virt_to_page(addr);
2833 if (likely(!PageCompound(page)))
2834 nr_pages <<= cache->gfporder;
2837 page->slab_cache = cache;
2838 page->slab_page = slab;
2840 } while (--nr_pages);
2844 * Grow (by 1) the number of slabs within a cache. This is called by
2845 * kmem_cache_alloc() when there are no active objs left in a cache.
2847 static int cache_grow(struct kmem_cache *cachep,
2848 gfp_t flags, int nodeid, void *objp)
2853 struct kmem_list3 *l3;
2856 * Be lazy and only check for valid flags here, keeping it out of the
2857 * critical path in kmem_cache_alloc().
2859 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2860 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2862 /* Take the l3 list lock to change the colour_next on this node */
2864 l3 = cachep->nodelists[nodeid];
2865 spin_lock(&l3->list_lock);
2867 /* Get colour for the slab, and cal the next value. */
2868 offset = l3->colour_next;
2870 if (l3->colour_next >= cachep->colour)
2871 l3->colour_next = 0;
2872 spin_unlock(&l3->list_lock);
2874 offset *= cachep->colour_off;
2876 if (local_flags & __GFP_WAIT)
2880 * The test for missing atomic flag is performed here, rather than
2881 * the more obvious place, simply to reduce the critical path length
2882 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2883 * will eventually be caught here (where it matters).
2885 kmem_flagcheck(cachep, flags);
2888 * Get mem for the objs. Attempt to allocate a physical page from
2892 objp = kmem_getpages(cachep, local_flags, nodeid);
2896 /* Get slab management. */
2897 slabp = alloc_slabmgmt(cachep, objp, offset,
2898 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2902 slab_map_pages(cachep, slabp, objp);
2904 cache_init_objs(cachep, slabp);
2906 if (local_flags & __GFP_WAIT)
2907 local_irq_disable();
2909 spin_lock(&l3->list_lock);
2911 /* Make slab active. */
2912 list_add_tail(&slabp->list, &(l3->slabs_free));
2913 STATS_INC_GROWN(cachep);
2914 l3->free_objects += cachep->num;
2915 spin_unlock(&l3->list_lock);
2918 kmem_freepages(cachep, objp);
2920 if (local_flags & __GFP_WAIT)
2921 local_irq_disable();
2928 * Perform extra freeing checks:
2929 * - detect bad pointers.
2930 * - POISON/RED_ZONE checking
2932 static void kfree_debugcheck(const void *objp)
2934 if (!virt_addr_valid(objp)) {
2935 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2936 (unsigned long)objp);
2941 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2943 unsigned long long redzone1, redzone2;
2945 redzone1 = *dbg_redzone1(cache, obj);
2946 redzone2 = *dbg_redzone2(cache, obj);
2951 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2954 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2955 slab_error(cache, "double free detected");
2957 slab_error(cache, "memory outside object was overwritten");
2959 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2960 obj, redzone1, redzone2);
2963 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2964 unsigned long caller)
2970 BUG_ON(virt_to_cache(objp) != cachep);
2972 objp -= obj_offset(cachep);
2973 kfree_debugcheck(objp);
2974 page = virt_to_head_page(objp);
2976 slabp = page->slab_page;
2978 if (cachep->flags & SLAB_RED_ZONE) {
2979 verify_redzone_free(cachep, objp);
2980 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2981 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2983 if (cachep->flags & SLAB_STORE_USER)
2984 *dbg_userword(cachep, objp) = (void *)caller;
2986 objnr = obj_to_index(cachep, slabp, objp);
2988 BUG_ON(objnr >= cachep->num);
2989 BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2991 #ifdef CONFIG_DEBUG_SLAB_LEAK
2992 slab_bufctl(slabp)[objnr] = BUFCTL_FREE;
2994 if (cachep->flags & SLAB_POISON) {
2995 #ifdef CONFIG_DEBUG_PAGEALLOC
2996 if ((cachep->size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2997 store_stackinfo(cachep, objp, caller);
2998 kernel_map_pages(virt_to_page(objp),
2999 cachep->size / PAGE_SIZE, 0);
3001 poison_obj(cachep, objp, POISON_FREE);
3004 poison_obj(cachep, objp, POISON_FREE);
3010 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
3015 /* Check slab's freelist to see if this obj is there. */
3016 for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
3018 if (entries > cachep->num || i >= cachep->num)
3021 if (entries != cachep->num - slabp->inuse) {
3023 printk(KERN_ERR "slab: Internal list corruption detected in "
3024 "cache '%s'(%d), slabp %p(%d). Tainted(%s). Hexdump:\n",
3025 cachep->name, cachep->num, slabp, slabp->inuse,
3027 print_hex_dump(KERN_ERR, "", DUMP_PREFIX_OFFSET, 16, 1, slabp,
3028 sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t),
3034 #define kfree_debugcheck(x) do { } while(0)
3035 #define cache_free_debugcheck(x,objp,z) (objp)
3036 #define check_slabp(x,y) do { } while(0)
3039 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
3043 struct kmem_list3 *l3;
3044 struct array_cache *ac;
3048 node = numa_mem_id();
3049 if (unlikely(force_refill))
3052 ac = cpu_cache_get(cachep);
3053 batchcount = ac->batchcount;
3054 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
3056 * If there was little recent activity on this cache, then
3057 * perform only a partial refill. Otherwise we could generate
3060 batchcount = BATCHREFILL_LIMIT;
3062 l3 = cachep->nodelists[node];
3064 BUG_ON(ac->avail > 0 || !l3);
3065 spin_lock(&l3->list_lock);
3067 /* See if we can refill from the shared array */
3068 if (l3->shared && transfer_objects(ac, l3->shared, batchcount)) {
3069 l3->shared->touched = 1;
3073 while (batchcount > 0) {
3074 struct list_head *entry;
3076 /* Get slab alloc is to come from. */
3077 entry = l3->slabs_partial.next;
3078 if (entry == &l3->slabs_partial) {
3079 l3->free_touched = 1;
3080 entry = l3->slabs_free.next;
3081 if (entry == &l3->slabs_free)
3085 slabp = list_entry(entry, struct slab, list);
3086 check_slabp(cachep, slabp);
3087 check_spinlock_acquired(cachep);
3090 * The slab was either on partial or free list so
3091 * there must be at least one object available for
3094 BUG_ON(slabp->inuse >= cachep->num);
3096 while (slabp->inuse < cachep->num && batchcount--) {
3097 STATS_INC_ALLOCED(cachep);
3098 STATS_INC_ACTIVE(cachep);
3099 STATS_SET_HIGH(cachep);
3101 ac_put_obj(cachep, ac, slab_get_obj(cachep, slabp,
3104 check_slabp(cachep, slabp);
3106 /* move slabp to correct slabp list: */
3107 list_del(&slabp->list);
3108 if (slabp->free == BUFCTL_END)
3109 list_add(&slabp->list, &l3->slabs_full);
3111 list_add(&slabp->list, &l3->slabs_partial);
3115 l3->free_objects -= ac->avail;
3117 spin_unlock(&l3->list_lock);
3119 if (unlikely(!ac->avail)) {
3122 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3124 /* cache_grow can reenable interrupts, then ac could change. */
3125 ac = cpu_cache_get(cachep);
3126 node = numa_mem_id();
3128 /* no objects in sight? abort */
3129 if (!x && (ac->avail == 0 || force_refill))
3132 if (!ac->avail) /* objects refilled by interrupt? */
3137 return ac_get_obj(cachep, ac, flags, force_refill);
3140 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3143 might_sleep_if(flags & __GFP_WAIT);
3145 kmem_flagcheck(cachep, flags);
3150 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3151 gfp_t flags, void *objp, unsigned long caller)
3155 if (cachep->flags & SLAB_POISON) {
3156 #ifdef CONFIG_DEBUG_PAGEALLOC
3157 if ((cachep->size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3158 kernel_map_pages(virt_to_page(objp),
3159 cachep->size / PAGE_SIZE, 1);
3161 check_poison_obj(cachep, objp);
3163 check_poison_obj(cachep, objp);
3165 poison_obj(cachep, objp, POISON_INUSE);
3167 if (cachep->flags & SLAB_STORE_USER)
3168 *dbg_userword(cachep, objp) = (void *)caller;
3170 if (cachep->flags & SLAB_RED_ZONE) {
3171 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3172 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3173 slab_error(cachep, "double free, or memory outside"
3174 " object was overwritten");
3176 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3177 objp, *dbg_redzone1(cachep, objp),
3178 *dbg_redzone2(cachep, objp));
3180 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3181 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3183 #ifdef CONFIG_DEBUG_SLAB_LEAK
3188 slabp = virt_to_head_page(objp)->slab_page;
3189 objnr = (unsigned)(objp - slabp->s_mem) / cachep->size;
3190 slab_bufctl(slabp)[objnr] = BUFCTL_ACTIVE;
3193 objp += obj_offset(cachep);
3194 if (cachep->ctor && cachep->flags & SLAB_POISON)
3196 if (ARCH_SLAB_MINALIGN &&
3197 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3198 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3199 objp, (int)ARCH_SLAB_MINALIGN);
3204 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3207 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3209 if (cachep == kmem_cache)
3212 return should_failslab(cachep->object_size, flags, cachep->flags);
3215 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3218 struct array_cache *ac;
3219 bool force_refill = false;
3223 ac = cpu_cache_get(cachep);
3224 if (likely(ac->avail)) {
3226 objp = ac_get_obj(cachep, ac, flags, false);
3229 * Allow for the possibility all avail objects are not allowed
3230 * by the current flags
3233 STATS_INC_ALLOCHIT(cachep);
3236 force_refill = true;
3239 STATS_INC_ALLOCMISS(cachep);
3240 objp = cache_alloc_refill(cachep, flags, force_refill);
3242 * the 'ac' may be updated by cache_alloc_refill(),
3243 * and kmemleak_erase() requires its correct value.
3245 ac = cpu_cache_get(cachep);
3249 * To avoid a false negative, if an object that is in one of the
3250 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3251 * treat the array pointers as a reference to the object.
3254 kmemleak_erase(&ac->entry[ac->avail]);
3260 * Try allocating on another node if PF_SPREAD_SLAB|PF_MEMPOLICY.
3262 * If we are in_interrupt, then process context, including cpusets and
3263 * mempolicy, may not apply and should not be used for allocation policy.
3265 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3267 int nid_alloc, nid_here;
3269 if (in_interrupt() || (flags & __GFP_THISNODE))
3271 nid_alloc = nid_here = numa_mem_id();
3272 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3273 nid_alloc = cpuset_slab_spread_node();
3274 else if (current->mempolicy)
3275 nid_alloc = slab_node();
3276 if (nid_alloc != nid_here)
3277 return ____cache_alloc_node(cachep, flags, nid_alloc);
3282 * Fallback function if there was no memory available and no objects on a
3283 * certain node and fall back is permitted. First we scan all the
3284 * available nodelists for available objects. If that fails then we
3285 * perform an allocation without specifying a node. This allows the page
3286 * allocator to do its reclaim / fallback magic. We then insert the
3287 * slab into the proper nodelist and then allocate from it.
3289 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3291 struct zonelist *zonelist;
3295 enum zone_type high_zoneidx = gfp_zone(flags);
3298 unsigned int cpuset_mems_cookie;
3300 if (flags & __GFP_THISNODE)
3303 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3306 cpuset_mems_cookie = get_mems_allowed();
3307 zonelist = node_zonelist(slab_node(), flags);
3311 * Look through allowed nodes for objects available
3312 * from existing per node queues.
3314 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3315 nid = zone_to_nid(zone);
3317 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3318 cache->nodelists[nid] &&
3319 cache->nodelists[nid]->free_objects) {
3320 obj = ____cache_alloc_node(cache,
3321 flags | GFP_THISNODE, nid);
3329 * This allocation will be performed within the constraints
3330 * of the current cpuset / memory policy requirements.
3331 * We may trigger various forms of reclaim on the allowed
3332 * set and go into memory reserves if necessary.
3334 if (local_flags & __GFP_WAIT)
3336 kmem_flagcheck(cache, flags);
3337 obj = kmem_getpages(cache, local_flags, numa_mem_id());
3338 if (local_flags & __GFP_WAIT)
3339 local_irq_disable();
3342 * Insert into the appropriate per node queues
3344 nid = page_to_nid(virt_to_page(obj));
3345 if (cache_grow(cache, flags, nid, obj)) {
3346 obj = ____cache_alloc_node(cache,
3347 flags | GFP_THISNODE, nid);
3350 * Another processor may allocate the
3351 * objects in the slab since we are
3352 * not holding any locks.
3356 /* cache_grow already freed obj */
3362 if (unlikely(!put_mems_allowed(cpuset_mems_cookie) && !obj))
3368 * A interface to enable slab creation on nodeid
3370 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3373 struct list_head *entry;
3375 struct kmem_list3 *l3;
3379 l3 = cachep->nodelists[nodeid];
3384 spin_lock(&l3->list_lock);
3385 entry = l3->slabs_partial.next;
3386 if (entry == &l3->slabs_partial) {
3387 l3->free_touched = 1;
3388 entry = l3->slabs_free.next;
3389 if (entry == &l3->slabs_free)
3393 slabp = list_entry(entry, struct slab, list);
3394 check_spinlock_acquired_node(cachep, nodeid);
3395 check_slabp(cachep, slabp);
3397 STATS_INC_NODEALLOCS(cachep);
3398 STATS_INC_ACTIVE(cachep);
3399 STATS_SET_HIGH(cachep);
3401 BUG_ON(slabp->inuse == cachep->num);
3403 obj = slab_get_obj(cachep, slabp, nodeid);
3404 check_slabp(cachep, slabp);
3406 /* move slabp to correct slabp list: */
3407 list_del(&slabp->list);
3409 if (slabp->free == BUFCTL_END)
3410 list_add(&slabp->list, &l3->slabs_full);
3412 list_add(&slabp->list, &l3->slabs_partial);
3414 spin_unlock(&l3->list_lock);
3418 spin_unlock(&l3->list_lock);
3419 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3423 return fallback_alloc(cachep, flags);
3430 * kmem_cache_alloc_node - Allocate an object on the specified node
3431 * @cachep: The cache to allocate from.
3432 * @flags: See kmalloc().
3433 * @nodeid: node number of the target node.
3434 * @caller: return address of caller, used for debug information
3436 * Identical to kmem_cache_alloc but it will allocate memory on the given
3437 * node, which can improve the performance for cpu bound structures.
3439 * Fallback to other node is possible if __GFP_THISNODE is not set.
3441 static __always_inline void *
3442 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3443 unsigned long caller)
3445 unsigned long save_flags;
3447 int slab_node = numa_mem_id();
3449 flags &= gfp_allowed_mask;
3451 lockdep_trace_alloc(flags);
3453 if (slab_should_failslab(cachep, flags))
3456 cache_alloc_debugcheck_before(cachep, flags);
3457 local_irq_save(save_flags);
3459 if (nodeid == NUMA_NO_NODE)
3462 if (unlikely(!cachep->nodelists[nodeid])) {
3463 /* Node not bootstrapped yet */
3464 ptr = fallback_alloc(cachep, flags);
3468 if (nodeid == slab_node) {
3470 * Use the locally cached objects if possible.
3471 * However ____cache_alloc does not allow fallback
3472 * to other nodes. It may fail while we still have
3473 * objects on other nodes available.
3475 ptr = ____cache_alloc(cachep, flags);
3479 /* ___cache_alloc_node can fall back to other nodes */
3480 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3482 local_irq_restore(save_flags);
3483 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3484 kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3488 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3490 if (unlikely((flags & __GFP_ZERO) && ptr))
3491 memset(ptr, 0, cachep->object_size);
3496 static __always_inline void *
3497 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3501 if (unlikely(current->flags & (PF_SPREAD_SLAB | PF_MEMPOLICY))) {
3502 objp = alternate_node_alloc(cache, flags);
3506 objp = ____cache_alloc(cache, flags);
3509 * We may just have run out of memory on the local node.
3510 * ____cache_alloc_node() knows how to locate memory on other nodes
3513 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3520 static __always_inline void *
3521 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3523 return ____cache_alloc(cachep, flags);
3526 #endif /* CONFIG_NUMA */
3528 static __always_inline void *
3529 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3531 unsigned long save_flags;
3534 flags &= gfp_allowed_mask;
3536 lockdep_trace_alloc(flags);
3538 if (slab_should_failslab(cachep, flags))
3541 cache_alloc_debugcheck_before(cachep, flags);
3542 local_irq_save(save_flags);
3543 objp = __do_cache_alloc(cachep, flags);
3544 local_irq_restore(save_flags);
3545 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3546 kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3551 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3553 if (unlikely((flags & __GFP_ZERO) && objp))
3554 memset(objp, 0, cachep->object_size);
3560 * Caller needs to acquire correct kmem_list's list_lock
3562 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3566 struct kmem_list3 *l3;
3568 for (i = 0; i < nr_objects; i++) {
3572 clear_obj_pfmemalloc(&objpp[i]);
3575 slabp = virt_to_slab(objp);
3576 l3 = cachep->nodelists[node];
3577 list_del(&slabp->list);
3578 check_spinlock_acquired_node(cachep, node);
3579 check_slabp(cachep, slabp);
3580 slab_put_obj(cachep, slabp, objp, node);
3581 STATS_DEC_ACTIVE(cachep);
3583 check_slabp(cachep, slabp);
3585 /* fixup slab chains */
3586 if (slabp->inuse == 0) {
3587 if (l3->free_objects > l3->free_limit) {
3588 l3->free_objects -= cachep->num;
3589 /* No need to drop any previously held
3590 * lock here, even if we have a off-slab slab
3591 * descriptor it is guaranteed to come from
3592 * a different cache, refer to comments before
3595 slab_destroy(cachep, slabp);
3597 list_add(&slabp->list, &l3->slabs_free);
3600 /* Unconditionally move a slab to the end of the
3601 * partial list on free - maximum time for the
3602 * other objects to be freed, too.
3604 list_add_tail(&slabp->list, &l3->slabs_partial);
3609 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3612 struct kmem_list3 *l3;
3613 int node = numa_mem_id();
3615 batchcount = ac->batchcount;
3617 BUG_ON(!batchcount || batchcount > ac->avail);
3620 l3 = cachep->nodelists[node];
3621 spin_lock(&l3->list_lock);
3623 struct array_cache *shared_array = l3->shared;
3624 int max = shared_array->limit - shared_array->avail;
3626 if (batchcount > max)
3628 memcpy(&(shared_array->entry[shared_array->avail]),
3629 ac->entry, sizeof(void *) * batchcount);
3630 shared_array->avail += batchcount;
3635 free_block(cachep, ac->entry, batchcount, node);
3640 struct list_head *p;
3642 p = l3->slabs_free.next;
3643 while (p != &(l3->slabs_free)) {
3646 slabp = list_entry(p, struct slab, list);
3647 BUG_ON(slabp->inuse);
3652 STATS_SET_FREEABLE(cachep, i);
3655 spin_unlock(&l3->list_lock);
3656 ac->avail -= batchcount;
3657 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3661 * Release an obj back to its cache. If the obj has a constructed state, it must
3662 * be in this state _before_ it is released. Called with disabled ints.
3664 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3665 unsigned long caller)
3667 struct array_cache *ac = cpu_cache_get(cachep);
3670 kmemleak_free_recursive(objp, cachep->flags);
3671 objp = cache_free_debugcheck(cachep, objp, caller);
3673 kmemcheck_slab_free(cachep, objp, cachep->object_size);
3676 * Skip calling cache_free_alien() when the platform is not numa.
3677 * This will avoid cache misses that happen while accessing slabp (which
3678 * is per page memory reference) to get nodeid. Instead use a global
3679 * variable to skip the call, which is mostly likely to be present in
3682 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3685 if (likely(ac->avail < ac->limit)) {
3686 STATS_INC_FREEHIT(cachep);
3688 STATS_INC_FREEMISS(cachep);
3689 cache_flusharray(cachep, ac);
3692 ac_put_obj(cachep, ac, objp);
3696 * kmem_cache_alloc - Allocate an object
3697 * @cachep: The cache to allocate from.
3698 * @flags: See kmalloc().
3700 * Allocate an object from this cache. The flags are only relevant
3701 * if the cache has no available objects.
3703 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3705 void *ret = slab_alloc(cachep, flags, _RET_IP_);
3707 trace_kmem_cache_alloc(_RET_IP_, ret,
3708 cachep->object_size, cachep->size, flags);
3712 EXPORT_SYMBOL(kmem_cache_alloc);
3714 #ifdef CONFIG_TRACING
3716 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3720 ret = slab_alloc(cachep, flags, _RET_IP_);
3722 trace_kmalloc(_RET_IP_, ret,
3723 size, cachep->size, flags);
3726 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3730 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3732 void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3734 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3735 cachep->object_size, cachep->size,
3740 EXPORT_SYMBOL(kmem_cache_alloc_node);
3742 #ifdef CONFIG_TRACING
3743 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3750 ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3752 trace_kmalloc_node(_RET_IP_, ret,
3757 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3760 static __always_inline void *
3761 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3763 struct kmem_cache *cachep;
3765 cachep = kmem_find_general_cachep(size, flags);
3766 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3768 return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3771 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3772 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3774 return __do_kmalloc_node(size, flags, node, _RET_IP_);
3776 EXPORT_SYMBOL(__kmalloc_node);
3778 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3779 int node, unsigned long caller)
3781 return __do_kmalloc_node(size, flags, node, caller);
3783 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3785 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3787 return __do_kmalloc_node(size, flags, node, 0);
3789 EXPORT_SYMBOL(__kmalloc_node);
3790 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3791 #endif /* CONFIG_NUMA */
3794 * __do_kmalloc - allocate memory
3795 * @size: how many bytes of memory are required.
3796 * @flags: the type of memory to allocate (see kmalloc).
3797 * @caller: function caller for debug tracking of the caller
3799 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3800 unsigned long caller)
3802 struct kmem_cache *cachep;
3805 /* If you want to save a few bytes .text space: replace
3807 * Then kmalloc uses the uninlined functions instead of the inline
3810 cachep = __find_general_cachep(size, flags);
3811 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3813 ret = slab_alloc(cachep, flags, caller);
3815 trace_kmalloc(caller, ret,
3816 size, cachep->size, flags);
3822 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3823 void *__kmalloc(size_t size, gfp_t flags)
3825 return __do_kmalloc(size, flags, _RET_IP_);
3827 EXPORT_SYMBOL(__kmalloc);
3829 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3831 return __do_kmalloc(size, flags, caller);
3833 EXPORT_SYMBOL(__kmalloc_track_caller);
3836 void *__kmalloc(size_t size, gfp_t flags)
3838 return __do_kmalloc(size, flags, 0);
3840 EXPORT_SYMBOL(__kmalloc);
3844 * kmem_cache_free - Deallocate an object
3845 * @cachep: The cache the allocation was from.
3846 * @objp: The previously allocated object.
3848 * Free an object which was previously allocated from this
3851 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3853 unsigned long flags;
3855 local_irq_save(flags);
3856 debug_check_no_locks_freed(objp, cachep->object_size);
3857 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3858 debug_check_no_obj_freed(objp, cachep->object_size);
3859 __cache_free(cachep, objp, _RET_IP_);
3860 local_irq_restore(flags);
3862 trace_kmem_cache_free(_RET_IP_, objp);
3864 EXPORT_SYMBOL(kmem_cache_free);
3867 * kfree - free previously allocated memory
3868 * @objp: pointer returned by kmalloc.
3870 * If @objp is NULL, no operation is performed.
3872 * Don't free memory not originally allocated by kmalloc()
3873 * or you will run into trouble.
3875 void kfree(const void *objp)
3877 struct kmem_cache *c;
3878 unsigned long flags;
3880 trace_kfree(_RET_IP_, objp);
3882 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3884 local_irq_save(flags);
3885 kfree_debugcheck(objp);
3886 c = virt_to_cache(objp);
3887 debug_check_no_locks_freed(objp, c->object_size);
3889 debug_check_no_obj_freed(objp, c->object_size);
3890 __cache_free(c, (void *)objp, _RET_IP_);
3891 local_irq_restore(flags);
3893 EXPORT_SYMBOL(kfree);
3896 * This initializes kmem_list3 or resizes various caches for all nodes.
3898 static int alloc_kmemlist(struct kmem_cache *cachep, gfp_t gfp)
3901 struct kmem_list3 *l3;
3902 struct array_cache *new_shared;
3903 struct array_cache **new_alien = NULL;
3905 for_each_online_node(node) {
3907 if (use_alien_caches) {
3908 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3914 if (cachep->shared) {
3915 new_shared = alloc_arraycache(node,
3916 cachep->shared*cachep->batchcount,
3919 free_alien_cache(new_alien);
3924 l3 = cachep->nodelists[node];
3926 struct array_cache *shared = l3->shared;
3928 spin_lock_irq(&l3->list_lock);
3931 free_block(cachep, shared->entry,
3932 shared->avail, node);
3934 l3->shared = new_shared;
3936 l3->alien = new_alien;
3939 l3->free_limit = (1 + nr_cpus_node(node)) *
3940 cachep->batchcount + cachep->num;
3941 spin_unlock_irq(&l3->list_lock);
3943 free_alien_cache(new_alien);
3946 l3 = kmalloc_node(sizeof(struct kmem_list3), gfp, node);
3948 free_alien_cache(new_alien);
3953 kmem_list3_init(l3);
3954 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3955 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3956 l3->shared = new_shared;
3957 l3->alien = new_alien;
3958 l3->free_limit = (1 + nr_cpus_node(node)) *
3959 cachep->batchcount + cachep->num;
3960 cachep->nodelists[node] = l3;
3965 if (!cachep->list.next) {
3966 /* Cache is not active yet. Roll back what we did */
3969 if (cachep->nodelists[node]) {
3970 l3 = cachep->nodelists[node];
3973 free_alien_cache(l3->alien);
3975 cachep->nodelists[node] = NULL;
3983 struct ccupdate_struct {
3984 struct kmem_cache *cachep;
3985 struct array_cache *new[0];
3988 static void do_ccupdate_local(void *info)
3990 struct ccupdate_struct *new = info;
3991 struct array_cache *old;
3994 old = cpu_cache_get(new->cachep);
3996 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3997 new->new[smp_processor_id()] = old;
4000 /* Always called with the slab_mutex held */
4001 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
4002 int batchcount, int shared, gfp_t gfp)
4004 struct ccupdate_struct *new;
4007 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
4012 for_each_online_cpu(i) {
4013 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
4016 for (i--; i >= 0; i--)
4022 new->cachep = cachep;
4024 on_each_cpu(do_ccupdate_local, (void *)new, 1);
4027 cachep->batchcount = batchcount;
4028 cachep->limit = limit;
4029 cachep->shared = shared;
4031 for_each_online_cpu(i) {
4032 struct array_cache *ccold = new->new[i];
4035 spin_lock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4036 free_block(cachep, ccold->entry, ccold->avail, cpu_to_mem(i));
4037 spin_unlock_irq(&cachep->nodelists[cpu_to_mem(i)]->list_lock);
4041 return alloc_kmemlist(cachep, gfp);
4044 /* Called with slab_mutex held always */
4045 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
4051 * The head array serves three purposes:
4052 * - create a LIFO ordering, i.e. return objects that are cache-warm
4053 * - reduce the number of spinlock operations.
4054 * - reduce the number of linked list operations on the slab and
4055 * bufctl chains: array operations are cheaper.
4056 * The numbers are guessed, we should auto-tune as described by
4059 if (cachep->size > 131072)
4061 else if (cachep->size > PAGE_SIZE)
4063 else if (cachep->size > 1024)
4065 else if (cachep->size > 256)
4071 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4072 * allocation behaviour: Most allocs on one cpu, most free operations
4073 * on another cpu. For these cases, an efficient object passing between
4074 * cpus is necessary. This is provided by a shared array. The array
4075 * replaces Bonwick's magazine layer.
4076 * On uniprocessor, it's functionally equivalent (but less efficient)
4077 * to a larger limit. Thus disabled by default.
4080 if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
4085 * With debugging enabled, large batchcount lead to excessively long
4086 * periods with disabled local interrupts. Limit the batchcount
4091 err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared, gfp);
4093 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4094 cachep->name, -err);
4099 * Drain an array if it contains any elements taking the l3 lock only if
4100 * necessary. Note that the l3 listlock also protects the array_cache
4101 * if drain_array() is used on the shared array.
4103 static void drain_array(struct kmem_cache *cachep, struct kmem_list3 *l3,
4104 struct array_cache *ac, int force, int node)
4108 if (!ac || !ac->avail)
4110 if (ac->touched && !force) {
4113 spin_lock_irq(&l3->list_lock);
4115 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4116 if (tofree > ac->avail)
4117 tofree = (ac->avail + 1) / 2;
4118 free_block(cachep, ac->entry, tofree, node);
4119 ac->avail -= tofree;
4120 memmove(ac->entry, &(ac->entry[tofree]),
4121 sizeof(void *) * ac->avail);
4123 spin_unlock_irq(&l3->list_lock);
4128 * cache_reap - Reclaim memory from caches.
4129 * @w: work descriptor
4131 * Called from workqueue/eventd every few seconds.
4133 * - clear the per-cpu caches for this CPU.
4134 * - return freeable pages to the main free memory pool.
4136 * If we cannot acquire the cache chain mutex then just give up - we'll try
4137 * again on the next iteration.
4139 static void cache_reap(struct work_struct *w)
4141 struct kmem_cache *searchp;
4142 struct kmem_list3 *l3;
4143 int node = numa_mem_id();
4144 struct delayed_work *work = to_delayed_work(w);
4146 if (!mutex_trylock(&slab_mutex))
4147 /* Give up. Setup the next iteration. */
4150 list_for_each_entry(searchp, &slab_caches, list) {
4154 * We only take the l3 lock if absolutely necessary and we
4155 * have established with reasonable certainty that
4156 * we can do some work if the lock was obtained.
4158 l3 = searchp->nodelists[node];
4160 reap_alien(searchp, l3);
4162 drain_array(searchp, l3, cpu_cache_get(searchp), 0, node);
4165 * These are racy checks but it does not matter
4166 * if we skip one check or scan twice.
4168 if (time_after(l3->next_reap, jiffies))
4171 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
4173 drain_array(searchp, l3, l3->shared, 0, node);
4175 if (l3->free_touched)
4176 l3->free_touched = 0;
4180 freed = drain_freelist(searchp, l3, (l3->free_limit +
4181 5 * searchp->num - 1) / (5 * searchp->num));
4182 STATS_ADD_REAPED(searchp, freed);
4188 mutex_unlock(&slab_mutex);
4191 /* Set up the next iteration */
4192 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_CPUC));
4195 #ifdef CONFIG_SLABINFO
4196 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4199 unsigned long active_objs;
4200 unsigned long num_objs;
4201 unsigned long active_slabs = 0;
4202 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4206 struct kmem_list3 *l3;
4210 for_each_online_node(node) {
4211 l3 = cachep->nodelists[node];
4216 spin_lock_irq(&l3->list_lock);
4218 list_for_each_entry(slabp, &l3->slabs_full, list) {
4219 if (slabp->inuse != cachep->num && !error)
4220 error = "slabs_full accounting error";
4221 active_objs += cachep->num;
4224 list_for_each_entry(slabp, &l3->slabs_partial, list) {
4225 if (slabp->inuse == cachep->num && !error)
4226 error = "slabs_partial inuse accounting error";
4227 if (!slabp->inuse && !error)
4228 error = "slabs_partial/inuse accounting error";
4229 active_objs += slabp->inuse;
4232 list_for_each_entry(slabp, &l3->slabs_free, list) {
4233 if (slabp->inuse && !error)
4234 error = "slabs_free/inuse accounting error";
4237 free_objects += l3->free_objects;
4239 shared_avail += l3->shared->avail;
4241 spin_unlock_irq(&l3->list_lock);
4243 num_slabs += active_slabs;
4244 num_objs = num_slabs * cachep->num;
4245 if (num_objs - active_objs != free_objects && !error)
4246 error = "free_objects accounting error";
4248 name = cachep->name;
4250 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4252 sinfo->active_objs = active_objs;
4253 sinfo->num_objs = num_objs;
4254 sinfo->active_slabs = active_slabs;
4255 sinfo->num_slabs = num_slabs;
4256 sinfo->shared_avail = shared_avail;
4257 sinfo->limit = cachep->limit;
4258 sinfo->batchcount = cachep->batchcount;
4259 sinfo->shared = cachep->shared;
4260 sinfo->objects_per_slab = cachep->num;
4261 sinfo->cache_order = cachep->gfporder;
4264 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4268 unsigned long high = cachep->high_mark;
4269 unsigned long allocs = cachep->num_allocations;
4270 unsigned long grown = cachep->grown;
4271 unsigned long reaped = cachep->reaped;
4272 unsigned long errors = cachep->errors;
4273 unsigned long max_freeable = cachep->max_freeable;
4274 unsigned long node_allocs = cachep->node_allocs;
4275 unsigned long node_frees = cachep->node_frees;
4276 unsigned long overflows = cachep->node_overflow;
4278 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4279 "%4lu %4lu %4lu %4lu %4lu",
4280 allocs, high, grown,
4281 reaped, errors, max_freeable, node_allocs,
4282 node_frees, overflows);
4286 unsigned long allochit = atomic_read(&cachep->allochit);
4287 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4288 unsigned long freehit = atomic_read(&cachep->freehit);
4289 unsigned long freemiss = atomic_read(&cachep->freemiss);
4291 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4292 allochit, allocmiss, freehit, freemiss);
4297 #define MAX_SLABINFO_WRITE 128
4299 * slabinfo_write - Tuning for the slab allocator
4301 * @buffer: user buffer
4302 * @count: data length
4305 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4306 size_t count, loff_t *ppos)
4308 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4309 int limit, batchcount, shared, res;
4310 struct kmem_cache *cachep;
4312 if (count > MAX_SLABINFO_WRITE)
4314 if (copy_from_user(&kbuf, buffer, count))
4316 kbuf[MAX_SLABINFO_WRITE] = '\0';
4318 tmp = strchr(kbuf, ' ');
4323 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4326 /* Find the cache in the chain of caches. */
4327 mutex_lock(&slab_mutex);
4329 list_for_each_entry(cachep, &slab_caches, list) {
4330 if (!strcmp(cachep->name, kbuf)) {
4331 if (limit < 1 || batchcount < 1 ||
4332 batchcount > limit || shared < 0) {
4335 res = do_tune_cpucache(cachep, limit,
4342 mutex_unlock(&slab_mutex);
4348 #ifdef CONFIG_DEBUG_SLAB_LEAK
4350 static void *leaks_start(struct seq_file *m, loff_t *pos)
4352 mutex_lock(&slab_mutex);
4353 return seq_list_start(&slab_caches, *pos);
4356 static inline int add_caller(unsigned long *n, unsigned long v)
4366 unsigned long *q = p + 2 * i;
4380 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4386 static void handle_slab(unsigned long *n, struct kmem_cache *c, struct slab *s)
4392 for (i = 0, p = s->s_mem; i < c->num; i++, p += c->size) {
4393 if (slab_bufctl(s)[i] != BUFCTL_ACTIVE)
4395 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4400 static void show_symbol(struct seq_file *m, unsigned long address)
4402 #ifdef CONFIG_KALLSYMS
4403 unsigned long offset, size;
4404 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4406 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4407 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4409 seq_printf(m, " [%s]", modname);
4413 seq_printf(m, "%p", (void *)address);
4416 static int leaks_show(struct seq_file *m, void *p)
4418 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4420 struct kmem_list3 *l3;
4422 unsigned long *n = m->private;
4426 if (!(cachep->flags & SLAB_STORE_USER))
4428 if (!(cachep->flags & SLAB_RED_ZONE))
4431 /* OK, we can do it */
4435 for_each_online_node(node) {
4436 l3 = cachep->nodelists[node];
4441 spin_lock_irq(&l3->list_lock);
4443 list_for_each_entry(slabp, &l3->slabs_full, list)
4444 handle_slab(n, cachep, slabp);
4445 list_for_each_entry(slabp, &l3->slabs_partial, list)
4446 handle_slab(n, cachep, slabp);
4447 spin_unlock_irq(&l3->list_lock);
4449 name = cachep->name;
4451 /* Increase the buffer size */
4452 mutex_unlock(&slab_mutex);
4453 m->private = kzalloc(n[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4455 /* Too bad, we are really out */
4457 mutex_lock(&slab_mutex);
4460 *(unsigned long *)m->private = n[0] * 2;
4462 mutex_lock(&slab_mutex);
4463 /* Now make sure this entry will be retried */
4467 for (i = 0; i < n[1]; i++) {
4468 seq_printf(m, "%s: %lu ", name, n[2*i+3]);
4469 show_symbol(m, n[2*i+2]);
4476 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4478 return seq_list_next(p, &slab_caches, pos);
4481 static void s_stop(struct seq_file *m, void *p)
4483 mutex_unlock(&slab_mutex);
4486 static const struct seq_operations slabstats_op = {
4487 .start = leaks_start,
4493 static int slabstats_open(struct inode *inode, struct file *file)
4495 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4498 ret = seq_open(file, &slabstats_op);
4500 struct seq_file *m = file->private_data;
4501 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4510 static const struct file_operations proc_slabstats_operations = {
4511 .open = slabstats_open,
4513 .llseek = seq_lseek,
4514 .release = seq_release_private,
4518 static int __init slab_proc_init(void)
4520 #ifdef CONFIG_DEBUG_SLAB_LEAK
4521 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4525 module_init(slab_proc_init);
4529 * ksize - get the actual amount of memory allocated for a given object
4530 * @objp: Pointer to the object
4532 * kmalloc may internally round up allocations and return more memory
4533 * than requested. ksize() can be used to determine the actual amount of
4534 * memory allocated. The caller may use this additional memory, even though
4535 * a smaller amount of memory was initially specified with the kmalloc call.
4536 * The caller must guarantee that objp points to a valid object previously
4537 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4538 * must not be freed during the duration of the call.
4540 size_t ksize(const void *objp)
4543 if (unlikely(objp == ZERO_SIZE_PTR))
4546 return virt_to_cache(objp)->object_size;
4548 EXPORT_SYMBOL(ksize);