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