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