SLUB Debug: fix initial object debug state of NUMA bootstrap objects
[linux-2.6/openmoko-kernel/knife-kernel.git] / mm / slub.c
bloba18708821c1e2264eea914a4f45c2bafec04337e
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>
25 * Lock order:
26 * 1. slab_lock(page)
27 * 2. slab->list_lock
29 * The slab_lock protects operations on the object of a particular
30 * slab and its metadata in the page struct. If the slab lock
31 * has been taken then no allocations nor frees can be performed
32 * on the objects in the slab nor can the slab be added or removed
33 * from the partial or full lists since this would mean modifying
34 * the page_struct of the slab.
36 * The list_lock protects the partial and full list on each node and
37 * the partial slab counter. If taken then no new slabs may be added or
38 * removed from the lists nor make the number of partial slabs be modified.
39 * (Note that the total number of slabs is an atomic value that may be
40 * modified without taking the list lock).
42 * The list_lock is a centralized lock and thus we avoid taking it as
43 * much as possible. As long as SLUB does not have to handle partial
44 * slabs, operations can continue without any centralized lock. F.e.
45 * allocating a long series of objects that fill up slabs does not require
46 * the list lock.
48 * The lock order is sometimes inverted when we are trying to get a slab
49 * off a list. We take the list_lock and then look for a page on the list
50 * to use. While we do that objects in the slabs may be freed. We can
51 * only operate on the slab if we have also taken the slab_lock. So we use
52 * a slab_trylock() on the slab. If trylock was successful then no frees
53 * can occur anymore and we can use the slab for allocations etc. If the
54 * slab_trylock() does not succeed then frees are in progress in the slab and
55 * we must stay away from it for a while since we may cause a bouncing
56 * cacheline if we try to acquire the lock. So go onto the next slab.
57 * If all pages are busy then we may allocate a new slab instead of reusing
58 * a partial slab. A new slab has noone operating on it and thus there is
59 * no danger of cacheline contention.
61 * Interrupts are disabled during allocation and deallocation in order to
62 * make the slab allocator safe to use in the context of an irq. In addition
63 * interrupts are disabled to ensure that the processor does not change
64 * while handling per_cpu slabs, due to kernel preemption.
66 * SLUB assigns one slab for allocation to each processor.
67 * Allocations only occur from these slabs called cpu slabs.
69 * Slabs with free elements are kept on a partial list and during regular
70 * operations no list for full slabs is used. If an object in a full slab is
71 * freed then the slab will show up again on the partial lists.
72 * We track full slabs for debugging purposes though because otherwise we
73 * cannot scan all objects.
75 * Slabs are freed when they become empty. Teardown and setup is
76 * minimal so we rely on the page allocators per cpu caches for
77 * fast frees and allocs.
79 * Overloading of page flags that are otherwise used for LRU management.
81 * PageActive The slab is frozen and exempt from list processing.
82 * This means that the slab is dedicated to a purpose
83 * such as satisfying allocations for a specific
84 * processor. Objects may be freed in the slab while
85 * it is frozen but slab_free will then skip the usual
86 * list operations. It is up to the processor holding
87 * the slab to integrate the slab into the slab lists
88 * when the slab is no longer needed.
90 * One use of this flag is to mark slabs that are
91 * used for allocations. Then such a slab becomes a cpu
92 * slab. The cpu slab may be equipped with an additional
93 * lockless_freelist that allows lockless access to
94 * free objects in addition to the regular freelist
95 * that requires the slab lock.
97 * PageError Slab requires special handling due to debug
98 * options set. This moves slab handling out of
99 * the fast path and disables lockless freelists.
102 #define FROZEN (1 << PG_active)
104 #ifdef CONFIG_SLUB_DEBUG
105 #define SLABDEBUG (1 << PG_error)
106 #else
107 #define SLABDEBUG 0
108 #endif
110 static inline int SlabFrozen(struct page *page)
112 return page->flags & FROZEN;
115 static inline void SetSlabFrozen(struct page *page)
117 page->flags |= FROZEN;
120 static inline void ClearSlabFrozen(struct page *page)
122 page->flags &= ~FROZEN;
125 static inline int SlabDebug(struct page *page)
127 return page->flags & SLABDEBUG;
130 static inline void SetSlabDebug(struct page *page)
132 page->flags |= SLABDEBUG;
135 static inline void ClearSlabDebug(struct page *page)
137 page->flags &= ~SLABDEBUG;
141 * Issues still to be resolved:
143 * - The per cpu array is updated for each new slab and and is a remote
144 * cacheline for most nodes. This could become a bouncing cacheline given
145 * enough frequent updates. There are 16 pointers in a cacheline, so at
146 * max 16 cpus could compete for the cacheline which may be okay.
148 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
150 * - Variable sizing of the per node arrays
153 /* Enable to test recovery from slab corruption on boot */
154 #undef SLUB_RESILIENCY_TEST
156 #if PAGE_SHIFT <= 12
159 * Small page size. Make sure that we do not fragment memory
161 #define DEFAULT_MAX_ORDER 1
162 #define DEFAULT_MIN_OBJECTS 4
164 #else
167 * Large page machines are customarily able to handle larger
168 * page orders.
170 #define DEFAULT_MAX_ORDER 2
171 #define DEFAULT_MIN_OBJECTS 8
173 #endif
176 * Mininum number of partial slabs. These will be left on the partial
177 * lists even if they are empty. kmem_cache_shrink may reclaim them.
179 #define MIN_PARTIAL 2
182 * Maximum number of desirable partial slabs.
183 * The existence of more partial slabs makes kmem_cache_shrink
184 * sort the partial list by the number of objects in the.
186 #define MAX_PARTIAL 10
188 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
189 SLAB_POISON | SLAB_STORE_USER)
192 * Set of flags that will prevent slab merging
194 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
195 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
197 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
198 SLAB_CACHE_DMA)
200 #ifndef ARCH_KMALLOC_MINALIGN
201 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
202 #endif
204 #ifndef ARCH_SLAB_MINALIGN
205 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
206 #endif
209 * The page->inuse field is 16 bit thus we have this limitation
211 #define MAX_OBJECTS_PER_SLAB 65535
213 /* Internal SLUB flags */
214 #define __OBJECT_POISON 0x80000000 /* Poison object */
216 /* Not all arches define cache_line_size */
217 #ifndef cache_line_size
218 #define cache_line_size() L1_CACHE_BYTES
219 #endif
221 static int kmem_size = sizeof(struct kmem_cache);
223 #ifdef CONFIG_SMP
224 static struct notifier_block slab_notifier;
225 #endif
227 static enum {
228 DOWN, /* No slab functionality available */
229 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
230 UP, /* Everything works but does not show up in sysfs */
231 SYSFS /* Sysfs up */
232 } slab_state = DOWN;
234 /* A list of all slab caches on the system */
235 static DECLARE_RWSEM(slub_lock);
236 LIST_HEAD(slab_caches);
239 * Tracking user of a slab.
241 struct track {
242 void *addr; /* Called from address */
243 int cpu; /* Was running on cpu */
244 int pid; /* Pid context */
245 unsigned long when; /* When did the operation occur */
248 enum track_item { TRACK_ALLOC, TRACK_FREE };
250 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
251 static int sysfs_slab_add(struct kmem_cache *);
252 static int sysfs_slab_alias(struct kmem_cache *, const char *);
253 static void sysfs_slab_remove(struct kmem_cache *);
254 #else
255 static int sysfs_slab_add(struct kmem_cache *s) { return 0; }
256 static int sysfs_slab_alias(struct kmem_cache *s, const char *p) { return 0; }
257 static void sysfs_slab_remove(struct kmem_cache *s) {}
258 #endif
260 /********************************************************************
261 * Core slab cache functions
262 *******************************************************************/
264 int slab_is_available(void)
266 return slab_state >= UP;
269 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
271 #ifdef CONFIG_NUMA
272 return s->node[node];
273 #else
274 return &s->local_node;
275 #endif
278 static inline int check_valid_pointer(struct kmem_cache *s,
279 struct page *page, const void *object)
281 void *base;
283 if (!object)
284 return 1;
286 base = page_address(page);
287 if (object < base || object >= base + s->objects * s->size ||
288 (object - base) % s->size) {
289 return 0;
292 return 1;
296 * Slow version of get and set free pointer.
298 * This version requires touching the cache lines of kmem_cache which
299 * we avoid to do in the fast alloc free paths. There we obtain the offset
300 * from the page struct.
302 static inline void *get_freepointer(struct kmem_cache *s, void *object)
304 return *(void **)(object + s->offset);
307 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
309 *(void **)(object + s->offset) = fp;
312 /* Loop over all objects in a slab */
313 #define for_each_object(__p, __s, __addr) \
314 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
315 __p += (__s)->size)
317 /* Scan freelist */
318 #define for_each_free_object(__p, __s, __free) \
319 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
321 /* Determine object index from a given position */
322 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
324 return (p - addr) / s->size;
327 #ifdef CONFIG_SLUB_DEBUG
329 * Debug settings:
331 #ifdef CONFIG_SLUB_DEBUG_ON
332 static int slub_debug = DEBUG_DEFAULT_FLAGS;
333 #else
334 static int slub_debug;
335 #endif
337 static char *slub_debug_slabs;
340 * Object debugging
342 static void print_section(char *text, u8 *addr, unsigned int length)
344 int i, offset;
345 int newline = 1;
346 char ascii[17];
348 ascii[16] = 0;
350 for (i = 0; i < length; i++) {
351 if (newline) {
352 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
353 newline = 0;
355 printk(" %02x", addr[i]);
356 offset = i % 16;
357 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
358 if (offset == 15) {
359 printk(" %s\n",ascii);
360 newline = 1;
363 if (!newline) {
364 i %= 16;
365 while (i < 16) {
366 printk(" ");
367 ascii[i] = ' ';
368 i++;
370 printk(" %s\n", ascii);
374 static struct track *get_track(struct kmem_cache *s, void *object,
375 enum track_item alloc)
377 struct track *p;
379 if (s->offset)
380 p = object + s->offset + sizeof(void *);
381 else
382 p = object + s->inuse;
384 return p + alloc;
387 static void set_track(struct kmem_cache *s, void *object,
388 enum track_item alloc, void *addr)
390 struct track *p;
392 if (s->offset)
393 p = object + s->offset + sizeof(void *);
394 else
395 p = object + s->inuse;
397 p += alloc;
398 if (addr) {
399 p->addr = addr;
400 p->cpu = smp_processor_id();
401 p->pid = current ? current->pid : -1;
402 p->when = jiffies;
403 } else
404 memset(p, 0, sizeof(struct track));
407 static void init_tracking(struct kmem_cache *s, void *object)
409 if (!(s->flags & SLAB_STORE_USER))
410 return;
412 set_track(s, object, TRACK_FREE, NULL);
413 set_track(s, object, TRACK_ALLOC, NULL);
416 static void print_track(const char *s, struct track *t)
418 if (!t->addr)
419 return;
421 printk(KERN_ERR "INFO: %s in ", s);
422 __print_symbol("%s", (unsigned long)t->addr);
423 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
426 static void print_tracking(struct kmem_cache *s, void *object)
428 if (!(s->flags & SLAB_STORE_USER))
429 return;
431 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
432 print_track("Freed", get_track(s, object, TRACK_FREE));
435 static void print_page_info(struct page *page)
437 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
438 page, page->inuse, page->freelist, page->flags);
442 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
444 va_list args;
445 char buf[100];
447 va_start(args, fmt);
448 vsnprintf(buf, sizeof(buf), fmt, args);
449 va_end(args);
450 printk(KERN_ERR "========================================"
451 "=====================================\n");
452 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
453 printk(KERN_ERR "----------------------------------------"
454 "-------------------------------------\n\n");
457 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
459 va_list args;
460 char buf[100];
462 va_start(args, fmt);
463 vsnprintf(buf, sizeof(buf), fmt, args);
464 va_end(args);
465 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
468 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
470 unsigned int off; /* Offset of last byte */
471 u8 *addr = page_address(page);
473 print_tracking(s, p);
475 print_page_info(page);
477 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
478 p, p - addr, get_freepointer(s, p));
480 if (p > addr + 16)
481 print_section("Bytes b4", p - 16, 16);
483 print_section("Object", p, min(s->objsize, 128));
485 if (s->flags & SLAB_RED_ZONE)
486 print_section("Redzone", p + s->objsize,
487 s->inuse - s->objsize);
489 if (s->offset)
490 off = s->offset + sizeof(void *);
491 else
492 off = s->inuse;
494 if (s->flags & SLAB_STORE_USER)
495 off += 2 * sizeof(struct track);
497 if (off != s->size)
498 /* Beginning of the filler is the free pointer */
499 print_section("Padding", p + off, s->size - off);
501 dump_stack();
504 static void object_err(struct kmem_cache *s, struct page *page,
505 u8 *object, char *reason)
507 slab_bug(s, reason);
508 print_trailer(s, page, object);
511 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
513 va_list args;
514 char buf[100];
516 va_start(args, fmt);
517 vsnprintf(buf, sizeof(buf), fmt, args);
518 va_end(args);
519 slab_bug(s, fmt);
520 print_page_info(page);
521 dump_stack();
524 static void init_object(struct kmem_cache *s, void *object, int active)
526 u8 *p = object;
528 if (s->flags & __OBJECT_POISON) {
529 memset(p, POISON_FREE, s->objsize - 1);
530 p[s->objsize -1] = POISON_END;
533 if (s->flags & SLAB_RED_ZONE)
534 memset(p + s->objsize,
535 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
536 s->inuse - s->objsize);
539 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
541 while (bytes) {
542 if (*start != (u8)value)
543 return start;
544 start++;
545 bytes--;
547 return NULL;
550 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
551 void *from, void *to)
553 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
554 memset(from, data, to - from);
557 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
558 u8 *object, char *what,
559 u8* start, unsigned int value, unsigned int bytes)
561 u8 *fault;
562 u8 *end;
564 fault = check_bytes(start, value, bytes);
565 if (!fault)
566 return 1;
568 end = start + bytes;
569 while (end > fault && end[-1] == value)
570 end--;
572 slab_bug(s, "%s overwritten", what);
573 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
574 fault, end - 1, fault[0], value);
575 print_trailer(s, page, object);
577 restore_bytes(s, what, value, fault, end);
578 return 0;
582 * Object layout:
584 * object address
585 * Bytes of the object to be managed.
586 * If the freepointer may overlay the object then the free
587 * pointer is the first word of the object.
589 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
590 * 0xa5 (POISON_END)
592 * object + s->objsize
593 * Padding to reach word boundary. This is also used for Redzoning.
594 * Padding is extended by another word if Redzoning is enabled and
595 * objsize == inuse.
597 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
598 * 0xcc (RED_ACTIVE) for objects in use.
600 * object + s->inuse
601 * Meta data starts here.
603 * A. Free pointer (if we cannot overwrite object on free)
604 * B. Tracking data for SLAB_STORE_USER
605 * C. Padding to reach required alignment boundary or at mininum
606 * one word if debuggin is on to be able to detect writes
607 * before the word boundary.
609 * Padding is done using 0x5a (POISON_INUSE)
611 * object + s->size
612 * Nothing is used beyond s->size.
614 * If slabcaches are merged then the objsize and inuse boundaries are mostly
615 * ignored. And therefore no slab options that rely on these boundaries
616 * may be used with merged slabcaches.
619 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
621 unsigned long off = s->inuse; /* The end of info */
623 if (s->offset)
624 /* Freepointer is placed after the object. */
625 off += sizeof(void *);
627 if (s->flags & SLAB_STORE_USER)
628 /* We also have user information there */
629 off += 2 * sizeof(struct track);
631 if (s->size == off)
632 return 1;
634 return check_bytes_and_report(s, page, p, "Object padding",
635 p + off, POISON_INUSE, s->size - off);
638 static int slab_pad_check(struct kmem_cache *s, struct page *page)
640 u8 *start;
641 u8 *fault;
642 u8 *end;
643 int length;
644 int remainder;
646 if (!(s->flags & SLAB_POISON))
647 return 1;
649 start = page_address(page);
650 end = start + (PAGE_SIZE << s->order);
651 length = s->objects * s->size;
652 remainder = end - (start + length);
653 if (!remainder)
654 return 1;
656 fault = check_bytes(start + length, POISON_INUSE, remainder);
657 if (!fault)
658 return 1;
659 while (end > fault && end[-1] == POISON_INUSE)
660 end--;
662 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
663 print_section("Padding", start, length);
665 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
666 return 0;
669 static int check_object(struct kmem_cache *s, struct page *page,
670 void *object, int active)
672 u8 *p = object;
673 u8 *endobject = object + s->objsize;
675 if (s->flags & SLAB_RED_ZONE) {
676 unsigned int red =
677 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
679 if (!check_bytes_and_report(s, page, object, "Redzone",
680 endobject, red, s->inuse - s->objsize))
681 return 0;
682 } else {
683 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
684 check_bytes_and_report(s, page, p, "Alignment padding", endobject,
685 POISON_INUSE, s->inuse - s->objsize);
688 if (s->flags & SLAB_POISON) {
689 if (!active && (s->flags & __OBJECT_POISON) &&
690 (!check_bytes_and_report(s, page, p, "Poison", p,
691 POISON_FREE, s->objsize - 1) ||
692 !check_bytes_and_report(s, page, p, "Poison",
693 p + s->objsize -1, POISON_END, 1)))
694 return 0;
696 * check_pad_bytes cleans up on its own.
698 check_pad_bytes(s, page, p);
701 if (!s->offset && active)
703 * Object and freepointer overlap. Cannot check
704 * freepointer while object is allocated.
706 return 1;
708 /* Check free pointer validity */
709 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
710 object_err(s, page, p, "Freepointer corrupt");
712 * No choice but to zap it and thus loose the remainder
713 * of the free objects in this slab. May cause
714 * another error because the object count is now wrong.
716 set_freepointer(s, p, NULL);
717 return 0;
719 return 1;
722 static int check_slab(struct kmem_cache *s, struct page *page)
724 VM_BUG_ON(!irqs_disabled());
726 if (!PageSlab(page)) {
727 slab_err(s, page, "Not a valid slab page");
728 return 0;
730 if (page->offset * sizeof(void *) != s->offset) {
731 slab_err(s, page, "Corrupted offset %lu",
732 (unsigned long)(page->offset * sizeof(void *)));
733 return 0;
735 if (page->inuse > s->objects) {
736 slab_err(s, page, "inuse %u > max %u",
737 s->name, page->inuse, s->objects);
738 return 0;
740 /* Slab_pad_check fixes things up after itself */
741 slab_pad_check(s, page);
742 return 1;
746 * Determine if a certain object on a page is on the freelist. Must hold the
747 * slab lock to guarantee that the chains are in a consistent state.
749 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
751 int nr = 0;
752 void *fp = page->freelist;
753 void *object = NULL;
755 while (fp && nr <= s->objects) {
756 if (fp == search)
757 return 1;
758 if (!check_valid_pointer(s, page, fp)) {
759 if (object) {
760 object_err(s, page, object,
761 "Freechain corrupt");
762 set_freepointer(s, object, NULL);
763 break;
764 } else {
765 slab_err(s, page, "Freepointer corrupt");
766 page->freelist = NULL;
767 page->inuse = s->objects;
768 slab_fix(s, "Freelist cleared");
769 return 0;
771 break;
773 object = fp;
774 fp = get_freepointer(s, object);
775 nr++;
778 if (page->inuse != s->objects - nr) {
779 slab_err(s, page, "Wrong object count. Counter is %d but "
780 "counted were %d", page->inuse, s->objects - nr);
781 page->inuse = s->objects - nr;
782 slab_fix(s, "Object count adjusted.");
784 return search == NULL;
787 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
789 if (s->flags & SLAB_TRACE) {
790 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
791 s->name,
792 alloc ? "alloc" : "free",
793 object, page->inuse,
794 page->freelist);
796 if (!alloc)
797 print_section("Object", (void *)object, s->objsize);
799 dump_stack();
804 * Tracking of fully allocated slabs for debugging purposes.
806 static void add_full(struct kmem_cache_node *n, struct page *page)
808 spin_lock(&n->list_lock);
809 list_add(&page->lru, &n->full);
810 spin_unlock(&n->list_lock);
813 static void remove_full(struct kmem_cache *s, struct page *page)
815 struct kmem_cache_node *n;
817 if (!(s->flags & SLAB_STORE_USER))
818 return;
820 n = get_node(s, page_to_nid(page));
822 spin_lock(&n->list_lock);
823 list_del(&page->lru);
824 spin_unlock(&n->list_lock);
827 static void setup_object_debug(struct kmem_cache *s, struct page *page,
828 void *object)
830 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
831 return;
833 init_object(s, object, 0);
834 init_tracking(s, object);
837 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
838 void *object, void *addr)
840 if (!check_slab(s, page))
841 goto bad;
843 if (object && !on_freelist(s, page, object)) {
844 object_err(s, page, object, "Object already allocated");
845 goto bad;
848 if (!check_valid_pointer(s, page, object)) {
849 object_err(s, page, object, "Freelist Pointer check fails");
850 goto bad;
853 if (object && !check_object(s, page, object, 0))
854 goto bad;
856 /* Success perform special debug activities for allocs */
857 if (s->flags & SLAB_STORE_USER)
858 set_track(s, object, TRACK_ALLOC, addr);
859 trace(s, page, object, 1);
860 init_object(s, object, 1);
861 return 1;
863 bad:
864 if (PageSlab(page)) {
866 * If this is a slab page then lets do the best we can
867 * to avoid issues in the future. Marking all objects
868 * as used avoids touching the remaining objects.
870 slab_fix(s, "Marking all objects used");
871 page->inuse = s->objects;
872 page->freelist = NULL;
873 /* Fix up fields that may be corrupted */
874 page->offset = s->offset / sizeof(void *);
876 return 0;
879 static int free_debug_processing(struct kmem_cache *s, struct page *page,
880 void *object, void *addr)
882 if (!check_slab(s, page))
883 goto fail;
885 if (!check_valid_pointer(s, page, object)) {
886 slab_err(s, page, "Invalid object pointer 0x%p", object);
887 goto fail;
890 if (on_freelist(s, page, object)) {
891 object_err(s, page, object, "Object already free");
892 goto fail;
895 if (!check_object(s, page, object, 1))
896 return 0;
898 if (unlikely(s != page->slab)) {
899 if (!PageSlab(page))
900 slab_err(s, page, "Attempt to free object(0x%p) "
901 "outside of slab", object);
902 else
903 if (!page->slab) {
904 printk(KERN_ERR
905 "SLUB <none>: no slab for object 0x%p.\n",
906 object);
907 dump_stack();
909 else
910 object_err(s, page, object,
911 "page slab pointer corrupt.");
912 goto fail;
915 /* Special debug activities for freeing objects */
916 if (!SlabFrozen(page) && !page->freelist)
917 remove_full(s, page);
918 if (s->flags & SLAB_STORE_USER)
919 set_track(s, object, TRACK_FREE, addr);
920 trace(s, page, object, 0);
921 init_object(s, object, 0);
922 return 1;
924 fail:
925 slab_fix(s, "Object at 0x%p not freed", object);
926 return 0;
929 static int __init setup_slub_debug(char *str)
931 slub_debug = DEBUG_DEFAULT_FLAGS;
932 if (*str++ != '=' || !*str)
934 * No options specified. Switch on full debugging.
936 goto out;
938 if (*str == ',')
940 * No options but restriction on slabs. This means full
941 * debugging for slabs matching a pattern.
943 goto check_slabs;
945 slub_debug = 0;
946 if (*str == '-')
948 * Switch off all debugging measures.
950 goto out;
953 * Determine which debug features should be switched on
955 for ( ;*str && *str != ','; str++) {
956 switch (tolower(*str)) {
957 case 'f':
958 slub_debug |= SLAB_DEBUG_FREE;
959 break;
960 case 'z':
961 slub_debug |= SLAB_RED_ZONE;
962 break;
963 case 'p':
964 slub_debug |= SLAB_POISON;
965 break;
966 case 'u':
967 slub_debug |= SLAB_STORE_USER;
968 break;
969 case 't':
970 slub_debug |= SLAB_TRACE;
971 break;
972 default:
973 printk(KERN_ERR "slub_debug option '%c' "
974 "unknown. skipped\n",*str);
978 check_slabs:
979 if (*str == ',')
980 slub_debug_slabs = str + 1;
981 out:
982 return 1;
985 __setup("slub_debug", setup_slub_debug);
987 static void kmem_cache_open_debug_check(struct kmem_cache *s)
990 * The page->offset field is only 16 bit wide. This is an offset
991 * in units of words from the beginning of an object. If the slab
992 * size is bigger then we cannot move the free pointer behind the
993 * object anymore.
995 * On 32 bit platforms the limit is 256k. On 64bit platforms
996 * the limit is 512k.
998 * Debugging or ctor may create a need to move the free
999 * pointer. Fail if this happens.
1001 if (s->objsize >= 65535 * sizeof(void *)) {
1002 BUG_ON(s->flags & (SLAB_RED_ZONE | SLAB_POISON |
1003 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
1004 BUG_ON(s->ctor);
1006 else
1008 * Enable debugging if selected on the kernel commandline.
1010 if (slub_debug && (!slub_debug_slabs ||
1011 strncmp(slub_debug_slabs, s->name,
1012 strlen(slub_debug_slabs)) == 0))
1013 s->flags |= slub_debug;
1015 #else
1016 static inline void setup_object_debug(struct kmem_cache *s,
1017 struct page *page, void *object) {}
1019 static inline int alloc_debug_processing(struct kmem_cache *s,
1020 struct page *page, void *object, void *addr) { return 0; }
1022 static inline int free_debug_processing(struct kmem_cache *s,
1023 struct page *page, void *object, void *addr) { return 0; }
1025 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1026 { return 1; }
1027 static inline int check_object(struct kmem_cache *s, struct page *page,
1028 void *object, int active) { return 1; }
1029 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1030 static inline void kmem_cache_open_debug_check(struct kmem_cache *s) {}
1031 #define slub_debug 0
1032 #endif
1034 * Slab allocation and freeing
1036 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1038 struct page * page;
1039 int pages = 1 << s->order;
1041 if (s->order)
1042 flags |= __GFP_COMP;
1044 if (s->flags & SLAB_CACHE_DMA)
1045 flags |= SLUB_DMA;
1047 if (node == -1)
1048 page = alloc_pages(flags, s->order);
1049 else
1050 page = alloc_pages_node(node, flags, s->order);
1052 if (!page)
1053 return NULL;
1055 mod_zone_page_state(page_zone(page),
1056 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1057 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1058 pages);
1060 return page;
1063 static void setup_object(struct kmem_cache *s, struct page *page,
1064 void *object)
1066 setup_object_debug(s, page, object);
1067 if (unlikely(s->ctor))
1068 s->ctor(object, s, 0);
1071 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1073 struct page *page;
1074 struct kmem_cache_node *n;
1075 void *start;
1076 void *end;
1077 void *last;
1078 void *p;
1080 BUG_ON(flags & ~(GFP_DMA | GFP_LEVEL_MASK));
1082 if (flags & __GFP_WAIT)
1083 local_irq_enable();
1085 page = allocate_slab(s, flags & GFP_LEVEL_MASK, node);
1086 if (!page)
1087 goto out;
1089 n = get_node(s, page_to_nid(page));
1090 if (n)
1091 atomic_long_inc(&n->nr_slabs);
1092 page->offset = s->offset / sizeof(void *);
1093 page->slab = s;
1094 page->flags |= 1 << PG_slab;
1095 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1096 SLAB_STORE_USER | SLAB_TRACE))
1097 SetSlabDebug(page);
1099 start = page_address(page);
1100 end = start + s->objects * s->size;
1102 if (unlikely(s->flags & SLAB_POISON))
1103 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1105 last = start;
1106 for_each_object(p, s, start) {
1107 setup_object(s, page, last);
1108 set_freepointer(s, last, p);
1109 last = p;
1111 setup_object(s, page, last);
1112 set_freepointer(s, last, NULL);
1114 page->freelist = start;
1115 page->lockless_freelist = NULL;
1116 page->inuse = 0;
1117 out:
1118 if (flags & __GFP_WAIT)
1119 local_irq_disable();
1120 return page;
1123 static void __free_slab(struct kmem_cache *s, struct page *page)
1125 int pages = 1 << s->order;
1127 if (unlikely(SlabDebug(page))) {
1128 void *p;
1130 slab_pad_check(s, page);
1131 for_each_object(p, s, page_address(page))
1132 check_object(s, page, p, 0);
1135 mod_zone_page_state(page_zone(page),
1136 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1137 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1138 - pages);
1140 page->mapping = NULL;
1141 __free_pages(page, s->order);
1144 static void rcu_free_slab(struct rcu_head *h)
1146 struct page *page;
1148 page = container_of((struct list_head *)h, struct page, lru);
1149 __free_slab(page->slab, page);
1152 static void free_slab(struct kmem_cache *s, struct page *page)
1154 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1156 * RCU free overloads the RCU head over the LRU
1158 struct rcu_head *head = (void *)&page->lru;
1160 call_rcu(head, rcu_free_slab);
1161 } else
1162 __free_slab(s, page);
1165 static void discard_slab(struct kmem_cache *s, struct page *page)
1167 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1169 atomic_long_dec(&n->nr_slabs);
1170 reset_page_mapcount(page);
1171 ClearSlabDebug(page);
1172 __ClearPageSlab(page);
1173 free_slab(s, page);
1177 * Per slab locking using the pagelock
1179 static __always_inline void slab_lock(struct page *page)
1181 bit_spin_lock(PG_locked, &page->flags);
1184 static __always_inline void slab_unlock(struct page *page)
1186 bit_spin_unlock(PG_locked, &page->flags);
1189 static __always_inline int slab_trylock(struct page *page)
1191 int rc = 1;
1193 rc = bit_spin_trylock(PG_locked, &page->flags);
1194 return rc;
1198 * Management of partially allocated slabs
1200 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1202 spin_lock(&n->list_lock);
1203 n->nr_partial++;
1204 list_add_tail(&page->lru, &n->partial);
1205 spin_unlock(&n->list_lock);
1208 static void add_partial(struct kmem_cache_node *n, struct page *page)
1210 spin_lock(&n->list_lock);
1211 n->nr_partial++;
1212 list_add(&page->lru, &n->partial);
1213 spin_unlock(&n->list_lock);
1216 static void remove_partial(struct kmem_cache *s,
1217 struct page *page)
1219 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1221 spin_lock(&n->list_lock);
1222 list_del(&page->lru);
1223 n->nr_partial--;
1224 spin_unlock(&n->list_lock);
1228 * Lock slab and remove from the partial list.
1230 * Must hold list_lock.
1232 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1234 if (slab_trylock(page)) {
1235 list_del(&page->lru);
1236 n->nr_partial--;
1237 SetSlabFrozen(page);
1238 return 1;
1240 return 0;
1244 * Try to allocate a partial slab from a specific node.
1246 static struct page *get_partial_node(struct kmem_cache_node *n)
1248 struct page *page;
1251 * Racy check. If we mistakenly see no partial slabs then we
1252 * just allocate an empty slab. If we mistakenly try to get a
1253 * partial slab and there is none available then get_partials()
1254 * will return NULL.
1256 if (!n || !n->nr_partial)
1257 return NULL;
1259 spin_lock(&n->list_lock);
1260 list_for_each_entry(page, &n->partial, lru)
1261 if (lock_and_freeze_slab(n, page))
1262 goto out;
1263 page = NULL;
1264 out:
1265 spin_unlock(&n->list_lock);
1266 return page;
1270 * Get a page from somewhere. Search in increasing NUMA distances.
1272 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1274 #ifdef CONFIG_NUMA
1275 struct zonelist *zonelist;
1276 struct zone **z;
1277 struct page *page;
1280 * The defrag ratio allows a configuration of the tradeoffs between
1281 * inter node defragmentation and node local allocations. A lower
1282 * defrag_ratio increases the tendency to do local allocations
1283 * instead of attempting to obtain partial slabs from other nodes.
1285 * If the defrag_ratio is set to 0 then kmalloc() always
1286 * returns node local objects. If the ratio is higher then kmalloc()
1287 * may return off node objects because partial slabs are obtained
1288 * from other nodes and filled up.
1290 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1291 * defrag_ratio = 1000) then every (well almost) allocation will
1292 * first attempt to defrag slab caches on other nodes. This means
1293 * scanning over all nodes to look for partial slabs which may be
1294 * expensive if we do it every time we are trying to find a slab
1295 * with available objects.
1297 if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1298 return NULL;
1300 zonelist = &NODE_DATA(slab_node(current->mempolicy))
1301 ->node_zonelists[gfp_zone(flags)];
1302 for (z = zonelist->zones; *z; z++) {
1303 struct kmem_cache_node *n;
1305 n = get_node(s, zone_to_nid(*z));
1307 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1308 n->nr_partial > MIN_PARTIAL) {
1309 page = get_partial_node(n);
1310 if (page)
1311 return page;
1314 #endif
1315 return NULL;
1319 * Get a partial page, lock it and return it.
1321 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1323 struct page *page;
1324 int searchnode = (node == -1) ? numa_node_id() : node;
1326 page = get_partial_node(get_node(s, searchnode));
1327 if (page || (flags & __GFP_THISNODE))
1328 return page;
1330 return get_any_partial(s, flags);
1334 * Move a page back to the lists.
1336 * Must be called with the slab lock held.
1338 * On exit the slab lock will have been dropped.
1340 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1342 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1344 ClearSlabFrozen(page);
1345 if (page->inuse) {
1347 if (page->freelist)
1348 add_partial(n, page);
1349 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1350 add_full(n, page);
1351 slab_unlock(page);
1353 } else {
1354 if (n->nr_partial < MIN_PARTIAL) {
1356 * Adding an empty slab to the partial slabs in order
1357 * to avoid page allocator overhead. This slab needs
1358 * to come after the other slabs with objects in
1359 * order to fill them up. That way the size of the
1360 * partial list stays small. kmem_cache_shrink can
1361 * reclaim empty slabs from the partial list.
1363 add_partial_tail(n, page);
1364 slab_unlock(page);
1365 } else {
1366 slab_unlock(page);
1367 discard_slab(s, page);
1373 * Remove the cpu slab
1375 static void deactivate_slab(struct kmem_cache *s, struct page *page, int cpu)
1378 * Merge cpu freelist into freelist. Typically we get here
1379 * because both freelists are empty. So this is unlikely
1380 * to occur.
1382 while (unlikely(page->lockless_freelist)) {
1383 void **object;
1385 /* Retrieve object from cpu_freelist */
1386 object = page->lockless_freelist;
1387 page->lockless_freelist = page->lockless_freelist[page->offset];
1389 /* And put onto the regular freelist */
1390 object[page->offset] = page->freelist;
1391 page->freelist = object;
1392 page->inuse--;
1394 s->cpu_slab[cpu] = NULL;
1395 unfreeze_slab(s, page);
1398 static void flush_slab(struct kmem_cache *s, struct page *page, int cpu)
1400 slab_lock(page);
1401 deactivate_slab(s, page, cpu);
1405 * Flush cpu slab.
1406 * Called from IPI handler with interrupts disabled.
1408 static void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1410 struct page *page = s->cpu_slab[cpu];
1412 if (likely(page))
1413 flush_slab(s, page, cpu);
1416 static void flush_cpu_slab(void *d)
1418 struct kmem_cache *s = d;
1419 int cpu = smp_processor_id();
1421 __flush_cpu_slab(s, cpu);
1424 static void flush_all(struct kmem_cache *s)
1426 #ifdef CONFIG_SMP
1427 on_each_cpu(flush_cpu_slab, s, 1, 1);
1428 #else
1429 unsigned long flags;
1431 local_irq_save(flags);
1432 flush_cpu_slab(s);
1433 local_irq_restore(flags);
1434 #endif
1438 * Slow path. The lockless freelist is empty or we need to perform
1439 * debugging duties.
1441 * Interrupts are disabled.
1443 * Processing is still very fast if new objects have been freed to the
1444 * regular freelist. In that case we simply take over the regular freelist
1445 * as the lockless freelist and zap the regular freelist.
1447 * If that is not working then we fall back to the partial lists. We take the
1448 * first element of the freelist as the object to allocate now and move the
1449 * rest of the freelist to the lockless freelist.
1451 * And if we were unable to get a new slab from the partial slab lists then
1452 * we need to allocate a new slab. This is slowest path since we may sleep.
1454 static void *__slab_alloc(struct kmem_cache *s,
1455 gfp_t gfpflags, int node, void *addr, struct page *page)
1457 void **object;
1458 int cpu = smp_processor_id();
1460 if (!page)
1461 goto new_slab;
1463 slab_lock(page);
1464 if (unlikely(node != -1 && page_to_nid(page) != node))
1465 goto another_slab;
1466 load_freelist:
1467 object = page->freelist;
1468 if (unlikely(!object))
1469 goto another_slab;
1470 if (unlikely(SlabDebug(page)))
1471 goto debug;
1473 object = page->freelist;
1474 page->lockless_freelist = object[page->offset];
1475 page->inuse = s->objects;
1476 page->freelist = NULL;
1477 slab_unlock(page);
1478 return object;
1480 another_slab:
1481 deactivate_slab(s, page, cpu);
1483 new_slab:
1484 page = get_partial(s, gfpflags, node);
1485 if (page) {
1486 s->cpu_slab[cpu] = page;
1487 goto load_freelist;
1490 page = new_slab(s, gfpflags, node);
1491 if (page) {
1492 cpu = smp_processor_id();
1493 if (s->cpu_slab[cpu]) {
1495 * Someone else populated the cpu_slab while we
1496 * enabled interrupts, or we have gotten scheduled
1497 * on another cpu. The page may not be on the
1498 * requested node even if __GFP_THISNODE was
1499 * specified. So we need to recheck.
1501 if (node == -1 ||
1502 page_to_nid(s->cpu_slab[cpu]) == node) {
1504 * Current cpuslab is acceptable and we
1505 * want the current one since its cache hot
1507 discard_slab(s, page);
1508 page = s->cpu_slab[cpu];
1509 slab_lock(page);
1510 goto load_freelist;
1512 /* New slab does not fit our expectations */
1513 flush_slab(s, s->cpu_slab[cpu], cpu);
1515 slab_lock(page);
1516 SetSlabFrozen(page);
1517 s->cpu_slab[cpu] = page;
1518 goto load_freelist;
1520 return NULL;
1521 debug:
1522 object = page->freelist;
1523 if (!alloc_debug_processing(s, page, object, addr))
1524 goto another_slab;
1526 page->inuse++;
1527 page->freelist = object[page->offset];
1528 slab_unlock(page);
1529 return object;
1533 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1534 * have the fastpath folded into their functions. So no function call
1535 * overhead for requests that can be satisfied on the fastpath.
1537 * The fastpath works by first checking if the lockless freelist can be used.
1538 * If not then __slab_alloc is called for slow processing.
1540 * Otherwise we can simply pick the next object from the lockless free list.
1542 static void __always_inline *slab_alloc(struct kmem_cache *s,
1543 gfp_t gfpflags, int node, void *addr)
1545 struct page *page;
1546 void **object;
1547 unsigned long flags;
1549 local_irq_save(flags);
1550 page = s->cpu_slab[smp_processor_id()];
1551 if (unlikely(!page || !page->lockless_freelist ||
1552 (node != -1 && page_to_nid(page) != node)))
1554 object = __slab_alloc(s, gfpflags, node, addr, page);
1556 else {
1557 object = page->lockless_freelist;
1558 page->lockless_freelist = object[page->offset];
1560 local_irq_restore(flags);
1561 return object;
1564 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1566 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1568 EXPORT_SYMBOL(kmem_cache_alloc);
1570 #ifdef CONFIG_NUMA
1571 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1573 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1575 EXPORT_SYMBOL(kmem_cache_alloc_node);
1576 #endif
1579 * Slow patch handling. This may still be called frequently since objects
1580 * have a longer lifetime than the cpu slabs in most processing loads.
1582 * So we still attempt to reduce cache line usage. Just take the slab
1583 * lock and free the item. If there is no additional partial page
1584 * handling required then we can return immediately.
1586 static void __slab_free(struct kmem_cache *s, struct page *page,
1587 void *x, void *addr)
1589 void *prior;
1590 void **object = (void *)x;
1592 slab_lock(page);
1594 if (unlikely(SlabDebug(page)))
1595 goto debug;
1596 checks_ok:
1597 prior = object[page->offset] = page->freelist;
1598 page->freelist = object;
1599 page->inuse--;
1601 if (unlikely(SlabFrozen(page)))
1602 goto out_unlock;
1604 if (unlikely(!page->inuse))
1605 goto slab_empty;
1608 * Objects left in the slab. If it
1609 * was not on the partial list before
1610 * then add it.
1612 if (unlikely(!prior))
1613 add_partial(get_node(s, page_to_nid(page)), page);
1615 out_unlock:
1616 slab_unlock(page);
1617 return;
1619 slab_empty:
1620 if (prior)
1622 * Slab still on the partial list.
1624 remove_partial(s, page);
1626 slab_unlock(page);
1627 discard_slab(s, page);
1628 return;
1630 debug:
1631 if (!free_debug_processing(s, page, x, addr))
1632 goto out_unlock;
1633 goto checks_ok;
1637 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1638 * can perform fastpath freeing without additional function calls.
1640 * The fastpath is only possible if we are freeing to the current cpu slab
1641 * of this processor. This typically the case if we have just allocated
1642 * the item before.
1644 * If fastpath is not possible then fall back to __slab_free where we deal
1645 * with all sorts of special processing.
1647 static void __always_inline slab_free(struct kmem_cache *s,
1648 struct page *page, void *x, void *addr)
1650 void **object = (void *)x;
1651 unsigned long flags;
1653 local_irq_save(flags);
1654 if (likely(page == s->cpu_slab[smp_processor_id()] &&
1655 !SlabDebug(page))) {
1656 object[page->offset] = page->lockless_freelist;
1657 page->lockless_freelist = object;
1658 } else
1659 __slab_free(s, page, x, addr);
1661 local_irq_restore(flags);
1664 void kmem_cache_free(struct kmem_cache *s, void *x)
1666 struct page *page;
1668 page = virt_to_head_page(x);
1670 slab_free(s, page, x, __builtin_return_address(0));
1672 EXPORT_SYMBOL(kmem_cache_free);
1674 /* Figure out on which slab object the object resides */
1675 static struct page *get_object_page(const void *x)
1677 struct page *page = virt_to_head_page(x);
1679 if (!PageSlab(page))
1680 return NULL;
1682 return page;
1686 * Object placement in a slab is made very easy because we always start at
1687 * offset 0. If we tune the size of the object to the alignment then we can
1688 * get the required alignment by putting one properly sized object after
1689 * another.
1691 * Notice that the allocation order determines the sizes of the per cpu
1692 * caches. Each processor has always one slab available for allocations.
1693 * Increasing the allocation order reduces the number of times that slabs
1694 * must be moved on and off the partial lists and is therefore a factor in
1695 * locking overhead.
1699 * Mininum / Maximum order of slab pages. This influences locking overhead
1700 * and slab fragmentation. A higher order reduces the number of partial slabs
1701 * and increases the number of allocations possible without having to
1702 * take the list_lock.
1704 static int slub_min_order;
1705 static int slub_max_order = DEFAULT_MAX_ORDER;
1706 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1709 * Merge control. If this is set then no merging of slab caches will occur.
1710 * (Could be removed. This was introduced to pacify the merge skeptics.)
1712 static int slub_nomerge;
1715 * Calculate the order of allocation given an slab object size.
1717 * The order of allocation has significant impact on performance and other
1718 * system components. Generally order 0 allocations should be preferred since
1719 * order 0 does not cause fragmentation in the page allocator. Larger objects
1720 * be problematic to put into order 0 slabs because there may be too much
1721 * unused space left. We go to a higher order if more than 1/8th of the slab
1722 * would be wasted.
1724 * In order to reach satisfactory performance we must ensure that a minimum
1725 * number of objects is in one slab. Otherwise we may generate too much
1726 * activity on the partial lists which requires taking the list_lock. This is
1727 * less a concern for large slabs though which are rarely used.
1729 * slub_max_order specifies the order where we begin to stop considering the
1730 * number of objects in a slab as critical. If we reach slub_max_order then
1731 * we try to keep the page order as low as possible. So we accept more waste
1732 * of space in favor of a small page order.
1734 * Higher order allocations also allow the placement of more objects in a
1735 * slab and thereby reduce object handling overhead. If the user has
1736 * requested a higher mininum order then we start with that one instead of
1737 * the smallest order which will fit the object.
1739 static inline int slab_order(int size, int min_objects,
1740 int max_order, int fract_leftover)
1742 int order;
1743 int rem;
1744 int min_order = slub_min_order;
1747 * If we would create too many object per slab then reduce
1748 * the slab order even if it goes below slub_min_order.
1750 while (min_order > 0 &&
1751 (PAGE_SIZE << min_order) >= MAX_OBJECTS_PER_SLAB * size)
1752 min_order--;
1754 for (order = max(min_order,
1755 fls(min_objects * size - 1) - PAGE_SHIFT);
1756 order <= max_order; order++) {
1758 unsigned long slab_size = PAGE_SIZE << order;
1760 if (slab_size < min_objects * size)
1761 continue;
1763 rem = slab_size % size;
1765 if (rem <= slab_size / fract_leftover)
1766 break;
1768 /* If the next size is too high then exit now */
1769 if (slab_size * 2 >= MAX_OBJECTS_PER_SLAB * size)
1770 break;
1773 return order;
1776 static inline int calculate_order(int size)
1778 int order;
1779 int min_objects;
1780 int fraction;
1783 * Attempt to find best configuration for a slab. This
1784 * works by first attempting to generate a layout with
1785 * the best configuration and backing off gradually.
1787 * First we reduce the acceptable waste in a slab. Then
1788 * we reduce the minimum objects required in a slab.
1790 min_objects = slub_min_objects;
1791 while (min_objects > 1) {
1792 fraction = 8;
1793 while (fraction >= 4) {
1794 order = slab_order(size, min_objects,
1795 slub_max_order, fraction);
1796 if (order <= slub_max_order)
1797 return order;
1798 fraction /= 2;
1800 min_objects /= 2;
1804 * We were unable to place multiple objects in a slab. Now
1805 * lets see if we can place a single object there.
1807 order = slab_order(size, 1, slub_max_order, 1);
1808 if (order <= slub_max_order)
1809 return order;
1812 * Doh this slab cannot be placed using slub_max_order.
1814 order = slab_order(size, 1, MAX_ORDER, 1);
1815 if (order <= MAX_ORDER)
1816 return order;
1817 return -ENOSYS;
1821 * Figure out what the alignment of the objects will be.
1823 static unsigned long calculate_alignment(unsigned long flags,
1824 unsigned long align, unsigned long size)
1827 * If the user wants hardware cache aligned objects then
1828 * follow that suggestion if the object is sufficiently
1829 * large.
1831 * The hardware cache alignment cannot override the
1832 * specified alignment though. If that is greater
1833 * then use it.
1835 if ((flags & SLAB_HWCACHE_ALIGN) &&
1836 size > cache_line_size() / 2)
1837 return max_t(unsigned long, align, cache_line_size());
1839 if (align < ARCH_SLAB_MINALIGN)
1840 return ARCH_SLAB_MINALIGN;
1842 return ALIGN(align, sizeof(void *));
1845 static void init_kmem_cache_node(struct kmem_cache_node *n)
1847 n->nr_partial = 0;
1848 atomic_long_set(&n->nr_slabs, 0);
1849 spin_lock_init(&n->list_lock);
1850 INIT_LIST_HEAD(&n->partial);
1851 INIT_LIST_HEAD(&n->full);
1854 #ifdef CONFIG_NUMA
1856 * No kmalloc_node yet so do it by hand. We know that this is the first
1857 * slab on the node for this slabcache. There are no concurrent accesses
1858 * possible.
1860 * Note that this function only works on the kmalloc_node_cache
1861 * when allocating for the kmalloc_node_cache.
1863 static struct kmem_cache_node * __init early_kmem_cache_node_alloc(gfp_t gfpflags,
1864 int node)
1866 struct page *page;
1867 struct kmem_cache_node *n;
1869 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
1871 page = new_slab(kmalloc_caches, gfpflags | GFP_THISNODE, node);
1873 BUG_ON(!page);
1874 n = page->freelist;
1875 BUG_ON(!n);
1876 page->freelist = get_freepointer(kmalloc_caches, n);
1877 page->inuse++;
1878 kmalloc_caches->node[node] = n;
1879 init_object(kmalloc_caches, n, 1);
1880 init_tracking(kmalloc_caches, n);
1881 init_kmem_cache_node(n);
1882 atomic_long_inc(&n->nr_slabs);
1883 add_partial(n, page);
1886 * new_slab() disables interupts. If we do not reenable interrupts here
1887 * then bootup would continue with interrupts disabled.
1889 local_irq_enable();
1890 return n;
1893 static void free_kmem_cache_nodes(struct kmem_cache *s)
1895 int node;
1897 for_each_online_node(node) {
1898 struct kmem_cache_node *n = s->node[node];
1899 if (n && n != &s->local_node)
1900 kmem_cache_free(kmalloc_caches, n);
1901 s->node[node] = NULL;
1905 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1907 int node;
1908 int local_node;
1910 if (slab_state >= UP)
1911 local_node = page_to_nid(virt_to_page(s));
1912 else
1913 local_node = 0;
1915 for_each_online_node(node) {
1916 struct kmem_cache_node *n;
1918 if (local_node == node)
1919 n = &s->local_node;
1920 else {
1921 if (slab_state == DOWN) {
1922 n = early_kmem_cache_node_alloc(gfpflags,
1923 node);
1924 continue;
1926 n = kmem_cache_alloc_node(kmalloc_caches,
1927 gfpflags, node);
1929 if (!n) {
1930 free_kmem_cache_nodes(s);
1931 return 0;
1935 s->node[node] = n;
1936 init_kmem_cache_node(n);
1938 return 1;
1940 #else
1941 static void free_kmem_cache_nodes(struct kmem_cache *s)
1945 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1947 init_kmem_cache_node(&s->local_node);
1948 return 1;
1950 #endif
1953 * calculate_sizes() determines the order and the distribution of data within
1954 * a slab object.
1956 static int calculate_sizes(struct kmem_cache *s)
1958 unsigned long flags = s->flags;
1959 unsigned long size = s->objsize;
1960 unsigned long align = s->align;
1963 * Determine if we can poison the object itself. If the user of
1964 * the slab may touch the object after free or before allocation
1965 * then we should never poison the object itself.
1967 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
1968 !s->ctor)
1969 s->flags |= __OBJECT_POISON;
1970 else
1971 s->flags &= ~__OBJECT_POISON;
1974 * Round up object size to the next word boundary. We can only
1975 * place the free pointer at word boundaries and this determines
1976 * the possible location of the free pointer.
1978 size = ALIGN(size, sizeof(void *));
1980 #ifdef CONFIG_SLUB_DEBUG
1982 * If we are Redzoning then check if there is some space between the
1983 * end of the object and the free pointer. If not then add an
1984 * additional word to have some bytes to store Redzone information.
1986 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
1987 size += sizeof(void *);
1988 #endif
1991 * With that we have determined the number of bytes in actual use
1992 * by the object. This is the potential offset to the free pointer.
1994 s->inuse = size;
1996 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
1997 s->ctor)) {
1999 * Relocate free pointer after the object if it is not
2000 * permitted to overwrite the first word of the object on
2001 * kmem_cache_free.
2003 * This is the case if we do RCU, have a constructor or
2004 * destructor or are poisoning the objects.
2006 s->offset = size;
2007 size += sizeof(void *);
2010 #ifdef CONFIG_SLUB_DEBUG
2011 if (flags & SLAB_STORE_USER)
2013 * Need to store information about allocs and frees after
2014 * the object.
2016 size += 2 * sizeof(struct track);
2018 if (flags & SLAB_RED_ZONE)
2020 * Add some empty padding so that we can catch
2021 * overwrites from earlier objects rather than let
2022 * tracking information or the free pointer be
2023 * corrupted if an user writes before the start
2024 * of the object.
2026 size += sizeof(void *);
2027 #endif
2030 * Determine the alignment based on various parameters that the
2031 * user specified and the dynamic determination of cache line size
2032 * on bootup.
2034 align = calculate_alignment(flags, align, s->objsize);
2037 * SLUB stores one object immediately after another beginning from
2038 * offset 0. In order to align the objects we have to simply size
2039 * each object to conform to the alignment.
2041 size = ALIGN(size, align);
2042 s->size = size;
2044 s->order = calculate_order(size);
2045 if (s->order < 0)
2046 return 0;
2049 * Determine the number of objects per slab
2051 s->objects = (PAGE_SIZE << s->order) / size;
2054 * Verify that the number of objects is within permitted limits.
2055 * The page->inuse field is only 16 bit wide! So we cannot have
2056 * more than 64k objects per slab.
2058 if (!s->objects || s->objects > MAX_OBJECTS_PER_SLAB)
2059 return 0;
2060 return 1;
2064 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2065 const char *name, size_t size,
2066 size_t align, unsigned long flags,
2067 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2069 memset(s, 0, kmem_size);
2070 s->name = name;
2071 s->ctor = ctor;
2072 s->objsize = size;
2073 s->flags = flags;
2074 s->align = align;
2075 kmem_cache_open_debug_check(s);
2077 if (!calculate_sizes(s))
2078 goto error;
2080 s->refcount = 1;
2081 #ifdef CONFIG_NUMA
2082 s->defrag_ratio = 100;
2083 #endif
2085 if (init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2086 return 1;
2087 error:
2088 if (flags & SLAB_PANIC)
2089 panic("Cannot create slab %s size=%lu realsize=%u "
2090 "order=%u offset=%u flags=%lx\n",
2091 s->name, (unsigned long)size, s->size, s->order,
2092 s->offset, flags);
2093 return 0;
2097 * Check if a given pointer is valid
2099 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2101 struct page * page;
2103 page = get_object_page(object);
2105 if (!page || s != page->slab)
2106 /* No slab or wrong slab */
2107 return 0;
2109 if (!check_valid_pointer(s, page, object))
2110 return 0;
2113 * We could also check if the object is on the slabs freelist.
2114 * But this would be too expensive and it seems that the main
2115 * purpose of kmem_ptr_valid is to check if the object belongs
2116 * to a certain slab.
2118 return 1;
2120 EXPORT_SYMBOL(kmem_ptr_validate);
2123 * Determine the size of a slab object
2125 unsigned int kmem_cache_size(struct kmem_cache *s)
2127 return s->objsize;
2129 EXPORT_SYMBOL(kmem_cache_size);
2131 const char *kmem_cache_name(struct kmem_cache *s)
2133 return s->name;
2135 EXPORT_SYMBOL(kmem_cache_name);
2138 * Attempt to free all slabs on a node. Return the number of slabs we
2139 * were unable to free.
2141 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2142 struct list_head *list)
2144 int slabs_inuse = 0;
2145 unsigned long flags;
2146 struct page *page, *h;
2148 spin_lock_irqsave(&n->list_lock, flags);
2149 list_for_each_entry_safe(page, h, list, lru)
2150 if (!page->inuse) {
2151 list_del(&page->lru);
2152 discard_slab(s, page);
2153 } else
2154 slabs_inuse++;
2155 spin_unlock_irqrestore(&n->list_lock, flags);
2156 return slabs_inuse;
2160 * Release all resources used by a slab cache.
2162 static int kmem_cache_close(struct kmem_cache *s)
2164 int node;
2166 flush_all(s);
2168 /* Attempt to free all objects */
2169 for_each_online_node(node) {
2170 struct kmem_cache_node *n = get_node(s, node);
2172 n->nr_partial -= free_list(s, n, &n->partial);
2173 if (atomic_long_read(&n->nr_slabs))
2174 return 1;
2176 free_kmem_cache_nodes(s);
2177 return 0;
2181 * Close a cache and release the kmem_cache structure
2182 * (must be used for caches created using kmem_cache_create)
2184 void kmem_cache_destroy(struct kmem_cache *s)
2186 down_write(&slub_lock);
2187 s->refcount--;
2188 if (!s->refcount) {
2189 list_del(&s->list);
2190 if (kmem_cache_close(s))
2191 WARN_ON(1);
2192 sysfs_slab_remove(s);
2193 kfree(s);
2195 up_write(&slub_lock);
2197 EXPORT_SYMBOL(kmem_cache_destroy);
2199 /********************************************************************
2200 * Kmalloc subsystem
2201 *******************************************************************/
2203 struct kmem_cache kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __cacheline_aligned;
2204 EXPORT_SYMBOL(kmalloc_caches);
2206 #ifdef CONFIG_ZONE_DMA
2207 static struct kmem_cache *kmalloc_caches_dma[KMALLOC_SHIFT_HIGH + 1];
2208 #endif
2210 static int __init setup_slub_min_order(char *str)
2212 get_option (&str, &slub_min_order);
2214 return 1;
2217 __setup("slub_min_order=", setup_slub_min_order);
2219 static int __init setup_slub_max_order(char *str)
2221 get_option (&str, &slub_max_order);
2223 return 1;
2226 __setup("slub_max_order=", setup_slub_max_order);
2228 static int __init setup_slub_min_objects(char *str)
2230 get_option (&str, &slub_min_objects);
2232 return 1;
2235 __setup("slub_min_objects=", setup_slub_min_objects);
2237 static int __init setup_slub_nomerge(char *str)
2239 slub_nomerge = 1;
2240 return 1;
2243 __setup("slub_nomerge", setup_slub_nomerge);
2245 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2246 const char *name, int size, gfp_t gfp_flags)
2248 unsigned int flags = 0;
2250 if (gfp_flags & SLUB_DMA)
2251 flags = SLAB_CACHE_DMA;
2253 down_write(&slub_lock);
2254 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2255 flags, NULL))
2256 goto panic;
2258 list_add(&s->list, &slab_caches);
2259 up_write(&slub_lock);
2260 if (sysfs_slab_add(s))
2261 goto panic;
2262 return s;
2264 panic:
2265 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2268 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2270 int index = kmalloc_index(size);
2272 if (!index)
2273 return NULL;
2275 /* Allocation too large? */
2276 BUG_ON(index < 0);
2278 #ifdef CONFIG_ZONE_DMA
2279 if ((flags & SLUB_DMA)) {
2280 struct kmem_cache *s;
2281 struct kmem_cache *x;
2282 char *text;
2283 size_t realsize;
2285 s = kmalloc_caches_dma[index];
2286 if (s)
2287 return s;
2289 /* Dynamically create dma cache */
2290 x = kmalloc(kmem_size, flags & ~SLUB_DMA);
2291 if (!x)
2292 panic("Unable to allocate memory for dma cache\n");
2294 if (index <= KMALLOC_SHIFT_HIGH)
2295 realsize = 1 << index;
2296 else {
2297 if (index == 1)
2298 realsize = 96;
2299 else
2300 realsize = 192;
2303 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2304 (unsigned int)realsize);
2305 s = create_kmalloc_cache(x, text, realsize, flags);
2306 kmalloc_caches_dma[index] = s;
2307 return s;
2309 #endif
2310 return &kmalloc_caches[index];
2313 void *__kmalloc(size_t size, gfp_t flags)
2315 struct kmem_cache *s = get_slab(size, flags);
2317 if (s)
2318 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2319 return ZERO_SIZE_PTR;
2321 EXPORT_SYMBOL(__kmalloc);
2323 #ifdef CONFIG_NUMA
2324 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2326 struct kmem_cache *s = get_slab(size, flags);
2328 if (s)
2329 return slab_alloc(s, flags, node, __builtin_return_address(0));
2330 return ZERO_SIZE_PTR;
2332 EXPORT_SYMBOL(__kmalloc_node);
2333 #endif
2335 size_t ksize(const void *object)
2337 struct page *page;
2338 struct kmem_cache *s;
2340 if (object == ZERO_SIZE_PTR)
2341 return 0;
2343 page = get_object_page(object);
2344 BUG_ON(!page);
2345 s = page->slab;
2346 BUG_ON(!s);
2349 * Debugging requires use of the padding between object
2350 * and whatever may come after it.
2352 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2353 return s->objsize;
2356 * If we have the need to store the freelist pointer
2357 * back there or track user information then we can
2358 * only use the space before that information.
2360 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2361 return s->inuse;
2364 * Else we can use all the padding etc for the allocation
2366 return s->size;
2368 EXPORT_SYMBOL(ksize);
2370 void kfree(const void *x)
2372 struct kmem_cache *s;
2373 struct page *page;
2376 * This has to be an unsigned comparison. According to Linus
2377 * some gcc version treat a pointer as a signed entity. Then
2378 * this comparison would be true for all "negative" pointers
2379 * (which would cover the whole upper half of the address space).
2381 if ((unsigned long)x <= (unsigned long)ZERO_SIZE_PTR)
2382 return;
2384 page = virt_to_head_page(x);
2385 s = page->slab;
2387 slab_free(s, page, (void *)x, __builtin_return_address(0));
2389 EXPORT_SYMBOL(kfree);
2392 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2393 * the remaining slabs by the number of items in use. The slabs with the
2394 * most items in use come first. New allocations will then fill those up
2395 * and thus they can be removed from the partial lists.
2397 * The slabs with the least items are placed last. This results in them
2398 * being allocated from last increasing the chance that the last objects
2399 * are freed in them.
2401 int kmem_cache_shrink(struct kmem_cache *s)
2403 int node;
2404 int i;
2405 struct kmem_cache_node *n;
2406 struct page *page;
2407 struct page *t;
2408 struct list_head *slabs_by_inuse =
2409 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2410 unsigned long flags;
2412 if (!slabs_by_inuse)
2413 return -ENOMEM;
2415 flush_all(s);
2416 for_each_online_node(node) {
2417 n = get_node(s, node);
2419 if (!n->nr_partial)
2420 continue;
2422 for (i = 0; i < s->objects; i++)
2423 INIT_LIST_HEAD(slabs_by_inuse + i);
2425 spin_lock_irqsave(&n->list_lock, flags);
2428 * Build lists indexed by the items in use in each slab.
2430 * Note that concurrent frees may occur while we hold the
2431 * list_lock. page->inuse here is the upper limit.
2433 list_for_each_entry_safe(page, t, &n->partial, lru) {
2434 if (!page->inuse && slab_trylock(page)) {
2436 * Must hold slab lock here because slab_free
2437 * may have freed the last object and be
2438 * waiting to release the slab.
2440 list_del(&page->lru);
2441 n->nr_partial--;
2442 slab_unlock(page);
2443 discard_slab(s, page);
2444 } else {
2445 if (n->nr_partial > MAX_PARTIAL)
2446 list_move(&page->lru,
2447 slabs_by_inuse + page->inuse);
2451 if (n->nr_partial <= MAX_PARTIAL)
2452 goto out;
2455 * Rebuild the partial list with the slabs filled up most
2456 * first and the least used slabs at the end.
2458 for (i = s->objects - 1; i >= 0; i--)
2459 list_splice(slabs_by_inuse + i, n->partial.prev);
2461 out:
2462 spin_unlock_irqrestore(&n->list_lock, flags);
2465 kfree(slabs_by_inuse);
2466 return 0;
2468 EXPORT_SYMBOL(kmem_cache_shrink);
2471 * krealloc - reallocate memory. The contents will remain unchanged.
2472 * @p: object to reallocate memory for.
2473 * @new_size: how many bytes of memory are required.
2474 * @flags: the type of memory to allocate.
2476 * The contents of the object pointed to are preserved up to the
2477 * lesser of the new and old sizes. If @p is %NULL, krealloc()
2478 * behaves exactly like kmalloc(). If @size is 0 and @p is not a
2479 * %NULL pointer, the object pointed to is freed.
2481 void *krealloc(const void *p, size_t new_size, gfp_t flags)
2483 void *ret;
2484 size_t ks;
2486 if (unlikely(!p || p == ZERO_SIZE_PTR))
2487 return kmalloc(new_size, flags);
2489 if (unlikely(!new_size)) {
2490 kfree(p);
2491 return ZERO_SIZE_PTR;
2494 ks = ksize(p);
2495 if (ks >= new_size)
2496 return (void *)p;
2498 ret = kmalloc(new_size, flags);
2499 if (ret) {
2500 memcpy(ret, p, min(new_size, ks));
2501 kfree(p);
2503 return ret;
2505 EXPORT_SYMBOL(krealloc);
2507 /********************************************************************
2508 * Basic setup of slabs
2509 *******************************************************************/
2511 void __init kmem_cache_init(void)
2513 int i;
2514 int caches = 0;
2516 #ifdef CONFIG_NUMA
2518 * Must first have the slab cache available for the allocations of the
2519 * struct kmem_cache_node's. There is special bootstrap code in
2520 * kmem_cache_open for slab_state == DOWN.
2522 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2523 sizeof(struct kmem_cache_node), GFP_KERNEL);
2524 kmalloc_caches[0].refcount = -1;
2525 caches++;
2526 #endif
2528 /* Able to allocate the per node structures */
2529 slab_state = PARTIAL;
2531 /* Caches that are not of the two-to-the-power-of size */
2532 if (KMALLOC_MIN_SIZE <= 64) {
2533 create_kmalloc_cache(&kmalloc_caches[1],
2534 "kmalloc-96", 96, GFP_KERNEL);
2535 caches++;
2537 if (KMALLOC_MIN_SIZE <= 128) {
2538 create_kmalloc_cache(&kmalloc_caches[2],
2539 "kmalloc-192", 192, GFP_KERNEL);
2540 caches++;
2543 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
2544 create_kmalloc_cache(&kmalloc_caches[i],
2545 "kmalloc", 1 << i, GFP_KERNEL);
2546 caches++;
2549 slab_state = UP;
2551 /* Provide the correct kmalloc names now that the caches are up */
2552 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++)
2553 kmalloc_caches[i]. name =
2554 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2556 #ifdef CONFIG_SMP
2557 register_cpu_notifier(&slab_notifier);
2558 #endif
2560 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2561 nr_cpu_ids * sizeof(struct page *);
2563 printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2564 " CPUs=%d, Nodes=%d\n",
2565 caches, cache_line_size(),
2566 slub_min_order, slub_max_order, slub_min_objects,
2567 nr_cpu_ids, nr_node_ids);
2571 * Find a mergeable slab cache
2573 static int slab_unmergeable(struct kmem_cache *s)
2575 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2576 return 1;
2578 if (s->ctor)
2579 return 1;
2582 * We may have set a slab to be unmergeable during bootstrap.
2584 if (s->refcount < 0)
2585 return 1;
2587 return 0;
2590 static struct kmem_cache *find_mergeable(size_t size,
2591 size_t align, unsigned long flags,
2592 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2594 struct kmem_cache *s;
2596 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2597 return NULL;
2599 if (ctor)
2600 return NULL;
2602 size = ALIGN(size, sizeof(void *));
2603 align = calculate_alignment(flags, align, size);
2604 size = ALIGN(size, align);
2606 list_for_each_entry(s, &slab_caches, list) {
2607 if (slab_unmergeable(s))
2608 continue;
2610 if (size > s->size)
2611 continue;
2613 if (((flags | slub_debug) & SLUB_MERGE_SAME) !=
2614 (s->flags & SLUB_MERGE_SAME))
2615 continue;
2617 * Check if alignment is compatible.
2618 * Courtesy of Adrian Drzewiecki
2620 if ((s->size & ~(align -1)) != s->size)
2621 continue;
2623 if (s->size - size >= sizeof(void *))
2624 continue;
2626 return s;
2628 return NULL;
2631 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2632 size_t align, unsigned long flags,
2633 void (*ctor)(void *, struct kmem_cache *, unsigned long),
2634 void (*dtor)(void *, struct kmem_cache *, unsigned long))
2636 struct kmem_cache *s;
2638 BUG_ON(dtor);
2639 down_write(&slub_lock);
2640 s = find_mergeable(size, align, flags, ctor);
2641 if (s) {
2642 s->refcount++;
2644 * Adjust the object sizes so that we clear
2645 * the complete object on kzalloc.
2647 s->objsize = max(s->objsize, (int)size);
2648 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2649 if (sysfs_slab_alias(s, name))
2650 goto err;
2651 } else {
2652 s = kmalloc(kmem_size, GFP_KERNEL);
2653 if (s && kmem_cache_open(s, GFP_KERNEL, name,
2654 size, align, flags, ctor)) {
2655 if (sysfs_slab_add(s)) {
2656 kfree(s);
2657 goto err;
2659 list_add(&s->list, &slab_caches);
2660 } else
2661 kfree(s);
2663 up_write(&slub_lock);
2664 return s;
2666 err:
2667 up_write(&slub_lock);
2668 if (flags & SLAB_PANIC)
2669 panic("Cannot create slabcache %s\n", name);
2670 else
2671 s = NULL;
2672 return s;
2674 EXPORT_SYMBOL(kmem_cache_create);
2676 void *kmem_cache_zalloc(struct kmem_cache *s, gfp_t flags)
2678 void *x;
2680 x = slab_alloc(s, flags, -1, __builtin_return_address(0));
2681 if (x)
2682 memset(x, 0, s->objsize);
2683 return x;
2685 EXPORT_SYMBOL(kmem_cache_zalloc);
2687 #ifdef CONFIG_SMP
2689 * Use the cpu notifier to insure that the cpu slabs are flushed when
2690 * necessary.
2692 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2693 unsigned long action, void *hcpu)
2695 long cpu = (long)hcpu;
2696 struct kmem_cache *s;
2697 unsigned long flags;
2699 switch (action) {
2700 case CPU_UP_CANCELED:
2701 case CPU_UP_CANCELED_FROZEN:
2702 case CPU_DEAD:
2703 case CPU_DEAD_FROZEN:
2704 down_read(&slub_lock);
2705 list_for_each_entry(s, &slab_caches, list) {
2706 local_irq_save(flags);
2707 __flush_cpu_slab(s, cpu);
2708 local_irq_restore(flags);
2710 up_read(&slub_lock);
2711 break;
2712 default:
2713 break;
2715 return NOTIFY_OK;
2718 static struct notifier_block __cpuinitdata slab_notifier =
2719 { &slab_cpuup_callback, NULL, 0 };
2721 #endif
2723 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2725 struct kmem_cache *s = get_slab(size, gfpflags);
2727 if (!s)
2728 return ZERO_SIZE_PTR;
2730 return slab_alloc(s, gfpflags, -1, caller);
2733 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2734 int node, void *caller)
2736 struct kmem_cache *s = get_slab(size, gfpflags);
2738 if (!s)
2739 return ZERO_SIZE_PTR;
2741 return slab_alloc(s, gfpflags, node, caller);
2744 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2745 static int validate_slab(struct kmem_cache *s, struct page *page)
2747 void *p;
2748 void *addr = page_address(page);
2749 DECLARE_BITMAP(map, s->objects);
2751 if (!check_slab(s, page) ||
2752 !on_freelist(s, page, NULL))
2753 return 0;
2755 /* Now we know that a valid freelist exists */
2756 bitmap_zero(map, s->objects);
2758 for_each_free_object(p, s, page->freelist) {
2759 set_bit(slab_index(p, s, addr), map);
2760 if (!check_object(s, page, p, 0))
2761 return 0;
2764 for_each_object(p, s, addr)
2765 if (!test_bit(slab_index(p, s, addr), map))
2766 if (!check_object(s, page, p, 1))
2767 return 0;
2768 return 1;
2771 static void validate_slab_slab(struct kmem_cache *s, struct page *page)
2773 if (slab_trylock(page)) {
2774 validate_slab(s, page);
2775 slab_unlock(page);
2776 } else
2777 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
2778 s->name, page);
2780 if (s->flags & DEBUG_DEFAULT_FLAGS) {
2781 if (!SlabDebug(page))
2782 printk(KERN_ERR "SLUB %s: SlabDebug not set "
2783 "on slab 0x%p\n", s->name, page);
2784 } else {
2785 if (SlabDebug(page))
2786 printk(KERN_ERR "SLUB %s: SlabDebug set on "
2787 "slab 0x%p\n", s->name, page);
2791 static int validate_slab_node(struct kmem_cache *s, struct kmem_cache_node *n)
2793 unsigned long count = 0;
2794 struct page *page;
2795 unsigned long flags;
2797 spin_lock_irqsave(&n->list_lock, flags);
2799 list_for_each_entry(page, &n->partial, lru) {
2800 validate_slab_slab(s, page);
2801 count++;
2803 if (count != n->nr_partial)
2804 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
2805 "counter=%ld\n", s->name, count, n->nr_partial);
2807 if (!(s->flags & SLAB_STORE_USER))
2808 goto out;
2810 list_for_each_entry(page, &n->full, lru) {
2811 validate_slab_slab(s, page);
2812 count++;
2814 if (count != atomic_long_read(&n->nr_slabs))
2815 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
2816 "counter=%ld\n", s->name, count,
2817 atomic_long_read(&n->nr_slabs));
2819 out:
2820 spin_unlock_irqrestore(&n->list_lock, flags);
2821 return count;
2824 static unsigned long validate_slab_cache(struct kmem_cache *s)
2826 int node;
2827 unsigned long count = 0;
2829 flush_all(s);
2830 for_each_online_node(node) {
2831 struct kmem_cache_node *n = get_node(s, node);
2833 count += validate_slab_node(s, n);
2835 return count;
2838 #ifdef SLUB_RESILIENCY_TEST
2839 static void resiliency_test(void)
2841 u8 *p;
2843 printk(KERN_ERR "SLUB resiliency testing\n");
2844 printk(KERN_ERR "-----------------------\n");
2845 printk(KERN_ERR "A. Corruption after allocation\n");
2847 p = kzalloc(16, GFP_KERNEL);
2848 p[16] = 0x12;
2849 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
2850 " 0x12->0x%p\n\n", p + 16);
2852 validate_slab_cache(kmalloc_caches + 4);
2854 /* Hmmm... The next two are dangerous */
2855 p = kzalloc(32, GFP_KERNEL);
2856 p[32 + sizeof(void *)] = 0x34;
2857 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
2858 " 0x34 -> -0x%p\n", p);
2859 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2861 validate_slab_cache(kmalloc_caches + 5);
2862 p = kzalloc(64, GFP_KERNEL);
2863 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
2864 *p = 0x56;
2865 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
2867 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2868 validate_slab_cache(kmalloc_caches + 6);
2870 printk(KERN_ERR "\nB. Corruption after free\n");
2871 p = kzalloc(128, GFP_KERNEL);
2872 kfree(p);
2873 *p = 0x78;
2874 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
2875 validate_slab_cache(kmalloc_caches + 7);
2877 p = kzalloc(256, GFP_KERNEL);
2878 kfree(p);
2879 p[50] = 0x9a;
2880 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
2881 validate_slab_cache(kmalloc_caches + 8);
2883 p = kzalloc(512, GFP_KERNEL);
2884 kfree(p);
2885 p[512] = 0xab;
2886 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
2887 validate_slab_cache(kmalloc_caches + 9);
2889 #else
2890 static void resiliency_test(void) {};
2891 #endif
2894 * Generate lists of code addresses where slabcache objects are allocated
2895 * and freed.
2898 struct location {
2899 unsigned long count;
2900 void *addr;
2901 long long sum_time;
2902 long min_time;
2903 long max_time;
2904 long min_pid;
2905 long max_pid;
2906 cpumask_t cpus;
2907 nodemask_t nodes;
2910 struct loc_track {
2911 unsigned long max;
2912 unsigned long count;
2913 struct location *loc;
2916 static void free_loc_track(struct loc_track *t)
2918 if (t->max)
2919 free_pages((unsigned long)t->loc,
2920 get_order(sizeof(struct location) * t->max));
2923 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
2925 struct location *l;
2926 int order;
2928 order = get_order(sizeof(struct location) * max);
2930 l = (void *)__get_free_pages(flags, order);
2931 if (!l)
2932 return 0;
2934 if (t->count) {
2935 memcpy(l, t->loc, sizeof(struct location) * t->count);
2936 free_loc_track(t);
2938 t->max = max;
2939 t->loc = l;
2940 return 1;
2943 static int add_location(struct loc_track *t, struct kmem_cache *s,
2944 const struct track *track)
2946 long start, end, pos;
2947 struct location *l;
2948 void *caddr;
2949 unsigned long age = jiffies - track->when;
2951 start = -1;
2952 end = t->count;
2954 for ( ; ; ) {
2955 pos = start + (end - start + 1) / 2;
2958 * There is nothing at "end". If we end up there
2959 * we need to add something to before end.
2961 if (pos == end)
2962 break;
2964 caddr = t->loc[pos].addr;
2965 if (track->addr == caddr) {
2967 l = &t->loc[pos];
2968 l->count++;
2969 if (track->when) {
2970 l->sum_time += age;
2971 if (age < l->min_time)
2972 l->min_time = age;
2973 if (age > l->max_time)
2974 l->max_time = age;
2976 if (track->pid < l->min_pid)
2977 l->min_pid = track->pid;
2978 if (track->pid > l->max_pid)
2979 l->max_pid = track->pid;
2981 cpu_set(track->cpu, l->cpus);
2983 node_set(page_to_nid(virt_to_page(track)), l->nodes);
2984 return 1;
2987 if (track->addr < caddr)
2988 end = pos;
2989 else
2990 start = pos;
2994 * Not found. Insert new tracking element.
2996 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
2997 return 0;
2999 l = t->loc + pos;
3000 if (pos < t->count)
3001 memmove(l + 1, l,
3002 (t->count - pos) * sizeof(struct location));
3003 t->count++;
3004 l->count = 1;
3005 l->addr = track->addr;
3006 l->sum_time = age;
3007 l->min_time = age;
3008 l->max_time = age;
3009 l->min_pid = track->pid;
3010 l->max_pid = track->pid;
3011 cpus_clear(l->cpus);
3012 cpu_set(track->cpu, l->cpus);
3013 nodes_clear(l->nodes);
3014 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3015 return 1;
3018 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3019 struct page *page, enum track_item alloc)
3021 void *addr = page_address(page);
3022 DECLARE_BITMAP(map, s->objects);
3023 void *p;
3025 bitmap_zero(map, s->objects);
3026 for_each_free_object(p, s, page->freelist)
3027 set_bit(slab_index(p, s, addr), map);
3029 for_each_object(p, s, addr)
3030 if (!test_bit(slab_index(p, s, addr), map))
3031 add_location(t, s, get_track(s, p, alloc));
3034 static int list_locations(struct kmem_cache *s, char *buf,
3035 enum track_item alloc)
3037 int n = 0;
3038 unsigned long i;
3039 struct loc_track t = { 0, 0, NULL };
3040 int node;
3042 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3043 GFP_KERNEL))
3044 return sprintf(buf, "Out of memory\n");
3046 /* Push back cpu slabs */
3047 flush_all(s);
3049 for_each_online_node(node) {
3050 struct kmem_cache_node *n = get_node(s, node);
3051 unsigned long flags;
3052 struct page *page;
3054 if (!atomic_read(&n->nr_slabs))
3055 continue;
3057 spin_lock_irqsave(&n->list_lock, flags);
3058 list_for_each_entry(page, &n->partial, lru)
3059 process_slab(&t, s, page, alloc);
3060 list_for_each_entry(page, &n->full, lru)
3061 process_slab(&t, s, page, alloc);
3062 spin_unlock_irqrestore(&n->list_lock, flags);
3065 for (i = 0; i < t.count; i++) {
3066 struct location *l = &t.loc[i];
3068 if (n > PAGE_SIZE - 100)
3069 break;
3070 n += sprintf(buf + n, "%7ld ", l->count);
3072 if (l->addr)
3073 n += sprint_symbol(buf + n, (unsigned long)l->addr);
3074 else
3075 n += sprintf(buf + n, "<not-available>");
3077 if (l->sum_time != l->min_time) {
3078 unsigned long remainder;
3080 n += sprintf(buf + n, " age=%ld/%ld/%ld",
3081 l->min_time,
3082 div_long_long_rem(l->sum_time, l->count, &remainder),
3083 l->max_time);
3084 } else
3085 n += sprintf(buf + n, " age=%ld",
3086 l->min_time);
3088 if (l->min_pid != l->max_pid)
3089 n += sprintf(buf + n, " pid=%ld-%ld",
3090 l->min_pid, l->max_pid);
3091 else
3092 n += sprintf(buf + n, " pid=%ld",
3093 l->min_pid);
3095 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3096 n < PAGE_SIZE - 60) {
3097 n += sprintf(buf + n, " cpus=");
3098 n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3099 l->cpus);
3102 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3103 n < PAGE_SIZE - 60) {
3104 n += sprintf(buf + n, " nodes=");
3105 n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3106 l->nodes);
3109 n += sprintf(buf + n, "\n");
3112 free_loc_track(&t);
3113 if (!t.count)
3114 n += sprintf(buf, "No data\n");
3115 return n;
3118 static unsigned long count_partial(struct kmem_cache_node *n)
3120 unsigned long flags;
3121 unsigned long x = 0;
3122 struct page *page;
3124 spin_lock_irqsave(&n->list_lock, flags);
3125 list_for_each_entry(page, &n->partial, lru)
3126 x += page->inuse;
3127 spin_unlock_irqrestore(&n->list_lock, flags);
3128 return x;
3131 enum slab_stat_type {
3132 SL_FULL,
3133 SL_PARTIAL,
3134 SL_CPU,
3135 SL_OBJECTS
3138 #define SO_FULL (1 << SL_FULL)
3139 #define SO_PARTIAL (1 << SL_PARTIAL)
3140 #define SO_CPU (1 << SL_CPU)
3141 #define SO_OBJECTS (1 << SL_OBJECTS)
3143 static unsigned long slab_objects(struct kmem_cache *s,
3144 char *buf, unsigned long flags)
3146 unsigned long total = 0;
3147 int cpu;
3148 int node;
3149 int x;
3150 unsigned long *nodes;
3151 unsigned long *per_cpu;
3153 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3154 per_cpu = nodes + nr_node_ids;
3156 for_each_possible_cpu(cpu) {
3157 struct page *page = s->cpu_slab[cpu];
3158 int node;
3160 if (page) {
3161 node = page_to_nid(page);
3162 if (flags & SO_CPU) {
3163 int x = 0;
3165 if (flags & SO_OBJECTS)
3166 x = page->inuse;
3167 else
3168 x = 1;
3169 total += x;
3170 nodes[node] += x;
3172 per_cpu[node]++;
3176 for_each_online_node(node) {
3177 struct kmem_cache_node *n = get_node(s, node);
3179 if (flags & SO_PARTIAL) {
3180 if (flags & SO_OBJECTS)
3181 x = count_partial(n);
3182 else
3183 x = n->nr_partial;
3184 total += x;
3185 nodes[node] += x;
3188 if (flags & SO_FULL) {
3189 int full_slabs = atomic_read(&n->nr_slabs)
3190 - per_cpu[node]
3191 - n->nr_partial;
3193 if (flags & SO_OBJECTS)
3194 x = full_slabs * s->objects;
3195 else
3196 x = full_slabs;
3197 total += x;
3198 nodes[node] += x;
3202 x = sprintf(buf, "%lu", total);
3203 #ifdef CONFIG_NUMA
3204 for_each_online_node(node)
3205 if (nodes[node])
3206 x += sprintf(buf + x, " N%d=%lu",
3207 node, nodes[node]);
3208 #endif
3209 kfree(nodes);
3210 return x + sprintf(buf + x, "\n");
3213 static int any_slab_objects(struct kmem_cache *s)
3215 int node;
3216 int cpu;
3218 for_each_possible_cpu(cpu)
3219 if (s->cpu_slab[cpu])
3220 return 1;
3222 for_each_node(node) {
3223 struct kmem_cache_node *n = get_node(s, node);
3225 if (n->nr_partial || atomic_read(&n->nr_slabs))
3226 return 1;
3228 return 0;
3231 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3232 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3234 struct slab_attribute {
3235 struct attribute attr;
3236 ssize_t (*show)(struct kmem_cache *s, char *buf);
3237 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3240 #define SLAB_ATTR_RO(_name) \
3241 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3243 #define SLAB_ATTR(_name) \
3244 static struct slab_attribute _name##_attr = \
3245 __ATTR(_name, 0644, _name##_show, _name##_store)
3247 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3249 return sprintf(buf, "%d\n", s->size);
3251 SLAB_ATTR_RO(slab_size);
3253 static ssize_t align_show(struct kmem_cache *s, char *buf)
3255 return sprintf(buf, "%d\n", s->align);
3257 SLAB_ATTR_RO(align);
3259 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3261 return sprintf(buf, "%d\n", s->objsize);
3263 SLAB_ATTR_RO(object_size);
3265 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3267 return sprintf(buf, "%d\n", s->objects);
3269 SLAB_ATTR_RO(objs_per_slab);
3271 static ssize_t order_show(struct kmem_cache *s, char *buf)
3273 return sprintf(buf, "%d\n", s->order);
3275 SLAB_ATTR_RO(order);
3277 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3279 if (s->ctor) {
3280 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3282 return n + sprintf(buf + n, "\n");
3284 return 0;
3286 SLAB_ATTR_RO(ctor);
3288 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3290 return sprintf(buf, "%d\n", s->refcount - 1);
3292 SLAB_ATTR_RO(aliases);
3294 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3296 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3298 SLAB_ATTR_RO(slabs);
3300 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3302 return slab_objects(s, buf, SO_PARTIAL);
3304 SLAB_ATTR_RO(partial);
3306 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3308 return slab_objects(s, buf, SO_CPU);
3310 SLAB_ATTR_RO(cpu_slabs);
3312 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3314 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3316 SLAB_ATTR_RO(objects);
3318 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3320 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3323 static ssize_t sanity_checks_store(struct kmem_cache *s,
3324 const char *buf, size_t length)
3326 s->flags &= ~SLAB_DEBUG_FREE;
3327 if (buf[0] == '1')
3328 s->flags |= SLAB_DEBUG_FREE;
3329 return length;
3331 SLAB_ATTR(sanity_checks);
3333 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3335 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3338 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3339 size_t length)
3341 s->flags &= ~SLAB_TRACE;
3342 if (buf[0] == '1')
3343 s->flags |= SLAB_TRACE;
3344 return length;
3346 SLAB_ATTR(trace);
3348 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3350 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3353 static ssize_t reclaim_account_store(struct kmem_cache *s,
3354 const char *buf, size_t length)
3356 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3357 if (buf[0] == '1')
3358 s->flags |= SLAB_RECLAIM_ACCOUNT;
3359 return length;
3361 SLAB_ATTR(reclaim_account);
3363 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3365 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3367 SLAB_ATTR_RO(hwcache_align);
3369 #ifdef CONFIG_ZONE_DMA
3370 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3372 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3374 SLAB_ATTR_RO(cache_dma);
3375 #endif
3377 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3379 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3381 SLAB_ATTR_RO(destroy_by_rcu);
3383 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3385 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3388 static ssize_t red_zone_store(struct kmem_cache *s,
3389 const char *buf, size_t length)
3391 if (any_slab_objects(s))
3392 return -EBUSY;
3394 s->flags &= ~SLAB_RED_ZONE;
3395 if (buf[0] == '1')
3396 s->flags |= SLAB_RED_ZONE;
3397 calculate_sizes(s);
3398 return length;
3400 SLAB_ATTR(red_zone);
3402 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3404 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3407 static ssize_t poison_store(struct kmem_cache *s,
3408 const char *buf, size_t length)
3410 if (any_slab_objects(s))
3411 return -EBUSY;
3413 s->flags &= ~SLAB_POISON;
3414 if (buf[0] == '1')
3415 s->flags |= SLAB_POISON;
3416 calculate_sizes(s);
3417 return length;
3419 SLAB_ATTR(poison);
3421 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3423 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3426 static ssize_t store_user_store(struct kmem_cache *s,
3427 const char *buf, size_t length)
3429 if (any_slab_objects(s))
3430 return -EBUSY;
3432 s->flags &= ~SLAB_STORE_USER;
3433 if (buf[0] == '1')
3434 s->flags |= SLAB_STORE_USER;
3435 calculate_sizes(s);
3436 return length;
3438 SLAB_ATTR(store_user);
3440 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3442 return 0;
3445 static ssize_t validate_store(struct kmem_cache *s,
3446 const char *buf, size_t length)
3448 if (buf[0] == '1')
3449 validate_slab_cache(s);
3450 else
3451 return -EINVAL;
3452 return length;
3454 SLAB_ATTR(validate);
3456 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3458 return 0;
3461 static ssize_t shrink_store(struct kmem_cache *s,
3462 const char *buf, size_t length)
3464 if (buf[0] == '1') {
3465 int rc = kmem_cache_shrink(s);
3467 if (rc)
3468 return rc;
3469 } else
3470 return -EINVAL;
3471 return length;
3473 SLAB_ATTR(shrink);
3475 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3477 if (!(s->flags & SLAB_STORE_USER))
3478 return -ENOSYS;
3479 return list_locations(s, buf, TRACK_ALLOC);
3481 SLAB_ATTR_RO(alloc_calls);
3483 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3485 if (!(s->flags & SLAB_STORE_USER))
3486 return -ENOSYS;
3487 return list_locations(s, buf, TRACK_FREE);
3489 SLAB_ATTR_RO(free_calls);
3491 #ifdef CONFIG_NUMA
3492 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3494 return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3497 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3498 const char *buf, size_t length)
3500 int n = simple_strtoul(buf, NULL, 10);
3502 if (n < 100)
3503 s->defrag_ratio = n * 10;
3504 return length;
3506 SLAB_ATTR(defrag_ratio);
3507 #endif
3509 static struct attribute * slab_attrs[] = {
3510 &slab_size_attr.attr,
3511 &object_size_attr.attr,
3512 &objs_per_slab_attr.attr,
3513 &order_attr.attr,
3514 &objects_attr.attr,
3515 &slabs_attr.attr,
3516 &partial_attr.attr,
3517 &cpu_slabs_attr.attr,
3518 &ctor_attr.attr,
3519 &aliases_attr.attr,
3520 &align_attr.attr,
3521 &sanity_checks_attr.attr,
3522 &trace_attr.attr,
3523 &hwcache_align_attr.attr,
3524 &reclaim_account_attr.attr,
3525 &destroy_by_rcu_attr.attr,
3526 &red_zone_attr.attr,
3527 &poison_attr.attr,
3528 &store_user_attr.attr,
3529 &validate_attr.attr,
3530 &shrink_attr.attr,
3531 &alloc_calls_attr.attr,
3532 &free_calls_attr.attr,
3533 #ifdef CONFIG_ZONE_DMA
3534 &cache_dma_attr.attr,
3535 #endif
3536 #ifdef CONFIG_NUMA
3537 &defrag_ratio_attr.attr,
3538 #endif
3539 NULL
3542 static struct attribute_group slab_attr_group = {
3543 .attrs = slab_attrs,
3546 static ssize_t slab_attr_show(struct kobject *kobj,
3547 struct attribute *attr,
3548 char *buf)
3550 struct slab_attribute *attribute;
3551 struct kmem_cache *s;
3552 int err;
3554 attribute = to_slab_attr(attr);
3555 s = to_slab(kobj);
3557 if (!attribute->show)
3558 return -EIO;
3560 err = attribute->show(s, buf);
3562 return err;
3565 static ssize_t slab_attr_store(struct kobject *kobj,
3566 struct attribute *attr,
3567 const char *buf, size_t len)
3569 struct slab_attribute *attribute;
3570 struct kmem_cache *s;
3571 int err;
3573 attribute = to_slab_attr(attr);
3574 s = to_slab(kobj);
3576 if (!attribute->store)
3577 return -EIO;
3579 err = attribute->store(s, buf, len);
3581 return err;
3584 static struct sysfs_ops slab_sysfs_ops = {
3585 .show = slab_attr_show,
3586 .store = slab_attr_store,
3589 static struct kobj_type slab_ktype = {
3590 .sysfs_ops = &slab_sysfs_ops,
3593 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3595 struct kobj_type *ktype = get_ktype(kobj);
3597 if (ktype == &slab_ktype)
3598 return 1;
3599 return 0;
3602 static struct kset_uevent_ops slab_uevent_ops = {
3603 .filter = uevent_filter,
3606 decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3608 #define ID_STR_LENGTH 64
3610 /* Create a unique string id for a slab cache:
3611 * format
3612 * :[flags-]size:[memory address of kmemcache]
3614 static char *create_unique_id(struct kmem_cache *s)
3616 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3617 char *p = name;
3619 BUG_ON(!name);
3621 *p++ = ':';
3623 * First flags affecting slabcache operations. We will only
3624 * get here for aliasable slabs so we do not need to support
3625 * too many flags. The flags here must cover all flags that
3626 * are matched during merging to guarantee that the id is
3627 * unique.
3629 if (s->flags & SLAB_CACHE_DMA)
3630 *p++ = 'd';
3631 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3632 *p++ = 'a';
3633 if (s->flags & SLAB_DEBUG_FREE)
3634 *p++ = 'F';
3635 if (p != name + 1)
3636 *p++ = '-';
3637 p += sprintf(p, "%07d", s->size);
3638 BUG_ON(p > name + ID_STR_LENGTH - 1);
3639 return name;
3642 static int sysfs_slab_add(struct kmem_cache *s)
3644 int err;
3645 const char *name;
3646 int unmergeable;
3648 if (slab_state < SYSFS)
3649 /* Defer until later */
3650 return 0;
3652 unmergeable = slab_unmergeable(s);
3653 if (unmergeable) {
3655 * Slabcache can never be merged so we can use the name proper.
3656 * This is typically the case for debug situations. In that
3657 * case we can catch duplicate names easily.
3659 sysfs_remove_link(&slab_subsys.kobj, s->name);
3660 name = s->name;
3661 } else {
3663 * Create a unique name for the slab as a target
3664 * for the symlinks.
3666 name = create_unique_id(s);
3669 kobj_set_kset_s(s, slab_subsys);
3670 kobject_set_name(&s->kobj, name);
3671 kobject_init(&s->kobj);
3672 err = kobject_add(&s->kobj);
3673 if (err)
3674 return err;
3676 err = sysfs_create_group(&s->kobj, &slab_attr_group);
3677 if (err)
3678 return err;
3679 kobject_uevent(&s->kobj, KOBJ_ADD);
3680 if (!unmergeable) {
3681 /* Setup first alias */
3682 sysfs_slab_alias(s, s->name);
3683 kfree(name);
3685 return 0;
3688 static void sysfs_slab_remove(struct kmem_cache *s)
3690 kobject_uevent(&s->kobj, KOBJ_REMOVE);
3691 kobject_del(&s->kobj);
3695 * Need to buffer aliases during bootup until sysfs becomes
3696 * available lest we loose that information.
3698 struct saved_alias {
3699 struct kmem_cache *s;
3700 const char *name;
3701 struct saved_alias *next;
3704 struct saved_alias *alias_list;
3706 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3708 struct saved_alias *al;
3710 if (slab_state == SYSFS) {
3712 * If we have a leftover link then remove it.
3714 sysfs_remove_link(&slab_subsys.kobj, name);
3715 return sysfs_create_link(&slab_subsys.kobj,
3716 &s->kobj, name);
3719 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3720 if (!al)
3721 return -ENOMEM;
3723 al->s = s;
3724 al->name = name;
3725 al->next = alias_list;
3726 alias_list = al;
3727 return 0;
3730 static int __init slab_sysfs_init(void)
3732 struct kmem_cache *s;
3733 int err;
3735 err = subsystem_register(&slab_subsys);
3736 if (err) {
3737 printk(KERN_ERR "Cannot register slab subsystem.\n");
3738 return -ENOSYS;
3741 slab_state = SYSFS;
3743 list_for_each_entry(s, &slab_caches, list) {
3744 err = sysfs_slab_add(s);
3745 BUG_ON(err);
3748 while (alias_list) {
3749 struct saved_alias *al = alias_list;
3751 alias_list = alias_list->next;
3752 err = sysfs_slab_alias(al->s, al->name);
3753 BUG_ON(err);
3754 kfree(al);
3757 resiliency_test();
3758 return 0;
3761 __initcall(slab_sysfs_init);
3762 #endif