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>
91 #include <linux/poison.h>
92 #include <linux/swap.h>
93 #include <linux/cache.h>
94 #include <linux/interrupt.h>
95 #include <linux/init.h>
96 #include <linux/compiler.h>
97 #include <linux/cpuset.h>
98 #include <linux/proc_fs.h>
99 #include <linux/seq_file.h>
100 #include <linux/notifier.h>
101 #include <linux/kallsyms.h>
102 #include <linux/cpu.h>
103 #include <linux/sysctl.h>
104 #include <linux/module.h>
105 #include <linux/rcupdate.h>
106 #include <linux/string.h>
107 #include <linux/uaccess.h>
108 #include <linux/nodemask.h>
109 #include <linux/kmemleak.h>
110 #include <linux/mempolicy.h>
111 #include <linux/mutex.h>
112 #include <linux/fault-inject.h>
113 #include <linux/rtmutex.h>
114 #include <linux/reciprocal_div.h>
115 #include <linux/debugobjects.h>
116 #include <linux/kmemcheck.h>
117 #include <linux/memory.h>
118 #include <linux/prefetch.h>
120 #include <net/sock.h>
122 #include <asm/cacheflush.h>
123 #include <asm/tlbflush.h>
124 #include <asm/page.h>
126 #include <trace/events/kmem.h>
128 #include "internal.h"
133 * DEBUG - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
134 * 0 for faster, smaller code (especially in the critical paths).
136 * STATS - 1 to collect stats for /proc/slabinfo.
137 * 0 for faster, smaller code (especially in the critical paths).
139 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
142 #ifdef CONFIG_DEBUG_SLAB
145 #define FORCED_DEBUG 1
149 #define FORCED_DEBUG 0
152 /* Shouldn't this be in a header file somewhere? */
153 #define BYTES_PER_WORD sizeof(void *)
154 #define REDZONE_ALIGN max(BYTES_PER_WORD, __alignof__(unsigned long long))
156 #ifndef ARCH_KMALLOC_FLAGS
157 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
160 #define FREELIST_BYTE_INDEX (((PAGE_SIZE >> BITS_PER_BYTE) \
161 <= SLAB_OBJ_MIN_SIZE) ? 1 : 0)
163 #if FREELIST_BYTE_INDEX
164 typedef unsigned char freelist_idx_t;
166 typedef unsigned short freelist_idx_t;
169 #define SLAB_OBJ_MAX_NUM ((1 << sizeof(freelist_idx_t) * BITS_PER_BYTE) - 1)
172 * true if a page was allocated from pfmemalloc reserves for network-based
175 static bool pfmemalloc_active __read_mostly;
181 * - LIFO ordering, to hand out cache-warm objects from _alloc
182 * - reduce the number of linked list operations
183 * - reduce spinlock operations
185 * The limit is stored in the per-cpu structure to reduce the data cache
192 unsigned int batchcount;
193 unsigned int touched;
196 * Must have this definition in here for the proper
197 * alignment of array_cache. Also simplifies accessing
200 * Entries should not be directly dereferenced as
201 * entries belonging to slabs marked pfmemalloc will
202 * have the lower bits set SLAB_OBJ_PFMEMALLOC
208 struct array_cache ac;
211 #define SLAB_OBJ_PFMEMALLOC 1
212 static inline bool is_obj_pfmemalloc(void *objp)
214 return (unsigned long)objp & SLAB_OBJ_PFMEMALLOC;
217 static inline void set_obj_pfmemalloc(void **objp)
219 *objp = (void *)((unsigned long)*objp | SLAB_OBJ_PFMEMALLOC);
223 static inline void clear_obj_pfmemalloc(void **objp)
225 *objp = (void *)((unsigned long)*objp & ~SLAB_OBJ_PFMEMALLOC);
229 * bootstrap: The caches do not work without cpuarrays anymore, but the
230 * cpuarrays are allocated from the generic caches...
232 #define BOOT_CPUCACHE_ENTRIES 1
233 struct arraycache_init {
234 struct array_cache cache;
235 void *entries[BOOT_CPUCACHE_ENTRIES];
239 * Need this for bootstrapping a per node allocator.
241 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
242 static struct kmem_cache_node __initdata init_kmem_cache_node[NUM_INIT_LISTS];
243 #define CACHE_CACHE 0
244 #define SIZE_AC MAX_NUMNODES
245 #define SIZE_NODE (2 * MAX_NUMNODES)
247 static int drain_freelist(struct kmem_cache *cache,
248 struct kmem_cache_node *n, int tofree);
249 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
250 int node, struct list_head *list);
251 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list);
252 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
253 static void cache_reap(struct work_struct *unused);
255 static int slab_early_init = 1;
257 #define INDEX_AC kmalloc_index(sizeof(struct arraycache_init))
258 #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
260 static void kmem_cache_node_init(struct kmem_cache_node *parent)
262 INIT_LIST_HEAD(&parent->slabs_full);
263 INIT_LIST_HEAD(&parent->slabs_partial);
264 INIT_LIST_HEAD(&parent->slabs_free);
265 parent->shared = NULL;
266 parent->alien = NULL;
267 parent->colour_next = 0;
268 spin_lock_init(&parent->list_lock);
269 parent->free_objects = 0;
270 parent->free_touched = 0;
273 #define MAKE_LIST(cachep, listp, slab, nodeid) \
275 INIT_LIST_HEAD(listp); \
276 list_splice(&get_node(cachep, nodeid)->slab, listp); \
279 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
281 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
282 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
283 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
286 #define CFLGS_OFF_SLAB (0x80000000UL)
287 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
289 #define BATCHREFILL_LIMIT 16
291 * Optimization question: fewer reaps means less probability for unnessary
292 * cpucache drain/refill cycles.
294 * OTOH the cpuarrays can contain lots of objects,
295 * which could lock up otherwise freeable slabs.
297 #define REAPTIMEOUT_AC (2*HZ)
298 #define REAPTIMEOUT_NODE (4*HZ)
301 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
302 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
303 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
304 #define STATS_INC_GROWN(x) ((x)->grown++)
305 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
306 #define STATS_SET_HIGH(x) \
308 if ((x)->num_active > (x)->high_mark) \
309 (x)->high_mark = (x)->num_active; \
311 #define STATS_INC_ERR(x) ((x)->errors++)
312 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
313 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
314 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
315 #define STATS_SET_FREEABLE(x, i) \
317 if ((x)->max_freeable < i) \
318 (x)->max_freeable = i; \
320 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
321 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
322 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
323 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
325 #define STATS_INC_ACTIVE(x) do { } while (0)
326 #define STATS_DEC_ACTIVE(x) do { } while (0)
327 #define STATS_INC_ALLOCED(x) do { } while (0)
328 #define STATS_INC_GROWN(x) do { } while (0)
329 #define STATS_ADD_REAPED(x,y) do { (void)(y); } while (0)
330 #define STATS_SET_HIGH(x) do { } while (0)
331 #define STATS_INC_ERR(x) do { } while (0)
332 #define STATS_INC_NODEALLOCS(x) do { } while (0)
333 #define STATS_INC_NODEFREES(x) do { } while (0)
334 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
335 #define STATS_SET_FREEABLE(x, i) do { } while (0)
336 #define STATS_INC_ALLOCHIT(x) do { } while (0)
337 #define STATS_INC_ALLOCMISS(x) do { } while (0)
338 #define STATS_INC_FREEHIT(x) do { } while (0)
339 #define STATS_INC_FREEMISS(x) do { } while (0)
345 * memory layout of objects:
347 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
348 * the end of an object is aligned with the end of the real
349 * allocation. Catches writes behind the end of the allocation.
350 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
352 * cachep->obj_offset: The real object.
353 * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
354 * cachep->size - 1* BYTES_PER_WORD: last caller address
355 * [BYTES_PER_WORD long]
357 static int obj_offset(struct kmem_cache *cachep)
359 return cachep->obj_offset;
362 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
364 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
365 return (unsigned long long*) (objp + obj_offset(cachep) -
366 sizeof(unsigned long long));
369 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
371 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
372 if (cachep->flags & SLAB_STORE_USER)
373 return (unsigned long long *)(objp + cachep->size -
374 sizeof(unsigned long long) -
376 return (unsigned long long *) (objp + cachep->size -
377 sizeof(unsigned long long));
380 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
382 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
383 return (void **)(objp + cachep->size - BYTES_PER_WORD);
388 #define obj_offset(x) 0
389 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
390 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
391 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
395 #define OBJECT_FREE (0)
396 #define OBJECT_ACTIVE (1)
398 #ifdef CONFIG_DEBUG_SLAB_LEAK
400 static void set_obj_status(struct page *page, int idx, int val)
404 struct kmem_cache *cachep = page->slab_cache;
406 freelist_size = cachep->num * sizeof(freelist_idx_t);
407 status = (char *)page->freelist + freelist_size;
411 static inline unsigned int get_obj_status(struct page *page, int idx)
415 struct kmem_cache *cachep = page->slab_cache;
417 freelist_size = cachep->num * sizeof(freelist_idx_t);
418 status = (char *)page->freelist + freelist_size;
424 static inline void set_obj_status(struct page *page, int idx, int val) {}
429 * Do not go above this order unless 0 objects fit into the slab or
430 * overridden on the command line.
432 #define SLAB_MAX_ORDER_HI 1
433 #define SLAB_MAX_ORDER_LO 0
434 static int slab_max_order = SLAB_MAX_ORDER_LO;
435 static bool slab_max_order_set __initdata;
437 static inline struct kmem_cache *virt_to_cache(const void *obj)
439 struct page *page = virt_to_head_page(obj);
440 return page->slab_cache;
443 static inline void *index_to_obj(struct kmem_cache *cache, struct page *page,
446 return page->s_mem + cache->size * idx;
450 * We want to avoid an expensive divide : (offset / cache->size)
451 * Using the fact that size is a constant for a particular cache,
452 * we can replace (offset / cache->size) by
453 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
455 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
456 const struct page *page, void *obj)
458 u32 offset = (obj - page->s_mem);
459 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
462 static struct arraycache_init initarray_generic =
463 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
465 /* internal cache of cache description objs */
466 static struct kmem_cache kmem_cache_boot = {
468 .limit = BOOT_CPUCACHE_ENTRIES,
470 .size = sizeof(struct kmem_cache),
471 .name = "kmem_cache",
474 #define BAD_ALIEN_MAGIC 0x01020304ul
476 #ifdef CONFIG_LOCKDEP
479 * Slab sometimes uses the kmalloc slabs to store the slab headers
480 * for other slabs "off slab".
481 * The locking for this is tricky in that it nests within the locks
482 * of all other slabs in a few places; to deal with this special
483 * locking we put on-slab caches into a separate lock-class.
485 * We set lock class for alien array caches which are up during init.
486 * The lock annotation will be lost if all cpus of a node goes down and
487 * then comes back up during hotplug
489 static struct lock_class_key on_slab_l3_key;
490 static struct lock_class_key on_slab_alc_key;
492 static struct lock_class_key debugobj_l3_key;
493 static struct lock_class_key debugobj_alc_key;
495 static void slab_set_lock_classes(struct kmem_cache *cachep,
496 struct lock_class_key *l3_key, struct lock_class_key *alc_key,
497 struct kmem_cache_node *n)
499 struct alien_cache **alc;
502 lockdep_set_class(&n->list_lock, l3_key);
505 * FIXME: This check for BAD_ALIEN_MAGIC
506 * should go away when common slab code is taught to
507 * work even without alien caches.
508 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
509 * for alloc_alien_cache,
511 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
515 lockdep_set_class(&(alc[r]->ac.lock), alc_key);
519 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep,
520 struct kmem_cache_node *n)
522 slab_set_lock_classes(cachep, &debugobj_l3_key, &debugobj_alc_key, n);
525 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
528 struct kmem_cache_node *n;
530 for_each_kmem_cache_node(cachep, node, n)
531 slab_set_debugobj_lock_classes_node(cachep, n);
534 static void init_node_lock_keys(int q)
541 for (i = 1; i <= KMALLOC_SHIFT_HIGH; i++) {
542 struct kmem_cache_node *n;
543 struct kmem_cache *cache = kmalloc_caches[i];
548 n = get_node(cache, q);
549 if (!n || OFF_SLAB(cache))
552 slab_set_lock_classes(cache, &on_slab_l3_key,
553 &on_slab_alc_key, n);
557 static void on_slab_lock_classes_node(struct kmem_cache *cachep,
558 struct kmem_cache_node *n)
560 slab_set_lock_classes(cachep, &on_slab_l3_key,
561 &on_slab_alc_key, n);
564 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
567 struct kmem_cache_node *n;
569 VM_BUG_ON(OFF_SLAB(cachep));
570 for_each_kmem_cache_node(cachep, node, n)
571 on_slab_lock_classes_node(cachep, n);
574 static inline void __init init_lock_keys(void)
579 init_node_lock_keys(node);
582 static void __init init_node_lock_keys(int q)
586 static inline void init_lock_keys(void)
590 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
594 static inline void on_slab_lock_classes_node(struct kmem_cache *cachep,
595 struct kmem_cache_node *n)
599 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep,
600 struct kmem_cache_node *n)
604 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
609 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
611 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
613 return cachep->array[smp_processor_id()];
616 static size_t calculate_freelist_size(int nr_objs, size_t align)
618 size_t freelist_size;
620 freelist_size = nr_objs * sizeof(freelist_idx_t);
621 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
622 freelist_size += nr_objs * sizeof(char);
625 freelist_size = ALIGN(freelist_size, align);
627 return freelist_size;
630 static int calculate_nr_objs(size_t slab_size, size_t buffer_size,
631 size_t idx_size, size_t align)
634 size_t remained_size;
635 size_t freelist_size;
638 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
639 extra_space = sizeof(char);
641 * Ignore padding for the initial guess. The padding
642 * is at most @align-1 bytes, and @buffer_size is at
643 * least @align. In the worst case, this result will
644 * be one greater than the number of objects that fit
645 * into the memory allocation when taking the padding
648 nr_objs = slab_size / (buffer_size + idx_size + extra_space);
651 * This calculated number will be either the right
652 * amount, or one greater than what we want.
654 remained_size = slab_size - nr_objs * buffer_size;
655 freelist_size = calculate_freelist_size(nr_objs, align);
656 if (remained_size < freelist_size)
663 * Calculate the number of objects and left-over bytes for a given buffer size.
665 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
666 size_t align, int flags, size_t *left_over,
671 size_t slab_size = PAGE_SIZE << gfporder;
674 * The slab management structure can be either off the slab or
675 * on it. For the latter case, the memory allocated for a
678 * - One unsigned int for each object
679 * - Padding to respect alignment of @align
680 * - @buffer_size bytes for each object
682 * If the slab management structure is off the slab, then the
683 * alignment will already be calculated into the size. Because
684 * the slabs are all pages aligned, the objects will be at the
685 * correct alignment when allocated.
687 if (flags & CFLGS_OFF_SLAB) {
689 nr_objs = slab_size / buffer_size;
692 nr_objs = calculate_nr_objs(slab_size, buffer_size,
693 sizeof(freelist_idx_t), align);
694 mgmt_size = calculate_freelist_size(nr_objs, align);
697 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
701 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
703 static void __slab_error(const char *function, struct kmem_cache *cachep,
706 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
707 function, cachep->name, msg);
709 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
714 * By default on NUMA we use alien caches to stage the freeing of
715 * objects allocated from other nodes. This causes massive memory
716 * inefficiencies when using fake NUMA setup to split memory into a
717 * large number of small nodes, so it can be disabled on the command
721 static int use_alien_caches __read_mostly = 1;
722 static int __init noaliencache_setup(char *s)
724 use_alien_caches = 0;
727 __setup("noaliencache", noaliencache_setup);
729 static int __init slab_max_order_setup(char *str)
731 get_option(&str, &slab_max_order);
732 slab_max_order = slab_max_order < 0 ? 0 :
733 min(slab_max_order, MAX_ORDER - 1);
734 slab_max_order_set = true;
738 __setup("slab_max_order=", slab_max_order_setup);
742 * Special reaping functions for NUMA systems called from cache_reap().
743 * These take care of doing round robin flushing of alien caches (containing
744 * objects freed on different nodes from which they were allocated) and the
745 * flushing of remote pcps by calling drain_node_pages.
747 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
749 static void init_reap_node(int cpu)
753 node = next_node(cpu_to_mem(cpu), node_online_map);
754 if (node == MAX_NUMNODES)
755 node = first_node(node_online_map);
757 per_cpu(slab_reap_node, cpu) = node;
760 static void next_reap_node(void)
762 int node = __this_cpu_read(slab_reap_node);
764 node = next_node(node, node_online_map);
765 if (unlikely(node >= MAX_NUMNODES))
766 node = first_node(node_online_map);
767 __this_cpu_write(slab_reap_node, node);
771 #define init_reap_node(cpu) do { } while (0)
772 #define next_reap_node(void) do { } while (0)
776 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
777 * via the workqueue/eventd.
778 * Add the CPU number into the expiration time to minimize the possibility of
779 * the CPUs getting into lockstep and contending for the global cache chain
782 static void start_cpu_timer(int cpu)
784 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
787 * When this gets called from do_initcalls via cpucache_init(),
788 * init_workqueues() has already run, so keventd will be setup
791 if (keventd_up() && reap_work->work.func == NULL) {
793 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
794 schedule_delayed_work_on(cpu, reap_work,
795 __round_jiffies_relative(HZ, cpu));
799 static void init_arraycache(struct array_cache *ac, int limit, int batch)
802 * The array_cache structures contain pointers to free object.
803 * However, when such objects are allocated or transferred to another
804 * cache the pointers are not cleared and they could be counted as
805 * valid references during a kmemleak scan. Therefore, kmemleak must
806 * not scan such objects.
808 kmemleak_no_scan(ac);
812 ac->batchcount = batch;
814 spin_lock_init(&ac->lock);
818 static struct array_cache *alloc_arraycache(int node, int entries,
819 int batchcount, gfp_t gfp)
821 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
822 struct array_cache *ac = NULL;
824 ac = kmalloc_node(memsize, gfp, node);
825 init_arraycache(ac, entries, batchcount);
829 static inline bool is_slab_pfmemalloc(struct page *page)
831 return PageSlabPfmemalloc(page);
834 /* Clears pfmemalloc_active if no slabs have pfmalloc set */
835 static void recheck_pfmemalloc_active(struct kmem_cache *cachep,
836 struct array_cache *ac)
838 struct kmem_cache_node *n = get_node(cachep, numa_mem_id());
842 if (!pfmemalloc_active)
845 spin_lock_irqsave(&n->list_lock, flags);
846 list_for_each_entry(page, &n->slabs_full, lru)
847 if (is_slab_pfmemalloc(page))
850 list_for_each_entry(page, &n->slabs_partial, lru)
851 if (is_slab_pfmemalloc(page))
854 list_for_each_entry(page, &n->slabs_free, lru)
855 if (is_slab_pfmemalloc(page))
858 pfmemalloc_active = false;
860 spin_unlock_irqrestore(&n->list_lock, flags);
863 static void *__ac_get_obj(struct kmem_cache *cachep, struct array_cache *ac,
864 gfp_t flags, bool force_refill)
867 void *objp = ac->entry[--ac->avail];
869 /* Ensure the caller is allowed to use objects from PFMEMALLOC slab */
870 if (unlikely(is_obj_pfmemalloc(objp))) {
871 struct kmem_cache_node *n;
873 if (gfp_pfmemalloc_allowed(flags)) {
874 clear_obj_pfmemalloc(&objp);
878 /* The caller cannot use PFMEMALLOC objects, find another one */
879 for (i = 0; i < ac->avail; i++) {
880 /* If a !PFMEMALLOC object is found, swap them */
881 if (!is_obj_pfmemalloc(ac->entry[i])) {
883 ac->entry[i] = ac->entry[ac->avail];
884 ac->entry[ac->avail] = objp;
890 * If there are empty slabs on the slabs_free list and we are
891 * being forced to refill the cache, mark this one !pfmemalloc.
893 n = get_node(cachep, numa_mem_id());
894 if (!list_empty(&n->slabs_free) && force_refill) {
895 struct page *page = virt_to_head_page(objp);
896 ClearPageSlabPfmemalloc(page);
897 clear_obj_pfmemalloc(&objp);
898 recheck_pfmemalloc_active(cachep, ac);
902 /* No !PFMEMALLOC objects available */
910 static inline void *ac_get_obj(struct kmem_cache *cachep,
911 struct array_cache *ac, gfp_t flags, bool force_refill)
915 if (unlikely(sk_memalloc_socks()))
916 objp = __ac_get_obj(cachep, ac, flags, force_refill);
918 objp = ac->entry[--ac->avail];
923 static void *__ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
926 if (unlikely(pfmemalloc_active)) {
927 /* Some pfmemalloc slabs exist, check if this is one */
928 struct page *page = virt_to_head_page(objp);
929 if (PageSlabPfmemalloc(page))
930 set_obj_pfmemalloc(&objp);
936 static inline void ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
939 if (unlikely(sk_memalloc_socks()))
940 objp = __ac_put_obj(cachep, ac, objp);
942 ac->entry[ac->avail++] = objp;
946 * Transfer objects in one arraycache to another.
947 * Locking must be handled by the caller.
949 * Return the number of entries transferred.
951 static int transfer_objects(struct array_cache *to,
952 struct array_cache *from, unsigned int max)
954 /* Figure out how many entries to transfer */
955 int nr = min3(from->avail, max, to->limit - to->avail);
960 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
970 #define drain_alien_cache(cachep, alien) do { } while (0)
971 #define reap_alien(cachep, n) do { } while (0)
973 static inline struct alien_cache **alloc_alien_cache(int node,
974 int limit, gfp_t gfp)
976 return (struct alien_cache **)BAD_ALIEN_MAGIC;
979 static inline void free_alien_cache(struct alien_cache **ac_ptr)
983 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
988 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
994 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
995 gfp_t flags, int nodeid)
1000 #else /* CONFIG_NUMA */
1002 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
1003 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
1005 static struct alien_cache *__alloc_alien_cache(int node, int entries,
1006 int batch, gfp_t gfp)
1008 int memsize = sizeof(void *) * entries + sizeof(struct alien_cache);
1009 struct alien_cache *alc = NULL;
1011 alc = kmalloc_node(memsize, gfp, node);
1012 init_arraycache(&alc->ac, entries, batch);
1016 static struct alien_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
1018 struct alien_cache **alc_ptr;
1019 int memsize = sizeof(void *) * nr_node_ids;
1024 alc_ptr = kzalloc_node(memsize, gfp, node);
1029 if (i == node || !node_online(i))
1031 alc_ptr[i] = __alloc_alien_cache(node, limit, 0xbaadf00d, gfp);
1033 for (i--; i >= 0; i--)
1042 static void free_alien_cache(struct alien_cache **alc_ptr)
1053 static void __drain_alien_cache(struct kmem_cache *cachep,
1054 struct array_cache *ac, int node)
1056 struct kmem_cache_node *n = get_node(cachep, node);
1060 spin_lock(&n->list_lock);
1062 * Stuff objects into the remote nodes shared array first.
1063 * That way we could avoid the overhead of putting the objects
1064 * into the free lists and getting them back later.
1067 transfer_objects(n->shared, ac, ac->limit);
1069 free_block(cachep, ac->entry, ac->avail, node, &list);
1071 spin_unlock(&n->list_lock);
1072 slabs_destroy(cachep, &list);
1077 * Called from cache_reap() to regularly drain alien caches round robin.
1079 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
1081 int node = __this_cpu_read(slab_reap_node);
1084 struct alien_cache *alc = n->alien[node];
1085 struct array_cache *ac;
1089 if (ac->avail && spin_trylock_irq(&ac->lock)) {
1090 __drain_alien_cache(cachep, ac, node);
1091 spin_unlock_irq(&ac->lock);
1097 static void drain_alien_cache(struct kmem_cache *cachep,
1098 struct alien_cache **alien)
1101 struct alien_cache *alc;
1102 struct array_cache *ac;
1103 unsigned long flags;
1105 for_each_online_node(i) {
1109 spin_lock_irqsave(&ac->lock, flags);
1110 __drain_alien_cache(cachep, ac, i);
1111 spin_unlock_irqrestore(&ac->lock, flags);
1116 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1118 int nodeid = page_to_nid(virt_to_page(objp));
1119 struct kmem_cache_node *n;
1120 struct alien_cache *alien = NULL;
1121 struct array_cache *ac;
1125 node = numa_mem_id();
1128 * Make sure we are not freeing a object from another node to the array
1129 * cache on this cpu.
1131 if (likely(nodeid == node))
1134 n = get_node(cachep, node);
1135 STATS_INC_NODEFREES(cachep);
1136 if (n->alien && n->alien[nodeid]) {
1137 alien = n->alien[nodeid];
1139 spin_lock(&ac->lock);
1140 if (unlikely(ac->avail == ac->limit)) {
1141 STATS_INC_ACOVERFLOW(cachep);
1142 __drain_alien_cache(cachep, ac, nodeid);
1144 ac_put_obj(cachep, ac, objp);
1145 spin_unlock(&ac->lock);
1147 n = get_node(cachep, nodeid);
1148 spin_lock(&n->list_lock);
1149 free_block(cachep, &objp, 1, nodeid, &list);
1150 spin_unlock(&n->list_lock);
1151 slabs_destroy(cachep, &list);
1158 * Allocates and initializes node for a node on each slab cache, used for
1159 * either memory or cpu hotplug. If memory is being hot-added, the kmem_cache_node
1160 * will be allocated off-node since memory is not yet online for the new node.
1161 * When hotplugging memory or a cpu, existing node are not replaced if
1164 * Must hold slab_mutex.
1166 static int init_cache_node_node(int node)
1168 struct kmem_cache *cachep;
1169 struct kmem_cache_node *n;
1170 const int memsize = sizeof(struct kmem_cache_node);
1172 list_for_each_entry(cachep, &slab_caches, list) {
1174 * Set up the kmem_cache_node for cpu before we can
1175 * begin anything. Make sure some other cpu on this
1176 * node has not already allocated this
1178 n = get_node(cachep, node);
1180 n = kmalloc_node(memsize, GFP_KERNEL, node);
1183 kmem_cache_node_init(n);
1184 n->next_reap = jiffies + REAPTIMEOUT_NODE +
1185 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1188 * The kmem_cache_nodes don't come and go as CPUs
1189 * come and go. slab_mutex is sufficient
1192 cachep->node[node] = n;
1195 spin_lock_irq(&n->list_lock);
1197 (1 + nr_cpus_node(node)) *
1198 cachep->batchcount + cachep->num;
1199 spin_unlock_irq(&n->list_lock);
1204 static inline int slabs_tofree(struct kmem_cache *cachep,
1205 struct kmem_cache_node *n)
1207 return (n->free_objects + cachep->num - 1) / cachep->num;
1210 static void cpuup_canceled(long cpu)
1212 struct kmem_cache *cachep;
1213 struct kmem_cache_node *n = NULL;
1214 int node = cpu_to_mem(cpu);
1215 const struct cpumask *mask = cpumask_of_node(node);
1217 list_for_each_entry(cachep, &slab_caches, list) {
1218 struct array_cache *nc;
1219 struct array_cache *shared;
1220 struct alien_cache **alien;
1223 /* cpu is dead; no one can alloc from it. */
1224 nc = cachep->array[cpu];
1225 cachep->array[cpu] = NULL;
1226 n = get_node(cachep, node);
1229 goto free_array_cache;
1231 spin_lock_irq(&n->list_lock);
1233 /* Free limit for this kmem_cache_node */
1234 n->free_limit -= cachep->batchcount;
1236 free_block(cachep, nc->entry, nc->avail, node, &list);
1238 if (!cpumask_empty(mask)) {
1239 spin_unlock_irq(&n->list_lock);
1240 goto free_array_cache;
1245 free_block(cachep, shared->entry,
1246 shared->avail, node, &list);
1253 spin_unlock_irq(&n->list_lock);
1257 drain_alien_cache(cachep, alien);
1258 free_alien_cache(alien);
1261 slabs_destroy(cachep, &list);
1265 * In the previous loop, all the objects were freed to
1266 * the respective cache's slabs, now we can go ahead and
1267 * shrink each nodelist to its limit.
1269 list_for_each_entry(cachep, &slab_caches, list) {
1270 n = get_node(cachep, node);
1273 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1277 static int cpuup_prepare(long cpu)
1279 struct kmem_cache *cachep;
1280 struct kmem_cache_node *n = NULL;
1281 int node = cpu_to_mem(cpu);
1285 * We need to do this right in the beginning since
1286 * alloc_arraycache's are going to use this list.
1287 * kmalloc_node allows us to add the slab to the right
1288 * kmem_cache_node and not this cpu's kmem_cache_node
1290 err = init_cache_node_node(node);
1295 * Now we can go ahead with allocating the shared arrays and
1298 list_for_each_entry(cachep, &slab_caches, list) {
1299 struct array_cache *nc;
1300 struct array_cache *shared = NULL;
1301 struct alien_cache **alien = NULL;
1303 nc = alloc_arraycache(node, cachep->limit,
1304 cachep->batchcount, GFP_KERNEL);
1307 if (cachep->shared) {
1308 shared = alloc_arraycache(node,
1309 cachep->shared * cachep->batchcount,
1310 0xbaadf00d, GFP_KERNEL);
1316 if (use_alien_caches) {
1317 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1324 cachep->array[cpu] = nc;
1325 n = get_node(cachep, node);
1328 spin_lock_irq(&n->list_lock);
1331 * We are serialised from CPU_DEAD or
1332 * CPU_UP_CANCELLED by the cpucontrol lock
1343 spin_unlock_irq(&n->list_lock);
1345 free_alien_cache(alien);
1346 if (cachep->flags & SLAB_DEBUG_OBJECTS)
1347 slab_set_debugobj_lock_classes_node(cachep, n);
1348 else if (!OFF_SLAB(cachep) &&
1349 !(cachep->flags & SLAB_DESTROY_BY_RCU))
1350 on_slab_lock_classes_node(cachep, n);
1352 init_node_lock_keys(node);
1356 cpuup_canceled(cpu);
1360 static int cpuup_callback(struct notifier_block *nfb,
1361 unsigned long action, void *hcpu)
1363 long cpu = (long)hcpu;
1367 case CPU_UP_PREPARE:
1368 case CPU_UP_PREPARE_FROZEN:
1369 mutex_lock(&slab_mutex);
1370 err = cpuup_prepare(cpu);
1371 mutex_unlock(&slab_mutex);
1374 case CPU_ONLINE_FROZEN:
1375 start_cpu_timer(cpu);
1377 #ifdef CONFIG_HOTPLUG_CPU
1378 case CPU_DOWN_PREPARE:
1379 case CPU_DOWN_PREPARE_FROZEN:
1381 * Shutdown cache reaper. Note that the slab_mutex is
1382 * held so that if cache_reap() is invoked it cannot do
1383 * anything expensive but will only modify reap_work
1384 * and reschedule the timer.
1386 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1387 /* Now the cache_reaper is guaranteed to be not running. */
1388 per_cpu(slab_reap_work, cpu).work.func = NULL;
1390 case CPU_DOWN_FAILED:
1391 case CPU_DOWN_FAILED_FROZEN:
1392 start_cpu_timer(cpu);
1395 case CPU_DEAD_FROZEN:
1397 * Even if all the cpus of a node are down, we don't free the
1398 * kmem_cache_node of any cache. This to avoid a race between
1399 * cpu_down, and a kmalloc allocation from another cpu for
1400 * memory from the node of the cpu going down. The node
1401 * structure is usually allocated from kmem_cache_create() and
1402 * gets destroyed at kmem_cache_destroy().
1406 case CPU_UP_CANCELED:
1407 case CPU_UP_CANCELED_FROZEN:
1408 mutex_lock(&slab_mutex);
1409 cpuup_canceled(cpu);
1410 mutex_unlock(&slab_mutex);
1413 return notifier_from_errno(err);
1416 static struct notifier_block cpucache_notifier = {
1417 &cpuup_callback, NULL, 0
1420 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1422 * Drains freelist for a node on each slab cache, used for memory hot-remove.
1423 * Returns -EBUSY if all objects cannot be drained so that the node is not
1426 * Must hold slab_mutex.
1428 static int __meminit drain_cache_node_node(int node)
1430 struct kmem_cache *cachep;
1433 list_for_each_entry(cachep, &slab_caches, list) {
1434 struct kmem_cache_node *n;
1436 n = get_node(cachep, node);
1440 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1442 if (!list_empty(&n->slabs_full) ||
1443 !list_empty(&n->slabs_partial)) {
1451 static int __meminit slab_memory_callback(struct notifier_block *self,
1452 unsigned long action, void *arg)
1454 struct memory_notify *mnb = arg;
1458 nid = mnb->status_change_nid;
1463 case MEM_GOING_ONLINE:
1464 mutex_lock(&slab_mutex);
1465 ret = init_cache_node_node(nid);
1466 mutex_unlock(&slab_mutex);
1468 case MEM_GOING_OFFLINE:
1469 mutex_lock(&slab_mutex);
1470 ret = drain_cache_node_node(nid);
1471 mutex_unlock(&slab_mutex);
1475 case MEM_CANCEL_ONLINE:
1476 case MEM_CANCEL_OFFLINE:
1480 return notifier_from_errno(ret);
1482 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1485 * swap the static kmem_cache_node with kmalloced memory
1487 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1490 struct kmem_cache_node *ptr;
1492 ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1495 memcpy(ptr, list, sizeof(struct kmem_cache_node));
1497 * Do not assume that spinlocks can be initialized via memcpy:
1499 spin_lock_init(&ptr->list_lock);
1501 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1502 cachep->node[nodeid] = ptr;
1506 * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1507 * size of kmem_cache_node.
1509 static void __init set_up_node(struct kmem_cache *cachep, int index)
1513 for_each_online_node(node) {
1514 cachep->node[node] = &init_kmem_cache_node[index + node];
1515 cachep->node[node]->next_reap = jiffies +
1517 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1522 * The memory after the last cpu cache pointer is used for the
1525 static void setup_node_pointer(struct kmem_cache *cachep)
1527 cachep->node = (struct kmem_cache_node **)&cachep->array[nr_cpu_ids];
1531 * Initialisation. Called after the page allocator have been initialised and
1532 * before smp_init().
1534 void __init kmem_cache_init(void)
1538 BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1539 sizeof(struct rcu_head));
1540 kmem_cache = &kmem_cache_boot;
1541 setup_node_pointer(kmem_cache);
1543 if (num_possible_nodes() == 1)
1544 use_alien_caches = 0;
1546 for (i = 0; i < NUM_INIT_LISTS; i++)
1547 kmem_cache_node_init(&init_kmem_cache_node[i]);
1549 set_up_node(kmem_cache, CACHE_CACHE);
1552 * Fragmentation resistance on low memory - only use bigger
1553 * page orders on machines with more than 32MB of memory if
1554 * not overridden on the command line.
1556 if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1557 slab_max_order = SLAB_MAX_ORDER_HI;
1559 /* Bootstrap is tricky, because several objects are allocated
1560 * from caches that do not exist yet:
1561 * 1) initialize the kmem_cache cache: it contains the struct
1562 * kmem_cache structures of all caches, except kmem_cache itself:
1563 * kmem_cache is statically allocated.
1564 * Initially an __init data area is used for the head array and the
1565 * kmem_cache_node structures, it's replaced with a kmalloc allocated
1566 * array at the end of the bootstrap.
1567 * 2) Create the first kmalloc cache.
1568 * The struct kmem_cache for the new cache is allocated normally.
1569 * An __init data area is used for the head array.
1570 * 3) Create the remaining kmalloc caches, with minimally sized
1572 * 4) Replace the __init data head arrays for kmem_cache and the first
1573 * kmalloc cache with kmalloc allocated arrays.
1574 * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1575 * the other cache's with kmalloc allocated memory.
1576 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1579 /* 1) create the kmem_cache */
1582 * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1584 create_boot_cache(kmem_cache, "kmem_cache",
1585 offsetof(struct kmem_cache, array[nr_cpu_ids]) +
1586 nr_node_ids * sizeof(struct kmem_cache_node *),
1587 SLAB_HWCACHE_ALIGN);
1588 list_add(&kmem_cache->list, &slab_caches);
1590 /* 2+3) create the kmalloc caches */
1593 * Initialize the caches that provide memory for the array cache and the
1594 * kmem_cache_node structures first. Without this, further allocations will
1598 kmalloc_caches[INDEX_AC] = create_kmalloc_cache("kmalloc-ac",
1599 kmalloc_size(INDEX_AC), ARCH_KMALLOC_FLAGS);
1601 if (INDEX_AC != INDEX_NODE)
1602 kmalloc_caches[INDEX_NODE] =
1603 create_kmalloc_cache("kmalloc-node",
1604 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1606 slab_early_init = 0;
1608 /* 4) Replace the bootstrap head arrays */
1610 struct array_cache *ptr;
1612 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1614 memcpy(ptr, cpu_cache_get(kmem_cache),
1615 sizeof(struct arraycache_init));
1617 * Do not assume that spinlocks can be initialized via memcpy:
1619 spin_lock_init(&ptr->lock);
1621 kmem_cache->array[smp_processor_id()] = ptr;
1623 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1625 BUG_ON(cpu_cache_get(kmalloc_caches[INDEX_AC])
1626 != &initarray_generic.cache);
1627 memcpy(ptr, cpu_cache_get(kmalloc_caches[INDEX_AC]),
1628 sizeof(struct arraycache_init));
1630 * Do not assume that spinlocks can be initialized via memcpy:
1632 spin_lock_init(&ptr->lock);
1634 kmalloc_caches[INDEX_AC]->array[smp_processor_id()] = ptr;
1636 /* 5) Replace the bootstrap kmem_cache_node */
1640 for_each_online_node(nid) {
1641 init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1643 init_list(kmalloc_caches[INDEX_AC],
1644 &init_kmem_cache_node[SIZE_AC + nid], nid);
1646 if (INDEX_AC != INDEX_NODE) {
1647 init_list(kmalloc_caches[INDEX_NODE],
1648 &init_kmem_cache_node[SIZE_NODE + nid], nid);
1653 create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1656 void __init kmem_cache_init_late(void)
1658 struct kmem_cache *cachep;
1662 /* 6) resize the head arrays to their final sizes */
1663 mutex_lock(&slab_mutex);
1664 list_for_each_entry(cachep, &slab_caches, list)
1665 if (enable_cpucache(cachep, GFP_NOWAIT))
1667 mutex_unlock(&slab_mutex);
1669 /* Annotate slab for lockdep -- annotate the malloc caches */
1676 * Register a cpu startup notifier callback that initializes
1677 * cpu_cache_get for all new cpus
1679 register_cpu_notifier(&cpucache_notifier);
1683 * Register a memory hotplug callback that initializes and frees
1686 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1690 * The reap timers are started later, with a module init call: That part
1691 * of the kernel is not yet operational.
1695 static int __init cpucache_init(void)
1700 * Register the timers that return unneeded pages to the page allocator
1702 for_each_online_cpu(cpu)
1703 start_cpu_timer(cpu);
1709 __initcall(cpucache_init);
1711 static noinline void
1712 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1715 struct kmem_cache_node *n;
1717 unsigned long flags;
1719 static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1720 DEFAULT_RATELIMIT_BURST);
1722 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1726 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1728 printk(KERN_WARNING " cache: %s, object size: %d, order: %d\n",
1729 cachep->name, cachep->size, cachep->gfporder);
1731 for_each_kmem_cache_node(cachep, node, n) {
1732 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1733 unsigned long active_slabs = 0, num_slabs = 0;
1735 spin_lock_irqsave(&n->list_lock, flags);
1736 list_for_each_entry(page, &n->slabs_full, lru) {
1737 active_objs += cachep->num;
1740 list_for_each_entry(page, &n->slabs_partial, lru) {
1741 active_objs += page->active;
1744 list_for_each_entry(page, &n->slabs_free, lru)
1747 free_objects += n->free_objects;
1748 spin_unlock_irqrestore(&n->list_lock, flags);
1750 num_slabs += active_slabs;
1751 num_objs = num_slabs * cachep->num;
1753 " node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1754 node, active_slabs, num_slabs, active_objs, num_objs,
1761 * Interface to system's page allocator. No need to hold the cache-lock.
1763 * If we requested dmaable memory, we will get it. Even if we
1764 * did not request dmaable memory, we might get it, but that
1765 * would be relatively rare and ignorable.
1767 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1773 flags |= cachep->allocflags;
1774 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1775 flags |= __GFP_RECLAIMABLE;
1777 if (memcg_charge_slab(cachep, flags, cachep->gfporder))
1780 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1782 memcg_uncharge_slab(cachep, cachep->gfporder);
1783 slab_out_of_memory(cachep, flags, nodeid);
1787 /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1788 if (unlikely(page->pfmemalloc))
1789 pfmemalloc_active = true;
1791 nr_pages = (1 << cachep->gfporder);
1792 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1793 add_zone_page_state(page_zone(page),
1794 NR_SLAB_RECLAIMABLE, nr_pages);
1796 add_zone_page_state(page_zone(page),
1797 NR_SLAB_UNRECLAIMABLE, nr_pages);
1798 __SetPageSlab(page);
1799 if (page->pfmemalloc)
1800 SetPageSlabPfmemalloc(page);
1802 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1803 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1806 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1808 kmemcheck_mark_unallocated_pages(page, nr_pages);
1815 * Interface to system's page release.
1817 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1819 const unsigned long nr_freed = (1 << cachep->gfporder);
1821 kmemcheck_free_shadow(page, cachep->gfporder);
1823 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1824 sub_zone_page_state(page_zone(page),
1825 NR_SLAB_RECLAIMABLE, nr_freed);
1827 sub_zone_page_state(page_zone(page),
1828 NR_SLAB_UNRECLAIMABLE, nr_freed);
1830 BUG_ON(!PageSlab(page));
1831 __ClearPageSlabPfmemalloc(page);
1832 __ClearPageSlab(page);
1833 page_mapcount_reset(page);
1834 page->mapping = NULL;
1836 if (current->reclaim_state)
1837 current->reclaim_state->reclaimed_slab += nr_freed;
1838 __free_pages(page, cachep->gfporder);
1839 memcg_uncharge_slab(cachep, cachep->gfporder);
1842 static void kmem_rcu_free(struct rcu_head *head)
1844 struct kmem_cache *cachep;
1847 page = container_of(head, struct page, rcu_head);
1848 cachep = page->slab_cache;
1850 kmem_freepages(cachep, page);
1855 #ifdef CONFIG_DEBUG_PAGEALLOC
1856 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1857 unsigned long caller)
1859 int size = cachep->object_size;
1861 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1863 if (size < 5 * sizeof(unsigned long))
1866 *addr++ = 0x12345678;
1868 *addr++ = smp_processor_id();
1869 size -= 3 * sizeof(unsigned long);
1871 unsigned long *sptr = &caller;
1872 unsigned long svalue;
1874 while (!kstack_end(sptr)) {
1876 if (kernel_text_address(svalue)) {
1878 size -= sizeof(unsigned long);
1879 if (size <= sizeof(unsigned long))
1885 *addr++ = 0x87654321;
1889 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1891 int size = cachep->object_size;
1892 addr = &((char *)addr)[obj_offset(cachep)];
1894 memset(addr, val, size);
1895 *(unsigned char *)(addr + size - 1) = POISON_END;
1898 static void dump_line(char *data, int offset, int limit)
1901 unsigned char error = 0;
1904 printk(KERN_ERR "%03x: ", offset);
1905 for (i = 0; i < limit; i++) {
1906 if (data[offset + i] != POISON_FREE) {
1907 error = data[offset + i];
1911 print_hex_dump(KERN_CONT, "", 0, 16, 1,
1912 &data[offset], limit, 1);
1914 if (bad_count == 1) {
1915 error ^= POISON_FREE;
1916 if (!(error & (error - 1))) {
1917 printk(KERN_ERR "Single bit error detected. Probably "
1920 printk(KERN_ERR "Run memtest86+ or a similar memory "
1923 printk(KERN_ERR "Run a memory test tool.\n");
1932 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1937 if (cachep->flags & SLAB_RED_ZONE) {
1938 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1939 *dbg_redzone1(cachep, objp),
1940 *dbg_redzone2(cachep, objp));
1943 if (cachep->flags & SLAB_STORE_USER) {
1944 printk(KERN_ERR "Last user: [<%p>](%pSR)\n",
1945 *dbg_userword(cachep, objp),
1946 *dbg_userword(cachep, objp));
1948 realobj = (char *)objp + obj_offset(cachep);
1949 size = cachep->object_size;
1950 for (i = 0; i < size && lines; i += 16, lines--) {
1953 if (i + limit > size)
1955 dump_line(realobj, i, limit);
1959 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1965 realobj = (char *)objp + obj_offset(cachep);
1966 size = cachep->object_size;
1968 for (i = 0; i < size; i++) {
1969 char exp = POISON_FREE;
1972 if (realobj[i] != exp) {
1978 "Slab corruption (%s): %s start=%p, len=%d\n",
1979 print_tainted(), cachep->name, realobj, size);
1980 print_objinfo(cachep, objp, 0);
1982 /* Hexdump the affected line */
1985 if (i + limit > size)
1987 dump_line(realobj, i, limit);
1990 /* Limit to 5 lines */
1996 /* Print some data about the neighboring objects, if they
1999 struct page *page = virt_to_head_page(objp);
2002 objnr = obj_to_index(cachep, page, objp);
2004 objp = index_to_obj(cachep, page, objnr - 1);
2005 realobj = (char *)objp + obj_offset(cachep);
2006 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
2008 print_objinfo(cachep, objp, 2);
2010 if (objnr + 1 < cachep->num) {
2011 objp = index_to_obj(cachep, page, objnr + 1);
2012 realobj = (char *)objp + obj_offset(cachep);
2013 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
2015 print_objinfo(cachep, objp, 2);
2022 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
2026 for (i = 0; i < cachep->num; i++) {
2027 void *objp = index_to_obj(cachep, page, i);
2029 if (cachep->flags & SLAB_POISON) {
2030 #ifdef CONFIG_DEBUG_PAGEALLOC
2031 if (cachep->size % PAGE_SIZE == 0 &&
2033 kernel_map_pages(virt_to_page(objp),
2034 cachep->size / PAGE_SIZE, 1);
2036 check_poison_obj(cachep, objp);
2038 check_poison_obj(cachep, objp);
2041 if (cachep->flags & SLAB_RED_ZONE) {
2042 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2043 slab_error(cachep, "start of a freed object "
2045 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2046 slab_error(cachep, "end of a freed object "
2052 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
2059 * slab_destroy - destroy and release all objects in a slab
2060 * @cachep: cache pointer being destroyed
2061 * @page: page pointer being destroyed
2063 * Destroy all the objs in a slab, and release the mem back to the system.
2064 * Before calling the slab must have been unlinked from the cache. The
2065 * cache-lock is not held/needed.
2067 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
2071 freelist = page->freelist;
2072 slab_destroy_debugcheck(cachep, page);
2073 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2074 struct rcu_head *head;
2077 * RCU free overloads the RCU head over the LRU.
2078 * slab_page has been overloeaded over the LRU,
2079 * however it is not used from now on so that
2080 * we can use it safely.
2082 head = (void *)&page->rcu_head;
2083 call_rcu(head, kmem_rcu_free);
2086 kmem_freepages(cachep, page);
2090 * From now on, we don't use freelist
2091 * although actual page can be freed in rcu context
2093 if (OFF_SLAB(cachep))
2094 kmem_cache_free(cachep->freelist_cache, freelist);
2097 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
2099 struct page *page, *n;
2101 list_for_each_entry_safe(page, n, list, lru) {
2102 list_del(&page->lru);
2103 slab_destroy(cachep, page);
2108 * calculate_slab_order - calculate size (page order) of slabs
2109 * @cachep: pointer to the cache that is being created
2110 * @size: size of objects to be created in this cache.
2111 * @align: required alignment for the objects.
2112 * @flags: slab allocation flags
2114 * Also calculates the number of objects per slab.
2116 * This could be made much more intelligent. For now, try to avoid using
2117 * high order pages for slabs. When the gfp() functions are more friendly
2118 * towards high-order requests, this should be changed.
2120 static size_t calculate_slab_order(struct kmem_cache *cachep,
2121 size_t size, size_t align, unsigned long flags)
2123 unsigned long offslab_limit;
2124 size_t left_over = 0;
2127 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2131 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2135 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
2136 if (num > SLAB_OBJ_MAX_NUM)
2139 if (flags & CFLGS_OFF_SLAB) {
2140 size_t freelist_size_per_obj = sizeof(freelist_idx_t);
2142 * Max number of objs-per-slab for caches which
2143 * use off-slab slabs. Needed to avoid a possible
2144 * looping condition in cache_grow().
2146 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
2147 freelist_size_per_obj += sizeof(char);
2148 offslab_limit = size;
2149 offslab_limit /= freelist_size_per_obj;
2151 if (num > offslab_limit)
2155 /* Found something acceptable - save it away */
2157 cachep->gfporder = gfporder;
2158 left_over = remainder;
2161 * A VFS-reclaimable slab tends to have most allocations
2162 * as GFP_NOFS and we really don't want to have to be allocating
2163 * higher-order pages when we are unable to shrink dcache.
2165 if (flags & SLAB_RECLAIM_ACCOUNT)
2169 * Large number of objects is good, but very large slabs are
2170 * currently bad for the gfp()s.
2172 if (gfporder >= slab_max_order)
2176 * Acceptable internal fragmentation?
2178 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2184 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2186 if (slab_state >= FULL)
2187 return enable_cpucache(cachep, gfp);
2189 if (slab_state == DOWN) {
2191 * Note: Creation of first cache (kmem_cache).
2192 * The setup_node is taken care
2193 * of by the caller of __kmem_cache_create
2195 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2196 slab_state = PARTIAL;
2197 } else if (slab_state == PARTIAL) {
2199 * Note: the second kmem_cache_create must create the cache
2200 * that's used by kmalloc(24), otherwise the creation of
2201 * further caches will BUG().
2203 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2206 * If the cache that's used by kmalloc(sizeof(kmem_cache_node)) is
2207 * the second cache, then we need to set up all its node/,
2208 * otherwise the creation of further caches will BUG().
2210 set_up_node(cachep, SIZE_AC);
2211 if (INDEX_AC == INDEX_NODE)
2212 slab_state = PARTIAL_NODE;
2214 slab_state = PARTIAL_ARRAYCACHE;
2216 /* Remaining boot caches */
2217 cachep->array[smp_processor_id()] =
2218 kmalloc(sizeof(struct arraycache_init), gfp);
2220 if (slab_state == PARTIAL_ARRAYCACHE) {
2221 set_up_node(cachep, SIZE_NODE);
2222 slab_state = PARTIAL_NODE;
2225 for_each_online_node(node) {
2226 cachep->node[node] =
2227 kmalloc_node(sizeof(struct kmem_cache_node),
2229 BUG_ON(!cachep->node[node]);
2230 kmem_cache_node_init(cachep->node[node]);
2234 cachep->node[numa_mem_id()]->next_reap =
2235 jiffies + REAPTIMEOUT_NODE +
2236 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
2238 cpu_cache_get(cachep)->avail = 0;
2239 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2240 cpu_cache_get(cachep)->batchcount = 1;
2241 cpu_cache_get(cachep)->touched = 0;
2242 cachep->batchcount = 1;
2243 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2248 * __kmem_cache_create - Create a cache.
2249 * @cachep: cache management descriptor
2250 * @flags: SLAB flags
2252 * Returns a ptr to the cache on success, NULL on failure.
2253 * Cannot be called within a int, but can be interrupted.
2254 * The @ctor is run when new pages are allocated by the cache.
2258 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2259 * to catch references to uninitialised memory.
2261 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2262 * for buffer overruns.
2264 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2265 * cacheline. This can be beneficial if you're counting cycles as closely
2269 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2271 size_t left_over, freelist_size, ralign;
2274 size_t size = cachep->size;
2279 * Enable redzoning and last user accounting, except for caches with
2280 * large objects, if the increased size would increase the object size
2281 * above the next power of two: caches with object sizes just above a
2282 * power of two have a significant amount of internal fragmentation.
2284 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2285 2 * sizeof(unsigned long long)))
2286 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2287 if (!(flags & SLAB_DESTROY_BY_RCU))
2288 flags |= SLAB_POISON;
2290 if (flags & SLAB_DESTROY_BY_RCU)
2291 BUG_ON(flags & SLAB_POISON);
2295 * Check that size is in terms of words. This is needed to avoid
2296 * unaligned accesses for some archs when redzoning is used, and makes
2297 * sure any on-slab bufctl's are also correctly aligned.
2299 if (size & (BYTES_PER_WORD - 1)) {
2300 size += (BYTES_PER_WORD - 1);
2301 size &= ~(BYTES_PER_WORD - 1);
2305 * Redzoning and user store require word alignment or possibly larger.
2306 * Note this will be overridden by architecture or caller mandated
2307 * alignment if either is greater than BYTES_PER_WORD.
2309 if (flags & SLAB_STORE_USER)
2310 ralign = BYTES_PER_WORD;
2312 if (flags & SLAB_RED_ZONE) {
2313 ralign = REDZONE_ALIGN;
2314 /* If redzoning, ensure that the second redzone is suitably
2315 * aligned, by adjusting the object size accordingly. */
2316 size += REDZONE_ALIGN - 1;
2317 size &= ~(REDZONE_ALIGN - 1);
2320 /* 3) caller mandated alignment */
2321 if (ralign < cachep->align) {
2322 ralign = cachep->align;
2324 /* disable debug if necessary */
2325 if (ralign > __alignof__(unsigned long long))
2326 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2330 cachep->align = ralign;
2332 if (slab_is_available())
2337 setup_node_pointer(cachep);
2341 * Both debugging options require word-alignment which is calculated
2344 if (flags & SLAB_RED_ZONE) {
2345 /* add space for red zone words */
2346 cachep->obj_offset += sizeof(unsigned long long);
2347 size += 2 * sizeof(unsigned long long);
2349 if (flags & SLAB_STORE_USER) {
2350 /* user store requires one word storage behind the end of
2351 * the real object. But if the second red zone needs to be
2352 * aligned to 64 bits, we must allow that much space.
2354 if (flags & SLAB_RED_ZONE)
2355 size += REDZONE_ALIGN;
2357 size += BYTES_PER_WORD;
2359 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2360 if (size >= kmalloc_size(INDEX_NODE + 1)
2361 && cachep->object_size > cache_line_size()
2362 && ALIGN(size, cachep->align) < PAGE_SIZE) {
2363 cachep->obj_offset += PAGE_SIZE - ALIGN(size, cachep->align);
2370 * Determine if the slab management is 'on' or 'off' slab.
2371 * (bootstrapping cannot cope with offslab caches so don't do
2372 * it too early on. Always use on-slab management when
2373 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2375 if ((size >= (PAGE_SIZE >> 5)) && !slab_early_init &&
2376 !(flags & SLAB_NOLEAKTRACE))
2378 * Size is large, assume best to place the slab management obj
2379 * off-slab (should allow better packing of objs).
2381 flags |= CFLGS_OFF_SLAB;
2383 size = ALIGN(size, cachep->align);
2385 * We should restrict the number of objects in a slab to implement
2386 * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
2388 if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
2389 size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
2391 left_over = calculate_slab_order(cachep, size, cachep->align, flags);
2396 freelist_size = calculate_freelist_size(cachep->num, cachep->align);
2399 * If the slab has been placed off-slab, and we have enough space then
2400 * move it on-slab. This is at the expense of any extra colouring.
2402 if (flags & CFLGS_OFF_SLAB && left_over >= freelist_size) {
2403 flags &= ~CFLGS_OFF_SLAB;
2404 left_over -= freelist_size;
2407 if (flags & CFLGS_OFF_SLAB) {
2408 /* really off slab. No need for manual alignment */
2409 freelist_size = calculate_freelist_size(cachep->num, 0);
2411 #ifdef CONFIG_PAGE_POISONING
2412 /* If we're going to use the generic kernel_map_pages()
2413 * poisoning, then it's going to smash the contents of
2414 * the redzone and userword anyhow, so switch them off.
2416 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2417 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2421 cachep->colour_off = cache_line_size();
2422 /* Offset must be a multiple of the alignment. */
2423 if (cachep->colour_off < cachep->align)
2424 cachep->colour_off = cachep->align;
2425 cachep->colour = left_over / cachep->colour_off;
2426 cachep->freelist_size = freelist_size;
2427 cachep->flags = flags;
2428 cachep->allocflags = __GFP_COMP;
2429 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2430 cachep->allocflags |= GFP_DMA;
2431 cachep->size = size;
2432 cachep->reciprocal_buffer_size = reciprocal_value(size);
2434 if (flags & CFLGS_OFF_SLAB) {
2435 cachep->freelist_cache = kmalloc_slab(freelist_size, 0u);
2437 * This is a possibility for one of the kmalloc_{dma,}_caches.
2438 * But since we go off slab only for object size greater than
2439 * PAGE_SIZE/8, and kmalloc_{dma,}_caches get created
2440 * in ascending order,this should not happen at all.
2441 * But leave a BUG_ON for some lucky dude.
2443 BUG_ON(ZERO_OR_NULL_PTR(cachep->freelist_cache));
2446 err = setup_cpu_cache(cachep, gfp);
2448 __kmem_cache_shutdown(cachep);
2452 if (flags & SLAB_DEBUG_OBJECTS) {
2454 * Would deadlock through slab_destroy()->call_rcu()->
2455 * debug_object_activate()->kmem_cache_alloc().
2457 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2459 slab_set_debugobj_lock_classes(cachep);
2460 } else if (!OFF_SLAB(cachep) && !(flags & SLAB_DESTROY_BY_RCU))
2461 on_slab_lock_classes(cachep);
2467 static void check_irq_off(void)
2469 BUG_ON(!irqs_disabled());
2472 static void check_irq_on(void)
2474 BUG_ON(irqs_disabled());
2477 static void check_spinlock_acquired(struct kmem_cache *cachep)
2481 assert_spin_locked(&get_node(cachep, numa_mem_id())->list_lock);
2485 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2489 assert_spin_locked(&get_node(cachep, node)->list_lock);
2494 #define check_irq_off() do { } while(0)
2495 #define check_irq_on() do { } while(0)
2496 #define check_spinlock_acquired(x) do { } while(0)
2497 #define check_spinlock_acquired_node(x, y) do { } while(0)
2500 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
2501 struct array_cache *ac,
2502 int force, int node);
2504 static void do_drain(void *arg)
2506 struct kmem_cache *cachep = arg;
2507 struct array_cache *ac;
2508 int node = numa_mem_id();
2509 struct kmem_cache_node *n;
2513 ac = cpu_cache_get(cachep);
2514 n = get_node(cachep, node);
2515 spin_lock(&n->list_lock);
2516 free_block(cachep, ac->entry, ac->avail, node, &list);
2517 spin_unlock(&n->list_lock);
2518 slabs_destroy(cachep, &list);
2522 static void drain_cpu_caches(struct kmem_cache *cachep)
2524 struct kmem_cache_node *n;
2527 on_each_cpu(do_drain, cachep, 1);
2529 for_each_kmem_cache_node(cachep, node, n)
2531 drain_alien_cache(cachep, n->alien);
2533 for_each_kmem_cache_node(cachep, node, n)
2534 drain_array(cachep, n, n->shared, 1, node);
2538 * Remove slabs from the list of free slabs.
2539 * Specify the number of slabs to drain in tofree.
2541 * Returns the actual number of slabs released.
2543 static int drain_freelist(struct kmem_cache *cache,
2544 struct kmem_cache_node *n, int tofree)
2546 struct list_head *p;
2551 while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
2553 spin_lock_irq(&n->list_lock);
2554 p = n->slabs_free.prev;
2555 if (p == &n->slabs_free) {
2556 spin_unlock_irq(&n->list_lock);
2560 page = list_entry(p, struct page, lru);
2562 BUG_ON(page->active);
2564 list_del(&page->lru);
2566 * Safe to drop the lock. The slab is no longer linked
2569 n->free_objects -= cache->num;
2570 spin_unlock_irq(&n->list_lock);
2571 slab_destroy(cache, page);
2578 int __kmem_cache_shrink(struct kmem_cache *cachep)
2582 struct kmem_cache_node *n;
2584 drain_cpu_caches(cachep);
2587 for_each_kmem_cache_node(cachep, node, n) {
2588 drain_freelist(cachep, n, slabs_tofree(cachep, n));
2590 ret += !list_empty(&n->slabs_full) ||
2591 !list_empty(&n->slabs_partial);
2593 return (ret ? 1 : 0);
2596 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2599 struct kmem_cache_node *n;
2600 int rc = __kmem_cache_shrink(cachep);
2605 for_each_online_cpu(i)
2606 kfree(cachep->array[i]);
2608 /* NUMA: free the node structures */
2609 for_each_kmem_cache_node(cachep, i, n) {
2611 free_alien_cache(n->alien);
2613 cachep->node[i] = NULL;
2619 * Get the memory for a slab management obj.
2621 * For a slab cache when the slab descriptor is off-slab, the
2622 * slab descriptor can't come from the same cache which is being created,
2623 * Because if it is the case, that means we defer the creation of
2624 * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
2625 * And we eventually call down to __kmem_cache_create(), which
2626 * in turn looks up in the kmalloc_{dma,}_caches for the disired-size one.
2627 * This is a "chicken-and-egg" problem.
2629 * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
2630 * which are all initialized during kmem_cache_init().
2632 static void *alloc_slabmgmt(struct kmem_cache *cachep,
2633 struct page *page, int colour_off,
2634 gfp_t local_flags, int nodeid)
2637 void *addr = page_address(page);
2639 if (OFF_SLAB(cachep)) {
2640 /* Slab management obj is off-slab. */
2641 freelist = kmem_cache_alloc_node(cachep->freelist_cache,
2642 local_flags, nodeid);
2646 freelist = addr + colour_off;
2647 colour_off += cachep->freelist_size;
2650 page->s_mem = addr + colour_off;
2654 static inline freelist_idx_t get_free_obj(struct page *page, unsigned int idx)
2656 return ((freelist_idx_t *)page->freelist)[idx];
2659 static inline void set_free_obj(struct page *page,
2660 unsigned int idx, freelist_idx_t val)
2662 ((freelist_idx_t *)(page->freelist))[idx] = val;
2665 static void cache_init_objs(struct kmem_cache *cachep,
2670 for (i = 0; i < cachep->num; i++) {
2671 void *objp = index_to_obj(cachep, page, i);
2673 /* need to poison the objs? */
2674 if (cachep->flags & SLAB_POISON)
2675 poison_obj(cachep, objp, POISON_FREE);
2676 if (cachep->flags & SLAB_STORE_USER)
2677 *dbg_userword(cachep, objp) = NULL;
2679 if (cachep->flags & SLAB_RED_ZONE) {
2680 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2681 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2684 * Constructors are not allowed to allocate memory from the same
2685 * cache which they are a constructor for. Otherwise, deadlock.
2686 * They must also be threaded.
2688 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2689 cachep->ctor(objp + obj_offset(cachep));
2691 if (cachep->flags & SLAB_RED_ZONE) {
2692 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2693 slab_error(cachep, "constructor overwrote the"
2694 " end of an object");
2695 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2696 slab_error(cachep, "constructor overwrote the"
2697 " start of an object");
2699 if ((cachep->size % PAGE_SIZE) == 0 &&
2700 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2701 kernel_map_pages(virt_to_page(objp),
2702 cachep->size / PAGE_SIZE, 0);
2707 set_obj_status(page, i, OBJECT_FREE);
2708 set_free_obj(page, i, i);
2712 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2714 if (CONFIG_ZONE_DMA_FLAG) {
2715 if (flags & GFP_DMA)
2716 BUG_ON(!(cachep->allocflags & GFP_DMA));
2718 BUG_ON(cachep->allocflags & GFP_DMA);
2722 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page,
2727 objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2730 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2736 static void slab_put_obj(struct kmem_cache *cachep, struct page *page,
2737 void *objp, int nodeid)
2739 unsigned int objnr = obj_to_index(cachep, page, objp);
2743 /* Verify that the slab belongs to the intended node */
2744 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2746 /* Verify double free bug */
2747 for (i = page->active; i < cachep->num; i++) {
2748 if (get_free_obj(page, i) == objnr) {
2749 printk(KERN_ERR "slab: double free detected in cache "
2750 "'%s', objp %p\n", cachep->name, objp);
2756 set_free_obj(page, page->active, objnr);
2760 * Map pages beginning at addr to the given cache and slab. This is required
2761 * for the slab allocator to be able to lookup the cache and slab of a
2762 * virtual address for kfree, ksize, and slab debugging.
2764 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2767 page->slab_cache = cache;
2768 page->freelist = freelist;
2772 * Grow (by 1) the number of slabs within a cache. This is called by
2773 * kmem_cache_alloc() when there are no active objs left in a cache.
2775 static int cache_grow(struct kmem_cache *cachep,
2776 gfp_t flags, int nodeid, struct page *page)
2781 struct kmem_cache_node *n;
2784 * Be lazy and only check for valid flags here, keeping it out of the
2785 * critical path in kmem_cache_alloc().
2787 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2788 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2790 /* Take the node list lock to change the colour_next on this node */
2792 n = get_node(cachep, nodeid);
2793 spin_lock(&n->list_lock);
2795 /* Get colour for the slab, and cal the next value. */
2796 offset = n->colour_next;
2798 if (n->colour_next >= cachep->colour)
2800 spin_unlock(&n->list_lock);
2802 offset *= cachep->colour_off;
2804 if (local_flags & __GFP_WAIT)
2808 * The test for missing atomic flag is performed here, rather than
2809 * the more obvious place, simply to reduce the critical path length
2810 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2811 * will eventually be caught here (where it matters).
2813 kmem_flagcheck(cachep, flags);
2816 * Get mem for the objs. Attempt to allocate a physical page from
2820 page = kmem_getpages(cachep, local_flags, nodeid);
2824 /* Get slab management. */
2825 freelist = alloc_slabmgmt(cachep, page, offset,
2826 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2830 slab_map_pages(cachep, page, freelist);
2832 cache_init_objs(cachep, page);
2834 if (local_flags & __GFP_WAIT)
2835 local_irq_disable();
2837 spin_lock(&n->list_lock);
2839 /* Make slab active. */
2840 list_add_tail(&page->lru, &(n->slabs_free));
2841 STATS_INC_GROWN(cachep);
2842 n->free_objects += cachep->num;
2843 spin_unlock(&n->list_lock);
2846 kmem_freepages(cachep, page);
2848 if (local_flags & __GFP_WAIT)
2849 local_irq_disable();
2856 * Perform extra freeing checks:
2857 * - detect bad pointers.
2858 * - POISON/RED_ZONE checking
2860 static void kfree_debugcheck(const void *objp)
2862 if (!virt_addr_valid(objp)) {
2863 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2864 (unsigned long)objp);
2869 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2871 unsigned long long redzone1, redzone2;
2873 redzone1 = *dbg_redzone1(cache, obj);
2874 redzone2 = *dbg_redzone2(cache, obj);
2879 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2882 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2883 slab_error(cache, "double free detected");
2885 slab_error(cache, "memory outside object was overwritten");
2887 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2888 obj, redzone1, redzone2);
2891 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2892 unsigned long caller)
2897 BUG_ON(virt_to_cache(objp) != cachep);
2899 objp -= obj_offset(cachep);
2900 kfree_debugcheck(objp);
2901 page = virt_to_head_page(objp);
2903 if (cachep->flags & SLAB_RED_ZONE) {
2904 verify_redzone_free(cachep, objp);
2905 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2906 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2908 if (cachep->flags & SLAB_STORE_USER)
2909 *dbg_userword(cachep, objp) = (void *)caller;
2911 objnr = obj_to_index(cachep, page, objp);
2913 BUG_ON(objnr >= cachep->num);
2914 BUG_ON(objp != index_to_obj(cachep, page, objnr));
2916 set_obj_status(page, objnr, OBJECT_FREE);
2917 if (cachep->flags & SLAB_POISON) {
2918 #ifdef CONFIG_DEBUG_PAGEALLOC
2919 if ((cachep->size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2920 store_stackinfo(cachep, objp, caller);
2921 kernel_map_pages(virt_to_page(objp),
2922 cachep->size / PAGE_SIZE, 0);
2924 poison_obj(cachep, objp, POISON_FREE);
2927 poison_obj(cachep, objp, POISON_FREE);
2934 #define kfree_debugcheck(x) do { } while(0)
2935 #define cache_free_debugcheck(x,objp,z) (objp)
2938 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
2942 struct kmem_cache_node *n;
2943 struct array_cache *ac;
2947 node = numa_mem_id();
2948 if (unlikely(force_refill))
2951 ac = cpu_cache_get(cachep);
2952 batchcount = ac->batchcount;
2953 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2955 * If there was little recent activity on this cache, then
2956 * perform only a partial refill. Otherwise we could generate
2959 batchcount = BATCHREFILL_LIMIT;
2961 n = get_node(cachep, node);
2963 BUG_ON(ac->avail > 0 || !n);
2964 spin_lock(&n->list_lock);
2966 /* See if we can refill from the shared array */
2967 if (n->shared && transfer_objects(ac, n->shared, batchcount)) {
2968 n->shared->touched = 1;
2972 while (batchcount > 0) {
2973 struct list_head *entry;
2975 /* Get slab alloc is to come from. */
2976 entry = n->slabs_partial.next;
2977 if (entry == &n->slabs_partial) {
2978 n->free_touched = 1;
2979 entry = n->slabs_free.next;
2980 if (entry == &n->slabs_free)
2984 page = list_entry(entry, struct page, lru);
2985 check_spinlock_acquired(cachep);
2988 * The slab was either on partial or free list so
2989 * there must be at least one object available for
2992 BUG_ON(page->active >= cachep->num);
2994 while (page->active < cachep->num && batchcount--) {
2995 STATS_INC_ALLOCED(cachep);
2996 STATS_INC_ACTIVE(cachep);
2997 STATS_SET_HIGH(cachep);
2999 ac_put_obj(cachep, ac, slab_get_obj(cachep, page,
3003 /* move slabp to correct slabp list: */
3004 list_del(&page->lru);
3005 if (page->active == cachep->num)
3006 list_add(&page->lru, &n->slabs_full);
3008 list_add(&page->lru, &n->slabs_partial);
3012 n->free_objects -= ac->avail;
3014 spin_unlock(&n->list_lock);
3016 if (unlikely(!ac->avail)) {
3019 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
3021 /* cache_grow can reenable interrupts, then ac could change. */
3022 ac = cpu_cache_get(cachep);
3023 node = numa_mem_id();
3025 /* no objects in sight? abort */
3026 if (!x && (ac->avail == 0 || force_refill))
3029 if (!ac->avail) /* objects refilled by interrupt? */
3034 return ac_get_obj(cachep, ac, flags, force_refill);
3037 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3040 might_sleep_if(flags & __GFP_WAIT);
3042 kmem_flagcheck(cachep, flags);
3047 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3048 gfp_t flags, void *objp, unsigned long caller)
3054 if (cachep->flags & SLAB_POISON) {
3055 #ifdef CONFIG_DEBUG_PAGEALLOC
3056 if ((cachep->size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3057 kernel_map_pages(virt_to_page(objp),
3058 cachep->size / PAGE_SIZE, 1);
3060 check_poison_obj(cachep, objp);
3062 check_poison_obj(cachep, objp);
3064 poison_obj(cachep, objp, POISON_INUSE);
3066 if (cachep->flags & SLAB_STORE_USER)
3067 *dbg_userword(cachep, objp) = (void *)caller;
3069 if (cachep->flags & SLAB_RED_ZONE) {
3070 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3071 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3072 slab_error(cachep, "double free, or memory outside"
3073 " object was overwritten");
3075 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3076 objp, *dbg_redzone1(cachep, objp),
3077 *dbg_redzone2(cachep, objp));
3079 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3080 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3083 page = virt_to_head_page(objp);
3084 set_obj_status(page, obj_to_index(cachep, page, objp), OBJECT_ACTIVE);
3085 objp += obj_offset(cachep);
3086 if (cachep->ctor && cachep->flags & SLAB_POISON)
3088 if (ARCH_SLAB_MINALIGN &&
3089 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3090 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3091 objp, (int)ARCH_SLAB_MINALIGN);
3096 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3099 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3101 if (unlikely(cachep == kmem_cache))
3104 return should_failslab(cachep->object_size, flags, cachep->flags);
3107 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3110 struct array_cache *ac;
3111 bool force_refill = false;
3115 ac = cpu_cache_get(cachep);
3116 if (likely(ac->avail)) {
3118 objp = ac_get_obj(cachep, ac, flags, false);
3121 * Allow for the possibility all avail objects are not allowed
3122 * by the current flags
3125 STATS_INC_ALLOCHIT(cachep);
3128 force_refill = true;
3131 STATS_INC_ALLOCMISS(cachep);
3132 objp = cache_alloc_refill(cachep, flags, force_refill);
3134 * the 'ac' may be updated by cache_alloc_refill(),
3135 * and kmemleak_erase() requires its correct value.
3137 ac = cpu_cache_get(cachep);
3141 * To avoid a false negative, if an object that is in one of the
3142 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3143 * treat the array pointers as a reference to the object.
3146 kmemleak_erase(&ac->entry[ac->avail]);
3152 * Try allocating on another node if PF_SPREAD_SLAB is a mempolicy is set.
3154 * If we are in_interrupt, then process context, including cpusets and
3155 * mempolicy, may not apply and should not be used for allocation policy.
3157 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3159 int nid_alloc, nid_here;
3161 if (in_interrupt() || (flags & __GFP_THISNODE))
3163 nid_alloc = nid_here = numa_mem_id();
3164 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3165 nid_alloc = cpuset_slab_spread_node();
3166 else if (current->mempolicy)
3167 nid_alloc = mempolicy_slab_node();
3168 if (nid_alloc != nid_here)
3169 return ____cache_alloc_node(cachep, flags, nid_alloc);
3174 * Fallback function if there was no memory available and no objects on a
3175 * certain node and fall back is permitted. First we scan all the
3176 * available node for available objects. If that fails then we
3177 * perform an allocation without specifying a node. This allows the page
3178 * allocator to do its reclaim / fallback magic. We then insert the
3179 * slab into the proper nodelist and then allocate from it.
3181 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3183 struct zonelist *zonelist;
3187 enum zone_type high_zoneidx = gfp_zone(flags);
3190 unsigned int cpuset_mems_cookie;
3192 if (flags & __GFP_THISNODE)
3195 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3198 cpuset_mems_cookie = read_mems_allowed_begin();
3199 zonelist = node_zonelist(mempolicy_slab_node(), flags);
3203 * Look through allowed nodes for objects available
3204 * from existing per node queues.
3206 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3207 nid = zone_to_nid(zone);
3209 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3210 get_node(cache, nid) &&
3211 get_node(cache, nid)->free_objects) {
3212 obj = ____cache_alloc_node(cache,
3213 flags | GFP_THISNODE, nid);
3221 * This allocation will be performed within the constraints
3222 * of the current cpuset / memory policy requirements.
3223 * We may trigger various forms of reclaim on the allowed
3224 * set and go into memory reserves if necessary.
3228 if (local_flags & __GFP_WAIT)
3230 kmem_flagcheck(cache, flags);
3231 page = kmem_getpages(cache, local_flags, numa_mem_id());
3232 if (local_flags & __GFP_WAIT)
3233 local_irq_disable();
3236 * Insert into the appropriate per node queues
3238 nid = page_to_nid(page);
3239 if (cache_grow(cache, flags, nid, page)) {
3240 obj = ____cache_alloc_node(cache,
3241 flags | GFP_THISNODE, nid);
3244 * Another processor may allocate the
3245 * objects in the slab since we are
3246 * not holding any locks.
3250 /* cache_grow already freed obj */
3256 if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3262 * A interface to enable slab creation on nodeid
3264 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3267 struct list_head *entry;
3269 struct kmem_cache_node *n;
3273 VM_BUG_ON(nodeid > num_online_nodes());
3274 n = get_node(cachep, nodeid);
3279 spin_lock(&n->list_lock);
3280 entry = n->slabs_partial.next;
3281 if (entry == &n->slabs_partial) {
3282 n->free_touched = 1;
3283 entry = n->slabs_free.next;
3284 if (entry == &n->slabs_free)
3288 page = list_entry(entry, struct page, lru);
3289 check_spinlock_acquired_node(cachep, nodeid);
3291 STATS_INC_NODEALLOCS(cachep);
3292 STATS_INC_ACTIVE(cachep);
3293 STATS_SET_HIGH(cachep);
3295 BUG_ON(page->active == cachep->num);
3297 obj = slab_get_obj(cachep, page, nodeid);
3299 /* move slabp to correct slabp list: */
3300 list_del(&page->lru);
3302 if (page->active == cachep->num)
3303 list_add(&page->lru, &n->slabs_full);
3305 list_add(&page->lru, &n->slabs_partial);
3307 spin_unlock(&n->list_lock);
3311 spin_unlock(&n->list_lock);
3312 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3316 return fallback_alloc(cachep, flags);
3322 static __always_inline void *
3323 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3324 unsigned long caller)
3326 unsigned long save_flags;
3328 int slab_node = numa_mem_id();
3330 flags &= gfp_allowed_mask;
3332 lockdep_trace_alloc(flags);
3334 if (slab_should_failslab(cachep, flags))
3337 cachep = memcg_kmem_get_cache(cachep, flags);
3339 cache_alloc_debugcheck_before(cachep, flags);
3340 local_irq_save(save_flags);
3342 if (nodeid == NUMA_NO_NODE)
3345 if (unlikely(!get_node(cachep, nodeid))) {
3346 /* Node not bootstrapped yet */
3347 ptr = fallback_alloc(cachep, flags);
3351 if (nodeid == slab_node) {
3353 * Use the locally cached objects if possible.
3354 * However ____cache_alloc does not allow fallback
3355 * to other nodes. It may fail while we still have
3356 * objects on other nodes available.
3358 ptr = ____cache_alloc(cachep, flags);
3362 /* ___cache_alloc_node can fall back to other nodes */
3363 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3365 local_irq_restore(save_flags);
3366 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3367 kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3371 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3372 if (unlikely(flags & __GFP_ZERO))
3373 memset(ptr, 0, cachep->object_size);
3379 static __always_inline void *
3380 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3384 if (current->mempolicy || unlikely(current->flags & PF_SPREAD_SLAB)) {
3385 objp = alternate_node_alloc(cache, flags);
3389 objp = ____cache_alloc(cache, flags);
3392 * We may just have run out of memory on the local node.
3393 * ____cache_alloc_node() knows how to locate memory on other nodes
3396 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3403 static __always_inline void *
3404 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3406 return ____cache_alloc(cachep, flags);
3409 #endif /* CONFIG_NUMA */
3411 static __always_inline void *
3412 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3414 unsigned long save_flags;
3417 flags &= gfp_allowed_mask;
3419 lockdep_trace_alloc(flags);
3421 if (slab_should_failslab(cachep, flags))
3424 cachep = memcg_kmem_get_cache(cachep, flags);
3426 cache_alloc_debugcheck_before(cachep, flags);
3427 local_irq_save(save_flags);
3428 objp = __do_cache_alloc(cachep, flags);
3429 local_irq_restore(save_flags);
3430 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3431 kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3436 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3437 if (unlikely(flags & __GFP_ZERO))
3438 memset(objp, 0, cachep->object_size);
3445 * Caller needs to acquire correct kmem_cache_node's list_lock
3446 * @list: List of detached free slabs should be freed by caller
3448 static void free_block(struct kmem_cache *cachep, void **objpp,
3449 int nr_objects, int node, struct list_head *list)
3452 struct kmem_cache_node *n = get_node(cachep, node);
3454 for (i = 0; i < nr_objects; i++) {
3458 clear_obj_pfmemalloc(&objpp[i]);
3461 page = virt_to_head_page(objp);
3462 list_del(&page->lru);
3463 check_spinlock_acquired_node(cachep, node);
3464 slab_put_obj(cachep, page, objp, node);
3465 STATS_DEC_ACTIVE(cachep);
3468 /* fixup slab chains */
3469 if (page->active == 0) {
3470 if (n->free_objects > n->free_limit) {
3471 n->free_objects -= cachep->num;
3472 list_add_tail(&page->lru, list);
3474 list_add(&page->lru, &n->slabs_free);
3477 /* Unconditionally move a slab to the end of the
3478 * partial list on free - maximum time for the
3479 * other objects to be freed, too.
3481 list_add_tail(&page->lru, &n->slabs_partial);
3486 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3489 struct kmem_cache_node *n;
3490 int node = numa_mem_id();
3493 batchcount = ac->batchcount;
3495 BUG_ON(!batchcount || batchcount > ac->avail);
3498 n = get_node(cachep, node);
3499 spin_lock(&n->list_lock);
3501 struct array_cache *shared_array = n->shared;
3502 int max = shared_array->limit - shared_array->avail;
3504 if (batchcount > max)
3506 memcpy(&(shared_array->entry[shared_array->avail]),
3507 ac->entry, sizeof(void *) * batchcount);
3508 shared_array->avail += batchcount;
3513 free_block(cachep, ac->entry, batchcount, node, &list);
3518 struct list_head *p;
3520 p = n->slabs_free.next;
3521 while (p != &(n->slabs_free)) {
3524 page = list_entry(p, struct page, lru);
3525 BUG_ON(page->active);
3530 STATS_SET_FREEABLE(cachep, i);
3533 spin_unlock(&n->list_lock);
3534 slabs_destroy(cachep, &list);
3535 ac->avail -= batchcount;
3536 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3540 * Release an obj back to its cache. If the obj has a constructed state, it must
3541 * be in this state _before_ it is released. Called with disabled ints.
3543 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3544 unsigned long caller)
3546 struct array_cache *ac = cpu_cache_get(cachep);
3549 kmemleak_free_recursive(objp, cachep->flags);
3550 objp = cache_free_debugcheck(cachep, objp, caller);
3552 kmemcheck_slab_free(cachep, objp, cachep->object_size);
3555 * Skip calling cache_free_alien() when the platform is not numa.
3556 * This will avoid cache misses that happen while accessing slabp (which
3557 * is per page memory reference) to get nodeid. Instead use a global
3558 * variable to skip the call, which is mostly likely to be present in
3561 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3564 if (likely(ac->avail < ac->limit)) {
3565 STATS_INC_FREEHIT(cachep);
3567 STATS_INC_FREEMISS(cachep);
3568 cache_flusharray(cachep, ac);
3571 ac_put_obj(cachep, ac, objp);
3575 * kmem_cache_alloc - Allocate an object
3576 * @cachep: The cache to allocate from.
3577 * @flags: See kmalloc().
3579 * Allocate an object from this cache. The flags are only relevant
3580 * if the cache has no available objects.
3582 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3584 void *ret = slab_alloc(cachep, flags, _RET_IP_);
3586 trace_kmem_cache_alloc(_RET_IP_, ret,
3587 cachep->object_size, cachep->size, flags);
3591 EXPORT_SYMBOL(kmem_cache_alloc);
3593 #ifdef CONFIG_TRACING
3595 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3599 ret = slab_alloc(cachep, flags, _RET_IP_);
3601 trace_kmalloc(_RET_IP_, ret,
3602 size, cachep->size, flags);
3605 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3610 * kmem_cache_alloc_node - Allocate an object on the specified node
3611 * @cachep: The cache to allocate from.
3612 * @flags: See kmalloc().
3613 * @nodeid: node number of the target node.
3615 * Identical to kmem_cache_alloc but it will allocate memory on the given
3616 * node, which can improve the performance for cpu bound structures.
3618 * Fallback to other node is possible if __GFP_THISNODE is not set.
3620 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3622 void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3624 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3625 cachep->object_size, cachep->size,
3630 EXPORT_SYMBOL(kmem_cache_alloc_node);
3632 #ifdef CONFIG_TRACING
3633 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3640 ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3642 trace_kmalloc_node(_RET_IP_, ret,
3647 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3650 static __always_inline void *
3651 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3653 struct kmem_cache *cachep;
3655 cachep = kmalloc_slab(size, flags);
3656 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3658 return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3661 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3662 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3664 return __do_kmalloc_node(size, flags, node, _RET_IP_);
3666 EXPORT_SYMBOL(__kmalloc_node);
3668 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3669 int node, unsigned long caller)
3671 return __do_kmalloc_node(size, flags, node, caller);
3673 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3675 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3677 return __do_kmalloc_node(size, flags, node, 0);
3679 EXPORT_SYMBOL(__kmalloc_node);
3680 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3681 #endif /* CONFIG_NUMA */
3684 * __do_kmalloc - allocate memory
3685 * @size: how many bytes of memory are required.
3686 * @flags: the type of memory to allocate (see kmalloc).
3687 * @caller: function caller for debug tracking of the caller
3689 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3690 unsigned long caller)
3692 struct kmem_cache *cachep;
3695 cachep = kmalloc_slab(size, flags);
3696 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3698 ret = slab_alloc(cachep, flags, caller);
3700 trace_kmalloc(caller, ret,
3701 size, cachep->size, flags);
3707 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3708 void *__kmalloc(size_t size, gfp_t flags)
3710 return __do_kmalloc(size, flags, _RET_IP_);
3712 EXPORT_SYMBOL(__kmalloc);
3714 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3716 return __do_kmalloc(size, flags, caller);
3718 EXPORT_SYMBOL(__kmalloc_track_caller);
3721 void *__kmalloc(size_t size, gfp_t flags)
3723 return __do_kmalloc(size, flags, 0);
3725 EXPORT_SYMBOL(__kmalloc);
3729 * kmem_cache_free - Deallocate an object
3730 * @cachep: The cache the allocation was from.
3731 * @objp: The previously allocated object.
3733 * Free an object which was previously allocated from this
3736 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3738 unsigned long flags;
3739 cachep = cache_from_obj(cachep, objp);
3743 local_irq_save(flags);
3744 debug_check_no_locks_freed(objp, cachep->object_size);
3745 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3746 debug_check_no_obj_freed(objp, cachep->object_size);
3747 __cache_free(cachep, objp, _RET_IP_);
3748 local_irq_restore(flags);
3750 trace_kmem_cache_free(_RET_IP_, objp);
3752 EXPORT_SYMBOL(kmem_cache_free);
3755 * kfree - free previously allocated memory
3756 * @objp: pointer returned by kmalloc.
3758 * If @objp is NULL, no operation is performed.
3760 * Don't free memory not originally allocated by kmalloc()
3761 * or you will run into trouble.
3763 void kfree(const void *objp)
3765 struct kmem_cache *c;
3766 unsigned long flags;
3768 trace_kfree(_RET_IP_, objp);
3770 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3772 local_irq_save(flags);
3773 kfree_debugcheck(objp);
3774 c = virt_to_cache(objp);
3775 debug_check_no_locks_freed(objp, c->object_size);
3777 debug_check_no_obj_freed(objp, c->object_size);
3778 __cache_free(c, (void *)objp, _RET_IP_);
3779 local_irq_restore(flags);
3781 EXPORT_SYMBOL(kfree);
3784 * This initializes kmem_cache_node or resizes various caches for all nodes.
3786 static int alloc_kmem_cache_node(struct kmem_cache *cachep, gfp_t gfp)
3789 struct kmem_cache_node *n;
3790 struct array_cache *new_shared;
3791 struct alien_cache **new_alien = NULL;
3793 for_each_online_node(node) {
3795 if (use_alien_caches) {
3796 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3802 if (cachep->shared) {
3803 new_shared = alloc_arraycache(node,
3804 cachep->shared*cachep->batchcount,
3807 free_alien_cache(new_alien);
3812 n = get_node(cachep, node);
3814 struct array_cache *shared = n->shared;
3817 spin_lock_irq(&n->list_lock);
3820 free_block(cachep, shared->entry,
3821 shared->avail, node, &list);
3823 n->shared = new_shared;
3825 n->alien = new_alien;
3828 n->free_limit = (1 + nr_cpus_node(node)) *
3829 cachep->batchcount + cachep->num;
3830 spin_unlock_irq(&n->list_lock);
3831 slabs_destroy(cachep, &list);
3833 free_alien_cache(new_alien);
3836 n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
3838 free_alien_cache(new_alien);
3843 kmem_cache_node_init(n);
3844 n->next_reap = jiffies + REAPTIMEOUT_NODE +
3845 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
3846 n->shared = new_shared;
3847 n->alien = new_alien;
3848 n->free_limit = (1 + nr_cpus_node(node)) *
3849 cachep->batchcount + cachep->num;
3850 cachep->node[node] = n;
3855 if (!cachep->list.next) {
3856 /* Cache is not active yet. Roll back what we did */
3859 n = get_node(cachep, node);
3862 free_alien_cache(n->alien);
3864 cachep->node[node] = NULL;
3872 struct ccupdate_struct {
3873 struct kmem_cache *cachep;
3874 struct array_cache *new[0];
3877 static void do_ccupdate_local(void *info)
3879 struct ccupdate_struct *new = info;
3880 struct array_cache *old;
3883 old = cpu_cache_get(new->cachep);
3885 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3886 new->new[smp_processor_id()] = old;
3889 /* Always called with the slab_mutex held */
3890 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3891 int batchcount, int shared, gfp_t gfp)
3893 struct ccupdate_struct *new;
3896 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
3901 for_each_online_cpu(i) {
3902 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
3905 for (i--; i >= 0; i--)
3911 new->cachep = cachep;
3913 on_each_cpu(do_ccupdate_local, (void *)new, 1);
3916 cachep->batchcount = batchcount;
3917 cachep->limit = limit;
3918 cachep->shared = shared;
3920 for_each_online_cpu(i) {
3922 struct array_cache *ccold = new->new[i];
3924 struct kmem_cache_node *n;
3929 node = cpu_to_mem(i);
3930 n = get_node(cachep, node);
3931 spin_lock_irq(&n->list_lock);
3932 free_block(cachep, ccold->entry, ccold->avail, node, &list);
3933 spin_unlock_irq(&n->list_lock);
3934 slabs_destroy(cachep, &list);
3938 return alloc_kmem_cache_node(cachep, gfp);
3941 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3942 int batchcount, int shared, gfp_t gfp)
3945 struct kmem_cache *c = NULL;
3948 ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3950 if (slab_state < FULL)
3953 if ((ret < 0) || !is_root_cache(cachep))
3956 VM_BUG_ON(!mutex_is_locked(&slab_mutex));
3957 for_each_memcg_cache_index(i) {
3958 c = cache_from_memcg_idx(cachep, i);
3960 /* return value determined by the parent cache only */
3961 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3967 /* Called with slab_mutex held always */
3968 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3975 if (!is_root_cache(cachep)) {
3976 struct kmem_cache *root = memcg_root_cache(cachep);
3977 limit = root->limit;
3978 shared = root->shared;
3979 batchcount = root->batchcount;
3982 if (limit && shared && batchcount)
3985 * The head array serves three purposes:
3986 * - create a LIFO ordering, i.e. return objects that are cache-warm
3987 * - reduce the number of spinlock operations.
3988 * - reduce the number of linked list operations on the slab and
3989 * bufctl chains: array operations are cheaper.
3990 * The numbers are guessed, we should auto-tune as described by
3993 if (cachep->size > 131072)
3995 else if (cachep->size > PAGE_SIZE)
3997 else if (cachep->size > 1024)
3999 else if (cachep->size > 256)
4005 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
4006 * allocation behaviour: Most allocs on one cpu, most free operations
4007 * on another cpu. For these cases, an efficient object passing between
4008 * cpus is necessary. This is provided by a shared array. The array
4009 * replaces Bonwick's magazine layer.
4010 * On uniprocessor, it's functionally equivalent (but less efficient)
4011 * to a larger limit. Thus disabled by default.
4014 if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
4019 * With debugging enabled, large batchcount lead to excessively long
4020 * periods with disabled local interrupts. Limit the batchcount
4025 batchcount = (limit + 1) / 2;
4027 err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
4029 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
4030 cachep->name, -err);
4035 * Drain an array if it contains any elements taking the node lock only if
4036 * necessary. Note that the node listlock also protects the array_cache
4037 * if drain_array() is used on the shared array.
4039 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
4040 struct array_cache *ac, int force, int node)
4045 if (!ac || !ac->avail)
4047 if (ac->touched && !force) {
4050 spin_lock_irq(&n->list_lock);
4052 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4053 if (tofree > ac->avail)
4054 tofree = (ac->avail + 1) / 2;
4055 free_block(cachep, ac->entry, tofree, node, &list);
4056 ac->avail -= tofree;
4057 memmove(ac->entry, &(ac->entry[tofree]),
4058 sizeof(void *) * ac->avail);
4060 spin_unlock_irq(&n->list_lock);
4061 slabs_destroy(cachep, &list);
4066 * cache_reap - Reclaim memory from caches.
4067 * @w: work descriptor
4069 * Called from workqueue/eventd every few seconds.
4071 * - clear the per-cpu caches for this CPU.
4072 * - return freeable pages to the main free memory pool.
4074 * If we cannot acquire the cache chain mutex then just give up - we'll try
4075 * again on the next iteration.
4077 static void cache_reap(struct work_struct *w)
4079 struct kmem_cache *searchp;
4080 struct kmem_cache_node *n;
4081 int node = numa_mem_id();
4082 struct delayed_work *work = to_delayed_work(w);
4084 if (!mutex_trylock(&slab_mutex))
4085 /* Give up. Setup the next iteration. */
4088 list_for_each_entry(searchp, &slab_caches, list) {
4092 * We only take the node lock if absolutely necessary and we
4093 * have established with reasonable certainty that
4094 * we can do some work if the lock was obtained.
4096 n = get_node(searchp, node);
4098 reap_alien(searchp, n);
4100 drain_array(searchp, n, cpu_cache_get(searchp), 0, node);
4103 * These are racy checks but it does not matter
4104 * if we skip one check or scan twice.
4106 if (time_after(n->next_reap, jiffies))
4109 n->next_reap = jiffies + REAPTIMEOUT_NODE;
4111 drain_array(searchp, n, n->shared, 0, node);
4113 if (n->free_touched)
4114 n->free_touched = 0;
4118 freed = drain_freelist(searchp, n, (n->free_limit +
4119 5 * searchp->num - 1) / (5 * searchp->num));
4120 STATS_ADD_REAPED(searchp, freed);
4126 mutex_unlock(&slab_mutex);
4129 /* Set up the next iteration */
4130 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
4133 #ifdef CONFIG_SLABINFO
4134 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4137 unsigned long active_objs;
4138 unsigned long num_objs;
4139 unsigned long active_slabs = 0;
4140 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4144 struct kmem_cache_node *n;
4148 for_each_kmem_cache_node(cachep, node, n) {
4151 spin_lock_irq(&n->list_lock);
4153 list_for_each_entry(page, &n->slabs_full, lru) {
4154 if (page->active != cachep->num && !error)
4155 error = "slabs_full accounting error";
4156 active_objs += cachep->num;
4159 list_for_each_entry(page, &n->slabs_partial, lru) {
4160 if (page->active == cachep->num && !error)
4161 error = "slabs_partial accounting error";
4162 if (!page->active && !error)
4163 error = "slabs_partial accounting error";
4164 active_objs += page->active;
4167 list_for_each_entry(page, &n->slabs_free, lru) {
4168 if (page->active && !error)
4169 error = "slabs_free accounting error";
4172 free_objects += n->free_objects;
4174 shared_avail += n->shared->avail;
4176 spin_unlock_irq(&n->list_lock);
4178 num_slabs += active_slabs;
4179 num_objs = num_slabs * cachep->num;
4180 if (num_objs - active_objs != free_objects && !error)
4181 error = "free_objects accounting error";
4183 name = cachep->name;
4185 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4187 sinfo->active_objs = active_objs;
4188 sinfo->num_objs = num_objs;
4189 sinfo->active_slabs = active_slabs;
4190 sinfo->num_slabs = num_slabs;
4191 sinfo->shared_avail = shared_avail;
4192 sinfo->limit = cachep->limit;
4193 sinfo->batchcount = cachep->batchcount;
4194 sinfo->shared = cachep->shared;
4195 sinfo->objects_per_slab = cachep->num;
4196 sinfo->cache_order = cachep->gfporder;
4199 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4203 unsigned long high = cachep->high_mark;
4204 unsigned long allocs = cachep->num_allocations;
4205 unsigned long grown = cachep->grown;
4206 unsigned long reaped = cachep->reaped;
4207 unsigned long errors = cachep->errors;
4208 unsigned long max_freeable = cachep->max_freeable;
4209 unsigned long node_allocs = cachep->node_allocs;
4210 unsigned long node_frees = cachep->node_frees;
4211 unsigned long overflows = cachep->node_overflow;
4213 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4214 "%4lu %4lu %4lu %4lu %4lu",
4215 allocs, high, grown,
4216 reaped, errors, max_freeable, node_allocs,
4217 node_frees, overflows);
4221 unsigned long allochit = atomic_read(&cachep->allochit);
4222 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4223 unsigned long freehit = atomic_read(&cachep->freehit);
4224 unsigned long freemiss = atomic_read(&cachep->freemiss);
4226 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4227 allochit, allocmiss, freehit, freemiss);
4232 #define MAX_SLABINFO_WRITE 128
4234 * slabinfo_write - Tuning for the slab allocator
4236 * @buffer: user buffer
4237 * @count: data length
4240 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4241 size_t count, loff_t *ppos)
4243 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4244 int limit, batchcount, shared, res;
4245 struct kmem_cache *cachep;
4247 if (count > MAX_SLABINFO_WRITE)
4249 if (copy_from_user(&kbuf, buffer, count))
4251 kbuf[MAX_SLABINFO_WRITE] = '\0';
4253 tmp = strchr(kbuf, ' ');
4258 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4261 /* Find the cache in the chain of caches. */
4262 mutex_lock(&slab_mutex);
4264 list_for_each_entry(cachep, &slab_caches, list) {
4265 if (!strcmp(cachep->name, kbuf)) {
4266 if (limit < 1 || batchcount < 1 ||
4267 batchcount > limit || shared < 0) {
4270 res = do_tune_cpucache(cachep, limit,
4277 mutex_unlock(&slab_mutex);
4283 #ifdef CONFIG_DEBUG_SLAB_LEAK
4285 static void *leaks_start(struct seq_file *m, loff_t *pos)
4287 mutex_lock(&slab_mutex);
4288 return seq_list_start(&slab_caches, *pos);
4291 static inline int add_caller(unsigned long *n, unsigned long v)
4301 unsigned long *q = p + 2 * i;
4315 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4321 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4329 for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4330 if (get_obj_status(page, i) != OBJECT_ACTIVE)
4333 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4338 static void show_symbol(struct seq_file *m, unsigned long address)
4340 #ifdef CONFIG_KALLSYMS
4341 unsigned long offset, size;
4342 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4344 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4345 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4347 seq_printf(m, " [%s]", modname);
4351 seq_printf(m, "%p", (void *)address);
4354 static int leaks_show(struct seq_file *m, void *p)
4356 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4358 struct kmem_cache_node *n;
4360 unsigned long *x = m->private;
4364 if (!(cachep->flags & SLAB_STORE_USER))
4366 if (!(cachep->flags & SLAB_RED_ZONE))
4369 /* OK, we can do it */
4373 for_each_kmem_cache_node(cachep, node, n) {
4376 spin_lock_irq(&n->list_lock);
4378 list_for_each_entry(page, &n->slabs_full, lru)
4379 handle_slab(x, cachep, page);
4380 list_for_each_entry(page, &n->slabs_partial, lru)
4381 handle_slab(x, cachep, page);
4382 spin_unlock_irq(&n->list_lock);
4384 name = cachep->name;
4386 /* Increase the buffer size */
4387 mutex_unlock(&slab_mutex);
4388 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4390 /* Too bad, we are really out */
4392 mutex_lock(&slab_mutex);
4395 *(unsigned long *)m->private = x[0] * 2;
4397 mutex_lock(&slab_mutex);
4398 /* Now make sure this entry will be retried */
4402 for (i = 0; i < x[1]; i++) {
4403 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4404 show_symbol(m, x[2*i+2]);
4411 static const struct seq_operations slabstats_op = {
4412 .start = leaks_start,
4418 static int slabstats_open(struct inode *inode, struct file *file)
4420 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4423 ret = seq_open(file, &slabstats_op);
4425 struct seq_file *m = file->private_data;
4426 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4435 static const struct file_operations proc_slabstats_operations = {
4436 .open = slabstats_open,
4438 .llseek = seq_lseek,
4439 .release = seq_release_private,
4443 static int __init slab_proc_init(void)
4445 #ifdef CONFIG_DEBUG_SLAB_LEAK
4446 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4450 module_init(slab_proc_init);
4454 * ksize - get the actual amount of memory allocated for a given object
4455 * @objp: Pointer to the object
4457 * kmalloc may internally round up allocations and return more memory
4458 * than requested. ksize() can be used to determine the actual amount of
4459 * memory allocated. The caller may use this additional memory, even though
4460 * a smaller amount of memory was initially specified with the kmalloc call.
4461 * The caller must guarantee that objp points to a valid object previously
4462 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4463 * must not be freed during the duration of the call.
4465 size_t ksize(const void *objp)
4468 if (unlikely(objp == ZERO_SIZE_PTR))
4471 return virt_to_cache(objp)->object_size;
4473 EXPORT_SYMBOL(ksize);