kmemtrace: SLOB hooks.
[linux-2.6/kmemtrace.git] / mm / slub.c
blob940145f4aeb776c43eb9038417b055e20aef6ffd
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
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/debugobjects.h>
23 #include <linux/kallsyms.h>
24 #include <linux/memory.h>
25 #include <linux/math64.h>
26 #include <linux/kmemtrace.h>
29 * Lock order:
30 * 1. slab_lock(page)
31 * 2. slab->list_lock
33 * The slab_lock protects operations on the object of a particular
34 * slab and its metadata in the page struct. If the slab lock
35 * has been taken then no allocations nor frees can be performed
36 * on the objects in the slab nor can the slab be added or removed
37 * from the partial or full lists since this would mean modifying
38 * the page_struct of the slab.
40 * The list_lock protects the partial and full list on each node and
41 * the partial slab counter. If taken then no new slabs may be added or
42 * removed from the lists nor make the number of partial slabs be modified.
43 * (Note that the total number of slabs is an atomic value that may be
44 * modified without taking the list lock).
46 * The list_lock is a centralized lock and thus we avoid taking it as
47 * much as possible. As long as SLUB does not have to handle partial
48 * slabs, operations can continue without any centralized lock. F.e.
49 * allocating a long series of objects that fill up slabs does not require
50 * the list lock.
52 * The lock order is sometimes inverted when we are trying to get a slab
53 * off a list. We take the list_lock and then look for a page on the list
54 * to use. While we do that objects in the slabs may be freed. We can
55 * only operate on the slab if we have also taken the slab_lock. So we use
56 * a slab_trylock() on the slab. If trylock was successful then no frees
57 * can occur anymore and we can use the slab for allocations etc. If the
58 * slab_trylock() does not succeed then frees are in progress in the slab and
59 * we must stay away from it for a while since we may cause a bouncing
60 * cacheline if we try to acquire the lock. So go onto the next slab.
61 * If all pages are busy then we may allocate a new slab instead of reusing
62 * a partial slab. A new slab has noone operating on it and thus there is
63 * no danger of cacheline contention.
65 * Interrupts are disabled during allocation and deallocation in order to
66 * make the slab allocator safe to use in the context of an irq. In addition
67 * interrupts are disabled to ensure that the processor does not change
68 * while handling per_cpu slabs, due to kernel preemption.
70 * SLUB assigns one slab for allocation to each processor.
71 * Allocations only occur from these slabs called cpu slabs.
73 * Slabs with free elements are kept on a partial list and during regular
74 * operations no list for full slabs is used. If an object in a full slab is
75 * freed then the slab will show up again on the partial lists.
76 * We track full slabs for debugging purposes though because otherwise we
77 * cannot scan all objects.
79 * Slabs are freed when they become empty. Teardown and setup is
80 * minimal so we rely on the page allocators per cpu caches for
81 * fast frees and allocs.
83 * Overloading of page flags that are otherwise used for LRU management.
85 * PageActive The slab is frozen and exempt from list processing.
86 * This means that the slab is dedicated to a purpose
87 * such as satisfying allocations for a specific
88 * processor. Objects may be freed in the slab while
89 * it is frozen but slab_free will then skip the usual
90 * list operations. It is up to the processor holding
91 * the slab to integrate the slab into the slab lists
92 * when the slab is no longer needed.
94 * One use of this flag is to mark slabs that are
95 * used for allocations. Then such a slab becomes a cpu
96 * slab. The cpu slab may be equipped with an additional
97 * freelist that allows lockless access to
98 * free objects in addition to the regular freelist
99 * that requires the slab lock.
101 * PageError Slab requires special handling due to debug
102 * options set. This moves slab handling out of
103 * the fast path and disables lockless freelists.
106 #define FROZEN (1 << PG_active)
108 #ifdef CONFIG_SLUB_DEBUG
109 #define SLABDEBUG (1 << PG_error)
110 #else
111 #define SLABDEBUG 0
112 #endif
114 static inline int SlabFrozen(struct page *page)
116 return page->flags & FROZEN;
119 static inline void SetSlabFrozen(struct page *page)
121 page->flags |= FROZEN;
124 static inline void ClearSlabFrozen(struct page *page)
126 page->flags &= ~FROZEN;
129 static inline int SlabDebug(struct page *page)
131 return page->flags & SLABDEBUG;
134 static inline void SetSlabDebug(struct page *page)
136 page->flags |= SLABDEBUG;
139 static inline void ClearSlabDebug(struct page *page)
141 page->flags &= ~SLABDEBUG;
145 * Issues still to be resolved:
147 * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
149 * - Variable sizing of the per node arrays
152 /* Enable to test recovery from slab corruption on boot */
153 #undef SLUB_RESILIENCY_TEST
156 * Mininum number of partial slabs. These will be left on the partial
157 * lists even if they are empty. kmem_cache_shrink may reclaim them.
159 #define MIN_PARTIAL 5
162 * Maximum number of desirable partial slabs.
163 * The existence of more partial slabs makes kmem_cache_shrink
164 * sort the partial list by the number of objects in the.
166 #define MAX_PARTIAL 10
168 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
169 SLAB_POISON | SLAB_STORE_USER)
172 * Set of flags that will prevent slab merging
174 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
175 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
177 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
178 SLAB_CACHE_DMA)
180 #ifndef ARCH_KMALLOC_MINALIGN
181 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
182 #endif
184 #ifndef ARCH_SLAB_MINALIGN
185 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
186 #endif
188 /* Internal SLUB flags */
189 #define __OBJECT_POISON 0x80000000 /* Poison object */
190 #define __SYSFS_ADD_DEFERRED 0x40000000 /* Not yet visible via sysfs */
192 static int kmem_size = sizeof(struct kmem_cache);
194 #ifdef CONFIG_SMP
195 static struct notifier_block slab_notifier;
196 #endif
198 static enum {
199 DOWN, /* No slab functionality available */
200 PARTIAL, /* kmem_cache_open() works but kmalloc does not */
201 UP, /* Everything works but does not show up in sysfs */
202 SYSFS /* Sysfs up */
203 } slab_state = DOWN;
205 /* A list of all slab caches on the system */
206 static DECLARE_RWSEM(slub_lock);
207 static LIST_HEAD(slab_caches);
210 * Tracking user of a slab.
212 struct track {
213 void *addr; /* Called from address */
214 int cpu; /* Was running on cpu */
215 int pid; /* Pid context */
216 unsigned long when; /* When did the operation occur */
219 enum track_item { TRACK_ALLOC, TRACK_FREE };
221 #ifdef CONFIG_SLUB_DEBUG
222 static int sysfs_slab_add(struct kmem_cache *);
223 static int sysfs_slab_alias(struct kmem_cache *, const char *);
224 static void sysfs_slab_remove(struct kmem_cache *);
226 #else
227 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; }
228 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p)
229 { return 0; }
230 static inline void sysfs_slab_remove(struct kmem_cache *s)
232 kfree(s);
235 #endif
237 static inline void stat(struct kmem_cache_cpu *c, enum stat_item si)
239 #ifdef CONFIG_SLUB_STATS
240 c->stat[si]++;
241 #endif
244 /********************************************************************
245 * Core slab cache functions
246 *******************************************************************/
248 int slab_is_available(void)
250 return slab_state >= UP;
253 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
255 #ifdef CONFIG_NUMA
256 return s->node[node];
257 #else
258 return &s->local_node;
259 #endif
262 static inline struct kmem_cache_cpu *get_cpu_slab(struct kmem_cache *s, int cpu)
264 #ifdef CONFIG_SMP
265 return s->cpu_slab[cpu];
266 #else
267 return &s->cpu_slab;
268 #endif
271 /* Verify that a pointer has an address that is valid within a slab page */
272 static inline int check_valid_pointer(struct kmem_cache *s,
273 struct page *page, const void *object)
275 void *base;
277 if (!object)
278 return 1;
280 base = page_address(page);
281 if (object < base || object >= base + page->objects * s->size ||
282 (object - base) % s->size) {
283 return 0;
286 return 1;
290 * Slow version of get and set free pointer.
292 * This version requires touching the cache lines of kmem_cache which
293 * we avoid to do in the fast alloc free paths. There we obtain the offset
294 * from the page struct.
296 static inline void *get_freepointer(struct kmem_cache *s, void *object)
298 return *(void **)(object + s->offset);
301 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
303 *(void **)(object + s->offset) = fp;
306 /* Loop over all objects in a slab */
307 #define for_each_object(__p, __s, __addr, __objects) \
308 for (__p = (__addr); __p < (__addr) + (__objects) * (__s)->size;\
309 __p += (__s)->size)
311 /* Scan freelist */
312 #define for_each_free_object(__p, __s, __free) \
313 for (__p = (__free); __p; __p = get_freepointer((__s), __p))
315 /* Determine object index from a given position */
316 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
318 return (p - addr) / s->size;
321 static inline struct kmem_cache_order_objects oo_make(int order,
322 unsigned long size)
324 struct kmem_cache_order_objects x = {
325 (order << 16) + (PAGE_SIZE << order) / size
328 return x;
331 static inline int oo_order(struct kmem_cache_order_objects x)
333 return x.x >> 16;
336 static inline int oo_objects(struct kmem_cache_order_objects x)
338 return x.x & ((1 << 16) - 1);
341 #ifdef CONFIG_SLUB_DEBUG
343 * Debug settings:
345 #ifdef CONFIG_SLUB_DEBUG_ON
346 static int slub_debug = DEBUG_DEFAULT_FLAGS;
347 #else
348 static int slub_debug;
349 #endif
351 static char *slub_debug_slabs;
354 * Object debugging
356 static void print_section(char *text, u8 *addr, unsigned int length)
358 int i, offset;
359 int newline = 1;
360 char ascii[17];
362 ascii[16] = 0;
364 for (i = 0; i < length; i++) {
365 if (newline) {
366 printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
367 newline = 0;
369 printk(KERN_CONT " %02x", addr[i]);
370 offset = i % 16;
371 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
372 if (offset == 15) {
373 printk(KERN_CONT " %s\n", ascii);
374 newline = 1;
377 if (!newline) {
378 i %= 16;
379 while (i < 16) {
380 printk(KERN_CONT " ");
381 ascii[i] = ' ';
382 i++;
384 printk(KERN_CONT " %s\n", ascii);
388 static struct track *get_track(struct kmem_cache *s, void *object,
389 enum track_item alloc)
391 struct track *p;
393 if (s->offset)
394 p = object + s->offset + sizeof(void *);
395 else
396 p = object + s->inuse;
398 return p + alloc;
401 static void set_track(struct kmem_cache *s, void *object,
402 enum track_item alloc, void *addr)
404 struct track *p;
406 if (s->offset)
407 p = object + s->offset + sizeof(void *);
408 else
409 p = object + s->inuse;
411 p += alloc;
412 if (addr) {
413 p->addr = addr;
414 p->cpu = smp_processor_id();
415 p->pid = current ? current->pid : -1;
416 p->when = jiffies;
417 } else
418 memset(p, 0, sizeof(struct track));
421 static void init_tracking(struct kmem_cache *s, void *object)
423 if (!(s->flags & SLAB_STORE_USER))
424 return;
426 set_track(s, object, TRACK_FREE, NULL);
427 set_track(s, object, TRACK_ALLOC, NULL);
430 static void print_track(const char *s, struct track *t)
432 if (!t->addr)
433 return;
435 printk(KERN_ERR "INFO: %s in ", s);
436 __print_symbol("%s", (unsigned long)t->addr);
437 printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
440 static void print_tracking(struct kmem_cache *s, void *object)
442 if (!(s->flags & SLAB_STORE_USER))
443 return;
445 print_track("Allocated", get_track(s, object, TRACK_ALLOC));
446 print_track("Freed", get_track(s, object, TRACK_FREE));
449 static void print_page_info(struct page *page)
451 printk(KERN_ERR "INFO: Slab 0x%p objects=%u used=%u fp=0x%p flags=0x%04lx\n",
452 page, page->objects, page->inuse, page->freelist, page->flags);
456 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
458 va_list args;
459 char buf[100];
461 va_start(args, fmt);
462 vsnprintf(buf, sizeof(buf), fmt, args);
463 va_end(args);
464 printk(KERN_ERR "========================================"
465 "=====================================\n");
466 printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
467 printk(KERN_ERR "----------------------------------------"
468 "-------------------------------------\n\n");
471 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
473 va_list args;
474 char buf[100];
476 va_start(args, fmt);
477 vsnprintf(buf, sizeof(buf), fmt, args);
478 va_end(args);
479 printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
482 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
484 unsigned int off; /* Offset of last byte */
485 u8 *addr = page_address(page);
487 print_tracking(s, p);
489 print_page_info(page);
491 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
492 p, p - addr, get_freepointer(s, p));
494 if (p > addr + 16)
495 print_section("Bytes b4", p - 16, 16);
497 print_section("Object", p, min(s->objsize, 128));
499 if (s->flags & SLAB_RED_ZONE)
500 print_section("Redzone", p + s->objsize,
501 s->inuse - s->objsize);
503 if (s->offset)
504 off = s->offset + sizeof(void *);
505 else
506 off = s->inuse;
508 if (s->flags & SLAB_STORE_USER)
509 off += 2 * sizeof(struct track);
511 if (off != s->size)
512 /* Beginning of the filler is the free pointer */
513 print_section("Padding", p + off, s->size - off);
515 dump_stack();
518 static void object_err(struct kmem_cache *s, struct page *page,
519 u8 *object, char *reason)
521 slab_bug(s, "%s", reason);
522 print_trailer(s, page, object);
525 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
527 va_list args;
528 char buf[100];
530 va_start(args, fmt);
531 vsnprintf(buf, sizeof(buf), fmt, args);
532 va_end(args);
533 slab_bug(s, "%s", buf);
534 print_page_info(page);
535 dump_stack();
538 static void init_object(struct kmem_cache *s, void *object, int active)
540 u8 *p = object;
542 if (s->flags & __OBJECT_POISON) {
543 memset(p, POISON_FREE, s->objsize - 1);
544 p[s->objsize - 1] = POISON_END;
547 if (s->flags & SLAB_RED_ZONE)
548 memset(p + s->objsize,
549 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
550 s->inuse - s->objsize);
553 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
555 while (bytes) {
556 if (*start != (u8)value)
557 return start;
558 start++;
559 bytes--;
561 return NULL;
564 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
565 void *from, void *to)
567 slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
568 memset(from, data, to - from);
571 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
572 u8 *object, char *what,
573 u8 *start, unsigned int value, unsigned int bytes)
575 u8 *fault;
576 u8 *end;
578 fault = check_bytes(start, value, bytes);
579 if (!fault)
580 return 1;
582 end = start + bytes;
583 while (end > fault && end[-1] == value)
584 end--;
586 slab_bug(s, "%s overwritten", what);
587 printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
588 fault, end - 1, fault[0], value);
589 print_trailer(s, page, object);
591 restore_bytes(s, what, value, fault, end);
592 return 0;
596 * Object layout:
598 * object address
599 * Bytes of the object to be managed.
600 * If the freepointer may overlay the object then the free
601 * pointer is the first word of the object.
603 * Poisoning uses 0x6b (POISON_FREE) and the last byte is
604 * 0xa5 (POISON_END)
606 * object + s->objsize
607 * Padding to reach word boundary. This is also used for Redzoning.
608 * Padding is extended by another word if Redzoning is enabled and
609 * objsize == inuse.
611 * We fill with 0xbb (RED_INACTIVE) for inactive objects and with
612 * 0xcc (RED_ACTIVE) for objects in use.
614 * object + s->inuse
615 * Meta data starts here.
617 * A. Free pointer (if we cannot overwrite object on free)
618 * B. Tracking data for SLAB_STORE_USER
619 * C. Padding to reach required alignment boundary or at mininum
620 * one word if debugging is on to be able to detect writes
621 * before the word boundary.
623 * Padding is done using 0x5a (POISON_INUSE)
625 * object + s->size
626 * Nothing is used beyond s->size.
628 * If slabcaches are merged then the objsize and inuse boundaries are mostly
629 * ignored. And therefore no slab options that rely on these boundaries
630 * may be used with merged slabcaches.
633 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
635 unsigned long off = s->inuse; /* The end of info */
637 if (s->offset)
638 /* Freepointer is placed after the object. */
639 off += sizeof(void *);
641 if (s->flags & SLAB_STORE_USER)
642 /* We also have user information there */
643 off += 2 * sizeof(struct track);
645 if (s->size == off)
646 return 1;
648 return check_bytes_and_report(s, page, p, "Object padding",
649 p + off, POISON_INUSE, s->size - off);
652 /* Check the pad bytes at the end of a slab page */
653 static int slab_pad_check(struct kmem_cache *s, struct page *page)
655 u8 *start;
656 u8 *fault;
657 u8 *end;
658 int length;
659 int remainder;
661 if (!(s->flags & SLAB_POISON))
662 return 1;
664 start = page_address(page);
665 length = (PAGE_SIZE << compound_order(page));
666 end = start + length;
667 remainder = length % s->size;
668 if (!remainder)
669 return 1;
671 fault = check_bytes(end - remainder, POISON_INUSE, remainder);
672 if (!fault)
673 return 1;
674 while (end > fault && end[-1] == POISON_INUSE)
675 end--;
677 slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
678 print_section("Padding", end - remainder, remainder);
680 restore_bytes(s, "slab padding", POISON_INUSE, start, end);
681 return 0;
684 static int check_object(struct kmem_cache *s, struct page *page,
685 void *object, int active)
687 u8 *p = object;
688 u8 *endobject = object + s->objsize;
690 if (s->flags & SLAB_RED_ZONE) {
691 unsigned int red =
692 active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
694 if (!check_bytes_and_report(s, page, object, "Redzone",
695 endobject, red, s->inuse - s->objsize))
696 return 0;
697 } else {
698 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse) {
699 check_bytes_and_report(s, page, p, "Alignment padding",
700 endobject, POISON_INUSE, s->inuse - s->objsize);
704 if (s->flags & SLAB_POISON) {
705 if (!active && (s->flags & __OBJECT_POISON) &&
706 (!check_bytes_and_report(s, page, p, "Poison", p,
707 POISON_FREE, s->objsize - 1) ||
708 !check_bytes_and_report(s, page, p, "Poison",
709 p + s->objsize - 1, POISON_END, 1)))
710 return 0;
712 * check_pad_bytes cleans up on its own.
714 check_pad_bytes(s, page, p);
717 if (!s->offset && active)
719 * Object and freepointer overlap. Cannot check
720 * freepointer while object is allocated.
722 return 1;
724 /* Check free pointer validity */
725 if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
726 object_err(s, page, p, "Freepointer corrupt");
728 * No choice but to zap it and thus loose the remainder
729 * of the free objects in this slab. May cause
730 * another error because the object count is now wrong.
732 set_freepointer(s, p, NULL);
733 return 0;
735 return 1;
738 static int check_slab(struct kmem_cache *s, struct page *page)
740 int maxobj;
742 VM_BUG_ON(!irqs_disabled());
744 if (!PageSlab(page)) {
745 slab_err(s, page, "Not a valid slab page");
746 return 0;
749 maxobj = (PAGE_SIZE << compound_order(page)) / s->size;
750 if (page->objects > maxobj) {
751 slab_err(s, page, "objects %u > max %u",
752 s->name, page->objects, maxobj);
753 return 0;
755 if (page->inuse > page->objects) {
756 slab_err(s, page, "inuse %u > max %u",
757 s->name, page->inuse, page->objects);
758 return 0;
760 /* Slab_pad_check fixes things up after itself */
761 slab_pad_check(s, page);
762 return 1;
766 * Determine if a certain object on a page is on the freelist. Must hold the
767 * slab lock to guarantee that the chains are in a consistent state.
769 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
771 int nr = 0;
772 void *fp = page->freelist;
773 void *object = NULL;
774 unsigned long max_objects;
776 while (fp && nr <= page->objects) {
777 if (fp == search)
778 return 1;
779 if (!check_valid_pointer(s, page, fp)) {
780 if (object) {
781 object_err(s, page, object,
782 "Freechain corrupt");
783 set_freepointer(s, object, NULL);
784 break;
785 } else {
786 slab_err(s, page, "Freepointer corrupt");
787 page->freelist = NULL;
788 page->inuse = page->objects;
789 slab_fix(s, "Freelist cleared");
790 return 0;
792 break;
794 object = fp;
795 fp = get_freepointer(s, object);
796 nr++;
799 max_objects = (PAGE_SIZE << compound_order(page)) / s->size;
800 if (max_objects > 65535)
801 max_objects = 65535;
803 if (page->objects != max_objects) {
804 slab_err(s, page, "Wrong number of objects. Found %d but "
805 "should be %d", page->objects, max_objects);
806 page->objects = max_objects;
807 slab_fix(s, "Number of objects adjusted.");
809 if (page->inuse != page->objects - nr) {
810 slab_err(s, page, "Wrong object count. Counter is %d but "
811 "counted were %d", page->inuse, page->objects - nr);
812 page->inuse = page->objects - nr;
813 slab_fix(s, "Object count adjusted.");
815 return search == NULL;
818 static void trace(struct kmem_cache *s, struct page *page, void *object,
819 int alloc)
821 if (s->flags & SLAB_TRACE) {
822 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
823 s->name,
824 alloc ? "alloc" : "free",
825 object, page->inuse,
826 page->freelist);
828 if (!alloc)
829 print_section("Object", (void *)object, s->objsize);
831 dump_stack();
836 * Tracking of fully allocated slabs for debugging purposes.
838 static void add_full(struct kmem_cache_node *n, struct page *page)
840 spin_lock(&n->list_lock);
841 list_add(&page->lru, &n->full);
842 spin_unlock(&n->list_lock);
845 static void remove_full(struct kmem_cache *s, struct page *page)
847 struct kmem_cache_node *n;
849 if (!(s->flags & SLAB_STORE_USER))
850 return;
852 n = get_node(s, page_to_nid(page));
854 spin_lock(&n->list_lock);
855 list_del(&page->lru);
856 spin_unlock(&n->list_lock);
859 /* Tracking of the number of slabs for debugging purposes */
860 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
862 struct kmem_cache_node *n = get_node(s, node);
864 return atomic_long_read(&n->nr_slabs);
867 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects)
869 struct kmem_cache_node *n = get_node(s, node);
872 * May be called early in order to allocate a slab for the
873 * kmem_cache_node structure. Solve the chicken-egg
874 * dilemma by deferring the increment of the count during
875 * bootstrap (see early_kmem_cache_node_alloc).
877 if (!NUMA_BUILD || n) {
878 atomic_long_inc(&n->nr_slabs);
879 atomic_long_add(objects, &n->total_objects);
882 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects)
884 struct kmem_cache_node *n = get_node(s, node);
886 atomic_long_dec(&n->nr_slabs);
887 atomic_long_sub(objects, &n->total_objects);
890 /* Object debug checks for alloc/free paths */
891 static void setup_object_debug(struct kmem_cache *s, struct page *page,
892 void *object)
894 if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
895 return;
897 init_object(s, object, 0);
898 init_tracking(s, object);
901 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
902 void *object, void *addr)
904 if (!check_slab(s, page))
905 goto bad;
907 if (!on_freelist(s, page, object)) {
908 object_err(s, page, object, "Object already allocated");
909 goto bad;
912 if (!check_valid_pointer(s, page, object)) {
913 object_err(s, page, object, "Freelist Pointer check fails");
914 goto bad;
917 if (!check_object(s, page, object, 0))
918 goto bad;
920 /* Success perform special debug activities for allocs */
921 if (s->flags & SLAB_STORE_USER)
922 set_track(s, object, TRACK_ALLOC, addr);
923 trace(s, page, object, 1);
924 init_object(s, object, 1);
925 return 1;
927 bad:
928 if (PageSlab(page)) {
930 * If this is a slab page then lets do the best we can
931 * to avoid issues in the future. Marking all objects
932 * as used avoids touching the remaining objects.
934 slab_fix(s, "Marking all objects used");
935 page->inuse = page->objects;
936 page->freelist = NULL;
938 return 0;
941 static int free_debug_processing(struct kmem_cache *s, struct page *page,
942 void *object, void *addr)
944 if (!check_slab(s, page))
945 goto fail;
947 if (!check_valid_pointer(s, page, object)) {
948 slab_err(s, page, "Invalid object pointer 0x%p", object);
949 goto fail;
952 if (on_freelist(s, page, object)) {
953 object_err(s, page, object, "Object already free");
954 goto fail;
957 if (!check_object(s, page, object, 1))
958 return 0;
960 if (unlikely(s != page->slab)) {
961 if (!PageSlab(page)) {
962 slab_err(s, page, "Attempt to free object(0x%p) "
963 "outside of slab", object);
964 } else if (!page->slab) {
965 printk(KERN_ERR
966 "SLUB <none>: no slab for object 0x%p.\n",
967 object);
968 dump_stack();
969 } else
970 object_err(s, page, object,
971 "page slab pointer corrupt.");
972 goto fail;
975 /* Special debug activities for freeing objects */
976 if (!SlabFrozen(page) && !page->freelist)
977 remove_full(s, page);
978 if (s->flags & SLAB_STORE_USER)
979 set_track(s, object, TRACK_FREE, addr);
980 trace(s, page, object, 0);
981 init_object(s, object, 0);
982 return 1;
984 fail:
985 slab_fix(s, "Object at 0x%p not freed", object);
986 return 0;
989 static int __init setup_slub_debug(char *str)
991 slub_debug = DEBUG_DEFAULT_FLAGS;
992 if (*str++ != '=' || !*str)
994 * No options specified. Switch on full debugging.
996 goto out;
998 if (*str == ',')
1000 * No options but restriction on slabs. This means full
1001 * debugging for slabs matching a pattern.
1003 goto check_slabs;
1005 slub_debug = 0;
1006 if (*str == '-')
1008 * Switch off all debugging measures.
1010 goto out;
1013 * Determine which debug features should be switched on
1015 for (; *str && *str != ','; str++) {
1016 switch (tolower(*str)) {
1017 case 'f':
1018 slub_debug |= SLAB_DEBUG_FREE;
1019 break;
1020 case 'z':
1021 slub_debug |= SLAB_RED_ZONE;
1022 break;
1023 case 'p':
1024 slub_debug |= SLAB_POISON;
1025 break;
1026 case 'u':
1027 slub_debug |= SLAB_STORE_USER;
1028 break;
1029 case 't':
1030 slub_debug |= SLAB_TRACE;
1031 break;
1032 default:
1033 printk(KERN_ERR "slub_debug option '%c' "
1034 "unknown. skipped\n", *str);
1038 check_slabs:
1039 if (*str == ',')
1040 slub_debug_slabs = str + 1;
1041 out:
1042 return 1;
1045 __setup("slub_debug", setup_slub_debug);
1047 static unsigned long kmem_cache_flags(unsigned long objsize,
1048 unsigned long flags, const char *name,
1049 void (*ctor)(struct kmem_cache *, void *))
1052 * Enable debugging if selected on the kernel commandline.
1054 if (slub_debug && (!slub_debug_slabs ||
1055 strncmp(slub_debug_slabs, name, strlen(slub_debug_slabs)) == 0))
1056 flags |= slub_debug;
1058 return flags;
1060 #else
1061 static inline void setup_object_debug(struct kmem_cache *s,
1062 struct page *page, void *object) {}
1064 static inline int alloc_debug_processing(struct kmem_cache *s,
1065 struct page *page, void *object, void *addr) { return 0; }
1067 static inline int free_debug_processing(struct kmem_cache *s,
1068 struct page *page, void *object, void *addr) { return 0; }
1070 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1071 { return 1; }
1072 static inline int check_object(struct kmem_cache *s, struct page *page,
1073 void *object, int active) { return 1; }
1074 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1075 static inline unsigned long kmem_cache_flags(unsigned long objsize,
1076 unsigned long flags, const char *name,
1077 void (*ctor)(struct kmem_cache *, void *))
1079 return flags;
1081 #define slub_debug 0
1083 static inline unsigned long slabs_node(struct kmem_cache *s, int node)
1084 { return 0; }
1085 static inline void inc_slabs_node(struct kmem_cache *s, int node,
1086 int objects) {}
1087 static inline void dec_slabs_node(struct kmem_cache *s, int node,
1088 int objects) {}
1089 #endif
1092 * Slab allocation and freeing
1094 static inline struct page *alloc_slab_page(gfp_t flags, int node,
1095 struct kmem_cache_order_objects oo)
1097 int order = oo_order(oo);
1099 if (node == -1)
1100 return alloc_pages(flags, order);
1101 else
1102 return alloc_pages_node(node, flags, order);
1105 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1107 struct page *page;
1108 struct kmem_cache_order_objects oo = s->oo;
1110 flags |= s->allocflags;
1112 page = alloc_slab_page(flags | __GFP_NOWARN | __GFP_NORETRY, node,
1113 oo);
1114 if (unlikely(!page)) {
1115 oo = s->min;
1117 * Allocation may have failed due to fragmentation.
1118 * Try a lower order alloc if possible
1120 page = alloc_slab_page(flags, node, oo);
1121 if (!page)
1122 return NULL;
1124 stat(get_cpu_slab(s, raw_smp_processor_id()), ORDER_FALLBACK);
1126 page->objects = oo_objects(oo);
1127 mod_zone_page_state(page_zone(page),
1128 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1129 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1130 1 << oo_order(oo));
1132 return page;
1135 static void setup_object(struct kmem_cache *s, struct page *page,
1136 void *object)
1138 setup_object_debug(s, page, object);
1139 if (unlikely(s->ctor))
1140 s->ctor(s, object);
1143 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1145 struct page *page;
1146 void *start;
1147 void *last;
1148 void *p;
1150 BUG_ON(flags & GFP_SLAB_BUG_MASK);
1152 page = allocate_slab(s,
1153 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node);
1154 if (!page)
1155 goto out;
1157 inc_slabs_node(s, page_to_nid(page), page->objects);
1158 page->slab = s;
1159 page->flags |= 1 << PG_slab;
1160 if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1161 SLAB_STORE_USER | SLAB_TRACE))
1162 SetSlabDebug(page);
1164 start = page_address(page);
1166 if (unlikely(s->flags & SLAB_POISON))
1167 memset(start, POISON_INUSE, PAGE_SIZE << compound_order(page));
1169 last = start;
1170 for_each_object(p, s, start, page->objects) {
1171 setup_object(s, page, last);
1172 set_freepointer(s, last, p);
1173 last = p;
1175 setup_object(s, page, last);
1176 set_freepointer(s, last, NULL);
1178 page->freelist = start;
1179 page->inuse = 0;
1180 out:
1181 return page;
1184 static void __free_slab(struct kmem_cache *s, struct page *page)
1186 int order = compound_order(page);
1187 int pages = 1 << order;
1189 if (unlikely(SlabDebug(page))) {
1190 void *p;
1192 slab_pad_check(s, page);
1193 for_each_object(p, s, page_address(page),
1194 page->objects)
1195 check_object(s, page, p, 0);
1196 ClearSlabDebug(page);
1199 mod_zone_page_state(page_zone(page),
1200 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1201 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1202 -pages);
1204 __ClearPageSlab(page);
1205 reset_page_mapcount(page);
1206 __free_pages(page, order);
1209 static void rcu_free_slab(struct rcu_head *h)
1211 struct page *page;
1213 page = container_of((struct list_head *)h, struct page, lru);
1214 __free_slab(page->slab, page);
1217 static void free_slab(struct kmem_cache *s, struct page *page)
1219 if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1221 * RCU free overloads the RCU head over the LRU
1223 struct rcu_head *head = (void *)&page->lru;
1225 call_rcu(head, rcu_free_slab);
1226 } else
1227 __free_slab(s, page);
1230 static void discard_slab(struct kmem_cache *s, struct page *page)
1232 dec_slabs_node(s, page_to_nid(page), page->objects);
1233 free_slab(s, page);
1237 * Per slab locking using the pagelock
1239 static __always_inline void slab_lock(struct page *page)
1241 bit_spin_lock(PG_locked, &page->flags);
1244 static __always_inline void slab_unlock(struct page *page)
1246 __bit_spin_unlock(PG_locked, &page->flags);
1249 static __always_inline int slab_trylock(struct page *page)
1251 int rc = 1;
1253 rc = bit_spin_trylock(PG_locked, &page->flags);
1254 return rc;
1258 * Management of partially allocated slabs
1260 static void add_partial(struct kmem_cache_node *n,
1261 struct page *page, int tail)
1263 spin_lock(&n->list_lock);
1264 n->nr_partial++;
1265 if (tail)
1266 list_add_tail(&page->lru, &n->partial);
1267 else
1268 list_add(&page->lru, &n->partial);
1269 spin_unlock(&n->list_lock);
1272 static void remove_partial(struct kmem_cache *s, struct page *page)
1274 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1276 spin_lock(&n->list_lock);
1277 list_del(&page->lru);
1278 n->nr_partial--;
1279 spin_unlock(&n->list_lock);
1283 * Lock slab and remove from the partial list.
1285 * Must hold list_lock.
1287 static inline int lock_and_freeze_slab(struct kmem_cache_node *n,
1288 struct page *page)
1290 if (slab_trylock(page)) {
1291 list_del(&page->lru);
1292 n->nr_partial--;
1293 SetSlabFrozen(page);
1294 return 1;
1296 return 0;
1300 * Try to allocate a partial slab from a specific node.
1302 static struct page *get_partial_node(struct kmem_cache_node *n)
1304 struct page *page;
1307 * Racy check. If we mistakenly see no partial slabs then we
1308 * just allocate an empty slab. If we mistakenly try to get a
1309 * partial slab and there is none available then get_partials()
1310 * will return NULL.
1312 if (!n || !n->nr_partial)
1313 return NULL;
1315 spin_lock(&n->list_lock);
1316 list_for_each_entry(page, &n->partial, lru)
1317 if (lock_and_freeze_slab(n, page))
1318 goto out;
1319 page = NULL;
1320 out:
1321 spin_unlock(&n->list_lock);
1322 return page;
1326 * Get a page from somewhere. Search in increasing NUMA distances.
1328 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1330 #ifdef CONFIG_NUMA
1331 struct zonelist *zonelist;
1332 struct zoneref *z;
1333 struct zone *zone;
1334 enum zone_type high_zoneidx = gfp_zone(flags);
1335 struct page *page;
1338 * The defrag ratio allows a configuration of the tradeoffs between
1339 * inter node defragmentation and node local allocations. A lower
1340 * defrag_ratio increases the tendency to do local allocations
1341 * instead of attempting to obtain partial slabs from other nodes.
1343 * If the defrag_ratio is set to 0 then kmalloc() always
1344 * returns node local objects. If the ratio is higher then kmalloc()
1345 * may return off node objects because partial slabs are obtained
1346 * from other nodes and filled up.
1348 * If /sys/kernel/slab/xx/defrag_ratio is set to 100 (which makes
1349 * defrag_ratio = 1000) then every (well almost) allocation will
1350 * first attempt to defrag slab caches on other nodes. This means
1351 * scanning over all nodes to look for partial slabs which may be
1352 * expensive if we do it every time we are trying to find a slab
1353 * with available objects.
1355 if (!s->remote_node_defrag_ratio ||
1356 get_cycles() % 1024 > s->remote_node_defrag_ratio)
1357 return NULL;
1359 zonelist = node_zonelist(slab_node(current->mempolicy), flags);
1360 for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
1361 struct kmem_cache_node *n;
1363 n = get_node(s, zone_to_nid(zone));
1365 if (n && cpuset_zone_allowed_hardwall(zone, flags) &&
1366 n->nr_partial > MIN_PARTIAL) {
1367 page = get_partial_node(n);
1368 if (page)
1369 return page;
1372 #endif
1373 return NULL;
1377 * Get a partial page, lock it and return it.
1379 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1381 struct page *page;
1382 int searchnode = (node == -1) ? numa_node_id() : node;
1384 page = get_partial_node(get_node(s, searchnode));
1385 if (page || (flags & __GFP_THISNODE))
1386 return page;
1388 return get_any_partial(s, flags);
1392 * Move a page back to the lists.
1394 * Must be called with the slab lock held.
1396 * On exit the slab lock will have been dropped.
1398 static void unfreeze_slab(struct kmem_cache *s, struct page *page, int tail)
1400 struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1401 struct kmem_cache_cpu *c = get_cpu_slab(s, smp_processor_id());
1403 ClearSlabFrozen(page);
1404 if (page->inuse) {
1406 if (page->freelist) {
1407 add_partial(n, page, tail);
1408 stat(c, tail ? DEACTIVATE_TO_TAIL : DEACTIVATE_TO_HEAD);
1409 } else {
1410 stat(c, DEACTIVATE_FULL);
1411 if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1412 add_full(n, page);
1414 slab_unlock(page);
1415 } else {
1416 stat(c, DEACTIVATE_EMPTY);
1417 if (n->nr_partial < MIN_PARTIAL) {
1419 * Adding an empty slab to the partial slabs in order
1420 * to avoid page allocator overhead. This slab needs
1421 * to come after the other slabs with objects in
1422 * so that the others get filled first. That way the
1423 * size of the partial list stays small.
1425 * kmem_cache_shrink can reclaim any empty slabs from
1426 * the partial list.
1428 add_partial(n, page, 1);
1429 slab_unlock(page);
1430 } else {
1431 slab_unlock(page);
1432 stat(get_cpu_slab(s, raw_smp_processor_id()), FREE_SLAB);
1433 discard_slab(s, page);
1439 * Remove the cpu slab
1441 static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1443 struct page *page = c->page;
1444 int tail = 1;
1446 if (page->freelist)
1447 stat(c, DEACTIVATE_REMOTE_FREES);
1449 * Merge cpu freelist into slab freelist. Typically we get here
1450 * because both freelists are empty. So this is unlikely
1451 * to occur.
1453 while (unlikely(c->freelist)) {
1454 void **object;
1456 tail = 0; /* Hot objects. Put the slab first */
1458 /* Retrieve object from cpu_freelist */
1459 object = c->freelist;
1460 c->freelist = c->freelist[c->offset];
1462 /* And put onto the regular freelist */
1463 object[c->offset] = page->freelist;
1464 page->freelist = object;
1465 page->inuse--;
1467 c->page = NULL;
1468 unfreeze_slab(s, page, tail);
1471 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c)
1473 stat(c, CPUSLAB_FLUSH);
1474 slab_lock(c->page);
1475 deactivate_slab(s, c);
1479 * Flush cpu slab.
1481 * Called from IPI handler with interrupts disabled.
1483 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1485 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
1487 if (likely(c && c->page))
1488 flush_slab(s, c);
1491 static void flush_cpu_slab(void *d)
1493 struct kmem_cache *s = d;
1495 __flush_cpu_slab(s, smp_processor_id());
1498 static void flush_all(struct kmem_cache *s)
1500 #ifdef CONFIG_SMP
1501 on_each_cpu(flush_cpu_slab, s, 1, 1);
1502 #else
1503 unsigned long flags;
1505 local_irq_save(flags);
1506 flush_cpu_slab(s);
1507 local_irq_restore(flags);
1508 #endif
1512 * Check if the objects in a per cpu structure fit numa
1513 * locality expectations.
1515 static inline int node_match(struct kmem_cache_cpu *c, int node)
1517 #ifdef CONFIG_NUMA
1518 if (node != -1 && c->node != node)
1519 return 0;
1520 #endif
1521 return 1;
1525 * Slow path. The lockless freelist is empty or we need to perform
1526 * debugging duties.
1528 * Interrupts are disabled.
1530 * Processing is still very fast if new objects have been freed to the
1531 * regular freelist. In that case we simply take over the regular freelist
1532 * as the lockless freelist and zap the regular freelist.
1534 * If that is not working then we fall back to the partial lists. We take the
1535 * first element of the freelist as the object to allocate now and move the
1536 * rest of the freelist to the lockless freelist.
1538 * And if we were unable to get a new slab from the partial slab lists then
1539 * we need to allocate a new slab. This is the slowest path since it involves
1540 * a call to the page allocator and the setup of a new slab.
1542 static void *__slab_alloc(struct kmem_cache *s,
1543 gfp_t gfpflags, int node, void *addr, struct kmem_cache_cpu *c)
1545 void **object;
1546 struct page *new;
1548 /* We handle __GFP_ZERO in the caller */
1549 gfpflags &= ~__GFP_ZERO;
1551 if (!c->page)
1552 goto new_slab;
1554 slab_lock(c->page);
1555 if (unlikely(!node_match(c, node)))
1556 goto another_slab;
1558 stat(c, ALLOC_REFILL);
1560 load_freelist:
1561 object = c->page->freelist;
1562 if (unlikely(!object))
1563 goto another_slab;
1564 if (unlikely(SlabDebug(c->page)))
1565 goto debug;
1567 c->freelist = object[c->offset];
1568 c->page->inuse = c->page->objects;
1569 c->page->freelist = NULL;
1570 c->node = page_to_nid(c->page);
1571 unlock_out:
1572 slab_unlock(c->page);
1573 stat(c, ALLOC_SLOWPATH);
1574 return object;
1576 another_slab:
1577 deactivate_slab(s, c);
1579 new_slab:
1580 new = get_partial(s, gfpflags, node);
1581 if (new) {
1582 c->page = new;
1583 stat(c, ALLOC_FROM_PARTIAL);
1584 goto load_freelist;
1587 if (gfpflags & __GFP_WAIT)
1588 local_irq_enable();
1590 new = new_slab(s, gfpflags, node);
1592 if (gfpflags & __GFP_WAIT)
1593 local_irq_disable();
1595 if (new) {
1596 c = get_cpu_slab(s, smp_processor_id());
1597 stat(c, ALLOC_SLAB);
1598 if (c->page)
1599 flush_slab(s, c);
1600 slab_lock(new);
1601 SetSlabFrozen(new);
1602 c->page = new;
1603 goto load_freelist;
1605 return NULL;
1606 debug:
1607 if (!alloc_debug_processing(s, c->page, object, addr))
1608 goto another_slab;
1610 c->page->inuse++;
1611 c->page->freelist = object[c->offset];
1612 c->node = -1;
1613 goto unlock_out;
1617 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1618 * have the fastpath folded into their functions. So no function call
1619 * overhead for requests that can be satisfied on the fastpath.
1621 * The fastpath works by first checking if the lockless freelist can be used.
1622 * If not then __slab_alloc is called for slow processing.
1624 * Otherwise we can simply pick the next object from the lockless free list.
1626 static __always_inline void *slab_alloc(struct kmem_cache *s,
1627 gfp_t gfpflags, int node, void *addr)
1629 void **object;
1630 struct kmem_cache_cpu *c;
1631 unsigned long flags;
1632 unsigned int objsize;
1634 local_irq_save(flags);
1635 c = get_cpu_slab(s, smp_processor_id());
1636 objsize = c->objsize;
1637 if (unlikely(!c->freelist || !node_match(c, node)))
1639 object = __slab_alloc(s, gfpflags, node, addr, c);
1641 else {
1642 object = c->freelist;
1643 c->freelist = object[c->offset];
1644 stat(c, ALLOC_FASTPATH);
1646 local_irq_restore(flags);
1648 if (unlikely((gfpflags & __GFP_ZERO) && object))
1649 memset(object, 0, objsize);
1651 return object;
1654 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1656 void *ret = slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1658 kmemtrace_mark_alloc(KMEMTRACE_TYPE_CACHE, _RET_IP_, ret,
1659 s->objsize, s->size, gfpflags);
1661 return ret;
1663 EXPORT_SYMBOL(kmem_cache_alloc);
1665 #ifdef CONFIG_KMEMTRACE
1666 void *kmem_cache_alloc_notrace(struct kmem_cache *s, gfp_t gfpflags)
1668 return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1670 EXPORT_SYMBOL(kmem_cache_alloc_notrace);
1671 #endif
1673 #ifdef CONFIG_NUMA
1674 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1676 void *ret = slab_alloc(s, gfpflags, node,
1677 __builtin_return_address(0));
1679 kmemtrace_mark_alloc_node(KMEMTRACE_TYPE_CACHE, _RET_IP_, ret,
1680 s->objsize, s->size, gfpflags, node);
1682 return ret;
1684 EXPORT_SYMBOL(kmem_cache_alloc_node);
1685 #endif
1687 #ifdef CONFIG_KMEMTRACE
1688 void *kmem_cache_alloc_node_notrace(struct kmem_cache *s,
1689 gfp_t gfpflags,
1690 int node)
1692 return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1694 EXPORT_SYMBOL(kmem_cache_alloc_node_notrace);
1695 #endif
1698 * Slow patch handling. This may still be called frequently since objects
1699 * have a longer lifetime than the cpu slabs in most processing loads.
1701 * So we still attempt to reduce cache line usage. Just take the slab
1702 * lock and free the item. If there is no additional partial page
1703 * handling required then we can return immediately.
1705 static void __slab_free(struct kmem_cache *s, struct page *page,
1706 void *x, void *addr, unsigned int offset)
1708 void *prior;
1709 void **object = (void *)x;
1710 struct kmem_cache_cpu *c;
1712 c = get_cpu_slab(s, raw_smp_processor_id());
1713 stat(c, FREE_SLOWPATH);
1714 slab_lock(page);
1716 if (unlikely(SlabDebug(page)))
1717 goto debug;
1719 checks_ok:
1720 prior = object[offset] = page->freelist;
1721 page->freelist = object;
1722 page->inuse--;
1724 if (unlikely(SlabFrozen(page))) {
1725 stat(c, FREE_FROZEN);
1726 goto out_unlock;
1729 if (unlikely(!page->inuse))
1730 goto slab_empty;
1733 * Objects left in the slab. If it was not on the partial list before
1734 * then add it.
1736 if (unlikely(!prior)) {
1737 add_partial(get_node(s, page_to_nid(page)), page, 1);
1738 stat(c, FREE_ADD_PARTIAL);
1741 out_unlock:
1742 slab_unlock(page);
1743 return;
1745 slab_empty:
1746 if (prior) {
1748 * Slab still on the partial list.
1750 remove_partial(s, page);
1751 stat(c, FREE_REMOVE_PARTIAL);
1753 slab_unlock(page);
1754 stat(c, FREE_SLAB);
1755 discard_slab(s, page);
1756 return;
1758 debug:
1759 if (!free_debug_processing(s, page, x, addr))
1760 goto out_unlock;
1761 goto checks_ok;
1765 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1766 * can perform fastpath freeing without additional function calls.
1768 * The fastpath is only possible if we are freeing to the current cpu slab
1769 * of this processor. This typically the case if we have just allocated
1770 * the item before.
1772 * If fastpath is not possible then fall back to __slab_free where we deal
1773 * with all sorts of special processing.
1775 static __always_inline void slab_free(struct kmem_cache *s,
1776 struct page *page, void *x, void *addr)
1778 void **object = (void *)x;
1779 struct kmem_cache_cpu *c;
1780 unsigned long flags;
1782 local_irq_save(flags);
1783 c = get_cpu_slab(s, smp_processor_id());
1784 debug_check_no_locks_freed(object, c->objsize);
1785 if (!(s->flags & SLAB_DEBUG_OBJECTS))
1786 debug_check_no_obj_freed(object, s->objsize);
1787 if (likely(page == c->page && c->node >= 0)) {
1788 object[c->offset] = c->freelist;
1789 c->freelist = object;
1790 stat(c, FREE_FASTPATH);
1791 } else
1792 __slab_free(s, page, x, addr, c->offset);
1794 local_irq_restore(flags);
1797 void kmem_cache_free(struct kmem_cache *s, void *x)
1799 struct page *page;
1801 page = virt_to_head_page(x);
1803 slab_free(s, page, x, __builtin_return_address(0));
1805 kmemtrace_mark_free(KMEMTRACE_TYPE_CACHE, _RET_IP_, x);
1807 EXPORT_SYMBOL(kmem_cache_free);
1809 /* Figure out on which slab object the object resides */
1810 static struct page *get_object_page(const void *x)
1812 struct page *page = virt_to_head_page(x);
1814 if (!PageSlab(page))
1815 return NULL;
1817 return page;
1821 * Object placement in a slab is made very easy because we always start at
1822 * offset 0. If we tune the size of the object to the alignment then we can
1823 * get the required alignment by putting one properly sized object after
1824 * another.
1826 * Notice that the allocation order determines the sizes of the per cpu
1827 * caches. Each processor has always one slab available for allocations.
1828 * Increasing the allocation order reduces the number of times that slabs
1829 * must be moved on and off the partial lists and is therefore a factor in
1830 * locking overhead.
1834 * Mininum / Maximum order of slab pages. This influences locking overhead
1835 * and slab fragmentation. A higher order reduces the number of partial slabs
1836 * and increases the number of allocations possible without having to
1837 * take the list_lock.
1839 static int slub_min_order;
1840 static int slub_max_order = PAGE_ALLOC_COSTLY_ORDER;
1841 static int slub_min_objects;
1844 * Merge control. If this is set then no merging of slab caches will occur.
1845 * (Could be removed. This was introduced to pacify the merge skeptics.)
1847 static int slub_nomerge;
1850 * Calculate the order of allocation given an slab object size.
1852 * The order of allocation has significant impact on performance and other
1853 * system components. Generally order 0 allocations should be preferred since
1854 * order 0 does not cause fragmentation in the page allocator. Larger objects
1855 * be problematic to put into order 0 slabs because there may be too much
1856 * unused space left. We go to a higher order if more than 1/16th of the slab
1857 * would be wasted.
1859 * In order to reach satisfactory performance we must ensure that a minimum
1860 * number of objects is in one slab. Otherwise we may generate too much
1861 * activity on the partial lists which requires taking the list_lock. This is
1862 * less a concern for large slabs though which are rarely used.
1864 * slub_max_order specifies the order where we begin to stop considering the
1865 * number of objects in a slab as critical. If we reach slub_max_order then
1866 * we try to keep the page order as low as possible. So we accept more waste
1867 * of space in favor of a small page order.
1869 * Higher order allocations also allow the placement of more objects in a
1870 * slab and thereby reduce object handling overhead. If the user has
1871 * requested a higher mininum order then we start with that one instead of
1872 * the smallest order which will fit the object.
1874 static inline int slab_order(int size, int min_objects,
1875 int max_order, int fract_leftover)
1877 int order;
1878 int rem;
1879 int min_order = slub_min_order;
1881 if ((PAGE_SIZE << min_order) / size > 65535)
1882 return get_order(size * 65535) - 1;
1884 for (order = max(min_order,
1885 fls(min_objects * size - 1) - PAGE_SHIFT);
1886 order <= max_order; order++) {
1888 unsigned long slab_size = PAGE_SIZE << order;
1890 if (slab_size < min_objects * size)
1891 continue;
1893 rem = slab_size % size;
1895 if (rem <= slab_size / fract_leftover)
1896 break;
1900 return order;
1903 static inline int calculate_order(int size)
1905 int order;
1906 int min_objects;
1907 int fraction;
1910 * Attempt to find best configuration for a slab. This
1911 * works by first attempting to generate a layout with
1912 * the best configuration and backing off gradually.
1914 * First we reduce the acceptable waste in a slab. Then
1915 * we reduce the minimum objects required in a slab.
1917 min_objects = slub_min_objects;
1918 if (!min_objects)
1919 min_objects = 4 * (fls(nr_cpu_ids) + 1);
1920 while (min_objects > 1) {
1921 fraction = 16;
1922 while (fraction >= 4) {
1923 order = slab_order(size, min_objects,
1924 slub_max_order, fraction);
1925 if (order <= slub_max_order)
1926 return order;
1927 fraction /= 2;
1929 min_objects /= 2;
1933 * We were unable to place multiple objects in a slab. Now
1934 * lets see if we can place a single object there.
1936 order = slab_order(size, 1, slub_max_order, 1);
1937 if (order <= slub_max_order)
1938 return order;
1941 * Doh this slab cannot be placed using slub_max_order.
1943 order = slab_order(size, 1, MAX_ORDER, 1);
1944 if (order <= MAX_ORDER)
1945 return order;
1946 return -ENOSYS;
1950 * Figure out what the alignment of the objects will be.
1952 static unsigned long calculate_alignment(unsigned long flags,
1953 unsigned long align, unsigned long size)
1956 * If the user wants hardware cache aligned objects then follow that
1957 * suggestion if the object is sufficiently large.
1959 * The hardware cache alignment cannot override the specified
1960 * alignment though. If that is greater then use it.
1962 if (flags & SLAB_HWCACHE_ALIGN) {
1963 unsigned long ralign = cache_line_size();
1964 while (size <= ralign / 2)
1965 ralign /= 2;
1966 align = max(align, ralign);
1969 if (align < ARCH_SLAB_MINALIGN)
1970 align = ARCH_SLAB_MINALIGN;
1972 return ALIGN(align, sizeof(void *));
1975 static void init_kmem_cache_cpu(struct kmem_cache *s,
1976 struct kmem_cache_cpu *c)
1978 c->page = NULL;
1979 c->freelist = NULL;
1980 c->node = 0;
1981 c->offset = s->offset / sizeof(void *);
1982 c->objsize = s->objsize;
1983 #ifdef CONFIG_SLUB_STATS
1984 memset(c->stat, 0, NR_SLUB_STAT_ITEMS * sizeof(unsigned));
1985 #endif
1988 static void init_kmem_cache_node(struct kmem_cache_node *n)
1990 n->nr_partial = 0;
1991 spin_lock_init(&n->list_lock);
1992 INIT_LIST_HEAD(&n->partial);
1993 #ifdef CONFIG_SLUB_DEBUG
1994 atomic_long_set(&n->nr_slabs, 0);
1995 INIT_LIST_HEAD(&n->full);
1996 #endif
1999 #ifdef CONFIG_SMP
2001 * Per cpu array for per cpu structures.
2003 * The per cpu array places all kmem_cache_cpu structures from one processor
2004 * close together meaning that it becomes possible that multiple per cpu
2005 * structures are contained in one cacheline. This may be particularly
2006 * beneficial for the kmalloc caches.
2008 * A desktop system typically has around 60-80 slabs. With 100 here we are
2009 * likely able to get per cpu structures for all caches from the array defined
2010 * here. We must be able to cover all kmalloc caches during bootstrap.
2012 * If the per cpu array is exhausted then fall back to kmalloc
2013 * of individual cachelines. No sharing is possible then.
2015 #define NR_KMEM_CACHE_CPU 100
2017 static DEFINE_PER_CPU(struct kmem_cache_cpu,
2018 kmem_cache_cpu)[NR_KMEM_CACHE_CPU];
2020 static DEFINE_PER_CPU(struct kmem_cache_cpu *, kmem_cache_cpu_free);
2021 static cpumask_t kmem_cach_cpu_free_init_once = CPU_MASK_NONE;
2023 static struct kmem_cache_cpu *alloc_kmem_cache_cpu(struct kmem_cache *s,
2024 int cpu, gfp_t flags)
2026 struct kmem_cache_cpu *c = per_cpu(kmem_cache_cpu_free, cpu);
2028 if (c)
2029 per_cpu(kmem_cache_cpu_free, cpu) =
2030 (void *)c->freelist;
2031 else {
2032 /* Table overflow: So allocate ourselves */
2033 c = kmalloc_node(
2034 ALIGN(sizeof(struct kmem_cache_cpu), cache_line_size()),
2035 flags, cpu_to_node(cpu));
2036 if (!c)
2037 return NULL;
2040 init_kmem_cache_cpu(s, c);
2041 return c;
2044 static void free_kmem_cache_cpu(struct kmem_cache_cpu *c, int cpu)
2046 if (c < per_cpu(kmem_cache_cpu, cpu) ||
2047 c > per_cpu(kmem_cache_cpu, cpu) + NR_KMEM_CACHE_CPU) {
2048 kfree(c);
2049 return;
2051 c->freelist = (void *)per_cpu(kmem_cache_cpu_free, cpu);
2052 per_cpu(kmem_cache_cpu_free, cpu) = c;
2055 static void free_kmem_cache_cpus(struct kmem_cache *s)
2057 int cpu;
2059 for_each_online_cpu(cpu) {
2060 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2062 if (c) {
2063 s->cpu_slab[cpu] = NULL;
2064 free_kmem_cache_cpu(c, cpu);
2069 static int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2071 int cpu;
2073 for_each_online_cpu(cpu) {
2074 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
2076 if (c)
2077 continue;
2079 c = alloc_kmem_cache_cpu(s, cpu, flags);
2080 if (!c) {
2081 free_kmem_cache_cpus(s);
2082 return 0;
2084 s->cpu_slab[cpu] = c;
2086 return 1;
2090 * Initialize the per cpu array.
2092 static void init_alloc_cpu_cpu(int cpu)
2094 int i;
2096 if (cpu_isset(cpu, kmem_cach_cpu_free_init_once))
2097 return;
2099 for (i = NR_KMEM_CACHE_CPU - 1; i >= 0; i--)
2100 free_kmem_cache_cpu(&per_cpu(kmem_cache_cpu, cpu)[i], cpu);
2102 cpu_set(cpu, kmem_cach_cpu_free_init_once);
2105 static void __init init_alloc_cpu(void)
2107 int cpu;
2109 for_each_online_cpu(cpu)
2110 init_alloc_cpu_cpu(cpu);
2113 #else
2114 static inline void free_kmem_cache_cpus(struct kmem_cache *s) {}
2115 static inline void init_alloc_cpu(void) {}
2117 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s, gfp_t flags)
2119 init_kmem_cache_cpu(s, &s->cpu_slab);
2120 return 1;
2122 #endif
2124 #ifdef CONFIG_NUMA
2126 * No kmalloc_node yet so do it by hand. We know that this is the first
2127 * slab on the node for this slabcache. There are no concurrent accesses
2128 * possible.
2130 * Note that this function only works on the kmalloc_node_cache
2131 * when allocating for the kmalloc_node_cache. This is used for bootstrapping
2132 * memory on a fresh node that has no slab structures yet.
2134 static struct kmem_cache_node *early_kmem_cache_node_alloc(gfp_t gfpflags,
2135 int node)
2137 struct page *page;
2138 struct kmem_cache_node *n;
2139 unsigned long flags;
2141 BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
2143 page = new_slab(kmalloc_caches, gfpflags, node);
2145 BUG_ON(!page);
2146 if (page_to_nid(page) != node) {
2147 printk(KERN_ERR "SLUB: Unable to allocate memory from "
2148 "node %d\n", node);
2149 printk(KERN_ERR "SLUB: Allocating a useless per node structure "
2150 "in order to be able to continue\n");
2153 n = page->freelist;
2154 BUG_ON(!n);
2155 page->freelist = get_freepointer(kmalloc_caches, n);
2156 page->inuse++;
2157 kmalloc_caches->node[node] = n;
2158 #ifdef CONFIG_SLUB_DEBUG
2159 init_object(kmalloc_caches, n, 1);
2160 init_tracking(kmalloc_caches, n);
2161 #endif
2162 init_kmem_cache_node(n);
2163 inc_slabs_node(kmalloc_caches, node, page->objects);
2166 * lockdep requires consistent irq usage for each lock
2167 * so even though there cannot be a race this early in
2168 * the boot sequence, we still disable irqs.
2170 local_irq_save(flags);
2171 add_partial(n, page, 0);
2172 local_irq_restore(flags);
2173 return n;
2176 static void free_kmem_cache_nodes(struct kmem_cache *s)
2178 int node;
2180 for_each_node_state(node, N_NORMAL_MEMORY) {
2181 struct kmem_cache_node *n = s->node[node];
2182 if (n && n != &s->local_node)
2183 kmem_cache_free(kmalloc_caches, n);
2184 s->node[node] = NULL;
2188 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2190 int node;
2191 int local_node;
2193 if (slab_state >= UP)
2194 local_node = page_to_nid(virt_to_page(s));
2195 else
2196 local_node = 0;
2198 for_each_node_state(node, N_NORMAL_MEMORY) {
2199 struct kmem_cache_node *n;
2201 if (local_node == node)
2202 n = &s->local_node;
2203 else {
2204 if (slab_state == DOWN) {
2205 n = early_kmem_cache_node_alloc(gfpflags,
2206 node);
2207 continue;
2209 n = kmem_cache_alloc_node(kmalloc_caches,
2210 gfpflags, node);
2212 if (!n) {
2213 free_kmem_cache_nodes(s);
2214 return 0;
2218 s->node[node] = n;
2219 init_kmem_cache_node(n);
2221 return 1;
2223 #else
2224 static void free_kmem_cache_nodes(struct kmem_cache *s)
2228 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
2230 init_kmem_cache_node(&s->local_node);
2231 return 1;
2233 #endif
2236 * calculate_sizes() determines the order and the distribution of data within
2237 * a slab object.
2239 static int calculate_sizes(struct kmem_cache *s, int forced_order)
2241 unsigned long flags = s->flags;
2242 unsigned long size = s->objsize;
2243 unsigned long align = s->align;
2244 int order;
2247 * Round up object size to the next word boundary. We can only
2248 * place the free pointer at word boundaries and this determines
2249 * the possible location of the free pointer.
2251 size = ALIGN(size, sizeof(void *));
2253 #ifdef CONFIG_SLUB_DEBUG
2255 * Determine if we can poison the object itself. If the user of
2256 * the slab may touch the object after free or before allocation
2257 * then we should never poison the object itself.
2259 if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
2260 !s->ctor)
2261 s->flags |= __OBJECT_POISON;
2262 else
2263 s->flags &= ~__OBJECT_POISON;
2267 * If we are Redzoning then check if there is some space between the
2268 * end of the object and the free pointer. If not then add an
2269 * additional word to have some bytes to store Redzone information.
2271 if ((flags & SLAB_RED_ZONE) && size == s->objsize)
2272 size += sizeof(void *);
2273 #endif
2276 * With that we have determined the number of bytes in actual use
2277 * by the object. This is the potential offset to the free pointer.
2279 s->inuse = size;
2281 if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
2282 s->ctor)) {
2284 * Relocate free pointer after the object if it is not
2285 * permitted to overwrite the first word of the object on
2286 * kmem_cache_free.
2288 * This is the case if we do RCU, have a constructor or
2289 * destructor or are poisoning the objects.
2291 s->offset = size;
2292 size += sizeof(void *);
2295 #ifdef CONFIG_SLUB_DEBUG
2296 if (flags & SLAB_STORE_USER)
2298 * Need to store information about allocs and frees after
2299 * the object.
2301 size += 2 * sizeof(struct track);
2303 if (flags & SLAB_RED_ZONE)
2305 * Add some empty padding so that we can catch
2306 * overwrites from earlier objects rather than let
2307 * tracking information or the free pointer be
2308 * corrupted if an user writes before the start
2309 * of the object.
2311 size += sizeof(void *);
2312 #endif
2315 * Determine the alignment based on various parameters that the
2316 * user specified and the dynamic determination of cache line size
2317 * on bootup.
2319 align = calculate_alignment(flags, align, s->objsize);
2322 * SLUB stores one object immediately after another beginning from
2323 * offset 0. In order to align the objects we have to simply size
2324 * each object to conform to the alignment.
2326 size = ALIGN(size, align);
2327 s->size = size;
2328 if (forced_order >= 0)
2329 order = forced_order;
2330 else
2331 order = calculate_order(size);
2333 if (order < 0)
2334 return 0;
2336 s->allocflags = 0;
2337 if (order)
2338 s->allocflags |= __GFP_COMP;
2340 if (s->flags & SLAB_CACHE_DMA)
2341 s->allocflags |= SLUB_DMA;
2343 if (s->flags & SLAB_RECLAIM_ACCOUNT)
2344 s->allocflags |= __GFP_RECLAIMABLE;
2347 * Determine the number of objects per slab
2349 s->oo = oo_make(order, size);
2350 s->min = oo_make(get_order(size), size);
2351 if (oo_objects(s->oo) > oo_objects(s->max))
2352 s->max = s->oo;
2354 return !!oo_objects(s->oo);
2358 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2359 const char *name, size_t size,
2360 size_t align, unsigned long flags,
2361 void (*ctor)(struct kmem_cache *, void *))
2363 memset(s, 0, kmem_size);
2364 s->name = name;
2365 s->ctor = ctor;
2366 s->objsize = size;
2367 s->align = align;
2368 s->flags = kmem_cache_flags(size, flags, name, ctor);
2370 if (!calculate_sizes(s, -1))
2371 goto error;
2373 s->refcount = 1;
2374 #ifdef CONFIG_NUMA
2375 s->remote_node_defrag_ratio = 100;
2376 #endif
2377 if (!init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2378 goto error;
2380 if (alloc_kmem_cache_cpus(s, gfpflags & ~SLUB_DMA))
2381 return 1;
2382 free_kmem_cache_nodes(s);
2383 error:
2384 if (flags & SLAB_PANIC)
2385 panic("Cannot create slab %s size=%lu realsize=%u "
2386 "order=%u offset=%u flags=%lx\n",
2387 s->name, (unsigned long)size, s->size, oo_order(s->oo),
2388 s->offset, flags);
2389 return 0;
2393 * Check if a given pointer is valid
2395 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2397 struct page *page;
2399 page = get_object_page(object);
2401 if (!page || s != page->slab)
2402 /* No slab or wrong slab */
2403 return 0;
2405 if (!check_valid_pointer(s, page, object))
2406 return 0;
2409 * We could also check if the object is on the slabs freelist.
2410 * But this would be too expensive and it seems that the main
2411 * purpose of kmem_ptr_valid() is to check if the object belongs
2412 * to a certain slab.
2414 return 1;
2416 EXPORT_SYMBOL(kmem_ptr_validate);
2419 * Determine the size of a slab object
2421 unsigned int kmem_cache_size(struct kmem_cache *s)
2423 return s->objsize;
2425 EXPORT_SYMBOL(kmem_cache_size);
2427 const char *kmem_cache_name(struct kmem_cache *s)
2429 return s->name;
2431 EXPORT_SYMBOL(kmem_cache_name);
2433 static void list_slab_objects(struct kmem_cache *s, struct page *page,
2434 const char *text)
2436 #ifdef CONFIG_SLUB_DEBUG
2437 void *addr = page_address(page);
2438 void *p;
2439 DECLARE_BITMAP(map, page->objects);
2441 bitmap_zero(map, page->objects);
2442 slab_err(s, page, "%s", text);
2443 slab_lock(page);
2444 for_each_free_object(p, s, page->freelist)
2445 set_bit(slab_index(p, s, addr), map);
2447 for_each_object(p, s, addr, page->objects) {
2449 if (!test_bit(slab_index(p, s, addr), map)) {
2450 printk(KERN_ERR "INFO: Object 0x%p @offset=%tu\n",
2451 p, p - addr);
2452 print_tracking(s, p);
2455 slab_unlock(page);
2456 #endif
2460 * Attempt to free all partial slabs on a node.
2462 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
2464 unsigned long flags;
2465 struct page *page, *h;
2467 spin_lock_irqsave(&n->list_lock, flags);
2468 list_for_each_entry_safe(page, h, &n->partial, lru) {
2469 if (!page->inuse) {
2470 list_del(&page->lru);
2471 discard_slab(s, page);
2472 n->nr_partial--;
2473 } else {
2474 list_slab_objects(s, page,
2475 "Objects remaining on kmem_cache_close()");
2478 spin_unlock_irqrestore(&n->list_lock, flags);
2482 * Release all resources used by a slab cache.
2484 static inline int kmem_cache_close(struct kmem_cache *s)
2486 int node;
2488 flush_all(s);
2490 /* Attempt to free all objects */
2491 free_kmem_cache_cpus(s);
2492 for_each_node_state(node, N_NORMAL_MEMORY) {
2493 struct kmem_cache_node *n = get_node(s, node);
2495 free_partial(s, n);
2496 if (n->nr_partial || slabs_node(s, node))
2497 return 1;
2499 free_kmem_cache_nodes(s);
2500 return 0;
2504 * Close a cache and release the kmem_cache structure
2505 * (must be used for caches created using kmem_cache_create)
2507 void kmem_cache_destroy(struct kmem_cache *s)
2509 down_write(&slub_lock);
2510 s->refcount--;
2511 if (!s->refcount) {
2512 list_del(&s->list);
2513 up_write(&slub_lock);
2514 if (kmem_cache_close(s)) {
2515 printk(KERN_ERR "SLUB %s: %s called for cache that "
2516 "still has objects.\n", s->name, __func__);
2517 dump_stack();
2519 sysfs_slab_remove(s);
2520 } else
2521 up_write(&slub_lock);
2523 EXPORT_SYMBOL(kmem_cache_destroy);
2525 /********************************************************************
2526 * Kmalloc subsystem
2527 *******************************************************************/
2529 struct kmem_cache kmalloc_caches[PAGE_SHIFT + 1] __cacheline_aligned;
2530 EXPORT_SYMBOL(kmalloc_caches);
2532 static int __init setup_slub_min_order(char *str)
2534 get_option(&str, &slub_min_order);
2536 return 1;
2539 __setup("slub_min_order=", setup_slub_min_order);
2541 static int __init setup_slub_max_order(char *str)
2543 get_option(&str, &slub_max_order);
2545 return 1;
2548 __setup("slub_max_order=", setup_slub_max_order);
2550 static int __init setup_slub_min_objects(char *str)
2552 get_option(&str, &slub_min_objects);
2554 return 1;
2557 __setup("slub_min_objects=", setup_slub_min_objects);
2559 static int __init setup_slub_nomerge(char *str)
2561 slub_nomerge = 1;
2562 return 1;
2565 __setup("slub_nomerge", setup_slub_nomerge);
2567 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2568 const char *name, int size, gfp_t gfp_flags)
2570 unsigned int flags = 0;
2572 if (gfp_flags & SLUB_DMA)
2573 flags = SLAB_CACHE_DMA;
2575 down_write(&slub_lock);
2576 if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2577 flags, NULL))
2578 goto panic;
2580 list_add(&s->list, &slab_caches);
2581 up_write(&slub_lock);
2582 if (sysfs_slab_add(s))
2583 goto panic;
2584 return s;
2586 panic:
2587 panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2590 #ifdef CONFIG_ZONE_DMA
2591 static struct kmem_cache *kmalloc_caches_dma[PAGE_SHIFT + 1];
2593 static void sysfs_add_func(struct work_struct *w)
2595 struct kmem_cache *s;
2597 down_write(&slub_lock);
2598 list_for_each_entry(s, &slab_caches, list) {
2599 if (s->flags & __SYSFS_ADD_DEFERRED) {
2600 s->flags &= ~__SYSFS_ADD_DEFERRED;
2601 sysfs_slab_add(s);
2604 up_write(&slub_lock);
2607 static DECLARE_WORK(sysfs_add_work, sysfs_add_func);
2609 static noinline struct kmem_cache *dma_kmalloc_cache(int index, gfp_t flags)
2611 struct kmem_cache *s;
2612 char *text;
2613 size_t realsize;
2615 s = kmalloc_caches_dma[index];
2616 if (s)
2617 return s;
2619 /* Dynamically create dma cache */
2620 if (flags & __GFP_WAIT)
2621 down_write(&slub_lock);
2622 else {
2623 if (!down_write_trylock(&slub_lock))
2624 goto out;
2627 if (kmalloc_caches_dma[index])
2628 goto unlock_out;
2630 realsize = kmalloc_caches[index].objsize;
2631 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2632 (unsigned int)realsize);
2633 s = kmalloc(kmem_size, flags & ~SLUB_DMA);
2635 if (!s || !text || !kmem_cache_open(s, flags, text,
2636 realsize, ARCH_KMALLOC_MINALIGN,
2637 SLAB_CACHE_DMA|__SYSFS_ADD_DEFERRED, NULL)) {
2638 kfree(s);
2639 kfree(text);
2640 goto unlock_out;
2643 list_add(&s->list, &slab_caches);
2644 kmalloc_caches_dma[index] = s;
2646 schedule_work(&sysfs_add_work);
2648 unlock_out:
2649 up_write(&slub_lock);
2650 out:
2651 return kmalloc_caches_dma[index];
2653 #endif
2656 * Conversion table for small slabs sizes / 8 to the index in the
2657 * kmalloc array. This is necessary for slabs < 192 since we have non power
2658 * of two cache sizes there. The size of larger slabs can be determined using
2659 * fls.
2661 static s8 size_index[24] = {
2662 3, /* 8 */
2663 4, /* 16 */
2664 5, /* 24 */
2665 5, /* 32 */
2666 6, /* 40 */
2667 6, /* 48 */
2668 6, /* 56 */
2669 6, /* 64 */
2670 1, /* 72 */
2671 1, /* 80 */
2672 1, /* 88 */
2673 1, /* 96 */
2674 7, /* 104 */
2675 7, /* 112 */
2676 7, /* 120 */
2677 7, /* 128 */
2678 2, /* 136 */
2679 2, /* 144 */
2680 2, /* 152 */
2681 2, /* 160 */
2682 2, /* 168 */
2683 2, /* 176 */
2684 2, /* 184 */
2685 2 /* 192 */
2688 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2690 int index;
2692 if (size <= 192) {
2693 if (!size)
2694 return ZERO_SIZE_PTR;
2696 index = size_index[(size - 1) / 8];
2697 } else
2698 index = fls(size - 1);
2700 #ifdef CONFIG_ZONE_DMA
2701 if (unlikely((flags & SLUB_DMA)))
2702 return dma_kmalloc_cache(index, flags);
2704 #endif
2705 return &kmalloc_caches[index];
2708 void *__kmalloc(size_t size, gfp_t flags)
2710 struct kmem_cache *s;
2711 void *ret;
2713 if (unlikely(size > PAGE_SIZE))
2714 return kmalloc_large(size, flags);
2716 s = get_slab(size, flags);
2718 if (unlikely(ZERO_OR_NULL_PTR(s)))
2719 return s;
2721 ret = slab_alloc(s, flags, -1, __builtin_return_address(0));
2723 kmemtrace_mark_alloc(KMEMTRACE_TYPE_KMALLOC, _RET_IP_, ret,
2724 size, s->size, flags);
2726 return ret;
2728 EXPORT_SYMBOL(__kmalloc);
2730 static void *kmalloc_large_node(size_t size, gfp_t flags, int node)
2732 struct page *page = alloc_pages_node(node, flags | __GFP_COMP,
2733 get_order(size));
2735 if (page)
2736 return page_address(page);
2737 else
2738 return NULL;
2741 #ifdef CONFIG_NUMA
2742 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2744 struct kmem_cache *s;
2745 void *ret;
2747 if (unlikely(size > PAGE_SIZE)) {
2748 ret = kmalloc_large_node(size, flags, node);
2750 kmemtrace_mark_alloc_node(KMEMTRACE_TYPE_KMALLOC,
2751 _RET_IP_, ret,
2752 size, PAGE_SIZE << get_order(size),
2753 flags, node);
2755 return ret;
2758 s = get_slab(size, flags);
2760 if (unlikely(ZERO_OR_NULL_PTR(s)))
2761 return s;
2763 ret = slab_alloc(s, flags, node, __builtin_return_address(0));
2765 kmemtrace_mark_alloc_node(KMEMTRACE_TYPE_KMALLOC, _RET_IP_, ret,
2766 size, s->size, flags, node);
2768 return ret;
2770 EXPORT_SYMBOL(__kmalloc_node);
2771 #endif
2773 size_t ksize(const void *object)
2775 struct page *page;
2776 struct kmem_cache *s;
2778 if (unlikely(object == ZERO_SIZE_PTR))
2779 return 0;
2781 page = virt_to_head_page(object);
2783 if (unlikely(!PageSlab(page))) {
2784 WARN_ON(!PageCompound(page));
2785 return PAGE_SIZE << compound_order(page);
2787 s = page->slab;
2789 #ifdef CONFIG_SLUB_DEBUG
2791 * Debugging requires use of the padding between object
2792 * and whatever may come after it.
2794 if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2795 return s->objsize;
2797 #endif
2799 * If we have the need to store the freelist pointer
2800 * back there or track user information then we can
2801 * only use the space before that information.
2803 if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2804 return s->inuse;
2806 * Else we can use all the padding etc for the allocation
2808 return s->size;
2810 EXPORT_SYMBOL(ksize);
2812 void kfree(const void *x)
2814 struct page *page;
2815 void *object = (void *)x;
2817 if (unlikely(ZERO_OR_NULL_PTR(x)))
2818 return;
2820 page = virt_to_head_page(x);
2821 if (unlikely(!PageSlab(page))) {
2822 put_page(page);
2823 return;
2825 slab_free(page->slab, page, object, __builtin_return_address(0));
2827 kmemtrace_mark_free(KMEMTRACE_TYPE_KMALLOC, _RET_IP_, x);
2829 EXPORT_SYMBOL(kfree);
2832 * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2833 * the remaining slabs by the number of items in use. The slabs with the
2834 * most items in use come first. New allocations will then fill those up
2835 * and thus they can be removed from the partial lists.
2837 * The slabs with the least items are placed last. This results in them
2838 * being allocated from last increasing the chance that the last objects
2839 * are freed in them.
2841 int kmem_cache_shrink(struct kmem_cache *s)
2843 int node;
2844 int i;
2845 struct kmem_cache_node *n;
2846 struct page *page;
2847 struct page *t;
2848 int objects = oo_objects(s->max);
2849 struct list_head *slabs_by_inuse =
2850 kmalloc(sizeof(struct list_head) * objects, GFP_KERNEL);
2851 unsigned long flags;
2853 if (!slabs_by_inuse)
2854 return -ENOMEM;
2856 flush_all(s);
2857 for_each_node_state(node, N_NORMAL_MEMORY) {
2858 n = get_node(s, node);
2860 if (!n->nr_partial)
2861 continue;
2863 for (i = 0; i < objects; i++)
2864 INIT_LIST_HEAD(slabs_by_inuse + i);
2866 spin_lock_irqsave(&n->list_lock, flags);
2869 * Build lists indexed by the items in use in each slab.
2871 * Note that concurrent frees may occur while we hold the
2872 * list_lock. page->inuse here is the upper limit.
2874 list_for_each_entry_safe(page, t, &n->partial, lru) {
2875 if (!page->inuse && slab_trylock(page)) {
2877 * Must hold slab lock here because slab_free
2878 * may have freed the last object and be
2879 * waiting to release the slab.
2881 list_del(&page->lru);
2882 n->nr_partial--;
2883 slab_unlock(page);
2884 discard_slab(s, page);
2885 } else {
2886 list_move(&page->lru,
2887 slabs_by_inuse + page->inuse);
2892 * Rebuild the partial list with the slabs filled up most
2893 * first and the least used slabs at the end.
2895 for (i = objects - 1; i >= 0; i--)
2896 list_splice(slabs_by_inuse + i, n->partial.prev);
2898 spin_unlock_irqrestore(&n->list_lock, flags);
2901 kfree(slabs_by_inuse);
2902 return 0;
2904 EXPORT_SYMBOL(kmem_cache_shrink);
2906 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
2907 static int slab_mem_going_offline_callback(void *arg)
2909 struct kmem_cache *s;
2911 down_read(&slub_lock);
2912 list_for_each_entry(s, &slab_caches, list)
2913 kmem_cache_shrink(s);
2914 up_read(&slub_lock);
2916 return 0;
2919 static void slab_mem_offline_callback(void *arg)
2921 struct kmem_cache_node *n;
2922 struct kmem_cache *s;
2923 struct memory_notify *marg = arg;
2924 int offline_node;
2926 offline_node = marg->status_change_nid;
2929 * If the node still has available memory. we need kmem_cache_node
2930 * for it yet.
2932 if (offline_node < 0)
2933 return;
2935 down_read(&slub_lock);
2936 list_for_each_entry(s, &slab_caches, list) {
2937 n = get_node(s, offline_node);
2938 if (n) {
2940 * if n->nr_slabs > 0, slabs still exist on the node
2941 * that is going down. We were unable to free them,
2942 * and offline_pages() function shoudn't call this
2943 * callback. So, we must fail.
2945 BUG_ON(slabs_node(s, offline_node));
2947 s->node[offline_node] = NULL;
2948 kmem_cache_free(kmalloc_caches, n);
2951 up_read(&slub_lock);
2954 static int slab_mem_going_online_callback(void *arg)
2956 struct kmem_cache_node *n;
2957 struct kmem_cache *s;
2958 struct memory_notify *marg = arg;
2959 int nid = marg->status_change_nid;
2960 int ret = 0;
2963 * If the node's memory is already available, then kmem_cache_node is
2964 * already created. Nothing to do.
2966 if (nid < 0)
2967 return 0;
2970 * We are bringing a node online. No memory is available yet. We must
2971 * allocate a kmem_cache_node structure in order to bring the node
2972 * online.
2974 down_read(&slub_lock);
2975 list_for_each_entry(s, &slab_caches, list) {
2977 * XXX: kmem_cache_alloc_node will fallback to other nodes
2978 * since memory is not yet available from the node that
2979 * is brought up.
2981 n = kmem_cache_alloc(kmalloc_caches, GFP_KERNEL);
2982 if (!n) {
2983 ret = -ENOMEM;
2984 goto out;
2986 init_kmem_cache_node(n);
2987 s->node[nid] = n;
2989 out:
2990 up_read(&slub_lock);
2991 return ret;
2994 static int slab_memory_callback(struct notifier_block *self,
2995 unsigned long action, void *arg)
2997 int ret = 0;
2999 switch (action) {
3000 case MEM_GOING_ONLINE:
3001 ret = slab_mem_going_online_callback(arg);
3002 break;
3003 case MEM_GOING_OFFLINE:
3004 ret = slab_mem_going_offline_callback(arg);
3005 break;
3006 case MEM_OFFLINE:
3007 case MEM_CANCEL_ONLINE:
3008 slab_mem_offline_callback(arg);
3009 break;
3010 case MEM_ONLINE:
3011 case MEM_CANCEL_OFFLINE:
3012 break;
3015 ret = notifier_from_errno(ret);
3016 return ret;
3019 #endif /* CONFIG_MEMORY_HOTPLUG */
3021 /********************************************************************
3022 * Basic setup of slabs
3023 *******************************************************************/
3025 void __init kmem_cache_init(void)
3027 int i;
3028 int caches = 0;
3030 init_alloc_cpu();
3032 #ifdef CONFIG_NUMA
3034 * Must first have the slab cache available for the allocations of the
3035 * struct kmem_cache_node's. There is special bootstrap code in
3036 * kmem_cache_open for slab_state == DOWN.
3038 create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
3039 sizeof(struct kmem_cache_node), GFP_KERNEL);
3040 kmalloc_caches[0].refcount = -1;
3041 caches++;
3043 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
3044 #endif
3046 /* Able to allocate the per node structures */
3047 slab_state = PARTIAL;
3049 /* Caches that are not of the two-to-the-power-of size */
3050 if (KMALLOC_MIN_SIZE <= 64) {
3051 create_kmalloc_cache(&kmalloc_caches[1],
3052 "kmalloc-96", 96, GFP_KERNEL);
3053 caches++;
3054 create_kmalloc_cache(&kmalloc_caches[2],
3055 "kmalloc-192", 192, GFP_KERNEL);
3056 caches++;
3059 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++) {
3060 create_kmalloc_cache(&kmalloc_caches[i],
3061 "kmalloc", 1 << i, GFP_KERNEL);
3062 caches++;
3067 * Patch up the size_index table if we have strange large alignment
3068 * requirements for the kmalloc array. This is only the case for
3069 * MIPS it seems. The standard arches will not generate any code here.
3071 * Largest permitted alignment is 256 bytes due to the way we
3072 * handle the index determination for the smaller caches.
3074 * Make sure that nothing crazy happens if someone starts tinkering
3075 * around with ARCH_KMALLOC_MINALIGN
3077 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 ||
3078 (KMALLOC_MIN_SIZE & (KMALLOC_MIN_SIZE - 1)));
3080 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8)
3081 size_index[(i - 1) / 8] = KMALLOC_SHIFT_LOW;
3083 if (KMALLOC_MIN_SIZE == 128) {
3085 * The 192 byte sized cache is not used if the alignment
3086 * is 128 byte. Redirect kmalloc to use the 256 byte cache
3087 * instead.
3089 for (i = 128 + 8; i <= 192; i += 8)
3090 size_index[(i - 1) / 8] = 8;
3093 slab_state = UP;
3095 /* Provide the correct kmalloc names now that the caches are up */
3096 for (i = KMALLOC_SHIFT_LOW; i <= PAGE_SHIFT; i++)
3097 kmalloc_caches[i]. name =
3098 kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
3100 #ifdef CONFIG_SMP
3101 register_cpu_notifier(&slab_notifier);
3102 kmem_size = offsetof(struct kmem_cache, cpu_slab) +
3103 nr_cpu_ids * sizeof(struct kmem_cache_cpu *);
3104 #else
3105 kmem_size = sizeof(struct kmem_cache);
3106 #endif
3108 printk(KERN_INFO
3109 "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
3110 " CPUs=%d, Nodes=%d\n",
3111 caches, cache_line_size(),
3112 slub_min_order, slub_max_order, slub_min_objects,
3113 nr_cpu_ids, nr_node_ids);
3117 * Find a mergeable slab cache
3119 static int slab_unmergeable(struct kmem_cache *s)
3121 if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
3122 return 1;
3124 if (s->ctor)
3125 return 1;
3128 * We may have set a slab to be unmergeable during bootstrap.
3130 if (s->refcount < 0)
3131 return 1;
3133 return 0;
3136 static struct kmem_cache *find_mergeable(size_t size,
3137 size_t align, unsigned long flags, const char *name,
3138 void (*ctor)(struct kmem_cache *, void *))
3140 struct kmem_cache *s;
3142 if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
3143 return NULL;
3145 if (ctor)
3146 return NULL;
3148 size = ALIGN(size, sizeof(void *));
3149 align = calculate_alignment(flags, align, size);
3150 size = ALIGN(size, align);
3151 flags = kmem_cache_flags(size, flags, name, NULL);
3153 list_for_each_entry(s, &slab_caches, list) {
3154 if (slab_unmergeable(s))
3155 continue;
3157 if (size > s->size)
3158 continue;
3160 if ((flags & SLUB_MERGE_SAME) != (s->flags & SLUB_MERGE_SAME))
3161 continue;
3163 * Check if alignment is compatible.
3164 * Courtesy of Adrian Drzewiecki
3166 if ((s->size & ~(align - 1)) != s->size)
3167 continue;
3169 if (s->size - size >= sizeof(void *))
3170 continue;
3172 return s;
3174 return NULL;
3177 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
3178 size_t align, unsigned long flags,
3179 void (*ctor)(struct kmem_cache *, void *))
3181 struct kmem_cache *s;
3183 down_write(&slub_lock);
3184 s = find_mergeable(size, align, flags, name, ctor);
3185 if (s) {
3186 int cpu;
3188 s->refcount++;
3190 * Adjust the object sizes so that we clear
3191 * the complete object on kzalloc.
3193 s->objsize = max(s->objsize, (int)size);
3196 * And then we need to update the object size in the
3197 * per cpu structures
3199 for_each_online_cpu(cpu)
3200 get_cpu_slab(s, cpu)->objsize = s->objsize;
3202 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
3203 up_write(&slub_lock);
3205 if (sysfs_slab_alias(s, name))
3206 goto err;
3207 return s;
3210 s = kmalloc(kmem_size, GFP_KERNEL);
3211 if (s) {
3212 if (kmem_cache_open(s, GFP_KERNEL, name,
3213 size, align, flags, ctor)) {
3214 list_add(&s->list, &slab_caches);
3215 up_write(&slub_lock);
3216 if (sysfs_slab_add(s))
3217 goto err;
3218 return s;
3220 kfree(s);
3222 up_write(&slub_lock);
3224 err:
3225 if (flags & SLAB_PANIC)
3226 panic("Cannot create slabcache %s\n", name);
3227 else
3228 s = NULL;
3229 return s;
3231 EXPORT_SYMBOL(kmem_cache_create);
3233 #ifdef CONFIG_SMP
3235 * Use the cpu notifier to insure that the cpu slabs are flushed when
3236 * necessary.
3238 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
3239 unsigned long action, void *hcpu)
3241 long cpu = (long)hcpu;
3242 struct kmem_cache *s;
3243 unsigned long flags;
3245 switch (action) {
3246 case CPU_UP_PREPARE:
3247 case CPU_UP_PREPARE_FROZEN:
3248 init_alloc_cpu_cpu(cpu);
3249 down_read(&slub_lock);
3250 list_for_each_entry(s, &slab_caches, list)
3251 s->cpu_slab[cpu] = alloc_kmem_cache_cpu(s, cpu,
3252 GFP_KERNEL);
3253 up_read(&slub_lock);
3254 break;
3256 case CPU_UP_CANCELED:
3257 case CPU_UP_CANCELED_FROZEN:
3258 case CPU_DEAD:
3259 case CPU_DEAD_FROZEN:
3260 down_read(&slub_lock);
3261 list_for_each_entry(s, &slab_caches, list) {
3262 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3264 local_irq_save(flags);
3265 __flush_cpu_slab(s, cpu);
3266 local_irq_restore(flags);
3267 free_kmem_cache_cpu(c, cpu);
3268 s->cpu_slab[cpu] = NULL;
3270 up_read(&slub_lock);
3271 break;
3272 default:
3273 break;
3275 return NOTIFY_OK;
3278 static struct notifier_block __cpuinitdata slab_notifier = {
3279 .notifier_call = slab_cpuup_callback
3282 #endif
3284 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
3286 struct kmem_cache *s;
3288 if (unlikely(size > PAGE_SIZE))
3289 return kmalloc_large(size, gfpflags);
3291 s = get_slab(size, gfpflags);
3293 if (unlikely(ZERO_OR_NULL_PTR(s)))
3294 return s;
3296 return slab_alloc(s, gfpflags, -1, caller);
3299 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
3300 int node, void *caller)
3302 struct kmem_cache *s;
3304 if (unlikely(size > PAGE_SIZE))
3305 return kmalloc_large_node(size, gfpflags, node);
3307 s = get_slab(size, gfpflags);
3309 if (unlikely(ZERO_OR_NULL_PTR(s)))
3310 return s;
3312 return slab_alloc(s, gfpflags, node, caller);
3315 #ifdef CONFIG_SLUB_DEBUG
3316 static unsigned long count_partial(struct kmem_cache_node *n,
3317 int (*get_count)(struct page *))
3319 unsigned long flags;
3320 unsigned long x = 0;
3321 struct page *page;
3323 spin_lock_irqsave(&n->list_lock, flags);
3324 list_for_each_entry(page, &n->partial, lru)
3325 x += get_count(page);
3326 spin_unlock_irqrestore(&n->list_lock, flags);
3327 return x;
3330 static int count_inuse(struct page *page)
3332 return page->inuse;
3335 static int count_total(struct page *page)
3337 return page->objects;
3340 static int count_free(struct page *page)
3342 return page->objects - page->inuse;
3345 static int validate_slab(struct kmem_cache *s, struct page *page,
3346 unsigned long *map)
3348 void *p;
3349 void *addr = page_address(page);
3351 if (!check_slab(s, page) ||
3352 !on_freelist(s, page, NULL))
3353 return 0;
3355 /* Now we know that a valid freelist exists */
3356 bitmap_zero(map, page->objects);
3358 for_each_free_object(p, s, page->freelist) {
3359 set_bit(slab_index(p, s, addr), map);
3360 if (!check_object(s, page, p, 0))
3361 return 0;
3364 for_each_object(p, s, addr, page->objects)
3365 if (!test_bit(slab_index(p, s, addr), map))
3366 if (!check_object(s, page, p, 1))
3367 return 0;
3368 return 1;
3371 static void validate_slab_slab(struct kmem_cache *s, struct page *page,
3372 unsigned long *map)
3374 if (slab_trylock(page)) {
3375 validate_slab(s, page, map);
3376 slab_unlock(page);
3377 } else
3378 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
3379 s->name, page);
3381 if (s->flags & DEBUG_DEFAULT_FLAGS) {
3382 if (!SlabDebug(page))
3383 printk(KERN_ERR "SLUB %s: SlabDebug not set "
3384 "on slab 0x%p\n", s->name, page);
3385 } else {
3386 if (SlabDebug(page))
3387 printk(KERN_ERR "SLUB %s: SlabDebug set on "
3388 "slab 0x%p\n", s->name, page);
3392 static int validate_slab_node(struct kmem_cache *s,
3393 struct kmem_cache_node *n, unsigned long *map)
3395 unsigned long count = 0;
3396 struct page *page;
3397 unsigned long flags;
3399 spin_lock_irqsave(&n->list_lock, flags);
3401 list_for_each_entry(page, &n->partial, lru) {
3402 validate_slab_slab(s, page, map);
3403 count++;
3405 if (count != n->nr_partial)
3406 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
3407 "counter=%ld\n", s->name, count, n->nr_partial);
3409 if (!(s->flags & SLAB_STORE_USER))
3410 goto out;
3412 list_for_each_entry(page, &n->full, lru) {
3413 validate_slab_slab(s, page, map);
3414 count++;
3416 if (count != atomic_long_read(&n->nr_slabs))
3417 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
3418 "counter=%ld\n", s->name, count,
3419 atomic_long_read(&n->nr_slabs));
3421 out:
3422 spin_unlock_irqrestore(&n->list_lock, flags);
3423 return count;
3426 static long validate_slab_cache(struct kmem_cache *s)
3428 int node;
3429 unsigned long count = 0;
3430 unsigned long *map = kmalloc(BITS_TO_LONGS(oo_objects(s->max)) *
3431 sizeof(unsigned long), GFP_KERNEL);
3433 if (!map)
3434 return -ENOMEM;
3436 flush_all(s);
3437 for_each_node_state(node, N_NORMAL_MEMORY) {
3438 struct kmem_cache_node *n = get_node(s, node);
3440 count += validate_slab_node(s, n, map);
3442 kfree(map);
3443 return count;
3446 #ifdef SLUB_RESILIENCY_TEST
3447 static void resiliency_test(void)
3449 u8 *p;
3451 printk(KERN_ERR "SLUB resiliency testing\n");
3452 printk(KERN_ERR "-----------------------\n");
3453 printk(KERN_ERR "A. Corruption after allocation\n");
3455 p = kzalloc(16, GFP_KERNEL);
3456 p[16] = 0x12;
3457 printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
3458 " 0x12->0x%p\n\n", p + 16);
3460 validate_slab_cache(kmalloc_caches + 4);
3462 /* Hmmm... The next two are dangerous */
3463 p = kzalloc(32, GFP_KERNEL);
3464 p[32 + sizeof(void *)] = 0x34;
3465 printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
3466 " 0x34 -> -0x%p\n", p);
3467 printk(KERN_ERR
3468 "If allocated object is overwritten then not detectable\n\n");
3470 validate_slab_cache(kmalloc_caches + 5);
3471 p = kzalloc(64, GFP_KERNEL);
3472 p += 64 + (get_cycles() & 0xff) * sizeof(void *);
3473 *p = 0x56;
3474 printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
3476 printk(KERN_ERR
3477 "If allocated object is overwritten then not detectable\n\n");
3478 validate_slab_cache(kmalloc_caches + 6);
3480 printk(KERN_ERR "\nB. Corruption after free\n");
3481 p = kzalloc(128, GFP_KERNEL);
3482 kfree(p);
3483 *p = 0x78;
3484 printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
3485 validate_slab_cache(kmalloc_caches + 7);
3487 p = kzalloc(256, GFP_KERNEL);
3488 kfree(p);
3489 p[50] = 0x9a;
3490 printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n",
3492 validate_slab_cache(kmalloc_caches + 8);
3494 p = kzalloc(512, GFP_KERNEL);
3495 kfree(p);
3496 p[512] = 0xab;
3497 printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
3498 validate_slab_cache(kmalloc_caches + 9);
3500 #else
3501 static void resiliency_test(void) {};
3502 #endif
3505 * Generate lists of code addresses where slabcache objects are allocated
3506 * and freed.
3509 struct location {
3510 unsigned long count;
3511 void *addr;
3512 long long sum_time;
3513 long min_time;
3514 long max_time;
3515 long min_pid;
3516 long max_pid;
3517 cpumask_t cpus;
3518 nodemask_t nodes;
3521 struct loc_track {
3522 unsigned long max;
3523 unsigned long count;
3524 struct location *loc;
3527 static void free_loc_track(struct loc_track *t)
3529 if (t->max)
3530 free_pages((unsigned long)t->loc,
3531 get_order(sizeof(struct location) * t->max));
3534 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
3536 struct location *l;
3537 int order;
3539 order = get_order(sizeof(struct location) * max);
3541 l = (void *)__get_free_pages(flags, order);
3542 if (!l)
3543 return 0;
3545 if (t->count) {
3546 memcpy(l, t->loc, sizeof(struct location) * t->count);
3547 free_loc_track(t);
3549 t->max = max;
3550 t->loc = l;
3551 return 1;
3554 static int add_location(struct loc_track *t, struct kmem_cache *s,
3555 const struct track *track)
3557 long start, end, pos;
3558 struct location *l;
3559 void *caddr;
3560 unsigned long age = jiffies - track->when;
3562 start = -1;
3563 end = t->count;
3565 for ( ; ; ) {
3566 pos = start + (end - start + 1) / 2;
3569 * There is nothing at "end". If we end up there
3570 * we need to add something to before end.
3572 if (pos == end)
3573 break;
3575 caddr = t->loc[pos].addr;
3576 if (track->addr == caddr) {
3578 l = &t->loc[pos];
3579 l->count++;
3580 if (track->when) {
3581 l->sum_time += age;
3582 if (age < l->min_time)
3583 l->min_time = age;
3584 if (age > l->max_time)
3585 l->max_time = age;
3587 if (track->pid < l->min_pid)
3588 l->min_pid = track->pid;
3589 if (track->pid > l->max_pid)
3590 l->max_pid = track->pid;
3592 cpu_set(track->cpu, l->cpus);
3594 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3595 return 1;
3598 if (track->addr < caddr)
3599 end = pos;
3600 else
3601 start = pos;
3605 * Not found. Insert new tracking element.
3607 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
3608 return 0;
3610 l = t->loc + pos;
3611 if (pos < t->count)
3612 memmove(l + 1, l,
3613 (t->count - pos) * sizeof(struct location));
3614 t->count++;
3615 l->count = 1;
3616 l->addr = track->addr;
3617 l->sum_time = age;
3618 l->min_time = age;
3619 l->max_time = age;
3620 l->min_pid = track->pid;
3621 l->max_pid = track->pid;
3622 cpus_clear(l->cpus);
3623 cpu_set(track->cpu, l->cpus);
3624 nodes_clear(l->nodes);
3625 node_set(page_to_nid(virt_to_page(track)), l->nodes);
3626 return 1;
3629 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3630 struct page *page, enum track_item alloc)
3632 void *addr = page_address(page);
3633 DECLARE_BITMAP(map, page->objects);
3634 void *p;
3636 bitmap_zero(map, page->objects);
3637 for_each_free_object(p, s, page->freelist)
3638 set_bit(slab_index(p, s, addr), map);
3640 for_each_object(p, s, addr, page->objects)
3641 if (!test_bit(slab_index(p, s, addr), map))
3642 add_location(t, s, get_track(s, p, alloc));
3645 static int list_locations(struct kmem_cache *s, char *buf,
3646 enum track_item alloc)
3648 int len = 0;
3649 unsigned long i;
3650 struct loc_track t = { 0, 0, NULL };
3651 int node;
3653 if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3654 GFP_TEMPORARY))
3655 return sprintf(buf, "Out of memory\n");
3657 /* Push back cpu slabs */
3658 flush_all(s);
3660 for_each_node_state(node, N_NORMAL_MEMORY) {
3661 struct kmem_cache_node *n = get_node(s, node);
3662 unsigned long flags;
3663 struct page *page;
3665 if (!atomic_long_read(&n->nr_slabs))
3666 continue;
3668 spin_lock_irqsave(&n->list_lock, flags);
3669 list_for_each_entry(page, &n->partial, lru)
3670 process_slab(&t, s, page, alloc);
3671 list_for_each_entry(page, &n->full, lru)
3672 process_slab(&t, s, page, alloc);
3673 spin_unlock_irqrestore(&n->list_lock, flags);
3676 for (i = 0; i < t.count; i++) {
3677 struct location *l = &t.loc[i];
3679 if (len > PAGE_SIZE - 100)
3680 break;
3681 len += sprintf(buf + len, "%7ld ", l->count);
3683 if (l->addr)
3684 len += sprint_symbol(buf + len, (unsigned long)l->addr);
3685 else
3686 len += sprintf(buf + len, "<not-available>");
3688 if (l->sum_time != l->min_time) {
3689 len += sprintf(buf + len, " age=%ld/%ld/%ld",
3690 l->min_time,
3691 (long)div_u64(l->sum_time, l->count),
3692 l->max_time);
3693 } else
3694 len += sprintf(buf + len, " age=%ld",
3695 l->min_time);
3697 if (l->min_pid != l->max_pid)
3698 len += sprintf(buf + len, " pid=%ld-%ld",
3699 l->min_pid, l->max_pid);
3700 else
3701 len += sprintf(buf + len, " pid=%ld",
3702 l->min_pid);
3704 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3705 len < PAGE_SIZE - 60) {
3706 len += sprintf(buf + len, " cpus=");
3707 len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3708 l->cpus);
3711 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3712 len < PAGE_SIZE - 60) {
3713 len += sprintf(buf + len, " nodes=");
3714 len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
3715 l->nodes);
3718 len += sprintf(buf + len, "\n");
3721 free_loc_track(&t);
3722 if (!t.count)
3723 len += sprintf(buf, "No data\n");
3724 return len;
3727 enum slab_stat_type {
3728 SL_ALL, /* All slabs */
3729 SL_PARTIAL, /* Only partially allocated slabs */
3730 SL_CPU, /* Only slabs used for cpu caches */
3731 SL_OBJECTS, /* Determine allocated objects not slabs */
3732 SL_TOTAL /* Determine object capacity not slabs */
3735 #define SO_ALL (1 << SL_ALL)
3736 #define SO_PARTIAL (1 << SL_PARTIAL)
3737 #define SO_CPU (1 << SL_CPU)
3738 #define SO_OBJECTS (1 << SL_OBJECTS)
3739 #define SO_TOTAL (1 << SL_TOTAL)
3741 static ssize_t show_slab_objects(struct kmem_cache *s,
3742 char *buf, unsigned long flags)
3744 unsigned long total = 0;
3745 int node;
3746 int x;
3747 unsigned long *nodes;
3748 unsigned long *per_cpu;
3750 nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3751 if (!nodes)
3752 return -ENOMEM;
3753 per_cpu = nodes + nr_node_ids;
3755 if (flags & SO_CPU) {
3756 int cpu;
3758 for_each_possible_cpu(cpu) {
3759 struct kmem_cache_cpu *c = get_cpu_slab(s, cpu);
3761 if (!c || c->node < 0)
3762 continue;
3764 if (c->page) {
3765 if (flags & SO_TOTAL)
3766 x = c->page->objects;
3767 else if (flags & SO_OBJECTS)
3768 x = c->page->inuse;
3769 else
3770 x = 1;
3772 total += x;
3773 nodes[c->node] += x;
3775 per_cpu[c->node]++;
3779 if (flags & SO_ALL) {
3780 for_each_node_state(node, N_NORMAL_MEMORY) {
3781 struct kmem_cache_node *n = get_node(s, node);
3783 if (flags & SO_TOTAL)
3784 x = atomic_long_read(&n->total_objects);
3785 else if (flags & SO_OBJECTS)
3786 x = atomic_long_read(&n->total_objects) -
3787 count_partial(n, count_free);
3789 else
3790 x = atomic_long_read(&n->nr_slabs);
3791 total += x;
3792 nodes[node] += x;
3795 } else if (flags & SO_PARTIAL) {
3796 for_each_node_state(node, N_NORMAL_MEMORY) {
3797 struct kmem_cache_node *n = get_node(s, node);
3799 if (flags & SO_TOTAL)
3800 x = count_partial(n, count_total);
3801 else if (flags & SO_OBJECTS)
3802 x = count_partial(n, count_inuse);
3803 else
3804 x = n->nr_partial;
3805 total += x;
3806 nodes[node] += x;
3809 x = sprintf(buf, "%lu", total);
3810 #ifdef CONFIG_NUMA
3811 for_each_node_state(node, N_NORMAL_MEMORY)
3812 if (nodes[node])
3813 x += sprintf(buf + x, " N%d=%lu",
3814 node, nodes[node]);
3815 #endif
3816 kfree(nodes);
3817 return x + sprintf(buf + x, "\n");
3820 static int any_slab_objects(struct kmem_cache *s)
3822 int node;
3824 for_each_online_node(node) {
3825 struct kmem_cache_node *n = get_node(s, node);
3827 if (!n)
3828 continue;
3830 if (atomic_long_read(&n->total_objects))
3831 return 1;
3833 return 0;
3836 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3837 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3839 struct slab_attribute {
3840 struct attribute attr;
3841 ssize_t (*show)(struct kmem_cache *s, char *buf);
3842 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3845 #define SLAB_ATTR_RO(_name) \
3846 static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3848 #define SLAB_ATTR(_name) \
3849 static struct slab_attribute _name##_attr = \
3850 __ATTR(_name, 0644, _name##_show, _name##_store)
3852 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3854 return sprintf(buf, "%d\n", s->size);
3856 SLAB_ATTR_RO(slab_size);
3858 static ssize_t align_show(struct kmem_cache *s, char *buf)
3860 return sprintf(buf, "%d\n", s->align);
3862 SLAB_ATTR_RO(align);
3864 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3866 return sprintf(buf, "%d\n", s->objsize);
3868 SLAB_ATTR_RO(object_size);
3870 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3872 return sprintf(buf, "%d\n", oo_objects(s->oo));
3874 SLAB_ATTR_RO(objs_per_slab);
3876 static ssize_t order_store(struct kmem_cache *s,
3877 const char *buf, size_t length)
3879 unsigned long order;
3880 int err;
3882 err = strict_strtoul(buf, 10, &order);
3883 if (err)
3884 return err;
3886 if (order > slub_max_order || order < slub_min_order)
3887 return -EINVAL;
3889 calculate_sizes(s, order);
3890 return length;
3893 static ssize_t order_show(struct kmem_cache *s, char *buf)
3895 return sprintf(buf, "%d\n", oo_order(s->oo));
3897 SLAB_ATTR(order);
3899 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3901 if (s->ctor) {
3902 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3904 return n + sprintf(buf + n, "\n");
3906 return 0;
3908 SLAB_ATTR_RO(ctor);
3910 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3912 return sprintf(buf, "%d\n", s->refcount - 1);
3914 SLAB_ATTR_RO(aliases);
3916 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3918 return show_slab_objects(s, buf, SO_ALL);
3920 SLAB_ATTR_RO(slabs);
3922 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3924 return show_slab_objects(s, buf, SO_PARTIAL);
3926 SLAB_ATTR_RO(partial);
3928 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3930 return show_slab_objects(s, buf, SO_CPU);
3932 SLAB_ATTR_RO(cpu_slabs);
3934 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3936 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS);
3938 SLAB_ATTR_RO(objects);
3940 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf)
3942 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS);
3944 SLAB_ATTR_RO(objects_partial);
3946 static ssize_t total_objects_show(struct kmem_cache *s, char *buf)
3948 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL);
3950 SLAB_ATTR_RO(total_objects);
3952 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3954 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3957 static ssize_t sanity_checks_store(struct kmem_cache *s,
3958 const char *buf, size_t length)
3960 s->flags &= ~SLAB_DEBUG_FREE;
3961 if (buf[0] == '1')
3962 s->flags |= SLAB_DEBUG_FREE;
3963 return length;
3965 SLAB_ATTR(sanity_checks);
3967 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3969 return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3972 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3973 size_t length)
3975 s->flags &= ~SLAB_TRACE;
3976 if (buf[0] == '1')
3977 s->flags |= SLAB_TRACE;
3978 return length;
3980 SLAB_ATTR(trace);
3982 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3984 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3987 static ssize_t reclaim_account_store(struct kmem_cache *s,
3988 const char *buf, size_t length)
3990 s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3991 if (buf[0] == '1')
3992 s->flags |= SLAB_RECLAIM_ACCOUNT;
3993 return length;
3995 SLAB_ATTR(reclaim_account);
3997 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3999 return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
4001 SLAB_ATTR_RO(hwcache_align);
4003 #ifdef CONFIG_ZONE_DMA
4004 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
4006 return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
4008 SLAB_ATTR_RO(cache_dma);
4009 #endif
4011 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
4013 return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
4015 SLAB_ATTR_RO(destroy_by_rcu);
4017 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
4019 return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
4022 static ssize_t red_zone_store(struct kmem_cache *s,
4023 const char *buf, size_t length)
4025 if (any_slab_objects(s))
4026 return -EBUSY;
4028 s->flags &= ~SLAB_RED_ZONE;
4029 if (buf[0] == '1')
4030 s->flags |= SLAB_RED_ZONE;
4031 calculate_sizes(s, -1);
4032 return length;
4034 SLAB_ATTR(red_zone);
4036 static ssize_t poison_show(struct kmem_cache *s, char *buf)
4038 return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
4041 static ssize_t poison_store(struct kmem_cache *s,
4042 const char *buf, size_t length)
4044 if (any_slab_objects(s))
4045 return -EBUSY;
4047 s->flags &= ~SLAB_POISON;
4048 if (buf[0] == '1')
4049 s->flags |= SLAB_POISON;
4050 calculate_sizes(s, -1);
4051 return length;
4053 SLAB_ATTR(poison);
4055 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
4057 return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
4060 static ssize_t store_user_store(struct kmem_cache *s,
4061 const char *buf, size_t length)
4063 if (any_slab_objects(s))
4064 return -EBUSY;
4066 s->flags &= ~SLAB_STORE_USER;
4067 if (buf[0] == '1')
4068 s->flags |= SLAB_STORE_USER;
4069 calculate_sizes(s, -1);
4070 return length;
4072 SLAB_ATTR(store_user);
4074 static ssize_t validate_show(struct kmem_cache *s, char *buf)
4076 return 0;
4079 static ssize_t validate_store(struct kmem_cache *s,
4080 const char *buf, size_t length)
4082 int ret = -EINVAL;
4084 if (buf[0] == '1') {
4085 ret = validate_slab_cache(s);
4086 if (ret >= 0)
4087 ret = length;
4089 return ret;
4091 SLAB_ATTR(validate);
4093 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
4095 return 0;
4098 static ssize_t shrink_store(struct kmem_cache *s,
4099 const char *buf, size_t length)
4101 if (buf[0] == '1') {
4102 int rc = kmem_cache_shrink(s);
4104 if (rc)
4105 return rc;
4106 } else
4107 return -EINVAL;
4108 return length;
4110 SLAB_ATTR(shrink);
4112 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
4114 if (!(s->flags & SLAB_STORE_USER))
4115 return -ENOSYS;
4116 return list_locations(s, buf, TRACK_ALLOC);
4118 SLAB_ATTR_RO(alloc_calls);
4120 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
4122 if (!(s->flags & SLAB_STORE_USER))
4123 return -ENOSYS;
4124 return list_locations(s, buf, TRACK_FREE);
4126 SLAB_ATTR_RO(free_calls);
4128 #ifdef CONFIG_NUMA
4129 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf)
4131 return sprintf(buf, "%d\n", s->remote_node_defrag_ratio / 10);
4134 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s,
4135 const char *buf, size_t length)
4137 unsigned long ratio;
4138 int err;
4140 err = strict_strtoul(buf, 10, &ratio);
4141 if (err)
4142 return err;
4144 if (ratio < 100)
4145 s->remote_node_defrag_ratio = ratio * 10;
4147 return length;
4149 SLAB_ATTR(remote_node_defrag_ratio);
4150 #endif
4152 #ifdef CONFIG_SLUB_STATS
4153 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si)
4155 unsigned long sum = 0;
4156 int cpu;
4157 int len;
4158 int *data = kmalloc(nr_cpu_ids * sizeof(int), GFP_KERNEL);
4160 if (!data)
4161 return -ENOMEM;
4163 for_each_online_cpu(cpu) {
4164 unsigned x = get_cpu_slab(s, cpu)->stat[si];
4166 data[cpu] = x;
4167 sum += x;
4170 len = sprintf(buf, "%lu", sum);
4172 #ifdef CONFIG_SMP
4173 for_each_online_cpu(cpu) {
4174 if (data[cpu] && len < PAGE_SIZE - 20)
4175 len += sprintf(buf + len, " C%d=%u", cpu, data[cpu]);
4177 #endif
4178 kfree(data);
4179 return len + sprintf(buf + len, "\n");
4182 #define STAT_ATTR(si, text) \
4183 static ssize_t text##_show(struct kmem_cache *s, char *buf) \
4185 return show_stat(s, buf, si); \
4187 SLAB_ATTR_RO(text); \
4189 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath);
4190 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath);
4191 STAT_ATTR(FREE_FASTPATH, free_fastpath);
4192 STAT_ATTR(FREE_SLOWPATH, free_slowpath);
4193 STAT_ATTR(FREE_FROZEN, free_frozen);
4194 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial);
4195 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial);
4196 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial);
4197 STAT_ATTR(ALLOC_SLAB, alloc_slab);
4198 STAT_ATTR(ALLOC_REFILL, alloc_refill);
4199 STAT_ATTR(FREE_SLAB, free_slab);
4200 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush);
4201 STAT_ATTR(DEACTIVATE_FULL, deactivate_full);
4202 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty);
4203 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head);
4204 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail);
4205 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees);
4206 STAT_ATTR(ORDER_FALLBACK, order_fallback);
4207 #endif
4209 static struct attribute *slab_attrs[] = {
4210 &slab_size_attr.attr,
4211 &object_size_attr.attr,
4212 &objs_per_slab_attr.attr,
4213 &order_attr.attr,
4214 &objects_attr.attr,
4215 &objects_partial_attr.attr,
4216 &total_objects_attr.attr,
4217 &slabs_attr.attr,
4218 &partial_attr.attr,
4219 &cpu_slabs_attr.attr,
4220 &ctor_attr.attr,
4221 &aliases_attr.attr,
4222 &align_attr.attr,
4223 &sanity_checks_attr.attr,
4224 &trace_attr.attr,
4225 &hwcache_align_attr.attr,
4226 &reclaim_account_attr.attr,
4227 &destroy_by_rcu_attr.attr,
4228 &red_zone_attr.attr,
4229 &poison_attr.attr,
4230 &store_user_attr.attr,
4231 &validate_attr.attr,
4232 &shrink_attr.attr,
4233 &alloc_calls_attr.attr,
4234 &free_calls_attr.attr,
4235 #ifdef CONFIG_ZONE_DMA
4236 &cache_dma_attr.attr,
4237 #endif
4238 #ifdef CONFIG_NUMA
4239 &remote_node_defrag_ratio_attr.attr,
4240 #endif
4241 #ifdef CONFIG_SLUB_STATS
4242 &alloc_fastpath_attr.attr,
4243 &alloc_slowpath_attr.attr,
4244 &free_fastpath_attr.attr,
4245 &free_slowpath_attr.attr,
4246 &free_frozen_attr.attr,
4247 &free_add_partial_attr.attr,
4248 &free_remove_partial_attr.attr,
4249 &alloc_from_partial_attr.attr,
4250 &alloc_slab_attr.attr,
4251 &alloc_refill_attr.attr,
4252 &free_slab_attr.attr,
4253 &cpuslab_flush_attr.attr,
4254 &deactivate_full_attr.attr,
4255 &deactivate_empty_attr.attr,
4256 &deactivate_to_head_attr.attr,
4257 &deactivate_to_tail_attr.attr,
4258 &deactivate_remote_frees_attr.attr,
4259 &order_fallback_attr.attr,
4260 #endif
4261 NULL
4264 static struct attribute_group slab_attr_group = {
4265 .attrs = slab_attrs,
4268 static ssize_t slab_attr_show(struct kobject *kobj,
4269 struct attribute *attr,
4270 char *buf)
4272 struct slab_attribute *attribute;
4273 struct kmem_cache *s;
4274 int err;
4276 attribute = to_slab_attr(attr);
4277 s = to_slab(kobj);
4279 if (!attribute->show)
4280 return -EIO;
4282 err = attribute->show(s, buf);
4284 return err;
4287 static ssize_t slab_attr_store(struct kobject *kobj,
4288 struct attribute *attr,
4289 const char *buf, size_t len)
4291 struct slab_attribute *attribute;
4292 struct kmem_cache *s;
4293 int err;
4295 attribute = to_slab_attr(attr);
4296 s = to_slab(kobj);
4298 if (!attribute->store)
4299 return -EIO;
4301 err = attribute->store(s, buf, len);
4303 return err;
4306 static void kmem_cache_release(struct kobject *kobj)
4308 struct kmem_cache *s = to_slab(kobj);
4310 kfree(s);
4313 static struct sysfs_ops slab_sysfs_ops = {
4314 .show = slab_attr_show,
4315 .store = slab_attr_store,
4318 static struct kobj_type slab_ktype = {
4319 .sysfs_ops = &slab_sysfs_ops,
4320 .release = kmem_cache_release
4323 static int uevent_filter(struct kset *kset, struct kobject *kobj)
4325 struct kobj_type *ktype = get_ktype(kobj);
4327 if (ktype == &slab_ktype)
4328 return 1;
4329 return 0;
4332 static struct kset_uevent_ops slab_uevent_ops = {
4333 .filter = uevent_filter,
4336 static struct kset *slab_kset;
4338 #define ID_STR_LENGTH 64
4340 /* Create a unique string id for a slab cache:
4342 * Format :[flags-]size
4344 static char *create_unique_id(struct kmem_cache *s)
4346 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
4347 char *p = name;
4349 BUG_ON(!name);
4351 *p++ = ':';
4353 * First flags affecting slabcache operations. We will only
4354 * get here for aliasable slabs so we do not need to support
4355 * too many flags. The flags here must cover all flags that
4356 * are matched during merging to guarantee that the id is
4357 * unique.
4359 if (s->flags & SLAB_CACHE_DMA)
4360 *p++ = 'd';
4361 if (s->flags & SLAB_RECLAIM_ACCOUNT)
4362 *p++ = 'a';
4363 if (s->flags & SLAB_DEBUG_FREE)
4364 *p++ = 'F';
4365 if (p != name + 1)
4366 *p++ = '-';
4367 p += sprintf(p, "%07d", s->size);
4368 BUG_ON(p > name + ID_STR_LENGTH - 1);
4369 return name;
4372 static int sysfs_slab_add(struct kmem_cache *s)
4374 int err;
4375 const char *name;
4376 int unmergeable;
4378 if (slab_state < SYSFS)
4379 /* Defer until later */
4380 return 0;
4382 unmergeable = slab_unmergeable(s);
4383 if (unmergeable) {
4385 * Slabcache can never be merged so we can use the name proper.
4386 * This is typically the case for debug situations. In that
4387 * case we can catch duplicate names easily.
4389 sysfs_remove_link(&slab_kset->kobj, s->name);
4390 name = s->name;
4391 } else {
4393 * Create a unique name for the slab as a target
4394 * for the symlinks.
4396 name = create_unique_id(s);
4399 s->kobj.kset = slab_kset;
4400 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, name);
4401 if (err) {
4402 kobject_put(&s->kobj);
4403 return err;
4406 err = sysfs_create_group(&s->kobj, &slab_attr_group);
4407 if (err)
4408 return err;
4409 kobject_uevent(&s->kobj, KOBJ_ADD);
4410 if (!unmergeable) {
4411 /* Setup first alias */
4412 sysfs_slab_alias(s, s->name);
4413 kfree(name);
4415 return 0;
4418 static void sysfs_slab_remove(struct kmem_cache *s)
4420 kobject_uevent(&s->kobj, KOBJ_REMOVE);
4421 kobject_del(&s->kobj);
4422 kobject_put(&s->kobj);
4426 * Need to buffer aliases during bootup until sysfs becomes
4427 * available lest we loose that information.
4429 struct saved_alias {
4430 struct kmem_cache *s;
4431 const char *name;
4432 struct saved_alias *next;
4435 static struct saved_alias *alias_list;
4437 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
4439 struct saved_alias *al;
4441 if (slab_state == SYSFS) {
4443 * If we have a leftover link then remove it.
4445 sysfs_remove_link(&slab_kset->kobj, name);
4446 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
4449 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
4450 if (!al)
4451 return -ENOMEM;
4453 al->s = s;
4454 al->name = name;
4455 al->next = alias_list;
4456 alias_list = al;
4457 return 0;
4460 static int __init slab_sysfs_init(void)
4462 struct kmem_cache *s;
4463 int err;
4465 slab_kset = kset_create_and_add("slab", &slab_uevent_ops, kernel_kobj);
4466 if (!slab_kset) {
4467 printk(KERN_ERR "Cannot register slab subsystem.\n");
4468 return -ENOSYS;
4471 slab_state = SYSFS;
4473 list_for_each_entry(s, &slab_caches, list) {
4474 err = sysfs_slab_add(s);
4475 if (err)
4476 printk(KERN_ERR "SLUB: Unable to add boot slab %s"
4477 " to sysfs\n", s->name);
4480 while (alias_list) {
4481 struct saved_alias *al = alias_list;
4483 alias_list = alias_list->next;
4484 err = sysfs_slab_alias(al->s, al->name);
4485 if (err)
4486 printk(KERN_ERR "SLUB: Unable to add boot slab alias"
4487 " %s to sysfs\n", s->name);
4488 kfree(al);
4491 resiliency_test();
4492 return 0;
4495 __initcall(slab_sysfs_init);
4496 #endif
4499 * The /proc/slabinfo ABI
4501 #ifdef CONFIG_SLABINFO
4503 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4504 size_t count, loff_t *ppos)
4506 return -EINVAL;
4510 static void print_slabinfo_header(struct seq_file *m)
4512 seq_puts(m, "slabinfo - version: 2.1\n");
4513 seq_puts(m, "# name <active_objs> <num_objs> <objsize> "
4514 "<objperslab> <pagesperslab>");
4515 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>");
4516 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>");
4517 seq_putc(m, '\n');
4520 static void *s_start(struct seq_file *m, loff_t *pos)
4522 loff_t n = *pos;
4524 down_read(&slub_lock);
4525 if (!n)
4526 print_slabinfo_header(m);
4528 return seq_list_start(&slab_caches, *pos);
4531 static void *s_next(struct seq_file *m, void *p, loff_t *pos)
4533 return seq_list_next(p, &slab_caches, pos);
4536 static void s_stop(struct seq_file *m, void *p)
4538 up_read(&slub_lock);
4541 static int s_show(struct seq_file *m, void *p)
4543 unsigned long nr_partials = 0;
4544 unsigned long nr_slabs = 0;
4545 unsigned long nr_inuse = 0;
4546 unsigned long nr_objs = 0;
4547 unsigned long nr_free = 0;
4548 struct kmem_cache *s;
4549 int node;
4551 s = list_entry(p, struct kmem_cache, list);
4553 for_each_online_node(node) {
4554 struct kmem_cache_node *n = get_node(s, node);
4556 if (!n)
4557 continue;
4559 nr_partials += n->nr_partial;
4560 nr_slabs += atomic_long_read(&n->nr_slabs);
4561 nr_objs += atomic_long_read(&n->total_objects);
4562 nr_free += count_partial(n, count_free);
4565 nr_inuse = nr_objs - nr_free;
4567 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", s->name, nr_inuse,
4568 nr_objs, s->size, oo_objects(s->oo),
4569 (1 << oo_order(s->oo)));
4570 seq_printf(m, " : tunables %4u %4u %4u", 0, 0, 0);
4571 seq_printf(m, " : slabdata %6lu %6lu %6lu", nr_slabs, nr_slabs,
4572 0UL);
4573 seq_putc(m, '\n');
4574 return 0;
4577 const struct seq_operations slabinfo_op = {
4578 .start = s_start,
4579 .next = s_next,
4580 .stop = s_stop,
4581 .show = s_show,
4584 #endif /* CONFIG_SLABINFO */