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 * 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 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
145 * - Variable sizing of the per node arrays
148 /* Enable to test recovery from slab corruption on boot */
149 #undef SLUB_RESILIENCY_TEST
154 * Small page size. Make sure that we do not fragment memory
156 #define DEFAULT_MAX_ORDER 1
157 #define DEFAULT_MIN_OBJECTS 4
162 * Large page machines are customarily able to handle larger
165 #define DEFAULT_MAX_ORDER 2
166 #define DEFAULT_MIN_OBJECTS 8
171 * Mininum number of partial slabs. These will be left on the partial
172 * lists even if they are empty. kmem_cache_shrink may reclaim them.
174 #define MIN_PARTIAL 2
177 * Maximum number of desirable partial slabs.
178 * The existence of more partial slabs makes kmem_cache_shrink
179 * sort the partial list by the number of objects in the.
181 #define MAX_PARTIAL 10
183 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
184 SLAB_POISON | SLAB_STORE_USER)
187 * Set of flags that will prevent slab merging
189 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
190 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
192 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
195 #ifndef ARCH_KMALLOC_MINALIGN
196 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
199 #ifndef ARCH_SLAB_MINALIGN
200 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
203 /* Internal SLUB flags */
204 #define __OBJECT_POISON 0x80000000 /* Poison object */
205 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
207 /* Not all arches define cache_line_size */
208 #ifndef cache_line_size
209 #define cache_line_size() L1_CACHE_BYTES
212 static int kmem_size = sizeof(struct kmem_cache);
215 static struct notifier_block slab_notifier;
219 DOWN, /* No slab functionality available */
220 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
221 UP, /* Everything works but does not show up in sysfs */
225 /* A list of all slab caches on the system */
226 static DECLARE_RWSEM(slub_lock);
227 static LIST_HEAD(slab_caches);
230 * Tracking user of a slab.
233 void *addr; /* Called from address */
234 int cpu; /* Was running on cpu */
235 int pid; /* Pid context */
236 unsigned long when; /* When did the operation occur */
239 enum track_item { TRACK_ALLOC, TRACK_FREE };
241 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
242 static int sysfs_slab_add(struct kmem_cache *);
243 static int sysfs_slab_alias(struct kmem_cache *, const char *);
244 static void sysfs_slab_remove(struct kmem_cache *);
246 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
247 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
249 static inline void sysfs_slab_remove(struct kmem_cache *s) {}
252 /********************************************************************
253 * Core slab cache functions
254 *******************************************************************/
256 int slab_is_available(void)
258 return slab_state >= UP;
261 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
264 return s->node[node];
266 return &s->local_node;
270 static inline struct kmem_cache_cpu *get_cpu_slab(struct kmem_cache *s, int cpu)
273 return s->cpu_slab[cpu];
279 static inline int check_valid_pointer(struct kmem_cache *s,
280 struct page *page, const void *object)
287 base = page_address(page);
288 if (object < base || object >= base + s->objects * s->size ||
289 (object - base) % s->size) {
297 * Slow version of get and set free pointer.
299 * This version requires touching the cache lines of kmem_cache which
300 * we avoid to do in the fast alloc free paths. There we obtain the offset
301 * from the page struct.
303 static inline void *get_freepointer(struct kmem_cache *s, void *object)
305 return *(void **)(object + s->offset);
308 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
310 *(void **)(object + s->offset) = fp;
313 /* Loop over all objects in a slab */
314 #define for_each_object(__p, __s, __addr) \
315 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
319 #define for_each_free_object(__p, __s, __free) \
320 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
322 /* Determine object index from a given position */
323 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
325 return (p - addr) / s->size;
328 #ifdef CONFIG_SLUB_DEBUG
332 #ifdef CONFIG_SLUB_DEBUG_ON
333 static int slub_debug = DEBUG_DEFAULT_FLAGS;
335 static int slub_debug;
338 static char *slub_debug_slabs;
343 static void print_section(char *text, u8 *addr, unsigned int length)
351 for (i = 0; i < length; i++) {
353 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
356 printk(" %02x", addr[i]);
358 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
360 printk(" %s\n",ascii);
371 printk(" %s\n", ascii);
375 static struct track *get_track(struct kmem_cache *s, void *object,
376 enum track_item alloc)
381 p = object + s->offset + sizeof(void *);
383 p = object + s->inuse;
388 static void set_track(struct kmem_cache *s, void *object,
389 enum track_item alloc, void *addr)
394 p = object + s->offset + sizeof(void *);
396 p = object + s->inuse;
401 p->cpu = smp_processor_id();
402 p->pid = current ? current->pid : -1;
405 memset(p, 0, sizeof(struct track));
408 static void init_tracking(struct kmem_cache *s, void *object)
410 if (!(s->flags & SLAB_STORE_USER))
413 set_track(s, object, TRACK_FREE, NULL);
414 set_track(s, object, TRACK_ALLOC, NULL);
417 static void print_track(const char *s, struct track *t)
422 printk(KERN_ERR "INFO: %s in ", s);
423 __print_symbol("%s", (unsigned long)t->addr);
424 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
427 static void print_tracking(struct kmem_cache *s, void *object)
429 if (!(s->flags & SLAB_STORE_USER))
432 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
433 print_track("Freed", get_track(s, object, TRACK_FREE));
436 static void print_page_info(struct page *page)
438 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
439 page, page->inuse, page->freelist, page->flags);
443 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
449 vsnprintf(buf, sizeof(buf), fmt, args);
451 printk(KERN_ERR "========================================"
452 "=====================================\n");
453 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
454 printk(KERN_ERR "----------------------------------------"
455 "-------------------------------------\n\n");
458 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
464 vsnprintf(buf, sizeof(buf), fmt, args);
466 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
469 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
471 unsigned int off; /* Offset of last byte */
472 u8 *addr = page_address(page);
474 print_tracking(s, p);
476 print_page_info(page);
478 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
479 p, p - addr, get_freepointer(s, p));
482 print_section("Bytes b4", p - 16, 16);
484 print_section("Object", p, min(s->objsize, 128));
486 if (s->flags & SLAB_RED_ZONE)
487 print_section("Redzone", p + s->objsize,
488 s->inuse - s->objsize);
491 off = s->offset + sizeof(void *);
495 if (s->flags & SLAB_STORE_USER)
496 off += 2 * sizeof(struct track);
499 /* Beginning of the filler is the free pointer */
500 print_section("Padding", p + off, s->size - off);
505 static void object_err(struct kmem_cache *s, struct page *page,
506 u8 *object, char *reason)
509 print_trailer(s, page, object);
512 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
518 vsnprintf(buf, sizeof(buf), fmt, args);
521 print_page_info(page);
525 static void init_object(struct kmem_cache *s, void *object, int active)
529 if (s->flags & __OBJECT_POISON) {
530 memset(p, POISON_FREE, s->objsize - 1);
531 p[s->objsize -1] = POISON_END;
534 if (s->flags & SLAB_RED_ZONE)
535 memset(p + s->objsize,
536 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
537 s->inuse - s->objsize);
540 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
543 if (*start != (u8)value)
551 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
552 void *from, void *to)
554 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
555 memset(from, data, to - from);
558 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
559 u8 *object, char *what,
560 u8* start, unsigned int value, unsigned int bytes)
565 fault = check_bytes(start, value, bytes);
570 while (end > fault && end[-1] == value)
573 slab_bug(s, "%s overwritten", what);
574 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
575 fault, end - 1, fault[0], value);
576 print_trailer(s, page, object);
578 restore_bytes(s, what, value, fault, end);
586 * Bytes of the object to be managed.
587 * If the freepointer may overlay the object then the free
588 * pointer is the first word of the object.
590 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
593 * object + s->objsize
594 * Padding to reach word boundary. This is also used for Redzoning.
595 * Padding is extended by another word if Redzoning is enabled and
598 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
599 * 0xcc (RED_ACTIVE) for objects in use.
602 * Meta data starts here.
604 * A. Free pointer (if we cannot overwrite object on free)
605 * B. Tracking data for SLAB_STORE_USER
606 * C. Padding to reach required alignment boundary or at mininum
607 * one word if debuggin is on to be able to detect writes
608 * before the word boundary.
610 * Padding is done using 0x5a (POISON_INUSE)
613 * Nothing is used beyond s->size.
615 * If slabcaches are merged then the objsize and inuse boundaries are mostly
616 * ignored. And therefore no slab options that rely on these boundaries
617 * may be used with merged slabcaches.
620 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
622 unsigned long off = s->inuse; /* The end of info */
625 /* Freepointer is placed after the object. */
626 off += sizeof(void *);
628 if (s->flags & SLAB_STORE_USER)
629 /* We also have user information there */
630 off += 2 * sizeof(struct track);
635 return check_bytes_and_report(s, page, p, "Object padding",
636 p + off, POISON_INUSE, s->size - off);
639 static int slab_pad_check(struct kmem_cache *s, struct page *page)
647 if (!(s->flags & SLAB_POISON))
650 start = page_address(page);
651 end = start + (PAGE_SIZE << s->order);
652 length = s->objects * s->size;
653 remainder = end - (start + length);
657 fault = check_bytes(start + length, POISON_INUSE, remainder);
660 while (end > fault && end[-1] == POISON_INUSE)
663 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
664 print_section("Padding", start, length);
666 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
670 static int check_object(struct kmem_cache *s, struct page *page,
671 void *object, int active)
674 u8 *endobject = object + s->objsize;
676 if (s->flags & SLAB_RED_ZONE) {
678 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
680 if (!check_bytes_and_report(s, page, object, "Redzone",
681 endobject, red, s->inuse - s->objsize))
684 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
685 check_bytes_and_report(s, page, p, "Alignment padding", endobject,
686 POISON_INUSE, s->inuse - s->objsize);
689 if (s->flags & SLAB_POISON) {
690 if (!active && (s->flags & __OBJECT_POISON) &&
691 (!check_bytes_and_report(s, page, p, "Poison", p,
692 POISON_FREE, s->objsize - 1) ||
693 !check_bytes_and_report(s, page, p, "Poison",
694 p + s->objsize -1, POISON_END, 1)))
697 * check_pad_bytes cleans up on its own.
699 check_pad_bytes(s, page, p);
702 if (!s->offset && active)
704 * Object and freepointer overlap. Cannot check
705 * freepointer while object is allocated.
709 /* Check free pointer validity */
710 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
711 object_err(s, page, p, "Freepointer corrupt");
713 * No choice but to zap it and thus loose the remainder
714 * of the free objects in this slab. May cause
715 * another error because the object count is now wrong.
717 set_freepointer(s, p, NULL);
723 static int check_slab(struct kmem_cache *s, struct page *page)
725 VM_BUG_ON(!irqs_disabled());
727 if (!PageSlab(page)) {
728 slab_err(s, page, "Not a valid slab page");
731 if (page->inuse > s->objects) {
732 slab_err(s, page, "inuse %u > max %u",
733 s->name, page->inuse, s->objects);
736 /* Slab_pad_check fixes things up after itself */
737 slab_pad_check(s, page);
742 * Determine if a certain object on a page is on the freelist. Must hold the
743 * slab lock to guarantee that the chains are in a consistent state.
745 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
748 void *fp = page->freelist;
751 while (fp && nr <= s->objects) {
754 if (!check_valid_pointer(s, page, fp)) {
756 object_err(s, page, object,
757 "Freechain corrupt");
758 set_freepointer(s, object, NULL);
761 slab_err(s, page, "Freepointer corrupt");
762 page->freelist = NULL;
763 page->inuse = s->objects;
764 slab_fix(s, "Freelist cleared");
770 fp = get_freepointer(s, object);
774 if (page->inuse != s->objects - nr) {
775 slab_err(s, page, "Wrong object count. Counter is %d but "
776 "counted were %d", page->inuse, s->objects - nr);
777 page->inuse = s->objects - nr;
778 slab_fix(s, "Object count adjusted.");
780 return search == NULL;
783 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
785 if (s->flags & SLAB_TRACE) {
786 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
788 alloc ? "alloc" : "free",
793 print_section("Object", (void *)object, s->objsize);
800 * Tracking of fully allocated slabs for debugging purposes.
802 static void add_full(struct kmem_cache_node *n, struct page *page)
804 spin_lock(&n->list_lock);
805 list_add(&page->lru, &n->full);
806 spin_unlock(&n->list_lock);
809 static void remove_full(struct kmem_cache *s, struct page *page)
811 struct kmem_cache_node *n;
813 if (!(s->flags & SLAB_STORE_USER))
816 n = get_node(s, page_to_nid(page));
818 spin_lock(&n->list_lock);
819 list_del(&page->lru);
820 spin_unlock(&n->list_lock);
823 static void setup_object_debug(struct kmem_cache *s, struct page *page,
826 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
829 init_object(s, object, 0);
830 init_tracking(s, object);
833 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
834 void *object, void *addr)
836 if (!check_slab(s, page))
839 if (object && !on_freelist(s, page, object)) {
840 object_err(s, page, object, "Object already allocated");
844 if (!check_valid_pointer(s, page, object)) {
845 object_err(s, page, object, "Freelist Pointer check fails");
849 if (object && !check_object(s, page, object, 0))
852 /* Success perform special debug activities for allocs */
853 if (s->flags & SLAB_STORE_USER)
854 set_track(s, object, TRACK_ALLOC, addr);
855 trace(s, page, object, 1);
856 init_object(s, object, 1);
860 if (PageSlab(page)) {
862 * If this is a slab page then lets do the best we can
863 * to avoid issues in the future. Marking all objects
864 * as used avoids touching the remaining objects.
866 slab_fix(s, "Marking all objects used");
867 page->inuse = s->objects;
868 page->freelist = NULL;
873 static int free_debug_processing(struct kmem_cache *s, struct page *page,
874 void *object, void *addr)
876 if (!check_slab(s, page))
879 if (!check_valid_pointer(s, page, object)) {
880 slab_err(s, page, "Invalid object pointer 0x%p", object);
884 if (on_freelist(s, page, object)) {
885 object_err(s, page, object, "Object already free");
889 if (!check_object(s, page, object, 1))
892 if (unlikely(s != page->slab)) {
894 slab_err(s, page, "Attempt to free object(0x%p) "
895 "outside of slab", object);
899 "SLUB <none>: no slab for object 0x%p.\n",
904 object_err(s, page, object,
905 "page slab pointer corrupt.");
909 /* Special debug activities for freeing objects */
910 if (!SlabFrozen(page) && !page->freelist)
911 remove_full(s, page);
912 if (s->flags & SLAB_STORE_USER)
913 set_track(s, object, TRACK_FREE, addr);
914 trace(s, page, object, 0);
915 init_object(s, object, 0);
919 slab_fix(s, "Object at 0x%p not freed", object);
923 static int __init setup_slub_debug(char *str)
925 slub_debug = DEBUG_DEFAULT_FLAGS;
926 if (*str++ != '=' || !*str)
928 * No options specified. Switch on full debugging.
934 * No options but restriction on slabs. This means full
935 * debugging for slabs matching a pattern.
942 * Switch off all debugging measures.
947 * Determine which debug features should be switched on
949 for ( ;*str && *str != ','; str++) {
950 switch (tolower(*str)) {
952 slub_debug |= SLAB_DEBUG_FREE;
955 slub_debug |= SLAB_RED_ZONE;
958 slub_debug |= SLAB_POISON;
961 slub_debug |= SLAB_STORE_USER;
964 slub_debug |= SLAB_TRACE;
967 printk(KERN_ERR "slub_debug option '%c' "
968 "unknown. skipped\n",*str);
974 slub_debug_slabs = str + 1;
979 __setup("slub_debug", setup_slub_debug);
981 static unsigned long kmem_cache_flags(unsigned long objsize,
982 unsigned long flags, const char *name,
983 void (*ctor)(void *, struct kmem_cache *, unsigned long))
986 * The page->offset field is only 16 bit wide. This is an offset
987 * in units of words from the beginning of an object. If the slab
988 * size is bigger then we cannot move the free pointer behind the
991 * On 32 bit platforms the limit is 256k. On 64bit platforms
994 * Debugging or ctor may create a need to move the free
995 * pointer. Fail if this happens.
997 if (objsize >= 65535 * sizeof(void *)) {
998 BUG_ON(flags & (SLAB_RED_ZONE | SLAB_POISON |
999 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, name,
1007 strlen(slub_debug_slabs)) == 0))
1008 flags |= slub_debug;
1014 static inline void setup_object_debug(struct kmem_cache *s,
1015 struct page *page, void *object) {}
1017 static inline int alloc_debug_processing(struct kmem_cache *s,
1018 struct page *page, void *object, void *addr) { return 0; }
1020 static inline int free_debug_processing(struct kmem_cache *s,
1021 struct page *page, void *object, void *addr) { return 0; }
1023 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1025 static inline int check_object(struct kmem_cache *s, struct page *page,
1026 void *object, int active) { return 1; }
1027 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1028 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1029 unsigned long flags, const char *name,
1030 void (*ctor)(void *, struct kmem_cache *, unsigned long))
1034 #define slub_debug 0
1037 * Slab allocation and freeing
1039 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1042 int pages = 1 << s->order;
1045 flags |= __GFP_COMP;
1047 if (s->flags & SLAB_CACHE_DMA)
1050 if (s->flags & SLAB_RECLAIM_ACCOUNT)
1051 flags |= __GFP_RECLAIMABLE;
1054 page = alloc_pages(flags, s->order);
1056 page = alloc_pages_node(node, flags, s->order);
1061 mod_zone_page_state(page_zone(page),
1062 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1063 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1069 static void setup_object(struct kmem_cache *s, struct page *page,
1072 setup_object_debug(s, page, object);
1073 if (unlikely(s->ctor))
1074 s->ctor(object, s, 0);
1077 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1080 struct kmem_cache_node *n;
1086 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1088 if (flags & __GFP_WAIT)
1091 page = allocate_slab(s,
1092 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1096 n = get_node(s, page_to_nid(page));
1098 atomic_long_inc(&n->nr_slabs);
1100 page->flags |= 1 << PG_slab;
1101 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1102 SLAB_STORE_USER | SLAB_TRACE))
1105 start = page_address(page);
1106 end = start + s->objects * s->size;
1108 if (unlikely(s->flags & SLAB_POISON))
1109 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1112 for_each_object(p, s, start) {
1113 setup_object(s, page, last);
1114 set_freepointer(s, last, p);
1117 setup_object(s, page, last);
1118 set_freepointer(s, last, NULL);
1120 page->freelist = start;
1123 if (flags & __GFP_WAIT)
1124 local_irq_disable();
1128 static void __free_slab(struct kmem_cache *s, struct page *page)
1130 int pages = 1 << s->order;
1132 if (unlikely(SlabDebug(page))) {
1135 slab_pad_check(s, page);
1136 for_each_object(p, s, page_address(page))
1137 check_object(s, page, p, 0);
1138 ClearSlabDebug(page);
1141 mod_zone_page_state(page_zone(page),
1142 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1143 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1146 __free_pages(page, s->order);
1149 static void rcu_free_slab(struct rcu_head *h)
1153 page = container_of((struct list_head *)h, struct page, lru);
1154 __free_slab(page->slab, page);
1157 static void free_slab(struct kmem_cache *s, struct page *page)
1159 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1161 * RCU free overloads the RCU head over the LRU
1163 struct rcu_head *head = (void *)&page->lru;
1165 call_rcu(head, rcu_free_slab);
1167 __free_slab(s, page);
1170 static void discard_slab(struct kmem_cache *s, struct page *page)
1172 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1174 atomic_long_dec(&n->nr_slabs);
1175 reset_page_mapcount(page);
1176 __ClearPageSlab(page);
1181 * Per slab locking using the pagelock
1183 static __always_inline void slab_lock(struct page *page)
1185 bit_spin_lock(PG_locked, &page->flags);
1188 static __always_inline void slab_unlock(struct page *page)
1190 bit_spin_unlock(PG_locked, &page->flags);
1193 static __always_inline int slab_trylock(struct page *page)
1197 rc = bit_spin_trylock(PG_locked, &page->flags);
1202 * Management of partially allocated slabs
1204 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1206 spin_lock(&n->list_lock);
1208 list_add_tail(&page->lru, &n->partial);
1209 spin_unlock(&n->list_lock);
1212 static void add_partial(struct kmem_cache_node *n, struct page *page)
1214 spin_lock(&n->list_lock);
1216 list_add(&page->lru, &n->partial);
1217 spin_unlock(&n->list_lock);
1220 static void remove_partial(struct kmem_cache *s,
1223 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1225 spin_lock(&n->list_lock);
1226 list_del(&page->lru);
1228 spin_unlock(&n->list_lock);
1232 * Lock slab and remove from the partial list.
1234 * Must hold list_lock.
1236 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1238 if (slab_trylock(page)) {
1239 list_del(&page->lru);
1241 SetSlabFrozen(page);
1248 * Try to allocate a partial slab from a specific node.
1250 static struct page *get_partial_node(struct kmem_cache_node *n)
1255 * Racy check. If we mistakenly see no partial slabs then we
1256 * just allocate an empty slab. If we mistakenly try to get a
1257 * partial slab and there is none available then get_partials()
1260 if (!n || !n->nr_partial)
1263 spin_lock(&n->list_lock);
1264 list_for_each_entry(page, &n->partial, lru)
1265 if (lock_and_freeze_slab(n, page))
1269 spin_unlock(&n->list_lock);
1274 * Get a page from somewhere. Search in increasing NUMA distances.
1276 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1279 struct zonelist *zonelist;
1284 * The defrag ratio allows a configuration of the tradeoffs between
1285 * inter node defragmentation and node local allocations. A lower
1286 * defrag_ratio increases the tendency to do local allocations
1287 * instead of attempting to obtain partial slabs from other nodes.
1289 * If the defrag_ratio is set to 0 then kmalloc() always
1290 * returns node local objects. If the ratio is higher then kmalloc()
1291 * may return off node objects because partial slabs are obtained
1292 * from other nodes and filled up.
1294 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1295 * defrag_ratio = 1000) then every (well almost) allocation will
1296 * first attempt to defrag slab caches on other nodes. This means
1297 * scanning over all nodes to look for partial slabs which may be
1298 * expensive if we do it every time we are trying to find a slab
1299 * with available objects.
1301 if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1304 zonelist = &NODE_DATA(slab_node(current->mempolicy))
1305 ->node_zonelists[gfp_zone(flags)];
1306 for (z = zonelist->zones; *z; z++) {
1307 struct kmem_cache_node *n;
1309 n = get_node(s, zone_to_nid(*z));
1311 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1312 n->nr_partial > MIN_PARTIAL) {
1313 page = get_partial_node(n);
1323 * Get a partial page, lock it and return it.
1325 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1328 int searchnode = (node == -1) ? numa_node_id() : node;
1330 page = get_partial_node(get_node(s, searchnode));
1331 if (page || (flags & __GFP_THISNODE))
1334 return get_any_partial(s, flags);
1338 * Move a page back to the lists.
1340 * Must be called with the slab lock held.
1342 * On exit the slab lock will have been dropped.
1344 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1346 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1348 ClearSlabFrozen(page);
1352 add_partial(n, page);
1353 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1358 if (n->nr_partial < MIN_PARTIAL) {
1360 * Adding an empty slab to the partial slabs in order
1361 * to avoid page allocator overhead. This slab needs
1362 * to come after the other slabs with objects in
1363 * order to fill them up. That way the size of the
1364 * partial list stays small. kmem_cache_shrink can
1365 * reclaim empty slabs from the partial list.
1367 add_partial_tail(n, page);
1371 discard_slab(s, page);
1377 * Remove the cpu slab
1379 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1381 struct page *page = c->page;
1383 * Merge cpu freelist into freelist. Typically we get here
1384 * because both freelists are empty. So this is unlikely
1387 while (unlikely(c->freelist)) {
1390 /* Retrieve object from cpu_freelist */
1391 object = c->freelist;
1392 c->freelist = c->freelist[c->offset];
1394 /* And put onto the regular freelist */
1395 object[c->offset] = page->freelist;
1396 page->freelist = object;
1400 unfreeze_slab(s, page);
1403 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1406 deactivate_slab(s, c);
1411 * Called from IPI handler with interrupts disabled.
1413 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1415 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1417 if (likely(c && c->page))
1421 static void flush_cpu_slab(void *d)
1423 struct kmem_cache *s = d;
1425 __flush_cpu_slab(s, smp_processor_id());
1428 static void flush_all(struct kmem_cache *s)
1431 on_each_cpu(flush_cpu_slab, s, 1, 1);
1433 unsigned long flags;
1435 local_irq_save(flags);
1437 local_irq_restore(flags);
1442 * Check if the objects in a per cpu structure fit numa
1443 * locality expectations.
1445 static inline int node_match(struct kmem_cache_cpu *c, int node)
1448 if (node != -1 && c->node != node)
1455 * Slow path. The lockless freelist is empty or we need to perform
1458 * Interrupts are disabled.
1460 * Processing is still very fast if new objects have been freed to the
1461 * regular freelist. In that case we simply take over the regular freelist
1462 * as the lockless freelist and zap the regular freelist.
1464 * If that is not working then we fall back to the partial lists. We take the
1465 * first element of the freelist as the object to allocate now and move the
1466 * rest of the freelist to the lockless freelist.
1468 * And if we were unable to get a new slab from the partial slab lists then
1469 * we need to allocate a new slab. This is slowest path since we may sleep.
1471 static void *__slab_alloc(struct kmem_cache *s,
1472 gfp_t gfpflags, int node, void *addr, struct kmem_cache_cpu *c)
1481 if (unlikely(!node_match(c, node)))
1484 object = c->page->freelist;
1485 if (unlikely(!object))
1487 if (unlikely(SlabDebug(c->page)))
1490 object = c->page->freelist;
1491 c->freelist = object[c->offset];
1492 c->page->inuse = s->objects;
1493 c->page->freelist = NULL;
1494 c->node = page_to_nid(c->page);
1495 slab_unlock(c->page);
1499 deactivate_slab(s, c);
1502 new = get_partial(s, gfpflags, node);
1508 new = new_slab(s, gfpflags, node);
1510 c = get_cpu_slab(s, smp_processor_id());
1513 * Someone else populated the cpu_slab while we
1514 * enabled interrupts, or we have gotten scheduled
1515 * on another cpu. The page may not be on the
1516 * requested node even if __GFP_THISNODE was
1517 * specified. So we need to recheck.
1519 if (node_match(c, node)) {
1521 * Current cpuslab is acceptable and we
1522 * want the current one since its cache hot
1524 discard_slab(s, new);
1528 /* New slab does not fit our expectations */
1538 object = c->page->freelist;
1539 if (!alloc_debug_processing(s, c->page, object, addr))
1543 c->page->freelist = object[c->offset];
1545 slab_unlock(c->page);
1550 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1551 * have the fastpath folded into their functions. So no function call
1552 * overhead for requests that can be satisfied on the fastpath.
1554 * The fastpath works by first checking if the lockless freelist can be used.
1555 * If not then __slab_alloc is called for slow processing.
1557 * Otherwise we can simply pick the next object from the lockless free list.
1559 static void __always_inline *slab_alloc(struct kmem_cache *s,
1560 gfp_t gfpflags, int node, void *addr)
1563 unsigned long flags;
1564 struct kmem_cache_cpu *c;
1566 local_irq_save(flags);
1567 c = get_cpu_slab(s, smp_processor_id());
1568 if (unlikely(!c->freelist || !node_match(c, node)))
1570 object = __slab_alloc(s, gfpflags, node, addr, c);
1573 object = c->freelist;
1574 c->freelist = object[c->offset];
1576 local_irq_restore(flags);
1578 if (unlikely((gfpflags & __GFP_ZERO) && object))
1579 memset(object, 0, s->objsize);
1584 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1586 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1588 EXPORT_SYMBOL(kmem_cache_alloc);
1591 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1593 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1595 EXPORT_SYMBOL(kmem_cache_alloc_node);
1599 * Slow patch handling. This may still be called frequently since objects
1600 * have a longer lifetime than the cpu slabs in most processing loads.
1602 * So we still attempt to reduce cache line usage. Just take the slab
1603 * lock and free the item. If there is no additional partial page
1604 * handling required then we can return immediately.
1606 static void __slab_free(struct kmem_cache *s, struct page *page,
1607 void *x, void *addr, unsigned int offset)
1610 void **object = (void *)x;
1614 if (unlikely(SlabDebug(page)))
1617 prior = object[offset] = page->freelist;
1618 page->freelist = object;
1621 if (unlikely(SlabFrozen(page)))
1624 if (unlikely(!page->inuse))
1628 * Objects left in the slab. If it
1629 * was not on the partial list before
1632 if (unlikely(!prior))
1633 add_partial(get_node(s, page_to_nid(page)), page);
1642 * Slab still on the partial list.
1644 remove_partial(s, page);
1647 discard_slab(s, page);
1651 if (!free_debug_processing(s, page, x, addr))
1657 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1658 * can perform fastpath freeing without additional function calls.
1660 * The fastpath is only possible if we are freeing to the current cpu slab
1661 * of this processor. This typically the case if we have just allocated
1664 * If fastpath is not possible then fall back to __slab_free where we deal
1665 * with all sorts of special processing.
1667 static void __always_inline slab_free(struct kmem_cache *s,
1668 struct page *page, void *x, void *addr)
1670 void **object = (void *)x;
1671 unsigned long flags;
1672 struct kmem_cache_cpu *c;
1674 local_irq_save(flags);
1675 debug_check_no_locks_freed(object, s->objsize);
1676 c = get_cpu_slab(s, smp_processor_id());
1677 if (likely(page == c->page && c->node >= 0)) {
1678 object[c->offset] = c->freelist;
1679 c->freelist = object;
1681 __slab_free(s, page, x, addr, c->offset);
1683 local_irq_restore(flags);
1686 void kmem_cache_free(struct kmem_cache *s, void *x)
1690 page = virt_to_head_page(x);
1692 slab_free(s, page, x, __builtin_return_address(0));
1694 EXPORT_SYMBOL(kmem_cache_free);
1696 /* Figure out on which slab object the object resides */
1697 static struct page *get_object_page(const void *x)
1699 struct page *page = virt_to_head_page(x);
1701 if (!PageSlab(page))
1708 * Object placement in a slab is made very easy because we always start at
1709 * offset 0. If we tune the size of the object to the alignment then we can
1710 * get the required alignment by putting one properly sized object after
1713 * Notice that the allocation order determines the sizes of the per cpu
1714 * caches. Each processor has always one slab available for allocations.
1715 * Increasing the allocation order reduces the number of times that slabs
1716 * must be moved on and off the partial lists and is therefore a factor in
1721 * Mininum / Maximum order of slab pages. This influences locking overhead
1722 * and slab fragmentation. A higher order reduces the number of partial slabs
1723 * and increases the number of allocations possible without having to
1724 * take the list_lock.
1726 static int slub_min_order;
1727 static int slub_max_order = DEFAULT_MAX_ORDER;
1728 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1731 * Merge control. If this is set then no merging of slab caches will occur.
1732 * (Could be removed. This was introduced to pacify the merge skeptics.)
1734 static int slub_nomerge;
1737 * Calculate the order of allocation given an slab object size.
1739 * The order of allocation has significant impact on performance and other
1740 * system components. Generally order 0 allocations should be preferred since
1741 * order 0 does not cause fragmentation in the page allocator. Larger objects
1742 * be problematic to put into order 0 slabs because there may be too much
1743 * unused space left. We go to a higher order if more than 1/8th of the slab
1746 * In order to reach satisfactory performance we must ensure that a minimum
1747 * number of objects is in one slab. Otherwise we may generate too much
1748 * activity on the partial lists which requires taking the list_lock. This is
1749 * less a concern for large slabs though which are rarely used.
1751 * slub_max_order specifies the order where we begin to stop considering the
1752 * number of objects in a slab as critical. If we reach slub_max_order then
1753 * we try to keep the page order as low as possible. So we accept more waste
1754 * of space in favor of a small page order.
1756 * Higher order allocations also allow the placement of more objects in a
1757 * slab and thereby reduce object handling overhead. If the user has
1758 * requested a higher mininum order then we start with that one instead of
1759 * the smallest order which will fit the object.
1761 static inline int slab_order(int size, int min_objects,
1762 int max_order, int fract_leftover)
1766 int min_order = slub_min_order;
1768 for (order = max(min_order,
1769 fls(min_objects * size - 1) - PAGE_SHIFT);
1770 order <= max_order; order++) {
1772 unsigned long slab_size = PAGE_SIZE << order;
1774 if (slab_size < min_objects * size)
1777 rem = slab_size % size;
1779 if (rem <= slab_size / fract_leftover)
1787 static inline int calculate_order(int size)
1794 * Attempt to find best configuration for a slab. This
1795 * works by first attempting to generate a layout with
1796 * the best configuration and backing off gradually.
1798 * First we reduce the acceptable waste in a slab. Then
1799 * we reduce the minimum objects required in a slab.
1801 min_objects = slub_min_objects;
1802 while (min_objects > 1) {
1804 while (fraction >= 4) {
1805 order = slab_order(size, min_objects,
1806 slub_max_order, fraction);
1807 if (order <= slub_max_order)
1815 * We were unable to place multiple objects in a slab. Now
1816 * lets see if we can place a single object there.
1818 order = slab_order(size, 1, slub_max_order, 1);
1819 if (order <= slub_max_order)
1823 * Doh this slab cannot be placed using slub_max_order.
1825 order = slab_order(size, 1, MAX_ORDER, 1);
1826 if (order <= MAX_ORDER)
1832 * Figure out what the alignment of the objects will be.
1834 static unsigned long calculate_alignment(unsigned long flags,
1835 unsigned long align, unsigned long size)
1838 * If the user wants hardware cache aligned objects then
1839 * follow that suggestion if the object is sufficiently
1842 * The hardware cache alignment cannot override the
1843 * specified alignment though. If that is greater
1846 if ((flags & SLAB_HWCACHE_ALIGN) &&
1847 size > cache_line_size() / 2)
1848 return max_t(unsigned long, align, cache_line_size());
1850 if (align < ARCH_SLAB_MINALIGN)
1851 return ARCH_SLAB_MINALIGN;
1853 return ALIGN(align, sizeof(void *));
1856 static void init_kmem_cache_cpu(struct kmem_cache *s,
1857 struct kmem_cache_cpu *c)
1861 c->offset = s->offset / sizeof(void *);
1865 static void init_kmem_cache_node(struct kmem_cache_node *n)
1868 atomic_long_set(&n->nr_slabs, 0);
1869 spin_lock_init(&n->list_lock);
1870 INIT_LIST_HEAD(&n->partial);
1871 #ifdef CONFIG_SLUB_DEBUG
1872 INIT_LIST_HEAD(&n->full);
1878 * Per cpu array for per cpu structures.
1880 * The per cpu array places all kmem_cache_cpu structures from one processor
1881 * close together meaning that it becomes possible that multiple per cpu
1882 * structures are contained in one cacheline. This may be particularly
1883 * beneficial for the kmalloc caches.
1885 * A desktop system typically has around 60-80 slabs. With 100 here we are
1886 * likely able to get per cpu structures for all caches from the array defined
1887 * here. We must be able to cover all kmalloc caches during bootstrap.
1889 * If the per cpu array is exhausted then fall back to kmalloc
1890 * of individual cachelines. No sharing is possible then.
1892 #define NR_KMEM_CACHE_CPU 100
1894 static DEFINE_PER_CPU(struct kmem_cache_cpu,
1895 kmem_cache_cpu)[NR_KMEM_CACHE_CPU];
1897 static DEFINE_PER_CPU(struct kmem_cache_cpu *, kmem_cache_cpu_free);
1898 static cpumask_t kmem_cach_cpu_free_init_once = CPU_MASK_NONE;
1900 static struct kmem_cache_cpu *alloc_kmem_cache_cpu(struct kmem_cache *s,
1901 int cpu, gfp_t flags)
1903 struct kmem_cache_cpu *c = per_cpu(kmem_cache_cpu_free, cpu);
1906 per_cpu(kmem_cache_cpu_free, cpu) =
1907 (void *)c->freelist;
1909 /* Table overflow: So allocate ourselves */
1911 ALIGN(sizeof(struct kmem_cache_cpu), cache_line_size()),
1912 flags, cpu_to_node(cpu));
1917 init_kmem_cache_cpu(s, c);
1921 static void free_kmem_cache_cpu(struct kmem_cache_cpu *c, int cpu)
1923 if (c < per_cpu(kmem_cache_cpu, cpu) ||
1924 c > per_cpu(kmem_cache_cpu, cpu) + NR_KMEM_CACHE_CPU) {
1928 c->freelist = (void *)per_cpu(kmem_cache_cpu_free, cpu);
1929 per_cpu(kmem_cache_cpu_free, cpu) = c;
1932 static void free_kmem_cache_cpus(struct kmem_cache *s)
1936 for_each_online_cpu(cpu) {
1937 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1940 s->cpu_slab[cpu] = NULL;
1941 free_kmem_cache_cpu(c, cpu);
1946 static int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
1950 for_each_online_cpu(cpu) {
1951 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1956 c = alloc_kmem_cache_cpu(s, cpu, flags);
1958 free_kmem_cache_cpus(s);
1961 s->cpu_slab[cpu] = c;
1967 * Initialize the per cpu array.
1969 static void init_alloc_cpu_cpu(int cpu)
1973 if (cpu_isset(cpu, kmem_cach_cpu_free_init_once))
1976 for (i = NR_KMEM_CACHE_CPU - 1; i >= 0; i--)
1977 free_kmem_cache_cpu(&per_cpu(kmem_cache_cpu, cpu)[i], cpu);
1979 cpu_set(cpu, kmem_cach_cpu_free_init_once);
1982 static void __init init_alloc_cpu(void)
1986 for_each_online_cpu(cpu)
1987 init_alloc_cpu_cpu(cpu);
1991 static inline void free_kmem_cache_cpus(struct kmem_cache *s) {}
1992 static inline void init_alloc_cpu(void) {}
1994 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
1996 init_kmem_cache_cpu(s, &s->cpu_slab);
2003 * No kmalloc_node yet so do it by hand. We know that this is the first
2004 * slab on the node for this slabcache. There are no concurrent accesses
2007 * Note that this function only works on the kmalloc_node_cache
2008 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2009 * memory on a fresh node that has no slab structures yet.
2011 static struct kmem_cache_node *early_kmem_cache_node_alloc(gfp_t gfpflags,
2015 struct kmem_cache_node *n;
2017 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
2019 page = new_slab(kmalloc_caches, gfpflags, node);
2022 if (page_to_nid(page) != node) {
2023 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2025 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2026 "in order to be able to continue\n");
2031 page->freelist = get_freepointer(kmalloc_caches, n);
2033 kmalloc_caches->node[node] = n;
2034 #ifdef CONFIG_SLUB_DEBUG
2035 init_object(kmalloc_caches, n, 1);
2036 init_tracking(kmalloc_caches, n);
2038 init_kmem_cache_node(n);
2039 atomic_long_inc(&n->nr_slabs);
2040 add_partial(n, page);
2043 * new_slab() disables interupts. If we do not reenable interrupts here
2044 * then bootup would continue with interrupts disabled.
2050 static void free_kmem_cache_nodes(struct kmem_cache *s)
2054 for_each_node_state(node, N_NORMAL_MEMORY) {
2055 struct kmem_cache_node *n = s->node[node];
2056 if (n && n != &s->local_node)
2057 kmem_cache_free(kmalloc_caches, n);
2058 s->node[node] = NULL;
2062 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2067 if (slab_state >= UP)
2068 local_node = page_to_nid(virt_to_page(s));
2072 for_each_node_state(node, N_NORMAL_MEMORY) {
2073 struct kmem_cache_node *n;
2075 if (local_node == node)
2078 if (slab_state == DOWN) {
2079 n = early_kmem_cache_node_alloc(gfpflags,
2083 n = kmem_cache_alloc_node(kmalloc_caches,
2087 free_kmem_cache_nodes(s);
2093 init_kmem_cache_node(n);
2098 static void free_kmem_cache_nodes(struct kmem_cache *s)
2102 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2104 init_kmem_cache_node(&s->local_node);
2110 * calculate_sizes() determines the order and the distribution of data within
2113 static int calculate_sizes(struct kmem_cache *s)
2115 unsigned long flags = s->flags;
2116 unsigned long size = s->objsize;
2117 unsigned long align = s->align;
2120 * Determine if we can poison the object itself. If the user of
2121 * the slab may touch the object after free or before allocation
2122 * then we should never poison the object itself.
2124 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2126 s->flags |= __OBJECT_POISON;
2128 s->flags &= ~__OBJECT_POISON;
2131 * Round up object size to the next word boundary. We can only
2132 * place the free pointer at word boundaries and this determines
2133 * the possible location of the free pointer.
2135 size = ALIGN(size, sizeof(void *));
2137 #ifdef CONFIG_SLUB_DEBUG
2139 * If we are Redzoning then check if there is some space between the
2140 * end of the object and the free pointer. If not then add an
2141 * additional word to have some bytes to store Redzone information.
2143 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2144 size += sizeof(void *);
2148 * With that we have determined the number of bytes in actual use
2149 * by the object. This is the potential offset to the free pointer.
2153 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2156 * Relocate free pointer after the object if it is not
2157 * permitted to overwrite the first word of the object on
2160 * This is the case if we do RCU, have a constructor or
2161 * destructor or are poisoning the objects.
2164 size += sizeof(void *);
2167 #ifdef CONFIG_SLUB_DEBUG
2168 if (flags & SLAB_STORE_USER)
2170 * Need to store information about allocs and frees after
2173 size += 2 * sizeof(struct track);
2175 if (flags & SLAB_RED_ZONE)
2177 * Add some empty padding so that we can catch
2178 * overwrites from earlier objects rather than let
2179 * tracking information or the free pointer be
2180 * corrupted if an user writes before the start
2183 size += sizeof(void *);
2187 * Determine the alignment based on various parameters that the
2188 * user specified and the dynamic determination of cache line size
2191 align = calculate_alignment(flags, align, s->objsize);
2194 * SLUB stores one object immediately after another beginning from
2195 * offset 0. In order to align the objects we have to simply size
2196 * each object to conform to the alignment.
2198 size = ALIGN(size, align);
2201 s->order = calculate_order(size);
2206 * Determine the number of objects per slab
2208 s->objects = (PAGE_SIZE << s->order) / size;
2210 return !!s->objects;
2214 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2215 const char *name, size_t size,
2216 size_t align, unsigned long flags,
2217 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2219 memset(s, 0, kmem_size);
2224 s->flags = kmem_cache_flags(size, flags, name, ctor);
2226 if (!calculate_sizes(s))
2231 s->defrag_ratio = 100;
2233 if (!init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2236 if (alloc_kmem_cache_cpus(s, gfpflags & ~SLUB_DMA))
2238 free_kmem_cache_nodes(s);
2240 if (flags & SLAB_PANIC)
2241 panic("Cannot create slab %s size=%lu realsize=%u "
2242 "order=%u offset=%u flags=%lx\n",
2243 s->name, (unsigned long)size, s->size, s->order,
2249 * Check if a given pointer is valid
2251 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2255 page = get_object_page(object);
2257 if (!page || s != page->slab)
2258 /* No slab or wrong slab */
2261 if (!check_valid_pointer(s, page, object))
2265 * We could also check if the object is on the slabs freelist.
2266 * But this would be too expensive and it seems that the main
2267 * purpose of kmem_ptr_valid is to check if the object belongs
2268 * to a certain slab.
2272 EXPORT_SYMBOL(kmem_ptr_validate);
2275 * Determine the size of a slab object
2277 unsigned int kmem_cache_size(struct kmem_cache *s)
2281 EXPORT_SYMBOL(kmem_cache_size);
2283 const char *kmem_cache_name(struct kmem_cache *s)
2287 EXPORT_SYMBOL(kmem_cache_name);
2290 * Attempt to free all slabs on a node. Return the number of slabs we
2291 * were unable to free.
2293 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2294 struct list_head *list)
2296 int slabs_inuse = 0;
2297 unsigned long flags;
2298 struct page *page, *h;
2300 spin_lock_irqsave(&n->list_lock, flags);
2301 list_for_each_entry_safe(page, h, list, lru)
2303 list_del(&page->lru);
2304 discard_slab(s, page);
2307 spin_unlock_irqrestore(&n->list_lock, flags);
2312 * Release all resources used by a slab cache.
2314 static inline int kmem_cache_close(struct kmem_cache *s)
2320 /* Attempt to free all objects */
2321 free_kmem_cache_cpus(s);
2322 for_each_node_state(node, N_NORMAL_MEMORY) {
2323 struct kmem_cache_node *n = get_node(s, node);
2325 n->nr_partial -= free_list(s, n, &n->partial);
2326 if (atomic_long_read(&n->nr_slabs))
2329 free_kmem_cache_nodes(s);
2334 * Close a cache and release the kmem_cache structure
2335 * (must be used for caches created using kmem_cache_create)
2337 void kmem_cache_destroy(struct kmem_cache *s)
2339 down_write(&slub_lock);
2343 up_write(&slub_lock);
2344 if (kmem_cache_close(s))
2346 sysfs_slab_remove(s);
2349 up_write(&slub_lock);
2351 EXPORT_SYMBOL(kmem_cache_destroy);
2353 /********************************************************************
2355 *******************************************************************/
2357 struct kmem_cache kmalloc_caches[PAGE_SHIFT] __cacheline_aligned;
2358 EXPORT_SYMBOL(kmalloc_caches);
2360 #ifdef CONFIG_ZONE_DMA
2361 static struct kmem_cache *kmalloc_caches_dma[PAGE_SHIFT];
2364 static int __init setup_slub_min_order(char *str)
2366 get_option (&str, &slub_min_order);
2371 __setup("slub_min_order=", setup_slub_min_order);
2373 static int __init setup_slub_max_order(char *str)
2375 get_option (&str, &slub_max_order);
2380 __setup("slub_max_order=", setup_slub_max_order);
2382 static int __init setup_slub_min_objects(char *str)
2384 get_option (&str, &slub_min_objects);
2389 __setup("slub_min_objects=", setup_slub_min_objects);
2391 static int __init setup_slub_nomerge(char *str)
2397 __setup("slub_nomerge", setup_slub_nomerge);
2399 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2400 const char *name, int size, gfp_t gfp_flags)
2402 unsigned int flags = 0;
2404 if (gfp_flags & SLUB_DMA)
2405 flags = SLAB_CACHE_DMA;
2407 down_write(&slub_lock);
2408 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2412 list_add(&s->list, &slab_caches);
2413 up_write(&slub_lock);
2414 if (sysfs_slab_add(s))
2419 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2422 #ifdef CONFIG_ZONE_DMA
2424 static void sysfs_add_func(struct work_struct *w)
2426 struct kmem_cache *s;
2428 down_write(&slub_lock);
2429 list_for_each_entry(s, &slab_caches, list) {
2430 if (s->flags & __SYSFS_ADD_DEFERRED) {
2431 s->flags &= ~__SYSFS_ADD_DEFERRED;
2435 up_write(&slub_lock);
2438 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2440 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2442 struct kmem_cache *s;
2446 s = kmalloc_caches_dma[index];
2450 /* Dynamically create dma cache */
2451 if (flags & __GFP_WAIT)
2452 down_write(&slub_lock);
2454 if (!down_write_trylock(&slub_lock))
2458 if (kmalloc_caches_dma[index])
2461 realsize = kmalloc_caches[index].objsize;
2462 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d", (unsigned int)realsize),
2463 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2465 if (!s || !text || !kmem_cache_open(s, flags, text,
2466 realsize, ARCH_KMALLOC_MINALIGN,
2467 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2473 list_add(&s->list, &slab_caches);
2474 kmalloc_caches_dma[index] = s;
2476 schedule_work(&sysfs_add_work);
2479 up_write(&slub_lock);
2481 return kmalloc_caches_dma[index];
2486 * Conversion table for small slabs sizes / 8 to the index in the
2487 * kmalloc array. This is necessary for slabs < 192 since we have non power
2488 * of two cache sizes there. The size of larger slabs can be determined using
2491 static s8 size_index[24] = {
2518 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2524 return ZERO_SIZE_PTR;
2526 index = size_index[(size - 1) / 8];
2528 index = fls(size - 1);
2530 #ifdef CONFIG_ZONE_DMA
2531 if (unlikely((flags & SLUB_DMA)))
2532 return dma_kmalloc_cache(index, flags);
2535 return &kmalloc_caches[index];
2538 void *__kmalloc(size_t size, gfp_t flags)
2540 struct kmem_cache *s;
2542 if (unlikely(size > PAGE_SIZE / 2))
2543 return (void *)__get_free_pages(flags | __GFP_COMP,
2546 s = get_slab(size, flags);
2548 if (unlikely(ZERO_OR_NULL_PTR(s)))
2551 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2553 EXPORT_SYMBOL(__kmalloc);
2556 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2558 struct kmem_cache *s;
2560 if (unlikely(size > PAGE_SIZE / 2))
2561 return (void *)__get_free_pages(flags | __GFP_COMP,
2564 s = get_slab(size, flags);
2566 if (unlikely(ZERO_OR_NULL_PTR(s)))
2569 return slab_alloc(s, flags, node, __builtin_return_address(0));
2571 EXPORT_SYMBOL(__kmalloc_node);
2574 size_t ksize(const void *object)
2577 struct kmem_cache *s;
2580 if (unlikely(object == ZERO_SIZE_PTR))
2583 page = get_object_page(object);
2589 * Debugging requires use of the padding between object
2590 * and whatever may come after it.
2592 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2596 * If we have the need to store the freelist pointer
2597 * back there or track user information then we can
2598 * only use the space before that information.
2600 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2604 * Else we can use all the padding etc for the allocation
2608 EXPORT_SYMBOL(ksize);
2610 void kfree(const void *x)
2614 if (unlikely(ZERO_OR_NULL_PTR(x)))
2617 page = virt_to_head_page(x);
2618 if (unlikely(!PageSlab(page))) {
2622 slab_free(page->slab, page, (void *)x, __builtin_return_address(0));
2624 EXPORT_SYMBOL(kfree);
2627 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2628 * the remaining slabs by the number of items in use. The slabs with the
2629 * most items in use come first. New allocations will then fill those up
2630 * and thus they can be removed from the partial lists.
2632 * The slabs with the least items are placed last. This results in them
2633 * being allocated from last increasing the chance that the last objects
2634 * are freed in them.
2636 int kmem_cache_shrink(struct kmem_cache *s)
2640 struct kmem_cache_node *n;
2643 struct list_head *slabs_by_inuse =
2644 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2645 unsigned long flags;
2647 if (!slabs_by_inuse)
2651 for_each_node_state(node, N_NORMAL_MEMORY) {
2652 n = get_node(s, node);
2657 for (i = 0; i < s->objects; i++)
2658 INIT_LIST_HEAD(slabs_by_inuse + i);
2660 spin_lock_irqsave(&n->list_lock, flags);
2663 * Build lists indexed by the items in use in each slab.
2665 * Note that concurrent frees may occur while we hold the
2666 * list_lock. page->inuse here is the upper limit.
2668 list_for_each_entry_safe(page, t, &n->partial, lru) {
2669 if (!page->inuse && slab_trylock(page)) {
2671 * Must hold slab lock here because slab_free
2672 * may have freed the last object and be
2673 * waiting to release the slab.
2675 list_del(&page->lru);
2678 discard_slab(s, page);
2680 list_move(&page->lru,
2681 slabs_by_inuse + page->inuse);
2686 * Rebuild the partial list with the slabs filled up most
2687 * first and the least used slabs at the end.
2689 for (i = s->objects - 1; i >= 0; i--)
2690 list_splice(slabs_by_inuse + i, n->partial.prev);
2692 spin_unlock_irqrestore(&n->list_lock, flags);
2695 kfree(slabs_by_inuse);
2698 EXPORT_SYMBOL(kmem_cache_shrink);
2700 /********************************************************************
2701 * Basic setup of slabs
2702 *******************************************************************/
2704 void __init kmem_cache_init(void)
2713 * Must first have the slab cache available for the allocations of the
2714 * struct kmem_cache_node's. There is special bootstrap code in
2715 * kmem_cache_open for slab_state == DOWN.
2717 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2718 sizeof(struct kmem_cache_node), GFP_KERNEL);
2719 kmalloc_caches[0].refcount = -1;
2723 /* Able to allocate the per node structures */
2724 slab_state = PARTIAL;
2726 /* Caches that are not of the two-to-the-power-of size */
2727 if (KMALLOC_MIN_SIZE <= 64) {
2728 create_kmalloc_cache(&kmalloc_caches[1],
2729 "kmalloc-96", 96, GFP_KERNEL);
2732 if (KMALLOC_MIN_SIZE <= 128) {
2733 create_kmalloc_cache(&kmalloc_caches[2],
2734 "kmalloc-192", 192, GFP_KERNEL);
2738 for (i = KMALLOC_SHIFT_LOW; i < PAGE_SHIFT; i++) {
2739 create_kmalloc_cache(&kmalloc_caches[i],
2740 "kmalloc", 1 << i, GFP_KERNEL);
2746 * Patch up the size_index table if we have strange large alignment
2747 * requirements for the kmalloc array. This is only the case for
2748 * mips it seems. The standard arches will not generate any code here.
2750 * Largest permitted alignment is 256 bytes due to the way we
2751 * handle the index determination for the smaller caches.
2753 * Make sure that nothing crazy happens if someone starts tinkering
2754 * around with ARCH_KMALLOC_MINALIGN
2756 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
2757 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
2759 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
2760 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
2764 /* Provide the correct kmalloc names now that the caches are up */
2765 for (i = KMALLOC_SHIFT_LOW; i < PAGE_SHIFT; i++)
2766 kmalloc_caches[i]. name =
2767 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2770 register_cpu_notifier(&slab_notifier);
2771 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2772 nr_cpu_ids * sizeof(struct kmem_cache_cpu *);
2774 kmem_size = sizeof(struct kmem_cache);
2778 printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2779 " CPUs=%d, Nodes=%d\n",
2780 caches, cache_line_size(),
2781 slub_min_order, slub_max_order, slub_min_objects,
2782 nr_cpu_ids, nr_node_ids);
2786 * Find a mergeable slab cache
2788 static int slab_unmergeable(struct kmem_cache *s)
2790 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2797 * We may have set a slab to be unmergeable during bootstrap.
2799 if (s->refcount < 0)
2805 static struct kmem_cache *find_mergeable(size_t size,
2806 size_t align, unsigned long flags, const char *name,
2807 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2809 struct kmem_cache *s;
2811 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2817 size = ALIGN(size, sizeof(void *));
2818 align = calculate_alignment(flags, align, size);
2819 size = ALIGN(size, align);
2820 flags = kmem_cache_flags(size, flags, name, NULL);
2822 list_for_each_entry(s, &slab_caches, list) {
2823 if (slab_unmergeable(s))
2829 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
2832 * Check if alignment is compatible.
2833 * Courtesy of Adrian Drzewiecki
2835 if ((s->size & ~(align -1)) != s->size)
2838 if (s->size - size >= sizeof(void *))
2846 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2847 size_t align, unsigned long flags,
2848 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2850 struct kmem_cache *s;
2852 down_write(&slub_lock);
2853 s = find_mergeable(size, align, flags, name, ctor);
2857 * Adjust the object sizes so that we clear
2858 * the complete object on kzalloc.
2860 s->objsize = max(s->objsize, (int)size);
2861 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2862 up_write(&slub_lock);
2863 if (sysfs_slab_alias(s, name))
2867 s = kmalloc(kmem_size, GFP_KERNEL);
2869 if (kmem_cache_open(s, GFP_KERNEL, name,
2870 size, align, flags, ctor)) {
2871 list_add(&s->list, &slab_caches);
2872 up_write(&slub_lock);
2873 if (sysfs_slab_add(s))
2879 up_write(&slub_lock);
2882 if (flags & SLAB_PANIC)
2883 panic("Cannot create slabcache %s\n", name);
2888 EXPORT_SYMBOL(kmem_cache_create);
2892 * Use the cpu notifier to insure that the cpu slabs are flushed when
2895 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2896 unsigned long action, void *hcpu)
2898 long cpu = (long)hcpu;
2899 struct kmem_cache *s;
2900 unsigned long flags;
2903 case CPU_UP_PREPARE:
2904 case CPU_UP_PREPARE_FROZEN:
2905 init_alloc_cpu_cpu(cpu);
2906 down_read(&slub_lock);
2907 list_for_each_entry(s, &slab_caches, list)
2908 s->cpu_slab[cpu] = alloc_kmem_cache_cpu(s, cpu,
2910 up_read(&slub_lock);
2913 case CPU_UP_CANCELED:
2914 case CPU_UP_CANCELED_FROZEN:
2916 case CPU_DEAD_FROZEN:
2917 down_read(&slub_lock);
2918 list_for_each_entry(s, &slab_caches, list) {
2919 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2921 local_irq_save(flags);
2922 __flush_cpu_slab(s, cpu);
2923 local_irq_restore(flags);
2924 free_kmem_cache_cpu(c, cpu);
2925 s->cpu_slab[cpu] = NULL;
2927 up_read(&slub_lock);
2935 static struct notifier_block __cpuinitdata slab_notifier =
2936 { &slab_cpuup_callback, NULL, 0 };
2940 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2942 struct kmem_cache *s;
2944 if (unlikely(size > PAGE_SIZE / 2))
2945 return (void *)__get_free_pages(gfpflags | __GFP_COMP,
2947 s = get_slab(size, gfpflags);
2949 if (unlikely(ZERO_OR_NULL_PTR(s)))
2952 return slab_alloc(s, gfpflags, -1, caller);
2955 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2956 int node, void *caller)
2958 struct kmem_cache *s;
2960 if (unlikely(size > PAGE_SIZE / 2))
2961 return (void *)__get_free_pages(gfpflags | __GFP_COMP,
2963 s = get_slab(size, gfpflags);
2965 if (unlikely(ZERO_OR_NULL_PTR(s)))
2968 return slab_alloc(s, gfpflags, node, caller);
2971 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2972 static int validate_slab(struct kmem_cache *s, struct page *page,
2976 void *addr = page_address(page);
2978 if (!check_slab(s, page) ||
2979 !on_freelist(s, page, NULL))
2982 /* Now we know that a valid freelist exists */
2983 bitmap_zero(map, s->objects);
2985 for_each_free_object(p, s, page->freelist) {
2986 set_bit(slab_index(p, s, addr), map);
2987 if (!check_object(s, page, p, 0))
2991 for_each_object(p, s, addr)
2992 if (!test_bit(slab_index(p, s, addr), map))
2993 if (!check_object(s, page, p, 1))
2998 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
3001 if (slab_trylock(page)) {
3002 validate_slab(s, page, map);
3005 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
3008 if (s->flags & DEBUG_DEFAULT_FLAGS) {
3009 if (!SlabDebug(page))
3010 printk(KERN_ERR "SLUB %s: SlabDebug not set "
3011 "on slab 0x%p\n", s->name, page);
3013 if (SlabDebug(page))
3014 printk(KERN_ERR "SLUB %s: SlabDebug set on "
3015 "slab 0x%p\n", s->name, page);
3019 static int validate_slab_node(struct kmem_cache *s,
3020 struct kmem_cache_node *n, unsigned long *map)
3022 unsigned long count = 0;
3024 unsigned long flags;
3026 spin_lock_irqsave(&n->list_lock, flags);
3028 list_for_each_entry(page, &n->partial, lru) {
3029 validate_slab_slab(s, page, map);
3032 if (count != n->nr_partial)
3033 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
3034 "counter=%ld\n", s->name, count, n->nr_partial);
3036 if (!(s->flags & SLAB_STORE_USER))
3039 list_for_each_entry(page, &n->full, lru) {
3040 validate_slab_slab(s, page, map);
3043 if (count != atomic_long_read(&n->nr_slabs))
3044 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
3045 "counter=%ld\n", s->name, count,
3046 atomic_long_read(&n->nr_slabs));
3049 spin_unlock_irqrestore(&n->list_lock, flags);
3053 static long validate_slab_cache(struct kmem_cache *s)
3056 unsigned long count = 0;
3057 unsigned long *map = kmalloc(BITS_TO_LONGS(s->objects) *
3058 sizeof(unsigned long), GFP_KERNEL);
3064 for_each_node_state(node, N_NORMAL_MEMORY) {
3065 struct kmem_cache_node *n = get_node(s, node);
3067 count += validate_slab_node(s, n, map);
3073 #ifdef SLUB_RESILIENCY_TEST
3074 static void resiliency_test(void)
3078 printk(KERN_ERR "SLUB resiliency testing\n");
3079 printk(KERN_ERR "-----------------------\n");
3080 printk(KERN_ERR "A. Corruption after allocation\n");
3082 p = kzalloc(16, GFP_KERNEL);
3084 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
3085 " 0x12->0x%p\n\n", p + 16);
3087 validate_slab_cache(kmalloc_caches + 4);
3089 /* Hmmm... The next two are dangerous */
3090 p = kzalloc(32, GFP_KERNEL);
3091 p[32 + sizeof(void *)] = 0x34;
3092 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
3093 " 0x34 -> -0x%p\n", p);
3094 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
3096 validate_slab_cache(kmalloc_caches + 5);
3097 p = kzalloc(64, GFP_KERNEL);
3098 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
3100 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
3102 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
3103 validate_slab_cache(kmalloc_caches + 6);
3105 printk(KERN_ERR "\nB. Corruption after free\n");
3106 p = kzalloc(128, GFP_KERNEL);
3109 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
3110 validate_slab_cache(kmalloc_caches + 7);
3112 p = kzalloc(256, GFP_KERNEL);
3115 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
3116 validate_slab_cache(kmalloc_caches + 8);
3118 p = kzalloc(512, GFP_KERNEL);
3121 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
3122 validate_slab_cache(kmalloc_caches + 9);
3125 static void resiliency_test(void) {};
3129 * Generate lists of code addresses where slabcache objects are allocated
3134 unsigned long count;
3147 unsigned long count;
3148 struct location *loc;
3151 static void free_loc_track(struct loc_track *t)
3154 free_pages((unsigned long)t->loc,
3155 get_order(sizeof(struct location) * t->max));
3158 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3163 order = get_order(sizeof(struct location) * max);
3165 l = (void *)__get_free_pages(flags, order);
3170 memcpy(l, t->loc, sizeof(struct location) * t->count);
3178 static int add_location(struct loc_track *t, struct kmem_cache *s,
3179 const struct track *track)
3181 long start, end, pos;
3184 unsigned long age = jiffies - track->when;
3190 pos = start + (end - start + 1) / 2;
3193 * There is nothing at "end". If we end up there
3194 * we need to add something to before end.
3199 caddr = t->loc[pos].addr;
3200 if (track->addr == caddr) {
3206 if (age < l->min_time)
3208 if (age > l->max_time)
3211 if (track->pid < l->min_pid)
3212 l->min_pid = track->pid;
3213 if (track->pid > l->max_pid)
3214 l->max_pid = track->pid;
3216 cpu_set(track->cpu, l->cpus);
3218 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3222 if (track->addr < caddr)
3229 * Not found. Insert new tracking element.
3231 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3237 (t->count - pos) * sizeof(struct location));
3240 l->addr = track->addr;
3244 l->min_pid = track->pid;
3245 l->max_pid = track->pid;
3246 cpus_clear(l->cpus);
3247 cpu_set(track->cpu, l->cpus);
3248 nodes_clear(l->nodes);
3249 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3253 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3254 struct page *page, enum track_item alloc)
3256 void *addr = page_address(page);
3257 DECLARE_BITMAP(map, s->objects);
3260 bitmap_zero(map, s->objects);
3261 for_each_free_object(p, s, page->freelist)
3262 set_bit(slab_index(p, s, addr), map);
3264 for_each_object(p, s, addr)
3265 if (!test_bit(slab_index(p, s, addr), map))
3266 add_location(t, s, get_track(s, p, alloc));
3269 static int list_locations(struct kmem_cache *s, char *buf,
3270 enum track_item alloc)
3274 struct loc_track t = { 0, 0, NULL };
3277 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3279 return sprintf(buf, "Out of memory\n");
3281 /* Push back cpu slabs */
3284 for_each_node_state(node, N_NORMAL_MEMORY) {
3285 struct kmem_cache_node *n = get_node(s, node);
3286 unsigned long flags;
3289 if (!atomic_long_read(&n->nr_slabs))
3292 spin_lock_irqsave(&n->list_lock, flags);
3293 list_for_each_entry(page, &n->partial, lru)
3294 process_slab(&t, s, page, alloc);
3295 list_for_each_entry(page, &n->full, lru)
3296 process_slab(&t, s, page, alloc);
3297 spin_unlock_irqrestore(&n->list_lock, flags);
3300 for (i = 0; i < t.count; i++) {
3301 struct location *l = &t.loc[i];
3303 if (n > PAGE_SIZE - 100)
3305 n += sprintf(buf + n, "%7ld ", l->count);
3308 n += sprint_symbol(buf + n, (unsigned long)l->addr);
3310 n += sprintf(buf + n, "<not-available>");
3312 if (l->sum_time != l->min_time) {
3313 unsigned long remainder;
3315 n += sprintf(buf + n, " age=%ld/%ld/%ld",
3317 div_long_long_rem(l->sum_time, l->count, &remainder),
3320 n += sprintf(buf + n, " age=%ld",
3323 if (l->min_pid != l->max_pid)
3324 n += sprintf(buf + n, " pid=%ld-%ld",
3325 l->min_pid, l->max_pid);
3327 n += sprintf(buf + n, " pid=%ld",
3330 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3331 n < PAGE_SIZE - 60) {
3332 n += sprintf(buf + n, " cpus=");
3333 n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3337 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3338 n < PAGE_SIZE - 60) {
3339 n += sprintf(buf + n, " nodes=");
3340 n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3344 n += sprintf(buf + n, "\n");
3349 n += sprintf(buf, "No data\n");
3353 static unsigned long count_partial(struct kmem_cache_node *n)
3355 unsigned long flags;
3356 unsigned long x = 0;
3359 spin_lock_irqsave(&n->list_lock, flags);
3360 list_for_each_entry(page, &n->partial, lru)
3362 spin_unlock_irqrestore(&n->list_lock, flags);
3366 enum slab_stat_type {
3373 #define SO_FULL (1 << SL_FULL)
3374 #define SO_PARTIAL (1 << SL_PARTIAL)
3375 #define SO_CPU (1 << SL_CPU)
3376 #define SO_OBJECTS (1 << SL_OBJECTS)
3378 static unsigned long slab_objects(struct kmem_cache *s,
3379 char *buf, unsigned long flags)
3381 unsigned long total = 0;
3385 unsigned long *nodes;
3386 unsigned long *per_cpu;
3388 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3389 per_cpu = nodes + nr_node_ids;
3391 for_each_possible_cpu(cpu) {
3394 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3404 if (flags & SO_CPU) {
3407 if (flags & SO_OBJECTS)
3418 for_each_node_state(node, N_NORMAL_MEMORY) {
3419 struct kmem_cache_node *n = get_node(s, node);
3421 if (flags & SO_PARTIAL) {
3422 if (flags & SO_OBJECTS)
3423 x = count_partial(n);
3430 if (flags & SO_FULL) {
3431 int full_slabs = atomic_long_read(&n->nr_slabs)
3435 if (flags & SO_OBJECTS)
3436 x = full_slabs * s->objects;
3444 x = sprintf(buf, "%lu", total);
3446 for_each_node_state(node, N_NORMAL_MEMORY)
3448 x += sprintf(buf + x, " N%d=%lu",
3452 return x + sprintf(buf + x, "\n");
3455 static int any_slab_objects(struct kmem_cache *s)
3460 for_each_possible_cpu(cpu) {
3461 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3467 for_each_online_node(node) {
3468 struct kmem_cache_node *n = get_node(s, node);
3473 if (n->nr_partial || atomic_long_read(&n->nr_slabs))
3479 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3480 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3482 struct slab_attribute {
3483 struct attribute attr;
3484 ssize_t (*show)(struct kmem_cache *s, char *buf);
3485 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3488 #define SLAB_ATTR_RO(_name) \
3489 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3491 #define SLAB_ATTR(_name) \
3492 static struct slab_attribute _name##_attr = \
3493 __ATTR(_name, 0644, _name##_show, _name##_store)
3495 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3497 return sprintf(buf, "%d\n", s->size);
3499 SLAB_ATTR_RO(slab_size);
3501 static ssize_t align_show(struct kmem_cache *s, char *buf)
3503 return sprintf(buf, "%d\n", s->align);
3505 SLAB_ATTR_RO(align);
3507 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3509 return sprintf(buf, "%d\n", s->objsize);
3511 SLAB_ATTR_RO(object_size);
3513 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3515 return sprintf(buf, "%d\n", s->objects);
3517 SLAB_ATTR_RO(objs_per_slab);
3519 static ssize_t order_show(struct kmem_cache *s, char *buf)
3521 return sprintf(buf, "%d\n", s->order);
3523 SLAB_ATTR_RO(order);
3525 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3528 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3530 return n + sprintf(buf + n, "\n");
3536 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3538 return sprintf(buf, "%d\n", s->refcount - 1);
3540 SLAB_ATTR_RO(aliases);
3542 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3544 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3546 SLAB_ATTR_RO(slabs);
3548 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3550 return slab_objects(s, buf, SO_PARTIAL);
3552 SLAB_ATTR_RO(partial);
3554 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3556 return slab_objects(s, buf, SO_CPU);
3558 SLAB_ATTR_RO(cpu_slabs);
3560 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3562 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3564 SLAB_ATTR_RO(objects);
3566 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3568 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3571 static ssize_t sanity_checks_store(struct kmem_cache *s,
3572 const char *buf, size_t length)
3574 s->flags &= ~SLAB_DEBUG_FREE;
3576 s->flags |= SLAB_DEBUG_FREE;
3579 SLAB_ATTR(sanity_checks);
3581 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3583 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3586 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3589 s->flags &= ~SLAB_TRACE;
3591 s->flags |= SLAB_TRACE;
3596 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3598 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3601 static ssize_t reclaim_account_store(struct kmem_cache *s,
3602 const char *buf, size_t length)
3604 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3606 s->flags |= SLAB_RECLAIM_ACCOUNT;
3609 SLAB_ATTR(reclaim_account);
3611 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3613 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3615 SLAB_ATTR_RO(hwcache_align);
3617 #ifdef CONFIG_ZONE_DMA
3618 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3620 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3622 SLAB_ATTR_RO(cache_dma);
3625 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3627 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3629 SLAB_ATTR_RO(destroy_by_rcu);
3631 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3633 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3636 static ssize_t red_zone_store(struct kmem_cache *s,
3637 const char *buf, size_t length)
3639 if (any_slab_objects(s))
3642 s->flags &= ~SLAB_RED_ZONE;
3644 s->flags |= SLAB_RED_ZONE;
3648 SLAB_ATTR(red_zone);
3650 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3652 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3655 static ssize_t poison_store(struct kmem_cache *s,
3656 const char *buf, size_t length)
3658 if (any_slab_objects(s))
3661 s->flags &= ~SLAB_POISON;
3663 s->flags |= SLAB_POISON;
3669 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3671 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3674 static ssize_t store_user_store(struct kmem_cache *s,
3675 const char *buf, size_t length)
3677 if (any_slab_objects(s))
3680 s->flags &= ~SLAB_STORE_USER;
3682 s->flags |= SLAB_STORE_USER;
3686 SLAB_ATTR(store_user);
3688 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3693 static ssize_t validate_store(struct kmem_cache *s,
3694 const char *buf, size_t length)
3698 if (buf[0] == '1') {
3699 ret = validate_slab_cache(s);
3705 SLAB_ATTR(validate);
3707 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3712 static ssize_t shrink_store(struct kmem_cache *s,
3713 const char *buf, size_t length)
3715 if (buf[0] == '1') {
3716 int rc = kmem_cache_shrink(s);
3726 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3728 if (!(s->flags & SLAB_STORE_USER))
3730 return list_locations(s, buf, TRACK_ALLOC);
3732 SLAB_ATTR_RO(alloc_calls);
3734 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3736 if (!(s->flags & SLAB_STORE_USER))
3738 return list_locations(s, buf, TRACK_FREE);
3740 SLAB_ATTR_RO(free_calls);
3743 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3745 return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3748 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3749 const char *buf, size_t length)
3751 int n = simple_strtoul(buf, NULL, 10);
3754 s->defrag_ratio = n * 10;
3757 SLAB_ATTR(defrag_ratio);
3760 static struct attribute * slab_attrs[] = {
3761 &slab_size_attr.attr,
3762 &object_size_attr.attr,
3763 &objs_per_slab_attr.attr,
3768 &cpu_slabs_attr.attr,
3772 &sanity_checks_attr.attr,
3774 &hwcache_align_attr.attr,
3775 &reclaim_account_attr.attr,
3776 &destroy_by_rcu_attr.attr,
3777 &red_zone_attr.attr,
3779 &store_user_attr.attr,
3780 &validate_attr.attr,
3782 &alloc_calls_attr.attr,
3783 &free_calls_attr.attr,
3784 #ifdef CONFIG_ZONE_DMA
3785 &cache_dma_attr.attr,
3788 &defrag_ratio_attr.attr,
3793 static struct attribute_group slab_attr_group = {
3794 .attrs = slab_attrs,
3797 static ssize_t slab_attr_show(struct kobject *kobj,
3798 struct attribute *attr,
3801 struct slab_attribute *attribute;
3802 struct kmem_cache *s;
3805 attribute = to_slab_attr(attr);
3808 if (!attribute->show)
3811 err = attribute->show(s, buf);
3816 static ssize_t slab_attr_store(struct kobject *kobj,
3817 struct attribute *attr,
3818 const char *buf, size_t len)
3820 struct slab_attribute *attribute;
3821 struct kmem_cache *s;
3824 attribute = to_slab_attr(attr);
3827 if (!attribute->store)
3830 err = attribute->store(s, buf, len);
3835 static struct sysfs_ops slab_sysfs_ops = {
3836 .show = slab_attr_show,
3837 .store = slab_attr_store,
3840 static struct kobj_type slab_ktype = {
3841 .sysfs_ops = &slab_sysfs_ops,
3844 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3846 struct kobj_type *ktype = get_ktype(kobj);
3848 if (ktype == &slab_ktype)
3853 static struct kset_uevent_ops slab_uevent_ops = {
3854 .filter = uevent_filter,
3857 static decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3859 #define ID_STR_LENGTH 64
3861 /* Create a unique string id for a slab cache:
3863 * :[flags-]size:[memory address of kmemcache]
3865 static char *create_unique_id(struct kmem_cache *s)
3867 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3874 * First flags affecting slabcache operations. We will only
3875 * get here for aliasable slabs so we do not need to support
3876 * too many flags. The flags here must cover all flags that
3877 * are matched during merging to guarantee that the id is
3880 if (s->flags & SLAB_CACHE_DMA)
3882 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3884 if (s->flags & SLAB_DEBUG_FREE)
3888 p += sprintf(p, "%07d", s->size);
3889 BUG_ON(p > name + ID_STR_LENGTH - 1);
3893 static int sysfs_slab_add(struct kmem_cache *s)
3899 if (slab_state < SYSFS)
3900 /* Defer until later */
3903 unmergeable = slab_unmergeable(s);
3906 * Slabcache can never be merged so we can use the name proper.
3907 * This is typically the case for debug situations. In that
3908 * case we can catch duplicate names easily.
3910 sysfs_remove_link(&slab_subsys.kobj, s->name);
3914 * Create a unique name for the slab as a target
3917 name = create_unique_id(s);
3920 kobj_set_kset_s(s, slab_subsys);
3921 kobject_set_name(&s->kobj, name);
3922 kobject_init(&s->kobj);
3923 err = kobject_add(&s->kobj);
3927 err = sysfs_create_group(&s->kobj, &slab_attr_group);
3930 kobject_uevent(&s->kobj, KOBJ_ADD);
3932 /* Setup first alias */
3933 sysfs_slab_alias(s, s->name);
3939 static void sysfs_slab_remove(struct kmem_cache *s)
3941 kobject_uevent(&s->kobj, KOBJ_REMOVE);
3942 kobject_del(&s->kobj);
3946 * Need to buffer aliases during bootup until sysfs becomes
3947 * available lest we loose that information.
3949 struct saved_alias {
3950 struct kmem_cache *s;
3952 struct saved_alias *next;
3955 static struct saved_alias *alias_list;
3957 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3959 struct saved_alias *al;
3961 if (slab_state == SYSFS) {
3963 * If we have a leftover link then remove it.
3965 sysfs_remove_link(&slab_subsys.kobj, name);
3966 return sysfs_create_link(&slab_subsys.kobj,
3970 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3976 al->next = alias_list;
3981 static int __init slab_sysfs_init(void)
3983 struct kmem_cache *s;
3986 err = subsystem_register(&slab_subsys);
3988 printk(KERN_ERR "Cannot register slab subsystem.\n");
3994 list_for_each_entry(s, &slab_caches, list) {
3995 err = sysfs_slab_add(s);
3997 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
3998 " to sysfs\n", s->name);
4001 while (alias_list) {
4002 struct saved_alias *al = alias_list;
4004 alias_list = alias_list->next;
4005 err = sysfs_slab_alias(al->s, al->name);
4007 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
4008 " %s to sysfs\n", s->name);
4016 __initcall(slab_sysfs_init);