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