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