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>
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>
29 * The slab_lock protects operations on the object of a particular
30 * slab and its metadata in the page struct. If the slab lock
31 * has been taken then no allocations nor frees can be performed
32 * on the objects in the slab nor can the slab be added or removed
33 * from the partial or full lists since this would mean modifying
34 * the page_struct of the slab.
36 * The list_lock protects the partial and full list on each node and
37 * the partial slab counter. If taken then no new slabs may be added or
38 * removed from the lists nor make the number of partial slabs be modified.
39 * (Note that the total number of slabs is an atomic value that may be
40 * modified without taking the list lock).
42 * The list_lock is a centralized lock and thus we avoid taking it as
43 * much as possible. As long as SLUB does not have to handle partial
44 * slabs, operations can continue without any centralized lock. F.e.
45 * allocating a long series of objects that fill up slabs does not require
48 * The lock order is sometimes inverted when we are trying to get a slab
49 * off a list. We take the list_lock and then look for a page on the list
50 * to use. While we do that objects in the slabs may be freed. We can
51 * only operate on the slab if we have also taken the slab_lock. So we use
52 * a slab_trylock() on the slab. If trylock was successful then no frees
53 * can occur anymore and we can use the slab for allocations etc. If the
54 * slab_trylock() does not succeed then frees are in progress in the slab and
55 * we must stay away from it for a while since we may cause a bouncing
56 * cacheline if we try to acquire the lock. So go onto the next slab.
57 * If all pages are busy then we may allocate a new slab instead of reusing
58 * a partial slab. A new slab has noone operating on it and thus there is
59 * no danger of cacheline contention.
61 * Interrupts are disabled during allocation and deallocation in order to
62 * make the slab allocator safe to use in the context of an irq. In addition
63 * interrupts are disabled to ensure that the processor does not change
64 * while handling per_cpu slabs, due to kernel preemption.
66 * SLUB assigns one slab for allocation to each processor.
67 * Allocations only occur from these slabs called cpu slabs.
69 * Slabs with free elements are kept on a partial list and during regular
70 * operations no list for full slabs is used. If an object in a full slab is
71 * freed then the slab will show up again on the partial lists.
72 * We track full slabs for debugging purposes though because otherwise we
73 * cannot scan all objects.
75 * Slabs are freed when they become empty. Teardown and setup is
76 * minimal so we rely on the page allocators per cpu caches for
77 * fast frees and allocs.
79 * Overloading of page flags that are otherwise used for LRU management.
81 * PageActive The slab is frozen and exempt from list processing.
82 * This means that the slab is dedicated to a purpose
83 * such as satisfying allocations for a specific
84 * processor. Objects may be freed in the slab while
85 * it is frozen but slab_free will then skip the usual
86 * list operations. It is up to the processor holding
87 * the slab to integrate the slab into the slab lists
88 * when the slab is no longer needed.
90 * One use of this flag is to mark slabs that are
91 * used for allocations. Then such a slab becomes a cpu
92 * slab. The cpu slab may be equipped with an additional
93 * lockless_freelist that allows lockless access to
94 * free objects in addition to the regular freelist
95 * that requires the slab lock.
97 * PageError Slab requires special handling due to debug
98 * options set. This moves slab handling out of
99 * the fast path and disables lockless freelists.
102 #define FROZEN (1 << PG_active)
104 #ifdef CONFIG_SLUB_DEBUG
105 #define SLABDEBUG (1 << PG_error)
110 static inline int SlabFrozen(struct page *page)
112 return page->flags & FROZEN;
115 static inline void SetSlabFrozen(struct page *page)
117 page->flags |= FROZEN;
120 static inline void ClearSlabFrozen(struct page *page)
122 page->flags &= ~FROZEN;
125 static inline int SlabDebug(struct page *page)
127 return page->flags & SLABDEBUG;
130 static inline void SetSlabDebug(struct page *page)
132 page->flags |= SLABDEBUG;
135 static inline void ClearSlabDebug(struct page *page)
137 page->flags &= ~SLABDEBUG;
141 * Issues still to be resolved:
143 * - The per cpu array is updated for each new slab and and is a remote
144 * cacheline for most nodes. This could become a bouncing cacheline given
145 * enough frequent updates. There are 16 pointers in a cacheline, so at
146 * max 16 cpus could compete for the cacheline which may be okay.
148 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
150 * - Variable sizing of the per node arrays
153 /* Enable to test recovery from slab corruption on boot */
154 #undef SLUB_RESILIENCY_TEST
159 * Small page size. Make sure that we do not fragment memory
161 #define DEFAULT_MAX_ORDER 1
162 #define DEFAULT_MIN_OBJECTS 4
167 * Large page machines are customarily able to handle larger
170 #define DEFAULT_MAX_ORDER 2
171 #define DEFAULT_MIN_OBJECTS 8
176 * Mininum number of partial slabs. These will be left on the partial
177 * lists even if they are empty. kmem_cache_shrink may reclaim them.
179 #define MIN_PARTIAL 2
182 * Maximum number of desirable partial slabs.
183 * The existence of more partial slabs makes kmem_cache_shrink
184 * sort the partial list by the number of objects in the.
186 #define MAX_PARTIAL 10
188 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
189 SLAB_POISON | SLAB_STORE_USER)
192 * Set of flags that will prevent slab merging
194 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
195 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
197 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
200 #ifndef ARCH_KMALLOC_MINALIGN
201 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
204 #ifndef ARCH_SLAB_MINALIGN
205 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
208 /* Internal SLUB flags */
209 #define __OBJECT_POISON 0x80000000 /* Poison object */
211 /* Not all arches define cache_line_size */
212 #ifndef cache_line_size
213 #define cache_line_size() L1_CACHE_BYTES
216 static int kmem_size = sizeof(struct kmem_cache);
219 static struct notifier_block slab_notifier;
223 DOWN, /* No slab functionality available */
224 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
225 UP, /* Everything works but does not show up in sysfs */
229 /* A list of all slab caches on the system */
230 static DECLARE_RWSEM(slub_lock);
231 LIST_HEAD(slab_caches);
234 * Tracking user of a slab.
237 void *addr; /* Called from address */
238 int cpu; /* Was running on cpu */
239 int pid; /* Pid context */
240 unsigned long when; /* When did the operation occur */
243 enum track_item { TRACK_ALLOC, TRACK_FREE };
245 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
246 static int sysfs_slab_add(struct kmem_cache *);
247 static int sysfs_slab_alias(struct kmem_cache *, const char *);
248 static void sysfs_slab_remove(struct kmem_cache *);
250 static int sysfs_slab_add(struct kmem_cache *s) { return 0; }
251 static int sysfs_slab_alias(struct kmem_cache *s, const char *p) { return 0; }
252 static void sysfs_slab_remove(struct kmem_cache *s) {}
255 /********************************************************************
256 * Core slab cache functions
257 *******************************************************************/
259 int slab_is_available(void)
261 return slab_state >= UP;
264 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
267 return s->node[node];
269 return &s->local_node;
273 static inline int check_valid_pointer(struct kmem_cache *s,
274 struct page *page, const void *object)
281 base = page_address(page);
282 if (object < base || object >= base + s->objects * s->size ||
283 (object - base) % s->size) {
291 * Slow version of get and set free pointer.
293 * This version requires touching the cache lines of kmem_cache which
294 * we avoid to do in the fast alloc free paths. There we obtain the offset
295 * from the page struct.
297 static inline void *get_freepointer(struct kmem_cache *s, void *object)
299 return *(void **)(object + s->offset);
302 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
304 *(void **)(object + s->offset) = fp;
307 /* Loop over all objects in a slab */
308 #define for_each_object(__p, __s, __addr) \
309 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
313 #define for_each_free_object(__p, __s, __free) \
314 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
316 /* Determine object index from a given position */
317 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
319 return (p - addr) / s->size;
322 #ifdef CONFIG_SLUB_DEBUG
326 #ifdef CONFIG_SLUB_DEBUG_ON
327 static int slub_debug = DEBUG_DEFAULT_FLAGS;
329 static int slub_debug;
332 static char *slub_debug_slabs;
337 static void print_section(char *text, u8 *addr, unsigned int length)
345 for (i = 0; i < length; i++) {
347 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
350 printk(" %02x", addr[i]);
352 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
354 printk(" %s\n",ascii);
365 printk(" %s\n", ascii);
369 static struct track *get_track(struct kmem_cache *s, void *object,
370 enum track_item alloc)
375 p = object + s->offset + sizeof(void *);
377 p = object + s->inuse;
382 static void set_track(struct kmem_cache *s, void *object,
383 enum track_item alloc, void *addr)
388 p = object + s->offset + sizeof(void *);
390 p = object + s->inuse;
395 p->cpu = smp_processor_id();
396 p->pid = current ? current->pid : -1;
399 memset(p, 0, sizeof(struct track));
402 static void init_tracking(struct kmem_cache *s, void *object)
404 if (!(s->flags & SLAB_STORE_USER))
407 set_track(s, object, TRACK_FREE, NULL);
408 set_track(s, object, TRACK_ALLOC, NULL);
411 static void print_track(const char *s, struct track *t)
416 printk(KERN_ERR "INFO: %s in ", s);
417 __print_symbol("%s", (unsigned long)t->addr);
418 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
421 static void print_tracking(struct kmem_cache *s, void *object)
423 if (!(s->flags & SLAB_STORE_USER))
426 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
427 print_track("Freed", get_track(s, object, TRACK_FREE));
430 static void print_page_info(struct page *page)
432 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
433 page, page->inuse, page->freelist, page->flags);
437 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
443 vsnprintf(buf, sizeof(buf), fmt, args);
445 printk(KERN_ERR "========================================"
446 "=====================================\n");
447 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
448 printk(KERN_ERR "----------------------------------------"
449 "-------------------------------------\n\n");
452 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
458 vsnprintf(buf, sizeof(buf), fmt, args);
460 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
463 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
465 unsigned int off; /* Offset of last byte */
466 u8 *addr = page_address(page);
468 print_tracking(s, p);
470 print_page_info(page);
472 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
473 p, p - addr, get_freepointer(s, p));
476 print_section("Bytes b4", p - 16, 16);
478 print_section("Object", p, min(s->objsize, 128));
480 if (s->flags & SLAB_RED_ZONE)
481 print_section("Redzone", p + s->objsize,
482 s->inuse - s->objsize);
485 off = s->offset + sizeof(void *);
489 if (s->flags & SLAB_STORE_USER)
490 off += 2 * sizeof(struct track);
493 /* Beginning of the filler is the free pointer */
494 print_section("Padding", p + off, s->size - off);
499 static void object_err(struct kmem_cache *s, struct page *page,
500 u8 *object, char *reason)
503 print_trailer(s, page, object);
506 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
512 vsnprintf(buf, sizeof(buf), fmt, args);
515 print_page_info(page);
519 static void init_object(struct kmem_cache *s, void *object, int active)
523 if (s->flags & __OBJECT_POISON) {
524 memset(p, POISON_FREE, s->objsize - 1);
525 p[s->objsize -1] = POISON_END;
528 if (s->flags & SLAB_RED_ZONE)
529 memset(p + s->objsize,
530 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
531 s->inuse - s->objsize);
534 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
537 if (*start != (u8)value)
545 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
546 void *from, void *to)
548 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
549 memset(from, data, to - from);
552 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
553 u8 *object, char *what,
554 u8* start, unsigned int value, unsigned int bytes)
559 fault = check_bytes(start, value, bytes);
564 while (end > fault && end[-1] == value)
567 slab_bug(s, "%s overwritten", what);
568 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
569 fault, end - 1, fault[0], value);
570 print_trailer(s, page, object);
572 restore_bytes(s, what, value, fault, end);
580 * Bytes of the object to be managed.
581 * If the freepointer may overlay the object then the free
582 * pointer is the first word of the object.
584 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
587 * object + s->objsize
588 * Padding to reach word boundary. This is also used for Redzoning.
589 * Padding is extended by another word if Redzoning is enabled and
592 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
593 * 0xcc (RED_ACTIVE) for objects in use.
596 * Meta data starts here.
598 * A. Free pointer (if we cannot overwrite object on free)
599 * B. Tracking data for SLAB_STORE_USER
600 * C. Padding to reach required alignment boundary or at mininum
601 * one word if debuggin is on to be able to detect writes
602 * before the word boundary.
604 * Padding is done using 0x5a (POISON_INUSE)
607 * Nothing is used beyond s->size.
609 * If slabcaches are merged then the objsize and inuse boundaries are mostly
610 * ignored. And therefore no slab options that rely on these boundaries
611 * may be used with merged slabcaches.
614 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
616 unsigned long off = s->inuse; /* The end of info */
619 /* Freepointer is placed after the object. */
620 off += sizeof(void *);
622 if (s->flags & SLAB_STORE_USER)
623 /* We also have user information there */
624 off += 2 * sizeof(struct track);
629 return check_bytes_and_report(s, page, p, "Object padding",
630 p + off, POISON_INUSE, s->size - off);
633 static int slab_pad_check(struct kmem_cache *s, struct page *page)
641 if (!(s->flags & SLAB_POISON))
644 start = page_address(page);
645 end = start + (PAGE_SIZE << s->order);
646 length = s->objects * s->size;
647 remainder = end - (start + length);
651 fault = check_bytes(start + length, POISON_INUSE, remainder);
654 while (end > fault && end[-1] == POISON_INUSE)
657 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
658 print_section("Padding", start, length);
660 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
664 static int check_object(struct kmem_cache *s, struct page *page,
665 void *object, int active)
668 u8 *endobject = object + s->objsize;
670 if (s->flags & SLAB_RED_ZONE) {
672 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
674 if (!check_bytes_and_report(s, page, object, "Redzone",
675 endobject, red, s->inuse - s->objsize))
678 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
679 check_bytes_and_report(s, page, p, "Alignment padding", endobject,
680 POISON_INUSE, s->inuse - s->objsize);
683 if (s->flags & SLAB_POISON) {
684 if (!active && (s->flags & __OBJECT_POISON) &&
685 (!check_bytes_and_report(s, page, p, "Poison", p,
686 POISON_FREE, s->objsize - 1) ||
687 !check_bytes_and_report(s, page, p, "Poison",
688 p + s->objsize -1, POISON_END, 1)))
691 * check_pad_bytes cleans up on its own.
693 check_pad_bytes(s, page, p);
696 if (!s->offset && active)
698 * Object and freepointer overlap. Cannot check
699 * freepointer while object is allocated.
703 /* Check free pointer validity */
704 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
705 object_err(s, page, p, "Freepointer corrupt");
707 * No choice but to zap it and thus loose the remainder
708 * of the free objects in this slab. May cause
709 * another error because the object count is now wrong.
711 set_freepointer(s, p, NULL);
717 static int check_slab(struct kmem_cache *s, struct page *page)
719 VM_BUG_ON(!irqs_disabled());
721 if (!PageSlab(page)) {
722 slab_err(s, page, "Not a valid slab page");
725 if (page->offset * sizeof(void *) != s->offset) {
726 slab_err(s, page, "Corrupted offset %lu",
727 (unsigned long)(page->offset * sizeof(void *)));
730 if (page->inuse > s->objects) {
731 slab_err(s, page, "inuse %u > max %u",
732 s->name, page->inuse, s->objects);
735 /* Slab_pad_check fixes things up after itself */
736 slab_pad_check(s, page);
741 * Determine if a certain object on a page is on the freelist. Must hold the
742 * slab lock to guarantee that the chains are in a consistent state.
744 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
747 void *fp = page->freelist;
750 while (fp && nr <= s->objects) {
753 if (!check_valid_pointer(s, page, fp)) {
755 object_err(s, page, object,
756 "Freechain corrupt");
757 set_freepointer(s, object, NULL);
760 slab_err(s, page, "Freepointer corrupt");
761 page->freelist = NULL;
762 page->inuse = s->objects;
763 slab_fix(s, "Freelist cleared");
769 fp = get_freepointer(s, object);
773 if (page->inuse != s->objects - nr) {
774 slab_err(s, page, "Wrong object count. Counter is %d but "
775 "counted were %d", page->inuse, s->objects - nr);
776 page->inuse = s->objects - nr;
777 slab_fix(s, "Object count adjusted.");
779 return search == NULL;
782 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
784 if (s->flags & SLAB_TRACE) {
785 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
787 alloc ? "alloc" : "free",
792 print_section("Object", (void *)object, s->objsize);
799 * Tracking of fully allocated slabs for debugging purposes.
801 static void add_full(struct kmem_cache_node *n, struct page *page)
803 spin_lock(&n->list_lock);
804 list_add(&page->lru, &n->full);
805 spin_unlock(&n->list_lock);
808 static void remove_full(struct kmem_cache *s, struct page *page)
810 struct kmem_cache_node *n;
812 if (!(s->flags & SLAB_STORE_USER))
815 n = get_node(s, page_to_nid(page));
817 spin_lock(&n->list_lock);
818 list_del(&page->lru);
819 spin_unlock(&n->list_lock);
822 static void setup_object_debug(struct kmem_cache *s, struct page *page,
825 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
828 init_object(s, object, 0);
829 init_tracking(s, object);
832 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
833 void *object, void *addr)
835 if (!check_slab(s, page))
838 if (object && !on_freelist(s, page, object)) {
839 object_err(s, page, object, "Object already allocated");
843 if (!check_valid_pointer(s, page, object)) {
844 object_err(s, page, object, "Freelist Pointer check fails");
848 if (object && !check_object(s, page, object, 0))
851 /* Success perform special debug activities for allocs */
852 if (s->flags & SLAB_STORE_USER)
853 set_track(s, object, TRACK_ALLOC, addr);
854 trace(s, page, object, 1);
855 init_object(s, object, 1);
859 if (PageSlab(page)) {
861 * If this is a slab page then lets do the best we can
862 * to avoid issues in the future. Marking all objects
863 * as used avoids touching the remaining objects.
865 slab_fix(s, "Marking all objects used");
866 page->inuse = s->objects;
867 page->freelist = NULL;
868 /* Fix up fields that may be corrupted */
869 page->offset = s->offset / sizeof(void *);
874 static int free_debug_processing(struct kmem_cache *s, struct page *page,
875 void *object, void *addr)
877 if (!check_slab(s, page))
880 if (!check_valid_pointer(s, page, object)) {
881 slab_err(s, page, "Invalid object pointer 0x%p", object);
885 if (on_freelist(s, page, object)) {
886 object_err(s, page, object, "Object already free");
890 if (!check_object(s, page, object, 1))
893 if (unlikely(s != page->slab)) {
895 slab_err(s, page, "Attempt to free object(0x%p) "
896 "outside of slab", object);
900 "SLUB <none>: no slab for object 0x%p.\n",
905 object_err(s, page, object,
906 "page slab pointer corrupt.");
910 /* Special debug activities for freeing objects */
911 if (!SlabFrozen(page) && !page->freelist)
912 remove_full(s, page);
913 if (s->flags & SLAB_STORE_USER)
914 set_track(s, object, TRACK_FREE, addr);
915 trace(s, page, object, 0);
916 init_object(s, object, 0);
920 slab_fix(s, "Object at 0x%p not freed", object);
924 static int __init setup_slub_debug(char *str)
926 slub_debug = DEBUG_DEFAULT_FLAGS;
927 if (*str++ != '=' || !*str)
929 * No options specified. Switch on full debugging.
935 * No options but restriction on slabs. This means full
936 * debugging for slabs matching a pattern.
943 * Switch off all debugging measures.
948 * Determine which debug features should be switched on
950 for ( ;*str && *str != ','; str++) {
951 switch (tolower(*str)) {
953 slub_debug |= SLAB_DEBUG_FREE;
956 slub_debug |= SLAB_RED_ZONE;
959 slub_debug |= SLAB_POISON;
962 slub_debug |= SLAB_STORE_USER;
965 slub_debug |= SLAB_TRACE;
968 printk(KERN_ERR "slub_debug option '%c' "
969 "unknown. skipped\n",*str);
975 slub_debug_slabs = str + 1;
980 __setup("slub_debug", setup_slub_debug);
982 static void kmem_cache_open_debug_check(struct kmem_cache *s)
985 * The page->offset field is only 16 bit wide. This is an offset
986 * in units of words from the beginning of an object. If the slab
987 * size is bigger then we cannot move the free pointer behind the
990 * On 32 bit platforms the limit is 256k. On 64bit platforms
993 * Debugging or ctor may create a need to move the free
994 * pointer. Fail if this happens.
996 if (s->objsize >= 65535 * sizeof(void *)) {
997 BUG_ON(s->flags & (SLAB_RED_ZONE | SLAB_POISON |
998 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
1003 * Enable debugging if selected on the kernel commandline.
1005 if (slub_debug && (!slub_debug_slabs ||
1006 strncmp(slub_debug_slabs, s->name,
1007 strlen(slub_debug_slabs)) == 0))
1008 s->flags |= slub_debug;
1011 static inline void setup_object_debug(struct kmem_cache *s,
1012 struct page *page, void *object) {}
1014 static inline int alloc_debug_processing(struct kmem_cache *s,
1015 struct page *page, void *object, void *addr) { return 0; }
1017 static inline int free_debug_processing(struct kmem_cache *s,
1018 struct page *page, void *object, void *addr) { return 0; }
1020 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1022 static inline int check_object(struct kmem_cache *s, struct page *page,
1023 void *object, int active) { return 1; }
1024 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1025 static inline void kmem_cache_open_debug_check(struct kmem_cache *s) {}
1026 #define slub_debug 0
1029 * Slab allocation and freeing
1031 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1034 int pages = 1 << s->order;
1037 flags |= __GFP_COMP;
1039 if (s->flags & SLAB_CACHE_DMA)
1043 page = alloc_pages(flags, s->order);
1045 page = alloc_pages_node(node, flags, s->order);
1050 mod_zone_page_state(page_zone(page),
1051 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1052 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1058 static void setup_object(struct kmem_cache *s, struct page *page,
1061 setup_object_debug(s, page, object);
1062 if (unlikely(s->ctor))
1063 s->ctor(object, s, 0);
1066 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1069 struct kmem_cache_node *n;
1075 BUG_ON(flags & ~(GFP_DMA | GFP_LEVEL_MASK));
1077 if (flags & __GFP_WAIT)
1080 page = allocate_slab(s, flags & GFP_LEVEL_MASK, node);
1084 n = get_node(s, page_to_nid(page));
1086 atomic_long_inc(&n->nr_slabs);
1087 page->offset = s->offset / sizeof(void *);
1089 page->flags |= 1 << PG_slab;
1090 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1091 SLAB_STORE_USER | SLAB_TRACE))
1094 start = page_address(page);
1095 end = start + s->objects * s->size;
1097 if (unlikely(s->flags & SLAB_POISON))
1098 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1101 for_each_object(p, s, start) {
1102 setup_object(s, page, last);
1103 set_freepointer(s, last, p);
1106 setup_object(s, page, last);
1107 set_freepointer(s, last, NULL);
1109 page->freelist = start;
1110 page->lockless_freelist = NULL;
1113 if (flags & __GFP_WAIT)
1114 local_irq_disable();
1118 static void __free_slab(struct kmem_cache *s, struct page *page)
1120 int pages = 1 << s->order;
1122 if (unlikely(SlabDebug(page))) {
1125 slab_pad_check(s, page);
1126 for_each_object(p, s, page_address(page))
1127 check_object(s, page, p, 0);
1130 mod_zone_page_state(page_zone(page),
1131 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1132 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1135 page->mapping = NULL;
1136 __free_pages(page, s->order);
1139 static void rcu_free_slab(struct rcu_head *h)
1143 page = container_of((struct list_head *)h, struct page, lru);
1144 __free_slab(page->slab, page);
1147 static void free_slab(struct kmem_cache *s, struct page *page)
1149 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1151 * RCU free overloads the RCU head over the LRU
1153 struct rcu_head *head = (void *)&page->lru;
1155 call_rcu(head, rcu_free_slab);
1157 __free_slab(s, page);
1160 static void discard_slab(struct kmem_cache *s, struct page *page)
1162 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1164 atomic_long_dec(&n->nr_slabs);
1165 reset_page_mapcount(page);
1166 ClearSlabDebug(page);
1167 __ClearPageSlab(page);
1172 * Per slab locking using the pagelock
1174 static __always_inline void slab_lock(struct page *page)
1176 bit_spin_lock(PG_locked, &page->flags);
1179 static __always_inline void slab_unlock(struct page *page)
1181 bit_spin_unlock(PG_locked, &page->flags);
1184 static __always_inline int slab_trylock(struct page *page)
1188 rc = bit_spin_trylock(PG_locked, &page->flags);
1193 * Management of partially allocated slabs
1195 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1197 spin_lock(&n->list_lock);
1199 list_add_tail(&page->lru, &n->partial);
1200 spin_unlock(&n->list_lock);
1203 static void add_partial(struct kmem_cache_node *n, struct page *page)
1205 spin_lock(&n->list_lock);
1207 list_add(&page->lru, &n->partial);
1208 spin_unlock(&n->list_lock);
1211 static void remove_partial(struct kmem_cache *s,
1214 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1216 spin_lock(&n->list_lock);
1217 list_del(&page->lru);
1219 spin_unlock(&n->list_lock);
1223 * Lock slab and remove from the partial list.
1225 * Must hold list_lock.
1227 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1229 if (slab_trylock(page)) {
1230 list_del(&page->lru);
1232 SetSlabFrozen(page);
1239 * Try to allocate a partial slab from a specific node.
1241 static struct page *get_partial_node(struct kmem_cache_node *n)
1246 * Racy check. If we mistakenly see no partial slabs then we
1247 * just allocate an empty slab. If we mistakenly try to get a
1248 * partial slab and there is none available then get_partials()
1251 if (!n || !n->nr_partial)
1254 spin_lock(&n->list_lock);
1255 list_for_each_entry(page, &n->partial, lru)
1256 if (lock_and_freeze_slab(n, page))
1260 spin_unlock(&n->list_lock);
1265 * Get a page from somewhere. Search in increasing NUMA distances.
1267 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1270 struct zonelist *zonelist;
1275 * The defrag ratio allows a configuration of the tradeoffs between
1276 * inter node defragmentation and node local allocations. A lower
1277 * defrag_ratio increases the tendency to do local allocations
1278 * instead of attempting to obtain partial slabs from other nodes.
1280 * If the defrag_ratio is set to 0 then kmalloc() always
1281 * returns node local objects. If the ratio is higher then kmalloc()
1282 * may return off node objects because partial slabs are obtained
1283 * from other nodes and filled up.
1285 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1286 * defrag_ratio = 1000) then every (well almost) allocation will
1287 * first attempt to defrag slab caches on other nodes. This means
1288 * scanning over all nodes to look for partial slabs which may be
1289 * expensive if we do it every time we are trying to find a slab
1290 * with available objects.
1292 if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1295 zonelist = &NODE_DATA(slab_node(current->mempolicy))
1296 ->node_zonelists[gfp_zone(flags)];
1297 for (z = zonelist->zones; *z; z++) {
1298 struct kmem_cache_node *n;
1300 n = get_node(s, zone_to_nid(*z));
1302 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1303 n->nr_partial > MIN_PARTIAL) {
1304 page = get_partial_node(n);
1314 * Get a partial page, lock it and return it.
1316 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1319 int searchnode = (node == -1) ? numa_node_id() : node;
1321 page = get_partial_node(get_node(s, searchnode));
1322 if (page || (flags & __GFP_THISNODE))
1325 return get_any_partial(s, flags);
1329 * Move a page back to the lists.
1331 * Must be called with the slab lock held.
1333 * On exit the slab lock will have been dropped.
1335 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1337 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1339 ClearSlabFrozen(page);
1343 add_partial(n, page);
1344 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1349 if (n->nr_partial < MIN_PARTIAL) {
1351 * Adding an empty slab to the partial slabs in order
1352 * to avoid page allocator overhead. This slab needs
1353 * to come after the other slabs with objects in
1354 * order to fill them up. That way the size of the
1355 * partial list stays small. kmem_cache_shrink can
1356 * reclaim empty slabs from the partial list.
1358 add_partial_tail(n, page);
1362 discard_slab(s, page);
1368 * Remove the cpu slab
1370 static void deactivate_slab(struct kmem_cache *s, struct page *page, int cpu)
1373 * Merge cpu freelist into freelist. Typically we get here
1374 * because both freelists are empty. So this is unlikely
1377 while (unlikely(page->lockless_freelist)) {
1380 /* Retrieve object from cpu_freelist */
1381 object = page->lockless_freelist;
1382 page->lockless_freelist = page->lockless_freelist[page->offset];
1384 /* And put onto the regular freelist */
1385 object[page->offset] = page->freelist;
1386 page->freelist = object;
1389 s->cpu_slab[cpu] = NULL;
1390 unfreeze_slab(s, page);
1393 static void flush_slab(struct kmem_cache *s, struct page *page, int cpu)
1396 deactivate_slab(s, page, cpu);
1401 * Called from IPI handler with interrupts disabled.
1403 static void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1405 struct page *page = s->cpu_slab[cpu];
1408 flush_slab(s, page, cpu);
1411 static void flush_cpu_slab(void *d)
1413 struct kmem_cache *s = d;
1414 int cpu = smp_processor_id();
1416 __flush_cpu_slab(s, cpu);
1419 static void flush_all(struct kmem_cache *s)
1422 on_each_cpu(flush_cpu_slab, s, 1, 1);
1424 unsigned long flags;
1426 local_irq_save(flags);
1428 local_irq_restore(flags);
1433 * Slow path. The lockless freelist is empty or we need to perform
1436 * Interrupts are disabled.
1438 * Processing is still very fast if new objects have been freed to the
1439 * regular freelist. In that case we simply take over the regular freelist
1440 * as the lockless freelist and zap the regular freelist.
1442 * If that is not working then we fall back to the partial lists. We take the
1443 * first element of the freelist as the object to allocate now and move the
1444 * rest of the freelist to the lockless freelist.
1446 * And if we were unable to get a new slab from the partial slab lists then
1447 * we need to allocate a new slab. This is slowest path since we may sleep.
1449 static void *__slab_alloc(struct kmem_cache *s,
1450 gfp_t gfpflags, int node, void *addr, struct page *page)
1453 int cpu = smp_processor_id();
1459 if (unlikely(node != -1 && page_to_nid(page) != node))
1462 object = page->freelist;
1463 if (unlikely(!object))
1465 if (unlikely(SlabDebug(page)))
1468 object = page->freelist;
1469 page->lockless_freelist = object[page->offset];
1470 page->inuse = s->objects;
1471 page->freelist = NULL;
1476 deactivate_slab(s, page, cpu);
1479 page = get_partial(s, gfpflags, node);
1481 s->cpu_slab[cpu] = page;
1485 page = new_slab(s, gfpflags, node);
1487 cpu = smp_processor_id();
1488 if (s->cpu_slab[cpu]) {
1490 * Someone else populated the cpu_slab while we
1491 * enabled interrupts, or we have gotten scheduled
1492 * on another cpu. The page may not be on the
1493 * requested node even if __GFP_THISNODE was
1494 * specified. So we need to recheck.
1497 page_to_nid(s->cpu_slab[cpu]) == node) {
1499 * Current cpuslab is acceptable and we
1500 * want the current one since its cache hot
1502 discard_slab(s, page);
1503 page = s->cpu_slab[cpu];
1507 /* New slab does not fit our expectations */
1508 flush_slab(s, s->cpu_slab[cpu], cpu);
1511 SetSlabFrozen(page);
1512 s->cpu_slab[cpu] = page;
1517 object = page->freelist;
1518 if (!alloc_debug_processing(s, page, object, addr))
1522 page->freelist = object[page->offset];
1528 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1529 * have the fastpath folded into their functions. So no function call
1530 * overhead for requests that can be satisfied on the fastpath.
1532 * The fastpath works by first checking if the lockless freelist can be used.
1533 * If not then __slab_alloc is called for slow processing.
1535 * Otherwise we can simply pick the next object from the lockless free list.
1537 static void __always_inline *slab_alloc(struct kmem_cache *s,
1538 gfp_t gfpflags, int node, void *addr)
1542 unsigned long flags;
1544 local_irq_save(flags);
1545 page = s->cpu_slab[smp_processor_id()];
1546 if (unlikely(!page || !page->lockless_freelist ||
1547 (node != -1 && page_to_nid(page) != node)))
1549 object = __slab_alloc(s, gfpflags, node, addr, page);
1552 object = page->lockless_freelist;
1553 page->lockless_freelist = object[page->offset];
1555 local_irq_restore(flags);
1559 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1561 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1563 EXPORT_SYMBOL(kmem_cache_alloc);
1566 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1568 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1570 EXPORT_SYMBOL(kmem_cache_alloc_node);
1574 * Slow patch handling. This may still be called frequently since objects
1575 * have a longer lifetime than the cpu slabs in most processing loads.
1577 * So we still attempt to reduce cache line usage. Just take the slab
1578 * lock and free the item. If there is no additional partial page
1579 * handling required then we can return immediately.
1581 static void __slab_free(struct kmem_cache *s, struct page *page,
1582 void *x, void *addr)
1585 void **object = (void *)x;
1589 if (unlikely(SlabDebug(page)))
1592 prior = object[page->offset] = page->freelist;
1593 page->freelist = object;
1596 if (unlikely(SlabFrozen(page)))
1599 if (unlikely(!page->inuse))
1603 * Objects left in the slab. If it
1604 * was not on the partial list before
1607 if (unlikely(!prior))
1608 add_partial(get_node(s, page_to_nid(page)), page);
1617 * Slab still on the partial list.
1619 remove_partial(s, page);
1622 discard_slab(s, page);
1626 if (!free_debug_processing(s, page, x, addr))
1632 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1633 * can perform fastpath freeing without additional function calls.
1635 * The fastpath is only possible if we are freeing to the current cpu slab
1636 * of this processor. This typically the case if we have just allocated
1639 * If fastpath is not possible then fall back to __slab_free where we deal
1640 * with all sorts of special processing.
1642 static void __always_inline slab_free(struct kmem_cache *s,
1643 struct page *page, void *x, void *addr)
1645 void **object = (void *)x;
1646 unsigned long flags;
1648 local_irq_save(flags);
1649 if (likely(page == s->cpu_slab[smp_processor_id()] &&
1650 !SlabDebug(page))) {
1651 object[page->offset] = page->lockless_freelist;
1652 page->lockless_freelist = object;
1654 __slab_free(s, page, x, addr);
1656 local_irq_restore(flags);
1659 void kmem_cache_free(struct kmem_cache *s, void *x)
1663 page = virt_to_head_page(x);
1665 slab_free(s, page, x, __builtin_return_address(0));
1667 EXPORT_SYMBOL(kmem_cache_free);
1669 /* Figure out on which slab object the object resides */
1670 static struct page *get_object_page(const void *x)
1672 struct page *page = virt_to_head_page(x);
1674 if (!PageSlab(page))
1681 * Object placement in a slab is made very easy because we always start at
1682 * offset 0. If we tune the size of the object to the alignment then we can
1683 * get the required alignment by putting one properly sized object after
1686 * Notice that the allocation order determines the sizes of the per cpu
1687 * caches. Each processor has always one slab available for allocations.
1688 * Increasing the allocation order reduces the number of times that slabs
1689 * must be moved on and off the partial lists and is therefore a factor in
1694 * Mininum / Maximum order of slab pages. This influences locking overhead
1695 * and slab fragmentation. A higher order reduces the number of partial slabs
1696 * and increases the number of allocations possible without having to
1697 * take the list_lock.
1699 static int slub_min_order;
1700 static int slub_max_order = DEFAULT_MAX_ORDER;
1701 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1704 * Merge control. If this is set then no merging of slab caches will occur.
1705 * (Could be removed. This was introduced to pacify the merge skeptics.)
1707 static int slub_nomerge;
1710 * Calculate the order of allocation given an slab object size.
1712 * The order of allocation has significant impact on performance and other
1713 * system components. Generally order 0 allocations should be preferred since
1714 * order 0 does not cause fragmentation in the page allocator. Larger objects
1715 * be problematic to put into order 0 slabs because there may be too much
1716 * unused space left. We go to a higher order if more than 1/8th of the slab
1719 * In order to reach satisfactory performance we must ensure that a minimum
1720 * number of objects is in one slab. Otherwise we may generate too much
1721 * activity on the partial lists which requires taking the list_lock. This is
1722 * less a concern for large slabs though which are rarely used.
1724 * slub_max_order specifies the order where we begin to stop considering the
1725 * number of objects in a slab as critical. If we reach slub_max_order then
1726 * we try to keep the page order as low as possible. So we accept more waste
1727 * of space in favor of a small page order.
1729 * Higher order allocations also allow the placement of more objects in a
1730 * slab and thereby reduce object handling overhead. If the user has
1731 * requested a higher mininum order then we start with that one instead of
1732 * the smallest order which will fit the object.
1734 static inline int slab_order(int size, int min_objects,
1735 int max_order, int fract_leftover)
1740 for (order = max(slub_min_order,
1741 fls(min_objects * size - 1) - PAGE_SHIFT);
1742 order <= max_order; order++) {
1744 unsigned long slab_size = PAGE_SIZE << order;
1746 if (slab_size < min_objects * size)
1749 rem = slab_size % size;
1751 if (rem <= slab_size / fract_leftover)
1759 static inline int calculate_order(int size)
1766 * Attempt to find best configuration for a slab. This
1767 * works by first attempting to generate a layout with
1768 * the best configuration and backing off gradually.
1770 * First we reduce the acceptable waste in a slab. Then
1771 * we reduce the minimum objects required in a slab.
1773 min_objects = slub_min_objects;
1774 while (min_objects > 1) {
1776 while (fraction >= 4) {
1777 order = slab_order(size, min_objects,
1778 slub_max_order, fraction);
1779 if (order <= slub_max_order)
1787 * We were unable to place multiple objects in a slab. Now
1788 * lets see if we can place a single object there.
1790 order = slab_order(size, 1, slub_max_order, 1);
1791 if (order <= slub_max_order)
1795 * Doh this slab cannot be placed using slub_max_order.
1797 order = slab_order(size, 1, MAX_ORDER, 1);
1798 if (order <= MAX_ORDER)
1804 * Figure out what the alignment of the objects will be.
1806 static unsigned long calculate_alignment(unsigned long flags,
1807 unsigned long align, unsigned long size)
1810 * If the user wants hardware cache aligned objects then
1811 * follow that suggestion if the object is sufficiently
1814 * The hardware cache alignment cannot override the
1815 * specified alignment though. If that is greater
1818 if ((flags & SLAB_HWCACHE_ALIGN) &&
1819 size > cache_line_size() / 2)
1820 return max_t(unsigned long, align, cache_line_size());
1822 if (align < ARCH_SLAB_MINALIGN)
1823 return ARCH_SLAB_MINALIGN;
1825 return ALIGN(align, sizeof(void *));
1828 static void init_kmem_cache_node(struct kmem_cache_node *n)
1831 atomic_long_set(&n->nr_slabs, 0);
1832 spin_lock_init(&n->list_lock);
1833 INIT_LIST_HEAD(&n->partial);
1834 INIT_LIST_HEAD(&n->full);
1839 * No kmalloc_node yet so do it by hand. We know that this is the first
1840 * slab on the node for this slabcache. There are no concurrent accesses
1843 * Note that this function only works on the kmalloc_node_cache
1844 * when allocating for the kmalloc_node_cache.
1846 static struct kmem_cache_node * __init early_kmem_cache_node_alloc(gfp_t gfpflags,
1850 struct kmem_cache_node *n;
1852 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
1854 page = new_slab(kmalloc_caches, gfpflags | GFP_THISNODE, node);
1859 page->freelist = get_freepointer(kmalloc_caches, n);
1861 kmalloc_caches->node[node] = n;
1862 setup_object_debug(kmalloc_caches, page, n);
1863 init_kmem_cache_node(n);
1864 atomic_long_inc(&n->nr_slabs);
1865 add_partial(n, page);
1868 * new_slab() disables interupts. If we do not reenable interrupts here
1869 * then bootup would continue with interrupts disabled.
1875 static void free_kmem_cache_nodes(struct kmem_cache *s)
1879 for_each_online_node(node) {
1880 struct kmem_cache_node *n = s->node[node];
1881 if (n && n != &s->local_node)
1882 kmem_cache_free(kmalloc_caches, n);
1883 s->node[node] = NULL;
1887 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1892 if (slab_state >= UP)
1893 local_node = page_to_nid(virt_to_page(s));
1897 for_each_online_node(node) {
1898 struct kmem_cache_node *n;
1900 if (local_node == node)
1903 if (slab_state == DOWN) {
1904 n = early_kmem_cache_node_alloc(gfpflags,
1908 n = kmem_cache_alloc_node(kmalloc_caches,
1912 free_kmem_cache_nodes(s);
1918 init_kmem_cache_node(n);
1923 static void free_kmem_cache_nodes(struct kmem_cache *s)
1927 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1929 init_kmem_cache_node(&s->local_node);
1935 * calculate_sizes() determines the order and the distribution of data within
1938 static int calculate_sizes(struct kmem_cache *s)
1940 unsigned long flags = s->flags;
1941 unsigned long size = s->objsize;
1942 unsigned long align = s->align;
1945 * Determine if we can poison the object itself. If the user of
1946 * the slab may touch the object after free or before allocation
1947 * then we should never poison the object itself.
1949 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
1951 s->flags |= __OBJECT_POISON;
1953 s->flags &= ~__OBJECT_POISON;
1956 * Round up object size to the next word boundary. We can only
1957 * place the free pointer at word boundaries and this determines
1958 * the possible location of the free pointer.
1960 size = ALIGN(size, sizeof(void *));
1962 #ifdef CONFIG_SLUB_DEBUG
1964 * If we are Redzoning then check if there is some space between the
1965 * end of the object and the free pointer. If not then add an
1966 * additional word to have some bytes to store Redzone information.
1968 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
1969 size += sizeof(void *);
1973 * With that we have determined the number of bytes in actual use
1974 * by the object. This is the potential offset to the free pointer.
1978 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
1981 * Relocate free pointer after the object if it is not
1982 * permitted to overwrite the first word of the object on
1985 * This is the case if we do RCU, have a constructor or
1986 * destructor or are poisoning the objects.
1989 size += sizeof(void *);
1992 #ifdef CONFIG_SLUB_DEBUG
1993 if (flags & SLAB_STORE_USER)
1995 * Need to store information about allocs and frees after
1998 size += 2 * sizeof(struct track);
2000 if (flags & SLAB_RED_ZONE)
2002 * Add some empty padding so that we can catch
2003 * overwrites from earlier objects rather than let
2004 * tracking information or the free pointer be
2005 * corrupted if an user writes before the start
2008 size += sizeof(void *);
2012 * Determine the alignment based on various parameters that the
2013 * user specified and the dynamic determination of cache line size
2016 align = calculate_alignment(flags, align, s->objsize);
2019 * SLUB stores one object immediately after another beginning from
2020 * offset 0. In order to align the objects we have to simply size
2021 * each object to conform to the alignment.
2023 size = ALIGN(size, align);
2026 s->order = calculate_order(size);
2031 * Determine the number of objects per slab
2033 s->objects = (PAGE_SIZE << s->order) / size;
2036 * Verify that the number of objects is within permitted limits.
2037 * The page->inuse field is only 16 bit wide! So we cannot have
2038 * more than 64k objects per slab.
2040 if (!s->objects || s->objects > 65535)
2046 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2047 const char *name, size_t size,
2048 size_t align, unsigned long flags,
2049 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2051 memset(s, 0, kmem_size);
2057 kmem_cache_open_debug_check(s);
2059 if (!calculate_sizes(s))
2064 s->defrag_ratio = 100;
2067 if (init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2070 if (flags & SLAB_PANIC)
2071 panic("Cannot create slab %s size=%lu realsize=%u "
2072 "order=%u offset=%u flags=%lx\n",
2073 s->name, (unsigned long)size, s->size, s->order,
2079 * Check if a given pointer is valid
2081 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2085 page = get_object_page(object);
2087 if (!page || s != page->slab)
2088 /* No slab or wrong slab */
2091 if (!check_valid_pointer(s, page, object))
2095 * We could also check if the object is on the slabs freelist.
2096 * But this would be too expensive and it seems that the main
2097 * purpose of kmem_ptr_valid is to check if the object belongs
2098 * to a certain slab.
2102 EXPORT_SYMBOL(kmem_ptr_validate);
2105 * Determine the size of a slab object
2107 unsigned int kmem_cache_size(struct kmem_cache *s)
2111 EXPORT_SYMBOL(kmem_cache_size);
2113 const char *kmem_cache_name(struct kmem_cache *s)
2117 EXPORT_SYMBOL(kmem_cache_name);
2120 * Attempt to free all slabs on a node. Return the number of slabs we
2121 * were unable to free.
2123 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2124 struct list_head *list)
2126 int slabs_inuse = 0;
2127 unsigned long flags;
2128 struct page *page, *h;
2130 spin_lock_irqsave(&n->list_lock, flags);
2131 list_for_each_entry_safe(page, h, list, lru)
2133 list_del(&page->lru);
2134 discard_slab(s, page);
2137 spin_unlock_irqrestore(&n->list_lock, flags);
2142 * Release all resources used by a slab cache.
2144 static int kmem_cache_close(struct kmem_cache *s)
2150 /* Attempt to free all objects */
2151 for_each_online_node(node) {
2152 struct kmem_cache_node *n = get_node(s, node);
2154 n->nr_partial -= free_list(s, n, &n->partial);
2155 if (atomic_long_read(&n->nr_slabs))
2158 free_kmem_cache_nodes(s);
2163 * Close a cache and release the kmem_cache structure
2164 * (must be used for caches created using kmem_cache_create)
2166 void kmem_cache_destroy(struct kmem_cache *s)
2168 down_write(&slub_lock);
2172 if (kmem_cache_close(s))
2174 sysfs_slab_remove(s);
2177 up_write(&slub_lock);
2179 EXPORT_SYMBOL(kmem_cache_destroy);
2181 /********************************************************************
2183 *******************************************************************/
2185 struct kmem_cache kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __cacheline_aligned;
2186 EXPORT_SYMBOL(kmalloc_caches);
2188 #ifdef CONFIG_ZONE_DMA
2189 static struct kmem_cache *kmalloc_caches_dma[KMALLOC_SHIFT_HIGH + 1];
2192 static int __init setup_slub_min_order(char *str)
2194 get_option (&str, &slub_min_order);
2199 __setup("slub_min_order=", setup_slub_min_order);
2201 static int __init setup_slub_max_order(char *str)
2203 get_option (&str, &slub_max_order);
2208 __setup("slub_max_order=", setup_slub_max_order);
2210 static int __init setup_slub_min_objects(char *str)
2212 get_option (&str, &slub_min_objects);
2217 __setup("slub_min_objects=", setup_slub_min_objects);
2219 static int __init setup_slub_nomerge(char *str)
2225 __setup("slub_nomerge", setup_slub_nomerge);
2227 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2228 const char *name, int size, gfp_t gfp_flags)
2230 unsigned int flags = 0;
2232 if (gfp_flags & SLUB_DMA)
2233 flags = SLAB_CACHE_DMA;
2235 down_write(&slub_lock);
2236 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2240 list_add(&s->list, &slab_caches);
2241 up_write(&slub_lock);
2242 if (sysfs_slab_add(s))
2247 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2250 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2252 int index = kmalloc_index(size);
2257 /* Allocation too large? */
2260 #ifdef CONFIG_ZONE_DMA
2261 if ((flags & SLUB_DMA)) {
2262 struct kmem_cache *s;
2263 struct kmem_cache *x;
2267 s = kmalloc_caches_dma[index];
2271 /* Dynamically create dma cache */
2272 x = kmalloc(kmem_size, flags & ~SLUB_DMA);
2274 panic("Unable to allocate memory for dma cache\n");
2276 if (index <= KMALLOC_SHIFT_HIGH)
2277 realsize = 1 << index;
2285 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2286 (unsigned int)realsize);
2287 s = create_kmalloc_cache(x, text, realsize, flags);
2288 kmalloc_caches_dma[index] = s;
2292 return &kmalloc_caches[index];
2295 void *__kmalloc(size_t size, gfp_t flags)
2297 struct kmem_cache *s = get_slab(size, flags);
2300 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2301 return ZERO_SIZE_PTR;
2303 EXPORT_SYMBOL(__kmalloc);
2306 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2308 struct kmem_cache *s = get_slab(size, flags);
2311 return slab_alloc(s, flags, node, __builtin_return_address(0));
2312 return ZERO_SIZE_PTR;
2314 EXPORT_SYMBOL(__kmalloc_node);
2317 size_t ksize(const void *object)
2320 struct kmem_cache *s;
2322 if (object == ZERO_SIZE_PTR)
2325 page = get_object_page(object);
2331 * Debugging requires use of the padding between object
2332 * and whatever may come after it.
2334 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2338 * If we have the need to store the freelist pointer
2339 * back there or track user information then we can
2340 * only use the space before that information.
2342 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2346 * Else we can use all the padding etc for the allocation
2350 EXPORT_SYMBOL(ksize);
2352 void kfree(const void *x)
2354 struct kmem_cache *s;
2358 * This has to be an unsigned comparison. According to Linus
2359 * some gcc version treat a pointer as a signed entity. Then
2360 * this comparison would be true for all "negative" pointers
2361 * (which would cover the whole upper half of the address space).
2363 if ((unsigned long)x <= (unsigned long)ZERO_SIZE_PTR)
2366 page = virt_to_head_page(x);
2369 slab_free(s, page, (void *)x, __builtin_return_address(0));
2371 EXPORT_SYMBOL(kfree);
2374 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2375 * the remaining slabs by the number of items in use. The slabs with the
2376 * most items in use come first. New allocations will then fill those up
2377 * and thus they can be removed from the partial lists.
2379 * The slabs with the least items are placed last. This results in them
2380 * being allocated from last increasing the chance that the last objects
2381 * are freed in them.
2383 int kmem_cache_shrink(struct kmem_cache *s)
2387 struct kmem_cache_node *n;
2390 struct list_head *slabs_by_inuse =
2391 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2392 unsigned long flags;
2394 if (!slabs_by_inuse)
2398 for_each_online_node(node) {
2399 n = get_node(s, node);
2404 for (i = 0; i < s->objects; i++)
2405 INIT_LIST_HEAD(slabs_by_inuse + i);
2407 spin_lock_irqsave(&n->list_lock, flags);
2410 * Build lists indexed by the items in use in each slab.
2412 * Note that concurrent frees may occur while we hold the
2413 * list_lock. page->inuse here is the upper limit.
2415 list_for_each_entry_safe(page, t, &n->partial, lru) {
2416 if (!page->inuse && slab_trylock(page)) {
2418 * Must hold slab lock here because slab_free
2419 * may have freed the last object and be
2420 * waiting to release the slab.
2422 list_del(&page->lru);
2425 discard_slab(s, page);
2427 if (n->nr_partial > MAX_PARTIAL)
2428 list_move(&page->lru,
2429 slabs_by_inuse + page->inuse);
2433 if (n->nr_partial <= MAX_PARTIAL)
2437 * Rebuild the partial list with the slabs filled up most
2438 * first and the least used slabs at the end.
2440 for (i = s->objects - 1; i >= 0; i--)
2441 list_splice(slabs_by_inuse + i, n->partial.prev);
2444 spin_unlock_irqrestore(&n->list_lock, flags);
2447 kfree(slabs_by_inuse);
2450 EXPORT_SYMBOL(kmem_cache_shrink);
2453 * krealloc - reallocate memory. The contents will remain unchanged.
2454 * @p: object to reallocate memory for.
2455 * @new_size: how many bytes of memory are required.
2456 * @flags: the type of memory to allocate.
2458 * The contents of the object pointed to are preserved up to the
2459 * lesser of the new and old sizes. If @p is %NULL, krealloc()
2460 * behaves exactly like kmalloc(). If @size is 0 and @p is not a
2461 * %NULL pointer, the object pointed to is freed.
2463 void *krealloc(const void *p, size_t new_size, gfp_t flags)
2468 if (unlikely(!p || p == ZERO_SIZE_PTR))
2469 return kmalloc(new_size, flags);
2471 if (unlikely(!new_size)) {
2473 return ZERO_SIZE_PTR;
2480 ret = kmalloc(new_size, flags);
2482 memcpy(ret, p, min(new_size, ks));
2487 EXPORT_SYMBOL(krealloc);
2489 /********************************************************************
2490 * Basic setup of slabs
2491 *******************************************************************/
2493 void __init kmem_cache_init(void)
2500 * Must first have the slab cache available for the allocations of the
2501 * struct kmem_cache_node's. There is special bootstrap code in
2502 * kmem_cache_open for slab_state == DOWN.
2504 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2505 sizeof(struct kmem_cache_node), GFP_KERNEL);
2506 kmalloc_caches[0].refcount = -1;
2510 /* Able to allocate the per node structures */
2511 slab_state = PARTIAL;
2513 /* Caches that are not of the two-to-the-power-of size */
2514 if (KMALLOC_MIN_SIZE <= 64) {
2515 create_kmalloc_cache(&kmalloc_caches[1],
2516 "kmalloc-96", 96, GFP_KERNEL);
2519 if (KMALLOC_MIN_SIZE <= 128) {
2520 create_kmalloc_cache(&kmalloc_caches[2],
2521 "kmalloc-192", 192, GFP_KERNEL);
2525 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
2526 create_kmalloc_cache(&kmalloc_caches[i],
2527 "kmalloc", 1 << i, GFP_KERNEL);
2533 /* Provide the correct kmalloc names now that the caches are up */
2534 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++)
2535 kmalloc_caches[i]. name =
2536 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2539 register_cpu_notifier(&slab_notifier);
2542 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2543 nr_cpu_ids * sizeof(struct page *);
2545 printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2546 " CPUs=%d, Nodes=%d\n",
2547 caches, cache_line_size(),
2548 slub_min_order, slub_max_order, slub_min_objects,
2549 nr_cpu_ids, nr_node_ids);
2553 * Find a mergeable slab cache
2555 static int slab_unmergeable(struct kmem_cache *s)
2557 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2564 * We may have set a slab to be unmergeable during bootstrap.
2566 if (s->refcount < 0)
2572 static struct kmem_cache *find_mergeable(size_t size,
2573 size_t align, unsigned long flags,
2574 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2576 struct list_head *h;
2578 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2584 size = ALIGN(size, sizeof(void *));
2585 align = calculate_alignment(flags, align, size);
2586 size = ALIGN(size, align);
2588 list_for_each(h, &slab_caches) {
2589 struct kmem_cache *s =
2590 container_of(h, struct kmem_cache, list);
2592 if (slab_unmergeable(s))
2598 if (((flags | slub_debug) & SLUB_MERGE_SAME) !=
2599 (s->flags & SLUB_MERGE_SAME))
2602 * Check if alignment is compatible.
2603 * Courtesy of Adrian Drzewiecki
2605 if ((s->size & ~(align -1)) != s->size)
2608 if (s->size - size >= sizeof(void *))
2616 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2617 size_t align, unsigned long flags,
2618 void (*ctor)(void *, struct kmem_cache *, unsigned long),
2619 void (*dtor)(void *, struct kmem_cache *, unsigned long))
2621 struct kmem_cache *s;
2624 down_write(&slub_lock);
2625 s = find_mergeable(size, align, flags, ctor);
2629 * Adjust the object sizes so that we clear
2630 * the complete object on kzalloc.
2632 s->objsize = max(s->objsize, (int)size);
2633 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2634 if (sysfs_slab_alias(s, name))
2637 s = kmalloc(kmem_size, GFP_KERNEL);
2638 if (s && kmem_cache_open(s, GFP_KERNEL, name,
2639 size, align, flags, ctor)) {
2640 if (sysfs_slab_add(s)) {
2644 list_add(&s->list, &slab_caches);
2648 up_write(&slub_lock);
2652 up_write(&slub_lock);
2653 if (flags & SLAB_PANIC)
2654 panic("Cannot create slabcache %s\n", name);
2659 EXPORT_SYMBOL(kmem_cache_create);
2661 void *kmem_cache_zalloc(struct kmem_cache *s, gfp_t flags)
2665 x = slab_alloc(s, flags, -1, __builtin_return_address(0));
2667 memset(x, 0, s->objsize);
2670 EXPORT_SYMBOL(kmem_cache_zalloc);
2673 static void for_all_slabs(void (*func)(struct kmem_cache *, int), int cpu)
2675 struct list_head *h;
2677 down_read(&slub_lock);
2678 list_for_each(h, &slab_caches) {
2679 struct kmem_cache *s =
2680 container_of(h, struct kmem_cache, list);
2684 up_read(&slub_lock);
2688 * Version of __flush_cpu_slab for the case that interrupts
2691 static void cpu_slab_flush(struct kmem_cache *s, int cpu)
2693 unsigned long flags;
2695 local_irq_save(flags);
2696 __flush_cpu_slab(s, cpu);
2697 local_irq_restore(flags);
2701 * Use the cpu notifier to insure that the cpu slabs are flushed when
2704 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2705 unsigned long action, void *hcpu)
2707 long cpu = (long)hcpu;
2710 case CPU_UP_CANCELED:
2711 case CPU_UP_CANCELED_FROZEN:
2713 case CPU_DEAD_FROZEN:
2714 for_all_slabs(cpu_slab_flush, cpu);
2722 static struct notifier_block __cpuinitdata slab_notifier =
2723 { &slab_cpuup_callback, NULL, 0 };
2727 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2729 struct kmem_cache *s = get_slab(size, gfpflags);
2732 return ZERO_SIZE_PTR;
2734 return slab_alloc(s, gfpflags, -1, caller);
2737 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2738 int node, void *caller)
2740 struct kmem_cache *s = get_slab(size, gfpflags);
2743 return ZERO_SIZE_PTR;
2745 return slab_alloc(s, gfpflags, node, caller);
2748 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2749 static int validate_slab(struct kmem_cache *s, struct page *page)
2752 void *addr = page_address(page);
2753 DECLARE_BITMAP(map, s->objects);
2755 if (!check_slab(s, page) ||
2756 !on_freelist(s, page, NULL))
2759 /* Now we know that a valid freelist exists */
2760 bitmap_zero(map, s->objects);
2762 for_each_free_object(p, s, page->freelist) {
2763 set_bit(slab_index(p, s, addr), map);
2764 if (!check_object(s, page, p, 0))
2768 for_each_object(p, s, addr)
2769 if (!test_bit(slab_index(p, s, addr), map))
2770 if (!check_object(s, page, p, 1))
2775 static void validate_slab_slab(struct kmem_cache *s, struct page *page)
2777 if (slab_trylock(page)) {
2778 validate_slab(s, page);
2781 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
2784 if (s->flags & DEBUG_DEFAULT_FLAGS) {
2785 if (!SlabDebug(page))
2786 printk(KERN_ERR "SLUB %s: SlabDebug not set "
2787 "on slab 0x%p\n", s->name, page);
2789 if (SlabDebug(page))
2790 printk(KERN_ERR "SLUB %s: SlabDebug set on "
2791 "slab 0x%p\n", s->name, page);
2795 static int validate_slab_node(struct kmem_cache *s, struct kmem_cache_node *n)
2797 unsigned long count = 0;
2799 unsigned long flags;
2801 spin_lock_irqsave(&n->list_lock, flags);
2803 list_for_each_entry(page, &n->partial, lru) {
2804 validate_slab_slab(s, page);
2807 if (count != n->nr_partial)
2808 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
2809 "counter=%ld\n", s->name, count, n->nr_partial);
2811 if (!(s->flags & SLAB_STORE_USER))
2814 list_for_each_entry(page, &n->full, lru) {
2815 validate_slab_slab(s, page);
2818 if (count != atomic_long_read(&n->nr_slabs))
2819 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
2820 "counter=%ld\n", s->name, count,
2821 atomic_long_read(&n->nr_slabs));
2824 spin_unlock_irqrestore(&n->list_lock, flags);
2828 static unsigned long validate_slab_cache(struct kmem_cache *s)
2831 unsigned long count = 0;
2834 for_each_online_node(node) {
2835 struct kmem_cache_node *n = get_node(s, node);
2837 count += validate_slab_node(s, n);
2842 #ifdef SLUB_RESILIENCY_TEST
2843 static void resiliency_test(void)
2847 printk(KERN_ERR "SLUB resiliency testing\n");
2848 printk(KERN_ERR "-----------------------\n");
2849 printk(KERN_ERR "A. Corruption after allocation\n");
2851 p = kzalloc(16, GFP_KERNEL);
2853 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
2854 " 0x12->0x%p\n\n", p + 16);
2856 validate_slab_cache(kmalloc_caches + 4);
2858 /* Hmmm... The next two are dangerous */
2859 p = kzalloc(32, GFP_KERNEL);
2860 p[32 + sizeof(void *)] = 0x34;
2861 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
2862 " 0x34 -> -0x%p\n", p);
2863 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2865 validate_slab_cache(kmalloc_caches + 5);
2866 p = kzalloc(64, GFP_KERNEL);
2867 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
2869 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
2871 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2872 validate_slab_cache(kmalloc_caches + 6);
2874 printk(KERN_ERR "\nB. Corruption after free\n");
2875 p = kzalloc(128, GFP_KERNEL);
2878 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
2879 validate_slab_cache(kmalloc_caches + 7);
2881 p = kzalloc(256, GFP_KERNEL);
2884 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
2885 validate_slab_cache(kmalloc_caches + 8);
2887 p = kzalloc(512, GFP_KERNEL);
2890 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
2891 validate_slab_cache(kmalloc_caches + 9);
2894 static void resiliency_test(void) {};
2898 * Generate lists of code addresses where slabcache objects are allocated
2903 unsigned long count;
2916 unsigned long count;
2917 struct location *loc;
2920 static void free_loc_track(struct loc_track *t)
2923 free_pages((unsigned long)t->loc,
2924 get_order(sizeof(struct location) * t->max));
2927 static int alloc_loc_track(struct loc_track *t, unsigned long max)
2933 max = PAGE_SIZE / sizeof(struct location);
2935 order = get_order(sizeof(struct location) * max);
2937 l = (void *)__get_free_pages(GFP_ATOMIC, order);
2943 memcpy(l, t->loc, sizeof(struct location) * t->count);
2951 static int add_location(struct loc_track *t, struct kmem_cache *s,
2952 const struct track *track)
2954 long start, end, pos;
2957 unsigned long age = jiffies - track->when;
2963 pos = start + (end - start + 1) / 2;
2966 * There is nothing at "end". If we end up there
2967 * we need to add something to before end.
2972 caddr = t->loc[pos].addr;
2973 if (track->addr == caddr) {
2979 if (age < l->min_time)
2981 if (age > l->max_time)
2984 if (track->pid < l->min_pid)
2985 l->min_pid = track->pid;
2986 if (track->pid > l->max_pid)
2987 l->max_pid = track->pid;
2989 cpu_set(track->cpu, l->cpus);
2991 node_set(page_to_nid(virt_to_page(track)), l->nodes);
2995 if (track->addr < caddr)
3002 * Not found. Insert new tracking element.
3004 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max))
3010 (t->count - pos) * sizeof(struct location));
3013 l->addr = track->addr;
3017 l->min_pid = track->pid;
3018 l->max_pid = track->pid;
3019 cpus_clear(l->cpus);
3020 cpu_set(track->cpu, l->cpus);
3021 nodes_clear(l->nodes);
3022 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3026 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3027 struct page *page, enum track_item alloc)
3029 void *addr = page_address(page);
3030 DECLARE_BITMAP(map, s->objects);
3033 bitmap_zero(map, s->objects);
3034 for_each_free_object(p, s, page->freelist)
3035 set_bit(slab_index(p, s, addr), map);
3037 for_each_object(p, s, addr)
3038 if (!test_bit(slab_index(p, s, addr), map))
3039 add_location(t, s, get_track(s, p, alloc));
3042 static int list_locations(struct kmem_cache *s, char *buf,
3043 enum track_item alloc)
3053 /* Push back cpu slabs */
3056 for_each_online_node(node) {
3057 struct kmem_cache_node *n = get_node(s, node);
3058 unsigned long flags;
3061 if (!atomic_read(&n->nr_slabs))
3064 spin_lock_irqsave(&n->list_lock, flags);
3065 list_for_each_entry(page, &n->partial, lru)
3066 process_slab(&t, s, page, alloc);
3067 list_for_each_entry(page, &n->full, lru)
3068 process_slab(&t, s, page, alloc);
3069 spin_unlock_irqrestore(&n->list_lock, flags);
3072 for (i = 0; i < t.count; i++) {
3073 struct location *l = &t.loc[i];
3075 if (n > PAGE_SIZE - 100)
3077 n += sprintf(buf + n, "%7ld ", l->count);
3080 n += sprint_symbol(buf + n, (unsigned long)l->addr);
3082 n += sprintf(buf + n, "<not-available>");
3084 if (l->sum_time != l->min_time) {
3085 unsigned long remainder;
3087 n += sprintf(buf + n, " age=%ld/%ld/%ld",
3089 div_long_long_rem(l->sum_time, l->count, &remainder),
3092 n += sprintf(buf + n, " age=%ld",
3095 if (l->min_pid != l->max_pid)
3096 n += sprintf(buf + n, " pid=%ld-%ld",
3097 l->min_pid, l->max_pid);
3099 n += sprintf(buf + n, " pid=%ld",
3102 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3103 n < PAGE_SIZE - 60) {
3104 n += sprintf(buf + n, " cpus=");
3105 n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3109 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3110 n < PAGE_SIZE - 60) {
3111 n += sprintf(buf + n, " nodes=");
3112 n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3116 n += sprintf(buf + n, "\n");
3121 n += sprintf(buf, "No data\n");
3125 static unsigned long count_partial(struct kmem_cache_node *n)
3127 unsigned long flags;
3128 unsigned long x = 0;
3131 spin_lock_irqsave(&n->list_lock, flags);
3132 list_for_each_entry(page, &n->partial, lru)
3134 spin_unlock_irqrestore(&n->list_lock, flags);
3138 enum slab_stat_type {
3145 #define SO_FULL (1 << SL_FULL)
3146 #define SO_PARTIAL (1 << SL_PARTIAL)
3147 #define SO_CPU (1 << SL_CPU)
3148 #define SO_OBJECTS (1 << SL_OBJECTS)
3150 static unsigned long slab_objects(struct kmem_cache *s,
3151 char *buf, unsigned long flags)
3153 unsigned long total = 0;
3157 unsigned long *nodes;
3158 unsigned long *per_cpu;
3160 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3161 per_cpu = nodes + nr_node_ids;
3163 for_each_possible_cpu(cpu) {
3164 struct page *page = s->cpu_slab[cpu];
3168 node = page_to_nid(page);
3169 if (flags & SO_CPU) {
3172 if (flags & SO_OBJECTS)
3183 for_each_online_node(node) {
3184 struct kmem_cache_node *n = get_node(s, node);
3186 if (flags & SO_PARTIAL) {
3187 if (flags & SO_OBJECTS)
3188 x = count_partial(n);
3195 if (flags & SO_FULL) {
3196 int full_slabs = atomic_read(&n->nr_slabs)
3200 if (flags & SO_OBJECTS)
3201 x = full_slabs * s->objects;
3209 x = sprintf(buf, "%lu", total);
3211 for_each_online_node(node)
3213 x += sprintf(buf + x, " N%d=%lu",
3217 return x + sprintf(buf + x, "\n");
3220 static int any_slab_objects(struct kmem_cache *s)
3225 for_each_possible_cpu(cpu)
3226 if (s->cpu_slab[cpu])
3229 for_each_node(node) {
3230 struct kmem_cache_node *n = get_node(s, node);
3232 if (n->nr_partial || atomic_read(&n->nr_slabs))
3238 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3239 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3241 struct slab_attribute {
3242 struct attribute attr;
3243 ssize_t (*show)(struct kmem_cache *s, char *buf);
3244 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3247 #define SLAB_ATTR_RO(_name) \
3248 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3250 #define SLAB_ATTR(_name) \
3251 static struct slab_attribute _name##_attr = \
3252 __ATTR(_name, 0644, _name##_show, _name##_store)
3254 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3256 return sprintf(buf, "%d\n", s->size);
3258 SLAB_ATTR_RO(slab_size);
3260 static ssize_t align_show(struct kmem_cache *s, char *buf)
3262 return sprintf(buf, "%d\n", s->align);
3264 SLAB_ATTR_RO(align);
3266 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3268 return sprintf(buf, "%d\n", s->objsize);
3270 SLAB_ATTR_RO(object_size);
3272 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3274 return sprintf(buf, "%d\n", s->objects);
3276 SLAB_ATTR_RO(objs_per_slab);
3278 static ssize_t order_show(struct kmem_cache *s, char *buf)
3280 return sprintf(buf, "%d\n", s->order);
3282 SLAB_ATTR_RO(order);
3284 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3287 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3289 return n + sprintf(buf + n, "\n");
3295 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3297 return sprintf(buf, "%d\n", s->refcount - 1);
3299 SLAB_ATTR_RO(aliases);
3301 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3303 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3305 SLAB_ATTR_RO(slabs);
3307 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3309 return slab_objects(s, buf, SO_PARTIAL);
3311 SLAB_ATTR_RO(partial);
3313 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3315 return slab_objects(s, buf, SO_CPU);
3317 SLAB_ATTR_RO(cpu_slabs);
3319 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3321 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3323 SLAB_ATTR_RO(objects);
3325 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3327 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3330 static ssize_t sanity_checks_store(struct kmem_cache *s,
3331 const char *buf, size_t length)
3333 s->flags &= ~SLAB_DEBUG_FREE;
3335 s->flags |= SLAB_DEBUG_FREE;
3338 SLAB_ATTR(sanity_checks);
3340 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3342 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3345 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3348 s->flags &= ~SLAB_TRACE;
3350 s->flags |= SLAB_TRACE;
3355 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3357 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3360 static ssize_t reclaim_account_store(struct kmem_cache *s,
3361 const char *buf, size_t length)
3363 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3365 s->flags |= SLAB_RECLAIM_ACCOUNT;
3368 SLAB_ATTR(reclaim_account);
3370 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3372 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3374 SLAB_ATTR_RO(hwcache_align);
3376 #ifdef CONFIG_ZONE_DMA
3377 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3379 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3381 SLAB_ATTR_RO(cache_dma);
3384 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3386 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3388 SLAB_ATTR_RO(destroy_by_rcu);
3390 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3392 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3395 static ssize_t red_zone_store(struct kmem_cache *s,
3396 const char *buf, size_t length)
3398 if (any_slab_objects(s))
3401 s->flags &= ~SLAB_RED_ZONE;
3403 s->flags |= SLAB_RED_ZONE;
3407 SLAB_ATTR(red_zone);
3409 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3411 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3414 static ssize_t poison_store(struct kmem_cache *s,
3415 const char *buf, size_t length)
3417 if (any_slab_objects(s))
3420 s->flags &= ~SLAB_POISON;
3422 s->flags |= SLAB_POISON;
3428 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3430 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3433 static ssize_t store_user_store(struct kmem_cache *s,
3434 const char *buf, size_t length)
3436 if (any_slab_objects(s))
3439 s->flags &= ~SLAB_STORE_USER;
3441 s->flags |= SLAB_STORE_USER;
3445 SLAB_ATTR(store_user);
3447 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3452 static ssize_t validate_store(struct kmem_cache *s,
3453 const char *buf, size_t length)
3456 validate_slab_cache(s);
3461 SLAB_ATTR(validate);
3463 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3468 static ssize_t shrink_store(struct kmem_cache *s,
3469 const char *buf, size_t length)
3471 if (buf[0] == '1') {
3472 int rc = kmem_cache_shrink(s);
3482 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3484 if (!(s->flags & SLAB_STORE_USER))
3486 return list_locations(s, buf, TRACK_ALLOC);
3488 SLAB_ATTR_RO(alloc_calls);
3490 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3492 if (!(s->flags & SLAB_STORE_USER))
3494 return list_locations(s, buf, TRACK_FREE);
3496 SLAB_ATTR_RO(free_calls);
3499 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3501 return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3504 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3505 const char *buf, size_t length)
3507 int n = simple_strtoul(buf, NULL, 10);
3510 s->defrag_ratio = n * 10;
3513 SLAB_ATTR(defrag_ratio);
3516 static struct attribute * slab_attrs[] = {
3517 &slab_size_attr.attr,
3518 &object_size_attr.attr,
3519 &objs_per_slab_attr.attr,
3524 &cpu_slabs_attr.attr,
3528 &sanity_checks_attr.attr,
3530 &hwcache_align_attr.attr,
3531 &reclaim_account_attr.attr,
3532 &destroy_by_rcu_attr.attr,
3533 &red_zone_attr.attr,
3535 &store_user_attr.attr,
3536 &validate_attr.attr,
3538 &alloc_calls_attr.attr,
3539 &free_calls_attr.attr,
3540 #ifdef CONFIG_ZONE_DMA
3541 &cache_dma_attr.attr,
3544 &defrag_ratio_attr.attr,
3549 static struct attribute_group slab_attr_group = {
3550 .attrs = slab_attrs,
3553 static ssize_t slab_attr_show(struct kobject *kobj,
3554 struct attribute *attr,
3557 struct slab_attribute *attribute;
3558 struct kmem_cache *s;
3561 attribute = to_slab_attr(attr);
3564 if (!attribute->show)
3567 err = attribute->show(s, buf);
3572 static ssize_t slab_attr_store(struct kobject *kobj,
3573 struct attribute *attr,
3574 const char *buf, size_t len)
3576 struct slab_attribute *attribute;
3577 struct kmem_cache *s;
3580 attribute = to_slab_attr(attr);
3583 if (!attribute->store)
3586 err = attribute->store(s, buf, len);
3591 static struct sysfs_ops slab_sysfs_ops = {
3592 .show = slab_attr_show,
3593 .store = slab_attr_store,
3596 static struct kobj_type slab_ktype = {
3597 .sysfs_ops = &slab_sysfs_ops,
3600 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3602 struct kobj_type *ktype = get_ktype(kobj);
3604 if (ktype == &slab_ktype)
3609 static struct kset_uevent_ops slab_uevent_ops = {
3610 .filter = uevent_filter,
3613 decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3615 #define ID_STR_LENGTH 64
3617 /* Create a unique string id for a slab cache:
3619 * :[flags-]size:[memory address of kmemcache]
3621 static char *create_unique_id(struct kmem_cache *s)
3623 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3630 * First flags affecting slabcache operations. We will only
3631 * get here for aliasable slabs so we do not need to support
3632 * too many flags. The flags here must cover all flags that
3633 * are matched during merging to guarantee that the id is
3636 if (s->flags & SLAB_CACHE_DMA)
3638 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3640 if (s->flags & SLAB_DEBUG_FREE)
3644 p += sprintf(p, "%07d", s->size);
3645 BUG_ON(p > name + ID_STR_LENGTH - 1);
3649 static int sysfs_slab_add(struct kmem_cache *s)
3655 if (slab_state < SYSFS)
3656 /* Defer until later */
3659 unmergeable = slab_unmergeable(s);
3662 * Slabcache can never be merged so we can use the name proper.
3663 * This is typically the case for debug situations. In that
3664 * case we can catch duplicate names easily.
3666 sysfs_remove_link(&slab_subsys.kobj, s->name);
3670 * Create a unique name for the slab as a target
3673 name = create_unique_id(s);
3676 kobj_set_kset_s(s, slab_subsys);
3677 kobject_set_name(&s->kobj, name);
3678 kobject_init(&s->kobj);
3679 err = kobject_add(&s->kobj);
3683 err = sysfs_create_group(&s->kobj, &slab_attr_group);
3686 kobject_uevent(&s->kobj, KOBJ_ADD);
3688 /* Setup first alias */
3689 sysfs_slab_alias(s, s->name);
3695 static void sysfs_slab_remove(struct kmem_cache *s)
3697 kobject_uevent(&s->kobj, KOBJ_REMOVE);
3698 kobject_del(&s->kobj);
3702 * Need to buffer aliases during bootup until sysfs becomes
3703 * available lest we loose that information.
3705 struct saved_alias {
3706 struct kmem_cache *s;
3708 struct saved_alias *next;
3711 struct saved_alias *alias_list;
3713 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3715 struct saved_alias *al;
3717 if (slab_state == SYSFS) {
3719 * If we have a leftover link then remove it.
3721 sysfs_remove_link(&slab_subsys.kobj, name);
3722 return sysfs_create_link(&slab_subsys.kobj,
3726 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3732 al->next = alias_list;
3737 static int __init slab_sysfs_init(void)
3739 struct list_head *h;
3742 err = subsystem_register(&slab_subsys);
3744 printk(KERN_ERR "Cannot register slab subsystem.\n");
3750 list_for_each(h, &slab_caches) {
3751 struct kmem_cache *s =
3752 container_of(h, struct kmem_cache, list);
3754 err = sysfs_slab_add(s);
3758 while (alias_list) {
3759 struct saved_alias *al = alias_list;
3761 alias_list = alias_list->next;
3762 err = sysfs_slab_alias(al->s, al->name);
3771 __initcall(slab_sysfs_init);