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