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