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