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