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