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