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