memory hotplug: allocate usemap on the section with pgdat
[linux-2.6/kmemtrace.git] / mm / slub.c
blob38914bc64aca2cd58a4c40e35b1b8ef45b9e55d9
1 /*
2 * SLUB: A slab allocator that limits cache line use instead of queuing
3 * objects in per cpu and per node lists.
5 * The allocator synchronizes using per slab locks and only
6 * uses a centralized lock to manage a pool of partial slabs.
8 * (C) 2007 SGI, Christoph Lameter <clameter@sgi.com>
9 */
11 #include <linux/mm.h>
12 #include <linux/module.h>
13 #include <linux/bit_spinlock.h>
14 #include <linux/interrupt.h>
15 #include <linux/bitops.h>
16 #include <linux/slab.h>
17 #include <linux/seq_file.h>
18 #include <linux/cpu.h>
19 #include <linux/cpuset.h>
20 #include <linux/mempolicy.h>
21 #include <linux/ctype.h>
22 #include <linux/kallsyms.h>
23 #include <linux/memory.h>
26 * Lock order:
27 * 1. slab_lock(page)
28 * 2. slab->list_lock
30 * The slab_lock protects operations on the object of a particular
31 * slab and its metadata in the page struct. If the slab lock
32 * has been taken then no allocations nor frees can be performed
33 * on the objects in the slab nor can the slab be added or removed
34 * from the partial or full lists since this would mean modifying
35 * the page_struct of the slab.
37 * The list_lock protects the partial and full list on each node and
38 * the partial slab counter. If taken then no new slabs may be added or
39 * removed from the lists nor make the number of partial slabs be modified.
40 * (Note that the total number of slabs is an atomic value that may be
41 * modified without taking the list lock).
43 * The list_lock is a centralized lock and thus we avoid taking it as
44 * much as possible. As long as SLUB does not have to handle partial
45 * slabs, operations can continue without any centralized lock. F.e.
46 * allocating a long series of objects that fill up slabs does not require
47 * the list lock.
49 * The lock order is sometimes inverted when we are trying to get a slab
50 * off a list. We take the list_lock and then look for a page on the list
51 * to use. While we do that objects in the slabs may be freed. We can
52 * only operate on the slab if we have also taken the slab_lock. So we use
53 * a slab_trylock() on the slab. If trylock was successful then no frees
54 * can occur anymore and we can use the slab for allocations etc. If the
55 * slab_trylock() does not succeed then frees are in progress in the slab and
56 * we must stay away from it for a while since we may cause a bouncing
57 * cacheline if we try to acquire the lock. So go onto the next slab.
58 * If all pages are busy then we may allocate a new slab instead of reusing
59 * a partial slab. A new slab has noone operating on it and thus there is
60 * no danger of cacheline contention.
62 * Interrupts are disabled during allocation and deallocation in order to
63 * make the slab allocator safe to use in the context of an irq. In addition
64 * interrupts are disabled to ensure that the processor does not change
65 * while handling per_cpu slabs, due to kernel preemption.
67 * SLUB assigns one slab for allocation to each processor.
68 * Allocations only occur from these slabs called cpu slabs.
70 * Slabs with free elements are kept on a partial list and during regular
71 * operations no list for full slabs is used. If an object in a full slab is
72 * freed then the slab will show up again on the partial lists.
73 * We track full slabs for debugging purposes though because otherwise we
74 * cannot scan all objects.
76 * Slabs are freed when they become empty. Teardown and setup is
77 * minimal so we rely on the page allocators per cpu caches for
78 * fast frees and allocs.
80 * Overloading of page flags that are otherwise used for LRU management.
82 * PageActive The slab is frozen and exempt from list processing.
83 * This means that the slab is dedicated to a purpose
84 * such as satisfying allocations for a specific
85 * processor. Objects may be freed in the slab while
86 * it is frozen but slab_free will then skip the usual
87 * list operations. It is up to the processor holding
88 * the slab to integrate the slab into the slab lists
89 * when the slab is no longer needed.
91 * One use of this flag is to mark slabs that are
92 * used for allocations. Then such a slab becomes a cpu
93 * slab. The cpu slab may be equipped with an additional
94 * freelist that allows lockless access to
95 * free objects in addition to the regular freelist
96 * that requires the slab lock.
98 * PageError Slab requires special handling due to debug
99 * options set. This moves slab handling out of
100 * the fast path and disables lockless freelists.
103 #define FROZEN (1 << PG_active)
105 #ifdef CONFIG_SLUB_DEBUG
106 #define SLABDEBUG (1 << PG_error)
107 #else
108 #define SLABDEBUG 0
109 #endif
111 static inline int SlabFrozen(struct page *page)
113 return page->flags & FROZEN;
116 static inline void SetSlabFrozen(struct page *page)
118 page->flags |= FROZEN;
121 static inline void ClearSlabFrozen(struct page *page)
123 page->flags &= ~FROZEN;
126 static inline int SlabDebug(struct page *page)
128 return page->flags & SLABDEBUG;
131 static inline void SetSlabDebug(struct page *page)
133 page->flags |= SLABDEBUG;
136 static inline void ClearSlabDebug(struct page *page)
138 page->flags &= ~SLABDEBUG;
142 * Issues still to be resolved:
144 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
146 * - Variable sizing of the per node arrays
149 /* Enable to test recovery from slab corruption on boot */
150 #undef SLUB_RESILIENCY_TEST
152 #if PAGE_SHIFT <= 12
155 * Small page size. Make sure that we do not fragment memory
157 #define DEFAULT_MAX_ORDER 1
158 #define DEFAULT_MIN_OBJECTS 4
160 #else
163 * Large page machines are customarily able to handle larger
164 * page orders.
166 #define DEFAULT_MAX_ORDER 2
167 #define DEFAULT_MIN_OBJECTS 8
169 #endif
172 * Mininum number of partial slabs. These will be left on the partial
173 * lists even if they are empty. kmem_cache_shrink may reclaim them.
175 #define MIN_PARTIAL 5
178 * Maximum number of desirable partial slabs.
179 * The existence of more partial slabs makes kmem_cache_shrink
180 * sort the partial list by the number of objects in the.
182 #define MAX_PARTIAL 10
184 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
185 SLAB_POISON | SLAB_STORE_USER)
188 * Set of flags that will prevent slab merging
190 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
191 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
193 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
194 SLAB_CACHE_DMA)
196 #ifndef ARCH_KMALLOC_MINALIGN
197 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
198 #endif
200 #ifndef ARCH_SLAB_MINALIGN
201 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
202 #endif
204 /* Internal SLUB flags */
205 #define __OBJECT_POISON 0x80000000 /* Poison object */
206 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
207 #define __KMALLOC_CACHE 0x20000000 /* objects freed using kfree */
208 #define __PAGE_ALLOC_FALLBACK 0x10000000 /* Allow fallback to page alloc */
210 static int kmem_size = sizeof(struct kmem_cache);
212 #ifdef CONFIG_SMP
213 static struct notifier_block slab_notifier;
214 #endif
216 static enum {
217 DOWN, /* No slab functionality available */
218 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
219 UP, /* Everything works but does not show up in sysfs */
220 SYSFS /* Sysfs up */
221 } slab_state = DOWN;
223 /* A list of all slab caches on the system */
224 static DECLARE_RWSEM(slub_lock);
225 static LIST_HEAD(slab_caches);
228 * Tracking user of a slab.
230 struct track {
231 void *addr; /* Called from address */
232 int cpu; /* Was running on cpu */
233 int pid; /* Pid context */
234 unsigned long when; /* When did the operation occur */
237 enum track_item { TRACK_ALLOC, TRACK_FREE };
239 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
240 static int sysfs_slab_add(struct kmem_cache *);
241 static int sysfs_slab_alias(struct kmem_cache *, const char *);
242 static void sysfs_slab_remove(struct kmem_cache *);
244 #else
245 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
246 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
247 { return 0; }
248 static inline void sysfs_slab_remove(struct kmem_cache *s)
250 kfree(s);
253 #endif
255 static inline void stat(struct kmem_cache_cpu *c, enum stat_item si)
257 #ifdef CONFIG_SLUB_STATS
258 c->stat[si]++;
259 #endif
262 /********************************************************************
263 * Core slab cache functions
264 *******************************************************************/
266 int slab_is_available(void)
268 return slab_state >= UP;
271 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
273 #ifdef CONFIG_NUMA
274 return s->node[node];
275 #else
276 return &s->local_node;
277 #endif
280 static inline struct kmem_cache_cpu *get_cpu_slab(struct kmem_cache *s, int cpu)
282 #ifdef CONFIG_SMP
283 return s->cpu_slab[cpu];
284 #else
285 return &s->cpu_slab;
286 #endif
289 /* Verify that a pointer has an address that is valid within a slab page */
290 static inline int check_valid_pointer(struct kmem_cache *s,
291 struct page *page, const void *object)
293 void *base;
295 if (!object)
296 return 1;
298 base = page_address(page);
299 if (object < base || object >= base + s->objects * s->size ||
300 (object - base) % s->size) {
301 return 0;
304 return 1;
308 * Slow version of get and set free pointer.
310 * This version requires touching the cache lines of kmem_cache which
311 * we avoid to do in the fast alloc free paths. There we obtain the offset
312 * from the page struct.
314 static inline void *get_freepointer(struct kmem_cache *s, void *object)
316 return *(void **)(object + s->offset);
319 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
321 *(void **)(object + s->offset) = fp;
324 /* Loop over all objects in a slab */
325 #define for_each_object(__p, __s, __addr) \
326 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
327 __p += (__s)->size)
329 /* Scan freelist */
330 #define for_each_free_object(__p, __s, __free) \
331 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
333 /* Determine object index from a given position */
334 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
336 return (p - addr) / s->size;
339 #ifdef CONFIG_SLUB_DEBUG
341 * Debug settings:
343 #ifdef CONFIG_SLUB_DEBUG_ON
344 static int slub_debug = DEBUG_DEFAULT_FLAGS;
345 #else
346 static int slub_debug;
347 #endif
349 static char *slub_debug_slabs;
352 * Object debugging
354 static void print_section(char *text, u8 *addr, unsigned int length)
356 int i, offset;
357 int newline = 1;
358 char ascii[17];
360 ascii[16] = 0;
362 for (i = 0; i < length; i++) {
363 if (newline) {
364 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
365 newline = 0;
367 printk(KERN_CONT " %02x", addr[i]);
368 offset = i % 16;
369 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
370 if (offset == 15) {
371 printk(KERN_CONT " %s\n", ascii);
372 newline = 1;
375 if (!newline) {
376 i %= 16;
377 while (i < 16) {
378 printk(KERN_CONT " ");
379 ascii[i] = ' ';
380 i++;
382 printk(KERN_CONT " %s\n", ascii);
386 static struct track *get_track(struct kmem_cache *s, void *object,
387 enum track_item alloc)
389 struct track *p;
391 if (s->offset)
392 p = object + s->offset + sizeof(void *);
393 else
394 p = object + s->inuse;
396 return p + alloc;
399 static void set_track(struct kmem_cache *s, void *object,
400 enum track_item alloc, void *addr)
402 struct track *p;
404 if (s->offset)
405 p = object + s->offset + sizeof(void *);
406 else
407 p = object + s->inuse;
409 p += alloc;
410 if (addr) {
411 p->addr = addr;
412 p->cpu = smp_processor_id();
413 p->pid = current ? current->pid : -1;
414 p->when = jiffies;
415 } else
416 memset(p, 0, sizeof(struct track));
419 static void init_tracking(struct kmem_cache *s, void *object)
421 if (!(s->flags & SLAB_STORE_USER))
422 return;
424 set_track(s, object, TRACK_FREE, NULL);
425 set_track(s, object, TRACK_ALLOC, NULL);
428 static void print_track(const char *s, struct track *t)
430 if (!t->addr)
431 return;
433 printk(KERN_ERR "INFO: %s in ", s);
434 __print_symbol("%s", (unsigned long)t->addr);
435 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
438 static void print_tracking(struct kmem_cache *s, void *object)
440 if (!(s->flags & SLAB_STORE_USER))
441 return;
443 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
444 print_track("Freed", get_track(s, object, TRACK_FREE));
447 static void print_page_info(struct page *page)
449 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
450 page, page->inuse, page->freelist, page->flags);
454 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
456 va_list args;
457 char buf[100];
459 va_start(args, fmt);
460 vsnprintf(buf, sizeof(buf), fmt, args);
461 va_end(args);
462 printk(KERN_ERR "========================================"
463 "=====================================\n");
464 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
465 printk(KERN_ERR "----------------------------------------"
466 "-------------------------------------\n\n");
469 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
471 va_list args;
472 char buf[100];
474 va_start(args, fmt);
475 vsnprintf(buf, sizeof(buf), fmt, args);
476 va_end(args);
477 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
480 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
482 unsigned int off; /* Offset of last byte */
483 u8 *addr = page_address(page);
485 print_tracking(s, p);
487 print_page_info(page);
489 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
490 p, p - addr, get_freepointer(s, p));
492 if (p > addr + 16)
493 print_section("Bytes b4", p - 16, 16);
495 print_section("Object", p, min(s->objsize, 128));
497 if (s->flags & SLAB_RED_ZONE)
498 print_section("Redzone", p + s->objsize,
499 s->inuse - s->objsize);
501 if (s->offset)
502 off = s->offset + sizeof(void *);
503 else
504 off = s->inuse;
506 if (s->flags & SLAB_STORE_USER)
507 off += 2 * sizeof(struct track);
509 if (off != s->size)
510 /* Beginning of the filler is the free pointer */
511 print_section("Padding", p + off, s->size - off);
513 dump_stack();
516 static void object_err(struct kmem_cache *s, struct page *page,
517 u8 *object, char *reason)
519 slab_bug(s, "%s", reason);
520 print_trailer(s, page, object);
523 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
525 va_list args;
526 char buf[100];
528 va_start(args, fmt);
529 vsnprintf(buf, sizeof(buf), fmt, args);
530 va_end(args);
531 slab_bug(s, "%s", buf);
532 print_page_info(page);
533 dump_stack();
536 static void init_object(struct kmem_cache *s, void *object, int active)
538 u8 *p = object;
540 if (s->flags & __OBJECT_POISON) {
541 memset(p, POISON_FREE, s->objsize - 1);
542 p[s->objsize - 1] = POISON_END;
545 if (s->flags & SLAB_RED_ZONE)
546 memset(p + s->objsize,
547 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
548 s->inuse - s->objsize);
551 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
553 while (bytes) {
554 if (*start != (u8)value)
555 return start;
556 start++;
557 bytes--;
559 return NULL;
562 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
563 void *from, void *to)
565 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
566 memset(from, data, to - from);
569 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
570 u8 *object, char *what,
571 u8 *start, unsigned int value, unsigned int bytes)
573 u8 *fault;
574 u8 *end;
576 fault = check_bytes(start, value, bytes);
577 if (!fault)
578 return 1;
580 end = start + bytes;
581 while (end > fault && end[-1] == value)
582 end--;
584 slab_bug(s, "%s overwritten", what);
585 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
586 fault, end - 1, fault[0], value);
587 print_trailer(s, page, object);
589 restore_bytes(s, what, value, fault, end);
590 return 0;
594 * Object layout:
596 * object address
597 * Bytes of the object to be managed.
598 * If the freepointer may overlay the object then the free
599 * pointer is the first word of the object.
601 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
602 * 0xa5 (POISON_END)
604 * object + s->objsize
605 * Padding to reach word boundary. This is also used for Redzoning.
606 * Padding is extended by another word if Redzoning is enabled and
607 * objsize == inuse.
609 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
610 * 0xcc (RED_ACTIVE) for objects in use.
612 * object + s->inuse
613 * Meta data starts here.
615 * A. Free pointer (if we cannot overwrite object on free)
616 * B. Tracking data for SLAB_STORE_USER
617 * C. Padding to reach required alignment boundary or at mininum
618 * one word if debugging is on to be able to detect writes
619 * before the word boundary.
621 * Padding is done using 0x5a (POISON_INUSE)
623 * object + s->size
624 * Nothing is used beyond s->size.
626 * If slabcaches are merged then the objsize and inuse boundaries are mostly
627 * ignored. And therefore no slab options that rely on these boundaries
628 * may be used with merged slabcaches.
631 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
633 unsigned long off = s->inuse; /* The end of info */
635 if (s->offset)
636 /* Freepointer is placed after the object. */
637 off += sizeof(void *);
639 if (s->flags & SLAB_STORE_USER)
640 /* We also have user information there */
641 off += 2 * sizeof(struct track);
643 if (s->size == off)
644 return 1;
646 return check_bytes_and_report(s, page, p, "Object padding",
647 p + off, POISON_INUSE, s->size - off);
650 static int slab_pad_check(struct kmem_cache *s, struct page *page)
652 u8 *start;
653 u8 *fault;
654 u8 *end;
655 int length;
656 int remainder;
658 if (!(s->flags & SLAB_POISON))
659 return 1;
661 start = page_address(page);
662 end = start + (PAGE_SIZE << s->order);
663 length = s->objects * s->size;
664 remainder = end - (start + length);
665 if (!remainder)
666 return 1;
668 fault = check_bytes(start + length, POISON_INUSE, remainder);
669 if (!fault)
670 return 1;
671 while (end > fault && end[-1] == POISON_INUSE)
672 end--;
674 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
675 print_section("Padding", start, length);
677 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
678 return 0;
681 static int check_object(struct kmem_cache *s, struct page *page,
682 void *object, int active)
684 u8 *p = object;
685 u8 *endobject = object + s->objsize;
687 if (s->flags & SLAB_RED_ZONE) {
688 unsigned int red =
689 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
691 if (!check_bytes_and_report(s, page, object, "Redzone",
692 endobject, red, s->inuse - s->objsize))
693 return 0;
694 } else {
695 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse) {
696 check_bytes_and_report(s, page, p, "Alignment padding",
697 endobject, POISON_INUSE, s->inuse - s->objsize);
701 if (s->flags & SLAB_POISON) {
702 if (!active && (s->flags & __OBJECT_POISON) &&
703 (!check_bytes_and_report(s, page, p, "Poison", p,
704 POISON_FREE, s->objsize - 1) ||
705 !check_bytes_and_report(s, page, p, "Poison",
706 p + s->objsize - 1, POISON_END, 1)))
707 return 0;
709 * check_pad_bytes cleans up on its own.
711 check_pad_bytes(s, page, p);
714 if (!s->offset && active)
716 * Object and freepointer overlap. Cannot check
717 * freepointer while object is allocated.
719 return 1;
721 /* Check free pointer validity */
722 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
723 object_err(s, page, p, "Freepointer corrupt");
725 * No choice but to zap it and thus loose the remainder
726 * of the free objects in this slab. May cause
727 * another error because the object count is now wrong.
729 set_freepointer(s, p, NULL);
730 return 0;
732 return 1;
735 static int check_slab(struct kmem_cache *s, struct page *page)
737 VM_BUG_ON(!irqs_disabled());
739 if (!PageSlab(page)) {
740 slab_err(s, page, "Not a valid slab page");
741 return 0;
743 if (page->inuse > s->objects) {
744 slab_err(s, page, "inuse %u > max %u",
745 s->name, page->inuse, s->objects);
746 return 0;
748 /* Slab_pad_check fixes things up after itself */
749 slab_pad_check(s, page);
750 return 1;
754 * Determine if a certain object on a page is on the freelist. Must hold the
755 * slab lock to guarantee that the chains are in a consistent state.
757 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
759 int nr = 0;
760 void *fp = page->freelist;
761 void *object = NULL;
763 while (fp && nr <= s->objects) {
764 if (fp == search)
765 return 1;
766 if (!check_valid_pointer(s, page, fp)) {
767 if (object) {
768 object_err(s, page, object,
769 "Freechain corrupt");
770 set_freepointer(s, object, NULL);
771 break;
772 } else {
773 slab_err(s, page, "Freepointer corrupt");
774 page->freelist = NULL;
775 page->inuse = s->objects;
776 slab_fix(s, "Freelist cleared");
777 return 0;
779 break;
781 object = fp;
782 fp = get_freepointer(s, object);
783 nr++;
786 if (page->inuse != s->objects - nr) {
787 slab_err(s, page, "Wrong object count. Counter is %d but "
788 "counted were %d", page->inuse, s->objects - nr);
789 page->inuse = s->objects - nr;
790 slab_fix(s, "Object count adjusted.");
792 return search == NULL;
795 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
797 if (s->flags & SLAB_TRACE) {
798 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
799 s->name,
800 alloc ? "alloc" : "free",
801 object, page->inuse,
802 page->freelist);
804 if (!alloc)
805 print_section("Object", (void *)object, s->objsize);
807 dump_stack();
812 * Tracking of fully allocated slabs for debugging purposes.
814 static void add_full(struct kmem_cache_node *n, struct page *page)
816 spin_lock(&n->list_lock);
817 list_add(&page->lru, &n->full);
818 spin_unlock(&n->list_lock);
821 static void remove_full(struct kmem_cache *s, struct page *page)
823 struct kmem_cache_node *n;
825 if (!(s->flags & SLAB_STORE_USER))
826 return;
828 n = get_node(s, page_to_nid(page));
830 spin_lock(&n->list_lock);
831 list_del(&page->lru);
832 spin_unlock(&n->list_lock);
835 /* Tracking of the number of slabs for debugging purposes */
836 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
838 struct kmem_cache_node *n = get_node(s, node);
840 return atomic_long_read(&n->nr_slabs);
843 static inline void inc_slabs_node(struct kmem_cache *s, int node)
845 struct kmem_cache_node *n = get_node(s, node);
848 * May be called early in order to allocate a slab for the
849 * kmem_cache_node structure. Solve the chicken-egg
850 * dilemma by deferring the increment of the count during
851 * bootstrap (see early_kmem_cache_node_alloc).
853 if (!NUMA_BUILD || n)
854 atomic_long_inc(&n->nr_slabs);
856 static inline void dec_slabs_node(struct kmem_cache *s, int node)
858 struct kmem_cache_node *n = get_node(s, node);
860 atomic_long_dec(&n->nr_slabs);
863 /* Object debug checks for alloc/free paths */
864 static void setup_object_debug(struct kmem_cache *s, struct page *page,
865 void *object)
867 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
868 return;
870 init_object(s, object, 0);
871 init_tracking(s, object);
874 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
875 void *object, void *addr)
877 if (!check_slab(s, page))
878 goto bad;
880 if (!on_freelist(s, page, object)) {
881 object_err(s, page, object, "Object already allocated");
882 goto bad;
885 if (!check_valid_pointer(s, page, object)) {
886 object_err(s, page, object, "Freelist Pointer check fails");
887 goto bad;
890 if (!check_object(s, page, object, 0))
891 goto bad;
893 /* Success perform special debug activities for allocs */
894 if (s->flags & SLAB_STORE_USER)
895 set_track(s, object, TRACK_ALLOC, addr);
896 trace(s, page, object, 1);
897 init_object(s, object, 1);
898 return 1;
900 bad:
901 if (PageSlab(page)) {
903 * If this is a slab page then lets do the best we can
904 * to avoid issues in the future. Marking all objects
905 * as used avoids touching the remaining objects.
907 slab_fix(s, "Marking all objects used");
908 page->inuse = s->objects;
909 page->freelist = NULL;
911 return 0;
914 static int free_debug_processing(struct kmem_cache *s, struct page *page,
915 void *object, void *addr)
917 if (!check_slab(s, page))
918 goto fail;
920 if (!check_valid_pointer(s, page, object)) {
921 slab_err(s, page, "Invalid object pointer 0x%p", object);
922 goto fail;
925 if (on_freelist(s, page, object)) {
926 object_err(s, page, object, "Object already free");
927 goto fail;
930 if (!check_object(s, page, object, 1))
931 return 0;
933 if (unlikely(s != page->slab)) {
934 if (!PageSlab(page)) {
935 slab_err(s, page, "Attempt to free object(0x%p) "
936 "outside of slab", object);
937 } else if (!page->slab) {
938 printk(KERN_ERR
939 "SLUB <none>: no slab for object 0x%p.\n",
940 object);
941 dump_stack();
942 } else
943 object_err(s, page, object,
944 "page slab pointer corrupt.");
945 goto fail;
948 /* Special debug activities for freeing objects */
949 if (!SlabFrozen(page) && !page->freelist)
950 remove_full(s, page);
951 if (s->flags & SLAB_STORE_USER)
952 set_track(s, object, TRACK_FREE, addr);
953 trace(s, page, object, 0);
954 init_object(s, object, 0);
955 return 1;
957 fail:
958 slab_fix(s, "Object at 0x%p not freed", object);
959 return 0;
962 static int __init setup_slub_debug(char *str)
964 slub_debug = DEBUG_DEFAULT_FLAGS;
965 if (*str++ != '=' || !*str)
967 * No options specified. Switch on full debugging.
969 goto out;
971 if (*str == ',')
973 * No options but restriction on slabs. This means full
974 * debugging for slabs matching a pattern.
976 goto check_slabs;
978 slub_debug = 0;
979 if (*str == '-')
981 * Switch off all debugging measures.
983 goto out;
986 * Determine which debug features should be switched on
988 for (; *str && *str != ','; str++) {
989 switch (tolower(*str)) {
990 case 'f':
991 slub_debug |= SLAB_DEBUG_FREE;
992 break;
993 case 'z':
994 slub_debug |= SLAB_RED_ZONE;
995 break;
996 case 'p':
997 slub_debug |= SLAB_POISON;
998 break;
999 case 'u':
1000 slub_debug |= SLAB_STORE_USER;
1001 break;
1002 case 't':
1003 slub_debug |= SLAB_TRACE;
1004 break;
1005 default:
1006 printk(KERN_ERR "slub_debug option '%c' "
1007 "unknown. skipped\n", *str);
1011 check_slabs:
1012 if (*str == ',')
1013 slub_debug_slabs = str + 1;
1014 out:
1015 return 1;
1018 __setup("slub_debug", setup_slub_debug);
1020 static unsigned long kmem_cache_flags(unsigned long objsize,
1021 unsigned long flags, const char *name,
1022 void (*ctor)(struct kmem_cache *, void *))
1025 * Enable debugging if selected on the kernel commandline.
1027 if (slub_debug && (!slub_debug_slabs ||
1028 strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs)) == 0))
1029 flags |= slub_debug;
1031 return flags;
1033 #else
1034 static inline void setup_object_debug(struct kmem_cache *s,
1035 struct page *page, void *object) {}
1037 static inline int alloc_debug_processing(struct kmem_cache *s,
1038 struct page *page, void *object, void *addr) { return 0; }
1040 static inline int free_debug_processing(struct kmem_cache *s,
1041 struct page *page, void *object, void *addr) { return 0; }
1043 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1044 { return 1; }
1045 static inline int check_object(struct kmem_cache *s, struct page *page,
1046 void *object, int active) { return 1; }
1047 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1048 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1049 unsigned long flags, const char *name,
1050 void (*ctor)(struct kmem_cache *, void *))
1052 return flags;
1054 #define slub_debug 0
1056 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1057 { return 0; }
1058 static inline void inc_slabs_node(struct kmem_cache *s, int node) {}
1059 static inline void dec_slabs_node(struct kmem_cache *s, int node) {}
1060 #endif
1062 * Slab allocation and freeing
1064 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1066 struct page *page;
1067 int pages = 1 << s->order;
1069 flags |= s->allocflags;
1071 if (node == -1)
1072 page = alloc_pages(flags, s->order);
1073 else
1074 page = alloc_pages_node(node, flags, s->order);
1076 if (!page)
1077 return NULL;
1079 mod_zone_page_state(page_zone(page),
1080 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1081 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1082 pages);
1084 return page;
1087 static void setup_object(struct kmem_cache *s, struct page *page,
1088 void *object)
1090 setup_object_debug(s, page, object);
1091 if (unlikely(s->ctor))
1092 s->ctor(s, object);
1095 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1097 struct page *page;
1098 void *start;
1099 void *last;
1100 void *p;
1102 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1104 page = allocate_slab(s,
1105 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1106 if (!page)
1107 goto out;
1109 inc_slabs_node(s, page_to_nid(page));
1110 page->slab = s;
1111 page->flags |= 1 << PG_slab;
1112 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1113 SLAB_STORE_USER | SLAB_TRACE))
1114 SetSlabDebug(page);
1116 start = page_address(page);
1118 if (unlikely(s->flags & SLAB_POISON))
1119 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1121 last = start;
1122 for_each_object(p, s, start) {
1123 setup_object(s, page, last);
1124 set_freepointer(s, last, p);
1125 last = p;
1127 setup_object(s, page, last);
1128 set_freepointer(s, last, NULL);
1130 page->freelist = start;
1131 page->inuse = 0;
1132 out:
1133 return page;
1136 static void __free_slab(struct kmem_cache *s, struct page *page)
1138 int pages = 1 << s->order;
1140 if (unlikely(SlabDebug(page))) {
1141 void *p;
1143 slab_pad_check(s, page);
1144 for_each_object(p, s, page_address(page))
1145 check_object(s, page, p, 0);
1146 ClearSlabDebug(page);
1149 mod_zone_page_state(page_zone(page),
1150 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1151 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1152 -pages);
1154 __ClearPageSlab(page);
1155 reset_page_mapcount(page);
1156 __free_pages(page, s->order);
1159 static void rcu_free_slab(struct rcu_head *h)
1161 struct page *page;
1163 page = container_of((struct list_head *)h, struct page, lru);
1164 __free_slab(page->slab, page);
1167 static void free_slab(struct kmem_cache *s, struct page *page)
1169 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1171 * RCU free overloads the RCU head over the LRU
1173 struct rcu_head *head = (void *)&page->lru;
1175 call_rcu(head, rcu_free_slab);
1176 } else
1177 __free_slab(s, page);
1180 static void discard_slab(struct kmem_cache *s, struct page *page)
1182 dec_slabs_node(s, page_to_nid(page));
1183 free_slab(s, page);
1187 * Per slab locking using the pagelock
1189 static __always_inline void slab_lock(struct page *page)
1191 bit_spin_lock(PG_locked, &page->flags);
1194 static __always_inline void slab_unlock(struct page *page)
1196 __bit_spin_unlock(PG_locked, &page->flags);
1199 static __always_inline int slab_trylock(struct page *page)
1201 int rc = 1;
1203 rc = bit_spin_trylock(PG_locked, &page->flags);
1204 return rc;
1208 * Management of partially allocated slabs
1210 static void add_partial(struct kmem_cache_node *n,
1211 struct page *page, int tail)
1213 spin_lock(&n->list_lock);
1214 n->nr_partial++;
1215 if (tail)
1216 list_add_tail(&page->lru, &n->partial);
1217 else
1218 list_add(&page->lru, &n->partial);
1219 spin_unlock(&n->list_lock);
1222 static void remove_partial(struct kmem_cache *s,
1223 struct page *page)
1225 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1227 spin_lock(&n->list_lock);
1228 list_del(&page->lru);
1229 n->nr_partial--;
1230 spin_unlock(&n->list_lock);
1234 * Lock slab and remove from the partial list.
1236 * Must hold list_lock.
1238 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1240 if (slab_trylock(page)) {
1241 list_del(&page->lru);
1242 n->nr_partial--;
1243 SetSlabFrozen(page);
1244 return 1;
1246 return 0;
1250 * Try to allocate a partial slab from a specific node.
1252 static struct page *get_partial_node(struct kmem_cache_node *n)
1254 struct page *page;
1257 * Racy check. If we mistakenly see no partial slabs then we
1258 * just allocate an empty slab. If we mistakenly try to get a
1259 * partial slab and there is none available then get_partials()
1260 * will return NULL.
1262 if (!n || !n->nr_partial)
1263 return NULL;
1265 spin_lock(&n->list_lock);
1266 list_for_each_entry(page, &n->partial, lru)
1267 if (lock_and_freeze_slab(n, page))
1268 goto out;
1269 page = NULL;
1270 out:
1271 spin_unlock(&n->list_lock);
1272 return page;
1276 * Get a page from somewhere. Search in increasing NUMA distances.
1278 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1280 #ifdef CONFIG_NUMA
1281 struct zonelist *zonelist;
1282 struct zoneref *z;
1283 struct zone *zone;
1284 enum zone_type high_zoneidx = gfp_zone(flags);
1285 struct page *page;
1288 * The defrag ratio allows a configuration of the tradeoffs between
1289 * inter node defragmentation and node local allocations. A lower
1290 * defrag_ratio increases the tendency to do local allocations
1291 * instead of attempting to obtain partial slabs from other nodes.
1293 * If the defrag_ratio is set to 0 then kmalloc() always
1294 * returns node local objects. If the ratio is higher then kmalloc()
1295 * may return off node objects because partial slabs are obtained
1296 * from other nodes and filled up.
1298 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1299 * defrag_ratio = 1000) then every (well almost) allocation will
1300 * first attempt to defrag slab caches on other nodes. This means
1301 * scanning over all nodes to look for partial slabs which may be
1302 * expensive if we do it every time we are trying to find a slab
1303 * with available objects.
1305 if (!s->remote_node_defrag_ratio ||
1306 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1307 return NULL;
1309 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
1310 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1311 struct kmem_cache_node *n;
1313 n = get_node(s, zone_to_nid(zone));
1315 if (n && cpuset_zone_allowed_hardwall(zone, flags) &&
1316 n->nr_partial > MIN_PARTIAL) {
1317 page = get_partial_node(n);
1318 if (page)
1319 return page;
1322 #endif
1323 return NULL;
1327 * Get a partial page, lock it and return it.
1329 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1331 struct page *page;
1332 int searchnode = (node == -1) ? numa_node_id() : node;
1334 page = get_partial_node(get_node(s, searchnode));
1335 if (page || (flags & __GFP_THISNODE))
1336 return page;
1338 return get_any_partial(s, flags);
1342 * Move a page back to the lists.
1344 * Must be called with the slab lock held.
1346 * On exit the slab lock will have been dropped.
1348 static void unfreeze_slab(struct kmem_cache *s, struct page *page, int tail)
1350 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1351 struct kmem_cache_cpu *c = get_cpu_slab(s, smp_processor_id());
1353 ClearSlabFrozen(page);
1354 if (page->inuse) {
1356 if (page->freelist) {
1357 add_partial(n, page, tail);
1358 stat(c, tail ? DEACTIVATE_TO_TAIL : DEACTIVATE_TO_HEAD);
1359 } else {
1360 stat(c, DEACTIVATE_FULL);
1361 if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1362 add_full(n, page);
1364 slab_unlock(page);
1365 } else {
1366 stat(c, DEACTIVATE_EMPTY);
1367 if (n->nr_partial < MIN_PARTIAL) {
1369 * Adding an empty slab to the partial slabs in order
1370 * to avoid page allocator overhead. This slab needs
1371 * to come after the other slabs with objects in
1372 * so that the others get filled first. That way the
1373 * size of the partial list stays small.
1375 * kmem_cache_shrink can reclaim any empty slabs from the
1376 * partial list.
1378 add_partial(n, page, 1);
1379 slab_unlock(page);
1380 } else {
1381 slab_unlock(page);
1382 stat(get_cpu_slab(s, raw_smp_processor_id()), FREE_SLAB);
1383 discard_slab(s, page);
1389 * Remove the cpu slab
1391 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1393 struct page *page = c->page;
1394 int tail = 1;
1396 if (page->freelist)
1397 stat(c, DEACTIVATE_REMOTE_FREES);
1399 * Merge cpu freelist into slab freelist. Typically we get here
1400 * because both freelists are empty. So this is unlikely
1401 * to occur.
1403 while (unlikely(c->freelist)) {
1404 void **object;
1406 tail = 0; /* Hot objects. Put the slab first */
1408 /* Retrieve object from cpu_freelist */
1409 object = c->freelist;
1410 c->freelist = c->freelist[c->offset];
1412 /* And put onto the regular freelist */
1413 object[c->offset] = page->freelist;
1414 page->freelist = object;
1415 page->inuse--;
1417 c->page = NULL;
1418 unfreeze_slab(s, page, tail);
1421 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1423 stat(c, CPUSLAB_FLUSH);
1424 slab_lock(c->page);
1425 deactivate_slab(s, c);
1429 * Flush cpu slab.
1431 * Called from IPI handler with interrupts disabled.
1433 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1435 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1437 if (likely(c && c->page))
1438 flush_slab(s, c);
1441 static void flush_cpu_slab(void *d)
1443 struct kmem_cache *s = d;
1445 __flush_cpu_slab(s, smp_processor_id());
1448 static void flush_all(struct kmem_cache *s)
1450 #ifdef CONFIG_SMP
1451 on_each_cpu(flush_cpu_slab, s, 1, 1);
1452 #else
1453 unsigned long flags;
1455 local_irq_save(flags);
1456 flush_cpu_slab(s);
1457 local_irq_restore(flags);
1458 #endif
1462 * Check if the objects in a per cpu structure fit numa
1463 * locality expectations.
1465 static inline int node_match(struct kmem_cache_cpu *c, int node)
1467 #ifdef CONFIG_NUMA
1468 if (node != -1 && c->node != node)
1469 return 0;
1470 #endif
1471 return 1;
1475 * Slow path. The lockless freelist is empty or we need to perform
1476 * debugging duties.
1478 * Interrupts are disabled.
1480 * Processing is still very fast if new objects have been freed to the
1481 * regular freelist. In that case we simply take over the regular freelist
1482 * as the lockless freelist and zap the regular freelist.
1484 * If that is not working then we fall back to the partial lists. We take the
1485 * first element of the freelist as the object to allocate now and move the
1486 * rest of the freelist to the lockless freelist.
1488 * And if we were unable to get a new slab from the partial slab lists then
1489 * we need to allocate a new slab. This is the slowest path since it involves
1490 * a call to the page allocator and the setup of a new slab.
1492 static void *__slab_alloc(struct kmem_cache *s,
1493 gfp_t gfpflags, int node, void *addr, struct kmem_cache_cpu *c)
1495 void **object;
1496 struct page *new;
1498 /* We handle __GFP_ZERO in the caller */
1499 gfpflags &= ~__GFP_ZERO;
1501 if (!c->page)
1502 goto new_slab;
1504 slab_lock(c->page);
1505 if (unlikely(!node_match(c, node)))
1506 goto another_slab;
1508 stat(c, ALLOC_REFILL);
1510 load_freelist:
1511 object = c->page->freelist;
1512 if (unlikely(!object))
1513 goto another_slab;
1514 if (unlikely(SlabDebug(c->page)))
1515 goto debug;
1517 c->freelist = object[c->offset];
1518 c->page->inuse = s->objects;
1519 c->page->freelist = NULL;
1520 c->node = page_to_nid(c->page);
1521 unlock_out:
1522 slab_unlock(c->page);
1523 stat(c, ALLOC_SLOWPATH);
1524 return object;
1526 another_slab:
1527 deactivate_slab(s, c);
1529 new_slab:
1530 new = get_partial(s, gfpflags, node);
1531 if (new) {
1532 c->page = new;
1533 stat(c, ALLOC_FROM_PARTIAL);
1534 goto load_freelist;
1537 if (gfpflags & __GFP_WAIT)
1538 local_irq_enable();
1540 new = new_slab(s, gfpflags, node);
1542 if (gfpflags & __GFP_WAIT)
1543 local_irq_disable();
1545 if (new) {
1546 c = get_cpu_slab(s, smp_processor_id());
1547 stat(c, ALLOC_SLAB);
1548 if (c->page)
1549 flush_slab(s, c);
1550 slab_lock(new);
1551 SetSlabFrozen(new);
1552 c->page = new;
1553 goto load_freelist;
1557 * No memory available.
1559 * If the slab uses higher order allocs but the object is
1560 * smaller than a page size then we can fallback in emergencies
1561 * to the page allocator via kmalloc_large. The page allocator may
1562 * have failed to obtain a higher order page and we can try to
1563 * allocate a single page if the object fits into a single page.
1564 * That is only possible if certain conditions are met that are being
1565 * checked when a slab is created.
1567 if (!(gfpflags & __GFP_NORETRY) &&
1568 (s->flags & __PAGE_ALLOC_FALLBACK)) {
1569 if (gfpflags & __GFP_WAIT)
1570 local_irq_enable();
1571 object = kmalloc_large(s->objsize, gfpflags);
1572 if (gfpflags & __GFP_WAIT)
1573 local_irq_disable();
1574 return object;
1576 return NULL;
1577 debug:
1578 if (!alloc_debug_processing(s, c->page, object, addr))
1579 goto another_slab;
1581 c->page->inuse++;
1582 c->page->freelist = object[c->offset];
1583 c->node = -1;
1584 goto unlock_out;
1588 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1589 * have the fastpath folded into their functions. So no function call
1590 * overhead for requests that can be satisfied on the fastpath.
1592 * The fastpath works by first checking if the lockless freelist can be used.
1593 * If not then __slab_alloc is called for slow processing.
1595 * Otherwise we can simply pick the next object from the lockless free list.
1597 static __always_inline void *slab_alloc(struct kmem_cache *s,
1598 gfp_t gfpflags, int node, void *addr)
1600 void **object;
1601 struct kmem_cache_cpu *c;
1602 unsigned long flags;
1604 local_irq_save(flags);
1605 c = get_cpu_slab(s, smp_processor_id());
1606 if (unlikely(!c->freelist || !node_match(c, node)))
1608 object = __slab_alloc(s, gfpflags, node, addr, c);
1610 else {
1611 object = c->freelist;
1612 c->freelist = object[c->offset];
1613 stat(c, ALLOC_FASTPATH);
1615 local_irq_restore(flags);
1617 if (unlikely((gfpflags & __GFP_ZERO) && object))
1618 memset(object, 0, c->objsize);
1620 return object;
1623 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1625 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1627 EXPORT_SYMBOL(kmem_cache_alloc);
1629 #ifdef CONFIG_NUMA
1630 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1632 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1634 EXPORT_SYMBOL(kmem_cache_alloc_node);
1635 #endif
1638 * Slow patch handling. This may still be called frequently since objects
1639 * have a longer lifetime than the cpu slabs in most processing loads.
1641 * So we still attempt to reduce cache line usage. Just take the slab
1642 * lock and free the item. If there is no additional partial page
1643 * handling required then we can return immediately.
1645 static void __slab_free(struct kmem_cache *s, struct page *page,
1646 void *x, void *addr, unsigned int offset)
1648 void *prior;
1649 void **object = (void *)x;
1650 struct kmem_cache_cpu *c;
1652 c = get_cpu_slab(s, raw_smp_processor_id());
1653 stat(c, FREE_SLOWPATH);
1654 slab_lock(page);
1656 if (unlikely(SlabDebug(page)))
1657 goto debug;
1659 checks_ok:
1660 prior = object[offset] = page->freelist;
1661 page->freelist = object;
1662 page->inuse--;
1664 if (unlikely(SlabFrozen(page))) {
1665 stat(c, FREE_FROZEN);
1666 goto out_unlock;
1669 if (unlikely(!page->inuse))
1670 goto slab_empty;
1673 * Objects left in the slab. If it was not on the partial list before
1674 * then add it.
1676 if (unlikely(!prior)) {
1677 add_partial(get_node(s, page_to_nid(page)), page, 1);
1678 stat(c, FREE_ADD_PARTIAL);
1681 out_unlock:
1682 slab_unlock(page);
1683 return;
1685 slab_empty:
1686 if (prior) {
1688 * Slab still on the partial list.
1690 remove_partial(s, page);
1691 stat(c, FREE_REMOVE_PARTIAL);
1693 slab_unlock(page);
1694 stat(c, FREE_SLAB);
1695 discard_slab(s, page);
1696 return;
1698 debug:
1699 if (!free_debug_processing(s, page, x, addr))
1700 goto out_unlock;
1701 goto checks_ok;
1705 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1706 * can perform fastpath freeing without additional function calls.
1708 * The fastpath is only possible if we are freeing to the current cpu slab
1709 * of this processor. This typically the case if we have just allocated
1710 * the item before.
1712 * If fastpath is not possible then fall back to __slab_free where we deal
1713 * with all sorts of special processing.
1715 static __always_inline void slab_free(struct kmem_cache *s,
1716 struct page *page, void *x, void *addr)
1718 void **object = (void *)x;
1719 struct kmem_cache_cpu *c;
1720 unsigned long flags;
1722 local_irq_save(flags);
1723 c = get_cpu_slab(s, smp_processor_id());
1724 debug_check_no_locks_freed(object, c->objsize);
1725 if (likely(page == c->page && c->node >= 0)) {
1726 object[c->offset] = c->freelist;
1727 c->freelist = object;
1728 stat(c, FREE_FASTPATH);
1729 } else
1730 __slab_free(s, page, x, addr, c->offset);
1732 local_irq_restore(flags);
1735 void kmem_cache_free(struct kmem_cache *s, void *x)
1737 struct page *page;
1739 page = virt_to_head_page(x);
1741 slab_free(s, page, x, __builtin_return_address(0));
1743 EXPORT_SYMBOL(kmem_cache_free);
1745 /* Figure out on which slab object the object resides */
1746 static struct page *get_object_page(const void *x)
1748 struct page *page = virt_to_head_page(x);
1750 if (!PageSlab(page))
1751 return NULL;
1753 return page;
1757 * Object placement in a slab is made very easy because we always start at
1758 * offset 0. If we tune the size of the object to the alignment then we can
1759 * get the required alignment by putting one properly sized object after
1760 * another.
1762 * Notice that the allocation order determines the sizes of the per cpu
1763 * caches. Each processor has always one slab available for allocations.
1764 * Increasing the allocation order reduces the number of times that slabs
1765 * must be moved on and off the partial lists and is therefore a factor in
1766 * locking overhead.
1770 * Mininum / Maximum order of slab pages. This influences locking overhead
1771 * and slab fragmentation. A higher order reduces the number of partial slabs
1772 * and increases the number of allocations possible without having to
1773 * take the list_lock.
1775 static int slub_min_order;
1776 static int slub_max_order = DEFAULT_MAX_ORDER;
1777 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1780 * Merge control. If this is set then no merging of slab caches will occur.
1781 * (Could be removed. This was introduced to pacify the merge skeptics.)
1783 static int slub_nomerge;
1786 * Calculate the order of allocation given an slab object size.
1788 * The order of allocation has significant impact on performance and other
1789 * system components. Generally order 0 allocations should be preferred since
1790 * order 0 does not cause fragmentation in the page allocator. Larger objects
1791 * be problematic to put into order 0 slabs because there may be too much
1792 * unused space left. We go to a higher order if more than 1/8th of the slab
1793 * would be wasted.
1795 * In order to reach satisfactory performance we must ensure that a minimum
1796 * number of objects is in one slab. Otherwise we may generate too much
1797 * activity on the partial lists which requires taking the list_lock. This is
1798 * less a concern for large slabs though which are rarely used.
1800 * slub_max_order specifies the order where we begin to stop considering the
1801 * number of objects in a slab as critical. If we reach slub_max_order then
1802 * we try to keep the page order as low as possible. So we accept more waste
1803 * of space in favor of a small page order.
1805 * Higher order allocations also allow the placement of more objects in a
1806 * slab and thereby reduce object handling overhead. If the user has
1807 * requested a higher mininum order then we start with that one instead of
1808 * the smallest order which will fit the object.
1810 static inline int slab_order(int size, int min_objects,
1811 int max_order, int fract_leftover)
1813 int order;
1814 int rem;
1815 int min_order = slub_min_order;
1817 for (order = max(min_order,
1818 fls(min_objects * size - 1) - PAGE_SHIFT);
1819 order <= max_order; order++) {
1821 unsigned long slab_size = PAGE_SIZE << order;
1823 if (slab_size < min_objects * size)
1824 continue;
1826 rem = slab_size % size;
1828 if (rem <= slab_size / fract_leftover)
1829 break;
1833 return order;
1836 static inline int calculate_order(int size)
1838 int order;
1839 int min_objects;
1840 int fraction;
1843 * Attempt to find best configuration for a slab. This
1844 * works by first attempting to generate a layout with
1845 * the best configuration and backing off gradually.
1847 * First we reduce the acceptable waste in a slab. Then
1848 * we reduce the minimum objects required in a slab.
1850 min_objects = slub_min_objects;
1851 while (min_objects > 1) {
1852 fraction = 8;
1853 while (fraction >= 4) {
1854 order = slab_order(size, min_objects,
1855 slub_max_order, fraction);
1856 if (order <= slub_max_order)
1857 return order;
1858 fraction /= 2;
1860 min_objects /= 2;
1864 * We were unable to place multiple objects in a slab. Now
1865 * lets see if we can place a single object there.
1867 order = slab_order(size, 1, slub_max_order, 1);
1868 if (order <= slub_max_order)
1869 return order;
1872 * Doh this slab cannot be placed using slub_max_order.
1874 order = slab_order(size, 1, MAX_ORDER, 1);
1875 if (order <= MAX_ORDER)
1876 return order;
1877 return -ENOSYS;
1881 * Figure out what the alignment of the objects will be.
1883 static unsigned long calculate_alignment(unsigned long flags,
1884 unsigned long align, unsigned long size)
1887 * If the user wants hardware cache aligned objects then follow that
1888 * suggestion if the object is sufficiently large.
1890 * The hardware cache alignment cannot override the specified
1891 * alignment though. If that is greater then use it.
1893 if (flags & SLAB_HWCACHE_ALIGN) {
1894 unsigned long ralign = cache_line_size();
1895 while (size <= ralign / 2)
1896 ralign /= 2;
1897 align = max(align, ralign);
1900 if (align < ARCH_SLAB_MINALIGN)
1901 align = ARCH_SLAB_MINALIGN;
1903 return ALIGN(align, sizeof(void *));
1906 static void init_kmem_cache_cpu(struct kmem_cache *s,
1907 struct kmem_cache_cpu *c)
1909 c->page = NULL;
1910 c->freelist = NULL;
1911 c->node = 0;
1912 c->offset = s->offset / sizeof(void *);
1913 c->objsize = s->objsize;
1914 #ifdef CONFIG_SLUB_STATS
1915 memset(c->stat, 0, NR_SLUB_STAT_ITEMS * sizeof(unsigned));
1916 #endif
1919 static void init_kmem_cache_node(struct kmem_cache_node *n)
1921 n->nr_partial = 0;
1922 spin_lock_init(&n->list_lock);
1923 INIT_LIST_HEAD(&n->partial);
1924 #ifdef CONFIG_SLUB_DEBUG
1925 atomic_long_set(&n->nr_slabs, 0);
1926 INIT_LIST_HEAD(&n->full);
1927 #endif
1930 #ifdef CONFIG_SMP
1932 * Per cpu array for per cpu structures.
1934 * The per cpu array places all kmem_cache_cpu structures from one processor
1935 * close together meaning that it becomes possible that multiple per cpu
1936 * structures are contained in one cacheline. This may be particularly
1937 * beneficial for the kmalloc caches.
1939 * A desktop system typically has around 60-80 slabs. With 100 here we are
1940 * likely able to get per cpu structures for all caches from the array defined
1941 * here. We must be able to cover all kmalloc caches during bootstrap.
1943 * If the per cpu array is exhausted then fall back to kmalloc
1944 * of individual cachelines. No sharing is possible then.
1946 #define NR_KMEM_CACHE_CPU 100
1948 static DEFINE_PER_CPU(struct kmem_cache_cpu,
1949 kmem_cache_cpu)[NR_KMEM_CACHE_CPU];
1951 static DEFINE_PER_CPU(struct kmem_cache_cpu *, kmem_cache_cpu_free);
1952 static cpumask_t kmem_cach_cpu_free_init_once = CPU_MASK_NONE;
1954 static struct kmem_cache_cpu *alloc_kmem_cache_cpu(struct kmem_cache *s,
1955 int cpu, gfp_t flags)
1957 struct kmem_cache_cpu *c = per_cpu(kmem_cache_cpu_free, cpu);
1959 if (c)
1960 per_cpu(kmem_cache_cpu_free, cpu) =
1961 (void *)c->freelist;
1962 else {
1963 /* Table overflow: So allocate ourselves */
1964 c = kmalloc_node(
1965 ALIGN(sizeof(struct kmem_cache_cpu), cache_line_size()),
1966 flags, cpu_to_node(cpu));
1967 if (!c)
1968 return NULL;
1971 init_kmem_cache_cpu(s, c);
1972 return c;
1975 static void free_kmem_cache_cpu(struct kmem_cache_cpu *c, int cpu)
1977 if (c < per_cpu(kmem_cache_cpu, cpu) ||
1978 c > per_cpu(kmem_cache_cpu, cpu) + NR_KMEM_CACHE_CPU) {
1979 kfree(c);
1980 return;
1982 c->freelist = (void *)per_cpu(kmem_cache_cpu_free, cpu);
1983 per_cpu(kmem_cache_cpu_free, cpu) = c;
1986 static void free_kmem_cache_cpus(struct kmem_cache *s)
1988 int cpu;
1990 for_each_online_cpu(cpu) {
1991 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1993 if (c) {
1994 s->cpu_slab[cpu] = NULL;
1995 free_kmem_cache_cpu(c, cpu);
2000 static int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2002 int cpu;
2004 for_each_online_cpu(cpu) {
2005 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2007 if (c)
2008 continue;
2010 c = alloc_kmem_cache_cpu(s, cpu, flags);
2011 if (!c) {
2012 free_kmem_cache_cpus(s);
2013 return 0;
2015 s->cpu_slab[cpu] = c;
2017 return 1;
2021 * Initialize the per cpu array.
2023 static void init_alloc_cpu_cpu(int cpu)
2025 int i;
2027 if (cpu_isset(cpu, kmem_cach_cpu_free_init_once))
2028 return;
2030 for (i = NR_KMEM_CACHE_CPU - 1; i >= 0; i--)
2031 free_kmem_cache_cpu(&per_cpu(kmem_cache_cpu, cpu)[i], cpu);
2033 cpu_set(cpu, kmem_cach_cpu_free_init_once);
2036 static void __init init_alloc_cpu(void)
2038 int cpu;
2040 for_each_online_cpu(cpu)
2041 init_alloc_cpu_cpu(cpu);
2044 #else
2045 static inline void free_kmem_cache_cpus(struct kmem_cache *s) {}
2046 static inline void init_alloc_cpu(void) {}
2048 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2050 init_kmem_cache_cpu(s, &s->cpu_slab);
2051 return 1;
2053 #endif
2055 #ifdef CONFIG_NUMA
2057 * No kmalloc_node yet so do it by hand. We know that this is the first
2058 * slab on the node for this slabcache. There are no concurrent accesses
2059 * possible.
2061 * Note that this function only works on the kmalloc_node_cache
2062 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2063 * memory on a fresh node that has no slab structures yet.
2065 static struct kmem_cache_node *early_kmem_cache_node_alloc(gfp_t gfpflags,
2066 int node)
2068 struct page *page;
2069 struct kmem_cache_node *n;
2070 unsigned long flags;
2072 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
2074 page = new_slab(kmalloc_caches, gfpflags, node);
2076 BUG_ON(!page);
2077 if (page_to_nid(page) != node) {
2078 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2079 "node %d\n", node);
2080 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2081 "in order to be able to continue\n");
2084 n = page->freelist;
2085 BUG_ON(!n);
2086 page->freelist = get_freepointer(kmalloc_caches, n);
2087 page->inuse++;
2088 kmalloc_caches->node[node] = n;
2089 #ifdef CONFIG_SLUB_DEBUG
2090 init_object(kmalloc_caches, n, 1);
2091 init_tracking(kmalloc_caches, n);
2092 #endif
2093 init_kmem_cache_node(n);
2094 inc_slabs_node(kmalloc_caches, node);
2097 * lockdep requires consistent irq usage for each lock
2098 * so even though there cannot be a race this early in
2099 * the boot sequence, we still disable irqs.
2101 local_irq_save(flags);
2102 add_partial(n, page, 0);
2103 local_irq_restore(flags);
2104 return n;
2107 static void free_kmem_cache_nodes(struct kmem_cache *s)
2109 int node;
2111 for_each_node_state(node, N_NORMAL_MEMORY) {
2112 struct kmem_cache_node *n = s->node[node];
2113 if (n && n != &s->local_node)
2114 kmem_cache_free(kmalloc_caches, n);
2115 s->node[node] = NULL;
2119 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2121 int node;
2122 int local_node;
2124 if (slab_state >= UP)
2125 local_node = page_to_nid(virt_to_page(s));
2126 else
2127 local_node = 0;
2129 for_each_node_state(node, N_NORMAL_MEMORY) {
2130 struct kmem_cache_node *n;
2132 if (local_node == node)
2133 n = &s->local_node;
2134 else {
2135 if (slab_state == DOWN) {
2136 n = early_kmem_cache_node_alloc(gfpflags,
2137 node);
2138 continue;
2140 n = kmem_cache_alloc_node(kmalloc_caches,
2141 gfpflags, node);
2143 if (!n) {
2144 free_kmem_cache_nodes(s);
2145 return 0;
2149 s->node[node] = n;
2150 init_kmem_cache_node(n);
2152 return 1;
2154 #else
2155 static void free_kmem_cache_nodes(struct kmem_cache *s)
2159 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2161 init_kmem_cache_node(&s->local_node);
2162 return 1;
2164 #endif
2167 * calculate_sizes() determines the order and the distribution of data within
2168 * a slab object.
2170 static int calculate_sizes(struct kmem_cache *s)
2172 unsigned long flags = s->flags;
2173 unsigned long size = s->objsize;
2174 unsigned long align = s->align;
2177 * Round up object size to the next word boundary. We can only
2178 * place the free pointer at word boundaries and this determines
2179 * the possible location of the free pointer.
2181 size = ALIGN(size, sizeof(void *));
2183 #ifdef CONFIG_SLUB_DEBUG
2185 * Determine if we can poison the object itself. If the user of
2186 * the slab may touch the object after free or before allocation
2187 * then we should never poison the object itself.
2189 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2190 !s->ctor)
2191 s->flags |= __OBJECT_POISON;
2192 else
2193 s->flags &= ~__OBJECT_POISON;
2197 * If we are Redzoning then check if there is some space between the
2198 * end of the object and the free pointer. If not then add an
2199 * additional word to have some bytes to store Redzone information.
2201 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2202 size += sizeof(void *);
2203 #endif
2206 * With that we have determined the number of bytes in actual use
2207 * by the object. This is the potential offset to the free pointer.
2209 s->inuse = size;
2211 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2212 s->ctor)) {
2214 * Relocate free pointer after the object if it is not
2215 * permitted to overwrite the first word of the object on
2216 * kmem_cache_free.
2218 * This is the case if we do RCU, have a constructor or
2219 * destructor or are poisoning the objects.
2221 s->offset = size;
2222 size += sizeof(void *);
2225 #ifdef CONFIG_SLUB_DEBUG
2226 if (flags & SLAB_STORE_USER)
2228 * Need to store information about allocs and frees after
2229 * the object.
2231 size += 2 * sizeof(struct track);
2233 if (flags & SLAB_RED_ZONE)
2235 * Add some empty padding so that we can catch
2236 * overwrites from earlier objects rather than let
2237 * tracking information or the free pointer be
2238 * corrupted if an user writes before the start
2239 * of the object.
2241 size += sizeof(void *);
2242 #endif
2245 * Determine the alignment based on various parameters that the
2246 * user specified and the dynamic determination of cache line size
2247 * on bootup.
2249 align = calculate_alignment(flags, align, s->objsize);
2252 * SLUB stores one object immediately after another beginning from
2253 * offset 0. In order to align the objects we have to simply size
2254 * each object to conform to the alignment.
2256 size = ALIGN(size, align);
2257 s->size = size;
2259 if ((flags & __KMALLOC_CACHE) &&
2260 PAGE_SIZE / size < slub_min_objects) {
2262 * Kmalloc cache that would not have enough objects in
2263 * an order 0 page. Kmalloc slabs can fallback to
2264 * page allocator order 0 allocs so take a reasonably large
2265 * order that will allows us a good number of objects.
2267 s->order = max(slub_max_order, PAGE_ALLOC_COSTLY_ORDER);
2268 s->flags |= __PAGE_ALLOC_FALLBACK;
2269 s->allocflags |= __GFP_NOWARN;
2270 } else
2271 s->order = calculate_order(size);
2273 if (s->order < 0)
2274 return 0;
2276 s->allocflags = 0;
2277 if (s->order)
2278 s->allocflags |= __GFP_COMP;
2280 if (s->flags & SLAB_CACHE_DMA)
2281 s->allocflags |= SLUB_DMA;
2283 if (s->flags & SLAB_RECLAIM_ACCOUNT)
2284 s->allocflags |= __GFP_RECLAIMABLE;
2287 * Determine the number of objects per slab
2289 s->objects = (PAGE_SIZE << s->order) / size;
2291 return !!s->objects;
2295 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2296 const char *name, size_t size,
2297 size_t align, unsigned long flags,
2298 void (*ctor)(struct kmem_cache *, void *))
2300 memset(s, 0, kmem_size);
2301 s->name = name;
2302 s->ctor = ctor;
2303 s->objsize = size;
2304 s->align = align;
2305 s->flags = kmem_cache_flags(size, flags, name, ctor);
2307 if (!calculate_sizes(s))
2308 goto error;
2310 s->refcount = 1;
2311 #ifdef CONFIG_NUMA
2312 s->remote_node_defrag_ratio = 100;
2313 #endif
2314 if (!init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2315 goto error;
2317 if (alloc_kmem_cache_cpus(s, gfpflags & ~SLUB_DMA))
2318 return 1;
2319 free_kmem_cache_nodes(s);
2320 error:
2321 if (flags & SLAB_PANIC)
2322 panic("Cannot create slab %s size=%lu realsize=%u "
2323 "order=%u offset=%u flags=%lx\n",
2324 s->name, (unsigned long)size, s->size, s->order,
2325 s->offset, flags);
2326 return 0;
2330 * Check if a given pointer is valid
2332 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2334 struct page *page;
2336 page = get_object_page(object);
2338 if (!page || s != page->slab)
2339 /* No slab or wrong slab */
2340 return 0;
2342 if (!check_valid_pointer(s, page, object))
2343 return 0;
2346 * We could also check if the object is on the slabs freelist.
2347 * But this would be too expensive and it seems that the main
2348 * purpose of kmem_ptr_valid() is to check if the object belongs
2349 * to a certain slab.
2351 return 1;
2353 EXPORT_SYMBOL(kmem_ptr_validate);
2356 * Determine the size of a slab object
2358 unsigned int kmem_cache_size(struct kmem_cache *s)
2360 return s->objsize;
2362 EXPORT_SYMBOL(kmem_cache_size);
2364 const char *kmem_cache_name(struct kmem_cache *s)
2366 return s->name;
2368 EXPORT_SYMBOL(kmem_cache_name);
2371 * Attempt to free all slabs on a node. Return the number of slabs we
2372 * were unable to free.
2374 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2375 struct list_head *list)
2377 int slabs_inuse = 0;
2378 unsigned long flags;
2379 struct page *page, *h;
2381 spin_lock_irqsave(&n->list_lock, flags);
2382 list_for_each_entry_safe(page, h, list, lru)
2383 if (!page->inuse) {
2384 list_del(&page->lru);
2385 discard_slab(s, page);
2386 } else
2387 slabs_inuse++;
2388 spin_unlock_irqrestore(&n->list_lock, flags);
2389 return slabs_inuse;
2393 * Release all resources used by a slab cache.
2395 static inline int kmem_cache_close(struct kmem_cache *s)
2397 int node;
2399 flush_all(s);
2401 /* Attempt to free all objects */
2402 free_kmem_cache_cpus(s);
2403 for_each_node_state(node, N_NORMAL_MEMORY) {
2404 struct kmem_cache_node *n = get_node(s, node);
2406 n->nr_partial -= free_list(s, n, &n->partial);
2407 if (slabs_node(s, node))
2408 return 1;
2410 free_kmem_cache_nodes(s);
2411 return 0;
2415 * Close a cache and release the kmem_cache structure
2416 * (must be used for caches created using kmem_cache_create)
2418 void kmem_cache_destroy(struct kmem_cache *s)
2420 down_write(&slub_lock);
2421 s->refcount--;
2422 if (!s->refcount) {
2423 list_del(&s->list);
2424 up_write(&slub_lock);
2425 if (kmem_cache_close(s))
2426 WARN_ON(1);
2427 sysfs_slab_remove(s);
2428 } else
2429 up_write(&slub_lock);
2431 EXPORT_SYMBOL(kmem_cache_destroy);
2433 /********************************************************************
2434 * Kmalloc subsystem
2435 *******************************************************************/
2437 struct kmem_cache kmalloc_caches[PAGE_SHIFT + 1] __cacheline_aligned;
2438 EXPORT_SYMBOL(kmalloc_caches);
2440 static int __init setup_slub_min_order(char *str)
2442 get_option(&str, &slub_min_order);
2444 return 1;
2447 __setup("slub_min_order=", setup_slub_min_order);
2449 static int __init setup_slub_max_order(char *str)
2451 get_option(&str, &slub_max_order);
2453 return 1;
2456 __setup("slub_max_order=", setup_slub_max_order);
2458 static int __init setup_slub_min_objects(char *str)
2460 get_option(&str, &slub_min_objects);
2462 return 1;
2465 __setup("slub_min_objects=", setup_slub_min_objects);
2467 static int __init setup_slub_nomerge(char *str)
2469 slub_nomerge = 1;
2470 return 1;
2473 __setup("slub_nomerge", setup_slub_nomerge);
2475 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2476 const char *name, int size, gfp_t gfp_flags)
2478 unsigned int flags = 0;
2480 if (gfp_flags & SLUB_DMA)
2481 flags = SLAB_CACHE_DMA;
2483 down_write(&slub_lock);
2484 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2485 flags | __KMALLOC_CACHE, NULL))
2486 goto panic;
2488 list_add(&s->list, &slab_caches);
2489 up_write(&slub_lock);
2490 if (sysfs_slab_add(s))
2491 goto panic;
2492 return s;
2494 panic:
2495 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2498 #ifdef CONFIG_ZONE_DMA
2499 static struct kmem_cache *kmalloc_caches_dma[PAGE_SHIFT + 1];
2501 static void sysfs_add_func(struct work_struct *w)
2503 struct kmem_cache *s;
2505 down_write(&slub_lock);
2506 list_for_each_entry(s, &slab_caches, list) {
2507 if (s->flags & __SYSFS_ADD_DEFERRED) {
2508 s->flags &= ~__SYSFS_ADD_DEFERRED;
2509 sysfs_slab_add(s);
2512 up_write(&slub_lock);
2515 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2517 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2519 struct kmem_cache *s;
2520 char *text;
2521 size_t realsize;
2523 s = kmalloc_caches_dma[index];
2524 if (s)
2525 return s;
2527 /* Dynamically create dma cache */
2528 if (flags & __GFP_WAIT)
2529 down_write(&slub_lock);
2530 else {
2531 if (!down_write_trylock(&slub_lock))
2532 goto out;
2535 if (kmalloc_caches_dma[index])
2536 goto unlock_out;
2538 realsize = kmalloc_caches[index].objsize;
2539 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2540 (unsigned int)realsize);
2541 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2543 if (!s || !text || !kmem_cache_open(s, flags, text,
2544 realsize, ARCH_KMALLOC_MINALIGN,
2545 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2546 kfree(s);
2547 kfree(text);
2548 goto unlock_out;
2551 list_add(&s->list, &slab_caches);
2552 kmalloc_caches_dma[index] = s;
2554 schedule_work(&sysfs_add_work);
2556 unlock_out:
2557 up_write(&slub_lock);
2558 out:
2559 return kmalloc_caches_dma[index];
2561 #endif
2564 * Conversion table for small slabs sizes / 8 to the index in the
2565 * kmalloc array. This is necessary for slabs < 192 since we have non power
2566 * of two cache sizes there. The size of larger slabs can be determined using
2567 * fls.
2569 static s8 size_index[24] = {
2570 3, /* 8 */
2571 4, /* 16 */
2572 5, /* 24 */
2573 5, /* 32 */
2574 6, /* 40 */
2575 6, /* 48 */
2576 6, /* 56 */
2577 6, /* 64 */
2578 1, /* 72 */
2579 1, /* 80 */
2580 1, /* 88 */
2581 1, /* 96 */
2582 7, /* 104 */
2583 7, /* 112 */
2584 7, /* 120 */
2585 7, /* 128 */
2586 2, /* 136 */
2587 2, /* 144 */
2588 2, /* 152 */
2589 2, /* 160 */
2590 2, /* 168 */
2591 2, /* 176 */
2592 2, /* 184 */
2593 2 /* 192 */
2596 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2598 int index;
2600 if (size <= 192) {
2601 if (!size)
2602 return ZERO_SIZE_PTR;
2604 index = size_index[(size - 1) / 8];
2605 } else
2606 index = fls(size - 1);
2608 #ifdef CONFIG_ZONE_DMA
2609 if (unlikely((flags & SLUB_DMA)))
2610 return dma_kmalloc_cache(index, flags);
2612 #endif
2613 return &kmalloc_caches[index];
2616 void *__kmalloc(size_t size, gfp_t flags)
2618 struct kmem_cache *s;
2620 if (unlikely(size > PAGE_SIZE))
2621 return kmalloc_large(size, flags);
2623 s = get_slab(size, flags);
2625 if (unlikely(ZERO_OR_NULL_PTR(s)))
2626 return s;
2628 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2630 EXPORT_SYMBOL(__kmalloc);
2632 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
2634 struct page *page = alloc_pages_node(node, flags | __GFP_COMP,
2635 get_order(size));
2637 if (page)
2638 return page_address(page);
2639 else
2640 return NULL;
2643 #ifdef CONFIG_NUMA
2644 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2646 struct kmem_cache *s;
2648 if (unlikely(size > PAGE_SIZE))
2649 return kmalloc_large_node(size, flags, node);
2651 s = get_slab(size, flags);
2653 if (unlikely(ZERO_OR_NULL_PTR(s)))
2654 return s;
2656 return slab_alloc(s, flags, node, __builtin_return_address(0));
2658 EXPORT_SYMBOL(__kmalloc_node);
2659 #endif
2661 size_t ksize(const void *object)
2663 struct page *page;
2664 struct kmem_cache *s;
2666 if (unlikely(object == ZERO_SIZE_PTR))
2667 return 0;
2669 page = virt_to_head_page(object);
2671 if (unlikely(!PageSlab(page)))
2672 return PAGE_SIZE << compound_order(page);
2674 s = page->slab;
2676 #ifdef CONFIG_SLUB_DEBUG
2678 * Debugging requires use of the padding between object
2679 * and whatever may come after it.
2681 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2682 return s->objsize;
2684 #endif
2686 * If we have the need to store the freelist pointer
2687 * back there or track user information then we can
2688 * only use the space before that information.
2690 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2691 return s->inuse;
2693 * Else we can use all the padding etc for the allocation
2695 return s->size;
2697 EXPORT_SYMBOL(ksize);
2699 void kfree(const void *x)
2701 struct page *page;
2702 void *object = (void *)x;
2704 if (unlikely(ZERO_OR_NULL_PTR(x)))
2705 return;
2707 page = virt_to_head_page(x);
2708 if (unlikely(!PageSlab(page))) {
2709 put_page(page);
2710 return;
2712 slab_free(page->slab, page, object, __builtin_return_address(0));
2714 EXPORT_SYMBOL(kfree);
2717 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2718 * the remaining slabs by the number of items in use. The slabs with the
2719 * most items in use come first. New allocations will then fill those up
2720 * and thus they can be removed from the partial lists.
2722 * The slabs with the least items are placed last. This results in them
2723 * being allocated from last increasing the chance that the last objects
2724 * are freed in them.
2726 int kmem_cache_shrink(struct kmem_cache *s)
2728 int node;
2729 int i;
2730 struct kmem_cache_node *n;
2731 struct page *page;
2732 struct page *t;
2733 struct list_head *slabs_by_inuse =
2734 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2735 unsigned long flags;
2737 if (!slabs_by_inuse)
2738 return -ENOMEM;
2740 flush_all(s);
2741 for_each_node_state(node, N_NORMAL_MEMORY) {
2742 n = get_node(s, node);
2744 if (!n->nr_partial)
2745 continue;
2747 for (i = 0; i < s->objects; i++)
2748 INIT_LIST_HEAD(slabs_by_inuse + i);
2750 spin_lock_irqsave(&n->list_lock, flags);
2753 * Build lists indexed by the items in use in each slab.
2755 * Note that concurrent frees may occur while we hold the
2756 * list_lock. page->inuse here is the upper limit.
2758 list_for_each_entry_safe(page, t, &n->partial, lru) {
2759 if (!page->inuse && slab_trylock(page)) {
2761 * Must hold slab lock here because slab_free
2762 * may have freed the last object and be
2763 * waiting to release the slab.
2765 list_del(&page->lru);
2766 n->nr_partial--;
2767 slab_unlock(page);
2768 discard_slab(s, page);
2769 } else {
2770 list_move(&page->lru,
2771 slabs_by_inuse + page->inuse);
2776 * Rebuild the partial list with the slabs filled up most
2777 * first and the least used slabs at the end.
2779 for (i = s->objects - 1; i >= 0; i--)
2780 list_splice(slabs_by_inuse + i, n->partial.prev);
2782 spin_unlock_irqrestore(&n->list_lock, flags);
2785 kfree(slabs_by_inuse);
2786 return 0;
2788 EXPORT_SYMBOL(kmem_cache_shrink);
2790 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
2791 static int slab_mem_going_offline_callback(void *arg)
2793 struct kmem_cache *s;
2795 down_read(&slub_lock);
2796 list_for_each_entry(s, &slab_caches, list)
2797 kmem_cache_shrink(s);
2798 up_read(&slub_lock);
2800 return 0;
2803 static void slab_mem_offline_callback(void *arg)
2805 struct kmem_cache_node *n;
2806 struct kmem_cache *s;
2807 struct memory_notify *marg = arg;
2808 int offline_node;
2810 offline_node = marg->status_change_nid;
2813 * If the node still has available memory. we need kmem_cache_node
2814 * for it yet.
2816 if (offline_node < 0)
2817 return;
2819 down_read(&slub_lock);
2820 list_for_each_entry(s, &slab_caches, list) {
2821 n = get_node(s, offline_node);
2822 if (n) {
2824 * if n->nr_slabs > 0, slabs still exist on the node
2825 * that is going down. We were unable to free them,
2826 * and offline_pages() function shoudn't call this
2827 * callback. So, we must fail.
2829 BUG_ON(slabs_node(s, offline_node));
2831 s->node[offline_node] = NULL;
2832 kmem_cache_free(kmalloc_caches, n);
2835 up_read(&slub_lock);
2838 static int slab_mem_going_online_callback(void *arg)
2840 struct kmem_cache_node *n;
2841 struct kmem_cache *s;
2842 struct memory_notify *marg = arg;
2843 int nid = marg->status_change_nid;
2844 int ret = 0;
2847 * If the node's memory is already available, then kmem_cache_node is
2848 * already created. Nothing to do.
2850 if (nid < 0)
2851 return 0;
2854 * We are bringing a node online. No memory is availabe yet. We must
2855 * allocate a kmem_cache_node structure in order to bring the node
2856 * online.
2858 down_read(&slub_lock);
2859 list_for_each_entry(s, &slab_caches, list) {
2861 * XXX: kmem_cache_alloc_node will fallback to other nodes
2862 * since memory is not yet available from the node that
2863 * is brought up.
2865 n = kmem_cache_alloc(kmalloc_caches, GFP_KERNEL);
2866 if (!n) {
2867 ret = -ENOMEM;
2868 goto out;
2870 init_kmem_cache_node(n);
2871 s->node[nid] = n;
2873 out:
2874 up_read(&slub_lock);
2875 return ret;
2878 static int slab_memory_callback(struct notifier_block *self,
2879 unsigned long action, void *arg)
2881 int ret = 0;
2883 switch (action) {
2884 case MEM_GOING_ONLINE:
2885 ret = slab_mem_going_online_callback(arg);
2886 break;
2887 case MEM_GOING_OFFLINE:
2888 ret = slab_mem_going_offline_callback(arg);
2889 break;
2890 case MEM_OFFLINE:
2891 case MEM_CANCEL_ONLINE:
2892 slab_mem_offline_callback(arg);
2893 break;
2894 case MEM_ONLINE:
2895 case MEM_CANCEL_OFFLINE:
2896 break;
2899 ret = notifier_from_errno(ret);
2900 return ret;
2903 #endif /* CONFIG_MEMORY_HOTPLUG */
2905 /********************************************************************
2906 * Basic setup of slabs
2907 *******************************************************************/
2909 void __init kmem_cache_init(void)
2911 int i;
2912 int caches = 0;
2914 init_alloc_cpu();
2916 #ifdef CONFIG_NUMA
2918 * Must first have the slab cache available for the allocations of the
2919 * struct kmem_cache_node's. There is special bootstrap code in
2920 * kmem_cache_open for slab_state == DOWN.
2922 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2923 sizeof(struct kmem_cache_node), GFP_KERNEL);
2924 kmalloc_caches[0].refcount = -1;
2925 caches++;
2927 hotplug_memory_notifier(slab_memory_callback, 1);
2928 #endif
2930 /* Able to allocate the per node structures */
2931 slab_state = PARTIAL;
2933 /* Caches that are not of the two-to-the-power-of size */
2934 if (KMALLOC_MIN_SIZE <= 64) {
2935 create_kmalloc_cache(&kmalloc_caches[1],
2936 "kmalloc-96", 96, GFP_KERNEL);
2937 caches++;
2939 if (KMALLOC_MIN_SIZE <= 128) {
2940 create_kmalloc_cache(&kmalloc_caches[2],
2941 "kmalloc-192", 192, GFP_KERNEL);
2942 caches++;
2945 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++) {
2946 create_kmalloc_cache(&kmalloc_caches[i],
2947 "kmalloc", 1 << i, GFP_KERNEL);
2948 caches++;
2953 * Patch up the size_index table if we have strange large alignment
2954 * requirements for the kmalloc array. This is only the case for
2955 * MIPS it seems. The standard arches will not generate any code here.
2957 * Largest permitted alignment is 256 bytes due to the way we
2958 * handle the index determination for the smaller caches.
2960 * Make sure that nothing crazy happens if someone starts tinkering
2961 * around with ARCH_KMALLOC_MINALIGN
2963 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
2964 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
2966 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
2967 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
2969 slab_state = UP;
2971 /* Provide the correct kmalloc names now that the caches are up */
2972 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++)
2973 kmalloc_caches[i]. name =
2974 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2976 #ifdef CONFIG_SMP
2977 register_cpu_notifier(&slab_notifier);
2978 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2979 nr_cpu_ids * sizeof(struct kmem_cache_cpu *);
2980 #else
2981 kmem_size = sizeof(struct kmem_cache);
2982 #endif
2984 printk(KERN_INFO
2985 "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2986 " CPUs=%d, Nodes=%d\n",
2987 caches, cache_line_size(),
2988 slub_min_order, slub_max_order, slub_min_objects,
2989 nr_cpu_ids, nr_node_ids);
2993 * Find a mergeable slab cache
2995 static int slab_unmergeable(struct kmem_cache *s)
2997 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2998 return 1;
3000 if ((s->flags & __PAGE_ALLOC_FALLBACK))
3001 return 1;
3003 if (s->ctor)
3004 return 1;
3007 * We may have set a slab to be unmergeable during bootstrap.
3009 if (s->refcount < 0)
3010 return 1;
3012 return 0;
3015 static struct kmem_cache *find_mergeable(size_t size,
3016 size_t align, unsigned long flags, const char *name,
3017 void (*ctor)(struct kmem_cache *, void *))
3019 struct kmem_cache *s;
3021 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
3022 return NULL;
3024 if (ctor)
3025 return NULL;
3027 size = ALIGN(size, sizeof(void *));
3028 align = calculate_alignment(flags, align, size);
3029 size = ALIGN(size, align);
3030 flags = kmem_cache_flags(size, flags, name, NULL);
3032 list_for_each_entry(s, &slab_caches, list) {
3033 if (slab_unmergeable(s))
3034 continue;
3036 if (size > s->size)
3037 continue;
3039 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
3040 continue;
3042 * Check if alignment is compatible.
3043 * Courtesy of Adrian Drzewiecki
3045 if ((s->size & ~(align - 1)) != s->size)
3046 continue;
3048 if (s->size - size >= sizeof(void *))
3049 continue;
3051 return s;
3053 return NULL;
3056 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
3057 size_t align, unsigned long flags,
3058 void (*ctor)(struct kmem_cache *, void *))
3060 struct kmem_cache *s;
3062 down_write(&slub_lock);
3063 s = find_mergeable(size, align, flags, name, ctor);
3064 if (s) {
3065 int cpu;
3067 s->refcount++;
3069 * Adjust the object sizes so that we clear
3070 * the complete object on kzalloc.
3072 s->objsize = max(s->objsize, (int)size);
3075 * And then we need to update the object size in the
3076 * per cpu structures
3078 for_each_online_cpu(cpu)
3079 get_cpu_slab(s, cpu)->objsize = s->objsize;
3081 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
3082 up_write(&slub_lock);
3084 if (sysfs_slab_alias(s, name))
3085 goto err;
3086 return s;
3089 s = kmalloc(kmem_size, GFP_KERNEL);
3090 if (s) {
3091 if (kmem_cache_open(s, GFP_KERNEL, name,
3092 size, align, flags, ctor)) {
3093 list_add(&s->list, &slab_caches);
3094 up_write(&slub_lock);
3095 if (sysfs_slab_add(s))
3096 goto err;
3097 return s;
3099 kfree(s);
3101 up_write(&slub_lock);
3103 err:
3104 if (flags & SLAB_PANIC)
3105 panic("Cannot create slabcache %s\n", name);
3106 else
3107 s = NULL;
3108 return s;
3110 EXPORT_SYMBOL(kmem_cache_create);
3112 #ifdef CONFIG_SMP
3114 * Use the cpu notifier to insure that the cpu slabs are flushed when
3115 * necessary.
3117 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
3118 unsigned long action, void *hcpu)
3120 long cpu = (long)hcpu;
3121 struct kmem_cache *s;
3122 unsigned long flags;
3124 switch (action) {
3125 case CPU_UP_PREPARE:
3126 case CPU_UP_PREPARE_FROZEN:
3127 init_alloc_cpu_cpu(cpu);
3128 down_read(&slub_lock);
3129 list_for_each_entry(s, &slab_caches, list)
3130 s->cpu_slab[cpu] = alloc_kmem_cache_cpu(s, cpu,
3131 GFP_KERNEL);
3132 up_read(&slub_lock);
3133 break;
3135 case CPU_UP_CANCELED:
3136 case CPU_UP_CANCELED_FROZEN:
3137 case CPU_DEAD:
3138 case CPU_DEAD_FROZEN:
3139 down_read(&slub_lock);
3140 list_for_each_entry(s, &slab_caches, list) {
3141 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3143 local_irq_save(flags);
3144 __flush_cpu_slab(s, cpu);
3145 local_irq_restore(flags);
3146 free_kmem_cache_cpu(c, cpu);
3147 s->cpu_slab[cpu] = NULL;
3149 up_read(&slub_lock);
3150 break;
3151 default:
3152 break;
3154 return NOTIFY_OK;
3157 static struct notifier_block __cpuinitdata slab_notifier = {
3158 .notifier_call = slab_cpuup_callback
3161 #endif
3163 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
3165 struct kmem_cache *s;
3167 if (unlikely(size > PAGE_SIZE))
3168 return kmalloc_large(size, gfpflags);
3170 s = get_slab(size, gfpflags);
3172 if (unlikely(ZERO_OR_NULL_PTR(s)))
3173 return s;
3175 return slab_alloc(s, gfpflags, -1, caller);
3178 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
3179 int node, void *caller)
3181 struct kmem_cache *s;
3183 if (unlikely(size > PAGE_SIZE))
3184 return kmalloc_large_node(size, gfpflags, node);
3186 s = get_slab(size, gfpflags);
3188 if (unlikely(ZERO_OR_NULL_PTR(s)))
3189 return s;
3191 return slab_alloc(s, gfpflags, node, caller);
3194 #if (defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)) || defined(CONFIG_SLABINFO)
3195 static unsigned long count_partial(struct kmem_cache_node *n)
3197 unsigned long flags;
3198 unsigned long x = 0;
3199 struct page *page;
3201 spin_lock_irqsave(&n->list_lock, flags);
3202 list_for_each_entry(page, &n->partial, lru)
3203 x += page->inuse;
3204 spin_unlock_irqrestore(&n->list_lock, flags);
3205 return x;
3207 #endif
3209 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
3210 static int validate_slab(struct kmem_cache *s, struct page *page,
3211 unsigned long *map)
3213 void *p;
3214 void *addr = page_address(page);
3216 if (!check_slab(s, page) ||
3217 !on_freelist(s, page, NULL))
3218 return 0;
3220 /* Now we know that a valid freelist exists */
3221 bitmap_zero(map, s->objects);
3223 for_each_free_object(p, s, page->freelist) {
3224 set_bit(slab_index(p, s, addr), map);
3225 if (!check_object(s, page, p, 0))
3226 return 0;
3229 for_each_object(p, s, addr)
3230 if (!test_bit(slab_index(p, s, addr), map))
3231 if (!check_object(s, page, p, 1))
3232 return 0;
3233 return 1;
3236 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
3237 unsigned long *map)
3239 if (slab_trylock(page)) {
3240 validate_slab(s, page, map);
3241 slab_unlock(page);
3242 } else
3243 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
3244 s->name, page);
3246 if (s->flags & DEBUG_DEFAULT_FLAGS) {
3247 if (!SlabDebug(page))
3248 printk(KERN_ERR "SLUB %s: SlabDebug not set "
3249 "on slab 0x%p\n", s->name, page);
3250 } else {
3251 if (SlabDebug(page))
3252 printk(KERN_ERR "SLUB %s: SlabDebug set on "
3253 "slab 0x%p\n", s->name, page);
3257 static int validate_slab_node(struct kmem_cache *s,
3258 struct kmem_cache_node *n, unsigned long *map)
3260 unsigned long count = 0;
3261 struct page *page;
3262 unsigned long flags;
3264 spin_lock_irqsave(&n->list_lock, flags);
3266 list_for_each_entry(page, &n->partial, lru) {
3267 validate_slab_slab(s, page, map);
3268 count++;
3270 if (count != n->nr_partial)
3271 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
3272 "counter=%ld\n", s->name, count, n->nr_partial);
3274 if (!(s->flags & SLAB_STORE_USER))
3275 goto out;
3277 list_for_each_entry(page, &n->full, lru) {
3278 validate_slab_slab(s, page, map);
3279 count++;
3281 if (count != atomic_long_read(&n->nr_slabs))
3282 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
3283 "counter=%ld\n", s->name, count,
3284 atomic_long_read(&n->nr_slabs));
3286 out:
3287 spin_unlock_irqrestore(&n->list_lock, flags);
3288 return count;
3291 static long validate_slab_cache(struct kmem_cache *s)
3293 int node;
3294 unsigned long count = 0;
3295 unsigned long *map = kmalloc(BITS_TO_LONGS(s->objects) *
3296 sizeof(unsigned long), GFP_KERNEL);
3298 if (!map)
3299 return -ENOMEM;
3301 flush_all(s);
3302 for_each_node_state(node, N_NORMAL_MEMORY) {
3303 struct kmem_cache_node *n = get_node(s, node);
3305 count += validate_slab_node(s, n, map);
3307 kfree(map);
3308 return count;
3311 #ifdef SLUB_RESILIENCY_TEST
3312 static void resiliency_test(void)
3314 u8 *p;
3316 printk(KERN_ERR "SLUB resiliency testing\n");
3317 printk(KERN_ERR "-----------------------\n");
3318 printk(KERN_ERR "A. Corruption after allocation\n");
3320 p = kzalloc(16, GFP_KERNEL);
3321 p[16] = 0x12;
3322 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
3323 " 0x12->0x%p\n\n", p + 16);
3325 validate_slab_cache(kmalloc_caches + 4);
3327 /* Hmmm... The next two are dangerous */
3328 p = kzalloc(32, GFP_KERNEL);
3329 p[32 + sizeof(void *)] = 0x34;
3330 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
3331 " 0x34 -> -0x%p\n", p);
3332 printk(KERN_ERR
3333 "If allocated object is overwritten then not detectable\n\n");
3335 validate_slab_cache(kmalloc_caches + 5);
3336 p = kzalloc(64, GFP_KERNEL);
3337 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
3338 *p = 0x56;
3339 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
3341 printk(KERN_ERR
3342 "If allocated object is overwritten then not detectable\n\n");
3343 validate_slab_cache(kmalloc_caches + 6);
3345 printk(KERN_ERR "\nB. Corruption after free\n");
3346 p = kzalloc(128, GFP_KERNEL);
3347 kfree(p);
3348 *p = 0x78;
3349 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
3350 validate_slab_cache(kmalloc_caches + 7);
3352 p = kzalloc(256, GFP_KERNEL);
3353 kfree(p);
3354 p[50] = 0x9a;
3355 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n",
3357 validate_slab_cache(kmalloc_caches + 8);
3359 p = kzalloc(512, GFP_KERNEL);
3360 kfree(p);
3361 p[512] = 0xab;
3362 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
3363 validate_slab_cache(kmalloc_caches + 9);
3365 #else
3366 static void resiliency_test(void) {};
3367 #endif
3370 * Generate lists of code addresses where slabcache objects are allocated
3371 * and freed.
3374 struct location {
3375 unsigned long count;
3376 void *addr;
3377 long long sum_time;
3378 long min_time;
3379 long max_time;
3380 long min_pid;
3381 long max_pid;
3382 cpumask_t cpus;
3383 nodemask_t nodes;
3386 struct loc_track {
3387 unsigned long max;
3388 unsigned long count;
3389 struct location *loc;
3392 static void free_loc_track(struct loc_track *t)
3394 if (t->max)
3395 free_pages((unsigned long)t->loc,
3396 get_order(sizeof(struct location) * t->max));
3399 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3401 struct location *l;
3402 int order;
3404 order = get_order(sizeof(struct location) * max);
3406 l = (void *)__get_free_pages(flags, order);
3407 if (!l)
3408 return 0;
3410 if (t->count) {
3411 memcpy(l, t->loc, sizeof(struct location) * t->count);
3412 free_loc_track(t);
3414 t->max = max;
3415 t->loc = l;
3416 return 1;
3419 static int add_location(struct loc_track *t, struct kmem_cache *s,
3420 const struct track *track)
3422 long start, end, pos;
3423 struct location *l;
3424 void *caddr;
3425 unsigned long age = jiffies - track->when;
3427 start = -1;
3428 end = t->count;
3430 for ( ; ; ) {
3431 pos = start + (end - start + 1) / 2;
3434 * There is nothing at "end". If we end up there
3435 * we need to add something to before end.
3437 if (pos == end)
3438 break;
3440 caddr = t->loc[pos].addr;
3441 if (track->addr == caddr) {
3443 l = &t->loc[pos];
3444 l->count++;
3445 if (track->when) {
3446 l->sum_time += age;
3447 if (age < l->min_time)
3448 l->min_time = age;
3449 if (age > l->max_time)
3450 l->max_time = age;
3452 if (track->pid < l->min_pid)
3453 l->min_pid = track->pid;
3454 if (track->pid > l->max_pid)
3455 l->max_pid = track->pid;
3457 cpu_set(track->cpu, l->cpus);
3459 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3460 return 1;
3463 if (track->addr < caddr)
3464 end = pos;
3465 else
3466 start = pos;
3470 * Not found. Insert new tracking element.
3472 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3473 return 0;
3475 l = t->loc + pos;
3476 if (pos < t->count)
3477 memmove(l + 1, l,
3478 (t->count - pos) * sizeof(struct location));
3479 t->count++;
3480 l->count = 1;
3481 l->addr = track->addr;
3482 l->sum_time = age;
3483 l->min_time = age;
3484 l->max_time = age;
3485 l->min_pid = track->pid;
3486 l->max_pid = track->pid;
3487 cpus_clear(l->cpus);
3488 cpu_set(track->cpu, l->cpus);
3489 nodes_clear(l->nodes);
3490 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3491 return 1;
3494 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3495 struct page *page, enum track_item alloc)
3497 void *addr = page_address(page);
3498 DECLARE_BITMAP(map, s->objects);
3499 void *p;
3501 bitmap_zero(map, s->objects);
3502 for_each_free_object(p, s, page->freelist)
3503 set_bit(slab_index(p, s, addr), map);
3505 for_each_object(p, s, addr)
3506 if (!test_bit(slab_index(p, s, addr), map))
3507 add_location(t, s, get_track(s, p, alloc));
3510 static int list_locations(struct kmem_cache *s, char *buf,
3511 enum track_item alloc)
3513 int len = 0;
3514 unsigned long i;
3515 struct loc_track t = { 0, 0, NULL };
3516 int node;
3518 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3519 GFP_TEMPORARY))
3520 return sprintf(buf, "Out of memory\n");
3522 /* Push back cpu slabs */
3523 flush_all(s);
3525 for_each_node_state(node, N_NORMAL_MEMORY) {
3526 struct kmem_cache_node *n = get_node(s, node);
3527 unsigned long flags;
3528 struct page *page;
3530 if (!atomic_long_read(&n->nr_slabs))
3531 continue;
3533 spin_lock_irqsave(&n->list_lock, flags);
3534 list_for_each_entry(page, &n->partial, lru)
3535 process_slab(&t, s, page, alloc);
3536 list_for_each_entry(page, &n->full, lru)
3537 process_slab(&t, s, page, alloc);
3538 spin_unlock_irqrestore(&n->list_lock, flags);
3541 for (i = 0; i < t.count; i++) {
3542 struct location *l = &t.loc[i];
3544 if (len > PAGE_SIZE - 100)
3545 break;
3546 len += sprintf(buf + len, "%7ld ", l->count);
3548 if (l->addr)
3549 len += sprint_symbol(buf + len, (unsigned long)l->addr);
3550 else
3551 len += sprintf(buf + len, "<not-available>");
3553 if (l->sum_time != l->min_time) {
3554 unsigned long remainder;
3556 len += sprintf(buf + len, " age=%ld/%ld/%ld",
3557 l->min_time,
3558 div_long_long_rem(l->sum_time, l->count, &remainder),
3559 l->max_time);
3560 } else
3561 len += sprintf(buf + len, " age=%ld",
3562 l->min_time);
3564 if (l->min_pid != l->max_pid)
3565 len += sprintf(buf + len, " pid=%ld-%ld",
3566 l->min_pid, l->max_pid);
3567 else
3568 len += sprintf(buf + len, " pid=%ld",
3569 l->min_pid);
3571 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3572 len < PAGE_SIZE - 60) {
3573 len += sprintf(buf + len, " cpus=");
3574 len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3575 l->cpus);
3578 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3579 len < PAGE_SIZE - 60) {
3580 len += sprintf(buf + len, " nodes=");
3581 len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3582 l->nodes);
3585 len += sprintf(buf + len, "\n");
3588 free_loc_track(&t);
3589 if (!t.count)
3590 len += sprintf(buf, "No data\n");
3591 return len;
3594 enum slab_stat_type {
3595 SL_FULL,
3596 SL_PARTIAL,
3597 SL_CPU,
3598 SL_OBJECTS
3601 #define SO_FULL (1 << SL_FULL)
3602 #define SO_PARTIAL (1 << SL_PARTIAL)
3603 #define SO_CPU (1 << SL_CPU)
3604 #define SO_OBJECTS (1 << SL_OBJECTS)
3606 static ssize_t show_slab_objects(struct kmem_cache *s,
3607 char *buf, unsigned long flags)
3609 unsigned long total = 0;
3610 int cpu;
3611 int node;
3612 int x;
3613 unsigned long *nodes;
3614 unsigned long *per_cpu;
3616 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3617 if (!nodes)
3618 return -ENOMEM;
3619 per_cpu = nodes + nr_node_ids;
3621 for_each_possible_cpu(cpu) {
3622 struct page *page;
3623 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3625 if (!c)
3626 continue;
3628 page = c->page;
3629 node = c->node;
3630 if (node < 0)
3631 continue;
3632 if (page) {
3633 if (flags & SO_CPU) {
3634 if (flags & SO_OBJECTS)
3635 x = page->inuse;
3636 else
3637 x = 1;
3638 total += x;
3639 nodes[node] += x;
3641 per_cpu[node]++;
3645 for_each_node_state(node, N_NORMAL_MEMORY) {
3646 struct kmem_cache_node *n = get_node(s, node);
3648 if (flags & SO_PARTIAL) {
3649 if (flags & SO_OBJECTS)
3650 x = count_partial(n);
3651 else
3652 x = n->nr_partial;
3653 total += x;
3654 nodes[node] += x;
3657 if (flags & SO_FULL) {
3658 int full_slabs = atomic_long_read(&n->nr_slabs)
3659 - per_cpu[node]
3660 - n->nr_partial;
3662 if (flags & SO_OBJECTS)
3663 x = full_slabs * s->objects;
3664 else
3665 x = full_slabs;
3666 total += x;
3667 nodes[node] += x;
3671 x = sprintf(buf, "%lu", total);
3672 #ifdef CONFIG_NUMA
3673 for_each_node_state(node, N_NORMAL_MEMORY)
3674 if (nodes[node])
3675 x += sprintf(buf + x, " N%d=%lu",
3676 node, nodes[node]);
3677 #endif
3678 kfree(nodes);
3679 return x + sprintf(buf + x, "\n");
3682 static int any_slab_objects(struct kmem_cache *s)
3684 int node;
3685 int cpu;
3687 for_each_possible_cpu(cpu) {
3688 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3690 if (c && c->page)
3691 return 1;
3694 for_each_online_node(node) {
3695 struct kmem_cache_node *n = get_node(s, node);
3697 if (!n)
3698 continue;
3700 if (n->nr_partial || atomic_long_read(&n->nr_slabs))
3701 return 1;
3703 return 0;
3706 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3707 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3709 struct slab_attribute {
3710 struct attribute attr;
3711 ssize_t (*show)(struct kmem_cache *s, char *buf);
3712 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3715 #define SLAB_ATTR_RO(_name) \
3716 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3718 #define SLAB_ATTR(_name) \
3719 static struct slab_attribute _name##_attr = \
3720 __ATTR(_name, 0644, _name##_show, _name##_store)
3722 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3724 return sprintf(buf, "%d\n", s->size);
3726 SLAB_ATTR_RO(slab_size);
3728 static ssize_t align_show(struct kmem_cache *s, char *buf)
3730 return sprintf(buf, "%d\n", s->align);
3732 SLAB_ATTR_RO(align);
3734 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3736 return sprintf(buf, "%d\n", s->objsize);
3738 SLAB_ATTR_RO(object_size);
3740 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3742 return sprintf(buf, "%d\n", s->objects);
3744 SLAB_ATTR_RO(objs_per_slab);
3746 static ssize_t order_show(struct kmem_cache *s, char *buf)
3748 return sprintf(buf, "%d\n", s->order);
3750 SLAB_ATTR_RO(order);
3752 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3754 if (s->ctor) {
3755 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3757 return n + sprintf(buf + n, "\n");
3759 return 0;
3761 SLAB_ATTR_RO(ctor);
3763 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3765 return sprintf(buf, "%d\n", s->refcount - 1);
3767 SLAB_ATTR_RO(aliases);
3769 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3771 return show_slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3773 SLAB_ATTR_RO(slabs);
3775 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3777 return show_slab_objects(s, buf, SO_PARTIAL);
3779 SLAB_ATTR_RO(partial);
3781 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3783 return show_slab_objects(s, buf, SO_CPU);
3785 SLAB_ATTR_RO(cpu_slabs);
3787 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3789 return show_slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3791 SLAB_ATTR_RO(objects);
3793 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3795 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3798 static ssize_t sanity_checks_store(struct kmem_cache *s,
3799 const char *buf, size_t length)
3801 s->flags &= ~SLAB_DEBUG_FREE;
3802 if (buf[0] == '1')
3803 s->flags |= SLAB_DEBUG_FREE;
3804 return length;
3806 SLAB_ATTR(sanity_checks);
3808 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3810 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3813 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3814 size_t length)
3816 s->flags &= ~SLAB_TRACE;
3817 if (buf[0] == '1')
3818 s->flags |= SLAB_TRACE;
3819 return length;
3821 SLAB_ATTR(trace);
3823 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3825 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3828 static ssize_t reclaim_account_store(struct kmem_cache *s,
3829 const char *buf, size_t length)
3831 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3832 if (buf[0] == '1')
3833 s->flags |= SLAB_RECLAIM_ACCOUNT;
3834 return length;
3836 SLAB_ATTR(reclaim_account);
3838 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3840 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3842 SLAB_ATTR_RO(hwcache_align);
3844 #ifdef CONFIG_ZONE_DMA
3845 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3847 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3849 SLAB_ATTR_RO(cache_dma);
3850 #endif
3852 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3854 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3856 SLAB_ATTR_RO(destroy_by_rcu);
3858 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3860 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3863 static ssize_t red_zone_store(struct kmem_cache *s,
3864 const char *buf, size_t length)
3866 if (any_slab_objects(s))
3867 return -EBUSY;
3869 s->flags &= ~SLAB_RED_ZONE;
3870 if (buf[0] == '1')
3871 s->flags |= SLAB_RED_ZONE;
3872 calculate_sizes(s);
3873 return length;
3875 SLAB_ATTR(red_zone);
3877 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3879 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3882 static ssize_t poison_store(struct kmem_cache *s,
3883 const char *buf, size_t length)
3885 if (any_slab_objects(s))
3886 return -EBUSY;
3888 s->flags &= ~SLAB_POISON;
3889 if (buf[0] == '1')
3890 s->flags |= SLAB_POISON;
3891 calculate_sizes(s);
3892 return length;
3894 SLAB_ATTR(poison);
3896 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3898 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3901 static ssize_t store_user_store(struct kmem_cache *s,
3902 const char *buf, size_t length)
3904 if (any_slab_objects(s))
3905 return -EBUSY;
3907 s->flags &= ~SLAB_STORE_USER;
3908 if (buf[0] == '1')
3909 s->flags |= SLAB_STORE_USER;
3910 calculate_sizes(s);
3911 return length;
3913 SLAB_ATTR(store_user);
3915 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3917 return 0;
3920 static ssize_t validate_store(struct kmem_cache *s,
3921 const char *buf, size_t length)
3923 int ret = -EINVAL;
3925 if (buf[0] == '1') {
3926 ret = validate_slab_cache(s);
3927 if (ret >= 0)
3928 ret = length;
3930 return ret;
3932 SLAB_ATTR(validate);
3934 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3936 return 0;
3939 static ssize_t shrink_store(struct kmem_cache *s,
3940 const char *buf, size_t length)
3942 if (buf[0] == '1') {
3943 int rc = kmem_cache_shrink(s);
3945 if (rc)
3946 return rc;
3947 } else
3948 return -EINVAL;
3949 return length;
3951 SLAB_ATTR(shrink);
3953 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3955 if (!(s->flags & SLAB_STORE_USER))
3956 return -ENOSYS;
3957 return list_locations(s, buf, TRACK_ALLOC);
3959 SLAB_ATTR_RO(alloc_calls);
3961 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3963 if (!(s->flags & SLAB_STORE_USER))
3964 return -ENOSYS;
3965 return list_locations(s, buf, TRACK_FREE);
3967 SLAB_ATTR_RO(free_calls);
3969 #ifdef CONFIG_NUMA
3970 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
3972 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
3975 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
3976 const char *buf, size_t length)
3978 int n = simple_strtoul(buf, NULL, 10);
3980 if (n < 100)
3981 s->remote_node_defrag_ratio = n * 10;
3982 return length;
3984 SLAB_ATTR(remote_node_defrag_ratio);
3985 #endif
3987 #ifdef CONFIG_SLUB_STATS
3988 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
3990 unsigned long sum = 0;
3991 int cpu;
3992 int len;
3993 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
3995 if (!data)
3996 return -ENOMEM;
3998 for_each_online_cpu(cpu) {
3999 unsigned x = get_cpu_slab(s, cpu)->stat[si];
4001 data[cpu] = x;
4002 sum += x;
4005 len = sprintf(buf, "%lu", sum);
4007 #ifdef CONFIG_SMP
4008 for_each_online_cpu(cpu) {
4009 if (data[cpu] && len < PAGE_SIZE - 20)
4010 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
4012 #endif
4013 kfree(data);
4014 return len + sprintf(buf + len, "\n");
4017 #define STAT_ATTR(si, text) \
4018 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
4020 return show_stat(s, buf, si); \
4022 SLAB_ATTR_RO(text); \
4024 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
4025 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
4026 STAT_ATTR(FREE_FASTPATH, free_fastpath);
4027 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
4028 STAT_ATTR(FREE_FROZEN, free_frozen);
4029 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
4030 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
4031 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
4032 STAT_ATTR(ALLOC_SLAB, alloc_slab);
4033 STAT_ATTR(ALLOC_REFILL, alloc_refill);
4034 STAT_ATTR(FREE_SLAB, free_slab);
4035 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
4036 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
4037 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
4038 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
4039 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
4040 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
4042 #endif
4044 static struct attribute *slab_attrs[] = {
4045 &slab_size_attr.attr,
4046 &object_size_attr.attr,
4047 &objs_per_slab_attr.attr,
4048 &order_attr.attr,
4049 &objects_attr.attr,
4050 &slabs_attr.attr,
4051 &partial_attr.attr,
4052 &cpu_slabs_attr.attr,
4053 &ctor_attr.attr,
4054 &aliases_attr.attr,
4055 &align_attr.attr,
4056 &sanity_checks_attr.attr,
4057 &trace_attr.attr,
4058 &hwcache_align_attr.attr,
4059 &reclaim_account_attr.attr,
4060 &destroy_by_rcu_attr.attr,
4061 &red_zone_attr.attr,
4062 &poison_attr.attr,
4063 &store_user_attr.attr,
4064 &validate_attr.attr,
4065 &shrink_attr.attr,
4066 &alloc_calls_attr.attr,
4067 &free_calls_attr.attr,
4068 #ifdef CONFIG_ZONE_DMA
4069 &cache_dma_attr.attr,
4070 #endif
4071 #ifdef CONFIG_NUMA
4072 &remote_node_defrag_ratio_attr.attr,
4073 #endif
4074 #ifdef CONFIG_SLUB_STATS
4075 &alloc_fastpath_attr.attr,
4076 &alloc_slowpath_attr.attr,
4077 &free_fastpath_attr.attr,
4078 &free_slowpath_attr.attr,
4079 &free_frozen_attr.attr,
4080 &free_add_partial_attr.attr,
4081 &free_remove_partial_attr.attr,
4082 &alloc_from_partial_attr.attr,
4083 &alloc_slab_attr.attr,
4084 &alloc_refill_attr.attr,
4085 &free_slab_attr.attr,
4086 &cpuslab_flush_attr.attr,
4087 &deactivate_full_attr.attr,
4088 &deactivate_empty_attr.attr,
4089 &deactivate_to_head_attr.attr,
4090 &deactivate_to_tail_attr.attr,
4091 &deactivate_remote_frees_attr.attr,
4092 #endif
4093 NULL
4096 static struct attribute_group slab_attr_group = {
4097 .attrs = slab_attrs,
4100 static ssize_t slab_attr_show(struct kobject *kobj,
4101 struct attribute *attr,
4102 char *buf)
4104 struct slab_attribute *attribute;
4105 struct kmem_cache *s;
4106 int err;
4108 attribute = to_slab_attr(attr);
4109 s = to_slab(kobj);
4111 if (!attribute->show)
4112 return -EIO;
4114 err = attribute->show(s, buf);
4116 return err;
4119 static ssize_t slab_attr_store(struct kobject *kobj,
4120 struct attribute *attr,
4121 const char *buf, size_t len)
4123 struct slab_attribute *attribute;
4124 struct kmem_cache *s;
4125 int err;
4127 attribute = to_slab_attr(attr);
4128 s = to_slab(kobj);
4130 if (!attribute->store)
4131 return -EIO;
4133 err = attribute->store(s, buf, len);
4135 return err;
4138 static void kmem_cache_release(struct kobject *kobj)
4140 struct kmem_cache *s = to_slab(kobj);
4142 kfree(s);
4145 static struct sysfs_ops slab_sysfs_ops = {
4146 .show = slab_attr_show,
4147 .store = slab_attr_store,
4150 static struct kobj_type slab_ktype = {
4151 .sysfs_ops = &slab_sysfs_ops,
4152 .release = kmem_cache_release
4155 static int uevent_filter(struct kset *kset, struct kobject *kobj)
4157 struct kobj_type *ktype = get_ktype(kobj);
4159 if (ktype == &slab_ktype)
4160 return 1;
4161 return 0;
4164 static struct kset_uevent_ops slab_uevent_ops = {
4165 .filter = uevent_filter,
4168 static struct kset *slab_kset;
4170 #define ID_STR_LENGTH 64
4172 /* Create a unique string id for a slab cache:
4174 * Format :[flags-]size
4176 static char *create_unique_id(struct kmem_cache *s)
4178 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
4179 char *p = name;
4181 BUG_ON(!name);
4183 *p++ = ':';
4185 * First flags affecting slabcache operations. We will only
4186 * get here for aliasable slabs so we do not need to support
4187 * too many flags. The flags here must cover all flags that
4188 * are matched during merging to guarantee that the id is
4189 * unique.
4191 if (s->flags & SLAB_CACHE_DMA)
4192 *p++ = 'd';
4193 if (s->flags & SLAB_RECLAIM_ACCOUNT)
4194 *p++ = 'a';
4195 if (s->flags & SLAB_DEBUG_FREE)
4196 *p++ = 'F';
4197 if (p != name + 1)
4198 *p++ = '-';
4199 p += sprintf(p, "%07d", s->size);
4200 BUG_ON(p > name + ID_STR_LENGTH - 1);
4201 return name;
4204 static int sysfs_slab_add(struct kmem_cache *s)
4206 int err;
4207 const char *name;
4208 int unmergeable;
4210 if (slab_state < SYSFS)
4211 /* Defer until later */
4212 return 0;
4214 unmergeable = slab_unmergeable(s);
4215 if (unmergeable) {
4217 * Slabcache can never be merged so we can use the name proper.
4218 * This is typically the case for debug situations. In that
4219 * case we can catch duplicate names easily.
4221 sysfs_remove_link(&slab_kset->kobj, s->name);
4222 name = s->name;
4223 } else {
4225 * Create a unique name for the slab as a target
4226 * for the symlinks.
4228 name = create_unique_id(s);
4231 s->kobj.kset = slab_kset;
4232 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, name);
4233 if (err) {
4234 kobject_put(&s->kobj);
4235 return err;
4238 err = sysfs_create_group(&s->kobj, &slab_attr_group);
4239 if (err)
4240 return err;
4241 kobject_uevent(&s->kobj, KOBJ_ADD);
4242 if (!unmergeable) {
4243 /* Setup first alias */
4244 sysfs_slab_alias(s, s->name);
4245 kfree(name);
4247 return 0;
4250 static void sysfs_slab_remove(struct kmem_cache *s)
4252 kobject_uevent(&s->kobj, KOBJ_REMOVE);
4253 kobject_del(&s->kobj);
4254 kobject_put(&s->kobj);
4258 * Need to buffer aliases during bootup until sysfs becomes
4259 * available lest we loose that information.
4261 struct saved_alias {
4262 struct kmem_cache *s;
4263 const char *name;
4264 struct saved_alias *next;
4267 static struct saved_alias *alias_list;
4269 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
4271 struct saved_alias *al;
4273 if (slab_state == SYSFS) {
4275 * If we have a leftover link then remove it.
4277 sysfs_remove_link(&slab_kset->kobj, name);
4278 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
4281 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
4282 if (!al)
4283 return -ENOMEM;
4285 al->s = s;
4286 al->name = name;
4287 al->next = alias_list;
4288 alias_list = al;
4289 return 0;
4292 static int __init slab_sysfs_init(void)
4294 struct kmem_cache *s;
4295 int err;
4297 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
4298 if (!slab_kset) {
4299 printk(KERN_ERR "Cannot register slab subsystem.\n");
4300 return -ENOSYS;
4303 slab_state = SYSFS;
4305 list_for_each_entry(s, &slab_caches, list) {
4306 err = sysfs_slab_add(s);
4307 if (err)
4308 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
4309 " to sysfs\n", s->name);
4312 while (alias_list) {
4313 struct saved_alias *al = alias_list;
4315 alias_list = alias_list->next;
4316 err = sysfs_slab_alias(al->s, al->name);
4317 if (err)
4318 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
4319 " %s to sysfs\n", s->name);
4320 kfree(al);
4323 resiliency_test();
4324 return 0;
4327 __initcall(slab_sysfs_init);
4328 #endif
4331 * The /proc/slabinfo ABI
4333 #ifdef CONFIG_SLABINFO
4335 ssize_t slabinfo_write(struct file *file, const char __user * buffer,
4336 size_t count, loff_t *ppos)
4338 return -EINVAL;
4342 static void print_slabinfo_header(struct seq_file *m)
4344 seq_puts(m, "slabinfo - version: 2.1\n");
4345 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4346 "<objperslab> <pagesperslab>");
4347 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4348 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4349 seq_putc(m, '\n');
4352 static void *s_start(struct seq_file *m, loff_t *pos)
4354 loff_t n = *pos;
4356 down_read(&slub_lock);
4357 if (!n)
4358 print_slabinfo_header(m);
4360 return seq_list_start(&slab_caches, *pos);
4363 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4365 return seq_list_next(p, &slab_caches, pos);
4368 static void s_stop(struct seq_file *m, void *p)
4370 up_read(&slub_lock);
4373 static int s_show(struct seq_file *m, void *p)
4375 unsigned long nr_partials = 0;
4376 unsigned long nr_slabs = 0;
4377 unsigned long nr_inuse = 0;
4378 unsigned long nr_objs;
4379 struct kmem_cache *s;
4380 int node;
4382 s = list_entry(p, struct kmem_cache, list);
4384 for_each_online_node(node) {
4385 struct kmem_cache_node *n = get_node(s, node);
4387 if (!n)
4388 continue;
4390 nr_partials += n->nr_partial;
4391 nr_slabs += atomic_long_read(&n->nr_slabs);
4392 nr_inuse += count_partial(n);
4395 nr_objs = nr_slabs * s->objects;
4396 nr_inuse += (nr_slabs - nr_partials) * s->objects;
4398 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", s->name, nr_inuse,
4399 nr_objs, s->size, s->objects, (1 << s->order));
4400 seq_printf(m, " : tunables %4u %4u %4u", 0, 0, 0);
4401 seq_printf(m, " : slabdata %6lu %6lu %6lu", nr_slabs, nr_slabs,
4402 0UL);
4403 seq_putc(m, '\n');
4404 return 0;
4407 const struct seq_operations slabinfo_op = {
4408 .start = s_start,
4409 .next = s_next,
4410 .stop = s_stop,
4411 .show = s_show,
4414 #endif /* CONFIG_SLABINFO */