i386: make Oprofile call shutdown() only once per session
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / mm / slub.c
blobe29a42988c78ca17d9594c2cb9fdb3cb87c257d0
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 and only
6 * uses a centralized lock to manage a pool of partial slabs.
8 * (C) 2007 SGI, Christoph Lameter <clameter@sgi.com>
9 */
11 #include <linux/mm.h>
12 #include <linux/module.h>
13 #include <linux/bit_spinlock.h>
14 #include <linux/interrupt.h>
15 #include <linux/bitops.h>
16 #include <linux/slab.h>
17 #include <linux/seq_file.h>
18 #include <linux/cpu.h>
19 #include <linux/cpuset.h>
20 #include <linux/mempolicy.h>
21 #include <linux/ctype.h>
22 #include <linux/kallsyms.h>
25 * Lock order:
26 * 1. slab_lock(page)
27 * 2. slab->list_lock
29 * The slab_lock protects operations on the object of a particular
30 * slab and its metadata in the page struct. If the slab lock
31 * has been taken then no allocations nor frees can be performed
32 * on the objects in the slab nor can the slab be added or removed
33 * from the partial or full lists since this would mean modifying
34 * the page_struct of the slab.
36 * The list_lock protects the partial and full list on each node and
37 * the partial slab counter. If taken then no new slabs may be added or
38 * removed from the lists nor make the number of partial slabs be modified.
39 * (Note that the total number of slabs is an atomic value that may be
40 * modified without taking the list lock).
42 * The list_lock is a centralized lock and thus we avoid taking it as
43 * much as possible. As long as SLUB does not have to handle partial
44 * slabs, operations can continue without any centralized lock. F.e.
45 * allocating a long series of objects that fill up slabs does not require
46 * the list lock.
48 * The lock order is sometimes inverted when we are trying to get a slab
49 * off a list. We take the list_lock and then look for a page on the list
50 * to use. While we do that objects in the slabs may be freed. We can
51 * only operate on the slab if we have also taken the slab_lock. So we use
52 * a slab_trylock() on the slab. If trylock was successful then no frees
53 * can occur anymore and we can use the slab for allocations etc. If the
54 * slab_trylock() does not succeed then frees are in progress in the slab and
55 * we must stay away from it for a while since we may cause a bouncing
56 * cacheline if we try to acquire the lock. So go onto the next slab.
57 * If all pages are busy then we may allocate a new slab instead of reusing
58 * a partial slab. A new slab has noone operating on it and thus there is
59 * no danger of cacheline contention.
61 * Interrupts are disabled during allocation and deallocation in order to
62 * make the slab allocator safe to use in the context of an irq. In addition
63 * interrupts are disabled to ensure that the processor does not change
64 * while handling per_cpu slabs, due to kernel preemption.
66 * SLUB assigns one slab for allocation to each processor.
67 * Allocations only occur from these slabs called cpu slabs.
69 * Slabs with free elements are kept on a partial list and during regular
70 * operations no list for full slabs is used. If an object in a full slab is
71 * freed then the slab will show up again on the partial lists.
72 * We track full slabs for debugging purposes though because otherwise we
73 * cannot scan all objects.
75 * Slabs are freed when they become empty. Teardown and setup is
76 * minimal so we rely on the page allocators per cpu caches for
77 * fast frees and allocs.
79 * Overloading of page flags that are otherwise used for LRU management.
81 * PageActive The slab is frozen and exempt from list processing.
82 * This means that the slab is dedicated to a purpose
83 * such as satisfying allocations for a specific
84 * processor. Objects may be freed in the slab while
85 * it is frozen but slab_free will then skip the usual
86 * list operations. It is up to the processor holding
87 * the slab to integrate the slab into the slab lists
88 * when the slab is no longer needed.
90 * One use of this flag is to mark slabs that are
91 * used for allocations. Then such a slab becomes a cpu
92 * slab. The cpu slab may be equipped with an additional
93 * freelist that allows lockless access to
94 * free objects in addition to the regular freelist
95 * that requires the slab lock.
97 * PageError Slab requires special handling due to debug
98 * options set. This moves slab handling out of
99 * the fast path and disables lockless freelists.
102 #define FROZEN (1 << PG_active)
104 #ifdef CONFIG_SLUB_DEBUG
105 #define SLABDEBUG (1 << PG_error)
106 #else
107 #define SLABDEBUG 0
108 #endif
110 static inline int SlabFrozen(struct page *page)
112 return page->flags & FROZEN;
115 static inline void SetSlabFrozen(struct page *page)
117 page->flags |= FROZEN;
120 static inline void ClearSlabFrozen(struct page *page)
122 page->flags &= ~FROZEN;
125 static inline int SlabDebug(struct page *page)
127 return page->flags & SLABDEBUG;
130 static inline void SetSlabDebug(struct page *page)
132 page->flags |= SLABDEBUG;
135 static inline void ClearSlabDebug(struct page *page)
137 page->flags &= ~SLABDEBUG;
141 * Issues still to be resolved:
143 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
145 * - Variable sizing of the per node arrays
148 /* Enable to test recovery from slab corruption on boot */
149 #undef SLUB_RESILIENCY_TEST
151 #if PAGE_SHIFT <= 12
154 * Small page size. Make sure that we do not fragment memory
156 #define DEFAULT_MAX_ORDER 1
157 #define DEFAULT_MIN_OBJECTS 4
159 #else
162 * Large page machines are customarily able to handle larger
163 * page orders.
165 #define DEFAULT_MAX_ORDER 2
166 #define DEFAULT_MIN_OBJECTS 8
168 #endif
171 * Mininum number of partial slabs. These will be left on the partial
172 * lists even if they are empty. kmem_cache_shrink may reclaim them.
174 #define MIN_PARTIAL 2
177 * Maximum number of desirable partial slabs.
178 * The existence of more partial slabs makes kmem_cache_shrink
179 * sort the partial list by the number of objects in the.
181 #define MAX_PARTIAL 10
183 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
184 SLAB_POISON | SLAB_STORE_USER)
187 * Set of flags that will prevent slab merging
189 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
190 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
192 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
193 SLAB_CACHE_DMA)
195 #ifndef ARCH_KMALLOC_MINALIGN
196 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
197 #endif
199 #ifndef ARCH_SLAB_MINALIGN
200 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
201 #endif
203 /* Internal SLUB flags */
204 #define __OBJECT_POISON 0x80000000 /* Poison object */
205 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
207 /* Not all arches define cache_line_size */
208 #ifndef cache_line_size
209 #define cache_line_size() L1_CACHE_BYTES
210 #endif
212 static int kmem_size = sizeof(struct kmem_cache);
214 #ifdef CONFIG_SMP
215 static struct notifier_block slab_notifier;
216 #endif
218 static enum {
219 DOWN, /* No slab functionality available */
220 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
221 UP, /* Everything works but does not show up in sysfs */
222 SYSFS /* Sysfs up */
223 } slab_state = DOWN;
225 /* A list of all slab caches on the system */
226 static DECLARE_RWSEM(slub_lock);
227 static LIST_HEAD(slab_caches);
230 * Tracking user of a slab.
232 struct track {
233 void *addr; /* Called from address */
234 int cpu; /* Was running on cpu */
235 int pid; /* Pid context */
236 unsigned long when; /* When did the operation occur */
239 enum track_item { TRACK_ALLOC, TRACK_FREE };
241 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
242 static int sysfs_slab_add(struct kmem_cache *);
243 static int sysfs_slab_alias(struct kmem_cache *, const char *);
244 static void sysfs_slab_remove(struct kmem_cache *);
245 #else
246 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
247 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
248 { return 0; }
249 static inline void sysfs_slab_remove(struct kmem_cache *s) {}
250 #endif
252 /********************************************************************
253 * Core slab cache functions
254 *******************************************************************/
256 int slab_is_available(void)
258 return slab_state >= UP;
261 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
263 #ifdef CONFIG_NUMA
264 return s->node[node];
265 #else
266 return &s->local_node;
267 #endif
270 static inline struct kmem_cache_cpu *get_cpu_slab(struct kmem_cache *s, int cpu)
272 #ifdef CONFIG_SMP
273 return s->cpu_slab[cpu];
274 #else
275 return &s->cpu_slab;
276 #endif
279 static inline int check_valid_pointer(struct kmem_cache *s,
280 struct page *page, const void *object)
282 void *base;
284 if (!object)
285 return 1;
287 base = page_address(page);
288 if (object < base || object >= base + s->objects * s->size ||
289 (object - base) % s->size) {
290 return 0;
293 return 1;
297 * Slow version of get and set free pointer.
299 * This version requires touching the cache lines of kmem_cache which
300 * we avoid to do in the fast alloc free paths. There we obtain the offset
301 * from the page struct.
303 static inline void *get_freepointer(struct kmem_cache *s, void *object)
305 return *(void **)(object + s->offset);
308 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
310 *(void **)(object + s->offset) = fp;
313 /* Loop over all objects in a slab */
314 #define for_each_object(__p, __s, __addr) \
315 for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
316 __p += (__s)->size)
318 /* Scan freelist */
319 #define for_each_free_object(__p, __s, __free) \
320 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
322 /* Determine object index from a given position */
323 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
325 return (p - addr) / s->size;
328 #ifdef CONFIG_SLUB_DEBUG
330 * Debug settings:
332 #ifdef CONFIG_SLUB_DEBUG_ON
333 static int slub_debug = DEBUG_DEFAULT_FLAGS;
334 #else
335 static int slub_debug;
336 #endif
338 static char *slub_debug_slabs;
341 * Object debugging
343 static void print_section(char *text, u8 *addr, unsigned int length)
345 int i, offset;
346 int newline = 1;
347 char ascii[17];
349 ascii[16] = 0;
351 for (i = 0; i < length; i++) {
352 if (newline) {
353 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
354 newline = 0;
356 printk(" %02x", addr[i]);
357 offset = i % 16;
358 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
359 if (offset == 15) {
360 printk(" %s\n",ascii);
361 newline = 1;
364 if (!newline) {
365 i %= 16;
366 while (i < 16) {
367 printk(" ");
368 ascii[i] = ' ';
369 i++;
371 printk(" %s\n", ascii);
375 static struct track *get_track(struct kmem_cache *s, void *object,
376 enum track_item alloc)
378 struct track *p;
380 if (s->offset)
381 p = object + s->offset + sizeof(void *);
382 else
383 p = object + s->inuse;
385 return p + alloc;
388 static void set_track(struct kmem_cache *s, void *object,
389 enum track_item alloc, void *addr)
391 struct track *p;
393 if (s->offset)
394 p = object + s->offset + sizeof(void *);
395 else
396 p = object + s->inuse;
398 p += alloc;
399 if (addr) {
400 p->addr = addr;
401 p->cpu = smp_processor_id();
402 p->pid = current ? current->pid : -1;
403 p->when = jiffies;
404 } else
405 memset(p, 0, sizeof(struct track));
408 static void init_tracking(struct kmem_cache *s, void *object)
410 if (!(s->flags & SLAB_STORE_USER))
411 return;
413 set_track(s, object, TRACK_FREE, NULL);
414 set_track(s, object, TRACK_ALLOC, NULL);
417 static void print_track(const char *s, struct track *t)
419 if (!t->addr)
420 return;
422 printk(KERN_ERR "INFO: %s in ", s);
423 __print_symbol("%s", (unsigned long)t->addr);
424 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
427 static void print_tracking(struct kmem_cache *s, void *object)
429 if (!(s->flags & SLAB_STORE_USER))
430 return;
432 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
433 print_track("Freed", get_track(s, object, TRACK_FREE));
436 static void print_page_info(struct page *page)
438 printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
439 page, page->inuse, page->freelist, page->flags);
443 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
445 va_list args;
446 char buf[100];
448 va_start(args, fmt);
449 vsnprintf(buf, sizeof(buf), fmt, args);
450 va_end(args);
451 printk(KERN_ERR "========================================"
452 "=====================================\n");
453 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
454 printk(KERN_ERR "----------------------------------------"
455 "-------------------------------------\n\n");
458 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
460 va_list args;
461 char buf[100];
463 va_start(args, fmt);
464 vsnprintf(buf, sizeof(buf), fmt, args);
465 va_end(args);
466 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
469 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
471 unsigned int off; /* Offset of last byte */
472 u8 *addr = page_address(page);
474 print_tracking(s, p);
476 print_page_info(page);
478 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
479 p, p - addr, get_freepointer(s, p));
481 if (p > addr + 16)
482 print_section("Bytes b4", p - 16, 16);
484 print_section("Object", p, min(s->objsize, 128));
486 if (s->flags & SLAB_RED_ZONE)
487 print_section("Redzone", p + s->objsize,
488 s->inuse - s->objsize);
490 if (s->offset)
491 off = s->offset + sizeof(void *);
492 else
493 off = s->inuse;
495 if (s->flags & SLAB_STORE_USER)
496 off += 2 * sizeof(struct track);
498 if (off != s->size)
499 /* Beginning of the filler is the free pointer */
500 print_section("Padding", p + off, s->size - off);
502 dump_stack();
505 static void object_err(struct kmem_cache *s, struct page *page,
506 u8 *object, char *reason)
508 slab_bug(s, reason);
509 print_trailer(s, page, object);
512 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
514 va_list args;
515 char buf[100];
517 va_start(args, fmt);
518 vsnprintf(buf, sizeof(buf), fmt, args);
519 va_end(args);
520 slab_bug(s, fmt);
521 print_page_info(page);
522 dump_stack();
525 static void init_object(struct kmem_cache *s, void *object, int active)
527 u8 *p = object;
529 if (s->flags & __OBJECT_POISON) {
530 memset(p, POISON_FREE, s->objsize - 1);
531 p[s->objsize -1] = POISON_END;
534 if (s->flags & SLAB_RED_ZONE)
535 memset(p + s->objsize,
536 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
537 s->inuse - s->objsize);
540 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
542 while (bytes) {
543 if (*start != (u8)value)
544 return start;
545 start++;
546 bytes--;
548 return NULL;
551 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
552 void *from, void *to)
554 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
555 memset(from, data, to - from);
558 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
559 u8 *object, char *what,
560 u8* start, unsigned int value, unsigned int bytes)
562 u8 *fault;
563 u8 *end;
565 fault = check_bytes(start, value, bytes);
566 if (!fault)
567 return 1;
569 end = start + bytes;
570 while (end > fault && end[-1] == value)
571 end--;
573 slab_bug(s, "%s overwritten", what);
574 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
575 fault, end - 1, fault[0], value);
576 print_trailer(s, page, object);
578 restore_bytes(s, what, value, fault, end);
579 return 0;
583 * Object layout:
585 * object address
586 * Bytes of the object to be managed.
587 * If the freepointer may overlay the object then the free
588 * pointer is the first word of the object.
590 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
591 * 0xa5 (POISON_END)
593 * object + s->objsize
594 * Padding to reach word boundary. This is also used for Redzoning.
595 * Padding is extended by another word if Redzoning is enabled and
596 * objsize == inuse.
598 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
599 * 0xcc (RED_ACTIVE) for objects in use.
601 * object + s->inuse
602 * Meta data starts here.
604 * A. Free pointer (if we cannot overwrite object on free)
605 * B. Tracking data for SLAB_STORE_USER
606 * C. Padding to reach required alignment boundary or at mininum
607 * one word if debuggin is on to be able to detect writes
608 * before the word boundary.
610 * Padding is done using 0x5a (POISON_INUSE)
612 * object + s->size
613 * Nothing is used beyond s->size.
615 * If slabcaches are merged then the objsize and inuse boundaries are mostly
616 * ignored. And therefore no slab options that rely on these boundaries
617 * may be used with merged slabcaches.
620 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
622 unsigned long off = s->inuse; /* The end of info */
624 if (s->offset)
625 /* Freepointer is placed after the object. */
626 off += sizeof(void *);
628 if (s->flags & SLAB_STORE_USER)
629 /* We also have user information there */
630 off += 2 * sizeof(struct track);
632 if (s->size == off)
633 return 1;
635 return check_bytes_and_report(s, page, p, "Object padding",
636 p + off, POISON_INUSE, s->size - off);
639 static int slab_pad_check(struct kmem_cache *s, struct page *page)
641 u8 *start;
642 u8 *fault;
643 u8 *end;
644 int length;
645 int remainder;
647 if (!(s->flags & SLAB_POISON))
648 return 1;
650 start = page_address(page);
651 end = start + (PAGE_SIZE << s->order);
652 length = s->objects * s->size;
653 remainder = end - (start + length);
654 if (!remainder)
655 return 1;
657 fault = check_bytes(start + length, POISON_INUSE, remainder);
658 if (!fault)
659 return 1;
660 while (end > fault && end[-1] == POISON_INUSE)
661 end--;
663 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
664 print_section("Padding", start, length);
666 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
667 return 0;
670 static int check_object(struct kmem_cache *s, struct page *page,
671 void *object, int active)
673 u8 *p = object;
674 u8 *endobject = object + s->objsize;
676 if (s->flags & SLAB_RED_ZONE) {
677 unsigned int red =
678 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
680 if (!check_bytes_and_report(s, page, object, "Redzone",
681 endobject, red, s->inuse - s->objsize))
682 return 0;
683 } else {
684 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
685 check_bytes_and_report(s, page, p, "Alignment padding", endobject,
686 POISON_INUSE, s->inuse - s->objsize);
689 if (s->flags & SLAB_POISON) {
690 if (!active && (s->flags & __OBJECT_POISON) &&
691 (!check_bytes_and_report(s, page, p, "Poison", p,
692 POISON_FREE, s->objsize - 1) ||
693 !check_bytes_and_report(s, page, p, "Poison",
694 p + s->objsize -1, POISON_END, 1)))
695 return 0;
697 * check_pad_bytes cleans up on its own.
699 check_pad_bytes(s, page, p);
702 if (!s->offset && active)
704 * Object and freepointer overlap. Cannot check
705 * freepointer while object is allocated.
707 return 1;
709 /* Check free pointer validity */
710 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
711 object_err(s, page, p, "Freepointer corrupt");
713 * No choice but to zap it and thus loose the remainder
714 * of the free objects in this slab. May cause
715 * another error because the object count is now wrong.
717 set_freepointer(s, p, NULL);
718 return 0;
720 return 1;
723 static int check_slab(struct kmem_cache *s, struct page *page)
725 VM_BUG_ON(!irqs_disabled());
727 if (!PageSlab(page)) {
728 slab_err(s, page, "Not a valid slab page");
729 return 0;
731 if (page->inuse > s->objects) {
732 slab_err(s, page, "inuse %u > max %u",
733 s->name, page->inuse, s->objects);
734 return 0;
736 /* Slab_pad_check fixes things up after itself */
737 slab_pad_check(s, page);
738 return 1;
742 * Determine if a certain object on a page is on the freelist. Must hold the
743 * slab lock to guarantee that the chains are in a consistent state.
745 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
747 int nr = 0;
748 void *fp = page->freelist;
749 void *object = NULL;
751 while (fp && nr <= s->objects) {
752 if (fp == search)
753 return 1;
754 if (!check_valid_pointer(s, page, fp)) {
755 if (object) {
756 object_err(s, page, object,
757 "Freechain corrupt");
758 set_freepointer(s, object, NULL);
759 break;
760 } else {
761 slab_err(s, page, "Freepointer corrupt");
762 page->freelist = NULL;
763 page->inuse = s->objects;
764 slab_fix(s, "Freelist cleared");
765 return 0;
767 break;
769 object = fp;
770 fp = get_freepointer(s, object);
771 nr++;
774 if (page->inuse != s->objects - nr) {
775 slab_err(s, page, "Wrong object count. Counter is %d but "
776 "counted were %d", page->inuse, s->objects - nr);
777 page->inuse = s->objects - nr;
778 slab_fix(s, "Object count adjusted.");
780 return search == NULL;
783 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
785 if (s->flags & SLAB_TRACE) {
786 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
787 s->name,
788 alloc ? "alloc" : "free",
789 object, page->inuse,
790 page->freelist);
792 if (!alloc)
793 print_section("Object", (void *)object, s->objsize);
795 dump_stack();
800 * Tracking of fully allocated slabs for debugging purposes.
802 static void add_full(struct kmem_cache_node *n, struct page *page)
804 spin_lock(&n->list_lock);
805 list_add(&page->lru, &n->full);
806 spin_unlock(&n->list_lock);
809 static void remove_full(struct kmem_cache *s, struct page *page)
811 struct kmem_cache_node *n;
813 if (!(s->flags & SLAB_STORE_USER))
814 return;
816 n = get_node(s, page_to_nid(page));
818 spin_lock(&n->list_lock);
819 list_del(&page->lru);
820 spin_unlock(&n->list_lock);
823 static void setup_object_debug(struct kmem_cache *s, struct page *page,
824 void *object)
826 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
827 return;
829 init_object(s, object, 0);
830 init_tracking(s, object);
833 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
834 void *object, void *addr)
836 if (!check_slab(s, page))
837 goto bad;
839 if (object && !on_freelist(s, page, object)) {
840 object_err(s, page, object, "Object already allocated");
841 goto bad;
844 if (!check_valid_pointer(s, page, object)) {
845 object_err(s, page, object, "Freelist Pointer check fails");
846 goto bad;
849 if (object && !check_object(s, page, object, 0))
850 goto bad;
852 /* Success perform special debug activities for allocs */
853 if (s->flags & SLAB_STORE_USER)
854 set_track(s, object, TRACK_ALLOC, addr);
855 trace(s, page, object, 1);
856 init_object(s, object, 1);
857 return 1;
859 bad:
860 if (PageSlab(page)) {
862 * If this is a slab page then lets do the best we can
863 * to avoid issues in the future. Marking all objects
864 * as used avoids touching the remaining objects.
866 slab_fix(s, "Marking all objects used");
867 page->inuse = s->objects;
868 page->freelist = NULL;
870 return 0;
873 static int free_debug_processing(struct kmem_cache *s, struct page *page,
874 void *object, void *addr)
876 if (!check_slab(s, page))
877 goto fail;
879 if (!check_valid_pointer(s, page, object)) {
880 slab_err(s, page, "Invalid object pointer 0x%p", object);
881 goto fail;
884 if (on_freelist(s, page, object)) {
885 object_err(s, page, object, "Object already free");
886 goto fail;
889 if (!check_object(s, page, object, 1))
890 return 0;
892 if (unlikely(s != page->slab)) {
893 if (!PageSlab(page))
894 slab_err(s, page, "Attempt to free object(0x%p) "
895 "outside of slab", object);
896 else
897 if (!page->slab) {
898 printk(KERN_ERR
899 "SLUB <none>: no slab for object 0x%p.\n",
900 object);
901 dump_stack();
903 else
904 object_err(s, page, object,
905 "page slab pointer corrupt.");
906 goto fail;
909 /* Special debug activities for freeing objects */
910 if (!SlabFrozen(page) && !page->freelist)
911 remove_full(s, page);
912 if (s->flags & SLAB_STORE_USER)
913 set_track(s, object, TRACK_FREE, addr);
914 trace(s, page, object, 0);
915 init_object(s, object, 0);
916 return 1;
918 fail:
919 slab_fix(s, "Object at 0x%p not freed", object);
920 return 0;
923 static int __init setup_slub_debug(char *str)
925 slub_debug = DEBUG_DEFAULT_FLAGS;
926 if (*str++ != '=' || !*str)
928 * No options specified. Switch on full debugging.
930 goto out;
932 if (*str == ',')
934 * No options but restriction on slabs. This means full
935 * debugging for slabs matching a pattern.
937 goto check_slabs;
939 slub_debug = 0;
940 if (*str == '-')
942 * Switch off all debugging measures.
944 goto out;
947 * Determine which debug features should be switched on
949 for ( ;*str && *str != ','; str++) {
950 switch (tolower(*str)) {
951 case 'f':
952 slub_debug |= SLAB_DEBUG_FREE;
953 break;
954 case 'z':
955 slub_debug |= SLAB_RED_ZONE;
956 break;
957 case 'p':
958 slub_debug |= SLAB_POISON;
959 break;
960 case 'u':
961 slub_debug |= SLAB_STORE_USER;
962 break;
963 case 't':
964 slub_debug |= SLAB_TRACE;
965 break;
966 default:
967 printk(KERN_ERR "slub_debug option '%c' "
968 "unknown. skipped\n",*str);
972 check_slabs:
973 if (*str == ',')
974 slub_debug_slabs = str + 1;
975 out:
976 return 1;
979 __setup("slub_debug", setup_slub_debug);
981 static unsigned long kmem_cache_flags(unsigned long objsize,
982 unsigned long flags, const char *name,
983 void (*ctor)(struct kmem_cache *, void *))
986 * The page->offset field is only 16 bit wide. This is an offset
987 * in units of words from the beginning of an object. If the slab
988 * size is bigger then we cannot move the free pointer behind the
989 * object anymore.
991 * On 32 bit platforms the limit is 256k. On 64bit platforms
992 * the limit is 512k.
994 * Debugging or ctor may create a need to move the free
995 * pointer. Fail if this happens.
997 if (objsize >= 65535 * sizeof(void *)) {
998 BUG_ON(flags & (SLAB_RED_ZONE | SLAB_POISON |
999 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
1000 BUG_ON(ctor);
1001 } else {
1003 * Enable debugging if selected on the kernel commandline.
1005 if (slub_debug && (!slub_debug_slabs ||
1006 strncmp(slub_debug_slabs, name,
1007 strlen(slub_debug_slabs)) == 0))
1008 flags |= slub_debug;
1011 return flags;
1013 #else
1014 static inline void setup_object_debug(struct kmem_cache *s,
1015 struct page *page, void *object) {}
1017 static inline int alloc_debug_processing(struct kmem_cache *s,
1018 struct page *page, void *object, void *addr) { return 0; }
1020 static inline int free_debug_processing(struct kmem_cache *s,
1021 struct page *page, void *object, void *addr) { return 0; }
1023 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1024 { return 1; }
1025 static inline int check_object(struct kmem_cache *s, struct page *page,
1026 void *object, int active) { return 1; }
1027 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1028 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1029 unsigned long flags, const char *name,
1030 void (*ctor)(struct kmem_cache *, void *))
1032 return flags;
1034 #define slub_debug 0
1035 #endif
1037 * Slab allocation and freeing
1039 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1041 struct page * page;
1042 int pages = 1 << s->order;
1044 if (s->order)
1045 flags |= __GFP_COMP;
1047 if (s->flags & SLAB_CACHE_DMA)
1048 flags |= SLUB_DMA;
1050 if (s->flags & SLAB_RECLAIM_ACCOUNT)
1051 flags |= __GFP_RECLAIMABLE;
1053 if (node == -1)
1054 page = alloc_pages(flags, s->order);
1055 else
1056 page = alloc_pages_node(node, flags, s->order);
1058 if (!page)
1059 return NULL;
1061 mod_zone_page_state(page_zone(page),
1062 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1063 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1064 pages);
1066 return page;
1069 static void setup_object(struct kmem_cache *s, struct page *page,
1070 void *object)
1072 setup_object_debug(s, page, object);
1073 if (unlikely(s->ctor))
1074 s->ctor(s, object);
1077 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1079 struct page *page;
1080 struct kmem_cache_node *n;
1081 void *start;
1082 void *end;
1083 void *last;
1084 void *p;
1086 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1088 page = allocate_slab(s,
1089 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1090 if (!page)
1091 goto out;
1093 n = get_node(s, page_to_nid(page));
1094 if (n)
1095 atomic_long_inc(&n->nr_slabs);
1096 page->slab = s;
1097 page->flags |= 1 << PG_slab;
1098 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1099 SLAB_STORE_USER | SLAB_TRACE))
1100 SetSlabDebug(page);
1102 start = page_address(page);
1103 end = start + s->objects * s->size;
1105 if (unlikely(s->flags & SLAB_POISON))
1106 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1108 last = start;
1109 for_each_object(p, s, start) {
1110 setup_object(s, page, last);
1111 set_freepointer(s, last, p);
1112 last = p;
1114 setup_object(s, page, last);
1115 set_freepointer(s, last, NULL);
1117 page->freelist = start;
1118 page->inuse = 0;
1119 out:
1120 return page;
1123 static void __free_slab(struct kmem_cache *s, struct page *page)
1125 int pages = 1 << s->order;
1127 if (unlikely(SlabDebug(page))) {
1128 void *p;
1130 slab_pad_check(s, page);
1131 for_each_object(p, s, page_address(page))
1132 check_object(s, page, p, 0);
1133 ClearSlabDebug(page);
1136 mod_zone_page_state(page_zone(page),
1137 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1138 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1139 - pages);
1141 __free_pages(page, s->order);
1144 static void rcu_free_slab(struct rcu_head *h)
1146 struct page *page;
1148 page = container_of((struct list_head *)h, struct page, lru);
1149 __free_slab(page->slab, page);
1152 static void free_slab(struct kmem_cache *s, struct page *page)
1154 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1156 * RCU free overloads the RCU head over the LRU
1158 struct rcu_head *head = (void *)&page->lru;
1160 call_rcu(head, rcu_free_slab);
1161 } else
1162 __free_slab(s, page);
1165 static void discard_slab(struct kmem_cache *s, struct page *page)
1167 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1169 atomic_long_dec(&n->nr_slabs);
1170 reset_page_mapcount(page);
1171 __ClearPageSlab(page);
1172 free_slab(s, page);
1176 * Per slab locking using the pagelock
1178 static __always_inline void slab_lock(struct page *page)
1180 bit_spin_lock(PG_locked, &page->flags);
1183 static __always_inline void slab_unlock(struct page *page)
1185 bit_spin_unlock(PG_locked, &page->flags);
1188 static __always_inline int slab_trylock(struct page *page)
1190 int rc = 1;
1192 rc = bit_spin_trylock(PG_locked, &page->flags);
1193 return rc;
1197 * Management of partially allocated slabs
1199 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1201 spin_lock(&n->list_lock);
1202 n->nr_partial++;
1203 list_add_tail(&page->lru, &n->partial);
1204 spin_unlock(&n->list_lock);
1207 static void add_partial(struct kmem_cache_node *n, struct page *page)
1209 spin_lock(&n->list_lock);
1210 n->nr_partial++;
1211 list_add(&page->lru, &n->partial);
1212 spin_unlock(&n->list_lock);
1215 static void remove_partial(struct kmem_cache *s,
1216 struct page *page)
1218 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1220 spin_lock(&n->list_lock);
1221 list_del(&page->lru);
1222 n->nr_partial--;
1223 spin_unlock(&n->list_lock);
1227 * Lock slab and remove from the partial list.
1229 * Must hold list_lock.
1231 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1233 if (slab_trylock(page)) {
1234 list_del(&page->lru);
1235 n->nr_partial--;
1236 SetSlabFrozen(page);
1237 return 1;
1239 return 0;
1243 * Try to allocate a partial slab from a specific node.
1245 static struct page *get_partial_node(struct kmem_cache_node *n)
1247 struct page *page;
1250 * Racy check. If we mistakenly see no partial slabs then we
1251 * just allocate an empty slab. If we mistakenly try to get a
1252 * partial slab and there is none available then get_partials()
1253 * will return NULL.
1255 if (!n || !n->nr_partial)
1256 return NULL;
1258 spin_lock(&n->list_lock);
1259 list_for_each_entry(page, &n->partial, lru)
1260 if (lock_and_freeze_slab(n, page))
1261 goto out;
1262 page = NULL;
1263 out:
1264 spin_unlock(&n->list_lock);
1265 return page;
1269 * Get a page from somewhere. Search in increasing NUMA distances.
1271 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1273 #ifdef CONFIG_NUMA
1274 struct zonelist *zonelist;
1275 struct zone **z;
1276 struct page *page;
1279 * The defrag ratio allows a configuration of the tradeoffs between
1280 * inter node defragmentation and node local allocations. A lower
1281 * defrag_ratio increases the tendency to do local allocations
1282 * instead of attempting to obtain partial slabs from other nodes.
1284 * If the defrag_ratio is set to 0 then kmalloc() always
1285 * returns node local objects. If the ratio is higher then kmalloc()
1286 * may return off node objects because partial slabs are obtained
1287 * from other nodes and filled up.
1289 * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1290 * defrag_ratio = 1000) then every (well almost) allocation will
1291 * first attempt to defrag slab caches on other nodes. This means
1292 * scanning over all nodes to look for partial slabs which may be
1293 * expensive if we do it every time we are trying to find a slab
1294 * with available objects.
1296 if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1297 return NULL;
1299 zonelist = &NODE_DATA(slab_node(current->mempolicy))
1300 ->node_zonelists[gfp_zone(flags)];
1301 for (z = zonelist->zones; *z; z++) {
1302 struct kmem_cache_node *n;
1304 n = get_node(s, zone_to_nid(*z));
1306 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1307 n->nr_partial > MIN_PARTIAL) {
1308 page = get_partial_node(n);
1309 if (page)
1310 return page;
1313 #endif
1314 return NULL;
1318 * Get a partial page, lock it and return it.
1320 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1322 struct page *page;
1323 int searchnode = (node == -1) ? numa_node_id() : node;
1325 page = get_partial_node(get_node(s, searchnode));
1326 if (page || (flags & __GFP_THISNODE))
1327 return page;
1329 return get_any_partial(s, flags);
1333 * Move a page back to the lists.
1335 * Must be called with the slab lock held.
1337 * On exit the slab lock will have been dropped.
1339 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1341 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1343 ClearSlabFrozen(page);
1344 if (page->inuse) {
1346 if (page->freelist)
1347 add_partial(n, page);
1348 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1349 add_full(n, page);
1350 slab_unlock(page);
1352 } else {
1353 if (n->nr_partial < MIN_PARTIAL) {
1355 * Adding an empty slab to the partial slabs in order
1356 * to avoid page allocator overhead. This slab needs
1357 * to come after the other slabs with objects in
1358 * order to fill them up. That way the size of the
1359 * partial list stays small. kmem_cache_shrink can
1360 * reclaim empty slabs from the partial list.
1362 add_partial_tail(n, page);
1363 slab_unlock(page);
1364 } else {
1365 slab_unlock(page);
1366 discard_slab(s, page);
1372 * Remove the cpu slab
1374 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1376 struct page *page = c->page;
1378 * Merge cpu freelist into freelist. Typically we get here
1379 * because both freelists are empty. So this is unlikely
1380 * to occur.
1382 while (unlikely(c->freelist)) {
1383 void **object;
1385 /* Retrieve object from cpu_freelist */
1386 object = c->freelist;
1387 c->freelist = c->freelist[c->offset];
1389 /* And put onto the regular freelist */
1390 object[c->offset] = page->freelist;
1391 page->freelist = object;
1392 page->inuse--;
1394 c->page = NULL;
1395 unfreeze_slab(s, page);
1398 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1400 slab_lock(c->page);
1401 deactivate_slab(s, c);
1405 * Flush cpu slab.
1406 * Called from IPI handler with interrupts disabled.
1408 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1410 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1412 if (likely(c && c->page))
1413 flush_slab(s, c);
1416 static void flush_cpu_slab(void *d)
1418 struct kmem_cache *s = d;
1420 __flush_cpu_slab(s, smp_processor_id());
1423 static void flush_all(struct kmem_cache *s)
1425 #ifdef CONFIG_SMP
1426 on_each_cpu(flush_cpu_slab, s, 1, 1);
1427 #else
1428 unsigned long flags;
1430 local_irq_save(flags);
1431 flush_cpu_slab(s);
1432 local_irq_restore(flags);
1433 #endif
1437 * Check if the objects in a per cpu structure fit numa
1438 * locality expectations.
1440 static inline int node_match(struct kmem_cache_cpu *c, int node)
1442 #ifdef CONFIG_NUMA
1443 if (node != -1 && c->node != node)
1444 return 0;
1445 #endif
1446 return 1;
1450 * Slow path. The lockless freelist is empty or we need to perform
1451 * debugging duties.
1453 * Interrupts are disabled.
1455 * Processing is still very fast if new objects have been freed to the
1456 * regular freelist. In that case we simply take over the regular freelist
1457 * as the lockless freelist and zap the regular freelist.
1459 * If that is not working then we fall back to the partial lists. We take the
1460 * first element of the freelist as the object to allocate now and move the
1461 * rest of the freelist to the lockless freelist.
1463 * And if we were unable to get a new slab from the partial slab lists then
1464 * we need to allocate a new slab. This is slowest path since we may sleep.
1466 static void *__slab_alloc(struct kmem_cache *s,
1467 gfp_t gfpflags, int node, void *addr, struct kmem_cache_cpu *c)
1469 void **object;
1470 struct page *new;
1472 if (!c->page)
1473 goto new_slab;
1475 slab_lock(c->page);
1476 if (unlikely(!node_match(c, node)))
1477 goto another_slab;
1478 load_freelist:
1479 object = c->page->freelist;
1480 if (unlikely(!object))
1481 goto another_slab;
1482 if (unlikely(SlabDebug(c->page)))
1483 goto debug;
1485 object = c->page->freelist;
1486 c->freelist = object[c->offset];
1487 c->page->inuse = s->objects;
1488 c->page->freelist = NULL;
1489 c->node = page_to_nid(c->page);
1490 slab_unlock(c->page);
1491 return object;
1493 another_slab:
1494 deactivate_slab(s, c);
1496 new_slab:
1497 new = get_partial(s, gfpflags, node);
1498 if (new) {
1499 c->page = new;
1500 goto load_freelist;
1503 if (gfpflags & __GFP_WAIT)
1504 local_irq_enable();
1506 new = new_slab(s, gfpflags, node);
1508 if (gfpflags & __GFP_WAIT)
1509 local_irq_disable();
1511 if (new) {
1512 c = get_cpu_slab(s, smp_processor_id());
1513 if (c->page) {
1515 * Someone else populated the cpu_slab while we
1516 * enabled interrupts, or we have gotten scheduled
1517 * on another cpu. The page may not be on the
1518 * requested node even if __GFP_THISNODE was
1519 * specified. So we need to recheck.
1521 if (node_match(c, node)) {
1523 * Current cpuslab is acceptable and we
1524 * want the current one since its cache hot
1526 discard_slab(s, new);
1527 slab_lock(c->page);
1528 goto load_freelist;
1530 /* New slab does not fit our expectations */
1531 flush_slab(s, c);
1533 slab_lock(new);
1534 SetSlabFrozen(new);
1535 c->page = new;
1536 goto load_freelist;
1538 return NULL;
1539 debug:
1540 object = c->page->freelist;
1541 if (!alloc_debug_processing(s, c->page, object, addr))
1542 goto another_slab;
1544 c->page->inuse++;
1545 c->page->freelist = object[c->offset];
1546 c->node = -1;
1547 slab_unlock(c->page);
1548 return object;
1552 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1553 * have the fastpath folded into their functions. So no function call
1554 * overhead for requests that can be satisfied on the fastpath.
1556 * The fastpath works by first checking if the lockless freelist can be used.
1557 * If not then __slab_alloc is called for slow processing.
1559 * Otherwise we can simply pick the next object from the lockless free list.
1561 static void __always_inline *slab_alloc(struct kmem_cache *s,
1562 gfp_t gfpflags, int node, void *addr)
1564 void **object;
1565 unsigned long flags;
1566 struct kmem_cache_cpu *c;
1568 local_irq_save(flags);
1569 c = get_cpu_slab(s, smp_processor_id());
1570 if (unlikely(!c->freelist || !node_match(c, node)))
1572 object = __slab_alloc(s, gfpflags, node, addr, c);
1574 else {
1575 object = c->freelist;
1576 c->freelist = object[c->offset];
1578 local_irq_restore(flags);
1580 if (unlikely((gfpflags & __GFP_ZERO) && object))
1581 memset(object, 0, c->objsize);
1583 return object;
1586 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1588 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1590 EXPORT_SYMBOL(kmem_cache_alloc);
1592 #ifdef CONFIG_NUMA
1593 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1595 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1597 EXPORT_SYMBOL(kmem_cache_alloc_node);
1598 #endif
1601 * Slow patch handling. This may still be called frequently since objects
1602 * have a longer lifetime than the cpu slabs in most processing loads.
1604 * So we still attempt to reduce cache line usage. Just take the slab
1605 * lock and free the item. If there is no additional partial page
1606 * handling required then we can return immediately.
1608 static void __slab_free(struct kmem_cache *s, struct page *page,
1609 void *x, void *addr, unsigned int offset)
1611 void *prior;
1612 void **object = (void *)x;
1614 slab_lock(page);
1616 if (unlikely(SlabDebug(page)))
1617 goto debug;
1618 checks_ok:
1619 prior = object[offset] = page->freelist;
1620 page->freelist = object;
1621 page->inuse--;
1623 if (unlikely(SlabFrozen(page)))
1624 goto out_unlock;
1626 if (unlikely(!page->inuse))
1627 goto slab_empty;
1630 * Objects left in the slab. If it
1631 * was not on the partial list before
1632 * then add it.
1634 if (unlikely(!prior))
1635 add_partial(get_node(s, page_to_nid(page)), page);
1637 out_unlock:
1638 slab_unlock(page);
1639 return;
1641 slab_empty:
1642 if (prior)
1644 * Slab still on the partial list.
1646 remove_partial(s, page);
1648 slab_unlock(page);
1649 discard_slab(s, page);
1650 return;
1652 debug:
1653 if (!free_debug_processing(s, page, x, addr))
1654 goto out_unlock;
1655 goto checks_ok;
1659 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1660 * can perform fastpath freeing without additional function calls.
1662 * The fastpath is only possible if we are freeing to the current cpu slab
1663 * of this processor. This typically the case if we have just allocated
1664 * the item before.
1666 * If fastpath is not possible then fall back to __slab_free where we deal
1667 * with all sorts of special processing.
1669 static void __always_inline slab_free(struct kmem_cache *s,
1670 struct page *page, void *x, void *addr)
1672 void **object = (void *)x;
1673 unsigned long flags;
1674 struct kmem_cache_cpu *c;
1676 local_irq_save(flags);
1677 debug_check_no_locks_freed(object, s->objsize);
1678 c = get_cpu_slab(s, smp_processor_id());
1679 if (likely(page == c->page && c->node >= 0)) {
1680 object[c->offset] = c->freelist;
1681 c->freelist = object;
1682 } else
1683 __slab_free(s, page, x, addr, c->offset);
1685 local_irq_restore(flags);
1688 void kmem_cache_free(struct kmem_cache *s, void *x)
1690 struct page *page;
1692 page = virt_to_head_page(x);
1694 slab_free(s, page, x, __builtin_return_address(0));
1696 EXPORT_SYMBOL(kmem_cache_free);
1698 /* Figure out on which slab object the object resides */
1699 static struct page *get_object_page(const void *x)
1701 struct page *page = virt_to_head_page(x);
1703 if (!PageSlab(page))
1704 return NULL;
1706 return page;
1710 * Object placement in a slab is made very easy because we always start at
1711 * offset 0. If we tune the size of the object to the alignment then we can
1712 * get the required alignment by putting one properly sized object after
1713 * another.
1715 * Notice that the allocation order determines the sizes of the per cpu
1716 * caches. Each processor has always one slab available for allocations.
1717 * Increasing the allocation order reduces the number of times that slabs
1718 * must be moved on and off the partial lists and is therefore a factor in
1719 * locking overhead.
1723 * Mininum / Maximum order of slab pages. This influences locking overhead
1724 * and slab fragmentation. A higher order reduces the number of partial slabs
1725 * and increases the number of allocations possible without having to
1726 * take the list_lock.
1728 static int slub_min_order;
1729 static int slub_max_order = DEFAULT_MAX_ORDER;
1730 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1733 * Merge control. If this is set then no merging of slab caches will occur.
1734 * (Could be removed. This was introduced to pacify the merge skeptics.)
1736 static int slub_nomerge;
1739 * Calculate the order of allocation given an slab object size.
1741 * The order of allocation has significant impact on performance and other
1742 * system components. Generally order 0 allocations should be preferred since
1743 * order 0 does not cause fragmentation in the page allocator. Larger objects
1744 * be problematic to put into order 0 slabs because there may be too much
1745 * unused space left. We go to a higher order if more than 1/8th of the slab
1746 * would be wasted.
1748 * In order to reach satisfactory performance we must ensure that a minimum
1749 * number of objects is in one slab. Otherwise we may generate too much
1750 * activity on the partial lists which requires taking the list_lock. This is
1751 * less a concern for large slabs though which are rarely used.
1753 * slub_max_order specifies the order where we begin to stop considering the
1754 * number of objects in a slab as critical. If we reach slub_max_order then
1755 * we try to keep the page order as low as possible. So we accept more waste
1756 * of space in favor of a small page order.
1758 * Higher order allocations also allow the placement of more objects in a
1759 * slab and thereby reduce object handling overhead. If the user has
1760 * requested a higher mininum order then we start with that one instead of
1761 * the smallest order which will fit the object.
1763 static inline int slab_order(int size, int min_objects,
1764 int max_order, int fract_leftover)
1766 int order;
1767 int rem;
1768 int min_order = slub_min_order;
1770 for (order = max(min_order,
1771 fls(min_objects * size - 1) - PAGE_SHIFT);
1772 order <= max_order; order++) {
1774 unsigned long slab_size = PAGE_SIZE << order;
1776 if (slab_size < min_objects * size)
1777 continue;
1779 rem = slab_size % size;
1781 if (rem <= slab_size / fract_leftover)
1782 break;
1786 return order;
1789 static inline int calculate_order(int size)
1791 int order;
1792 int min_objects;
1793 int fraction;
1796 * Attempt to find best configuration for a slab. This
1797 * works by first attempting to generate a layout with
1798 * the best configuration and backing off gradually.
1800 * First we reduce the acceptable waste in a slab. Then
1801 * we reduce the minimum objects required in a slab.
1803 min_objects = slub_min_objects;
1804 while (min_objects > 1) {
1805 fraction = 8;
1806 while (fraction >= 4) {
1807 order = slab_order(size, min_objects,
1808 slub_max_order, fraction);
1809 if (order <= slub_max_order)
1810 return order;
1811 fraction /= 2;
1813 min_objects /= 2;
1817 * We were unable to place multiple objects in a slab. Now
1818 * lets see if we can place a single object there.
1820 order = slab_order(size, 1, slub_max_order, 1);
1821 if (order <= slub_max_order)
1822 return order;
1825 * Doh this slab cannot be placed using slub_max_order.
1827 order = slab_order(size, 1, MAX_ORDER, 1);
1828 if (order <= MAX_ORDER)
1829 return order;
1830 return -ENOSYS;
1834 * Figure out what the alignment of the objects will be.
1836 static unsigned long calculate_alignment(unsigned long flags,
1837 unsigned long align, unsigned long size)
1840 * If the user wants hardware cache aligned objects then
1841 * follow that suggestion if the object is sufficiently
1842 * large.
1844 * The hardware cache alignment cannot override the
1845 * specified alignment though. If that is greater
1846 * then use it.
1848 if ((flags & SLAB_HWCACHE_ALIGN) &&
1849 size > cache_line_size() / 2)
1850 return max_t(unsigned long, align, cache_line_size());
1852 if (align < ARCH_SLAB_MINALIGN)
1853 return ARCH_SLAB_MINALIGN;
1855 return ALIGN(align, sizeof(void *));
1858 static void init_kmem_cache_cpu(struct kmem_cache *s,
1859 struct kmem_cache_cpu *c)
1861 c->page = NULL;
1862 c->freelist = NULL;
1863 c->node = 0;
1864 c->offset = s->offset / sizeof(void *);
1865 c->objsize = s->objsize;
1868 static void init_kmem_cache_node(struct kmem_cache_node *n)
1870 n->nr_partial = 0;
1871 atomic_long_set(&n->nr_slabs, 0);
1872 spin_lock_init(&n->list_lock);
1873 INIT_LIST_HEAD(&n->partial);
1874 #ifdef CONFIG_SLUB_DEBUG
1875 INIT_LIST_HEAD(&n->full);
1876 #endif
1879 #ifdef CONFIG_SMP
1881 * Per cpu array for per cpu structures.
1883 * The per cpu array places all kmem_cache_cpu structures from one processor
1884 * close together meaning that it becomes possible that multiple per cpu
1885 * structures are contained in one cacheline. This may be particularly
1886 * beneficial for the kmalloc caches.
1888 * A desktop system typically has around 60-80 slabs. With 100 here we are
1889 * likely able to get per cpu structures for all caches from the array defined
1890 * here. We must be able to cover all kmalloc caches during bootstrap.
1892 * If the per cpu array is exhausted then fall back to kmalloc
1893 * of individual cachelines. No sharing is possible then.
1895 #define NR_KMEM_CACHE_CPU 100
1897 static DEFINE_PER_CPU(struct kmem_cache_cpu,
1898 kmem_cache_cpu)[NR_KMEM_CACHE_CPU];
1900 static DEFINE_PER_CPU(struct kmem_cache_cpu *, kmem_cache_cpu_free);
1901 static cpumask_t kmem_cach_cpu_free_init_once = CPU_MASK_NONE;
1903 static struct kmem_cache_cpu *alloc_kmem_cache_cpu(struct kmem_cache *s,
1904 int cpu, gfp_t flags)
1906 struct kmem_cache_cpu *c = per_cpu(kmem_cache_cpu_free, cpu);
1908 if (c)
1909 per_cpu(kmem_cache_cpu_free, cpu) =
1910 (void *)c->freelist;
1911 else {
1912 /* Table overflow: So allocate ourselves */
1913 c = kmalloc_node(
1914 ALIGN(sizeof(struct kmem_cache_cpu), cache_line_size()),
1915 flags, cpu_to_node(cpu));
1916 if (!c)
1917 return NULL;
1920 init_kmem_cache_cpu(s, c);
1921 return c;
1924 static void free_kmem_cache_cpu(struct kmem_cache_cpu *c, int cpu)
1926 if (c < per_cpu(kmem_cache_cpu, cpu) ||
1927 c > per_cpu(kmem_cache_cpu, cpu) + NR_KMEM_CACHE_CPU) {
1928 kfree(c);
1929 return;
1931 c->freelist = (void *)per_cpu(kmem_cache_cpu_free, cpu);
1932 per_cpu(kmem_cache_cpu_free, cpu) = c;
1935 static void free_kmem_cache_cpus(struct kmem_cache *s)
1937 int cpu;
1939 for_each_online_cpu(cpu) {
1940 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1942 if (c) {
1943 s->cpu_slab[cpu] = NULL;
1944 free_kmem_cache_cpu(c, cpu);
1949 static int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
1951 int cpu;
1953 for_each_online_cpu(cpu) {
1954 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1956 if (c)
1957 continue;
1959 c = alloc_kmem_cache_cpu(s, cpu, flags);
1960 if (!c) {
1961 free_kmem_cache_cpus(s);
1962 return 0;
1964 s->cpu_slab[cpu] = c;
1966 return 1;
1970 * Initialize the per cpu array.
1972 static void init_alloc_cpu_cpu(int cpu)
1974 int i;
1976 if (cpu_isset(cpu, kmem_cach_cpu_free_init_once))
1977 return;
1979 for (i = NR_KMEM_CACHE_CPU - 1; i >= 0; i--)
1980 free_kmem_cache_cpu(&per_cpu(kmem_cache_cpu, cpu)[i], cpu);
1982 cpu_set(cpu, kmem_cach_cpu_free_init_once);
1985 static void __init init_alloc_cpu(void)
1987 int cpu;
1989 for_each_online_cpu(cpu)
1990 init_alloc_cpu_cpu(cpu);
1993 #else
1994 static inline void free_kmem_cache_cpus(struct kmem_cache *s) {}
1995 static inline void init_alloc_cpu(void) {}
1997 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
1999 init_kmem_cache_cpu(s, &s->cpu_slab);
2000 return 1;
2002 #endif
2004 #ifdef CONFIG_NUMA
2006 * No kmalloc_node yet so do it by hand. We know that this is the first
2007 * slab on the node for this slabcache. There are no concurrent accesses
2008 * possible.
2010 * Note that this function only works on the kmalloc_node_cache
2011 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2012 * memory on a fresh node that has no slab structures yet.
2014 static struct kmem_cache_node *early_kmem_cache_node_alloc(gfp_t gfpflags,
2015 int node)
2017 struct page *page;
2018 struct kmem_cache_node *n;
2020 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
2022 page = new_slab(kmalloc_caches, gfpflags, node);
2024 BUG_ON(!page);
2025 if (page_to_nid(page) != node) {
2026 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2027 "node %d\n", node);
2028 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2029 "in order to be able to continue\n");
2032 n = page->freelist;
2033 BUG_ON(!n);
2034 page->freelist = get_freepointer(kmalloc_caches, n);
2035 page->inuse++;
2036 kmalloc_caches->node[node] = n;
2037 #ifdef CONFIG_SLUB_DEBUG
2038 init_object(kmalloc_caches, n, 1);
2039 init_tracking(kmalloc_caches, n);
2040 #endif
2041 init_kmem_cache_node(n);
2042 atomic_long_inc(&n->nr_slabs);
2043 add_partial(n, page);
2044 return n;
2047 static void free_kmem_cache_nodes(struct kmem_cache *s)
2049 int node;
2051 for_each_node_state(node, N_NORMAL_MEMORY) {
2052 struct kmem_cache_node *n = s->node[node];
2053 if (n && n != &s->local_node)
2054 kmem_cache_free(kmalloc_caches, n);
2055 s->node[node] = NULL;
2059 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2061 int node;
2062 int local_node;
2064 if (slab_state >= UP)
2065 local_node = page_to_nid(virt_to_page(s));
2066 else
2067 local_node = 0;
2069 for_each_node_state(node, N_NORMAL_MEMORY) {
2070 struct kmem_cache_node *n;
2072 if (local_node == node)
2073 n = &s->local_node;
2074 else {
2075 if (slab_state == DOWN) {
2076 n = early_kmem_cache_node_alloc(gfpflags,
2077 node);
2078 continue;
2080 n = kmem_cache_alloc_node(kmalloc_caches,
2081 gfpflags, node);
2083 if (!n) {
2084 free_kmem_cache_nodes(s);
2085 return 0;
2089 s->node[node] = n;
2090 init_kmem_cache_node(n);
2092 return 1;
2094 #else
2095 static void free_kmem_cache_nodes(struct kmem_cache *s)
2099 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2101 init_kmem_cache_node(&s->local_node);
2102 return 1;
2104 #endif
2107 * calculate_sizes() determines the order and the distribution of data within
2108 * a slab object.
2110 static int calculate_sizes(struct kmem_cache *s)
2112 unsigned long flags = s->flags;
2113 unsigned long size = s->objsize;
2114 unsigned long align = s->align;
2117 * Determine if we can poison the object itself. If the user of
2118 * the slab may touch the object after free or before allocation
2119 * then we should never poison the object itself.
2121 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2122 !s->ctor)
2123 s->flags |= __OBJECT_POISON;
2124 else
2125 s->flags &= ~__OBJECT_POISON;
2128 * Round up object size to the next word boundary. We can only
2129 * place the free pointer at word boundaries and this determines
2130 * the possible location of the free pointer.
2132 size = ALIGN(size, sizeof(void *));
2134 #ifdef CONFIG_SLUB_DEBUG
2136 * If we are Redzoning then check if there is some space between the
2137 * end of the object and the free pointer. If not then add an
2138 * additional word to have some bytes to store Redzone information.
2140 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2141 size += sizeof(void *);
2142 #endif
2145 * With that we have determined the number of bytes in actual use
2146 * by the object. This is the potential offset to the free pointer.
2148 s->inuse = size;
2150 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2151 s->ctor)) {
2153 * Relocate free pointer after the object if it is not
2154 * permitted to overwrite the first word of the object on
2155 * kmem_cache_free.
2157 * This is the case if we do RCU, have a constructor or
2158 * destructor or are poisoning the objects.
2160 s->offset = size;
2161 size += sizeof(void *);
2164 #ifdef CONFIG_SLUB_DEBUG
2165 if (flags & SLAB_STORE_USER)
2167 * Need to store information about allocs and frees after
2168 * the object.
2170 size += 2 * sizeof(struct track);
2172 if (flags & SLAB_RED_ZONE)
2174 * Add some empty padding so that we can catch
2175 * overwrites from earlier objects rather than let
2176 * tracking information or the free pointer be
2177 * corrupted if an user writes before the start
2178 * of the object.
2180 size += sizeof(void *);
2181 #endif
2184 * Determine the alignment based on various parameters that the
2185 * user specified and the dynamic determination of cache line size
2186 * on bootup.
2188 align = calculate_alignment(flags, align, s->objsize);
2191 * SLUB stores one object immediately after another beginning from
2192 * offset 0. In order to align the objects we have to simply size
2193 * each object to conform to the alignment.
2195 size = ALIGN(size, align);
2196 s->size = size;
2198 s->order = calculate_order(size);
2199 if (s->order < 0)
2200 return 0;
2203 * Determine the number of objects per slab
2205 s->objects = (PAGE_SIZE << s->order) / size;
2207 return !!s->objects;
2211 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2212 const char *name, size_t size,
2213 size_t align, unsigned long flags,
2214 void (*ctor)(struct kmem_cache *, void *))
2216 memset(s, 0, kmem_size);
2217 s->name = name;
2218 s->ctor = ctor;
2219 s->objsize = size;
2220 s->align = align;
2221 s->flags = kmem_cache_flags(size, flags, name, ctor);
2223 if (!calculate_sizes(s))
2224 goto error;
2226 s->refcount = 1;
2227 #ifdef CONFIG_NUMA
2228 s->defrag_ratio = 100;
2229 #endif
2230 if (!init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2231 goto error;
2233 if (alloc_kmem_cache_cpus(s, gfpflags & ~SLUB_DMA))
2234 return 1;
2235 free_kmem_cache_nodes(s);
2236 error:
2237 if (flags & SLAB_PANIC)
2238 panic("Cannot create slab %s size=%lu realsize=%u "
2239 "order=%u offset=%u flags=%lx\n",
2240 s->name, (unsigned long)size, s->size, s->order,
2241 s->offset, flags);
2242 return 0;
2246 * Check if a given pointer is valid
2248 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2250 struct page * page;
2252 page = get_object_page(object);
2254 if (!page || s != page->slab)
2255 /* No slab or wrong slab */
2256 return 0;
2258 if (!check_valid_pointer(s, page, object))
2259 return 0;
2262 * We could also check if the object is on the slabs freelist.
2263 * But this would be too expensive and it seems that the main
2264 * purpose of kmem_ptr_valid is to check if the object belongs
2265 * to a certain slab.
2267 return 1;
2269 EXPORT_SYMBOL(kmem_ptr_validate);
2272 * Determine the size of a slab object
2274 unsigned int kmem_cache_size(struct kmem_cache *s)
2276 return s->objsize;
2278 EXPORT_SYMBOL(kmem_cache_size);
2280 const char *kmem_cache_name(struct kmem_cache *s)
2282 return s->name;
2284 EXPORT_SYMBOL(kmem_cache_name);
2287 * Attempt to free all slabs on a node. Return the number of slabs we
2288 * were unable to free.
2290 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2291 struct list_head *list)
2293 int slabs_inuse = 0;
2294 unsigned long flags;
2295 struct page *page, *h;
2297 spin_lock_irqsave(&n->list_lock, flags);
2298 list_for_each_entry_safe(page, h, list, lru)
2299 if (!page->inuse) {
2300 list_del(&page->lru);
2301 discard_slab(s, page);
2302 } else
2303 slabs_inuse++;
2304 spin_unlock_irqrestore(&n->list_lock, flags);
2305 return slabs_inuse;
2309 * Release all resources used by a slab cache.
2311 static inline int kmem_cache_close(struct kmem_cache *s)
2313 int node;
2315 flush_all(s);
2317 /* Attempt to free all objects */
2318 free_kmem_cache_cpus(s);
2319 for_each_node_state(node, N_NORMAL_MEMORY) {
2320 struct kmem_cache_node *n = get_node(s, node);
2322 n->nr_partial -= free_list(s, n, &n->partial);
2323 if (atomic_long_read(&n->nr_slabs))
2324 return 1;
2326 free_kmem_cache_nodes(s);
2327 return 0;
2331 * Close a cache and release the kmem_cache structure
2332 * (must be used for caches created using kmem_cache_create)
2334 void kmem_cache_destroy(struct kmem_cache *s)
2336 down_write(&slub_lock);
2337 s->refcount--;
2338 if (!s->refcount) {
2339 list_del(&s->list);
2340 up_write(&slub_lock);
2341 if (kmem_cache_close(s))
2342 WARN_ON(1);
2343 sysfs_slab_remove(s);
2344 kfree(s);
2345 } else
2346 up_write(&slub_lock);
2348 EXPORT_SYMBOL(kmem_cache_destroy);
2350 /********************************************************************
2351 * Kmalloc subsystem
2352 *******************************************************************/
2354 struct kmem_cache kmalloc_caches[PAGE_SHIFT] __cacheline_aligned;
2355 EXPORT_SYMBOL(kmalloc_caches);
2357 #ifdef CONFIG_ZONE_DMA
2358 static struct kmem_cache *kmalloc_caches_dma[PAGE_SHIFT];
2359 #endif
2361 static int __init setup_slub_min_order(char *str)
2363 get_option (&str, &slub_min_order);
2365 return 1;
2368 __setup("slub_min_order=", setup_slub_min_order);
2370 static int __init setup_slub_max_order(char *str)
2372 get_option (&str, &slub_max_order);
2374 return 1;
2377 __setup("slub_max_order=", setup_slub_max_order);
2379 static int __init setup_slub_min_objects(char *str)
2381 get_option (&str, &slub_min_objects);
2383 return 1;
2386 __setup("slub_min_objects=", setup_slub_min_objects);
2388 static int __init setup_slub_nomerge(char *str)
2390 slub_nomerge = 1;
2391 return 1;
2394 __setup("slub_nomerge", setup_slub_nomerge);
2396 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2397 const char *name, int size, gfp_t gfp_flags)
2399 unsigned int flags = 0;
2401 if (gfp_flags & SLUB_DMA)
2402 flags = SLAB_CACHE_DMA;
2404 down_write(&slub_lock);
2405 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2406 flags, NULL))
2407 goto panic;
2409 list_add(&s->list, &slab_caches);
2410 up_write(&slub_lock);
2411 if (sysfs_slab_add(s))
2412 goto panic;
2413 return s;
2415 panic:
2416 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2419 #ifdef CONFIG_ZONE_DMA
2421 static void sysfs_add_func(struct work_struct *w)
2423 struct kmem_cache *s;
2425 down_write(&slub_lock);
2426 list_for_each_entry(s, &slab_caches, list) {
2427 if (s->flags & __SYSFS_ADD_DEFERRED) {
2428 s->flags &= ~__SYSFS_ADD_DEFERRED;
2429 sysfs_slab_add(s);
2432 up_write(&slub_lock);
2435 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2437 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2439 struct kmem_cache *s;
2440 char *text;
2441 size_t realsize;
2443 s = kmalloc_caches_dma[index];
2444 if (s)
2445 return s;
2447 /* Dynamically create dma cache */
2448 if (flags & __GFP_WAIT)
2449 down_write(&slub_lock);
2450 else {
2451 if (!down_write_trylock(&slub_lock))
2452 goto out;
2455 if (kmalloc_caches_dma[index])
2456 goto unlock_out;
2458 realsize = kmalloc_caches[index].objsize;
2459 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d", (unsigned int)realsize),
2460 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2462 if (!s || !text || !kmem_cache_open(s, flags, text,
2463 realsize, ARCH_KMALLOC_MINALIGN,
2464 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2465 kfree(s);
2466 kfree(text);
2467 goto unlock_out;
2470 list_add(&s->list, &slab_caches);
2471 kmalloc_caches_dma[index] = s;
2473 schedule_work(&sysfs_add_work);
2475 unlock_out:
2476 up_write(&slub_lock);
2477 out:
2478 return kmalloc_caches_dma[index];
2480 #endif
2483 * Conversion table for small slabs sizes / 8 to the index in the
2484 * kmalloc array. This is necessary for slabs < 192 since we have non power
2485 * of two cache sizes there. The size of larger slabs can be determined using
2486 * fls.
2488 static s8 size_index[24] = {
2489 3, /* 8 */
2490 4, /* 16 */
2491 5, /* 24 */
2492 5, /* 32 */
2493 6, /* 40 */
2494 6, /* 48 */
2495 6, /* 56 */
2496 6, /* 64 */
2497 1, /* 72 */
2498 1, /* 80 */
2499 1, /* 88 */
2500 1, /* 96 */
2501 7, /* 104 */
2502 7, /* 112 */
2503 7, /* 120 */
2504 7, /* 128 */
2505 2, /* 136 */
2506 2, /* 144 */
2507 2, /* 152 */
2508 2, /* 160 */
2509 2, /* 168 */
2510 2, /* 176 */
2511 2, /* 184 */
2512 2 /* 192 */
2515 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2517 int index;
2519 if (size <= 192) {
2520 if (!size)
2521 return ZERO_SIZE_PTR;
2523 index = size_index[(size - 1) / 8];
2524 } else
2525 index = fls(size - 1);
2527 #ifdef CONFIG_ZONE_DMA
2528 if (unlikely((flags & SLUB_DMA)))
2529 return dma_kmalloc_cache(index, flags);
2531 #endif
2532 return &kmalloc_caches[index];
2535 void *__kmalloc(size_t size, gfp_t flags)
2537 struct kmem_cache *s;
2539 if (unlikely(size > PAGE_SIZE / 2))
2540 return (void *)__get_free_pages(flags | __GFP_COMP,
2541 get_order(size));
2543 s = get_slab(size, flags);
2545 if (unlikely(ZERO_OR_NULL_PTR(s)))
2546 return s;
2548 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2550 EXPORT_SYMBOL(__kmalloc);
2552 #ifdef CONFIG_NUMA
2553 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2555 struct kmem_cache *s;
2557 if (unlikely(size > PAGE_SIZE / 2))
2558 return (void *)__get_free_pages(flags | __GFP_COMP,
2559 get_order(size));
2561 s = get_slab(size, flags);
2563 if (unlikely(ZERO_OR_NULL_PTR(s)))
2564 return s;
2566 return slab_alloc(s, flags, node, __builtin_return_address(0));
2568 EXPORT_SYMBOL(__kmalloc_node);
2569 #endif
2571 size_t ksize(const void *object)
2573 struct page *page;
2574 struct kmem_cache *s;
2576 BUG_ON(!object);
2577 if (unlikely(object == ZERO_SIZE_PTR))
2578 return 0;
2580 page = get_object_page(object);
2581 BUG_ON(!page);
2582 s = page->slab;
2583 BUG_ON(!s);
2586 * Debugging requires use of the padding between object
2587 * and whatever may come after it.
2589 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2590 return s->objsize;
2593 * If we have the need to store the freelist pointer
2594 * back there or track user information then we can
2595 * only use the space before that information.
2597 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2598 return s->inuse;
2601 * Else we can use all the padding etc for the allocation
2603 return s->size;
2605 EXPORT_SYMBOL(ksize);
2607 void kfree(const void *x)
2609 struct page *page;
2611 if (unlikely(ZERO_OR_NULL_PTR(x)))
2612 return;
2614 page = virt_to_head_page(x);
2615 if (unlikely(!PageSlab(page))) {
2616 put_page(page);
2617 return;
2619 slab_free(page->slab, page, (void *)x, __builtin_return_address(0));
2621 EXPORT_SYMBOL(kfree);
2624 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2625 * the remaining slabs by the number of items in use. The slabs with the
2626 * most items in use come first. New allocations will then fill those up
2627 * and thus they can be removed from the partial lists.
2629 * The slabs with the least items are placed last. This results in them
2630 * being allocated from last increasing the chance that the last objects
2631 * are freed in them.
2633 int kmem_cache_shrink(struct kmem_cache *s)
2635 int node;
2636 int i;
2637 struct kmem_cache_node *n;
2638 struct page *page;
2639 struct page *t;
2640 struct list_head *slabs_by_inuse =
2641 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2642 unsigned long flags;
2644 if (!slabs_by_inuse)
2645 return -ENOMEM;
2647 flush_all(s);
2648 for_each_node_state(node, N_NORMAL_MEMORY) {
2649 n = get_node(s, node);
2651 if (!n->nr_partial)
2652 continue;
2654 for (i = 0; i < s->objects; i++)
2655 INIT_LIST_HEAD(slabs_by_inuse + i);
2657 spin_lock_irqsave(&n->list_lock, flags);
2660 * Build lists indexed by the items in use in each slab.
2662 * Note that concurrent frees may occur while we hold the
2663 * list_lock. page->inuse here is the upper limit.
2665 list_for_each_entry_safe(page, t, &n->partial, lru) {
2666 if (!page->inuse && slab_trylock(page)) {
2668 * Must hold slab lock here because slab_free
2669 * may have freed the last object and be
2670 * waiting to release the slab.
2672 list_del(&page->lru);
2673 n->nr_partial--;
2674 slab_unlock(page);
2675 discard_slab(s, page);
2676 } else {
2677 list_move(&page->lru,
2678 slabs_by_inuse + page->inuse);
2683 * Rebuild the partial list with the slabs filled up most
2684 * first and the least used slabs at the end.
2686 for (i = s->objects - 1; i >= 0; i--)
2687 list_splice(slabs_by_inuse + i, n->partial.prev);
2689 spin_unlock_irqrestore(&n->list_lock, flags);
2692 kfree(slabs_by_inuse);
2693 return 0;
2695 EXPORT_SYMBOL(kmem_cache_shrink);
2697 /********************************************************************
2698 * Basic setup of slabs
2699 *******************************************************************/
2701 void __init kmem_cache_init(void)
2703 int i;
2704 int caches = 0;
2706 init_alloc_cpu();
2708 #ifdef CONFIG_NUMA
2710 * Must first have the slab cache available for the allocations of the
2711 * struct kmem_cache_node's. There is special bootstrap code in
2712 * kmem_cache_open for slab_state == DOWN.
2714 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2715 sizeof(struct kmem_cache_node), GFP_KERNEL);
2716 kmalloc_caches[0].refcount = -1;
2717 caches++;
2718 #endif
2720 /* Able to allocate the per node structures */
2721 slab_state = PARTIAL;
2723 /* Caches that are not of the two-to-the-power-of size */
2724 if (KMALLOC_MIN_SIZE <= 64) {
2725 create_kmalloc_cache(&kmalloc_caches[1],
2726 "kmalloc-96", 96, GFP_KERNEL);
2727 caches++;
2729 if (KMALLOC_MIN_SIZE <= 128) {
2730 create_kmalloc_cache(&kmalloc_caches[2],
2731 "kmalloc-192", 192, GFP_KERNEL);
2732 caches++;
2735 for (i = KMALLOC_SHIFT_LOW; i < PAGE_SHIFT; i++) {
2736 create_kmalloc_cache(&kmalloc_caches[i],
2737 "kmalloc", 1 << i, GFP_KERNEL);
2738 caches++;
2743 * Patch up the size_index table if we have strange large alignment
2744 * requirements for the kmalloc array. This is only the case for
2745 * mips it seems. The standard arches will not generate any code here.
2747 * Largest permitted alignment is 256 bytes due to the way we
2748 * handle the index determination for the smaller caches.
2750 * Make sure that nothing crazy happens if someone starts tinkering
2751 * around with ARCH_KMALLOC_MINALIGN
2753 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
2754 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
2756 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
2757 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
2759 slab_state = UP;
2761 /* Provide the correct kmalloc names now that the caches are up */
2762 for (i = KMALLOC_SHIFT_LOW; i < PAGE_SHIFT; i++)
2763 kmalloc_caches[i]. name =
2764 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2766 #ifdef CONFIG_SMP
2767 register_cpu_notifier(&slab_notifier);
2768 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2769 nr_cpu_ids * sizeof(struct kmem_cache_cpu *);
2770 #else
2771 kmem_size = sizeof(struct kmem_cache);
2772 #endif
2775 printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2776 " CPUs=%d, Nodes=%d\n",
2777 caches, cache_line_size(),
2778 slub_min_order, slub_max_order, slub_min_objects,
2779 nr_cpu_ids, nr_node_ids);
2783 * Find a mergeable slab cache
2785 static int slab_unmergeable(struct kmem_cache *s)
2787 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2788 return 1;
2790 if (s->ctor)
2791 return 1;
2794 * We may have set a slab to be unmergeable during bootstrap.
2796 if (s->refcount < 0)
2797 return 1;
2799 return 0;
2802 static struct kmem_cache *find_mergeable(size_t size,
2803 size_t align, unsigned long flags, const char *name,
2804 void (*ctor)(struct kmem_cache *, void *))
2806 struct kmem_cache *s;
2808 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2809 return NULL;
2811 if (ctor)
2812 return NULL;
2814 size = ALIGN(size, sizeof(void *));
2815 align = calculate_alignment(flags, align, size);
2816 size = ALIGN(size, align);
2817 flags = kmem_cache_flags(size, flags, name, NULL);
2819 list_for_each_entry(s, &slab_caches, list) {
2820 if (slab_unmergeable(s))
2821 continue;
2823 if (size > s->size)
2824 continue;
2826 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
2827 continue;
2829 * Check if alignment is compatible.
2830 * Courtesy of Adrian Drzewiecki
2832 if ((s->size & ~(align -1)) != s->size)
2833 continue;
2835 if (s->size - size >= sizeof(void *))
2836 continue;
2838 return s;
2840 return NULL;
2843 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2844 size_t align, unsigned long flags,
2845 void (*ctor)(struct kmem_cache *, void *))
2847 struct kmem_cache *s;
2849 down_write(&slub_lock);
2850 s = find_mergeable(size, align, flags, name, ctor);
2851 if (s) {
2852 int cpu;
2854 s->refcount++;
2856 * Adjust the object sizes so that we clear
2857 * the complete object on kzalloc.
2859 s->objsize = max(s->objsize, (int)size);
2862 * And then we need to update the object size in the
2863 * per cpu structures
2865 for_each_online_cpu(cpu)
2866 get_cpu_slab(s, cpu)->objsize = s->objsize;
2867 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2868 up_write(&slub_lock);
2869 if (sysfs_slab_alias(s, name))
2870 goto err;
2871 return s;
2873 s = kmalloc(kmem_size, GFP_KERNEL);
2874 if (s) {
2875 if (kmem_cache_open(s, GFP_KERNEL, name,
2876 size, align, flags, ctor)) {
2877 list_add(&s->list, &slab_caches);
2878 up_write(&slub_lock);
2879 if (sysfs_slab_add(s))
2880 goto err;
2881 return s;
2883 kfree(s);
2885 up_write(&slub_lock);
2887 err:
2888 if (flags & SLAB_PANIC)
2889 panic("Cannot create slabcache %s\n", name);
2890 else
2891 s = NULL;
2892 return s;
2894 EXPORT_SYMBOL(kmem_cache_create);
2896 #ifdef CONFIG_SMP
2898 * Use the cpu notifier to insure that the cpu slabs are flushed when
2899 * necessary.
2901 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2902 unsigned long action, void *hcpu)
2904 long cpu = (long)hcpu;
2905 struct kmem_cache *s;
2906 unsigned long flags;
2908 switch (action) {
2909 case CPU_UP_PREPARE:
2910 case CPU_UP_PREPARE_FROZEN:
2911 init_alloc_cpu_cpu(cpu);
2912 down_read(&slub_lock);
2913 list_for_each_entry(s, &slab_caches, list)
2914 s->cpu_slab[cpu] = alloc_kmem_cache_cpu(s, cpu,
2915 GFP_KERNEL);
2916 up_read(&slub_lock);
2917 break;
2919 case CPU_UP_CANCELED:
2920 case CPU_UP_CANCELED_FROZEN:
2921 case CPU_DEAD:
2922 case CPU_DEAD_FROZEN:
2923 down_read(&slub_lock);
2924 list_for_each_entry(s, &slab_caches, list) {
2925 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2927 local_irq_save(flags);
2928 __flush_cpu_slab(s, cpu);
2929 local_irq_restore(flags);
2930 free_kmem_cache_cpu(c, cpu);
2931 s->cpu_slab[cpu] = NULL;
2933 up_read(&slub_lock);
2934 break;
2935 default:
2936 break;
2938 return NOTIFY_OK;
2941 static struct notifier_block __cpuinitdata slab_notifier =
2942 { &slab_cpuup_callback, NULL, 0 };
2944 #endif
2946 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2948 struct kmem_cache *s;
2950 if (unlikely(size > PAGE_SIZE / 2))
2951 return (void *)__get_free_pages(gfpflags | __GFP_COMP,
2952 get_order(size));
2953 s = get_slab(size, gfpflags);
2955 if (unlikely(ZERO_OR_NULL_PTR(s)))
2956 return s;
2958 return slab_alloc(s, gfpflags, -1, caller);
2961 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2962 int node, void *caller)
2964 struct kmem_cache *s;
2966 if (unlikely(size > PAGE_SIZE / 2))
2967 return (void *)__get_free_pages(gfpflags | __GFP_COMP,
2968 get_order(size));
2969 s = get_slab(size, gfpflags);
2971 if (unlikely(ZERO_OR_NULL_PTR(s)))
2972 return s;
2974 return slab_alloc(s, gfpflags, node, caller);
2977 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2978 static int validate_slab(struct kmem_cache *s, struct page *page,
2979 unsigned long *map)
2981 void *p;
2982 void *addr = page_address(page);
2984 if (!check_slab(s, page) ||
2985 !on_freelist(s, page, NULL))
2986 return 0;
2988 /* Now we know that a valid freelist exists */
2989 bitmap_zero(map, s->objects);
2991 for_each_free_object(p, s, page->freelist) {
2992 set_bit(slab_index(p, s, addr), map);
2993 if (!check_object(s, page, p, 0))
2994 return 0;
2997 for_each_object(p, s, addr)
2998 if (!test_bit(slab_index(p, s, addr), map))
2999 if (!check_object(s, page, p, 1))
3000 return 0;
3001 return 1;
3004 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
3005 unsigned long *map)
3007 if (slab_trylock(page)) {
3008 validate_slab(s, page, map);
3009 slab_unlock(page);
3010 } else
3011 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
3012 s->name, page);
3014 if (s->flags & DEBUG_DEFAULT_FLAGS) {
3015 if (!SlabDebug(page))
3016 printk(KERN_ERR "SLUB %s: SlabDebug not set "
3017 "on slab 0x%p\n", s->name, page);
3018 } else {
3019 if (SlabDebug(page))
3020 printk(KERN_ERR "SLUB %s: SlabDebug set on "
3021 "slab 0x%p\n", s->name, page);
3025 static int validate_slab_node(struct kmem_cache *s,
3026 struct kmem_cache_node *n, unsigned long *map)
3028 unsigned long count = 0;
3029 struct page *page;
3030 unsigned long flags;
3032 spin_lock_irqsave(&n->list_lock, flags);
3034 list_for_each_entry(page, &n->partial, lru) {
3035 validate_slab_slab(s, page, map);
3036 count++;
3038 if (count != n->nr_partial)
3039 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
3040 "counter=%ld\n", s->name, count, n->nr_partial);
3042 if (!(s->flags & SLAB_STORE_USER))
3043 goto out;
3045 list_for_each_entry(page, &n->full, lru) {
3046 validate_slab_slab(s, page, map);
3047 count++;
3049 if (count != atomic_long_read(&n->nr_slabs))
3050 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
3051 "counter=%ld\n", s->name, count,
3052 atomic_long_read(&n->nr_slabs));
3054 out:
3055 spin_unlock_irqrestore(&n->list_lock, flags);
3056 return count;
3059 static long validate_slab_cache(struct kmem_cache *s)
3061 int node;
3062 unsigned long count = 0;
3063 unsigned long *map = kmalloc(BITS_TO_LONGS(s->objects) *
3064 sizeof(unsigned long), GFP_KERNEL);
3066 if (!map)
3067 return -ENOMEM;
3069 flush_all(s);
3070 for_each_node_state(node, N_NORMAL_MEMORY) {
3071 struct kmem_cache_node *n = get_node(s, node);
3073 count += validate_slab_node(s, n, map);
3075 kfree(map);
3076 return count;
3079 #ifdef SLUB_RESILIENCY_TEST
3080 static void resiliency_test(void)
3082 u8 *p;
3084 printk(KERN_ERR "SLUB resiliency testing\n");
3085 printk(KERN_ERR "-----------------------\n");
3086 printk(KERN_ERR "A. Corruption after allocation\n");
3088 p = kzalloc(16, GFP_KERNEL);
3089 p[16] = 0x12;
3090 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
3091 " 0x12->0x%p\n\n", p + 16);
3093 validate_slab_cache(kmalloc_caches + 4);
3095 /* Hmmm... The next two are dangerous */
3096 p = kzalloc(32, GFP_KERNEL);
3097 p[32 + sizeof(void *)] = 0x34;
3098 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
3099 " 0x34 -> -0x%p\n", p);
3100 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
3102 validate_slab_cache(kmalloc_caches + 5);
3103 p = kzalloc(64, GFP_KERNEL);
3104 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
3105 *p = 0x56;
3106 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
3108 printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
3109 validate_slab_cache(kmalloc_caches + 6);
3111 printk(KERN_ERR "\nB. Corruption after free\n");
3112 p = kzalloc(128, GFP_KERNEL);
3113 kfree(p);
3114 *p = 0x78;
3115 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
3116 validate_slab_cache(kmalloc_caches + 7);
3118 p = kzalloc(256, GFP_KERNEL);
3119 kfree(p);
3120 p[50] = 0x9a;
3121 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
3122 validate_slab_cache(kmalloc_caches + 8);
3124 p = kzalloc(512, GFP_KERNEL);
3125 kfree(p);
3126 p[512] = 0xab;
3127 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
3128 validate_slab_cache(kmalloc_caches + 9);
3130 #else
3131 static void resiliency_test(void) {};
3132 #endif
3135 * Generate lists of code addresses where slabcache objects are allocated
3136 * and freed.
3139 struct location {
3140 unsigned long count;
3141 void *addr;
3142 long long sum_time;
3143 long min_time;
3144 long max_time;
3145 long min_pid;
3146 long max_pid;
3147 cpumask_t cpus;
3148 nodemask_t nodes;
3151 struct loc_track {
3152 unsigned long max;
3153 unsigned long count;
3154 struct location *loc;
3157 static void free_loc_track(struct loc_track *t)
3159 if (t->max)
3160 free_pages((unsigned long)t->loc,
3161 get_order(sizeof(struct location) * t->max));
3164 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3166 struct location *l;
3167 int order;
3169 order = get_order(sizeof(struct location) * max);
3171 l = (void *)__get_free_pages(flags, order);
3172 if (!l)
3173 return 0;
3175 if (t->count) {
3176 memcpy(l, t->loc, sizeof(struct location) * t->count);
3177 free_loc_track(t);
3179 t->max = max;
3180 t->loc = l;
3181 return 1;
3184 static int add_location(struct loc_track *t, struct kmem_cache *s,
3185 const struct track *track)
3187 long start, end, pos;
3188 struct location *l;
3189 void *caddr;
3190 unsigned long age = jiffies - track->when;
3192 start = -1;
3193 end = t->count;
3195 for ( ; ; ) {
3196 pos = start + (end - start + 1) / 2;
3199 * There is nothing at "end". If we end up there
3200 * we need to add something to before end.
3202 if (pos == end)
3203 break;
3205 caddr = t->loc[pos].addr;
3206 if (track->addr == caddr) {
3208 l = &t->loc[pos];
3209 l->count++;
3210 if (track->when) {
3211 l->sum_time += age;
3212 if (age < l->min_time)
3213 l->min_time = age;
3214 if (age > l->max_time)
3215 l->max_time = age;
3217 if (track->pid < l->min_pid)
3218 l->min_pid = track->pid;
3219 if (track->pid > l->max_pid)
3220 l->max_pid = track->pid;
3222 cpu_set(track->cpu, l->cpus);
3224 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3225 return 1;
3228 if (track->addr < caddr)
3229 end = pos;
3230 else
3231 start = pos;
3235 * Not found. Insert new tracking element.
3237 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3238 return 0;
3240 l = t->loc + pos;
3241 if (pos < t->count)
3242 memmove(l + 1, l,
3243 (t->count - pos) * sizeof(struct location));
3244 t->count++;
3245 l->count = 1;
3246 l->addr = track->addr;
3247 l->sum_time = age;
3248 l->min_time = age;
3249 l->max_time = age;
3250 l->min_pid = track->pid;
3251 l->max_pid = track->pid;
3252 cpus_clear(l->cpus);
3253 cpu_set(track->cpu, l->cpus);
3254 nodes_clear(l->nodes);
3255 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3256 return 1;
3259 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3260 struct page *page, enum track_item alloc)
3262 void *addr = page_address(page);
3263 DECLARE_BITMAP(map, s->objects);
3264 void *p;
3266 bitmap_zero(map, s->objects);
3267 for_each_free_object(p, s, page->freelist)
3268 set_bit(slab_index(p, s, addr), map);
3270 for_each_object(p, s, addr)
3271 if (!test_bit(slab_index(p, s, addr), map))
3272 add_location(t, s, get_track(s, p, alloc));
3275 static int list_locations(struct kmem_cache *s, char *buf,
3276 enum track_item alloc)
3278 int n = 0;
3279 unsigned long i;
3280 struct loc_track t = { 0, 0, NULL };
3281 int node;
3283 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3284 GFP_TEMPORARY))
3285 return sprintf(buf, "Out of memory\n");
3287 /* Push back cpu slabs */
3288 flush_all(s);
3290 for_each_node_state(node, N_NORMAL_MEMORY) {
3291 struct kmem_cache_node *n = get_node(s, node);
3292 unsigned long flags;
3293 struct page *page;
3295 if (!atomic_long_read(&n->nr_slabs))
3296 continue;
3298 spin_lock_irqsave(&n->list_lock, flags);
3299 list_for_each_entry(page, &n->partial, lru)
3300 process_slab(&t, s, page, alloc);
3301 list_for_each_entry(page, &n->full, lru)
3302 process_slab(&t, s, page, alloc);
3303 spin_unlock_irqrestore(&n->list_lock, flags);
3306 for (i = 0; i < t.count; i++) {
3307 struct location *l = &t.loc[i];
3309 if (n > PAGE_SIZE - 100)
3310 break;
3311 n += sprintf(buf + n, "%7ld ", l->count);
3313 if (l->addr)
3314 n += sprint_symbol(buf + n, (unsigned long)l->addr);
3315 else
3316 n += sprintf(buf + n, "<not-available>");
3318 if (l->sum_time != l->min_time) {
3319 unsigned long remainder;
3321 n += sprintf(buf + n, " age=%ld/%ld/%ld",
3322 l->min_time,
3323 div_long_long_rem(l->sum_time, l->count, &remainder),
3324 l->max_time);
3325 } else
3326 n += sprintf(buf + n, " age=%ld",
3327 l->min_time);
3329 if (l->min_pid != l->max_pid)
3330 n += sprintf(buf + n, " pid=%ld-%ld",
3331 l->min_pid, l->max_pid);
3332 else
3333 n += sprintf(buf + n, " pid=%ld",
3334 l->min_pid);
3336 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3337 n < PAGE_SIZE - 60) {
3338 n += sprintf(buf + n, " cpus=");
3339 n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3340 l->cpus);
3343 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3344 n < PAGE_SIZE - 60) {
3345 n += sprintf(buf + n, " nodes=");
3346 n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3347 l->nodes);
3350 n += sprintf(buf + n, "\n");
3353 free_loc_track(&t);
3354 if (!t.count)
3355 n += sprintf(buf, "No data\n");
3356 return n;
3359 static unsigned long count_partial(struct kmem_cache_node *n)
3361 unsigned long flags;
3362 unsigned long x = 0;
3363 struct page *page;
3365 spin_lock_irqsave(&n->list_lock, flags);
3366 list_for_each_entry(page, &n->partial, lru)
3367 x += page->inuse;
3368 spin_unlock_irqrestore(&n->list_lock, flags);
3369 return x;
3372 enum slab_stat_type {
3373 SL_FULL,
3374 SL_PARTIAL,
3375 SL_CPU,
3376 SL_OBJECTS
3379 #define SO_FULL (1 << SL_FULL)
3380 #define SO_PARTIAL (1 << SL_PARTIAL)
3381 #define SO_CPU (1 << SL_CPU)
3382 #define SO_OBJECTS (1 << SL_OBJECTS)
3384 static unsigned long slab_objects(struct kmem_cache *s,
3385 char *buf, unsigned long flags)
3387 unsigned long total = 0;
3388 int cpu;
3389 int node;
3390 int x;
3391 unsigned long *nodes;
3392 unsigned long *per_cpu;
3394 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3395 per_cpu = nodes + nr_node_ids;
3397 for_each_possible_cpu(cpu) {
3398 struct page *page;
3399 int node;
3400 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3402 if (!c)
3403 continue;
3405 page = c->page;
3406 node = c->node;
3407 if (node < 0)
3408 continue;
3409 if (page) {
3410 if (flags & SO_CPU) {
3411 int x = 0;
3413 if (flags & SO_OBJECTS)
3414 x = page->inuse;
3415 else
3416 x = 1;
3417 total += x;
3418 nodes[node] += x;
3420 per_cpu[node]++;
3424 for_each_node_state(node, N_NORMAL_MEMORY) {
3425 struct kmem_cache_node *n = get_node(s, node);
3427 if (flags & SO_PARTIAL) {
3428 if (flags & SO_OBJECTS)
3429 x = count_partial(n);
3430 else
3431 x = n->nr_partial;
3432 total += x;
3433 nodes[node] += x;
3436 if (flags & SO_FULL) {
3437 int full_slabs = atomic_long_read(&n->nr_slabs)
3438 - per_cpu[node]
3439 - n->nr_partial;
3441 if (flags & SO_OBJECTS)
3442 x = full_slabs * s->objects;
3443 else
3444 x = full_slabs;
3445 total += x;
3446 nodes[node] += x;
3450 x = sprintf(buf, "%lu", total);
3451 #ifdef CONFIG_NUMA
3452 for_each_node_state(node, N_NORMAL_MEMORY)
3453 if (nodes[node])
3454 x += sprintf(buf + x, " N%d=%lu",
3455 node, nodes[node]);
3456 #endif
3457 kfree(nodes);
3458 return x + sprintf(buf + x, "\n");
3461 static int any_slab_objects(struct kmem_cache *s)
3463 int node;
3464 int cpu;
3466 for_each_possible_cpu(cpu) {
3467 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3469 if (c && c->page)
3470 return 1;
3473 for_each_online_node(node) {
3474 struct kmem_cache_node *n = get_node(s, node);
3476 if (!n)
3477 continue;
3479 if (n->nr_partial || atomic_long_read(&n->nr_slabs))
3480 return 1;
3482 return 0;
3485 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3486 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3488 struct slab_attribute {
3489 struct attribute attr;
3490 ssize_t (*show)(struct kmem_cache *s, char *buf);
3491 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3494 #define SLAB_ATTR_RO(_name) \
3495 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3497 #define SLAB_ATTR(_name) \
3498 static struct slab_attribute _name##_attr = \
3499 __ATTR(_name, 0644, _name##_show, _name##_store)
3501 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3503 return sprintf(buf, "%d\n", s->size);
3505 SLAB_ATTR_RO(slab_size);
3507 static ssize_t align_show(struct kmem_cache *s, char *buf)
3509 return sprintf(buf, "%d\n", s->align);
3511 SLAB_ATTR_RO(align);
3513 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3515 return sprintf(buf, "%d\n", s->objsize);
3517 SLAB_ATTR_RO(object_size);
3519 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3521 return sprintf(buf, "%d\n", s->objects);
3523 SLAB_ATTR_RO(objs_per_slab);
3525 static ssize_t order_show(struct kmem_cache *s, char *buf)
3527 return sprintf(buf, "%d\n", s->order);
3529 SLAB_ATTR_RO(order);
3531 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3533 if (s->ctor) {
3534 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3536 return n + sprintf(buf + n, "\n");
3538 return 0;
3540 SLAB_ATTR_RO(ctor);
3542 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3544 return sprintf(buf, "%d\n", s->refcount - 1);
3546 SLAB_ATTR_RO(aliases);
3548 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3550 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3552 SLAB_ATTR_RO(slabs);
3554 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3556 return slab_objects(s, buf, SO_PARTIAL);
3558 SLAB_ATTR_RO(partial);
3560 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3562 return slab_objects(s, buf, SO_CPU);
3564 SLAB_ATTR_RO(cpu_slabs);
3566 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3568 return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3570 SLAB_ATTR_RO(objects);
3572 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3574 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3577 static ssize_t sanity_checks_store(struct kmem_cache *s,
3578 const char *buf, size_t length)
3580 s->flags &= ~SLAB_DEBUG_FREE;
3581 if (buf[0] == '1')
3582 s->flags |= SLAB_DEBUG_FREE;
3583 return length;
3585 SLAB_ATTR(sanity_checks);
3587 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3589 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3592 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3593 size_t length)
3595 s->flags &= ~SLAB_TRACE;
3596 if (buf[0] == '1')
3597 s->flags |= SLAB_TRACE;
3598 return length;
3600 SLAB_ATTR(trace);
3602 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3604 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3607 static ssize_t reclaim_account_store(struct kmem_cache *s,
3608 const char *buf, size_t length)
3610 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3611 if (buf[0] == '1')
3612 s->flags |= SLAB_RECLAIM_ACCOUNT;
3613 return length;
3615 SLAB_ATTR(reclaim_account);
3617 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3619 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3621 SLAB_ATTR_RO(hwcache_align);
3623 #ifdef CONFIG_ZONE_DMA
3624 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3626 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3628 SLAB_ATTR_RO(cache_dma);
3629 #endif
3631 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3633 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3635 SLAB_ATTR_RO(destroy_by_rcu);
3637 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3639 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3642 static ssize_t red_zone_store(struct kmem_cache *s,
3643 const char *buf, size_t length)
3645 if (any_slab_objects(s))
3646 return -EBUSY;
3648 s->flags &= ~SLAB_RED_ZONE;
3649 if (buf[0] == '1')
3650 s->flags |= SLAB_RED_ZONE;
3651 calculate_sizes(s);
3652 return length;
3654 SLAB_ATTR(red_zone);
3656 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3658 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3661 static ssize_t poison_store(struct kmem_cache *s,
3662 const char *buf, size_t length)
3664 if (any_slab_objects(s))
3665 return -EBUSY;
3667 s->flags &= ~SLAB_POISON;
3668 if (buf[0] == '1')
3669 s->flags |= SLAB_POISON;
3670 calculate_sizes(s);
3671 return length;
3673 SLAB_ATTR(poison);
3675 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3677 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3680 static ssize_t store_user_store(struct kmem_cache *s,
3681 const char *buf, size_t length)
3683 if (any_slab_objects(s))
3684 return -EBUSY;
3686 s->flags &= ~SLAB_STORE_USER;
3687 if (buf[0] == '1')
3688 s->flags |= SLAB_STORE_USER;
3689 calculate_sizes(s);
3690 return length;
3692 SLAB_ATTR(store_user);
3694 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3696 return 0;
3699 static ssize_t validate_store(struct kmem_cache *s,
3700 const char *buf, size_t length)
3702 int ret = -EINVAL;
3704 if (buf[0] == '1') {
3705 ret = validate_slab_cache(s);
3706 if (ret >= 0)
3707 ret = length;
3709 return ret;
3711 SLAB_ATTR(validate);
3713 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3715 return 0;
3718 static ssize_t shrink_store(struct kmem_cache *s,
3719 const char *buf, size_t length)
3721 if (buf[0] == '1') {
3722 int rc = kmem_cache_shrink(s);
3724 if (rc)
3725 return rc;
3726 } else
3727 return -EINVAL;
3728 return length;
3730 SLAB_ATTR(shrink);
3732 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3734 if (!(s->flags & SLAB_STORE_USER))
3735 return -ENOSYS;
3736 return list_locations(s, buf, TRACK_ALLOC);
3738 SLAB_ATTR_RO(alloc_calls);
3740 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3742 if (!(s->flags & SLAB_STORE_USER))
3743 return -ENOSYS;
3744 return list_locations(s, buf, TRACK_FREE);
3746 SLAB_ATTR_RO(free_calls);
3748 #ifdef CONFIG_NUMA
3749 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3751 return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3754 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3755 const char *buf, size_t length)
3757 int n = simple_strtoul(buf, NULL, 10);
3759 if (n < 100)
3760 s->defrag_ratio = n * 10;
3761 return length;
3763 SLAB_ATTR(defrag_ratio);
3764 #endif
3766 static struct attribute * slab_attrs[] = {
3767 &slab_size_attr.attr,
3768 &object_size_attr.attr,
3769 &objs_per_slab_attr.attr,
3770 &order_attr.attr,
3771 &objects_attr.attr,
3772 &slabs_attr.attr,
3773 &partial_attr.attr,
3774 &cpu_slabs_attr.attr,
3775 &ctor_attr.attr,
3776 &aliases_attr.attr,
3777 &align_attr.attr,
3778 &sanity_checks_attr.attr,
3779 &trace_attr.attr,
3780 &hwcache_align_attr.attr,
3781 &reclaim_account_attr.attr,
3782 &destroy_by_rcu_attr.attr,
3783 &red_zone_attr.attr,
3784 &poison_attr.attr,
3785 &store_user_attr.attr,
3786 &validate_attr.attr,
3787 &shrink_attr.attr,
3788 &alloc_calls_attr.attr,
3789 &free_calls_attr.attr,
3790 #ifdef CONFIG_ZONE_DMA
3791 &cache_dma_attr.attr,
3792 #endif
3793 #ifdef CONFIG_NUMA
3794 &defrag_ratio_attr.attr,
3795 #endif
3796 NULL
3799 static struct attribute_group slab_attr_group = {
3800 .attrs = slab_attrs,
3803 static ssize_t slab_attr_show(struct kobject *kobj,
3804 struct attribute *attr,
3805 char *buf)
3807 struct slab_attribute *attribute;
3808 struct kmem_cache *s;
3809 int err;
3811 attribute = to_slab_attr(attr);
3812 s = to_slab(kobj);
3814 if (!attribute->show)
3815 return -EIO;
3817 err = attribute->show(s, buf);
3819 return err;
3822 static ssize_t slab_attr_store(struct kobject *kobj,
3823 struct attribute *attr,
3824 const char *buf, size_t len)
3826 struct slab_attribute *attribute;
3827 struct kmem_cache *s;
3828 int err;
3830 attribute = to_slab_attr(attr);
3831 s = to_slab(kobj);
3833 if (!attribute->store)
3834 return -EIO;
3836 err = attribute->store(s, buf, len);
3838 return err;
3841 static struct sysfs_ops slab_sysfs_ops = {
3842 .show = slab_attr_show,
3843 .store = slab_attr_store,
3846 static struct kobj_type slab_ktype = {
3847 .sysfs_ops = &slab_sysfs_ops,
3850 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3852 struct kobj_type *ktype = get_ktype(kobj);
3854 if (ktype == &slab_ktype)
3855 return 1;
3856 return 0;
3859 static struct kset_uevent_ops slab_uevent_ops = {
3860 .filter = uevent_filter,
3863 static decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3865 #define ID_STR_LENGTH 64
3867 /* Create a unique string id for a slab cache:
3868 * format
3869 * :[flags-]size:[memory address of kmemcache]
3871 static char *create_unique_id(struct kmem_cache *s)
3873 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3874 char *p = name;
3876 BUG_ON(!name);
3878 *p++ = ':';
3880 * First flags affecting slabcache operations. We will only
3881 * get here for aliasable slabs so we do not need to support
3882 * too many flags. The flags here must cover all flags that
3883 * are matched during merging to guarantee that the id is
3884 * unique.
3886 if (s->flags & SLAB_CACHE_DMA)
3887 *p++ = 'd';
3888 if (s->flags & SLAB_RECLAIM_ACCOUNT)
3889 *p++ = 'a';
3890 if (s->flags & SLAB_DEBUG_FREE)
3891 *p++ = 'F';
3892 if (p != name + 1)
3893 *p++ = '-';
3894 p += sprintf(p, "%07d", s->size);
3895 BUG_ON(p > name + ID_STR_LENGTH - 1);
3896 return name;
3899 static int sysfs_slab_add(struct kmem_cache *s)
3901 int err;
3902 const char *name;
3903 int unmergeable;
3905 if (slab_state < SYSFS)
3906 /* Defer until later */
3907 return 0;
3909 unmergeable = slab_unmergeable(s);
3910 if (unmergeable) {
3912 * Slabcache can never be merged so we can use the name proper.
3913 * This is typically the case for debug situations. In that
3914 * case we can catch duplicate names easily.
3916 sysfs_remove_link(&slab_subsys.kobj, s->name);
3917 name = s->name;
3918 } else {
3920 * Create a unique name for the slab as a target
3921 * for the symlinks.
3923 name = create_unique_id(s);
3926 kobj_set_kset_s(s, slab_subsys);
3927 kobject_set_name(&s->kobj, name);
3928 kobject_init(&s->kobj);
3929 err = kobject_add(&s->kobj);
3930 if (err)
3931 return err;
3933 err = sysfs_create_group(&s->kobj, &slab_attr_group);
3934 if (err)
3935 return err;
3936 kobject_uevent(&s->kobj, KOBJ_ADD);
3937 if (!unmergeable) {
3938 /* Setup first alias */
3939 sysfs_slab_alias(s, s->name);
3940 kfree(name);
3942 return 0;
3945 static void sysfs_slab_remove(struct kmem_cache *s)
3947 kobject_uevent(&s->kobj, KOBJ_REMOVE);
3948 kobject_del(&s->kobj);
3952 * Need to buffer aliases during bootup until sysfs becomes
3953 * available lest we loose that information.
3955 struct saved_alias {
3956 struct kmem_cache *s;
3957 const char *name;
3958 struct saved_alias *next;
3961 static struct saved_alias *alias_list;
3963 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3965 struct saved_alias *al;
3967 if (slab_state == SYSFS) {
3969 * If we have a leftover link then remove it.
3971 sysfs_remove_link(&slab_subsys.kobj, name);
3972 return sysfs_create_link(&slab_subsys.kobj,
3973 &s->kobj, name);
3976 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3977 if (!al)
3978 return -ENOMEM;
3980 al->s = s;
3981 al->name = name;
3982 al->next = alias_list;
3983 alias_list = al;
3984 return 0;
3987 static int __init slab_sysfs_init(void)
3989 struct kmem_cache *s;
3990 int err;
3992 err = subsystem_register(&slab_subsys);
3993 if (err) {
3994 printk(KERN_ERR "Cannot register slab subsystem.\n");
3995 return -ENOSYS;
3998 slab_state = SYSFS;
4000 list_for_each_entry(s, &slab_caches, list) {
4001 err = sysfs_slab_add(s);
4002 if (err)
4003 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
4004 " to sysfs\n", s->name);
4007 while (alias_list) {
4008 struct saved_alias *al = alias_list;
4010 alias_list = alias_list->next;
4011 err = sysfs_slab_alias(al->s, al->name);
4012 if (err)
4013 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
4014 " %s to sysfs\n", s->name);
4015 kfree(al);
4018 resiliency_test();
4019 return 0;
4022 __initcall(slab_sysfs_init);
4023 #endif