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