mm: slub: SLUB_DEBUG=n: use the same alloc/free hooks as for SLUB_DEBUG=y
[deliverable/linux.git] / mm / slab.c
1 /*
2 * linux/mm/slab.c
3 * Written by Mark Hemment, 1996/97.
4 * (markhe@nextd.demon.co.uk)
5 *
6 * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
7 *
8 * Major cleanup, different bufctl logic, per-cpu arrays
9 * (c) 2000 Manfred Spraul
10 *
11 * Cleanup, make the head arrays unconditional, preparation for NUMA
12 * (c) 2002 Manfred Spraul
13 *
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
21 *
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.
27 *
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.
31 *
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.
35 *
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
40 *
41 * If partial slabs exist, then new allocations come from these slabs,
42 * otherwise from empty slabs or new slabs are allocated.
43 *
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.
46 *
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.
52 *
53 * The c_cpuarray may not be read with enabled local interrupts -
54 * it's changed with a smp_call_function().
55 *
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.
63 *
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.
67 *
68 * Further notes from the original documentation:
69 *
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()).
75 *
76 * At present, each engine can be growing a cache. This should be blocked.
77 *
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>
83 *
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.
87 */
88
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>
119
120 #include <net/sock.h>
121
122 #include <asm/cacheflush.h>
123 #include <asm/tlbflush.h>
124 #include <asm/page.h>
125
126 #include <trace/events/kmem.h>
127
128 #include "internal.h"
129
130 #include "slab.h"
131
132 /*
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).
135 *
136 * STATS - 1 to collect stats for /proc/slabinfo.
137 * 0 for faster, smaller code (especially in the critical paths).
138 *
139 * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
140 */
141
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
151
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))
155
156 #ifndef ARCH_KMALLOC_FLAGS
157 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
158 #endif
159
160 #define FREELIST_BYTE_INDEX (((PAGE_SIZE >> BITS_PER_BYTE) \
161 <= SLAB_OBJ_MIN_SIZE) ? 1 : 0)
162
163 #if FREELIST_BYTE_INDEX
164 typedef unsigned char freelist_idx_t;
165 #else
166 typedef unsigned short freelist_idx_t;
167 #endif
168
169 #define SLAB_OBJ_MAX_NUM ((1 << sizeof(freelist_idx_t) * BITS_PER_BYTE) - 1)
170
171 /*
172 * true if a page was allocated from pfmemalloc reserves for network-based
173 * swap
174 */
175 static bool pfmemalloc_active __read_mostly;
176
177 /*
178 * struct array_cache
179 *
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
184 *
185 * The limit is stored in the per-cpu structure to reduce the data cache
186 * footprint.
187 *
188 */
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.
199 *
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
203 */
204 };
205
206 #define SLAB_OBJ_PFMEMALLOC 1
207 static inline bool is_obj_pfmemalloc(void *objp)
208 {
209 return (unsigned long)objp & SLAB_OBJ_PFMEMALLOC;
210 }
211
212 static inline void set_obj_pfmemalloc(void **objp)
213 {
214 *objp = (void *)((unsigned long)*objp | SLAB_OBJ_PFMEMALLOC);
215 return;
216 }
217
218 static inline void clear_obj_pfmemalloc(void **objp)
219 {
220 *objp = (void *)((unsigned long)*objp & ~SLAB_OBJ_PFMEMALLOC);
221 }
222
223 /*
224 * bootstrap: The caches do not work without cpuarrays anymore, but the
225 * cpuarrays are allocated from the generic caches...
226 */
227 #define BOOT_CPUCACHE_ENTRIES 1
228 struct arraycache_init {
229 struct array_cache cache;
230 void *entries[BOOT_CPUCACHE_ENTRIES];
231 };
232
233 /*
234 * Need this for bootstrapping a per node allocator.
235 */
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)
241
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);
248
249 static int slab_early_init = 1;
250
251 #define INDEX_AC kmalloc_index(sizeof(struct arraycache_init))
252 #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
253
254 static void kmem_cache_node_init(struct kmem_cache_node *parent)
255 {
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;
265 }
266
267 #define MAKE_LIST(cachep, listp, slab, nodeid) \
268 do { \
269 INIT_LIST_HEAD(listp); \
270 list_splice(&get_node(cachep, nodeid)->slab, listp); \
271 } while (0)
272
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)
279
280 #define CFLGS_OFF_SLAB (0x80000000UL)
281 #define OFF_SLAB(x) ((x)->flags & CFLGS_OFF_SLAB)
282
283 #define BATCHREFILL_LIMIT 16
284 /*
285 * Optimization question: fewer reaps means less probability for unnessary
286 * cpucache drain/refill cycles.
287 *
288 * OTOH the cpuarrays can contain lots of objects,
289 * which could lock up otherwise freeable slabs.
290 */
291 #define REAPTIMEOUT_AC (2*HZ)
292 #define REAPTIMEOUT_NODE (4*HZ)
293
294 #if STATS
295 #define STATS_INC_ACTIVE(x) ((x)->num_active++)
296 #define STATS_DEC_ACTIVE(x) ((x)->num_active--)
297 #define STATS_INC_ALLOCED(x) ((x)->num_allocations++)
298 #define STATS_INC_GROWN(x) ((x)->grown++)
299 #define STATS_ADD_REAPED(x,y) ((x)->reaped += (y))
300 #define STATS_SET_HIGH(x) \
301 do { \
302 if ((x)->num_active > (x)->high_mark) \
303 (x)->high_mark = (x)->num_active; \
304 } while (0)
305 #define STATS_INC_ERR(x) ((x)->errors++)
306 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
307 #define STATS_INC_NODEFREES(x) ((x)->node_frees++)
308 #define STATS_INC_ACOVERFLOW(x) ((x)->node_overflow++)
309 #define STATS_SET_FREEABLE(x, i) \
310 do { \
311 if ((x)->max_freeable < i) \
312 (x)->max_freeable = i; \
313 } while (0)
314 #define STATS_INC_ALLOCHIT(x) atomic_inc(&(x)->allochit)
315 #define STATS_INC_ALLOCMISS(x) atomic_inc(&(x)->allocmiss)
316 #define STATS_INC_FREEHIT(x) atomic_inc(&(x)->freehit)
317 #define STATS_INC_FREEMISS(x) atomic_inc(&(x)->freemiss)
318 #else
319 #define STATS_INC_ACTIVE(x) do { } while (0)
320 #define STATS_DEC_ACTIVE(x) do { } while (0)
321 #define STATS_INC_ALLOCED(x) do { } while (0)
322 #define STATS_INC_GROWN(x) do { } while (0)
323 #define STATS_ADD_REAPED(x,y) do { (void)(y); } while (0)
324 #define STATS_SET_HIGH(x) do { } while (0)
325 #define STATS_INC_ERR(x) do { } while (0)
326 #define STATS_INC_NODEALLOCS(x) do { } while (0)
327 #define STATS_INC_NODEFREES(x) do { } while (0)
328 #define STATS_INC_ACOVERFLOW(x) do { } while (0)
329 #define STATS_SET_FREEABLE(x, i) do { } while (0)
330 #define STATS_INC_ALLOCHIT(x) do { } while (0)
331 #define STATS_INC_ALLOCMISS(x) do { } while (0)
332 #define STATS_INC_FREEHIT(x) do { } while (0)
333 #define STATS_INC_FREEMISS(x) do { } while (0)
334 #endif
335
336 #if DEBUG
337
338 /*
339 * memory layout of objects:
340 * 0 : objp
341 * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
342 * the end of an object is aligned with the end of the real
343 * allocation. Catches writes behind the end of the allocation.
344 * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
345 * redzone word.
346 * cachep->obj_offset: The real object.
347 * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
348 * cachep->size - 1* BYTES_PER_WORD: last caller address
349 * [BYTES_PER_WORD long]
350 */
351 static int obj_offset(struct kmem_cache *cachep)
352 {
353 return cachep->obj_offset;
354 }
355
356 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
357 {
358 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
359 return (unsigned long long*) (objp + obj_offset(cachep) -
360 sizeof(unsigned long long));
361 }
362
363 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
364 {
365 BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
366 if (cachep->flags & SLAB_STORE_USER)
367 return (unsigned long long *)(objp + cachep->size -
368 sizeof(unsigned long long) -
369 REDZONE_ALIGN);
370 return (unsigned long long *) (objp + cachep->size -
371 sizeof(unsigned long long));
372 }
373
374 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
375 {
376 BUG_ON(!(cachep->flags & SLAB_STORE_USER));
377 return (void **)(objp + cachep->size - BYTES_PER_WORD);
378 }
379
380 #else
381
382 #define obj_offset(x) 0
383 #define dbg_redzone1(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
384 #define dbg_redzone2(cachep, objp) ({BUG(); (unsigned long long *)NULL;})
385 #define dbg_userword(cachep, objp) ({BUG(); (void **)NULL;})
386
387 #endif
388
389 #define OBJECT_FREE (0)
390 #define OBJECT_ACTIVE (1)
391
392 #ifdef CONFIG_DEBUG_SLAB_LEAK
393
394 static void set_obj_status(struct page *page, int idx, int val)
395 {
396 int freelist_size;
397 char *status;
398 struct kmem_cache *cachep = page->slab_cache;
399
400 freelist_size = cachep->num * sizeof(freelist_idx_t);
401 status = (char *)page->freelist + freelist_size;
402 status[idx] = val;
403 }
404
405 static inline unsigned int get_obj_status(struct page *page, int idx)
406 {
407 int freelist_size;
408 char *status;
409 struct kmem_cache *cachep = page->slab_cache;
410
411 freelist_size = cachep->num * sizeof(freelist_idx_t);
412 status = (char *)page->freelist + freelist_size;
413
414 return status[idx];
415 }
416
417 #else
418 static inline void set_obj_status(struct page *page, int idx, int val) {}
419
420 #endif
421
422 /*
423 * Do not go above this order unless 0 objects fit into the slab or
424 * overridden on the command line.
425 */
426 #define SLAB_MAX_ORDER_HI 1
427 #define SLAB_MAX_ORDER_LO 0
428 static int slab_max_order = SLAB_MAX_ORDER_LO;
429 static bool slab_max_order_set __initdata;
430
431 static inline struct kmem_cache *virt_to_cache(const void *obj)
432 {
433 struct page *page = virt_to_head_page(obj);
434 return page->slab_cache;
435 }
436
437 static inline void *index_to_obj(struct kmem_cache *cache, struct page *page,
438 unsigned int idx)
439 {
440 return page->s_mem + cache->size * idx;
441 }
442
443 /*
444 * We want to avoid an expensive divide : (offset / cache->size)
445 * Using the fact that size is a constant for a particular cache,
446 * we can replace (offset / cache->size) by
447 * reciprocal_divide(offset, cache->reciprocal_buffer_size)
448 */
449 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
450 const struct page *page, void *obj)
451 {
452 u32 offset = (obj - page->s_mem);
453 return reciprocal_divide(offset, cache->reciprocal_buffer_size);
454 }
455
456 static struct arraycache_init initarray_generic =
457 { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
458
459 /* internal cache of cache description objs */
460 static struct kmem_cache kmem_cache_boot = {
461 .batchcount = 1,
462 .limit = BOOT_CPUCACHE_ENTRIES,
463 .shared = 1,
464 .size = sizeof(struct kmem_cache),
465 .name = "kmem_cache",
466 };
467
468 #define BAD_ALIEN_MAGIC 0x01020304ul
469
470 #ifdef CONFIG_LOCKDEP
471
472 /*
473 * Slab sometimes uses the kmalloc slabs to store the slab headers
474 * for other slabs "off slab".
475 * The locking for this is tricky in that it nests within the locks
476 * of all other slabs in a few places; to deal with this special
477 * locking we put on-slab caches into a separate lock-class.
478 *
479 * We set lock class for alien array caches which are up during init.
480 * The lock annotation will be lost if all cpus of a node goes down and
481 * then comes back up during hotplug
482 */
483 static struct lock_class_key on_slab_l3_key;
484 static struct lock_class_key on_slab_alc_key;
485
486 static struct lock_class_key debugobj_l3_key;
487 static struct lock_class_key debugobj_alc_key;
488
489 static void slab_set_lock_classes(struct kmem_cache *cachep,
490 struct lock_class_key *l3_key, struct lock_class_key *alc_key,
491 struct kmem_cache_node *n)
492 {
493 struct array_cache **alc;
494 int r;
495
496 lockdep_set_class(&n->list_lock, l3_key);
497 alc = n->alien;
498 /*
499 * FIXME: This check for BAD_ALIEN_MAGIC
500 * should go away when common slab code is taught to
501 * work even without alien caches.
502 * Currently, non NUMA code returns BAD_ALIEN_MAGIC
503 * for alloc_alien_cache,
504 */
505 if (!alc || (unsigned long)alc == BAD_ALIEN_MAGIC)
506 return;
507 for_each_node(r) {
508 if (alc[r])
509 lockdep_set_class(&alc[r]->lock, alc_key);
510 }
511 }
512
513 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep,
514 struct kmem_cache_node *n)
515 {
516 slab_set_lock_classes(cachep, &debugobj_l3_key, &debugobj_alc_key, n);
517 }
518
519 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
520 {
521 int node;
522 struct kmem_cache_node *n;
523
524 for_each_kmem_cache_node(cachep, node, n)
525 slab_set_debugobj_lock_classes_node(cachep, n);
526 }
527
528 static void init_node_lock_keys(int q)
529 {
530 int i;
531
532 if (slab_state < UP)
533 return;
534
535 for (i = 1; i <= KMALLOC_SHIFT_HIGH; i++) {
536 struct kmem_cache_node *n;
537 struct kmem_cache *cache = kmalloc_caches[i];
538
539 if (!cache)
540 continue;
541
542 n = get_node(cache, q);
543 if (!n || OFF_SLAB(cache))
544 continue;
545
546 slab_set_lock_classes(cache, &on_slab_l3_key,
547 &on_slab_alc_key, n);
548 }
549 }
550
551 static void on_slab_lock_classes_node(struct kmem_cache *cachep,
552 struct kmem_cache_node *n)
553 {
554 slab_set_lock_classes(cachep, &on_slab_l3_key,
555 &on_slab_alc_key, n);
556 }
557
558 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
559 {
560 int node;
561 struct kmem_cache_node *n;
562
563 VM_BUG_ON(OFF_SLAB(cachep));
564 for_each_kmem_cache_node(cachep, node, n)
565 on_slab_lock_classes_node(cachep, n);
566 }
567
568 static inline void __init init_lock_keys(void)
569 {
570 int node;
571
572 for_each_node(node)
573 init_node_lock_keys(node);
574 }
575 #else
576 static void __init init_node_lock_keys(int q)
577 {
578 }
579
580 static inline void init_lock_keys(void)
581 {
582 }
583
584 static inline void on_slab_lock_classes(struct kmem_cache *cachep)
585 {
586 }
587
588 static inline void on_slab_lock_classes_node(struct kmem_cache *cachep,
589 struct kmem_cache_node *n)
590 {
591 }
592
593 static void slab_set_debugobj_lock_classes_node(struct kmem_cache *cachep,
594 struct kmem_cache_node *n)
595 {
596 }
597
598 static void slab_set_debugobj_lock_classes(struct kmem_cache *cachep)
599 {
600 }
601 #endif
602
603 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
604
605 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
606 {
607 return cachep->array[smp_processor_id()];
608 }
609
610 static size_t calculate_freelist_size(int nr_objs, size_t align)
611 {
612 size_t freelist_size;
613
614 freelist_size = nr_objs * sizeof(freelist_idx_t);
615 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
616 freelist_size += nr_objs * sizeof(char);
617
618 if (align)
619 freelist_size = ALIGN(freelist_size, align);
620
621 return freelist_size;
622 }
623
624 static int calculate_nr_objs(size_t slab_size, size_t buffer_size,
625 size_t idx_size, size_t align)
626 {
627 int nr_objs;
628 size_t remained_size;
629 size_t freelist_size;
630 int extra_space = 0;
631
632 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
633 extra_space = sizeof(char);
634 /*
635 * Ignore padding for the initial guess. The padding
636 * is at most @align-1 bytes, and @buffer_size is at
637 * least @align. In the worst case, this result will
638 * be one greater than the number of objects that fit
639 * into the memory allocation when taking the padding
640 * into account.
641 */
642 nr_objs = slab_size / (buffer_size + idx_size + extra_space);
643
644 /*
645 * This calculated number will be either the right
646 * amount, or one greater than what we want.
647 */
648 remained_size = slab_size - nr_objs * buffer_size;
649 freelist_size = calculate_freelist_size(nr_objs, align);
650 if (remained_size < freelist_size)
651 nr_objs--;
652
653 return nr_objs;
654 }
655
656 /*
657 * Calculate the number of objects and left-over bytes for a given buffer size.
658 */
659 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
660 size_t align, int flags, size_t *left_over,
661 unsigned int *num)
662 {
663 int nr_objs;
664 size_t mgmt_size;
665 size_t slab_size = PAGE_SIZE << gfporder;
666
667 /*
668 * The slab management structure can be either off the slab or
669 * on it. For the latter case, the memory allocated for a
670 * slab is used for:
671 *
672 * - One unsigned int for each object
673 * - Padding to respect alignment of @align
674 * - @buffer_size bytes for each object
675 *
676 * If the slab management structure is off the slab, then the
677 * alignment will already be calculated into the size. Because
678 * the slabs are all pages aligned, the objects will be at the
679 * correct alignment when allocated.
680 */
681 if (flags & CFLGS_OFF_SLAB) {
682 mgmt_size = 0;
683 nr_objs = slab_size / buffer_size;
684
685 } else {
686 nr_objs = calculate_nr_objs(slab_size, buffer_size,
687 sizeof(freelist_idx_t), align);
688 mgmt_size = calculate_freelist_size(nr_objs, align);
689 }
690 *num = nr_objs;
691 *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
692 }
693
694 #if DEBUG
695 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
696
697 static void __slab_error(const char *function, struct kmem_cache *cachep,
698 char *msg)
699 {
700 printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
701 function, cachep->name, msg);
702 dump_stack();
703 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
704 }
705 #endif
706
707 /*
708 * By default on NUMA we use alien caches to stage the freeing of
709 * objects allocated from other nodes. This causes massive memory
710 * inefficiencies when using fake NUMA setup to split memory into a
711 * large number of small nodes, so it can be disabled on the command
712 * line
713 */
714
715 static int use_alien_caches __read_mostly = 1;
716 static int __init noaliencache_setup(char *s)
717 {
718 use_alien_caches = 0;
719 return 1;
720 }
721 __setup("noaliencache", noaliencache_setup);
722
723 static int __init slab_max_order_setup(char *str)
724 {
725 get_option(&str, &slab_max_order);
726 slab_max_order = slab_max_order < 0 ? 0 :
727 min(slab_max_order, MAX_ORDER - 1);
728 slab_max_order_set = true;
729
730 return 1;
731 }
732 __setup("slab_max_order=", slab_max_order_setup);
733
734 #ifdef CONFIG_NUMA
735 /*
736 * Special reaping functions for NUMA systems called from cache_reap().
737 * These take care of doing round robin flushing of alien caches (containing
738 * objects freed on different nodes from which they were allocated) and the
739 * flushing of remote pcps by calling drain_node_pages.
740 */
741 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
742
743 static void init_reap_node(int cpu)
744 {
745 int node;
746
747 node = next_node(cpu_to_mem(cpu), node_online_map);
748 if (node == MAX_NUMNODES)
749 node = first_node(node_online_map);
750
751 per_cpu(slab_reap_node, cpu) = node;
752 }
753
754 static void next_reap_node(void)
755 {
756 int node = __this_cpu_read(slab_reap_node);
757
758 node = next_node(node, node_online_map);
759 if (unlikely(node >= MAX_NUMNODES))
760 node = first_node(node_online_map);
761 __this_cpu_write(slab_reap_node, node);
762 }
763
764 #else
765 #define init_reap_node(cpu) do { } while (0)
766 #define next_reap_node(void) do { } while (0)
767 #endif
768
769 /*
770 * Initiate the reap timer running on the target CPU. We run at around 1 to 2Hz
771 * via the workqueue/eventd.
772 * Add the CPU number into the expiration time to minimize the possibility of
773 * the CPUs getting into lockstep and contending for the global cache chain
774 * lock.
775 */
776 static void start_cpu_timer(int cpu)
777 {
778 struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
779
780 /*
781 * When this gets called from do_initcalls via cpucache_init(),
782 * init_workqueues() has already run, so keventd will be setup
783 * at that time.
784 */
785 if (keventd_up() && reap_work->work.func == NULL) {
786 init_reap_node(cpu);
787 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
788 schedule_delayed_work_on(cpu, reap_work,
789 __round_jiffies_relative(HZ, cpu));
790 }
791 }
792
793 static struct array_cache *alloc_arraycache(int node, int entries,
794 int batchcount, gfp_t gfp)
795 {
796 int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
797 struct array_cache *nc = NULL;
798
799 nc = kmalloc_node(memsize, gfp, node);
800 /*
801 * The array_cache structures contain pointers to free object.
802 * However, when such objects are allocated or transferred to another
803 * cache the pointers are not cleared and they could be counted as
804 * valid references during a kmemleak scan. Therefore, kmemleak must
805 * not scan such objects.
806 */
807 kmemleak_no_scan(nc);
808 if (nc) {
809 nc->avail = 0;
810 nc->limit = entries;
811 nc->batchcount = batchcount;
812 nc->touched = 0;
813 spin_lock_init(&nc->lock);
814 }
815 return nc;
816 }
817
818 static inline bool is_slab_pfmemalloc(struct page *page)
819 {
820 return PageSlabPfmemalloc(page);
821 }
822
823 /* Clears pfmemalloc_active if no slabs have pfmalloc set */
824 static void recheck_pfmemalloc_active(struct kmem_cache *cachep,
825 struct array_cache *ac)
826 {
827 struct kmem_cache_node *n = get_node(cachep, numa_mem_id());
828 struct page *page;
829 unsigned long flags;
830
831 if (!pfmemalloc_active)
832 return;
833
834 spin_lock_irqsave(&n->list_lock, flags);
835 list_for_each_entry(page, &n->slabs_full, lru)
836 if (is_slab_pfmemalloc(page))
837 goto out;
838
839 list_for_each_entry(page, &n->slabs_partial, lru)
840 if (is_slab_pfmemalloc(page))
841 goto out;
842
843 list_for_each_entry(page, &n->slabs_free, lru)
844 if (is_slab_pfmemalloc(page))
845 goto out;
846
847 pfmemalloc_active = false;
848 out:
849 spin_unlock_irqrestore(&n->list_lock, flags);
850 }
851
852 static void *__ac_get_obj(struct kmem_cache *cachep, struct array_cache *ac,
853 gfp_t flags, bool force_refill)
854 {
855 int i;
856 void *objp = ac->entry[--ac->avail];
857
858 /* Ensure the caller is allowed to use objects from PFMEMALLOC slab */
859 if (unlikely(is_obj_pfmemalloc(objp))) {
860 struct kmem_cache_node *n;
861
862 if (gfp_pfmemalloc_allowed(flags)) {
863 clear_obj_pfmemalloc(&objp);
864 return objp;
865 }
866
867 /* The caller cannot use PFMEMALLOC objects, find another one */
868 for (i = 0; i < ac->avail; i++) {
869 /* If a !PFMEMALLOC object is found, swap them */
870 if (!is_obj_pfmemalloc(ac->entry[i])) {
871 objp = ac->entry[i];
872 ac->entry[i] = ac->entry[ac->avail];
873 ac->entry[ac->avail] = objp;
874 return objp;
875 }
876 }
877
878 /*
879 * If there are empty slabs on the slabs_free list and we are
880 * being forced to refill the cache, mark this one !pfmemalloc.
881 */
882 n = get_node(cachep, numa_mem_id());
883 if (!list_empty(&n->slabs_free) && force_refill) {
884 struct page *page = virt_to_head_page(objp);
885 ClearPageSlabPfmemalloc(page);
886 clear_obj_pfmemalloc(&objp);
887 recheck_pfmemalloc_active(cachep, ac);
888 return objp;
889 }
890
891 /* No !PFMEMALLOC objects available */
892 ac->avail++;
893 objp = NULL;
894 }
895
896 return objp;
897 }
898
899 static inline void *ac_get_obj(struct kmem_cache *cachep,
900 struct array_cache *ac, gfp_t flags, bool force_refill)
901 {
902 void *objp;
903
904 if (unlikely(sk_memalloc_socks()))
905 objp = __ac_get_obj(cachep, ac, flags, force_refill);
906 else
907 objp = ac->entry[--ac->avail];
908
909 return objp;
910 }
911
912 static void *__ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
913 void *objp)
914 {
915 if (unlikely(pfmemalloc_active)) {
916 /* Some pfmemalloc slabs exist, check if this is one */
917 struct page *page = virt_to_head_page(objp);
918 if (PageSlabPfmemalloc(page))
919 set_obj_pfmemalloc(&objp);
920 }
921
922 return objp;
923 }
924
925 static inline void ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
926 void *objp)
927 {
928 if (unlikely(sk_memalloc_socks()))
929 objp = __ac_put_obj(cachep, ac, objp);
930
931 ac->entry[ac->avail++] = objp;
932 }
933
934 /*
935 * Transfer objects in one arraycache to another.
936 * Locking must be handled by the caller.
937 *
938 * Return the number of entries transferred.
939 */
940 static int transfer_objects(struct array_cache *to,
941 struct array_cache *from, unsigned int max)
942 {
943 /* Figure out how many entries to transfer */
944 int nr = min3(from->avail, max, to->limit - to->avail);
945
946 if (!nr)
947 return 0;
948
949 memcpy(to->entry + to->avail, from->entry + from->avail -nr,
950 sizeof(void *) *nr);
951
952 from->avail -= nr;
953 to->avail += nr;
954 return nr;
955 }
956
957 #ifndef CONFIG_NUMA
958
959 #define drain_alien_cache(cachep, alien) do { } while (0)
960 #define reap_alien(cachep, n) do { } while (0)
961
962 static inline struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
963 {
964 return (struct array_cache **)BAD_ALIEN_MAGIC;
965 }
966
967 static inline void free_alien_cache(struct array_cache **ac_ptr)
968 {
969 }
970
971 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
972 {
973 return 0;
974 }
975
976 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
977 gfp_t flags)
978 {
979 return NULL;
980 }
981
982 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
983 gfp_t flags, int nodeid)
984 {
985 return NULL;
986 }
987
988 #else /* CONFIG_NUMA */
989
990 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
991 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
992
993 static struct array_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
994 {
995 struct array_cache **ac_ptr;
996 int memsize = sizeof(void *) * nr_node_ids;
997 int i;
998
999 if (limit > 1)
1000 limit = 12;
1001 ac_ptr = kzalloc_node(memsize, gfp, node);
1002 if (ac_ptr) {
1003 for_each_node(i) {
1004 if (i == node || !node_online(i))
1005 continue;
1006 ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d, gfp);
1007 if (!ac_ptr[i]) {
1008 for (i--; i >= 0; i--)
1009 kfree(ac_ptr[i]);
1010 kfree(ac_ptr);
1011 return NULL;
1012 }
1013 }
1014 }
1015 return ac_ptr;
1016 }
1017
1018 static void free_alien_cache(struct array_cache **ac_ptr)
1019 {
1020 int i;
1021
1022 if (!ac_ptr)
1023 return;
1024 for_each_node(i)
1025 kfree(ac_ptr[i]);
1026 kfree(ac_ptr);
1027 }
1028
1029 static void __drain_alien_cache(struct kmem_cache *cachep,
1030 struct array_cache *ac, int node)
1031 {
1032 struct kmem_cache_node *n = get_node(cachep, node);
1033
1034 if (ac->avail) {
1035 spin_lock(&n->list_lock);
1036 /*
1037 * Stuff objects into the remote nodes shared array first.
1038 * That way we could avoid the overhead of putting the objects
1039 * into the free lists and getting them back later.
1040 */
1041 if (n->shared)
1042 transfer_objects(n->shared, ac, ac->limit);
1043
1044 free_block(cachep, ac->entry, ac->avail, node);
1045 ac->avail = 0;
1046 spin_unlock(&n->list_lock);
1047 }
1048 }
1049
1050 /*
1051 * Called from cache_reap() to regularly drain alien caches round robin.
1052 */
1053 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
1054 {
1055 int node = __this_cpu_read(slab_reap_node);
1056
1057 if (n->alien) {
1058 struct array_cache *ac = n->alien[node];
1059
1060 if (ac && ac->avail && spin_trylock_irq(&ac->lock)) {
1061 __drain_alien_cache(cachep, ac, node);
1062 spin_unlock_irq(&ac->lock);
1063 }
1064 }
1065 }
1066
1067 static void drain_alien_cache(struct kmem_cache *cachep,
1068 struct array_cache **alien)
1069 {
1070 int i = 0;
1071 struct array_cache *ac;
1072 unsigned long flags;
1073
1074 for_each_online_node(i) {
1075 ac = alien[i];
1076 if (ac) {
1077 spin_lock_irqsave(&ac->lock, flags);
1078 __drain_alien_cache(cachep, ac, i);
1079 spin_unlock_irqrestore(&ac->lock, flags);
1080 }
1081 }
1082 }
1083
1084 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
1085 {
1086 int nodeid = page_to_nid(virt_to_page(objp));
1087 struct kmem_cache_node *n;
1088 struct array_cache *alien = NULL;
1089 int node;
1090
1091 node = numa_mem_id();
1092
1093 /*
1094 * Make sure we are not freeing a object from another node to the array
1095 * cache on this cpu.
1096 */
1097 if (likely(nodeid == node))
1098 return 0;
1099
1100 n = get_node(cachep, node);
1101 STATS_INC_NODEFREES(cachep);
1102 if (n->alien && n->alien[nodeid]) {
1103 alien = n->alien[nodeid];
1104 spin_lock(&alien->lock);
1105 if (unlikely(alien->avail == alien->limit)) {
1106 STATS_INC_ACOVERFLOW(cachep);
1107 __drain_alien_cache(cachep, alien, nodeid);
1108 }
1109 ac_put_obj(cachep, alien, objp);
1110 spin_unlock(&alien->lock);
1111 } else {
1112 n = get_node(cachep, nodeid);
1113 spin_lock(&n->list_lock);
1114 free_block(cachep, &objp, 1, nodeid);
1115 spin_unlock(&n->list_lock);
1116 }
1117 return 1;
1118 }
1119 #endif
1120
1121 /*
1122 * Allocates and initializes node for a node on each slab cache, used for
1123 * either memory or cpu hotplug. If memory is being hot-added, the kmem_cache_node
1124 * will be allocated off-node since memory is not yet online for the new node.
1125 * When hotplugging memory or a cpu, existing node are not replaced if
1126 * already in use.
1127 *
1128 * Must hold slab_mutex.
1129 */
1130 static int init_cache_node_node(int node)
1131 {
1132 struct kmem_cache *cachep;
1133 struct kmem_cache_node *n;
1134 const int memsize = sizeof(struct kmem_cache_node);
1135
1136 list_for_each_entry(cachep, &slab_caches, list) {
1137 /*
1138 * Set up the kmem_cache_node for cpu before we can
1139 * begin anything. Make sure some other cpu on this
1140 * node has not already allocated this
1141 */
1142 n = get_node(cachep, node);
1143 if (!n) {
1144 n = kmalloc_node(memsize, GFP_KERNEL, node);
1145 if (!n)
1146 return -ENOMEM;
1147 kmem_cache_node_init(n);
1148 n->next_reap = jiffies + REAPTIMEOUT_NODE +
1149 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1150
1151 /*
1152 * The kmem_cache_nodes don't come and go as CPUs
1153 * come and go. slab_mutex is sufficient
1154 * protection here.
1155 */
1156 cachep->node[node] = n;
1157 }
1158
1159 spin_lock_irq(&n->list_lock);
1160 n->free_limit =
1161 (1 + nr_cpus_node(node)) *
1162 cachep->batchcount + cachep->num;
1163 spin_unlock_irq(&n->list_lock);
1164 }
1165 return 0;
1166 }
1167
1168 static inline int slabs_tofree(struct kmem_cache *cachep,
1169 struct kmem_cache_node *n)
1170 {
1171 return (n->free_objects + cachep->num - 1) / cachep->num;
1172 }
1173
1174 static void cpuup_canceled(long cpu)
1175 {
1176 struct kmem_cache *cachep;
1177 struct kmem_cache_node *n = NULL;
1178 int node = cpu_to_mem(cpu);
1179 const struct cpumask *mask = cpumask_of_node(node);
1180
1181 list_for_each_entry(cachep, &slab_caches, list) {
1182 struct array_cache *nc;
1183 struct array_cache *shared;
1184 struct array_cache **alien;
1185
1186 /* cpu is dead; no one can alloc from it. */
1187 nc = cachep->array[cpu];
1188 cachep->array[cpu] = NULL;
1189 n = get_node(cachep, node);
1190
1191 if (!n)
1192 goto free_array_cache;
1193
1194 spin_lock_irq(&n->list_lock);
1195
1196 /* Free limit for this kmem_cache_node */
1197 n->free_limit -= cachep->batchcount;
1198 if (nc)
1199 free_block(cachep, nc->entry, nc->avail, node);
1200
1201 if (!cpumask_empty(mask)) {
1202 spin_unlock_irq(&n->list_lock);
1203 goto free_array_cache;
1204 }
1205
1206 shared = n->shared;
1207 if (shared) {
1208 free_block(cachep, shared->entry,
1209 shared->avail, node);
1210 n->shared = NULL;
1211 }
1212
1213 alien = n->alien;
1214 n->alien = NULL;
1215
1216 spin_unlock_irq(&n->list_lock);
1217
1218 kfree(shared);
1219 if (alien) {
1220 drain_alien_cache(cachep, alien);
1221 free_alien_cache(alien);
1222 }
1223 free_array_cache:
1224 kfree(nc);
1225 }
1226 /*
1227 * In the previous loop, all the objects were freed to
1228 * the respective cache's slabs, now we can go ahead and
1229 * shrink each nodelist to its limit.
1230 */
1231 list_for_each_entry(cachep, &slab_caches, list) {
1232 n = get_node(cachep, node);
1233 if (!n)
1234 continue;
1235 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1236 }
1237 }
1238
1239 static int cpuup_prepare(long cpu)
1240 {
1241 struct kmem_cache *cachep;
1242 struct kmem_cache_node *n = NULL;
1243 int node = cpu_to_mem(cpu);
1244 int err;
1245
1246 /*
1247 * We need to do this right in the beginning since
1248 * alloc_arraycache's are going to use this list.
1249 * kmalloc_node allows us to add the slab to the right
1250 * kmem_cache_node and not this cpu's kmem_cache_node
1251 */
1252 err = init_cache_node_node(node);
1253 if (err < 0)
1254 goto bad;
1255
1256 /*
1257 * Now we can go ahead with allocating the shared arrays and
1258 * array caches
1259 */
1260 list_for_each_entry(cachep, &slab_caches, list) {
1261 struct array_cache *nc;
1262 struct array_cache *shared = NULL;
1263 struct array_cache **alien = NULL;
1264
1265 nc = alloc_arraycache(node, cachep->limit,
1266 cachep->batchcount, GFP_KERNEL);
1267 if (!nc)
1268 goto bad;
1269 if (cachep->shared) {
1270 shared = alloc_arraycache(node,
1271 cachep->shared * cachep->batchcount,
1272 0xbaadf00d, GFP_KERNEL);
1273 if (!shared) {
1274 kfree(nc);
1275 goto bad;
1276 }
1277 }
1278 if (use_alien_caches) {
1279 alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1280 if (!alien) {
1281 kfree(shared);
1282 kfree(nc);
1283 goto bad;
1284 }
1285 }
1286 cachep->array[cpu] = nc;
1287 n = get_node(cachep, node);
1288 BUG_ON(!n);
1289
1290 spin_lock_irq(&n->list_lock);
1291 if (!n->shared) {
1292 /*
1293 * We are serialised from CPU_DEAD or
1294 * CPU_UP_CANCELLED by the cpucontrol lock
1295 */
1296 n->shared = shared;
1297 shared = NULL;
1298 }
1299 #ifdef CONFIG_NUMA
1300 if (!n->alien) {
1301 n->alien = alien;
1302 alien = NULL;
1303 }
1304 #endif
1305 spin_unlock_irq(&n->list_lock);
1306 kfree(shared);
1307 free_alien_cache(alien);
1308 if (cachep->flags & SLAB_DEBUG_OBJECTS)
1309 slab_set_debugobj_lock_classes_node(cachep, n);
1310 else if (!OFF_SLAB(cachep) &&
1311 !(cachep->flags & SLAB_DESTROY_BY_RCU))
1312 on_slab_lock_classes_node(cachep, n);
1313 }
1314 init_node_lock_keys(node);
1315
1316 return 0;
1317 bad:
1318 cpuup_canceled(cpu);
1319 return -ENOMEM;
1320 }
1321
1322 static int cpuup_callback(struct notifier_block *nfb,
1323 unsigned long action, void *hcpu)
1324 {
1325 long cpu = (long)hcpu;
1326 int err = 0;
1327
1328 switch (action) {
1329 case CPU_UP_PREPARE:
1330 case CPU_UP_PREPARE_FROZEN:
1331 mutex_lock(&slab_mutex);
1332 err = cpuup_prepare(cpu);
1333 mutex_unlock(&slab_mutex);
1334 break;
1335 case CPU_ONLINE:
1336 case CPU_ONLINE_FROZEN:
1337 start_cpu_timer(cpu);
1338 break;
1339 #ifdef CONFIG_HOTPLUG_CPU
1340 case CPU_DOWN_PREPARE:
1341 case CPU_DOWN_PREPARE_FROZEN:
1342 /*
1343 * Shutdown cache reaper. Note that the slab_mutex is
1344 * held so that if cache_reap() is invoked it cannot do
1345 * anything expensive but will only modify reap_work
1346 * and reschedule the timer.
1347 */
1348 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1349 /* Now the cache_reaper is guaranteed to be not running. */
1350 per_cpu(slab_reap_work, cpu).work.func = NULL;
1351 break;
1352 case CPU_DOWN_FAILED:
1353 case CPU_DOWN_FAILED_FROZEN:
1354 start_cpu_timer(cpu);
1355 break;
1356 case CPU_DEAD:
1357 case CPU_DEAD_FROZEN:
1358 /*
1359 * Even if all the cpus of a node are down, we don't free the
1360 * kmem_cache_node of any cache. This to avoid a race between
1361 * cpu_down, and a kmalloc allocation from another cpu for
1362 * memory from the node of the cpu going down. The node
1363 * structure is usually allocated from kmem_cache_create() and
1364 * gets destroyed at kmem_cache_destroy().
1365 */
1366 /* fall through */
1367 #endif
1368 case CPU_UP_CANCELED:
1369 case CPU_UP_CANCELED_FROZEN:
1370 mutex_lock(&slab_mutex);
1371 cpuup_canceled(cpu);
1372 mutex_unlock(&slab_mutex);
1373 break;
1374 }
1375 return notifier_from_errno(err);
1376 }
1377
1378 static struct notifier_block cpucache_notifier = {
1379 &cpuup_callback, NULL, 0
1380 };
1381
1382 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1383 /*
1384 * Drains freelist for a node on each slab cache, used for memory hot-remove.
1385 * Returns -EBUSY if all objects cannot be drained so that the node is not
1386 * removed.
1387 *
1388 * Must hold slab_mutex.
1389 */
1390 static int __meminit drain_cache_node_node(int node)
1391 {
1392 struct kmem_cache *cachep;
1393 int ret = 0;
1394
1395 list_for_each_entry(cachep, &slab_caches, list) {
1396 struct kmem_cache_node *n;
1397
1398 n = get_node(cachep, node);
1399 if (!n)
1400 continue;
1401
1402 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1403
1404 if (!list_empty(&n->slabs_full) ||
1405 !list_empty(&n->slabs_partial)) {
1406 ret = -EBUSY;
1407 break;
1408 }
1409 }
1410 return ret;
1411 }
1412
1413 static int __meminit slab_memory_callback(struct notifier_block *self,
1414 unsigned long action, void *arg)
1415 {
1416 struct memory_notify *mnb = arg;
1417 int ret = 0;
1418 int nid;
1419
1420 nid = mnb->status_change_nid;
1421 if (nid < 0)
1422 goto out;
1423
1424 switch (action) {
1425 case MEM_GOING_ONLINE:
1426 mutex_lock(&slab_mutex);
1427 ret = init_cache_node_node(nid);
1428 mutex_unlock(&slab_mutex);
1429 break;
1430 case MEM_GOING_OFFLINE:
1431 mutex_lock(&slab_mutex);
1432 ret = drain_cache_node_node(nid);
1433 mutex_unlock(&slab_mutex);
1434 break;
1435 case MEM_ONLINE:
1436 case MEM_OFFLINE:
1437 case MEM_CANCEL_ONLINE:
1438 case MEM_CANCEL_OFFLINE:
1439 break;
1440 }
1441 out:
1442 return notifier_from_errno(ret);
1443 }
1444 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1445
1446 /*
1447 * swap the static kmem_cache_node with kmalloced memory
1448 */
1449 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1450 int nodeid)
1451 {
1452 struct kmem_cache_node *ptr;
1453
1454 ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1455 BUG_ON(!ptr);
1456
1457 memcpy(ptr, list, sizeof(struct kmem_cache_node));
1458 /*
1459 * Do not assume that spinlocks can be initialized via memcpy:
1460 */
1461 spin_lock_init(&ptr->list_lock);
1462
1463 MAKE_ALL_LISTS(cachep, ptr, nodeid);
1464 cachep->node[nodeid] = ptr;
1465 }
1466
1467 /*
1468 * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1469 * size of kmem_cache_node.
1470 */
1471 static void __init set_up_node(struct kmem_cache *cachep, int index)
1472 {
1473 int node;
1474
1475 for_each_online_node(node) {
1476 cachep->node[node] = &init_kmem_cache_node[index + node];
1477 cachep->node[node]->next_reap = jiffies +
1478 REAPTIMEOUT_NODE +
1479 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1480 }
1481 }
1482
1483 /*
1484 * The memory after the last cpu cache pointer is used for the
1485 * the node pointer.
1486 */
1487 static void setup_node_pointer(struct kmem_cache *cachep)
1488 {
1489 cachep->node = (struct kmem_cache_node **)&cachep->array[nr_cpu_ids];
1490 }
1491
1492 /*
1493 * Initialisation. Called after the page allocator have been initialised and
1494 * before smp_init().
1495 */
1496 void __init kmem_cache_init(void)
1497 {
1498 int i;
1499
1500 BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1501 sizeof(struct rcu_head));
1502 kmem_cache = &kmem_cache_boot;
1503 setup_node_pointer(kmem_cache);
1504
1505 if (num_possible_nodes() == 1)
1506 use_alien_caches = 0;
1507
1508 for (i = 0; i < NUM_INIT_LISTS; i++)
1509 kmem_cache_node_init(&init_kmem_cache_node[i]);
1510
1511 set_up_node(kmem_cache, CACHE_CACHE);
1512
1513 /*
1514 * Fragmentation resistance on low memory - only use bigger
1515 * page orders on machines with more than 32MB of memory if
1516 * not overridden on the command line.
1517 */
1518 if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1519 slab_max_order = SLAB_MAX_ORDER_HI;
1520
1521 /* Bootstrap is tricky, because several objects are allocated
1522 * from caches that do not exist yet:
1523 * 1) initialize the kmem_cache cache: it contains the struct
1524 * kmem_cache structures of all caches, except kmem_cache itself:
1525 * kmem_cache is statically allocated.
1526 * Initially an __init data area is used for the head array and the
1527 * kmem_cache_node structures, it's replaced with a kmalloc allocated
1528 * array at the end of the bootstrap.
1529 * 2) Create the first kmalloc cache.
1530 * The struct kmem_cache for the new cache is allocated normally.
1531 * An __init data area is used for the head array.
1532 * 3) Create the remaining kmalloc caches, with minimally sized
1533 * head arrays.
1534 * 4) Replace the __init data head arrays for kmem_cache and the first
1535 * kmalloc cache with kmalloc allocated arrays.
1536 * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1537 * the other cache's with kmalloc allocated memory.
1538 * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1539 */
1540
1541 /* 1) create the kmem_cache */
1542
1543 /*
1544 * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1545 */
1546 create_boot_cache(kmem_cache, "kmem_cache",
1547 offsetof(struct kmem_cache, array[nr_cpu_ids]) +
1548 nr_node_ids * sizeof(struct kmem_cache_node *),
1549 SLAB_HWCACHE_ALIGN);
1550 list_add(&kmem_cache->list, &slab_caches);
1551
1552 /* 2+3) create the kmalloc caches */
1553
1554 /*
1555 * Initialize the caches that provide memory for the array cache and the
1556 * kmem_cache_node structures first. Without this, further allocations will
1557 * bug.
1558 */
1559
1560 kmalloc_caches[INDEX_AC] = create_kmalloc_cache("kmalloc-ac",
1561 kmalloc_size(INDEX_AC), ARCH_KMALLOC_FLAGS);
1562
1563 if (INDEX_AC != INDEX_NODE)
1564 kmalloc_caches[INDEX_NODE] =
1565 create_kmalloc_cache("kmalloc-node",
1566 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1567
1568 slab_early_init = 0;
1569
1570 /* 4) Replace the bootstrap head arrays */
1571 {
1572 struct array_cache *ptr;
1573
1574 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1575
1576 memcpy(ptr, cpu_cache_get(kmem_cache),
1577 sizeof(struct arraycache_init));
1578 /*
1579 * Do not assume that spinlocks can be initialized via memcpy:
1580 */
1581 spin_lock_init(&ptr->lock);
1582
1583 kmem_cache->array[smp_processor_id()] = ptr;
1584
1585 ptr = kmalloc(sizeof(struct arraycache_init), GFP_NOWAIT);
1586
1587 BUG_ON(cpu_cache_get(kmalloc_caches[INDEX_AC])
1588 != &initarray_generic.cache);
1589 memcpy(ptr, cpu_cache_get(kmalloc_caches[INDEX_AC]),
1590 sizeof(struct arraycache_init));
1591 /*
1592 * Do not assume that spinlocks can be initialized via memcpy:
1593 */
1594 spin_lock_init(&ptr->lock);
1595
1596 kmalloc_caches[INDEX_AC]->array[smp_processor_id()] = ptr;
1597 }
1598 /* 5) Replace the bootstrap kmem_cache_node */
1599 {
1600 int nid;
1601
1602 for_each_online_node(nid) {
1603 init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1604
1605 init_list(kmalloc_caches[INDEX_AC],
1606 &init_kmem_cache_node[SIZE_AC + nid], nid);
1607
1608 if (INDEX_AC != INDEX_NODE) {
1609 init_list(kmalloc_caches[INDEX_NODE],
1610 &init_kmem_cache_node[SIZE_NODE + nid], nid);
1611 }
1612 }
1613 }
1614
1615 create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1616 }
1617
1618 void __init kmem_cache_init_late(void)
1619 {
1620 struct kmem_cache *cachep;
1621
1622 slab_state = UP;
1623
1624 /* 6) resize the head arrays to their final sizes */
1625 mutex_lock(&slab_mutex);
1626 list_for_each_entry(cachep, &slab_caches, list)
1627 if (enable_cpucache(cachep, GFP_NOWAIT))
1628 BUG();
1629 mutex_unlock(&slab_mutex);
1630
1631 /* Annotate slab for lockdep -- annotate the malloc caches */
1632 init_lock_keys();
1633
1634 /* Done! */
1635 slab_state = FULL;
1636
1637 /*
1638 * Register a cpu startup notifier callback that initializes
1639 * cpu_cache_get for all new cpus
1640 */
1641 register_cpu_notifier(&cpucache_notifier);
1642
1643 #ifdef CONFIG_NUMA
1644 /*
1645 * Register a memory hotplug callback that initializes and frees
1646 * node.
1647 */
1648 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1649 #endif
1650
1651 /*
1652 * The reap timers are started later, with a module init call: That part
1653 * of the kernel is not yet operational.
1654 */
1655 }
1656
1657 static int __init cpucache_init(void)
1658 {
1659 int cpu;
1660
1661 /*
1662 * Register the timers that return unneeded pages to the page allocator
1663 */
1664 for_each_online_cpu(cpu)
1665 start_cpu_timer(cpu);
1666
1667 /* Done! */
1668 slab_state = FULL;
1669 return 0;
1670 }
1671 __initcall(cpucache_init);
1672
1673 static noinline void
1674 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1675 {
1676 #if DEBUG
1677 struct kmem_cache_node *n;
1678 struct page *page;
1679 unsigned long flags;
1680 int node;
1681 static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1682 DEFAULT_RATELIMIT_BURST);
1683
1684 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1685 return;
1686
1687 printk(KERN_WARNING
1688 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1689 nodeid, gfpflags);
1690 printk(KERN_WARNING " cache: %s, object size: %d, order: %d\n",
1691 cachep->name, cachep->size, cachep->gfporder);
1692
1693 for_each_kmem_cache_node(cachep, node, n) {
1694 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1695 unsigned long active_slabs = 0, num_slabs = 0;
1696
1697 spin_lock_irqsave(&n->list_lock, flags);
1698 list_for_each_entry(page, &n->slabs_full, lru) {
1699 active_objs += cachep->num;
1700 active_slabs++;
1701 }
1702 list_for_each_entry(page, &n->slabs_partial, lru) {
1703 active_objs += page->active;
1704 active_slabs++;
1705 }
1706 list_for_each_entry(page, &n->slabs_free, lru)
1707 num_slabs++;
1708
1709 free_objects += n->free_objects;
1710 spin_unlock_irqrestore(&n->list_lock, flags);
1711
1712 num_slabs += active_slabs;
1713 num_objs = num_slabs * cachep->num;
1714 printk(KERN_WARNING
1715 " node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1716 node, active_slabs, num_slabs, active_objs, num_objs,
1717 free_objects);
1718 }
1719 #endif
1720 }
1721
1722 /*
1723 * Interface to system's page allocator. No need to hold the cache-lock.
1724 *
1725 * If we requested dmaable memory, we will get it. Even if we
1726 * did not request dmaable memory, we might get it, but that
1727 * would be relatively rare and ignorable.
1728 */
1729 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1730 int nodeid)
1731 {
1732 struct page *page;
1733 int nr_pages;
1734
1735 flags |= cachep->allocflags;
1736 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1737 flags |= __GFP_RECLAIMABLE;
1738
1739 if (memcg_charge_slab(cachep, flags, cachep->gfporder))
1740 return NULL;
1741
1742 page = alloc_pages_exact_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1743 if (!page) {
1744 memcg_uncharge_slab(cachep, cachep->gfporder);
1745 slab_out_of_memory(cachep, flags, nodeid);
1746 return NULL;
1747 }
1748
1749 /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1750 if (unlikely(page->pfmemalloc))
1751 pfmemalloc_active = true;
1752
1753 nr_pages = (1 << cachep->gfporder);
1754 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1755 add_zone_page_state(page_zone(page),
1756 NR_SLAB_RECLAIMABLE, nr_pages);
1757 else
1758 add_zone_page_state(page_zone(page),
1759 NR_SLAB_UNRECLAIMABLE, nr_pages);
1760 __SetPageSlab(page);
1761 if (page->pfmemalloc)
1762 SetPageSlabPfmemalloc(page);
1763
1764 if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1765 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1766
1767 if (cachep->ctor)
1768 kmemcheck_mark_uninitialized_pages(page, nr_pages);
1769 else
1770 kmemcheck_mark_unallocated_pages(page, nr_pages);
1771 }
1772
1773 return page;
1774 }
1775
1776 /*
1777 * Interface to system's page release.
1778 */
1779 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1780 {
1781 const unsigned long nr_freed = (1 << cachep->gfporder);
1782
1783 kmemcheck_free_shadow(page, cachep->gfporder);
1784
1785 if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1786 sub_zone_page_state(page_zone(page),
1787 NR_SLAB_RECLAIMABLE, nr_freed);
1788 else
1789 sub_zone_page_state(page_zone(page),
1790 NR_SLAB_UNRECLAIMABLE, nr_freed);
1791
1792 BUG_ON(!PageSlab(page));
1793 __ClearPageSlabPfmemalloc(page);
1794 __ClearPageSlab(page);
1795 page_mapcount_reset(page);
1796 page->mapping = NULL;
1797
1798 if (current->reclaim_state)
1799 current->reclaim_state->reclaimed_slab += nr_freed;
1800 __free_pages(page, cachep->gfporder);
1801 memcg_uncharge_slab(cachep, cachep->gfporder);
1802 }
1803
1804 static void kmem_rcu_free(struct rcu_head *head)
1805 {
1806 struct kmem_cache *cachep;
1807 struct page *page;
1808
1809 page = container_of(head, struct page, rcu_head);
1810 cachep = page->slab_cache;
1811
1812 kmem_freepages(cachep, page);
1813 }
1814
1815 #if DEBUG
1816
1817 #ifdef CONFIG_DEBUG_PAGEALLOC
1818 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1819 unsigned long caller)
1820 {
1821 int size = cachep->object_size;
1822
1823 addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1824
1825 if (size < 5 * sizeof(unsigned long))
1826 return;
1827
1828 *addr++ = 0x12345678;
1829 *addr++ = caller;
1830 *addr++ = smp_processor_id();
1831 size -= 3 * sizeof(unsigned long);
1832 {
1833 unsigned long *sptr = &caller;
1834 unsigned long svalue;
1835
1836 while (!kstack_end(sptr)) {
1837 svalue = *sptr++;
1838 if (kernel_text_address(svalue)) {
1839 *addr++ = svalue;
1840 size -= sizeof(unsigned long);
1841 if (size <= sizeof(unsigned long))
1842 break;
1843 }
1844 }
1845
1846 }
1847 *addr++ = 0x87654321;
1848 }
1849 #endif
1850
1851 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1852 {
1853 int size = cachep->object_size;
1854 addr = &((char *)addr)[obj_offset(cachep)];
1855
1856 memset(addr, val, size);
1857 *(unsigned char *)(addr + size - 1) = POISON_END;
1858 }
1859
1860 static void dump_line(char *data, int offset, int limit)
1861 {
1862 int i;
1863 unsigned char error = 0;
1864 int bad_count = 0;
1865
1866 printk(KERN_ERR "%03x: ", offset);
1867 for (i = 0; i < limit; i++) {
1868 if (data[offset + i] != POISON_FREE) {
1869 error = data[offset + i];
1870 bad_count++;
1871 }
1872 }
1873 print_hex_dump(KERN_CONT, "", 0, 16, 1,
1874 &data[offset], limit, 1);
1875
1876 if (bad_count == 1) {
1877 error ^= POISON_FREE;
1878 if (!(error & (error - 1))) {
1879 printk(KERN_ERR "Single bit error detected. Probably "
1880 "bad RAM.\n");
1881 #ifdef CONFIG_X86
1882 printk(KERN_ERR "Run memtest86+ or a similar memory "
1883 "test tool.\n");
1884 #else
1885 printk(KERN_ERR "Run a memory test tool.\n");
1886 #endif
1887 }
1888 }
1889 }
1890 #endif
1891
1892 #if DEBUG
1893
1894 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1895 {
1896 int i, size;
1897 char *realobj;
1898
1899 if (cachep->flags & SLAB_RED_ZONE) {
1900 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1901 *dbg_redzone1(cachep, objp),
1902 *dbg_redzone2(cachep, objp));
1903 }
1904
1905 if (cachep->flags & SLAB_STORE_USER) {
1906 printk(KERN_ERR "Last user: [<%p>](%pSR)\n",
1907 *dbg_userword(cachep, objp),
1908 *dbg_userword(cachep, objp));
1909 }
1910 realobj = (char *)objp + obj_offset(cachep);
1911 size = cachep->object_size;
1912 for (i = 0; i < size && lines; i += 16, lines--) {
1913 int limit;
1914 limit = 16;
1915 if (i + limit > size)
1916 limit = size - i;
1917 dump_line(realobj, i, limit);
1918 }
1919 }
1920
1921 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1922 {
1923 char *realobj;
1924 int size, i;
1925 int lines = 0;
1926
1927 realobj = (char *)objp + obj_offset(cachep);
1928 size = cachep->object_size;
1929
1930 for (i = 0; i < size; i++) {
1931 char exp = POISON_FREE;
1932 if (i == size - 1)
1933 exp = POISON_END;
1934 if (realobj[i] != exp) {
1935 int limit;
1936 /* Mismatch ! */
1937 /* Print header */
1938 if (lines == 0) {
1939 printk(KERN_ERR
1940 "Slab corruption (%s): %s start=%p, len=%d\n",
1941 print_tainted(), cachep->name, realobj, size);
1942 print_objinfo(cachep, objp, 0);
1943 }
1944 /* Hexdump the affected line */
1945 i = (i / 16) * 16;
1946 limit = 16;
1947 if (i + limit > size)
1948 limit = size - i;
1949 dump_line(realobj, i, limit);
1950 i += 16;
1951 lines++;
1952 /* Limit to 5 lines */
1953 if (lines > 5)
1954 break;
1955 }
1956 }
1957 if (lines != 0) {
1958 /* Print some data about the neighboring objects, if they
1959 * exist:
1960 */
1961 struct page *page = virt_to_head_page(objp);
1962 unsigned int objnr;
1963
1964 objnr = obj_to_index(cachep, page, objp);
1965 if (objnr) {
1966 objp = index_to_obj(cachep, page, objnr - 1);
1967 realobj = (char *)objp + obj_offset(cachep);
1968 printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1969 realobj, size);
1970 print_objinfo(cachep, objp, 2);
1971 }
1972 if (objnr + 1 < cachep->num) {
1973 objp = index_to_obj(cachep, page, objnr + 1);
1974 realobj = (char *)objp + obj_offset(cachep);
1975 printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1976 realobj, size);
1977 print_objinfo(cachep, objp, 2);
1978 }
1979 }
1980 }
1981 #endif
1982
1983 #if DEBUG
1984 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1985 struct page *page)
1986 {
1987 int i;
1988 for (i = 0; i < cachep->num; i++) {
1989 void *objp = index_to_obj(cachep, page, i);
1990
1991 if (cachep->flags & SLAB_POISON) {
1992 #ifdef CONFIG_DEBUG_PAGEALLOC
1993 if (cachep->size % PAGE_SIZE == 0 &&
1994 OFF_SLAB(cachep))
1995 kernel_map_pages(virt_to_page(objp),
1996 cachep->size / PAGE_SIZE, 1);
1997 else
1998 check_poison_obj(cachep, objp);
1999 #else
2000 check_poison_obj(cachep, objp);
2001 #endif
2002 }
2003 if (cachep->flags & SLAB_RED_ZONE) {
2004 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2005 slab_error(cachep, "start of a freed object "
2006 "was overwritten");
2007 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2008 slab_error(cachep, "end of a freed object "
2009 "was overwritten");
2010 }
2011 }
2012 }
2013 #else
2014 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
2015 struct page *page)
2016 {
2017 }
2018 #endif
2019
2020 /**
2021 * slab_destroy - destroy and release all objects in a slab
2022 * @cachep: cache pointer being destroyed
2023 * @page: page pointer being destroyed
2024 *
2025 * Destroy all the objs in a slab, and release the mem back to the system.
2026 * Before calling the slab must have been unlinked from the cache. The
2027 * cache-lock is not held/needed.
2028 */
2029 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
2030 {
2031 void *freelist;
2032
2033 freelist = page->freelist;
2034 slab_destroy_debugcheck(cachep, page);
2035 if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
2036 struct rcu_head *head;
2037
2038 /*
2039 * RCU free overloads the RCU head over the LRU.
2040 * slab_page has been overloeaded over the LRU,
2041 * however it is not used from now on so that
2042 * we can use it safely.
2043 */
2044 head = (void *)&page->rcu_head;
2045 call_rcu(head, kmem_rcu_free);
2046
2047 } else {
2048 kmem_freepages(cachep, page);
2049 }
2050
2051 /*
2052 * From now on, we don't use freelist
2053 * although actual page can be freed in rcu context
2054 */
2055 if (OFF_SLAB(cachep))
2056 kmem_cache_free(cachep->freelist_cache, freelist);
2057 }
2058
2059 /**
2060 * calculate_slab_order - calculate size (page order) of slabs
2061 * @cachep: pointer to the cache that is being created
2062 * @size: size of objects to be created in this cache.
2063 * @align: required alignment for the objects.
2064 * @flags: slab allocation flags
2065 *
2066 * Also calculates the number of objects per slab.
2067 *
2068 * This could be made much more intelligent. For now, try to avoid using
2069 * high order pages for slabs. When the gfp() functions are more friendly
2070 * towards high-order requests, this should be changed.
2071 */
2072 static size_t calculate_slab_order(struct kmem_cache *cachep,
2073 size_t size, size_t align, unsigned long flags)
2074 {
2075 unsigned long offslab_limit;
2076 size_t left_over = 0;
2077 int gfporder;
2078
2079 for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
2080 unsigned int num;
2081 size_t remainder;
2082
2083 cache_estimate(gfporder, size, align, flags, &remainder, &num);
2084 if (!num)
2085 continue;
2086
2087 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
2088 if (num > SLAB_OBJ_MAX_NUM)
2089 break;
2090
2091 if (flags & CFLGS_OFF_SLAB) {
2092 size_t freelist_size_per_obj = sizeof(freelist_idx_t);
2093 /*
2094 * Max number of objs-per-slab for caches which
2095 * use off-slab slabs. Needed to avoid a possible
2096 * looping condition in cache_grow().
2097 */
2098 if (IS_ENABLED(CONFIG_DEBUG_SLAB_LEAK))
2099 freelist_size_per_obj += sizeof(char);
2100 offslab_limit = size;
2101 offslab_limit /= freelist_size_per_obj;
2102
2103 if (num > offslab_limit)
2104 break;
2105 }
2106
2107 /* Found something acceptable - save it away */
2108 cachep->num = num;
2109 cachep->gfporder = gfporder;
2110 left_over = remainder;
2111
2112 /*
2113 * A VFS-reclaimable slab tends to have most allocations
2114 * as GFP_NOFS and we really don't want to have to be allocating
2115 * higher-order pages when we are unable to shrink dcache.
2116 */
2117 if (flags & SLAB_RECLAIM_ACCOUNT)
2118 break;
2119
2120 /*
2121 * Large number of objects is good, but very large slabs are
2122 * currently bad for the gfp()s.
2123 */
2124 if (gfporder >= slab_max_order)
2125 break;
2126
2127 /*
2128 * Acceptable internal fragmentation?
2129 */
2130 if (left_over * 8 <= (PAGE_SIZE << gfporder))
2131 break;
2132 }
2133 return left_over;
2134 }
2135
2136 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
2137 {
2138 if (slab_state >= FULL)
2139 return enable_cpucache(cachep, gfp);
2140
2141 if (slab_state == DOWN) {
2142 /*
2143 * Note: Creation of first cache (kmem_cache).
2144 * The setup_node is taken care
2145 * of by the caller of __kmem_cache_create
2146 */
2147 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2148 slab_state = PARTIAL;
2149 } else if (slab_state == PARTIAL) {
2150 /*
2151 * Note: the second kmem_cache_create must create the cache
2152 * that's used by kmalloc(24), otherwise the creation of
2153 * further caches will BUG().
2154 */
2155 cachep->array[smp_processor_id()] = &initarray_generic.cache;
2156
2157 /*
2158 * If the cache that's used by kmalloc(sizeof(kmem_cache_node)) is
2159 * the second cache, then we need to set up all its node/,
2160 * otherwise the creation of further caches will BUG().
2161 */
2162 set_up_node(cachep, SIZE_AC);
2163 if (INDEX_AC == INDEX_NODE)
2164 slab_state = PARTIAL_NODE;
2165 else
2166 slab_state = PARTIAL_ARRAYCACHE;
2167 } else {
2168 /* Remaining boot caches */
2169 cachep->array[smp_processor_id()] =
2170 kmalloc(sizeof(struct arraycache_init), gfp);
2171
2172 if (slab_state == PARTIAL_ARRAYCACHE) {
2173 set_up_node(cachep, SIZE_NODE);
2174 slab_state = PARTIAL_NODE;
2175 } else {
2176 int node;
2177 for_each_online_node(node) {
2178 cachep->node[node] =
2179 kmalloc_node(sizeof(struct kmem_cache_node),
2180 gfp, node);
2181 BUG_ON(!cachep->node[node]);
2182 kmem_cache_node_init(cachep->node[node]);
2183 }
2184 }
2185 }
2186 cachep->node[numa_mem_id()]->next_reap =
2187 jiffies + REAPTIMEOUT_NODE +
2188 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
2189
2190 cpu_cache_get(cachep)->avail = 0;
2191 cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
2192 cpu_cache_get(cachep)->batchcount = 1;
2193 cpu_cache_get(cachep)->touched = 0;
2194 cachep->batchcount = 1;
2195 cachep->limit = BOOT_CPUCACHE_ENTRIES;
2196 return 0;
2197 }
2198
2199 /**
2200 * __kmem_cache_create - Create a cache.
2201 * @cachep: cache management descriptor
2202 * @flags: SLAB flags
2203 *
2204 * Returns a ptr to the cache on success, NULL on failure.
2205 * Cannot be called within a int, but can be interrupted.
2206 * The @ctor is run when new pages are allocated by the cache.
2207 *
2208 * The flags are
2209 *
2210 * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2211 * to catch references to uninitialised memory.
2212 *
2213 * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2214 * for buffer overruns.
2215 *
2216 * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2217 * cacheline. This can be beneficial if you're counting cycles as closely
2218 * as davem.
2219 */
2220 int
2221 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2222 {
2223 size_t left_over, freelist_size, ralign;
2224 gfp_t gfp;
2225 int err;
2226 size_t size = cachep->size;
2227
2228 #if DEBUG
2229 #if FORCED_DEBUG
2230 /*
2231 * Enable redzoning and last user accounting, except for caches with
2232 * large objects, if the increased size would increase the object size
2233 * above the next power of two: caches with object sizes just above a
2234 * power of two have a significant amount of internal fragmentation.
2235 */
2236 if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2237 2 * sizeof(unsigned long long)))
2238 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2239 if (!(flags & SLAB_DESTROY_BY_RCU))
2240 flags |= SLAB_POISON;
2241 #endif
2242 if (flags & SLAB_DESTROY_BY_RCU)
2243 BUG_ON(flags & SLAB_POISON);
2244 #endif
2245
2246 /*
2247 * Check that size is in terms of words. This is needed to avoid
2248 * unaligned accesses for some archs when redzoning is used, and makes
2249 * sure any on-slab bufctl's are also correctly aligned.
2250 */
2251 if (size & (BYTES_PER_WORD - 1)) {
2252 size += (BYTES_PER_WORD - 1);
2253 size &= ~(BYTES_PER_WORD - 1);
2254 }
2255
2256 /*
2257 * Redzoning and user store require word alignment or possibly larger.
2258 * Note this will be overridden by architecture or caller mandated
2259 * alignment if either is greater than BYTES_PER_WORD.
2260 */
2261 if (flags & SLAB_STORE_USER)
2262 ralign = BYTES_PER_WORD;
2263
2264 if (flags & SLAB_RED_ZONE) {
2265 ralign = REDZONE_ALIGN;
2266 /* If redzoning, ensure that the second redzone is suitably
2267 * aligned, by adjusting the object size accordingly. */
2268 size += REDZONE_ALIGN - 1;
2269 size &= ~(REDZONE_ALIGN - 1);
2270 }
2271
2272 /* 3) caller mandated alignment */
2273 if (ralign < cachep->align) {
2274 ralign = cachep->align;
2275 }
2276 /* disable debug if necessary */
2277 if (ralign > __alignof__(unsigned long long))
2278 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2279 /*
2280 * 4) Store it.
2281 */
2282 cachep->align = ralign;
2283
2284 if (slab_is_available())
2285 gfp = GFP_KERNEL;
2286 else
2287 gfp = GFP_NOWAIT;
2288
2289 setup_node_pointer(cachep);
2290 #if DEBUG
2291
2292 /*
2293 * Both debugging options require word-alignment which is calculated
2294 * into align above.
2295 */
2296 if (flags & SLAB_RED_ZONE) {
2297 /* add space for red zone words */
2298 cachep->obj_offset += sizeof(unsigned long long);
2299 size += 2 * sizeof(unsigned long long);
2300 }
2301 if (flags & SLAB_STORE_USER) {
2302 /* user store requires one word storage behind the end of
2303 * the real object. But if the second red zone needs to be
2304 * aligned to 64 bits, we must allow that much space.
2305 */
2306 if (flags & SLAB_RED_ZONE)
2307 size += REDZONE_ALIGN;
2308 else
2309 size += BYTES_PER_WORD;
2310 }
2311 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2312 if (size >= kmalloc_size(INDEX_NODE + 1)
2313 && cachep->object_size > cache_line_size()
2314 && ALIGN(size, cachep->align) < PAGE_SIZE) {
2315 cachep->obj_offset += PAGE_SIZE - ALIGN(size, cachep->align);
2316 size = PAGE_SIZE;
2317 }
2318 #endif
2319 #endif
2320
2321 /*
2322 * Determine if the slab management is 'on' or 'off' slab.
2323 * (bootstrapping cannot cope with offslab caches so don't do
2324 * it too early on. Always use on-slab management when
2325 * SLAB_NOLEAKTRACE to avoid recursive calls into kmemleak)
2326 */
2327 if ((size >= (PAGE_SIZE >> 5)) && !slab_early_init &&
2328 !(flags & SLAB_NOLEAKTRACE))
2329 /*
2330 * Size is large, assume best to place the slab management obj
2331 * off-slab (should allow better packing of objs).
2332 */
2333 flags |= CFLGS_OFF_SLAB;
2334
2335 size = ALIGN(size, cachep->align);
2336 /*
2337 * We should restrict the number of objects in a slab to implement
2338 * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
2339 */
2340 if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
2341 size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
2342
2343 left_over = calculate_slab_order(cachep, size, cachep->align, flags);
2344
2345 if (!cachep->num)
2346 return -E2BIG;
2347
2348 freelist_size = calculate_freelist_size(cachep->num, cachep->align);
2349
2350 /*
2351 * If the slab has been placed off-slab, and we have enough space then
2352 * move it on-slab. This is at the expense of any extra colouring.
2353 */
2354 if (flags & CFLGS_OFF_SLAB && left_over >= freelist_size) {
2355 flags &= ~CFLGS_OFF_SLAB;
2356 left_over -= freelist_size;
2357 }
2358
2359 if (flags & CFLGS_OFF_SLAB) {
2360 /* really off slab. No need for manual alignment */
2361 freelist_size = calculate_freelist_size(cachep->num, 0);
2362
2363 #ifdef CONFIG_PAGE_POISONING
2364 /* If we're going to use the generic kernel_map_pages()
2365 * poisoning, then it's going to smash the contents of
2366 * the redzone and userword anyhow, so switch them off.
2367 */
2368 if (size % PAGE_SIZE == 0 && flags & SLAB_POISON)
2369 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2370 #endif
2371 }
2372
2373 cachep->colour_off = cache_line_size();
2374 /* Offset must be a multiple of the alignment. */
2375 if (cachep->colour_off < cachep->align)
2376 cachep->colour_off = cachep->align;
2377 cachep->colour = left_over / cachep->colour_off;
2378 cachep->freelist_size = freelist_size;
2379 cachep->flags = flags;
2380 cachep->allocflags = __GFP_COMP;
2381 if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2382 cachep->allocflags |= GFP_DMA;
2383 cachep->size = size;
2384 cachep->reciprocal_buffer_size = reciprocal_value(size);
2385
2386 if (flags & CFLGS_OFF_SLAB) {
2387 cachep->freelist_cache = kmalloc_slab(freelist_size, 0u);
2388 /*
2389 * This is a possibility for one of the kmalloc_{dma,}_caches.
2390 * But since we go off slab only for object size greater than
2391 * PAGE_SIZE/8, and kmalloc_{dma,}_caches get created
2392 * in ascending order,this should not happen at all.
2393 * But leave a BUG_ON for some lucky dude.
2394 */
2395 BUG_ON(ZERO_OR_NULL_PTR(cachep->freelist_cache));
2396 }
2397
2398 err = setup_cpu_cache(cachep, gfp);
2399 if (err) {
2400 __kmem_cache_shutdown(cachep);
2401 return err;
2402 }
2403
2404 if (flags & SLAB_DEBUG_OBJECTS) {
2405 /*
2406 * Would deadlock through slab_destroy()->call_rcu()->
2407 * debug_object_activate()->kmem_cache_alloc().
2408 */
2409 WARN_ON_ONCE(flags & SLAB_DESTROY_BY_RCU);
2410
2411 slab_set_debugobj_lock_classes(cachep);
2412 } else if (!OFF_SLAB(cachep) && !(flags & SLAB_DESTROY_BY_RCU))
2413 on_slab_lock_classes(cachep);
2414
2415 return 0;
2416 }
2417
2418 #if DEBUG
2419 static void check_irq_off(void)
2420 {
2421 BUG_ON(!irqs_disabled());
2422 }
2423
2424 static void check_irq_on(void)
2425 {
2426 BUG_ON(irqs_disabled());
2427 }
2428
2429 static void check_spinlock_acquired(struct kmem_cache *cachep)
2430 {
2431 #ifdef CONFIG_SMP
2432 check_irq_off();
2433 assert_spin_locked(&get_node(cachep, numa_mem_id())->list_lock);
2434 #endif
2435 }
2436
2437 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2438 {
2439 #ifdef CONFIG_SMP
2440 check_irq_off();
2441 assert_spin_locked(&get_node(cachep, node)->list_lock);
2442 #endif
2443 }
2444
2445 #else
2446 #define check_irq_off() do { } while(0)
2447 #define check_irq_on() do { } while(0)
2448 #define check_spinlock_acquired(x) do { } while(0)
2449 #define check_spinlock_acquired_node(x, y) do { } while(0)
2450 #endif
2451
2452 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
2453 struct array_cache *ac,
2454 int force, int node);
2455
2456 static void do_drain(void *arg)
2457 {
2458 struct kmem_cache *cachep = arg;
2459 struct array_cache *ac;
2460 int node = numa_mem_id();
2461 struct kmem_cache_node *n;
2462
2463 check_irq_off();
2464 ac = cpu_cache_get(cachep);
2465 n = get_node(cachep, node);
2466 spin_lock(&n->list_lock);
2467 free_block(cachep, ac->entry, ac->avail, node);
2468 spin_unlock(&n->list_lock);
2469 ac->avail = 0;
2470 }
2471
2472 static void drain_cpu_caches(struct kmem_cache *cachep)
2473 {
2474 struct kmem_cache_node *n;
2475 int node;
2476
2477 on_each_cpu(do_drain, cachep, 1);
2478 check_irq_on();
2479 for_each_kmem_cache_node(cachep, node, n)
2480 if (n->alien)
2481 drain_alien_cache(cachep, n->alien);
2482
2483 for_each_kmem_cache_node(cachep, node, n)
2484 drain_array(cachep, n, n->shared, 1, node);
2485 }
2486
2487 /*
2488 * Remove slabs from the list of free slabs.
2489 * Specify the number of slabs to drain in tofree.
2490 *
2491 * Returns the actual number of slabs released.
2492 */
2493 static int drain_freelist(struct kmem_cache *cache,
2494 struct kmem_cache_node *n, int tofree)
2495 {
2496 struct list_head *p;
2497 int nr_freed;
2498 struct page *page;
2499
2500 nr_freed = 0;
2501 while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
2502
2503 spin_lock_irq(&n->list_lock);
2504 p = n->slabs_free.prev;
2505 if (p == &n->slabs_free) {
2506 spin_unlock_irq(&n->list_lock);
2507 goto out;
2508 }
2509
2510 page = list_entry(p, struct page, lru);
2511 #if DEBUG
2512 BUG_ON(page->active);
2513 #endif
2514 list_del(&page->lru);
2515 /*
2516 * Safe to drop the lock. The slab is no longer linked
2517 * to the cache.
2518 */
2519 n->free_objects -= cache->num;
2520 spin_unlock_irq(&n->list_lock);
2521 slab_destroy(cache, page);
2522 nr_freed++;
2523 }
2524 out:
2525 return nr_freed;
2526 }
2527
2528 int __kmem_cache_shrink(struct kmem_cache *cachep)
2529 {
2530 int ret = 0;
2531 int node;
2532 struct kmem_cache_node *n;
2533
2534 drain_cpu_caches(cachep);
2535
2536 check_irq_on();
2537 for_each_kmem_cache_node(cachep, node, n) {
2538 drain_freelist(cachep, n, slabs_tofree(cachep, n));
2539
2540 ret += !list_empty(&n->slabs_full) ||
2541 !list_empty(&n->slabs_partial);
2542 }
2543 return (ret ? 1 : 0);
2544 }
2545
2546 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2547 {
2548 int i;
2549 struct kmem_cache_node *n;
2550 int rc = __kmem_cache_shrink(cachep);
2551
2552 if (rc)
2553 return rc;
2554
2555 for_each_online_cpu(i)
2556 kfree(cachep->array[i]);
2557
2558 /* NUMA: free the node structures */
2559 for_each_kmem_cache_node(cachep, i, n) {
2560 kfree(n->shared);
2561 free_alien_cache(n->alien);
2562 kfree(n);
2563 cachep->node[i] = NULL;
2564 }
2565 return 0;
2566 }
2567
2568 /*
2569 * Get the memory for a slab management obj.
2570 *
2571 * For a slab cache when the slab descriptor is off-slab, the
2572 * slab descriptor can't come from the same cache which is being created,
2573 * Because if it is the case, that means we defer the creation of
2574 * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
2575 * And we eventually call down to __kmem_cache_create(), which
2576 * in turn looks up in the kmalloc_{dma,}_caches for the disired-size one.
2577 * This is a "chicken-and-egg" problem.
2578 *
2579 * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
2580 * which are all initialized during kmem_cache_init().
2581 */
2582 static void *alloc_slabmgmt(struct kmem_cache *cachep,
2583 struct page *page, int colour_off,
2584 gfp_t local_flags, int nodeid)
2585 {
2586 void *freelist;
2587 void *addr = page_address(page);
2588
2589 if (OFF_SLAB(cachep)) {
2590 /* Slab management obj is off-slab. */
2591 freelist = kmem_cache_alloc_node(cachep->freelist_cache,
2592 local_flags, nodeid);
2593 if (!freelist)
2594 return NULL;
2595 } else {
2596 freelist = addr + colour_off;
2597 colour_off += cachep->freelist_size;
2598 }
2599 page->active = 0;
2600 page->s_mem = addr + colour_off;
2601 return freelist;
2602 }
2603
2604 static inline freelist_idx_t get_free_obj(struct page *page, unsigned int idx)
2605 {
2606 return ((freelist_idx_t *)page->freelist)[idx];
2607 }
2608
2609 static inline void set_free_obj(struct page *page,
2610 unsigned int idx, freelist_idx_t val)
2611 {
2612 ((freelist_idx_t *)(page->freelist))[idx] = val;
2613 }
2614
2615 static void cache_init_objs(struct kmem_cache *cachep,
2616 struct page *page)
2617 {
2618 int i;
2619
2620 for (i = 0; i < cachep->num; i++) {
2621 void *objp = index_to_obj(cachep, page, i);
2622 #if DEBUG
2623 /* need to poison the objs? */
2624 if (cachep->flags & SLAB_POISON)
2625 poison_obj(cachep, objp, POISON_FREE);
2626 if (cachep->flags & SLAB_STORE_USER)
2627 *dbg_userword(cachep, objp) = NULL;
2628
2629 if (cachep->flags & SLAB_RED_ZONE) {
2630 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2631 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2632 }
2633 /*
2634 * Constructors are not allowed to allocate memory from the same
2635 * cache which they are a constructor for. Otherwise, deadlock.
2636 * They must also be threaded.
2637 */
2638 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2639 cachep->ctor(objp + obj_offset(cachep));
2640
2641 if (cachep->flags & SLAB_RED_ZONE) {
2642 if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2643 slab_error(cachep, "constructor overwrote the"
2644 " end of an object");
2645 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2646 slab_error(cachep, "constructor overwrote the"
2647 " start of an object");
2648 }
2649 if ((cachep->size % PAGE_SIZE) == 0 &&
2650 OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2651 kernel_map_pages(virt_to_page(objp),
2652 cachep->size / PAGE_SIZE, 0);
2653 #else
2654 if (cachep->ctor)
2655 cachep->ctor(objp);
2656 #endif
2657 set_obj_status(page, i, OBJECT_FREE);
2658 set_free_obj(page, i, i);
2659 }
2660 }
2661
2662 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2663 {
2664 if (CONFIG_ZONE_DMA_FLAG) {
2665 if (flags & GFP_DMA)
2666 BUG_ON(!(cachep->allocflags & GFP_DMA));
2667 else
2668 BUG_ON(cachep->allocflags & GFP_DMA);
2669 }
2670 }
2671
2672 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page,
2673 int nodeid)
2674 {
2675 void *objp;
2676
2677 objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2678 page->active++;
2679 #if DEBUG
2680 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2681 #endif
2682
2683 return objp;
2684 }
2685
2686 static void slab_put_obj(struct kmem_cache *cachep, struct page *page,
2687 void *objp, int nodeid)
2688 {
2689 unsigned int objnr = obj_to_index(cachep, page, objp);
2690 #if DEBUG
2691 unsigned int i;
2692
2693 /* Verify that the slab belongs to the intended node */
2694 WARN_ON(page_to_nid(virt_to_page(objp)) != nodeid);
2695
2696 /* Verify double free bug */
2697 for (i = page->active; i < cachep->num; i++) {
2698 if (get_free_obj(page, i) == objnr) {
2699 printk(KERN_ERR "slab: double free detected in cache "
2700 "'%s', objp %p\n", cachep->name, objp);
2701 BUG();
2702 }
2703 }
2704 #endif
2705 page->active--;
2706 set_free_obj(page, page->active, objnr);
2707 }
2708
2709 /*
2710 * Map pages beginning at addr to the given cache and slab. This is required
2711 * for the slab allocator to be able to lookup the cache and slab of a
2712 * virtual address for kfree, ksize, and slab debugging.
2713 */
2714 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2715 void *freelist)
2716 {
2717 page->slab_cache = cache;
2718 page->freelist = freelist;
2719 }
2720
2721 /*
2722 * Grow (by 1) the number of slabs within a cache. This is called by
2723 * kmem_cache_alloc() when there are no active objs left in a cache.
2724 */
2725 static int cache_grow(struct kmem_cache *cachep,
2726 gfp_t flags, int nodeid, struct page *page)
2727 {
2728 void *freelist;
2729 size_t offset;
2730 gfp_t local_flags;
2731 struct kmem_cache_node *n;
2732
2733 /*
2734 * Be lazy and only check for valid flags here, keeping it out of the
2735 * critical path in kmem_cache_alloc().
2736 */
2737 BUG_ON(flags & GFP_SLAB_BUG_MASK);
2738 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2739
2740 /* Take the node list lock to change the colour_next on this node */
2741 check_irq_off();
2742 n = get_node(cachep, nodeid);
2743 spin_lock(&n->list_lock);
2744
2745 /* Get colour for the slab, and cal the next value. */
2746 offset = n->colour_next;
2747 n->colour_next++;
2748 if (n->colour_next >= cachep->colour)
2749 n->colour_next = 0;
2750 spin_unlock(&n->list_lock);
2751
2752 offset *= cachep->colour_off;
2753
2754 if (local_flags & __GFP_WAIT)
2755 local_irq_enable();
2756
2757 /*
2758 * The test for missing atomic flag is performed here, rather than
2759 * the more obvious place, simply to reduce the critical path length
2760 * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2761 * will eventually be caught here (where it matters).
2762 */
2763 kmem_flagcheck(cachep, flags);
2764
2765 /*
2766 * Get mem for the objs. Attempt to allocate a physical page from
2767 * 'nodeid'.
2768 */
2769 if (!page)
2770 page = kmem_getpages(cachep, local_flags, nodeid);
2771 if (!page)
2772 goto failed;
2773
2774 /* Get slab management. */
2775 freelist = alloc_slabmgmt(cachep, page, offset,
2776 local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2777 if (!freelist)
2778 goto opps1;
2779
2780 slab_map_pages(cachep, page, freelist);
2781
2782 cache_init_objs(cachep, page);
2783
2784 if (local_flags & __GFP_WAIT)
2785 local_irq_disable();
2786 check_irq_off();
2787 spin_lock(&n->list_lock);
2788
2789 /* Make slab active. */
2790 list_add_tail(&page->lru, &(n->slabs_free));
2791 STATS_INC_GROWN(cachep);
2792 n->free_objects += cachep->num;
2793 spin_unlock(&n->list_lock);
2794 return 1;
2795 opps1:
2796 kmem_freepages(cachep, page);
2797 failed:
2798 if (local_flags & __GFP_WAIT)
2799 local_irq_disable();
2800 return 0;
2801 }
2802
2803 #if DEBUG
2804
2805 /*
2806 * Perform extra freeing checks:
2807 * - detect bad pointers.
2808 * - POISON/RED_ZONE checking
2809 */
2810 static void kfree_debugcheck(const void *objp)
2811 {
2812 if (!virt_addr_valid(objp)) {
2813 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2814 (unsigned long)objp);
2815 BUG();
2816 }
2817 }
2818
2819 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2820 {
2821 unsigned long long redzone1, redzone2;
2822
2823 redzone1 = *dbg_redzone1(cache, obj);
2824 redzone2 = *dbg_redzone2(cache, obj);
2825
2826 /*
2827 * Redzone is ok.
2828 */
2829 if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2830 return;
2831
2832 if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2833 slab_error(cache, "double free detected");
2834 else
2835 slab_error(cache, "memory outside object was overwritten");
2836
2837 printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2838 obj, redzone1, redzone2);
2839 }
2840
2841 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2842 unsigned long caller)
2843 {
2844 unsigned int objnr;
2845 struct page *page;
2846
2847 BUG_ON(virt_to_cache(objp) != cachep);
2848
2849 objp -= obj_offset(cachep);
2850 kfree_debugcheck(objp);
2851 page = virt_to_head_page(objp);
2852
2853 if (cachep->flags & SLAB_RED_ZONE) {
2854 verify_redzone_free(cachep, objp);
2855 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2856 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2857 }
2858 if (cachep->flags & SLAB_STORE_USER)
2859 *dbg_userword(cachep, objp) = (void *)caller;
2860
2861 objnr = obj_to_index(cachep, page, objp);
2862
2863 BUG_ON(objnr >= cachep->num);
2864 BUG_ON(objp != index_to_obj(cachep, page, objnr));
2865
2866 set_obj_status(page, objnr, OBJECT_FREE);
2867 if (cachep->flags & SLAB_POISON) {
2868 #ifdef CONFIG_DEBUG_PAGEALLOC
2869 if ((cachep->size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2870 store_stackinfo(cachep, objp, caller);
2871 kernel_map_pages(virt_to_page(objp),
2872 cachep->size / PAGE_SIZE, 0);
2873 } else {
2874 poison_obj(cachep, objp, POISON_FREE);
2875 }
2876 #else
2877 poison_obj(cachep, objp, POISON_FREE);
2878 #endif
2879 }
2880 return objp;
2881 }
2882
2883 #else
2884 #define kfree_debugcheck(x) do { } while(0)
2885 #define cache_free_debugcheck(x,objp,z) (objp)
2886 #endif
2887
2888 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
2889 bool force_refill)
2890 {
2891 int batchcount;
2892 struct kmem_cache_node *n;
2893 struct array_cache *ac;
2894 int node;
2895
2896 check_irq_off();
2897 node = numa_mem_id();
2898 if (unlikely(force_refill))
2899 goto force_grow;
2900 retry:
2901 ac = cpu_cache_get(cachep);
2902 batchcount = ac->batchcount;
2903 if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2904 /*
2905 * If there was little recent activity on this cache, then
2906 * perform only a partial refill. Otherwise we could generate
2907 * refill bouncing.
2908 */
2909 batchcount = BATCHREFILL_LIMIT;
2910 }
2911 n = get_node(cachep, node);
2912
2913 BUG_ON(ac->avail > 0 || !n);
2914 spin_lock(&n->list_lock);
2915
2916 /* See if we can refill from the shared array */
2917 if (n->shared && transfer_objects(ac, n->shared, batchcount)) {
2918 n->shared->touched = 1;
2919 goto alloc_done;
2920 }
2921
2922 while (batchcount > 0) {
2923 struct list_head *entry;
2924 struct page *page;
2925 /* Get slab alloc is to come from. */
2926 entry = n->slabs_partial.next;
2927 if (entry == &n->slabs_partial) {
2928 n->free_touched = 1;
2929 entry = n->slabs_free.next;
2930 if (entry == &n->slabs_free)
2931 goto must_grow;
2932 }
2933
2934 page = list_entry(entry, struct page, lru);
2935 check_spinlock_acquired(cachep);
2936
2937 /*
2938 * The slab was either on partial or free list so
2939 * there must be at least one object available for
2940 * allocation.
2941 */
2942 BUG_ON(page->active >= cachep->num);
2943
2944 while (page->active < cachep->num && batchcount--) {
2945 STATS_INC_ALLOCED(cachep);
2946 STATS_INC_ACTIVE(cachep);
2947 STATS_SET_HIGH(cachep);
2948
2949 ac_put_obj(cachep, ac, slab_get_obj(cachep, page,
2950 node));
2951 }
2952
2953 /* move slabp to correct slabp list: */
2954 list_del(&page->lru);
2955 if (page->active == cachep->num)
2956 list_add(&page->lru, &n->slabs_full);
2957 else
2958 list_add(&page->lru, &n->slabs_partial);
2959 }
2960
2961 must_grow:
2962 n->free_objects -= ac->avail;
2963 alloc_done:
2964 spin_unlock(&n->list_lock);
2965
2966 if (unlikely(!ac->avail)) {
2967 int x;
2968 force_grow:
2969 x = cache_grow(cachep, flags | GFP_THISNODE, node, NULL);
2970
2971 /* cache_grow can reenable interrupts, then ac could change. */
2972 ac = cpu_cache_get(cachep);
2973 node = numa_mem_id();
2974
2975 /* no objects in sight? abort */
2976 if (!x && (ac->avail == 0 || force_refill))
2977 return NULL;
2978
2979 if (!ac->avail) /* objects refilled by interrupt? */
2980 goto retry;
2981 }
2982 ac->touched = 1;
2983
2984 return ac_get_obj(cachep, ac, flags, force_refill);
2985 }
2986
2987 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2988 gfp_t flags)
2989 {
2990 might_sleep_if(flags & __GFP_WAIT);
2991 #if DEBUG
2992 kmem_flagcheck(cachep, flags);
2993 #endif
2994 }
2995
2996 #if DEBUG
2997 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
2998 gfp_t flags, void *objp, unsigned long caller)
2999 {
3000 struct page *page;
3001
3002 if (!objp)
3003 return objp;
3004 if (cachep->flags & SLAB_POISON) {
3005 #ifdef CONFIG_DEBUG_PAGEALLOC
3006 if ((cachep->size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
3007 kernel_map_pages(virt_to_page(objp),
3008 cachep->size / PAGE_SIZE, 1);
3009 else
3010 check_poison_obj(cachep, objp);
3011 #else
3012 check_poison_obj(cachep, objp);
3013 #endif
3014 poison_obj(cachep, objp, POISON_INUSE);
3015 }
3016 if (cachep->flags & SLAB_STORE_USER)
3017 *dbg_userword(cachep, objp) = (void *)caller;
3018
3019 if (cachep->flags & SLAB_RED_ZONE) {
3020 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
3021 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
3022 slab_error(cachep, "double free, or memory outside"
3023 " object was overwritten");
3024 printk(KERN_ERR
3025 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
3026 objp, *dbg_redzone1(cachep, objp),
3027 *dbg_redzone2(cachep, objp));
3028 }
3029 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
3030 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
3031 }
3032
3033 page = virt_to_head_page(objp);
3034 set_obj_status(page, obj_to_index(cachep, page, objp), OBJECT_ACTIVE);
3035 objp += obj_offset(cachep);
3036 if (cachep->ctor && cachep->flags & SLAB_POISON)
3037 cachep->ctor(objp);
3038 if (ARCH_SLAB_MINALIGN &&
3039 ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
3040 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
3041 objp, (int)ARCH_SLAB_MINALIGN);
3042 }
3043 return objp;
3044 }
3045 #else
3046 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
3047 #endif
3048
3049 static bool slab_should_failslab(struct kmem_cache *cachep, gfp_t flags)
3050 {
3051 if (cachep == kmem_cache)
3052 return false;
3053
3054 return should_failslab(cachep->object_size, flags, cachep->flags);
3055 }
3056
3057 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3058 {
3059 void *objp;
3060 struct array_cache *ac;
3061 bool force_refill = false;
3062
3063 check_irq_off();
3064
3065 ac = cpu_cache_get(cachep);
3066 if (likely(ac->avail)) {
3067 ac->touched = 1;
3068 objp = ac_get_obj(cachep, ac, flags, false);
3069
3070 /*
3071 * Allow for the possibility all avail objects are not allowed
3072 * by the current flags
3073 */
3074 if (objp) {
3075 STATS_INC_ALLOCHIT(cachep);
3076 goto out;
3077 }
3078 force_refill = true;
3079 }
3080
3081 STATS_INC_ALLOCMISS(cachep);
3082 objp = cache_alloc_refill(cachep, flags, force_refill);
3083 /*
3084 * the 'ac' may be updated by cache_alloc_refill(),
3085 * and kmemleak_erase() requires its correct value.
3086 */
3087 ac = cpu_cache_get(cachep);
3088
3089 out:
3090 /*
3091 * To avoid a false negative, if an object that is in one of the
3092 * per-CPU caches is leaked, we need to make sure kmemleak doesn't
3093 * treat the array pointers as a reference to the object.
3094 */
3095 if (objp)
3096 kmemleak_erase(&ac->entry[ac->avail]);
3097 return objp;
3098 }
3099
3100 #ifdef CONFIG_NUMA
3101 /*
3102 * Try allocating on another node if PF_SPREAD_SLAB is a mempolicy is set.
3103 *
3104 * If we are in_interrupt, then process context, including cpusets and
3105 * mempolicy, may not apply and should not be used for allocation policy.
3106 */
3107 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
3108 {
3109 int nid_alloc, nid_here;
3110
3111 if (in_interrupt() || (flags & __GFP_THISNODE))
3112 return NULL;
3113 nid_alloc = nid_here = numa_mem_id();
3114 if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
3115 nid_alloc = cpuset_slab_spread_node();
3116 else if (current->mempolicy)
3117 nid_alloc = mempolicy_slab_node();
3118 if (nid_alloc != nid_here)
3119 return ____cache_alloc_node(cachep, flags, nid_alloc);
3120 return NULL;
3121 }
3122
3123 /*
3124 * Fallback function if there was no memory available and no objects on a
3125 * certain node and fall back is permitted. First we scan all the
3126 * available node for available objects. If that fails then we
3127 * perform an allocation without specifying a node. This allows the page
3128 * allocator to do its reclaim / fallback magic. We then insert the
3129 * slab into the proper nodelist and then allocate from it.
3130 */
3131 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
3132 {
3133 struct zonelist *zonelist;
3134 gfp_t local_flags;
3135 struct zoneref *z;
3136 struct zone *zone;
3137 enum zone_type high_zoneidx = gfp_zone(flags);
3138 void *obj = NULL;
3139 int nid;
3140 unsigned int cpuset_mems_cookie;
3141
3142 if (flags & __GFP_THISNODE)
3143 return NULL;
3144
3145 local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
3146
3147 retry_cpuset:
3148 cpuset_mems_cookie = read_mems_allowed_begin();
3149 zonelist = node_zonelist(mempolicy_slab_node(), flags);
3150
3151 retry:
3152 /*
3153 * Look through allowed nodes for objects available
3154 * from existing per node queues.
3155 */
3156 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3157 nid = zone_to_nid(zone);
3158
3159 if (cpuset_zone_allowed_hardwall(zone, flags) &&
3160 get_node(cache, nid) &&
3161 get_node(cache, nid)->free_objects) {
3162 obj = ____cache_alloc_node(cache,
3163 flags | GFP_THISNODE, nid);
3164 if (obj)
3165 break;
3166 }
3167 }
3168
3169 if (!obj) {
3170 /*
3171 * This allocation will be performed within the constraints
3172 * of the current cpuset / memory policy requirements.
3173 * We may trigger various forms of reclaim on the allowed
3174 * set and go into memory reserves if necessary.
3175 */
3176 struct page *page;
3177
3178 if (local_flags & __GFP_WAIT)
3179 local_irq_enable();
3180 kmem_flagcheck(cache, flags);
3181 page = kmem_getpages(cache, local_flags, numa_mem_id());
3182 if (local_flags & __GFP_WAIT)
3183 local_irq_disable();
3184 if (page) {
3185 /*
3186 * Insert into the appropriate per node queues
3187 */
3188 nid = page_to_nid(page);
3189 if (cache_grow(cache, flags, nid, page)) {
3190 obj = ____cache_alloc_node(cache,
3191 flags | GFP_THISNODE, nid);
3192 if (!obj)
3193 /*
3194 * Another processor may allocate the
3195 * objects in the slab since we are
3196 * not holding any locks.
3197 */
3198 goto retry;
3199 } else {
3200 /* cache_grow already freed obj */
3201 obj = NULL;
3202 }
3203 }
3204 }
3205
3206 if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3207 goto retry_cpuset;
3208 return obj;
3209 }
3210
3211 /*
3212 * A interface to enable slab creation on nodeid
3213 */
3214 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3215 int nodeid)
3216 {
3217 struct list_head *entry;
3218 struct page *page;
3219 struct kmem_cache_node *n;
3220 void *obj;
3221 int x;
3222
3223 VM_BUG_ON(nodeid > num_online_nodes());
3224 n = get_node(cachep, nodeid);
3225 BUG_ON(!n);
3226
3227 retry:
3228 check_irq_off();
3229 spin_lock(&n->list_lock);
3230 entry = n->slabs_partial.next;
3231 if (entry == &n->slabs_partial) {
3232 n->free_touched = 1;
3233 entry = n->slabs_free.next;
3234 if (entry == &n->slabs_free)
3235 goto must_grow;
3236 }
3237
3238 page = list_entry(entry, struct page, lru);
3239 check_spinlock_acquired_node(cachep, nodeid);
3240
3241 STATS_INC_NODEALLOCS(cachep);
3242 STATS_INC_ACTIVE(cachep);
3243 STATS_SET_HIGH(cachep);
3244
3245 BUG_ON(page->active == cachep->num);
3246
3247 obj = slab_get_obj(cachep, page, nodeid);
3248 n->free_objects--;
3249 /* move slabp to correct slabp list: */
3250 list_del(&page->lru);
3251
3252 if (page->active == cachep->num)
3253 list_add(&page->lru, &n->slabs_full);
3254 else
3255 list_add(&page->lru, &n->slabs_partial);
3256
3257 spin_unlock(&n->list_lock);
3258 goto done;
3259
3260 must_grow:
3261 spin_unlock(&n->list_lock);
3262 x = cache_grow(cachep, flags | GFP_THISNODE, nodeid, NULL);
3263 if (x)
3264 goto retry;
3265
3266 return fallback_alloc(cachep, flags);
3267
3268 done:
3269 return obj;
3270 }
3271
3272 static __always_inline void *
3273 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3274 unsigned long caller)
3275 {
3276 unsigned long save_flags;
3277 void *ptr;
3278 int slab_node = numa_mem_id();
3279
3280 flags &= gfp_allowed_mask;
3281
3282 lockdep_trace_alloc(flags);
3283
3284 if (slab_should_failslab(cachep, flags))
3285 return NULL;
3286
3287 cachep = memcg_kmem_get_cache(cachep, flags);
3288
3289 cache_alloc_debugcheck_before(cachep, flags);
3290 local_irq_save(save_flags);
3291
3292 if (nodeid == NUMA_NO_NODE)
3293 nodeid = slab_node;
3294
3295 if (unlikely(!get_node(cachep, nodeid))) {
3296 /* Node not bootstrapped yet */
3297 ptr = fallback_alloc(cachep, flags);
3298 goto out;
3299 }
3300
3301 if (nodeid == slab_node) {
3302 /*
3303 * Use the locally cached objects if possible.
3304 * However ____cache_alloc does not allow fallback
3305 * to other nodes. It may fail while we still have
3306 * objects on other nodes available.
3307 */
3308 ptr = ____cache_alloc(cachep, flags);
3309 if (ptr)
3310 goto out;
3311 }
3312 /* ___cache_alloc_node can fall back to other nodes */
3313 ptr = ____cache_alloc_node(cachep, flags, nodeid);
3314 out:
3315 local_irq_restore(save_flags);
3316 ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3317 kmemleak_alloc_recursive(ptr, cachep->object_size, 1, cachep->flags,
3318 flags);
3319
3320 if (likely(ptr)) {
3321 kmemcheck_slab_alloc(cachep, flags, ptr, cachep->object_size);
3322 if (unlikely(flags & __GFP_ZERO))
3323 memset(ptr, 0, cachep->object_size);
3324 }
3325
3326 return ptr;
3327 }
3328
3329 static __always_inline void *
3330 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3331 {
3332 void *objp;
3333
3334 if (current->mempolicy || unlikely(current->flags & PF_SPREAD_SLAB)) {
3335 objp = alternate_node_alloc(cache, flags);
3336 if (objp)
3337 goto out;
3338 }
3339 objp = ____cache_alloc(cache, flags);
3340
3341 /*
3342 * We may just have run out of memory on the local node.
3343 * ____cache_alloc_node() knows how to locate memory on other nodes
3344 */
3345 if (!objp)
3346 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3347
3348 out:
3349 return objp;
3350 }
3351 #else
3352
3353 static __always_inline void *
3354 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3355 {
3356 return ____cache_alloc(cachep, flags);
3357 }
3358
3359 #endif /* CONFIG_NUMA */
3360
3361 static __always_inline void *
3362 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3363 {
3364 unsigned long save_flags;
3365 void *objp;
3366
3367 flags &= gfp_allowed_mask;
3368
3369 lockdep_trace_alloc(flags);
3370
3371 if (slab_should_failslab(cachep, flags))
3372 return NULL;
3373
3374 cachep = memcg_kmem_get_cache(cachep, flags);
3375
3376 cache_alloc_debugcheck_before(cachep, flags);
3377 local_irq_save(save_flags);
3378 objp = __do_cache_alloc(cachep, flags);
3379 local_irq_restore(save_flags);
3380 objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3381 kmemleak_alloc_recursive(objp, cachep->object_size, 1, cachep->flags,
3382 flags);
3383 prefetchw(objp);
3384
3385 if (likely(objp)) {
3386 kmemcheck_slab_alloc(cachep, flags, objp, cachep->object_size);
3387 if (unlikely(flags & __GFP_ZERO))
3388 memset(objp, 0, cachep->object_size);
3389 }
3390
3391 return objp;
3392 }
3393
3394 /*
3395 * Caller needs to acquire correct kmem_cache_node's list_lock
3396 */
3397 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
3398 int node)
3399 {
3400 int i;
3401 struct kmem_cache_node *n;
3402
3403 for (i = 0; i < nr_objects; i++) {
3404 void *objp;
3405 struct page *page;
3406
3407 clear_obj_pfmemalloc(&objpp[i]);
3408 objp = objpp[i];
3409
3410 page = virt_to_head_page(objp);
3411 n = get_node(cachep, node);
3412 list_del(&page->lru);
3413 check_spinlock_acquired_node(cachep, node);
3414 slab_put_obj(cachep, page, objp, node);
3415 STATS_DEC_ACTIVE(cachep);
3416 n->free_objects++;
3417
3418 /* fixup slab chains */
3419 if (page->active == 0) {
3420 if (n->free_objects > n->free_limit) {
3421 n->free_objects -= cachep->num;
3422 /* No need to drop any previously held
3423 * lock here, even if we have a off-slab slab
3424 * descriptor it is guaranteed to come from
3425 * a different cache, refer to comments before
3426 * alloc_slabmgmt.
3427 */
3428 slab_destroy(cachep, page);
3429 } else {
3430 list_add(&page->lru, &n->slabs_free);
3431 }
3432 } else {
3433 /* Unconditionally move a slab to the end of the
3434 * partial list on free - maximum time for the
3435 * other objects to be freed, too.
3436 */
3437 list_add_tail(&page->lru, &n->slabs_partial);
3438 }
3439 }
3440 }
3441
3442 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3443 {
3444 int batchcount;
3445 struct kmem_cache_node *n;
3446 int node = numa_mem_id();
3447
3448 batchcount = ac->batchcount;
3449 #if DEBUG
3450 BUG_ON(!batchcount || batchcount > ac->avail);
3451 #endif
3452 check_irq_off();
3453 n = get_node(cachep, node);
3454 spin_lock(&n->list_lock);
3455 if (n->shared) {
3456 struct array_cache *shared_array = n->shared;
3457 int max = shared_array->limit - shared_array->avail;
3458 if (max) {
3459 if (batchcount > max)
3460 batchcount = max;
3461 memcpy(&(shared_array->entry[shared_array->avail]),
3462 ac->entry, sizeof(void *) * batchcount);
3463 shared_array->avail += batchcount;
3464 goto free_done;
3465 }
3466 }
3467
3468 free_block(cachep, ac->entry, batchcount, node);
3469 free_done:
3470 #if STATS
3471 {
3472 int i = 0;
3473 struct list_head *p;
3474
3475 p = n->slabs_free.next;
3476 while (p != &(n->slabs_free)) {
3477 struct page *page;
3478
3479 page = list_entry(p, struct page, lru);
3480 BUG_ON(page->active);
3481
3482 i++;
3483 p = p->next;
3484 }
3485 STATS_SET_FREEABLE(cachep, i);
3486 }
3487 #endif
3488 spin_unlock(&n->list_lock);
3489 ac->avail -= batchcount;
3490 memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3491 }
3492
3493 /*
3494 * Release an obj back to its cache. If the obj has a constructed state, it must
3495 * be in this state _before_ it is released. Called with disabled ints.
3496 */
3497 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3498 unsigned long caller)
3499 {
3500 struct array_cache *ac = cpu_cache_get(cachep);
3501
3502 check_irq_off();
3503 kmemleak_free_recursive(objp, cachep->flags);
3504 objp = cache_free_debugcheck(cachep, objp, caller);
3505
3506 kmemcheck_slab_free(cachep, objp, cachep->object_size);
3507
3508 /*
3509 * Skip calling cache_free_alien() when the platform is not numa.
3510 * This will avoid cache misses that happen while accessing slabp (which
3511 * is per page memory reference) to get nodeid. Instead use a global
3512 * variable to skip the call, which is mostly likely to be present in
3513 * the cache.
3514 */
3515 if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3516 return;
3517
3518 if (likely(ac->avail < ac->limit)) {
3519 STATS_INC_FREEHIT(cachep);
3520 } else {
3521 STATS_INC_FREEMISS(cachep);
3522 cache_flusharray(cachep, ac);
3523 }
3524
3525 ac_put_obj(cachep, ac, objp);
3526 }
3527
3528 /**
3529 * kmem_cache_alloc - Allocate an object
3530 * @cachep: The cache to allocate from.
3531 * @flags: See kmalloc().
3532 *
3533 * Allocate an object from this cache. The flags are only relevant
3534 * if the cache has no available objects.
3535 */
3536 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3537 {
3538 void *ret = slab_alloc(cachep, flags, _RET_IP_);
3539
3540 trace_kmem_cache_alloc(_RET_IP_, ret,
3541 cachep->object_size, cachep->size, flags);
3542
3543 return ret;
3544 }
3545 EXPORT_SYMBOL(kmem_cache_alloc);
3546
3547 #ifdef CONFIG_TRACING
3548 void *
3549 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3550 {
3551 void *ret;
3552
3553 ret = slab_alloc(cachep, flags, _RET_IP_);
3554
3555 trace_kmalloc(_RET_IP_, ret,
3556 size, cachep->size, flags);
3557 return ret;
3558 }
3559 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3560 #endif
3561
3562 #ifdef CONFIG_NUMA
3563 /**
3564 * kmem_cache_alloc_node - Allocate an object on the specified node
3565 * @cachep: The cache to allocate from.
3566 * @flags: See kmalloc().
3567 * @nodeid: node number of the target node.
3568 *
3569 * Identical to kmem_cache_alloc but it will allocate memory on the given
3570 * node, which can improve the performance for cpu bound structures.
3571 *
3572 * Fallback to other node is possible if __GFP_THISNODE is not set.
3573 */
3574 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3575 {
3576 void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3577
3578 trace_kmem_cache_alloc_node(_RET_IP_, ret,
3579 cachep->object_size, cachep->size,
3580 flags, nodeid);
3581
3582 return ret;
3583 }
3584 EXPORT_SYMBOL(kmem_cache_alloc_node);
3585
3586 #ifdef CONFIG_TRACING
3587 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3588 gfp_t flags,
3589 int nodeid,
3590 size_t size)
3591 {
3592 void *ret;
3593
3594 ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3595
3596 trace_kmalloc_node(_RET_IP_, ret,
3597 size, cachep->size,
3598 flags, nodeid);
3599 return ret;
3600 }
3601 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3602 #endif
3603
3604 static __always_inline void *
3605 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3606 {
3607 struct kmem_cache *cachep;
3608
3609 cachep = kmalloc_slab(size, flags);
3610 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3611 return cachep;
3612 return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3613 }
3614
3615 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3616 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3617 {
3618 return __do_kmalloc_node(size, flags, node, _RET_IP_);
3619 }
3620 EXPORT_SYMBOL(__kmalloc_node);
3621
3622 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3623 int node, unsigned long caller)
3624 {
3625 return __do_kmalloc_node(size, flags, node, caller);
3626 }
3627 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3628 #else
3629 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3630 {
3631 return __do_kmalloc_node(size, flags, node, 0);
3632 }
3633 EXPORT_SYMBOL(__kmalloc_node);
3634 #endif /* CONFIG_DEBUG_SLAB || CONFIG_TRACING */
3635 #endif /* CONFIG_NUMA */
3636
3637 /**
3638 * __do_kmalloc - allocate memory
3639 * @size: how many bytes of memory are required.
3640 * @flags: the type of memory to allocate (see kmalloc).
3641 * @caller: function caller for debug tracking of the caller
3642 */
3643 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3644 unsigned long caller)
3645 {
3646 struct kmem_cache *cachep;
3647 void *ret;
3648
3649 cachep = kmalloc_slab(size, flags);
3650 if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3651 return cachep;
3652 ret = slab_alloc(cachep, flags, caller);
3653
3654 trace_kmalloc(caller, ret,
3655 size, cachep->size, flags);
3656
3657 return ret;
3658 }
3659
3660
3661 #if defined(CONFIG_DEBUG_SLAB) || defined(CONFIG_TRACING)
3662 void *__kmalloc(size_t size, gfp_t flags)
3663 {
3664 return __do_kmalloc(size, flags, _RET_IP_);
3665 }
3666 EXPORT_SYMBOL(__kmalloc);
3667
3668 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3669 {
3670 return __do_kmalloc(size, flags, caller);
3671 }
3672 EXPORT_SYMBOL(__kmalloc_track_caller);
3673
3674 #else
3675 void *__kmalloc(size_t size, gfp_t flags)
3676 {
3677 return __do_kmalloc(size, flags, 0);
3678 }
3679 EXPORT_SYMBOL(__kmalloc);
3680 #endif
3681
3682 /**
3683 * kmem_cache_free - Deallocate an object
3684 * @cachep: The cache the allocation was from.
3685 * @objp: The previously allocated object.
3686 *
3687 * Free an object which was previously allocated from this
3688 * cache.
3689 */
3690 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3691 {
3692 unsigned long flags;
3693 cachep = cache_from_obj(cachep, objp);
3694 if (!cachep)
3695 return;
3696
3697 local_irq_save(flags);
3698 debug_check_no_locks_freed(objp, cachep->object_size);
3699 if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3700 debug_check_no_obj_freed(objp, cachep->object_size);
3701 __cache_free(cachep, objp, _RET_IP_);
3702 local_irq_restore(flags);
3703
3704 trace_kmem_cache_free(_RET_IP_, objp);
3705 }
3706 EXPORT_SYMBOL(kmem_cache_free);
3707
3708 /**
3709 * kfree - free previously allocated memory
3710 * @objp: pointer returned by kmalloc.
3711 *
3712 * If @objp is NULL, no operation is performed.
3713 *
3714 * Don't free memory not originally allocated by kmalloc()
3715 * or you will run into trouble.
3716 */
3717 void kfree(const void *objp)
3718 {
3719 struct kmem_cache *c;
3720 unsigned long flags;
3721
3722 trace_kfree(_RET_IP_, objp);
3723
3724 if (unlikely(ZERO_OR_NULL_PTR(objp)))
3725 return;
3726 local_irq_save(flags);
3727 kfree_debugcheck(objp);
3728 c = virt_to_cache(objp);
3729 debug_check_no_locks_freed(objp, c->object_size);
3730
3731 debug_check_no_obj_freed(objp, c->object_size);
3732 __cache_free(c, (void *)objp, _RET_IP_);
3733 local_irq_restore(flags);
3734 }
3735 EXPORT_SYMBOL(kfree);
3736
3737 /*
3738 * This initializes kmem_cache_node or resizes various caches for all nodes.
3739 */
3740 static int alloc_kmem_cache_node(struct kmem_cache *cachep, gfp_t gfp)
3741 {
3742 int node;
3743 struct kmem_cache_node *n;
3744 struct array_cache *new_shared;
3745 struct array_cache **new_alien = NULL;
3746
3747 for_each_online_node(node) {
3748
3749 if (use_alien_caches) {
3750 new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3751 if (!new_alien)
3752 goto fail;
3753 }
3754
3755 new_shared = NULL;
3756 if (cachep->shared) {
3757 new_shared = alloc_arraycache(node,
3758 cachep->shared*cachep->batchcount,
3759 0xbaadf00d, gfp);
3760 if (!new_shared) {
3761 free_alien_cache(new_alien);
3762 goto fail;
3763 }
3764 }
3765
3766 n = get_node(cachep, node);
3767 if (n) {
3768 struct array_cache *shared = n->shared;
3769
3770 spin_lock_irq(&n->list_lock);
3771
3772 if (shared)
3773 free_block(cachep, shared->entry,
3774 shared->avail, node);
3775
3776 n->shared = new_shared;
3777 if (!n->alien) {
3778 n->alien = new_alien;
3779 new_alien = NULL;
3780 }
3781 n->free_limit = (1 + nr_cpus_node(node)) *
3782 cachep->batchcount + cachep->num;
3783 spin_unlock_irq(&n->list_lock);
3784 kfree(shared);
3785 free_alien_cache(new_alien);
3786 continue;
3787 }
3788 n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
3789 if (!n) {
3790 free_alien_cache(new_alien);
3791 kfree(new_shared);
3792 goto fail;
3793 }
3794
3795 kmem_cache_node_init(n);
3796 n->next_reap = jiffies + REAPTIMEOUT_NODE +
3797 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
3798 n->shared = new_shared;
3799 n->alien = new_alien;
3800 n->free_limit = (1 + nr_cpus_node(node)) *
3801 cachep->batchcount + cachep->num;
3802 cachep->node[node] = n;
3803 }
3804 return 0;
3805
3806 fail:
3807 if (!cachep->list.next) {
3808 /* Cache is not active yet. Roll back what we did */
3809 node--;
3810 while (node >= 0) {
3811 n = get_node(cachep, node);
3812 if (n) {
3813 kfree(n->shared);
3814 free_alien_cache(n->alien);
3815 kfree(n);
3816 cachep->node[node] = NULL;
3817 }
3818 node--;
3819 }
3820 }
3821 return -ENOMEM;
3822 }
3823
3824 struct ccupdate_struct {
3825 struct kmem_cache *cachep;
3826 struct array_cache *new[0];
3827 };
3828
3829 static void do_ccupdate_local(void *info)
3830 {
3831 struct ccupdate_struct *new = info;
3832 struct array_cache *old;
3833
3834 check_irq_off();
3835 old = cpu_cache_get(new->cachep);
3836
3837 new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3838 new->new[smp_processor_id()] = old;
3839 }
3840
3841 /* Always called with the slab_mutex held */
3842 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3843 int batchcount, int shared, gfp_t gfp)
3844 {
3845 struct ccupdate_struct *new;
3846 int i;
3847
3848 new = kzalloc(sizeof(*new) + nr_cpu_ids * sizeof(struct array_cache *),
3849 gfp);
3850 if (!new)
3851 return -ENOMEM;
3852
3853 for_each_online_cpu(i) {
3854 new->new[i] = alloc_arraycache(cpu_to_mem(i), limit,
3855 batchcount, gfp);
3856 if (!new->new[i]) {
3857 for (i--; i >= 0; i--)
3858 kfree(new->new[i]);
3859 kfree(new);
3860 return -ENOMEM;
3861 }
3862 }
3863 new->cachep = cachep;
3864
3865 on_each_cpu(do_ccupdate_local, (void *)new, 1);
3866
3867 check_irq_on();
3868 cachep->batchcount = batchcount;
3869 cachep->limit = limit;
3870 cachep->shared = shared;
3871
3872 for_each_online_cpu(i) {
3873 struct array_cache *ccold = new->new[i];
3874 int node;
3875 struct kmem_cache_node *n;
3876
3877 if (!ccold)
3878 continue;
3879
3880 node = cpu_to_mem(i);
3881 n = get_node(cachep, node);
3882 spin_lock_irq(&n->list_lock);
3883 free_block(cachep, ccold->entry, ccold->avail, node);
3884 spin_unlock_irq(&n->list_lock);
3885 kfree(ccold);
3886 }
3887 kfree(new);
3888 return alloc_kmem_cache_node(cachep, gfp);
3889 }
3890
3891 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3892 int batchcount, int shared, gfp_t gfp)
3893 {
3894 int ret;
3895 struct kmem_cache *c = NULL;
3896 int i = 0;
3897
3898 ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3899
3900 if (slab_state < FULL)
3901 return ret;
3902
3903 if ((ret < 0) || !is_root_cache(cachep))
3904 return ret;
3905
3906 VM_BUG_ON(!mutex_is_locked(&slab_mutex));
3907 for_each_memcg_cache_index(i) {
3908 c = cache_from_memcg_idx(cachep, i);
3909 if (c)
3910 /* return value determined by the parent cache only */
3911 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3912 }
3913
3914 return ret;
3915 }
3916
3917 /* Called with slab_mutex held always */
3918 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3919 {
3920 int err;
3921 int limit = 0;
3922 int shared = 0;
3923 int batchcount = 0;
3924
3925 if (!is_root_cache(cachep)) {
3926 struct kmem_cache *root = memcg_root_cache(cachep);
3927 limit = root->limit;
3928 shared = root->shared;
3929 batchcount = root->batchcount;
3930 }
3931
3932 if (limit && shared && batchcount)
3933 goto skip_setup;
3934 /*
3935 * The head array serves three purposes:
3936 * - create a LIFO ordering, i.e. return objects that are cache-warm
3937 * - reduce the number of spinlock operations.
3938 * - reduce the number of linked list operations on the slab and
3939 * bufctl chains: array operations are cheaper.
3940 * The numbers are guessed, we should auto-tune as described by
3941 * Bonwick.
3942 */
3943 if (cachep->size > 131072)
3944 limit = 1;
3945 else if (cachep->size > PAGE_SIZE)
3946 limit = 8;
3947 else if (cachep->size > 1024)
3948 limit = 24;
3949 else if (cachep->size > 256)
3950 limit = 54;
3951 else
3952 limit = 120;
3953
3954 /*
3955 * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3956 * allocation behaviour: Most allocs on one cpu, most free operations
3957 * on another cpu. For these cases, an efficient object passing between
3958 * cpus is necessary. This is provided by a shared array. The array
3959 * replaces Bonwick's magazine layer.
3960 * On uniprocessor, it's functionally equivalent (but less efficient)
3961 * to a larger limit. Thus disabled by default.
3962 */
3963 shared = 0;
3964 if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
3965 shared = 8;
3966
3967 #if DEBUG
3968 /*
3969 * With debugging enabled, large batchcount lead to excessively long
3970 * periods with disabled local interrupts. Limit the batchcount
3971 */
3972 if (limit > 32)
3973 limit = 32;
3974 #endif
3975 batchcount = (limit + 1) / 2;
3976 skip_setup:
3977 err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3978 if (err)
3979 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3980 cachep->name, -err);
3981 return err;
3982 }
3983
3984 /*
3985 * Drain an array if it contains any elements taking the node lock only if
3986 * necessary. Note that the node listlock also protects the array_cache
3987 * if drain_array() is used on the shared array.
3988 */
3989 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
3990 struct array_cache *ac, int force, int node)
3991 {
3992 int tofree;
3993
3994 if (!ac || !ac->avail)
3995 return;
3996 if (ac->touched && !force) {
3997 ac->touched = 0;
3998 } else {
3999 spin_lock_irq(&n->list_lock);
4000 if (ac->avail) {
4001 tofree = force ? ac->avail : (ac->limit + 4) / 5;
4002 if (tofree > ac->avail)
4003 tofree = (ac->avail + 1) / 2;
4004 free_block(cachep, ac->entry, tofree, node);
4005 ac->avail -= tofree;
4006 memmove(ac->entry, &(ac->entry[tofree]),
4007 sizeof(void *) * ac->avail);
4008 }
4009 spin_unlock_irq(&n->list_lock);
4010 }
4011 }
4012
4013 /**
4014 * cache_reap - Reclaim memory from caches.
4015 * @w: work descriptor
4016 *
4017 * Called from workqueue/eventd every few seconds.
4018 * Purpose:
4019 * - clear the per-cpu caches for this CPU.
4020 * - return freeable pages to the main free memory pool.
4021 *
4022 * If we cannot acquire the cache chain mutex then just give up - we'll try
4023 * again on the next iteration.
4024 */
4025 static void cache_reap(struct work_struct *w)
4026 {
4027 struct kmem_cache *searchp;
4028 struct kmem_cache_node *n;
4029 int node = numa_mem_id();
4030 struct delayed_work *work = to_delayed_work(w);
4031
4032 if (!mutex_trylock(&slab_mutex))
4033 /* Give up. Setup the next iteration. */
4034 goto out;
4035
4036 list_for_each_entry(searchp, &slab_caches, list) {
4037 check_irq_on();
4038
4039 /*
4040 * We only take the node lock if absolutely necessary and we
4041 * have established with reasonable certainty that
4042 * we can do some work if the lock was obtained.
4043 */
4044 n = get_node(searchp, node);
4045
4046 reap_alien(searchp, n);
4047
4048 drain_array(searchp, n, cpu_cache_get(searchp), 0, node);
4049
4050 /*
4051 * These are racy checks but it does not matter
4052 * if we skip one check or scan twice.
4053 */
4054 if (time_after(n->next_reap, jiffies))
4055 goto next;
4056
4057 n->next_reap = jiffies + REAPTIMEOUT_NODE;
4058
4059 drain_array(searchp, n, n->shared, 0, node);
4060
4061 if (n->free_touched)
4062 n->free_touched = 0;
4063 else {
4064 int freed;
4065
4066 freed = drain_freelist(searchp, n, (n->free_limit +
4067 5 * searchp->num - 1) / (5 * searchp->num));
4068 STATS_ADD_REAPED(searchp, freed);
4069 }
4070 next:
4071 cond_resched();
4072 }
4073 check_irq_on();
4074 mutex_unlock(&slab_mutex);
4075 next_reap_node();
4076 out:
4077 /* Set up the next iteration */
4078 schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
4079 }
4080
4081 #ifdef CONFIG_SLABINFO
4082 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
4083 {
4084 struct page *page;
4085 unsigned long active_objs;
4086 unsigned long num_objs;
4087 unsigned long active_slabs = 0;
4088 unsigned long num_slabs, free_objects = 0, shared_avail = 0;
4089 const char *name;
4090 char *error = NULL;
4091 int node;
4092 struct kmem_cache_node *n;
4093
4094 active_objs = 0;
4095 num_slabs = 0;
4096 for_each_kmem_cache_node(cachep, node, n) {
4097
4098 check_irq_on();
4099 spin_lock_irq(&n->list_lock);
4100
4101 list_for_each_entry(page, &n->slabs_full, lru) {
4102 if (page->active != cachep->num && !error)
4103 error = "slabs_full accounting error";
4104 active_objs += cachep->num;
4105 active_slabs++;
4106 }
4107 list_for_each_entry(page, &n->slabs_partial, lru) {
4108 if (page->active == cachep->num && !error)
4109 error = "slabs_partial accounting error";
4110 if (!page->active && !error)
4111 error = "slabs_partial accounting error";
4112 active_objs += page->active;
4113 active_slabs++;
4114 }
4115 list_for_each_entry(page, &n->slabs_free, lru) {
4116 if (page->active && !error)
4117 error = "slabs_free accounting error";
4118 num_slabs++;
4119 }
4120 free_objects += n->free_objects;
4121 if (n->shared)
4122 shared_avail += n->shared->avail;
4123
4124 spin_unlock_irq(&n->list_lock);
4125 }
4126 num_slabs += active_slabs;
4127 num_objs = num_slabs * cachep->num;
4128 if (num_objs - active_objs != free_objects && !error)
4129 error = "free_objects accounting error";
4130
4131 name = cachep->name;
4132 if (error)
4133 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
4134
4135 sinfo->active_objs = active_objs;
4136 sinfo->num_objs = num_objs;
4137 sinfo->active_slabs = active_slabs;
4138 sinfo->num_slabs = num_slabs;
4139 sinfo->shared_avail = shared_avail;
4140 sinfo->limit = cachep->limit;
4141 sinfo->batchcount = cachep->batchcount;
4142 sinfo->shared = cachep->shared;
4143 sinfo->objects_per_slab = cachep->num;
4144 sinfo->cache_order = cachep->gfporder;
4145 }
4146
4147 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
4148 {
4149 #if STATS
4150 { /* node stats */
4151 unsigned long high = cachep->high_mark;
4152 unsigned long allocs = cachep->num_allocations;
4153 unsigned long grown = cachep->grown;
4154 unsigned long reaped = cachep->reaped;
4155 unsigned long errors = cachep->errors;
4156 unsigned long max_freeable = cachep->max_freeable;
4157 unsigned long node_allocs = cachep->node_allocs;
4158 unsigned long node_frees = cachep->node_frees;
4159 unsigned long overflows = cachep->node_overflow;
4160
4161 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4162 "%4lu %4lu %4lu %4lu %4lu",
4163 allocs, high, grown,
4164 reaped, errors, max_freeable, node_allocs,
4165 node_frees, overflows);
4166 }
4167 /* cpu stats */
4168 {
4169 unsigned long allochit = atomic_read(&cachep->allochit);
4170 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4171 unsigned long freehit = atomic_read(&cachep->freehit);
4172 unsigned long freemiss = atomic_read(&cachep->freemiss);
4173
4174 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4175 allochit, allocmiss, freehit, freemiss);
4176 }
4177 #endif
4178 }
4179
4180 #define MAX_SLABINFO_WRITE 128
4181 /**
4182 * slabinfo_write - Tuning for the slab allocator
4183 * @file: unused
4184 * @buffer: user buffer
4185 * @count: data length
4186 * @ppos: unused
4187 */
4188 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4189 size_t count, loff_t *ppos)
4190 {
4191 char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4192 int limit, batchcount, shared, res;
4193 struct kmem_cache *cachep;
4194
4195 if (count > MAX_SLABINFO_WRITE)
4196 return -EINVAL;
4197 if (copy_from_user(&kbuf, buffer, count))
4198 return -EFAULT;
4199 kbuf[MAX_SLABINFO_WRITE] = '\0';
4200
4201 tmp = strchr(kbuf, ' ');
4202 if (!tmp)
4203 return -EINVAL;
4204 *tmp = '\0';
4205 tmp++;
4206 if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4207 return -EINVAL;
4208
4209 /* Find the cache in the chain of caches. */
4210 mutex_lock(&slab_mutex);
4211 res = -EINVAL;
4212 list_for_each_entry(cachep, &slab_caches, list) {
4213 if (!strcmp(cachep->name, kbuf)) {
4214 if (limit < 1 || batchcount < 1 ||
4215 batchcount > limit || shared < 0) {
4216 res = 0;
4217 } else {
4218 res = do_tune_cpucache(cachep, limit,
4219 batchcount, shared,
4220 GFP_KERNEL);
4221 }
4222 break;
4223 }
4224 }
4225 mutex_unlock(&slab_mutex);
4226 if (res >= 0)
4227 res = count;
4228 return res;
4229 }
4230
4231 #ifdef CONFIG_DEBUG_SLAB_LEAK
4232
4233 static void *leaks_start(struct seq_file *m, loff_t *pos)
4234 {
4235 mutex_lock(&slab_mutex);
4236 return seq_list_start(&slab_caches, *pos);
4237 }
4238
4239 static inline int add_caller(unsigned long *n, unsigned long v)
4240 {
4241 unsigned long *p;
4242 int l;
4243 if (!v)
4244 return 1;
4245 l = n[1];
4246 p = n + 2;
4247 while (l) {
4248 int i = l/2;
4249 unsigned long *q = p + 2 * i;
4250 if (*q == v) {
4251 q[1]++;
4252 return 1;
4253 }
4254 if (*q > v) {
4255 l = i;
4256 } else {
4257 p = q + 2;
4258 l -= i + 1;
4259 }
4260 }
4261 if (++n[1] == n[0])
4262 return 0;
4263 memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4264 p[0] = v;
4265 p[1] = 1;
4266 return 1;
4267 }
4268
4269 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4270 struct page *page)
4271 {
4272 void *p;
4273 int i;
4274
4275 if (n[0] == n[1])
4276 return;
4277 for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4278 if (get_obj_status(page, i) != OBJECT_ACTIVE)
4279 continue;
4280
4281 if (!add_caller(n, (unsigned long)*dbg_userword(c, p)))
4282 return;
4283 }
4284 }
4285
4286 static void show_symbol(struct seq_file *m, unsigned long address)
4287 {
4288 #ifdef CONFIG_KALLSYMS
4289 unsigned long offset, size;
4290 char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4291
4292 if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4293 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4294 if (modname[0])
4295 seq_printf(m, " [%s]", modname);
4296 return;
4297 }
4298 #endif
4299 seq_printf(m, "%p", (void *)address);
4300 }
4301
4302 static int leaks_show(struct seq_file *m, void *p)
4303 {
4304 struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4305 struct page *page;
4306 struct kmem_cache_node *n;
4307 const char *name;
4308 unsigned long *x = m->private;
4309 int node;
4310 int i;
4311
4312 if (!(cachep->flags & SLAB_STORE_USER))
4313 return 0;
4314 if (!(cachep->flags & SLAB_RED_ZONE))
4315 return 0;
4316
4317 /* OK, we can do it */
4318
4319 x[1] = 0;
4320
4321 for_each_kmem_cache_node(cachep, node, n) {
4322
4323 check_irq_on();
4324 spin_lock_irq(&n->list_lock);
4325
4326 list_for_each_entry(page, &n->slabs_full, lru)
4327 handle_slab(x, cachep, page);
4328 list_for_each_entry(page, &n->slabs_partial, lru)
4329 handle_slab(x, cachep, page);
4330 spin_unlock_irq(&n->list_lock);
4331 }
4332 name = cachep->name;
4333 if (x[0] == x[1]) {
4334 /* Increase the buffer size */
4335 mutex_unlock(&slab_mutex);
4336 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4337 if (!m->private) {
4338 /* Too bad, we are really out */
4339 m->private = x;
4340 mutex_lock(&slab_mutex);
4341 return -ENOMEM;
4342 }
4343 *(unsigned long *)m->private = x[0] * 2;
4344 kfree(x);
4345 mutex_lock(&slab_mutex);
4346 /* Now make sure this entry will be retried */
4347 m->count = m->size;
4348 return 0;
4349 }
4350 for (i = 0; i < x[1]; i++) {
4351 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4352 show_symbol(m, x[2*i+2]);
4353 seq_putc(m, '\n');
4354 }
4355
4356 return 0;
4357 }
4358
4359 static const struct seq_operations slabstats_op = {
4360 .start = leaks_start,
4361 .next = slab_next,
4362 .stop = slab_stop,
4363 .show = leaks_show,
4364 };
4365
4366 static int slabstats_open(struct inode *inode, struct file *file)
4367 {
4368 unsigned long *n = kzalloc(PAGE_SIZE, GFP_KERNEL);
4369 int ret = -ENOMEM;
4370 if (n) {
4371 ret = seq_open(file, &slabstats_op);
4372 if (!ret) {
4373 struct seq_file *m = file->private_data;
4374 *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4375 m->private = n;
4376 n = NULL;
4377 }
4378 kfree(n);
4379 }
4380 return ret;
4381 }
4382
4383 static const struct file_operations proc_slabstats_operations = {
4384 .open = slabstats_open,
4385 .read = seq_read,
4386 .llseek = seq_lseek,
4387 .release = seq_release_private,
4388 };
4389 #endif
4390
4391 static int __init slab_proc_init(void)
4392 {
4393 #ifdef CONFIG_DEBUG_SLAB_LEAK
4394 proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4395 #endif
4396 return 0;
4397 }
4398 module_init(slab_proc_init);
4399 #endif
4400
4401 /**
4402 * ksize - get the actual amount of memory allocated for a given object
4403 * @objp: Pointer to the object
4404 *
4405 * kmalloc may internally round up allocations and return more memory
4406 * than requested. ksize() can be used to determine the actual amount of
4407 * memory allocated. The caller may use this additional memory, even though
4408 * a smaller amount of memory was initially specified with the kmalloc call.
4409 * The caller must guarantee that objp points to a valid object previously
4410 * allocated with either kmalloc() or kmem_cache_alloc(). The object
4411 * must not be freed during the duration of the call.
4412 */
4413 size_t ksize(const void *objp)
4414 {
4415 BUG_ON(!objp);
4416 if (unlikely(objp == ZERO_SIZE_PTR))
4417 return 0;
4418
4419 return virt_to_cache(objp)->object_size;
4420 }
4421 EXPORT_SYMBOL(ksize);
This page took 0.191446 seconds and 5 git commands to generate.