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 or atomic operatios
6 * and only uses a centralized lock to manage a pool of partial slabs.
8 * (C) 2007 SGI, Christoph Lameter
9 * (C) 2011 Linux Foundation, Christoph Lameter
13 #include <linux/swap.h> /* struct reclaim_state */
14 #include <linux/module.h>
15 #include <linux/bit_spinlock.h>
16 #include <linux/interrupt.h>
17 #include <linux/bitops.h>
18 #include <linux/slab.h>
20 #include <linux/proc_fs.h>
21 #include <linux/seq_file.h>
22 #include <linux/kmemcheck.h>
23 #include <linux/cpu.h>
24 #include <linux/cpuset.h>
25 #include <linux/mempolicy.h>
26 #include <linux/ctype.h>
27 #include <linux/debugobjects.h>
28 #include <linux/kallsyms.h>
29 #include <linux/memory.h>
30 #include <linux/math64.h>
31 #include <linux/fault-inject.h>
32 #include <linux/stacktrace.h>
33 #include <linux/prefetch.h>
35 #include <trace/events/kmem.h>
39 * 1. slab_mutex (Global Mutex)
41 * 3. slab_lock(page) (Only on some arches and for debugging)
45 * The role of the slab_mutex is to protect the list of all the slabs
46 * and to synchronize major metadata changes to slab cache structures.
48 * The slab_lock is only used for debugging and on arches that do not
49 * have the ability to do a cmpxchg_double. It only protects the second
50 * double word in the page struct. Meaning
51 * A. page->freelist -> List of object free in a page
52 * B. page->counters -> Counters of objects
53 * C. page->frozen -> frozen state
55 * If a slab is frozen then it is exempt from list management. It is not
56 * on any list. The processor that froze the slab is the one who can
57 * perform list operations on the page. Other processors may put objects
58 * onto the freelist but the processor that froze the slab is the only
59 * one that can retrieve the objects from the page's freelist.
61 * The list_lock protects the partial and full list on each node and
62 * the partial slab counter. If taken then no new slabs may be added or
63 * removed from the lists nor make the number of partial slabs be modified.
64 * (Note that the total number of slabs is an atomic value that may be
65 * modified without taking the list lock).
67 * The list_lock is a centralized lock and thus we avoid taking it as
68 * much as possible. As long as SLUB does not have to handle partial
69 * slabs, operations can continue without any centralized lock. F.e.
70 * allocating a long series of objects that fill up slabs does not require
72 * Interrupts are disabled during allocation and deallocation in order to
73 * make the slab allocator safe to use in the context of an irq. In addition
74 * interrupts are disabled to ensure that the processor does not change
75 * while handling per_cpu slabs, due to kernel preemption.
77 * SLUB assigns one slab for allocation to each processor.
78 * Allocations only occur from these slabs called cpu slabs.
80 * Slabs with free elements are kept on a partial list and during regular
81 * operations no list for full slabs is used. If an object in a full slab is
82 * freed then the slab will show up again on the partial lists.
83 * We track full slabs for debugging purposes though because otherwise we
84 * cannot scan all objects.
86 * Slabs are freed when they become empty. Teardown and setup is
87 * minimal so we rely on the page allocators per cpu caches for
88 * fast frees and allocs.
90 * Overloading of page flags that are otherwise used for LRU management.
92 * PageActive The slab is frozen and exempt from list processing.
93 * This means that the slab is dedicated to a purpose
94 * such as satisfying allocations for a specific
95 * processor. Objects may be freed in the slab while
96 * it is frozen but slab_free will then skip the usual
97 * list operations. It is up to the processor holding
98 * the slab to integrate the slab into the slab lists
99 * when the slab is no longer needed.
101 * One use of this flag is to mark slabs that are
102 * used for allocations. Then such a slab becomes a cpu
103 * slab. The cpu slab may be equipped with an additional
104 * freelist that allows lockless access to
105 * free objects in addition to the regular freelist
106 * that requires the slab lock.
108 * PageError Slab requires special handling due to debug
109 * options set. This moves slab handling out of
110 * the fast path and disables lockless freelists.
113 #define SLAB_DEBUG_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
114 SLAB_TRACE | SLAB_DEBUG_FREE)
116 static inline int kmem_cache_debug(struct kmem_cache *s)
118 #ifdef CONFIG_SLUB_DEBUG
119 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
126 * Issues still to be resolved:
128 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
130 * - Variable sizing of the per node arrays
133 /* Enable to test recovery from slab corruption on boot */
134 #undef SLUB_RESILIENCY_TEST
136 /* Enable to log cmpxchg failures */
137 #undef SLUB_DEBUG_CMPXCHG
140 * Mininum number of partial slabs. These will be left on the partial
141 * lists even if they are empty. kmem_cache_shrink may reclaim them.
143 #define MIN_PARTIAL 5
146 * Maximum number of desirable partial slabs.
147 * The existence of more partial slabs makes kmem_cache_shrink
148 * sort the partial list by the number of objects in the.
150 #define MAX_PARTIAL 10
152 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
153 SLAB_POISON | SLAB_STORE_USER)
156 * Debugging flags that require metadata to be stored in the slab. These get
157 * disabled when slub_debug=O is used and a cache's min order increases with
160 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
163 * Set of flags that will prevent slab merging
165 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
166 SLAB_TRACE | SLAB_DESTROY_BY_RCU | SLAB_NOLEAKTRACE | \
169 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
170 SLAB_CACHE_DMA | SLAB_NOTRACK)
173 #define OO_MASK ((1 << OO_SHIFT) - 1)
174 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
176 /* Internal SLUB flags */
177 #define __OBJECT_POISON 0x80000000UL /* Poison object */
178 #define __CMPXCHG_DOUBLE 0x40000000UL /* Use cmpxchg_double */
180 static int kmem_size = sizeof(struct kmem_cache);
183 static struct notifier_block slab_notifier;
187 * Tracking user of a slab.
189 #define TRACK_ADDRS_COUNT 16
191 unsigned long addr; /* Called from address */
192 #ifdef CONFIG_STACKTRACE
193 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
195 int cpu; /* Was running on cpu */
196 int pid; /* Pid context */
197 unsigned long when; /* When did the operation occur */
200 enum track_item { TRACK_ALLOC, TRACK_FREE };
203 static int sysfs_slab_add(struct kmem_cache *);
204 static int sysfs_slab_alias(struct kmem_cache *, const char *);
205 static void sysfs_slab_remove(struct kmem_cache *);
208 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
209 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
211 static inline void sysfs_slab_remove(struct kmem_cache *s)
219 static inline void stat(const struct kmem_cache *s, enum stat_item si)
221 #ifdef CONFIG_SLUB_STATS
222 __this_cpu_inc(s->cpu_slab->stat[si]);
226 /********************************************************************
227 * Core slab cache functions
228 *******************************************************************/
230 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
232 return s->node[node];
235 /* Verify that a pointer has an address that is valid within a slab page */
236 static inline int check_valid_pointer(struct kmem_cache *s,
237 struct page *page, const void *object)
244 base = page_address(page);
245 if (object < base || object >= base + page->objects * s->size ||
246 (object - base) % s->size) {
253 static inline void *get_freepointer(struct kmem_cache *s, void *object)
255 return *(void **)(object + s->offset);
258 static void prefetch_freepointer(const struct kmem_cache *s, void *object)
260 prefetch(object + s->offset);
263 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
267 #ifdef CONFIG_DEBUG_PAGEALLOC
268 probe_kernel_read(&p, (void **)(object + s->offset), sizeof(p));
270 p = get_freepointer(s, object);
275 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
277 *(void **)(object + s->offset) = fp;
280 /* Loop over all objects in a slab */
281 #define for_each_object(__p, __s, __addr, __objects) \
282 for (__p = (__addr); __p < (__addr) + (__objects) * (__s)->size;\
285 /* Determine object index from a given position */
286 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
288 return (p - addr) / s->size;
291 static inline size_t slab_ksize(const struct kmem_cache *s)
293 #ifdef CONFIG_SLUB_DEBUG
295 * Debugging requires use of the padding between object
296 * and whatever may come after it.
298 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
299 return s->object_size;
303 * If we have the need to store the freelist pointer
304 * back there or track user information then we can
305 * only use the space before that information.
307 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
310 * Else we can use all the padding etc for the allocation
315 static inline int order_objects(int order, unsigned long size, int reserved)
317 return ((PAGE_SIZE << order) - reserved) / size;
320 static inline struct kmem_cache_order_objects oo_make(int order,
321 unsigned long size, int reserved)
323 struct kmem_cache_order_objects x = {
324 (order << OO_SHIFT) + order_objects(order, size, reserved)
330 static inline int oo_order(struct kmem_cache_order_objects x)
332 return x.x >> OO_SHIFT;
335 static inline int oo_objects(struct kmem_cache_order_objects x)
337 return x.x & OO_MASK;
341 * Per slab locking using the pagelock
343 static __always_inline void slab_lock(struct page *page)
345 bit_spin_lock(PG_locked, &page->flags);
348 static __always_inline void slab_unlock(struct page *page)
350 __bit_spin_unlock(PG_locked, &page->flags);
353 /* Interrupts must be disabled (for the fallback code to work right) */
354 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
355 void *freelist_old, unsigned long counters_old,
356 void *freelist_new, unsigned long counters_new,
359 VM_BUG_ON(!irqs_disabled());
360 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
361 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
362 if (s->flags & __CMPXCHG_DOUBLE) {
363 if (cmpxchg_double(&page->freelist, &page->counters,
364 freelist_old, counters_old,
365 freelist_new, counters_new))
371 if (page->freelist == freelist_old && page->counters == counters_old) {
372 page->freelist = freelist_new;
373 page->counters = counters_new;
381 stat(s, CMPXCHG_DOUBLE_FAIL);
383 #ifdef SLUB_DEBUG_CMPXCHG
384 printk(KERN_INFO "%s %s: cmpxchg double redo ", n, s->name);
390 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
391 void *freelist_old, unsigned long counters_old,
392 void *freelist_new, unsigned long counters_new,
395 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
396 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
397 if (s->flags & __CMPXCHG_DOUBLE) {
398 if (cmpxchg_double(&page->freelist, &page->counters,
399 freelist_old, counters_old,
400 freelist_new, counters_new))
407 local_irq_save(flags);
409 if (page->freelist == freelist_old && page->counters == counters_old) {
410 page->freelist = freelist_new;
411 page->counters = counters_new;
413 local_irq_restore(flags);
417 local_irq_restore(flags);
421 stat(s, CMPXCHG_DOUBLE_FAIL);
423 #ifdef SLUB_DEBUG_CMPXCHG
424 printk(KERN_INFO "%s %s: cmpxchg double redo ", n, s->name);
430 #ifdef CONFIG_SLUB_DEBUG
432 * Determine a map of object in use on a page.
434 * Node listlock must be held to guarantee that the page does
435 * not vanish from under us.
437 static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
440 void *addr = page_address(page);
442 for (p = page->freelist; p; p = get_freepointer(s, p))
443 set_bit(slab_index(p, s, addr), map);
449 #ifdef CONFIG_SLUB_DEBUG_ON
450 static int slub_debug = DEBUG_DEFAULT_FLAGS;
452 static int slub_debug;
455 static char *slub_debug_slabs;
456 static int disable_higher_order_debug;
461 static void print_section(char *text, u8 *addr, unsigned int length)
463 print_hex_dump(KERN_ERR, text, DUMP_PREFIX_ADDRESS, 16, 1, addr,
467 static struct track *get_track(struct kmem_cache *s, void *object,
468 enum track_item alloc)
473 p = object + s->offset + sizeof(void *);
475 p = object + s->inuse;
480 static void set_track(struct kmem_cache *s, void *object,
481 enum track_item alloc, unsigned long addr)
483 struct track *p = get_track(s, object, alloc);
486 #ifdef CONFIG_STACKTRACE
487 struct stack_trace trace;
490 trace.nr_entries = 0;
491 trace.max_entries = TRACK_ADDRS_COUNT;
492 trace.entries = p->addrs;
494 save_stack_trace(&trace);
496 /* See rant in lockdep.c */
497 if (trace.nr_entries != 0 &&
498 trace.entries[trace.nr_entries - 1] == ULONG_MAX)
501 for (i = trace.nr_entries; i < TRACK_ADDRS_COUNT; i++)
505 p->cpu = smp_processor_id();
506 p->pid = current->pid;
509 memset(p, 0, sizeof(struct track));
512 static void init_tracking(struct kmem_cache *s, void *object)
514 if (!(s->flags & SLAB_STORE_USER))
517 set_track(s, object, TRACK_FREE, 0UL);
518 set_track(s, object, TRACK_ALLOC, 0UL);
521 static void print_track(const char *s, struct track *t)
526 printk(KERN_ERR "INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
527 s, (void *)t->addr, jiffies - t->when, t->cpu, t->pid);
528 #ifdef CONFIG_STACKTRACE
531 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
533 printk(KERN_ERR "\t%pS\n", (void *)t->addrs[i]);
540 static void print_tracking(struct kmem_cache *s, void *object)
542 if (!(s->flags & SLAB_STORE_USER))
545 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
546 print_track("Freed", get_track(s, object, TRACK_FREE));
549 static void print_page_info(struct page *page)
551 printk(KERN_ERR "INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
552 page, page->objects, page->inuse, page->freelist, page->flags);
556 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
562 vsnprintf(buf, sizeof(buf), fmt, args);
564 printk(KERN_ERR "========================================"
565 "=====================================\n");
566 printk(KERN_ERR "BUG %s (%s): %s\n", s->name, print_tainted(), buf);
567 printk(KERN_ERR "----------------------------------------"
568 "-------------------------------------\n\n");
571 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
577 vsnprintf(buf, sizeof(buf), fmt, args);
579 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
582 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
584 unsigned int off; /* Offset of last byte */
585 u8 *addr = page_address(page);
587 print_tracking(s, p);
589 print_page_info(page);
591 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
592 p, p - addr, get_freepointer(s, p));
595 print_section("Bytes b4 ", p - 16, 16);
597 print_section("Object ", p, min_t(unsigned long, s->object_size,
599 if (s->flags & SLAB_RED_ZONE)
600 print_section("Redzone ", p + s->object_size,
601 s->inuse - s->object_size);
604 off = s->offset + sizeof(void *);
608 if (s->flags & SLAB_STORE_USER)
609 off += 2 * sizeof(struct track);
612 /* Beginning of the filler is the free pointer */
613 print_section("Padding ", p + off, s->size - off);
618 static void object_err(struct kmem_cache *s, struct page *page,
619 u8 *object, char *reason)
621 slab_bug(s, "%s", reason);
622 print_trailer(s, page, object);
625 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
631 vsnprintf(buf, sizeof(buf), fmt, args);
633 slab_bug(s, "%s", buf);
634 print_page_info(page);
638 static void init_object(struct kmem_cache *s, void *object, u8 val)
642 if (s->flags & __OBJECT_POISON) {
643 memset(p, POISON_FREE, s->object_size - 1);
644 p[s->object_size - 1] = POISON_END;
647 if (s->flags & SLAB_RED_ZONE)
648 memset(p + s->object_size, val, s->inuse - s->object_size);
651 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
652 void *from, void *to)
654 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
655 memset(from, data, to - from);
658 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
659 u8 *object, char *what,
660 u8 *start, unsigned int value, unsigned int bytes)
665 fault = memchr_inv(start, value, bytes);
670 while (end > fault && end[-1] == value)
673 slab_bug(s, "%s overwritten", what);
674 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
675 fault, end - 1, fault[0], value);
676 print_trailer(s, page, object);
678 restore_bytes(s, what, value, fault, end);
686 * Bytes of the object to be managed.
687 * If the freepointer may overlay the object then the free
688 * pointer is the first word of the object.
690 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
693 * object + s->object_size
694 * Padding to reach word boundary. This is also used for Redzoning.
695 * Padding is extended by another word if Redzoning is enabled and
696 * object_size == inuse.
698 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
699 * 0xcc (RED_ACTIVE) for objects in use.
702 * Meta data starts here.
704 * A. Free pointer (if we cannot overwrite object on free)
705 * B. Tracking data for SLAB_STORE_USER
706 * C. Padding to reach required alignment boundary or at mininum
707 * one word if debugging is on to be able to detect writes
708 * before the word boundary.
710 * Padding is done using 0x5a (POISON_INUSE)
713 * Nothing is used beyond s->size.
715 * If slabcaches are merged then the object_size and inuse boundaries are mostly
716 * ignored. And therefore no slab options that rely on these boundaries
717 * may be used with merged slabcaches.
720 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
722 unsigned long off = s->inuse; /* The end of info */
725 /* Freepointer is placed after the object. */
726 off += sizeof(void *);
728 if (s->flags & SLAB_STORE_USER)
729 /* We also have user information there */
730 off += 2 * sizeof(struct track);
735 return check_bytes_and_report(s, page, p, "Object padding",
736 p + off, POISON_INUSE, s->size - off);
739 /* Check the pad bytes at the end of a slab page */
740 static int slab_pad_check(struct kmem_cache *s, struct page *page)
748 if (!(s->flags & SLAB_POISON))
751 start = page_address(page);
752 length = (PAGE_SIZE << compound_order(page)) - s->reserved;
753 end = start + length;
754 remainder = length % s->size;
758 fault = memchr_inv(end - remainder, POISON_INUSE, remainder);
761 while (end > fault && end[-1] == POISON_INUSE)
764 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
765 print_section("Padding ", end - remainder, remainder);
767 restore_bytes(s, "slab padding", POISON_INUSE, end - remainder, end);
771 static int check_object(struct kmem_cache *s, struct page *page,
772 void *object, u8 val)
775 u8 *endobject = object + s->object_size;
777 if (s->flags & SLAB_RED_ZONE) {
778 if (!check_bytes_and_report(s, page, object, "Redzone",
779 endobject, val, s->inuse - s->object_size))
782 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) {
783 check_bytes_and_report(s, page, p, "Alignment padding",
784 endobject, POISON_INUSE, s->inuse - s->object_size);
788 if (s->flags & SLAB_POISON) {
789 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
790 (!check_bytes_and_report(s, page, p, "Poison", p,
791 POISON_FREE, s->object_size - 1) ||
792 !check_bytes_and_report(s, page, p, "Poison",
793 p + s->object_size - 1, POISON_END, 1)))
796 * check_pad_bytes cleans up on its own.
798 check_pad_bytes(s, page, p);
801 if (!s->offset && val == SLUB_RED_ACTIVE)
803 * Object and freepointer overlap. Cannot check
804 * freepointer while object is allocated.
808 /* Check free pointer validity */
809 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
810 object_err(s, page, p, "Freepointer corrupt");
812 * No choice but to zap it and thus lose the remainder
813 * of the free objects in this slab. May cause
814 * another error because the object count is now wrong.
816 set_freepointer(s, p, NULL);
822 static int check_slab(struct kmem_cache *s, struct page *page)
826 VM_BUG_ON(!irqs_disabled());
828 if (!PageSlab(page)) {
829 slab_err(s, page, "Not a valid slab page");
833 maxobj = order_objects(compound_order(page), s->size, s->reserved);
834 if (page->objects > maxobj) {
835 slab_err(s, page, "objects %u > max %u",
836 s->name, page->objects, maxobj);
839 if (page->inuse > page->objects) {
840 slab_err(s, page, "inuse %u > max %u",
841 s->name, page->inuse, page->objects);
844 /* Slab_pad_check fixes things up after itself */
845 slab_pad_check(s, page);
850 * Determine if a certain object on a page is on the freelist. Must hold the
851 * slab lock to guarantee that the chains are in a consistent state.
853 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
858 unsigned long max_objects;
861 while (fp && nr <= page->objects) {
864 if (!check_valid_pointer(s, page, fp)) {
866 object_err(s, page, object,
867 "Freechain corrupt");
868 set_freepointer(s, object, NULL);
871 slab_err(s, page, "Freepointer corrupt");
872 page->freelist = NULL;
873 page->inuse = page->objects;
874 slab_fix(s, "Freelist cleared");
880 fp = get_freepointer(s, object);
884 max_objects = order_objects(compound_order(page), s->size, s->reserved);
885 if (max_objects > MAX_OBJS_PER_PAGE)
886 max_objects = MAX_OBJS_PER_PAGE;
888 if (page->objects != max_objects) {
889 slab_err(s, page, "Wrong number of objects. Found %d but "
890 "should be %d", page->objects, max_objects);
891 page->objects = max_objects;
892 slab_fix(s, "Number of objects adjusted.");
894 if (page->inuse != page->objects - nr) {
895 slab_err(s, page, "Wrong object count. Counter is %d but "
896 "counted were %d", page->inuse, page->objects - nr);
897 page->inuse = page->objects - nr;
898 slab_fix(s, "Object count adjusted.");
900 return search == NULL;
903 static void trace(struct kmem_cache *s, struct page *page, void *object,
906 if (s->flags & SLAB_TRACE) {
907 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
909 alloc ? "alloc" : "free",
914 print_section("Object ", (void *)object, s->object_size);
921 * Hooks for other subsystems that check memory allocations. In a typical
922 * production configuration these hooks all should produce no code at all.
924 static inline int slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
926 flags &= gfp_allowed_mask;
927 lockdep_trace_alloc(flags);
928 might_sleep_if(flags & __GFP_WAIT);
930 return should_failslab(s->object_size, flags, s->flags);
933 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags, void *object)
935 flags &= gfp_allowed_mask;
936 kmemcheck_slab_alloc(s, flags, object, slab_ksize(s));
937 kmemleak_alloc_recursive(object, s->object_size, 1, s->flags, flags);
940 static inline void slab_free_hook(struct kmem_cache *s, void *x)
942 kmemleak_free_recursive(x, s->flags);
945 * Trouble is that we may no longer disable interupts in the fast path
946 * So in order to make the debug calls that expect irqs to be
947 * disabled we need to disable interrupts temporarily.
949 #if defined(CONFIG_KMEMCHECK) || defined(CONFIG_LOCKDEP)
953 local_irq_save(flags);
954 kmemcheck_slab_free(s, x, s->object_size);
955 debug_check_no_locks_freed(x, s->object_size);
956 local_irq_restore(flags);
959 if (!(s->flags & SLAB_DEBUG_OBJECTS))
960 debug_check_no_obj_freed(x, s->object_size);
964 * Tracking of fully allocated slabs for debugging purposes.
966 * list_lock must be held.
968 static void add_full(struct kmem_cache *s,
969 struct kmem_cache_node *n, struct page *page)
971 if (!(s->flags & SLAB_STORE_USER))
974 list_add(&page->lru, &n->full);
978 * list_lock must be held.
980 static void remove_full(struct kmem_cache *s, struct page *page)
982 if (!(s->flags & SLAB_STORE_USER))
985 list_del(&page->lru);
988 /* Tracking of the number of slabs for debugging purposes */
989 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
991 struct kmem_cache_node *n = get_node(s, node);
993 return atomic_long_read(&n->nr_slabs);
996 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
998 return atomic_long_read(&n->nr_slabs);
1001 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1003 struct kmem_cache_node *n = get_node(s, node);
1006 * May be called early in order to allocate a slab for the
1007 * kmem_cache_node structure. Solve the chicken-egg
1008 * dilemma by deferring the increment of the count during
1009 * bootstrap (see early_kmem_cache_node_alloc).
1012 atomic_long_inc(&n->nr_slabs);
1013 atomic_long_add(objects, &n->total_objects);
1016 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1018 struct kmem_cache_node *n = get_node(s, node);
1020 atomic_long_dec(&n->nr_slabs);
1021 atomic_long_sub(objects, &n->total_objects);
1024 /* Object debug checks for alloc/free paths */
1025 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1028 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1031 init_object(s, object, SLUB_RED_INACTIVE);
1032 init_tracking(s, object);
1035 static noinline int alloc_debug_processing(struct kmem_cache *s, struct page *page,
1036 void *object, unsigned long addr)
1038 if (!check_slab(s, page))
1041 if (!check_valid_pointer(s, page, object)) {
1042 object_err(s, page, object, "Freelist Pointer check fails");
1046 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1049 /* Success perform special debug activities for allocs */
1050 if (s->flags & SLAB_STORE_USER)
1051 set_track(s, object, TRACK_ALLOC, addr);
1052 trace(s, page, object, 1);
1053 init_object(s, object, SLUB_RED_ACTIVE);
1057 if (PageSlab(page)) {
1059 * If this is a slab page then lets do the best we can
1060 * to avoid issues in the future. Marking all objects
1061 * as used avoids touching the remaining objects.
1063 slab_fix(s, "Marking all objects used");
1064 page->inuse = page->objects;
1065 page->freelist = NULL;
1070 static noinline int free_debug_processing(struct kmem_cache *s,
1071 struct page *page, void *object, unsigned long addr)
1073 unsigned long flags;
1076 local_irq_save(flags);
1079 if (!check_slab(s, page))
1082 if (!check_valid_pointer(s, page, object)) {
1083 slab_err(s, page, "Invalid object pointer 0x%p", object);
1087 if (on_freelist(s, page, object)) {
1088 object_err(s, page, object, "Object already free");
1092 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1095 if (unlikely(s != page->slab)) {
1096 if (!PageSlab(page)) {
1097 slab_err(s, page, "Attempt to free object(0x%p) "
1098 "outside of slab", object);
1099 } else if (!page->slab) {
1101 "SLUB <none>: no slab for object 0x%p.\n",
1105 object_err(s, page, object,
1106 "page slab pointer corrupt.");
1110 if (s->flags & SLAB_STORE_USER)
1111 set_track(s, object, TRACK_FREE, addr);
1112 trace(s, page, object, 0);
1113 init_object(s, object, SLUB_RED_INACTIVE);
1117 local_irq_restore(flags);
1121 slab_fix(s, "Object at 0x%p not freed", object);
1125 static int __init setup_slub_debug(char *str)
1127 slub_debug = DEBUG_DEFAULT_FLAGS;
1128 if (*str++ != '=' || !*str)
1130 * No options specified. Switch on full debugging.
1136 * No options but restriction on slabs. This means full
1137 * debugging for slabs matching a pattern.
1141 if (tolower(*str) == 'o') {
1143 * Avoid enabling debugging on caches if its minimum order
1144 * would increase as a result.
1146 disable_higher_order_debug = 1;
1153 * Switch off all debugging measures.
1158 * Determine which debug features should be switched on
1160 for (; *str && *str != ','; str++) {
1161 switch (tolower(*str)) {
1163 slub_debug |= SLAB_DEBUG_FREE;
1166 slub_debug |= SLAB_RED_ZONE;
1169 slub_debug |= SLAB_POISON;
1172 slub_debug |= SLAB_STORE_USER;
1175 slub_debug |= SLAB_TRACE;
1178 slub_debug |= SLAB_FAILSLAB;
1181 printk(KERN_ERR "slub_debug option '%c' "
1182 "unknown. skipped\n", *str);
1188 slub_debug_slabs = str + 1;
1193 __setup("slub_debug", setup_slub_debug);
1195 static unsigned long kmem_cache_flags(unsigned long object_size,
1196 unsigned long flags, const char *name,
1197 void (*ctor)(void *))
1200 * Enable debugging if selected on the kernel commandline.
1202 if (slub_debug && (!slub_debug_slabs ||
1203 !strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs))))
1204 flags |= slub_debug;
1209 static inline void setup_object_debug(struct kmem_cache *s,
1210 struct page *page, void *object) {}
1212 static inline int alloc_debug_processing(struct kmem_cache *s,
1213 struct page *page, void *object, unsigned long addr) { return 0; }
1215 static inline int free_debug_processing(struct kmem_cache *s,
1216 struct page *page, void *object, unsigned long addr) { return 0; }
1218 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1220 static inline int check_object(struct kmem_cache *s, struct page *page,
1221 void *object, u8 val) { return 1; }
1222 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1223 struct page *page) {}
1224 static inline void remove_full(struct kmem_cache *s, struct page *page) {}
1225 static inline unsigned long kmem_cache_flags(unsigned long object_size,
1226 unsigned long flags, const char *name,
1227 void (*ctor)(void *))
1231 #define slub_debug 0
1233 #define disable_higher_order_debug 0
1235 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1237 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1239 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1241 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1244 static inline int slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
1247 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags,
1250 static inline void slab_free_hook(struct kmem_cache *s, void *x) {}
1252 #endif /* CONFIG_SLUB_DEBUG */
1255 * Slab allocation and freeing
1257 static inline struct page *alloc_slab_page(gfp_t flags, int node,
1258 struct kmem_cache_order_objects oo)
1260 int order = oo_order(oo);
1262 flags |= __GFP_NOTRACK;
1264 if (node == NUMA_NO_NODE)
1265 return alloc_pages(flags, order);
1267 return alloc_pages_exact_node(node, flags, order);
1270 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1273 struct kmem_cache_order_objects oo = s->oo;
1276 flags &= gfp_allowed_mask;
1278 if (flags & __GFP_WAIT)
1281 flags |= s->allocflags;
1284 * Let the initial higher-order allocation fail under memory pressure
1285 * so we fall-back to the minimum order allocation.
1287 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1289 page = alloc_slab_page(alloc_gfp, node, oo);
1290 if (unlikely(!page)) {
1293 * Allocation may have failed due to fragmentation.
1294 * Try a lower order alloc if possible
1296 page = alloc_slab_page(flags, node, oo);
1299 stat(s, ORDER_FALLBACK);
1302 if (flags & __GFP_WAIT)
1303 local_irq_disable();
1308 if (kmemcheck_enabled
1309 && !(s->flags & (SLAB_NOTRACK | DEBUG_DEFAULT_FLAGS))) {
1310 int pages = 1 << oo_order(oo);
1312 kmemcheck_alloc_shadow(page, oo_order(oo), flags, node);
1315 * Objects from caches that have a constructor don't get
1316 * cleared when they're allocated, so we need to do it here.
1319 kmemcheck_mark_uninitialized_pages(page, pages);
1321 kmemcheck_mark_unallocated_pages(page, pages);
1324 page->objects = oo_objects(oo);
1325 mod_zone_page_state(page_zone(page),
1326 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1327 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1333 static void setup_object(struct kmem_cache *s, struct page *page,
1336 setup_object_debug(s, page, object);
1337 if (unlikely(s->ctor))
1341 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1348 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1350 page = allocate_slab(s,
1351 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1355 inc_slabs_node(s, page_to_nid(page), page->objects);
1357 __SetPageSlab(page);
1359 start = page_address(page);
1361 if (unlikely(s->flags & SLAB_POISON))
1362 memset(start, POISON_INUSE, PAGE_SIZE << compound_order(page));
1365 for_each_object(p, s, start, page->objects) {
1366 setup_object(s, page, last);
1367 set_freepointer(s, last, p);
1370 setup_object(s, page, last);
1371 set_freepointer(s, last, NULL);
1373 page->freelist = start;
1374 page->inuse = page->objects;
1380 static void __free_slab(struct kmem_cache *s, struct page *page)
1382 int order = compound_order(page);
1383 int pages = 1 << order;
1385 if (kmem_cache_debug(s)) {
1388 slab_pad_check(s, page);
1389 for_each_object(p, s, page_address(page),
1391 check_object(s, page, p, SLUB_RED_INACTIVE);
1394 kmemcheck_free_shadow(page, compound_order(page));
1396 mod_zone_page_state(page_zone(page),
1397 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1398 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1401 __ClearPageSlab(page);
1402 reset_page_mapcount(page);
1403 if (current->reclaim_state)
1404 current->reclaim_state->reclaimed_slab += pages;
1405 __free_pages(page, order);
1408 #define need_reserve_slab_rcu \
1409 (sizeof(((struct page *)NULL)->lru) < sizeof(struct rcu_head))
1411 static void rcu_free_slab(struct rcu_head *h)
1415 if (need_reserve_slab_rcu)
1416 page = virt_to_head_page(h);
1418 page = container_of((struct list_head *)h, struct page, lru);
1420 __free_slab(page->slab, page);
1423 static void free_slab(struct kmem_cache *s, struct page *page)
1425 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1426 struct rcu_head *head;
1428 if (need_reserve_slab_rcu) {
1429 int order = compound_order(page);
1430 int offset = (PAGE_SIZE << order) - s->reserved;
1432 VM_BUG_ON(s->reserved != sizeof(*head));
1433 head = page_address(page) + offset;
1436 * RCU free overloads the RCU head over the LRU
1438 head = (void *)&page->lru;
1441 call_rcu(head, rcu_free_slab);
1443 __free_slab(s, page);
1446 static void discard_slab(struct kmem_cache *s, struct page *page)
1448 dec_slabs_node(s, page_to_nid(page), page->objects);
1453 * Management of partially allocated slabs.
1455 * list_lock must be held.
1457 static inline void add_partial(struct kmem_cache_node *n,
1458 struct page *page, int tail)
1461 if (tail == DEACTIVATE_TO_TAIL)
1462 list_add_tail(&page->lru, &n->partial);
1464 list_add(&page->lru, &n->partial);
1468 * list_lock must be held.
1470 static inline void remove_partial(struct kmem_cache_node *n,
1473 list_del(&page->lru);
1478 * Remove slab from the partial list, freeze it and
1479 * return the pointer to the freelist.
1481 * Returns a list of objects or NULL if it fails.
1483 * Must hold list_lock since we modify the partial list.
1485 static inline void *acquire_slab(struct kmem_cache *s,
1486 struct kmem_cache_node *n, struct page *page,
1490 unsigned long counters;
1494 * Zap the freelist and set the frozen bit.
1495 * The old freelist is the list of objects for the
1496 * per cpu allocation list.
1498 freelist = page->freelist;
1499 counters = page->counters;
1500 new.counters = counters;
1502 new.inuse = page->objects;
1503 new.freelist = NULL;
1505 new.freelist = freelist;
1508 VM_BUG_ON(new.frozen);
1511 if (!__cmpxchg_double_slab(s, page,
1513 new.freelist, new.counters,
1517 remove_partial(n, page);
1522 static int put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1525 * Try to allocate a partial slab from a specific node.
1527 static void *get_partial_node(struct kmem_cache *s,
1528 struct kmem_cache_node *n, struct kmem_cache_cpu *c)
1530 struct page *page, *page2;
1531 void *object = NULL;
1534 * Racy check. If we mistakenly see no partial slabs then we
1535 * just allocate an empty slab. If we mistakenly try to get a
1536 * partial slab and there is none available then get_partials()
1539 if (!n || !n->nr_partial)
1542 spin_lock(&n->list_lock);
1543 list_for_each_entry_safe(page, page2, &n->partial, lru) {
1544 void *t = acquire_slab(s, n, page, object == NULL);
1552 stat(s, ALLOC_FROM_PARTIAL);
1554 available = page->objects - page->inuse;
1556 available = put_cpu_partial(s, page, 0);
1557 stat(s, CPU_PARTIAL_NODE);
1559 if (kmem_cache_debug(s) || available > s->cpu_partial / 2)
1563 spin_unlock(&n->list_lock);
1568 * Get a page from somewhere. Search in increasing NUMA distances.
1570 static void *get_any_partial(struct kmem_cache *s, gfp_t flags,
1571 struct kmem_cache_cpu *c)
1574 struct zonelist *zonelist;
1577 enum zone_type high_zoneidx = gfp_zone(flags);
1579 unsigned int cpuset_mems_cookie;
1582 * The defrag ratio allows a configuration of the tradeoffs between
1583 * inter node defragmentation and node local allocations. A lower
1584 * defrag_ratio increases the tendency to do local allocations
1585 * instead of attempting to obtain partial slabs from other nodes.
1587 * If the defrag_ratio is set to 0 then kmalloc() always
1588 * returns node local objects. If the ratio is higher then kmalloc()
1589 * may return off node objects because partial slabs are obtained
1590 * from other nodes and filled up.
1592 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1593 * defrag_ratio = 1000) then every (well almost) allocation will
1594 * first attempt to defrag slab caches on other nodes. This means
1595 * scanning over all nodes to look for partial slabs which may be
1596 * expensive if we do it every time we are trying to find a slab
1597 * with available objects.
1599 if (!s->remote_node_defrag_ratio ||
1600 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1604 cpuset_mems_cookie = get_mems_allowed();
1605 zonelist = node_zonelist(slab_node(), flags);
1606 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1607 struct kmem_cache_node *n;
1609 n = get_node(s, zone_to_nid(zone));
1611 if (n && cpuset_zone_allowed_hardwall(zone, flags) &&
1612 n->nr_partial > s->min_partial) {
1613 object = get_partial_node(s, n, c);
1616 * Return the object even if
1617 * put_mems_allowed indicated that
1618 * the cpuset mems_allowed was
1619 * updated in parallel. It's a
1620 * harmless race between the alloc
1621 * and the cpuset update.
1623 put_mems_allowed(cpuset_mems_cookie);
1628 } while (!put_mems_allowed(cpuset_mems_cookie));
1634 * Get a partial page, lock it and return it.
1636 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1637 struct kmem_cache_cpu *c)
1640 int searchnode = (node == NUMA_NO_NODE) ? numa_node_id() : node;
1642 object = get_partial_node(s, get_node(s, searchnode), c);
1643 if (object || node != NUMA_NO_NODE)
1646 return get_any_partial(s, flags, c);
1649 #ifdef CONFIG_PREEMPT
1651 * Calculate the next globally unique transaction for disambiguiation
1652 * during cmpxchg. The transactions start with the cpu number and are then
1653 * incremented by CONFIG_NR_CPUS.
1655 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
1658 * No preemption supported therefore also no need to check for
1664 static inline unsigned long next_tid(unsigned long tid)
1666 return tid + TID_STEP;
1669 static inline unsigned int tid_to_cpu(unsigned long tid)
1671 return tid % TID_STEP;
1674 static inline unsigned long tid_to_event(unsigned long tid)
1676 return tid / TID_STEP;
1679 static inline unsigned int init_tid(int cpu)
1684 static inline void note_cmpxchg_failure(const char *n,
1685 const struct kmem_cache *s, unsigned long tid)
1687 #ifdef SLUB_DEBUG_CMPXCHG
1688 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
1690 printk(KERN_INFO "%s %s: cmpxchg redo ", n, s->name);
1692 #ifdef CONFIG_PREEMPT
1693 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
1694 printk("due to cpu change %d -> %d\n",
1695 tid_to_cpu(tid), tid_to_cpu(actual_tid));
1698 if (tid_to_event(tid) != tid_to_event(actual_tid))
1699 printk("due to cpu running other code. Event %ld->%ld\n",
1700 tid_to_event(tid), tid_to_event(actual_tid));
1702 printk("for unknown reason: actual=%lx was=%lx target=%lx\n",
1703 actual_tid, tid, next_tid(tid));
1705 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
1708 void init_kmem_cache_cpus(struct kmem_cache *s)
1712 for_each_possible_cpu(cpu)
1713 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
1717 * Remove the cpu slab
1719 static void deactivate_slab(struct kmem_cache *s, struct page *page, void *freelist)
1721 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
1722 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1724 enum slab_modes l = M_NONE, m = M_NONE;
1726 int tail = DEACTIVATE_TO_HEAD;
1730 if (page->freelist) {
1731 stat(s, DEACTIVATE_REMOTE_FREES);
1732 tail = DEACTIVATE_TO_TAIL;
1736 * Stage one: Free all available per cpu objects back
1737 * to the page freelist while it is still frozen. Leave the
1740 * There is no need to take the list->lock because the page
1743 while (freelist && (nextfree = get_freepointer(s, freelist))) {
1745 unsigned long counters;
1748 prior = page->freelist;
1749 counters = page->counters;
1750 set_freepointer(s, freelist, prior);
1751 new.counters = counters;
1753 VM_BUG_ON(!new.frozen);
1755 } while (!__cmpxchg_double_slab(s, page,
1757 freelist, new.counters,
1758 "drain percpu freelist"));
1760 freelist = nextfree;
1764 * Stage two: Ensure that the page is unfrozen while the
1765 * list presence reflects the actual number of objects
1768 * We setup the list membership and then perform a cmpxchg
1769 * with the count. If there is a mismatch then the page
1770 * is not unfrozen but the page is on the wrong list.
1772 * Then we restart the process which may have to remove
1773 * the page from the list that we just put it on again
1774 * because the number of objects in the slab may have
1779 old.freelist = page->freelist;
1780 old.counters = page->counters;
1781 VM_BUG_ON(!old.frozen);
1783 /* Determine target state of the slab */
1784 new.counters = old.counters;
1787 set_freepointer(s, freelist, old.freelist);
1788 new.freelist = freelist;
1790 new.freelist = old.freelist;
1794 if (!new.inuse && n->nr_partial > s->min_partial)
1796 else if (new.freelist) {
1801 * Taking the spinlock removes the possiblity
1802 * that acquire_slab() will see a slab page that
1805 spin_lock(&n->list_lock);
1809 if (kmem_cache_debug(s) && !lock) {
1812 * This also ensures that the scanning of full
1813 * slabs from diagnostic functions will not see
1816 spin_lock(&n->list_lock);
1824 remove_partial(n, page);
1826 else if (l == M_FULL)
1828 remove_full(s, page);
1830 if (m == M_PARTIAL) {
1832 add_partial(n, page, tail);
1835 } else if (m == M_FULL) {
1837 stat(s, DEACTIVATE_FULL);
1838 add_full(s, n, page);
1844 if (!__cmpxchg_double_slab(s, page,
1845 old.freelist, old.counters,
1846 new.freelist, new.counters,
1851 spin_unlock(&n->list_lock);
1854 stat(s, DEACTIVATE_EMPTY);
1855 discard_slab(s, page);
1861 * Unfreeze all the cpu partial slabs.
1863 * This function must be called with interrupt disabled.
1865 static void unfreeze_partials(struct kmem_cache *s)
1867 struct kmem_cache_node *n = NULL, *n2 = NULL;
1868 struct kmem_cache_cpu *c = this_cpu_ptr(s->cpu_slab);
1869 struct page *page, *discard_page = NULL;
1871 while ((page = c->partial)) {
1875 c->partial = page->next;
1877 n2 = get_node(s, page_to_nid(page));
1880 spin_unlock(&n->list_lock);
1883 spin_lock(&n->list_lock);
1888 old.freelist = page->freelist;
1889 old.counters = page->counters;
1890 VM_BUG_ON(!old.frozen);
1892 new.counters = old.counters;
1893 new.freelist = old.freelist;
1897 } while (!__cmpxchg_double_slab(s, page,
1898 old.freelist, old.counters,
1899 new.freelist, new.counters,
1900 "unfreezing slab"));
1902 if (unlikely(!new.inuse && n->nr_partial > s->min_partial)) {
1903 page->next = discard_page;
1904 discard_page = page;
1906 add_partial(n, page, DEACTIVATE_TO_TAIL);
1907 stat(s, FREE_ADD_PARTIAL);
1912 spin_unlock(&n->list_lock);
1914 while (discard_page) {
1915 page = discard_page;
1916 discard_page = discard_page->next;
1918 stat(s, DEACTIVATE_EMPTY);
1919 discard_slab(s, page);
1925 * Put a page that was just frozen (in __slab_free) into a partial page
1926 * slot if available. This is done without interrupts disabled and without
1927 * preemption disabled. The cmpxchg is racy and may put the partial page
1928 * onto a random cpus partial slot.
1930 * If we did not find a slot then simply move all the partials to the
1931 * per node partial list.
1933 int put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
1935 struct page *oldpage;
1942 oldpage = this_cpu_read(s->cpu_slab->partial);
1945 pobjects = oldpage->pobjects;
1946 pages = oldpage->pages;
1947 if (drain && pobjects > s->cpu_partial) {
1948 unsigned long flags;
1950 * partial array is full. Move the existing
1951 * set to the per node partial list.
1953 local_irq_save(flags);
1954 unfreeze_partials(s);
1955 local_irq_restore(flags);
1958 stat(s, CPU_PARTIAL_DRAIN);
1963 pobjects += page->objects - page->inuse;
1965 page->pages = pages;
1966 page->pobjects = pobjects;
1967 page->next = oldpage;
1969 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page) != oldpage);
1973 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1975 stat(s, CPUSLAB_FLUSH);
1976 deactivate_slab(s, c->page, c->freelist);
1978 c->tid = next_tid(c->tid);
1986 * Called from IPI handler with interrupts disabled.
1988 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1990 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
1996 unfreeze_partials(s);
2000 static void flush_cpu_slab(void *d)
2002 struct kmem_cache *s = d;
2004 __flush_cpu_slab(s, smp_processor_id());
2007 static bool has_cpu_slab(int cpu, void *info)
2009 struct kmem_cache *s = info;
2010 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2012 return c->page || c->partial;
2015 static void flush_all(struct kmem_cache *s)
2017 on_each_cpu_cond(has_cpu_slab, flush_cpu_slab, s, 1, GFP_ATOMIC);
2021 * Check if the objects in a per cpu structure fit numa
2022 * locality expectations.
2024 static inline int node_match(struct page *page, int node)
2027 if (node != NUMA_NO_NODE && page_to_nid(page) != node)
2033 static int count_free(struct page *page)
2035 return page->objects - page->inuse;
2038 static unsigned long count_partial(struct kmem_cache_node *n,
2039 int (*get_count)(struct page *))
2041 unsigned long flags;
2042 unsigned long x = 0;
2045 spin_lock_irqsave(&n->list_lock, flags);
2046 list_for_each_entry(page, &n->partial, lru)
2047 x += get_count(page);
2048 spin_unlock_irqrestore(&n->list_lock, flags);
2052 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2054 #ifdef CONFIG_SLUB_DEBUG
2055 return atomic_long_read(&n->total_objects);
2061 static noinline void
2062 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2067 "SLUB: Unable to allocate memory on node %d (gfp=0x%x)\n",
2069 printk(KERN_WARNING " cache: %s, object size: %d, buffer size: %d, "
2070 "default order: %d, min order: %d\n", s->name, s->object_size,
2071 s->size, oo_order(s->oo), oo_order(s->min));
2073 if (oo_order(s->min) > get_order(s->object_size))
2074 printk(KERN_WARNING " %s debugging increased min order, use "
2075 "slub_debug=O to disable.\n", s->name);
2077 for_each_online_node(node) {
2078 struct kmem_cache_node *n = get_node(s, node);
2079 unsigned long nr_slabs;
2080 unsigned long nr_objs;
2081 unsigned long nr_free;
2086 nr_free = count_partial(n, count_free);
2087 nr_slabs = node_nr_slabs(n);
2088 nr_objs = node_nr_objs(n);
2091 " node %d: slabs: %ld, objs: %ld, free: %ld\n",
2092 node, nr_slabs, nr_objs, nr_free);
2096 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2097 int node, struct kmem_cache_cpu **pc)
2100 struct kmem_cache_cpu *c = *pc;
2103 freelist = get_partial(s, flags, node, c);
2108 page = new_slab(s, flags, node);
2110 c = __this_cpu_ptr(s->cpu_slab);
2115 * No other reference to the page yet so we can
2116 * muck around with it freely without cmpxchg
2118 freelist = page->freelist;
2119 page->freelist = NULL;
2121 stat(s, ALLOC_SLAB);
2131 * Check the page->freelist of a page and either transfer the freelist to the per cpu freelist
2132 * or deactivate the page.
2134 * The page is still frozen if the return value is not NULL.
2136 * If this function returns NULL then the page has been unfrozen.
2138 * This function must be called with interrupt disabled.
2140 static inline void *get_freelist(struct kmem_cache *s, struct page *page)
2143 unsigned long counters;
2147 freelist = page->freelist;
2148 counters = page->counters;
2150 new.counters = counters;
2151 VM_BUG_ON(!new.frozen);
2153 new.inuse = page->objects;
2154 new.frozen = freelist != NULL;
2156 } while (!__cmpxchg_double_slab(s, page,
2165 * Slow path. The lockless freelist is empty or we need to perform
2168 * Processing is still very fast if new objects have been freed to the
2169 * regular freelist. In that case we simply take over the regular freelist
2170 * as the lockless freelist and zap the regular freelist.
2172 * If that is not working then we fall back to the partial lists. We take the
2173 * first element of the freelist as the object to allocate now and move the
2174 * rest of the freelist to the lockless freelist.
2176 * And if we were unable to get a new slab from the partial slab lists then
2177 * we need to allocate a new slab. This is the slowest path since it involves
2178 * a call to the page allocator and the setup of a new slab.
2180 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2181 unsigned long addr, struct kmem_cache_cpu *c)
2185 unsigned long flags;
2187 local_irq_save(flags);
2188 #ifdef CONFIG_PREEMPT
2190 * We may have been preempted and rescheduled on a different
2191 * cpu before disabling interrupts. Need to reload cpu area
2194 c = this_cpu_ptr(s->cpu_slab);
2202 if (unlikely(!node_match(page, node))) {
2203 stat(s, ALLOC_NODE_MISMATCH);
2204 deactivate_slab(s, page, c->freelist);
2210 /* must check again c->freelist in case of cpu migration or IRQ */
2211 freelist = c->freelist;
2215 stat(s, ALLOC_SLOWPATH);
2217 freelist = get_freelist(s, page);
2221 stat(s, DEACTIVATE_BYPASS);
2225 stat(s, ALLOC_REFILL);
2229 * freelist is pointing to the list of objects to be used.
2230 * page is pointing to the page from which the objects are obtained.
2231 * That page must be frozen for per cpu allocations to work.
2233 VM_BUG_ON(!c->page->frozen);
2234 c->freelist = get_freepointer(s, freelist);
2235 c->tid = next_tid(c->tid);
2236 local_irq_restore(flags);
2242 page = c->page = c->partial;
2243 c->partial = page->next;
2244 stat(s, CPU_PARTIAL_ALLOC);
2249 freelist = new_slab_objects(s, gfpflags, node, &c);
2251 if (unlikely(!freelist)) {
2252 if (!(gfpflags & __GFP_NOWARN) && printk_ratelimit())
2253 slab_out_of_memory(s, gfpflags, node);
2255 local_irq_restore(flags);
2260 if (likely(!kmem_cache_debug(s)))
2263 /* Only entered in the debug case */
2264 if (!alloc_debug_processing(s, page, freelist, addr))
2265 goto new_slab; /* Slab failed checks. Next slab needed */
2267 deactivate_slab(s, page, get_freepointer(s, freelist));
2270 local_irq_restore(flags);
2275 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2276 * have the fastpath folded into their functions. So no function call
2277 * overhead for requests that can be satisfied on the fastpath.
2279 * The fastpath works by first checking if the lockless freelist can be used.
2280 * If not then __slab_alloc is called for slow processing.
2282 * Otherwise we can simply pick the next object from the lockless free list.
2284 static __always_inline void *slab_alloc(struct kmem_cache *s,
2285 gfp_t gfpflags, int node, unsigned long addr)
2288 struct kmem_cache_cpu *c;
2292 if (slab_pre_alloc_hook(s, gfpflags))
2298 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2299 * enabled. We may switch back and forth between cpus while
2300 * reading from one cpu area. That does not matter as long
2301 * as we end up on the original cpu again when doing the cmpxchg.
2303 c = __this_cpu_ptr(s->cpu_slab);
2306 * The transaction ids are globally unique per cpu and per operation on
2307 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2308 * occurs on the right processor and that there was no operation on the
2309 * linked list in between.
2314 object = c->freelist;
2316 if (unlikely(!object || !node_match(page, node)))
2318 object = __slab_alloc(s, gfpflags, node, addr, c);
2321 void *next_object = get_freepointer_safe(s, object);
2324 * The cmpxchg will only match if there was no additional
2325 * operation and if we are on the right processor.
2327 * The cmpxchg does the following atomically (without lock semantics!)
2328 * 1. Relocate first pointer to the current per cpu area.
2329 * 2. Verify that tid and freelist have not been changed
2330 * 3. If they were not changed replace tid and freelist
2332 * Since this is without lock semantics the protection is only against
2333 * code executing on this cpu *not* from access by other cpus.
2335 if (unlikely(!this_cpu_cmpxchg_double(
2336 s->cpu_slab->freelist, s->cpu_slab->tid,
2338 next_object, next_tid(tid)))) {
2340 note_cmpxchg_failure("slab_alloc", s, tid);
2343 prefetch_freepointer(s, next_object);
2344 stat(s, ALLOC_FASTPATH);
2347 if (unlikely(gfpflags & __GFP_ZERO) && object)
2348 memset(object, 0, s->object_size);
2350 slab_post_alloc_hook(s, gfpflags, object);
2355 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2357 void *ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, _RET_IP_);
2359 trace_kmem_cache_alloc(_RET_IP_, ret, s->object_size, s->size, gfpflags);
2363 EXPORT_SYMBOL(kmem_cache_alloc);
2365 #ifdef CONFIG_TRACING
2366 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2368 void *ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, _RET_IP_);
2369 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2372 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2374 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
2376 void *ret = kmalloc_order(size, flags, order);
2377 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
2380 EXPORT_SYMBOL(kmalloc_order_trace);
2384 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2386 void *ret = slab_alloc(s, gfpflags, node, _RET_IP_);
2388 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2389 s->object_size, s->size, gfpflags, node);
2393 EXPORT_SYMBOL(kmem_cache_alloc_node);
2395 #ifdef CONFIG_TRACING
2396 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2398 int node, size_t size)
2400 void *ret = slab_alloc(s, gfpflags, node, _RET_IP_);
2402 trace_kmalloc_node(_RET_IP_, ret,
2403 size, s->size, gfpflags, node);
2406 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2411 * Slow patch handling. This may still be called frequently since objects
2412 * have a longer lifetime than the cpu slabs in most processing loads.
2414 * So we still attempt to reduce cache line usage. Just take the slab
2415 * lock and free the item. If there is no additional partial page
2416 * handling required then we can return immediately.
2418 static void __slab_free(struct kmem_cache *s, struct page *page,
2419 void *x, unsigned long addr)
2422 void **object = (void *)x;
2426 unsigned long counters;
2427 struct kmem_cache_node *n = NULL;
2428 unsigned long uninitialized_var(flags);
2430 stat(s, FREE_SLOWPATH);
2432 if (kmem_cache_debug(s) && !free_debug_processing(s, page, x, addr))
2436 prior = page->freelist;
2437 counters = page->counters;
2438 set_freepointer(s, object, prior);
2439 new.counters = counters;
2440 was_frozen = new.frozen;
2442 if ((!new.inuse || !prior) && !was_frozen && !n) {
2444 if (!kmem_cache_debug(s) && !prior)
2447 * Slab was on no list before and will be partially empty
2448 * We can defer the list move and instead freeze it.
2452 else { /* Needs to be taken off a list */
2454 n = get_node(s, page_to_nid(page));
2456 * Speculatively acquire the list_lock.
2457 * If the cmpxchg does not succeed then we may
2458 * drop the list_lock without any processing.
2460 * Otherwise the list_lock will synchronize with
2461 * other processors updating the list of slabs.
2463 spin_lock_irqsave(&n->list_lock, flags);
2469 } while (!cmpxchg_double_slab(s, page,
2471 object, new.counters,
2477 * If we just froze the page then put it onto the
2478 * per cpu partial list.
2480 if (new.frozen && !was_frozen) {
2481 put_cpu_partial(s, page, 1);
2482 stat(s, CPU_PARTIAL_FREE);
2485 * The list lock was not taken therefore no list
2486 * activity can be necessary.
2489 stat(s, FREE_FROZEN);
2494 * was_frozen may have been set after we acquired the list_lock in
2495 * an earlier loop. So we need to check it here again.
2498 stat(s, FREE_FROZEN);
2500 if (unlikely(!inuse && n->nr_partial > s->min_partial))
2504 * Objects left in the slab. If it was not on the partial list before
2507 if (unlikely(!prior)) {
2508 remove_full(s, page);
2509 add_partial(n, page, DEACTIVATE_TO_TAIL);
2510 stat(s, FREE_ADD_PARTIAL);
2513 spin_unlock_irqrestore(&n->list_lock, flags);
2519 * Slab on the partial list.
2521 remove_partial(n, page);
2522 stat(s, FREE_REMOVE_PARTIAL);
2524 /* Slab must be on the full list */
2525 remove_full(s, page);
2527 spin_unlock_irqrestore(&n->list_lock, flags);
2529 discard_slab(s, page);
2533 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2534 * can perform fastpath freeing without additional function calls.
2536 * The fastpath is only possible if we are freeing to the current cpu slab
2537 * of this processor. This typically the case if we have just allocated
2540 * If fastpath is not possible then fall back to __slab_free where we deal
2541 * with all sorts of special processing.
2543 static __always_inline void slab_free(struct kmem_cache *s,
2544 struct page *page, void *x, unsigned long addr)
2546 void **object = (void *)x;
2547 struct kmem_cache_cpu *c;
2550 slab_free_hook(s, x);
2554 * Determine the currently cpus per cpu slab.
2555 * The cpu may change afterward. However that does not matter since
2556 * data is retrieved via this pointer. If we are on the same cpu
2557 * during the cmpxchg then the free will succedd.
2559 c = __this_cpu_ptr(s->cpu_slab);
2564 if (likely(page == c->page)) {
2565 set_freepointer(s, object, c->freelist);
2567 if (unlikely(!this_cpu_cmpxchg_double(
2568 s->cpu_slab->freelist, s->cpu_slab->tid,
2570 object, next_tid(tid)))) {
2572 note_cmpxchg_failure("slab_free", s, tid);
2575 stat(s, FREE_FASTPATH);
2577 __slab_free(s, page, x, addr);
2581 void kmem_cache_free(struct kmem_cache *s, void *x)
2585 page = virt_to_head_page(x);
2587 slab_free(s, page, x, _RET_IP_);
2589 trace_kmem_cache_free(_RET_IP_, x);
2591 EXPORT_SYMBOL(kmem_cache_free);
2594 * Object placement in a slab is made very easy because we always start at
2595 * offset 0. If we tune the size of the object to the alignment then we can
2596 * get the required alignment by putting one properly sized object after
2599 * Notice that the allocation order determines the sizes of the per cpu
2600 * caches. Each processor has always one slab available for allocations.
2601 * Increasing the allocation order reduces the number of times that slabs
2602 * must be moved on and off the partial lists and is therefore a factor in
2607 * Mininum / Maximum order of slab pages. This influences locking overhead
2608 * and slab fragmentation. A higher order reduces the number of partial slabs
2609 * and increases the number of allocations possible without having to
2610 * take the list_lock.
2612 static int slub_min_order;
2613 static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
2614 static int slub_min_objects;
2617 * Merge control. If this is set then no merging of slab caches will occur.
2618 * (Could be removed. This was introduced to pacify the merge skeptics.)
2620 static int slub_nomerge;
2623 * Calculate the order of allocation given an slab object size.
2625 * The order of allocation has significant impact on performance and other
2626 * system components. Generally order 0 allocations should be preferred since
2627 * order 0 does not cause fragmentation in the page allocator. Larger objects
2628 * be problematic to put into order 0 slabs because there may be too much
2629 * unused space left. We go to a higher order if more than 1/16th of the slab
2632 * In order to reach satisfactory performance we must ensure that a minimum
2633 * number of objects is in one slab. Otherwise we may generate too much
2634 * activity on the partial lists which requires taking the list_lock. This is
2635 * less a concern for large slabs though which are rarely used.
2637 * slub_max_order specifies the order where we begin to stop considering the
2638 * number of objects in a slab as critical. If we reach slub_max_order then
2639 * we try to keep the page order as low as possible. So we accept more waste
2640 * of space in favor of a small page order.
2642 * Higher order allocations also allow the placement of more objects in a
2643 * slab and thereby reduce object handling overhead. If the user has
2644 * requested a higher mininum order then we start with that one instead of
2645 * the smallest order which will fit the object.
2647 static inline int slab_order(int size, int min_objects,
2648 int max_order, int fract_leftover, int reserved)
2652 int min_order = slub_min_order;
2654 if (order_objects(min_order, size, reserved) > MAX_OBJS_PER_PAGE)
2655 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
2657 for (order = max(min_order,
2658 fls(min_objects * size - 1) - PAGE_SHIFT);
2659 order <= max_order; order++) {
2661 unsigned long slab_size = PAGE_SIZE << order;
2663 if (slab_size < min_objects * size + reserved)
2666 rem = (slab_size - reserved) % size;
2668 if (rem <= slab_size / fract_leftover)
2676 static inline int calculate_order(int size, int reserved)
2684 * Attempt to find best configuration for a slab. This
2685 * works by first attempting to generate a layout with
2686 * the best configuration and backing off gradually.
2688 * First we reduce the acceptable waste in a slab. Then
2689 * we reduce the minimum objects required in a slab.
2691 min_objects = slub_min_objects;
2693 min_objects = 4 * (fls(nr_cpu_ids) + 1);
2694 max_objects = order_objects(slub_max_order, size, reserved);
2695 min_objects = min(min_objects, max_objects);
2697 while (min_objects > 1) {
2699 while (fraction >= 4) {
2700 order = slab_order(size, min_objects,
2701 slub_max_order, fraction, reserved);
2702 if (order <= slub_max_order)
2710 * We were unable to place multiple objects in a slab. Now
2711 * lets see if we can place a single object there.
2713 order = slab_order(size, 1, slub_max_order, 1, reserved);
2714 if (order <= slub_max_order)
2718 * Doh this slab cannot be placed using slub_max_order.
2720 order = slab_order(size, 1, MAX_ORDER, 1, reserved);
2721 if (order < MAX_ORDER)
2727 * Figure out what the alignment of the objects will be.
2729 static unsigned long calculate_alignment(unsigned long flags,
2730 unsigned long align, unsigned long size)
2733 * If the user wants hardware cache aligned objects then follow that
2734 * suggestion if the object is sufficiently large.
2736 * The hardware cache alignment cannot override the specified
2737 * alignment though. If that is greater then use it.
2739 if (flags & SLAB_HWCACHE_ALIGN) {
2740 unsigned long ralign = cache_line_size();
2741 while (size <= ralign / 2)
2743 align = max(align, ralign);
2746 if (align < ARCH_SLAB_MINALIGN)
2747 align = ARCH_SLAB_MINALIGN;
2749 return ALIGN(align, sizeof(void *));
2753 init_kmem_cache_node(struct kmem_cache_node *n)
2756 spin_lock_init(&n->list_lock);
2757 INIT_LIST_HEAD(&n->partial);
2758 #ifdef CONFIG_SLUB_DEBUG
2759 atomic_long_set(&n->nr_slabs, 0);
2760 atomic_long_set(&n->total_objects, 0);
2761 INIT_LIST_HEAD(&n->full);
2765 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
2767 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
2768 SLUB_PAGE_SHIFT * sizeof(struct kmem_cache_cpu));
2771 * Must align to double word boundary for the double cmpxchg
2772 * instructions to work; see __pcpu_double_call_return_bool().
2774 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
2775 2 * sizeof(void *));
2780 init_kmem_cache_cpus(s);
2785 static struct kmem_cache *kmem_cache_node;
2788 * No kmalloc_node yet so do it by hand. We know that this is the first
2789 * slab on the node for this slabcache. There are no concurrent accesses
2792 * Note that this function only works on the kmalloc_node_cache
2793 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2794 * memory on a fresh node that has no slab structures yet.
2796 static void early_kmem_cache_node_alloc(int node)
2799 struct kmem_cache_node *n;
2801 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
2803 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
2806 if (page_to_nid(page) != node) {
2807 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2809 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2810 "in order to be able to continue\n");
2815 page->freelist = get_freepointer(kmem_cache_node, n);
2818 kmem_cache_node->node[node] = n;
2819 #ifdef CONFIG_SLUB_DEBUG
2820 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
2821 init_tracking(kmem_cache_node, n);
2823 init_kmem_cache_node(n);
2824 inc_slabs_node(kmem_cache_node, node, page->objects);
2826 add_partial(n, page, DEACTIVATE_TO_HEAD);
2829 static void free_kmem_cache_nodes(struct kmem_cache *s)
2833 for_each_node_state(node, N_NORMAL_MEMORY) {
2834 struct kmem_cache_node *n = s->node[node];
2837 kmem_cache_free(kmem_cache_node, n);
2839 s->node[node] = NULL;
2843 static int init_kmem_cache_nodes(struct kmem_cache *s)
2847 for_each_node_state(node, N_NORMAL_MEMORY) {
2848 struct kmem_cache_node *n;
2850 if (slab_state == DOWN) {
2851 early_kmem_cache_node_alloc(node);
2854 n = kmem_cache_alloc_node(kmem_cache_node,
2858 free_kmem_cache_nodes(s);
2863 init_kmem_cache_node(n);
2868 static void set_min_partial(struct kmem_cache *s, unsigned long min)
2870 if (min < MIN_PARTIAL)
2872 else if (min > MAX_PARTIAL)
2874 s->min_partial = min;
2878 * calculate_sizes() determines the order and the distribution of data within
2881 static int calculate_sizes(struct kmem_cache *s, int forced_order)
2883 unsigned long flags = s->flags;
2884 unsigned long size = s->object_size;
2885 unsigned long align = s->align;
2889 * Round up object size to the next word boundary. We can only
2890 * place the free pointer at word boundaries and this determines
2891 * the possible location of the free pointer.
2893 size = ALIGN(size, sizeof(void *));
2895 #ifdef CONFIG_SLUB_DEBUG
2897 * Determine if we can poison the object itself. If the user of
2898 * the slab may touch the object after free or before allocation
2899 * then we should never poison the object itself.
2901 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2903 s->flags |= __OBJECT_POISON;
2905 s->flags &= ~__OBJECT_POISON;
2909 * If we are Redzoning then check if there is some space between the
2910 * end of the object and the free pointer. If not then add an
2911 * additional word to have some bytes to store Redzone information.
2913 if ((flags & SLAB_RED_ZONE) && size == s->object_size)
2914 size += sizeof(void *);
2918 * With that we have determined the number of bytes in actual use
2919 * by the object. This is the potential offset to the free pointer.
2923 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2926 * Relocate free pointer after the object if it is not
2927 * permitted to overwrite the first word of the object on
2930 * This is the case if we do RCU, have a constructor or
2931 * destructor or are poisoning the objects.
2934 size += sizeof(void *);
2937 #ifdef CONFIG_SLUB_DEBUG
2938 if (flags & SLAB_STORE_USER)
2940 * Need to store information about allocs and frees after
2943 size += 2 * sizeof(struct track);
2945 if (flags & SLAB_RED_ZONE)
2947 * Add some empty padding so that we can catch
2948 * overwrites from earlier objects rather than let
2949 * tracking information or the free pointer be
2950 * corrupted if a user writes before the start
2953 size += sizeof(void *);
2957 * Determine the alignment based on various parameters that the
2958 * user specified and the dynamic determination of cache line size
2961 align = calculate_alignment(flags, align, s->object_size);
2965 * SLUB stores one object immediately after another beginning from
2966 * offset 0. In order to align the objects we have to simply size
2967 * each object to conform to the alignment.
2969 size = ALIGN(size, align);
2971 if (forced_order >= 0)
2972 order = forced_order;
2974 order = calculate_order(size, s->reserved);
2981 s->allocflags |= __GFP_COMP;
2983 if (s->flags & SLAB_CACHE_DMA)
2984 s->allocflags |= SLUB_DMA;
2986 if (s->flags & SLAB_RECLAIM_ACCOUNT)
2987 s->allocflags |= __GFP_RECLAIMABLE;
2990 * Determine the number of objects per slab
2992 s->oo = oo_make(order, size, s->reserved);
2993 s->min = oo_make(get_order(size), size, s->reserved);
2994 if (oo_objects(s->oo) > oo_objects(s->max))
2997 return !!oo_objects(s->oo);
3001 static int kmem_cache_open(struct kmem_cache *s,
3002 const char *name, size_t size,
3003 size_t align, unsigned long flags,
3004 void (*ctor)(void *))
3006 memset(s, 0, kmem_size);
3009 s->object_size = size;
3011 s->flags = kmem_cache_flags(size, flags, name, ctor);
3014 if (need_reserve_slab_rcu && (s->flags & SLAB_DESTROY_BY_RCU))
3015 s->reserved = sizeof(struct rcu_head);
3017 if (!calculate_sizes(s, -1))
3019 if (disable_higher_order_debug) {
3021 * Disable debugging flags that store metadata if the min slab
3024 if (get_order(s->size) > get_order(s->object_size)) {
3025 s->flags &= ~DEBUG_METADATA_FLAGS;
3027 if (!calculate_sizes(s, -1))
3032 #if defined(CONFIG_HAVE_CMPXCHG_DOUBLE) && \
3033 defined(CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
3034 if (system_has_cmpxchg_double() && (s->flags & SLAB_DEBUG_FLAGS) == 0)
3035 /* Enable fast mode */
3036 s->flags |= __CMPXCHG_DOUBLE;
3040 * The larger the object size is, the more pages we want on the partial
3041 * list to avoid pounding the page allocator excessively.
3043 set_min_partial(s, ilog2(s->size) / 2);
3046 * cpu_partial determined the maximum number of objects kept in the
3047 * per cpu partial lists of a processor.
3049 * Per cpu partial lists mainly contain slabs that just have one
3050 * object freed. If they are used for allocation then they can be
3051 * filled up again with minimal effort. The slab will never hit the
3052 * per node partial lists and therefore no locking will be required.
3054 * This setting also determines
3056 * A) The number of objects from per cpu partial slabs dumped to the
3057 * per node list when we reach the limit.
3058 * B) The number of objects in cpu partial slabs to extract from the
3059 * per node list when we run out of per cpu objects. We only fetch 50%
3060 * to keep some capacity around for frees.
3062 if (kmem_cache_debug(s))
3064 else if (s->size >= PAGE_SIZE)
3066 else if (s->size >= 1024)
3068 else if (s->size >= 256)
3069 s->cpu_partial = 13;
3071 s->cpu_partial = 30;
3075 s->remote_node_defrag_ratio = 1000;
3077 if (!init_kmem_cache_nodes(s))
3080 if (alloc_kmem_cache_cpus(s))
3083 free_kmem_cache_nodes(s);
3085 if (flags & SLAB_PANIC)
3086 panic("Cannot create slab %s size=%lu realsize=%u "
3087 "order=%u offset=%u flags=%lx\n",
3088 s->name, (unsigned long)size, s->size, oo_order(s->oo),
3094 * Determine the size of a slab object
3096 unsigned int kmem_cache_size(struct kmem_cache *s)
3098 return s->object_size;
3100 EXPORT_SYMBOL(kmem_cache_size);
3102 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3105 #ifdef CONFIG_SLUB_DEBUG
3106 void *addr = page_address(page);
3108 unsigned long *map = kzalloc(BITS_TO_LONGS(page->objects) *
3109 sizeof(long), GFP_ATOMIC);
3112 slab_err(s, page, "%s", text);
3115 get_map(s, page, map);
3116 for_each_object(p, s, addr, page->objects) {
3118 if (!test_bit(slab_index(p, s, addr), map)) {
3119 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu\n",
3121 print_tracking(s, p);
3130 * Attempt to free all partial slabs on a node.
3131 * This is called from kmem_cache_close(). We must be the last thread
3132 * using the cache and therefore we do not need to lock anymore.
3134 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3136 struct page *page, *h;
3138 list_for_each_entry_safe(page, h, &n->partial, lru) {
3140 remove_partial(n, page);
3141 discard_slab(s, page);
3143 list_slab_objects(s, page,
3144 "Objects remaining on kmem_cache_close()");
3150 * Release all resources used by a slab cache.
3152 static inline int kmem_cache_close(struct kmem_cache *s)
3157 free_percpu(s->cpu_slab);
3158 /* Attempt to free all objects */
3159 for_each_node_state(node, N_NORMAL_MEMORY) {
3160 struct kmem_cache_node *n = get_node(s, node);
3163 if (n->nr_partial || slabs_node(s, node))
3166 free_kmem_cache_nodes(s);
3171 * Close a cache and release the kmem_cache structure
3172 * (must be used for caches created using kmem_cache_create)
3174 void kmem_cache_destroy(struct kmem_cache *s)
3176 mutex_lock(&slab_mutex);
3180 mutex_unlock(&slab_mutex);
3181 if (kmem_cache_close(s)) {
3182 printk(KERN_ERR "SLUB %s: %s called for cache that "
3183 "still has objects.\n", s->name, __func__);
3186 if (s->flags & SLAB_DESTROY_BY_RCU)
3188 sysfs_slab_remove(s);
3190 mutex_unlock(&slab_mutex);
3192 EXPORT_SYMBOL(kmem_cache_destroy);
3194 /********************************************************************
3196 *******************************************************************/
3198 struct kmem_cache *kmalloc_caches[SLUB_PAGE_SHIFT];
3199 EXPORT_SYMBOL(kmalloc_caches);
3201 static struct kmem_cache *kmem_cache;
3203 #ifdef CONFIG_ZONE_DMA
3204 static struct kmem_cache *kmalloc_dma_caches[SLUB_PAGE_SHIFT];
3207 static int __init setup_slub_min_order(char *str)
3209 get_option(&str, &slub_min_order);
3214 __setup("slub_min_order=", setup_slub_min_order);
3216 static int __init setup_slub_max_order(char *str)
3218 get_option(&str, &slub_max_order);
3219 slub_max_order = min(slub_max_order, MAX_ORDER - 1);
3224 __setup("slub_max_order=", setup_slub_max_order);
3226 static int __init setup_slub_min_objects(char *str)
3228 get_option(&str, &slub_min_objects);
3233 __setup("slub_min_objects=", setup_slub_min_objects);
3235 static int __init setup_slub_nomerge(char *str)
3241 __setup("slub_nomerge", setup_slub_nomerge);
3243 static struct kmem_cache *__init create_kmalloc_cache(const char *name,
3244 int size, unsigned int flags)
3246 struct kmem_cache *s;
3248 s = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3251 * This function is called with IRQs disabled during early-boot on
3252 * single CPU so there's no need to take slab_mutex here.
3254 if (!kmem_cache_open(s, name, size, ARCH_KMALLOC_MINALIGN,
3258 list_add(&s->list, &slab_caches);
3262 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
3267 * Conversion table for small slabs sizes / 8 to the index in the
3268 * kmalloc array. This is necessary for slabs < 192 since we have non power
3269 * of two cache sizes there. The size of larger slabs can be determined using
3272 static s8 size_index[24] = {
3299 static inline int size_index_elem(size_t bytes)
3301 return (bytes - 1) / 8;
3304 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
3310 return ZERO_SIZE_PTR;
3312 index = size_index[size_index_elem(size)];
3314 index = fls(size - 1);
3316 #ifdef CONFIG_ZONE_DMA
3317 if (unlikely((flags & SLUB_DMA)))
3318 return kmalloc_dma_caches[index];
3321 return kmalloc_caches[index];
3324 void *__kmalloc(size_t size, gfp_t flags)
3326 struct kmem_cache *s;
3329 if (unlikely(size > SLUB_MAX_SIZE))
3330 return kmalloc_large(size, flags);
3332 s = get_slab(size, flags);
3334 if (unlikely(ZERO_OR_NULL_PTR(s)))
3337 ret = slab_alloc(s, flags, NUMA_NO_NODE, _RET_IP_);
3339 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3343 EXPORT_SYMBOL(__kmalloc);
3346 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3351 flags |= __GFP_COMP | __GFP_NOTRACK;
3352 page = alloc_pages_node(node, flags, get_order(size));
3354 ptr = page_address(page);
3356 kmemleak_alloc(ptr, size, 1, flags);
3360 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3362 struct kmem_cache *s;
3365 if (unlikely(size > SLUB_MAX_SIZE)) {
3366 ret = kmalloc_large_node(size, flags, node);
3368 trace_kmalloc_node(_RET_IP_, ret,
3369 size, PAGE_SIZE << get_order(size),
3375 s = get_slab(size, flags);
3377 if (unlikely(ZERO_OR_NULL_PTR(s)))
3380 ret = slab_alloc(s, flags, node, _RET_IP_);
3382 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3386 EXPORT_SYMBOL(__kmalloc_node);
3389 size_t ksize(const void *object)
3393 if (unlikely(object == ZERO_SIZE_PTR))
3396 page = virt_to_head_page(object);
3398 if (unlikely(!PageSlab(page))) {
3399 WARN_ON(!PageCompound(page));
3400 return PAGE_SIZE << compound_order(page);
3403 return slab_ksize(page->slab);
3405 EXPORT_SYMBOL(ksize);
3407 #ifdef CONFIG_SLUB_DEBUG
3408 bool verify_mem_not_deleted(const void *x)
3411 void *object = (void *)x;
3412 unsigned long flags;
3415 if (unlikely(ZERO_OR_NULL_PTR(x)))
3418 local_irq_save(flags);
3420 page = virt_to_head_page(x);
3421 if (unlikely(!PageSlab(page))) {
3422 /* maybe it was from stack? */
3428 if (on_freelist(page->slab, page, object)) {
3429 object_err(page->slab, page, object, "Object is on free-list");
3437 local_irq_restore(flags);
3440 EXPORT_SYMBOL(verify_mem_not_deleted);
3443 void kfree(const void *x)
3446 void *object = (void *)x;
3448 trace_kfree(_RET_IP_, x);
3450 if (unlikely(ZERO_OR_NULL_PTR(x)))
3453 page = virt_to_head_page(x);
3454 if (unlikely(!PageSlab(page))) {
3455 BUG_ON(!PageCompound(page));
3460 slab_free(page->slab, page, object, _RET_IP_);
3462 EXPORT_SYMBOL(kfree);
3465 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
3466 * the remaining slabs by the number of items in use. The slabs with the
3467 * most items in use come first. New allocations will then fill those up
3468 * and thus they can be removed from the partial lists.
3470 * The slabs with the least items are placed last. This results in them
3471 * being allocated from last increasing the chance that the last objects
3472 * are freed in them.
3474 int kmem_cache_shrink(struct kmem_cache *s)
3478 struct kmem_cache_node *n;
3481 int objects = oo_objects(s->max);
3482 struct list_head *slabs_by_inuse =
3483 kmalloc(sizeof(struct list_head) * objects, GFP_KERNEL);
3484 unsigned long flags;
3486 if (!slabs_by_inuse)
3490 for_each_node_state(node, N_NORMAL_MEMORY) {
3491 n = get_node(s, node);
3496 for (i = 0; i < objects; i++)
3497 INIT_LIST_HEAD(slabs_by_inuse + i);
3499 spin_lock_irqsave(&n->list_lock, flags);
3502 * Build lists indexed by the items in use in each slab.
3504 * Note that concurrent frees may occur while we hold the
3505 * list_lock. page->inuse here is the upper limit.
3507 list_for_each_entry_safe(page, t, &n->partial, lru) {
3508 list_move(&page->lru, slabs_by_inuse + page->inuse);
3514 * Rebuild the partial list with the slabs filled up most
3515 * first and the least used slabs at the end.
3517 for (i = objects - 1; i > 0; i--)
3518 list_splice(slabs_by_inuse + i, n->partial.prev);
3520 spin_unlock_irqrestore(&n->list_lock, flags);
3522 /* Release empty slabs */
3523 list_for_each_entry_safe(page, t, slabs_by_inuse, lru)
3524 discard_slab(s, page);
3527 kfree(slabs_by_inuse);
3530 EXPORT_SYMBOL(kmem_cache_shrink);
3532 #if defined(CONFIG_MEMORY_HOTPLUG)
3533 static int slab_mem_going_offline_callback(void *arg)
3535 struct kmem_cache *s;
3537 mutex_lock(&slab_mutex);
3538 list_for_each_entry(s, &slab_caches, list)
3539 kmem_cache_shrink(s);
3540 mutex_unlock(&slab_mutex);
3545 static void slab_mem_offline_callback(void *arg)
3547 struct kmem_cache_node *n;
3548 struct kmem_cache *s;
3549 struct memory_notify *marg = arg;
3552 offline_node = marg->status_change_nid;
3555 * If the node still has available memory. we need kmem_cache_node
3558 if (offline_node < 0)
3561 mutex_lock(&slab_mutex);
3562 list_for_each_entry(s, &slab_caches, list) {
3563 n = get_node(s, offline_node);
3566 * if n->nr_slabs > 0, slabs still exist on the node
3567 * that is going down. We were unable to free them,
3568 * and offline_pages() function shouldn't call this
3569 * callback. So, we must fail.
3571 BUG_ON(slabs_node(s, offline_node));
3573 s->node[offline_node] = NULL;
3574 kmem_cache_free(kmem_cache_node, n);
3577 mutex_unlock(&slab_mutex);
3580 static int slab_mem_going_online_callback(void *arg)
3582 struct kmem_cache_node *n;
3583 struct kmem_cache *s;
3584 struct memory_notify *marg = arg;
3585 int nid = marg->status_change_nid;
3589 * If the node's memory is already available, then kmem_cache_node is
3590 * already created. Nothing to do.
3596 * We are bringing a node online. No memory is available yet. We must
3597 * allocate a kmem_cache_node structure in order to bring the node
3600 mutex_lock(&slab_mutex);
3601 list_for_each_entry(s, &slab_caches, list) {
3603 * XXX: kmem_cache_alloc_node will fallback to other nodes
3604 * since memory is not yet available from the node that
3607 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
3612 init_kmem_cache_node(n);
3616 mutex_unlock(&slab_mutex);
3620 static int slab_memory_callback(struct notifier_block *self,
3621 unsigned long action, void *arg)
3626 case MEM_GOING_ONLINE:
3627 ret = slab_mem_going_online_callback(arg);
3629 case MEM_GOING_OFFLINE:
3630 ret = slab_mem_going_offline_callback(arg);
3633 case MEM_CANCEL_ONLINE:
3634 slab_mem_offline_callback(arg);
3637 case MEM_CANCEL_OFFLINE:
3641 ret = notifier_from_errno(ret);
3647 #endif /* CONFIG_MEMORY_HOTPLUG */
3649 /********************************************************************
3650 * Basic setup of slabs
3651 *******************************************************************/
3654 * Used for early kmem_cache structures that were allocated using
3655 * the page allocator
3658 static void __init kmem_cache_bootstrap_fixup(struct kmem_cache *s)
3662 list_add(&s->list, &slab_caches);
3665 for_each_node_state(node, N_NORMAL_MEMORY) {
3666 struct kmem_cache_node *n = get_node(s, node);
3670 list_for_each_entry(p, &n->partial, lru)
3673 #ifdef CONFIG_SLUB_DEBUG
3674 list_for_each_entry(p, &n->full, lru)
3681 void __init kmem_cache_init(void)
3685 struct kmem_cache *temp_kmem_cache;
3687 struct kmem_cache *temp_kmem_cache_node;
3688 unsigned long kmalloc_size;
3690 if (debug_guardpage_minorder())
3693 kmem_size = offsetof(struct kmem_cache, node) +
3694 nr_node_ids * sizeof(struct kmem_cache_node *);
3696 /* Allocate two kmem_caches from the page allocator */
3697 kmalloc_size = ALIGN(kmem_size, cache_line_size());
3698 order = get_order(2 * kmalloc_size);
3699 kmem_cache = (void *)__get_free_pages(GFP_NOWAIT, order);
3702 * Must first have the slab cache available for the allocations of the
3703 * struct kmem_cache_node's. There is special bootstrap code in
3704 * kmem_cache_open for slab_state == DOWN.
3706 kmem_cache_node = (void *)kmem_cache + kmalloc_size;
3708 kmem_cache_open(kmem_cache_node, "kmem_cache_node",
3709 sizeof(struct kmem_cache_node),
3710 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
3712 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
3714 /* Able to allocate the per node structures */
3715 slab_state = PARTIAL;
3717 temp_kmem_cache = kmem_cache;
3718 kmem_cache_open(kmem_cache, "kmem_cache", kmem_size,
3719 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
3720 kmem_cache = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3721 memcpy(kmem_cache, temp_kmem_cache, kmem_size);
3724 * Allocate kmem_cache_node properly from the kmem_cache slab.
3725 * kmem_cache_node is separately allocated so no need to
3726 * update any list pointers.
3728 temp_kmem_cache_node = kmem_cache_node;
3730 kmem_cache_node = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3731 memcpy(kmem_cache_node, temp_kmem_cache_node, kmem_size);
3733 kmem_cache_bootstrap_fixup(kmem_cache_node);
3736 kmem_cache_bootstrap_fixup(kmem_cache);
3738 /* Free temporary boot structure */
3739 free_pages((unsigned long)temp_kmem_cache, order);
3741 /* Now we can use the kmem_cache to allocate kmalloc slabs */
3744 * Patch up the size_index table if we have strange large alignment
3745 * requirements for the kmalloc array. This is only the case for
3746 * MIPS it seems. The standard arches will not generate any code here.
3748 * Largest permitted alignment is 256 bytes due to the way we
3749 * handle the index determination for the smaller caches.
3751 * Make sure that nothing crazy happens if someone starts tinkering
3752 * around with ARCH_KMALLOC_MINALIGN
3754 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
3755 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
3757 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
3758 int elem = size_index_elem(i);
3759 if (elem >= ARRAY_SIZE(size_index))
3761 size_index[elem] = KMALLOC_SHIFT_LOW;
3764 if (KMALLOC_MIN_SIZE == 64) {
3766 * The 96 byte size cache is not used if the alignment
3769 for (i = 64 + 8; i <= 96; i += 8)
3770 size_index[size_index_elem(i)] = 7;
3771 } else if (KMALLOC_MIN_SIZE == 128) {
3773 * The 192 byte sized cache is not used if the alignment
3774 * is 128 byte. Redirect kmalloc to use the 256 byte cache
3777 for (i = 128 + 8; i <= 192; i += 8)
3778 size_index[size_index_elem(i)] = 8;
3781 /* Caches that are not of the two-to-the-power-of size */
3782 if (KMALLOC_MIN_SIZE <= 32) {
3783 kmalloc_caches[1] = create_kmalloc_cache("kmalloc-96", 96, 0);
3787 if (KMALLOC_MIN_SIZE <= 64) {
3788 kmalloc_caches[2] = create_kmalloc_cache("kmalloc-192", 192, 0);
3792 for (i = KMALLOC_SHIFT_LOW; i < SLUB_PAGE_SHIFT; i++) {
3793 kmalloc_caches[i] = create_kmalloc_cache("kmalloc", 1 << i, 0);
3799 /* Provide the correct kmalloc names now that the caches are up */
3800 if (KMALLOC_MIN_SIZE <= 32) {
3801 kmalloc_caches[1]->name = kstrdup(kmalloc_caches[1]->name, GFP_NOWAIT);
3802 BUG_ON(!kmalloc_caches[1]->name);
3805 if (KMALLOC_MIN_SIZE <= 64) {
3806 kmalloc_caches[2]->name = kstrdup(kmalloc_caches[2]->name, GFP_NOWAIT);
3807 BUG_ON(!kmalloc_caches[2]->name);
3810 for (i = KMALLOC_SHIFT_LOW; i < SLUB_PAGE_SHIFT; i++) {
3811 char *s = kasprintf(GFP_NOWAIT, "kmalloc-%d", 1 << i);
3814 kmalloc_caches[i]->name = s;
3818 register_cpu_notifier(&slab_notifier);
3821 #ifdef CONFIG_ZONE_DMA
3822 for (i = 0; i < SLUB_PAGE_SHIFT; i++) {
3823 struct kmem_cache *s = kmalloc_caches[i];
3826 char *name = kasprintf(GFP_NOWAIT,
3827 "dma-kmalloc-%d", s->object_size);
3830 kmalloc_dma_caches[i] = create_kmalloc_cache(name,
3831 s->object_size, SLAB_CACHE_DMA);
3836 "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
3837 " CPUs=%d, Nodes=%d\n",
3838 caches, cache_line_size(),
3839 slub_min_order, slub_max_order, slub_min_objects,
3840 nr_cpu_ids, nr_node_ids);
3843 void __init kmem_cache_init_late(void)
3848 * Find a mergeable slab cache
3850 static int slab_unmergeable(struct kmem_cache *s)
3852 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
3859 * We may have set a slab to be unmergeable during bootstrap.
3861 if (s->refcount < 0)
3867 static struct kmem_cache *find_mergeable(size_t size,
3868 size_t align, unsigned long flags, const char *name,
3869 void (*ctor)(void *))
3871 struct kmem_cache *s;
3873 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
3879 size = ALIGN(size, sizeof(void *));
3880 align = calculate_alignment(flags, align, size);
3881 size = ALIGN(size, align);
3882 flags = kmem_cache_flags(size, flags, name, NULL);
3884 list_for_each_entry(s, &slab_caches, list) {
3885 if (slab_unmergeable(s))
3891 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
3894 * Check if alignment is compatible.
3895 * Courtesy of Adrian Drzewiecki
3897 if ((s->size & ~(align - 1)) != s->size)
3900 if (s->size - size >= sizeof(void *))
3908 struct kmem_cache *__kmem_cache_create(const char *name, size_t size,
3909 size_t align, unsigned long flags, void (*ctor)(void *))
3911 struct kmem_cache *s;
3914 mutex_lock(&slab_mutex);
3915 s = find_mergeable(size, align, flags, name, ctor);
3919 * Adjust the object sizes so that we clear
3920 * the complete object on kzalloc.
3922 s->object_size = max(s->object_size, (int)size);
3923 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
3925 if (sysfs_slab_alias(s, name)) {
3929 mutex_unlock(&slab_mutex);
3933 n = kstrdup(name, GFP_KERNEL);
3937 s = kmalloc(kmem_size, GFP_KERNEL);
3939 if (kmem_cache_open(s, n,
3940 size, align, flags, ctor)) {
3941 list_add(&s->list, &slab_caches);
3942 mutex_unlock(&slab_mutex);
3943 if (sysfs_slab_add(s)) {
3944 mutex_lock(&slab_mutex);
3956 mutex_unlock(&slab_mutex);
3962 * Use the cpu notifier to insure that the cpu slabs are flushed when
3965 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
3966 unsigned long action, void *hcpu)
3968 long cpu = (long)hcpu;
3969 struct kmem_cache *s;
3970 unsigned long flags;
3973 case CPU_UP_CANCELED:
3974 case CPU_UP_CANCELED_FROZEN:
3976 case CPU_DEAD_FROZEN:
3977 mutex_lock(&slab_mutex);
3978 list_for_each_entry(s, &slab_caches, list) {
3979 local_irq_save(flags);
3980 __flush_cpu_slab(s, cpu);
3981 local_irq_restore(flags);
3983 mutex_unlock(&slab_mutex);
3991 static struct notifier_block __cpuinitdata slab_notifier = {
3992 .notifier_call = slab_cpuup_callback
3997 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
3999 struct kmem_cache *s;
4002 if (unlikely(size > SLUB_MAX_SIZE))
4003 return kmalloc_large(size, gfpflags);
4005 s = get_slab(size, gfpflags);
4007 if (unlikely(ZERO_OR_NULL_PTR(s)))
4010 ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, caller);
4012 /* Honor the call site pointer we received. */
4013 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4019 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4020 int node, unsigned long caller)
4022 struct kmem_cache *s;
4025 if (unlikely(size > SLUB_MAX_SIZE)) {
4026 ret = kmalloc_large_node(size, gfpflags, node);
4028 trace_kmalloc_node(caller, ret,
4029 size, PAGE_SIZE << get_order(size),
4035 s = get_slab(size, gfpflags);
4037 if (unlikely(ZERO_OR_NULL_PTR(s)))
4040 ret = slab_alloc(s, gfpflags, node, caller);
4042 /* Honor the call site pointer we received. */
4043 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4050 static int count_inuse(struct page *page)
4055 static int count_total(struct page *page)
4057 return page->objects;
4061 #ifdef CONFIG_SLUB_DEBUG
4062 static int validate_slab(struct kmem_cache *s, struct page *page,
4066 void *addr = page_address(page);
4068 if (!check_slab(s, page) ||
4069 !on_freelist(s, page, NULL))
4072 /* Now we know that a valid freelist exists */
4073 bitmap_zero(map, page->objects);
4075 get_map(s, page, map);
4076 for_each_object(p, s, addr, page->objects) {
4077 if (test_bit(slab_index(p, s, addr), map))
4078 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4082 for_each_object(p, s, addr, page->objects)
4083 if (!test_bit(slab_index(p, s, addr), map))
4084 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4089 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4093 validate_slab(s, page, map);
4097 static int validate_slab_node(struct kmem_cache *s,
4098 struct kmem_cache_node *n, unsigned long *map)
4100 unsigned long count = 0;
4102 unsigned long flags;
4104 spin_lock_irqsave(&n->list_lock, flags);
4106 list_for_each_entry(page, &n->partial, lru) {
4107 validate_slab_slab(s, page, map);
4110 if (count != n->nr_partial)
4111 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
4112 "counter=%ld\n", s->name, count, n->nr_partial);
4114 if (!(s->flags & SLAB_STORE_USER))
4117 list_for_each_entry(page, &n->full, lru) {
4118 validate_slab_slab(s, page, map);
4121 if (count != atomic_long_read(&n->nr_slabs))
4122 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
4123 "counter=%ld\n", s->name, count,
4124 atomic_long_read(&n->nr_slabs));
4127 spin_unlock_irqrestore(&n->list_lock, flags);
4131 static long validate_slab_cache(struct kmem_cache *s)
4134 unsigned long count = 0;
4135 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4136 sizeof(unsigned long), GFP_KERNEL);
4142 for_each_node_state(node, N_NORMAL_MEMORY) {
4143 struct kmem_cache_node *n = get_node(s, node);
4145 count += validate_slab_node(s, n, map);
4151 * Generate lists of code addresses where slabcache objects are allocated
4156 unsigned long count;
4163 DECLARE_BITMAP(cpus, NR_CPUS);
4169 unsigned long count;
4170 struct location *loc;
4173 static void free_loc_track(struct loc_track *t)
4176 free_pages((unsigned long)t->loc,
4177 get_order(sizeof(struct location) * t->max));
4180 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4185 order = get_order(sizeof(struct location) * max);
4187 l = (void *)__get_free_pages(flags, order);
4192 memcpy(l, t->loc, sizeof(struct location) * t->count);
4200 static int add_location(struct loc_track *t, struct kmem_cache *s,
4201 const struct track *track)
4203 long start, end, pos;
4205 unsigned long caddr;
4206 unsigned long age = jiffies - track->when;
4212 pos = start + (end - start + 1) / 2;
4215 * There is nothing at "end". If we end up there
4216 * we need to add something to before end.
4221 caddr = t->loc[pos].addr;
4222 if (track->addr == caddr) {
4228 if (age < l->min_time)
4230 if (age > l->max_time)
4233 if (track->pid < l->min_pid)
4234 l->min_pid = track->pid;
4235 if (track->pid > l->max_pid)
4236 l->max_pid = track->pid;
4238 cpumask_set_cpu(track->cpu,
4239 to_cpumask(l->cpus));
4241 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4245 if (track->addr < caddr)
4252 * Not found. Insert new tracking element.
4254 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4260 (t->count - pos) * sizeof(struct location));
4263 l->addr = track->addr;
4267 l->min_pid = track->pid;
4268 l->max_pid = track->pid;
4269 cpumask_clear(to_cpumask(l->cpus));
4270 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4271 nodes_clear(l->nodes);
4272 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4276 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4277 struct page *page, enum track_item alloc,
4280 void *addr = page_address(page);
4283 bitmap_zero(map, page->objects);
4284 get_map(s, page, map);
4286 for_each_object(p, s, addr, page->objects)
4287 if (!test_bit(slab_index(p, s, addr), map))
4288 add_location(t, s, get_track(s, p, alloc));
4291 static int list_locations(struct kmem_cache *s, char *buf,
4292 enum track_item alloc)
4296 struct loc_track t = { 0, 0, NULL };
4298 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4299 sizeof(unsigned long), GFP_KERNEL);
4301 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4304 return sprintf(buf, "Out of memory\n");
4306 /* Push back cpu slabs */
4309 for_each_node_state(node, N_NORMAL_MEMORY) {
4310 struct kmem_cache_node *n = get_node(s, node);
4311 unsigned long flags;
4314 if (!atomic_long_read(&n->nr_slabs))
4317 spin_lock_irqsave(&n->list_lock, flags);
4318 list_for_each_entry(page, &n->partial, lru)
4319 process_slab(&t, s, page, alloc, map);
4320 list_for_each_entry(page, &n->full, lru)
4321 process_slab(&t, s, page, alloc, map);
4322 spin_unlock_irqrestore(&n->list_lock, flags);
4325 for (i = 0; i < t.count; i++) {
4326 struct location *l = &t.loc[i];
4328 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4330 len += sprintf(buf + len, "%7ld ", l->count);
4333 len += sprintf(buf + len, "%pS", (void *)l->addr);
4335 len += sprintf(buf + len, "<not-available>");
4337 if (l->sum_time != l->min_time) {
4338 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4340 (long)div_u64(l->sum_time, l->count),
4343 len += sprintf(buf + len, " age=%ld",
4346 if (l->min_pid != l->max_pid)
4347 len += sprintf(buf + len, " pid=%ld-%ld",
4348 l->min_pid, l->max_pid);
4350 len += sprintf(buf + len, " pid=%ld",
4353 if (num_online_cpus() > 1 &&
4354 !cpumask_empty(to_cpumask(l->cpus)) &&
4355 len < PAGE_SIZE - 60) {
4356 len += sprintf(buf + len, " cpus=");
4357 len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
4358 to_cpumask(l->cpus));
4361 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4362 len < PAGE_SIZE - 60) {
4363 len += sprintf(buf + len, " nodes=");
4364 len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
4368 len += sprintf(buf + len, "\n");
4374 len += sprintf(buf, "No data\n");
4379 #ifdef SLUB_RESILIENCY_TEST
4380 static void resiliency_test(void)
4384 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || SLUB_PAGE_SHIFT < 10);
4386 printk(KERN_ERR "SLUB resiliency testing\n");
4387 printk(KERN_ERR "-----------------------\n");
4388 printk(KERN_ERR "A. Corruption after allocation\n");
4390 p = kzalloc(16, GFP_KERNEL);
4392 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
4393 " 0x12->0x%p\n\n", p + 16);
4395 validate_slab_cache(kmalloc_caches[4]);
4397 /* Hmmm... The next two are dangerous */
4398 p = kzalloc(32, GFP_KERNEL);
4399 p[32 + sizeof(void *)] = 0x34;
4400 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
4401 " 0x34 -> -0x%p\n", p);
4403 "If allocated object is overwritten then not detectable\n\n");
4405 validate_slab_cache(kmalloc_caches[5]);
4406 p = kzalloc(64, GFP_KERNEL);
4407 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4409 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4412 "If allocated object is overwritten then not detectable\n\n");
4413 validate_slab_cache(kmalloc_caches[6]);
4415 printk(KERN_ERR "\nB. Corruption after free\n");
4416 p = kzalloc(128, GFP_KERNEL);
4419 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4420 validate_slab_cache(kmalloc_caches[7]);
4422 p = kzalloc(256, GFP_KERNEL);
4425 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n",
4427 validate_slab_cache(kmalloc_caches[8]);
4429 p = kzalloc(512, GFP_KERNEL);
4432 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4433 validate_slab_cache(kmalloc_caches[9]);
4437 static void resiliency_test(void) {};
4442 enum slab_stat_type {
4443 SL_ALL, /* All slabs */
4444 SL_PARTIAL, /* Only partially allocated slabs */
4445 SL_CPU, /* Only slabs used for cpu caches */
4446 SL_OBJECTS, /* Determine allocated objects not slabs */
4447 SL_TOTAL /* Determine object capacity not slabs */
4450 #define SO_ALL (1 << SL_ALL)
4451 #define SO_PARTIAL (1 << SL_PARTIAL)
4452 #define SO_CPU (1 << SL_CPU)
4453 #define SO_OBJECTS (1 << SL_OBJECTS)
4454 #define SO_TOTAL (1 << SL_TOTAL)
4456 static ssize_t show_slab_objects(struct kmem_cache *s,
4457 char *buf, unsigned long flags)
4459 unsigned long total = 0;
4462 unsigned long *nodes;
4463 unsigned long *per_cpu;
4465 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
4468 per_cpu = nodes + nr_node_ids;
4470 if (flags & SO_CPU) {
4473 for_each_possible_cpu(cpu) {
4474 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
4478 page = ACCESS_ONCE(c->page);
4482 node = page_to_nid(page);
4483 if (flags & SO_TOTAL)
4485 else if (flags & SO_OBJECTS)
4493 page = ACCESS_ONCE(c->partial);
4504 lock_memory_hotplug();
4505 #ifdef CONFIG_SLUB_DEBUG
4506 if (flags & SO_ALL) {
4507 for_each_node_state(node, N_NORMAL_MEMORY) {
4508 struct kmem_cache_node *n = get_node(s, node);
4510 if (flags & SO_TOTAL)
4511 x = atomic_long_read(&n->total_objects);
4512 else if (flags & SO_OBJECTS)
4513 x = atomic_long_read(&n->total_objects) -
4514 count_partial(n, count_free);
4517 x = atomic_long_read(&n->nr_slabs);
4524 if (flags & SO_PARTIAL) {
4525 for_each_node_state(node, N_NORMAL_MEMORY) {
4526 struct kmem_cache_node *n = get_node(s, node);
4528 if (flags & SO_TOTAL)
4529 x = count_partial(n, count_total);
4530 else if (flags & SO_OBJECTS)
4531 x = count_partial(n, count_inuse);
4538 x = sprintf(buf, "%lu", total);
4540 for_each_node_state(node, N_NORMAL_MEMORY)
4542 x += sprintf(buf + x, " N%d=%lu",
4545 unlock_memory_hotplug();
4547 return x + sprintf(buf + x, "\n");
4550 #ifdef CONFIG_SLUB_DEBUG
4551 static int any_slab_objects(struct kmem_cache *s)
4555 for_each_online_node(node) {
4556 struct kmem_cache_node *n = get_node(s, node);
4561 if (atomic_long_read(&n->total_objects))
4568 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4569 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4571 struct slab_attribute {
4572 struct attribute attr;
4573 ssize_t (*show)(struct kmem_cache *s, char *buf);
4574 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4577 #define SLAB_ATTR_RO(_name) \
4578 static struct slab_attribute _name##_attr = \
4579 __ATTR(_name, 0400, _name##_show, NULL)
4581 #define SLAB_ATTR(_name) \
4582 static struct slab_attribute _name##_attr = \
4583 __ATTR(_name, 0600, _name##_show, _name##_store)
4585 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4587 return sprintf(buf, "%d\n", s->size);
4589 SLAB_ATTR_RO(slab_size);
4591 static ssize_t align_show(struct kmem_cache *s, char *buf)
4593 return sprintf(buf, "%d\n", s->align);
4595 SLAB_ATTR_RO(align);
4597 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
4599 return sprintf(buf, "%d\n", s->object_size);
4601 SLAB_ATTR_RO(object_size);
4603 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
4605 return sprintf(buf, "%d\n", oo_objects(s->oo));
4607 SLAB_ATTR_RO(objs_per_slab);
4609 static ssize_t order_store(struct kmem_cache *s,
4610 const char *buf, size_t length)
4612 unsigned long order;
4615 err = strict_strtoul(buf, 10, &order);
4619 if (order > slub_max_order || order < slub_min_order)
4622 calculate_sizes(s, order);
4626 static ssize_t order_show(struct kmem_cache *s, char *buf)
4628 return sprintf(buf, "%d\n", oo_order(s->oo));
4632 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
4634 return sprintf(buf, "%lu\n", s->min_partial);
4637 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
4643 err = strict_strtoul(buf, 10, &min);
4647 set_min_partial(s, min);
4650 SLAB_ATTR(min_partial);
4652 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
4654 return sprintf(buf, "%u\n", s->cpu_partial);
4657 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
4660 unsigned long objects;
4663 err = strict_strtoul(buf, 10, &objects);
4666 if (objects && kmem_cache_debug(s))
4669 s->cpu_partial = objects;
4673 SLAB_ATTR(cpu_partial);
4675 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
4679 return sprintf(buf, "%pS\n", s->ctor);
4683 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
4685 return sprintf(buf, "%d\n", s->refcount - 1);
4687 SLAB_ATTR_RO(aliases);
4689 static ssize_t partial_show(struct kmem_cache *s, char *buf)
4691 return show_slab_objects(s, buf, SO_PARTIAL);
4693 SLAB_ATTR_RO(partial);
4695 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
4697 return show_slab_objects(s, buf, SO_CPU);
4699 SLAB_ATTR_RO(cpu_slabs);
4701 static ssize_t objects_show(struct kmem_cache *s, char *buf)
4703 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
4705 SLAB_ATTR_RO(objects);
4707 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
4709 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
4711 SLAB_ATTR_RO(objects_partial);
4713 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
4720 for_each_online_cpu(cpu) {
4721 struct page *page = per_cpu_ptr(s->cpu_slab, cpu)->partial;
4724 pages += page->pages;
4725 objects += page->pobjects;
4729 len = sprintf(buf, "%d(%d)", objects, pages);
4732 for_each_online_cpu(cpu) {
4733 struct page *page = per_cpu_ptr(s->cpu_slab, cpu) ->partial;
4735 if (page && len < PAGE_SIZE - 20)
4736 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
4737 page->pobjects, page->pages);
4740 return len + sprintf(buf + len, "\n");
4742 SLAB_ATTR_RO(slabs_cpu_partial);
4744 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
4746 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
4749 static ssize_t reclaim_account_store(struct kmem_cache *s,
4750 const char *buf, size_t length)
4752 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
4754 s->flags |= SLAB_RECLAIM_ACCOUNT;
4757 SLAB_ATTR(reclaim_account);
4759 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
4761 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
4763 SLAB_ATTR_RO(hwcache_align);
4765 #ifdef CONFIG_ZONE_DMA
4766 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
4768 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
4770 SLAB_ATTR_RO(cache_dma);
4773 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
4775 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
4777 SLAB_ATTR_RO(destroy_by_rcu);
4779 static ssize_t reserved_show(struct kmem_cache *s, char *buf)
4781 return sprintf(buf, "%d\n", s->reserved);
4783 SLAB_ATTR_RO(reserved);
4785 #ifdef CONFIG_SLUB_DEBUG
4786 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
4788 return show_slab_objects(s, buf, SO_ALL);
4790 SLAB_ATTR_RO(slabs);
4792 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
4794 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
4796 SLAB_ATTR_RO(total_objects);
4798 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
4800 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
4803 static ssize_t sanity_checks_store(struct kmem_cache *s,
4804 const char *buf, size_t length)
4806 s->flags &= ~SLAB_DEBUG_FREE;
4807 if (buf[0] == '1') {
4808 s->flags &= ~__CMPXCHG_DOUBLE;
4809 s->flags |= SLAB_DEBUG_FREE;
4813 SLAB_ATTR(sanity_checks);
4815 static ssize_t trace_show(struct kmem_cache *s, char *buf)
4817 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
4820 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
4823 s->flags &= ~SLAB_TRACE;
4824 if (buf[0] == '1') {
4825 s->flags &= ~__CMPXCHG_DOUBLE;
4826 s->flags |= SLAB_TRACE;
4832 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
4834 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
4837 static ssize_t red_zone_store(struct kmem_cache *s,
4838 const char *buf, size_t length)
4840 if (any_slab_objects(s))
4843 s->flags &= ~SLAB_RED_ZONE;
4844 if (buf[0] == '1') {
4845 s->flags &= ~__CMPXCHG_DOUBLE;
4846 s->flags |= SLAB_RED_ZONE;
4848 calculate_sizes(s, -1);
4851 SLAB_ATTR(red_zone);
4853 static ssize_t poison_show(struct kmem_cache *s, char *buf)
4855 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
4858 static ssize_t poison_store(struct kmem_cache *s,
4859 const char *buf, size_t length)
4861 if (any_slab_objects(s))
4864 s->flags &= ~SLAB_POISON;
4865 if (buf[0] == '1') {
4866 s->flags &= ~__CMPXCHG_DOUBLE;
4867 s->flags |= SLAB_POISON;
4869 calculate_sizes(s, -1);
4874 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
4876 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
4879 static ssize_t store_user_store(struct kmem_cache *s,
4880 const char *buf, size_t length)
4882 if (any_slab_objects(s))
4885 s->flags &= ~SLAB_STORE_USER;
4886 if (buf[0] == '1') {
4887 s->flags &= ~__CMPXCHG_DOUBLE;
4888 s->flags |= SLAB_STORE_USER;
4890 calculate_sizes(s, -1);
4893 SLAB_ATTR(store_user);
4895 static ssize_t validate_show(struct kmem_cache *s, char *buf)
4900 static ssize_t validate_store(struct kmem_cache *s,
4901 const char *buf, size_t length)
4905 if (buf[0] == '1') {
4906 ret = validate_slab_cache(s);
4912 SLAB_ATTR(validate);
4914 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
4916 if (!(s->flags & SLAB_STORE_USER))
4918 return list_locations(s, buf, TRACK_ALLOC);
4920 SLAB_ATTR_RO(alloc_calls);
4922 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
4924 if (!(s->flags & SLAB_STORE_USER))
4926 return list_locations(s, buf, TRACK_FREE);
4928 SLAB_ATTR_RO(free_calls);
4929 #endif /* CONFIG_SLUB_DEBUG */
4931 #ifdef CONFIG_FAILSLAB
4932 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
4934 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
4937 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
4940 s->flags &= ~SLAB_FAILSLAB;
4942 s->flags |= SLAB_FAILSLAB;
4945 SLAB_ATTR(failslab);
4948 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
4953 static ssize_t shrink_store(struct kmem_cache *s,
4954 const char *buf, size_t length)
4956 if (buf[0] == '1') {
4957 int rc = kmem_cache_shrink(s);
4968 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
4970 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
4973 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
4974 const char *buf, size_t length)
4976 unsigned long ratio;
4979 err = strict_strtoul(buf, 10, &ratio);
4984 s->remote_node_defrag_ratio = ratio * 10;
4988 SLAB_ATTR(remote_node_defrag_ratio);
4991 #ifdef CONFIG_SLUB_STATS
4992 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
4994 unsigned long sum = 0;
4997 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
5002 for_each_online_cpu(cpu) {
5003 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
5009 len = sprintf(buf, "%lu", sum);
5012 for_each_online_cpu(cpu) {
5013 if (data[cpu] && len < PAGE_SIZE - 20)
5014 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5018 return len + sprintf(buf + len, "\n");
5021 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5025 for_each_online_cpu(cpu)
5026 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5029 #define STAT_ATTR(si, text) \
5030 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5032 return show_stat(s, buf, si); \
5034 static ssize_t text##_store(struct kmem_cache *s, \
5035 const char *buf, size_t length) \
5037 if (buf[0] != '0') \
5039 clear_stat(s, si); \
5044 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5045 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5046 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5047 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5048 STAT_ATTR(FREE_FROZEN, free_frozen);
5049 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5050 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5051 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5052 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5053 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5054 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5055 STAT_ATTR(FREE_SLAB, free_slab);
5056 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5057 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5058 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5059 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5060 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5061 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5062 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5063 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5064 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5065 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5066 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5067 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5068 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node);
5069 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain);
5072 static struct attribute *slab_attrs[] = {
5073 &slab_size_attr.attr,
5074 &object_size_attr.attr,
5075 &objs_per_slab_attr.attr,
5077 &min_partial_attr.attr,
5078 &cpu_partial_attr.attr,
5080 &objects_partial_attr.attr,
5082 &cpu_slabs_attr.attr,
5086 &hwcache_align_attr.attr,
5087 &reclaim_account_attr.attr,
5088 &destroy_by_rcu_attr.attr,
5090 &reserved_attr.attr,
5091 &slabs_cpu_partial_attr.attr,
5092 #ifdef CONFIG_SLUB_DEBUG
5093 &total_objects_attr.attr,
5095 &sanity_checks_attr.attr,
5097 &red_zone_attr.attr,
5099 &store_user_attr.attr,
5100 &validate_attr.attr,
5101 &alloc_calls_attr.attr,
5102 &free_calls_attr.attr,
5104 #ifdef CONFIG_ZONE_DMA
5105 &cache_dma_attr.attr,
5108 &remote_node_defrag_ratio_attr.attr,
5110 #ifdef CONFIG_SLUB_STATS
5111 &alloc_fastpath_attr.attr,
5112 &alloc_slowpath_attr.attr,
5113 &free_fastpath_attr.attr,
5114 &free_slowpath_attr.attr,
5115 &free_frozen_attr.attr,
5116 &free_add_partial_attr.attr,
5117 &free_remove_partial_attr.attr,
5118 &alloc_from_partial_attr.attr,
5119 &alloc_slab_attr.attr,
5120 &alloc_refill_attr.attr,
5121 &alloc_node_mismatch_attr.attr,
5122 &free_slab_attr.attr,
5123 &cpuslab_flush_attr.attr,
5124 &deactivate_full_attr.attr,
5125 &deactivate_empty_attr.attr,
5126 &deactivate_to_head_attr.attr,
5127 &deactivate_to_tail_attr.attr,
5128 &deactivate_remote_frees_attr.attr,
5129 &deactivate_bypass_attr.attr,
5130 &order_fallback_attr.attr,
5131 &cmpxchg_double_fail_attr.attr,
5132 &cmpxchg_double_cpu_fail_attr.attr,
5133 &cpu_partial_alloc_attr.attr,
5134 &cpu_partial_free_attr.attr,
5135 &cpu_partial_node_attr.attr,
5136 &cpu_partial_drain_attr.attr,
5138 #ifdef CONFIG_FAILSLAB
5139 &failslab_attr.attr,
5145 static struct attribute_group slab_attr_group = {
5146 .attrs = slab_attrs,
5149 static ssize_t slab_attr_show(struct kobject *kobj,
5150 struct attribute *attr,
5153 struct slab_attribute *attribute;
5154 struct kmem_cache *s;
5157 attribute = to_slab_attr(attr);
5160 if (!attribute->show)
5163 err = attribute->show(s, buf);
5168 static ssize_t slab_attr_store(struct kobject *kobj,
5169 struct attribute *attr,
5170 const char *buf, size_t len)
5172 struct slab_attribute *attribute;
5173 struct kmem_cache *s;
5176 attribute = to_slab_attr(attr);
5179 if (!attribute->store)
5182 err = attribute->store(s, buf, len);
5187 static void kmem_cache_release(struct kobject *kobj)
5189 struct kmem_cache *s = to_slab(kobj);
5195 static const struct sysfs_ops slab_sysfs_ops = {
5196 .show = slab_attr_show,
5197 .store = slab_attr_store,
5200 static struct kobj_type slab_ktype = {
5201 .sysfs_ops = &slab_sysfs_ops,
5202 .release = kmem_cache_release
5205 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5207 struct kobj_type *ktype = get_ktype(kobj);
5209 if (ktype == &slab_ktype)
5214 static const struct kset_uevent_ops slab_uevent_ops = {
5215 .filter = uevent_filter,
5218 static struct kset *slab_kset;
5220 #define ID_STR_LENGTH 64
5222 /* Create a unique string id for a slab cache:
5224 * Format :[flags-]size
5226 static char *create_unique_id(struct kmem_cache *s)
5228 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5235 * First flags affecting slabcache operations. We will only
5236 * get here for aliasable slabs so we do not need to support
5237 * too many flags. The flags here must cover all flags that
5238 * are matched during merging to guarantee that the id is
5241 if (s->flags & SLAB_CACHE_DMA)
5243 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5245 if (s->flags & SLAB_DEBUG_FREE)
5247 if (!(s->flags & SLAB_NOTRACK))
5251 p += sprintf(p, "%07d", s->size);
5252 BUG_ON(p > name + ID_STR_LENGTH - 1);
5256 static int sysfs_slab_add(struct kmem_cache *s)
5262 if (slab_state < FULL)
5263 /* Defer until later */
5266 unmergeable = slab_unmergeable(s);
5269 * Slabcache can never be merged so we can use the name proper.
5270 * This is typically the case for debug situations. In that
5271 * case we can catch duplicate names easily.
5273 sysfs_remove_link(&slab_kset->kobj, s->name);
5277 * Create a unique name for the slab as a target
5280 name = create_unique_id(s);
5283 s->kobj.kset = slab_kset;
5284 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, name);
5286 kobject_put(&s->kobj);
5290 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5292 kobject_del(&s->kobj);
5293 kobject_put(&s->kobj);
5296 kobject_uevent(&s->kobj, KOBJ_ADD);
5298 /* Setup first alias */
5299 sysfs_slab_alias(s, s->name);
5305 static void sysfs_slab_remove(struct kmem_cache *s)
5307 if (slab_state < FULL)
5309 * Sysfs has not been setup yet so no need to remove the
5314 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5315 kobject_del(&s->kobj);
5316 kobject_put(&s->kobj);
5320 * Need to buffer aliases during bootup until sysfs becomes
5321 * available lest we lose that information.
5323 struct saved_alias {
5324 struct kmem_cache *s;
5326 struct saved_alias *next;
5329 static struct saved_alias *alias_list;
5331 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5333 struct saved_alias *al;
5335 if (slab_state == FULL) {
5337 * If we have a leftover link then remove it.
5339 sysfs_remove_link(&slab_kset->kobj, name);
5340 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5343 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5349 al->next = alias_list;
5354 static int __init slab_sysfs_init(void)
5356 struct kmem_cache *s;
5359 mutex_lock(&slab_mutex);
5361 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5363 mutex_unlock(&slab_mutex);
5364 printk(KERN_ERR "Cannot register slab subsystem.\n");
5370 list_for_each_entry(s, &slab_caches, list) {
5371 err = sysfs_slab_add(s);
5373 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
5374 " to sysfs\n", s->name);
5377 while (alias_list) {
5378 struct saved_alias *al = alias_list;
5380 alias_list = alias_list->next;
5381 err = sysfs_slab_alias(al->s, al->name);
5383 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
5384 " %s to sysfs\n", al->name);
5388 mutex_unlock(&slab_mutex);
5393 __initcall(slab_sysfs_init);
5394 #endif /* CONFIG_SYSFS */
5397 * The /proc/slabinfo ABI
5399 #ifdef CONFIG_SLABINFO
5400 static void print_slabinfo_header(struct seq_file *m)
5402 seq_puts(m, "slabinfo - version: 2.1\n");
5403 seq_puts(m, "# name <active_objs> <num_objs> <object_size> "
5404 "<objperslab> <pagesperslab>");
5405 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
5406 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
5410 static void *s_start(struct seq_file *m, loff_t *pos)
5414 mutex_lock(&slab_mutex);
5416 print_slabinfo_header(m);
5418 return seq_list_start(&slab_caches, *pos);
5421 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
5423 return seq_list_next(p, &slab_caches, pos);
5426 static void s_stop(struct seq_file *m, void *p)
5428 mutex_unlock(&slab_mutex);
5431 static int s_show(struct seq_file *m, void *p)
5433 unsigned long nr_partials = 0;
5434 unsigned long nr_slabs = 0;
5435 unsigned long nr_inuse = 0;
5436 unsigned long nr_objs = 0;
5437 unsigned long nr_free = 0;
5438 struct kmem_cache *s;
5441 s = list_entry(p, struct kmem_cache, list);
5443 for_each_online_node(node) {
5444 struct kmem_cache_node *n = get_node(s, node);
5449 nr_partials += n->nr_partial;
5450 nr_slabs += atomic_long_read(&n->nr_slabs);
5451 nr_objs += atomic_long_read(&n->total_objects);
5452 nr_free += count_partial(n, count_free);
5455 nr_inuse = nr_objs - nr_free;
5457 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", s->name, nr_inuse,
5458 nr_objs, s->size, oo_objects(s->oo),
5459 (1 << oo_order(s->oo)));
5460 seq_printf(m, " : tunables %4u %4u %4u", 0, 0, 0);
5461 seq_printf(m, " : slabdata %6lu %6lu %6lu", nr_slabs, nr_slabs,
5467 static const struct seq_operations slabinfo_op = {
5474 static int slabinfo_open(struct inode *inode, struct file *file)
5476 return seq_open(file, &slabinfo_op);
5479 static const struct file_operations proc_slabinfo_operations = {
5480 .open = slabinfo_open,
5482 .llseek = seq_lseek,
5483 .release = seq_release,
5486 static int __init slab_proc_init(void)
5488 proc_create("slabinfo", S_IRUSR, NULL, &proc_slabinfo_operations);
5491 module_init(slab_proc_init);
5492 #endif /* CONFIG_SLABINFO */