usb: renesas_usbhs: disable TX IRQ before starting TX DMAC transfer
[linux/fpc-iii.git] / mm / slab.c
blob084985404fecf6efe185918ec11b29e0bac54469
1 /*
2 * linux/mm/slab.c
3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
14 * An implementation of the Slab Allocator as described in outline in;
15 * UNIX Internals: The New Frontiers by Uresh Vahalia
16 * Pub: Prentice Hall ISBN 0-13-101908-2
17 * or with a little more detail in;
18 * The Slab Allocator: An Object-Caching Kernel Memory Allocator
19 * Jeff Bonwick (Sun Microsystems).
20 * Presented at: USENIX Summer 1994 Technical Conference
22 * The memory is organized in caches, one cache for each object type.
23 * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24 * Each cache consists out of many slabs (they are small (usually one
25 * page long) and always contiguous), and each slab contains multiple
26 * initialized objects.
28 * This means, that your constructor is used only for newly allocated
29 * slabs and you must pass objects with the same initializations to
30 * kmem_cache_free.
32 * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33 * normal). If you need a special memory type, then must create a new
34 * cache for that memory type.
36 * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37 * full slabs with 0 free objects
38 * partial slabs
39 * empty slabs with no allocated objects
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
44 * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45 * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
47 * Each cache has a short per-cpu head array, most allocs
48 * and frees go into that array, and if that array overflows, then 1/2
49 * of the entries in the array are given back into the global cache.
50 * The head array is strictly LIFO and should improve the cache hit rates.
51 * On SMP, it additionally reduces the spinlock operations.
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
56 * SMP synchronization:
57 * constructors and destructors are called without any locking.
58 * Several members in struct kmem_cache and struct slab never change, they
59 * are accessed without any locking.
60 * The per-cpu arrays are never accessed from the wrong cpu, no locking,
61 * and local interrupts are disabled so slab code is preempt-safe.
62 * The non-constant members are protected with a per-cache irq spinlock.
64 * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65 * in 2000 - many ideas in the current implementation are derived from
66 * his patch.
68 * Further notes from the original documentation:
70 * 11 April '97. Started multi-threading - markhe
71 * The global cache-chain is protected by the mutex '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>
90 #include <linux/mm.h>
91 #include <linux/poison.h>
92 #include <linux/swap.h>
93 #include <linux/cache.h>
94 #include <linux/interrupt.h>
95 #include <linux/init.h>
96 #include <linux/compiler.h>
97 #include <linux/cpuset.h>
98 #include <linux/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"
130 #include "slab.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
143 #define DEBUG 1
144 #define STATS 1
145 #define FORCED_DEBUG 1
146 #else
147 #define DEBUG 0
148 #define STATS 0
149 #define FORCED_DEBUG 0
150 #endif
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
158 #endif
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;
165 #else
166 typedef unsigned short freelist_idx_t;
167 #endif
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
173 * swap
175 static bool pfmemalloc_active __read_mostly;
178 * struct array_cache
180 * Purpose:
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
186 * footprint.
189 struct array_cache {
190 unsigned int avail;
191 unsigned int limit;
192 unsigned int batchcount;
193 unsigned int touched;
194 spinlock_t lock;
195 void *entry[]; /*
196 * Must have this definition in here for the proper
197 * alignment of array_cache. Also simplifies accessing
198 * the entries.
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
206 #define SLAB_OBJ_PFMEMALLOC 1
207 static inline bool is_obj_pfmemalloc(void *objp)
209 return (unsigned long)objp & SLAB_OBJ_PFMEMALLOC;
212 static inline void set_obj_pfmemalloc(void **objp)
214 *objp = (void *)((unsigned long)*objp | SLAB_OBJ_PFMEMALLOC);
215 return;
218 static inline void clear_obj_pfmemalloc(void **objp)
220 *objp = (void *)((unsigned long)*objp & ~SLAB_OBJ_PFMEMALLOC);
224 * bootstrap: The caches do not work without cpuarrays anymore, but the
225 * cpuarrays are allocated from the generic caches...
227 #define BOOT_CPUCACHE_ENTRIES 1
228 struct arraycache_init {
229 struct array_cache cache;
230 void *entries[BOOT_CPUCACHE_ENTRIES];
234 * Need this for bootstrapping a per node allocator.
236 #define NUM_INIT_LISTS (3 * MAX_NUMNODES)
237 static struct kmem_cache_node __initdata init_kmem_cache_node[NUM_INIT_LISTS];
238 #define CACHE_CACHE 0
239 #define SIZE_AC MAX_NUMNODES
240 #define SIZE_NODE (2 * MAX_NUMNODES)
242 static int drain_freelist(struct kmem_cache *cache,
243 struct kmem_cache_node *n, int tofree);
244 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
245 int node);
246 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
247 static void cache_reap(struct work_struct *unused);
249 static int slab_early_init = 1;
251 #define INDEX_AC kmalloc_index(sizeof(struct arraycache_init))
252 #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
254 static void kmem_cache_node_init(struct kmem_cache_node *parent)
256 INIT_LIST_HEAD(&parent->slabs_full);
257 INIT_LIST_HEAD(&parent->slabs_partial);
258 INIT_LIST_HEAD(&parent->slabs_free);
259 parent->shared = NULL;
260 parent->alien = NULL;
261 parent->colour_next = 0;
262 spin_lock_init(&parent->list_lock);
263 parent->free_objects = 0;
264 parent->free_touched = 0;
267 #define MAKE_LIST(cachep, listp, slab, nodeid) \
268 do { \
269 INIT_LIST_HEAD(listp); \
270 list_splice(&(cachep->node[nodeid]->slab), listp); \
271 } while (0)
273 #define MAKE_ALL_LISTS(cachep, ptr, nodeid) \
274 do { \
275 MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid); \
276 MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
277 MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid); \
278 } while (0)
280 #define CFLGS_OFF_SLAB (0x80000000UL)
281 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
282 #define OFF_SLAB_MIN_SIZE (max_t(size_t, PAGE_SIZE >> 5, KMALLOC_MIN_SIZE + 1))
284 #define BATCHREFILL_LIMIT 16
286 * Optimization question: fewer reaps means less probability for unnessary
287 * cpucache drain/refill cycles.
289 * OTOH the cpuarrays can contain lots of objects,
290 * which could lock up otherwise freeable slabs.
292 #define REAPTIMEOUT_AC (2*HZ)
293 #define REAPTIMEOUT_NODE (4*HZ)
295 #if STATS
296 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
297 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
298 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
299 #define STATS_INC_GROWN(x) ((x)->grown++)
300 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
301 #define STATS_SET_HIGH(x) \
302 do { \
303 if ((x)->num_active > (x)->high_mark) \
304 (x)->high_mark = (x)->num_active; \
305 } while (0)
306 #define STATS_INC_ERR(x) ((x)->errors++)
307 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
308 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
309 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
310 #define STATS_SET_FREEABLE(x, i) \
311 do { \
312 if ((x)->max_freeable < i) \
313 (x)->max_freeable = i; \
314 } while (0)
315 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
316 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
317 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
318 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
319 #else
320 #define STATS_INC_ACTIVE(x) do { } while (0)
321 #define STATS_DEC_ACTIVE(x) do { } while (0)
322 #define STATS_INC_ALLOCED(x) do { } while (0)
323 #define STATS_INC_GROWN(x) do { } while (0)
324 #define STATS_ADD_REAPED(x,y) do { (void)(y); } while (0)
325 #define STATS_SET_HIGH(x) do { } while (0)
326 #define STATS_INC_ERR(x) do { } while (0)
327 #define STATS_INC_NODEALLOCS(x) do { } while (0)
328 #define STATS_INC_NODEFREES(x) do { } while (0)
329 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
330 #define STATS_SET_FREEABLE(x, i) do { } while (0)
331 #define STATS_INC_ALLOCHIT(x) do { } while (0)
332 #define STATS_INC_ALLOCMISS(x) do { } while (0)
333 #define STATS_INC_FREEHIT(x) do { } while (0)
334 #define STATS_INC_FREEMISS(x) do { } while (0)
335 #endif
337 #if DEBUG
340 * memory layout of objects:
341 * 0 : objp
342 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
343 * the end of an object is aligned with the end of the real
344 * allocation. Catches writes behind the end of the allocation.
345 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
346 * redzone word.
347 * cachep->obj_offset: The real object.
348 * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
349 * cachep->size - 1* BYTES_PER_WORD: last caller address
350 * [BYTES_PER_WORD long]
352 static int obj_offset(struct kmem_cache *cachep)
354 return cachep->obj_offset;
357 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
359 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
360 return (unsigned long long*) (objp + obj_offset(cachep) -
361 sizeof(unsigned long long));
364 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
366 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
367 if (cachep->flags & SLAB_STORE_USER)
368 return (unsigned long long *)(objp + cachep->size -
369 sizeof(unsigned long long) -
370 REDZONE_ALIGN);
371 return (unsigned long long *) (objp + cachep->size -
372 sizeof(unsigned long long));
375 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
377 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
378 return (void **)(objp + cachep->size - BYTES_PER_WORD);
381 #else
383 #define obj_offset(x) 0
384 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
385 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
386 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
388 #endif
390 #define OBJECT_FREE (0)
391 #define OBJECT_ACTIVE (1)
393 #ifdef CONFIG_DEBUG_SLAB_LEAK
395 static void set_obj_status(struct page *page, int idx, int val)
397 int freelist_size;
398 char *status;
399 struct kmem_cache *cachep = page->slab_cache;
401 freelist_size = cachep->num * sizeof(freelist_idx_t);
402 status = (char *)page->freelist + freelist_size;
403 status[idx] = val;
406 static inline unsigned int get_obj_status(struct page *page, int idx)
408 int freelist_size;
409 char *status;
410 struct kmem_cache *cachep = page->slab_cache;
412 freelist_size = cachep->num * sizeof(freelist_idx_t);
413 status = (char *)page->freelist + freelist_size;
415 return status[idx];
418 #else
419 static inline void set_obj_status(struct page *page, int idx, int val) {}
421 #endif
424 * Do not go above this order unless 0 objects fit into the slab or
425 * overridden on the command line.
427 #define SLAB_MAX_ORDER_HI 1
428 #define SLAB_MAX_ORDER_LO 0
429 static int slab_max_order = SLAB_MAX_ORDER_LO;
430 static bool slab_max_order_set __initdata;
432 static inline struct kmem_cache *virt_to_cache(const void *obj)
434 struct page *page = virt_to_head_page(obj);
435 return page->slab_cache;
438 static inline void *index_to_obj(struct kmem_cache *cache, struct page *page,
439 unsigned int idx)
441 return page->s_mem + cache->size * idx;
445 * We want to avoid an expensive divide : (offset / cache->size)
446 * Using the fact that size is a constant for a particular cache,
447 * we can replace (offset / cache->size) by
448 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
450 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
451 const struct page *page, void *obj)
453 u32 offset = (obj - page->s_mem);
454 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
457 static struct arraycache_init initarray_generic =
458 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
460 /* internal cache of cache description objs */
461 static struct kmem_cache kmem_cache_boot = {
462 .batchcount = 1,
463 .limit = BOOT_CPUCACHE_ENTRIES,
464 .shared = 1,
465 .size = sizeof(struct kmem_cache),
466 .name = "kmem_cache",
469 #define BAD_ALIEN_MAGIC 0x01020304ul
471 #ifdef CONFIG_LOCKDEP
474 * Slab sometimes uses the kmalloc slabs to store the slab headers
475 * for other slabs "off slab".
476 * The locking for this is tricky in that it nests within the locks
477 * of all other slabs in a few places; to deal with this special
478 * locking we put on-slab caches into a separate lock-class.
480 * We set lock class for alien array caches which are up during init.
481 * The lock annotation will be lost if all cpus of a node goes down and
482 * then comes back up during hotplug
484 static struct lock_class_key on_slab_l3_key;
485 static struct lock_class_key on_slab_alc_key;
487 static struct lock_class_key debugobj_l3_key;
488 static struct lock_class_key debugobj_alc_key;
490 static void slab_set_lock_classes(struct kmem_cache *cachep,
491 struct lock_class_key *l3_key, struct lock_class_key *alc_key,
492 int q)
494 struct array_cache **alc;
495 struct kmem_cache_node *n;
496 int r;
498 n = cachep->node[q];
499 if (!n)
500 return;
502 lockdep_set_class(&n->list_lock, l3_key);
503 alc = n->alien;
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)
512 return;
513 for_each_node(r) {
514 if (alc[r])
515 lockdep_set_class(&alc[r]->lock, alc_key);
519 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
521 slab_set_lock_classes(cachep, &debugobj_l3_key, &debugobj_alc_key, node);
524 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
526 int node;
528 for_each_online_node(node)
529 slab_set_debugobj_lock_classes_node(cachep, node);
532 static void init_node_lock_keys(int q)
534 int i;
536 if (slab_state < UP)
537 return;
539 for (i = 1; i <= KMALLOC_SHIFT_HIGH; i++) {
540 struct kmem_cache_node *n;
541 struct kmem_cache *cache = kmalloc_caches[i];
543 if (!cache)
544 continue;
546 n = cache->node[q];
547 if (!n || OFF_SLAB(cache))
548 continue;
550 slab_set_lock_classes(cache, &on_slab_l3_key,
551 &on_slab_alc_key, q);
555 static void on_slab_lock_classes_node(struct kmem_cache *cachep, int q)
557 if (!cachep->node[q])
558 return;
560 slab_set_lock_classes(cachep, &on_slab_l3_key,
561 &on_slab_alc_key, q);
564 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
566 int node;
568 VM_BUG_ON(OFF_SLAB(cachep));
569 for_each_node(node)
570 on_slab_lock_classes_node(cachep, node);
573 static inline void init_lock_keys(void)
575 int node;
577 for_each_node(node)
578 init_node_lock_keys(node);
580 #else
581 static void init_node_lock_keys(int q)
585 static inline void init_lock_keys(void)
589 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
593 static inline void on_slab_lock_classes_node(struct kmem_cache *cachep, int node)
597 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep, int node)
601 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
604 #endif
606 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
608 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
610 return cachep->array[smp_processor_id()];
613 static size_t calculate_freelist_size(int nr_objs, size_t align)
615 size_t freelist_size;
617 freelist_size = nr_objs * sizeof(freelist_idx_t);
618 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
619 freelist_size += nr_objs * sizeof(char);
621 if (align)
622 freelist_size = ALIGN(freelist_size, align);
624 return freelist_size;
627 static int calculate_nr_objs(size_t slab_size, size_t buffer_size,
628 size_t idx_size, size_t align)
630 int nr_objs;
631 size_t remained_size;
632 size_t freelist_size;
633 int extra_space = 0;
635 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
636 extra_space = sizeof(char);
638 * Ignore padding for the initial guess. The padding
639 * is at most @align-1 bytes, and @buffer_size is at
640 * least @align. In the worst case, this result will
641 * be one greater than the number of objects that fit
642 * into the memory allocation when taking the padding
643 * into account.
645 nr_objs = slab_size / (buffer_size + idx_size + extra_space);
648 * This calculated number will be either the right
649 * amount, or one greater than what we want.
651 remained_size = slab_size - nr_objs * buffer_size;
652 freelist_size = calculate_freelist_size(nr_objs, align);
653 if (remained_size < freelist_size)
654 nr_objs--;
656 return nr_objs;
660 * Calculate the number of objects and left-over bytes for a given buffer size.
662 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
663 size_t align, int flags, size_t *left_over,
664 unsigned int *num)
666 int nr_objs;
667 size_t mgmt_size;
668 size_t slab_size = PAGE_SIZE << gfporder;
671 * The slab management structure can be either off the slab or
672 * on it. For the latter case, the memory allocated for a
673 * slab is used for:
675 * - One unsigned int for each object
676 * - Padding to respect alignment of @align
677 * - @buffer_size bytes for each object
679 * If the slab management structure is off the slab, then the
680 * alignment will already be calculated into the size. Because
681 * the slabs are all pages aligned, the objects will be at the
682 * correct alignment when allocated.
684 if (flags & CFLGS_OFF_SLAB) {
685 mgmt_size = 0;
686 nr_objs = slab_size / buffer_size;
688 } else {
689 nr_objs = calculate_nr_objs(slab_size, buffer_size,
690 sizeof(freelist_idx_t), align);
691 mgmt_size = calculate_freelist_size(nr_objs, align);
693 *num = nr_objs;
694 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
697 #if DEBUG
698 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
700 static void __slab_error(const char *function, struct kmem_cache *cachep,
701 char *msg)
703 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
704 function, cachep->name, msg);
705 dump_stack();
706 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
708 #endif
711 * By default on NUMA we use alien caches to stage the freeing of
712 * objects allocated from other nodes. This causes massive memory
713 * inefficiencies when using fake NUMA setup to split memory into a
714 * large number of small nodes, so it can be disabled on the command
715 * line
718 static int use_alien_caches __read_mostly = 1;
719 static int __init noaliencache_setup(char *s)
721 use_alien_caches = 0;
722 return 1;
724 __setup("noaliencache", noaliencache_setup);
726 static int __init slab_max_order_setup(char *str)
728 get_option(&str, &slab_max_order);
729 slab_max_order = slab_max_order < 0 ? 0 :
730 min(slab_max_order, MAX_ORDER - 1);
731 slab_max_order_set = true;
733 return 1;
735 __setup("slab_max_order=", slab_max_order_setup);
737 #ifdef CONFIG_NUMA
739 * Special reaping functions for NUMA systems called from cache_reap().
740 * These take care of doing round robin flushing of alien caches (containing
741 * objects freed on different nodes from which they were allocated) and the
742 * flushing of remote pcps by calling drain_node_pages.
744 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
746 static void init_reap_node(int cpu)
748 int node;
750 node = next_node(cpu_to_mem(cpu), node_online_map);
751 if (node == MAX_NUMNODES)
752 node = first_node(node_online_map);
754 per_cpu(slab_reap_node, cpu) = node;
757 static void next_reap_node(void)
759 int node = __this_cpu_read(slab_reap_node);
761 node = next_node(node, node_online_map);
762 if (unlikely(node >= MAX_NUMNODES))
763 node = first_node(node_online_map);
764 __this_cpu_write(slab_reap_node, node);
767 #else
768 #define init_reap_node(cpu) do { } while (0)
769 #define next_reap_node(void) do { } while (0)
770 #endif
773 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
774 * via the workqueue/eventd.
775 * Add the CPU number into the expiration time to minimize the possibility of
776 * the CPUs getting into lockstep and contending for the global cache chain
777 * lock.
779 static void start_cpu_timer(int cpu)
781 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
784 * When this gets called from do_initcalls via cpucache_init(),
785 * init_workqueues() has already run, so keventd will be setup
786 * at that time.
788 if (keventd_up() && reap_work->work.func == NULL) {
789 init_reap_node(cpu);
790 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
791 schedule_delayed_work_on(cpu, reap_work,
792 __round_jiffies_relative(HZ, cpu));
796 static struct array_cache *alloc_arraycache(int node, int entries,
797 int batchcount, gfp_t gfp)
799 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
800 struct array_cache *nc = NULL;
802 nc = kmalloc_node(memsize, gfp, node);
804 * The array_cache structures contain pointers to free object.
805 * However, when such objects are allocated or transferred to another
806 * cache the pointers are not cleared and they could be counted as
807 * valid references during a kmemleak scan. Therefore, kmemleak must
808 * not scan such objects.
810 kmemleak_no_scan(nc);
811 if (nc) {
812 nc->avail = 0;
813 nc->limit = entries;
814 nc->batchcount = batchcount;
815 nc->touched = 0;
816 spin_lock_init(&nc->lock);
818 return nc;
821 static inline bool is_slab_pfmemalloc(struct page *page)
823 return PageSlabPfmemalloc(page);
826 /* Clears pfmemalloc_active if no slabs have pfmalloc set */
827 static void recheck_pfmemalloc_active(struct kmem_cache *cachep,
828 struct array_cache *ac)
830 struct kmem_cache_node *n = cachep->node[numa_mem_id()];
831 struct page *page;
832 unsigned long flags;
834 if (!pfmemalloc_active)
835 return;
837 spin_lock_irqsave(&n->list_lock, flags);
838 list_for_each_entry(page, &n->slabs_full, lru)
839 if (is_slab_pfmemalloc(page))
840 goto out;
842 list_for_each_entry(page, &n->slabs_partial, lru)
843 if (is_slab_pfmemalloc(page))
844 goto out;
846 list_for_each_entry(page, &n->slabs_free, lru)
847 if (is_slab_pfmemalloc(page))
848 goto out;
850 pfmemalloc_active = false;
851 out:
852 spin_unlock_irqrestore(&n->list_lock, flags);
855 static void *__ac_get_obj(struct kmem_cache *cachep, struct array_cache *ac,
856 gfp_t flags, bool force_refill)
858 int i;
859 void *objp = ac->entry[--ac->avail];
861 /* Ensure the caller is allowed to use objects from PFMEMALLOC slab */
862 if (unlikely(is_obj_pfmemalloc(objp))) {
863 struct kmem_cache_node *n;
865 if (gfp_pfmemalloc_allowed(flags)) {
866 clear_obj_pfmemalloc(&objp);
867 return objp;
870 /* The caller cannot use PFMEMALLOC objects, find another one */
871 for (i = 0; i < ac->avail; i++) {
872 /* If a !PFMEMALLOC object is found, swap them */
873 if (!is_obj_pfmemalloc(ac->entry[i])) {
874 objp = ac->entry[i];
875 ac->entry[i] = ac->entry[ac->avail];
876 ac->entry[ac->avail] = objp;
877 return objp;
882 * If there are empty slabs on the slabs_free list and we are
883 * being forced to refill the cache, mark this one !pfmemalloc.
885 n = cachep->node[numa_mem_id()];
886 if (!list_empty(&n->slabs_free) && force_refill) {
887 struct page *page = virt_to_head_page(objp);
888 ClearPageSlabPfmemalloc(page);
889 clear_obj_pfmemalloc(&objp);
890 recheck_pfmemalloc_active(cachep, ac);
891 return objp;
894 /* No !PFMEMALLOC objects available */
895 ac->avail++;
896 objp = NULL;
899 return objp;
902 static inline void *ac_get_obj(struct kmem_cache *cachep,
903 struct array_cache *ac, gfp_t flags, bool force_refill)
905 void *objp;
907 if (unlikely(sk_memalloc_socks()))
908 objp = __ac_get_obj(cachep, ac, flags, force_refill);
909 else
910 objp = ac->entry[--ac->avail];
912 return objp;
915 static void *__ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
916 void *objp)
918 if (unlikely(pfmemalloc_active)) {
919 /* Some pfmemalloc slabs exist, check if this is one */
920 struct page *page = virt_to_head_page(objp);
921 if (PageSlabPfmemalloc(page))
922 set_obj_pfmemalloc(&objp);
925 return objp;
928 static inline void ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
929 void *objp)
931 if (unlikely(sk_memalloc_socks()))
932 objp = __ac_put_obj(cachep, ac, objp);
934 ac->entry[ac->avail++] = objp;
938 * Transfer objects in one arraycache to another.
939 * Locking must be handled by the caller.
941 * Return the number of entries transferred.
943 static int transfer_objects(struct array_cache *to,
944 struct array_cache *from, unsigned int max)
946 /* Figure out how many entries to transfer */
947 int nr = min3(from->avail, max, to->limit - to->avail);
949 if (!nr)
950 return 0;
952 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
953 sizeof(void *) *nr);
955 from->avail -= nr;
956 to->avail += nr;
957 return nr;
960 #ifndef CONFIG_NUMA
962 #define drain_alien_cache(cachep, alien) do { } while (0)
963 #define reap_alien(cachep, n) do { } while (0)
965 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
967 return (struct array_cache **)BAD_ALIEN_MAGIC;
970 static inline void free_alien_cache(struct array_cache **ac_ptr)
974 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
976 return 0;
979 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
980 gfp_t flags)
982 return NULL;
985 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
986 gfp_t flags, int nodeid)
988 return NULL;
991 #else /* CONFIG_NUMA */
993 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
994 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
996 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
998 struct array_cache **ac_ptr;
999 int memsize = sizeof(void *) * nr_node_ids;
1000 int i;
1002 if (limit > 1)
1003 limit = 12;
1004 ac_ptr = kzalloc_node(memsize, gfp, node);
1005 if (ac_ptr) {
1006 for_each_node(i) {
1007 if (i == node || !node_online(i))
1008 continue;
1009 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
1010 if (!ac_ptr[i]) {
1011 for (i--; i >= 0; i--)
1012 kfree(ac_ptr[i]);
1013 kfree(ac_ptr);
1014 return NULL;
1018 return ac_ptr;
1021 static void free_alien_cache(struct array_cache **ac_ptr)
1023 int i;
1025 if (!ac_ptr)
1026 return;
1027 for_each_node(i)
1028 kfree(ac_ptr[i]);
1029 kfree(ac_ptr);
1032 static void __drain_alien_cache(struct kmem_cache *cachep,
1033 struct array_cache *ac, int node)
1035 struct kmem_cache_node *n = cachep->node[node];
1037 if (ac->avail) {
1038 spin_lock(&n->list_lock);
1040 * Stuff objects into the remote nodes shared array first.
1041 * That way we could avoid the overhead of putting the objects
1042 * into the free lists and getting them back later.
1044 if (n->shared)
1045 transfer_objects(n->shared, ac, ac->limit);
1047 free_block(cachep, ac->entry, ac->avail, node);
1048 ac->avail = 0;
1049 spin_unlock(&n->list_lock);
1054 * Called from cache_reap() to regularly drain alien caches round robin.
1056 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
1058 int node = __this_cpu_read(slab_reap_node);
1060 if (n->alien) {
1061 struct array_cache *ac = n->alien[node];
1063 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1064 __drain_alien_cache(cachep, ac, node);
1065 spin_unlock_irq(&ac->lock);
1070 static void drain_alien_cache(struct kmem_cache *cachep,
1071 struct array_cache **alien)
1073 int i = 0;
1074 struct array_cache *ac;
1075 unsigned long flags;
1077 for_each_online_node(i) {
1078 ac = alien[i];
1079 if (ac) {
1080 spin_lock_irqsave(&ac->lock, flags);
1081 __drain_alien_cache(cachep, ac, i);
1082 spin_unlock_irqrestore(&ac->lock, flags);
1087 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1089 int nodeid = page_to_nid(virt_to_page(objp));
1090 struct kmem_cache_node *n;
1091 struct array_cache *alien = NULL;
1092 int node;
1094 node = numa_mem_id();
1097 * Make sure we are not freeing a object from another node to the array
1098 * cache on this cpu.
1100 if (likely(nodeid == node))
1101 return 0;
1103 n = cachep->node[node];
1104 STATS_INC_NODEFREES(cachep);
1105 if (n->alien && n->alien[nodeid]) {
1106 alien = n->alien[nodeid];
1107 spin_lock(&alien->lock);
1108 if (unlikely(alien->avail == alien->limit)) {
1109 STATS_INC_ACOVERFLOW(cachep);
1110 __drain_alien_cache(cachep, alien, nodeid);
1112 ac_put_obj(cachep, alien, objp);
1113 spin_unlock(&alien->lock);
1114 } else {
1115 spin_lock(&(cachep->node[nodeid])->list_lock);
1116 free_block(cachep, &objp, 1, nodeid);
1117 spin_unlock(&(cachep->node[nodeid])->list_lock);
1119 return 1;
1121 #endif
1124 * Allocates and initializes node for a node on each slab cache, used for
1125 * either memory or cpu hotplug. If memory is being hot-added, the kmem_cache_node
1126 * will be allocated off-node since memory is not yet online for the new node.
1127 * When hotplugging memory or a cpu, existing node are not replaced if
1128 * already in use.
1130 * Must hold slab_mutex.
1132 static int init_cache_node_node(int node)
1134 struct kmem_cache *cachep;
1135 struct kmem_cache_node *n;
1136 const int memsize = sizeof(struct kmem_cache_node);
1138 list_for_each_entry(cachep, &slab_caches, list) {
1140 * Set up the kmem_cache_node for cpu before we can
1141 * begin anything. Make sure some other cpu on this
1142 * node has not already allocated this
1144 if (!cachep->node[node]) {
1145 n = kmalloc_node(memsize, GFP_KERNEL, node);
1146 if (!n)
1147 return -ENOMEM;
1148 kmem_cache_node_init(n);
1149 n->next_reap = jiffies + REAPTIMEOUT_NODE +
1150 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1153 * The kmem_cache_nodes don't come and go as CPUs
1154 * come and go. slab_mutex is sufficient
1155 * protection here.
1157 cachep->node[node] = n;
1160 spin_lock_irq(&cachep->node[node]->list_lock);
1161 cachep->node[node]->free_limit =
1162 (1 + nr_cpus_node(node)) *
1163 cachep->batchcount + cachep->num;
1164 spin_unlock_irq(&cachep->node[node]->list_lock);
1166 return 0;
1169 static inline int slabs_tofree(struct kmem_cache *cachep,
1170 struct kmem_cache_node *n)
1172 return (n->free_objects + cachep->num - 1) / cachep->num;
1175 static void cpuup_canceled(long cpu)
1177 struct kmem_cache *cachep;
1178 struct kmem_cache_node *n = NULL;
1179 int node = cpu_to_mem(cpu);
1180 const struct cpumask *mask = cpumask_of_node(node);
1182 list_for_each_entry(cachep, &slab_caches, list) {
1183 struct array_cache *nc;
1184 struct array_cache *shared;
1185 struct array_cache **alien;
1187 /* cpu is dead; no one can alloc from it. */
1188 nc = cachep->array[cpu];
1189 cachep->array[cpu] = NULL;
1190 n = cachep->node[node];
1192 if (!n)
1193 goto free_array_cache;
1195 spin_lock_irq(&n->list_lock);
1197 /* Free limit for this kmem_cache_node */
1198 n->free_limit -= cachep->batchcount;
1199 if (nc)
1200 free_block(cachep, nc->entry, nc->avail, node);
1202 if (!cpumask_empty(mask)) {
1203 spin_unlock_irq(&n->list_lock);
1204 goto free_array_cache;
1207 shared = n->shared;
1208 if (shared) {
1209 free_block(cachep, shared->entry,
1210 shared->avail, node);
1211 n->shared = NULL;
1214 alien = n->alien;
1215 n->alien = NULL;
1217 spin_unlock_irq(&n->list_lock);
1219 kfree(shared);
1220 if (alien) {
1221 drain_alien_cache(cachep, alien);
1222 free_alien_cache(alien);
1224 free_array_cache:
1225 kfree(nc);
1228 * In the previous loop, all the objects were freed to
1229 * the respective cache's slabs, now we can go ahead and
1230 * shrink each nodelist to its limit.
1232 list_for_each_entry(cachep, &slab_caches, list) {
1233 n = cachep->node[node];
1234 if (!n)
1235 continue;
1236 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1240 static int cpuup_prepare(long cpu)
1242 struct kmem_cache *cachep;
1243 struct kmem_cache_node *n = NULL;
1244 int node = cpu_to_mem(cpu);
1245 int err;
1248 * We need to do this right in the beginning since
1249 * alloc_arraycache's are going to use this list.
1250 * kmalloc_node allows us to add the slab to the right
1251 * kmem_cache_node and not this cpu's kmem_cache_node
1253 err = init_cache_node_node(node);
1254 if (err < 0)
1255 goto bad;
1258 * Now we can go ahead with allocating the shared arrays and
1259 * array caches
1261 list_for_each_entry(cachep, &slab_caches, list) {
1262 struct array_cache *nc;
1263 struct array_cache *shared = NULL;
1264 struct array_cache **alien = NULL;
1266 nc = alloc_arraycache(node, cachep->limit,
1267 cachep->batchcount, GFP_KERNEL);
1268 if (!nc)
1269 goto bad;
1270 if (cachep->shared) {
1271 shared = alloc_arraycache(node,
1272 cachep->shared * cachep->batchcount,
1273 0xbaadf00d, GFP_KERNEL);
1274 if (!shared) {
1275 kfree(nc);
1276 goto bad;
1279 if (use_alien_caches) {
1280 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1281 if (!alien) {
1282 kfree(shared);
1283 kfree(nc);
1284 goto bad;
1287 cachep->array[cpu] = nc;
1288 n = cachep->node[node];
1289 BUG_ON(!n);
1291 spin_lock_irq(&n->list_lock);
1292 if (!n->shared) {
1294 * We are serialised from CPU_DEAD or
1295 * CPU_UP_CANCELLED by the cpucontrol lock
1297 n->shared = shared;
1298 shared = NULL;
1300 #ifdef CONFIG_NUMA
1301 if (!n->alien) {
1302 n->alien = alien;
1303 alien = NULL;
1305 #endif
1306 spin_unlock_irq(&n->list_lock);
1307 kfree(shared);
1308 free_alien_cache(alien);
1309 if (cachep->flags & SLAB_DEBUG_OBJECTS)
1310 slab_set_debugobj_lock_classes_node(cachep, node);
1311 else if (!OFF_SLAB(cachep) &&
1312 !(cachep->flags & SLAB_DESTROY_BY_RCU))
1313 on_slab_lock_classes_node(cachep, node);
1315 init_node_lock_keys(node);
1317 return 0;
1318 bad:
1319 cpuup_canceled(cpu);
1320 return -ENOMEM;
1323 static int cpuup_callback(struct notifier_block *nfb,
1324 unsigned long action, void *hcpu)
1326 long cpu = (long)hcpu;
1327 int err = 0;
1329 switch (action) {
1330 case CPU_UP_PREPARE:
1331 case CPU_UP_PREPARE_FROZEN:
1332 mutex_lock(&slab_mutex);
1333 err = cpuup_prepare(cpu);
1334 mutex_unlock(&slab_mutex);
1335 break;
1336 case CPU_ONLINE:
1337 case CPU_ONLINE_FROZEN:
1338 start_cpu_timer(cpu);
1339 break;
1340 #ifdef CONFIG_HOTPLUG_CPU
1341 case CPU_DOWN_PREPARE:
1342 case CPU_DOWN_PREPARE_FROZEN:
1344 * Shutdown cache reaper. Note that the slab_mutex is
1345 * held so that if cache_reap() is invoked it cannot do
1346 * anything expensive but will only modify reap_work
1347 * and reschedule the timer.
1349 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1350 /* Now the cache_reaper is guaranteed to be not running. */
1351 per_cpu(slab_reap_work, cpu).work.func = NULL;
1352 break;
1353 case CPU_DOWN_FAILED:
1354 case CPU_DOWN_FAILED_FROZEN:
1355 start_cpu_timer(cpu);
1356 break;
1357 case CPU_DEAD:
1358 case CPU_DEAD_FROZEN:
1360 * Even if all the cpus of a node are down, we don't free the
1361 * kmem_cache_node of any cache. This to avoid a race between
1362 * cpu_down, and a kmalloc allocation from another cpu for
1363 * memory from the node of the cpu going down. The node
1364 * structure is usually allocated from kmem_cache_create() and
1365 * gets destroyed at kmem_cache_destroy().
1367 /* fall through */
1368 #endif
1369 case CPU_UP_CANCELED:
1370 case CPU_UP_CANCELED_FROZEN:
1371 mutex_lock(&slab_mutex);
1372 cpuup_canceled(cpu);
1373 mutex_unlock(&slab_mutex);
1374 break;
1376 return notifier_from_errno(err);
1379 static struct notifier_block cpucache_notifier = {
1380 &cpuup_callback, NULL, 0
1383 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1385 * Drains freelist for a node on each slab cache, used for memory hot-remove.
1386 * Returns -EBUSY if all objects cannot be drained so that the node is not
1387 * removed.
1389 * Must hold slab_mutex.
1391 static int __meminit drain_cache_node_node(int node)
1393 struct kmem_cache *cachep;
1394 int ret = 0;
1396 list_for_each_entry(cachep, &slab_caches, list) {
1397 struct kmem_cache_node *n;
1399 n = cachep->node[node];
1400 if (!n)
1401 continue;
1403 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1405 if (!list_empty(&n->slabs_full) ||
1406 !list_empty(&n->slabs_partial)) {
1407 ret = -EBUSY;
1408 break;
1411 return ret;
1414 static int __meminit slab_memory_callback(struct notifier_block *self,
1415 unsigned long action, void *arg)
1417 struct memory_notify *mnb = arg;
1418 int ret = 0;
1419 int nid;
1421 nid = mnb->status_change_nid;
1422 if (nid < 0)
1423 goto out;
1425 switch (action) {
1426 case MEM_GOING_ONLINE:
1427 mutex_lock(&slab_mutex);
1428 ret = init_cache_node_node(nid);
1429 mutex_unlock(&slab_mutex);
1430 break;
1431 case MEM_GOING_OFFLINE:
1432 mutex_lock(&slab_mutex);
1433 ret = drain_cache_node_node(nid);
1434 mutex_unlock(&slab_mutex);
1435 break;
1436 case MEM_ONLINE:
1437 case MEM_OFFLINE:
1438 case MEM_CANCEL_ONLINE:
1439 case MEM_CANCEL_OFFLINE:
1440 break;
1442 out:
1443 return notifier_from_errno(ret);
1445 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1448 * swap the static kmem_cache_node with kmalloced memory
1450 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1451 int nodeid)
1453 struct kmem_cache_node *ptr;
1455 ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1456 BUG_ON(!ptr);
1458 memcpy(ptr, list, sizeof(struct kmem_cache_node));
1460 * Do not assume that spinlocks can be initialized via memcpy:
1462 spin_lock_init(&ptr->list_lock);
1464 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1465 cachep->node[nodeid] = ptr;
1469 * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1470 * size of kmem_cache_node.
1472 static void __init set_up_node(struct kmem_cache *cachep, int index)
1474 int node;
1476 for_each_online_node(node) {
1477 cachep->node[node] = &init_kmem_cache_node[index + node];
1478 cachep->node[node]->next_reap = jiffies +
1479 REAPTIMEOUT_NODE +
1480 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1485 * The memory after the last cpu cache pointer is used for the
1486 * the node pointer.
1488 static void setup_node_pointer(struct kmem_cache *cachep)
1490 cachep->node = (struct kmem_cache_node **)&cachep->array[nr_cpu_ids];
1494 * Initialisation. Called after the page allocator have been initialised and
1495 * before smp_init().
1497 void __init kmem_cache_init(void)
1499 int i;
1501 BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1502 sizeof(struct rcu_head));
1503 kmem_cache = &kmem_cache_boot;
1504 setup_node_pointer(kmem_cache);
1506 if (num_possible_nodes() == 1)
1507 use_alien_caches = 0;
1509 for (i = 0; i < NUM_INIT_LISTS; i++)
1510 kmem_cache_node_init(&init_kmem_cache_node[i]);
1512 set_up_node(kmem_cache, CACHE_CACHE);
1515 * Fragmentation resistance on low memory - only use bigger
1516 * page orders on machines with more than 32MB of memory if
1517 * not overridden on the command line.
1519 if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1520 slab_max_order = SLAB_MAX_ORDER_HI;
1522 /* Bootstrap is tricky, because several objects are allocated
1523 * from caches that do not exist yet:
1524 * 1) initialize the kmem_cache cache: it contains the struct
1525 * kmem_cache structures of all caches, except kmem_cache itself:
1526 * kmem_cache is statically allocated.
1527 * Initially an __init data area is used for the head array and the
1528 * kmem_cache_node structures, it's replaced with a kmalloc allocated
1529 * array at the end of the bootstrap.
1530 * 2) Create the first kmalloc cache.
1531 * The struct kmem_cache for the new cache is allocated normally.
1532 * An __init data area is used for the head array.
1533 * 3) Create the remaining kmalloc caches, with minimally sized
1534 * head arrays.
1535 * 4) Replace the __init data head arrays for kmem_cache and the first
1536 * kmalloc cache with kmalloc allocated arrays.
1537 * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1538 * the other cache's with kmalloc allocated memory.
1539 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1542 /* 1) create the kmem_cache */
1545 * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1547 create_boot_cache(kmem_cache, "kmem_cache",
1548 offsetof(struct kmem_cache, array[nr_cpu_ids]) +
1549 nr_node_ids * sizeof(struct kmem_cache_node *),
1550 SLAB_HWCACHE_ALIGN);
1551 list_add(&kmem_cache->list, &slab_caches);
1553 /* 2+3) create the kmalloc caches */
1556 * Initialize the caches that provide memory for the array cache and the
1557 * kmem_cache_node structures first. Without this, further allocations will
1558 * bug.
1561 kmalloc_caches[INDEX_AC] = create_kmalloc_cache("kmalloc-ac",
1562 kmalloc_size(INDEX_AC), ARCH_KMALLOC_FLAGS);
1564 if (INDEX_AC != INDEX_NODE)
1565 kmalloc_caches[INDEX_NODE] =
1566 create_kmalloc_cache("kmalloc-node",
1567 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1569 slab_early_init = 0;
1571 /* 4) Replace the bootstrap head arrays */
1573 struct array_cache *ptr;
1575 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1577 memcpy(ptr, cpu_cache_get(kmem_cache),
1578 sizeof(struct arraycache_init));
1580 * Do not assume that spinlocks can be initialized via memcpy:
1582 spin_lock_init(&ptr->lock);
1584 kmem_cache->array[smp_processor_id()] = ptr;
1586 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1588 BUG_ON(cpu_cache_get(kmalloc_caches[INDEX_AC])
1589 != &initarray_generic.cache);
1590 memcpy(ptr, cpu_cache_get(kmalloc_caches[INDEX_AC]),
1591 sizeof(struct arraycache_init));
1593 * Do not assume that spinlocks can be initialized via memcpy:
1595 spin_lock_init(&ptr->lock);
1597 kmalloc_caches[INDEX_AC]->array[smp_processor_id()] = ptr;
1599 /* 5) Replace the bootstrap kmem_cache_node */
1601 int nid;
1603 for_each_online_node(nid) {
1604 init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1606 init_list(kmalloc_caches[INDEX_AC],
1607 &init_kmem_cache_node[SIZE_AC + nid], nid);
1609 if (INDEX_AC != INDEX_NODE) {
1610 init_list(kmalloc_caches[INDEX_NODE],
1611 &init_kmem_cache_node[SIZE_NODE + nid], nid);
1616 create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1619 void __init kmem_cache_init_late(void)
1621 struct kmem_cache *cachep;
1623 slab_state = UP;
1625 /* 6) resize the head arrays to their final sizes */
1626 mutex_lock(&slab_mutex);
1627 list_for_each_entry(cachep, &slab_caches, list)
1628 if (enable_cpucache(cachep, GFP_NOWAIT))
1629 BUG();
1630 mutex_unlock(&slab_mutex);
1632 /* Annotate slab for lockdep -- annotate the malloc caches */
1633 init_lock_keys();
1635 /* Done! */
1636 slab_state = FULL;
1639 * Register a cpu startup notifier callback that initializes
1640 * cpu_cache_get for all new cpus
1642 register_cpu_notifier(&cpucache_notifier);
1644 #ifdef CONFIG_NUMA
1646 * Register a memory hotplug callback that initializes and frees
1647 * node.
1649 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1650 #endif
1653 * The reap timers are started later, with a module init call: That part
1654 * of the kernel is not yet operational.
1658 static int __init cpucache_init(void)
1660 int cpu;
1663 * Register the timers that return unneeded pages to the page allocator
1665 for_each_online_cpu(cpu)
1666 start_cpu_timer(cpu);
1668 /* Done! */
1669 slab_state = FULL;
1670 return 0;
1672 __initcall(cpucache_init);
1674 static noinline void
1675 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1677 #if DEBUG
1678 struct kmem_cache_node *n;
1679 struct page *page;
1680 unsigned long flags;
1681 int node;
1682 static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1683 DEFAULT_RATELIMIT_BURST);
1685 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1686 return;
1688 printk(KERN_WARNING
1689 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1690 nodeid, gfpflags);
1691 printk(KERN_WARNING " cache: %s, object size: %d, order: %d\n",
1692 cachep->name, cachep->size, cachep->gfporder);
1694 for_each_online_node(node) {
1695 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1696 unsigned long active_slabs = 0, num_slabs = 0;
1698 n = cachep->node[node];
1699 if (!n)
1700 continue;
1702 spin_lock_irqsave(&n->list_lock, flags);
1703 list_for_each_entry(page, &n->slabs_full, lru) {
1704 active_objs += cachep->num;
1705 active_slabs++;
1707 list_for_each_entry(page, &n->slabs_partial, lru) {
1708 active_objs += page->active;
1709 active_slabs++;
1711 list_for_each_entry(page, &n->slabs_free, lru)
1712 num_slabs++;
1714 free_objects += n->free_objects;
1715 spin_unlock_irqrestore(&n->list_lock, flags);
1717 num_slabs += active_slabs;
1718 num_objs = num_slabs * cachep->num;
1719 printk(KERN_WARNING
1720 " node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1721 node, active_slabs, num_slabs, active_objs, num_objs,
1722 free_objects);
1724 #endif
1728 * Interface to system's page allocator. No need to hold the cache-lock.
1730 * If we requested dmaable memory, we will get it. Even if we
1731 * did not request dmaable memory, we might get it, but that
1732 * would be relatively rare and ignorable.
1734 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1735 int nodeid)
1737 struct page *page;
1738 int nr_pages;
1740 flags |= cachep->allocflags;
1741 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1742 flags |= __GFP_RECLAIMABLE;
1744 if (memcg_charge_slab(cachep, flags, cachep->gfporder))
1745 return NULL;
1747 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1748 if (!page) {
1749 memcg_uncharge_slab(cachep, cachep->gfporder);
1750 slab_out_of_memory(cachep, flags, nodeid);
1751 return NULL;
1754 /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1755 if (unlikely(page->pfmemalloc))
1756 pfmemalloc_active = true;
1758 nr_pages = (1 << cachep->gfporder);
1759 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1760 add_zone_page_state(page_zone(page),
1761 NR_SLAB_RECLAIMABLE, nr_pages);
1762 else
1763 add_zone_page_state(page_zone(page),
1764 NR_SLAB_UNRECLAIMABLE, nr_pages);
1765 __SetPageSlab(page);
1766 if (page->pfmemalloc)
1767 SetPageSlabPfmemalloc(page);
1769 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1770 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1772 if (cachep->ctor)
1773 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1774 else
1775 kmemcheck_mark_unallocated_pages(page, nr_pages);
1778 return page;
1782 * Interface to system's page release.
1784 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1786 const unsigned long nr_freed = (1 << cachep->gfporder);
1788 kmemcheck_free_shadow(page, cachep->gfporder);
1790 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1791 sub_zone_page_state(page_zone(page),
1792 NR_SLAB_RECLAIMABLE, nr_freed);
1793 else
1794 sub_zone_page_state(page_zone(page),
1795 NR_SLAB_UNRECLAIMABLE, nr_freed);
1797 BUG_ON(!PageSlab(page));
1798 __ClearPageSlabPfmemalloc(page);
1799 __ClearPageSlab(page);
1800 page_mapcount_reset(page);
1801 page->mapping = NULL;
1803 if (current->reclaim_state)
1804 current->reclaim_state->reclaimed_slab += nr_freed;
1805 __free_pages(page, cachep->gfporder);
1806 memcg_uncharge_slab(cachep, cachep->gfporder);
1809 static void kmem_rcu_free(struct rcu_head *head)
1811 struct kmem_cache *cachep;
1812 struct page *page;
1814 page = container_of(head, struct page, rcu_head);
1815 cachep = page->slab_cache;
1817 kmem_freepages(cachep, page);
1820 #if DEBUG
1822 #ifdef CONFIG_DEBUG_PAGEALLOC
1823 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1824 unsigned long caller)
1826 int size = cachep->object_size;
1828 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1830 if (size < 5 * sizeof(unsigned long))
1831 return;
1833 *addr++ = 0x12345678;
1834 *addr++ = caller;
1835 *addr++ = smp_processor_id();
1836 size -= 3 * sizeof(unsigned long);
1838 unsigned long *sptr = &caller;
1839 unsigned long svalue;
1841 while (!kstack_end(sptr)) {
1842 svalue = *sptr++;
1843 if (kernel_text_address(svalue)) {
1844 *addr++ = svalue;
1845 size -= sizeof(unsigned long);
1846 if (size <= sizeof(unsigned long))
1847 break;
1852 *addr++ = 0x87654321;
1854 #endif
1856 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1858 int size = cachep->object_size;
1859 addr = &((char *)addr)[obj_offset(cachep)];
1861 memset(addr, val, size);
1862 *(unsigned char *)(addr + size - 1) = POISON_END;
1865 static void dump_line(char *data, int offset, int limit)
1867 int i;
1868 unsigned char error = 0;
1869 int bad_count = 0;
1871 printk(KERN_ERR "%03x: ", offset);
1872 for (i = 0; i < limit; i++) {
1873 if (data[offset + i] != POISON_FREE) {
1874 error = data[offset + i];
1875 bad_count++;
1878 print_hex_dump(KERN_CONT, "", 0, 16, 1,
1879 &data[offset], limit, 1);
1881 if (bad_count == 1) {
1882 error ^= POISON_FREE;
1883 if (!(error & (error - 1))) {
1884 printk(KERN_ERR "Single bit error detected. Probably "
1885 "bad RAM.\n");
1886 #ifdef CONFIG_X86
1887 printk(KERN_ERR "Run memtest86+ or a similar memory "
1888 "test tool.\n");
1889 #else
1890 printk(KERN_ERR "Run a memory test tool.\n");
1891 #endif
1895 #endif
1897 #if DEBUG
1899 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1901 int i, size;
1902 char *realobj;
1904 if (cachep->flags & SLAB_RED_ZONE) {
1905 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1906 *dbg_redzone1(cachep, objp),
1907 *dbg_redzone2(cachep, objp));
1910 if (cachep->flags & SLAB_STORE_USER) {
1911 printk(KERN_ERR "Last user: [<%p>](%pSR)\n",
1912 *dbg_userword(cachep, objp),
1913 *dbg_userword(cachep, objp));
1915 realobj = (char *)objp + obj_offset(cachep);
1916 size = cachep->object_size;
1917 for (i = 0; i < size && lines; i += 16, lines--) {
1918 int limit;
1919 limit = 16;
1920 if (i + limit > size)
1921 limit = size - i;
1922 dump_line(realobj, i, limit);
1926 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1928 char *realobj;
1929 int size, i;
1930 int lines = 0;
1932 realobj = (char *)objp + obj_offset(cachep);
1933 size = cachep->object_size;
1935 for (i = 0; i < size; i++) {
1936 char exp = POISON_FREE;
1937 if (i == size - 1)
1938 exp = POISON_END;
1939 if (realobj[i] != exp) {
1940 int limit;
1941 /* Mismatch ! */
1942 /* Print header */
1943 if (lines == 0) {
1944 printk(KERN_ERR
1945 "Slab corruption (%s): %s start=%p, len=%d\n",
1946 print_tainted(), cachep->name, realobj, size);
1947 print_objinfo(cachep, objp, 0);
1949 /* Hexdump the affected line */
1950 i = (i / 16) * 16;
1951 limit = 16;
1952 if (i + limit > size)
1953 limit = size - i;
1954 dump_line(realobj, i, limit);
1955 i += 16;
1956 lines++;
1957 /* Limit to 5 lines */
1958 if (lines > 5)
1959 break;
1962 if (lines != 0) {
1963 /* Print some data about the neighboring objects, if they
1964 * exist:
1966 struct page *page = virt_to_head_page(objp);
1967 unsigned int objnr;
1969 objnr = obj_to_index(cachep, page, objp);
1970 if (objnr) {
1971 objp = index_to_obj(cachep, page, objnr - 1);
1972 realobj = (char *)objp + obj_offset(cachep);
1973 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1974 realobj, size);
1975 print_objinfo(cachep, objp, 2);
1977 if (objnr + 1 < cachep->num) {
1978 objp = index_to_obj(cachep, page, objnr + 1);
1979 realobj = (char *)objp + obj_offset(cachep);
1980 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1981 realobj, size);
1982 print_objinfo(cachep, objp, 2);
1986 #endif
1988 #if DEBUG
1989 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1990 struct page *page)
1992 int i;
1993 for (i = 0; i < cachep->num; i++) {
1994 void *objp = index_to_obj(cachep, page, i);
1996 if (cachep->flags & SLAB_POISON) {
1997 #ifdef CONFIG_DEBUG_PAGEALLOC
1998 if (cachep->size % PAGE_SIZE == 0 &&
1999 OFF_SLAB(cachep))
2000 kernel_map_pages(virt_to_page(objp),
2001 cachep->size / PAGE_SIZE, 1);
2002 else
2003 check_poison_obj(cachep, objp);
2004 #else
2005 check_poison_obj(cachep, objp);
2006 #endif
2008 if (cachep->flags & SLAB_RED_ZONE) {
2009 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2010 slab_error(cachep, "start of a freed object "
2011 "was overwritten");
2012 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2013 slab_error(cachep, "end of a freed object "
2014 "was overwritten");
2018 #else
2019 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
2020 struct page *page)
2023 #endif
2026 * slab_destroy - destroy and release all objects in a slab
2027 * @cachep: cache pointer being destroyed
2028 * @page: page pointer being destroyed
2030 * Destroy all the objs in a slab, and release the mem back to the system.
2031 * Before calling the slab must have been unlinked from the cache. The
2032 * cache-lock is not held/needed.
2034 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
2036 void *freelist;
2038 freelist = page->freelist;
2039 slab_destroy_debugcheck(cachep, page);
2040 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2041 struct rcu_head *head;
2044 * RCU free overloads the RCU head over the LRU.
2045 * slab_page has been overloeaded over the LRU,
2046 * however it is not used from now on so that
2047 * we can use it safely.
2049 head = (void *)&page->rcu_head;
2050 call_rcu(head, kmem_rcu_free);
2052 } else {
2053 kmem_freepages(cachep, page);
2057 * From now on, we don't use freelist
2058 * although actual page can be freed in rcu context
2060 if (OFF_SLAB(cachep))
2061 kmem_cache_free(cachep->freelist_cache, freelist);
2065 * calculate_slab_order - calculate size (page order) of slabs
2066 * @cachep: pointer to the cache that is being created
2067 * @size: size of objects to be created in this cache.
2068 * @align: required alignment for the objects.
2069 * @flags: slab allocation flags
2071 * Also calculates the number of objects per slab.
2073 * This could be made much more intelligent. For now, try to avoid using
2074 * high order pages for slabs. When the gfp() functions are more friendly
2075 * towards high-order requests, this should be changed.
2077 static size_t calculate_slab_order(struct kmem_cache *cachep,
2078 size_t size, size_t align, unsigned long flags)
2080 unsigned long offslab_limit;
2081 size_t left_over = 0;
2082 int gfporder;
2084 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2085 unsigned int num;
2086 size_t remainder;
2088 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2089 if (!num)
2090 continue;
2092 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
2093 if (num > SLAB_OBJ_MAX_NUM)
2094 break;
2096 if (flags & CFLGS_OFF_SLAB) {
2097 size_t freelist_size_per_obj = sizeof(freelist_idx_t);
2099 * Max number of objs-per-slab for caches which
2100 * use off-slab slabs. Needed to avoid a possible
2101 * looping condition in cache_grow().
2103 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
2104 freelist_size_per_obj += sizeof(char);
2105 offslab_limit = size;
2106 offslab_limit /= freelist_size_per_obj;
2108 if (num > offslab_limit)
2109 break;
2112 /* Found something acceptable - save it away */
2113 cachep->num = num;
2114 cachep->gfporder = gfporder;
2115 left_over = remainder;
2118 * A VFS-reclaimable slab tends to have most allocations
2119 * as GFP_NOFS and we really don't want to have to be allocating
2120 * higher-order pages when we are unable to shrink dcache.
2122 if (flags & SLAB_RECLAIM_ACCOUNT)
2123 break;
2126 * Large number of objects is good, but very large slabs are
2127 * currently bad for the gfp()s.
2129 if (gfporder >= slab_max_order)
2130 break;
2133 * Acceptable internal fragmentation?
2135 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2136 break;
2138 return left_over;
2141 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2143 if (slab_state >= FULL)
2144 return enable_cpucache(cachep, gfp);
2146 if (slab_state == DOWN) {
2148 * Note: Creation of first cache (kmem_cache).
2149 * The setup_node is taken care
2150 * of by the caller of __kmem_cache_create
2152 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2153 slab_state = PARTIAL;
2154 } else if (slab_state == PARTIAL) {
2156 * Note: the second kmem_cache_create must create the cache
2157 * that's used by kmalloc(24), otherwise the creation of
2158 * further caches will BUG().
2160 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2163 * If the cache that's used by kmalloc(sizeof(kmem_cache_node)) is
2164 * the second cache, then we need to set up all its node/,
2165 * otherwise the creation of further caches will BUG().
2167 set_up_node(cachep, SIZE_AC);
2168 if (INDEX_AC == INDEX_NODE)
2169 slab_state = PARTIAL_NODE;
2170 else
2171 slab_state = PARTIAL_ARRAYCACHE;
2172 } else {
2173 /* Remaining boot caches */
2174 cachep->array[smp_processor_id()] =
2175 kmalloc(sizeof(struct arraycache_init), gfp);
2177 if (slab_state == PARTIAL_ARRAYCACHE) {
2178 set_up_node(cachep, SIZE_NODE);
2179 slab_state = PARTIAL_NODE;
2180 } else {
2181 int node;
2182 for_each_online_node(node) {
2183 cachep->node[node] =
2184 kmalloc_node(sizeof(struct kmem_cache_node),
2185 gfp, node);
2186 BUG_ON(!cachep->node[node]);
2187 kmem_cache_node_init(cachep->node[node]);
2191 cachep->node[numa_mem_id()]->next_reap =
2192 jiffies + REAPTIMEOUT_NODE +
2193 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
2195 cpu_cache_get(cachep)->avail = 0;
2196 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2197 cpu_cache_get(cachep)->batchcount = 1;
2198 cpu_cache_get(cachep)->touched = 0;
2199 cachep->batchcount = 1;
2200 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2201 return 0;
2205 * __kmem_cache_create - Create a cache.
2206 * @cachep: cache management descriptor
2207 * @flags: SLAB flags
2209 * Returns a ptr to the cache on success, NULL on failure.
2210 * Cannot be called within a int, but can be interrupted.
2211 * The @ctor is run when new pages are allocated by the cache.
2213 * The flags are
2215 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2216 * to catch references to uninitialised memory.
2218 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2219 * for buffer overruns.
2221 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2222 * cacheline. This can be beneficial if you're counting cycles as closely
2223 * as davem.
2226 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2228 size_t left_over, freelist_size;
2229 size_t ralign = BYTES_PER_WORD;
2230 gfp_t gfp;
2231 int err;
2232 size_t size = cachep->size;
2234 #if DEBUG
2235 #if FORCED_DEBUG
2237 * Enable redzoning and last user accounting, except for caches with
2238 * large objects, if the increased size would increase the object size
2239 * above the next power of two: caches with object sizes just above a
2240 * power of two have a significant amount of internal fragmentation.
2242 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2243 2 * sizeof(unsigned long long)))
2244 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2245 if (!(flags & SLAB_DESTROY_BY_RCU))
2246 flags |= SLAB_POISON;
2247 #endif
2248 if (flags & SLAB_DESTROY_BY_RCU)
2249 BUG_ON(flags & SLAB_POISON);
2250 #endif
2253 * Check that size is in terms of words. This is needed to avoid
2254 * unaligned accesses for some archs when redzoning is used, and makes
2255 * sure any on-slab bufctl's are also correctly aligned.
2257 if (size & (BYTES_PER_WORD - 1)) {
2258 size += (BYTES_PER_WORD - 1);
2259 size &= ~(BYTES_PER_WORD - 1);
2262 if (flags & SLAB_RED_ZONE) {
2263 ralign = REDZONE_ALIGN;
2264 /* If redzoning, ensure that the second redzone is suitably
2265 * aligned, by adjusting the object size accordingly. */
2266 size += REDZONE_ALIGN - 1;
2267 size &= ~(REDZONE_ALIGN - 1);
2270 /* 3) caller mandated alignment */
2271 if (ralign < cachep->align) {
2272 ralign = cachep->align;
2274 /* disable debug if necessary */
2275 if (ralign > __alignof__(unsigned long long))
2276 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2278 * 4) Store it.
2280 cachep->align = ralign;
2282 if (slab_is_available())
2283 gfp = GFP_KERNEL;
2284 else
2285 gfp = GFP_NOWAIT;
2287 setup_node_pointer(cachep);
2288 #if DEBUG
2291 * Both debugging options require word-alignment which is calculated
2292 * into align above.
2294 if (flags & SLAB_RED_ZONE) {
2295 /* add space for red zone words */
2296 cachep->obj_offset += sizeof(unsigned long long);
2297 size += 2 * sizeof(unsigned long long);
2299 if (flags & SLAB_STORE_USER) {
2300 /* user store requires one word storage behind the end of
2301 * the real object. But if the second red zone needs to be
2302 * aligned to 64 bits, we must allow that much space.
2304 if (flags & SLAB_RED_ZONE)
2305 size += REDZONE_ALIGN;
2306 else
2307 size += BYTES_PER_WORD;
2309 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2311 * To activate debug pagealloc, off-slab management is necessary
2312 * requirement. In early phase of initialization, small sized slab
2313 * doesn't get initialized so it would not be possible. So, we need
2314 * to check size >= 256. It guarantees that all necessary small
2315 * sized slab is initialized in current slab initialization sequence.
2317 if (!slab_early_init && size >= kmalloc_size(INDEX_NODE) &&
2318 size >= 256 && cachep->object_size > cache_line_size() &&
2319 ALIGN(size, cachep->align) < PAGE_SIZE) {
2320 cachep->obj_offset += PAGE_SIZE - ALIGN(size, cachep->align);
2321 size = PAGE_SIZE;
2323 #endif
2324 #endif
2327 * Determine if the slab management is 'on' or 'off' slab.
2328 * (bootstrapping cannot cope with offslab caches so don't do
2329 * it too early on. Always use on-slab management when
2330 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2332 if (size >= OFF_SLAB_MIN_SIZE && !slab_early_init &&
2333 !(flags & SLAB_NOLEAKTRACE))
2335 * Size is large, assume best to place the slab management obj
2336 * off-slab (should allow better packing of objs).
2338 flags |= CFLGS_OFF_SLAB;
2340 size = ALIGN(size, cachep->align);
2342 * We should restrict the number of objects in a slab to implement
2343 * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
2345 if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
2346 size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
2348 left_over = calculate_slab_order(cachep, size, cachep->align, flags);
2350 if (!cachep->num)
2351 return -E2BIG;
2353 freelist_size = calculate_freelist_size(cachep->num, cachep->align);
2356 * If the slab has been placed off-slab, and we have enough space then
2357 * move it on-slab. This is at the expense of any extra colouring.
2359 if (flags & CFLGS_OFF_SLAB && left_over >= freelist_size) {
2360 flags &= ~CFLGS_OFF_SLAB;
2361 left_over -= freelist_size;
2364 if (flags & CFLGS_OFF_SLAB) {
2365 /* really off slab. No need for manual alignment */
2366 freelist_size = calculate_freelist_size(cachep->num, 0);
2368 #ifdef CONFIG_PAGE_POISONING
2369 /* If we're going to use the generic kernel_map_pages()
2370 * poisoning, then it's going to smash the contents of
2371 * the redzone and userword anyhow, so switch them off.
2373 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2374 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2375 #endif
2378 cachep->colour_off = cache_line_size();
2379 /* Offset must be a multiple of the alignment. */
2380 if (cachep->colour_off < cachep->align)
2381 cachep->colour_off = cachep->align;
2382 cachep->colour = left_over / cachep->colour_off;
2383 cachep->freelist_size = freelist_size;
2384 cachep->flags = flags;
2385 cachep->allocflags = __GFP_COMP;
2386 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2387 cachep->allocflags |= GFP_DMA;
2388 cachep->size = size;
2389 cachep->reciprocal_buffer_size = reciprocal_value(size);
2391 if (flags & CFLGS_OFF_SLAB) {
2392 cachep->freelist_cache = kmalloc_slab(freelist_size, 0u);
2394 * This is a possibility for one of the kmalloc_{dma,}_caches.
2395 * But since we go off slab only for object size greater than
2396 * OFF_SLAB_MIN_SIZE, and kmalloc_{dma,}_caches get created
2397 * in ascending order,this should not happen at all.
2398 * But leave a BUG_ON for some lucky dude.
2400 BUG_ON(ZERO_OR_NULL_PTR(cachep->freelist_cache));
2403 err = setup_cpu_cache(cachep, gfp);
2404 if (err) {
2405 __kmem_cache_shutdown(cachep);
2406 return err;
2409 if (flags & SLAB_DEBUG_OBJECTS) {
2411 * Would deadlock through slab_destroy()->call_rcu()->
2412 * debug_object_activate()->kmem_cache_alloc().
2414 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2416 slab_set_debugobj_lock_classes(cachep);
2417 } else if (!OFF_SLAB(cachep) && !(flags & SLAB_DESTROY_BY_RCU))
2418 on_slab_lock_classes(cachep);
2420 return 0;
2423 #if DEBUG
2424 static void check_irq_off(void)
2426 BUG_ON(!irqs_disabled());
2429 static void check_irq_on(void)
2431 BUG_ON(irqs_disabled());
2434 static void check_spinlock_acquired(struct kmem_cache *cachep)
2436 #ifdef CONFIG_SMP
2437 check_irq_off();
2438 assert_spin_locked(&cachep->node[numa_mem_id()]->list_lock);
2439 #endif
2442 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2444 #ifdef CONFIG_SMP
2445 check_irq_off();
2446 assert_spin_locked(&cachep->node[node]->list_lock);
2447 #endif
2450 #else
2451 #define check_irq_off() do { } while(0)
2452 #define check_irq_on() do { } while(0)
2453 #define check_spinlock_acquired(x) do { } while(0)
2454 #define check_spinlock_acquired_node(x, y) do { } while(0)
2455 #endif
2457 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
2458 struct array_cache *ac,
2459 int force, int node);
2461 static void do_drain(void *arg)
2463 struct kmem_cache *cachep = arg;
2464 struct array_cache *ac;
2465 int node = numa_mem_id();
2467 check_irq_off();
2468 ac = cpu_cache_get(cachep);
2469 spin_lock(&cachep->node[node]->list_lock);
2470 free_block(cachep, ac->entry, ac->avail, node);
2471 spin_unlock(&cachep->node[node]->list_lock);
2472 ac->avail = 0;
2475 static void drain_cpu_caches(struct kmem_cache *cachep)
2477 struct kmem_cache_node *n;
2478 int node;
2480 on_each_cpu(do_drain, cachep, 1);
2481 check_irq_on();
2482 for_each_online_node(node) {
2483 n = cachep->node[node];
2484 if (n && n->alien)
2485 drain_alien_cache(cachep, n->alien);
2488 for_each_online_node(node) {
2489 n = cachep->node[node];
2490 if (n)
2491 drain_array(cachep, n, n->shared, 1, node);
2496 * Remove slabs from the list of free slabs.
2497 * Specify the number of slabs to drain in tofree.
2499 * Returns the actual number of slabs released.
2501 static int drain_freelist(struct kmem_cache *cache,
2502 struct kmem_cache_node *n, int tofree)
2504 struct list_head *p;
2505 int nr_freed;
2506 struct page *page;
2508 nr_freed = 0;
2509 while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
2511 spin_lock_irq(&n->list_lock);
2512 p = n->slabs_free.prev;
2513 if (p == &n->slabs_free) {
2514 spin_unlock_irq(&n->list_lock);
2515 goto out;
2518 page = list_entry(p, struct page, lru);
2519 #if DEBUG
2520 BUG_ON(page->active);
2521 #endif
2522 list_del(&page->lru);
2524 * Safe to drop the lock. The slab is no longer linked
2525 * to the cache.
2527 n->free_objects -= cache->num;
2528 spin_unlock_irq(&n->list_lock);
2529 slab_destroy(cache, page);
2530 nr_freed++;
2532 out:
2533 return nr_freed;
2536 int __kmem_cache_shrink(struct kmem_cache *cachep)
2538 int ret = 0, i = 0;
2539 struct kmem_cache_node *n;
2541 drain_cpu_caches(cachep);
2543 check_irq_on();
2544 for_each_online_node(i) {
2545 n = cachep->node[i];
2546 if (!n)
2547 continue;
2549 drain_freelist(cachep, n, slabs_tofree(cachep, n));
2551 ret += !list_empty(&n->slabs_full) ||
2552 !list_empty(&n->slabs_partial);
2554 return (ret ? 1 : 0);
2557 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2559 int i;
2560 struct kmem_cache_node *n;
2561 int rc = __kmem_cache_shrink(cachep);
2563 if (rc)
2564 return rc;
2566 for_each_online_cpu(i)
2567 kfree(cachep->array[i]);
2569 /* NUMA: free the node structures */
2570 for_each_online_node(i) {
2571 n = cachep->node[i];
2572 if (n) {
2573 kfree(n->shared);
2574 free_alien_cache(n->alien);
2575 kfree(n);
2578 return 0;
2582 * Get the memory for a slab management obj.
2584 * For a slab cache when the slab descriptor is off-slab, the
2585 * slab descriptor can't come from the same cache which is being created,
2586 * Because if it is the case, that means we defer the creation of
2587 * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
2588 * And we eventually call down to __kmem_cache_create(), which
2589 * in turn looks up in the kmalloc_{dma,}_caches for the disired-size one.
2590 * This is a "chicken-and-egg" problem.
2592 * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
2593 * which are all initialized during kmem_cache_init().
2595 static void *alloc_slabmgmt(struct kmem_cache *cachep,
2596 struct page *page, int colour_off,
2597 gfp_t local_flags, int nodeid)
2599 void *freelist;
2600 void *addr = page_address(page);
2602 if (OFF_SLAB(cachep)) {
2603 /* Slab management obj is off-slab. */
2604 freelist = kmem_cache_alloc_node(cachep->freelist_cache,
2605 local_flags, nodeid);
2606 if (!freelist)
2607 return NULL;
2608 } else {
2609 freelist = addr + colour_off;
2610 colour_off += cachep->freelist_size;
2612 page->active = 0;
2613 page->s_mem = addr + colour_off;
2614 return freelist;
2617 static inline freelist_idx_t get_free_obj(struct page *page, unsigned int idx)
2619 return ((freelist_idx_t *)page->freelist)[idx];
2622 static inline void set_free_obj(struct page *page,
2623 unsigned int idx, freelist_idx_t val)
2625 ((freelist_idx_t *)(page->freelist))[idx] = val;
2628 static void cache_init_objs(struct kmem_cache *cachep,
2629 struct page *page)
2631 int i;
2633 for (i = 0; i < cachep->num; i++) {
2634 void *objp = index_to_obj(cachep, page, i);
2635 #if DEBUG
2636 /* need to poison the objs? */
2637 if (cachep->flags & SLAB_POISON)
2638 poison_obj(cachep, objp, POISON_FREE);
2639 if (cachep->flags & SLAB_STORE_USER)
2640 *dbg_userword(cachep, objp) = NULL;
2642 if (cachep->flags & SLAB_RED_ZONE) {
2643 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2644 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2647 * Constructors are not allowed to allocate memory from the same
2648 * cache which they are a constructor for. Otherwise, deadlock.
2649 * They must also be threaded.
2651 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2652 cachep->ctor(objp + obj_offset(cachep));
2654 if (cachep->flags & SLAB_RED_ZONE) {
2655 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2656 slab_error(cachep, "constructor overwrote the"
2657 " end of an object");
2658 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2659 slab_error(cachep, "constructor overwrote the"
2660 " start of an object");
2662 if ((cachep->size % PAGE_SIZE) == 0 &&
2663 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2664 kernel_map_pages(virt_to_page(objp),
2665 cachep->size / PAGE_SIZE, 0);
2666 #else
2667 if (cachep->ctor)
2668 cachep->ctor(objp);
2669 #endif
2670 set_obj_status(page, i, OBJECT_FREE);
2671 set_free_obj(page, i, i);
2675 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2677 if (CONFIG_ZONE_DMA_FLAG) {
2678 if (flags & GFP_DMA)
2679 BUG_ON(!(cachep->allocflags & GFP_DMA));
2680 else
2681 BUG_ON(cachep->allocflags & GFP_DMA);
2685 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page,
2686 int nodeid)
2688 void *objp;
2690 objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2691 page->active++;
2692 #if DEBUG
2693 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2694 #endif
2696 return objp;
2699 static void slab_put_obj(struct kmem_cache *cachep, struct page *page,
2700 void *objp, int nodeid)
2702 unsigned int objnr = obj_to_index(cachep, page, objp);
2703 #if DEBUG
2704 unsigned int i;
2706 /* Verify that the slab belongs to the intended node */
2707 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2709 /* Verify double free bug */
2710 for (i = page->active; i < cachep->num; i++) {
2711 if (get_free_obj(page, i) == objnr) {
2712 printk(KERN_ERR "slab: double free detected in cache "
2713 "'%s', objp %p\n", cachep->name, objp);
2714 BUG();
2717 #endif
2718 page->active--;
2719 set_free_obj(page, page->active, objnr);
2723 * Map pages beginning at addr to the given cache and slab. This is required
2724 * for the slab allocator to be able to lookup the cache and slab of a
2725 * virtual address for kfree, ksize, and slab debugging.
2727 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2728 void *freelist)
2730 page->slab_cache = cache;
2731 page->freelist = freelist;
2735 * Grow (by 1) the number of slabs within a cache. This is called by
2736 * kmem_cache_alloc() when there are no active objs left in a cache.
2738 static int cache_grow(struct kmem_cache *cachep,
2739 gfp_t flags, int nodeid, struct page *page)
2741 void *freelist;
2742 size_t offset;
2743 gfp_t local_flags;
2744 struct kmem_cache_node *n;
2747 * Be lazy and only check for valid flags here, keeping it out of the
2748 * critical path in kmem_cache_alloc().
2750 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2751 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2753 /* Take the node list lock to change the colour_next on this node */
2754 check_irq_off();
2755 n = cachep->node[nodeid];
2756 spin_lock(&n->list_lock);
2758 /* Get colour for the slab, and cal the next value. */
2759 offset = n->colour_next;
2760 n->colour_next++;
2761 if (n->colour_next >= cachep->colour)
2762 n->colour_next = 0;
2763 spin_unlock(&n->list_lock);
2765 offset *= cachep->colour_off;
2767 if (local_flags & __GFP_WAIT)
2768 local_irq_enable();
2771 * The test for missing atomic flag is performed here, rather than
2772 * the more obvious place, simply to reduce the critical path length
2773 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2774 * will eventually be caught here (where it matters).
2776 kmem_flagcheck(cachep, flags);
2779 * Get mem for the objs. Attempt to allocate a physical page from
2780 * 'nodeid'.
2782 if (!page)
2783 page = kmem_getpages(cachep, local_flags, nodeid);
2784 if (!page)
2785 goto failed;
2787 /* Get slab management. */
2788 freelist = alloc_slabmgmt(cachep, page, offset,
2789 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2790 if (!freelist)
2791 goto opps1;
2793 slab_map_pages(cachep, page, freelist);
2795 cache_init_objs(cachep, page);
2797 if (local_flags & __GFP_WAIT)
2798 local_irq_disable();
2799 check_irq_off();
2800 spin_lock(&n->list_lock);
2802 /* Make slab active. */
2803 list_add_tail(&page->lru, &(n->slabs_free));
2804 STATS_INC_GROWN(cachep);
2805 n->free_objects += cachep->num;
2806 spin_unlock(&n->list_lock);
2807 return 1;
2808 opps1:
2809 kmem_freepages(cachep, page);
2810 failed:
2811 if (local_flags & __GFP_WAIT)
2812 local_irq_disable();
2813 return 0;
2816 #if DEBUG
2819 * Perform extra freeing checks:
2820 * - detect bad pointers.
2821 * - POISON/RED_ZONE checking
2823 static void kfree_debugcheck(const void *objp)
2825 if (!virt_addr_valid(objp)) {
2826 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2827 (unsigned long)objp);
2828 BUG();
2832 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2834 unsigned long long redzone1, redzone2;
2836 redzone1 = *dbg_redzone1(cache, obj);
2837 redzone2 = *dbg_redzone2(cache, obj);
2840 * Redzone is ok.
2842 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2843 return;
2845 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2846 slab_error(cache, "double free detected");
2847 else
2848 slab_error(cache, "memory outside object was overwritten");
2850 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2851 obj, redzone1, redzone2);
2854 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2855 unsigned long caller)
2857 unsigned int objnr;
2858 struct page *page;
2860 BUG_ON(virt_to_cache(objp) != cachep);
2862 objp -= obj_offset(cachep);
2863 kfree_debugcheck(objp);
2864 page = virt_to_head_page(objp);
2866 if (cachep->flags & SLAB_RED_ZONE) {
2867 verify_redzone_free(cachep, objp);
2868 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2869 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2871 if (cachep->flags & SLAB_STORE_USER)
2872 *dbg_userword(cachep, objp) = (void *)caller;
2874 objnr = obj_to_index(cachep, page, objp);
2876 BUG_ON(objnr >= cachep->num);
2877 BUG_ON(objp != index_to_obj(cachep, page, objnr));
2879 set_obj_status(page, objnr, OBJECT_FREE);
2880 if (cachep->flags & SLAB_POISON) {
2881 #ifdef CONFIG_DEBUG_PAGEALLOC
2882 if ((cachep->size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2883 store_stackinfo(cachep, objp, caller);
2884 kernel_map_pages(virt_to_page(objp),
2885 cachep->size / PAGE_SIZE, 0);
2886 } else {
2887 poison_obj(cachep, objp, POISON_FREE);
2889 #else
2890 poison_obj(cachep, objp, POISON_FREE);
2891 #endif
2893 return objp;
2896 #else
2897 #define kfree_debugcheck(x) do { } while(0)
2898 #define cache_free_debugcheck(x,objp,z) (objp)
2899 #endif
2901 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
2902 bool force_refill)
2904 int batchcount;
2905 struct kmem_cache_node *n;
2906 struct array_cache *ac;
2907 int node;
2909 check_irq_off();
2910 node = numa_mem_id();
2911 if (unlikely(force_refill))
2912 goto force_grow;
2913 retry:
2914 ac = cpu_cache_get(cachep);
2915 batchcount = ac->batchcount;
2916 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2918 * If there was little recent activity on this cache, then
2919 * perform only a partial refill. Otherwise we could generate
2920 * refill bouncing.
2922 batchcount = BATCHREFILL_LIMIT;
2924 n = cachep->node[node];
2926 BUG_ON(ac->avail > 0 || !n);
2927 spin_lock(&n->list_lock);
2929 /* See if we can refill from the shared array */
2930 if (n->shared && transfer_objects(ac, n->shared, batchcount)) {
2931 n->shared->touched = 1;
2932 goto alloc_done;
2935 while (batchcount > 0) {
2936 struct list_head *entry;
2937 struct page *page;
2938 /* Get slab alloc is to come from. */
2939 entry = n->slabs_partial.next;
2940 if (entry == &n->slabs_partial) {
2941 n->free_touched = 1;
2942 entry = n->slabs_free.next;
2943 if (entry == &n->slabs_free)
2944 goto must_grow;
2947 page = list_entry(entry, struct page, lru);
2948 check_spinlock_acquired(cachep);
2951 * The slab was either on partial or free list so
2952 * there must be at least one object available for
2953 * allocation.
2955 BUG_ON(page->active >= cachep->num);
2957 while (page->active < cachep->num && batchcount--) {
2958 STATS_INC_ALLOCED(cachep);
2959 STATS_INC_ACTIVE(cachep);
2960 STATS_SET_HIGH(cachep);
2962 ac_put_obj(cachep, ac, slab_get_obj(cachep, page,
2963 node));
2966 /* move slabp to correct slabp list: */
2967 list_del(&page->lru);
2968 if (page->active == cachep->num)
2969 list_add(&page->lru, &n->slabs_full);
2970 else
2971 list_add(&page->lru, &n->slabs_partial);
2974 must_grow:
2975 n->free_objects -= ac->avail;
2976 alloc_done:
2977 spin_unlock(&n->list_lock);
2979 if (unlikely(!ac->avail)) {
2980 int x;
2981 force_grow:
2982 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
2984 /* cache_grow can reenable interrupts, then ac could change. */
2985 ac = cpu_cache_get(cachep);
2986 node = numa_mem_id();
2988 /* no objects in sight? abort */
2989 if (!x && (ac->avail == 0 || force_refill))
2990 return NULL;
2992 if (!ac->avail) /* objects refilled by interrupt? */
2993 goto retry;
2995 ac->touched = 1;
2997 return ac_get_obj(cachep, ac, flags, force_refill);
3000 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
3001 gfp_t flags)
3003 might_sleep_if(flags & __GFP_WAIT);
3004 #if DEBUG
3005 kmem_flagcheck(cachep, flags);
3006 #endif
3009 #if DEBUG
3010 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
3011 gfp_t flags, void *objp, unsigned long caller)
3013 struct page *page;
3015 if (!objp)
3016 return objp;
3017 if (cachep->flags & SLAB_POISON) {
3018 #ifdef CONFIG_DEBUG_PAGEALLOC
3019 if ((cachep->size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3020 kernel_map_pages(virt_to_page(objp),
3021 cachep->size / PAGE_SIZE, 1);
3022 else
3023 check_poison_obj(cachep, objp);
3024 #else
3025 check_poison_obj(cachep, objp);
3026 #endif
3027 poison_obj(cachep, objp, POISON_INUSE);
3029 if (cachep->flags & SLAB_STORE_USER)
3030 *dbg_userword(cachep, objp) = (void *)caller;
3032 if (cachep->flags & SLAB_RED_ZONE) {
3033 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3034 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3035 slab_error(cachep, "double free, or memory outside"
3036 " object was overwritten");
3037 printk(KERN_ERR
3038 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3039 objp, *dbg_redzone1(cachep, objp),
3040 *dbg_redzone2(cachep, objp));
3042 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3043 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3046 page = virt_to_head_page(objp);
3047 set_obj_status(page, obj_to_index(cachep, page, objp), OBJECT_ACTIVE);
3048 objp += obj_offset(cachep);
3049 if (cachep->ctor && cachep->flags & SLAB_POISON)
3050 cachep->ctor(objp);
3051 if (ARCH_SLAB_MINALIGN &&
3052 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3053 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3054 objp, (int)ARCH_SLAB_MINALIGN);
3056 return objp;
3058 #else
3059 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3060 #endif
3062 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3064 if (cachep == kmem_cache)
3065 return false;
3067 return should_failslab(cachep->object_size, flags, cachep->flags);
3070 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3072 void *objp;
3073 struct array_cache *ac;
3074 bool force_refill = false;
3076 check_irq_off();
3078 ac = cpu_cache_get(cachep);
3079 if (likely(ac->avail)) {
3080 ac->touched = 1;
3081 objp = ac_get_obj(cachep, ac, flags, false);
3084 * Allow for the possibility all avail objects are not allowed
3085 * by the current flags
3087 if (objp) {
3088 STATS_INC_ALLOCHIT(cachep);
3089 goto out;
3091 force_refill = true;
3094 STATS_INC_ALLOCMISS(cachep);
3095 objp = cache_alloc_refill(cachep, flags, force_refill);
3097 * the 'ac' may be updated by cache_alloc_refill(),
3098 * and kmemleak_erase() requires its correct value.
3100 ac = cpu_cache_get(cachep);
3102 out:
3104 * To avoid a false negative, if an object that is in one of the
3105 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3106 * treat the array pointers as a reference to the object.
3108 if (objp)
3109 kmemleak_erase(&ac->entry[ac->avail]);
3110 return objp;
3113 #ifdef CONFIG_NUMA
3115 * Try allocating on another node if PF_SPREAD_SLAB is a mempolicy is set.
3117 * If we are in_interrupt, then process context, including cpusets and
3118 * mempolicy, may not apply and should not be used for allocation policy.
3120 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3122 int nid_alloc, nid_here;
3124 if (in_interrupt() || (flags & __GFP_THISNODE))
3125 return NULL;
3126 nid_alloc = nid_here = numa_mem_id();
3127 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3128 nid_alloc = cpuset_slab_spread_node();
3129 else if (current->mempolicy)
3130 nid_alloc = mempolicy_slab_node();
3131 if (nid_alloc != nid_here)
3132 return ____cache_alloc_node(cachep, flags, nid_alloc);
3133 return NULL;
3137 * Fallback function if there was no memory available and no objects on a
3138 * certain node and fall back is permitted. First we scan all the
3139 * available node for available objects. If that fails then we
3140 * perform an allocation without specifying a node. This allows the page
3141 * allocator to do its reclaim / fallback magic. We then insert the
3142 * slab into the proper nodelist and then allocate from it.
3144 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3146 struct zonelist *zonelist;
3147 gfp_t local_flags;
3148 struct zoneref *z;
3149 struct zone *zone;
3150 enum zone_type high_zoneidx = gfp_zone(flags);
3151 void *obj = NULL;
3152 int nid;
3153 unsigned int cpuset_mems_cookie;
3155 if (flags & __GFP_THISNODE)
3156 return NULL;
3158 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3160 retry_cpuset:
3161 cpuset_mems_cookie = read_mems_allowed_begin();
3162 zonelist = node_zonelist(mempolicy_slab_node(), flags);
3164 retry:
3166 * Look through allowed nodes for objects available
3167 * from existing per node queues.
3169 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3170 nid = zone_to_nid(zone);
3172 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3173 cache->node[nid] &&
3174 cache->node[nid]->free_objects) {
3175 obj = ____cache_alloc_node(cache,
3176 flags | GFP_THISNODE, nid);
3177 if (obj)
3178 break;
3182 if (!obj) {
3184 * This allocation will be performed within the constraints
3185 * of the current cpuset / memory policy requirements.
3186 * We may trigger various forms of reclaim on the allowed
3187 * set and go into memory reserves if necessary.
3189 struct page *page;
3191 if (local_flags & __GFP_WAIT)
3192 local_irq_enable();
3193 kmem_flagcheck(cache, flags);
3194 page = kmem_getpages(cache, local_flags, numa_mem_id());
3195 if (local_flags & __GFP_WAIT)
3196 local_irq_disable();
3197 if (page) {
3199 * Insert into the appropriate per node queues
3201 nid = page_to_nid(page);
3202 if (cache_grow(cache, flags, nid, page)) {
3203 obj = ____cache_alloc_node(cache,
3204 flags | GFP_THISNODE, nid);
3205 if (!obj)
3207 * Another processor may allocate the
3208 * objects in the slab since we are
3209 * not holding any locks.
3211 goto retry;
3212 } else {
3213 /* cache_grow already freed obj */
3214 obj = NULL;
3219 if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3220 goto retry_cpuset;
3221 return obj;
3225 * A interface to enable slab creation on nodeid
3227 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3228 int nodeid)
3230 struct list_head *entry;
3231 struct page *page;
3232 struct kmem_cache_node *n;
3233 void *obj;
3234 int x;
3236 VM_BUG_ON(nodeid < 0 || nodeid >= MAX_NUMNODES);
3237 n = cachep->node[nodeid];
3238 BUG_ON(!n);
3240 retry:
3241 check_irq_off();
3242 spin_lock(&n->list_lock);
3243 entry = n->slabs_partial.next;
3244 if (entry == &n->slabs_partial) {
3245 n->free_touched = 1;
3246 entry = n->slabs_free.next;
3247 if (entry == &n->slabs_free)
3248 goto must_grow;
3251 page = list_entry(entry, struct page, lru);
3252 check_spinlock_acquired_node(cachep, nodeid);
3254 STATS_INC_NODEALLOCS(cachep);
3255 STATS_INC_ACTIVE(cachep);
3256 STATS_SET_HIGH(cachep);
3258 BUG_ON(page->active == cachep->num);
3260 obj = slab_get_obj(cachep, page, nodeid);
3261 n->free_objects--;
3262 /* move slabp to correct slabp list: */
3263 list_del(&page->lru);
3265 if (page->active == cachep->num)
3266 list_add(&page->lru, &n->slabs_full);
3267 else
3268 list_add(&page->lru, &n->slabs_partial);
3270 spin_unlock(&n->list_lock);
3271 goto done;
3273 must_grow:
3274 spin_unlock(&n->list_lock);
3275 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3276 if (x)
3277 goto retry;
3279 return fallback_alloc(cachep, flags);
3281 done:
3282 return obj;
3285 static __always_inline void *
3286 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3287 unsigned long caller)
3289 unsigned long save_flags;
3290 void *ptr;
3291 int slab_node = numa_mem_id();
3293 flags &= gfp_allowed_mask;
3295 lockdep_trace_alloc(flags);
3297 if (slab_should_failslab(cachep, flags))
3298 return NULL;
3300 cachep = memcg_kmem_get_cache(cachep, flags);
3302 cache_alloc_debugcheck_before(cachep, flags);
3303 local_irq_save(save_flags);
3305 if (nodeid == NUMA_NO_NODE)
3306 nodeid = slab_node;
3308 if (unlikely(!cachep->node[nodeid])) {
3309 /* Node not bootstrapped yet */
3310 ptr = fallback_alloc(cachep, flags);
3311 goto out;
3314 if (nodeid == slab_node) {
3316 * Use the locally cached objects if possible.
3317 * However ____cache_alloc does not allow fallback
3318 * to other nodes. It may fail while we still have
3319 * objects on other nodes available.
3321 ptr = ____cache_alloc(cachep, flags);
3322 if (ptr)
3323 goto out;
3325 /* ___cache_alloc_node can fall back to other nodes */
3326 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3327 out:
3328 local_irq_restore(save_flags);
3329 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3330 kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3331 flags);
3333 if (likely(ptr)) {
3334 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3335 if (unlikely(flags & __GFP_ZERO))
3336 memset(ptr, 0, cachep->object_size);
3339 return ptr;
3342 static __always_inline void *
3343 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3345 void *objp;
3347 if (current->mempolicy || unlikely(current->flags & PF_SPREAD_SLAB)) {
3348 objp = alternate_node_alloc(cache, flags);
3349 if (objp)
3350 goto out;
3352 objp = ____cache_alloc(cache, flags);
3355 * We may just have run out of memory on the local node.
3356 * ____cache_alloc_node() knows how to locate memory on other nodes
3358 if (!objp)
3359 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3361 out:
3362 return objp;
3364 #else
3366 static __always_inline void *
3367 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3369 return ____cache_alloc(cachep, flags);
3372 #endif /* CONFIG_NUMA */
3374 static __always_inline void *
3375 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3377 unsigned long save_flags;
3378 void *objp;
3380 flags &= gfp_allowed_mask;
3382 lockdep_trace_alloc(flags);
3384 if (slab_should_failslab(cachep, flags))
3385 return NULL;
3387 cachep = memcg_kmem_get_cache(cachep, flags);
3389 cache_alloc_debugcheck_before(cachep, flags);
3390 local_irq_save(save_flags);
3391 objp = __do_cache_alloc(cachep, flags);
3392 local_irq_restore(save_flags);
3393 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3394 kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3395 flags);
3396 prefetchw(objp);
3398 if (likely(objp)) {
3399 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3400 if (unlikely(flags & __GFP_ZERO))
3401 memset(objp, 0, cachep->object_size);
3404 return objp;
3408 * Caller needs to acquire correct kmem_cache_node's list_lock
3410 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3411 int node)
3413 int i;
3414 struct kmem_cache_node *n;
3416 for (i = 0; i < nr_objects; i++) {
3417 void *objp;
3418 struct page *page;
3420 clear_obj_pfmemalloc(&objpp[i]);
3421 objp = objpp[i];
3423 page = virt_to_head_page(objp);
3424 n = cachep->node[node];
3425 list_del(&page->lru);
3426 check_spinlock_acquired_node(cachep, node);
3427 slab_put_obj(cachep, page, objp, node);
3428 STATS_DEC_ACTIVE(cachep);
3429 n->free_objects++;
3431 /* fixup slab chains */
3432 if (page->active == 0) {
3433 if (n->free_objects > n->free_limit) {
3434 n->free_objects -= cachep->num;
3435 /* No need to drop any previously held
3436 * lock here, even if we have a off-slab slab
3437 * descriptor it is guaranteed to come from
3438 * a different cache, refer to comments before
3439 * alloc_slabmgmt.
3441 slab_destroy(cachep, page);
3442 } else {
3443 list_add(&page->lru, &n->slabs_free);
3445 } else {
3446 /* Unconditionally move a slab to the end of the
3447 * partial list on free - maximum time for the
3448 * other objects to be freed, too.
3450 list_add_tail(&page->lru, &n->slabs_partial);
3455 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3457 int batchcount;
3458 struct kmem_cache_node *n;
3459 int node = numa_mem_id();
3461 batchcount = ac->batchcount;
3462 #if DEBUG
3463 BUG_ON(!batchcount || batchcount > ac->avail);
3464 #endif
3465 check_irq_off();
3466 n = cachep->node[node];
3467 spin_lock(&n->list_lock);
3468 if (n->shared) {
3469 struct array_cache *shared_array = n->shared;
3470 int max = shared_array->limit - shared_array->avail;
3471 if (max) {
3472 if (batchcount > max)
3473 batchcount = max;
3474 memcpy(&(shared_array->entry[shared_array->avail]),
3475 ac->entry, sizeof(void *) * batchcount);
3476 shared_array->avail += batchcount;
3477 goto free_done;
3481 free_block(cachep, ac->entry, batchcount, node);
3482 free_done:
3483 #if STATS
3485 int i = 0;
3486 struct list_head *p;
3488 p = n->slabs_free.next;
3489 while (p != &(n->slabs_free)) {
3490 struct page *page;
3492 page = list_entry(p, struct page, lru);
3493 BUG_ON(page->active);
3495 i++;
3496 p = p->next;
3498 STATS_SET_FREEABLE(cachep, i);
3500 #endif
3501 spin_unlock(&n->list_lock);
3502 ac->avail -= batchcount;
3503 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3507 * Release an obj back to its cache. If the obj has a constructed state, it must
3508 * be in this state _before_ it is released. Called with disabled ints.
3510 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3511 unsigned long caller)
3513 struct array_cache *ac = cpu_cache_get(cachep);
3515 check_irq_off();
3516 kmemleak_free_recursive(objp, cachep->flags);
3517 objp = cache_free_debugcheck(cachep, objp, caller);
3519 kmemcheck_slab_free(cachep, objp, cachep->object_size);
3522 * Skip calling cache_free_alien() when the platform is not numa.
3523 * This will avoid cache misses that happen while accessing slabp (which
3524 * is per page memory reference) to get nodeid. Instead use a global
3525 * variable to skip the call, which is mostly likely to be present in
3526 * the cache.
3528 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3529 return;
3531 if (likely(ac->avail < ac->limit)) {
3532 STATS_INC_FREEHIT(cachep);
3533 } else {
3534 STATS_INC_FREEMISS(cachep);
3535 cache_flusharray(cachep, ac);
3538 ac_put_obj(cachep, ac, objp);
3542 * kmem_cache_alloc - Allocate an object
3543 * @cachep: The cache to allocate from.
3544 * @flags: See kmalloc().
3546 * Allocate an object from this cache. The flags are only relevant
3547 * if the cache has no available objects.
3549 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3551 void *ret = slab_alloc(cachep, flags, _RET_IP_);
3553 trace_kmem_cache_alloc(_RET_IP_, ret,
3554 cachep->object_size, cachep->size, flags);
3556 return ret;
3558 EXPORT_SYMBOL(kmem_cache_alloc);
3560 #ifdef CONFIG_TRACING
3561 void *
3562 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3564 void *ret;
3566 ret = slab_alloc(cachep, flags, _RET_IP_);
3568 trace_kmalloc(_RET_IP_, ret,
3569 size, cachep->size, flags);
3570 return ret;
3572 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3573 #endif
3575 #ifdef CONFIG_NUMA
3577 * kmem_cache_alloc_node - Allocate an object on the specified node
3578 * @cachep: The cache to allocate from.
3579 * @flags: See kmalloc().
3580 * @nodeid: node number of the target node.
3582 * Identical to kmem_cache_alloc but it will allocate memory on the given
3583 * node, which can improve the performance for cpu bound structures.
3585 * Fallback to other node is possible if __GFP_THISNODE is not set.
3587 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3589 void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3591 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3592 cachep->object_size, cachep->size,
3593 flags, nodeid);
3595 return ret;
3597 EXPORT_SYMBOL(kmem_cache_alloc_node);
3599 #ifdef CONFIG_TRACING
3600 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3601 gfp_t flags,
3602 int nodeid,
3603 size_t size)
3605 void *ret;
3607 ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3609 trace_kmalloc_node(_RET_IP_, ret,
3610 size, cachep->size,
3611 flags, nodeid);
3612 return ret;
3614 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3615 #endif
3617 static __always_inline void *
3618 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3620 struct kmem_cache *cachep;
3622 cachep = kmalloc_slab(size, flags);
3623 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3624 return cachep;
3625 return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3628 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3629 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3631 return __do_kmalloc_node(size, flags, node, _RET_IP_);
3633 EXPORT_SYMBOL(__kmalloc_node);
3635 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3636 int node, unsigned long caller)
3638 return __do_kmalloc_node(size, flags, node, caller);
3640 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3641 #else
3642 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3644 return __do_kmalloc_node(size, flags, node, 0);
3646 EXPORT_SYMBOL(__kmalloc_node);
3647 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3648 #endif /* CONFIG_NUMA */
3651 * __do_kmalloc - allocate memory
3652 * @size: how many bytes of memory are required.
3653 * @flags: the type of memory to allocate (see kmalloc).
3654 * @caller: function caller for debug tracking of the caller
3656 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3657 unsigned long caller)
3659 struct kmem_cache *cachep;
3660 void *ret;
3662 cachep = kmalloc_slab(size, flags);
3663 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3664 return cachep;
3665 ret = slab_alloc(cachep, flags, caller);
3667 trace_kmalloc(caller, ret,
3668 size, cachep->size, flags);
3670 return ret;
3674 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3675 void *__kmalloc(size_t size, gfp_t flags)
3677 return __do_kmalloc(size, flags, _RET_IP_);
3679 EXPORT_SYMBOL(__kmalloc);
3681 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3683 return __do_kmalloc(size, flags, caller);
3685 EXPORT_SYMBOL(__kmalloc_track_caller);
3687 #else
3688 void *__kmalloc(size_t size, gfp_t flags)
3690 return __do_kmalloc(size, flags, 0);
3692 EXPORT_SYMBOL(__kmalloc);
3693 #endif
3696 * kmem_cache_free - Deallocate an object
3697 * @cachep: The cache the allocation was from.
3698 * @objp: The previously allocated object.
3700 * Free an object which was previously allocated from this
3701 * cache.
3703 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3705 unsigned long flags;
3706 cachep = cache_from_obj(cachep, objp);
3707 if (!cachep)
3708 return;
3710 local_irq_save(flags);
3711 debug_check_no_locks_freed(objp, cachep->object_size);
3712 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3713 debug_check_no_obj_freed(objp, cachep->object_size);
3714 __cache_free(cachep, objp, _RET_IP_);
3715 local_irq_restore(flags);
3717 trace_kmem_cache_free(_RET_IP_, objp);
3719 EXPORT_SYMBOL(kmem_cache_free);
3722 * kfree - free previously allocated memory
3723 * @objp: pointer returned by kmalloc.
3725 * If @objp is NULL, no operation is performed.
3727 * Don't free memory not originally allocated by kmalloc()
3728 * or you will run into trouble.
3730 void kfree(const void *objp)
3732 struct kmem_cache *c;
3733 unsigned long flags;
3735 trace_kfree(_RET_IP_, objp);
3737 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3738 return;
3739 local_irq_save(flags);
3740 kfree_debugcheck(objp);
3741 c = virt_to_cache(objp);
3742 debug_check_no_locks_freed(objp, c->object_size);
3744 debug_check_no_obj_freed(objp, c->object_size);
3745 __cache_free(c, (void *)objp, _RET_IP_);
3746 local_irq_restore(flags);
3748 EXPORT_SYMBOL(kfree);
3751 * This initializes kmem_cache_node or resizes various caches for all nodes.
3753 static int alloc_kmem_cache_node(struct kmem_cache *cachep, gfp_t gfp)
3755 int node;
3756 struct kmem_cache_node *n;
3757 struct array_cache *new_shared;
3758 struct array_cache **new_alien = NULL;
3760 for_each_online_node(node) {
3762 if (use_alien_caches) {
3763 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3764 if (!new_alien)
3765 goto fail;
3768 new_shared = NULL;
3769 if (cachep->shared) {
3770 new_shared = alloc_arraycache(node,
3771 cachep->shared*cachep->batchcount,
3772 0xbaadf00d, gfp);
3773 if (!new_shared) {
3774 free_alien_cache(new_alien);
3775 goto fail;
3779 n = cachep->node[node];
3780 if (n) {
3781 struct array_cache *shared = n->shared;
3783 spin_lock_irq(&n->list_lock);
3785 if (shared)
3786 free_block(cachep, shared->entry,
3787 shared->avail, node);
3789 n->shared = new_shared;
3790 if (!n->alien) {
3791 n->alien = new_alien;
3792 new_alien = NULL;
3794 n->free_limit = (1 + nr_cpus_node(node)) *
3795 cachep->batchcount + cachep->num;
3796 spin_unlock_irq(&n->list_lock);
3797 kfree(shared);
3798 free_alien_cache(new_alien);
3799 continue;
3801 n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
3802 if (!n) {
3803 free_alien_cache(new_alien);
3804 kfree(new_shared);
3805 goto fail;
3808 kmem_cache_node_init(n);
3809 n->next_reap = jiffies + REAPTIMEOUT_NODE +
3810 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
3811 n->shared = new_shared;
3812 n->alien = new_alien;
3813 n->free_limit = (1 + nr_cpus_node(node)) *
3814 cachep->batchcount + cachep->num;
3815 cachep->node[node] = n;
3817 return 0;
3819 fail:
3820 if (!cachep->list.next) {
3821 /* Cache is not active yet. Roll back what we did */
3822 node--;
3823 while (node >= 0) {
3824 if (cachep->node[node]) {
3825 n = cachep->node[node];
3827 kfree(n->shared);
3828 free_alien_cache(n->alien);
3829 kfree(n);
3830 cachep->node[node] = NULL;
3832 node--;
3835 return -ENOMEM;
3838 struct ccupdate_struct {
3839 struct kmem_cache *cachep;
3840 struct array_cache *new[0];
3843 static void do_ccupdate_local(void *info)
3845 struct ccupdate_struct *new = info;
3846 struct array_cache *old;
3848 check_irq_off();
3849 old = cpu_cache_get(new->cachep);
3851 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3852 new->new[smp_processor_id()] = old;
3855 /* Always called with the slab_mutex held */
3856 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3857 int batchcount, int shared, gfp_t gfp)
3859 struct ccupdate_struct *new;
3860 int i;
3862 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
3863 gfp);
3864 if (!new)
3865 return -ENOMEM;
3867 for_each_online_cpu(i) {
3868 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
3869 batchcount, gfp);
3870 if (!new->new[i]) {
3871 for (i--; i >= 0; i--)
3872 kfree(new->new[i]);
3873 kfree(new);
3874 return -ENOMEM;
3877 new->cachep = cachep;
3879 on_each_cpu(do_ccupdate_local, (void *)new, 1);
3881 check_irq_on();
3882 cachep->batchcount = batchcount;
3883 cachep->limit = limit;
3884 cachep->shared = shared;
3886 for_each_online_cpu(i) {
3887 struct array_cache *ccold = new->new[i];
3888 if (!ccold)
3889 continue;
3890 spin_lock_irq(&cachep->node[cpu_to_mem(i)]->list_lock);
3891 free_block(cachep, ccold->entry, ccold->avail, cpu_to_mem(i));
3892 spin_unlock_irq(&cachep->node[cpu_to_mem(i)]->list_lock);
3893 kfree(ccold);
3895 kfree(new);
3896 return alloc_kmem_cache_node(cachep, gfp);
3899 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3900 int batchcount, int shared, gfp_t gfp)
3902 int ret;
3903 struct kmem_cache *c = NULL;
3904 int i = 0;
3906 ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3908 if (slab_state < FULL)
3909 return ret;
3911 if ((ret < 0) || !is_root_cache(cachep))
3912 return ret;
3914 VM_BUG_ON(!mutex_is_locked(&slab_mutex));
3915 for_each_memcg_cache_index(i) {
3916 c = cache_from_memcg_idx(cachep, i);
3917 if (c)
3918 /* return value determined by the parent cache only */
3919 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3922 return ret;
3925 /* Called with slab_mutex held always */
3926 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3928 int err;
3929 int limit = 0;
3930 int shared = 0;
3931 int batchcount = 0;
3933 if (!is_root_cache(cachep)) {
3934 struct kmem_cache *root = memcg_root_cache(cachep);
3935 limit = root->limit;
3936 shared = root->shared;
3937 batchcount = root->batchcount;
3940 if (limit && shared && batchcount)
3941 goto skip_setup;
3943 * The head array serves three purposes:
3944 * - create a LIFO ordering, i.e. return objects that are cache-warm
3945 * - reduce the number of spinlock operations.
3946 * - reduce the number of linked list operations on the slab and
3947 * bufctl chains: array operations are cheaper.
3948 * The numbers are guessed, we should auto-tune as described by
3949 * Bonwick.
3951 if (cachep->size > 131072)
3952 limit = 1;
3953 else if (cachep->size > PAGE_SIZE)
3954 limit = 8;
3955 else if (cachep->size > 1024)
3956 limit = 24;
3957 else if (cachep->size > 256)
3958 limit = 54;
3959 else
3960 limit = 120;
3963 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3964 * allocation behaviour: Most allocs on one cpu, most free operations
3965 * on another cpu. For these cases, an efficient object passing between
3966 * cpus is necessary. This is provided by a shared array. The array
3967 * replaces Bonwick's magazine layer.
3968 * On uniprocessor, it's functionally equivalent (but less efficient)
3969 * to a larger limit. Thus disabled by default.
3971 shared = 0;
3972 if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
3973 shared = 8;
3975 #if DEBUG
3977 * With debugging enabled, large batchcount lead to excessively long
3978 * periods with disabled local interrupts. Limit the batchcount
3980 if (limit > 32)
3981 limit = 32;
3982 #endif
3983 batchcount = (limit + 1) / 2;
3984 skip_setup:
3985 err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3986 if (err)
3987 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3988 cachep->name, -err);
3989 return err;
3993 * Drain an array if it contains any elements taking the node lock only if
3994 * necessary. Note that the node listlock also protects the array_cache
3995 * if drain_array() is used on the shared array.
3997 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
3998 struct array_cache *ac, int force, int node)
4000 int tofree;
4002 if (!ac || !ac->avail)
4003 return;
4004 if (ac->touched && !force) {
4005 ac->touched = 0;
4006 } else {
4007 spin_lock_irq(&n->list_lock);
4008 if (ac->avail) {
4009 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4010 if (tofree > ac->avail)
4011 tofree = (ac->avail + 1) / 2;
4012 free_block(cachep, ac->entry, tofree, node);
4013 ac->avail -= tofree;
4014 memmove(ac->entry, &(ac->entry[tofree]),
4015 sizeof(void *) * ac->avail);
4017 spin_unlock_irq(&n->list_lock);
4022 * cache_reap - Reclaim memory from caches.
4023 * @w: work descriptor
4025 * Called from workqueue/eventd every few seconds.
4026 * Purpose:
4027 * - clear the per-cpu caches for this CPU.
4028 * - return freeable pages to the main free memory pool.
4030 * If we cannot acquire the cache chain mutex then just give up - we'll try
4031 * again on the next iteration.
4033 static void cache_reap(struct work_struct *w)
4035 struct kmem_cache *searchp;
4036 struct kmem_cache_node *n;
4037 int node = numa_mem_id();
4038 struct delayed_work *work = to_delayed_work(w);
4040 if (!mutex_trylock(&slab_mutex))
4041 /* Give up. Setup the next iteration. */
4042 goto out;
4044 list_for_each_entry(searchp, &slab_caches, list) {
4045 check_irq_on();
4048 * We only take the node lock if absolutely necessary and we
4049 * have established with reasonable certainty that
4050 * we can do some work if the lock was obtained.
4052 n = searchp->node[node];
4054 reap_alien(searchp, n);
4056 drain_array(searchp, n, cpu_cache_get(searchp), 0, node);
4059 * These are racy checks but it does not matter
4060 * if we skip one check or scan twice.
4062 if (time_after(n->next_reap, jiffies))
4063 goto next;
4065 n->next_reap = jiffies + REAPTIMEOUT_NODE;
4067 drain_array(searchp, n, n->shared, 0, node);
4069 if (n->free_touched)
4070 n->free_touched = 0;
4071 else {
4072 int freed;
4074 freed = drain_freelist(searchp, n, (n->free_limit +
4075 5 * searchp->num - 1) / (5 * searchp->num));
4076 STATS_ADD_REAPED(searchp, freed);
4078 next:
4079 cond_resched();
4081 check_irq_on();
4082 mutex_unlock(&slab_mutex);
4083 next_reap_node();
4084 out:
4085 /* Set up the next iteration */
4086 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
4089 #ifdef CONFIG_SLABINFO
4090 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4092 struct page *page;
4093 unsigned long active_objs;
4094 unsigned long num_objs;
4095 unsigned long active_slabs = 0;
4096 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4097 const char *name;
4098 char *error = NULL;
4099 int node;
4100 struct kmem_cache_node *n;
4102 active_objs = 0;
4103 num_slabs = 0;
4104 for_each_online_node(node) {
4105 n = cachep->node[node];
4106 if (!n)
4107 continue;
4109 check_irq_on();
4110 spin_lock_irq(&n->list_lock);
4112 list_for_each_entry(page, &n->slabs_full, lru) {
4113 if (page->active != cachep->num && !error)
4114 error = "slabs_full accounting error";
4115 active_objs += cachep->num;
4116 active_slabs++;
4118 list_for_each_entry(page, &n->slabs_partial, lru) {
4119 if (page->active == cachep->num && !error)
4120 error = "slabs_partial accounting error";
4121 if (!page->active && !error)
4122 error = "slabs_partial accounting error";
4123 active_objs += page->active;
4124 active_slabs++;
4126 list_for_each_entry(page, &n->slabs_free, lru) {
4127 if (page->active && !error)
4128 error = "slabs_free accounting error";
4129 num_slabs++;
4131 free_objects += n->free_objects;
4132 if (n->shared)
4133 shared_avail += n->shared->avail;
4135 spin_unlock_irq(&n->list_lock);
4137 num_slabs += active_slabs;
4138 num_objs = num_slabs * cachep->num;
4139 if (num_objs - active_objs != free_objects && !error)
4140 error = "free_objects accounting error";
4142 name = cachep->name;
4143 if (error)
4144 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4146 sinfo->active_objs = active_objs;
4147 sinfo->num_objs = num_objs;
4148 sinfo->active_slabs = active_slabs;
4149 sinfo->num_slabs = num_slabs;
4150 sinfo->shared_avail = shared_avail;
4151 sinfo->limit = cachep->limit;
4152 sinfo->batchcount = cachep->batchcount;
4153 sinfo->shared = cachep->shared;
4154 sinfo->objects_per_slab = cachep->num;
4155 sinfo->cache_order = cachep->gfporder;
4158 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4160 #if STATS
4161 { /* node stats */
4162 unsigned long high = cachep->high_mark;
4163 unsigned long allocs = cachep->num_allocations;
4164 unsigned long grown = cachep->grown;
4165 unsigned long reaped = cachep->reaped;
4166 unsigned long errors = cachep->errors;
4167 unsigned long max_freeable = cachep->max_freeable;
4168 unsigned long node_allocs = cachep->node_allocs;
4169 unsigned long node_frees = cachep->node_frees;
4170 unsigned long overflows = cachep->node_overflow;
4172 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4173 "%4lu %4lu %4lu %4lu %4lu",
4174 allocs, high, grown,
4175 reaped, errors, max_freeable, node_allocs,
4176 node_frees, overflows);
4178 /* cpu stats */
4180 unsigned long allochit = atomic_read(&cachep->allochit);
4181 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4182 unsigned long freehit = atomic_read(&cachep->freehit);
4183 unsigned long freemiss = atomic_read(&cachep->freemiss);
4185 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4186 allochit, allocmiss, freehit, freemiss);
4188 #endif
4191 #define MAX_SLABINFO_WRITE 128
4193 * slabinfo_write - Tuning for the slab allocator
4194 * @file: unused
4195 * @buffer: user buffer
4196 * @count: data length
4197 * @ppos: unused
4199 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4200 size_t count, loff_t *ppos)
4202 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4203 int limit, batchcount, shared, res;
4204 struct kmem_cache *cachep;
4206 if (count > MAX_SLABINFO_WRITE)
4207 return -EINVAL;
4208 if (copy_from_user(&kbuf, buffer, count))
4209 return -EFAULT;
4210 kbuf[MAX_SLABINFO_WRITE] = '\0';
4212 tmp = strchr(kbuf, ' ');
4213 if (!tmp)
4214 return -EINVAL;
4215 *tmp = '\0';
4216 tmp++;
4217 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4218 return -EINVAL;
4220 /* Find the cache in the chain of caches. */
4221 mutex_lock(&slab_mutex);
4222 res = -EINVAL;
4223 list_for_each_entry(cachep, &slab_caches, list) {
4224 if (!strcmp(cachep->name, kbuf)) {
4225 if (limit < 1 || batchcount < 1 ||
4226 batchcount > limit || shared < 0) {
4227 res = 0;
4228 } else {
4229 res = do_tune_cpucache(cachep, limit,
4230 batchcount, shared,
4231 GFP_KERNEL);
4233 break;
4236 mutex_unlock(&slab_mutex);
4237 if (res >= 0)
4238 res = count;
4239 return res;
4242 #ifdef CONFIG_DEBUG_SLAB_LEAK
4244 static void *leaks_start(struct seq_file *m, loff_t *pos)
4246 mutex_lock(&slab_mutex);
4247 return seq_list_start(&slab_caches, *pos);
4250 static inline int add_caller(unsigned long *n, unsigned long v)
4252 unsigned long *p;
4253 int l;
4254 if (!v)
4255 return 1;
4256 l = n[1];
4257 p = n + 2;
4258 while (l) {
4259 int i = l/2;
4260 unsigned long *q = p + 2 * i;
4261 if (*q == v) {
4262 q[1]++;
4263 return 1;
4265 if (*q > v) {
4266 l = i;
4267 } else {
4268 p = q + 2;
4269 l -= i + 1;
4272 if (++n[1] == n[0])
4273 return 0;
4274 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4275 p[0] = v;
4276 p[1] = 1;
4277 return 1;
4280 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4281 struct page *page)
4283 void *p;
4284 int i;
4286 if (n[0] == n[1])
4287 return;
4288 for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4289 if (get_obj_status(page, i) != OBJECT_ACTIVE)
4290 continue;
4292 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4293 return;
4297 static void show_symbol(struct seq_file *m, unsigned long address)
4299 #ifdef CONFIG_KALLSYMS
4300 unsigned long offset, size;
4301 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4303 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4304 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4305 if (modname[0])
4306 seq_printf(m, " [%s]", modname);
4307 return;
4309 #endif
4310 seq_printf(m, "%p", (void *)address);
4313 static int leaks_show(struct seq_file *m, void *p)
4315 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4316 struct page *page;
4317 struct kmem_cache_node *n;
4318 const char *name;
4319 unsigned long *x = m->private;
4320 int node;
4321 int i;
4323 if (!(cachep->flags & SLAB_STORE_USER))
4324 return 0;
4325 if (!(cachep->flags & SLAB_RED_ZONE))
4326 return 0;
4328 /* OK, we can do it */
4330 x[1] = 0;
4332 for_each_online_node(node) {
4333 n = cachep->node[node];
4334 if (!n)
4335 continue;
4337 check_irq_on();
4338 spin_lock_irq(&n->list_lock);
4340 list_for_each_entry(page, &n->slabs_full, lru)
4341 handle_slab(x, cachep, page);
4342 list_for_each_entry(page, &n->slabs_partial, lru)
4343 handle_slab(x, cachep, page);
4344 spin_unlock_irq(&n->list_lock);
4346 name = cachep->name;
4347 if (x[0] == x[1]) {
4348 /* Increase the buffer size */
4349 mutex_unlock(&slab_mutex);
4350 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4351 if (!m->private) {
4352 /* Too bad, we are really out */
4353 m->private = x;
4354 mutex_lock(&slab_mutex);
4355 return -ENOMEM;
4357 *(unsigned long *)m->private = x[0] * 2;
4358 kfree(x);
4359 mutex_lock(&slab_mutex);
4360 /* Now make sure this entry will be retried */
4361 m->count = m->size;
4362 return 0;
4364 for (i = 0; i < x[1]; i++) {
4365 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4366 show_symbol(m, x[2*i+2]);
4367 seq_putc(m, '\n');
4370 return 0;
4373 static const struct seq_operations slabstats_op = {
4374 .start = leaks_start,
4375 .next = slab_next,
4376 .stop = slab_stop,
4377 .show = leaks_show,
4380 static int slabstats_open(struct inode *inode, struct file *file)
4382 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4383 int ret = -ENOMEM;
4384 if (n) {
4385 ret = seq_open(file, &slabstats_op);
4386 if (!ret) {
4387 struct seq_file *m = file->private_data;
4388 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4389 m->private = n;
4390 n = NULL;
4392 kfree(n);
4394 return ret;
4397 static const struct file_operations proc_slabstats_operations = {
4398 .open = slabstats_open,
4399 .read = seq_read,
4400 .llseek = seq_lseek,
4401 .release = seq_release_private,
4403 #endif
4405 static int __init slab_proc_init(void)
4407 #ifdef CONFIG_DEBUG_SLAB_LEAK
4408 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4409 #endif
4410 return 0;
4412 module_init(slab_proc_init);
4413 #endif
4416 * ksize - get the actual amount of memory allocated for a given object
4417 * @objp: Pointer to the object
4419 * kmalloc may internally round up allocations and return more memory
4420 * than requested. ksize() can be used to determine the actual amount of
4421 * memory allocated. The caller may use this additional memory, even though
4422 * a smaller amount of memory was initially specified with the kmalloc call.
4423 * The caller must guarantee that objp points to a valid object previously
4424 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4425 * must not be freed during the duration of the call.
4427 size_t ksize(const void *objp)
4429 BUG_ON(!objp);
4430 if (unlikely(objp == ZERO_SIZE_PTR))
4431 return 0;
4433 return virt_to_cache(objp)->object_size;
4435 EXPORT_SYMBOL(ksize);