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