[S390] cio: Remember to initialize recovery_lock.
[linux-2.6/verdex.git] / mm / slub.c
blob4b3895cb90ee15b23ff7588e4b3079e405d8d8e1
1 /*
2 * SLUB: A slab allocator that limits cache line use instead of queuing
3 * objects in per cpu and per node lists.
5 * The allocator synchronizes using per slab locks and only
6 * uses a centralized lock to manage a pool of partial slabs.
8 * (C) 2007 SGI, Christoph Lameter <clameter@sgi.com>
9 */
11 #include <linux/mm.h>
12 #include <linux/module.h>
13 #include <linux/bit_spinlock.h>
14 #include <linux/interrupt.h>
15 #include <linux/bitops.h>
16 #include <linux/slab.h>
17 #include <linux/seq_file.h>
18 #include <linux/cpu.h>
19 #include <linux/cpuset.h>
20 #include <linux/mempolicy.h>
21 #include <linux/ctype.h>
22 #include <linux/kallsyms.h>
23 #include <linux/memory.h>
26 * Lock order:
27 * 1. slab_lock(page)
28 * 2. slab->list_lock
30 * The slab_lock protects operations on the object of a particular
31 * slab and its metadata in the page struct. If the slab lock
32 * has been taken then no allocations nor frees can be performed
33 * on the objects in the slab nor can the slab be added or removed
34 * from the partial or full lists since this would mean modifying
35 * the page_struct of the slab.
37 * The list_lock protects the partial and full list on each node and
38 * the partial slab counter. If taken then no new slabs may be added or
39 * removed from the lists nor make the number of partial slabs be modified.
40 * (Note that the total number of slabs is an atomic value that may be
41 * modified without taking the list lock).
43 * The list_lock is a centralized lock and thus we avoid taking it as
44 * much as possible. As long as SLUB does not have to handle partial
45 * slabs, operations can continue without any centralized lock. F.e.
46 * allocating a long series of objects that fill up slabs does not require
47 * the list lock.
49 * The lock order is sometimes inverted when we are trying to get a slab
50 * off a list. We take the list_lock and then look for a page on the list
51 * to use. While we do that objects in the slabs may be freed. We can
52 * only operate on the slab if we have also taken the slab_lock. So we use
53 * a slab_trylock() on the slab. If trylock was successful then no frees
54 * can occur anymore and we can use the slab for allocations etc. If the
55 * slab_trylock() does not succeed then frees are in progress in the slab and
56 * we must stay away from it for a while since we may cause a bouncing
57 * cacheline if we try to acquire the lock. So go onto the next slab.
58 * If all pages are busy then we may allocate a new slab instead of reusing
59 * a partial slab. A new slab has noone operating on it and thus there is
60 * no danger of cacheline contention.
62 * Interrupts are disabled during allocation and deallocation in order to
63 * make the slab allocator safe to use in the context of an irq. In addition
64 * interrupts are disabled to ensure that the processor does not change
65 * while handling per_cpu slabs, due to kernel preemption.
67 * SLUB assigns one slab for allocation to each processor.
68 * Allocations only occur from these slabs called cpu slabs.
70 * Slabs with free elements are kept on a partial list and during regular
71 * operations no list for full slabs is used. If an object in a full slab is
72 * freed then the slab will show up again on the partial lists.
73 * We track full slabs for debugging purposes though because otherwise we
74 * cannot scan all objects.
76 * Slabs are freed when they become empty. Teardown and setup is
77 * minimal so we rely on the page allocators per cpu caches for
78 * fast frees and allocs.
80 * Overloading of page flags that are otherwise used for LRU management.
82 * PageActive The slab is frozen and exempt from list processing.
83 * This means that the slab is dedicated to a purpose
84 * such as satisfying allocations for a specific
85 * processor. Objects may be freed in the slab while
86 * it is frozen but slab_free will then skip the usual
87 * list operations. It is up to the processor holding
88 * the slab to integrate the slab into the slab lists
89 * when the slab is no longer needed.
91 * One use of this flag is to mark slabs that are
92 * used for allocations. Then such a slab becomes a cpu
93 * slab. The cpu slab may be equipped with an additional
94 * freelist that allows lockless access to
95 * free objects in addition to the regular freelist
96 * that requires the slab lock.
98 * PageError Slab requires special handling due to debug
99 * options set. This moves slab handling out of
100 * the fast path and disables lockless freelists.
103 #define FROZEN (1 << PG_active)
105 #ifdef CONFIG_SLUB_DEBUG
106 #define SLABDEBUG (1 << PG_error)
107 #else
108 #define SLABDEBUG 0
109 #endif
111 static inline int SlabFrozen(struct page *page)
113 return page->flags & FROZEN;
116 static inline void SetSlabFrozen(struct page *page)
118 page->flags |= FROZEN;
121 static inline void ClearSlabFrozen(struct page *page)
123 page->flags &= ~FROZEN;
126 static inline int SlabDebug(struct page *page)
128 return page->flags & SLABDEBUG;
131 static inline void SetSlabDebug(struct page *page)
133 page->flags |= SLABDEBUG;
136 static inline void ClearSlabDebug(struct page *page)
138 page->flags &= ~SLABDEBUG;
142 * Issues still to be resolved:
144 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
146 * - Variable sizing of the per node arrays
149 /* Enable to test recovery from slab corruption on boot */
150 #undef SLUB_RESILIENCY_TEST
153 * Currently fastpath is not supported if preemption is enabled.
155 #if defined(CONFIG_FAST_CMPXCHG_LOCAL) && !defined(CONFIG_PREEMPT)
156 #define SLUB_FASTPATH
157 #endif
159 #if PAGE_SHIFT <= 12
162 * Small page size. Make sure that we do not fragment memory
164 #define DEFAULT_MAX_ORDER 1
165 #define DEFAULT_MIN_OBJECTS 4
167 #else
170 * Large page machines are customarily able to handle larger
171 * page orders.
173 #define DEFAULT_MAX_ORDER 2
174 #define DEFAULT_MIN_OBJECTS 8
176 #endif
179 * Mininum number of partial slabs. These will be left on the partial
180 * lists even if they are empty. kmem_cache_shrink may reclaim them.
182 #define MIN_PARTIAL 5
185 * Maximum number of desirable partial slabs.
186 * The existence of more partial slabs makes kmem_cache_shrink
187 * sort the partial list by the number of objects in the.
189 #define MAX_PARTIAL 10
191 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
192 SLAB_POISON | SLAB_STORE_USER)
195 * Set of flags that will prevent slab merging
197 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
198 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
200 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
201 SLAB_CACHE_DMA)
203 #ifndef ARCH_KMALLOC_MINALIGN
204 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
205 #endif
207 #ifndef ARCH_SLAB_MINALIGN
208 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
209 #endif
211 /* Internal SLUB flags */
212 #define __OBJECT_POISON 0x80000000 /* Poison object */
213 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
214 #define __KMALLOC_CACHE 0x20000000 /* objects freed using kfree */
215 #define __PAGE_ALLOC_FALLBACK 0x10000000 /* Allow fallback to page alloc */
217 /* Not all arches define cache_line_size */
218 #ifndef cache_line_size
219 #define cache_line_size() L1_CACHE_BYTES
220 #endif
222 static int kmem_size = sizeof(struct kmem_cache);
224 #ifdef CONFIG_SMP
225 static struct notifier_block slab_notifier;
226 #endif
228 static enum {
229 DOWN, /* No slab functionality available */
230 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
231 UP, /* Everything works but does not show up in sysfs */
232 SYSFS /* Sysfs up */
233 } slab_state = DOWN;
235 /* A list of all slab caches on the system */
236 static DECLARE_RWSEM(slub_lock);
237 static LIST_HEAD(slab_caches);
240 * Tracking user of a slab.
242 struct track {
243 void *addr; /* Called from address */
244 int cpu; /* Was running on cpu */
245 int pid; /* Pid context */
246 unsigned long when; /* When did the operation occur */
249 enum track_item { TRACK_ALLOC, TRACK_FREE };
251 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
252 static int sysfs_slab_add(struct kmem_cache *);
253 static int sysfs_slab_alias(struct kmem_cache *, const char *);
254 static void sysfs_slab_remove(struct kmem_cache *);
256 #else
257 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
258 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
259 { return 0; }
260 static inline void sysfs_slab_remove(struct kmem_cache *s)
262 kfree(s);
265 #endif
267 static inline void stat(struct kmem_cache_cpu *c, enum stat_item si)
269 #ifdef CONFIG_SLUB_STATS
270 c->stat[si]++;
271 #endif
274 /********************************************************************
275 * Core slab cache functions
276 *******************************************************************/
278 int slab_is_available(void)
280 return slab_state >= UP;
283 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
285 #ifdef CONFIG_NUMA
286 return s->node[node];
287 #else
288 return &s->local_node;
289 #endif
292 static inline struct kmem_cache_cpu *get_cpu_slab(struct kmem_cache *s, int cpu)
294 #ifdef CONFIG_SMP
295 return s->cpu_slab[cpu];
296 #else
297 return &s->cpu_slab;
298 #endif
302 * The end pointer in a slab is special. It points to the first object in the
303 * slab but has bit 0 set to mark it.
305 * Note that SLUB relies on page_mapping returning NULL for pages with bit 0
306 * in the mapping set.
308 static inline int is_end(void *addr)
310 return (unsigned long)addr & PAGE_MAPPING_ANON;
313 static void *slab_address(struct page *page)
315 return page->end - PAGE_MAPPING_ANON;
318 static inline int check_valid_pointer(struct kmem_cache *s,
319 struct page *page, const void *object)
321 void *base;
323 if (object == page->end)
324 return 1;
326 base = slab_address(page);
327 if (object < base || object >= base + s->objects * s->size ||
328 (object - base) % s->size) {
329 return 0;
332 return 1;
336 * Slow version of get and set free pointer.
338 * This version requires touching the cache lines of kmem_cache which
339 * we avoid to do in the fast alloc free paths. There we obtain the offset
340 * from the page struct.
342 static inline void *get_freepointer(struct kmem_cache *s, void *object)
344 return *(void **)(object + s->offset);
347 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
349 *(void **)(object + s->offset) = fp;
352 /* Loop over all objects in a slab */
353 #define for_each_object(__p, __s, __addr) \
354 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
355 __p += (__s)->size)
357 /* Scan freelist */
358 #define for_each_free_object(__p, __s, __free) \
359 for (__p = (__free); (__p) != page->end; __p = get_freepointer((__s),\
360 __p))
362 /* Determine object index from a given position */
363 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
365 return (p - addr) / s->size;
368 #ifdef CONFIG_SLUB_DEBUG
370 * Debug settings:
372 #ifdef CONFIG_SLUB_DEBUG_ON
373 static int slub_debug = DEBUG_DEFAULT_FLAGS;
374 #else
375 static int slub_debug;
376 #endif
378 static char *slub_debug_slabs;
381 * Object debugging
383 static void print_section(char *text, u8 *addr, unsigned int length)
385 int i, offset;
386 int newline = 1;
387 char ascii[17];
389 ascii[16] = 0;
391 for (i = 0; i < length; i++) {
392 if (newline) {
393 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
394 newline = 0;
396 printk(KERN_CONT " %02x", addr[i]);
397 offset = i % 16;
398 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
399 if (offset == 15) {
400 printk(KERN_CONT " %s\n", ascii);
401 newline = 1;
404 if (!newline) {
405 i %= 16;
406 while (i < 16) {
407 printk(KERN_CONT " ");
408 ascii[i] = ' ';
409 i++;
411 printk(KERN_CONT " %s\n", ascii);
415 static struct track *get_track(struct kmem_cache *s, void *object,
416 enum track_item alloc)
418 struct track *p;
420 if (s->offset)
421 p = object + s->offset + sizeof(void *);
422 else
423 p = object + s->inuse;
425 return p + alloc;
428 static void set_track(struct kmem_cache *s, void *object,
429 enum track_item alloc, void *addr)
431 struct track *p;
433 if (s->offset)
434 p = object + s->offset + sizeof(void *);
435 else
436 p = object + s->inuse;
438 p += alloc;
439 if (addr) {
440 p->addr = addr;
441 p->cpu = smp_processor_id();
442 p->pid = current ? current->pid : -1;
443 p->when = jiffies;
444 } else
445 memset(p, 0, sizeof(struct track));
448 static void init_tracking(struct kmem_cache *s, void *object)
450 if (!(s->flags & SLAB_STORE_USER))
451 return;
453 set_track(s, object, TRACK_FREE, NULL);
454 set_track(s, object, TRACK_ALLOC, NULL);
457 static void print_track(const char *s, struct track *t)
459 if (!t->addr)
460 return;
462 printk(KERN_ERR "INFO: %s in ", s);
463 __print_symbol("%s", (unsigned long)t->addr);
464 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
467 static void print_tracking(struct kmem_cache *s, void *object)
469 if (!(s->flags & SLAB_STORE_USER))
470 return;
472 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
473 print_track("Freed", get_track(s, object, TRACK_FREE));
476 static void print_page_info(struct page *page)
478 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
479 page, page->inuse, page->freelist, page->flags);
483 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
485 va_list args;
486 char buf[100];
488 va_start(args, fmt);
489 vsnprintf(buf, sizeof(buf), fmt, args);
490 va_end(args);
491 printk(KERN_ERR "========================================"
492 "=====================================\n");
493 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
494 printk(KERN_ERR "----------------------------------------"
495 "-------------------------------------\n\n");
498 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
500 va_list args;
501 char buf[100];
503 va_start(args, fmt);
504 vsnprintf(buf, sizeof(buf), fmt, args);
505 va_end(args);
506 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
509 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
511 unsigned int off; /* Offset of last byte */
512 u8 *addr = slab_address(page);
514 print_tracking(s, p);
516 print_page_info(page);
518 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
519 p, p - addr, get_freepointer(s, p));
521 if (p > addr + 16)
522 print_section("Bytes b4", p - 16, 16);
524 print_section("Object", p, min(s->objsize, 128));
526 if (s->flags & SLAB_RED_ZONE)
527 print_section("Redzone", p + s->objsize,
528 s->inuse - s->objsize);
530 if (s->offset)
531 off = s->offset + sizeof(void *);
532 else
533 off = s->inuse;
535 if (s->flags & SLAB_STORE_USER)
536 off += 2 * sizeof(struct track);
538 if (off != s->size)
539 /* Beginning of the filler is the free pointer */
540 print_section("Padding", p + off, s->size - off);
542 dump_stack();
545 static void object_err(struct kmem_cache *s, struct page *page,
546 u8 *object, char *reason)
548 slab_bug(s, reason);
549 print_trailer(s, page, object);
552 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
554 va_list args;
555 char buf[100];
557 va_start(args, fmt);
558 vsnprintf(buf, sizeof(buf), fmt, args);
559 va_end(args);
560 slab_bug(s, fmt);
561 print_page_info(page);
562 dump_stack();
565 static void init_object(struct kmem_cache *s, void *object, int active)
567 u8 *p = object;
569 if (s->flags & __OBJECT_POISON) {
570 memset(p, POISON_FREE, s->objsize - 1);
571 p[s->objsize - 1] = POISON_END;
574 if (s->flags & SLAB_RED_ZONE)
575 memset(p + s->objsize,
576 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
577 s->inuse - s->objsize);
580 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
582 while (bytes) {
583 if (*start != (u8)value)
584 return start;
585 start++;
586 bytes--;
588 return NULL;
591 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
592 void *from, void *to)
594 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
595 memset(from, data, to - from);
598 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
599 u8 *object, char *what,
600 u8 *start, unsigned int value, unsigned int bytes)
602 u8 *fault;
603 u8 *end;
605 fault = check_bytes(start, value, bytes);
606 if (!fault)
607 return 1;
609 end = start + bytes;
610 while (end > fault && end[-1] == value)
611 end--;
613 slab_bug(s, "%s overwritten", what);
614 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
615 fault, end - 1, fault[0], value);
616 print_trailer(s, page, object);
618 restore_bytes(s, what, value, fault, end);
619 return 0;
623 * Object layout:
625 * object address
626 * Bytes of the object to be managed.
627 * If the freepointer may overlay the object then the free
628 * pointer is the first word of the object.
630 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
631 * 0xa5 (POISON_END)
633 * object + s->objsize
634 * Padding to reach word boundary. This is also used for Redzoning.
635 * Padding is extended by another word if Redzoning is enabled and
636 * objsize == inuse.
638 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
639 * 0xcc (RED_ACTIVE) for objects in use.
641 * object + s->inuse
642 * Meta data starts here.
644 * A. Free pointer (if we cannot overwrite object on free)
645 * B. Tracking data for SLAB_STORE_USER
646 * C. Padding to reach required alignment boundary or at mininum
647 * one word if debuggin is on to be able to detect writes
648 * before the word boundary.
650 * Padding is done using 0x5a (POISON_INUSE)
652 * object + s->size
653 * Nothing is used beyond s->size.
655 * If slabcaches are merged then the objsize and inuse boundaries are mostly
656 * ignored. And therefore no slab options that rely on these boundaries
657 * may be used with merged slabcaches.
660 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
662 unsigned long off = s->inuse; /* The end of info */
664 if (s->offset)
665 /* Freepointer is placed after the object. */
666 off += sizeof(void *);
668 if (s->flags & SLAB_STORE_USER)
669 /* We also have user information there */
670 off += 2 * sizeof(struct track);
672 if (s->size == off)
673 return 1;
675 return check_bytes_and_report(s, page, p, "Object padding",
676 p + off, POISON_INUSE, s->size - off);
679 static int slab_pad_check(struct kmem_cache *s, struct page *page)
681 u8 *start;
682 u8 *fault;
683 u8 *end;
684 int length;
685 int remainder;
687 if (!(s->flags & SLAB_POISON))
688 return 1;
690 start = slab_address(page);
691 end = start + (PAGE_SIZE << s->order);
692 length = s->objects * s->size;
693 remainder = end - (start + length);
694 if (!remainder)
695 return 1;
697 fault = check_bytes(start + length, POISON_INUSE, remainder);
698 if (!fault)
699 return 1;
700 while (end > fault && end[-1] == POISON_INUSE)
701 end--;
703 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
704 print_section("Padding", start, length);
706 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
707 return 0;
710 static int check_object(struct kmem_cache *s, struct page *page,
711 void *object, int active)
713 u8 *p = object;
714 u8 *endobject = object + s->objsize;
716 if (s->flags & SLAB_RED_ZONE) {
717 unsigned int red =
718 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
720 if (!check_bytes_and_report(s, page, object, "Redzone",
721 endobject, red, s->inuse - s->objsize))
722 return 0;
723 } else {
724 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse) {
725 check_bytes_and_report(s, page, p, "Alignment padding",
726 endobject, POISON_INUSE, s->inuse - s->objsize);
730 if (s->flags & SLAB_POISON) {
731 if (!active && (s->flags & __OBJECT_POISON) &&
732 (!check_bytes_and_report(s, page, p, "Poison", p,
733 POISON_FREE, s->objsize - 1) ||
734 !check_bytes_and_report(s, page, p, "Poison",
735 p + s->objsize - 1, POISON_END, 1)))
736 return 0;
738 * check_pad_bytes cleans up on its own.
740 check_pad_bytes(s, page, p);
743 if (!s->offset && active)
745 * Object and freepointer overlap. Cannot check
746 * freepointer while object is allocated.
748 return 1;
750 /* Check free pointer validity */
751 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
752 object_err(s, page, p, "Freepointer corrupt");
754 * No choice but to zap it and thus loose the remainder
755 * of the free objects in this slab. May cause
756 * another error because the object count is now wrong.
758 set_freepointer(s, p, page->end);
759 return 0;
761 return 1;
764 static int check_slab(struct kmem_cache *s, struct page *page)
766 VM_BUG_ON(!irqs_disabled());
768 if (!PageSlab(page)) {
769 slab_err(s, page, "Not a valid slab page");
770 return 0;
772 if (page->inuse > s->objects) {
773 slab_err(s, page, "inuse %u > max %u",
774 s->name, page->inuse, s->objects);
775 return 0;
777 /* Slab_pad_check fixes things up after itself */
778 slab_pad_check(s, page);
779 return 1;
783 * Determine if a certain object on a page is on the freelist. Must hold the
784 * slab lock to guarantee that the chains are in a consistent state.
786 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
788 int nr = 0;
789 void *fp = page->freelist;
790 void *object = NULL;
792 while (fp != page->end && nr <= s->objects) {
793 if (fp == search)
794 return 1;
795 if (!check_valid_pointer(s, page, fp)) {
796 if (object) {
797 object_err(s, page, object,
798 "Freechain corrupt");
799 set_freepointer(s, object, page->end);
800 break;
801 } else {
802 slab_err(s, page, "Freepointer corrupt");
803 page->freelist = page->end;
804 page->inuse = s->objects;
805 slab_fix(s, "Freelist cleared");
806 return 0;
808 break;
810 object = fp;
811 fp = get_freepointer(s, object);
812 nr++;
815 if (page->inuse != s->objects - nr) {
816 slab_err(s, page, "Wrong object count. Counter is %d but "
817 "counted were %d", page->inuse, s->objects - nr);
818 page->inuse = s->objects - nr;
819 slab_fix(s, "Object count adjusted.");
821 return search == NULL;
824 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
826 if (s->flags & SLAB_TRACE) {
827 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
828 s->name,
829 alloc ? "alloc" : "free",
830 object, page->inuse,
831 page->freelist);
833 if (!alloc)
834 print_section("Object", (void *)object, s->objsize);
836 dump_stack();
841 * Tracking of fully allocated slabs for debugging purposes.
843 static void add_full(struct kmem_cache_node *n, struct page *page)
845 spin_lock(&n->list_lock);
846 list_add(&page->lru, &n->full);
847 spin_unlock(&n->list_lock);
850 static void remove_full(struct kmem_cache *s, struct page *page)
852 struct kmem_cache_node *n;
854 if (!(s->flags & SLAB_STORE_USER))
855 return;
857 n = get_node(s, page_to_nid(page));
859 spin_lock(&n->list_lock);
860 list_del(&page->lru);
861 spin_unlock(&n->list_lock);
864 static void setup_object_debug(struct kmem_cache *s, struct page *page,
865 void *object)
867 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
868 return;
870 init_object(s, object, 0);
871 init_tracking(s, object);
874 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
875 void *object, void *addr)
877 if (!check_slab(s, page))
878 goto bad;
880 if (object && !on_freelist(s, page, object)) {
881 object_err(s, page, object, "Object already allocated");
882 goto bad;
885 if (!check_valid_pointer(s, page, object)) {
886 object_err(s, page, object, "Freelist Pointer check fails");
887 goto bad;
890 if (object && !check_object(s, page, object, 0))
891 goto bad;
893 /* Success perform special debug activities for allocs */
894 if (s->flags & SLAB_STORE_USER)
895 set_track(s, object, TRACK_ALLOC, addr);
896 trace(s, page, object, 1);
897 init_object(s, object, 1);
898 return 1;
900 bad:
901 if (PageSlab(page)) {
903 * If this is a slab page then lets do the best we can
904 * to avoid issues in the future. Marking all objects
905 * as used avoids touching the remaining objects.
907 slab_fix(s, "Marking all objects used");
908 page->inuse = s->objects;
909 page->freelist = page->end;
911 return 0;
914 static int free_debug_processing(struct kmem_cache *s, struct page *page,
915 void *object, void *addr)
917 if (!check_slab(s, page))
918 goto fail;
920 if (!check_valid_pointer(s, page, object)) {
921 slab_err(s, page, "Invalid object pointer 0x%p", object);
922 goto fail;
925 if (on_freelist(s, page, object)) {
926 object_err(s, page, object, "Object already free");
927 goto fail;
930 if (!check_object(s, page, object, 1))
931 return 0;
933 if (unlikely(s != page->slab)) {
934 if (!PageSlab(page)) {
935 slab_err(s, page, "Attempt to free object(0x%p) "
936 "outside of slab", object);
937 } else if (!page->slab) {
938 printk(KERN_ERR
939 "SLUB <none>: no slab for object 0x%p.\n",
940 object);
941 dump_stack();
942 } else
943 object_err(s, page, object,
944 "page slab pointer corrupt.");
945 goto fail;
948 /* Special debug activities for freeing objects */
949 if (!SlabFrozen(page) && page->freelist == page->end)
950 remove_full(s, page);
951 if (s->flags & SLAB_STORE_USER)
952 set_track(s, object, TRACK_FREE, addr);
953 trace(s, page, object, 0);
954 init_object(s, object, 0);
955 return 1;
957 fail:
958 slab_fix(s, "Object at 0x%p not freed", object);
959 return 0;
962 static int __init setup_slub_debug(char *str)
964 slub_debug = DEBUG_DEFAULT_FLAGS;
965 if (*str++ != '=' || !*str)
967 * No options specified. Switch on full debugging.
969 goto out;
971 if (*str == ',')
973 * No options but restriction on slabs. This means full
974 * debugging for slabs matching a pattern.
976 goto check_slabs;
978 slub_debug = 0;
979 if (*str == '-')
981 * Switch off all debugging measures.
983 goto out;
986 * Determine which debug features should be switched on
988 for (; *str && *str != ','; str++) {
989 switch (tolower(*str)) {
990 case 'f':
991 slub_debug |= SLAB_DEBUG_FREE;
992 break;
993 case 'z':
994 slub_debug |= SLAB_RED_ZONE;
995 break;
996 case 'p':
997 slub_debug |= SLAB_POISON;
998 break;
999 case 'u':
1000 slub_debug |= SLAB_STORE_USER;
1001 break;
1002 case 't':
1003 slub_debug |= SLAB_TRACE;
1004 break;
1005 default:
1006 printk(KERN_ERR "slub_debug option '%c' "
1007 "unknown. skipped\n", *str);
1011 check_slabs:
1012 if (*str == ',')
1013 slub_debug_slabs = str + 1;
1014 out:
1015 return 1;
1018 __setup("slub_debug", setup_slub_debug);
1020 static unsigned long kmem_cache_flags(unsigned long objsize,
1021 unsigned long flags, const char *name,
1022 void (*ctor)(struct kmem_cache *, void *))
1025 * The page->offset field is only 16 bit wide. This is an offset
1026 * in units of words from the beginning of an object. If the slab
1027 * size is bigger then we cannot move the free pointer behind the
1028 * object anymore.
1030 * On 32 bit platforms the limit is 256k. On 64bit platforms
1031 * the limit is 512k.
1033 * Debugging or ctor may create a need to move the free
1034 * pointer. Fail if this happens.
1036 if (objsize >= 65535 * sizeof(void *)) {
1037 BUG_ON(flags & (SLAB_RED_ZONE | SLAB_POISON |
1038 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
1039 BUG_ON(ctor);
1040 } else {
1042 * Enable debugging if selected on the kernel commandline.
1044 if (slub_debug && (!slub_debug_slabs ||
1045 strncmp(slub_debug_slabs, name,
1046 strlen(slub_debug_slabs)) == 0))
1047 flags |= slub_debug;
1050 return flags;
1052 #else
1053 static inline void setup_object_debug(struct kmem_cache *s,
1054 struct page *page, void *object) {}
1056 static inline int alloc_debug_processing(struct kmem_cache *s,
1057 struct page *page, void *object, void *addr) { return 0; }
1059 static inline int free_debug_processing(struct kmem_cache *s,
1060 struct page *page, void *object, void *addr) { return 0; }
1062 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1063 { return 1; }
1064 static inline int check_object(struct kmem_cache *s, struct page *page,
1065 void *object, int active) { return 1; }
1066 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1067 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1068 unsigned long flags, const char *name,
1069 void (*ctor)(struct kmem_cache *, void *))
1071 return flags;
1073 #define slub_debug 0
1074 #endif
1076 * Slab allocation and freeing
1078 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1080 struct page *page;
1081 int pages = 1 << s->order;
1083 flags |= s->allocflags;
1085 if (node == -1)
1086 page = alloc_pages(flags, s->order);
1087 else
1088 page = alloc_pages_node(node, flags, s->order);
1090 if (!page)
1091 return NULL;
1093 mod_zone_page_state(page_zone(page),
1094 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1095 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1096 pages);
1098 return page;
1101 static void setup_object(struct kmem_cache *s, struct page *page,
1102 void *object)
1104 setup_object_debug(s, page, object);
1105 if (unlikely(s->ctor))
1106 s->ctor(s, object);
1109 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1111 struct page *page;
1112 struct kmem_cache_node *n;
1113 void *start;
1114 void *last;
1115 void *p;
1117 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1119 page = allocate_slab(s,
1120 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1121 if (!page)
1122 goto out;
1124 n = get_node(s, page_to_nid(page));
1125 if (n)
1126 atomic_long_inc(&n->nr_slabs);
1127 page->slab = s;
1128 page->flags |= 1 << PG_slab;
1129 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1130 SLAB_STORE_USER | SLAB_TRACE))
1131 SetSlabDebug(page);
1133 start = page_address(page);
1134 page->end = start + 1;
1136 if (unlikely(s->flags & SLAB_POISON))
1137 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1139 last = start;
1140 for_each_object(p, s, start) {
1141 setup_object(s, page, last);
1142 set_freepointer(s, last, p);
1143 last = p;
1145 setup_object(s, page, last);
1146 set_freepointer(s, last, page->end);
1148 page->freelist = start;
1149 page->inuse = 0;
1150 out:
1151 return page;
1154 static void __free_slab(struct kmem_cache *s, struct page *page)
1156 int pages = 1 << s->order;
1158 if (unlikely(SlabDebug(page))) {
1159 void *p;
1161 slab_pad_check(s, page);
1162 for_each_object(p, s, slab_address(page))
1163 check_object(s, page, p, 0);
1164 ClearSlabDebug(page);
1167 mod_zone_page_state(page_zone(page),
1168 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1169 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1170 -pages);
1172 page->mapping = NULL;
1173 __free_pages(page, s->order);
1176 static void rcu_free_slab(struct rcu_head *h)
1178 struct page *page;
1180 page = container_of((struct list_head *)h, struct page, lru);
1181 __free_slab(page->slab, page);
1184 static void free_slab(struct kmem_cache *s, struct page *page)
1186 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1188 * RCU free overloads the RCU head over the LRU
1190 struct rcu_head *head = (void *)&page->lru;
1192 call_rcu(head, rcu_free_slab);
1193 } else
1194 __free_slab(s, page);
1197 static void discard_slab(struct kmem_cache *s, struct page *page)
1199 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1201 atomic_long_dec(&n->nr_slabs);
1202 reset_page_mapcount(page);
1203 __ClearPageSlab(page);
1204 free_slab(s, page);
1208 * Per slab locking using the pagelock
1210 static __always_inline void slab_lock(struct page *page)
1212 bit_spin_lock(PG_locked, &page->flags);
1215 static __always_inline void slab_unlock(struct page *page)
1217 __bit_spin_unlock(PG_locked, &page->flags);
1220 static __always_inline int slab_trylock(struct page *page)
1222 int rc = 1;
1224 rc = bit_spin_trylock(PG_locked, &page->flags);
1225 return rc;
1229 * Management of partially allocated slabs
1231 static void add_partial(struct kmem_cache_node *n,
1232 struct page *page, int tail)
1234 spin_lock(&n->list_lock);
1235 n->nr_partial++;
1236 if (tail)
1237 list_add_tail(&page->lru, &n->partial);
1238 else
1239 list_add(&page->lru, &n->partial);
1240 spin_unlock(&n->list_lock);
1243 static void remove_partial(struct kmem_cache *s,
1244 struct page *page)
1246 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1248 spin_lock(&n->list_lock);
1249 list_del(&page->lru);
1250 n->nr_partial--;
1251 spin_unlock(&n->list_lock);
1255 * Lock slab and remove from the partial list.
1257 * Must hold list_lock.
1259 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1261 if (slab_trylock(page)) {
1262 list_del(&page->lru);
1263 n->nr_partial--;
1264 SetSlabFrozen(page);
1265 return 1;
1267 return 0;
1271 * Try to allocate a partial slab from a specific node.
1273 static struct page *get_partial_node(struct kmem_cache_node *n)
1275 struct page *page;
1278 * Racy check. If we mistakenly see no partial slabs then we
1279 * just allocate an empty slab. If we mistakenly try to get a
1280 * partial slab and there is none available then get_partials()
1281 * will return NULL.
1283 if (!n || !n->nr_partial)
1284 return NULL;
1286 spin_lock(&n->list_lock);
1287 list_for_each_entry(page, &n->partial, lru)
1288 if (lock_and_freeze_slab(n, page))
1289 goto out;
1290 page = NULL;
1291 out:
1292 spin_unlock(&n->list_lock);
1293 return page;
1297 * Get a page from somewhere. Search in increasing NUMA distances.
1299 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1301 #ifdef CONFIG_NUMA
1302 struct zonelist *zonelist;
1303 struct zone **z;
1304 struct page *page;
1307 * The defrag ratio allows a configuration of the tradeoffs between
1308 * inter node defragmentation and node local allocations. A lower
1309 * defrag_ratio increases the tendency to do local allocations
1310 * instead of attempting to obtain partial slabs from other nodes.
1312 * If the defrag_ratio is set to 0 then kmalloc() always
1313 * returns node local objects. If the ratio is higher then kmalloc()
1314 * may return off node objects because partial slabs are obtained
1315 * from other nodes and filled up.
1317 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1318 * defrag_ratio = 1000) then every (well almost) allocation will
1319 * first attempt to defrag slab caches on other nodes. This means
1320 * scanning over all nodes to look for partial slabs which may be
1321 * expensive if we do it every time we are trying to find a slab
1322 * with available objects.
1324 if (!s->remote_node_defrag_ratio ||
1325 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1326 return NULL;
1328 zonelist = &NODE_DATA(
1329 slab_node(current->mempolicy))->node_zonelists[gfp_zone(flags)];
1330 for (z = zonelist->zones; *z; z++) {
1331 struct kmem_cache_node *n;
1333 n = get_node(s, zone_to_nid(*z));
1335 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1336 n->nr_partial > MIN_PARTIAL) {
1337 page = get_partial_node(n);
1338 if (page)
1339 return page;
1342 #endif
1343 return NULL;
1347 * Get a partial page, lock it and return it.
1349 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1351 struct page *page;
1352 int searchnode = (node == -1) ? numa_node_id() : node;
1354 page = get_partial_node(get_node(s, searchnode));
1355 if (page || (flags & __GFP_THISNODE))
1356 return page;
1358 return get_any_partial(s, flags);
1362 * Move a page back to the lists.
1364 * Must be called with the slab lock held.
1366 * On exit the slab lock will have been dropped.
1368 static void unfreeze_slab(struct kmem_cache *s, struct page *page, int tail)
1370 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1371 struct kmem_cache_cpu *c = get_cpu_slab(s, smp_processor_id());
1373 ClearSlabFrozen(page);
1374 if (page->inuse) {
1376 if (page->freelist != page->end) {
1377 add_partial(n, page, tail);
1378 stat(c, tail ? DEACTIVATE_TO_TAIL : DEACTIVATE_TO_HEAD);
1379 } else {
1380 stat(c, DEACTIVATE_FULL);
1381 if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1382 add_full(n, page);
1384 slab_unlock(page);
1385 } else {
1386 stat(c, DEACTIVATE_EMPTY);
1387 if (n->nr_partial < MIN_PARTIAL) {
1389 * Adding an empty slab to the partial slabs in order
1390 * to avoid page allocator overhead. This slab needs
1391 * to come after the other slabs with objects in
1392 * order to fill them up. That way the size of the
1393 * partial list stays small. kmem_cache_shrink can
1394 * reclaim empty slabs from the partial list.
1396 add_partial(n, page, 1);
1397 slab_unlock(page);
1398 } else {
1399 slab_unlock(page);
1400 stat(get_cpu_slab(s, raw_smp_processor_id()), FREE_SLAB);
1401 discard_slab(s, page);
1407 * Remove the cpu slab
1409 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1411 struct page *page = c->page;
1412 int tail = 1;
1414 if (c->freelist)
1415 stat(c, DEACTIVATE_REMOTE_FREES);
1417 * Merge cpu freelist into freelist. Typically we get here
1418 * because both freelists are empty. So this is unlikely
1419 * to occur.
1421 * We need to use _is_end here because deactivate slab may
1422 * be called for a debug slab. Then c->freelist may contain
1423 * a dummy pointer.
1425 while (unlikely(!is_end(c->freelist))) {
1426 void **object;
1428 tail = 0; /* Hot objects. Put the slab first */
1430 /* Retrieve object from cpu_freelist */
1431 object = c->freelist;
1432 c->freelist = c->freelist[c->offset];
1434 /* And put onto the regular freelist */
1435 object[c->offset] = page->freelist;
1436 page->freelist = object;
1437 page->inuse--;
1439 c->page = NULL;
1440 unfreeze_slab(s, page, tail);
1443 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1445 stat(c, CPUSLAB_FLUSH);
1446 slab_lock(c->page);
1447 deactivate_slab(s, c);
1451 * Flush cpu slab.
1452 * Called from IPI handler with interrupts disabled.
1454 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1456 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1458 if (likely(c && c->page))
1459 flush_slab(s, c);
1462 static void flush_cpu_slab(void *d)
1464 struct kmem_cache *s = d;
1466 __flush_cpu_slab(s, smp_processor_id());
1469 static void flush_all(struct kmem_cache *s)
1471 #ifdef CONFIG_SMP
1472 on_each_cpu(flush_cpu_slab, s, 1, 1);
1473 #else
1474 unsigned long flags;
1476 local_irq_save(flags);
1477 flush_cpu_slab(s);
1478 local_irq_restore(flags);
1479 #endif
1483 * Check if the objects in a per cpu structure fit numa
1484 * locality expectations.
1486 static inline int node_match(struct kmem_cache_cpu *c, int node)
1488 #ifdef CONFIG_NUMA
1489 if (node != -1 && c->node != node)
1490 return 0;
1491 #endif
1492 return 1;
1496 * Slow path. The lockless freelist is empty or we need to perform
1497 * debugging duties.
1499 * Interrupts are disabled.
1501 * Processing is still very fast if new objects have been freed to the
1502 * regular freelist. In that case we simply take over the regular freelist
1503 * as the lockless freelist and zap the regular freelist.
1505 * If that is not working then we fall back to the partial lists. We take the
1506 * first element of the freelist as the object to allocate now and move the
1507 * rest of the freelist to the lockless freelist.
1509 * And if we were unable to get a new slab from the partial slab lists then
1510 * we need to allocate a new slab. This is slowest path since we may sleep.
1512 static void *__slab_alloc(struct kmem_cache *s,
1513 gfp_t gfpflags, int node, void *addr, struct kmem_cache_cpu *c)
1515 void **object;
1516 struct page *new;
1517 #ifdef SLUB_FASTPATH
1518 unsigned long flags;
1520 local_irq_save(flags);
1521 #endif
1522 if (!c->page)
1523 goto new_slab;
1525 slab_lock(c->page);
1526 if (unlikely(!node_match(c, node)))
1527 goto another_slab;
1528 stat(c, ALLOC_REFILL);
1529 load_freelist:
1530 object = c->page->freelist;
1531 if (unlikely(object == c->page->end))
1532 goto another_slab;
1533 if (unlikely(SlabDebug(c->page)))
1534 goto debug;
1536 object = c->page->freelist;
1537 c->freelist = object[c->offset];
1538 c->page->inuse = s->objects;
1539 c->page->freelist = c->page->end;
1540 c->node = page_to_nid(c->page);
1541 unlock_out:
1542 slab_unlock(c->page);
1543 stat(c, ALLOC_SLOWPATH);
1544 #ifdef SLUB_FASTPATH
1545 local_irq_restore(flags);
1546 #endif
1547 return object;
1549 another_slab:
1550 deactivate_slab(s, c);
1552 new_slab:
1553 new = get_partial(s, gfpflags, node);
1554 if (new) {
1555 c->page = new;
1556 stat(c, ALLOC_FROM_PARTIAL);
1557 goto load_freelist;
1560 if (gfpflags & __GFP_WAIT)
1561 local_irq_enable();
1563 new = new_slab(s, gfpflags, node);
1565 if (gfpflags & __GFP_WAIT)
1566 local_irq_disable();
1568 if (new) {
1569 c = get_cpu_slab(s, smp_processor_id());
1570 stat(c, ALLOC_SLAB);
1571 if (c->page)
1572 flush_slab(s, c);
1573 slab_lock(new);
1574 SetSlabFrozen(new);
1575 c->page = new;
1576 goto load_freelist;
1578 #ifdef SLUB_FASTPATH
1579 local_irq_restore(flags);
1580 #endif
1582 * No memory available.
1584 * If the slab uses higher order allocs but the object is
1585 * smaller than a page size then we can fallback in emergencies
1586 * to the page allocator via kmalloc_large. The page allocator may
1587 * have failed to obtain a higher order page and we can try to
1588 * allocate a single page if the object fits into a single page.
1589 * That is only possible if certain conditions are met that are being
1590 * checked when a slab is created.
1592 if (!(gfpflags & __GFP_NORETRY) && (s->flags & __PAGE_ALLOC_FALLBACK))
1593 return kmalloc_large(s->objsize, gfpflags);
1595 return NULL;
1596 debug:
1597 object = c->page->freelist;
1598 if (!alloc_debug_processing(s, c->page, object, addr))
1599 goto another_slab;
1601 c->page->inuse++;
1602 c->page->freelist = object[c->offset];
1603 c->node = -1;
1604 goto unlock_out;
1608 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1609 * have the fastpath folded into their functions. So no function call
1610 * overhead for requests that can be satisfied on the fastpath.
1612 * The fastpath works by first checking if the lockless freelist can be used.
1613 * If not then __slab_alloc is called for slow processing.
1615 * Otherwise we can simply pick the next object from the lockless free list.
1617 static __always_inline void *slab_alloc(struct kmem_cache *s,
1618 gfp_t gfpflags, int node, void *addr)
1620 void **object;
1621 struct kmem_cache_cpu *c;
1624 * The SLUB_FASTPATH path is provisional and is currently disabled if the
1625 * kernel is compiled with preemption or if the arch does not support
1626 * fast cmpxchg operations. There are a couple of coming changes that will
1627 * simplify matters and allow preemption. Ultimately we may end up making
1628 * SLUB_FASTPATH the default.
1630 * 1. The introduction of the per cpu allocator will avoid array lookups
1631 * through get_cpu_slab(). A special register can be used instead.
1633 * 2. The introduction of per cpu atomic operations (cpu_ops) means that
1634 * we can realize the logic here entirely with per cpu atomics. The
1635 * per cpu atomic ops will take care of the preemption issues.
1638 #ifdef SLUB_FASTPATH
1639 c = get_cpu_slab(s, raw_smp_processor_id());
1640 do {
1641 object = c->freelist;
1642 if (unlikely(is_end(object) || !node_match(c, node))) {
1643 object = __slab_alloc(s, gfpflags, node, addr, c);
1644 break;
1646 stat(c, ALLOC_FASTPATH);
1647 } while (cmpxchg_local(&c->freelist, object, object[c->offset])
1648 != object);
1649 #else
1650 unsigned long flags;
1652 local_irq_save(flags);
1653 c = get_cpu_slab(s, smp_processor_id());
1654 if (unlikely(is_end(c->freelist) || !node_match(c, node)))
1656 object = __slab_alloc(s, gfpflags, node, addr, c);
1658 else {
1659 object = c->freelist;
1660 c->freelist = object[c->offset];
1661 stat(c, ALLOC_FASTPATH);
1663 local_irq_restore(flags);
1664 #endif
1666 if (unlikely((gfpflags & __GFP_ZERO) && object))
1667 memset(object, 0, c->objsize);
1669 return object;
1672 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1674 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1676 EXPORT_SYMBOL(kmem_cache_alloc);
1678 #ifdef CONFIG_NUMA
1679 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1681 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1683 EXPORT_SYMBOL(kmem_cache_alloc_node);
1684 #endif
1687 * Slow patch handling. This may still be called frequently since objects
1688 * have a longer lifetime than the cpu slabs in most processing loads.
1690 * So we still attempt to reduce cache line usage. Just take the slab
1691 * lock and free the item. If there is no additional partial page
1692 * handling required then we can return immediately.
1694 static void __slab_free(struct kmem_cache *s, struct page *page,
1695 void *x, void *addr, unsigned int offset)
1697 void *prior;
1698 void **object = (void *)x;
1699 struct kmem_cache_cpu *c;
1701 #ifdef SLUB_FASTPATH
1702 unsigned long flags;
1704 local_irq_save(flags);
1705 #endif
1706 c = get_cpu_slab(s, raw_smp_processor_id());
1707 stat(c, FREE_SLOWPATH);
1708 slab_lock(page);
1710 if (unlikely(SlabDebug(page)))
1711 goto debug;
1712 checks_ok:
1713 prior = object[offset] = page->freelist;
1714 page->freelist = object;
1715 page->inuse--;
1717 if (unlikely(SlabFrozen(page))) {
1718 stat(c, FREE_FROZEN);
1719 goto out_unlock;
1722 if (unlikely(!page->inuse))
1723 goto slab_empty;
1726 * Objects left in the slab. If it
1727 * was not on the partial list before
1728 * then add it.
1730 if (unlikely(prior == page->end)) {
1731 add_partial(get_node(s, page_to_nid(page)), page, 1);
1732 stat(c, FREE_ADD_PARTIAL);
1735 out_unlock:
1736 slab_unlock(page);
1737 #ifdef SLUB_FASTPATH
1738 local_irq_restore(flags);
1739 #endif
1740 return;
1742 slab_empty:
1743 if (prior != page->end) {
1745 * Slab still on the partial list.
1747 remove_partial(s, page);
1748 stat(c, FREE_REMOVE_PARTIAL);
1750 slab_unlock(page);
1751 stat(c, FREE_SLAB);
1752 #ifdef SLUB_FASTPATH
1753 local_irq_restore(flags);
1754 #endif
1755 discard_slab(s, page);
1756 return;
1758 debug:
1759 if (!free_debug_processing(s, page, x, addr))
1760 goto out_unlock;
1761 goto checks_ok;
1765 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1766 * can perform fastpath freeing without additional function calls.
1768 * The fastpath is only possible if we are freeing to the current cpu slab
1769 * of this processor. This typically the case if we have just allocated
1770 * the item before.
1772 * If fastpath is not possible then fall back to __slab_free where we deal
1773 * with all sorts of special processing.
1775 static __always_inline void slab_free(struct kmem_cache *s,
1776 struct page *page, void *x, void *addr)
1778 void **object = (void *)x;
1779 struct kmem_cache_cpu *c;
1781 #ifdef SLUB_FASTPATH
1782 void **freelist;
1784 c = get_cpu_slab(s, raw_smp_processor_id());
1785 debug_check_no_locks_freed(object, s->objsize);
1786 do {
1787 freelist = c->freelist;
1788 barrier();
1790 * If the compiler would reorder the retrieval of c->page to
1791 * come before c->freelist then an interrupt could
1792 * change the cpu slab before we retrieve c->freelist. We
1793 * could be matching on a page no longer active and put the
1794 * object onto the freelist of the wrong slab.
1796 * On the other hand: If we already have the freelist pointer
1797 * then any change of cpu_slab will cause the cmpxchg to fail
1798 * since the freelist pointers are unique per slab.
1800 if (unlikely(page != c->page || c->node < 0)) {
1801 __slab_free(s, page, x, addr, c->offset);
1802 break;
1804 object[c->offset] = freelist;
1805 stat(c, FREE_FASTPATH);
1806 } while (cmpxchg_local(&c->freelist, freelist, object) != freelist);
1807 #else
1808 unsigned long flags;
1810 local_irq_save(flags);
1811 debug_check_no_locks_freed(object, s->objsize);
1812 c = get_cpu_slab(s, smp_processor_id());
1813 if (likely(page == c->page && c->node >= 0)) {
1814 object[c->offset] = c->freelist;
1815 c->freelist = object;
1816 stat(c, FREE_FASTPATH);
1817 } else
1818 __slab_free(s, page, x, addr, c->offset);
1820 local_irq_restore(flags);
1821 #endif
1824 void kmem_cache_free(struct kmem_cache *s, void *x)
1826 struct page *page;
1828 page = virt_to_head_page(x);
1830 slab_free(s, page, x, __builtin_return_address(0));
1832 EXPORT_SYMBOL(kmem_cache_free);
1834 /* Figure out on which slab object the object resides */
1835 static struct page *get_object_page(const void *x)
1837 struct page *page = virt_to_head_page(x);
1839 if (!PageSlab(page))
1840 return NULL;
1842 return page;
1846 * Object placement in a slab is made very easy because we always start at
1847 * offset 0. If we tune the size of the object to the alignment then we can
1848 * get the required alignment by putting one properly sized object after
1849 * another.
1851 * Notice that the allocation order determines the sizes of the per cpu
1852 * caches. Each processor has always one slab available for allocations.
1853 * Increasing the allocation order reduces the number of times that slabs
1854 * must be moved on and off the partial lists and is therefore a factor in
1855 * locking overhead.
1859 * Mininum / Maximum order of slab pages. This influences locking overhead
1860 * and slab fragmentation. A higher order reduces the number of partial slabs
1861 * and increases the number of allocations possible without having to
1862 * take the list_lock.
1864 static int slub_min_order;
1865 static int slub_max_order = DEFAULT_MAX_ORDER;
1866 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1869 * Merge control. If this is set then no merging of slab caches will occur.
1870 * (Could be removed. This was introduced to pacify the merge skeptics.)
1872 static int slub_nomerge;
1875 * Calculate the order of allocation given an slab object size.
1877 * The order of allocation has significant impact on performance and other
1878 * system components. Generally order 0 allocations should be preferred since
1879 * order 0 does not cause fragmentation in the page allocator. Larger objects
1880 * be problematic to put into order 0 slabs because there may be too much
1881 * unused space left. We go to a higher order if more than 1/8th of the slab
1882 * would be wasted.
1884 * In order to reach satisfactory performance we must ensure that a minimum
1885 * number of objects is in one slab. Otherwise we may generate too much
1886 * activity on the partial lists which requires taking the list_lock. This is
1887 * less a concern for large slabs though which are rarely used.
1889 * slub_max_order specifies the order where we begin to stop considering the
1890 * number of objects in a slab as critical. If we reach slub_max_order then
1891 * we try to keep the page order as low as possible. So we accept more waste
1892 * of space in favor of a small page order.
1894 * Higher order allocations also allow the placement of more objects in a
1895 * slab and thereby reduce object handling overhead. If the user has
1896 * requested a higher mininum order then we start with that one instead of
1897 * the smallest order which will fit the object.
1899 static inline int slab_order(int size, int min_objects,
1900 int max_order, int fract_leftover)
1902 int order;
1903 int rem;
1904 int min_order = slub_min_order;
1906 for (order = max(min_order,
1907 fls(min_objects * size - 1) - PAGE_SHIFT);
1908 order <= max_order; order++) {
1910 unsigned long slab_size = PAGE_SIZE << order;
1912 if (slab_size < min_objects * size)
1913 continue;
1915 rem = slab_size % size;
1917 if (rem <= slab_size / fract_leftover)
1918 break;
1922 return order;
1925 static inline int calculate_order(int size)
1927 int order;
1928 int min_objects;
1929 int fraction;
1932 * Attempt to find best configuration for a slab. This
1933 * works by first attempting to generate a layout with
1934 * the best configuration and backing off gradually.
1936 * First we reduce the acceptable waste in a slab. Then
1937 * we reduce the minimum objects required in a slab.
1939 min_objects = slub_min_objects;
1940 while (min_objects > 1) {
1941 fraction = 8;
1942 while (fraction >= 4) {
1943 order = slab_order(size, min_objects,
1944 slub_max_order, fraction);
1945 if (order <= slub_max_order)
1946 return order;
1947 fraction /= 2;
1949 min_objects /= 2;
1953 * We were unable to place multiple objects in a slab. Now
1954 * lets see if we can place a single object there.
1956 order = slab_order(size, 1, slub_max_order, 1);
1957 if (order <= slub_max_order)
1958 return order;
1961 * Doh this slab cannot be placed using slub_max_order.
1963 order = slab_order(size, 1, MAX_ORDER, 1);
1964 if (order <= MAX_ORDER)
1965 return order;
1966 return -ENOSYS;
1970 * Figure out what the alignment of the objects will be.
1972 static unsigned long calculate_alignment(unsigned long flags,
1973 unsigned long align, unsigned long size)
1976 * If the user wants hardware cache aligned objects then
1977 * follow that suggestion if the object is sufficiently
1978 * large.
1980 * The hardware cache alignment cannot override the
1981 * specified alignment though. If that is greater
1982 * then use it.
1984 if ((flags & SLAB_HWCACHE_ALIGN) &&
1985 size > cache_line_size() / 2)
1986 return max_t(unsigned long, align, cache_line_size());
1988 if (align < ARCH_SLAB_MINALIGN)
1989 return ARCH_SLAB_MINALIGN;
1991 return ALIGN(align, sizeof(void *));
1994 static void init_kmem_cache_cpu(struct kmem_cache *s,
1995 struct kmem_cache_cpu *c)
1997 c->page = NULL;
1998 c->freelist = (void *)PAGE_MAPPING_ANON;
1999 c->node = 0;
2000 c->offset = s->offset / sizeof(void *);
2001 c->objsize = s->objsize;
2004 static void init_kmem_cache_node(struct kmem_cache_node *n)
2006 n->nr_partial = 0;
2007 atomic_long_set(&n->nr_slabs, 0);
2008 spin_lock_init(&n->list_lock);
2009 INIT_LIST_HEAD(&n->partial);
2010 #ifdef CONFIG_SLUB_DEBUG
2011 INIT_LIST_HEAD(&n->full);
2012 #endif
2015 #ifdef CONFIG_SMP
2017 * Per cpu array for per cpu structures.
2019 * The per cpu array places all kmem_cache_cpu structures from one processor
2020 * close together meaning that it becomes possible that multiple per cpu
2021 * structures are contained in one cacheline. This may be particularly
2022 * beneficial for the kmalloc caches.
2024 * A desktop system typically has around 60-80 slabs. With 100 here we are
2025 * likely able to get per cpu structures for all caches from the array defined
2026 * here. We must be able to cover all kmalloc caches during bootstrap.
2028 * If the per cpu array is exhausted then fall back to kmalloc
2029 * of individual cachelines. No sharing is possible then.
2031 #define NR_KMEM_CACHE_CPU 100
2033 static DEFINE_PER_CPU(struct kmem_cache_cpu,
2034 kmem_cache_cpu)[NR_KMEM_CACHE_CPU];
2036 static DEFINE_PER_CPU(struct kmem_cache_cpu *, kmem_cache_cpu_free);
2037 static cpumask_t kmem_cach_cpu_free_init_once = CPU_MASK_NONE;
2039 static struct kmem_cache_cpu *alloc_kmem_cache_cpu(struct kmem_cache *s,
2040 int cpu, gfp_t flags)
2042 struct kmem_cache_cpu *c = per_cpu(kmem_cache_cpu_free, cpu);
2044 if (c)
2045 per_cpu(kmem_cache_cpu_free, cpu) =
2046 (void *)c->freelist;
2047 else {
2048 /* Table overflow: So allocate ourselves */
2049 c = kmalloc_node(
2050 ALIGN(sizeof(struct kmem_cache_cpu), cache_line_size()),
2051 flags, cpu_to_node(cpu));
2052 if (!c)
2053 return NULL;
2056 init_kmem_cache_cpu(s, c);
2057 return c;
2060 static void free_kmem_cache_cpu(struct kmem_cache_cpu *c, int cpu)
2062 if (c < per_cpu(kmem_cache_cpu, cpu) ||
2063 c > per_cpu(kmem_cache_cpu, cpu) + NR_KMEM_CACHE_CPU) {
2064 kfree(c);
2065 return;
2067 c->freelist = (void *)per_cpu(kmem_cache_cpu_free, cpu);
2068 per_cpu(kmem_cache_cpu_free, cpu) = c;
2071 static void free_kmem_cache_cpus(struct kmem_cache *s)
2073 int cpu;
2075 for_each_online_cpu(cpu) {
2076 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2078 if (c) {
2079 s->cpu_slab[cpu] = NULL;
2080 free_kmem_cache_cpu(c, cpu);
2085 static int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2087 int cpu;
2089 for_each_online_cpu(cpu) {
2090 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2092 if (c)
2093 continue;
2095 c = alloc_kmem_cache_cpu(s, cpu, flags);
2096 if (!c) {
2097 free_kmem_cache_cpus(s);
2098 return 0;
2100 s->cpu_slab[cpu] = c;
2102 return 1;
2106 * Initialize the per cpu array.
2108 static void init_alloc_cpu_cpu(int cpu)
2110 int i;
2112 if (cpu_isset(cpu, kmem_cach_cpu_free_init_once))
2113 return;
2115 for (i = NR_KMEM_CACHE_CPU - 1; i >= 0; i--)
2116 free_kmem_cache_cpu(&per_cpu(kmem_cache_cpu, cpu)[i], cpu);
2118 cpu_set(cpu, kmem_cach_cpu_free_init_once);
2121 static void __init init_alloc_cpu(void)
2123 int cpu;
2125 for_each_online_cpu(cpu)
2126 init_alloc_cpu_cpu(cpu);
2129 #else
2130 static inline void free_kmem_cache_cpus(struct kmem_cache *s) {}
2131 static inline void init_alloc_cpu(void) {}
2133 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2135 init_kmem_cache_cpu(s, &s->cpu_slab);
2136 return 1;
2138 #endif
2140 #ifdef CONFIG_NUMA
2142 * No kmalloc_node yet so do it by hand. We know that this is the first
2143 * slab on the node for this slabcache. There are no concurrent accesses
2144 * possible.
2146 * Note that this function only works on the kmalloc_node_cache
2147 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2148 * memory on a fresh node that has no slab structures yet.
2150 static struct kmem_cache_node *early_kmem_cache_node_alloc(gfp_t gfpflags,
2151 int node)
2153 struct page *page;
2154 struct kmem_cache_node *n;
2155 unsigned long flags;
2157 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
2159 page = new_slab(kmalloc_caches, gfpflags, node);
2161 BUG_ON(!page);
2162 if (page_to_nid(page) != node) {
2163 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2164 "node %d\n", node);
2165 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2166 "in order to be able to continue\n");
2169 n = page->freelist;
2170 BUG_ON(!n);
2171 page->freelist = get_freepointer(kmalloc_caches, n);
2172 page->inuse++;
2173 kmalloc_caches->node[node] = n;
2174 #ifdef CONFIG_SLUB_DEBUG
2175 init_object(kmalloc_caches, n, 1);
2176 init_tracking(kmalloc_caches, n);
2177 #endif
2178 init_kmem_cache_node(n);
2179 atomic_long_inc(&n->nr_slabs);
2181 * lockdep requires consistent irq usage for each lock
2182 * so even though there cannot be a race this early in
2183 * the boot sequence, we still disable irqs.
2185 local_irq_save(flags);
2186 add_partial(n, page, 0);
2187 local_irq_restore(flags);
2188 return n;
2191 static void free_kmem_cache_nodes(struct kmem_cache *s)
2193 int node;
2195 for_each_node_state(node, N_NORMAL_MEMORY) {
2196 struct kmem_cache_node *n = s->node[node];
2197 if (n && n != &s->local_node)
2198 kmem_cache_free(kmalloc_caches, n);
2199 s->node[node] = NULL;
2203 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2205 int node;
2206 int local_node;
2208 if (slab_state >= UP)
2209 local_node = page_to_nid(virt_to_page(s));
2210 else
2211 local_node = 0;
2213 for_each_node_state(node, N_NORMAL_MEMORY) {
2214 struct kmem_cache_node *n;
2216 if (local_node == node)
2217 n = &s->local_node;
2218 else {
2219 if (slab_state == DOWN) {
2220 n = early_kmem_cache_node_alloc(gfpflags,
2221 node);
2222 continue;
2224 n = kmem_cache_alloc_node(kmalloc_caches,
2225 gfpflags, node);
2227 if (!n) {
2228 free_kmem_cache_nodes(s);
2229 return 0;
2233 s->node[node] = n;
2234 init_kmem_cache_node(n);
2236 return 1;
2238 #else
2239 static void free_kmem_cache_nodes(struct kmem_cache *s)
2243 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2245 init_kmem_cache_node(&s->local_node);
2246 return 1;
2248 #endif
2251 * calculate_sizes() determines the order and the distribution of data within
2252 * a slab object.
2254 static int calculate_sizes(struct kmem_cache *s)
2256 unsigned long flags = s->flags;
2257 unsigned long size = s->objsize;
2258 unsigned long align = s->align;
2261 * Determine if we can poison the object itself. If the user of
2262 * the slab may touch the object after free or before allocation
2263 * then we should never poison the object itself.
2265 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2266 !s->ctor)
2267 s->flags |= __OBJECT_POISON;
2268 else
2269 s->flags &= ~__OBJECT_POISON;
2272 * Round up object size to the next word boundary. We can only
2273 * place the free pointer at word boundaries and this determines
2274 * the possible location of the free pointer.
2276 size = ALIGN(size, sizeof(void *));
2278 #ifdef CONFIG_SLUB_DEBUG
2280 * If we are Redzoning then check if there is some space between the
2281 * end of the object and the free pointer. If not then add an
2282 * additional word to have some bytes to store Redzone information.
2284 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2285 size += sizeof(void *);
2286 #endif
2289 * With that we have determined the number of bytes in actual use
2290 * by the object. This is the potential offset to the free pointer.
2292 s->inuse = size;
2294 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2295 s->ctor)) {
2297 * Relocate free pointer after the object if it is not
2298 * permitted to overwrite the first word of the object on
2299 * kmem_cache_free.
2301 * This is the case if we do RCU, have a constructor or
2302 * destructor or are poisoning the objects.
2304 s->offset = size;
2305 size += sizeof(void *);
2308 #ifdef CONFIG_SLUB_DEBUG
2309 if (flags & SLAB_STORE_USER)
2311 * Need to store information about allocs and frees after
2312 * the object.
2314 size += 2 * sizeof(struct track);
2316 if (flags & SLAB_RED_ZONE)
2318 * Add some empty padding so that we can catch
2319 * overwrites from earlier objects rather than let
2320 * tracking information or the free pointer be
2321 * corrupted if an user writes before the start
2322 * of the object.
2324 size += sizeof(void *);
2325 #endif
2328 * Determine the alignment based on various parameters that the
2329 * user specified and the dynamic determination of cache line size
2330 * on bootup.
2332 align = calculate_alignment(flags, align, s->objsize);
2335 * SLUB stores one object immediately after another beginning from
2336 * offset 0. In order to align the objects we have to simply size
2337 * each object to conform to the alignment.
2339 size = ALIGN(size, align);
2340 s->size = size;
2342 if ((flags & __KMALLOC_CACHE) &&
2343 PAGE_SIZE / size < slub_min_objects) {
2345 * Kmalloc cache that would not have enough objects in
2346 * an order 0 page. Kmalloc slabs can fallback to
2347 * page allocator order 0 allocs so take a reasonably large
2348 * order that will allows us a good number of objects.
2350 s->order = max(slub_max_order, PAGE_ALLOC_COSTLY_ORDER);
2351 s->flags |= __PAGE_ALLOC_FALLBACK;
2352 s->allocflags |= __GFP_NOWARN;
2353 } else
2354 s->order = calculate_order(size);
2356 if (s->order < 0)
2357 return 0;
2359 s->allocflags = 0;
2360 if (s->order)
2361 s->allocflags |= __GFP_COMP;
2363 if (s->flags & SLAB_CACHE_DMA)
2364 s->allocflags |= SLUB_DMA;
2366 if (s->flags & SLAB_RECLAIM_ACCOUNT)
2367 s->allocflags |= __GFP_RECLAIMABLE;
2370 * Determine the number of objects per slab
2372 s->objects = (PAGE_SIZE << s->order) / size;
2374 return !!s->objects;
2378 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2379 const char *name, size_t size,
2380 size_t align, unsigned long flags,
2381 void (*ctor)(struct kmem_cache *, void *))
2383 memset(s, 0, kmem_size);
2384 s->name = name;
2385 s->ctor = ctor;
2386 s->objsize = size;
2387 s->align = align;
2388 s->flags = kmem_cache_flags(size, flags, name, ctor);
2390 if (!calculate_sizes(s))
2391 goto error;
2393 s->refcount = 1;
2394 #ifdef CONFIG_NUMA
2395 s->remote_node_defrag_ratio = 100;
2396 #endif
2397 if (!init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2398 goto error;
2400 if (alloc_kmem_cache_cpus(s, gfpflags & ~SLUB_DMA))
2401 return 1;
2402 free_kmem_cache_nodes(s);
2403 error:
2404 if (flags & SLAB_PANIC)
2405 panic("Cannot create slab %s size=%lu realsize=%u "
2406 "order=%u offset=%u flags=%lx\n",
2407 s->name, (unsigned long)size, s->size, s->order,
2408 s->offset, flags);
2409 return 0;
2413 * Check if a given pointer is valid
2415 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2417 struct page *page;
2419 page = get_object_page(object);
2421 if (!page || s != page->slab)
2422 /* No slab or wrong slab */
2423 return 0;
2425 if (!check_valid_pointer(s, page, object))
2426 return 0;
2429 * We could also check if the object is on the slabs freelist.
2430 * But this would be too expensive and it seems that the main
2431 * purpose of kmem_ptr_valid is to check if the object belongs
2432 * to a certain slab.
2434 return 1;
2436 EXPORT_SYMBOL(kmem_ptr_validate);
2439 * Determine the size of a slab object
2441 unsigned int kmem_cache_size(struct kmem_cache *s)
2443 return s->objsize;
2445 EXPORT_SYMBOL(kmem_cache_size);
2447 const char *kmem_cache_name(struct kmem_cache *s)
2449 return s->name;
2451 EXPORT_SYMBOL(kmem_cache_name);
2454 * Attempt to free all slabs on a node. Return the number of slabs we
2455 * were unable to free.
2457 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2458 struct list_head *list)
2460 int slabs_inuse = 0;
2461 unsigned long flags;
2462 struct page *page, *h;
2464 spin_lock_irqsave(&n->list_lock, flags);
2465 list_for_each_entry_safe(page, h, list, lru)
2466 if (!page->inuse) {
2467 list_del(&page->lru);
2468 discard_slab(s, page);
2469 } else
2470 slabs_inuse++;
2471 spin_unlock_irqrestore(&n->list_lock, flags);
2472 return slabs_inuse;
2476 * Release all resources used by a slab cache.
2478 static inline int kmem_cache_close(struct kmem_cache *s)
2480 int node;
2482 flush_all(s);
2484 /* Attempt to free all objects */
2485 free_kmem_cache_cpus(s);
2486 for_each_node_state(node, N_NORMAL_MEMORY) {
2487 struct kmem_cache_node *n = get_node(s, node);
2489 n->nr_partial -= free_list(s, n, &n->partial);
2490 if (atomic_long_read(&n->nr_slabs))
2491 return 1;
2493 free_kmem_cache_nodes(s);
2494 return 0;
2498 * Close a cache and release the kmem_cache structure
2499 * (must be used for caches created using kmem_cache_create)
2501 void kmem_cache_destroy(struct kmem_cache *s)
2503 down_write(&slub_lock);
2504 s->refcount--;
2505 if (!s->refcount) {
2506 list_del(&s->list);
2507 up_write(&slub_lock);
2508 if (kmem_cache_close(s))
2509 WARN_ON(1);
2510 sysfs_slab_remove(s);
2511 } else
2512 up_write(&slub_lock);
2514 EXPORT_SYMBOL(kmem_cache_destroy);
2516 /********************************************************************
2517 * Kmalloc subsystem
2518 *******************************************************************/
2520 struct kmem_cache kmalloc_caches[PAGE_SHIFT + 1] __cacheline_aligned;
2521 EXPORT_SYMBOL(kmalloc_caches);
2523 #ifdef CONFIG_ZONE_DMA
2524 static struct kmem_cache *kmalloc_caches_dma[PAGE_SHIFT + 1];
2525 #endif
2527 static int __init setup_slub_min_order(char *str)
2529 get_option(&str, &slub_min_order);
2531 return 1;
2534 __setup("slub_min_order=", setup_slub_min_order);
2536 static int __init setup_slub_max_order(char *str)
2538 get_option(&str, &slub_max_order);
2540 return 1;
2543 __setup("slub_max_order=", setup_slub_max_order);
2545 static int __init setup_slub_min_objects(char *str)
2547 get_option(&str, &slub_min_objects);
2549 return 1;
2552 __setup("slub_min_objects=", setup_slub_min_objects);
2554 static int __init setup_slub_nomerge(char *str)
2556 slub_nomerge = 1;
2557 return 1;
2560 __setup("slub_nomerge", setup_slub_nomerge);
2562 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2563 const char *name, int size, gfp_t gfp_flags)
2565 unsigned int flags = 0;
2567 if (gfp_flags & SLUB_DMA)
2568 flags = SLAB_CACHE_DMA;
2570 down_write(&slub_lock);
2571 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2572 flags | __KMALLOC_CACHE, NULL))
2573 goto panic;
2575 list_add(&s->list, &slab_caches);
2576 up_write(&slub_lock);
2577 if (sysfs_slab_add(s))
2578 goto panic;
2579 return s;
2581 panic:
2582 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2585 #ifdef CONFIG_ZONE_DMA
2587 static void sysfs_add_func(struct work_struct *w)
2589 struct kmem_cache *s;
2591 down_write(&slub_lock);
2592 list_for_each_entry(s, &slab_caches, list) {
2593 if (s->flags & __SYSFS_ADD_DEFERRED) {
2594 s->flags &= ~__SYSFS_ADD_DEFERRED;
2595 sysfs_slab_add(s);
2598 up_write(&slub_lock);
2601 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2603 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2605 struct kmem_cache *s;
2606 char *text;
2607 size_t realsize;
2609 s = kmalloc_caches_dma[index];
2610 if (s)
2611 return s;
2613 /* Dynamically create dma cache */
2614 if (flags & __GFP_WAIT)
2615 down_write(&slub_lock);
2616 else {
2617 if (!down_write_trylock(&slub_lock))
2618 goto out;
2621 if (kmalloc_caches_dma[index])
2622 goto unlock_out;
2624 realsize = kmalloc_caches[index].objsize;
2625 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2626 (unsigned int)realsize);
2627 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2629 if (!s || !text || !kmem_cache_open(s, flags, text,
2630 realsize, ARCH_KMALLOC_MINALIGN,
2631 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2632 kfree(s);
2633 kfree(text);
2634 goto unlock_out;
2637 list_add(&s->list, &slab_caches);
2638 kmalloc_caches_dma[index] = s;
2640 schedule_work(&sysfs_add_work);
2642 unlock_out:
2643 up_write(&slub_lock);
2644 out:
2645 return kmalloc_caches_dma[index];
2647 #endif
2650 * Conversion table for small slabs sizes / 8 to the index in the
2651 * kmalloc array. This is necessary for slabs < 192 since we have non power
2652 * of two cache sizes there. The size of larger slabs can be determined using
2653 * fls.
2655 static s8 size_index[24] = {
2656 3, /* 8 */
2657 4, /* 16 */
2658 5, /* 24 */
2659 5, /* 32 */
2660 6, /* 40 */
2661 6, /* 48 */
2662 6, /* 56 */
2663 6, /* 64 */
2664 1, /* 72 */
2665 1, /* 80 */
2666 1, /* 88 */
2667 1, /* 96 */
2668 7, /* 104 */
2669 7, /* 112 */
2670 7, /* 120 */
2671 7, /* 128 */
2672 2, /* 136 */
2673 2, /* 144 */
2674 2, /* 152 */
2675 2, /* 160 */
2676 2, /* 168 */
2677 2, /* 176 */
2678 2, /* 184 */
2679 2 /* 192 */
2682 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2684 int index;
2686 if (size <= 192) {
2687 if (!size)
2688 return ZERO_SIZE_PTR;
2690 index = size_index[(size - 1) / 8];
2691 } else
2692 index = fls(size - 1);
2694 #ifdef CONFIG_ZONE_DMA
2695 if (unlikely((flags & SLUB_DMA)))
2696 return dma_kmalloc_cache(index, flags);
2698 #endif
2699 return &kmalloc_caches[index];
2702 void *__kmalloc(size_t size, gfp_t flags)
2704 struct kmem_cache *s;
2706 if (unlikely(size > PAGE_SIZE))
2707 return kmalloc_large(size, flags);
2709 s = get_slab(size, flags);
2711 if (unlikely(ZERO_OR_NULL_PTR(s)))
2712 return s;
2714 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2716 EXPORT_SYMBOL(__kmalloc);
2718 #ifdef CONFIG_NUMA
2719 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2721 struct kmem_cache *s;
2723 if (unlikely(size > PAGE_SIZE))
2724 return kmalloc_large(size, flags);
2726 s = get_slab(size, flags);
2728 if (unlikely(ZERO_OR_NULL_PTR(s)))
2729 return s;
2731 return slab_alloc(s, flags, node, __builtin_return_address(0));
2733 EXPORT_SYMBOL(__kmalloc_node);
2734 #endif
2736 size_t ksize(const void *object)
2738 struct page *page;
2739 struct kmem_cache *s;
2741 BUG_ON(!object);
2742 if (unlikely(object == ZERO_SIZE_PTR))
2743 return 0;
2745 page = virt_to_head_page(object);
2746 BUG_ON(!page);
2748 if (unlikely(!PageSlab(page)))
2749 return PAGE_SIZE << compound_order(page);
2751 s = page->slab;
2752 BUG_ON(!s);
2755 * Debugging requires use of the padding between object
2756 * and whatever may come after it.
2758 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2759 return s->objsize;
2762 * If we have the need to store the freelist pointer
2763 * back there or track user information then we can
2764 * only use the space before that information.
2766 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2767 return s->inuse;
2770 * Else we can use all the padding etc for the allocation
2772 return s->size;
2774 EXPORT_SYMBOL(ksize);
2776 void kfree(const void *x)
2778 struct page *page;
2779 void *object = (void *)x;
2781 if (unlikely(ZERO_OR_NULL_PTR(x)))
2782 return;
2784 page = virt_to_head_page(x);
2785 if (unlikely(!PageSlab(page))) {
2786 put_page(page);
2787 return;
2789 slab_free(page->slab, page, object, __builtin_return_address(0));
2791 EXPORT_SYMBOL(kfree);
2793 static unsigned long count_partial(struct kmem_cache_node *n)
2795 unsigned long flags;
2796 unsigned long x = 0;
2797 struct page *page;
2799 spin_lock_irqsave(&n->list_lock, flags);
2800 list_for_each_entry(page, &n->partial, lru)
2801 x += page->inuse;
2802 spin_unlock_irqrestore(&n->list_lock, flags);
2803 return x;
2807 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2808 * the remaining slabs by the number of items in use. The slabs with the
2809 * most items in use come first. New allocations will then fill those up
2810 * and thus they can be removed from the partial lists.
2812 * The slabs with the least items are placed last. This results in them
2813 * being allocated from last increasing the chance that the last objects
2814 * are freed in them.
2816 int kmem_cache_shrink(struct kmem_cache *s)
2818 int node;
2819 int i;
2820 struct kmem_cache_node *n;
2821 struct page *page;
2822 struct page *t;
2823 struct list_head *slabs_by_inuse =
2824 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2825 unsigned long flags;
2827 if (!slabs_by_inuse)
2828 return -ENOMEM;
2830 flush_all(s);
2831 for_each_node_state(node, N_NORMAL_MEMORY) {
2832 n = get_node(s, node);
2834 if (!n->nr_partial)
2835 continue;
2837 for (i = 0; i < s->objects; i++)
2838 INIT_LIST_HEAD(slabs_by_inuse + i);
2840 spin_lock_irqsave(&n->list_lock, flags);
2843 * Build lists indexed by the items in use in each slab.
2845 * Note that concurrent frees may occur while we hold the
2846 * list_lock. page->inuse here is the upper limit.
2848 list_for_each_entry_safe(page, t, &n->partial, lru) {
2849 if (!page->inuse && slab_trylock(page)) {
2851 * Must hold slab lock here because slab_free
2852 * may have freed the last object and be
2853 * waiting to release the slab.
2855 list_del(&page->lru);
2856 n->nr_partial--;
2857 slab_unlock(page);
2858 discard_slab(s, page);
2859 } else {
2860 list_move(&page->lru,
2861 slabs_by_inuse + page->inuse);
2866 * Rebuild the partial list with the slabs filled up most
2867 * first and the least used slabs at the end.
2869 for (i = s->objects - 1; i >= 0; i--)
2870 list_splice(slabs_by_inuse + i, n->partial.prev);
2872 spin_unlock_irqrestore(&n->list_lock, flags);
2875 kfree(slabs_by_inuse);
2876 return 0;
2878 EXPORT_SYMBOL(kmem_cache_shrink);
2880 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
2881 static int slab_mem_going_offline_callback(void *arg)
2883 struct kmem_cache *s;
2885 down_read(&slub_lock);
2886 list_for_each_entry(s, &slab_caches, list)
2887 kmem_cache_shrink(s);
2888 up_read(&slub_lock);
2890 return 0;
2893 static void slab_mem_offline_callback(void *arg)
2895 struct kmem_cache_node *n;
2896 struct kmem_cache *s;
2897 struct memory_notify *marg = arg;
2898 int offline_node;
2900 offline_node = marg->status_change_nid;
2903 * If the node still has available memory. we need kmem_cache_node
2904 * for it yet.
2906 if (offline_node < 0)
2907 return;
2909 down_read(&slub_lock);
2910 list_for_each_entry(s, &slab_caches, list) {
2911 n = get_node(s, offline_node);
2912 if (n) {
2914 * if n->nr_slabs > 0, slabs still exist on the node
2915 * that is going down. We were unable to free them,
2916 * and offline_pages() function shoudn't call this
2917 * callback. So, we must fail.
2919 BUG_ON(atomic_long_read(&n->nr_slabs));
2921 s->node[offline_node] = NULL;
2922 kmem_cache_free(kmalloc_caches, n);
2925 up_read(&slub_lock);
2928 static int slab_mem_going_online_callback(void *arg)
2930 struct kmem_cache_node *n;
2931 struct kmem_cache *s;
2932 struct memory_notify *marg = arg;
2933 int nid = marg->status_change_nid;
2934 int ret = 0;
2937 * If the node's memory is already available, then kmem_cache_node is
2938 * already created. Nothing to do.
2940 if (nid < 0)
2941 return 0;
2944 * We are bringing a node online. No memory is availabe yet. We must
2945 * allocate a kmem_cache_node structure in order to bring the node
2946 * online.
2948 down_read(&slub_lock);
2949 list_for_each_entry(s, &slab_caches, list) {
2951 * XXX: kmem_cache_alloc_node will fallback to other nodes
2952 * since memory is not yet available from the node that
2953 * is brought up.
2955 n = kmem_cache_alloc(kmalloc_caches, GFP_KERNEL);
2956 if (!n) {
2957 ret = -ENOMEM;
2958 goto out;
2960 init_kmem_cache_node(n);
2961 s->node[nid] = n;
2963 out:
2964 up_read(&slub_lock);
2965 return ret;
2968 static int slab_memory_callback(struct notifier_block *self,
2969 unsigned long action, void *arg)
2971 int ret = 0;
2973 switch (action) {
2974 case MEM_GOING_ONLINE:
2975 ret = slab_mem_going_online_callback(arg);
2976 break;
2977 case MEM_GOING_OFFLINE:
2978 ret = slab_mem_going_offline_callback(arg);
2979 break;
2980 case MEM_OFFLINE:
2981 case MEM_CANCEL_ONLINE:
2982 slab_mem_offline_callback(arg);
2983 break;
2984 case MEM_ONLINE:
2985 case MEM_CANCEL_OFFLINE:
2986 break;
2989 ret = notifier_from_errno(ret);
2990 return ret;
2993 #endif /* CONFIG_MEMORY_HOTPLUG */
2995 /********************************************************************
2996 * Basic setup of slabs
2997 *******************************************************************/
2999 void __init kmem_cache_init(void)
3001 int i;
3002 int caches = 0;
3004 init_alloc_cpu();
3006 #ifdef CONFIG_NUMA
3008 * Must first have the slab cache available for the allocations of the
3009 * struct kmem_cache_node's. There is special bootstrap code in
3010 * kmem_cache_open for slab_state == DOWN.
3012 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
3013 sizeof(struct kmem_cache_node), GFP_KERNEL);
3014 kmalloc_caches[0].refcount = -1;
3015 caches++;
3017 hotplug_memory_notifier(slab_memory_callback, 1);
3018 #endif
3020 /* Able to allocate the per node structures */
3021 slab_state = PARTIAL;
3023 /* Caches that are not of the two-to-the-power-of size */
3024 if (KMALLOC_MIN_SIZE <= 64) {
3025 create_kmalloc_cache(&kmalloc_caches[1],
3026 "kmalloc-96", 96, GFP_KERNEL);
3027 caches++;
3029 if (KMALLOC_MIN_SIZE <= 128) {
3030 create_kmalloc_cache(&kmalloc_caches[2],
3031 "kmalloc-192", 192, GFP_KERNEL);
3032 caches++;
3035 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++) {
3036 create_kmalloc_cache(&kmalloc_caches[i],
3037 "kmalloc", 1 << i, GFP_KERNEL);
3038 caches++;
3043 * Patch up the size_index table if we have strange large alignment
3044 * requirements for the kmalloc array. This is only the case for
3045 * mips it seems. The standard arches will not generate any code here.
3047 * Largest permitted alignment is 256 bytes due to the way we
3048 * handle the index determination for the smaller caches.
3050 * Make sure that nothing crazy happens if someone starts tinkering
3051 * around with ARCH_KMALLOC_MINALIGN
3053 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
3054 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
3056 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
3057 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
3059 slab_state = UP;
3061 /* Provide the correct kmalloc names now that the caches are up */
3062 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++)
3063 kmalloc_caches[i]. name =
3064 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
3066 #ifdef CONFIG_SMP
3067 register_cpu_notifier(&slab_notifier);
3068 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
3069 nr_cpu_ids * sizeof(struct kmem_cache_cpu *);
3070 #else
3071 kmem_size = sizeof(struct kmem_cache);
3072 #endif
3075 printk(KERN_INFO
3076 "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
3077 " CPUs=%d, Nodes=%d\n",
3078 caches, cache_line_size(),
3079 slub_min_order, slub_max_order, slub_min_objects,
3080 nr_cpu_ids, nr_node_ids);
3084 * Find a mergeable slab cache
3086 static int slab_unmergeable(struct kmem_cache *s)
3088 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
3089 return 1;
3091 if ((s->flags & __PAGE_ALLOC_FALLBACK))
3092 return 1;
3094 if (s->ctor)
3095 return 1;
3098 * We may have set a slab to be unmergeable during bootstrap.
3100 if (s->refcount < 0)
3101 return 1;
3103 return 0;
3106 static struct kmem_cache *find_mergeable(size_t size,
3107 size_t align, unsigned long flags, const char *name,
3108 void (*ctor)(struct kmem_cache *, void *))
3110 struct kmem_cache *s;
3112 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
3113 return NULL;
3115 if (ctor)
3116 return NULL;
3118 size = ALIGN(size, sizeof(void *));
3119 align = calculate_alignment(flags, align, size);
3120 size = ALIGN(size, align);
3121 flags = kmem_cache_flags(size, flags, name, NULL);
3123 list_for_each_entry(s, &slab_caches, list) {
3124 if (slab_unmergeable(s))
3125 continue;
3127 if (size > s->size)
3128 continue;
3130 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
3131 continue;
3133 * Check if alignment is compatible.
3134 * Courtesy of Adrian Drzewiecki
3136 if ((s->size & ~(align - 1)) != s->size)
3137 continue;
3139 if (s->size - size >= sizeof(void *))
3140 continue;
3142 return s;
3144 return NULL;
3147 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
3148 size_t align, unsigned long flags,
3149 void (*ctor)(struct kmem_cache *, void *))
3151 struct kmem_cache *s;
3153 down_write(&slub_lock);
3154 s = find_mergeable(size, align, flags, name, ctor);
3155 if (s) {
3156 int cpu;
3158 s->refcount++;
3160 * Adjust the object sizes so that we clear
3161 * the complete object on kzalloc.
3163 s->objsize = max(s->objsize, (int)size);
3166 * And then we need to update the object size in the
3167 * per cpu structures
3169 for_each_online_cpu(cpu)
3170 get_cpu_slab(s, cpu)->objsize = s->objsize;
3171 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
3172 up_write(&slub_lock);
3173 if (sysfs_slab_alias(s, name))
3174 goto err;
3175 return s;
3177 s = kmalloc(kmem_size, GFP_KERNEL);
3178 if (s) {
3179 if (kmem_cache_open(s, GFP_KERNEL, name,
3180 size, align, flags, ctor)) {
3181 list_add(&s->list, &slab_caches);
3182 up_write(&slub_lock);
3183 if (sysfs_slab_add(s))
3184 goto err;
3185 return s;
3187 kfree(s);
3189 up_write(&slub_lock);
3191 err:
3192 if (flags & SLAB_PANIC)
3193 panic("Cannot create slabcache %s\n", name);
3194 else
3195 s = NULL;
3196 return s;
3198 EXPORT_SYMBOL(kmem_cache_create);
3200 #ifdef CONFIG_SMP
3202 * Use the cpu notifier to insure that the cpu slabs are flushed when
3203 * necessary.
3205 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
3206 unsigned long action, void *hcpu)
3208 long cpu = (long)hcpu;
3209 struct kmem_cache *s;
3210 unsigned long flags;
3212 switch (action) {
3213 case CPU_UP_PREPARE:
3214 case CPU_UP_PREPARE_FROZEN:
3215 init_alloc_cpu_cpu(cpu);
3216 down_read(&slub_lock);
3217 list_for_each_entry(s, &slab_caches, list)
3218 s->cpu_slab[cpu] = alloc_kmem_cache_cpu(s, cpu,
3219 GFP_KERNEL);
3220 up_read(&slub_lock);
3221 break;
3223 case CPU_UP_CANCELED:
3224 case CPU_UP_CANCELED_FROZEN:
3225 case CPU_DEAD:
3226 case CPU_DEAD_FROZEN:
3227 down_read(&slub_lock);
3228 list_for_each_entry(s, &slab_caches, list) {
3229 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3231 local_irq_save(flags);
3232 __flush_cpu_slab(s, cpu);
3233 local_irq_restore(flags);
3234 free_kmem_cache_cpu(c, cpu);
3235 s->cpu_slab[cpu] = NULL;
3237 up_read(&slub_lock);
3238 break;
3239 default:
3240 break;
3242 return NOTIFY_OK;
3245 static struct notifier_block __cpuinitdata slab_notifier = {
3246 .notifier_call = slab_cpuup_callback
3249 #endif
3251 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
3253 struct kmem_cache *s;
3255 if (unlikely(size > PAGE_SIZE))
3256 return kmalloc_large(size, gfpflags);
3258 s = get_slab(size, gfpflags);
3260 if (unlikely(ZERO_OR_NULL_PTR(s)))
3261 return s;
3263 return slab_alloc(s, gfpflags, -1, caller);
3266 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
3267 int node, void *caller)
3269 struct kmem_cache *s;
3271 if (unlikely(size > PAGE_SIZE))
3272 return kmalloc_large(size, gfpflags);
3274 s = get_slab(size, gfpflags);
3276 if (unlikely(ZERO_OR_NULL_PTR(s)))
3277 return s;
3279 return slab_alloc(s, gfpflags, node, caller);
3282 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
3283 static int validate_slab(struct kmem_cache *s, struct page *page,
3284 unsigned long *map)
3286 void *p;
3287 void *addr = slab_address(page);
3289 if (!check_slab(s, page) ||
3290 !on_freelist(s, page, NULL))
3291 return 0;
3293 /* Now we know that a valid freelist exists */
3294 bitmap_zero(map, s->objects);
3296 for_each_free_object(p, s, page->freelist) {
3297 set_bit(slab_index(p, s, addr), map);
3298 if (!check_object(s, page, p, 0))
3299 return 0;
3302 for_each_object(p, s, addr)
3303 if (!test_bit(slab_index(p, s, addr), map))
3304 if (!check_object(s, page, p, 1))
3305 return 0;
3306 return 1;
3309 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
3310 unsigned long *map)
3312 if (slab_trylock(page)) {
3313 validate_slab(s, page, map);
3314 slab_unlock(page);
3315 } else
3316 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
3317 s->name, page);
3319 if (s->flags & DEBUG_DEFAULT_FLAGS) {
3320 if (!SlabDebug(page))
3321 printk(KERN_ERR "SLUB %s: SlabDebug not set "
3322 "on slab 0x%p\n", s->name, page);
3323 } else {
3324 if (SlabDebug(page))
3325 printk(KERN_ERR "SLUB %s: SlabDebug set on "
3326 "slab 0x%p\n", s->name, page);
3330 static int validate_slab_node(struct kmem_cache *s,
3331 struct kmem_cache_node *n, unsigned long *map)
3333 unsigned long count = 0;
3334 struct page *page;
3335 unsigned long flags;
3337 spin_lock_irqsave(&n->list_lock, flags);
3339 list_for_each_entry(page, &n->partial, lru) {
3340 validate_slab_slab(s, page, map);
3341 count++;
3343 if (count != n->nr_partial)
3344 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
3345 "counter=%ld\n", s->name, count, n->nr_partial);
3347 if (!(s->flags & SLAB_STORE_USER))
3348 goto out;
3350 list_for_each_entry(page, &n->full, lru) {
3351 validate_slab_slab(s, page, map);
3352 count++;
3354 if (count != atomic_long_read(&n->nr_slabs))
3355 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
3356 "counter=%ld\n", s->name, count,
3357 atomic_long_read(&n->nr_slabs));
3359 out:
3360 spin_unlock_irqrestore(&n->list_lock, flags);
3361 return count;
3364 static long validate_slab_cache(struct kmem_cache *s)
3366 int node;
3367 unsigned long count = 0;
3368 unsigned long *map = kmalloc(BITS_TO_LONGS(s->objects) *
3369 sizeof(unsigned long), GFP_KERNEL);
3371 if (!map)
3372 return -ENOMEM;
3374 flush_all(s);
3375 for_each_node_state(node, N_NORMAL_MEMORY) {
3376 struct kmem_cache_node *n = get_node(s, node);
3378 count += validate_slab_node(s, n, map);
3380 kfree(map);
3381 return count;
3384 #ifdef SLUB_RESILIENCY_TEST
3385 static void resiliency_test(void)
3387 u8 *p;
3389 printk(KERN_ERR "SLUB resiliency testing\n");
3390 printk(KERN_ERR "-----------------------\n");
3391 printk(KERN_ERR "A. Corruption after allocation\n");
3393 p = kzalloc(16, GFP_KERNEL);
3394 p[16] = 0x12;
3395 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
3396 " 0x12->0x%p\n\n", p + 16);
3398 validate_slab_cache(kmalloc_caches + 4);
3400 /* Hmmm... The next two are dangerous */
3401 p = kzalloc(32, GFP_KERNEL);
3402 p[32 + sizeof(void *)] = 0x34;
3403 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
3404 " 0x34 -> -0x%p\n", p);
3405 printk(KERN_ERR
3406 "If allocated object is overwritten then not detectable\n\n");
3408 validate_slab_cache(kmalloc_caches + 5);
3409 p = kzalloc(64, GFP_KERNEL);
3410 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
3411 *p = 0x56;
3412 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
3414 printk(KERN_ERR
3415 "If allocated object is overwritten then not detectable\n\n");
3416 validate_slab_cache(kmalloc_caches + 6);
3418 printk(KERN_ERR "\nB. Corruption after free\n");
3419 p = kzalloc(128, GFP_KERNEL);
3420 kfree(p);
3421 *p = 0x78;
3422 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
3423 validate_slab_cache(kmalloc_caches + 7);
3425 p = kzalloc(256, GFP_KERNEL);
3426 kfree(p);
3427 p[50] = 0x9a;
3428 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n",
3430 validate_slab_cache(kmalloc_caches + 8);
3432 p = kzalloc(512, GFP_KERNEL);
3433 kfree(p);
3434 p[512] = 0xab;
3435 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
3436 validate_slab_cache(kmalloc_caches + 9);
3438 #else
3439 static void resiliency_test(void) {};
3440 #endif
3443 * Generate lists of code addresses where slabcache objects are allocated
3444 * and freed.
3447 struct location {
3448 unsigned long count;
3449 void *addr;
3450 long long sum_time;
3451 long min_time;
3452 long max_time;
3453 long min_pid;
3454 long max_pid;
3455 cpumask_t cpus;
3456 nodemask_t nodes;
3459 struct loc_track {
3460 unsigned long max;
3461 unsigned long count;
3462 struct location *loc;
3465 static void free_loc_track(struct loc_track *t)
3467 if (t->max)
3468 free_pages((unsigned long)t->loc,
3469 get_order(sizeof(struct location) * t->max));
3472 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3474 struct location *l;
3475 int order;
3477 order = get_order(sizeof(struct location) * max);
3479 l = (void *)__get_free_pages(flags, order);
3480 if (!l)
3481 return 0;
3483 if (t->count) {
3484 memcpy(l, t->loc, sizeof(struct location) * t->count);
3485 free_loc_track(t);
3487 t->max = max;
3488 t->loc = l;
3489 return 1;
3492 static int add_location(struct loc_track *t, struct kmem_cache *s,
3493 const struct track *track)
3495 long start, end, pos;
3496 struct location *l;
3497 void *caddr;
3498 unsigned long age = jiffies - track->when;
3500 start = -1;
3501 end = t->count;
3503 for ( ; ; ) {
3504 pos = start + (end - start + 1) / 2;
3507 * There is nothing at "end". If we end up there
3508 * we need to add something to before end.
3510 if (pos == end)
3511 break;
3513 caddr = t->loc[pos].addr;
3514 if (track->addr == caddr) {
3516 l = &t->loc[pos];
3517 l->count++;
3518 if (track->when) {
3519 l->sum_time += age;
3520 if (age < l->min_time)
3521 l->min_time = age;
3522 if (age > l->max_time)
3523 l->max_time = age;
3525 if (track->pid < l->min_pid)
3526 l->min_pid = track->pid;
3527 if (track->pid > l->max_pid)
3528 l->max_pid = track->pid;
3530 cpu_set(track->cpu, l->cpus);
3532 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3533 return 1;
3536 if (track->addr < caddr)
3537 end = pos;
3538 else
3539 start = pos;
3543 * Not found. Insert new tracking element.
3545 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3546 return 0;
3548 l = t->loc + pos;
3549 if (pos < t->count)
3550 memmove(l + 1, l,
3551 (t->count - pos) * sizeof(struct location));
3552 t->count++;
3553 l->count = 1;
3554 l->addr = track->addr;
3555 l->sum_time = age;
3556 l->min_time = age;
3557 l->max_time = age;
3558 l->min_pid = track->pid;
3559 l->max_pid = track->pid;
3560 cpus_clear(l->cpus);
3561 cpu_set(track->cpu, l->cpus);
3562 nodes_clear(l->nodes);
3563 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3564 return 1;
3567 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3568 struct page *page, enum track_item alloc)
3570 void *addr = slab_address(page);
3571 DECLARE_BITMAP(map, s->objects);
3572 void *p;
3574 bitmap_zero(map, s->objects);
3575 for_each_free_object(p, s, page->freelist)
3576 set_bit(slab_index(p, s, addr), map);
3578 for_each_object(p, s, addr)
3579 if (!test_bit(slab_index(p, s, addr), map))
3580 add_location(t, s, get_track(s, p, alloc));
3583 static int list_locations(struct kmem_cache *s, char *buf,
3584 enum track_item alloc)
3586 int len = 0;
3587 unsigned long i;
3588 struct loc_track t = { 0, 0, NULL };
3589 int node;
3591 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3592 GFP_TEMPORARY))
3593 return sprintf(buf, "Out of memory\n");
3595 /* Push back cpu slabs */
3596 flush_all(s);
3598 for_each_node_state(node, N_NORMAL_MEMORY) {
3599 struct kmem_cache_node *n = get_node(s, node);
3600 unsigned long flags;
3601 struct page *page;
3603 if (!atomic_long_read(&n->nr_slabs))
3604 continue;
3606 spin_lock_irqsave(&n->list_lock, flags);
3607 list_for_each_entry(page, &n->partial, lru)
3608 process_slab(&t, s, page, alloc);
3609 list_for_each_entry(page, &n->full, lru)
3610 process_slab(&t, s, page, alloc);
3611 spin_unlock_irqrestore(&n->list_lock, flags);
3614 for (i = 0; i < t.count; i++) {
3615 struct location *l = &t.loc[i];
3617 if (len > PAGE_SIZE - 100)
3618 break;
3619 len += sprintf(buf + len, "%7ld ", l->count);
3621 if (l->addr)
3622 len += sprint_symbol(buf + len, (unsigned long)l->addr);
3623 else
3624 len += sprintf(buf + len, "<not-available>");
3626 if (l->sum_time != l->min_time) {
3627 unsigned long remainder;
3629 len += sprintf(buf + len, " age=%ld/%ld/%ld",
3630 l->min_time,
3631 div_long_long_rem(l->sum_time, l->count, &remainder),
3632 l->max_time);
3633 } else
3634 len += sprintf(buf + len, " age=%ld",
3635 l->min_time);
3637 if (l->min_pid != l->max_pid)
3638 len += sprintf(buf + len, " pid=%ld-%ld",
3639 l->min_pid, l->max_pid);
3640 else
3641 len += sprintf(buf + len, " pid=%ld",
3642 l->min_pid);
3644 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3645 len < PAGE_SIZE - 60) {
3646 len += sprintf(buf + len, " cpus=");
3647 len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3648 l->cpus);
3651 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3652 len < PAGE_SIZE - 60) {
3653 len += sprintf(buf + len, " nodes=");
3654 len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3655 l->nodes);
3658 len += sprintf(buf + len, "\n");
3661 free_loc_track(&t);
3662 if (!t.count)
3663 len += sprintf(buf, "No data\n");
3664 return len;
3667 enum slab_stat_type {
3668 SL_FULL,
3669 SL_PARTIAL,
3670 SL_CPU,
3671 SL_OBJECTS
3674 #define SO_FULL (1 << SL_FULL)
3675 #define SO_PARTIAL (1 << SL_PARTIAL)
3676 #define SO_CPU (1 << SL_CPU)
3677 #define SO_OBJECTS (1 << SL_OBJECTS)
3679 static unsigned long slab_objects(struct kmem_cache *s,
3680 char *buf, unsigned long flags)
3682 unsigned long total = 0;
3683 int cpu;
3684 int node;
3685 int x;
3686 unsigned long *nodes;
3687 unsigned long *per_cpu;
3689 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3690 per_cpu = nodes + nr_node_ids;
3692 for_each_possible_cpu(cpu) {
3693 struct page *page;
3694 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3696 if (!c)
3697 continue;
3699 page = c->page;
3700 node = c->node;
3701 if (node < 0)
3702 continue;
3703 if (page) {
3704 if (flags & SO_CPU) {
3705 if (flags & SO_OBJECTS)
3706 x = page->inuse;
3707 else
3708 x = 1;
3709 total += x;
3710 nodes[node] += x;
3712 per_cpu[node]++;
3716 for_each_node_state(node, N_NORMAL_MEMORY) {
3717 struct kmem_cache_node *n = get_node(s, node);
3719 if (flags & SO_PARTIAL) {
3720 if (flags & SO_OBJECTS)
3721 x = count_partial(n);
3722 else
3723 x = n->nr_partial;
3724 total += x;
3725 nodes[node] += x;
3728 if (flags & SO_FULL) {
3729 int full_slabs = atomic_long_read(&n->nr_slabs)
3730 - per_cpu[node]
3731 - n->nr_partial;
3733 if (flags & SO_OBJECTS)
3734 x = full_slabs * s->objects;
3735 else
3736 x = full_slabs;
3737 total += x;
3738 nodes[node] += x;
3742 x = sprintf(buf, "%lu", total);
3743 #ifdef CONFIG_NUMA
3744 for_each_node_state(node, N_NORMAL_MEMORY)
3745 if (nodes[node])
3746 x += sprintf(buf + x, " N%d=%lu",
3747 node, nodes[node]);
3748 #endif
3749 kfree(nodes);
3750 return x + sprintf(buf + x, "\n");
3753 static int any_slab_objects(struct kmem_cache *s)
3755 int node;
3756 int cpu;
3758 for_each_possible_cpu(cpu) {
3759 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3761 if (c && c->page)
3762 return 1;
3765 for_each_online_node(node) {
3766 struct kmem_cache_node *n = get_node(s, node);
3768 if (!n)
3769 continue;
3771 if (n->nr_partial || atomic_long_read(&n->nr_slabs))
3772 return 1;
3774 return 0;
3777 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3778 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3780 struct slab_attribute {
3781 struct attribute attr;
3782 ssize_t (*show)(struct kmem_cache *s, char *buf);
3783 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3786 #define SLAB_ATTR_RO(_name) \
3787 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3789 #define SLAB_ATTR(_name) \
3790 static struct slab_attribute _name##_attr = \
3791 __ATTR(_name, 0644, _name##_show, _name##_store)
3793 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3795 return sprintf(buf, "%d\n", s->size);
3797 SLAB_ATTR_RO(slab_size);
3799 static ssize_t align_show(struct kmem_cache *s, char *buf)
3801 return sprintf(buf, "%d\n", s->align);
3803 SLAB_ATTR_RO(align);
3805 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3807 return sprintf(buf, "%d\n", s->objsize);
3809 SLAB_ATTR_RO(object_size);
3811 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3813 return sprintf(buf, "%d\n", s->objects);
3815 SLAB_ATTR_RO(objs_per_slab);
3817 static ssize_t order_show(struct kmem_cache *s, char *buf)
3819 return sprintf(buf, "%d\n", s->order);
3821 SLAB_ATTR_RO(order);
3823 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3825 if (s->ctor) {
3826 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3828 return n + sprintf(buf + n, "\n");
3830 return 0;
3832 SLAB_ATTR_RO(ctor);
3834 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3836 return sprintf(buf, "%d\n", s->refcount - 1);
3838 SLAB_ATTR_RO(aliases);
3840 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3842 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3844 SLAB_ATTR_RO(slabs);
3846 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3848 return slab_objects(s, buf, SO_PARTIAL);
3850 SLAB_ATTR_RO(partial);
3852 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3854 return slab_objects(s, buf, SO_CPU);
3856 SLAB_ATTR_RO(cpu_slabs);
3858 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3860 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3862 SLAB_ATTR_RO(objects);
3864 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3866 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3869 static ssize_t sanity_checks_store(struct kmem_cache *s,
3870 const char *buf, size_t length)
3872 s->flags &= ~SLAB_DEBUG_FREE;
3873 if (buf[0] == '1')
3874 s->flags |= SLAB_DEBUG_FREE;
3875 return length;
3877 SLAB_ATTR(sanity_checks);
3879 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3881 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3884 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3885 size_t length)
3887 s->flags &= ~SLAB_TRACE;
3888 if (buf[0] == '1')
3889 s->flags |= SLAB_TRACE;
3890 return length;
3892 SLAB_ATTR(trace);
3894 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3896 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3899 static ssize_t reclaim_account_store(struct kmem_cache *s,
3900 const char *buf, size_t length)
3902 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3903 if (buf[0] == '1')
3904 s->flags |= SLAB_RECLAIM_ACCOUNT;
3905 return length;
3907 SLAB_ATTR(reclaim_account);
3909 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3911 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3913 SLAB_ATTR_RO(hwcache_align);
3915 #ifdef CONFIG_ZONE_DMA
3916 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3918 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3920 SLAB_ATTR_RO(cache_dma);
3921 #endif
3923 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3925 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3927 SLAB_ATTR_RO(destroy_by_rcu);
3929 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3931 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3934 static ssize_t red_zone_store(struct kmem_cache *s,
3935 const char *buf, size_t length)
3937 if (any_slab_objects(s))
3938 return -EBUSY;
3940 s->flags &= ~SLAB_RED_ZONE;
3941 if (buf[0] == '1')
3942 s->flags |= SLAB_RED_ZONE;
3943 calculate_sizes(s);
3944 return length;
3946 SLAB_ATTR(red_zone);
3948 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3950 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3953 static ssize_t poison_store(struct kmem_cache *s,
3954 const char *buf, size_t length)
3956 if (any_slab_objects(s))
3957 return -EBUSY;
3959 s->flags &= ~SLAB_POISON;
3960 if (buf[0] == '1')
3961 s->flags |= SLAB_POISON;
3962 calculate_sizes(s);
3963 return length;
3965 SLAB_ATTR(poison);
3967 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3969 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3972 static ssize_t store_user_store(struct kmem_cache *s,
3973 const char *buf, size_t length)
3975 if (any_slab_objects(s))
3976 return -EBUSY;
3978 s->flags &= ~SLAB_STORE_USER;
3979 if (buf[0] == '1')
3980 s->flags |= SLAB_STORE_USER;
3981 calculate_sizes(s);
3982 return length;
3984 SLAB_ATTR(store_user);
3986 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3988 return 0;
3991 static ssize_t validate_store(struct kmem_cache *s,
3992 const char *buf, size_t length)
3994 int ret = -EINVAL;
3996 if (buf[0] == '1') {
3997 ret = validate_slab_cache(s);
3998 if (ret >= 0)
3999 ret = length;
4001 return ret;
4003 SLAB_ATTR(validate);
4005 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
4007 return 0;
4010 static ssize_t shrink_store(struct kmem_cache *s,
4011 const char *buf, size_t length)
4013 if (buf[0] == '1') {
4014 int rc = kmem_cache_shrink(s);
4016 if (rc)
4017 return rc;
4018 } else
4019 return -EINVAL;
4020 return length;
4022 SLAB_ATTR(shrink);
4024 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
4026 if (!(s->flags & SLAB_STORE_USER))
4027 return -ENOSYS;
4028 return list_locations(s, buf, TRACK_ALLOC);
4030 SLAB_ATTR_RO(alloc_calls);
4032 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
4034 if (!(s->flags & SLAB_STORE_USER))
4035 return -ENOSYS;
4036 return list_locations(s, buf, TRACK_FREE);
4038 SLAB_ATTR_RO(free_calls);
4040 #ifdef CONFIG_NUMA
4041 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
4043 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
4046 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
4047 const char *buf, size_t length)
4049 int n = simple_strtoul(buf, NULL, 10);
4051 if (n < 100)
4052 s->remote_node_defrag_ratio = n * 10;
4053 return length;
4055 SLAB_ATTR(remote_node_defrag_ratio);
4056 #endif
4058 #ifdef CONFIG_SLUB_STATS
4060 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
4062 unsigned long sum = 0;
4063 int cpu;
4064 int len;
4065 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
4067 if (!data)
4068 return -ENOMEM;
4070 for_each_online_cpu(cpu) {
4071 unsigned x = get_cpu_slab(s, cpu)->stat[si];
4073 data[cpu] = x;
4074 sum += x;
4077 len = sprintf(buf, "%lu", sum);
4079 for_each_online_cpu(cpu) {
4080 if (data[cpu] && len < PAGE_SIZE - 20)
4081 len += sprintf(buf + len, " c%d=%u", cpu, data[cpu]);
4083 kfree(data);
4084 return len + sprintf(buf + len, "\n");
4087 #define STAT_ATTR(si, text) \
4088 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
4090 return show_stat(s, buf, si); \
4092 SLAB_ATTR_RO(text); \
4094 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
4095 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
4096 STAT_ATTR(FREE_FASTPATH, free_fastpath);
4097 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
4098 STAT_ATTR(FREE_FROZEN, free_frozen);
4099 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
4100 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
4101 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
4102 STAT_ATTR(ALLOC_SLAB, alloc_slab);
4103 STAT_ATTR(ALLOC_REFILL, alloc_refill);
4104 STAT_ATTR(FREE_SLAB, free_slab);
4105 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
4106 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
4107 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
4108 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
4109 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
4110 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
4112 #endif
4114 static struct attribute *slab_attrs[] = {
4115 &slab_size_attr.attr,
4116 &object_size_attr.attr,
4117 &objs_per_slab_attr.attr,
4118 &order_attr.attr,
4119 &objects_attr.attr,
4120 &slabs_attr.attr,
4121 &partial_attr.attr,
4122 &cpu_slabs_attr.attr,
4123 &ctor_attr.attr,
4124 &aliases_attr.attr,
4125 &align_attr.attr,
4126 &sanity_checks_attr.attr,
4127 &trace_attr.attr,
4128 &hwcache_align_attr.attr,
4129 &reclaim_account_attr.attr,
4130 &destroy_by_rcu_attr.attr,
4131 &red_zone_attr.attr,
4132 &poison_attr.attr,
4133 &store_user_attr.attr,
4134 &validate_attr.attr,
4135 &shrink_attr.attr,
4136 &alloc_calls_attr.attr,
4137 &free_calls_attr.attr,
4138 #ifdef CONFIG_ZONE_DMA
4139 &cache_dma_attr.attr,
4140 #endif
4141 #ifdef CONFIG_NUMA
4142 &remote_node_defrag_ratio_attr.attr,
4143 #endif
4144 #ifdef CONFIG_SLUB_STATS
4145 &alloc_fastpath_attr.attr,
4146 &alloc_slowpath_attr.attr,
4147 &free_fastpath_attr.attr,
4148 &free_slowpath_attr.attr,
4149 &free_frozen_attr.attr,
4150 &free_add_partial_attr.attr,
4151 &free_remove_partial_attr.attr,
4152 &alloc_from_partial_attr.attr,
4153 &alloc_slab_attr.attr,
4154 &alloc_refill_attr.attr,
4155 &free_slab_attr.attr,
4156 &cpuslab_flush_attr.attr,
4157 &deactivate_full_attr.attr,
4158 &deactivate_empty_attr.attr,
4159 &deactivate_to_head_attr.attr,
4160 &deactivate_to_tail_attr.attr,
4161 &deactivate_remote_frees_attr.attr,
4162 #endif
4163 NULL
4166 static struct attribute_group slab_attr_group = {
4167 .attrs = slab_attrs,
4170 static ssize_t slab_attr_show(struct kobject *kobj,
4171 struct attribute *attr,
4172 char *buf)
4174 struct slab_attribute *attribute;
4175 struct kmem_cache *s;
4176 int err;
4178 attribute = to_slab_attr(attr);
4179 s = to_slab(kobj);
4181 if (!attribute->show)
4182 return -EIO;
4184 err = attribute->show(s, buf);
4186 return err;
4189 static ssize_t slab_attr_store(struct kobject *kobj,
4190 struct attribute *attr,
4191 const char *buf, size_t len)
4193 struct slab_attribute *attribute;
4194 struct kmem_cache *s;
4195 int err;
4197 attribute = to_slab_attr(attr);
4198 s = to_slab(kobj);
4200 if (!attribute->store)
4201 return -EIO;
4203 err = attribute->store(s, buf, len);
4205 return err;
4208 static void kmem_cache_release(struct kobject *kobj)
4210 struct kmem_cache *s = to_slab(kobj);
4212 kfree(s);
4215 static struct sysfs_ops slab_sysfs_ops = {
4216 .show = slab_attr_show,
4217 .store = slab_attr_store,
4220 static struct kobj_type slab_ktype = {
4221 .sysfs_ops = &slab_sysfs_ops,
4222 .release = kmem_cache_release
4225 static int uevent_filter(struct kset *kset, struct kobject *kobj)
4227 struct kobj_type *ktype = get_ktype(kobj);
4229 if (ktype == &slab_ktype)
4230 return 1;
4231 return 0;
4234 static struct kset_uevent_ops slab_uevent_ops = {
4235 .filter = uevent_filter,
4238 static struct kset *slab_kset;
4240 #define ID_STR_LENGTH 64
4242 /* Create a unique string id for a slab cache:
4243 * format
4244 * :[flags-]size:[memory address of kmemcache]
4246 static char *create_unique_id(struct kmem_cache *s)
4248 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
4249 char *p = name;
4251 BUG_ON(!name);
4253 *p++ = ':';
4255 * First flags affecting slabcache operations. We will only
4256 * get here for aliasable slabs so we do not need to support
4257 * too many flags. The flags here must cover all flags that
4258 * are matched during merging to guarantee that the id is
4259 * unique.
4261 if (s->flags & SLAB_CACHE_DMA)
4262 *p++ = 'd';
4263 if (s->flags & SLAB_RECLAIM_ACCOUNT)
4264 *p++ = 'a';
4265 if (s->flags & SLAB_DEBUG_FREE)
4266 *p++ = 'F';
4267 if (p != name + 1)
4268 *p++ = '-';
4269 p += sprintf(p, "%07d", s->size);
4270 BUG_ON(p > name + ID_STR_LENGTH - 1);
4271 return name;
4274 static int sysfs_slab_add(struct kmem_cache *s)
4276 int err;
4277 const char *name;
4278 int unmergeable;
4280 if (slab_state < SYSFS)
4281 /* Defer until later */
4282 return 0;
4284 unmergeable = slab_unmergeable(s);
4285 if (unmergeable) {
4287 * Slabcache can never be merged so we can use the name proper.
4288 * This is typically the case for debug situations. In that
4289 * case we can catch duplicate names easily.
4291 sysfs_remove_link(&slab_kset->kobj, s->name);
4292 name = s->name;
4293 } else {
4295 * Create a unique name for the slab as a target
4296 * for the symlinks.
4298 name = create_unique_id(s);
4301 s->kobj.kset = slab_kset;
4302 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, name);
4303 if (err) {
4304 kobject_put(&s->kobj);
4305 return err;
4308 err = sysfs_create_group(&s->kobj, &slab_attr_group);
4309 if (err)
4310 return err;
4311 kobject_uevent(&s->kobj, KOBJ_ADD);
4312 if (!unmergeable) {
4313 /* Setup first alias */
4314 sysfs_slab_alias(s, s->name);
4315 kfree(name);
4317 return 0;
4320 static void sysfs_slab_remove(struct kmem_cache *s)
4322 kobject_uevent(&s->kobj, KOBJ_REMOVE);
4323 kobject_del(&s->kobj);
4324 kobject_put(&s->kobj);
4328 * Need to buffer aliases during bootup until sysfs becomes
4329 * available lest we loose that information.
4331 struct saved_alias {
4332 struct kmem_cache *s;
4333 const char *name;
4334 struct saved_alias *next;
4337 static struct saved_alias *alias_list;
4339 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
4341 struct saved_alias *al;
4343 if (slab_state == SYSFS) {
4345 * If we have a leftover link then remove it.
4347 sysfs_remove_link(&slab_kset->kobj, name);
4348 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
4351 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
4352 if (!al)
4353 return -ENOMEM;
4355 al->s = s;
4356 al->name = name;
4357 al->next = alias_list;
4358 alias_list = al;
4359 return 0;
4362 static int __init slab_sysfs_init(void)
4364 struct kmem_cache *s;
4365 int err;
4367 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
4368 if (!slab_kset) {
4369 printk(KERN_ERR "Cannot register slab subsystem.\n");
4370 return -ENOSYS;
4373 slab_state = SYSFS;
4375 list_for_each_entry(s, &slab_caches, list) {
4376 err = sysfs_slab_add(s);
4377 if (err)
4378 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
4379 " to sysfs\n", s->name);
4382 while (alias_list) {
4383 struct saved_alias *al = alias_list;
4385 alias_list = alias_list->next;
4386 err = sysfs_slab_alias(al->s, al->name);
4387 if (err)
4388 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
4389 " %s to sysfs\n", s->name);
4390 kfree(al);
4393 resiliency_test();
4394 return 0;
4397 __initcall(slab_sysfs_init);
4398 #endif
4401 * The /proc/slabinfo ABI
4403 #ifdef CONFIG_SLABINFO
4405 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4406 size_t count, loff_t *ppos)
4408 return -EINVAL;
4412 static void print_slabinfo_header(struct seq_file *m)
4414 seq_puts(m, "slabinfo - version: 2.1\n");
4415 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4416 "<objperslab> <pagesperslab>");
4417 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4418 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4419 seq_putc(m, '\n');
4422 static void *s_start(struct seq_file *m, loff_t *pos)
4424 loff_t n = *pos;
4426 down_read(&slub_lock);
4427 if (!n)
4428 print_slabinfo_header(m);
4430 return seq_list_start(&slab_caches, *pos);
4433 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4435 return seq_list_next(p, &slab_caches, pos);
4438 static void s_stop(struct seq_file *m, void *p)
4440 up_read(&slub_lock);
4443 static int s_show(struct seq_file *m, void *p)
4445 unsigned long nr_partials = 0;
4446 unsigned long nr_slabs = 0;
4447 unsigned long nr_inuse = 0;
4448 unsigned long nr_objs;
4449 struct kmem_cache *s;
4450 int node;
4452 s = list_entry(p, struct kmem_cache, list);
4454 for_each_online_node(node) {
4455 struct kmem_cache_node *n = get_node(s, node);
4457 if (!n)
4458 continue;
4460 nr_partials += n->nr_partial;
4461 nr_slabs += atomic_long_read(&n->nr_slabs);
4462 nr_inuse += count_partial(n);
4465 nr_objs = nr_slabs * s->objects;
4466 nr_inuse += (nr_slabs - nr_partials) * s->objects;
4468 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", s->name, nr_inuse,
4469 nr_objs, s->size, s->objects, (1 << s->order));
4470 seq_printf(m, " : tunables %4u %4u %4u", 0, 0, 0);
4471 seq_printf(m, " : slabdata %6lu %6lu %6lu", nr_slabs, nr_slabs,
4472 0UL);
4473 seq_putc(m, '\n');
4474 return 0;
4477 const struct seq_operations slabinfo_op = {
4478 .start = s_start,
4479 .next = s_next,
4480 .stop = s_stop,
4481 .show = s_show,
4484 #endif /* CONFIG_SLABINFO */