]> err.no Git - linux-2.6/blob - mm/slab.c
[PATCH] slab: remove cachep->spinlock
[linux-2.6] / 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 intializations 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/config.h>
90 #include        <linux/slab.h>
91 #include        <linux/mm.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/seq_file.h>
98 #include        <linux/notifier.h>
99 #include        <linux/kallsyms.h>
100 #include        <linux/cpu.h>
101 #include        <linux/sysctl.h>
102 #include        <linux/module.h>
103 #include        <linux/rcupdate.h>
104 #include        <linux/string.h>
105 #include        <linux/nodemask.h>
106 #include        <linux/mempolicy.h>
107 #include        <linux/mutex.h>
108
109 #include        <asm/uaccess.h>
110 #include        <asm/cacheflush.h>
111 #include        <asm/tlbflush.h>
112 #include        <asm/page.h>
113
114 /*
115  * DEBUG        - 1 for kmem_cache_create() to honour; SLAB_DEBUG_INITIAL,
116  *                SLAB_RED_ZONE & SLAB_POISON.
117  *                0 for faster, smaller code (especially in the critical paths).
118  *
119  * STATS        - 1 to collect stats for /proc/slabinfo.
120  *                0 for faster, smaller code (especially in the critical paths).
121  *
122  * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
123  */
124
125 #ifdef CONFIG_DEBUG_SLAB
126 #define DEBUG           1
127 #define STATS           1
128 #define FORCED_DEBUG    1
129 #else
130 #define DEBUG           0
131 #define STATS           0
132 #define FORCED_DEBUG    0
133 #endif
134
135 /* Shouldn't this be in a header file somewhere? */
136 #define BYTES_PER_WORD          sizeof(void *)
137
138 #ifndef cache_line_size
139 #define cache_line_size()       L1_CACHE_BYTES
140 #endif
141
142 #ifndef ARCH_KMALLOC_MINALIGN
143 /*
144  * Enforce a minimum alignment for the kmalloc caches.
145  * Usually, the kmalloc caches are cache_line_size() aligned, except when
146  * DEBUG and FORCED_DEBUG are enabled, then they are BYTES_PER_WORD aligned.
147  * Some archs want to perform DMA into kmalloc caches and need a guaranteed
148  * alignment larger than BYTES_PER_WORD. ARCH_KMALLOC_MINALIGN allows that.
149  * Note that this flag disables some debug features.
150  */
151 #define ARCH_KMALLOC_MINALIGN 0
152 #endif
153
154 #ifndef ARCH_SLAB_MINALIGN
155 /*
156  * Enforce a minimum alignment for all caches.
157  * Intended for archs that get misalignment faults even for BYTES_PER_WORD
158  * aligned buffers. Includes ARCH_KMALLOC_MINALIGN.
159  * If possible: Do not enable this flag for CONFIG_DEBUG_SLAB, it disables
160  * some debug features.
161  */
162 #define ARCH_SLAB_MINALIGN 0
163 #endif
164
165 #ifndef ARCH_KMALLOC_FLAGS
166 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
167 #endif
168
169 /* Legal flag mask for kmem_cache_create(). */
170 #if DEBUG
171 # define CREATE_MASK    (SLAB_DEBUG_INITIAL | SLAB_RED_ZONE | \
172                          SLAB_POISON | SLAB_HWCACHE_ALIGN | \
173                          SLAB_NO_REAP | SLAB_CACHE_DMA | \
174                          SLAB_MUST_HWCACHE_ALIGN | SLAB_STORE_USER | \
175                          SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
176                          SLAB_DESTROY_BY_RCU)
177 #else
178 # define CREATE_MASK    (SLAB_HWCACHE_ALIGN | SLAB_NO_REAP | \
179                          SLAB_CACHE_DMA | SLAB_MUST_HWCACHE_ALIGN | \
180                          SLAB_RECLAIM_ACCOUNT | SLAB_PANIC | \
181                          SLAB_DESTROY_BY_RCU)
182 #endif
183
184 /*
185  * kmem_bufctl_t:
186  *
187  * Bufctl's are used for linking objs within a slab
188  * linked offsets.
189  *
190  * This implementation relies on "struct page" for locating the cache &
191  * slab an object belongs to.
192  * This allows the bufctl structure to be small (one int), but limits
193  * the number of objects a slab (not a cache) can contain when off-slab
194  * bufctls are used. The limit is the size of the largest general cache
195  * that does not use off-slab slabs.
196  * For 32bit archs with 4 kB pages, is this 56.
197  * This is not serious, as it is only for large objects, when it is unwise
198  * to have too many per slab.
199  * Note: This limit can be raised by introducing a general cache whose size
200  * is less than 512 (PAGE_SIZE<<3), but greater than 256.
201  */
202
203 typedef unsigned int kmem_bufctl_t;
204 #define BUFCTL_END      (((kmem_bufctl_t)(~0U))-0)
205 #define BUFCTL_FREE     (((kmem_bufctl_t)(~0U))-1)
206 #define SLAB_LIMIT      (((kmem_bufctl_t)(~0U))-2)
207
208 /* Max number of objs-per-slab for caches which use off-slab slabs.
209  * Needed to avoid a possible looping condition in cache_grow().
210  */
211 static unsigned long offslab_limit;
212
213 /*
214  * struct slab
215  *
216  * Manages the objs in a slab. Placed either at the beginning of mem allocated
217  * for a slab, or allocated from an general cache.
218  * Slabs are chained into three list: fully used, partial, fully free slabs.
219  */
220 struct slab {
221         struct list_head list;
222         unsigned long colouroff;
223         void *s_mem;            /* including colour offset */
224         unsigned int inuse;     /* num of objs active in slab */
225         kmem_bufctl_t free;
226         unsigned short nodeid;
227 };
228
229 /*
230  * struct slab_rcu
231  *
232  * slab_destroy on a SLAB_DESTROY_BY_RCU cache uses this structure to
233  * arrange for kmem_freepages to be called via RCU.  This is useful if
234  * we need to approach a kernel structure obliquely, from its address
235  * obtained without the usual locking.  We can lock the structure to
236  * stabilize it and check it's still at the given address, only if we
237  * can be sure that the memory has not been meanwhile reused for some
238  * other kind of object (which our subsystem's lock might corrupt).
239  *
240  * rcu_read_lock before reading the address, then rcu_read_unlock after
241  * taking the spinlock within the structure expected at that address.
242  *
243  * We assume struct slab_rcu can overlay struct slab when destroying.
244  */
245 struct slab_rcu {
246         struct rcu_head head;
247         struct kmem_cache *cachep;
248         void *addr;
249 };
250
251 /*
252  * struct array_cache
253  *
254  * Purpose:
255  * - LIFO ordering, to hand out cache-warm objects from _alloc
256  * - reduce the number of linked list operations
257  * - reduce spinlock operations
258  *
259  * The limit is stored in the per-cpu structure to reduce the data cache
260  * footprint.
261  *
262  */
263 struct array_cache {
264         unsigned int avail;
265         unsigned int limit;
266         unsigned int batchcount;
267         unsigned int touched;
268         spinlock_t lock;
269         void *entry[0]; /*
270                          * Must have this definition in here for the proper
271                          * alignment of array_cache. Also simplifies accessing
272                          * the entries.
273                          * [0] is for gcc 2.95. It should really be [].
274                          */
275 };
276
277 /*
278  * bootstrap: The caches do not work without cpuarrays anymore, but the
279  * cpuarrays are allocated from the generic caches...
280  */
281 #define BOOT_CPUCACHE_ENTRIES   1
282 struct arraycache_init {
283         struct array_cache cache;
284         void *entries[BOOT_CPUCACHE_ENTRIES];
285 };
286
287 /*
288  * The slab lists for all objects.
289  */
290 struct kmem_list3 {
291         struct list_head slabs_partial; /* partial list first, better asm code */
292         struct list_head slabs_full;
293         struct list_head slabs_free;
294         unsigned long free_objects;
295         unsigned long next_reap;
296         int free_touched;
297         unsigned int free_limit;
298         unsigned int colour_next;       /* Per-node cache coloring */
299         spinlock_t list_lock;
300         struct array_cache *shared;     /* shared per node */
301         struct array_cache **alien;     /* on other nodes */
302 };
303
304 /*
305  * Need this for bootstrapping a per node allocator.
306  */
307 #define NUM_INIT_LISTS (2 * MAX_NUMNODES + 1)
308 struct kmem_list3 __initdata initkmem_list3[NUM_INIT_LISTS];
309 #define CACHE_CACHE 0
310 #define SIZE_AC 1
311 #define SIZE_L3 (1 + MAX_NUMNODES)
312
313 /*
314  * This function must be completely optimized away if a constant is passed to
315  * it.  Mostly the same as what is in linux/slab.h except it returns an index.
316  */
317 static __always_inline int index_of(const size_t size)
318 {
319         extern void __bad_size(void);
320
321         if (__builtin_constant_p(size)) {
322                 int i = 0;
323
324 #define CACHE(x) \
325         if (size <=x) \
326                 return i; \
327         else \
328                 i++;
329 #include "linux/kmalloc_sizes.h"
330 #undef CACHE
331                 __bad_size();
332         } else
333                 __bad_size();
334         return 0;
335 }
336
337 #define INDEX_AC index_of(sizeof(struct arraycache_init))
338 #define INDEX_L3 index_of(sizeof(struct kmem_list3))
339
340 static void kmem_list3_init(struct kmem_list3 *parent)
341 {
342         INIT_LIST_HEAD(&parent->slabs_full);
343         INIT_LIST_HEAD(&parent->slabs_partial);
344         INIT_LIST_HEAD(&parent->slabs_free);
345         parent->shared = NULL;
346         parent->alien = NULL;
347         parent->colour_next = 0;
348         spin_lock_init(&parent->list_lock);
349         parent->free_objects = 0;
350         parent->free_touched = 0;
351 }
352
353 #define MAKE_LIST(cachep, listp, slab, nodeid)                          \
354         do {                                                            \
355                 INIT_LIST_HEAD(listp);                                  \
356                 list_splice(&(cachep->nodelists[nodeid]->slab), listp); \
357         } while (0)
358
359 #define MAKE_ALL_LISTS(cachep, ptr, nodeid)                             \
360         do {                                                            \
361         MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid);  \
362         MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
363         MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid);  \
364         } while (0)
365
366 /*
367  * struct kmem_cache
368  *
369  * manages a cache.
370  */
371
372 struct kmem_cache {
373 /* 1) per-cpu data, touched during every alloc/free */
374         struct array_cache *array[NR_CPUS];
375 /* 2) Cache tunables. Protected by cache_chain_mutex */
376         unsigned int batchcount;
377         unsigned int limit;
378         unsigned int shared;
379
380         unsigned int buffer_size;
381 /* 3) touched by every alloc & free from the backend */
382         struct kmem_list3 *nodelists[MAX_NUMNODES];
383
384         unsigned int flags;             /* constant flags */
385         unsigned int num;               /* # of objs per slab */
386
387 /* 4) cache_grow/shrink */
388         /* order of pgs per slab (2^n) */
389         unsigned int gfporder;
390
391         /* force GFP flags, e.g. GFP_DMA */
392         gfp_t gfpflags;
393
394         size_t colour;                  /* cache colouring range */
395         unsigned int colour_off;        /* colour offset */
396         struct kmem_cache *slabp_cache;
397         unsigned int slab_size;
398         unsigned int dflags;            /* dynamic flags */
399
400         /* constructor func */
401         void (*ctor) (void *, struct kmem_cache *, unsigned long);
402
403         /* de-constructor func */
404         void (*dtor) (void *, struct kmem_cache *, unsigned long);
405
406 /* 5) cache creation/removal */
407         const char *name;
408         struct list_head next;
409
410 /* 6) statistics */
411 #if STATS
412         unsigned long num_active;
413         unsigned long num_allocations;
414         unsigned long high_mark;
415         unsigned long grown;
416         unsigned long reaped;
417         unsigned long errors;
418         unsigned long max_freeable;
419         unsigned long node_allocs;
420         unsigned long node_frees;
421         atomic_t allochit;
422         atomic_t allocmiss;
423         atomic_t freehit;
424         atomic_t freemiss;
425 #endif
426 #if DEBUG
427         /*
428          * If debugging is enabled, then the allocator can add additional
429          * fields and/or padding to every object. buffer_size contains the total
430          * object size including these internal fields, the following two
431          * variables contain the offset to the user object and its size.
432          */
433         int obj_offset;
434         int obj_size;
435 #endif
436 };
437
438 #define CFLGS_OFF_SLAB          (0x80000000UL)
439 #define OFF_SLAB(x)     ((x)->flags & CFLGS_OFF_SLAB)
440
441 #define BATCHREFILL_LIMIT       16
442 /*
443  * Optimization question: fewer reaps means less probability for unnessary
444  * cpucache drain/refill cycles.
445  *
446  * OTOH the cpuarrays can contain lots of objects,
447  * which could lock up otherwise freeable slabs.
448  */
449 #define REAPTIMEOUT_CPUC        (2*HZ)
450 #define REAPTIMEOUT_LIST3       (4*HZ)
451
452 #if STATS
453 #define STATS_INC_ACTIVE(x)     ((x)->num_active++)
454 #define STATS_DEC_ACTIVE(x)     ((x)->num_active--)
455 #define STATS_INC_ALLOCED(x)    ((x)->num_allocations++)
456 #define STATS_INC_GROWN(x)      ((x)->grown++)
457 #define STATS_INC_REAPED(x)     ((x)->reaped++)
458 #define STATS_SET_HIGH(x)                                               \
459         do {                                                            \
460                 if ((x)->num_active > (x)->high_mark)                   \
461                         (x)->high_mark = (x)->num_active;               \
462         } while (0)
463 #define STATS_INC_ERR(x)        ((x)->errors++)
464 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
465 #define STATS_INC_NODEFREES(x)  ((x)->node_frees++)
466 #define STATS_SET_FREEABLE(x, i)                                        \
467         do {                                                            \
468                 if ((x)->max_freeable < i)                              \
469                         (x)->max_freeable = i;                          \
470         } while (0)
471 #define STATS_INC_ALLOCHIT(x)   atomic_inc(&(x)->allochit)
472 #define STATS_INC_ALLOCMISS(x)  atomic_inc(&(x)->allocmiss)
473 #define STATS_INC_FREEHIT(x)    atomic_inc(&(x)->freehit)
474 #define STATS_INC_FREEMISS(x)   atomic_inc(&(x)->freemiss)
475 #else
476 #define STATS_INC_ACTIVE(x)     do { } while (0)
477 #define STATS_DEC_ACTIVE(x)     do { } while (0)
478 #define STATS_INC_ALLOCED(x)    do { } while (0)
479 #define STATS_INC_GROWN(x)      do { } while (0)
480 #define STATS_INC_REAPED(x)     do { } while (0)
481 #define STATS_SET_HIGH(x)       do { } while (0)
482 #define STATS_INC_ERR(x)        do { } while (0)
483 #define STATS_INC_NODEALLOCS(x) do { } while (0)
484 #define STATS_INC_NODEFREES(x)  do { } while (0)
485 #define STATS_SET_FREEABLE(x, i) do { } while (0)
486 #define STATS_INC_ALLOCHIT(x)   do { } while (0)
487 #define STATS_INC_ALLOCMISS(x)  do { } while (0)
488 #define STATS_INC_FREEHIT(x)    do { } while (0)
489 #define STATS_INC_FREEMISS(x)   do { } while (0)
490 #endif
491
492 #if DEBUG
493 /*
494  * Magic nums for obj red zoning.
495  * Placed in the first word before and the first word after an obj.
496  */
497 #define RED_INACTIVE    0x5A2CF071UL    /* when obj is inactive */
498 #define RED_ACTIVE      0x170FC2A5UL    /* when obj is active */
499
500 /* ...and for poisoning */
501 #define POISON_INUSE    0x5a    /* for use-uninitialised poisoning */
502 #define POISON_FREE     0x6b    /* for use-after-free poisoning */
503 #define POISON_END      0xa5    /* end-byte of poisoning */
504
505 /*
506  * memory layout of objects:
507  * 0            : objp
508  * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
509  *              the end of an object is aligned with the end of the real
510  *              allocation. Catches writes behind the end of the allocation.
511  * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
512  *              redzone word.
513  * cachep->obj_offset: The real object.
514  * cachep->buffer_size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
515  * cachep->buffer_size - 1* BYTES_PER_WORD: last caller address
516  *                                      [BYTES_PER_WORD long]
517  */
518 static int obj_offset(struct kmem_cache *cachep)
519 {
520         return cachep->obj_offset;
521 }
522
523 static int obj_size(struct kmem_cache *cachep)
524 {
525         return cachep->obj_size;
526 }
527
528 static unsigned long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
529 {
530         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
531         return (unsigned long*) (objp+obj_offset(cachep)-BYTES_PER_WORD);
532 }
533
534 static unsigned long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
535 {
536         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
537         if (cachep->flags & SLAB_STORE_USER)
538                 return (unsigned long *)(objp + cachep->buffer_size -
539                                          2 * BYTES_PER_WORD);
540         return (unsigned long *)(objp + cachep->buffer_size - BYTES_PER_WORD);
541 }
542
543 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
544 {
545         BUG_ON(!(cachep->flags & SLAB_STORE_USER));
546         return (void **)(objp + cachep->buffer_size - BYTES_PER_WORD);
547 }
548
549 #else
550
551 #define obj_offset(x)                   0
552 #define obj_size(cachep)                (cachep->buffer_size)
553 #define dbg_redzone1(cachep, objp)      ({BUG(); (unsigned long *)NULL;})
554 #define dbg_redzone2(cachep, objp)      ({BUG(); (unsigned long *)NULL;})
555 #define dbg_userword(cachep, objp)      ({BUG(); (void **)NULL;})
556
557 #endif
558
559 /*
560  * Maximum size of an obj (in 2^order pages) and absolute limit for the gfp
561  * order.
562  */
563 #if defined(CONFIG_LARGE_ALLOCS)
564 #define MAX_OBJ_ORDER   13      /* up to 32Mb */
565 #define MAX_GFP_ORDER   13      /* up to 32Mb */
566 #elif defined(CONFIG_MMU)
567 #define MAX_OBJ_ORDER   5       /* 32 pages */
568 #define MAX_GFP_ORDER   5       /* 32 pages */
569 #else
570 #define MAX_OBJ_ORDER   8       /* up to 1Mb */
571 #define MAX_GFP_ORDER   8       /* up to 1Mb */
572 #endif
573
574 /*
575  * Do not go above this order unless 0 objects fit into the slab.
576  */
577 #define BREAK_GFP_ORDER_HI      1
578 #define BREAK_GFP_ORDER_LO      0
579 static int slab_break_gfp_order = BREAK_GFP_ORDER_LO;
580
581 /*
582  * Functions for storing/retrieving the cachep and or slab from the page
583  * allocator.  These are used to find the slab an obj belongs to.  With kfree(),
584  * these are used to find the cache which an obj belongs to.
585  */
586 static inline void page_set_cache(struct page *page, struct kmem_cache *cache)
587 {
588         page->lru.next = (struct list_head *)cache;
589 }
590
591 static inline struct kmem_cache *page_get_cache(struct page *page)
592 {
593         return (struct kmem_cache *)page->lru.next;
594 }
595
596 static inline void page_set_slab(struct page *page, struct slab *slab)
597 {
598         page->lru.prev = (struct list_head *)slab;
599 }
600
601 static inline struct slab *page_get_slab(struct page *page)
602 {
603         return (struct slab *)page->lru.prev;
604 }
605
606 static inline struct kmem_cache *virt_to_cache(const void *obj)
607 {
608         struct page *page = virt_to_page(obj);
609         return page_get_cache(page);
610 }
611
612 static inline struct slab *virt_to_slab(const void *obj)
613 {
614         struct page *page = virt_to_page(obj);
615         return page_get_slab(page);
616 }
617
618 static inline void *index_to_obj(struct kmem_cache *cache, struct slab *slab,
619                                  unsigned int idx)
620 {
621         return slab->s_mem + cache->buffer_size * idx;
622 }
623
624 static inline unsigned int obj_to_index(struct kmem_cache *cache,
625                                         struct slab *slab, void *obj)
626 {
627         return (unsigned)(obj - slab->s_mem) / cache->buffer_size;
628 }
629
630 /*
631  * These are the default caches for kmalloc. Custom caches can have other sizes.
632  */
633 struct cache_sizes malloc_sizes[] = {
634 #define CACHE(x) { .cs_size = (x) },
635 #include <linux/kmalloc_sizes.h>
636         CACHE(ULONG_MAX)
637 #undef CACHE
638 };
639 EXPORT_SYMBOL(malloc_sizes);
640
641 /* Must match cache_sizes above. Out of line to keep cache footprint low. */
642 struct cache_names {
643         char *name;
644         char *name_dma;
645 };
646
647 static struct cache_names __initdata cache_names[] = {
648 #define CACHE(x) { .name = "size-" #x, .name_dma = "size-" #x "(DMA)" },
649 #include <linux/kmalloc_sizes.h>
650         {NULL,}
651 #undef CACHE
652 };
653
654 static struct arraycache_init initarray_cache __initdata =
655     { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
656 static struct arraycache_init initarray_generic =
657     { {0, BOOT_CPUCACHE_ENTRIES, 1, 0} };
658
659 /* internal cache of cache description objs */
660 static struct kmem_cache cache_cache = {
661         .batchcount = 1,
662         .limit = BOOT_CPUCACHE_ENTRIES,
663         .shared = 1,
664         .buffer_size = sizeof(struct kmem_cache),
665         .flags = SLAB_NO_REAP,
666         .name = "kmem_cache",
667 #if DEBUG
668         .obj_size = sizeof(struct kmem_cache),
669 #endif
670 };
671
672 /* Guard access to the cache-chain. */
673 static DEFINE_MUTEX(cache_chain_mutex);
674 static struct list_head cache_chain;
675
676 /*
677  * vm_enough_memory() looks at this to determine how many slab-allocated pages
678  * are possibly freeable under pressure
679  *
680  * SLAB_RECLAIM_ACCOUNT turns this on per-slab
681  */
682 atomic_t slab_reclaim_pages;
683
684 /*
685  * chicken and egg problem: delay the per-cpu array allocation
686  * until the general caches are up.
687  */
688 static enum {
689         NONE,
690         PARTIAL_AC,
691         PARTIAL_L3,
692         FULL
693 } g_cpucache_up;
694
695 static DEFINE_PER_CPU(struct work_struct, reap_work);
696
697 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
698                         int node);
699 static void enable_cpucache(struct kmem_cache *cachep);
700 static void cache_reap(void *unused);
701 static int __node_shrink(struct kmem_cache *cachep, int node);
702
703 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
704 {
705         return cachep->array[smp_processor_id()];
706 }
707
708 static inline struct kmem_cache *__find_general_cachep(size_t size,
709                                                         gfp_t gfpflags)
710 {
711         struct cache_sizes *csizep = malloc_sizes;
712
713 #if DEBUG
714         /* This happens if someone tries to call
715          * kmem_cache_create(), or __kmalloc(), before
716          * the generic caches are initialized.
717          */
718         BUG_ON(malloc_sizes[INDEX_AC].cs_cachep == NULL);
719 #endif
720         while (size > csizep->cs_size)
721                 csizep++;
722
723         /*
724          * Really subtle: The last entry with cs->cs_size==ULONG_MAX
725          * has cs_{dma,}cachep==NULL. Thus no special case
726          * for large kmalloc calls required.
727          */
728         if (unlikely(gfpflags & GFP_DMA))
729                 return csizep->cs_dmacachep;
730         return csizep->cs_cachep;
731 }
732
733 struct kmem_cache *kmem_find_general_cachep(size_t size, gfp_t gfpflags)
734 {
735         return __find_general_cachep(size, gfpflags);
736 }
737 EXPORT_SYMBOL(kmem_find_general_cachep);
738
739 static size_t slab_mgmt_size(size_t nr_objs, size_t align)
740 {
741         return ALIGN(sizeof(struct slab)+nr_objs*sizeof(kmem_bufctl_t), align);
742 }
743
744 /*
745  * Calculate the number of objects and left-over bytes for a given buffer size.
746  */
747 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
748                            size_t align, int flags, size_t *left_over,
749                            unsigned int *num)
750 {
751         int nr_objs;
752         size_t mgmt_size;
753         size_t slab_size = PAGE_SIZE << gfporder;
754
755         /*
756          * The slab management structure can be either off the slab or
757          * on it. For the latter case, the memory allocated for a
758          * slab is used for:
759          *
760          * - The struct slab
761          * - One kmem_bufctl_t for each object
762          * - Padding to respect alignment of @align
763          * - @buffer_size bytes for each object
764          *
765          * If the slab management structure is off the slab, then the
766          * alignment will already be calculated into the size. Because
767          * the slabs are all pages aligned, the objects will be at the
768          * correct alignment when allocated.
769          */
770         if (flags & CFLGS_OFF_SLAB) {
771                 mgmt_size = 0;
772                 nr_objs = slab_size / buffer_size;
773
774                 if (nr_objs > SLAB_LIMIT)
775                         nr_objs = SLAB_LIMIT;
776         } else {
777                 /*
778                  * Ignore padding for the initial guess. The padding
779                  * is at most @align-1 bytes, and @buffer_size is at
780                  * least @align. In the worst case, this result will
781                  * be one greater than the number of objects that fit
782                  * into the memory allocation when taking the padding
783                  * into account.
784                  */
785                 nr_objs = (slab_size - sizeof(struct slab)) /
786                           (buffer_size + sizeof(kmem_bufctl_t));
787
788                 /*
789                  * This calculated number will be either the right
790                  * amount, or one greater than what we want.
791                  */
792                 if (slab_mgmt_size(nr_objs, align) + nr_objs*buffer_size
793                        > slab_size)
794                         nr_objs--;
795
796                 if (nr_objs > SLAB_LIMIT)
797                         nr_objs = SLAB_LIMIT;
798
799                 mgmt_size = slab_mgmt_size(nr_objs, align);
800         }
801         *num = nr_objs;
802         *left_over = slab_size - nr_objs*buffer_size - mgmt_size;
803 }
804
805 #define slab_error(cachep, msg) __slab_error(__FUNCTION__, cachep, msg)
806
807 static void __slab_error(const char *function, struct kmem_cache *cachep,
808                         char *msg)
809 {
810         printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
811                function, cachep->name, msg);
812         dump_stack();
813 }
814
815 #ifdef CONFIG_NUMA
816 /*
817  * Special reaping functions for NUMA systems called from cache_reap().
818  * These take care of doing round robin flushing of alien caches (containing
819  * objects freed on different nodes from which they were allocated) and the
820  * flushing of remote pcps by calling drain_node_pages.
821  */
822 static DEFINE_PER_CPU(unsigned long, reap_node);
823
824 static void init_reap_node(int cpu)
825 {
826         int node;
827
828         node = next_node(cpu_to_node(cpu), node_online_map);
829         if (node == MAX_NUMNODES)
830                 node = 0;
831
832         __get_cpu_var(reap_node) = node;
833 }
834
835 static void next_reap_node(void)
836 {
837         int node = __get_cpu_var(reap_node);
838
839         /*
840          * Also drain per cpu pages on remote zones
841          */
842         if (node != numa_node_id())
843                 drain_node_pages(node);
844
845         node = next_node(node, node_online_map);
846         if (unlikely(node >= MAX_NUMNODES))
847                 node = first_node(node_online_map);
848         __get_cpu_var(reap_node) = node;
849 }
850
851 #else
852 #define init_reap_node(cpu) do { } while (0)
853 #define next_reap_node(void) do { } while (0)
854 #endif
855
856 /*
857  * Initiate the reap timer running on the target CPU.  We run at around 1 to 2Hz
858  * via the workqueue/eventd.
859  * Add the CPU number into the expiration time to minimize the possibility of
860  * the CPUs getting into lockstep and contending for the global cache chain
861  * lock.
862  */
863 static void __devinit start_cpu_timer(int cpu)
864 {
865         struct work_struct *reap_work = &per_cpu(reap_work, cpu);
866
867         /*
868          * When this gets called from do_initcalls via cpucache_init(),
869          * init_workqueues() has already run, so keventd will be setup
870          * at that time.
871          */
872         if (keventd_up() && reap_work->func == NULL) {
873                 init_reap_node(cpu);
874                 INIT_WORK(reap_work, cache_reap, NULL);
875                 schedule_delayed_work_on(cpu, reap_work, HZ + 3 * cpu);
876         }
877 }
878
879 static struct array_cache *alloc_arraycache(int node, int entries,
880                                             int batchcount)
881 {
882         int memsize = sizeof(void *) * entries + sizeof(struct array_cache);
883         struct array_cache *nc = NULL;
884
885         nc = kmalloc_node(memsize, GFP_KERNEL, node);
886         if (nc) {
887                 nc->avail = 0;
888                 nc->limit = entries;
889                 nc->batchcount = batchcount;
890                 nc->touched = 0;
891                 spin_lock_init(&nc->lock);
892         }
893         return nc;
894 }
895
896 #ifdef CONFIG_NUMA
897 static void *__cache_alloc_node(struct kmem_cache *, gfp_t, int);
898
899 static struct array_cache **alloc_alien_cache(int node, int limit)
900 {
901         struct array_cache **ac_ptr;
902         int memsize = sizeof(void *) * MAX_NUMNODES;
903         int i;
904
905         if (limit > 1)
906                 limit = 12;
907         ac_ptr = kmalloc_node(memsize, GFP_KERNEL, node);
908         if (ac_ptr) {
909                 for_each_node(i) {
910                         if (i == node || !node_online(i)) {
911                                 ac_ptr[i] = NULL;
912                                 continue;
913                         }
914                         ac_ptr[i] = alloc_arraycache(node, limit, 0xbaadf00d);
915                         if (!ac_ptr[i]) {
916                                 for (i--; i <= 0; i--)
917                                         kfree(ac_ptr[i]);
918                                 kfree(ac_ptr);
919                                 return NULL;
920                         }
921                 }
922         }
923         return ac_ptr;
924 }
925
926 static void free_alien_cache(struct array_cache **ac_ptr)
927 {
928         int i;
929
930         if (!ac_ptr)
931                 return;
932         for_each_node(i)
933             kfree(ac_ptr[i]);
934         kfree(ac_ptr);
935 }
936
937 static void __drain_alien_cache(struct kmem_cache *cachep,
938                                 struct array_cache *ac, int node)
939 {
940         struct kmem_list3 *rl3 = cachep->nodelists[node];
941
942         if (ac->avail) {
943                 spin_lock(&rl3->list_lock);
944                 free_block(cachep, ac->entry, ac->avail, node);
945                 ac->avail = 0;
946                 spin_unlock(&rl3->list_lock);
947         }
948 }
949
950 /*
951  * Called from cache_reap() to regularly drain alien caches round robin.
952  */
953 static void reap_alien(struct kmem_cache *cachep, struct kmem_list3 *l3)
954 {
955         int node = __get_cpu_var(reap_node);
956
957         if (l3->alien) {
958                 struct array_cache *ac = l3->alien[node];
959                 if (ac && ac->avail) {
960                         spin_lock_irq(&ac->lock);
961                         __drain_alien_cache(cachep, ac, node);
962                         spin_unlock_irq(&ac->lock);
963                 }
964         }
965 }
966
967 static void drain_alien_cache(struct kmem_cache *cachep,
968                                 struct array_cache **alien)
969 {
970         int i = 0;
971         struct array_cache *ac;
972         unsigned long flags;
973
974         for_each_online_node(i) {
975                 ac = alien[i];
976                 if (ac) {
977                         spin_lock_irqsave(&ac->lock, flags);
978                         __drain_alien_cache(cachep, ac, i);
979                         spin_unlock_irqrestore(&ac->lock, flags);
980                 }
981         }
982 }
983 #else
984
985 #define drain_alien_cache(cachep, alien) do { } while (0)
986 #define reap_alien(cachep, l3) do { } while (0)
987
988 static inline struct array_cache **alloc_alien_cache(int node, int limit)
989 {
990         return (struct array_cache **) 0x01020304ul;
991 }
992
993 static inline void free_alien_cache(struct array_cache **ac_ptr)
994 {
995 }
996
997 #endif
998
999 static int __devinit cpuup_callback(struct notifier_block *nfb,
1000                                     unsigned long action, void *hcpu)
1001 {
1002         long cpu = (long)hcpu;
1003         struct kmem_cache *cachep;
1004         struct kmem_list3 *l3 = NULL;
1005         int node = cpu_to_node(cpu);
1006         int memsize = sizeof(struct kmem_list3);
1007
1008         switch (action) {
1009         case CPU_UP_PREPARE:
1010                 mutex_lock(&cache_chain_mutex);
1011                 /*
1012                  * We need to do this right in the beginning since
1013                  * alloc_arraycache's are going to use this list.
1014                  * kmalloc_node allows us to add the slab to the right
1015                  * kmem_list3 and not this cpu's kmem_list3
1016                  */
1017
1018                 list_for_each_entry(cachep, &cache_chain, next) {
1019                         /*
1020                          * Set up the size64 kmemlist for cpu before we can
1021                          * begin anything. Make sure some other cpu on this
1022                          * node has not already allocated this
1023                          */
1024                         if (!cachep->nodelists[node]) {
1025                                 l3 = kmalloc_node(memsize, GFP_KERNEL, node);
1026                                 if (!l3)
1027                                         goto bad;
1028                                 kmem_list3_init(l3);
1029                                 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
1030                                     ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1031
1032                                 /*
1033                                  * The l3s don't come and go as CPUs come and
1034                                  * go.  cache_chain_mutex is sufficient
1035                                  * protection here.
1036                                  */
1037                                 cachep->nodelists[node] = l3;
1038                         }
1039
1040                         spin_lock_irq(&cachep->nodelists[node]->list_lock);
1041                         cachep->nodelists[node]->free_limit =
1042                                 (1 + nr_cpus_node(node)) *
1043                                 cachep->batchcount + cachep->num;
1044                         spin_unlock_irq(&cachep->nodelists[node]->list_lock);
1045                 }
1046
1047                 /*
1048                  * Now we can go ahead with allocating the shared arrays and
1049                  * array caches
1050                  */
1051                 list_for_each_entry(cachep, &cache_chain, next) {
1052                         struct array_cache *nc;
1053                         struct array_cache *shared;
1054                         struct array_cache **alien;
1055
1056                         nc = alloc_arraycache(node, cachep->limit,
1057                                                 cachep->batchcount);
1058                         if (!nc)
1059                                 goto bad;
1060                         shared = alloc_arraycache(node,
1061                                         cachep->shared * cachep->batchcount,
1062                                         0xbaadf00d);
1063                         if (!shared)
1064                                 goto bad;
1065
1066                         alien = alloc_alien_cache(node, cachep->limit);
1067                         if (!alien)
1068                                 goto bad;
1069                         cachep->array[cpu] = nc;
1070                         l3 = cachep->nodelists[node];
1071                         BUG_ON(!l3);
1072
1073                         spin_lock_irq(&l3->list_lock);
1074                         if (!l3->shared) {
1075                                 /*
1076                                  * We are serialised from CPU_DEAD or
1077                                  * CPU_UP_CANCELLED by the cpucontrol lock
1078                                  */
1079                                 l3->shared = shared;
1080                                 shared = NULL;
1081                         }
1082 #ifdef CONFIG_NUMA
1083                         if (!l3->alien) {
1084                                 l3->alien = alien;
1085                                 alien = NULL;
1086                         }
1087 #endif
1088                         spin_unlock_irq(&l3->list_lock);
1089                         kfree(shared);
1090                         free_alien_cache(alien);
1091                 }
1092                 mutex_unlock(&cache_chain_mutex);
1093                 break;
1094         case CPU_ONLINE:
1095                 start_cpu_timer(cpu);
1096                 break;
1097 #ifdef CONFIG_HOTPLUG_CPU
1098         case CPU_DEAD:
1099                 /*
1100                  * Even if all the cpus of a node are down, we don't free the
1101                  * kmem_list3 of any cache. This to avoid a race between
1102                  * cpu_down, and a kmalloc allocation from another cpu for
1103                  * memory from the node of the cpu going down.  The list3
1104                  * structure is usually allocated from kmem_cache_create() and
1105                  * gets destroyed at kmem_cache_destroy().
1106                  */
1107                 /* fall thru */
1108         case CPU_UP_CANCELED:
1109                 mutex_lock(&cache_chain_mutex);
1110                 list_for_each_entry(cachep, &cache_chain, next) {
1111                         struct array_cache *nc;
1112                         struct array_cache *shared;
1113                         struct array_cache **alien;
1114                         cpumask_t mask;
1115
1116                         mask = node_to_cpumask(node);
1117                         /* cpu is dead; no one can alloc from it. */
1118                         nc = cachep->array[cpu];
1119                         cachep->array[cpu] = NULL;
1120                         l3 = cachep->nodelists[node];
1121
1122                         if (!l3)
1123                                 goto free_array_cache;
1124
1125                         spin_lock_irq(&l3->list_lock);
1126
1127                         /* Free limit for this kmem_list3 */
1128                         l3->free_limit -= cachep->batchcount;
1129                         if (nc)
1130                                 free_block(cachep, nc->entry, nc->avail, node);
1131
1132                         if (!cpus_empty(mask)) {
1133                                 spin_unlock_irq(&l3->list_lock);
1134                                 goto free_array_cache;
1135                         }
1136
1137                         shared = l3->shared;
1138                         if (shared) {
1139                                 free_block(cachep, l3->shared->entry,
1140                                            l3->shared->avail, node);
1141                                 l3->shared = NULL;
1142                         }
1143
1144                         alien = l3->alien;
1145                         l3->alien = NULL;
1146
1147                         spin_unlock_irq(&l3->list_lock);
1148
1149                         kfree(shared);
1150                         if (alien) {
1151                                 drain_alien_cache(cachep, alien);
1152                                 free_alien_cache(alien);
1153                         }
1154 free_array_cache:
1155                         kfree(nc);
1156                 }
1157                 /*
1158                  * In the previous loop, all the objects were freed to
1159                  * the respective cache's slabs,  now we can go ahead and
1160                  * shrink each nodelist to its limit.
1161                  */
1162                 list_for_each_entry(cachep, &cache_chain, next) {
1163                         l3 = cachep->nodelists[node];
1164                         if (!l3)
1165                                 continue;
1166                         spin_lock_irq(&l3->list_lock);
1167                         /* free slabs belonging to this node */
1168                         __node_shrink(cachep, node);
1169                         spin_unlock_irq(&l3->list_lock);
1170                 }
1171                 mutex_unlock(&cache_chain_mutex);
1172                 break;
1173 #endif
1174         }
1175         return NOTIFY_OK;
1176 bad:
1177         mutex_unlock(&cache_chain_mutex);
1178         return NOTIFY_BAD;
1179 }
1180
1181 static struct notifier_block cpucache_notifier = { &cpuup_callback, NULL, 0 };
1182
1183 /*
1184  * swap the static kmem_list3 with kmalloced memory
1185  */
1186 static void init_list(struct kmem_cache *cachep, struct kmem_list3 *list,
1187                         int nodeid)
1188 {
1189         struct kmem_list3 *ptr;
1190
1191         BUG_ON(cachep->nodelists[nodeid] != list);
1192         ptr = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, nodeid);
1193         BUG_ON(!ptr);
1194
1195         local_irq_disable();
1196         memcpy(ptr, list, sizeof(struct kmem_list3));
1197         MAKE_ALL_LISTS(cachep, ptr, nodeid);
1198         cachep->nodelists[nodeid] = ptr;
1199         local_irq_enable();
1200 }
1201
1202 /*
1203  * Initialisation.  Called after the page allocator have been initialised and
1204  * before smp_init().
1205  */
1206 void __init kmem_cache_init(void)
1207 {
1208         size_t left_over;
1209         struct cache_sizes *sizes;
1210         struct cache_names *names;
1211         int i;
1212         int order;
1213
1214         for (i = 0; i < NUM_INIT_LISTS; i++) {
1215                 kmem_list3_init(&initkmem_list3[i]);
1216                 if (i < MAX_NUMNODES)
1217                         cache_cache.nodelists[i] = NULL;
1218         }
1219
1220         /*
1221          * Fragmentation resistance on low memory - only use bigger
1222          * page orders on machines with more than 32MB of memory.
1223          */
1224         if (num_physpages > (32 << 20) >> PAGE_SHIFT)
1225                 slab_break_gfp_order = BREAK_GFP_ORDER_HI;
1226
1227         /* Bootstrap is tricky, because several objects are allocated
1228          * from caches that do not exist yet:
1229          * 1) initialize the cache_cache cache: it contains the struct
1230          *    kmem_cache structures of all caches, except cache_cache itself:
1231          *    cache_cache is statically allocated.
1232          *    Initially an __init data area is used for the head array and the
1233          *    kmem_list3 structures, it's replaced with a kmalloc allocated
1234          *    array at the end of the bootstrap.
1235          * 2) Create the first kmalloc cache.
1236          *    The struct kmem_cache for the new cache is allocated normally.
1237          *    An __init data area is used for the head array.
1238          * 3) Create the remaining kmalloc caches, with minimally sized
1239          *    head arrays.
1240          * 4) Replace the __init data head arrays for cache_cache and the first
1241          *    kmalloc cache with kmalloc allocated arrays.
1242          * 5) Replace the __init data for kmem_list3 for cache_cache and
1243          *    the other cache's with kmalloc allocated memory.
1244          * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1245          */
1246
1247         /* 1) create the cache_cache */
1248         INIT_LIST_HEAD(&cache_chain);
1249         list_add(&cache_cache.next, &cache_chain);
1250         cache_cache.colour_off = cache_line_size();
1251         cache_cache.array[smp_processor_id()] = &initarray_cache.cache;
1252         cache_cache.nodelists[numa_node_id()] = &initkmem_list3[CACHE_CACHE];
1253
1254         cache_cache.buffer_size = ALIGN(cache_cache.buffer_size,
1255                                         cache_line_size());
1256
1257         for (order = 0; order < MAX_ORDER; order++) {
1258                 cache_estimate(order, cache_cache.buffer_size,
1259                         cache_line_size(), 0, &left_over, &cache_cache.num);
1260                 if (cache_cache.num)
1261                         break;
1262         }
1263         if (!cache_cache.num)
1264                 BUG();
1265         cache_cache.gfporder = order;
1266         cache_cache.colour = left_over / cache_cache.colour_off;
1267         cache_cache.slab_size = ALIGN(cache_cache.num * sizeof(kmem_bufctl_t) +
1268                                       sizeof(struct slab), cache_line_size());
1269
1270         /* 2+3) create the kmalloc caches */
1271         sizes = malloc_sizes;
1272         names = cache_names;
1273
1274         /*
1275          * Initialize the caches that provide memory for the array cache and the
1276          * kmem_list3 structures first.  Without this, further allocations will
1277          * bug.
1278          */
1279
1280         sizes[INDEX_AC].cs_cachep = kmem_cache_create(names[INDEX_AC].name,
1281                                         sizes[INDEX_AC].cs_size,
1282                                         ARCH_KMALLOC_MINALIGN,
1283                                         ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1284                                         NULL, NULL);
1285
1286         if (INDEX_AC != INDEX_L3) {
1287                 sizes[INDEX_L3].cs_cachep =
1288                         kmem_cache_create(names[INDEX_L3].name,
1289                                 sizes[INDEX_L3].cs_size,
1290                                 ARCH_KMALLOC_MINALIGN,
1291                                 ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1292                                 NULL, NULL);
1293         }
1294
1295         while (sizes->cs_size != ULONG_MAX) {
1296                 /*
1297                  * For performance, all the general caches are L1 aligned.
1298                  * This should be particularly beneficial on SMP boxes, as it
1299                  * eliminates "false sharing".
1300                  * Note for systems short on memory removing the alignment will
1301                  * allow tighter packing of the smaller caches.
1302                  */
1303                 if (!sizes->cs_cachep) {
1304                         sizes->cs_cachep = kmem_cache_create(names->name,
1305                                         sizes->cs_size,
1306                                         ARCH_KMALLOC_MINALIGN,
1307                                         ARCH_KMALLOC_FLAGS|SLAB_PANIC,
1308                                         NULL, NULL);
1309                 }
1310
1311                 /* Inc off-slab bufctl limit until the ceiling is hit. */
1312                 if (!(OFF_SLAB(sizes->cs_cachep))) {
1313                         offslab_limit = sizes->cs_size - sizeof(struct slab);
1314                         offslab_limit /= sizeof(kmem_bufctl_t);
1315                 }
1316
1317                 sizes->cs_dmacachep = kmem_cache_create(names->name_dma,
1318                                         sizes->cs_size,
1319                                         ARCH_KMALLOC_MINALIGN,
1320                                         ARCH_KMALLOC_FLAGS|SLAB_CACHE_DMA|
1321                                                 SLAB_PANIC,
1322                                         NULL, NULL);
1323                 sizes++;
1324                 names++;
1325         }
1326         /* 4) Replace the bootstrap head arrays */
1327         {
1328                 void *ptr;
1329
1330                 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1331
1332                 local_irq_disable();
1333                 BUG_ON(cpu_cache_get(&cache_cache) != &initarray_cache.cache);
1334                 memcpy(ptr, cpu_cache_get(&cache_cache),
1335                        sizeof(struct arraycache_init));
1336                 cache_cache.array[smp_processor_id()] = ptr;
1337                 local_irq_enable();
1338
1339                 ptr = kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1340
1341                 local_irq_disable();
1342                 BUG_ON(cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep)
1343                        != &initarray_generic.cache);
1344                 memcpy(ptr, cpu_cache_get(malloc_sizes[INDEX_AC].cs_cachep),
1345                        sizeof(struct arraycache_init));
1346                 malloc_sizes[INDEX_AC].cs_cachep->array[smp_processor_id()] =
1347                     ptr;
1348                 local_irq_enable();
1349         }
1350         /* 5) Replace the bootstrap kmem_list3's */
1351         {
1352                 int node;
1353                 /* Replace the static kmem_list3 structures for the boot cpu */
1354                 init_list(&cache_cache, &initkmem_list3[CACHE_CACHE],
1355                           numa_node_id());
1356
1357                 for_each_online_node(node) {
1358                         init_list(malloc_sizes[INDEX_AC].cs_cachep,
1359                                   &initkmem_list3[SIZE_AC + node], node);
1360
1361                         if (INDEX_AC != INDEX_L3) {
1362                                 init_list(malloc_sizes[INDEX_L3].cs_cachep,
1363                                           &initkmem_list3[SIZE_L3 + node],
1364                                           node);
1365                         }
1366                 }
1367         }
1368
1369         /* 6) resize the head arrays to their final sizes */
1370         {
1371                 struct kmem_cache *cachep;
1372                 mutex_lock(&cache_chain_mutex);
1373                 list_for_each_entry(cachep, &cache_chain, next)
1374                         enable_cpucache(cachep);
1375                 mutex_unlock(&cache_chain_mutex);
1376         }
1377
1378         /* Done! */
1379         g_cpucache_up = FULL;
1380
1381         /*
1382          * Register a cpu startup notifier callback that initializes
1383          * cpu_cache_get for all new cpus
1384          */
1385         register_cpu_notifier(&cpucache_notifier);
1386
1387         /*
1388          * The reap timers are started later, with a module init call: That part
1389          * of the kernel is not yet operational.
1390          */
1391 }
1392
1393 static int __init cpucache_init(void)
1394 {
1395         int cpu;
1396
1397         /*
1398          * Register the timers that return unneeded pages to the page allocator
1399          */
1400         for_each_online_cpu(cpu)
1401                 start_cpu_timer(cpu);
1402         return 0;
1403 }
1404 __initcall(cpucache_init);
1405
1406 /*
1407  * Interface to system's page allocator. No need to hold the cache-lock.
1408  *
1409  * If we requested dmaable memory, we will get it. Even if we
1410  * did not request dmaable memory, we might get it, but that
1411  * would be relatively rare and ignorable.
1412  */
1413 static void *kmem_getpages(struct kmem_cache *cachep, gfp_t flags, int nodeid)
1414 {
1415         struct page *page;
1416         void *addr;
1417         int i;
1418
1419         flags |= cachep->gfpflags;
1420         page = alloc_pages_node(nodeid, flags, cachep->gfporder);
1421         if (!page)
1422                 return NULL;
1423         addr = page_address(page);
1424
1425         i = (1 << cachep->gfporder);
1426         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1427                 atomic_add(i, &slab_reclaim_pages);
1428         add_page_state(nr_slab, i);
1429         while (i--) {
1430                 __SetPageSlab(page);
1431                 page++;
1432         }
1433         return addr;
1434 }
1435
1436 /*
1437  * Interface to system's page release.
1438  */
1439 static void kmem_freepages(struct kmem_cache *cachep, void *addr)
1440 {
1441         unsigned long i = (1 << cachep->gfporder);
1442         struct page *page = virt_to_page(addr);
1443         const unsigned long nr_freed = i;
1444
1445         while (i--) {
1446                 BUG_ON(!PageSlab(page));
1447                 __ClearPageSlab(page);
1448                 page++;
1449         }
1450         sub_page_state(nr_slab, nr_freed);
1451         if (current->reclaim_state)
1452                 current->reclaim_state->reclaimed_slab += nr_freed;
1453         free_pages((unsigned long)addr, cachep->gfporder);
1454         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1455                 atomic_sub(1 << cachep->gfporder, &slab_reclaim_pages);
1456 }
1457
1458 static void kmem_rcu_free(struct rcu_head *head)
1459 {
1460         struct slab_rcu *slab_rcu = (struct slab_rcu *)head;
1461         struct kmem_cache *cachep = slab_rcu->cachep;
1462
1463         kmem_freepages(cachep, slab_rcu->addr);
1464         if (OFF_SLAB(cachep))
1465                 kmem_cache_free(cachep->slabp_cache, slab_rcu);
1466 }
1467
1468 #if DEBUG
1469
1470 #ifdef CONFIG_DEBUG_PAGEALLOC
1471 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1472                             unsigned long caller)
1473 {
1474         int size = obj_size(cachep);
1475
1476         addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1477
1478         if (size < 5 * sizeof(unsigned long))
1479                 return;
1480
1481         *addr++ = 0x12345678;
1482         *addr++ = caller;
1483         *addr++ = smp_processor_id();
1484         size -= 3 * sizeof(unsigned long);
1485         {
1486                 unsigned long *sptr = &caller;
1487                 unsigned long svalue;
1488
1489                 while (!kstack_end(sptr)) {
1490                         svalue = *sptr++;
1491                         if (kernel_text_address(svalue)) {
1492                                 *addr++ = svalue;
1493                                 size -= sizeof(unsigned long);
1494                                 if (size <= sizeof(unsigned long))
1495                                         break;
1496                         }
1497                 }
1498
1499         }
1500         *addr++ = 0x87654321;
1501 }
1502 #endif
1503
1504 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1505 {
1506         int size = obj_size(cachep);
1507         addr = &((char *)addr)[obj_offset(cachep)];
1508
1509         memset(addr, val, size);
1510         *(unsigned char *)(addr + size - 1) = POISON_END;
1511 }
1512
1513 static void dump_line(char *data, int offset, int limit)
1514 {
1515         int i;
1516         printk(KERN_ERR "%03x:", offset);
1517         for (i = 0; i < limit; i++)
1518                 printk(" %02x", (unsigned char)data[offset + i]);
1519         printk("\n");
1520 }
1521 #endif
1522
1523 #if DEBUG
1524
1525 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1526 {
1527         int i, size;
1528         char *realobj;
1529
1530         if (cachep->flags & SLAB_RED_ZONE) {
1531                 printk(KERN_ERR "Redzone: 0x%lx/0x%lx.\n",
1532                         *dbg_redzone1(cachep, objp),
1533                         *dbg_redzone2(cachep, objp));
1534         }
1535
1536         if (cachep->flags & SLAB_STORE_USER) {
1537                 printk(KERN_ERR "Last user: [<%p>]",
1538                         *dbg_userword(cachep, objp));
1539                 print_symbol("(%s)",
1540                                 (unsigned long)*dbg_userword(cachep, objp));
1541                 printk("\n");
1542         }
1543         realobj = (char *)objp + obj_offset(cachep);
1544         size = obj_size(cachep);
1545         for (i = 0; i < size && lines; i += 16, lines--) {
1546                 int limit;
1547                 limit = 16;
1548                 if (i + limit > size)
1549                         limit = size - i;
1550                 dump_line(realobj, i, limit);
1551         }
1552 }
1553
1554 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1555 {
1556         char *realobj;
1557         int size, i;
1558         int lines = 0;
1559
1560         realobj = (char *)objp + obj_offset(cachep);
1561         size = obj_size(cachep);
1562
1563         for (i = 0; i < size; i++) {
1564                 char exp = POISON_FREE;
1565                 if (i == size - 1)
1566                         exp = POISON_END;
1567                 if (realobj[i] != exp) {
1568                         int limit;
1569                         /* Mismatch ! */
1570                         /* Print header */
1571                         if (lines == 0) {
1572                                 printk(KERN_ERR
1573                                         "Slab corruption: start=%p, len=%d\n",
1574                                         realobj, size);
1575                                 print_objinfo(cachep, objp, 0);
1576                         }
1577                         /* Hexdump the affected line */
1578                         i = (i / 16) * 16;
1579                         limit = 16;
1580                         if (i + limit > size)
1581                                 limit = size - i;
1582                         dump_line(realobj, i, limit);
1583                         i += 16;
1584                         lines++;
1585                         /* Limit to 5 lines */
1586                         if (lines > 5)
1587                                 break;
1588                 }
1589         }
1590         if (lines != 0) {
1591                 /* Print some data about the neighboring objects, if they
1592                  * exist:
1593                  */
1594                 struct slab *slabp = virt_to_slab(objp);
1595                 unsigned int objnr;
1596
1597                 objnr = obj_to_index(cachep, slabp, objp);
1598                 if (objnr) {
1599                         objp = index_to_obj(cachep, slabp, objnr - 1);
1600                         realobj = (char *)objp + obj_offset(cachep);
1601                         printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1602                                realobj, size);
1603                         print_objinfo(cachep, objp, 2);
1604                 }
1605                 if (objnr + 1 < cachep->num) {
1606                         objp = index_to_obj(cachep, slabp, objnr + 1);
1607                         realobj = (char *)objp + obj_offset(cachep);
1608                         printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1609                                realobj, size);
1610                         print_objinfo(cachep, objp, 2);
1611                 }
1612         }
1613 }
1614 #endif
1615
1616 #if DEBUG
1617 /**
1618  * slab_destroy_objs - call the registered destructor for each object in
1619  *      a slab that is to be destroyed.
1620  */
1621 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1622 {
1623         int i;
1624         for (i = 0; i < cachep->num; i++) {
1625                 void *objp = index_to_obj(cachep, slabp, i);
1626
1627                 if (cachep->flags & SLAB_POISON) {
1628 #ifdef CONFIG_DEBUG_PAGEALLOC
1629                         if (cachep->buffer_size % PAGE_SIZE == 0 &&
1630                                         OFF_SLAB(cachep))
1631                                 kernel_map_pages(virt_to_page(objp),
1632                                         cachep->buffer_size / PAGE_SIZE, 1);
1633                         else
1634                                 check_poison_obj(cachep, objp);
1635 #else
1636                         check_poison_obj(cachep, objp);
1637 #endif
1638                 }
1639                 if (cachep->flags & SLAB_RED_ZONE) {
1640                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1641                                 slab_error(cachep, "start of a freed object "
1642                                            "was overwritten");
1643                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1644                                 slab_error(cachep, "end of a freed object "
1645                                            "was overwritten");
1646                 }
1647                 if (cachep->dtor && !(cachep->flags & SLAB_POISON))
1648                         (cachep->dtor) (objp + obj_offset(cachep), cachep, 0);
1649         }
1650 }
1651 #else
1652 static void slab_destroy_objs(struct kmem_cache *cachep, struct slab *slabp)
1653 {
1654         if (cachep->dtor) {
1655                 int i;
1656                 for (i = 0; i < cachep->num; i++) {
1657                         void *objp = index_to_obj(cachep, slabp, i);
1658                         (cachep->dtor) (objp, cachep, 0);
1659                 }
1660         }
1661 }
1662 #endif
1663
1664 /*
1665  * Destroy all the objs in a slab, and release the mem back to the system.
1666  * Before calling the slab must have been unlinked from the cache.  The
1667  * cache-lock is not held/needed.
1668  */
1669 static void slab_destroy(struct kmem_cache *cachep, struct slab *slabp)
1670 {
1671         void *addr = slabp->s_mem - slabp->colouroff;
1672
1673         slab_destroy_objs(cachep, slabp);
1674         if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU)) {
1675                 struct slab_rcu *slab_rcu;
1676
1677                 slab_rcu = (struct slab_rcu *)slabp;
1678                 slab_rcu->cachep = cachep;
1679                 slab_rcu->addr = addr;
1680                 call_rcu(&slab_rcu->head, kmem_rcu_free);
1681         } else {
1682                 kmem_freepages(cachep, addr);
1683                 if (OFF_SLAB(cachep))
1684                         kmem_cache_free(cachep->slabp_cache, slabp);
1685         }
1686 }
1687
1688 /*
1689  * For setting up all the kmem_list3s for cache whose buffer_size is same as
1690  * size of kmem_list3.
1691  */
1692 static void set_up_list3s(struct kmem_cache *cachep, int index)
1693 {
1694         int node;
1695
1696         for_each_online_node(node) {
1697                 cachep->nodelists[node] = &initkmem_list3[index + node];
1698                 cachep->nodelists[node]->next_reap = jiffies +
1699                     REAPTIMEOUT_LIST3 +
1700                     ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1701         }
1702 }
1703
1704 /**
1705  * calculate_slab_order - calculate size (page order) of slabs
1706  * @cachep: pointer to the cache that is being created
1707  * @size: size of objects to be created in this cache.
1708  * @align: required alignment for the objects.
1709  * @flags: slab allocation flags
1710  *
1711  * Also calculates the number of objects per slab.
1712  *
1713  * This could be made much more intelligent.  For now, try to avoid using
1714  * high order pages for slabs.  When the gfp() functions are more friendly
1715  * towards high-order requests, this should be changed.
1716  */
1717 static size_t calculate_slab_order(struct kmem_cache *cachep,
1718                         size_t size, size_t align, unsigned long flags)
1719 {
1720         size_t left_over = 0;
1721         int gfporder;
1722
1723         for (gfporder = 0; gfporder <= MAX_GFP_ORDER; gfporder++) {
1724                 unsigned int num;
1725                 size_t remainder;
1726
1727                 cache_estimate(gfporder, size, align, flags, &remainder, &num);
1728                 if (!num)
1729                         continue;
1730
1731                 /* More than offslab_limit objects will cause problems */
1732                 if ((flags & CFLGS_OFF_SLAB) && num > offslab_limit)
1733                         break;
1734
1735                 /* Found something acceptable - save it away */
1736                 cachep->num = num;
1737                 cachep->gfporder = gfporder;
1738                 left_over = remainder;
1739
1740                 /*
1741                  * A VFS-reclaimable slab tends to have most allocations
1742                  * as GFP_NOFS and we really don't want to have to be allocating
1743                  * higher-order pages when we are unable to shrink dcache.
1744                  */
1745                 if (flags & SLAB_RECLAIM_ACCOUNT)
1746                         break;
1747
1748                 /*
1749                  * Large number of objects is good, but very large slabs are
1750                  * currently bad for the gfp()s.
1751                  */
1752                 if (gfporder >= slab_break_gfp_order)
1753                         break;
1754
1755                 /*
1756                  * Acceptable internal fragmentation?
1757                  */
1758                 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1759                         break;
1760         }
1761         return left_over;
1762 }
1763
1764 static void setup_cpu_cache(struct kmem_cache *cachep)
1765 {
1766         if (g_cpucache_up == FULL) {
1767                 enable_cpucache(cachep);
1768                 return;
1769         }
1770         if (g_cpucache_up == NONE) {
1771                 /*
1772                  * Note: the first kmem_cache_create must create the cache
1773                  * that's used by kmalloc(24), otherwise the creation of
1774                  * further caches will BUG().
1775                  */
1776                 cachep->array[smp_processor_id()] = &initarray_generic.cache;
1777
1778                 /*
1779                  * If the cache that's used by kmalloc(sizeof(kmem_list3)) is
1780                  * the first cache, then we need to set up all its list3s,
1781                  * otherwise the creation of further caches will BUG().
1782                  */
1783                 set_up_list3s(cachep, SIZE_AC);
1784                 if (INDEX_AC == INDEX_L3)
1785                         g_cpucache_up = PARTIAL_L3;
1786                 else
1787                         g_cpucache_up = PARTIAL_AC;
1788         } else {
1789                 cachep->array[smp_processor_id()] =
1790                         kmalloc(sizeof(struct arraycache_init), GFP_KERNEL);
1791
1792                 if (g_cpucache_up == PARTIAL_AC) {
1793                         set_up_list3s(cachep, SIZE_L3);
1794                         g_cpucache_up = PARTIAL_L3;
1795                 } else {
1796                         int node;
1797                         for_each_online_node(node) {
1798                                 cachep->nodelists[node] =
1799                                     kmalloc_node(sizeof(struct kmem_list3),
1800                                                 GFP_KERNEL, node);
1801                                 BUG_ON(!cachep->nodelists[node]);
1802                                 kmem_list3_init(cachep->nodelists[node]);
1803                         }
1804                 }
1805         }
1806         cachep->nodelists[numa_node_id()]->next_reap =
1807                         jiffies + REAPTIMEOUT_LIST3 +
1808                         ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
1809
1810         cpu_cache_get(cachep)->avail = 0;
1811         cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1812         cpu_cache_get(cachep)->batchcount = 1;
1813         cpu_cache_get(cachep)->touched = 0;
1814         cachep->batchcount = 1;
1815         cachep->limit = BOOT_CPUCACHE_ENTRIES;
1816 }
1817
1818 /**
1819  * kmem_cache_create - Create a cache.
1820  * @name: A string which is used in /proc/slabinfo to identify this cache.
1821  * @size: The size of objects to be created in this cache.
1822  * @align: The required alignment for the objects.
1823  * @flags: SLAB flags
1824  * @ctor: A constructor for the objects.
1825  * @dtor: A destructor for the objects.
1826  *
1827  * Returns a ptr to the cache on success, NULL on failure.
1828  * Cannot be called within a int, but can be interrupted.
1829  * The @ctor is run when new pages are allocated by the cache
1830  * and the @dtor is run before the pages are handed back.
1831  *
1832  * @name must be valid until the cache is destroyed. This implies that
1833  * the module calling this has to destroy the cache before getting unloaded.
1834  *
1835  * The flags are
1836  *
1837  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
1838  * to catch references to uninitialised memory.
1839  *
1840  * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
1841  * for buffer overruns.
1842  *
1843  * %SLAB_NO_REAP - Don't automatically reap this cache when we're under
1844  * memory pressure.
1845  *
1846  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
1847  * cacheline.  This can be beneficial if you're counting cycles as closely
1848  * as davem.
1849  */
1850 struct kmem_cache *
1851 kmem_cache_create (const char *name, size_t size, size_t align,
1852         unsigned long flags,
1853         void (*ctor)(void*, struct kmem_cache *, unsigned long),
1854         void (*dtor)(void*, struct kmem_cache *, unsigned long))
1855 {
1856         size_t left_over, slab_size, ralign;
1857         struct kmem_cache *cachep = NULL;
1858         struct list_head *p;
1859
1860         /*
1861          * Sanity checks... these are all serious usage bugs.
1862          */
1863         if (!name || in_interrupt() || (size < BYTES_PER_WORD) ||
1864             (size > (1 << MAX_OBJ_ORDER) * PAGE_SIZE) || (dtor && !ctor)) {
1865                 printk(KERN_ERR "%s: Early error in slab %s\n", __FUNCTION__,
1866                                 name);
1867                 BUG();
1868         }
1869
1870         /*
1871          * Prevent CPUs from coming and going.
1872          * lock_cpu_hotplug() nests outside cache_chain_mutex
1873          */
1874         lock_cpu_hotplug();
1875
1876         mutex_lock(&cache_chain_mutex);
1877
1878         list_for_each(p, &cache_chain) {
1879                 struct kmem_cache *pc = list_entry(p, struct kmem_cache, next);
1880                 mm_segment_t old_fs = get_fs();
1881                 char tmp;
1882                 int res;
1883
1884                 /*
1885                  * This happens when the module gets unloaded and doesn't
1886                  * destroy its slab cache and no-one else reuses the vmalloc
1887                  * area of the module.  Print a warning.
1888                  */
1889                 set_fs(KERNEL_DS);
1890                 res = __get_user(tmp, pc->name);
1891                 set_fs(old_fs);
1892                 if (res) {
1893                         printk("SLAB: cache with size %d has lost its name\n",
1894                                pc->buffer_size);
1895                         continue;
1896                 }
1897
1898                 if (!strcmp(pc->name, name)) {
1899                         printk("kmem_cache_create: duplicate cache %s\n", name);
1900                         dump_stack();
1901                         goto oops;
1902                 }
1903         }
1904
1905 #if DEBUG
1906         WARN_ON(strchr(name, ' '));     /* It confuses parsers */
1907         if ((flags & SLAB_DEBUG_INITIAL) && !ctor) {
1908                 /* No constructor, but inital state check requested */
1909                 printk(KERN_ERR "%s: No con, but init state check "
1910                        "requested - %s\n", __FUNCTION__, name);
1911                 flags &= ~SLAB_DEBUG_INITIAL;
1912         }
1913 #if FORCED_DEBUG
1914         /*
1915          * Enable redzoning and last user accounting, except for caches with
1916          * large objects, if the increased size would increase the object size
1917          * above the next power of two: caches with object sizes just above a
1918          * power of two have a significant amount of internal fragmentation.
1919          */
1920         if (size < 4096 || fls(size - 1) == fls(size-1 + 3 * BYTES_PER_WORD))
1921                 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
1922         if (!(flags & SLAB_DESTROY_BY_RCU))
1923                 flags |= SLAB_POISON;
1924 #endif
1925         if (flags & SLAB_DESTROY_BY_RCU)
1926                 BUG_ON(flags & SLAB_POISON);
1927 #endif
1928         if (flags & SLAB_DESTROY_BY_RCU)
1929                 BUG_ON(dtor);
1930
1931         /*
1932          * Always checks flags, a caller might be expecting debug support which
1933          * isn't available.
1934          */
1935         if (flags & ~CREATE_MASK)
1936                 BUG();
1937
1938         /*
1939          * Check that size is in terms of words.  This is needed to avoid
1940          * unaligned accesses for some archs when redzoning is used, and makes
1941          * sure any on-slab bufctl's are also correctly aligned.
1942          */
1943         if (size & (BYTES_PER_WORD - 1)) {
1944                 size += (BYTES_PER_WORD - 1);
1945                 size &= ~(BYTES_PER_WORD - 1);
1946         }
1947
1948         /* calculate the final buffer alignment: */
1949
1950         /* 1) arch recommendation: can be overridden for debug */
1951         if (flags & SLAB_HWCACHE_ALIGN) {
1952                 /*
1953                  * Default alignment: as specified by the arch code.  Except if
1954                  * an object is really small, then squeeze multiple objects into
1955                  * one cacheline.
1956                  */
1957                 ralign = cache_line_size();
1958                 while (size <= ralign / 2)
1959                         ralign /= 2;
1960         } else {
1961                 ralign = BYTES_PER_WORD;
1962         }
1963         /* 2) arch mandated alignment: disables debug if necessary */
1964         if (ralign < ARCH_SLAB_MINALIGN) {
1965                 ralign = ARCH_SLAB_MINALIGN;
1966                 if (ralign > BYTES_PER_WORD)
1967                         flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
1968         }
1969         /* 3) caller mandated alignment: disables debug if necessary */
1970         if (ralign < align) {
1971                 ralign = align;
1972                 if (ralign > BYTES_PER_WORD)
1973                         flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
1974         }
1975         /*
1976          * 4) Store it. Note that the debug code below can reduce
1977          *    the alignment to BYTES_PER_WORD.
1978          */
1979         align = ralign;
1980
1981         /* Get cache's description obj. */
1982         cachep = kmem_cache_alloc(&cache_cache, SLAB_KERNEL);
1983         if (!cachep)
1984                 goto oops;
1985         memset(cachep, 0, sizeof(struct kmem_cache));
1986
1987 #if DEBUG
1988         cachep->obj_size = size;
1989
1990         if (flags & SLAB_RED_ZONE) {
1991                 /* redzoning only works with word aligned caches */
1992                 align = BYTES_PER_WORD;
1993
1994                 /* add space for red zone words */
1995                 cachep->obj_offset += BYTES_PER_WORD;
1996                 size += 2 * BYTES_PER_WORD;
1997         }
1998         if (flags & SLAB_STORE_USER) {
1999                 /* user store requires word alignment and
2000                  * one word storage behind the end of the real
2001                  * object.
2002                  */
2003                 align = BYTES_PER_WORD;
2004                 size += BYTES_PER_WORD;
2005         }
2006 #if FORCED_DEBUG && defined(CONFIG_DEBUG_PAGEALLOC)
2007         if (size >= malloc_sizes[INDEX_L3 + 1].cs_size
2008             && cachep->obj_size > cache_line_size() && size < PAGE_SIZE) {
2009                 cachep->obj_offset += PAGE_SIZE - size;
2010                 size = PAGE_SIZE;
2011         }
2012 #endif
2013 #endif
2014
2015         /* Determine if the slab management is 'on' or 'off' slab. */
2016         if (size >= (PAGE_SIZE >> 3))
2017                 /*
2018                  * Size is large, assume best to place the slab management obj
2019                  * off-slab (should allow better packing of objs).
2020                  */
2021                 flags |= CFLGS_OFF_SLAB;
2022
2023         size = ALIGN(size, align);
2024
2025         left_over = calculate_slab_order(cachep, size, align, flags);
2026
2027         if (!cachep->num) {
2028                 printk("kmem_cache_create: couldn't create cache %s.\n", name);
2029                 kmem_cache_free(&cache_cache, cachep);
2030                 cachep = NULL;
2031                 goto oops;
2032         }
2033         slab_size = ALIGN(cachep->num * sizeof(kmem_bufctl_t)
2034                           + sizeof(struct slab), align);
2035
2036         /*
2037          * If the slab has been placed off-slab, and we have enough space then
2038          * move it on-slab. This is at the expense of any extra colouring.
2039          */
2040         if (flags & CFLGS_OFF_SLAB && left_over >= slab_size) {
2041                 flags &= ~CFLGS_OFF_SLAB;
2042                 left_over -= slab_size;
2043         }
2044
2045         if (flags & CFLGS_OFF_SLAB) {
2046                 /* really off slab. No need for manual alignment */
2047                 slab_size =
2048                     cachep->num * sizeof(kmem_bufctl_t) + sizeof(struct slab);
2049         }
2050
2051         cachep->colour_off = cache_line_size();
2052         /* Offset must be a multiple of the alignment. */
2053         if (cachep->colour_off < align)
2054                 cachep->colour_off = align;
2055         cachep->colour = left_over / cachep->colour_off;
2056         cachep->slab_size = slab_size;
2057         cachep->flags = flags;
2058         cachep->gfpflags = 0;
2059         if (flags & SLAB_CACHE_DMA)
2060                 cachep->gfpflags |= GFP_DMA;
2061         cachep->buffer_size = size;
2062
2063         if (flags & CFLGS_OFF_SLAB)
2064                 cachep->slabp_cache = kmem_find_general_cachep(slab_size, 0u);
2065         cachep->ctor = ctor;
2066         cachep->dtor = dtor;
2067         cachep->name = name;
2068
2069
2070         setup_cpu_cache(cachep);
2071
2072         /* cache setup completed, link it into the list */
2073         list_add(&cachep->next, &cache_chain);
2074 oops:
2075         if (!cachep && (flags & SLAB_PANIC))
2076                 panic("kmem_cache_create(): failed to create slab `%s'\n",
2077                       name);
2078         mutex_unlock(&cache_chain_mutex);
2079         unlock_cpu_hotplug();
2080         return cachep;
2081 }
2082 EXPORT_SYMBOL(kmem_cache_create);
2083
2084 #if DEBUG
2085 static void check_irq_off(void)
2086 {
2087         BUG_ON(!irqs_disabled());
2088 }
2089
2090 static void check_irq_on(void)
2091 {
2092         BUG_ON(irqs_disabled());
2093 }
2094
2095 static void check_spinlock_acquired(struct kmem_cache *cachep)
2096 {
2097 #ifdef CONFIG_SMP
2098         check_irq_off();
2099         assert_spin_locked(&cachep->nodelists[numa_node_id()]->list_lock);
2100 #endif
2101 }
2102
2103 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2104 {
2105 #ifdef CONFIG_SMP
2106         check_irq_off();
2107         assert_spin_locked(&cachep->nodelists[node]->list_lock);
2108 #endif
2109 }
2110
2111 #else
2112 #define check_irq_off() do { } while(0)
2113 #define check_irq_on()  do { } while(0)
2114 #define check_spinlock_acquired(x) do { } while(0)
2115 #define check_spinlock_acquired_node(x, y) do { } while(0)
2116 #endif
2117
2118 /*
2119  * Waits for all CPUs to execute func().
2120  */
2121 static void smp_call_function_all_cpus(void (*func)(void *arg), void *arg)
2122 {
2123         check_irq_on();
2124         preempt_disable();
2125         local_irq_disable();
2126         func(arg);
2127         local_irq_enable();
2128
2129         if (smp_call_function(func, arg, 1, 1))
2130                 BUG();
2131
2132         preempt_enable();
2133 }
2134
2135 static void drain_array_locked(struct kmem_cache *cachep,
2136                         struct array_cache *ac, int force, int node);
2137
2138 static void do_drain(void *arg)
2139 {
2140         struct kmem_cache *cachep = arg;
2141         struct array_cache *ac;
2142         int node = numa_node_id();
2143
2144         check_irq_off();
2145         ac = cpu_cache_get(cachep);
2146         spin_lock(&cachep->nodelists[node]->list_lock);
2147         free_block(cachep, ac->entry, ac->avail, node);
2148         spin_unlock(&cachep->nodelists[node]->list_lock);
2149         ac->avail = 0;
2150 }
2151
2152 static void drain_cpu_caches(struct kmem_cache *cachep)
2153 {
2154         struct kmem_list3 *l3;
2155         int node;
2156
2157         smp_call_function_all_cpus(do_drain, cachep);
2158         check_irq_on();
2159         for_each_online_node(node) {
2160                 l3 = cachep->nodelists[node];
2161                 if (l3) {
2162                         spin_lock_irq(&l3->list_lock);
2163                         drain_array_locked(cachep, l3->shared, 1, node);
2164                         spin_unlock_irq(&l3->list_lock);
2165                         if (l3->alien)
2166                                 drain_alien_cache(cachep, l3->alien);
2167                 }
2168         }
2169 }
2170
2171 static int __node_shrink(struct kmem_cache *cachep, int node)
2172 {
2173         struct slab *slabp;
2174         struct kmem_list3 *l3 = cachep->nodelists[node];
2175         int ret;
2176
2177         for (;;) {
2178                 struct list_head *p;
2179
2180                 p = l3->slabs_free.prev;
2181                 if (p == &l3->slabs_free)
2182                         break;
2183
2184                 slabp = list_entry(l3->slabs_free.prev, struct slab, list);
2185 #if DEBUG
2186                 if (slabp->inuse)
2187                         BUG();
2188 #endif
2189                 list_del(&slabp->list);
2190
2191                 l3->free_objects -= cachep->num;
2192                 spin_unlock_irq(&l3->list_lock);
2193                 slab_destroy(cachep, slabp);
2194                 spin_lock_irq(&l3->list_lock);
2195         }
2196         ret = !list_empty(&l3->slabs_full) || !list_empty(&l3->slabs_partial);
2197         return ret;
2198 }
2199
2200 static int __cache_shrink(struct kmem_cache *cachep)
2201 {
2202         int ret = 0, i = 0;
2203         struct kmem_list3 *l3;
2204
2205         drain_cpu_caches(cachep);
2206
2207         check_irq_on();
2208         for_each_online_node(i) {
2209                 l3 = cachep->nodelists[i];
2210                 if (l3) {
2211                         spin_lock_irq(&l3->list_lock);
2212                         ret += __node_shrink(cachep, i);
2213                         spin_unlock_irq(&l3->list_lock);
2214                 }
2215         }
2216         return (ret ? 1 : 0);
2217 }
2218
2219 /**
2220  * kmem_cache_shrink - Shrink a cache.
2221  * @cachep: The cache to shrink.
2222  *
2223  * Releases as many slabs as possible for a cache.
2224  * To help debugging, a zero exit status indicates all slabs were released.
2225  */
2226 int kmem_cache_shrink(struct kmem_cache *cachep)
2227 {
2228         if (!cachep || in_interrupt())
2229                 BUG();
2230
2231         return __cache_shrink(cachep);
2232 }
2233 EXPORT_SYMBOL(kmem_cache_shrink);
2234
2235 /**
2236  * kmem_cache_destroy - delete a cache
2237  * @cachep: the cache to destroy
2238  *
2239  * Remove a struct kmem_cache object from the slab cache.
2240  * Returns 0 on success.
2241  *
2242  * It is expected this function will be called by a module when it is
2243  * unloaded.  This will remove the cache completely, and avoid a duplicate
2244  * cache being allocated each time a module is loaded and unloaded, if the
2245  * module doesn't have persistent in-kernel storage across loads and unloads.
2246  *
2247  * The cache must be empty before calling this function.
2248  *
2249  * The caller must guarantee that noone will allocate memory from the cache
2250  * during the kmem_cache_destroy().
2251  */
2252 int kmem_cache_destroy(struct kmem_cache *cachep)
2253 {
2254         int i;
2255         struct kmem_list3 *l3;
2256
2257         if (!cachep || in_interrupt())
2258                 BUG();
2259
2260         /* Don't let CPUs to come and go */
2261         lock_cpu_hotplug();
2262
2263         /* Find the cache in the chain of caches. */
2264         mutex_lock(&cache_chain_mutex);
2265         /*
2266          * the chain is never empty, cache_cache is never destroyed
2267          */
2268         list_del(&cachep->next);
2269         mutex_unlock(&cache_chain_mutex);
2270
2271         if (__cache_shrink(cachep)) {
2272                 slab_error(cachep, "Can't free all objects");
2273                 mutex_lock(&cache_chain_mutex);
2274                 list_add(&cachep->next, &cache_chain);
2275                 mutex_unlock(&cache_chain_mutex);
2276                 unlock_cpu_hotplug();
2277                 return 1;
2278         }
2279
2280         if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
2281                 synchronize_rcu();
2282
2283         for_each_online_cpu(i)
2284             kfree(cachep->array[i]);
2285
2286         /* NUMA: free the list3 structures */
2287         for_each_online_node(i) {
2288                 l3 = cachep->nodelists[i];
2289                 if (l3) {
2290                         kfree(l3->shared);
2291                         free_alien_cache(l3->alien);
2292                         kfree(l3);
2293                 }
2294         }
2295         kmem_cache_free(&cache_cache, cachep);
2296         unlock_cpu_hotplug();
2297         return 0;
2298 }
2299 EXPORT_SYMBOL(kmem_cache_destroy);
2300
2301 /* Get the memory for a slab management obj. */
2302 static struct slab *alloc_slabmgmt(struct kmem_cache *cachep, void *objp,
2303                                    int colour_off, gfp_t local_flags)
2304 {
2305         struct slab *slabp;
2306
2307         if (OFF_SLAB(cachep)) {
2308                 /* Slab management obj is off-slab. */
2309                 slabp = kmem_cache_alloc(cachep->slabp_cache, local_flags);
2310                 if (!slabp)
2311                         return NULL;
2312         } else {
2313                 slabp = objp + colour_off;
2314                 colour_off += cachep->slab_size;
2315         }
2316         slabp->inuse = 0;
2317         slabp->colouroff = colour_off;
2318         slabp->s_mem = objp + colour_off;
2319         return slabp;
2320 }
2321
2322 static inline kmem_bufctl_t *slab_bufctl(struct slab *slabp)
2323 {
2324         return (kmem_bufctl_t *) (slabp + 1);
2325 }
2326
2327 static void cache_init_objs(struct kmem_cache *cachep,
2328                             struct slab *slabp, unsigned long ctor_flags)
2329 {
2330         int i;
2331
2332         for (i = 0; i < cachep->num; i++) {
2333                 void *objp = index_to_obj(cachep, slabp, i);
2334 #if DEBUG
2335                 /* need to poison the objs? */
2336                 if (cachep->flags & SLAB_POISON)
2337                         poison_obj(cachep, objp, POISON_FREE);
2338                 if (cachep->flags & SLAB_STORE_USER)
2339                         *dbg_userword(cachep, objp) = NULL;
2340
2341                 if (cachep->flags & SLAB_RED_ZONE) {
2342                         *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2343                         *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2344                 }
2345                 /*
2346                  * Constructors are not allowed to allocate memory from the same
2347                  * cache which they are a constructor for.  Otherwise, deadlock.
2348                  * They must also be threaded.
2349                  */
2350                 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2351                         cachep->ctor(objp + obj_offset(cachep), cachep,
2352                                      ctor_flags);
2353
2354                 if (cachep->flags & SLAB_RED_ZONE) {
2355                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2356                                 slab_error(cachep, "constructor overwrote the"
2357                                            " end of an object");
2358                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2359                                 slab_error(cachep, "constructor overwrote the"
2360                                            " start of an object");
2361                 }
2362                 if ((cachep->buffer_size % PAGE_SIZE) == 0 &&
2363                             OFF_SLAB(cachep) && cachep->flags & SLAB_POISON)
2364                         kernel_map_pages(virt_to_page(objp),
2365                                          cachep->buffer_size / PAGE_SIZE, 0);
2366 #else
2367                 if (cachep->ctor)
2368                         cachep->ctor(objp, cachep, ctor_flags);
2369 #endif
2370                 slab_bufctl(slabp)[i] = i + 1;
2371         }
2372         slab_bufctl(slabp)[i - 1] = BUFCTL_END;
2373         slabp->free = 0;
2374 }
2375
2376 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2377 {
2378         if (flags & SLAB_DMA)
2379                 BUG_ON(!(cachep->gfpflags & GFP_DMA));
2380         else
2381                 BUG_ON(cachep->gfpflags & GFP_DMA);
2382 }
2383
2384 static void *slab_get_obj(struct kmem_cache *cachep, struct slab *slabp,
2385                                 int nodeid)
2386 {
2387         void *objp = index_to_obj(cachep, slabp, slabp->free);
2388         kmem_bufctl_t next;
2389
2390         slabp->inuse++;
2391         next = slab_bufctl(slabp)[slabp->free];
2392 #if DEBUG
2393         slab_bufctl(slabp)[slabp->free] = BUFCTL_FREE;
2394         WARN_ON(slabp->nodeid != nodeid);
2395 #endif
2396         slabp->free = next;
2397
2398         return objp;
2399 }
2400
2401 static void slab_put_obj(struct kmem_cache *cachep, struct slab *slabp,
2402                                 void *objp, int nodeid)
2403 {
2404         unsigned int objnr = obj_to_index(cachep, slabp, objp);
2405
2406 #if DEBUG
2407         /* Verify that the slab belongs to the intended node */
2408         WARN_ON(slabp->nodeid != nodeid);
2409
2410         if (slab_bufctl(slabp)[objnr] != BUFCTL_FREE) {
2411                 printk(KERN_ERR "slab: double free detected in cache "
2412                                 "'%s', objp %p\n", cachep->name, objp);
2413                 BUG();
2414         }
2415 #endif
2416         slab_bufctl(slabp)[objnr] = slabp->free;
2417         slabp->free = objnr;
2418         slabp->inuse--;
2419 }
2420
2421 static void set_slab_attr(struct kmem_cache *cachep, struct slab *slabp,
2422                         void *objp)
2423 {
2424         int i;
2425         struct page *page;
2426
2427         /* Nasty!!!!!! I hope this is OK. */
2428         i = 1 << cachep->gfporder;
2429         page = virt_to_page(objp);
2430         do {
2431                 page_set_cache(page, cachep);
2432                 page_set_slab(page, slabp);
2433                 page++;
2434         } while (--i);
2435 }
2436
2437 /*
2438  * Grow (by 1) the number of slabs within a cache.  This is called by
2439  * kmem_cache_alloc() when there are no active objs left in a cache.
2440  */
2441 static int cache_grow(struct kmem_cache *cachep, gfp_t flags, int nodeid)
2442 {
2443         struct slab *slabp;
2444         void *objp;
2445         size_t offset;
2446         gfp_t local_flags;
2447         unsigned long ctor_flags;
2448         struct kmem_list3 *l3;
2449
2450         /*
2451          * Be lazy and only check for valid flags here,  keeping it out of the
2452          * critical path in kmem_cache_alloc().
2453          */
2454         if (flags & ~(SLAB_DMA | SLAB_LEVEL_MASK | SLAB_NO_GROW))
2455                 BUG();
2456         if (flags & SLAB_NO_GROW)
2457                 return 0;
2458
2459         ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2460         local_flags = (flags & SLAB_LEVEL_MASK);
2461         if (!(local_flags & __GFP_WAIT))
2462                 /*
2463                  * Not allowed to sleep.  Need to tell a constructor about
2464                  * this - it might need to know...
2465                  */
2466                 ctor_flags |= SLAB_CTOR_ATOMIC;
2467
2468         /* Take the l3 list lock to change the colour_next on this node */
2469         check_irq_off();
2470         l3 = cachep->nodelists[nodeid];
2471         spin_lock(&l3->list_lock);
2472
2473         /* Get colour for the slab, and cal the next value. */
2474         offset = l3->colour_next;
2475         l3->colour_next++;
2476         if (l3->colour_next >= cachep->colour)
2477                 l3->colour_next = 0;
2478         spin_unlock(&l3->list_lock);
2479
2480         offset *= cachep->colour_off;
2481
2482         if (local_flags & __GFP_WAIT)
2483                 local_irq_enable();
2484
2485         /*
2486          * The test for missing atomic flag is performed here, rather than
2487          * the more obvious place, simply to reduce the critical path length
2488          * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2489          * will eventually be caught here (where it matters).
2490          */
2491         kmem_flagcheck(cachep, flags);
2492
2493         /*
2494          * Get mem for the objs.  Attempt to allocate a physical page from
2495          * 'nodeid'.
2496          */
2497         objp = kmem_getpages(cachep, flags, nodeid);
2498         if (!objp)
2499                 goto failed;
2500
2501         /* Get slab management. */
2502         slabp = alloc_slabmgmt(cachep, objp, offset, local_flags);
2503         if (!slabp)
2504                 goto opps1;
2505
2506         slabp->nodeid = nodeid;
2507         set_slab_attr(cachep, slabp, objp);
2508
2509         cache_init_objs(cachep, slabp, ctor_flags);
2510
2511         if (local_flags & __GFP_WAIT)
2512                 local_irq_disable();
2513         check_irq_off();
2514         spin_lock(&l3->list_lock);
2515
2516         /* Make slab active. */
2517         list_add_tail(&slabp->list, &(l3->slabs_free));
2518         STATS_INC_GROWN(cachep);
2519         l3->free_objects += cachep->num;
2520         spin_unlock(&l3->list_lock);
2521         return 1;
2522 opps1:
2523         kmem_freepages(cachep, objp);
2524 failed:
2525         if (local_flags & __GFP_WAIT)
2526                 local_irq_disable();
2527         return 0;
2528 }
2529
2530 #if DEBUG
2531
2532 /*
2533  * Perform extra freeing checks:
2534  * - detect bad pointers.
2535  * - POISON/RED_ZONE checking
2536  * - destructor calls, for caches with POISON+dtor
2537  */
2538 static void kfree_debugcheck(const void *objp)
2539 {
2540         struct page *page;
2541
2542         if (!virt_addr_valid(objp)) {
2543                 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2544                        (unsigned long)objp);
2545                 BUG();
2546         }
2547         page = virt_to_page(objp);
2548         if (!PageSlab(page)) {
2549                 printk(KERN_ERR "kfree_debugcheck: bad ptr %lxh.\n",
2550                        (unsigned long)objp);
2551                 BUG();
2552         }
2553 }
2554
2555 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2556                                    void *caller)
2557 {
2558         struct page *page;
2559         unsigned int objnr;
2560         struct slab *slabp;
2561
2562         objp -= obj_offset(cachep);
2563         kfree_debugcheck(objp);
2564         page = virt_to_page(objp);
2565
2566         if (page_get_cache(page) != cachep) {
2567                 printk(KERN_ERR "mismatch in kmem_cache_free: expected "
2568                                 "cache %p, got %p\n",
2569                        page_get_cache(page), cachep);
2570                 printk(KERN_ERR "%p is %s.\n", cachep, cachep->name);
2571                 printk(KERN_ERR "%p is %s.\n", page_get_cache(page),
2572                        page_get_cache(page)->name);
2573                 WARN_ON(1);
2574         }
2575         slabp = page_get_slab(page);
2576
2577         if (cachep->flags & SLAB_RED_ZONE) {
2578                 if (*dbg_redzone1(cachep, objp) != RED_ACTIVE ||
2579                                 *dbg_redzone2(cachep, objp) != RED_ACTIVE) {
2580                         slab_error(cachep, "double free, or memory outside"
2581                                                 " object was overwritten");
2582                         printk(KERN_ERR "%p: redzone 1:0x%lx, "
2583                                         "redzone 2:0x%lx.\n",
2584                                objp, *dbg_redzone1(cachep, objp),
2585                                *dbg_redzone2(cachep, objp));
2586                 }
2587                 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2588                 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2589         }
2590         if (cachep->flags & SLAB_STORE_USER)
2591                 *dbg_userword(cachep, objp) = caller;
2592
2593         objnr = obj_to_index(cachep, slabp, objp);
2594
2595         BUG_ON(objnr >= cachep->num);
2596         BUG_ON(objp != index_to_obj(cachep, slabp, objnr));
2597
2598         if (cachep->flags & SLAB_DEBUG_INITIAL) {
2599                 /*
2600                  * Need to call the slab's constructor so the caller can
2601                  * perform a verify of its state (debugging).  Called without
2602                  * the cache-lock held.
2603                  */
2604                 cachep->ctor(objp + obj_offset(cachep),
2605                              cachep, SLAB_CTOR_CONSTRUCTOR | SLAB_CTOR_VERIFY);
2606         }
2607         if (cachep->flags & SLAB_POISON && cachep->dtor) {
2608                 /* we want to cache poison the object,
2609                  * call the destruction callback
2610                  */
2611                 cachep->dtor(objp + obj_offset(cachep), cachep, 0);
2612         }
2613         if (cachep->flags & SLAB_POISON) {
2614 #ifdef CONFIG_DEBUG_PAGEALLOC
2615                 if ((cachep->buffer_size % PAGE_SIZE)==0 && OFF_SLAB(cachep)) {
2616                         store_stackinfo(cachep, objp, (unsigned long)caller);
2617                         kernel_map_pages(virt_to_page(objp),
2618                                          cachep->buffer_size / PAGE_SIZE, 0);
2619                 } else {
2620                         poison_obj(cachep, objp, POISON_FREE);
2621                 }
2622 #else
2623                 poison_obj(cachep, objp, POISON_FREE);
2624 #endif
2625         }
2626         return objp;
2627 }
2628
2629 static void check_slabp(struct kmem_cache *cachep, struct slab *slabp)
2630 {
2631         kmem_bufctl_t i;
2632         int entries = 0;
2633
2634         /* Check slab's freelist to see if this obj is there. */
2635         for (i = slabp->free; i != BUFCTL_END; i = slab_bufctl(slabp)[i]) {
2636                 entries++;
2637                 if (entries > cachep->num || i >= cachep->num)
2638                         goto bad;
2639         }
2640         if (entries != cachep->num - slabp->inuse) {
2641 bad:
2642                 printk(KERN_ERR "slab: Internal list corruption detected in "
2643                                 "cache '%s'(%d), slabp %p(%d). Hexdump:\n",
2644                         cachep->name, cachep->num, slabp, slabp->inuse);
2645                 for (i = 0;
2646                      i < sizeof(*slabp) + cachep->num * sizeof(kmem_bufctl_t);
2647                      i++) {
2648                         if (i % 16 == 0)
2649                                 printk("\n%03x:", i);
2650                         printk(" %02x", ((unsigned char *)slabp)[i]);
2651                 }
2652                 printk("\n");
2653                 BUG();
2654         }
2655 }
2656 #else
2657 #define kfree_debugcheck(x) do { } while(0)
2658 #define cache_free_debugcheck(x,objp,z) (objp)
2659 #define check_slabp(x,y) do { } while(0)
2660 #endif
2661
2662 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags)
2663 {
2664         int batchcount;
2665         struct kmem_list3 *l3;
2666         struct array_cache *ac;
2667
2668         check_irq_off();
2669         ac = cpu_cache_get(cachep);
2670 retry:
2671         batchcount = ac->batchcount;
2672         if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2673                 /*
2674                  * If there was little recent activity on this cache, then
2675                  * perform only a partial refill.  Otherwise we could generate
2676                  * refill bouncing.
2677                  */
2678                 batchcount = BATCHREFILL_LIMIT;
2679         }
2680         l3 = cachep->nodelists[numa_node_id()];
2681
2682         BUG_ON(ac->avail > 0 || !l3);
2683         spin_lock(&l3->list_lock);
2684
2685         if (l3->shared) {
2686                 struct array_cache *shared_array = l3->shared;
2687                 if (shared_array->avail) {
2688                         if (batchcount > shared_array->avail)
2689                                 batchcount = shared_array->avail;
2690                         shared_array->avail -= batchcount;
2691                         ac->avail = batchcount;
2692                         memcpy(ac->entry,
2693                                &(shared_array->entry[shared_array->avail]),
2694                                sizeof(void *) * batchcount);
2695                         shared_array->touched = 1;
2696                         goto alloc_done;
2697                 }
2698         }
2699         while (batchcount > 0) {
2700                 struct list_head *entry;
2701                 struct slab *slabp;
2702                 /* Get slab alloc is to come from. */
2703                 entry = l3->slabs_partial.next;
2704                 if (entry == &l3->slabs_partial) {
2705                         l3->free_touched = 1;
2706                         entry = l3->slabs_free.next;
2707                         if (entry == &l3->slabs_free)
2708                                 goto must_grow;
2709                 }
2710
2711                 slabp = list_entry(entry, struct slab, list);
2712                 check_slabp(cachep, slabp);
2713                 check_spinlock_acquired(cachep);
2714                 while (slabp->inuse < cachep->num && batchcount--) {
2715                         STATS_INC_ALLOCED(cachep);
2716                         STATS_INC_ACTIVE(cachep);
2717                         STATS_SET_HIGH(cachep);
2718
2719                         ac->entry[ac->avail++] = slab_get_obj(cachep, slabp,
2720                                                             numa_node_id());
2721                 }
2722                 check_slabp(cachep, slabp);
2723
2724                 /* move slabp to correct slabp list: */
2725                 list_del(&slabp->list);
2726                 if (slabp->free == BUFCTL_END)
2727                         list_add(&slabp->list, &l3->slabs_full);
2728                 else
2729                         list_add(&slabp->list, &l3->slabs_partial);
2730         }
2731
2732 must_grow:
2733         l3->free_objects -= ac->avail;
2734 alloc_done:
2735         spin_unlock(&l3->list_lock);
2736
2737         if (unlikely(!ac->avail)) {
2738                 int x;
2739                 x = cache_grow(cachep, flags, numa_node_id());
2740
2741                 /* cache_grow can reenable interrupts, then ac could change. */
2742                 ac = cpu_cache_get(cachep);
2743                 if (!x && ac->avail == 0)       /* no objects in sight? abort */
2744                         return NULL;
2745
2746                 if (!ac->avail)         /* objects refilled by interrupt? */
2747                         goto retry;
2748         }
2749         ac->touched = 1;
2750         return ac->entry[--ac->avail];
2751 }
2752
2753 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2754                                                 gfp_t flags)
2755 {
2756         might_sleep_if(flags & __GFP_WAIT);
2757 #if DEBUG
2758         kmem_flagcheck(cachep, flags);
2759 #endif
2760 }
2761
2762 #if DEBUG
2763 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
2764                                 gfp_t flags, void *objp, void *caller)
2765 {
2766         if (!objp)
2767                 return objp;
2768         if (cachep->flags & SLAB_POISON) {
2769 #ifdef CONFIG_DEBUG_PAGEALLOC
2770                 if ((cachep->buffer_size % PAGE_SIZE) == 0 && OFF_SLAB(cachep))
2771                         kernel_map_pages(virt_to_page(objp),
2772                                          cachep->buffer_size / PAGE_SIZE, 1);
2773                 else
2774                         check_poison_obj(cachep, objp);
2775 #else
2776                 check_poison_obj(cachep, objp);
2777 #endif
2778                 poison_obj(cachep, objp, POISON_INUSE);
2779         }
2780         if (cachep->flags & SLAB_STORE_USER)
2781                 *dbg_userword(cachep, objp) = caller;
2782
2783         if (cachep->flags & SLAB_RED_ZONE) {
2784                 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
2785                                 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2786                         slab_error(cachep, "double free, or memory outside"
2787                                                 " object was overwritten");
2788                         printk(KERN_ERR
2789                                 "%p: redzone 1:0x%lx, redzone 2:0x%lx\n",
2790                                 objp, *dbg_redzone1(cachep, objp),
2791                                 *dbg_redzone2(cachep, objp));
2792                 }
2793                 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2794                 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2795         }
2796         objp += obj_offset(cachep);
2797         if (cachep->ctor && cachep->flags & SLAB_POISON) {
2798                 unsigned long ctor_flags = SLAB_CTOR_CONSTRUCTOR;
2799
2800                 if (!(flags & __GFP_WAIT))
2801                         ctor_flags |= SLAB_CTOR_ATOMIC;
2802
2803                 cachep->ctor(objp, cachep, ctor_flags);
2804         }
2805         return objp;
2806 }
2807 #else
2808 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2809 #endif
2810
2811 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
2812 {
2813         void *objp;
2814         struct array_cache *ac;
2815
2816 #ifdef CONFIG_NUMA
2817         if (unlikely(current->mempolicy && !in_interrupt())) {
2818                 int nid = slab_node(current->mempolicy);
2819
2820                 if (nid != numa_node_id())
2821                         return __cache_alloc_node(cachep, flags, nid);
2822         }
2823 #endif
2824
2825         check_irq_off();
2826         ac = cpu_cache_get(cachep);
2827         if (likely(ac->avail)) {
2828                 STATS_INC_ALLOCHIT(cachep);
2829                 ac->touched = 1;
2830                 objp = ac->entry[--ac->avail];
2831         } else {
2832                 STATS_INC_ALLOCMISS(cachep);
2833                 objp = cache_alloc_refill(cachep, flags);
2834         }
2835         return objp;
2836 }
2837
2838 static __always_inline void *__cache_alloc(struct kmem_cache *cachep,
2839                                                 gfp_t flags, void *caller)
2840 {
2841         unsigned long save_flags;
2842         void *objp;
2843
2844         cache_alloc_debugcheck_before(cachep, flags);
2845
2846         local_irq_save(save_flags);
2847         objp = ____cache_alloc(cachep, flags);
2848         local_irq_restore(save_flags);
2849         objp = cache_alloc_debugcheck_after(cachep, flags, objp,
2850                                             caller);
2851         prefetchw(objp);
2852         return objp;
2853 }
2854
2855 #ifdef CONFIG_NUMA
2856 /*
2857  * A interface to enable slab creation on nodeid
2858  */
2859 static void *__cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
2860                                 int nodeid)
2861 {
2862         struct list_head *entry;
2863         struct slab *slabp;
2864         struct kmem_list3 *l3;
2865         void *obj;
2866         int x;
2867
2868         l3 = cachep->nodelists[nodeid];
2869         BUG_ON(!l3);
2870
2871 retry:
2872         check_irq_off();
2873         spin_lock(&l3->list_lock);
2874         entry = l3->slabs_partial.next;
2875         if (entry == &l3->slabs_partial) {
2876                 l3->free_touched = 1;
2877                 entry = l3->slabs_free.next;
2878                 if (entry == &l3->slabs_free)
2879                         goto must_grow;
2880         }
2881
2882         slabp = list_entry(entry, struct slab, list);
2883         check_spinlock_acquired_node(cachep, nodeid);
2884         check_slabp(cachep, slabp);
2885
2886         STATS_INC_NODEALLOCS(cachep);
2887         STATS_INC_ACTIVE(cachep);
2888         STATS_SET_HIGH(cachep);
2889
2890         BUG_ON(slabp->inuse == cachep->num);
2891
2892         obj = slab_get_obj(cachep, slabp, nodeid);
2893         check_slabp(cachep, slabp);
2894         l3->free_objects--;
2895         /* move slabp to correct slabp list: */
2896         list_del(&slabp->list);
2897
2898         if (slabp->free == BUFCTL_END)
2899                 list_add(&slabp->list, &l3->slabs_full);
2900         else
2901                 list_add(&slabp->list, &l3->slabs_partial);
2902
2903         spin_unlock(&l3->list_lock);
2904         goto done;
2905
2906 must_grow:
2907         spin_unlock(&l3->list_lock);
2908         x = cache_grow(cachep, flags, nodeid);
2909
2910         if (!x)
2911                 return NULL;
2912
2913         goto retry;
2914 done:
2915         return obj;
2916 }
2917 #endif
2918
2919 /*
2920  * Caller needs to acquire correct kmem_list's list_lock
2921  */
2922 static void free_block(struct kmem_cache *cachep, void **objpp, int nr_objects,
2923                        int node)
2924 {
2925         int i;
2926         struct kmem_list3 *l3;
2927
2928         for (i = 0; i < nr_objects; i++) {
2929                 void *objp = objpp[i];
2930                 struct slab *slabp;
2931
2932                 slabp = virt_to_slab(objp);
2933                 l3 = cachep->nodelists[node];
2934                 list_del(&slabp->list);
2935                 check_spinlock_acquired_node(cachep, node);
2936                 check_slabp(cachep, slabp);
2937                 slab_put_obj(cachep, slabp, objp, node);
2938                 STATS_DEC_ACTIVE(cachep);
2939                 l3->free_objects++;
2940                 check_slabp(cachep, slabp);
2941
2942                 /* fixup slab chains */
2943                 if (slabp->inuse == 0) {
2944                         if (l3->free_objects > l3->free_limit) {
2945                                 l3->free_objects -= cachep->num;
2946                                 slab_destroy(cachep, slabp);
2947                         } else {
2948                                 list_add(&slabp->list, &l3->slabs_free);
2949                         }
2950                 } else {
2951                         /* Unconditionally move a slab to the end of the
2952                          * partial list on free - maximum time for the
2953                          * other objects to be freed, too.
2954                          */
2955                         list_add_tail(&slabp->list, &l3->slabs_partial);
2956                 }
2957         }
2958 }
2959
2960 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
2961 {
2962         int batchcount;
2963         struct kmem_list3 *l3;
2964         int node = numa_node_id();
2965
2966         batchcount = ac->batchcount;
2967 #if DEBUG
2968         BUG_ON(!batchcount || batchcount > ac->avail);
2969 #endif
2970         check_irq_off();
2971         l3 = cachep->nodelists[node];
2972         spin_lock(&l3->list_lock);
2973         if (l3->shared) {
2974                 struct array_cache *shared_array = l3->shared;
2975                 int max = shared_array->limit - shared_array->avail;
2976                 if (max) {
2977                         if (batchcount > max)
2978                                 batchcount = max;
2979                         memcpy(&(shared_array->entry[shared_array->avail]),
2980                                ac->entry, sizeof(void *) * batchcount);
2981                         shared_array->avail += batchcount;
2982                         goto free_done;
2983                 }
2984         }
2985
2986         free_block(cachep, ac->entry, batchcount, node);
2987 free_done:
2988 #if STATS
2989         {
2990                 int i = 0;
2991                 struct list_head *p;
2992
2993                 p = l3->slabs_free.next;
2994                 while (p != &(l3->slabs_free)) {
2995                         struct slab *slabp;
2996
2997                         slabp = list_entry(p, struct slab, list);
2998                         BUG_ON(slabp->inuse);
2999
3000                         i++;
3001                         p = p->next;
3002                 }
3003                 STATS_SET_FREEABLE(cachep, i);
3004         }
3005 #endif
3006         spin_unlock(&l3->list_lock);
3007         ac->avail -= batchcount;
3008         memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3009 }
3010
3011 /*
3012  * Release an obj back to its cache. If the obj has a constructed state, it must
3013  * be in this state _before_ it is released.  Called with disabled ints.
3014  */
3015 static inline void __cache_free(struct kmem_cache *cachep, void *objp)
3016 {
3017         struct array_cache *ac = cpu_cache_get(cachep);
3018
3019         check_irq_off();
3020         objp = cache_free_debugcheck(cachep, objp, __builtin_return_address(0));
3021
3022         /* Make sure we are not freeing a object from another
3023          * node to the array cache on this cpu.
3024          */
3025 #ifdef CONFIG_NUMA
3026         {
3027                 struct slab *slabp;
3028                 slabp = virt_to_slab(objp);
3029                 if (unlikely(slabp->nodeid != numa_node_id())) {
3030                         struct array_cache *alien = NULL;
3031                         int nodeid = slabp->nodeid;
3032                         struct kmem_list3 *l3;
3033
3034                         l3 = cachep->nodelists[numa_node_id()];
3035                         STATS_INC_NODEFREES(cachep);
3036                         if (l3->alien && l3->alien[nodeid]) {
3037                                 alien = l3->alien[nodeid];
3038                                 spin_lock(&alien->lock);
3039                                 if (unlikely(alien->avail == alien->limit))
3040                                         __drain_alien_cache(cachep,
3041                                                             alien, nodeid);
3042                                 alien->entry[alien->avail++] = objp;
3043                                 spin_unlock(&alien->lock);
3044                         } else {
3045                                 spin_lock(&(cachep->nodelists[nodeid])->
3046                                           list_lock);
3047                                 free_block(cachep, &objp, 1, nodeid);
3048                                 spin_unlock(&(cachep->nodelists[nodeid])->
3049                                             list_lock);
3050                         }
3051                         return;
3052                 }
3053         }
3054 #endif
3055         if (likely(ac->avail < ac->limit)) {
3056                 STATS_INC_FREEHIT(cachep);
3057                 ac->entry[ac->avail++] = objp;
3058                 return;
3059         } else {
3060                 STATS_INC_FREEMISS(cachep);
3061                 cache_flusharray(cachep, ac);
3062                 ac->entry[ac->avail++] = objp;
3063         }
3064 }
3065
3066 /**
3067  * kmem_cache_alloc - Allocate an object
3068  * @cachep: The cache to allocate from.
3069  * @flags: See kmalloc().
3070  *
3071  * Allocate an object from this cache.  The flags are only relevant
3072  * if the cache has no available objects.
3073  */
3074 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3075 {
3076         return __cache_alloc(cachep, flags, __builtin_return_address(0));
3077 }
3078 EXPORT_SYMBOL(kmem_cache_alloc);
3079
3080 /**
3081  * kmem_ptr_validate - check if an untrusted pointer might
3082  *      be a slab entry.
3083  * @cachep: the cache we're checking against
3084  * @ptr: pointer to validate
3085  *
3086  * This verifies that the untrusted pointer looks sane:
3087  * it is _not_ a guarantee that the pointer is actually
3088  * part of the slab cache in question, but it at least
3089  * validates that the pointer can be dereferenced and
3090  * looks half-way sane.
3091  *
3092  * Currently only used for dentry validation.
3093  */
3094 int fastcall kmem_ptr_validate(struct kmem_cache *cachep, void *ptr)
3095 {
3096         unsigned long addr = (unsigned long)ptr;
3097         unsigned long min_addr = PAGE_OFFSET;
3098         unsigned long align_mask = BYTES_PER_WORD - 1;
3099         unsigned long size = cachep->buffer_size;
3100         struct page *page;
3101
3102         if (unlikely(addr < min_addr))
3103                 goto out;
3104         if (unlikely(addr > (unsigned long)high_memory - size))
3105                 goto out;
3106         if (unlikely(addr & align_mask))
3107                 goto out;
3108         if (unlikely(!kern_addr_valid(addr)))
3109                 goto out;
3110         if (unlikely(!kern_addr_valid(addr + size - 1)))
3111                 goto out;
3112         page = virt_to_page(ptr);
3113         if (unlikely(!PageSlab(page)))
3114                 goto out;
3115         if (unlikely(page_get_cache(page) != cachep))
3116                 goto out;
3117         return 1;
3118 out:
3119         return 0;
3120 }
3121
3122 #ifdef CONFIG_NUMA
3123 /**
3124  * kmem_cache_alloc_node - Allocate an object on the specified node
3125  * @cachep: The cache to allocate from.
3126  * @flags: See kmalloc().
3127  * @nodeid: node number of the target node.
3128  *
3129  * Identical to kmem_cache_alloc, except that this function is slow
3130  * and can sleep. And it will allocate memory on the given node, which
3131  * can improve the performance for cpu bound structures.
3132  * New and improved: it will now make sure that the object gets
3133  * put on the correct node list so that there is no false sharing.
3134  */
3135 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3136 {
3137         unsigned long save_flags;
3138         void *ptr;
3139
3140         cache_alloc_debugcheck_before(cachep, flags);
3141         local_irq_save(save_flags);
3142
3143         if (nodeid == -1 || nodeid == numa_node_id() ||
3144                         !cachep->nodelists[nodeid])
3145                 ptr = ____cache_alloc(cachep, flags);
3146         else
3147                 ptr = __cache_alloc_node(cachep, flags, nodeid);
3148         local_irq_restore(save_flags);
3149
3150         ptr = cache_alloc_debugcheck_after(cachep, flags, ptr,
3151                                            __builtin_return_address(0));
3152
3153         return ptr;
3154 }
3155 EXPORT_SYMBOL(kmem_cache_alloc_node);
3156
3157 void *kmalloc_node(size_t size, gfp_t flags, int node)
3158 {
3159         struct kmem_cache *cachep;
3160
3161         cachep = kmem_find_general_cachep(size, flags);
3162         if (unlikely(cachep == NULL))
3163                 return NULL;
3164         return kmem_cache_alloc_node(cachep, flags, node);
3165 }
3166 EXPORT_SYMBOL(kmalloc_node);
3167 #endif
3168
3169 /**
3170  * kmalloc - allocate memory
3171  * @size: how many bytes of memory are required.
3172  * @flags: the type of memory to allocate.
3173  *
3174  * kmalloc is the normal method of allocating memory
3175  * in the kernel.
3176  *
3177  * The @flags argument may be one of:
3178  *
3179  * %GFP_USER - Allocate memory on behalf of user.  May sleep.
3180  *
3181  * %GFP_KERNEL - Allocate normal kernel ram.  May sleep.
3182  *
3183  * %GFP_ATOMIC - Allocation will not sleep.  Use inside interrupt handlers.
3184  *
3185  * Additionally, the %GFP_DMA flag may be set to indicate the memory
3186  * must be suitable for DMA.  This can mean different things on different
3187  * platforms.  For example, on i386, it means that the memory must come
3188  * from the first 16MB.
3189  */
3190 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3191                                           void *caller)
3192 {
3193         struct kmem_cache *cachep;
3194
3195         /* If you want to save a few bytes .text space: replace
3196          * __ with kmem_.
3197          * Then kmalloc uses the uninlined functions instead of the inline
3198          * functions.
3199          */
3200         cachep = __find_general_cachep(size, flags);
3201         if (unlikely(cachep == NULL))
3202                 return NULL;
3203         return __cache_alloc(cachep, flags, caller);
3204 }
3205
3206 #ifndef CONFIG_DEBUG_SLAB
3207
3208 void *__kmalloc(size_t size, gfp_t flags)
3209 {
3210         return __do_kmalloc(size, flags, NULL);
3211 }
3212 EXPORT_SYMBOL(__kmalloc);
3213
3214 #else
3215
3216 void *__kmalloc_track_caller(size_t size, gfp_t flags, void *caller)
3217 {
3218         return __do_kmalloc(size, flags, caller);
3219 }
3220 EXPORT_SYMBOL(__kmalloc_track_caller);
3221
3222 #endif
3223
3224 #ifdef CONFIG_SMP
3225 /**
3226  * __alloc_percpu - allocate one copy of the object for every present
3227  * cpu in the system, zeroing them.
3228  * Objects should be dereferenced using the per_cpu_ptr macro only.
3229  *
3230  * @size: how many bytes of memory are required.
3231  */
3232 void *__alloc_percpu(size_t size)
3233 {
3234         int i;
3235         struct percpu_data *pdata = kmalloc(sizeof(*pdata), GFP_KERNEL);
3236
3237         if (!pdata)
3238                 return NULL;
3239
3240         /*
3241          * Cannot use for_each_online_cpu since a cpu may come online
3242          * and we have no way of figuring out how to fix the array
3243          * that we have allocated then....
3244          */
3245         for_each_cpu(i) {
3246                 int node = cpu_to_node(i);
3247
3248                 if (node_online(node))
3249                         pdata->ptrs[i] = kmalloc_node(size, GFP_KERNEL, node);
3250                 else
3251                         pdata->ptrs[i] = kmalloc(size, GFP_KERNEL);
3252
3253                 if (!pdata->ptrs[i])
3254                         goto unwind_oom;
3255                 memset(pdata->ptrs[i], 0, size);
3256         }
3257
3258         /* Catch derefs w/o wrappers */
3259         return (void *)(~(unsigned long)pdata);
3260
3261 unwind_oom:
3262         while (--i >= 0) {
3263                 if (!cpu_possible(i))
3264                         continue;
3265                 kfree(pdata->ptrs[i]);
3266         }
3267         kfree(pdata);
3268         return NULL;
3269 }
3270 EXPORT_SYMBOL(__alloc_percpu);
3271 #endif
3272
3273 /**
3274  * kmem_cache_free - Deallocate an object
3275  * @cachep: The cache the allocation was from.
3276  * @objp: The previously allocated object.
3277  *
3278  * Free an object which was previously allocated from this
3279  * cache.
3280  */
3281 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3282 {
3283         unsigned long flags;
3284
3285         local_irq_save(flags);
3286         __cache_free(cachep, objp);
3287         local_irq_restore(flags);
3288 }
3289 EXPORT_SYMBOL(kmem_cache_free);
3290
3291 /**
3292  * kfree - free previously allocated memory
3293  * @objp: pointer returned by kmalloc.
3294  *
3295  * If @objp is NULL, no operation is performed.
3296  *
3297  * Don't free memory not originally allocated by kmalloc()
3298  * or you will run into trouble.
3299  */
3300 void kfree(const void *objp)
3301 {
3302         struct kmem_cache *c;
3303         unsigned long flags;
3304
3305         if (unlikely(!objp))
3306                 return;
3307         local_irq_save(flags);
3308         kfree_debugcheck(objp);
3309         c = virt_to_cache(objp);
3310         mutex_debug_check_no_locks_freed(objp, obj_size(c));
3311         __cache_free(c, (void *)objp);
3312         local_irq_restore(flags);
3313 }
3314 EXPORT_SYMBOL(kfree);
3315
3316 #ifdef CONFIG_SMP
3317 /**
3318  * free_percpu - free previously allocated percpu memory
3319  * @objp: pointer returned by alloc_percpu.
3320  *
3321  * Don't free memory not originally allocated by alloc_percpu()
3322  * The complemented objp is to check for that.
3323  */
3324 void free_percpu(const void *objp)
3325 {
3326         int i;
3327         struct percpu_data *p = (struct percpu_data *)(~(unsigned long)objp);
3328
3329         /*
3330          * We allocate for all cpus so we cannot use for online cpu here.
3331          */
3332         for_each_cpu(i)
3333             kfree(p->ptrs[i]);
3334         kfree(p);
3335 }
3336 EXPORT_SYMBOL(free_percpu);
3337 #endif
3338
3339 unsigned int kmem_cache_size(struct kmem_cache *cachep)
3340 {
3341         return obj_size(cachep);
3342 }
3343 EXPORT_SYMBOL(kmem_cache_size);
3344
3345 const char *kmem_cache_name(struct kmem_cache *cachep)
3346 {
3347         return cachep->name;
3348 }
3349 EXPORT_SYMBOL_GPL(kmem_cache_name);
3350
3351 /*
3352  * This initializes kmem_list3 for all nodes.
3353  */
3354 static int alloc_kmemlist(struct kmem_cache *cachep)
3355 {
3356         int node;
3357         struct kmem_list3 *l3;
3358         int err = 0;
3359
3360         for_each_online_node(node) {
3361                 struct array_cache *nc = NULL, *new;
3362                 struct array_cache **new_alien = NULL;
3363 #ifdef CONFIG_NUMA
3364                 new_alien = alloc_alien_cache(node, cachep->limit);
3365                 if (!new_alien)
3366                         goto fail;
3367 #endif
3368                 new = alloc_arraycache(node, cachep->shared*cachep->batchcount,
3369                                         0xbaadf00d);
3370                 if (!new)
3371                         goto fail;
3372                 l3 = cachep->nodelists[node];
3373                 if (l3) {
3374                         spin_lock_irq(&l3->list_lock);
3375
3376                         nc = cachep->nodelists[node]->shared;
3377                         if (nc)
3378                                 free_block(cachep, nc->entry, nc->avail, node);
3379
3380                         l3->shared = new;
3381                         if (!cachep->nodelists[node]->alien) {
3382                                 l3->alien = new_alien;
3383                                 new_alien = NULL;
3384                         }
3385                         l3->free_limit = (1 + nr_cpus_node(node)) *
3386                                         cachep->batchcount + cachep->num;
3387                         spin_unlock_irq(&l3->list_lock);
3388                         kfree(nc);
3389                         free_alien_cache(new_alien);
3390                         continue;
3391                 }
3392                 l3 = kmalloc_node(sizeof(struct kmem_list3), GFP_KERNEL, node);
3393                 if (!l3)
3394                         goto fail;
3395
3396                 kmem_list3_init(l3);
3397                 l3->next_reap = jiffies + REAPTIMEOUT_LIST3 +
3398                                 ((unsigned long)cachep) % REAPTIMEOUT_LIST3;
3399                 l3->shared = new;
3400                 l3->alien = new_alien;
3401                 l3->free_limit = (1 + nr_cpus_node(node)) *
3402                                         cachep->batchcount + cachep->num;
3403                 cachep->nodelists[node] = l3;
3404         }
3405         return err;
3406 fail:
3407         err = -ENOMEM;
3408         return err;
3409 }
3410
3411 struct ccupdate_struct {
3412         struct kmem_cache *cachep;
3413         struct array_cache *new[NR_CPUS];
3414 };
3415
3416 static void do_ccupdate_local(void *info)
3417 {
3418         struct ccupdate_struct *new = info;
3419         struct array_cache *old;
3420
3421         check_irq_off();
3422         old = cpu_cache_get(new->cachep);
3423
3424         new->cachep->array[smp_processor_id()] = new->new[smp_processor_id()];
3425         new->new[smp_processor_id()] = old;
3426 }
3427
3428 /* Always called with the cache_chain_mutex held */
3429 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3430                                 int batchcount, int shared)
3431 {
3432         struct ccupdate_struct new;
3433         int i, err;
3434
3435         memset(&new.new, 0, sizeof(new.new));
3436         for_each_online_cpu(i) {
3437                 new.new[i] = alloc_arraycache(cpu_to_node(i), limit,
3438                                                 batchcount);
3439                 if (!new.new[i]) {
3440                         for (i--; i >= 0; i--)
3441                                 kfree(new.new[i]);
3442                         return -ENOMEM;
3443                 }
3444         }
3445         new.cachep = cachep;
3446
3447         smp_call_function_all_cpus(do_ccupdate_local, (void *)&new);
3448
3449         check_irq_on();
3450         cachep->batchcount = batchcount;
3451         cachep->limit = limit;
3452         cachep->shared = shared;
3453
3454         for_each_online_cpu(i) {
3455                 struct array_cache *ccold = new.new[i];
3456                 if (!ccold)
3457                         continue;
3458                 spin_lock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3459                 free_block(cachep, ccold->entry, ccold->avail, cpu_to_node(i));
3460                 spin_unlock_irq(&cachep->nodelists[cpu_to_node(i)]->list_lock);
3461                 kfree(ccold);
3462         }
3463
3464         err = alloc_kmemlist(cachep);
3465         if (err) {
3466                 printk(KERN_ERR "alloc_kmemlist failed for %s, error %d.\n",
3467                        cachep->name, -err);
3468                 BUG();
3469         }
3470         return 0;
3471 }
3472
3473 /* Called with cache_chain_mutex held always */
3474 static void enable_cpucache(struct kmem_cache *cachep)
3475 {
3476         int err;
3477         int limit, shared;
3478
3479         /*
3480          * The head array serves three purposes:
3481          * - create a LIFO ordering, i.e. return objects that are cache-warm
3482          * - reduce the number of spinlock operations.
3483          * - reduce the number of linked list operations on the slab and
3484          *   bufctl chains: array operations are cheaper.
3485          * The numbers are guessed, we should auto-tune as described by
3486          * Bonwick.
3487          */
3488         if (cachep->buffer_size > 131072)
3489                 limit = 1;
3490         else if (cachep->buffer_size > PAGE_SIZE)
3491                 limit = 8;
3492         else if (cachep->buffer_size > 1024)
3493                 limit = 24;
3494         else if (cachep->buffer_size > 256)
3495                 limit = 54;
3496         else
3497                 limit = 120;
3498
3499         /*
3500          * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3501          * allocation behaviour: Most allocs on one cpu, most free operations
3502          * on another cpu. For these cases, an efficient object passing between
3503          * cpus is necessary. This is provided by a shared array. The array
3504          * replaces Bonwick's magazine layer.
3505          * On uniprocessor, it's functionally equivalent (but less efficient)
3506          * to a larger limit. Thus disabled by default.
3507          */
3508         shared = 0;
3509 #ifdef CONFIG_SMP
3510         if (cachep->buffer_size <= PAGE_SIZE)
3511                 shared = 8;
3512 #endif
3513
3514 #if DEBUG
3515         /*
3516          * With debugging enabled, large batchcount lead to excessively long
3517          * periods with disabled local interrupts. Limit the batchcount
3518          */
3519         if (limit > 32)
3520                 limit = 32;
3521 #endif
3522         err = do_tune_cpucache(cachep, limit, (limit + 1) / 2, shared);
3523         if (err)
3524                 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3525                        cachep->name, -err);
3526 }
3527
3528 static void drain_array_locked(struct kmem_cache *cachep,
3529                                 struct array_cache *ac, int force, int node)
3530 {
3531         int tofree;
3532
3533         check_spinlock_acquired_node(cachep, node);
3534         if (ac->touched && !force) {
3535                 ac->touched = 0;
3536         } else if (ac->avail) {
3537                 tofree = force ? ac->avail : (ac->limit + 4) / 5;
3538                 if (tofree > ac->avail)
3539                         tofree = (ac->avail + 1) / 2;
3540                 free_block(cachep, ac->entry, tofree, node);
3541                 ac->avail -= tofree;
3542                 memmove(ac->entry, &(ac->entry[tofree]),
3543                         sizeof(void *) * ac->avail);
3544         }
3545 }
3546
3547 /**
3548  * cache_reap - Reclaim memory from caches.
3549  * @unused: unused parameter
3550  *
3551  * Called from workqueue/eventd every few seconds.
3552  * Purpose:
3553  * - clear the per-cpu caches for this CPU.
3554  * - return freeable pages to the main free memory pool.
3555  *
3556  * If we cannot acquire the cache chain mutex then just give up - we'll try
3557  * again on the next iteration.
3558  */
3559 static void cache_reap(void *unused)
3560 {
3561         struct list_head *walk;
3562         struct kmem_list3 *l3;
3563
3564         if (!mutex_trylock(&cache_chain_mutex)) {
3565                 /* Give up. Setup the next iteration. */
3566                 schedule_delayed_work(&__get_cpu_var(reap_work),
3567                                       REAPTIMEOUT_CPUC);
3568                 return;
3569         }
3570
3571         list_for_each(walk, &cache_chain) {
3572                 struct kmem_cache *searchp;
3573                 struct list_head *p;
3574                 int tofree;
3575                 struct slab *slabp;
3576
3577                 searchp = list_entry(walk, struct kmem_cache, next);
3578
3579                 if (searchp->flags & SLAB_NO_REAP)
3580                         goto next;
3581
3582                 check_irq_on();
3583
3584                 l3 = searchp->nodelists[numa_node_id()];
3585                 reap_alien(searchp, l3);
3586                 spin_lock_irq(&l3->list_lock);
3587
3588                 drain_array_locked(searchp, cpu_cache_get(searchp), 0,
3589                                    numa_node_id());
3590
3591                 if (time_after(l3->next_reap, jiffies))
3592                         goto next_unlock;
3593
3594                 l3->next_reap = jiffies + REAPTIMEOUT_LIST3;
3595
3596                 if (l3->shared)
3597                         drain_array_locked(searchp, l3->shared, 0,
3598                                            numa_node_id());
3599
3600                 if (l3->free_touched) {
3601                         l3->free_touched = 0;
3602                         goto next_unlock;
3603                 }
3604
3605                 tofree = (l3->free_limit + 5 * searchp->num - 1) /
3606                                 (5 * searchp->num);
3607                 do {
3608                         p = l3->slabs_free.next;
3609                         if (p == &(l3->slabs_free))
3610                                 break;
3611
3612                         slabp = list_entry(p, struct slab, list);
3613                         BUG_ON(slabp->inuse);
3614                         list_del(&slabp->list);
3615                         STATS_INC_REAPED(searchp);
3616
3617                         /*
3618                          * Safe to drop the lock. The slab is no longer linked
3619                          * to the cache. searchp cannot disappear, we hold
3620                          * cache_chain_lock
3621                          */
3622                         l3->free_objects -= searchp->num;
3623                         spin_unlock_irq(&l3->list_lock);
3624                         slab_destroy(searchp, slabp);
3625                         spin_lock_irq(&l3->list_lock);
3626                 } while (--tofree > 0);
3627 next_unlock:
3628                 spin_unlock_irq(&l3->list_lock);
3629 next:
3630                 cond_resched();
3631         }
3632         check_irq_on();
3633         mutex_unlock(&cache_chain_mutex);
3634         next_reap_node();
3635         /* Set up the next iteration */
3636         schedule_delayed_work(&__get_cpu_var(reap_work), REAPTIMEOUT_CPUC);
3637 }
3638
3639 #ifdef CONFIG_PROC_FS
3640
3641 static void print_slabinfo_header(struct seq_file *m)
3642 {
3643         /*
3644          * Output format version, so at least we can change it
3645          * without _too_ many complaints.
3646          */
3647 #if STATS
3648         seq_puts(m, "slabinfo - version: 2.1 (statistics)\n");
3649 #else
3650         seq_puts(m, "slabinfo - version: 2.1\n");
3651 #endif
3652         seq_puts(m, "# name            <active_objs> <num_objs> <objsize> "
3653                  "<objperslab> <pagesperslab>");
3654         seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
3655         seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
3656 #if STATS
3657         seq_puts(m, " : globalstat <listallocs> <maxobjs> <grown> <reaped> "
3658                  "<error> <maxfreeable> <nodeallocs> <remotefrees>");
3659         seq_puts(m, " : cpustat <allochit> <allocmiss> <freehit> <freemiss>");
3660 #endif
3661         seq_putc(m, '\n');
3662 }
3663
3664 static void *s_start(struct seq_file *m, loff_t *pos)
3665 {
3666         loff_t n = *pos;
3667         struct list_head *p;
3668
3669         mutex_lock(&cache_chain_mutex);
3670         if (!n)
3671                 print_slabinfo_header(m);
3672         p = cache_chain.next;
3673         while (n--) {
3674                 p = p->next;
3675                 if (p == &cache_chain)
3676                         return NULL;
3677         }
3678         return list_entry(p, struct kmem_cache, next);
3679 }
3680
3681 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
3682 {
3683         struct kmem_cache *cachep = p;
3684         ++*pos;
3685         return cachep->next.next == &cache_chain ?
3686                 NULL : list_entry(cachep->next.next, struct kmem_cache, next);
3687 }
3688
3689 static void s_stop(struct seq_file *m, void *p)
3690 {
3691         mutex_unlock(&cache_chain_mutex);
3692 }
3693
3694 static int s_show(struct seq_file *m, void *p)
3695 {
3696         struct kmem_cache *cachep = p;
3697         struct list_head *q;
3698         struct slab *slabp;
3699         unsigned long active_objs;
3700         unsigned long num_objs;
3701         unsigned long active_slabs = 0;
3702         unsigned long num_slabs, free_objects = 0, shared_avail = 0;
3703         const char *name;
3704         char *error = NULL;
3705         int node;
3706         struct kmem_list3 *l3;
3707
3708         active_objs = 0;
3709         num_slabs = 0;
3710         for_each_online_node(node) {
3711                 l3 = cachep->nodelists[node];
3712                 if (!l3)
3713                         continue;
3714
3715                 check_irq_on();
3716                 spin_lock_irq(&l3->list_lock);
3717
3718                 list_for_each(q, &l3->slabs_full) {
3719                         slabp = list_entry(q, struct slab, list);
3720                         if (slabp->inuse != cachep->num && !error)
3721                                 error = "slabs_full accounting error";
3722                         active_objs += cachep->num;
3723                         active_slabs++;
3724                 }
3725                 list_for_each(q, &l3->slabs_partial) {
3726                         slabp = list_entry(q, struct slab, list);
3727                         if (slabp->inuse == cachep->num && !error)
3728                                 error = "slabs_partial inuse accounting error";
3729                         if (!slabp->inuse && !error)
3730                                 error = "slabs_partial/inuse accounting error";
3731                         active_objs += slabp->inuse;
3732                         active_slabs++;
3733                 }
3734                 list_for_each(q, &l3->slabs_free) {
3735                         slabp = list_entry(q, struct slab, list);
3736                         if (slabp->inuse && !error)
3737                                 error = "slabs_free/inuse accounting error";
3738                         num_slabs++;
3739                 }
3740                 free_objects += l3->free_objects;
3741                 if (l3->shared)
3742                         shared_avail += l3->shared->avail;
3743
3744                 spin_unlock_irq(&l3->list_lock);
3745         }
3746         num_slabs += active_slabs;
3747         num_objs = num_slabs * cachep->num;
3748         if (num_objs - active_objs != free_objects && !error)
3749                 error = "free_objects accounting error";
3750
3751         name = cachep->name;
3752         if (error)
3753                 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3754
3755         seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d",
3756                    name, active_objs, num_objs, cachep->buffer_size,
3757                    cachep->num, (1 << cachep->gfporder));
3758         seq_printf(m, " : tunables %4u %4u %4u",
3759                    cachep->limit, cachep->batchcount, cachep->shared);
3760         seq_printf(m, " : slabdata %6lu %6lu %6lu",
3761                    active_slabs, num_slabs, shared_avail);
3762 #if STATS
3763         {                       /* list3 stats */
3764                 unsigned long high = cachep->high_mark;
3765                 unsigned long allocs = cachep->num_allocations;
3766                 unsigned long grown = cachep->grown;
3767                 unsigned long reaped = cachep->reaped;
3768                 unsigned long errors = cachep->errors;
3769                 unsigned long max_freeable = cachep->max_freeable;
3770                 unsigned long node_allocs = cachep->node_allocs;
3771                 unsigned long node_frees = cachep->node_frees;
3772
3773                 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu \
3774                                 %4lu %4lu %4lu %4lu", allocs, high, grown,
3775                                 reaped, errors, max_freeable, node_allocs,
3776                                 node_frees);
3777         }
3778         /* cpu stats */
3779         {
3780                 unsigned long allochit = atomic_read(&cachep->allochit);
3781                 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
3782                 unsigned long freehit = atomic_read(&cachep->freehit);
3783                 unsigned long freemiss = atomic_read(&cachep->freemiss);
3784
3785                 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
3786                            allochit, allocmiss, freehit, freemiss);
3787         }
3788 #endif
3789         seq_putc(m, '\n');
3790         return 0;
3791 }
3792
3793 /*
3794  * slabinfo_op - iterator that generates /proc/slabinfo
3795  *
3796  * Output layout:
3797  * cache-name
3798  * num-active-objs
3799  * total-objs
3800  * object size
3801  * num-active-slabs
3802  * total-slabs
3803  * num-pages-per-slab
3804  * + further values on SMP and with statistics enabled
3805  */
3806
3807 struct seq_operations slabinfo_op = {
3808         .start = s_start,
3809         .next = s_next,
3810         .stop = s_stop,
3811         .show = s_show,
3812 };
3813
3814 #define MAX_SLABINFO_WRITE 128
3815 /**
3816  * slabinfo_write - Tuning for the slab allocator
3817  * @file: unused
3818  * @buffer: user buffer
3819  * @count: data length
3820  * @ppos: unused
3821  */
3822 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
3823                        size_t count, loff_t *ppos)
3824 {
3825         char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
3826         int limit, batchcount, shared, res;
3827         struct list_head *p;
3828
3829         if (count > MAX_SLABINFO_WRITE)
3830                 return -EINVAL;
3831         if (copy_from_user(&kbuf, buffer, count))
3832                 return -EFAULT;
3833         kbuf[MAX_SLABINFO_WRITE] = '\0';
3834
3835         tmp = strchr(kbuf, ' ');
3836         if (!tmp)
3837                 return -EINVAL;
3838         *tmp = '\0';
3839         tmp++;
3840         if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
3841                 return -EINVAL;
3842
3843         /* Find the cache in the chain of caches. */
3844         mutex_lock(&cache_chain_mutex);
3845         res = -EINVAL;
3846         list_for_each(p, &cache_chain) {
3847                 struct kmem_cache *cachep;
3848
3849                 cachep = list_entry(p, struct kmem_cache, next);
3850                 if (!strcmp(cachep->name, kbuf)) {
3851                         if (limit < 1 || batchcount < 1 ||
3852                                         batchcount > limit || shared < 0) {
3853                                 res = 0;
3854                         } else {
3855                                 res = do_tune_cpucache(cachep, limit,
3856                                                        batchcount, shared);
3857                         }
3858                         break;
3859                 }
3860         }
3861         mutex_unlock(&cache_chain_mutex);
3862         if (res >= 0)
3863                 res = count;
3864         return res;
3865 }
3866 #endif
3867
3868 /**
3869  * ksize - get the actual amount of memory allocated for a given object
3870  * @objp: Pointer to the object
3871  *
3872  * kmalloc may internally round up allocations and return more memory
3873  * than requested. ksize() can be used to determine the actual amount of
3874  * memory allocated. The caller may use this additional memory, even though
3875  * a smaller amount of memory was initially specified with the kmalloc call.
3876  * The caller must guarantee that objp points to a valid object previously
3877  * allocated with either kmalloc() or kmem_cache_alloc(). The object
3878  * must not be freed during the duration of the call.
3879  */
3880 unsigned int ksize(const void *objp)
3881 {
3882         if (unlikely(objp == NULL))
3883                 return 0;
3884
3885         return obj_size(virt_to_cache(objp));
3886 }