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)
209 * The page->inuse field is 16 bit thus we have this limitation
211 #define MAX_OBJECTS_PER_SLAB 65535
213 /* Internal SLUB flags */
214 #define __OBJECT_POISON 0x80000000 /* Poison object */
215 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
217 /* Not all arches define cache_line_size */
218 #ifndef cache_line_size
219 #define cache_line_size() L1_CACHE_BYTES
222 static int kmem_size = sizeof(struct kmem_cache);
225 static struct notifier_block slab_notifier;
229 DOWN, /* No slab functionality available */
230 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
231 UP, /* Everything works but does not show up in sysfs */
235 /* A list of all slab caches on the system */
236 static DECLARE_RWSEM(slub_lock);
237 static LIST_HEAD(slab_caches);
240 * Tracking user of a slab.
243 void *addr; /* Called from address */
244 int cpu; /* Was running on cpu */
245 int pid; /* Pid context */
246 unsigned long when; /* When did the operation occur */
249 enum track_item { TRACK_ALLOC, TRACK_FREE };
251 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
252 static int sysfs_slab_add(struct kmem_cache *);
253 static int sysfs_slab_alias(struct kmem_cache *, const char *);
254 static void sysfs_slab_remove(struct kmem_cache *);
256 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
257 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
259 static inline void sysfs_slab_remove(struct kmem_cache *s) {}
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)
274 return s->node[node];
276 return &s->local_node;
280 static inline int check_valid_pointer(struct kmem_cache *s,
281 struct page *page, const void *object)
288 base = page_address(page);
289 if (object < base || object >= base + s->objects * s->size ||
290 (object - base) % s->size) {
298 * Slow version of get and set free pointer.
300 * This version requires touching the cache lines of kmem_cache which
301 * we avoid to do in the fast alloc free paths. There we obtain the offset
302 * from the page struct.
304 static inline void *get_freepointer(struct kmem_cache *s, void *object)
306 return *(void **)(object + s->offset);
309 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
311 *(void **)(object + s->offset) = fp;
314 /* Loop over all objects in a slab */
315 #define for_each_object(__p, __s, __addr) \
316 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
320 #define for_each_free_object(__p, __s, __free) \
321 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
323 /* Determine object index from a given position */
324 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
326 return (p - addr) / s->size;
329 #ifdef CONFIG_SLUB_DEBUG
333 #ifdef CONFIG_SLUB_DEBUG_ON
334 static int slub_debug = DEBUG_DEFAULT_FLAGS;
336 static int slub_debug;
339 static char *slub_debug_slabs;
344 static void print_section(char *text, u8 *addr, unsigned int length)
352 for (i = 0; i < length; i++) {
354 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
357 printk(" %02x", addr[i]);
359 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
361 printk(" %s\n",ascii);
372 printk(" %s\n", ascii);
376 static struct track *get_track(struct kmem_cache *s, void *object,
377 enum track_item alloc)
382 p = object + s->offset + sizeof(void *);
384 p = object + s->inuse;
389 static void set_track(struct kmem_cache *s, void *object,
390 enum track_item alloc, void *addr)
395 p = object + s->offset + sizeof(void *);
397 p = object + s->inuse;
402 p->cpu = smp_processor_id();
403 p->pid = current ? current->pid : -1;
406 memset(p, 0, sizeof(struct track));
409 static void init_tracking(struct kmem_cache *s, void *object)
411 if (!(s->flags & SLAB_STORE_USER))
414 set_track(s, object, TRACK_FREE, NULL);
415 set_track(s, object, TRACK_ALLOC, NULL);
418 static void print_track(const char *s, struct track *t)
423 printk(KERN_ERR "INFO: %s in ", s);
424 __print_symbol("%s", (unsigned long)t->addr);
425 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
428 static void print_tracking(struct kmem_cache *s, void *object)
430 if (!(s->flags & SLAB_STORE_USER))
433 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
434 print_track("Freed", get_track(s, object, TRACK_FREE));
437 static void print_page_info(struct page *page)
439 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
440 page, page->inuse, page->freelist, page->flags);
444 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
450 vsnprintf(buf, sizeof(buf), fmt, args);
452 printk(KERN_ERR "========================================"
453 "=====================================\n");
454 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
455 printk(KERN_ERR "----------------------------------------"
456 "-------------------------------------\n\n");
459 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
465 vsnprintf(buf, sizeof(buf), fmt, args);
467 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
470 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
472 unsigned int off; /* Offset of last byte */
473 u8 *addr = page_address(page);
475 print_tracking(s, p);
477 print_page_info(page);
479 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
480 p, p - addr, get_freepointer(s, p));
483 print_section("Bytes b4", p - 16, 16);
485 print_section("Object", p, min(s->objsize, 128));
487 if (s->flags & SLAB_RED_ZONE)
488 print_section("Redzone", p + s->objsize,
489 s->inuse - s->objsize);
492 off = s->offset + sizeof(void *);
496 if (s->flags & SLAB_STORE_USER)
497 off += 2 * sizeof(struct track);
500 /* Beginning of the filler is the free pointer */
501 print_section("Padding", p + off, s->size - off);
506 static void object_err(struct kmem_cache *s, struct page *page,
507 u8 *object, char *reason)
510 print_trailer(s, page, object);
513 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
519 vsnprintf(buf, sizeof(buf), fmt, args);
522 print_page_info(page);
526 static void init_object(struct kmem_cache *s, void *object, int active)
530 if (s->flags & __OBJECT_POISON) {
531 memset(p, POISON_FREE, s->objsize - 1);
532 p[s->objsize -1] = POISON_END;
535 if (s->flags & SLAB_RED_ZONE)
536 memset(p + s->objsize,
537 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
538 s->inuse - s->objsize);
541 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
544 if (*start != (u8)value)
552 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
553 void *from, void *to)
555 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
556 memset(from, data, to - from);
559 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
560 u8 *object, char *what,
561 u8* start, unsigned int value, unsigned int bytes)
566 fault = check_bytes(start, value, bytes);
571 while (end > fault && end[-1] == value)
574 slab_bug(s, "%s overwritten", what);
575 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
576 fault, end - 1, fault[0], value);
577 print_trailer(s, page, object);
579 restore_bytes(s, what, value, fault, end);
587 * Bytes of the object to be managed.
588 * If the freepointer may overlay the object then the free
589 * pointer is the first word of the object.
591 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
594 * object + s->objsize
595 * Padding to reach word boundary. This is also used for Redzoning.
596 * Padding is extended by another word if Redzoning is enabled and
599 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
600 * 0xcc (RED_ACTIVE) for objects in use.
603 * Meta data starts here.
605 * A. Free pointer (if we cannot overwrite object on free)
606 * B. Tracking data for SLAB_STORE_USER
607 * C. Padding to reach required alignment boundary or at mininum
608 * one word if debuggin is on to be able to detect writes
609 * before the word boundary.
611 * Padding is done using 0x5a (POISON_INUSE)
614 * Nothing is used beyond s->size.
616 * If slabcaches are merged then the objsize and inuse boundaries are mostly
617 * ignored. And therefore no slab options that rely on these boundaries
618 * may be used with merged slabcaches.
621 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
623 unsigned long off = s->inuse; /* The end of info */
626 /* Freepointer is placed after the object. */
627 off += sizeof(void *);
629 if (s->flags & SLAB_STORE_USER)
630 /* We also have user information there */
631 off += 2 * sizeof(struct track);
636 return check_bytes_and_report(s, page, p, "Object padding",
637 p + off, POISON_INUSE, s->size - off);
640 static int slab_pad_check(struct kmem_cache *s, struct page *page)
648 if (!(s->flags & SLAB_POISON))
651 start = page_address(page);
652 end = start + (PAGE_SIZE << s->order);
653 length = s->objects * s->size;
654 remainder = end - (start + length);
658 fault = check_bytes(start + length, POISON_INUSE, remainder);
661 while (end > fault && end[-1] == POISON_INUSE)
664 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
665 print_section("Padding", start, length);
667 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
671 static int check_object(struct kmem_cache *s, struct page *page,
672 void *object, int active)
675 u8 *endobject = object + s->objsize;
677 if (s->flags & SLAB_RED_ZONE) {
679 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
681 if (!check_bytes_and_report(s, page, object, "Redzone",
682 endobject, red, s->inuse - s->objsize))
685 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
686 check_bytes_and_report(s, page, p, "Alignment padding", endobject,
687 POISON_INUSE, s->inuse - s->objsize);
690 if (s->flags & SLAB_POISON) {
691 if (!active && (s->flags & __OBJECT_POISON) &&
692 (!check_bytes_and_report(s, page, p, "Poison", p,
693 POISON_FREE, s->objsize - 1) ||
694 !check_bytes_and_report(s, page, p, "Poison",
695 p + s->objsize -1, POISON_END, 1)))
698 * check_pad_bytes cleans up on its own.
700 check_pad_bytes(s, page, p);
703 if (!s->offset && active)
705 * Object and freepointer overlap. Cannot check
706 * freepointer while object is allocated.
710 /* Check free pointer validity */
711 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
712 object_err(s, page, p, "Freepointer corrupt");
714 * No choice but to zap it and thus loose the remainder
715 * of the free objects in this slab. May cause
716 * another error because the object count is now wrong.
718 set_freepointer(s, p, NULL);
724 static int check_slab(struct kmem_cache *s, struct page *page)
726 VM_BUG_ON(!irqs_disabled());
728 if (!PageSlab(page)) {
729 slab_err(s, page, "Not a valid slab page");
732 if (page->offset * sizeof(void *) != s->offset) {
733 slab_err(s, page, "Corrupted offset %lu",
734 (unsigned long)(page->offset * sizeof(void *)));
737 if (page->inuse > s->objects) {
738 slab_err(s, page, "inuse %u > max %u",
739 s->name, page->inuse, s->objects);
742 /* Slab_pad_check fixes things up after itself */
743 slab_pad_check(s, page);
748 * Determine if a certain object on a page is on the freelist. Must hold the
749 * slab lock to guarantee that the chains are in a consistent state.
751 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
754 void *fp = page->freelist;
757 while (fp && nr <= s->objects) {
760 if (!check_valid_pointer(s, page, fp)) {
762 object_err(s, page, object,
763 "Freechain corrupt");
764 set_freepointer(s, object, NULL);
767 slab_err(s, page, "Freepointer corrupt");
768 page->freelist = NULL;
769 page->inuse = s->objects;
770 slab_fix(s, "Freelist cleared");
776 fp = get_freepointer(s, object);
780 if (page->inuse != s->objects - nr) {
781 slab_err(s, page, "Wrong object count. Counter is %d but "
782 "counted were %d", page->inuse, s->objects - nr);
783 page->inuse = s->objects - nr;
784 slab_fix(s, "Object count adjusted.");
786 return search == NULL;
789 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
791 if (s->flags & SLAB_TRACE) {
792 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
794 alloc ? "alloc" : "free",
799 print_section("Object", (void *)object, s->objsize);
806 * Tracking of fully allocated slabs for debugging purposes.
808 static void add_full(struct kmem_cache_node *n, struct page *page)
810 spin_lock(&n->list_lock);
811 list_add(&page->lru, &n->full);
812 spin_unlock(&n->list_lock);
815 static void remove_full(struct kmem_cache *s, struct page *page)
817 struct kmem_cache_node *n;
819 if (!(s->flags & SLAB_STORE_USER))
822 n = get_node(s, page_to_nid(page));
824 spin_lock(&n->list_lock);
825 list_del(&page->lru);
826 spin_unlock(&n->list_lock);
829 static void setup_object_debug(struct kmem_cache *s, struct page *page,
832 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
835 init_object(s, object, 0);
836 init_tracking(s, object);
839 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
840 void *object, void *addr)
842 if (!check_slab(s, page))
845 if (object && !on_freelist(s, page, object)) {
846 object_err(s, page, object, "Object already allocated");
850 if (!check_valid_pointer(s, page, object)) {
851 object_err(s, page, object, "Freelist Pointer check fails");
855 if (object && !check_object(s, page, object, 0))
858 /* Success perform special debug activities for allocs */
859 if (s->flags & SLAB_STORE_USER)
860 set_track(s, object, TRACK_ALLOC, addr);
861 trace(s, page, object, 1);
862 init_object(s, object, 1);
866 if (PageSlab(page)) {
868 * If this is a slab page then lets do the best we can
869 * to avoid issues in the future. Marking all objects
870 * as used avoids touching the remaining objects.
872 slab_fix(s, "Marking all objects used");
873 page->inuse = s->objects;
874 page->freelist = NULL;
875 /* Fix up fields that may be corrupted */
876 page->offset = s->offset / sizeof(void *);
881 static int free_debug_processing(struct kmem_cache *s, struct page *page,
882 void *object, void *addr)
884 if (!check_slab(s, page))
887 if (!check_valid_pointer(s, page, object)) {
888 slab_err(s, page, "Invalid object pointer 0x%p", object);
892 if (on_freelist(s, page, object)) {
893 object_err(s, page, object, "Object already free");
897 if (!check_object(s, page, object, 1))
900 if (unlikely(s != page->slab)) {
902 slab_err(s, page, "Attempt to free object(0x%p) "
903 "outside of slab", object);
907 "SLUB <none>: no slab for object 0x%p.\n",
912 object_err(s, page, object,
913 "page slab pointer corrupt.");
917 /* Special debug activities for freeing objects */
918 if (!SlabFrozen(page) && !page->freelist)
919 remove_full(s, page);
920 if (s->flags & SLAB_STORE_USER)
921 set_track(s, object, TRACK_FREE, addr);
922 trace(s, page, object, 0);
923 init_object(s, object, 0);
927 slab_fix(s, "Object at 0x%p not freed", object);
931 static int __init setup_slub_debug(char *str)
933 slub_debug = DEBUG_DEFAULT_FLAGS;
934 if (*str++ != '=' || !*str)
936 * No options specified. Switch on full debugging.
942 * No options but restriction on slabs. This means full
943 * debugging for slabs matching a pattern.
950 * Switch off all debugging measures.
955 * Determine which debug features should be switched on
957 for ( ;*str && *str != ','; str++) {
958 switch (tolower(*str)) {
960 slub_debug |= SLAB_DEBUG_FREE;
963 slub_debug |= SLAB_RED_ZONE;
966 slub_debug |= SLAB_POISON;
969 slub_debug |= SLAB_STORE_USER;
972 slub_debug |= SLAB_TRACE;
975 printk(KERN_ERR "slub_debug option '%c' "
976 "unknown. skipped\n",*str);
982 slub_debug_slabs = str + 1;
987 __setup("slub_debug", setup_slub_debug);
989 static unsigned long kmem_cache_flags(unsigned long objsize,
990 unsigned long flags, const char *name,
991 void (*ctor)(void *, struct kmem_cache *, unsigned long))
994 * The page->offset field is only 16 bit wide. This is an offset
995 * in units of words from the beginning of an object. If the slab
996 * size is bigger then we cannot move the free pointer behind the
999 * On 32 bit platforms the limit is 256k. On 64bit platforms
1000 * the limit is 512k.
1002 * Debugging or ctor may create a need to move the free
1003 * pointer. Fail if this happens.
1005 if (objsize >= 65535 * sizeof(void *)) {
1006 BUG_ON(flags & (SLAB_RED_ZONE | SLAB_POISON |
1007 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
1011 * Enable debugging if selected on the kernel commandline.
1013 if (slub_debug && (!slub_debug_slabs ||
1014 strncmp(slub_debug_slabs, name,
1015 strlen(slub_debug_slabs)) == 0))
1016 flags |= slub_debug;
1022 static inline void setup_object_debug(struct kmem_cache *s,
1023 struct page *page, void *object) {}
1025 static inline int alloc_debug_processing(struct kmem_cache *s,
1026 struct page *page, void *object, void *addr) { return 0; }
1028 static inline int free_debug_processing(struct kmem_cache *s,
1029 struct page *page, void *object, void *addr) { return 0; }
1031 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1033 static inline int check_object(struct kmem_cache *s, struct page *page,
1034 void *object, int active) { return 1; }
1035 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1036 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1037 unsigned long flags, const char *name,
1038 void (*ctor)(void *, struct kmem_cache *, unsigned long))
1042 #define slub_debug 0
1045 * Slab allocation and freeing
1047 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1050 int pages = 1 << s->order;
1053 flags |= __GFP_COMP;
1055 if (s->flags & SLAB_CACHE_DMA)
1059 page = alloc_pages(flags, s->order);
1061 page = alloc_pages_node(node, flags, s->order);
1066 mod_zone_page_state(page_zone(page),
1067 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1068 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1074 static void setup_object(struct kmem_cache *s, struct page *page,
1077 setup_object_debug(s, page, object);
1078 if (unlikely(s->ctor))
1079 s->ctor(object, s, 0);
1082 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1085 struct kmem_cache_node *n;
1091 BUG_ON(flags & ~(GFP_DMA | __GFP_ZERO | GFP_LEVEL_MASK));
1093 if (flags & __GFP_WAIT)
1096 page = allocate_slab(s, flags & GFP_LEVEL_MASK, node);
1100 n = get_node(s, page_to_nid(page));
1102 atomic_long_inc(&n->nr_slabs);
1103 page->offset = s->offset / sizeof(void *);
1105 page->flags |= 1 << PG_slab;
1106 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1107 SLAB_STORE_USER | SLAB_TRACE))
1110 start = page_address(page);
1111 end = start + s->objects * s->size;
1113 if (unlikely(s->flags & SLAB_POISON))
1114 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1117 for_each_object(p, s, start) {
1118 setup_object(s, page, last);
1119 set_freepointer(s, last, p);
1122 setup_object(s, page, last);
1123 set_freepointer(s, last, NULL);
1125 page->freelist = start;
1126 page->lockless_freelist = NULL;
1129 if (flags & __GFP_WAIT)
1130 local_irq_disable();
1134 static void __free_slab(struct kmem_cache *s, struct page *page)
1136 int pages = 1 << s->order;
1138 if (unlikely(SlabDebug(page))) {
1141 slab_pad_check(s, page);
1142 for_each_object(p, s, page_address(page))
1143 check_object(s, page, p, 0);
1144 ClearSlabDebug(page);
1147 mod_zone_page_state(page_zone(page),
1148 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1149 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1152 page->mapping = NULL;
1153 __free_pages(page, s->order);
1156 static void rcu_free_slab(struct rcu_head *h)
1160 page = container_of((struct list_head *)h, struct page, lru);
1161 __free_slab(page->slab, page);
1164 static void free_slab(struct kmem_cache *s, struct page *page)
1166 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1168 * RCU free overloads the RCU head over the LRU
1170 struct rcu_head *head = (void *)&page->lru;
1172 call_rcu(head, rcu_free_slab);
1174 __free_slab(s, page);
1177 static void discard_slab(struct kmem_cache *s, struct page *page)
1179 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1181 atomic_long_dec(&n->nr_slabs);
1182 reset_page_mapcount(page);
1183 __ClearPageSlab(page);
1188 * Per slab locking using the pagelock
1190 static __always_inline void slab_lock(struct page *page)
1192 bit_spin_lock(PG_locked, &page->flags);
1195 static __always_inline void slab_unlock(struct page *page)
1197 bit_spin_unlock(PG_locked, &page->flags);
1200 static __always_inline int slab_trylock(struct page *page)
1204 rc = bit_spin_trylock(PG_locked, &page->flags);
1209 * Management of partially allocated slabs
1211 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1213 spin_lock(&n->list_lock);
1215 list_add_tail(&page->lru, &n->partial);
1216 spin_unlock(&n->list_lock);
1219 static void add_partial(struct kmem_cache_node *n, struct page *page)
1221 spin_lock(&n->list_lock);
1223 list_add(&page->lru, &n->partial);
1224 spin_unlock(&n->list_lock);
1227 static void remove_partial(struct kmem_cache *s,
1230 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1232 spin_lock(&n->list_lock);
1233 list_del(&page->lru);
1235 spin_unlock(&n->list_lock);
1239 * Lock slab and remove from the partial list.
1241 * Must hold list_lock.
1243 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1245 if (slab_trylock(page)) {
1246 list_del(&page->lru);
1248 SetSlabFrozen(page);
1255 * Try to allocate a partial slab from a specific node.
1257 static struct page *get_partial_node(struct kmem_cache_node *n)
1262 * Racy check. If we mistakenly see no partial slabs then we
1263 * just allocate an empty slab. If we mistakenly try to get a
1264 * partial slab and there is none available then get_partials()
1267 if (!n || !n->nr_partial)
1270 spin_lock(&n->list_lock);
1271 list_for_each_entry(page, &n->partial, lru)
1272 if (lock_and_freeze_slab(n, page))
1276 spin_unlock(&n->list_lock);
1281 * Get a page from somewhere. Search in increasing NUMA distances.
1283 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1286 struct zonelist *zonelist;
1291 * The defrag ratio allows a configuration of the tradeoffs between
1292 * inter node defragmentation and node local allocations. A lower
1293 * defrag_ratio increases the tendency to do local allocations
1294 * instead of attempting to obtain partial slabs from other nodes.
1296 * If the defrag_ratio is set to 0 then kmalloc() always
1297 * returns node local objects. If the ratio is higher then kmalloc()
1298 * may return off node objects because partial slabs are obtained
1299 * from other nodes and filled up.
1301 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1302 * defrag_ratio = 1000) then every (well almost) allocation will
1303 * first attempt to defrag slab caches on other nodes. This means
1304 * scanning over all nodes to look for partial slabs which may be
1305 * expensive if we do it every time we are trying to find a slab
1306 * with available objects.
1308 if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1311 zonelist = &NODE_DATA(slab_node(current->mempolicy))
1312 ->node_zonelists[gfp_zone(flags)];
1313 for (z = zonelist->zones; *z; z++) {
1314 struct kmem_cache_node *n;
1316 n = get_node(s, zone_to_nid(*z));
1318 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1319 n->nr_partial > MIN_PARTIAL) {
1320 page = get_partial_node(n);
1330 * Get a partial page, lock it and return it.
1332 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1335 int searchnode = (node == -1) ? numa_node_id() : node;
1337 page = get_partial_node(get_node(s, searchnode));
1338 if (page || (flags & __GFP_THISNODE))
1341 return get_any_partial(s, flags);
1345 * Move a page back to the lists.
1347 * Must be called with the slab lock held.
1349 * On exit the slab lock will have been dropped.
1351 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1353 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1355 ClearSlabFrozen(page);
1359 add_partial(n, page);
1360 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1365 if (n->nr_partial < MIN_PARTIAL) {
1367 * Adding an empty slab to the partial slabs in order
1368 * to avoid page allocator overhead. This slab needs
1369 * to come after the other slabs with objects in
1370 * order to fill them up. That way the size of the
1371 * partial list stays small. kmem_cache_shrink can
1372 * reclaim empty slabs from the partial list.
1374 add_partial_tail(n, page);
1378 discard_slab(s, page);
1384 * Remove the cpu slab
1386 static void deactivate_slab(struct kmem_cache *s, struct page *page, int cpu)
1389 * Merge cpu freelist into freelist. Typically we get here
1390 * because both freelists are empty. So this is unlikely
1393 while (unlikely(page->lockless_freelist)) {
1396 /* Retrieve object from cpu_freelist */
1397 object = page->lockless_freelist;
1398 page->lockless_freelist = page->lockless_freelist[page->offset];
1400 /* And put onto the regular freelist */
1401 object[page->offset] = page->freelist;
1402 page->freelist = object;
1405 s->cpu_slab[cpu] = NULL;
1406 unfreeze_slab(s, page);
1409 static inline void flush_slab(struct kmem_cache *s, struct page *page, int cpu)
1412 deactivate_slab(s, page, cpu);
1417 * Called from IPI handler with interrupts disabled.
1419 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1421 struct page *page = s->cpu_slab[cpu];
1424 flush_slab(s, page, cpu);
1427 static void flush_cpu_slab(void *d)
1429 struct kmem_cache *s = d;
1430 int cpu = smp_processor_id();
1432 __flush_cpu_slab(s, cpu);
1435 static void flush_all(struct kmem_cache *s)
1438 on_each_cpu(flush_cpu_slab, s, 1, 1);
1440 unsigned long flags;
1442 local_irq_save(flags);
1444 local_irq_restore(flags);
1449 * Slow path. The lockless freelist is empty or we need to perform
1452 * Interrupts are disabled.
1454 * Processing is still very fast if new objects have been freed to the
1455 * regular freelist. In that case we simply take over the regular freelist
1456 * as the lockless freelist and zap the regular freelist.
1458 * If that is not working then we fall back to the partial lists. We take the
1459 * first element of the freelist as the object to allocate now and move the
1460 * rest of the freelist to the lockless freelist.
1462 * And if we were unable to get a new slab from the partial slab lists then
1463 * we need to allocate a new slab. This is slowest path since we may sleep.
1465 static void *__slab_alloc(struct kmem_cache *s,
1466 gfp_t gfpflags, int node, void *addr, struct page *page)
1469 int cpu = smp_processor_id();
1475 if (unlikely(node != -1 && page_to_nid(page) != node))
1478 object = page->freelist;
1479 if (unlikely(!object))
1481 if (unlikely(SlabDebug(page)))
1484 object = page->freelist;
1485 page->lockless_freelist = object[page->offset];
1486 page->inuse = s->objects;
1487 page->freelist = NULL;
1492 deactivate_slab(s, page, cpu);
1495 page = get_partial(s, gfpflags, node);
1497 s->cpu_slab[cpu] = page;
1501 page = new_slab(s, gfpflags, node);
1503 cpu = smp_processor_id();
1504 if (s->cpu_slab[cpu]) {
1506 * Someone else populated the cpu_slab while we
1507 * enabled interrupts, or we have gotten scheduled
1508 * on another cpu. The page may not be on the
1509 * requested node even if __GFP_THISNODE was
1510 * specified. So we need to recheck.
1513 page_to_nid(s->cpu_slab[cpu]) == node) {
1515 * Current cpuslab is acceptable and we
1516 * want the current one since its cache hot
1518 discard_slab(s, page);
1519 page = s->cpu_slab[cpu];
1523 /* New slab does not fit our expectations */
1524 flush_slab(s, s->cpu_slab[cpu], cpu);
1527 SetSlabFrozen(page);
1528 s->cpu_slab[cpu] = page;
1533 object = page->freelist;
1534 if (!alloc_debug_processing(s, page, object, addr))
1538 page->freelist = object[page->offset];
1544 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1545 * have the fastpath folded into their functions. So no function call
1546 * overhead for requests that can be satisfied on the fastpath.
1548 * The fastpath works by first checking if the lockless freelist can be used.
1549 * If not then __slab_alloc is called for slow processing.
1551 * Otherwise we can simply pick the next object from the lockless free list.
1553 static void __always_inline *slab_alloc(struct kmem_cache *s,
1554 gfp_t gfpflags, int node, void *addr)
1558 unsigned long flags;
1560 local_irq_save(flags);
1561 page = s->cpu_slab[smp_processor_id()];
1562 if (unlikely(!page || !page->lockless_freelist ||
1563 (node != -1 && page_to_nid(page) != node)))
1565 object = __slab_alloc(s, gfpflags, node, addr, page);
1568 object = page->lockless_freelist;
1569 page->lockless_freelist = object[page->offset];
1571 local_irq_restore(flags);
1573 if (unlikely((gfpflags & __GFP_ZERO) && object))
1574 memset(object, 0, s->objsize);
1579 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1581 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1583 EXPORT_SYMBOL(kmem_cache_alloc);
1586 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1588 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1590 EXPORT_SYMBOL(kmem_cache_alloc_node);
1594 * Slow patch handling. This may still be called frequently since objects
1595 * have a longer lifetime than the cpu slabs in most processing loads.
1597 * So we still attempt to reduce cache line usage. Just take the slab
1598 * lock and free the item. If there is no additional partial page
1599 * handling required then we can return immediately.
1601 static void __slab_free(struct kmem_cache *s, struct page *page,
1602 void *x, void *addr)
1605 void **object = (void *)x;
1609 if (unlikely(SlabDebug(page)))
1612 prior = object[page->offset] = page->freelist;
1613 page->freelist = object;
1616 if (unlikely(SlabFrozen(page)))
1619 if (unlikely(!page->inuse))
1623 * Objects left in the slab. If it
1624 * was not on the partial list before
1627 if (unlikely(!prior))
1628 add_partial(get_node(s, page_to_nid(page)), page);
1637 * Slab still on the partial list.
1639 remove_partial(s, page);
1642 discard_slab(s, page);
1646 if (!free_debug_processing(s, page, x, addr))
1652 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1653 * can perform fastpath freeing without additional function calls.
1655 * The fastpath is only possible if we are freeing to the current cpu slab
1656 * of this processor. This typically the case if we have just allocated
1659 * If fastpath is not possible then fall back to __slab_free where we deal
1660 * with all sorts of special processing.
1662 static void __always_inline slab_free(struct kmem_cache *s,
1663 struct page *page, void *x, void *addr)
1665 void **object = (void *)x;
1666 unsigned long flags;
1668 local_irq_save(flags);
1669 debug_check_no_locks_freed(object, s->objsize);
1670 if (likely(page == s->cpu_slab[smp_processor_id()] &&
1671 !SlabDebug(page))) {
1672 object[page->offset] = page->lockless_freelist;
1673 page->lockless_freelist = object;
1675 __slab_free(s, page, x, addr);
1677 local_irq_restore(flags);
1680 void kmem_cache_free(struct kmem_cache *s, void *x)
1684 page = virt_to_head_page(x);
1686 slab_free(s, page, x, __builtin_return_address(0));
1688 EXPORT_SYMBOL(kmem_cache_free);
1690 /* Figure out on which slab object the object resides */
1691 static struct page *get_object_page(const void *x)
1693 struct page *page = virt_to_head_page(x);
1695 if (!PageSlab(page))
1702 * Object placement in a slab is made very easy because we always start at
1703 * offset 0. If we tune the size of the object to the alignment then we can
1704 * get the required alignment by putting one properly sized object after
1707 * Notice that the allocation order determines the sizes of the per cpu
1708 * caches. Each processor has always one slab available for allocations.
1709 * Increasing the allocation order reduces the number of times that slabs
1710 * must be moved on and off the partial lists and is therefore a factor in
1715 * Mininum / Maximum order of slab pages. This influences locking overhead
1716 * and slab fragmentation. A higher order reduces the number of partial slabs
1717 * and increases the number of allocations possible without having to
1718 * take the list_lock.
1720 static int slub_min_order;
1721 static int slub_max_order = DEFAULT_MAX_ORDER;
1722 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1725 * Merge control. If this is set then no merging of slab caches will occur.
1726 * (Could be removed. This was introduced to pacify the merge skeptics.)
1728 static int slub_nomerge;
1731 * Calculate the order of allocation given an slab object size.
1733 * The order of allocation has significant impact on performance and other
1734 * system components. Generally order 0 allocations should be preferred since
1735 * order 0 does not cause fragmentation in the page allocator. Larger objects
1736 * be problematic to put into order 0 slabs because there may be too much
1737 * unused space left. We go to a higher order if more than 1/8th of the slab
1740 * In order to reach satisfactory performance we must ensure that a minimum
1741 * number of objects is in one slab. Otherwise we may generate too much
1742 * activity on the partial lists which requires taking the list_lock. This is
1743 * less a concern for large slabs though which are rarely used.
1745 * slub_max_order specifies the order where we begin to stop considering the
1746 * number of objects in a slab as critical. If we reach slub_max_order then
1747 * we try to keep the page order as low as possible. So we accept more waste
1748 * of space in favor of a small page order.
1750 * Higher order allocations also allow the placement of more objects in a
1751 * slab and thereby reduce object handling overhead. If the user has
1752 * requested a higher mininum order then we start with that one instead of
1753 * the smallest order which will fit the object.
1755 static inline int slab_order(int size, int min_objects,
1756 int max_order, int fract_leftover)
1760 int min_order = slub_min_order;
1763 * If we would create too many object per slab then reduce
1764 * the slab order even if it goes below slub_min_order.
1766 while (min_order > 0 &&
1767 (PAGE_SIZE << min_order) >= MAX_OBJECTS_PER_SLAB * size)
1770 for (order = max(min_order,
1771 fls(min_objects * size - 1) - PAGE_SHIFT);
1772 order <= max_order; order++) {
1774 unsigned long slab_size = PAGE_SIZE << order;
1776 if (slab_size < min_objects * size)
1779 rem = slab_size % size;
1781 if (rem <= slab_size / fract_leftover)
1784 /* If the next size is too high then exit now */
1785 if (slab_size * 2 >= MAX_OBJECTS_PER_SLAB * size)
1792 static inline int calculate_order(int size)
1799 * Attempt to find best configuration for a slab. This
1800 * works by first attempting to generate a layout with
1801 * the best configuration and backing off gradually.
1803 * First we reduce the acceptable waste in a slab. Then
1804 * we reduce the minimum objects required in a slab.
1806 min_objects = slub_min_objects;
1807 while (min_objects > 1) {
1809 while (fraction >= 4) {
1810 order = slab_order(size, min_objects,
1811 slub_max_order, fraction);
1812 if (order <= slub_max_order)
1820 * We were unable to place multiple objects in a slab. Now
1821 * lets see if we can place a single object there.
1823 order = slab_order(size, 1, slub_max_order, 1);
1824 if (order <= slub_max_order)
1828 * Doh this slab cannot be placed using slub_max_order.
1830 order = slab_order(size, 1, MAX_ORDER, 1);
1831 if (order <= MAX_ORDER)
1837 * Figure out what the alignment of the objects will be.
1839 static unsigned long calculate_alignment(unsigned long flags,
1840 unsigned long align, unsigned long size)
1843 * If the user wants hardware cache aligned objects then
1844 * follow that suggestion if the object is sufficiently
1847 * The hardware cache alignment cannot override the
1848 * specified alignment though. If that is greater
1851 if ((flags & SLAB_HWCACHE_ALIGN) &&
1852 size > cache_line_size() / 2)
1853 return max_t(unsigned long, align, cache_line_size());
1855 if (align < ARCH_SLAB_MINALIGN)
1856 return ARCH_SLAB_MINALIGN;
1858 return ALIGN(align, sizeof(void *));
1861 static void init_kmem_cache_node(struct kmem_cache_node *n)
1864 atomic_long_set(&n->nr_slabs, 0);
1865 spin_lock_init(&n->list_lock);
1866 INIT_LIST_HEAD(&n->partial);
1867 #ifdef CONFIG_SLUB_DEBUG
1868 INIT_LIST_HEAD(&n->full);
1874 * No kmalloc_node yet so do it by hand. We know that this is the first
1875 * slab on the node for this slabcache. There are no concurrent accesses
1878 * Note that this function only works on the kmalloc_node_cache
1879 * when allocating for the kmalloc_node_cache.
1881 static struct kmem_cache_node * __init early_kmem_cache_node_alloc(gfp_t gfpflags,
1885 struct kmem_cache_node *n;
1887 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
1889 page = new_slab(kmalloc_caches, gfpflags, node);
1892 if (page_to_nid(page) != node) {
1893 printk(KERN_ERR "SLUB: Unable to allocate memory from "
1895 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
1896 "in order to be able to continue\n");
1901 page->freelist = get_freepointer(kmalloc_caches, n);
1903 kmalloc_caches->node[node] = n;
1904 #ifdef CONFIG_SLUB_DEBUG
1905 init_object(kmalloc_caches, n, 1);
1906 init_tracking(kmalloc_caches, n);
1908 init_kmem_cache_node(n);
1909 atomic_long_inc(&n->nr_slabs);
1910 add_partial(n, page);
1913 * new_slab() disables interupts. If we do not reenable interrupts here
1914 * then bootup would continue with interrupts disabled.
1920 static void free_kmem_cache_nodes(struct kmem_cache *s)
1924 for_each_online_node(node) {
1925 struct kmem_cache_node *n = s->node[node];
1926 if (n && n != &s->local_node)
1927 kmem_cache_free(kmalloc_caches, n);
1928 s->node[node] = NULL;
1932 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1937 if (slab_state >= UP)
1938 local_node = page_to_nid(virt_to_page(s));
1942 for_each_online_node(node) {
1943 struct kmem_cache_node *n;
1945 if (local_node == node)
1948 if (slab_state == DOWN) {
1949 n = early_kmem_cache_node_alloc(gfpflags,
1953 n = kmem_cache_alloc_node(kmalloc_caches,
1957 free_kmem_cache_nodes(s);
1963 init_kmem_cache_node(n);
1968 static void free_kmem_cache_nodes(struct kmem_cache *s)
1972 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1974 init_kmem_cache_node(&s->local_node);
1980 * calculate_sizes() determines the order and the distribution of data within
1983 static int calculate_sizes(struct kmem_cache *s)
1985 unsigned long flags = s->flags;
1986 unsigned long size = s->objsize;
1987 unsigned long align = s->align;
1990 * Determine if we can poison the object itself. If the user of
1991 * the slab may touch the object after free or before allocation
1992 * then we should never poison the object itself.
1994 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
1996 s->flags |= __OBJECT_POISON;
1998 s->flags &= ~__OBJECT_POISON;
2001 * Round up object size to the next word boundary. We can only
2002 * place the free pointer at word boundaries and this determines
2003 * the possible location of the free pointer.
2005 size = ALIGN(size, sizeof(void *));
2007 #ifdef CONFIG_SLUB_DEBUG
2009 * If we are Redzoning then check if there is some space between the
2010 * end of the object and the free pointer. If not then add an
2011 * additional word to have some bytes to store Redzone information.
2013 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2014 size += sizeof(void *);
2018 * With that we have determined the number of bytes in actual use
2019 * by the object. This is the potential offset to the free pointer.
2023 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2026 * Relocate free pointer after the object if it is not
2027 * permitted to overwrite the first word of the object on
2030 * This is the case if we do RCU, have a constructor or
2031 * destructor or are poisoning the objects.
2034 size += sizeof(void *);
2037 #ifdef CONFIG_SLUB_DEBUG
2038 if (flags & SLAB_STORE_USER)
2040 * Need to store information about allocs and frees after
2043 size += 2 * sizeof(struct track);
2045 if (flags & SLAB_RED_ZONE)
2047 * Add some empty padding so that we can catch
2048 * overwrites from earlier objects rather than let
2049 * tracking information or the free pointer be
2050 * corrupted if an user writes before the start
2053 size += sizeof(void *);
2057 * Determine the alignment based on various parameters that the
2058 * user specified and the dynamic determination of cache line size
2061 align = calculate_alignment(flags, align, s->objsize);
2064 * SLUB stores one object immediately after another beginning from
2065 * offset 0. In order to align the objects we have to simply size
2066 * each object to conform to the alignment.
2068 size = ALIGN(size, align);
2071 s->order = calculate_order(size);
2076 * Determine the number of objects per slab
2078 s->objects = (PAGE_SIZE << s->order) / size;
2081 * Verify that the number of objects is within permitted limits.
2082 * The page->inuse field is only 16 bit wide! So we cannot have
2083 * more than 64k objects per slab.
2085 if (!s->objects || s->objects > MAX_OBJECTS_PER_SLAB)
2091 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2092 const char *name, size_t size,
2093 size_t align, unsigned long flags,
2094 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2096 memset(s, 0, kmem_size);
2101 s->flags = kmem_cache_flags(size, flags, name, ctor);
2103 if (!calculate_sizes(s))
2108 s->defrag_ratio = 100;
2111 if (init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2114 if (flags & SLAB_PANIC)
2115 panic("Cannot create slab %s size=%lu realsize=%u "
2116 "order=%u offset=%u flags=%lx\n",
2117 s->name, (unsigned long)size, s->size, s->order,
2123 * Check if a given pointer is valid
2125 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2129 page = get_object_page(object);
2131 if (!page || s != page->slab)
2132 /* No slab or wrong slab */
2135 if (!check_valid_pointer(s, page, object))
2139 * We could also check if the object is on the slabs freelist.
2140 * But this would be too expensive and it seems that the main
2141 * purpose of kmem_ptr_valid is to check if the object belongs
2142 * to a certain slab.
2146 EXPORT_SYMBOL(kmem_ptr_validate);
2149 * Determine the size of a slab object
2151 unsigned int kmem_cache_size(struct kmem_cache *s)
2155 EXPORT_SYMBOL(kmem_cache_size);
2157 const char *kmem_cache_name(struct kmem_cache *s)
2161 EXPORT_SYMBOL(kmem_cache_name);
2164 * Attempt to free all slabs on a node. Return the number of slabs we
2165 * were unable to free.
2167 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2168 struct list_head *list)
2170 int slabs_inuse = 0;
2171 unsigned long flags;
2172 struct page *page, *h;
2174 spin_lock_irqsave(&n->list_lock, flags);
2175 list_for_each_entry_safe(page, h, list, lru)
2177 list_del(&page->lru);
2178 discard_slab(s, page);
2181 spin_unlock_irqrestore(&n->list_lock, flags);
2186 * Release all resources used by a slab cache.
2188 static inline int kmem_cache_close(struct kmem_cache *s)
2194 /* Attempt to free all objects */
2195 for_each_online_node(node) {
2196 struct kmem_cache_node *n = get_node(s, node);
2198 n->nr_partial -= free_list(s, n, &n->partial);
2199 if (atomic_long_read(&n->nr_slabs))
2202 free_kmem_cache_nodes(s);
2207 * Close a cache and release the kmem_cache structure
2208 * (must be used for caches created using kmem_cache_create)
2210 void kmem_cache_destroy(struct kmem_cache *s)
2212 down_write(&slub_lock);
2216 up_write(&slub_lock);
2217 if (kmem_cache_close(s))
2219 sysfs_slab_remove(s);
2222 up_write(&slub_lock);
2224 EXPORT_SYMBOL(kmem_cache_destroy);
2226 /********************************************************************
2228 *******************************************************************/
2230 struct kmem_cache kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __cacheline_aligned;
2231 EXPORT_SYMBOL(kmalloc_caches);
2233 #ifdef CONFIG_ZONE_DMA
2234 static struct kmem_cache *kmalloc_caches_dma[KMALLOC_SHIFT_HIGH + 1];
2237 static int __init setup_slub_min_order(char *str)
2239 get_option (&str, &slub_min_order);
2244 __setup("slub_min_order=", setup_slub_min_order);
2246 static int __init setup_slub_max_order(char *str)
2248 get_option (&str, &slub_max_order);
2253 __setup("slub_max_order=", setup_slub_max_order);
2255 static int __init setup_slub_min_objects(char *str)
2257 get_option (&str, &slub_min_objects);
2262 __setup("slub_min_objects=", setup_slub_min_objects);
2264 static int __init setup_slub_nomerge(char *str)
2270 __setup("slub_nomerge", setup_slub_nomerge);
2272 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2273 const char *name, int size, gfp_t gfp_flags)
2275 unsigned int flags = 0;
2277 if (gfp_flags & SLUB_DMA)
2278 flags = SLAB_CACHE_DMA;
2280 down_write(&slub_lock);
2281 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2285 list_add(&s->list, &slab_caches);
2286 up_write(&slub_lock);
2287 if (sysfs_slab_add(s))
2292 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2295 #ifdef CONFIG_ZONE_DMA
2297 static void sysfs_add_func(struct work_struct *w)
2299 struct kmem_cache *s;
2301 down_write(&slub_lock);
2302 list_for_each_entry(s, &slab_caches, list) {
2303 if (s->flags & __SYSFS_ADD_DEFERRED) {
2304 s->flags &= ~__SYSFS_ADD_DEFERRED;
2308 up_write(&slub_lock);
2311 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2313 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2315 struct kmem_cache *s;
2319 s = kmalloc_caches_dma[index];
2323 /* Dynamically create dma cache */
2324 if (flags & __GFP_WAIT)
2325 down_write(&slub_lock);
2327 if (!down_write_trylock(&slub_lock))
2331 if (kmalloc_caches_dma[index])
2334 realsize = kmalloc_caches[index].objsize;
2335 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d", (unsigned int)realsize),
2336 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2338 if (!s || !text || !kmem_cache_open(s, flags, text,
2339 realsize, ARCH_KMALLOC_MINALIGN,
2340 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2346 list_add(&s->list, &slab_caches);
2347 kmalloc_caches_dma[index] = s;
2349 schedule_work(&sysfs_add_work);
2352 up_write(&slub_lock);
2354 return kmalloc_caches_dma[index];
2359 * Conversion table for small slabs sizes / 8 to the index in the
2360 * kmalloc array. This is necessary for slabs < 192 since we have non power
2361 * of two cache sizes there. The size of larger slabs can be determined using
2364 static s8 size_index[24] = {
2391 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2397 return ZERO_SIZE_PTR;
2399 index = size_index[(size - 1) / 8];
2401 if (size > KMALLOC_MAX_SIZE)
2404 index = fls(size - 1);
2407 #ifdef CONFIG_ZONE_DMA
2408 if (unlikely((flags & SLUB_DMA)))
2409 return dma_kmalloc_cache(index, flags);
2412 return &kmalloc_caches[index];
2415 void *__kmalloc(size_t size, gfp_t flags)
2417 struct kmem_cache *s = get_slab(size, flags);
2419 if (ZERO_OR_NULL_PTR(s))
2422 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2424 EXPORT_SYMBOL(__kmalloc);
2427 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2429 struct kmem_cache *s = get_slab(size, flags);
2431 if (ZERO_OR_NULL_PTR(s))
2434 return slab_alloc(s, flags, node, __builtin_return_address(0));
2436 EXPORT_SYMBOL(__kmalloc_node);
2439 size_t ksize(const void *object)
2442 struct kmem_cache *s;
2444 if (ZERO_OR_NULL_PTR(object))
2447 page = get_object_page(object);
2453 * Debugging requires use of the padding between object
2454 * and whatever may come after it.
2456 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2460 * If we have the need to store the freelist pointer
2461 * back there or track user information then we can
2462 * only use the space before that information.
2464 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2468 * Else we can use all the padding etc for the allocation
2472 EXPORT_SYMBOL(ksize);
2474 void kfree(const void *x)
2476 struct kmem_cache *s;
2480 * This has to be an unsigned comparison. According to Linus
2481 * some gcc version treat a pointer as a signed entity. Then
2482 * this comparison would be true for all "negative" pointers
2483 * (which would cover the whole upper half of the address space).
2485 if (ZERO_OR_NULL_PTR(x))
2488 page = virt_to_head_page(x);
2491 slab_free(s, page, (void *)x, __builtin_return_address(0));
2493 EXPORT_SYMBOL(kfree);
2496 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2497 * the remaining slabs by the number of items in use. The slabs with the
2498 * most items in use come first. New allocations will then fill those up
2499 * and thus they can be removed from the partial lists.
2501 * The slabs with the least items are placed last. This results in them
2502 * being allocated from last increasing the chance that the last objects
2503 * are freed in them.
2505 int kmem_cache_shrink(struct kmem_cache *s)
2509 struct kmem_cache_node *n;
2512 struct list_head *slabs_by_inuse =
2513 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2514 unsigned long flags;
2516 if (!slabs_by_inuse)
2520 for_each_online_node(node) {
2521 n = get_node(s, node);
2526 for (i = 0; i < s->objects; i++)
2527 INIT_LIST_HEAD(slabs_by_inuse + i);
2529 spin_lock_irqsave(&n->list_lock, flags);
2532 * Build lists indexed by the items in use in each slab.
2534 * Note that concurrent frees may occur while we hold the
2535 * list_lock. page->inuse here is the upper limit.
2537 list_for_each_entry_safe(page, t, &n->partial, lru) {
2538 if (!page->inuse && slab_trylock(page)) {
2540 * Must hold slab lock here because slab_free
2541 * may have freed the last object and be
2542 * waiting to release the slab.
2544 list_del(&page->lru);
2547 discard_slab(s, page);
2549 list_move(&page->lru,
2550 slabs_by_inuse + page->inuse);
2555 * Rebuild the partial list with the slabs filled up most
2556 * first and the least used slabs at the end.
2558 for (i = s->objects - 1; i >= 0; i--)
2559 list_splice(slabs_by_inuse + i, n->partial.prev);
2561 spin_unlock_irqrestore(&n->list_lock, flags);
2564 kfree(slabs_by_inuse);
2567 EXPORT_SYMBOL(kmem_cache_shrink);
2569 /********************************************************************
2570 * Basic setup of slabs
2571 *******************************************************************/
2573 void __init kmem_cache_init(void)
2580 * Must first have the slab cache available for the allocations of the
2581 * struct kmem_cache_node's. There is special bootstrap code in
2582 * kmem_cache_open for slab_state == DOWN.
2584 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2585 sizeof(struct kmem_cache_node), GFP_KERNEL);
2586 kmalloc_caches[0].refcount = -1;
2590 /* Able to allocate the per node structures */
2591 slab_state = PARTIAL;
2593 /* Caches that are not of the two-to-the-power-of size */
2594 if (KMALLOC_MIN_SIZE <= 64) {
2595 create_kmalloc_cache(&kmalloc_caches[1],
2596 "kmalloc-96", 96, GFP_KERNEL);
2599 if (KMALLOC_MIN_SIZE <= 128) {
2600 create_kmalloc_cache(&kmalloc_caches[2],
2601 "kmalloc-192", 192, GFP_KERNEL);
2605 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
2606 create_kmalloc_cache(&kmalloc_caches[i],
2607 "kmalloc", 1 << i, GFP_KERNEL);
2613 * Patch up the size_index table if we have strange large alignment
2614 * requirements for the kmalloc array. This is only the case for
2615 * mips it seems. The standard arches will not generate any code here.
2617 * Largest permitted alignment is 256 bytes due to the way we
2618 * handle the index determination for the smaller caches.
2620 * Make sure that nothing crazy happens if someone starts tinkering
2621 * around with ARCH_KMALLOC_MINALIGN
2623 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
2624 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
2626 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
2627 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
2631 /* Provide the correct kmalloc names now that the caches are up */
2632 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++)
2633 kmalloc_caches[i]. name =
2634 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2637 register_cpu_notifier(&slab_notifier);
2640 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2641 nr_cpu_ids * sizeof(struct page *);
2643 printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2644 " CPUs=%d, Nodes=%d\n",
2645 caches, cache_line_size(),
2646 slub_min_order, slub_max_order, slub_min_objects,
2647 nr_cpu_ids, nr_node_ids);
2651 * Find a mergeable slab cache
2653 static int slab_unmergeable(struct kmem_cache *s)
2655 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2662 * We may have set a slab to be unmergeable during bootstrap.
2664 if (s->refcount < 0)
2670 static struct kmem_cache *find_mergeable(size_t size,
2671 size_t align, unsigned long flags, const char *name,
2672 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2674 struct kmem_cache *s;
2676 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2682 size = ALIGN(size, sizeof(void *));
2683 align = calculate_alignment(flags, align, size);
2684 size = ALIGN(size, align);
2685 flags = kmem_cache_flags(size, flags, name, NULL);
2687 list_for_each_entry(s, &slab_caches, list) {
2688 if (slab_unmergeable(s))
2694 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
2697 * Check if alignment is compatible.
2698 * Courtesy of Adrian Drzewiecki
2700 if ((s->size & ~(align -1)) != s->size)
2703 if (s->size - size >= sizeof(void *))
2711 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2712 size_t align, unsigned long flags,
2713 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2715 struct kmem_cache *s;
2717 down_write(&slub_lock);
2718 s = find_mergeable(size, align, flags, name, ctor);
2722 * Adjust the object sizes so that we clear
2723 * the complete object on kzalloc.
2725 s->objsize = max(s->objsize, (int)size);
2726 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2727 up_write(&slub_lock);
2728 if (sysfs_slab_alias(s, name))
2732 s = kmalloc(kmem_size, GFP_KERNEL);
2734 if (kmem_cache_open(s, GFP_KERNEL, name,
2735 size, align, flags, ctor)) {
2736 list_add(&s->list, &slab_caches);
2737 up_write(&slub_lock);
2738 if (sysfs_slab_add(s))
2744 up_write(&slub_lock);
2747 if (flags & SLAB_PANIC)
2748 panic("Cannot create slabcache %s\n", name);
2753 EXPORT_SYMBOL(kmem_cache_create);
2757 * Use the cpu notifier to insure that the cpu slabs are flushed when
2760 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2761 unsigned long action, void *hcpu)
2763 long cpu = (long)hcpu;
2764 struct kmem_cache *s;
2765 unsigned long flags;
2768 case CPU_UP_CANCELED:
2769 case CPU_UP_CANCELED_FROZEN:
2771 case CPU_DEAD_FROZEN:
2772 down_read(&slub_lock);
2773 list_for_each_entry(s, &slab_caches, list) {
2774 local_irq_save(flags);
2775 __flush_cpu_slab(s, cpu);
2776 local_irq_restore(flags);
2778 up_read(&slub_lock);
2786 static struct notifier_block __cpuinitdata slab_notifier =
2787 { &slab_cpuup_callback, NULL, 0 };
2791 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2793 struct kmem_cache *s = get_slab(size, gfpflags);
2795 if (ZERO_OR_NULL_PTR(s))
2798 return slab_alloc(s, gfpflags, -1, caller);
2801 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2802 int node, void *caller)
2804 struct kmem_cache *s = get_slab(size, gfpflags);
2806 if (ZERO_OR_NULL_PTR(s))
2809 return slab_alloc(s, gfpflags, node, caller);
2812 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2813 static int validate_slab(struct kmem_cache *s, struct page *page,
2817 void *addr = page_address(page);
2819 if (!check_slab(s, page) ||
2820 !on_freelist(s, page, NULL))
2823 /* Now we know that a valid freelist exists */
2824 bitmap_zero(map, s->objects);
2826 for_each_free_object(p, s, page->freelist) {
2827 set_bit(slab_index(p, s, addr), map);
2828 if (!check_object(s, page, p, 0))
2832 for_each_object(p, s, addr)
2833 if (!test_bit(slab_index(p, s, addr), map))
2834 if (!check_object(s, page, p, 1))
2839 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
2842 if (slab_trylock(page)) {
2843 validate_slab(s, page, map);
2846 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
2849 if (s->flags & DEBUG_DEFAULT_FLAGS) {
2850 if (!SlabDebug(page))
2851 printk(KERN_ERR "SLUB %s: SlabDebug not set "
2852 "on slab 0x%p\n", s->name, page);
2854 if (SlabDebug(page))
2855 printk(KERN_ERR "SLUB %s: SlabDebug set on "
2856 "slab 0x%p\n", s->name, page);
2860 static int validate_slab_node(struct kmem_cache *s,
2861 struct kmem_cache_node *n, unsigned long *map)
2863 unsigned long count = 0;
2865 unsigned long flags;
2867 spin_lock_irqsave(&n->list_lock, flags);
2869 list_for_each_entry(page, &n->partial, lru) {
2870 validate_slab_slab(s, page, map);
2873 if (count != n->nr_partial)
2874 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
2875 "counter=%ld\n", s->name, count, n->nr_partial);
2877 if (!(s->flags & SLAB_STORE_USER))
2880 list_for_each_entry(page, &n->full, lru) {
2881 validate_slab_slab(s, page, map);
2884 if (count != atomic_long_read(&n->nr_slabs))
2885 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
2886 "counter=%ld\n", s->name, count,
2887 atomic_long_read(&n->nr_slabs));
2890 spin_unlock_irqrestore(&n->list_lock, flags);
2894 static long validate_slab_cache(struct kmem_cache *s)
2897 unsigned long count = 0;
2898 unsigned long *map = kmalloc(BITS_TO_LONGS(s->objects) *
2899 sizeof(unsigned long), GFP_KERNEL);
2905 for_each_online_node(node) {
2906 struct kmem_cache_node *n = get_node(s, node);
2908 count += validate_slab_node(s, n, map);
2914 #ifdef SLUB_RESILIENCY_TEST
2915 static void resiliency_test(void)
2919 printk(KERN_ERR "SLUB resiliency testing\n");
2920 printk(KERN_ERR "-----------------------\n");
2921 printk(KERN_ERR "A. Corruption after allocation\n");
2923 p = kzalloc(16, GFP_KERNEL);
2925 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
2926 " 0x12->0x%p\n\n", p + 16);
2928 validate_slab_cache(kmalloc_caches + 4);
2930 /* Hmmm... The next two are dangerous */
2931 p = kzalloc(32, GFP_KERNEL);
2932 p[32 + sizeof(void *)] = 0x34;
2933 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
2934 " 0x34 -> -0x%p\n", p);
2935 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2937 validate_slab_cache(kmalloc_caches + 5);
2938 p = kzalloc(64, GFP_KERNEL);
2939 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
2941 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
2943 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2944 validate_slab_cache(kmalloc_caches + 6);
2946 printk(KERN_ERR "\nB. Corruption after free\n");
2947 p = kzalloc(128, GFP_KERNEL);
2950 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
2951 validate_slab_cache(kmalloc_caches + 7);
2953 p = kzalloc(256, GFP_KERNEL);
2956 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
2957 validate_slab_cache(kmalloc_caches + 8);
2959 p = kzalloc(512, GFP_KERNEL);
2962 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
2963 validate_slab_cache(kmalloc_caches + 9);
2966 static void resiliency_test(void) {};
2970 * Generate lists of code addresses where slabcache objects are allocated
2975 unsigned long count;
2988 unsigned long count;
2989 struct location *loc;
2992 static void free_loc_track(struct loc_track *t)
2995 free_pages((unsigned long)t->loc,
2996 get_order(sizeof(struct location) * t->max));
2999 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3004 order = get_order(sizeof(struct location) * max);
3006 l = (void *)__get_free_pages(flags, order);
3011 memcpy(l, t->loc, sizeof(struct location) * t->count);
3019 static int add_location(struct loc_track *t, struct kmem_cache *s,
3020 const struct track *track)
3022 long start, end, pos;
3025 unsigned long age = jiffies - track->when;
3031 pos = start + (end - start + 1) / 2;
3034 * There is nothing at "end". If we end up there
3035 * we need to add something to before end.
3040 caddr = t->loc[pos].addr;
3041 if (track->addr == caddr) {
3047 if (age < l->min_time)
3049 if (age > l->max_time)
3052 if (track->pid < l->min_pid)
3053 l->min_pid = track->pid;
3054 if (track->pid > l->max_pid)
3055 l->max_pid = track->pid;
3057 cpu_set(track->cpu, l->cpus);
3059 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3063 if (track->addr < caddr)
3070 * Not found. Insert new tracking element.
3072 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3078 (t->count - pos) * sizeof(struct location));
3081 l->addr = track->addr;
3085 l->min_pid = track->pid;
3086 l->max_pid = track->pid;
3087 cpus_clear(l->cpus);
3088 cpu_set(track->cpu, l->cpus);
3089 nodes_clear(l->nodes);
3090 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3094 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3095 struct page *page, enum track_item alloc)
3097 void *addr = page_address(page);
3098 DECLARE_BITMAP(map, s->objects);
3101 bitmap_zero(map, s->objects);
3102 for_each_free_object(p, s, page->freelist)
3103 set_bit(slab_index(p, s, addr), map);
3105 for_each_object(p, s, addr)
3106 if (!test_bit(slab_index(p, s, addr), map))
3107 add_location(t, s, get_track(s, p, alloc));
3110 static int list_locations(struct kmem_cache *s, char *buf,
3111 enum track_item alloc)
3115 struct loc_track t = { 0, 0, NULL };
3118 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3120 return sprintf(buf, "Out of memory\n");
3122 /* Push back cpu slabs */
3125 for_each_online_node(node) {
3126 struct kmem_cache_node *n = get_node(s, node);
3127 unsigned long flags;
3130 if (!atomic_long_read(&n->nr_slabs))
3133 spin_lock_irqsave(&n->list_lock, flags);
3134 list_for_each_entry(page, &n->partial, lru)
3135 process_slab(&t, s, page, alloc);
3136 list_for_each_entry(page, &n->full, lru)
3137 process_slab(&t, s, page, alloc);
3138 spin_unlock_irqrestore(&n->list_lock, flags);
3141 for (i = 0; i < t.count; i++) {
3142 struct location *l = &t.loc[i];
3144 if (n > PAGE_SIZE - 100)
3146 n += sprintf(buf + n, "%7ld ", l->count);
3149 n += sprint_symbol(buf + n, (unsigned long)l->addr);
3151 n += sprintf(buf + n, "<not-available>");
3153 if (l->sum_time != l->min_time) {
3154 unsigned long remainder;
3156 n += sprintf(buf + n, " age=%ld/%ld/%ld",
3158 div_long_long_rem(l->sum_time, l->count, &remainder),
3161 n += sprintf(buf + n, " age=%ld",
3164 if (l->min_pid != l->max_pid)
3165 n += sprintf(buf + n, " pid=%ld-%ld",
3166 l->min_pid, l->max_pid);
3168 n += sprintf(buf + n, " pid=%ld",
3171 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3172 n < PAGE_SIZE - 60) {
3173 n += sprintf(buf + n, " cpus=");
3174 n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3178 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3179 n < PAGE_SIZE - 60) {
3180 n += sprintf(buf + n, " nodes=");
3181 n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3185 n += sprintf(buf + n, "\n");
3190 n += sprintf(buf, "No data\n");
3194 static unsigned long count_partial(struct kmem_cache_node *n)
3196 unsigned long flags;
3197 unsigned long x = 0;
3200 spin_lock_irqsave(&n->list_lock, flags);
3201 list_for_each_entry(page, &n->partial, lru)
3203 spin_unlock_irqrestore(&n->list_lock, flags);
3207 enum slab_stat_type {
3214 #define SO_FULL (1 << SL_FULL)
3215 #define SO_PARTIAL (1 << SL_PARTIAL)
3216 #define SO_CPU (1 << SL_CPU)
3217 #define SO_OBJECTS (1 << SL_OBJECTS)
3219 static unsigned long slab_objects(struct kmem_cache *s,
3220 char *buf, unsigned long flags)
3222 unsigned long total = 0;
3226 unsigned long *nodes;
3227 unsigned long *per_cpu;
3229 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3230 per_cpu = nodes + nr_node_ids;
3232 for_each_possible_cpu(cpu) {
3233 struct page *page = s->cpu_slab[cpu];
3237 node = page_to_nid(page);
3238 if (flags & SO_CPU) {
3241 if (flags & SO_OBJECTS)
3252 for_each_online_node(node) {
3253 struct kmem_cache_node *n = get_node(s, node);
3255 if (flags & SO_PARTIAL) {
3256 if (flags & SO_OBJECTS)
3257 x = count_partial(n);
3264 if (flags & SO_FULL) {
3265 int full_slabs = atomic_long_read(&n->nr_slabs)
3269 if (flags & SO_OBJECTS)
3270 x = full_slabs * s->objects;
3278 x = sprintf(buf, "%lu", total);
3280 for_each_online_node(node)
3282 x += sprintf(buf + x, " N%d=%lu",
3286 return x + sprintf(buf + x, "\n");
3289 static int any_slab_objects(struct kmem_cache *s)
3294 for_each_possible_cpu(cpu)
3295 if (s->cpu_slab[cpu])
3298 for_each_node(node) {
3299 struct kmem_cache_node *n = get_node(s, node);
3301 if (n->nr_partial || atomic_long_read(&n->nr_slabs))
3307 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3308 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3310 struct slab_attribute {
3311 struct attribute attr;
3312 ssize_t (*show)(struct kmem_cache *s, char *buf);
3313 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3316 #define SLAB_ATTR_RO(_name) \
3317 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3319 #define SLAB_ATTR(_name) \
3320 static struct slab_attribute _name##_attr = \
3321 __ATTR(_name, 0644, _name##_show, _name##_store)
3323 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3325 return sprintf(buf, "%d\n", s->size);
3327 SLAB_ATTR_RO(slab_size);
3329 static ssize_t align_show(struct kmem_cache *s, char *buf)
3331 return sprintf(buf, "%d\n", s->align);
3333 SLAB_ATTR_RO(align);
3335 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3337 return sprintf(buf, "%d\n", s->objsize);
3339 SLAB_ATTR_RO(object_size);
3341 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3343 return sprintf(buf, "%d\n", s->objects);
3345 SLAB_ATTR_RO(objs_per_slab);
3347 static ssize_t order_show(struct kmem_cache *s, char *buf)
3349 return sprintf(buf, "%d\n", s->order);
3351 SLAB_ATTR_RO(order);
3353 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3356 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3358 return n + sprintf(buf + n, "\n");
3364 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3366 return sprintf(buf, "%d\n", s->refcount - 1);
3368 SLAB_ATTR_RO(aliases);
3370 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3372 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3374 SLAB_ATTR_RO(slabs);
3376 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3378 return slab_objects(s, buf, SO_PARTIAL);
3380 SLAB_ATTR_RO(partial);
3382 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3384 return slab_objects(s, buf, SO_CPU);
3386 SLAB_ATTR_RO(cpu_slabs);
3388 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3390 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3392 SLAB_ATTR_RO(objects);
3394 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3396 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3399 static ssize_t sanity_checks_store(struct kmem_cache *s,
3400 const char *buf, size_t length)
3402 s->flags &= ~SLAB_DEBUG_FREE;
3404 s->flags |= SLAB_DEBUG_FREE;
3407 SLAB_ATTR(sanity_checks);
3409 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3411 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3414 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3417 s->flags &= ~SLAB_TRACE;
3419 s->flags |= SLAB_TRACE;
3424 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3426 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3429 static ssize_t reclaim_account_store(struct kmem_cache *s,
3430 const char *buf, size_t length)
3432 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3434 s->flags |= SLAB_RECLAIM_ACCOUNT;
3437 SLAB_ATTR(reclaim_account);
3439 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3441 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3443 SLAB_ATTR_RO(hwcache_align);
3445 #ifdef CONFIG_ZONE_DMA
3446 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3448 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3450 SLAB_ATTR_RO(cache_dma);
3453 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3455 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3457 SLAB_ATTR_RO(destroy_by_rcu);
3459 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3461 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3464 static ssize_t red_zone_store(struct kmem_cache *s,
3465 const char *buf, size_t length)
3467 if (any_slab_objects(s))
3470 s->flags &= ~SLAB_RED_ZONE;
3472 s->flags |= SLAB_RED_ZONE;
3476 SLAB_ATTR(red_zone);
3478 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3480 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3483 static ssize_t poison_store(struct kmem_cache *s,
3484 const char *buf, size_t length)
3486 if (any_slab_objects(s))
3489 s->flags &= ~SLAB_POISON;
3491 s->flags |= SLAB_POISON;
3497 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3499 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3502 static ssize_t store_user_store(struct kmem_cache *s,
3503 const char *buf, size_t length)
3505 if (any_slab_objects(s))
3508 s->flags &= ~SLAB_STORE_USER;
3510 s->flags |= SLAB_STORE_USER;
3514 SLAB_ATTR(store_user);
3516 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3521 static ssize_t validate_store(struct kmem_cache *s,
3522 const char *buf, size_t length)
3526 if (buf[0] == '1') {
3527 ret = validate_slab_cache(s);
3533 SLAB_ATTR(validate);
3535 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3540 static ssize_t shrink_store(struct kmem_cache *s,
3541 const char *buf, size_t length)
3543 if (buf[0] == '1') {
3544 int rc = kmem_cache_shrink(s);
3554 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3556 if (!(s->flags & SLAB_STORE_USER))
3558 return list_locations(s, buf, TRACK_ALLOC);
3560 SLAB_ATTR_RO(alloc_calls);
3562 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3564 if (!(s->flags & SLAB_STORE_USER))
3566 return list_locations(s, buf, TRACK_FREE);
3568 SLAB_ATTR_RO(free_calls);
3571 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3573 return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3576 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3577 const char *buf, size_t length)
3579 int n = simple_strtoul(buf, NULL, 10);
3582 s->defrag_ratio = n * 10;
3585 SLAB_ATTR(defrag_ratio);
3588 static struct attribute * slab_attrs[] = {
3589 &slab_size_attr.attr,
3590 &object_size_attr.attr,
3591 &objs_per_slab_attr.attr,
3596 &cpu_slabs_attr.attr,
3600 &sanity_checks_attr.attr,
3602 &hwcache_align_attr.attr,
3603 &reclaim_account_attr.attr,
3604 &destroy_by_rcu_attr.attr,
3605 &red_zone_attr.attr,
3607 &store_user_attr.attr,
3608 &validate_attr.attr,
3610 &alloc_calls_attr.attr,
3611 &free_calls_attr.attr,
3612 #ifdef CONFIG_ZONE_DMA
3613 &cache_dma_attr.attr,
3616 &defrag_ratio_attr.attr,
3621 static struct attribute_group slab_attr_group = {
3622 .attrs = slab_attrs,
3625 static ssize_t slab_attr_show(struct kobject *kobj,
3626 struct attribute *attr,
3629 struct slab_attribute *attribute;
3630 struct kmem_cache *s;
3633 attribute = to_slab_attr(attr);
3636 if (!attribute->show)
3639 err = attribute->show(s, buf);
3644 static ssize_t slab_attr_store(struct kobject *kobj,
3645 struct attribute *attr,
3646 const char *buf, size_t len)
3648 struct slab_attribute *attribute;
3649 struct kmem_cache *s;
3652 attribute = to_slab_attr(attr);
3655 if (!attribute->store)
3658 err = attribute->store(s, buf, len);
3663 static struct sysfs_ops slab_sysfs_ops = {
3664 .show = slab_attr_show,
3665 .store = slab_attr_store,
3668 static struct kobj_type slab_ktype = {
3669 .sysfs_ops = &slab_sysfs_ops,
3672 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3674 struct kobj_type *ktype = get_ktype(kobj);
3676 if (ktype == &slab_ktype)
3681 static struct kset_uevent_ops slab_uevent_ops = {
3682 .filter = uevent_filter,
3685 static decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3687 #define ID_STR_LENGTH 64
3689 /* Create a unique string id for a slab cache:
3691 * :[flags-]size:[memory address of kmemcache]
3693 static char *create_unique_id(struct kmem_cache *s)
3695 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3702 * First flags affecting slabcache operations. We will only
3703 * get here for aliasable slabs so we do not need to support
3704 * too many flags. The flags here must cover all flags that
3705 * are matched during merging to guarantee that the id is
3708 if (s->flags & SLAB_CACHE_DMA)
3710 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3712 if (s->flags & SLAB_DEBUG_FREE)
3716 p += sprintf(p, "%07d", s->size);
3717 BUG_ON(p > name + ID_STR_LENGTH - 1);
3721 static int sysfs_slab_add(struct kmem_cache *s)
3727 if (slab_state < SYSFS)
3728 /* Defer until later */
3731 unmergeable = slab_unmergeable(s);
3734 * Slabcache can never be merged so we can use the name proper.
3735 * This is typically the case for debug situations. In that
3736 * case we can catch duplicate names easily.
3738 sysfs_remove_link(&slab_subsys.kobj, s->name);
3742 * Create a unique name for the slab as a target
3745 name = create_unique_id(s);
3748 kobj_set_kset_s(s, slab_subsys);
3749 kobject_set_name(&s->kobj, name);
3750 kobject_init(&s->kobj);
3751 err = kobject_add(&s->kobj);
3755 err = sysfs_create_group(&s->kobj, &slab_attr_group);
3758 kobject_uevent(&s->kobj, KOBJ_ADD);
3760 /* Setup first alias */
3761 sysfs_slab_alias(s, s->name);
3767 static void sysfs_slab_remove(struct kmem_cache *s)
3769 kobject_uevent(&s->kobj, KOBJ_REMOVE);
3770 kobject_del(&s->kobj);
3774 * Need to buffer aliases during bootup until sysfs becomes
3775 * available lest we loose that information.
3777 struct saved_alias {
3778 struct kmem_cache *s;
3780 struct saved_alias *next;
3783 static struct saved_alias *alias_list;
3785 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3787 struct saved_alias *al;
3789 if (slab_state == SYSFS) {
3791 * If we have a leftover link then remove it.
3793 sysfs_remove_link(&slab_subsys.kobj, name);
3794 return sysfs_create_link(&slab_subsys.kobj,
3798 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3804 al->next = alias_list;
3809 static int __init slab_sysfs_init(void)
3811 struct kmem_cache *s;
3814 err = subsystem_register(&slab_subsys);
3816 printk(KERN_ERR "Cannot register slab subsystem.\n");
3822 list_for_each_entry(s, &slab_caches, list) {
3823 err = sysfs_slab_add(s);
3825 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
3826 " to sysfs\n", s->name);
3829 while (alias_list) {
3830 struct saved_alias *al = alias_list;
3832 alias_list = alias_list->next;
3833 err = sysfs_slab_alias(al->s, al->name);
3835 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
3836 " %s to sysfs\n", s->name);
3844 __initcall(slab_sysfs_init);