While back-porting Johannes Weiner's patch "mm: memcg-aware global
[linux-2.6/next.git] / mm / slub.c
blobacdbe862ee00c2ccddd3a26f7f9e4597481d511b
1 /*
2 * SLUB: A slab allocator that limits cache line use instead of queuing
3 * objects in per cpu and per node lists.
5 * The allocator synchronizes using per slab locks 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
12 #include <linux/mm.h>
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>
19 #include <linux/proc_fs.h>
20 #include <linux/seq_file.h>
21 #include <linux/kmemcheck.h>
22 #include <linux/cpu.h>
23 #include <linux/cpuset.h>
24 #include <linux/mempolicy.h>
25 #include <linux/ctype.h>
26 #include <linux/debugobjects.h>
27 #include <linux/kallsyms.h>
28 #include <linux/memory.h>
29 #include <linux/math64.h>
30 #include <linux/fault-inject.h>
31 #include <linux/stacktrace.h>
33 #include <trace/events/kmem.h>
36 * Lock order:
37 * 1. slub_lock (Global Semaphore)
38 * 2. node->list_lock
39 * 3. slab_lock(page) (Only on some arches and for debugging)
41 * slub_lock
43 * The role of the slub_lock is to protect the list of all the slabs
44 * and to synchronize major metadata changes to slab cache structures.
46 * The slab_lock is only used for debugging and on arches that do not
47 * have the ability to do a cmpxchg_double. It only protects the second
48 * double word in the page struct. Meaning
49 * A. page->freelist -> List of object free in a page
50 * B. page->counters -> Counters of objects
51 * C. page->frozen -> frozen state
53 * If a slab is frozen then it is exempt from list management. It is not
54 * on any list. The processor that froze the slab is the one who can
55 * perform list operations on the page. Other processors may put objects
56 * onto the freelist but the processor that froze the slab is the only
57 * one that can retrieve the objects from the page's freelist.
59 * The list_lock protects the partial and full list on each node and
60 * the partial slab counter. If taken then no new slabs may be added or
61 * removed from the lists nor make the number of partial slabs be modified.
62 * (Note that the total number of slabs is an atomic value that may be
63 * modified without taking the list lock).
65 * The list_lock is a centralized lock and thus we avoid taking it as
66 * much as possible. As long as SLUB does not have to handle partial
67 * slabs, operations can continue without any centralized lock. F.e.
68 * allocating a long series of objects that fill up slabs does not require
69 * the list lock.
70 * Interrupts are disabled during allocation and deallocation in order to
71 * make the slab allocator safe to use in the context of an irq. In addition
72 * interrupts are disabled to ensure that the processor does not change
73 * while handling per_cpu slabs, due to kernel preemption.
75 * SLUB assigns one slab for allocation to each processor.
76 * Allocations only occur from these slabs called cpu slabs.
78 * Slabs with free elements are kept on a partial list and during regular
79 * operations no list for full slabs is used. If an object in a full slab is
80 * freed then the slab will show up again on the partial lists.
81 * We track full slabs for debugging purposes though because otherwise we
82 * cannot scan all objects.
84 * Slabs are freed when they become empty. Teardown and setup is
85 * minimal so we rely on the page allocators per cpu caches for
86 * fast frees and allocs.
88 * Overloading of page flags that are otherwise used for LRU management.
90 * PageActive The slab is frozen and exempt from list processing.
91 * This means that the slab is dedicated to a purpose
92 * such as satisfying allocations for a specific
93 * processor. Objects may be freed in the slab while
94 * it is frozen but slab_free will then skip the usual
95 * list operations. It is up to the processor holding
96 * the slab to integrate the slab into the slab lists
97 * when the slab is no longer needed.
99 * One use of this flag is to mark slabs that are
100 * used for allocations. Then such a slab becomes a cpu
101 * slab. The cpu slab may be equipped with an additional
102 * freelist that allows lockless access to
103 * free objects in addition to the regular freelist
104 * that requires the slab lock.
106 * PageError Slab requires special handling due to debug
107 * options set. This moves slab handling out of
108 * the fast path and disables lockless freelists.
111 #define SLAB_DEBUG_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
112 SLAB_TRACE | SLAB_DEBUG_FREE)
114 static inline int kmem_cache_debug(struct kmem_cache *s)
116 #ifdef CONFIG_SLUB_DEBUG
117 return unlikely(s->flags & SLAB_DEBUG_FLAGS);
118 #else
119 return 0;
120 #endif
124 * Issues still to be resolved:
126 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
128 * - Variable sizing of the per node arrays
131 /* Enable to test recovery from slab corruption on boot */
132 #undef SLUB_RESILIENCY_TEST
134 /* Enable to log cmpxchg failures */
135 #undef SLUB_DEBUG_CMPXCHG
138 * Mininum number of partial slabs. These will be left on the partial
139 * lists even if they are empty. kmem_cache_shrink may reclaim them.
141 #define MIN_PARTIAL 5
144 * Maximum number of desirable partial slabs.
145 * The existence of more partial slabs makes kmem_cache_shrink
146 * sort the partial list by the number of objects in the.
148 #define MAX_PARTIAL 10
150 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
151 SLAB_POISON | SLAB_STORE_USER)
154 * Debugging flags that require metadata to be stored in the slab. These get
155 * disabled when slub_debug=O is used and a cache's min order increases with
156 * metadata.
158 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
161 * Set of flags that will prevent slab merging
163 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
164 SLAB_TRACE | SLAB_DESTROY_BY_RCU | SLAB_NOLEAKTRACE | \
165 SLAB_FAILSLAB)
167 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
168 SLAB_CACHE_DMA | SLAB_NOTRACK)
170 #define OO_SHIFT 16
171 #define OO_MASK ((1 << OO_SHIFT) - 1)
172 #define MAX_OBJS_PER_PAGE 32767 /* since page.objects is u15 */
174 /* Internal SLUB flags */
175 #define __OBJECT_POISON 0x80000000UL /* Poison object */
176 #define __CMPXCHG_DOUBLE 0x40000000UL /* Use cmpxchg_double */
178 static int kmem_size = sizeof(struct kmem_cache);
180 #ifdef CONFIG_SMP
181 static struct notifier_block slab_notifier;
182 #endif
184 static enum {
185 DOWN, /* No slab functionality available */
186 PARTIAL, /* Kmem_cache_node works */
187 UP, /* Everything works but does not show up in sysfs */
188 SYSFS /* Sysfs up */
189 } slab_state = DOWN;
191 /* A list of all slab caches on the system */
192 static DECLARE_RWSEM(slub_lock);
193 static LIST_HEAD(slab_caches);
196 * Tracking user of a slab.
198 #define TRACK_ADDRS_COUNT 16
199 struct track {
200 unsigned long addr; /* Called from address */
201 #ifdef CONFIG_STACKTRACE
202 unsigned long addrs[TRACK_ADDRS_COUNT]; /* Called from address */
203 #endif
204 int cpu; /* Was running on cpu */
205 int pid; /* Pid context */
206 unsigned long when; /* When did the operation occur */
209 enum track_item { TRACK_ALLOC, TRACK_FREE };
211 #ifdef CONFIG_SYSFS
212 static int sysfs_slab_add(struct kmem_cache *);
213 static int sysfs_slab_alias(struct kmem_cache *, const char *);
214 static void sysfs_slab_remove(struct kmem_cache *);
216 #else
217 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
218 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
219 { return 0; }
220 static inline void sysfs_slab_remove(struct kmem_cache *s)
222 kfree(s->name);
223 kfree(s);
226 #endif
228 static inline void stat(const struct kmem_cache *s, enum stat_item si)
230 #ifdef CONFIG_SLUB_STATS
231 __this_cpu_inc(s->cpu_slab->stat[si]);
232 #endif
235 /********************************************************************
236 * Core slab cache functions
237 *******************************************************************/
239 int slab_is_available(void)
241 return slab_state >= UP;
244 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
246 return s->node[node];
249 /* Verify that a pointer has an address that is valid within a slab page */
250 static inline int check_valid_pointer(struct kmem_cache *s,
251 struct page *page, const void *object)
253 void *base;
255 if (!object)
256 return 1;
258 base = page_address(page);
259 if (object < base || object >= base + page->objects * s->size ||
260 (object - base) % s->size) {
261 return 0;
264 return 1;
267 static inline void *get_freepointer(struct kmem_cache *s, void *object)
269 return *(void **)(object + s->offset);
272 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object)
274 void *p;
276 #ifdef CONFIG_DEBUG_PAGEALLOC
277 probe_kernel_read(&p, (void **)(object + s->offset), sizeof(p));
278 #else
279 p = get_freepointer(s, object);
280 #endif
281 return p;
284 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
286 *(void **)(object + s->offset) = fp;
289 /* Loop over all objects in a slab */
290 #define for_each_object(__p, __s, __addr, __objects) \
291 for (__p = (__addr); __p < (__addr) + (__objects) * (__s)->size;\
292 __p += (__s)->size)
294 /* Determine object index from a given position */
295 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
297 return (p - addr) / s->size;
300 static inline size_t slab_ksize(const struct kmem_cache *s)
302 #ifdef CONFIG_SLUB_DEBUG
304 * Debugging requires use of the padding between object
305 * and whatever may come after it.
307 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
308 return s->objsize;
310 #endif
312 * If we have the need to store the freelist pointer
313 * back there or track user information then we can
314 * only use the space before that information.
316 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
317 return s->inuse;
319 * Else we can use all the padding etc for the allocation
321 return s->size;
324 static inline int order_objects(int order, unsigned long size, int reserved)
326 return ((PAGE_SIZE << order) - reserved) / size;
329 static inline struct kmem_cache_order_objects oo_make(int order,
330 unsigned long size, int reserved)
332 struct kmem_cache_order_objects x = {
333 (order << OO_SHIFT) + order_objects(order, size, reserved)
336 return x;
339 static inline int oo_order(struct kmem_cache_order_objects x)
341 return x.x >> OO_SHIFT;
344 static inline int oo_objects(struct kmem_cache_order_objects x)
346 return x.x & OO_MASK;
350 * Per slab locking using the pagelock
352 static __always_inline void slab_lock(struct page *page)
354 bit_spin_lock(PG_locked, &page->flags);
357 static __always_inline void slab_unlock(struct page *page)
359 __bit_spin_unlock(PG_locked, &page->flags);
362 /* Interrupts must be disabled (for the fallback code to work right) */
363 static inline bool __cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
364 void *freelist_old, unsigned long counters_old,
365 void *freelist_new, unsigned long counters_new,
366 const char *n)
368 VM_BUG_ON(!irqs_disabled());
369 #ifdef CONFIG_CMPXCHG_DOUBLE
370 if (s->flags & __CMPXCHG_DOUBLE) {
371 if (cmpxchg_double(&page->freelist,
372 freelist_old, counters_old,
373 freelist_new, counters_new))
374 return 1;
375 } else
376 #endif
378 slab_lock(page);
379 if (page->freelist == freelist_old && page->counters == counters_old) {
380 page->freelist = freelist_new;
381 page->counters = counters_new;
382 slab_unlock(page);
383 return 1;
385 slab_unlock(page);
388 cpu_relax();
389 stat(s, CMPXCHG_DOUBLE_FAIL);
391 #ifdef SLUB_DEBUG_CMPXCHG
392 printk(KERN_INFO "%s %s: cmpxchg double redo ", n, s->name);
393 #endif
395 return 0;
398 static inline bool cmpxchg_double_slab(struct kmem_cache *s, struct page *page,
399 void *freelist_old, unsigned long counters_old,
400 void *freelist_new, unsigned long counters_new,
401 const char *n)
403 #ifdef CONFIG_CMPXCHG_DOUBLE
404 if (s->flags & __CMPXCHG_DOUBLE) {
405 if (cmpxchg_double(&page->freelist,
406 freelist_old, counters_old,
407 freelist_new, counters_new))
408 return 1;
409 } else
410 #endif
412 unsigned long flags;
414 local_irq_save(flags);
415 slab_lock(page);
416 if (page->freelist == freelist_old && page->counters == counters_old) {
417 page->freelist = freelist_new;
418 page->counters = counters_new;
419 slab_unlock(page);
420 local_irq_restore(flags);
421 return 1;
423 slab_unlock(page);
424 local_irq_restore(flags);
427 cpu_relax();
428 stat(s, CMPXCHG_DOUBLE_FAIL);
430 #ifdef SLUB_DEBUG_CMPXCHG
431 printk(KERN_INFO "%s %s: cmpxchg double redo ", n, s->name);
432 #endif
434 return 0;
437 #ifdef CONFIG_SLUB_DEBUG
439 * Determine a map of object in use on a page.
441 * Node listlock must be held to guarantee that the page does
442 * not vanish from under us.
444 static void get_map(struct kmem_cache *s, struct page *page, unsigned long *map)
446 void *p;
447 void *addr = page_address(page);
449 for (p = page->freelist; p; p = get_freepointer(s, p))
450 set_bit(slab_index(p, s, addr), map);
454 * Debug settings:
456 #ifdef CONFIG_SLUB_DEBUG_ON
457 static int slub_debug = DEBUG_DEFAULT_FLAGS;
458 #else
459 static int slub_debug;
460 #endif
462 static char *slub_debug_slabs;
463 static int disable_higher_order_debug;
466 * Object debugging
468 static void print_section(char *text, u8 *addr, unsigned int length)
470 int i, offset;
471 int newline = 1;
472 char ascii[17];
474 ascii[16] = 0;
476 for (i = 0; i < length; i++) {
477 if (newline) {
478 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
479 newline = 0;
481 printk(KERN_CONT " %02x", addr[i]);
482 offset = i % 16;
483 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
484 if (offset == 15) {
485 printk(KERN_CONT " %s\n", ascii);
486 newline = 1;
489 if (!newline) {
490 i %= 16;
491 while (i < 16) {
492 printk(KERN_CONT " ");
493 ascii[i] = ' ';
494 i++;
496 printk(KERN_CONT " %s\n", ascii);
500 static struct track *get_track(struct kmem_cache *s, void *object,
501 enum track_item alloc)
503 struct track *p;
505 if (s->offset)
506 p = object + s->offset + sizeof(void *);
507 else
508 p = object + s->inuse;
510 return p + alloc;
513 static void set_track(struct kmem_cache *s, void *object,
514 enum track_item alloc, unsigned long addr)
516 struct track *p = get_track(s, object, alloc);
518 if (addr) {
519 #ifdef CONFIG_STACKTRACE
520 struct stack_trace trace;
521 int i;
523 trace.nr_entries = 0;
524 trace.max_entries = TRACK_ADDRS_COUNT;
525 trace.entries = p->addrs;
526 trace.skip = 3;
527 save_stack_trace(&trace);
529 /* See rant in lockdep.c */
530 if (trace.nr_entries != 0 &&
531 trace.entries[trace.nr_entries - 1] == ULONG_MAX)
532 trace.nr_entries--;
534 for (i = trace.nr_entries; i < TRACK_ADDRS_COUNT; i++)
535 p->addrs[i] = 0;
536 #endif
537 p->addr = addr;
538 p->cpu = smp_processor_id();
539 p->pid = current->pid;
540 p->when = jiffies;
541 } else
542 memset(p, 0, sizeof(struct track));
545 static void init_tracking(struct kmem_cache *s, void *object)
547 if (!(s->flags & SLAB_STORE_USER))
548 return;
550 set_track(s, object, TRACK_FREE, 0UL);
551 set_track(s, object, TRACK_ALLOC, 0UL);
554 static void print_track(const char *s, struct track *t)
556 if (!t->addr)
557 return;
559 printk(KERN_ERR "INFO: %s in %pS age=%lu cpu=%u pid=%d\n",
560 s, (void *)t->addr, jiffies - t->when, t->cpu, t->pid);
561 #ifdef CONFIG_STACKTRACE
563 int i;
564 for (i = 0; i < TRACK_ADDRS_COUNT; i++)
565 if (t->addrs[i])
566 printk(KERN_ERR "\t%pS\n", (void *)t->addrs[i]);
567 else
568 break;
570 #endif
573 static void print_tracking(struct kmem_cache *s, void *object)
575 if (!(s->flags & SLAB_STORE_USER))
576 return;
578 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
579 print_track("Freed", get_track(s, object, TRACK_FREE));
582 static void print_page_info(struct page *page)
584 printk(KERN_ERR "INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
585 page, page->objects, page->inuse, page->freelist, page->flags);
589 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
591 va_list args;
592 char buf[100];
594 va_start(args, fmt);
595 vsnprintf(buf, sizeof(buf), fmt, args);
596 va_end(args);
597 printk(KERN_ERR "========================================"
598 "=====================================\n");
599 printk(KERN_ERR "BUG %s (%s): %s\n", s->name, print_tainted(), buf);
600 printk(KERN_ERR "----------------------------------------"
601 "-------------------------------------\n\n");
604 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
606 va_list args;
607 char buf[100];
609 va_start(args, fmt);
610 vsnprintf(buf, sizeof(buf), fmt, args);
611 va_end(args);
612 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
615 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
617 unsigned int off; /* Offset of last byte */
618 u8 *addr = page_address(page);
620 print_tracking(s, p);
622 print_page_info(page);
624 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
625 p, p - addr, get_freepointer(s, p));
627 if (p > addr + 16)
628 print_section("Bytes b4", p - 16, 16);
630 print_section("Object", p, min_t(unsigned long, s->objsize, PAGE_SIZE));
632 if (s->flags & SLAB_RED_ZONE)
633 print_section("Redzone", p + s->objsize,
634 s->inuse - s->objsize);
636 if (s->offset)
637 off = s->offset + sizeof(void *);
638 else
639 off = s->inuse;
641 if (s->flags & SLAB_STORE_USER)
642 off += 2 * sizeof(struct track);
644 if (off != s->size)
645 /* Beginning of the filler is the free pointer */
646 print_section("Padding", p + off, s->size - off);
648 dump_stack();
651 static void object_err(struct kmem_cache *s, struct page *page,
652 u8 *object, char *reason)
654 slab_bug(s, "%s", reason);
655 print_trailer(s, page, object);
658 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
660 va_list args;
661 char buf[100];
663 va_start(args, fmt);
664 vsnprintf(buf, sizeof(buf), fmt, args);
665 va_end(args);
666 slab_bug(s, "%s", buf);
667 print_page_info(page);
668 dump_stack();
671 static void init_object(struct kmem_cache *s, void *object, u8 val)
673 u8 *p = object;
675 if (s->flags & __OBJECT_POISON) {
676 memset(p, POISON_FREE, s->objsize - 1);
677 p[s->objsize - 1] = POISON_END;
680 if (s->flags & SLAB_RED_ZONE)
681 memset(p + s->objsize, val, s->inuse - s->objsize);
684 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
685 void *from, void *to)
687 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
688 memset(from, data, to - from);
691 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
692 u8 *object, char *what,
693 u8 *start, unsigned int value, unsigned int bytes)
695 u8 *fault;
696 u8 *end;
698 fault = memchr_inv(start, value, bytes);
699 if (!fault)
700 return 1;
702 end = start + bytes;
703 while (end > fault && end[-1] == value)
704 end--;
706 slab_bug(s, "%s overwritten", what);
707 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
708 fault, end - 1, fault[0], value);
709 print_trailer(s, page, object);
711 restore_bytes(s, what, value, fault, end);
712 return 0;
716 * Object layout:
718 * object address
719 * Bytes of the object to be managed.
720 * If the freepointer may overlay the object then the free
721 * pointer is the first word of the object.
723 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
724 * 0xa5 (POISON_END)
726 * object + s->objsize
727 * Padding to reach word boundary. This is also used for Redzoning.
728 * Padding is extended by another word if Redzoning is enabled and
729 * objsize == inuse.
731 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
732 * 0xcc (RED_ACTIVE) for objects in use.
734 * object + s->inuse
735 * Meta data starts here.
737 * A. Free pointer (if we cannot overwrite object on free)
738 * B. Tracking data for SLAB_STORE_USER
739 * C. Padding to reach required alignment boundary or at mininum
740 * one word if debugging is on to be able to detect writes
741 * before the word boundary.
743 * Padding is done using 0x5a (POISON_INUSE)
745 * object + s->size
746 * Nothing is used beyond s->size.
748 * If slabcaches are merged then the objsize and inuse boundaries are mostly
749 * ignored. And therefore no slab options that rely on these boundaries
750 * may be used with merged slabcaches.
753 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
755 unsigned long off = s->inuse; /* The end of info */
757 if (s->offset)
758 /* Freepointer is placed after the object. */
759 off += sizeof(void *);
761 if (s->flags & SLAB_STORE_USER)
762 /* We also have user information there */
763 off += 2 * sizeof(struct track);
765 if (s->size == off)
766 return 1;
768 return check_bytes_and_report(s, page, p, "Object padding",
769 p + off, POISON_INUSE, s->size - off);
772 /* Check the pad bytes at the end of a slab page */
773 static int slab_pad_check(struct kmem_cache *s, struct page *page)
775 u8 *start;
776 u8 *fault;
777 u8 *end;
778 int length;
779 int remainder;
781 if (!(s->flags & SLAB_POISON))
782 return 1;
784 start = page_address(page);
785 length = (PAGE_SIZE << compound_order(page)) - s->reserved;
786 end = start + length;
787 remainder = length % s->size;
788 if (!remainder)
789 return 1;
791 fault = memchr_inv(end - remainder, POISON_INUSE, remainder);
792 if (!fault)
793 return 1;
794 while (end > fault && end[-1] == POISON_INUSE)
795 end--;
797 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
798 print_section("Padding", end - remainder, remainder);
800 restore_bytes(s, "slab padding", POISON_INUSE, end - remainder, end);
801 return 0;
804 static int check_object(struct kmem_cache *s, struct page *page,
805 void *object, u8 val)
807 u8 *p = object;
808 u8 *endobject = object + s->objsize;
810 if (s->flags & SLAB_RED_ZONE) {
811 if (!check_bytes_and_report(s, page, object, "Redzone",
812 endobject, val, s->inuse - s->objsize))
813 return 0;
814 } else {
815 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse) {
816 check_bytes_and_report(s, page, p, "Alignment padding",
817 endobject, POISON_INUSE, s->inuse - s->objsize);
821 if (s->flags & SLAB_POISON) {
822 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON) &&
823 (!check_bytes_and_report(s, page, p, "Poison", p,
824 POISON_FREE, s->objsize - 1) ||
825 !check_bytes_and_report(s, page, p, "Poison",
826 p + s->objsize - 1, POISON_END, 1)))
827 return 0;
829 * check_pad_bytes cleans up on its own.
831 check_pad_bytes(s, page, p);
834 if (!s->offset && val == SLUB_RED_ACTIVE)
836 * Object and freepointer overlap. Cannot check
837 * freepointer while object is allocated.
839 return 1;
841 /* Check free pointer validity */
842 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
843 object_err(s, page, p, "Freepointer corrupt");
845 * No choice but to zap it and thus lose the remainder
846 * of the free objects in this slab. May cause
847 * another error because the object count is now wrong.
849 set_freepointer(s, p, NULL);
850 return 0;
852 return 1;
855 static int check_slab(struct kmem_cache *s, struct page *page)
857 int maxobj;
859 VM_BUG_ON(!irqs_disabled());
861 if (!PageSlab(page)) {
862 slab_err(s, page, "Not a valid slab page");
863 return 0;
866 maxobj = order_objects(compound_order(page), s->size, s->reserved);
867 if (page->objects > maxobj) {
868 slab_err(s, page, "objects %u > max %u",
869 s->name, page->objects, maxobj);
870 return 0;
872 if (page->inuse > page->objects) {
873 slab_err(s, page, "inuse %u > max %u",
874 s->name, page->inuse, page->objects);
875 return 0;
877 /* Slab_pad_check fixes things up after itself */
878 slab_pad_check(s, page);
879 return 1;
883 * Determine if a certain object on a page is on the freelist. Must hold the
884 * slab lock to guarantee that the chains are in a consistent state.
886 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
888 int nr = 0;
889 void *fp;
890 void *object = NULL;
891 unsigned long max_objects;
893 fp = page->freelist;
894 while (fp && nr <= page->objects) {
895 if (fp == search)
896 return 1;
897 if (!check_valid_pointer(s, page, fp)) {
898 if (object) {
899 object_err(s, page, object,
900 "Freechain corrupt");
901 set_freepointer(s, object, NULL);
902 break;
903 } else {
904 slab_err(s, page, "Freepointer corrupt");
905 page->freelist = NULL;
906 page->inuse = page->objects;
907 slab_fix(s, "Freelist cleared");
908 return 0;
910 break;
912 object = fp;
913 fp = get_freepointer(s, object);
914 nr++;
917 max_objects = order_objects(compound_order(page), s->size, s->reserved);
918 if (max_objects > MAX_OBJS_PER_PAGE)
919 max_objects = MAX_OBJS_PER_PAGE;
921 if (page->objects != max_objects) {
922 slab_err(s, page, "Wrong number of objects. Found %d but "
923 "should be %d", page->objects, max_objects);
924 page->objects = max_objects;
925 slab_fix(s, "Number of objects adjusted.");
927 if (page->inuse != page->objects - nr) {
928 slab_err(s, page, "Wrong object count. Counter is %d but "
929 "counted were %d", page->inuse, page->objects - nr);
930 page->inuse = page->objects - nr;
931 slab_fix(s, "Object count adjusted.");
933 return search == NULL;
936 static void trace(struct kmem_cache *s, struct page *page, void *object,
937 int alloc)
939 if (s->flags & SLAB_TRACE) {
940 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
941 s->name,
942 alloc ? "alloc" : "free",
943 object, page->inuse,
944 page->freelist);
946 if (!alloc)
947 print_section("Object", (void *)object, s->objsize);
949 dump_stack();
954 * Hooks for other subsystems that check memory allocations. In a typical
955 * production configuration these hooks all should produce no code at all.
957 static inline int slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
959 flags &= gfp_allowed_mask;
960 lockdep_trace_alloc(flags);
961 might_sleep_if(flags & __GFP_WAIT);
963 return should_failslab(s->objsize, flags, s->flags);
966 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags, void *object)
968 flags &= gfp_allowed_mask;
969 kmemcheck_slab_alloc(s, flags, object, slab_ksize(s));
970 kmemleak_alloc_recursive(object, s->objsize, 1, s->flags, flags);
973 static inline void slab_free_hook(struct kmem_cache *s, void *x)
975 kmemleak_free_recursive(x, s->flags);
978 * Trouble is that we may no longer disable interupts in the fast path
979 * So in order to make the debug calls that expect irqs to be
980 * disabled we need to disable interrupts temporarily.
982 #if defined(CONFIG_KMEMCHECK) || defined(CONFIG_LOCKDEP)
984 unsigned long flags;
986 local_irq_save(flags);
987 kmemcheck_slab_free(s, x, s->objsize);
988 debug_check_no_locks_freed(x, s->objsize);
989 local_irq_restore(flags);
991 #endif
992 if (!(s->flags & SLAB_DEBUG_OBJECTS))
993 debug_check_no_obj_freed(x, s->objsize);
997 * Tracking of fully allocated slabs for debugging purposes.
999 * list_lock must be held.
1001 static void add_full(struct kmem_cache *s,
1002 struct kmem_cache_node *n, struct page *page)
1004 if (!(s->flags & SLAB_STORE_USER))
1005 return;
1007 list_add(&page->lru, &n->full);
1011 * list_lock must be held.
1013 static void remove_full(struct kmem_cache *s, struct page *page)
1015 if (!(s->flags & SLAB_STORE_USER))
1016 return;
1018 list_del(&page->lru);
1021 /* Tracking of the number of slabs for debugging purposes */
1022 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1024 struct kmem_cache_node *n = get_node(s, node);
1026 return atomic_long_read(&n->nr_slabs);
1029 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1031 return atomic_long_read(&n->nr_slabs);
1034 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
1036 struct kmem_cache_node *n = get_node(s, node);
1039 * May be called early in order to allocate a slab for the
1040 * kmem_cache_node structure. Solve the chicken-egg
1041 * dilemma by deferring the increment of the count during
1042 * bootstrap (see early_kmem_cache_node_alloc).
1044 if (n) {
1045 atomic_long_inc(&n->nr_slabs);
1046 atomic_long_add(objects, &n->total_objects);
1049 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
1051 struct kmem_cache_node *n = get_node(s, node);
1053 atomic_long_dec(&n->nr_slabs);
1054 atomic_long_sub(objects, &n->total_objects);
1057 /* Object debug checks for alloc/free paths */
1058 static void setup_object_debug(struct kmem_cache *s, struct page *page,
1059 void *object)
1061 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
1062 return;
1064 init_object(s, object, SLUB_RED_INACTIVE);
1065 init_tracking(s, object);
1068 static noinline int alloc_debug_processing(struct kmem_cache *s, struct page *page,
1069 void *object, unsigned long addr)
1071 if (!check_slab(s, page))
1072 goto bad;
1074 if (!check_valid_pointer(s, page, object)) {
1075 object_err(s, page, object, "Freelist Pointer check fails");
1076 goto bad;
1079 if (!check_object(s, page, object, SLUB_RED_INACTIVE))
1080 goto bad;
1082 /* Success perform special debug activities for allocs */
1083 if (s->flags & SLAB_STORE_USER)
1084 set_track(s, object, TRACK_ALLOC, addr);
1085 trace(s, page, object, 1);
1086 init_object(s, object, SLUB_RED_ACTIVE);
1087 return 1;
1089 bad:
1090 if (PageSlab(page)) {
1092 * If this is a slab page then lets do the best we can
1093 * to avoid issues in the future. Marking all objects
1094 * as used avoids touching the remaining objects.
1096 slab_fix(s, "Marking all objects used");
1097 page->inuse = page->objects;
1098 page->freelist = NULL;
1100 return 0;
1103 static noinline int free_debug_processing(struct kmem_cache *s,
1104 struct page *page, void *object, unsigned long addr)
1106 unsigned long flags;
1107 int rc = 0;
1109 local_irq_save(flags);
1110 slab_lock(page);
1112 if (!check_slab(s, page))
1113 goto fail;
1115 if (!check_valid_pointer(s, page, object)) {
1116 slab_err(s, page, "Invalid object pointer 0x%p", object);
1117 goto fail;
1120 if (on_freelist(s, page, object)) {
1121 object_err(s, page, object, "Object already free");
1122 goto fail;
1125 if (!check_object(s, page, object, SLUB_RED_ACTIVE))
1126 goto out;
1128 if (unlikely(s != page->slab)) {
1129 if (!PageSlab(page)) {
1130 slab_err(s, page, "Attempt to free object(0x%p) "
1131 "outside of slab", object);
1132 } else if (!page->slab) {
1133 printk(KERN_ERR
1134 "SLUB <none>: no slab for object 0x%p.\n",
1135 object);
1136 dump_stack();
1137 } else
1138 object_err(s, page, object,
1139 "page slab pointer corrupt.");
1140 goto fail;
1143 if (s->flags & SLAB_STORE_USER)
1144 set_track(s, object, TRACK_FREE, addr);
1145 trace(s, page, object, 0);
1146 init_object(s, object, SLUB_RED_INACTIVE);
1147 rc = 1;
1148 out:
1149 slab_unlock(page);
1150 local_irq_restore(flags);
1151 return rc;
1153 fail:
1154 slab_fix(s, "Object at 0x%p not freed", object);
1155 goto out;
1158 static int __init setup_slub_debug(char *str)
1160 slub_debug = DEBUG_DEFAULT_FLAGS;
1161 if (*str++ != '=' || !*str)
1163 * No options specified. Switch on full debugging.
1165 goto out;
1167 if (*str == ',')
1169 * No options but restriction on slabs. This means full
1170 * debugging for slabs matching a pattern.
1172 goto check_slabs;
1174 if (tolower(*str) == 'o') {
1176 * Avoid enabling debugging on caches if its minimum order
1177 * would increase as a result.
1179 disable_higher_order_debug = 1;
1180 goto out;
1183 slub_debug = 0;
1184 if (*str == '-')
1186 * Switch off all debugging measures.
1188 goto out;
1191 * Determine which debug features should be switched on
1193 for (; *str && *str != ','; str++) {
1194 switch (tolower(*str)) {
1195 case 'f':
1196 slub_debug |= SLAB_DEBUG_FREE;
1197 break;
1198 case 'z':
1199 slub_debug |= SLAB_RED_ZONE;
1200 break;
1201 case 'p':
1202 slub_debug |= SLAB_POISON;
1203 break;
1204 case 'u':
1205 slub_debug |= SLAB_STORE_USER;
1206 break;
1207 case 't':
1208 slub_debug |= SLAB_TRACE;
1209 break;
1210 case 'a':
1211 slub_debug |= SLAB_FAILSLAB;
1212 break;
1213 default:
1214 printk(KERN_ERR "slub_debug option '%c' "
1215 "unknown. skipped\n", *str);
1219 check_slabs:
1220 if (*str == ',')
1221 slub_debug_slabs = str + 1;
1222 out:
1223 return 1;
1226 __setup("slub_debug", setup_slub_debug);
1228 static unsigned long kmem_cache_flags(unsigned long objsize,
1229 unsigned long flags, const char *name,
1230 void (*ctor)(void *))
1233 * Enable debugging if selected on the kernel commandline.
1235 if (slub_debug && (!slub_debug_slabs ||
1236 !strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs))))
1237 flags |= slub_debug;
1239 return flags;
1241 #else
1242 static inline void setup_object_debug(struct kmem_cache *s,
1243 struct page *page, void *object) {}
1245 static inline int alloc_debug_processing(struct kmem_cache *s,
1246 struct page *page, void *object, unsigned long addr) { return 0; }
1248 static inline int free_debug_processing(struct kmem_cache *s,
1249 struct page *page, void *object, unsigned long addr) { return 0; }
1251 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1252 { return 1; }
1253 static inline int check_object(struct kmem_cache *s, struct page *page,
1254 void *object, u8 val) { return 1; }
1255 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n,
1256 struct page *page) {}
1257 static inline void remove_full(struct kmem_cache *s, struct page *page) {}
1258 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1259 unsigned long flags, const char *name,
1260 void (*ctor)(void *))
1262 return flags;
1264 #define slub_debug 0
1266 #define disable_higher_order_debug 0
1268 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1269 { return 0; }
1270 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n)
1271 { return 0; }
1272 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1273 int objects) {}
1274 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1275 int objects) {}
1277 static inline int slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags)
1278 { return 0; }
1280 static inline void slab_post_alloc_hook(struct kmem_cache *s, gfp_t flags,
1281 void *object) {}
1283 static inline void slab_free_hook(struct kmem_cache *s, void *x) {}
1285 #endif /* CONFIG_SLUB_DEBUG */
1288 * Slab allocation and freeing
1290 static inline struct page *alloc_slab_page(gfp_t flags, int node,
1291 struct kmem_cache_order_objects oo)
1293 int order = oo_order(oo);
1295 flags |= __GFP_NOTRACK;
1297 if (node == NUMA_NO_NODE)
1298 return alloc_pages(flags, order);
1299 else
1300 return alloc_pages_exact_node(node, flags, order);
1303 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1305 struct page *page;
1306 struct kmem_cache_order_objects oo = s->oo;
1307 gfp_t alloc_gfp;
1309 flags &= gfp_allowed_mask;
1311 if (flags & __GFP_WAIT)
1312 local_irq_enable();
1314 flags |= s->allocflags;
1317 * Let the initial higher-order allocation fail under memory pressure
1318 * so we fall-back to the minimum order allocation.
1320 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
1322 page = alloc_slab_page(alloc_gfp, node, oo);
1323 if (unlikely(!page)) {
1324 oo = s->min;
1326 * Allocation may have failed due to fragmentation.
1327 * Try a lower order alloc if possible
1329 page = alloc_slab_page(flags, node, oo);
1331 if (page)
1332 stat(s, ORDER_FALLBACK);
1335 if (flags & __GFP_WAIT)
1336 local_irq_disable();
1338 if (!page)
1339 return NULL;
1341 if (kmemcheck_enabled
1342 && !(s->flags & (SLAB_NOTRACK | DEBUG_DEFAULT_FLAGS))) {
1343 int pages = 1 << oo_order(oo);
1345 kmemcheck_alloc_shadow(page, oo_order(oo), flags, node);
1348 * Objects from caches that have a constructor don't get
1349 * cleared when they're allocated, so we need to do it here.
1351 if (s->ctor)
1352 kmemcheck_mark_uninitialized_pages(page, pages);
1353 else
1354 kmemcheck_mark_unallocated_pages(page, pages);
1357 page->objects = oo_objects(oo);
1358 mod_zone_page_state(page_zone(page),
1359 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1360 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1361 1 << oo_order(oo));
1363 return page;
1366 static void setup_object(struct kmem_cache *s, struct page *page,
1367 void *object)
1369 setup_object_debug(s, page, object);
1370 if (unlikely(s->ctor))
1371 s->ctor(object);
1374 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1376 struct page *page;
1377 void *start;
1378 void *last;
1379 void *p;
1381 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1383 page = allocate_slab(s,
1384 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1385 if (!page)
1386 goto out;
1388 inc_slabs_node(s, page_to_nid(page), page->objects);
1389 page->slab = s;
1390 page->flags |= 1 << PG_slab;
1392 start = page_address(page);
1394 if (unlikely(s->flags & SLAB_POISON))
1395 memset(start, POISON_INUSE, PAGE_SIZE << compound_order(page));
1397 last = start;
1398 for_each_object(p, s, start, page->objects) {
1399 setup_object(s, page, last);
1400 set_freepointer(s, last, p);
1401 last = p;
1403 setup_object(s, page, last);
1404 set_freepointer(s, last, NULL);
1406 page->freelist = start;
1407 page->inuse = page->objects;
1408 page->frozen = 1;
1409 out:
1410 return page;
1413 static void __free_slab(struct kmem_cache *s, struct page *page)
1415 int order = compound_order(page);
1416 int pages = 1 << order;
1418 if (kmem_cache_debug(s)) {
1419 void *p;
1421 slab_pad_check(s, page);
1422 for_each_object(p, s, page_address(page),
1423 page->objects)
1424 check_object(s, page, p, SLUB_RED_INACTIVE);
1427 kmemcheck_free_shadow(page, compound_order(page));
1429 mod_zone_page_state(page_zone(page),
1430 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1431 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1432 -pages);
1434 __ClearPageSlab(page);
1435 reset_page_mapcount(page);
1436 if (current->reclaim_state)
1437 current->reclaim_state->reclaimed_slab += pages;
1438 __free_pages(page, order);
1441 #define need_reserve_slab_rcu \
1442 (sizeof(((struct page *)NULL)->lru) < sizeof(struct rcu_head))
1444 static void rcu_free_slab(struct rcu_head *h)
1446 struct page *page;
1448 if (need_reserve_slab_rcu)
1449 page = virt_to_head_page(h);
1450 else
1451 page = container_of((struct list_head *)h, struct page, lru);
1453 __free_slab(page->slab, page);
1456 static void free_slab(struct kmem_cache *s, struct page *page)
1458 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1459 struct rcu_head *head;
1461 if (need_reserve_slab_rcu) {
1462 int order = compound_order(page);
1463 int offset = (PAGE_SIZE << order) - s->reserved;
1465 VM_BUG_ON(s->reserved != sizeof(*head));
1466 head = page_address(page) + offset;
1467 } else {
1469 * RCU free overloads the RCU head over the LRU
1471 head = (void *)&page->lru;
1474 call_rcu(head, rcu_free_slab);
1475 } else
1476 __free_slab(s, page);
1479 static void discard_slab(struct kmem_cache *s, struct page *page)
1481 dec_slabs_node(s, page_to_nid(page), page->objects);
1482 free_slab(s, page);
1486 * Management of partially allocated slabs.
1488 * list_lock must be held.
1490 static inline void add_partial(struct kmem_cache_node *n,
1491 struct page *page, int tail)
1493 n->nr_partial++;
1494 if (tail == DEACTIVATE_TO_TAIL)
1495 list_add_tail(&page->lru, &n->partial);
1496 else
1497 list_add(&page->lru, &n->partial);
1501 * list_lock must be held.
1503 static inline void remove_partial(struct kmem_cache_node *n,
1504 struct page *page)
1506 list_del(&page->lru);
1507 n->nr_partial--;
1511 * Lock slab, remove from the partial list and put the object into the
1512 * per cpu freelist.
1514 * Returns a list of objects or NULL if it fails.
1516 * Must hold list_lock.
1518 static inline void *acquire_slab(struct kmem_cache *s,
1519 struct kmem_cache_node *n, struct page *page,
1520 int mode)
1522 void *freelist;
1523 unsigned long counters;
1524 struct page new;
1527 * Zap the freelist and set the frozen bit.
1528 * The old freelist is the list of objects for the
1529 * per cpu allocation list.
1531 do {
1532 freelist = page->freelist;
1533 counters = page->counters;
1534 new.counters = counters;
1535 if (mode)
1536 new.inuse = page->objects;
1538 VM_BUG_ON(new.frozen);
1539 new.frozen = 1;
1541 } while (!__cmpxchg_double_slab(s, page,
1542 freelist, counters,
1543 NULL, new.counters,
1544 "lock and freeze"));
1546 remove_partial(n, page);
1547 return freelist;
1550 static int put_cpu_partial(struct kmem_cache *s, struct page *page, int drain);
1553 * Try to allocate a partial slab from a specific node.
1555 static void *get_partial_node(struct kmem_cache *s,
1556 struct kmem_cache_node *n, struct kmem_cache_cpu *c)
1558 struct page *page, *page2;
1559 void *object = NULL;
1560 int count = 0;
1563 * Racy check. If we mistakenly see no partial slabs then we
1564 * just allocate an empty slab. If we mistakenly try to get a
1565 * partial slab and there is none available then get_partials()
1566 * will return NULL.
1568 if (!n || !n->nr_partial)
1569 return NULL;
1571 spin_lock(&n->list_lock);
1572 list_for_each_entry_safe(page, page2, &n->partial, lru) {
1573 void *t = acquire_slab(s, n, page, count == 0);
1574 int available;
1576 if (!t)
1577 break;
1579 if (!count) {
1580 c->page = page;
1581 c->node = page_to_nid(page);
1582 stat(s, ALLOC_FROM_PARTIAL);
1583 count++;
1584 object = t;
1585 available = page->objects - page->inuse;
1586 } else {
1587 page->freelist = t;
1588 available = put_cpu_partial(s, page, 0);
1590 if (kmem_cache_debug(s) || available > s->cpu_partial / 2)
1591 break;
1594 spin_unlock(&n->list_lock);
1595 return object;
1599 * Get a page from somewhere. Search in increasing NUMA distances.
1601 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags,
1602 struct kmem_cache_cpu *c)
1604 #ifdef CONFIG_NUMA
1605 struct zonelist *zonelist;
1606 struct zoneref *z;
1607 struct zone *zone;
1608 enum zone_type high_zoneidx = gfp_zone(flags);
1609 void *object;
1612 * The defrag ratio allows a configuration of the tradeoffs between
1613 * inter node defragmentation and node local allocations. A lower
1614 * defrag_ratio increases the tendency to do local allocations
1615 * instead of attempting to obtain partial slabs from other nodes.
1617 * If the defrag_ratio is set to 0 then kmalloc() always
1618 * returns node local objects. If the ratio is higher then kmalloc()
1619 * may return off node objects because partial slabs are obtained
1620 * from other nodes and filled up.
1622 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1623 * defrag_ratio = 1000) then every (well almost) allocation will
1624 * first attempt to defrag slab caches on other nodes. This means
1625 * scanning over all nodes to look for partial slabs which may be
1626 * expensive if we do it every time we are trying to find a slab
1627 * with available objects.
1629 if (!s->remote_node_defrag_ratio ||
1630 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1631 return NULL;
1633 get_mems_allowed();
1634 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
1635 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1636 struct kmem_cache_node *n;
1638 n = get_node(s, zone_to_nid(zone));
1640 if (n && cpuset_zone_allowed_hardwall(zone, flags) &&
1641 n->nr_partial > s->min_partial) {
1642 object = get_partial_node(s, n, c);
1643 if (object) {
1644 put_mems_allowed();
1645 return object;
1649 put_mems_allowed();
1650 #endif
1651 return NULL;
1655 * Get a partial page, lock it and return it.
1657 static void *get_partial(struct kmem_cache *s, gfp_t flags, int node,
1658 struct kmem_cache_cpu *c)
1660 void *object;
1661 int searchnode = (node == NUMA_NO_NODE) ? numa_node_id() : node;
1663 object = get_partial_node(s, get_node(s, searchnode), c);
1664 if (object || node != NUMA_NO_NODE)
1665 return object;
1667 return get_any_partial(s, flags, c);
1670 #ifdef CONFIG_PREEMPT
1672 * Calculate the next globally unique transaction for disambiguiation
1673 * during cmpxchg. The transactions start with the cpu number and are then
1674 * incremented by CONFIG_NR_CPUS.
1676 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS)
1677 #else
1679 * No preemption supported therefore also no need to check for
1680 * different cpus.
1682 #define TID_STEP 1
1683 #endif
1685 static inline unsigned long next_tid(unsigned long tid)
1687 return tid + TID_STEP;
1690 static inline unsigned int tid_to_cpu(unsigned long tid)
1692 return tid % TID_STEP;
1695 static inline unsigned long tid_to_event(unsigned long tid)
1697 return tid / TID_STEP;
1700 static inline unsigned int init_tid(int cpu)
1702 return cpu;
1705 static inline void note_cmpxchg_failure(const char *n,
1706 const struct kmem_cache *s, unsigned long tid)
1708 #ifdef SLUB_DEBUG_CMPXCHG
1709 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid);
1711 printk(KERN_INFO "%s %s: cmpxchg redo ", n, s->name);
1713 #ifdef CONFIG_PREEMPT
1714 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid))
1715 printk("due to cpu change %d -> %d\n",
1716 tid_to_cpu(tid), tid_to_cpu(actual_tid));
1717 else
1718 #endif
1719 if (tid_to_event(tid) != tid_to_event(actual_tid))
1720 printk("due to cpu running other code. Event %ld->%ld\n",
1721 tid_to_event(tid), tid_to_event(actual_tid));
1722 else
1723 printk("for unknown reason: actual=%lx was=%lx target=%lx\n",
1724 actual_tid, tid, next_tid(tid));
1725 #endif
1726 stat(s, CMPXCHG_DOUBLE_CPU_FAIL);
1729 void init_kmem_cache_cpus(struct kmem_cache *s)
1731 int cpu;
1733 for_each_possible_cpu(cpu)
1734 per_cpu_ptr(s->cpu_slab, cpu)->tid = init_tid(cpu);
1738 * Remove the cpu slab
1740 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1742 enum slab_modes { M_NONE, M_PARTIAL, M_FULL, M_FREE };
1743 struct page *page = c->page;
1744 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1745 int lock = 0;
1746 enum slab_modes l = M_NONE, m = M_NONE;
1747 void *freelist;
1748 void *nextfree;
1749 int tail = DEACTIVATE_TO_HEAD;
1750 struct page new;
1751 struct page old;
1753 if (page->freelist) {
1754 stat(s, DEACTIVATE_REMOTE_FREES);
1755 tail = DEACTIVATE_TO_TAIL;
1758 c->tid = next_tid(c->tid);
1759 c->page = NULL;
1760 freelist = c->freelist;
1761 c->freelist = NULL;
1764 * Stage one: Free all available per cpu objects back
1765 * to the page freelist while it is still frozen. Leave the
1766 * last one.
1768 * There is no need to take the list->lock because the page
1769 * is still frozen.
1771 while (freelist && (nextfree = get_freepointer(s, freelist))) {
1772 void *prior;
1773 unsigned long counters;
1775 do {
1776 prior = page->freelist;
1777 counters = page->counters;
1778 set_freepointer(s, freelist, prior);
1779 new.counters = counters;
1780 new.inuse--;
1781 VM_BUG_ON(!new.frozen);
1783 } while (!__cmpxchg_double_slab(s, page,
1784 prior, counters,
1785 freelist, new.counters,
1786 "drain percpu freelist"));
1788 freelist = nextfree;
1792 * Stage two: Ensure that the page is unfrozen while the
1793 * list presence reflects the actual number of objects
1794 * during unfreeze.
1796 * We setup the list membership and then perform a cmpxchg
1797 * with the count. If there is a mismatch then the page
1798 * is not unfrozen but the page is on the wrong list.
1800 * Then we restart the process which may have to remove
1801 * the page from the list that we just put it on again
1802 * because the number of objects in the slab may have
1803 * changed.
1805 redo:
1807 old.freelist = page->freelist;
1808 old.counters = page->counters;
1809 VM_BUG_ON(!old.frozen);
1811 /* Determine target state of the slab */
1812 new.counters = old.counters;
1813 if (freelist) {
1814 new.inuse--;
1815 set_freepointer(s, freelist, old.freelist);
1816 new.freelist = freelist;
1817 } else
1818 new.freelist = old.freelist;
1820 new.frozen = 0;
1822 if (!new.inuse && n->nr_partial > s->min_partial)
1823 m = M_FREE;
1824 else if (new.freelist) {
1825 m = M_PARTIAL;
1826 if (!lock) {
1827 lock = 1;
1829 * Taking the spinlock removes the possiblity
1830 * that acquire_slab() will see a slab page that
1831 * is frozen
1833 spin_lock(&n->list_lock);
1835 } else {
1836 m = M_FULL;
1837 if (kmem_cache_debug(s) && !lock) {
1838 lock = 1;
1840 * This also ensures that the scanning of full
1841 * slabs from diagnostic functions will not see
1842 * any frozen slabs.
1844 spin_lock(&n->list_lock);
1848 if (l != m) {
1850 if (l == M_PARTIAL)
1852 remove_partial(n, page);
1854 else if (l == M_FULL)
1856 remove_full(s, page);
1858 if (m == M_PARTIAL) {
1860 add_partial(n, page, tail);
1861 stat(s, tail);
1863 } else if (m == M_FULL) {
1865 stat(s, DEACTIVATE_FULL);
1866 add_full(s, n, page);
1871 l = m;
1872 if (!__cmpxchg_double_slab(s, page,
1873 old.freelist, old.counters,
1874 new.freelist, new.counters,
1875 "unfreezing slab"))
1876 goto redo;
1878 if (lock)
1879 spin_unlock(&n->list_lock);
1881 if (m == M_FREE) {
1882 stat(s, DEACTIVATE_EMPTY);
1883 discard_slab(s, page);
1884 stat(s, FREE_SLAB);
1888 /* Unfreeze all the cpu partial slabs */
1889 static void unfreeze_partials(struct kmem_cache *s)
1891 struct kmem_cache_node *n = NULL;
1892 struct kmem_cache_cpu *c = this_cpu_ptr(s->cpu_slab);
1893 struct page *page;
1895 while ((page = c->partial)) {
1896 enum slab_modes { M_PARTIAL, M_FREE };
1897 enum slab_modes l, m;
1898 struct page new;
1899 struct page old;
1901 c->partial = page->next;
1902 l = M_FREE;
1904 do {
1906 old.freelist = page->freelist;
1907 old.counters = page->counters;
1908 VM_BUG_ON(!old.frozen);
1910 new.counters = old.counters;
1911 new.freelist = old.freelist;
1913 new.frozen = 0;
1915 if (!new.inuse && (!n || n->nr_partial < s->min_partial))
1916 m = M_FREE;
1917 else {
1918 struct kmem_cache_node *n2 = get_node(s,
1919 page_to_nid(page));
1921 m = M_PARTIAL;
1922 if (n != n2) {
1923 if (n)
1924 spin_unlock(&n->list_lock);
1926 n = n2;
1927 spin_lock(&n->list_lock);
1931 if (l != m) {
1932 if (l == M_PARTIAL)
1933 remove_partial(n, page);
1934 else
1935 add_partial(n, page, 1);
1937 l = m;
1940 } while (!cmpxchg_double_slab(s, page,
1941 old.freelist, old.counters,
1942 new.freelist, new.counters,
1943 "unfreezing slab"));
1945 if (m == M_FREE) {
1946 stat(s, DEACTIVATE_EMPTY);
1947 discard_slab(s, page);
1948 stat(s, FREE_SLAB);
1952 if (n)
1953 spin_unlock(&n->list_lock);
1957 * Put a page that was just frozen (in __slab_free) into a partial page
1958 * slot if available. This is done without interrupts disabled and without
1959 * preemption disabled. The cmpxchg is racy and may put the partial page
1960 * onto a random cpus partial slot.
1962 * If we did not find a slot then simply move all the partials to the
1963 * per node partial list.
1965 int put_cpu_partial(struct kmem_cache *s, struct page *page, int drain)
1967 struct page *oldpage;
1968 int pages;
1969 int pobjects;
1971 do {
1972 pages = 0;
1973 pobjects = 0;
1974 oldpage = this_cpu_read(s->cpu_slab->partial);
1976 if (oldpage) {
1977 pobjects = oldpage->pobjects;
1978 pages = oldpage->pages;
1979 if (drain && pobjects > s->cpu_partial) {
1980 unsigned long flags;
1982 * partial array is full. Move the existing
1983 * set to the per node partial list.
1985 local_irq_save(flags);
1986 unfreeze_partials(s);
1987 local_irq_restore(flags);
1988 pobjects = 0;
1989 pages = 0;
1993 pages++;
1994 pobjects += page->objects - page->inuse;
1996 page->pages = pages;
1997 page->pobjects = pobjects;
1998 page->next = oldpage;
2000 } while (this_cpu_cmpxchg(s->cpu_slab->partial, oldpage, page) != oldpage);
2001 stat(s, CPU_PARTIAL_FREE);
2002 return pobjects;
2005 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
2007 stat(s, CPUSLAB_FLUSH);
2008 deactivate_slab(s, c);
2012 * Flush cpu slab.
2014 * Called from IPI handler with interrupts disabled.
2016 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
2018 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
2020 if (likely(c)) {
2021 if (c->page)
2022 flush_slab(s, c);
2024 unfreeze_partials(s);
2028 static void flush_cpu_slab(void *d)
2030 struct kmem_cache *s = d;
2032 __flush_cpu_slab(s, smp_processor_id());
2035 static void flush_all(struct kmem_cache *s)
2037 on_each_cpu(flush_cpu_slab, s, 1);
2041 * Check if the objects in a per cpu structure fit numa
2042 * locality expectations.
2044 static inline int node_match(struct kmem_cache_cpu *c, int node)
2046 #ifdef CONFIG_NUMA
2047 if (node != NUMA_NO_NODE && c->node != node)
2048 return 0;
2049 #endif
2050 return 1;
2053 static int count_free(struct page *page)
2055 return page->objects - page->inuse;
2058 static unsigned long count_partial(struct kmem_cache_node *n,
2059 int (*get_count)(struct page *))
2061 unsigned long flags;
2062 unsigned long x = 0;
2063 struct page *page;
2065 spin_lock_irqsave(&n->list_lock, flags);
2066 list_for_each_entry(page, &n->partial, lru)
2067 x += get_count(page);
2068 spin_unlock_irqrestore(&n->list_lock, flags);
2069 return x;
2072 static inline unsigned long node_nr_objs(struct kmem_cache_node *n)
2074 #ifdef CONFIG_SLUB_DEBUG
2075 return atomic_long_read(&n->total_objects);
2076 #else
2077 return 0;
2078 #endif
2081 static noinline void
2082 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
2084 int node;
2086 printk(KERN_WARNING
2087 "SLUB: Unable to allocate memory on node %d (gfp=0x%x)\n",
2088 nid, gfpflags);
2089 printk(KERN_WARNING " cache: %s, object size: %d, buffer size: %d, "
2090 "default order: %d, min order: %d\n", s->name, s->objsize,
2091 s->size, oo_order(s->oo), oo_order(s->min));
2093 if (oo_order(s->min) > get_order(s->objsize))
2094 printk(KERN_WARNING " %s debugging increased min order, use "
2095 "slub_debug=O to disable.\n", s->name);
2097 for_each_online_node(node) {
2098 struct kmem_cache_node *n = get_node(s, node);
2099 unsigned long nr_slabs;
2100 unsigned long nr_objs;
2101 unsigned long nr_free;
2103 if (!n)
2104 continue;
2106 nr_free = count_partial(n, count_free);
2107 nr_slabs = node_nr_slabs(n);
2108 nr_objs = node_nr_objs(n);
2110 printk(KERN_WARNING
2111 " node %d: slabs: %ld, objs: %ld, free: %ld\n",
2112 node, nr_slabs, nr_objs, nr_free);
2116 static inline void *new_slab_objects(struct kmem_cache *s, gfp_t flags,
2117 int node, struct kmem_cache_cpu **pc)
2119 void *object;
2120 struct kmem_cache_cpu *c;
2121 struct page *page = new_slab(s, flags, node);
2123 if (page) {
2124 c = __this_cpu_ptr(s->cpu_slab);
2125 if (c->page)
2126 flush_slab(s, c);
2129 * No other reference to the page yet so we can
2130 * muck around with it freely without cmpxchg
2132 object = page->freelist;
2133 page->freelist = NULL;
2135 stat(s, ALLOC_SLAB);
2136 c->node = page_to_nid(page);
2137 c->page = page;
2138 *pc = c;
2139 } else
2140 object = NULL;
2142 return object;
2146 * Slow path. The lockless freelist is empty or we need to perform
2147 * debugging duties.
2149 * Processing is still very fast if new objects have been freed to the
2150 * regular freelist. In that case we simply take over the regular freelist
2151 * as the lockless freelist and zap the regular freelist.
2153 * If that is not working then we fall back to the partial lists. We take the
2154 * first element of the freelist as the object to allocate now and move the
2155 * rest of the freelist to the lockless freelist.
2157 * And if we were unable to get a new slab from the partial slab lists then
2158 * we need to allocate a new slab. This is the slowest path since it involves
2159 * a call to the page allocator and the setup of a new slab.
2161 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node,
2162 unsigned long addr, struct kmem_cache_cpu *c)
2164 void **object;
2165 unsigned long flags;
2166 struct page new;
2167 unsigned long counters;
2169 local_irq_save(flags);
2170 #ifdef CONFIG_PREEMPT
2172 * We may have been preempted and rescheduled on a different
2173 * cpu before disabling interrupts. Need to reload cpu area
2174 * pointer.
2176 c = this_cpu_ptr(s->cpu_slab);
2177 #endif
2179 if (!c->page)
2180 goto new_slab;
2181 redo:
2182 if (unlikely(!node_match(c, node))) {
2183 stat(s, ALLOC_NODE_MISMATCH);
2184 deactivate_slab(s, c);
2185 goto new_slab;
2188 stat(s, ALLOC_SLOWPATH);
2190 do {
2191 object = c->page->freelist;
2192 counters = c->page->counters;
2193 new.counters = counters;
2194 VM_BUG_ON(!new.frozen);
2197 * If there is no object left then we use this loop to
2198 * deactivate the slab which is simple since no objects
2199 * are left in the slab and therefore we do not need to
2200 * put the page back onto the partial list.
2202 * If there are objects left then we retrieve them
2203 * and use them to refill the per cpu queue.
2206 new.inuse = c->page->objects;
2207 new.frozen = object != NULL;
2209 } while (!__cmpxchg_double_slab(s, c->page,
2210 object, counters,
2211 NULL, new.counters,
2212 "__slab_alloc"));
2214 if (!object) {
2215 c->page = NULL;
2216 stat(s, DEACTIVATE_BYPASS);
2217 goto new_slab;
2220 stat(s, ALLOC_REFILL);
2222 load_freelist:
2223 c->freelist = get_freepointer(s, object);
2224 c->tid = next_tid(c->tid);
2225 local_irq_restore(flags);
2226 return object;
2228 new_slab:
2230 if (c->partial) {
2231 c->page = c->partial;
2232 c->partial = c->page->next;
2233 c->node = page_to_nid(c->page);
2234 stat(s, CPU_PARTIAL_ALLOC);
2235 c->freelist = NULL;
2236 goto redo;
2239 /* Then do expensive stuff like retrieving pages from the partial lists */
2240 object = get_partial(s, gfpflags, node, c);
2242 if (unlikely(!object)) {
2244 object = new_slab_objects(s, gfpflags, node, &c);
2246 if (unlikely(!object)) {
2247 if (!(gfpflags & __GFP_NOWARN) && printk_ratelimit())
2248 slab_out_of_memory(s, gfpflags, node);
2250 local_irq_restore(flags);
2251 return NULL;
2255 if (likely(!kmem_cache_debug(s)))
2256 goto load_freelist;
2258 /* Only entered in the debug case */
2259 if (!alloc_debug_processing(s, c->page, object, addr))
2260 goto new_slab; /* Slab failed checks. Next slab needed */
2262 c->freelist = get_freepointer(s, object);
2263 deactivate_slab(s, c);
2264 c->node = NUMA_NO_NODE;
2265 local_irq_restore(flags);
2266 return object;
2270 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
2271 * have the fastpath folded into their functions. So no function call
2272 * overhead for requests that can be satisfied on the fastpath.
2274 * The fastpath works by first checking if the lockless freelist can be used.
2275 * If not then __slab_alloc is called for slow processing.
2277 * Otherwise we can simply pick the next object from the lockless free list.
2279 static __always_inline void *slab_alloc(struct kmem_cache *s,
2280 gfp_t gfpflags, int node, unsigned long addr)
2282 void **object;
2283 struct kmem_cache_cpu *c;
2284 unsigned long tid;
2286 if (slab_pre_alloc_hook(s, gfpflags))
2287 return NULL;
2289 redo:
2292 * Must read kmem_cache cpu data via this cpu ptr. Preemption is
2293 * enabled. We may switch back and forth between cpus while
2294 * reading from one cpu area. That does not matter as long
2295 * as we end up on the original cpu again when doing the cmpxchg.
2297 c = __this_cpu_ptr(s->cpu_slab);
2300 * The transaction ids are globally unique per cpu and per operation on
2301 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double
2302 * occurs on the right processor and that there was no operation on the
2303 * linked list in between.
2305 tid = c->tid;
2306 barrier();
2308 object = c->freelist;
2309 if (unlikely(!object || !node_match(c, node)))
2311 object = __slab_alloc(s, gfpflags, node, addr, c);
2313 else {
2315 * The cmpxchg will only match if there was no additional
2316 * operation and if we are on the right processor.
2318 * The cmpxchg does the following atomically (without lock semantics!)
2319 * 1. Relocate first pointer to the current per cpu area.
2320 * 2. Verify that tid and freelist have not been changed
2321 * 3. If they were not changed replace tid and freelist
2323 * Since this is without lock semantics the protection is only against
2324 * code executing on this cpu *not* from access by other cpus.
2326 if (unlikely(!irqsafe_cpu_cmpxchg_double(
2327 s->cpu_slab->freelist, s->cpu_slab->tid,
2328 object, tid,
2329 get_freepointer_safe(s, object), next_tid(tid)))) {
2331 note_cmpxchg_failure("slab_alloc", s, tid);
2332 goto redo;
2334 stat(s, ALLOC_FASTPATH);
2337 if (unlikely(gfpflags & __GFP_ZERO) && object)
2338 memset(object, 0, s->objsize);
2340 slab_post_alloc_hook(s, gfpflags, object);
2342 return object;
2345 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
2347 void *ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, _RET_IP_);
2349 trace_kmem_cache_alloc(_RET_IP_, ret, s->objsize, s->size, gfpflags);
2351 return ret;
2353 EXPORT_SYMBOL(kmem_cache_alloc);
2355 #ifdef CONFIG_TRACING
2356 void *kmem_cache_alloc_trace(struct kmem_cache *s, gfp_t gfpflags, size_t size)
2358 void *ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, _RET_IP_);
2359 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags);
2360 return ret;
2362 EXPORT_SYMBOL(kmem_cache_alloc_trace);
2364 void *kmalloc_order_trace(size_t size, gfp_t flags, unsigned int order)
2366 void *ret = kmalloc_order(size, flags, order);
2367 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << order, flags);
2368 return ret;
2370 EXPORT_SYMBOL(kmalloc_order_trace);
2371 #endif
2373 #ifdef CONFIG_NUMA
2374 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
2376 void *ret = slab_alloc(s, gfpflags, node, _RET_IP_);
2378 trace_kmem_cache_alloc_node(_RET_IP_, ret,
2379 s->objsize, s->size, gfpflags, node);
2381 return ret;
2383 EXPORT_SYMBOL(kmem_cache_alloc_node);
2385 #ifdef CONFIG_TRACING
2386 void *kmem_cache_alloc_node_trace(struct kmem_cache *s,
2387 gfp_t gfpflags,
2388 int node, size_t size)
2390 void *ret = slab_alloc(s, gfpflags, node, _RET_IP_);
2392 trace_kmalloc_node(_RET_IP_, ret,
2393 size, s->size, gfpflags, node);
2394 return ret;
2396 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
2397 #endif
2398 #endif
2401 * Slow patch handling. This may still be called frequently since objects
2402 * have a longer lifetime than the cpu slabs in most processing loads.
2404 * So we still attempt to reduce cache line usage. Just take the slab
2405 * lock and free the item. If there is no additional partial page
2406 * handling required then we can return immediately.
2408 static void __slab_free(struct kmem_cache *s, struct page *page,
2409 void *x, unsigned long addr)
2411 void *prior;
2412 void **object = (void *)x;
2413 int was_frozen;
2414 int inuse;
2415 struct page new;
2416 unsigned long counters;
2417 struct kmem_cache_node *n = NULL;
2418 unsigned long uninitialized_var(flags);
2420 stat(s, FREE_SLOWPATH);
2422 if (kmem_cache_debug(s) && !free_debug_processing(s, page, x, addr))
2423 return;
2425 do {
2426 prior = page->freelist;
2427 counters = page->counters;
2428 set_freepointer(s, object, prior);
2429 new.counters = counters;
2430 was_frozen = new.frozen;
2431 new.inuse--;
2432 if ((!new.inuse || !prior) && !was_frozen && !n) {
2434 if (!kmem_cache_debug(s) && !prior)
2437 * Slab was on no list before and will be partially empty
2438 * We can defer the list move and instead freeze it.
2440 new.frozen = 1;
2442 else { /* Needs to be taken off a list */
2444 n = get_node(s, page_to_nid(page));
2446 * Speculatively acquire the list_lock.
2447 * If the cmpxchg does not succeed then we may
2448 * drop the list_lock without any processing.
2450 * Otherwise the list_lock will synchronize with
2451 * other processors updating the list of slabs.
2453 spin_lock_irqsave(&n->list_lock, flags);
2457 inuse = new.inuse;
2459 } while (!cmpxchg_double_slab(s, page,
2460 prior, counters,
2461 object, new.counters,
2462 "__slab_free"));
2464 if (likely(!n)) {
2467 * If we just froze the page then put it onto the
2468 * per cpu partial list.
2470 if (new.frozen && !was_frozen)
2471 put_cpu_partial(s, page, 1);
2474 * The list lock was not taken therefore no list
2475 * activity can be necessary.
2477 if (was_frozen)
2478 stat(s, FREE_FROZEN);
2479 return;
2483 * was_frozen may have been set after we acquired the list_lock in
2484 * an earlier loop. So we need to check it here again.
2486 if (was_frozen)
2487 stat(s, FREE_FROZEN);
2488 else {
2489 if (unlikely(!inuse && n->nr_partial > s->min_partial))
2490 goto slab_empty;
2493 * Objects left in the slab. If it was not on the partial list before
2494 * then add it.
2496 if (unlikely(!prior)) {
2497 remove_full(s, page);
2498 add_partial(n, page, DEACTIVATE_TO_TAIL);
2499 stat(s, FREE_ADD_PARTIAL);
2502 spin_unlock_irqrestore(&n->list_lock, flags);
2503 return;
2505 slab_empty:
2506 if (prior) {
2508 * Slab on the partial list.
2510 remove_partial(n, page);
2511 stat(s, FREE_REMOVE_PARTIAL);
2512 } else
2513 /* Slab must be on the full list */
2514 remove_full(s, page);
2516 spin_unlock_irqrestore(&n->list_lock, flags);
2517 stat(s, FREE_SLAB);
2518 discard_slab(s, page);
2522 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
2523 * can perform fastpath freeing without additional function calls.
2525 * The fastpath is only possible if we are freeing to the current cpu slab
2526 * of this processor. This typically the case if we have just allocated
2527 * the item before.
2529 * If fastpath is not possible then fall back to __slab_free where we deal
2530 * with all sorts of special processing.
2532 static __always_inline void slab_free(struct kmem_cache *s,
2533 struct page *page, void *x, unsigned long addr)
2535 void **object = (void *)x;
2536 struct kmem_cache_cpu *c;
2537 unsigned long tid;
2539 slab_free_hook(s, x);
2541 redo:
2543 * Determine the currently cpus per cpu slab.
2544 * The cpu may change afterward. However that does not matter since
2545 * data is retrieved via this pointer. If we are on the same cpu
2546 * during the cmpxchg then the free will succedd.
2548 c = __this_cpu_ptr(s->cpu_slab);
2550 tid = c->tid;
2551 barrier();
2553 if (likely(page == c->page)) {
2554 set_freepointer(s, object, c->freelist);
2556 if (unlikely(!irqsafe_cpu_cmpxchg_double(
2557 s->cpu_slab->freelist, s->cpu_slab->tid,
2558 c->freelist, tid,
2559 object, next_tid(tid)))) {
2561 note_cmpxchg_failure("slab_free", s, tid);
2562 goto redo;
2564 stat(s, FREE_FASTPATH);
2565 } else
2566 __slab_free(s, page, x, addr);
2570 void kmem_cache_free(struct kmem_cache *s, void *x)
2572 struct page *page;
2574 page = virt_to_head_page(x);
2576 slab_free(s, page, x, _RET_IP_);
2578 trace_kmem_cache_free(_RET_IP_, x);
2580 EXPORT_SYMBOL(kmem_cache_free);
2583 * Object placement in a slab is made very easy because we always start at
2584 * offset 0. If we tune the size of the object to the alignment then we can
2585 * get the required alignment by putting one properly sized object after
2586 * another.
2588 * Notice that the allocation order determines the sizes of the per cpu
2589 * caches. Each processor has always one slab available for allocations.
2590 * Increasing the allocation order reduces the number of times that slabs
2591 * must be moved on and off the partial lists and is therefore a factor in
2592 * locking overhead.
2596 * Mininum / Maximum order of slab pages. This influences locking overhead
2597 * and slab fragmentation. A higher order reduces the number of partial slabs
2598 * and increases the number of allocations possible without having to
2599 * take the list_lock.
2601 static int slub_min_order;
2602 static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
2603 static int slub_min_objects;
2606 * Merge control. If this is set then no merging of slab caches will occur.
2607 * (Could be removed. This was introduced to pacify the merge skeptics.)
2609 static int slub_nomerge;
2612 * Calculate the order of allocation given an slab object size.
2614 * The order of allocation has significant impact on performance and other
2615 * system components. Generally order 0 allocations should be preferred since
2616 * order 0 does not cause fragmentation in the page allocator. Larger objects
2617 * be problematic to put into order 0 slabs because there may be too much
2618 * unused space left. We go to a higher order if more than 1/16th of the slab
2619 * would be wasted.
2621 * In order to reach satisfactory performance we must ensure that a minimum
2622 * number of objects is in one slab. Otherwise we may generate too much
2623 * activity on the partial lists which requires taking the list_lock. This is
2624 * less a concern for large slabs though which are rarely used.
2626 * slub_max_order specifies the order where we begin to stop considering the
2627 * number of objects in a slab as critical. If we reach slub_max_order then
2628 * we try to keep the page order as low as possible. So we accept more waste
2629 * of space in favor of a small page order.
2631 * Higher order allocations also allow the placement of more objects in a
2632 * slab and thereby reduce object handling overhead. If the user has
2633 * requested a higher mininum order then we start with that one instead of
2634 * the smallest order which will fit the object.
2636 static inline int slab_order(int size, int min_objects,
2637 int max_order, int fract_leftover, int reserved)
2639 int order;
2640 int rem;
2641 int min_order = slub_min_order;
2643 if (order_objects(min_order, size, reserved) > MAX_OBJS_PER_PAGE)
2644 return get_order(size * MAX_OBJS_PER_PAGE) - 1;
2646 for (order = max(min_order,
2647 fls(min_objects * size - 1) - PAGE_SHIFT);
2648 order <= max_order; order++) {
2650 unsigned long slab_size = PAGE_SIZE << order;
2652 if (slab_size < min_objects * size + reserved)
2653 continue;
2655 rem = (slab_size - reserved) % size;
2657 if (rem <= slab_size / fract_leftover)
2658 break;
2662 return order;
2665 static inline int calculate_order(int size, int reserved)
2667 int order;
2668 int min_objects;
2669 int fraction;
2670 int max_objects;
2673 * Attempt to find best configuration for a slab. This
2674 * works by first attempting to generate a layout with
2675 * the best configuration and backing off gradually.
2677 * First we reduce the acceptable waste in a slab. Then
2678 * we reduce the minimum objects required in a slab.
2680 min_objects = slub_min_objects;
2681 if (!min_objects)
2682 min_objects = 4 * (fls(nr_cpu_ids) + 1);
2683 max_objects = order_objects(slub_max_order, size, reserved);
2684 min_objects = min(min_objects, max_objects);
2686 while (min_objects > 1) {
2687 fraction = 16;
2688 while (fraction >= 4) {
2689 order = slab_order(size, min_objects,
2690 slub_max_order, fraction, reserved);
2691 if (order <= slub_max_order)
2692 return order;
2693 fraction /= 2;
2695 min_objects--;
2699 * We were unable to place multiple objects in a slab. Now
2700 * lets see if we can place a single object there.
2702 order = slab_order(size, 1, slub_max_order, 1, reserved);
2703 if (order <= slub_max_order)
2704 return order;
2707 * Doh this slab cannot be placed using slub_max_order.
2709 order = slab_order(size, 1, MAX_ORDER, 1, reserved);
2710 if (order < MAX_ORDER)
2711 return order;
2712 return -ENOSYS;
2716 * Figure out what the alignment of the objects will be.
2718 static unsigned long calculate_alignment(unsigned long flags,
2719 unsigned long align, unsigned long size)
2722 * If the user wants hardware cache aligned objects then follow that
2723 * suggestion if the object is sufficiently large.
2725 * The hardware cache alignment cannot override the specified
2726 * alignment though. If that is greater then use it.
2728 if (flags & SLAB_HWCACHE_ALIGN) {
2729 unsigned long ralign = cache_line_size();
2730 while (size <= ralign / 2)
2731 ralign /= 2;
2732 align = max(align, ralign);
2735 if (align < ARCH_SLAB_MINALIGN)
2736 align = ARCH_SLAB_MINALIGN;
2738 return ALIGN(align, sizeof(void *));
2741 static void
2742 init_kmem_cache_node(struct kmem_cache_node *n, struct kmem_cache *s)
2744 n->nr_partial = 0;
2745 spin_lock_init(&n->list_lock);
2746 INIT_LIST_HEAD(&n->partial);
2747 #ifdef CONFIG_SLUB_DEBUG
2748 atomic_long_set(&n->nr_slabs, 0);
2749 atomic_long_set(&n->total_objects, 0);
2750 INIT_LIST_HEAD(&n->full);
2751 #endif
2754 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s)
2756 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE <
2757 SLUB_PAGE_SHIFT * sizeof(struct kmem_cache_cpu));
2760 * Must align to double word boundary for the double cmpxchg
2761 * instructions to work; see __pcpu_double_call_return_bool().
2763 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
2764 2 * sizeof(void *));
2766 if (!s->cpu_slab)
2767 return 0;
2769 init_kmem_cache_cpus(s);
2771 return 1;
2774 static struct kmem_cache *kmem_cache_node;
2777 * No kmalloc_node yet so do it by hand. We know that this is the first
2778 * slab on the node for this slabcache. There are no concurrent accesses
2779 * possible.
2781 * Note that this function only works on the kmalloc_node_cache
2782 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2783 * memory on a fresh node that has no slab structures yet.
2785 static void early_kmem_cache_node_alloc(int node)
2787 struct page *page;
2788 struct kmem_cache_node *n;
2790 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node));
2792 page = new_slab(kmem_cache_node, GFP_NOWAIT, node);
2794 BUG_ON(!page);
2795 if (page_to_nid(page) != node) {
2796 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2797 "node %d\n", node);
2798 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2799 "in order to be able to continue\n");
2802 n = page->freelist;
2803 BUG_ON(!n);
2804 page->freelist = get_freepointer(kmem_cache_node, n);
2805 page->inuse = 1;
2806 page->frozen = 0;
2807 kmem_cache_node->node[node] = n;
2808 #ifdef CONFIG_SLUB_DEBUG
2809 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE);
2810 init_tracking(kmem_cache_node, n);
2811 #endif
2812 init_kmem_cache_node(n, kmem_cache_node);
2813 inc_slabs_node(kmem_cache_node, node, page->objects);
2815 add_partial(n, page, DEACTIVATE_TO_HEAD);
2818 static void free_kmem_cache_nodes(struct kmem_cache *s)
2820 int node;
2822 for_each_node_state(node, N_NORMAL_MEMORY) {
2823 struct kmem_cache_node *n = s->node[node];
2825 if (n)
2826 kmem_cache_free(kmem_cache_node, n);
2828 s->node[node] = NULL;
2832 static int init_kmem_cache_nodes(struct kmem_cache *s)
2834 int node;
2836 for_each_node_state(node, N_NORMAL_MEMORY) {
2837 struct kmem_cache_node *n;
2839 if (slab_state == DOWN) {
2840 early_kmem_cache_node_alloc(node);
2841 continue;
2843 n = kmem_cache_alloc_node(kmem_cache_node,
2844 GFP_KERNEL, node);
2846 if (!n) {
2847 free_kmem_cache_nodes(s);
2848 return 0;
2851 s->node[node] = n;
2852 init_kmem_cache_node(n, s);
2854 return 1;
2857 static void set_min_partial(struct kmem_cache *s, unsigned long min)
2859 if (min < MIN_PARTIAL)
2860 min = MIN_PARTIAL;
2861 else if (min > MAX_PARTIAL)
2862 min = MAX_PARTIAL;
2863 s->min_partial = min;
2867 * calculate_sizes() determines the order and the distribution of data within
2868 * a slab object.
2870 static int calculate_sizes(struct kmem_cache *s, int forced_order)
2872 unsigned long flags = s->flags;
2873 unsigned long size = s->objsize;
2874 unsigned long align = s->align;
2875 int order;
2878 * Round up object size to the next word boundary. We can only
2879 * place the free pointer at word boundaries and this determines
2880 * the possible location of the free pointer.
2882 size = ALIGN(size, sizeof(void *));
2884 #ifdef CONFIG_SLUB_DEBUG
2886 * Determine if we can poison the object itself. If the user of
2887 * the slab may touch the object after free or before allocation
2888 * then we should never poison the object itself.
2890 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2891 !s->ctor)
2892 s->flags |= __OBJECT_POISON;
2893 else
2894 s->flags &= ~__OBJECT_POISON;
2898 * If we are Redzoning then check if there is some space between the
2899 * end of the object and the free pointer. If not then add an
2900 * additional word to have some bytes to store Redzone information.
2902 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2903 size += sizeof(void *);
2904 #endif
2907 * With that we have determined the number of bytes in actual use
2908 * by the object. This is the potential offset to the free pointer.
2910 s->inuse = size;
2912 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2913 s->ctor)) {
2915 * Relocate free pointer after the object if it is not
2916 * permitted to overwrite the first word of the object on
2917 * kmem_cache_free.
2919 * This is the case if we do RCU, have a constructor or
2920 * destructor or are poisoning the objects.
2922 s->offset = size;
2923 size += sizeof(void *);
2926 #ifdef CONFIG_SLUB_DEBUG
2927 if (flags & SLAB_STORE_USER)
2929 * Need to store information about allocs and frees after
2930 * the object.
2932 size += 2 * sizeof(struct track);
2934 if (flags & SLAB_RED_ZONE)
2936 * Add some empty padding so that we can catch
2937 * overwrites from earlier objects rather than let
2938 * tracking information or the free pointer be
2939 * corrupted if a user writes before the start
2940 * of the object.
2942 size += sizeof(void *);
2943 #endif
2946 * Determine the alignment based on various parameters that the
2947 * user specified and the dynamic determination of cache line size
2948 * on bootup.
2950 align = calculate_alignment(flags, align, s->objsize);
2951 s->align = align;
2954 * SLUB stores one object immediately after another beginning from
2955 * offset 0. In order to align the objects we have to simply size
2956 * each object to conform to the alignment.
2958 size = ALIGN(size, align);
2959 s->size = size;
2960 if (forced_order >= 0)
2961 order = forced_order;
2962 else
2963 order = calculate_order(size, s->reserved);
2965 if (order < 0)
2966 return 0;
2968 s->allocflags = 0;
2969 if (order)
2970 s->allocflags |= __GFP_COMP;
2972 if (s->flags & SLAB_CACHE_DMA)
2973 s->allocflags |= SLUB_DMA;
2975 if (s->flags & SLAB_RECLAIM_ACCOUNT)
2976 s->allocflags |= __GFP_RECLAIMABLE;
2979 * Determine the number of objects per slab
2981 s->oo = oo_make(order, size, s->reserved);
2982 s->min = oo_make(get_order(size), size, s->reserved);
2983 if (oo_objects(s->oo) > oo_objects(s->max))
2984 s->max = s->oo;
2986 return !!oo_objects(s->oo);
2990 static int kmem_cache_open(struct kmem_cache *s,
2991 const char *name, size_t size,
2992 size_t align, unsigned long flags,
2993 void (*ctor)(void *))
2995 memset(s, 0, kmem_size);
2996 s->name = name;
2997 s->ctor = ctor;
2998 s->objsize = size;
2999 s->align = align;
3000 s->flags = kmem_cache_flags(size, flags, name, ctor);
3001 s->reserved = 0;
3003 if (need_reserve_slab_rcu && (s->flags & SLAB_DESTROY_BY_RCU))
3004 s->reserved = sizeof(struct rcu_head);
3006 if (!calculate_sizes(s, -1))
3007 goto error;
3008 if (disable_higher_order_debug) {
3010 * Disable debugging flags that store metadata if the min slab
3011 * order increased.
3013 if (get_order(s->size) > get_order(s->objsize)) {
3014 s->flags &= ~DEBUG_METADATA_FLAGS;
3015 s->offset = 0;
3016 if (!calculate_sizes(s, -1))
3017 goto error;
3021 #ifdef CONFIG_CMPXCHG_DOUBLE
3022 if (system_has_cmpxchg_double() && (s->flags & SLAB_DEBUG_FLAGS) == 0)
3023 /* Enable fast mode */
3024 s->flags |= __CMPXCHG_DOUBLE;
3025 #endif
3028 * The larger the object size is, the more pages we want on the partial
3029 * list to avoid pounding the page allocator excessively.
3031 set_min_partial(s, ilog2(s->size) / 2);
3034 * cpu_partial determined the maximum number of objects kept in the
3035 * per cpu partial lists of a processor.
3037 * Per cpu partial lists mainly contain slabs that just have one
3038 * object freed. If they are used for allocation then they can be
3039 * filled up again with minimal effort. The slab will never hit the
3040 * per node partial lists and therefore no locking will be required.
3042 * This setting also determines
3044 * A) The number of objects from per cpu partial slabs dumped to the
3045 * per node list when we reach the limit.
3046 * B) The number of objects in partial partial slabs to extract from the
3047 * per node list when we run out of per cpu objects. We only fetch 50%
3048 * to keep some capacity around for frees.
3050 if (s->size >= PAGE_SIZE)
3051 s->cpu_partial = 2;
3052 else if (s->size >= 1024)
3053 s->cpu_partial = 6;
3054 else if (s->size >= 256)
3055 s->cpu_partial = 13;
3056 else
3057 s->cpu_partial = 30;
3059 s->refcount = 1;
3060 #ifdef CONFIG_NUMA
3061 s->remote_node_defrag_ratio = 1000;
3062 #endif
3063 if (!init_kmem_cache_nodes(s))
3064 goto error;
3066 if (alloc_kmem_cache_cpus(s))
3067 return 1;
3069 free_kmem_cache_nodes(s);
3070 error:
3071 if (flags & SLAB_PANIC)
3072 panic("Cannot create slab %s size=%lu realsize=%u "
3073 "order=%u offset=%u flags=%lx\n",
3074 s->name, (unsigned long)size, s->size, oo_order(s->oo),
3075 s->offset, flags);
3076 return 0;
3080 * Determine the size of a slab object
3082 unsigned int kmem_cache_size(struct kmem_cache *s)
3084 return s->objsize;
3086 EXPORT_SYMBOL(kmem_cache_size);
3088 static void list_slab_objects(struct kmem_cache *s, struct page *page,
3089 const char *text)
3091 #ifdef CONFIG_SLUB_DEBUG
3092 void *addr = page_address(page);
3093 void *p;
3094 unsigned long *map = kzalloc(BITS_TO_LONGS(page->objects) *
3095 sizeof(long), GFP_ATOMIC);
3096 if (!map)
3097 return;
3098 slab_err(s, page, "%s", text);
3099 slab_lock(page);
3101 get_map(s, page, map);
3102 for_each_object(p, s, addr, page->objects) {
3104 if (!test_bit(slab_index(p, s, addr), map)) {
3105 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu\n",
3106 p, p - addr);
3107 print_tracking(s, p);
3110 slab_unlock(page);
3111 kfree(map);
3112 #endif
3116 * Attempt to free all partial slabs on a node.
3117 * This is called from kmem_cache_close(). We must be the last thread
3118 * using the cache and therefore we do not need to lock anymore.
3120 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
3122 struct page *page, *h;
3124 list_for_each_entry_safe(page, h, &n->partial, lru) {
3125 if (!page->inuse) {
3126 remove_partial(n, page);
3127 discard_slab(s, page);
3128 } else {
3129 list_slab_objects(s, page,
3130 "Objects remaining on kmem_cache_close()");
3136 * Release all resources used by a slab cache.
3138 static inline int kmem_cache_close(struct kmem_cache *s)
3140 int node;
3142 flush_all(s);
3143 free_percpu(s->cpu_slab);
3144 /* Attempt to free all objects */
3145 for_each_node_state(node, N_NORMAL_MEMORY) {
3146 struct kmem_cache_node *n = get_node(s, node);
3148 free_partial(s, n);
3149 if (n->nr_partial || slabs_node(s, node))
3150 return 1;
3152 free_kmem_cache_nodes(s);
3153 return 0;
3157 * Close a cache and release the kmem_cache structure
3158 * (must be used for caches created using kmem_cache_create)
3160 void kmem_cache_destroy(struct kmem_cache *s)
3162 down_write(&slub_lock);
3163 s->refcount--;
3164 if (!s->refcount) {
3165 list_del(&s->list);
3166 up_write(&slub_lock);
3167 if (kmem_cache_close(s)) {
3168 printk(KERN_ERR "SLUB %s: %s called for cache that "
3169 "still has objects.\n", s->name, __func__);
3170 dump_stack();
3172 if (s->flags & SLAB_DESTROY_BY_RCU)
3173 rcu_barrier();
3174 sysfs_slab_remove(s);
3175 } else
3176 up_write(&slub_lock);
3178 EXPORT_SYMBOL(kmem_cache_destroy);
3180 /********************************************************************
3181 * Kmalloc subsystem
3182 *******************************************************************/
3184 struct kmem_cache *kmalloc_caches[SLUB_PAGE_SHIFT];
3185 EXPORT_SYMBOL(kmalloc_caches);
3187 static struct kmem_cache *kmem_cache;
3189 #ifdef CONFIG_ZONE_DMA
3190 static struct kmem_cache *kmalloc_dma_caches[SLUB_PAGE_SHIFT];
3191 #endif
3193 static int __init setup_slub_min_order(char *str)
3195 get_option(&str, &slub_min_order);
3197 return 1;
3200 __setup("slub_min_order=", setup_slub_min_order);
3202 static int __init setup_slub_max_order(char *str)
3204 get_option(&str, &slub_max_order);
3205 slub_max_order = min(slub_max_order, MAX_ORDER - 1);
3207 return 1;
3210 __setup("slub_max_order=", setup_slub_max_order);
3212 static int __init setup_slub_min_objects(char *str)
3214 get_option(&str, &slub_min_objects);
3216 return 1;
3219 __setup("slub_min_objects=", setup_slub_min_objects);
3221 static int __init setup_slub_nomerge(char *str)
3223 slub_nomerge = 1;
3224 return 1;
3227 __setup("slub_nomerge", setup_slub_nomerge);
3229 static struct kmem_cache *__init create_kmalloc_cache(const char *name,
3230 int size, unsigned int flags)
3232 struct kmem_cache *s;
3234 s = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3237 * This function is called with IRQs disabled during early-boot on
3238 * single CPU so there's no need to take slub_lock here.
3240 if (!kmem_cache_open(s, name, size, ARCH_KMALLOC_MINALIGN,
3241 flags, NULL))
3242 goto panic;
3244 list_add(&s->list, &slab_caches);
3245 return s;
3247 panic:
3248 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
3249 return NULL;
3253 * Conversion table for small slabs sizes / 8 to the index in the
3254 * kmalloc array. This is necessary for slabs < 192 since we have non power
3255 * of two cache sizes there. The size of larger slabs can be determined using
3256 * fls.
3258 static s8 size_index[24] = {
3259 3, /* 8 */
3260 4, /* 16 */
3261 5, /* 24 */
3262 5, /* 32 */
3263 6, /* 40 */
3264 6, /* 48 */
3265 6, /* 56 */
3266 6, /* 64 */
3267 1, /* 72 */
3268 1, /* 80 */
3269 1, /* 88 */
3270 1, /* 96 */
3271 7, /* 104 */
3272 7, /* 112 */
3273 7, /* 120 */
3274 7, /* 128 */
3275 2, /* 136 */
3276 2, /* 144 */
3277 2, /* 152 */
3278 2, /* 160 */
3279 2, /* 168 */
3280 2, /* 176 */
3281 2, /* 184 */
3282 2 /* 192 */
3285 static inline int size_index_elem(size_t bytes)
3287 return (bytes - 1) / 8;
3290 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
3292 int index;
3294 if (size <= 192) {
3295 if (!size)
3296 return ZERO_SIZE_PTR;
3298 index = size_index[size_index_elem(size)];
3299 } else
3300 index = fls(size - 1);
3302 #ifdef CONFIG_ZONE_DMA
3303 if (unlikely((flags & SLUB_DMA)))
3304 return kmalloc_dma_caches[index];
3306 #endif
3307 return kmalloc_caches[index];
3310 void *__kmalloc(size_t size, gfp_t flags)
3312 struct kmem_cache *s;
3313 void *ret;
3315 if (unlikely(size > SLUB_MAX_SIZE))
3316 return kmalloc_large(size, flags);
3318 s = get_slab(size, flags);
3320 if (unlikely(ZERO_OR_NULL_PTR(s)))
3321 return s;
3323 ret = slab_alloc(s, flags, NUMA_NO_NODE, _RET_IP_);
3325 trace_kmalloc(_RET_IP_, ret, size, s->size, flags);
3327 return ret;
3329 EXPORT_SYMBOL(__kmalloc);
3331 #ifdef CONFIG_NUMA
3332 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
3334 struct page *page;
3335 void *ptr = NULL;
3337 flags |= __GFP_COMP | __GFP_NOTRACK;
3338 page = alloc_pages_node(node, flags, get_order(size));
3339 if (page)
3340 ptr = page_address(page);
3342 kmemleak_alloc(ptr, size, 1, flags);
3343 return ptr;
3346 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3348 struct kmem_cache *s;
3349 void *ret;
3351 if (unlikely(size > SLUB_MAX_SIZE)) {
3352 ret = kmalloc_large_node(size, flags, node);
3354 trace_kmalloc_node(_RET_IP_, ret,
3355 size, PAGE_SIZE << get_order(size),
3356 flags, node);
3358 return ret;
3361 s = get_slab(size, flags);
3363 if (unlikely(ZERO_OR_NULL_PTR(s)))
3364 return s;
3366 ret = slab_alloc(s, flags, node, _RET_IP_);
3368 trace_kmalloc_node(_RET_IP_, ret, size, s->size, flags, node);
3370 return ret;
3372 EXPORT_SYMBOL(__kmalloc_node);
3373 #endif
3375 size_t ksize(const void *object)
3377 struct page *page;
3379 if (unlikely(object == ZERO_SIZE_PTR))
3380 return 0;
3382 page = virt_to_head_page(object);
3384 if (unlikely(!PageSlab(page))) {
3385 WARN_ON(!PageCompound(page));
3386 return PAGE_SIZE << compound_order(page);
3389 return slab_ksize(page->slab);
3391 EXPORT_SYMBOL(ksize);
3393 #ifdef CONFIG_SLUB_DEBUG
3394 bool verify_mem_not_deleted(const void *x)
3396 struct page *page;
3397 void *object = (void *)x;
3398 unsigned long flags;
3399 bool rv;
3401 if (unlikely(ZERO_OR_NULL_PTR(x)))
3402 return false;
3404 local_irq_save(flags);
3406 page = virt_to_head_page(x);
3407 if (unlikely(!PageSlab(page))) {
3408 /* maybe it was from stack? */
3409 rv = true;
3410 goto out_unlock;
3413 slab_lock(page);
3414 if (on_freelist(page->slab, page, object)) {
3415 object_err(page->slab, page, object, "Object is on free-list");
3416 rv = false;
3417 } else {
3418 rv = true;
3420 slab_unlock(page);
3422 out_unlock:
3423 local_irq_restore(flags);
3424 return rv;
3426 EXPORT_SYMBOL(verify_mem_not_deleted);
3427 #endif
3429 void kfree(const void *x)
3431 struct page *page;
3432 void *object = (void *)x;
3434 trace_kfree(_RET_IP_, x);
3436 if (unlikely(ZERO_OR_NULL_PTR(x)))
3437 return;
3439 page = virt_to_head_page(x);
3440 if (unlikely(!PageSlab(page))) {
3441 BUG_ON(!PageCompound(page));
3442 kmemleak_free(x);
3443 put_page(page);
3444 return;
3446 slab_free(page->slab, page, object, _RET_IP_);
3448 EXPORT_SYMBOL(kfree);
3451 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
3452 * the remaining slabs by the number of items in use. The slabs with the
3453 * most items in use come first. New allocations will then fill those up
3454 * and thus they can be removed from the partial lists.
3456 * The slabs with the least items are placed last. This results in them
3457 * being allocated from last increasing the chance that the last objects
3458 * are freed in them.
3460 int kmem_cache_shrink(struct kmem_cache *s)
3462 int node;
3463 int i;
3464 struct kmem_cache_node *n;
3465 struct page *page;
3466 struct page *t;
3467 int objects = oo_objects(s->max);
3468 struct list_head *slabs_by_inuse =
3469 kmalloc(sizeof(struct list_head) * objects, GFP_KERNEL);
3470 unsigned long flags;
3472 if (!slabs_by_inuse)
3473 return -ENOMEM;
3475 flush_all(s);
3476 for_each_node_state(node, N_NORMAL_MEMORY) {
3477 n = get_node(s, node);
3479 if (!n->nr_partial)
3480 continue;
3482 for (i = 0; i < objects; i++)
3483 INIT_LIST_HEAD(slabs_by_inuse + i);
3485 spin_lock_irqsave(&n->list_lock, flags);
3488 * Build lists indexed by the items in use in each slab.
3490 * Note that concurrent frees may occur while we hold the
3491 * list_lock. page->inuse here is the upper limit.
3493 list_for_each_entry_safe(page, t, &n->partial, lru) {
3494 list_move(&page->lru, slabs_by_inuse + page->inuse);
3495 if (!page->inuse)
3496 n->nr_partial--;
3500 * Rebuild the partial list with the slabs filled up most
3501 * first and the least used slabs at the end.
3503 for (i = objects - 1; i > 0; i--)
3504 list_splice(slabs_by_inuse + i, n->partial.prev);
3506 spin_unlock_irqrestore(&n->list_lock, flags);
3508 /* Release empty slabs */
3509 list_for_each_entry_safe(page, t, slabs_by_inuse, lru)
3510 discard_slab(s, page);
3513 kfree(slabs_by_inuse);
3514 return 0;
3516 EXPORT_SYMBOL(kmem_cache_shrink);
3518 #if defined(CONFIG_MEMORY_HOTPLUG)
3519 static int slab_mem_going_offline_callback(void *arg)
3521 struct kmem_cache *s;
3523 down_read(&slub_lock);
3524 list_for_each_entry(s, &slab_caches, list)
3525 kmem_cache_shrink(s);
3526 up_read(&slub_lock);
3528 return 0;
3531 static void slab_mem_offline_callback(void *arg)
3533 struct kmem_cache_node *n;
3534 struct kmem_cache *s;
3535 struct memory_notify *marg = arg;
3536 int offline_node;
3538 offline_node = marg->status_change_nid;
3541 * If the node still has available memory. we need kmem_cache_node
3542 * for it yet.
3544 if (offline_node < 0)
3545 return;
3547 down_read(&slub_lock);
3548 list_for_each_entry(s, &slab_caches, list) {
3549 n = get_node(s, offline_node);
3550 if (n) {
3552 * if n->nr_slabs > 0, slabs still exist on the node
3553 * that is going down. We were unable to free them,
3554 * and offline_pages() function shouldn't call this
3555 * callback. So, we must fail.
3557 BUG_ON(slabs_node(s, offline_node));
3559 s->node[offline_node] = NULL;
3560 kmem_cache_free(kmem_cache_node, n);
3563 up_read(&slub_lock);
3566 static int slab_mem_going_online_callback(void *arg)
3568 struct kmem_cache_node *n;
3569 struct kmem_cache *s;
3570 struct memory_notify *marg = arg;
3571 int nid = marg->status_change_nid;
3572 int ret = 0;
3575 * If the node's memory is already available, then kmem_cache_node is
3576 * already created. Nothing to do.
3578 if (nid < 0)
3579 return 0;
3582 * We are bringing a node online. No memory is available yet. We must
3583 * allocate a kmem_cache_node structure in order to bring the node
3584 * online.
3586 down_read(&slub_lock);
3587 list_for_each_entry(s, &slab_caches, list) {
3589 * XXX: kmem_cache_alloc_node will fallback to other nodes
3590 * since memory is not yet available from the node that
3591 * is brought up.
3593 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL);
3594 if (!n) {
3595 ret = -ENOMEM;
3596 goto out;
3598 init_kmem_cache_node(n, s);
3599 s->node[nid] = n;
3601 out:
3602 up_read(&slub_lock);
3603 return ret;
3606 static int slab_memory_callback(struct notifier_block *self,
3607 unsigned long action, void *arg)
3609 int ret = 0;
3611 switch (action) {
3612 case MEM_GOING_ONLINE:
3613 ret = slab_mem_going_online_callback(arg);
3614 break;
3615 case MEM_GOING_OFFLINE:
3616 ret = slab_mem_going_offline_callback(arg);
3617 break;
3618 case MEM_OFFLINE:
3619 case MEM_CANCEL_ONLINE:
3620 slab_mem_offline_callback(arg);
3621 break;
3622 case MEM_ONLINE:
3623 case MEM_CANCEL_OFFLINE:
3624 break;
3626 if (ret)
3627 ret = notifier_from_errno(ret);
3628 else
3629 ret = NOTIFY_OK;
3630 return ret;
3633 #endif /* CONFIG_MEMORY_HOTPLUG */
3635 /********************************************************************
3636 * Basic setup of slabs
3637 *******************************************************************/
3640 * Used for early kmem_cache structures that were allocated using
3641 * the page allocator
3644 static void __init kmem_cache_bootstrap_fixup(struct kmem_cache *s)
3646 int node;
3648 list_add(&s->list, &slab_caches);
3649 s->refcount = -1;
3651 for_each_node_state(node, N_NORMAL_MEMORY) {
3652 struct kmem_cache_node *n = get_node(s, node);
3653 struct page *p;
3655 if (n) {
3656 list_for_each_entry(p, &n->partial, lru)
3657 p->slab = s;
3659 #ifdef CONFIG_SLUB_DEBUG
3660 list_for_each_entry(p, &n->full, lru)
3661 p->slab = s;
3662 #endif
3667 void __init kmem_cache_init(void)
3669 int i;
3670 int caches = 0;
3671 struct kmem_cache *temp_kmem_cache;
3672 int order;
3673 struct kmem_cache *temp_kmem_cache_node;
3674 unsigned long kmalloc_size;
3676 kmem_size = offsetof(struct kmem_cache, node) +
3677 nr_node_ids * sizeof(struct kmem_cache_node *);
3679 /* Allocate two kmem_caches from the page allocator */
3680 kmalloc_size = ALIGN(kmem_size, cache_line_size());
3681 order = get_order(2 * kmalloc_size);
3682 kmem_cache = (void *)__get_free_pages(GFP_NOWAIT, order);
3685 * Must first have the slab cache available for the allocations of the
3686 * struct kmem_cache_node's. There is special bootstrap code in
3687 * kmem_cache_open for slab_state == DOWN.
3689 kmem_cache_node = (void *)kmem_cache + kmalloc_size;
3691 kmem_cache_open(kmem_cache_node, "kmem_cache_node",
3692 sizeof(struct kmem_cache_node),
3693 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
3695 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
3697 /* Able to allocate the per node structures */
3698 slab_state = PARTIAL;
3700 temp_kmem_cache = kmem_cache;
3701 kmem_cache_open(kmem_cache, "kmem_cache", kmem_size,
3702 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
3703 kmem_cache = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3704 memcpy(kmem_cache, temp_kmem_cache, kmem_size);
3707 * Allocate kmem_cache_node properly from the kmem_cache slab.
3708 * kmem_cache_node is separately allocated so no need to
3709 * update any list pointers.
3711 temp_kmem_cache_node = kmem_cache_node;
3713 kmem_cache_node = kmem_cache_alloc(kmem_cache, GFP_NOWAIT);
3714 memcpy(kmem_cache_node, temp_kmem_cache_node, kmem_size);
3716 kmem_cache_bootstrap_fixup(kmem_cache_node);
3718 caches++;
3719 kmem_cache_bootstrap_fixup(kmem_cache);
3720 caches++;
3721 /* Free temporary boot structure */
3722 free_pages((unsigned long)temp_kmem_cache, order);
3724 /* Now we can use the kmem_cache to allocate kmalloc slabs */
3727 * Patch up the size_index table if we have strange large alignment
3728 * requirements for the kmalloc array. This is only the case for
3729 * MIPS it seems. The standard arches will not generate any code here.
3731 * Largest permitted alignment is 256 bytes due to the way we
3732 * handle the index determination for the smaller caches.
3734 * Make sure that nothing crazy happens if someone starts tinkering
3735 * around with ARCH_KMALLOC_MINALIGN
3737 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
3738 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
3740 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) {
3741 int elem = size_index_elem(i);
3742 if (elem >= ARRAY_SIZE(size_index))
3743 break;
3744 size_index[elem] = KMALLOC_SHIFT_LOW;
3747 if (KMALLOC_MIN_SIZE == 64) {
3749 * The 96 byte size cache is not used if the alignment
3750 * is 64 byte.
3752 for (i = 64 + 8; i <= 96; i += 8)
3753 size_index[size_index_elem(i)] = 7;
3754 } else if (KMALLOC_MIN_SIZE == 128) {
3756 * The 192 byte sized cache is not used if the alignment
3757 * is 128 byte. Redirect kmalloc to use the 256 byte cache
3758 * instead.
3760 for (i = 128 + 8; i <= 192; i += 8)
3761 size_index[size_index_elem(i)] = 8;
3764 /* Caches that are not of the two-to-the-power-of size */
3765 if (KMALLOC_MIN_SIZE <= 32) {
3766 kmalloc_caches[1] = create_kmalloc_cache("kmalloc-96", 96, 0);
3767 caches++;
3770 if (KMALLOC_MIN_SIZE <= 64) {
3771 kmalloc_caches[2] = create_kmalloc_cache("kmalloc-192", 192, 0);
3772 caches++;
3775 for (i = KMALLOC_SHIFT_LOW; i < SLUB_PAGE_SHIFT; i++) {
3776 kmalloc_caches[i] = create_kmalloc_cache("kmalloc", 1 << i, 0);
3777 caches++;
3780 slab_state = UP;
3782 /* Provide the correct kmalloc names now that the caches are up */
3783 if (KMALLOC_MIN_SIZE <= 32) {
3784 kmalloc_caches[1]->name = kstrdup(kmalloc_caches[1]->name, GFP_NOWAIT);
3785 BUG_ON(!kmalloc_caches[1]->name);
3788 if (KMALLOC_MIN_SIZE <= 64) {
3789 kmalloc_caches[2]->name = kstrdup(kmalloc_caches[2]->name, GFP_NOWAIT);
3790 BUG_ON(!kmalloc_caches[2]->name);
3793 for (i = KMALLOC_SHIFT_LOW; i < SLUB_PAGE_SHIFT; i++) {
3794 char *s = kasprintf(GFP_NOWAIT, "kmalloc-%d", 1 << i);
3796 BUG_ON(!s);
3797 kmalloc_caches[i]->name = s;
3800 #ifdef CONFIG_SMP
3801 register_cpu_notifier(&slab_notifier);
3802 #endif
3804 #ifdef CONFIG_ZONE_DMA
3805 for (i = 0; i < SLUB_PAGE_SHIFT; i++) {
3806 struct kmem_cache *s = kmalloc_caches[i];
3808 if (s && s->size) {
3809 char *name = kasprintf(GFP_NOWAIT,
3810 "dma-kmalloc-%d", s->objsize);
3812 BUG_ON(!name);
3813 kmalloc_dma_caches[i] = create_kmalloc_cache(name,
3814 s->objsize, SLAB_CACHE_DMA);
3817 #endif
3818 printk(KERN_INFO
3819 "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
3820 " CPUs=%d, Nodes=%d\n",
3821 caches, cache_line_size(),
3822 slub_min_order, slub_max_order, slub_min_objects,
3823 nr_cpu_ids, nr_node_ids);
3826 void __init kmem_cache_init_late(void)
3831 * Find a mergeable slab cache
3833 static int slab_unmergeable(struct kmem_cache *s)
3835 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
3836 return 1;
3838 if (s->ctor)
3839 return 1;
3842 * We may have set a slab to be unmergeable during bootstrap.
3844 if (s->refcount < 0)
3845 return 1;
3847 return 0;
3850 static struct kmem_cache *find_mergeable(size_t size,
3851 size_t align, unsigned long flags, const char *name,
3852 void (*ctor)(void *))
3854 struct kmem_cache *s;
3856 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
3857 return NULL;
3859 if (ctor)
3860 return NULL;
3862 size = ALIGN(size, sizeof(void *));
3863 align = calculate_alignment(flags, align, size);
3864 size = ALIGN(size, align);
3865 flags = kmem_cache_flags(size, flags, name, NULL);
3867 list_for_each_entry(s, &slab_caches, list) {
3868 if (slab_unmergeable(s))
3869 continue;
3871 if (size > s->size)
3872 continue;
3874 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
3875 continue;
3877 * Check if alignment is compatible.
3878 * Courtesy of Adrian Drzewiecki
3880 if ((s->size & ~(align - 1)) != s->size)
3881 continue;
3883 if (s->size - size >= sizeof(void *))
3884 continue;
3886 return s;
3888 return NULL;
3891 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
3892 size_t align, unsigned long flags, void (*ctor)(void *))
3894 struct kmem_cache *s;
3895 char *n;
3897 if (WARN_ON(!name))
3898 return NULL;
3900 down_write(&slub_lock);
3901 s = find_mergeable(size, align, flags, name, ctor);
3902 if (s) {
3903 s->refcount++;
3905 * Adjust the object sizes so that we clear
3906 * the complete object on kzalloc.
3908 s->objsize = max(s->objsize, (int)size);
3909 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
3911 if (sysfs_slab_alias(s, name)) {
3912 s->refcount--;
3913 goto err;
3915 up_write(&slub_lock);
3916 return s;
3919 n = kstrdup(name, GFP_KERNEL);
3920 if (!n)
3921 goto err;
3923 s = kmalloc(kmem_size, GFP_KERNEL);
3924 if (s) {
3925 if (kmem_cache_open(s, n,
3926 size, align, flags, ctor)) {
3927 list_add(&s->list, &slab_caches);
3928 if (sysfs_slab_add(s)) {
3929 list_del(&s->list);
3930 kfree(n);
3931 kfree(s);
3932 goto err;
3934 up_write(&slub_lock);
3935 return s;
3937 kfree(n);
3938 kfree(s);
3940 err:
3941 up_write(&slub_lock);
3943 if (flags & SLAB_PANIC)
3944 panic("Cannot create slabcache %s\n", name);
3945 else
3946 s = NULL;
3947 return s;
3949 EXPORT_SYMBOL(kmem_cache_create);
3951 #ifdef CONFIG_SMP
3953 * Use the cpu notifier to insure that the cpu slabs are flushed when
3954 * necessary.
3956 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
3957 unsigned long action, void *hcpu)
3959 long cpu = (long)hcpu;
3960 struct kmem_cache *s;
3961 unsigned long flags;
3963 switch (action) {
3964 case CPU_UP_CANCELED:
3965 case CPU_UP_CANCELED_FROZEN:
3966 case CPU_DEAD:
3967 case CPU_DEAD_FROZEN:
3968 down_read(&slub_lock);
3969 list_for_each_entry(s, &slab_caches, list) {
3970 local_irq_save(flags);
3971 __flush_cpu_slab(s, cpu);
3972 local_irq_restore(flags);
3974 up_read(&slub_lock);
3975 break;
3976 default:
3977 break;
3979 return NOTIFY_OK;
3982 static struct notifier_block __cpuinitdata slab_notifier = {
3983 .notifier_call = slab_cpuup_callback
3986 #endif
3988 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, unsigned long caller)
3990 struct kmem_cache *s;
3991 void *ret;
3993 if (unlikely(size > SLUB_MAX_SIZE))
3994 return kmalloc_large(size, gfpflags);
3996 s = get_slab(size, gfpflags);
3998 if (unlikely(ZERO_OR_NULL_PTR(s)))
3999 return s;
4001 ret = slab_alloc(s, gfpflags, NUMA_NO_NODE, caller);
4003 /* Honor the call site pointer we received. */
4004 trace_kmalloc(caller, ret, size, s->size, gfpflags);
4006 return ret;
4009 #ifdef CONFIG_NUMA
4010 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
4011 int node, unsigned long caller)
4013 struct kmem_cache *s;
4014 void *ret;
4016 if (unlikely(size > SLUB_MAX_SIZE)) {
4017 ret = kmalloc_large_node(size, gfpflags, node);
4019 trace_kmalloc_node(caller, ret,
4020 size, PAGE_SIZE << get_order(size),
4021 gfpflags, node);
4023 return ret;
4026 s = get_slab(size, gfpflags);
4028 if (unlikely(ZERO_OR_NULL_PTR(s)))
4029 return s;
4031 ret = slab_alloc(s, gfpflags, node, caller);
4033 /* Honor the call site pointer we received. */
4034 trace_kmalloc_node(caller, ret, size, s->size, gfpflags, node);
4036 return ret;
4038 #endif
4040 #ifdef CONFIG_SYSFS
4041 static int count_inuse(struct page *page)
4043 return page->inuse;
4046 static int count_total(struct page *page)
4048 return page->objects;
4050 #endif
4052 #ifdef CONFIG_SLUB_DEBUG
4053 static int validate_slab(struct kmem_cache *s, struct page *page,
4054 unsigned long *map)
4056 void *p;
4057 void *addr = page_address(page);
4059 if (!check_slab(s, page) ||
4060 !on_freelist(s, page, NULL))
4061 return 0;
4063 /* Now we know that a valid freelist exists */
4064 bitmap_zero(map, page->objects);
4066 get_map(s, page, map);
4067 for_each_object(p, s, addr, page->objects) {
4068 if (test_bit(slab_index(p, s, addr), map))
4069 if (!check_object(s, page, p, SLUB_RED_INACTIVE))
4070 return 0;
4073 for_each_object(p, s, addr, page->objects)
4074 if (!test_bit(slab_index(p, s, addr), map))
4075 if (!check_object(s, page, p, SLUB_RED_ACTIVE))
4076 return 0;
4077 return 1;
4080 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
4081 unsigned long *map)
4083 slab_lock(page);
4084 validate_slab(s, page, map);
4085 slab_unlock(page);
4088 static int validate_slab_node(struct kmem_cache *s,
4089 struct kmem_cache_node *n, unsigned long *map)
4091 unsigned long count = 0;
4092 struct page *page;
4093 unsigned long flags;
4095 spin_lock_irqsave(&n->list_lock, flags);
4097 list_for_each_entry(page, &n->partial, lru) {
4098 validate_slab_slab(s, page, map);
4099 count++;
4101 if (count != n->nr_partial)
4102 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
4103 "counter=%ld\n", s->name, count, n->nr_partial);
4105 if (!(s->flags & SLAB_STORE_USER))
4106 goto out;
4108 list_for_each_entry(page, &n->full, lru) {
4109 validate_slab_slab(s, page, map);
4110 count++;
4112 if (count != atomic_long_read(&n->nr_slabs))
4113 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
4114 "counter=%ld\n", s->name, count,
4115 atomic_long_read(&n->nr_slabs));
4117 out:
4118 spin_unlock_irqrestore(&n->list_lock, flags);
4119 return count;
4122 static long validate_slab_cache(struct kmem_cache *s)
4124 int node;
4125 unsigned long count = 0;
4126 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4127 sizeof(unsigned long), GFP_KERNEL);
4129 if (!map)
4130 return -ENOMEM;
4132 flush_all(s);
4133 for_each_node_state(node, N_NORMAL_MEMORY) {
4134 struct kmem_cache_node *n = get_node(s, node);
4136 count += validate_slab_node(s, n, map);
4138 kfree(map);
4139 return count;
4142 * Generate lists of code addresses where slabcache objects are allocated
4143 * and freed.
4146 struct location {
4147 unsigned long count;
4148 unsigned long addr;
4149 long long sum_time;
4150 long min_time;
4151 long max_time;
4152 long min_pid;
4153 long max_pid;
4154 DECLARE_BITMAP(cpus, NR_CPUS);
4155 nodemask_t nodes;
4158 struct loc_track {
4159 unsigned long max;
4160 unsigned long count;
4161 struct location *loc;
4164 static void free_loc_track(struct loc_track *t)
4166 if (t->max)
4167 free_pages((unsigned long)t->loc,
4168 get_order(sizeof(struct location) * t->max));
4171 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
4173 struct location *l;
4174 int order;
4176 order = get_order(sizeof(struct location) * max);
4178 l = (void *)__get_free_pages(flags, order);
4179 if (!l)
4180 return 0;
4182 if (t->count) {
4183 memcpy(l, t->loc, sizeof(struct location) * t->count);
4184 free_loc_track(t);
4186 t->max = max;
4187 t->loc = l;
4188 return 1;
4191 static int add_location(struct loc_track *t, struct kmem_cache *s,
4192 const struct track *track)
4194 long start, end, pos;
4195 struct location *l;
4196 unsigned long caddr;
4197 unsigned long age = jiffies - track->when;
4199 start = -1;
4200 end = t->count;
4202 for ( ; ; ) {
4203 pos = start + (end - start + 1) / 2;
4206 * There is nothing at "end". If we end up there
4207 * we need to add something to before end.
4209 if (pos == end)
4210 break;
4212 caddr = t->loc[pos].addr;
4213 if (track->addr == caddr) {
4215 l = &t->loc[pos];
4216 l->count++;
4217 if (track->when) {
4218 l->sum_time += age;
4219 if (age < l->min_time)
4220 l->min_time = age;
4221 if (age > l->max_time)
4222 l->max_time = age;
4224 if (track->pid < l->min_pid)
4225 l->min_pid = track->pid;
4226 if (track->pid > l->max_pid)
4227 l->max_pid = track->pid;
4229 cpumask_set_cpu(track->cpu,
4230 to_cpumask(l->cpus));
4232 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4233 return 1;
4236 if (track->addr < caddr)
4237 end = pos;
4238 else
4239 start = pos;
4243 * Not found. Insert new tracking element.
4245 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
4246 return 0;
4248 l = t->loc + pos;
4249 if (pos < t->count)
4250 memmove(l + 1, l,
4251 (t->count - pos) * sizeof(struct location));
4252 t->count++;
4253 l->count = 1;
4254 l->addr = track->addr;
4255 l->sum_time = age;
4256 l->min_time = age;
4257 l->max_time = age;
4258 l->min_pid = track->pid;
4259 l->max_pid = track->pid;
4260 cpumask_clear(to_cpumask(l->cpus));
4261 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus));
4262 nodes_clear(l->nodes);
4263 node_set(page_to_nid(virt_to_page(track)), l->nodes);
4264 return 1;
4267 static void process_slab(struct loc_track *t, struct kmem_cache *s,
4268 struct page *page, enum track_item alloc,
4269 unsigned long *map)
4271 void *addr = page_address(page);
4272 void *p;
4274 bitmap_zero(map, page->objects);
4275 get_map(s, page, map);
4277 for_each_object(p, s, addr, page->objects)
4278 if (!test_bit(slab_index(p, s, addr), map))
4279 add_location(t, s, get_track(s, p, alloc));
4282 static int list_locations(struct kmem_cache *s, char *buf,
4283 enum track_item alloc)
4285 int len = 0;
4286 unsigned long i;
4287 struct loc_track t = { 0, 0, NULL };
4288 int node;
4289 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
4290 sizeof(unsigned long), GFP_KERNEL);
4292 if (!map || !alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
4293 GFP_TEMPORARY)) {
4294 kfree(map);
4295 return sprintf(buf, "Out of memory\n");
4297 /* Push back cpu slabs */
4298 flush_all(s);
4300 for_each_node_state(node, N_NORMAL_MEMORY) {
4301 struct kmem_cache_node *n = get_node(s, node);
4302 unsigned long flags;
4303 struct page *page;
4305 if (!atomic_long_read(&n->nr_slabs))
4306 continue;
4308 spin_lock_irqsave(&n->list_lock, flags);
4309 list_for_each_entry(page, &n->partial, lru)
4310 process_slab(&t, s, page, alloc, map);
4311 list_for_each_entry(page, &n->full, lru)
4312 process_slab(&t, s, page, alloc, map);
4313 spin_unlock_irqrestore(&n->list_lock, flags);
4316 for (i = 0; i < t.count; i++) {
4317 struct location *l = &t.loc[i];
4319 if (len > PAGE_SIZE - KSYM_SYMBOL_LEN - 100)
4320 break;
4321 len += sprintf(buf + len, "%7ld ", l->count);
4323 if (l->addr)
4324 len += sprintf(buf + len, "%pS", (void *)l->addr);
4325 else
4326 len += sprintf(buf + len, "<not-available>");
4328 if (l->sum_time != l->min_time) {
4329 len += sprintf(buf + len, " age=%ld/%ld/%ld",
4330 l->min_time,
4331 (long)div_u64(l->sum_time, l->count),
4332 l->max_time);
4333 } else
4334 len += sprintf(buf + len, " age=%ld",
4335 l->min_time);
4337 if (l->min_pid != l->max_pid)
4338 len += sprintf(buf + len, " pid=%ld-%ld",
4339 l->min_pid, l->max_pid);
4340 else
4341 len += sprintf(buf + len, " pid=%ld",
4342 l->min_pid);
4344 if (num_online_cpus() > 1 &&
4345 !cpumask_empty(to_cpumask(l->cpus)) &&
4346 len < PAGE_SIZE - 60) {
4347 len += sprintf(buf + len, " cpus=");
4348 len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
4349 to_cpumask(l->cpus));
4352 if (nr_online_nodes > 1 && !nodes_empty(l->nodes) &&
4353 len < PAGE_SIZE - 60) {
4354 len += sprintf(buf + len, " nodes=");
4355 len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
4356 l->nodes);
4359 len += sprintf(buf + len, "\n");
4362 free_loc_track(&t);
4363 kfree(map);
4364 if (!t.count)
4365 len += sprintf(buf, "No data\n");
4366 return len;
4368 #endif
4370 #ifdef SLUB_RESILIENCY_TEST
4371 static void resiliency_test(void)
4373 u8 *p;
4375 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 16 || SLUB_PAGE_SHIFT < 10);
4377 printk(KERN_ERR "SLUB resiliency testing\n");
4378 printk(KERN_ERR "-----------------------\n");
4379 printk(KERN_ERR "A. Corruption after allocation\n");
4381 p = kzalloc(16, GFP_KERNEL);
4382 p[16] = 0x12;
4383 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
4384 " 0x12->0x%p\n\n", p + 16);
4386 validate_slab_cache(kmalloc_caches[4]);
4388 /* Hmmm... The next two are dangerous */
4389 p = kzalloc(32, GFP_KERNEL);
4390 p[32 + sizeof(void *)] = 0x34;
4391 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
4392 " 0x34 -> -0x%p\n", p);
4393 printk(KERN_ERR
4394 "If allocated object is overwritten then not detectable\n\n");
4396 validate_slab_cache(kmalloc_caches[5]);
4397 p = kzalloc(64, GFP_KERNEL);
4398 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
4399 *p = 0x56;
4400 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
4402 printk(KERN_ERR
4403 "If allocated object is overwritten then not detectable\n\n");
4404 validate_slab_cache(kmalloc_caches[6]);
4406 printk(KERN_ERR "\nB. Corruption after free\n");
4407 p = kzalloc(128, GFP_KERNEL);
4408 kfree(p);
4409 *p = 0x78;
4410 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
4411 validate_slab_cache(kmalloc_caches[7]);
4413 p = kzalloc(256, GFP_KERNEL);
4414 kfree(p);
4415 p[50] = 0x9a;
4416 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n",
4418 validate_slab_cache(kmalloc_caches[8]);
4420 p = kzalloc(512, GFP_KERNEL);
4421 kfree(p);
4422 p[512] = 0xab;
4423 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
4424 validate_slab_cache(kmalloc_caches[9]);
4426 #else
4427 #ifdef CONFIG_SYSFS
4428 static void resiliency_test(void) {};
4429 #endif
4430 #endif
4432 #ifdef CONFIG_SYSFS
4433 enum slab_stat_type {
4434 SL_ALL, /* All slabs */
4435 SL_PARTIAL, /* Only partially allocated slabs */
4436 SL_CPU, /* Only slabs used for cpu caches */
4437 SL_OBJECTS, /* Determine allocated objects not slabs */
4438 SL_TOTAL /* Determine object capacity not slabs */
4441 #define SO_ALL (1 << SL_ALL)
4442 #define SO_PARTIAL (1 << SL_PARTIAL)
4443 #define SO_CPU (1 << SL_CPU)
4444 #define SO_OBJECTS (1 << SL_OBJECTS)
4445 #define SO_TOTAL (1 << SL_TOTAL)
4447 static ssize_t show_slab_objects(struct kmem_cache *s,
4448 char *buf, unsigned long flags)
4450 unsigned long total = 0;
4451 int node;
4452 int x;
4453 unsigned long *nodes;
4454 unsigned long *per_cpu;
4456 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
4457 if (!nodes)
4458 return -ENOMEM;
4459 per_cpu = nodes + nr_node_ids;
4461 if (flags & SO_CPU) {
4462 int cpu;
4464 for_each_possible_cpu(cpu) {
4465 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu);
4466 struct page *page;
4468 if (!c || c->node < 0)
4469 continue;
4471 if (c->page) {
4472 if (flags & SO_TOTAL)
4473 x = c->page->objects;
4474 else if (flags & SO_OBJECTS)
4475 x = c->page->inuse;
4476 else
4477 x = 1;
4479 total += x;
4480 nodes[c->node] += x;
4482 page = c->partial;
4484 if (page) {
4485 x = page->pobjects;
4486 total += x;
4487 nodes[c->node] += x;
4489 per_cpu[c->node]++;
4493 lock_memory_hotplug();
4494 #ifdef CONFIG_SLUB_DEBUG
4495 if (flags & SO_ALL) {
4496 for_each_node_state(node, N_NORMAL_MEMORY) {
4497 struct kmem_cache_node *n = get_node(s, node);
4499 if (flags & SO_TOTAL)
4500 x = atomic_long_read(&n->total_objects);
4501 else if (flags & SO_OBJECTS)
4502 x = atomic_long_read(&n->total_objects) -
4503 count_partial(n, count_free);
4505 else
4506 x = atomic_long_read(&n->nr_slabs);
4507 total += x;
4508 nodes[node] += x;
4511 } else
4512 #endif
4513 if (flags & SO_PARTIAL) {
4514 for_each_node_state(node, N_NORMAL_MEMORY) {
4515 struct kmem_cache_node *n = get_node(s, node);
4517 if (flags & SO_TOTAL)
4518 x = count_partial(n, count_total);
4519 else if (flags & SO_OBJECTS)
4520 x = count_partial(n, count_inuse);
4521 else
4522 x = n->nr_partial;
4523 total += x;
4524 nodes[node] += x;
4527 x = sprintf(buf, "%lu", total);
4528 #ifdef CONFIG_NUMA
4529 for_each_node_state(node, N_NORMAL_MEMORY)
4530 if (nodes[node])
4531 x += sprintf(buf + x, " N%d=%lu",
4532 node, nodes[node]);
4533 #endif
4534 unlock_memory_hotplug();
4535 kfree(nodes);
4536 return x + sprintf(buf + x, "\n");
4539 #ifdef CONFIG_SLUB_DEBUG
4540 static int any_slab_objects(struct kmem_cache *s)
4542 int node;
4544 for_each_online_node(node) {
4545 struct kmem_cache_node *n = get_node(s, node);
4547 if (!n)
4548 continue;
4550 if (atomic_long_read(&n->total_objects))
4551 return 1;
4553 return 0;
4555 #endif
4557 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
4558 #define to_slab(n) container_of(n, struct kmem_cache, kobj)
4560 struct slab_attribute {
4561 struct attribute attr;
4562 ssize_t (*show)(struct kmem_cache *s, char *buf);
4563 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
4566 #define SLAB_ATTR_RO(_name) \
4567 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
4569 #define SLAB_ATTR(_name) \
4570 static struct slab_attribute _name##_attr = \
4571 __ATTR(_name, 0644, _name##_show, _name##_store)
4573 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
4575 return sprintf(buf, "%d\n", s->size);
4577 SLAB_ATTR_RO(slab_size);
4579 static ssize_t align_show(struct kmem_cache *s, char *buf)
4581 return sprintf(buf, "%d\n", s->align);
4583 SLAB_ATTR_RO(align);
4585 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
4587 return sprintf(buf, "%d\n", s->objsize);
4589 SLAB_ATTR_RO(object_size);
4591 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
4593 return sprintf(buf, "%d\n", oo_objects(s->oo));
4595 SLAB_ATTR_RO(objs_per_slab);
4597 static ssize_t order_store(struct kmem_cache *s,
4598 const char *buf, size_t length)
4600 unsigned long order;
4601 int err;
4603 err = strict_strtoul(buf, 10, &order);
4604 if (err)
4605 return err;
4607 if (order > slub_max_order || order < slub_min_order)
4608 return -EINVAL;
4610 calculate_sizes(s, order);
4611 return length;
4614 static ssize_t order_show(struct kmem_cache *s, char *buf)
4616 return sprintf(buf, "%d\n", oo_order(s->oo));
4618 SLAB_ATTR(order);
4620 static ssize_t min_partial_show(struct kmem_cache *s, char *buf)
4622 return sprintf(buf, "%lu\n", s->min_partial);
4625 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf,
4626 size_t length)
4628 unsigned long min;
4629 int err;
4631 err = strict_strtoul(buf, 10, &min);
4632 if (err)
4633 return err;
4635 set_min_partial(s, min);
4636 return length;
4638 SLAB_ATTR(min_partial);
4640 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf)
4642 return sprintf(buf, "%u\n", s->cpu_partial);
4645 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf,
4646 size_t length)
4648 unsigned long objects;
4649 int err;
4651 err = strict_strtoul(buf, 10, &objects);
4652 if (err)
4653 return err;
4655 s->cpu_partial = objects;
4656 flush_all(s);
4657 return length;
4659 SLAB_ATTR(cpu_partial);
4661 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
4663 if (!s->ctor)
4664 return 0;
4665 return sprintf(buf, "%pS\n", s->ctor);
4667 SLAB_ATTR_RO(ctor);
4669 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
4671 return sprintf(buf, "%d\n", s->refcount - 1);
4673 SLAB_ATTR_RO(aliases);
4675 static ssize_t partial_show(struct kmem_cache *s, char *buf)
4677 return show_slab_objects(s, buf, SO_PARTIAL);
4679 SLAB_ATTR_RO(partial);
4681 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
4683 return show_slab_objects(s, buf, SO_CPU);
4685 SLAB_ATTR_RO(cpu_slabs);
4687 static ssize_t objects_show(struct kmem_cache *s, char *buf)
4689 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
4691 SLAB_ATTR_RO(objects);
4693 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
4695 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
4697 SLAB_ATTR_RO(objects_partial);
4699 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf)
4701 int objects = 0;
4702 int pages = 0;
4703 int cpu;
4704 int len;
4706 for_each_online_cpu(cpu) {
4707 struct page *page = per_cpu_ptr(s->cpu_slab, cpu)->partial;
4709 if (page) {
4710 pages += page->pages;
4711 objects += page->pobjects;
4715 len = sprintf(buf, "%d(%d)", objects, pages);
4717 #ifdef CONFIG_SMP
4718 for_each_online_cpu(cpu) {
4719 struct page *page = per_cpu_ptr(s->cpu_slab, cpu) ->partial;
4721 if (page && len < PAGE_SIZE - 20)
4722 len += sprintf(buf + len, " C%d=%d(%d)", cpu,
4723 page->pobjects, page->pages);
4725 #endif
4726 return len + sprintf(buf + len, "\n");
4728 SLAB_ATTR_RO(slabs_cpu_partial);
4730 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
4732 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
4735 static ssize_t reclaim_account_store(struct kmem_cache *s,
4736 const char *buf, size_t length)
4738 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
4739 if (buf[0] == '1')
4740 s->flags |= SLAB_RECLAIM_ACCOUNT;
4741 return length;
4743 SLAB_ATTR(reclaim_account);
4745 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
4747 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
4749 SLAB_ATTR_RO(hwcache_align);
4751 #ifdef CONFIG_ZONE_DMA
4752 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
4754 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
4756 SLAB_ATTR_RO(cache_dma);
4757 #endif
4759 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
4761 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
4763 SLAB_ATTR_RO(destroy_by_rcu);
4765 static ssize_t reserved_show(struct kmem_cache *s, char *buf)
4767 return sprintf(buf, "%d\n", s->reserved);
4769 SLAB_ATTR_RO(reserved);
4771 #ifdef CONFIG_SLUB_DEBUG
4772 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
4774 return show_slab_objects(s, buf, SO_ALL);
4776 SLAB_ATTR_RO(slabs);
4778 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
4780 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
4782 SLAB_ATTR_RO(total_objects);
4784 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
4786 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
4789 static ssize_t sanity_checks_store(struct kmem_cache *s,
4790 const char *buf, size_t length)
4792 s->flags &= ~SLAB_DEBUG_FREE;
4793 if (buf[0] == '1') {
4794 s->flags &= ~__CMPXCHG_DOUBLE;
4795 s->flags |= SLAB_DEBUG_FREE;
4797 return length;
4799 SLAB_ATTR(sanity_checks);
4801 static ssize_t trace_show(struct kmem_cache *s, char *buf)
4803 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
4806 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
4807 size_t length)
4809 s->flags &= ~SLAB_TRACE;
4810 if (buf[0] == '1') {
4811 s->flags &= ~__CMPXCHG_DOUBLE;
4812 s->flags |= SLAB_TRACE;
4814 return length;
4816 SLAB_ATTR(trace);
4818 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
4820 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
4823 static ssize_t red_zone_store(struct kmem_cache *s,
4824 const char *buf, size_t length)
4826 if (any_slab_objects(s))
4827 return -EBUSY;
4829 s->flags &= ~SLAB_RED_ZONE;
4830 if (buf[0] == '1') {
4831 s->flags &= ~__CMPXCHG_DOUBLE;
4832 s->flags |= SLAB_RED_ZONE;
4834 calculate_sizes(s, -1);
4835 return length;
4837 SLAB_ATTR(red_zone);
4839 static ssize_t poison_show(struct kmem_cache *s, char *buf)
4841 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
4844 static ssize_t poison_store(struct kmem_cache *s,
4845 const char *buf, size_t length)
4847 if (any_slab_objects(s))
4848 return -EBUSY;
4850 s->flags &= ~SLAB_POISON;
4851 if (buf[0] == '1') {
4852 s->flags &= ~__CMPXCHG_DOUBLE;
4853 s->flags |= SLAB_POISON;
4855 calculate_sizes(s, -1);
4856 return length;
4858 SLAB_ATTR(poison);
4860 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
4862 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
4865 static ssize_t store_user_store(struct kmem_cache *s,
4866 const char *buf, size_t length)
4868 if (any_slab_objects(s))
4869 return -EBUSY;
4871 s->flags &= ~SLAB_STORE_USER;
4872 if (buf[0] == '1') {
4873 s->flags &= ~__CMPXCHG_DOUBLE;
4874 s->flags |= SLAB_STORE_USER;
4876 calculate_sizes(s, -1);
4877 return length;
4879 SLAB_ATTR(store_user);
4881 static ssize_t validate_show(struct kmem_cache *s, char *buf)
4883 return 0;
4886 static ssize_t validate_store(struct kmem_cache *s,
4887 const char *buf, size_t length)
4889 int ret = -EINVAL;
4891 if (buf[0] == '1') {
4892 ret = validate_slab_cache(s);
4893 if (ret >= 0)
4894 ret = length;
4896 return ret;
4898 SLAB_ATTR(validate);
4900 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
4902 if (!(s->flags & SLAB_STORE_USER))
4903 return -ENOSYS;
4904 return list_locations(s, buf, TRACK_ALLOC);
4906 SLAB_ATTR_RO(alloc_calls);
4908 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
4910 if (!(s->flags & SLAB_STORE_USER))
4911 return -ENOSYS;
4912 return list_locations(s, buf, TRACK_FREE);
4914 SLAB_ATTR_RO(free_calls);
4915 #endif /* CONFIG_SLUB_DEBUG */
4917 #ifdef CONFIG_FAILSLAB
4918 static ssize_t failslab_show(struct kmem_cache *s, char *buf)
4920 return sprintf(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB));
4923 static ssize_t failslab_store(struct kmem_cache *s, const char *buf,
4924 size_t length)
4926 s->flags &= ~SLAB_FAILSLAB;
4927 if (buf[0] == '1')
4928 s->flags |= SLAB_FAILSLAB;
4929 return length;
4931 SLAB_ATTR(failslab);
4932 #endif
4934 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
4936 return 0;
4939 static ssize_t shrink_store(struct kmem_cache *s,
4940 const char *buf, size_t length)
4942 if (buf[0] == '1') {
4943 int rc = kmem_cache_shrink(s);
4945 if (rc)
4946 return rc;
4947 } else
4948 return -EINVAL;
4949 return length;
4951 SLAB_ATTR(shrink);
4953 #ifdef CONFIG_NUMA
4954 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
4956 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
4959 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
4960 const char *buf, size_t length)
4962 unsigned long ratio;
4963 int err;
4965 err = strict_strtoul(buf, 10, &ratio);
4966 if (err)
4967 return err;
4969 if (ratio <= 100)
4970 s->remote_node_defrag_ratio = ratio * 10;
4972 return length;
4974 SLAB_ATTR(remote_node_defrag_ratio);
4975 #endif
4977 #ifdef CONFIG_SLUB_STATS
4978 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
4980 unsigned long sum = 0;
4981 int cpu;
4982 int len;
4983 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
4985 if (!data)
4986 return -ENOMEM;
4988 for_each_online_cpu(cpu) {
4989 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si];
4991 data[cpu] = x;
4992 sum += x;
4995 len = sprintf(buf, "%lu", sum);
4997 #ifdef CONFIG_SMP
4998 for_each_online_cpu(cpu) {
4999 if (data[cpu] && len < PAGE_SIZE - 20)
5000 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
5002 #endif
5003 kfree(data);
5004 return len + sprintf(buf + len, "\n");
5007 static void clear_stat(struct kmem_cache *s, enum stat_item si)
5009 int cpu;
5011 for_each_online_cpu(cpu)
5012 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0;
5015 #define STAT_ATTR(si, text) \
5016 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
5018 return show_stat(s, buf, si); \
5020 static ssize_t text##_store(struct kmem_cache *s, \
5021 const char *buf, size_t length) \
5023 if (buf[0] != '0') \
5024 return -EINVAL; \
5025 clear_stat(s, si); \
5026 return length; \
5028 SLAB_ATTR(text); \
5030 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
5031 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
5032 STAT_ATTR(FREE_FASTPATH, free_fastpath);
5033 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
5034 STAT_ATTR(FREE_FROZEN, free_frozen);
5035 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
5036 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
5037 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
5038 STAT_ATTR(ALLOC_SLAB, alloc_slab);
5039 STAT_ATTR(ALLOC_REFILL, alloc_refill);
5040 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch);
5041 STAT_ATTR(FREE_SLAB, free_slab);
5042 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
5043 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
5044 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
5045 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
5046 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
5047 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
5048 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass);
5049 STAT_ATTR(ORDER_FALLBACK, order_fallback);
5050 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail);
5051 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail);
5052 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc);
5053 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free);
5054 #endif
5056 static struct attribute *slab_attrs[] = {
5057 &slab_size_attr.attr,
5058 &object_size_attr.attr,
5059 &objs_per_slab_attr.attr,
5060 &order_attr.attr,
5061 &min_partial_attr.attr,
5062 &cpu_partial_attr.attr,
5063 &objects_attr.attr,
5064 &objects_partial_attr.attr,
5065 &partial_attr.attr,
5066 &cpu_slabs_attr.attr,
5067 &ctor_attr.attr,
5068 &aliases_attr.attr,
5069 &align_attr.attr,
5070 &hwcache_align_attr.attr,
5071 &reclaim_account_attr.attr,
5072 &destroy_by_rcu_attr.attr,
5073 &shrink_attr.attr,
5074 &reserved_attr.attr,
5075 &slabs_cpu_partial_attr.attr,
5076 #ifdef CONFIG_SLUB_DEBUG
5077 &total_objects_attr.attr,
5078 &slabs_attr.attr,
5079 &sanity_checks_attr.attr,
5080 &trace_attr.attr,
5081 &red_zone_attr.attr,
5082 &poison_attr.attr,
5083 &store_user_attr.attr,
5084 &validate_attr.attr,
5085 &alloc_calls_attr.attr,
5086 &free_calls_attr.attr,
5087 #endif
5088 #ifdef CONFIG_ZONE_DMA
5089 &cache_dma_attr.attr,
5090 #endif
5091 #ifdef CONFIG_NUMA
5092 &remote_node_defrag_ratio_attr.attr,
5093 #endif
5094 #ifdef CONFIG_SLUB_STATS
5095 &alloc_fastpath_attr.attr,
5096 &alloc_slowpath_attr.attr,
5097 &free_fastpath_attr.attr,
5098 &free_slowpath_attr.attr,
5099 &free_frozen_attr.attr,
5100 &free_add_partial_attr.attr,
5101 &free_remove_partial_attr.attr,
5102 &alloc_from_partial_attr.attr,
5103 &alloc_slab_attr.attr,
5104 &alloc_refill_attr.attr,
5105 &alloc_node_mismatch_attr.attr,
5106 &free_slab_attr.attr,
5107 &cpuslab_flush_attr.attr,
5108 &deactivate_full_attr.attr,
5109 &deactivate_empty_attr.attr,
5110 &deactivate_to_head_attr.attr,
5111 &deactivate_to_tail_attr.attr,
5112 &deactivate_remote_frees_attr.attr,
5113 &deactivate_bypass_attr.attr,
5114 &order_fallback_attr.attr,
5115 &cmpxchg_double_fail_attr.attr,
5116 &cmpxchg_double_cpu_fail_attr.attr,
5117 &cpu_partial_alloc_attr.attr,
5118 &cpu_partial_free_attr.attr,
5119 #endif
5120 #ifdef CONFIG_FAILSLAB
5121 &failslab_attr.attr,
5122 #endif
5124 NULL
5127 static struct attribute_group slab_attr_group = {
5128 .attrs = slab_attrs,
5131 static ssize_t slab_attr_show(struct kobject *kobj,
5132 struct attribute *attr,
5133 char *buf)
5135 struct slab_attribute *attribute;
5136 struct kmem_cache *s;
5137 int err;
5139 attribute = to_slab_attr(attr);
5140 s = to_slab(kobj);
5142 if (!attribute->show)
5143 return -EIO;
5145 err = attribute->show(s, buf);
5147 return err;
5150 static ssize_t slab_attr_store(struct kobject *kobj,
5151 struct attribute *attr,
5152 const char *buf, size_t len)
5154 struct slab_attribute *attribute;
5155 struct kmem_cache *s;
5156 int err;
5158 attribute = to_slab_attr(attr);
5159 s = to_slab(kobj);
5161 if (!attribute->store)
5162 return -EIO;
5164 err = attribute->store(s, buf, len);
5166 return err;
5169 static void kmem_cache_release(struct kobject *kobj)
5171 struct kmem_cache *s = to_slab(kobj);
5173 kfree(s->name);
5174 kfree(s);
5177 static const struct sysfs_ops slab_sysfs_ops = {
5178 .show = slab_attr_show,
5179 .store = slab_attr_store,
5182 static struct kobj_type slab_ktype = {
5183 .sysfs_ops = &slab_sysfs_ops,
5184 .release = kmem_cache_release
5187 static int uevent_filter(struct kset *kset, struct kobject *kobj)
5189 struct kobj_type *ktype = get_ktype(kobj);
5191 if (ktype == &slab_ktype)
5192 return 1;
5193 return 0;
5196 static const struct kset_uevent_ops slab_uevent_ops = {
5197 .filter = uevent_filter,
5200 static struct kset *slab_kset;
5202 #define ID_STR_LENGTH 64
5204 /* Create a unique string id for a slab cache:
5206 * Format :[flags-]size
5208 static char *create_unique_id(struct kmem_cache *s)
5210 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
5211 char *p = name;
5213 BUG_ON(!name);
5215 *p++ = ':';
5217 * First flags affecting slabcache operations. We will only
5218 * get here for aliasable slabs so we do not need to support
5219 * too many flags. The flags here must cover all flags that
5220 * are matched during merging to guarantee that the id is
5221 * unique.
5223 if (s->flags & SLAB_CACHE_DMA)
5224 *p++ = 'd';
5225 if (s->flags & SLAB_RECLAIM_ACCOUNT)
5226 *p++ = 'a';
5227 if (s->flags & SLAB_DEBUG_FREE)
5228 *p++ = 'F';
5229 if (!(s->flags & SLAB_NOTRACK))
5230 *p++ = 't';
5231 if (p != name + 1)
5232 *p++ = '-';
5233 p += sprintf(p, "%07d", s->size);
5234 BUG_ON(p > name + ID_STR_LENGTH - 1);
5235 return name;
5238 static int sysfs_slab_add(struct kmem_cache *s)
5240 int err;
5241 const char *name;
5242 int unmergeable;
5244 if (slab_state < SYSFS)
5245 /* Defer until later */
5246 return 0;
5248 unmergeable = slab_unmergeable(s);
5249 if (unmergeable) {
5251 * Slabcache can never be merged so we can use the name proper.
5252 * This is typically the case for debug situations. In that
5253 * case we can catch duplicate names easily.
5255 sysfs_remove_link(&slab_kset->kobj, s->name);
5256 name = s->name;
5257 } else {
5259 * Create a unique name for the slab as a target
5260 * for the symlinks.
5262 name = create_unique_id(s);
5265 s->kobj.kset = slab_kset;
5266 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, name);
5267 if (err) {
5268 kobject_put(&s->kobj);
5269 return err;
5272 err = sysfs_create_group(&s->kobj, &slab_attr_group);
5273 if (err) {
5274 kobject_del(&s->kobj);
5275 kobject_put(&s->kobj);
5276 return err;
5278 kobject_uevent(&s->kobj, KOBJ_ADD);
5279 if (!unmergeable) {
5280 /* Setup first alias */
5281 sysfs_slab_alias(s, s->name);
5282 kfree(name);
5284 return 0;
5287 static void sysfs_slab_remove(struct kmem_cache *s)
5289 if (slab_state < SYSFS)
5291 * Sysfs has not been setup yet so no need to remove the
5292 * cache from sysfs.
5294 return;
5296 kobject_uevent(&s->kobj, KOBJ_REMOVE);
5297 kobject_del(&s->kobj);
5298 kobject_put(&s->kobj);
5302 * Need to buffer aliases during bootup until sysfs becomes
5303 * available lest we lose that information.
5305 struct saved_alias {
5306 struct kmem_cache *s;
5307 const char *name;
5308 struct saved_alias *next;
5311 static struct saved_alias *alias_list;
5313 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
5315 struct saved_alias *al;
5317 if (slab_state == SYSFS) {
5319 * If we have a leftover link then remove it.
5321 sysfs_remove_link(&slab_kset->kobj, name);
5322 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
5325 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
5326 if (!al)
5327 return -ENOMEM;
5329 al->s = s;
5330 al->name = name;
5331 al->next = alias_list;
5332 alias_list = al;
5333 return 0;
5336 static int __init slab_sysfs_init(void)
5338 struct kmem_cache *s;
5339 int err;
5341 down_write(&slub_lock);
5343 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
5344 if (!slab_kset) {
5345 up_write(&slub_lock);
5346 printk(KERN_ERR "Cannot register slab subsystem.\n");
5347 return -ENOSYS;
5350 slab_state = SYSFS;
5352 list_for_each_entry(s, &slab_caches, list) {
5353 err = sysfs_slab_add(s);
5354 if (err)
5355 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
5356 " to sysfs\n", s->name);
5359 while (alias_list) {
5360 struct saved_alias *al = alias_list;
5362 alias_list = alias_list->next;
5363 err = sysfs_slab_alias(al->s, al->name);
5364 if (err)
5365 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
5366 " %s to sysfs\n", s->name);
5367 kfree(al);
5370 up_write(&slub_lock);
5371 resiliency_test();
5372 return 0;
5375 __initcall(slab_sysfs_init);
5376 #endif /* CONFIG_SYSFS */
5379 * The /proc/slabinfo ABI
5381 #ifdef CONFIG_SLABINFO
5382 static void print_slabinfo_header(struct seq_file *m)
5384 seq_puts(m, "slabinfo - version: 2.1\n");
5385 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
5386 "<objperslab> <pagesperslab>");
5387 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
5388 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
5389 seq_putc(m, '\n');
5392 static void *s_start(struct seq_file *m, loff_t *pos)
5394 loff_t n = *pos;
5396 down_read(&slub_lock);
5397 if (!n)
5398 print_slabinfo_header(m);
5400 return seq_list_start(&slab_caches, *pos);
5403 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
5405 return seq_list_next(p, &slab_caches, pos);
5408 static void s_stop(struct seq_file *m, void *p)
5410 up_read(&slub_lock);
5413 static int s_show(struct seq_file *m, void *p)
5415 unsigned long nr_partials = 0;
5416 unsigned long nr_slabs = 0;
5417 unsigned long nr_inuse = 0;
5418 unsigned long nr_objs = 0;
5419 unsigned long nr_free = 0;
5420 struct kmem_cache *s;
5421 int node;
5423 s = list_entry(p, struct kmem_cache, list);
5425 for_each_online_node(node) {
5426 struct kmem_cache_node *n = get_node(s, node);
5428 if (!n)
5429 continue;
5431 nr_partials += n->nr_partial;
5432 nr_slabs += atomic_long_read(&n->nr_slabs);
5433 nr_objs += atomic_long_read(&n->total_objects);
5434 nr_free += count_partial(n, count_free);
5437 nr_inuse = nr_objs - nr_free;
5439 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", s->name, nr_inuse,
5440 nr_objs, s->size, oo_objects(s->oo),
5441 (1 << oo_order(s->oo)));
5442 seq_printf(m, " : tunables %4u %4u %4u", 0, 0, 0);
5443 seq_printf(m, " : slabdata %6lu %6lu %6lu", nr_slabs, nr_slabs,
5444 0UL);
5445 seq_putc(m, '\n');
5446 return 0;
5449 static const struct seq_operations slabinfo_op = {
5450 .start = s_start,
5451 .next = s_next,
5452 .stop = s_stop,
5453 .show = s_show,
5456 static int slabinfo_open(struct inode *inode, struct file *file)
5458 return seq_open(file, &slabinfo_op);
5461 static const struct file_operations proc_slabinfo_operations = {
5462 .open = slabinfo_open,
5463 .read = seq_read,
5464 .llseek = seq_lseek,
5465 .release = seq_release,
5468 static int __init slab_proc_init(void)
5470 proc_create("slabinfo", S_IRUGO, NULL, &proc_slabinfo_operations);
5471 return 0;
5473 module_init(slab_proc_init);
5474 #endif /* CONFIG_SLABINFO */