]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - mm/slub.c
SLUB slab validation: Move tracking information alloc outside of lock
[linux-2.6-omap-h63xx.git] / mm / slub.c
1 /*
2  * SLUB: A slab allocator that limits cache line use instead of queuing
3  * objects in per cpu and per node lists.
4  *
5  * The allocator synchronizes using per slab locks and only
6  * uses a centralized lock to manage a pool of partial slabs.
7  *
8  * (C) 2007 SGI, Christoph Lameter <clameter@sgi.com>
9  */
10
11 #include <linux/mm.h>
12 #include <linux/module.h>
13 #include <linux/bit_spinlock.h>
14 #include <linux/interrupt.h>
15 #include <linux/bitops.h>
16 #include <linux/slab.h>
17 #include <linux/seq_file.h>
18 #include <linux/cpu.h>
19 #include <linux/cpuset.h>
20 #include <linux/mempolicy.h>
21 #include <linux/ctype.h>
22 #include <linux/kallsyms.h>
23
24 /*
25  * Lock order:
26  *   1. slab_lock(page)
27  *   2. slab->list_lock
28  *
29  *   The slab_lock protects operations on the object of a particular
30  *   slab and its metadata in the page struct. If the slab lock
31  *   has been taken then no allocations nor frees can be performed
32  *   on the objects in the slab nor can the slab be added or removed
33  *   from the partial or full lists since this would mean modifying
34  *   the page_struct of the slab.
35  *
36  *   The list_lock protects the partial and full list on each node and
37  *   the partial slab counter. If taken then no new slabs may be added or
38  *   removed from the lists nor make the number of partial slabs be modified.
39  *   (Note that the total number of slabs is an atomic value that may be
40  *   modified without taking the list lock).
41  *
42  *   The list_lock is a centralized lock and thus we avoid taking it as
43  *   much as possible. As long as SLUB does not have to handle partial
44  *   slabs, operations can continue without any centralized lock. F.e.
45  *   allocating a long series of objects that fill up slabs does not require
46  *   the list lock.
47  *
48  *   The lock order is sometimes inverted when we are trying to get a slab
49  *   off a list. We take the list_lock and then look for a page on the list
50  *   to use. While we do that objects in the slabs may be freed. We can
51  *   only operate on the slab if we have also taken the slab_lock. So we use
52  *   a slab_trylock() on the slab. If trylock was successful then no frees
53  *   can occur anymore and we can use the slab for allocations etc. If the
54  *   slab_trylock() does not succeed then frees are in progress in the slab and
55  *   we must stay away from it for a while since we may cause a bouncing
56  *   cacheline if we try to acquire the lock. So go onto the next slab.
57  *   If all pages are busy then we may allocate a new slab instead of reusing
58  *   a partial slab. A new slab has noone operating on it and thus there is
59  *   no danger of cacheline contention.
60  *
61  *   Interrupts are disabled during allocation and deallocation in order to
62  *   make the slab allocator safe to use in the context of an irq. In addition
63  *   interrupts are disabled to ensure that the processor does not change
64  *   while handling per_cpu slabs, due to kernel preemption.
65  *
66  * SLUB assigns one slab for allocation to each processor.
67  * Allocations only occur from these slabs called cpu slabs.
68  *
69  * Slabs with free elements are kept on a partial list and during regular
70  * operations no list for full slabs is used. If an object in a full slab is
71  * freed then the slab will show up again on the partial lists.
72  * We track full slabs for debugging purposes though because otherwise we
73  * cannot scan all objects.
74  *
75  * Slabs are freed when they become empty. Teardown and setup is
76  * minimal so we rely on the page allocators per cpu caches for
77  * fast frees and allocs.
78  *
79  * Overloading of page flags that are otherwise used for LRU management.
80  *
81  * PageActive           The slab is frozen and exempt from list processing.
82  *                      This means that the slab is dedicated to a purpose
83  *                      such as satisfying allocations for a specific
84  *                      processor. Objects may be freed in the slab while
85  *                      it is frozen but slab_free will then skip the usual
86  *                      list operations. It is up to the processor holding
87  *                      the slab to integrate the slab into the slab lists
88  *                      when the slab is no longer needed.
89  *
90  *                      One use of this flag is to mark slabs that are
91  *                      used for allocations. Then such a slab becomes a cpu
92  *                      slab. The cpu slab may be equipped with an additional
93  *                      lockless_freelist that allows lockless access to
94  *                      free objects in addition to the regular freelist
95  *                      that requires the slab lock.
96  *
97  * PageError            Slab requires special handling due to debug
98  *                      options set. This moves slab handling out of
99  *                      the fast path and disables lockless freelists.
100  */
101
102 #define FROZEN (1 << PG_active)
103
104 #ifdef CONFIG_SLUB_DEBUG
105 #define SLABDEBUG (1 << PG_error)
106 #else
107 #define SLABDEBUG 0
108 #endif
109
110 static inline int SlabFrozen(struct page *page)
111 {
112         return page->flags & FROZEN;
113 }
114
115 static inline void SetSlabFrozen(struct page *page)
116 {
117         page->flags |= FROZEN;
118 }
119
120 static inline void ClearSlabFrozen(struct page *page)
121 {
122         page->flags &= ~FROZEN;
123 }
124
125 static inline int SlabDebug(struct page *page)
126 {
127         return page->flags & SLABDEBUG;
128 }
129
130 static inline void SetSlabDebug(struct page *page)
131 {
132         page->flags |= SLABDEBUG;
133 }
134
135 static inline void ClearSlabDebug(struct page *page)
136 {
137         page->flags &= ~SLABDEBUG;
138 }
139
140 /*
141  * Issues still to be resolved:
142  *
143  * - The per cpu array is updated for each new slab and and is a remote
144  *   cacheline for most nodes. This could become a bouncing cacheline given
145  *   enough frequent updates. There are 16 pointers in a cacheline, so at
146  *   max 16 cpus could compete for the cacheline which may be okay.
147  *
148  * - Support PAGE_ALLOC_DEBUG. Should be easy to do.
149  *
150  * - Variable sizing of the per node arrays
151  */
152
153 /* Enable to test recovery from slab corruption on boot */
154 #undef SLUB_RESILIENCY_TEST
155
156 #if PAGE_SHIFT <= 12
157
158 /*
159  * Small page size. Make sure that we do not fragment memory
160  */
161 #define DEFAULT_MAX_ORDER 1
162 #define DEFAULT_MIN_OBJECTS 4
163
164 #else
165
166 /*
167  * Large page machines are customarily able to handle larger
168  * page orders.
169  */
170 #define DEFAULT_MAX_ORDER 2
171 #define DEFAULT_MIN_OBJECTS 8
172
173 #endif
174
175 /*
176  * Mininum number of partial slabs. These will be left on the partial
177  * lists even if they are empty. kmem_cache_shrink may reclaim them.
178  */
179 #define MIN_PARTIAL 2
180
181 /*
182  * Maximum number of desirable partial slabs.
183  * The existence of more partial slabs makes kmem_cache_shrink
184  * sort the partial list by the number of objects in the.
185  */
186 #define MAX_PARTIAL 10
187
188 #define DEBUG_DEFAULT_FLAGS (SLAB_DEBUG_FREE | SLAB_RED_ZONE | \
189                                 SLAB_POISON | SLAB_STORE_USER)
190
191 /*
192  * Set of flags that will prevent slab merging
193  */
194 #define SLUB_NEVER_MERGE (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
195                 SLAB_TRACE | SLAB_DESTROY_BY_RCU)
196
197 #define SLUB_MERGE_SAME (SLAB_DEBUG_FREE | SLAB_RECLAIM_ACCOUNT | \
198                 SLAB_CACHE_DMA)
199
200 #ifndef ARCH_KMALLOC_MINALIGN
201 #define ARCH_KMALLOC_MINALIGN __alignof__(unsigned long long)
202 #endif
203
204 #ifndef ARCH_SLAB_MINALIGN
205 #define ARCH_SLAB_MINALIGN __alignof__(unsigned long long)
206 #endif
207
208 /* Internal SLUB flags */
209 #define __OBJECT_POISON 0x80000000      /* Poison object */
210
211 /* Not all arches define cache_line_size */
212 #ifndef cache_line_size
213 #define cache_line_size()       L1_CACHE_BYTES
214 #endif
215
216 static int kmem_size = sizeof(struct kmem_cache);
217
218 #ifdef CONFIG_SMP
219 static struct notifier_block slab_notifier;
220 #endif
221
222 static enum {
223         DOWN,           /* No slab functionality available */
224         PARTIAL,        /* kmem_cache_open() works but kmalloc does not */
225         UP,             /* Everything works but does not show up in sysfs */
226         SYSFS           /* Sysfs up */
227 } slab_state = DOWN;
228
229 /* A list of all slab caches on the system */
230 static DECLARE_RWSEM(slub_lock);
231 LIST_HEAD(slab_caches);
232
233 /*
234  * Tracking user of a slab.
235  */
236 struct track {
237         void *addr;             /* Called from address */
238         int cpu;                /* Was running on cpu */
239         int pid;                /* Pid context */
240         unsigned long when;     /* When did the operation occur */
241 };
242
243 enum track_item { TRACK_ALLOC, TRACK_FREE };
244
245 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
246 static int sysfs_slab_add(struct kmem_cache *);
247 static int sysfs_slab_alias(struct kmem_cache *, const char *);
248 static void sysfs_slab_remove(struct kmem_cache *);
249 #else
250 static int sysfs_slab_add(struct kmem_cache *s) { return 0; }
251 static int sysfs_slab_alias(struct kmem_cache *s, const char *p) { return 0; }
252 static void sysfs_slab_remove(struct kmem_cache *s) {}
253 #endif
254
255 /********************************************************************
256  *                      Core slab cache functions
257  *******************************************************************/
258
259 int slab_is_available(void)
260 {
261         return slab_state >= UP;
262 }
263
264 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node)
265 {
266 #ifdef CONFIG_NUMA
267         return s->node[node];
268 #else
269         return &s->local_node;
270 #endif
271 }
272
273 static inline int check_valid_pointer(struct kmem_cache *s,
274                                 struct page *page, const void *object)
275 {
276         void *base;
277
278         if (!object)
279                 return 1;
280
281         base = page_address(page);
282         if (object < base || object >= base + s->objects * s->size ||
283                 (object - base) % s->size) {
284                 return 0;
285         }
286
287         return 1;
288 }
289
290 /*
291  * Slow version of get and set free pointer.
292  *
293  * This version requires touching the cache lines of kmem_cache which
294  * we avoid to do in the fast alloc free paths. There we obtain the offset
295  * from the page struct.
296  */
297 static inline void *get_freepointer(struct kmem_cache *s, void *object)
298 {
299         return *(void **)(object + s->offset);
300 }
301
302 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp)
303 {
304         *(void **)(object + s->offset) = fp;
305 }
306
307 /* Loop over all objects in a slab */
308 #define for_each_object(__p, __s, __addr) \
309         for (__p = (__addr); __p < (__addr) + (__s)->objects * (__s)->size;\
310                         __p += (__s)->size)
311
312 /* Scan freelist */
313 #define for_each_free_object(__p, __s, __free) \
314         for (__p = (__free); __p; __p = get_freepointer((__s), __p))
315
316 /* Determine object index from a given position */
317 static inline int slab_index(void *p, struct kmem_cache *s, void *addr)
318 {
319         return (p - addr) / s->size;
320 }
321
322 #ifdef CONFIG_SLUB_DEBUG
323 /*
324  * Debug settings:
325  */
326 #ifdef CONFIG_SLUB_DEBUG_ON
327 static int slub_debug = DEBUG_DEFAULT_FLAGS;
328 #else
329 static int slub_debug;
330 #endif
331
332 static char *slub_debug_slabs;
333
334 /*
335  * Object debugging
336  */
337 static void print_section(char *text, u8 *addr, unsigned int length)
338 {
339         int i, offset;
340         int newline = 1;
341         char ascii[17];
342
343         ascii[16] = 0;
344
345         for (i = 0; i < length; i++) {
346                 if (newline) {
347                         printk(KERN_ERR "%8s 0x%p: ", text, addr + i);
348                         newline = 0;
349                 }
350                 printk(" %02x", addr[i]);
351                 offset = i % 16;
352                 ascii[offset] = isgraph(addr[i]) ? addr[i] : '.';
353                 if (offset == 15) {
354                         printk(" %s\n",ascii);
355                         newline = 1;
356                 }
357         }
358         if (!newline) {
359                 i %= 16;
360                 while (i < 16) {
361                         printk("   ");
362                         ascii[i] = ' ';
363                         i++;
364                 }
365                 printk(" %s\n", ascii);
366         }
367 }
368
369 static struct track *get_track(struct kmem_cache *s, void *object,
370         enum track_item alloc)
371 {
372         struct track *p;
373
374         if (s->offset)
375                 p = object + s->offset + sizeof(void *);
376         else
377                 p = object + s->inuse;
378
379         return p + alloc;
380 }
381
382 static void set_track(struct kmem_cache *s, void *object,
383                                 enum track_item alloc, void *addr)
384 {
385         struct track *p;
386
387         if (s->offset)
388                 p = object + s->offset + sizeof(void *);
389         else
390                 p = object + s->inuse;
391
392         p += alloc;
393         if (addr) {
394                 p->addr = addr;
395                 p->cpu = smp_processor_id();
396                 p->pid = current ? current->pid : -1;
397                 p->when = jiffies;
398         } else
399                 memset(p, 0, sizeof(struct track));
400 }
401
402 static void init_tracking(struct kmem_cache *s, void *object)
403 {
404         if (!(s->flags & SLAB_STORE_USER))
405                 return;
406
407         set_track(s, object, TRACK_FREE, NULL);
408         set_track(s, object, TRACK_ALLOC, NULL);
409 }
410
411 static void print_track(const char *s, struct track *t)
412 {
413         if (!t->addr)
414                 return;
415
416         printk(KERN_ERR "INFO: %s in ", s);
417         __print_symbol("%s", (unsigned long)t->addr);
418         printk(" age=%lu cpu=%u pid=%d\n", jiffies - t->when, t->cpu, t->pid);
419 }
420
421 static void print_tracking(struct kmem_cache *s, void *object)
422 {
423         if (!(s->flags & SLAB_STORE_USER))
424                 return;
425
426         print_track("Allocated", get_track(s, object, TRACK_ALLOC));
427         print_track("Freed", get_track(s, object, TRACK_FREE));
428 }
429
430 static void print_page_info(struct page *page)
431 {
432         printk(KERN_ERR "INFO: Slab 0x%p used=%u fp=0x%p flags=0x%04lx\n",
433                 page, page->inuse, page->freelist, page->flags);
434
435 }
436
437 static void slab_bug(struct kmem_cache *s, char *fmt, ...)
438 {
439         va_list args;
440         char buf[100];
441
442         va_start(args, fmt);
443         vsnprintf(buf, sizeof(buf), fmt, args);
444         va_end(args);
445         printk(KERN_ERR "========================================"
446                         "=====================================\n");
447         printk(KERN_ERR "BUG %s: %s\n", s->name, buf);
448         printk(KERN_ERR "----------------------------------------"
449                         "-------------------------------------\n\n");
450 }
451
452 static void slab_fix(struct kmem_cache *s, char *fmt, ...)
453 {
454         va_list args;
455         char buf[100];
456
457         va_start(args, fmt);
458         vsnprintf(buf, sizeof(buf), fmt, args);
459         va_end(args);
460         printk(KERN_ERR "FIX %s: %s\n", s->name, buf);
461 }
462
463 static void print_trailer(struct kmem_cache *s, struct page *page, u8 *p)
464 {
465         unsigned int off;       /* Offset of last byte */
466         u8 *addr = page_address(page);
467
468         print_tracking(s, p);
469
470         print_page_info(page);
471
472         printk(KERN_ERR "INFO: Object 0x%p @offset=%tu fp=0x%p\n\n",
473                         p, p - addr, get_freepointer(s, p));
474
475         if (p > addr + 16)
476                 print_section("Bytes b4", p - 16, 16);
477
478         print_section("Object", p, min(s->objsize, 128));
479
480         if (s->flags & SLAB_RED_ZONE)
481                 print_section("Redzone", p + s->objsize,
482                         s->inuse - s->objsize);
483
484         if (s->offset)
485                 off = s->offset + sizeof(void *);
486         else
487                 off = s->inuse;
488
489         if (s->flags & SLAB_STORE_USER)
490                 off += 2 * sizeof(struct track);
491
492         if (off != s->size)
493                 /* Beginning of the filler is the free pointer */
494                 print_section("Padding", p + off, s->size - off);
495
496         dump_stack();
497 }
498
499 static void object_err(struct kmem_cache *s, struct page *page,
500                         u8 *object, char *reason)
501 {
502         slab_bug(s, reason);
503         print_trailer(s, page, object);
504 }
505
506 static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
507 {
508         va_list args;
509         char buf[100];
510
511         va_start(args, fmt);
512         vsnprintf(buf, sizeof(buf), fmt, args);
513         va_end(args);
514         slab_bug(s, fmt);
515         print_page_info(page);
516         dump_stack();
517 }
518
519 static void init_object(struct kmem_cache *s, void *object, int active)
520 {
521         u8 *p = object;
522
523         if (s->flags & __OBJECT_POISON) {
524                 memset(p, POISON_FREE, s->objsize - 1);
525                 p[s->objsize -1] = POISON_END;
526         }
527
528         if (s->flags & SLAB_RED_ZONE)
529                 memset(p + s->objsize,
530                         active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE,
531                         s->inuse - s->objsize);
532 }
533
534 static u8 *check_bytes(u8 *start, unsigned int value, unsigned int bytes)
535 {
536         while (bytes) {
537                 if (*start != (u8)value)
538                         return start;
539                 start++;
540                 bytes--;
541         }
542         return NULL;
543 }
544
545 static void restore_bytes(struct kmem_cache *s, char *message, u8 data,
546                                                 void *from, void *to)
547 {
548         slab_fix(s, "Restoring 0x%p-0x%p=0x%x\n", from, to - 1, data);
549         memset(from, data, to - from);
550 }
551
552 static int check_bytes_and_report(struct kmem_cache *s, struct page *page,
553                         u8 *object, char *what,
554                         u8* start, unsigned int value, unsigned int bytes)
555 {
556         u8 *fault;
557         u8 *end;
558
559         fault = check_bytes(start, value, bytes);
560         if (!fault)
561                 return 1;
562
563         end = start + bytes;
564         while (end > fault && end[-1] == value)
565                 end--;
566
567         slab_bug(s, "%s overwritten", what);
568         printk(KERN_ERR "INFO: 0x%p-0x%p. First byte 0x%x instead of 0x%x\n",
569                                         fault, end - 1, fault[0], value);
570         print_trailer(s, page, object);
571
572         restore_bytes(s, what, value, fault, end);
573         return 0;
574 }
575
576 /*
577  * Object layout:
578  *
579  * object address
580  *      Bytes of the object to be managed.
581  *      If the freepointer may overlay the object then the free
582  *      pointer is the first word of the object.
583  *
584  *      Poisoning uses 0x6b (POISON_FREE) and the last byte is
585  *      0xa5 (POISON_END)
586  *
587  * object + s->objsize
588  *      Padding to reach word boundary. This is also used for Redzoning.
589  *      Padding is extended by another word if Redzoning is enabled and
590  *      objsize == inuse.
591  *
592  *      We fill with 0xbb (RED_INACTIVE) for inactive objects and with
593  *      0xcc (RED_ACTIVE) for objects in use.
594  *
595  * object + s->inuse
596  *      Meta data starts here.
597  *
598  *      A. Free pointer (if we cannot overwrite object on free)
599  *      B. Tracking data for SLAB_STORE_USER
600  *      C. Padding to reach required alignment boundary or at mininum
601  *              one word if debuggin is on to be able to detect writes
602  *              before the word boundary.
603  *
604  *      Padding is done using 0x5a (POISON_INUSE)
605  *
606  * object + s->size
607  *      Nothing is used beyond s->size.
608  *
609  * If slabcaches are merged then the objsize and inuse boundaries are mostly
610  * ignored. And therefore no slab options that rely on these boundaries
611  * may be used with merged slabcaches.
612  */
613
614 static int check_pad_bytes(struct kmem_cache *s, struct page *page, u8 *p)
615 {
616         unsigned long off = s->inuse;   /* The end of info */
617
618         if (s->offset)
619                 /* Freepointer is placed after the object. */
620                 off += sizeof(void *);
621
622         if (s->flags & SLAB_STORE_USER)
623                 /* We also have user information there */
624                 off += 2 * sizeof(struct track);
625
626         if (s->size == off)
627                 return 1;
628
629         return check_bytes_and_report(s, page, p, "Object padding",
630                                 p + off, POISON_INUSE, s->size - off);
631 }
632
633 static int slab_pad_check(struct kmem_cache *s, struct page *page)
634 {
635         u8 *start;
636         u8 *fault;
637         u8 *end;
638         int length;
639         int remainder;
640
641         if (!(s->flags & SLAB_POISON))
642                 return 1;
643
644         start = page_address(page);
645         end = start + (PAGE_SIZE << s->order);
646         length = s->objects * s->size;
647         remainder = end - (start + length);
648         if (!remainder)
649                 return 1;
650
651         fault = check_bytes(start + length, POISON_INUSE, remainder);
652         if (!fault)
653                 return 1;
654         while (end > fault && end[-1] == POISON_INUSE)
655                 end--;
656
657         slab_err(s, page, "Padding overwritten. 0x%p-0x%p", fault, end - 1);
658         print_section("Padding", start, length);
659
660         restore_bytes(s, "slab padding", POISON_INUSE, start, end);
661         return 0;
662 }
663
664 static int check_object(struct kmem_cache *s, struct page *page,
665                                         void *object, int active)
666 {
667         u8 *p = object;
668         u8 *endobject = object + s->objsize;
669
670         if (s->flags & SLAB_RED_ZONE) {
671                 unsigned int red =
672                         active ? SLUB_RED_ACTIVE : SLUB_RED_INACTIVE;
673
674                 if (!check_bytes_and_report(s, page, object, "Redzone",
675                         endobject, red, s->inuse - s->objsize))
676                         return 0;
677         } else {
678                 if ((s->flags & SLAB_POISON) && s->objsize < s->inuse)
679                         check_bytes_and_report(s, page, p, "Alignment padding", endobject,
680                                 POISON_INUSE, s->inuse - s->objsize);
681         }
682
683         if (s->flags & SLAB_POISON) {
684                 if (!active && (s->flags & __OBJECT_POISON) &&
685                         (!check_bytes_and_report(s, page, p, "Poison", p,
686                                         POISON_FREE, s->objsize - 1) ||
687                          !check_bytes_and_report(s, page, p, "Poison",
688                                 p + s->objsize -1, POISON_END, 1)))
689                         return 0;
690                 /*
691                  * check_pad_bytes cleans up on its own.
692                  */
693                 check_pad_bytes(s, page, p);
694         }
695
696         if (!s->offset && active)
697                 /*
698                  * Object and freepointer overlap. Cannot check
699                  * freepointer while object is allocated.
700                  */
701                 return 1;
702
703         /* Check free pointer validity */
704         if (!check_valid_pointer(s, page, get_freepointer(s, p))) {
705                 object_err(s, page, p, "Freepointer corrupt");
706                 /*
707                  * No choice but to zap it and thus loose the remainder
708                  * of the free objects in this slab. May cause
709                  * another error because the object count is now wrong.
710                  */
711                 set_freepointer(s, p, NULL);
712                 return 0;
713         }
714         return 1;
715 }
716
717 static int check_slab(struct kmem_cache *s, struct page *page)
718 {
719         VM_BUG_ON(!irqs_disabled());
720
721         if (!PageSlab(page)) {
722                 slab_err(s, page, "Not a valid slab page");
723                 return 0;
724         }
725         if (page->offset * sizeof(void *) != s->offset) {
726                 slab_err(s, page, "Corrupted offset %lu",
727                         (unsigned long)(page->offset * sizeof(void *)));
728                 return 0;
729         }
730         if (page->inuse > s->objects) {
731                 slab_err(s, page, "inuse %u > max %u",
732                         s->name, page->inuse, s->objects);
733                 return 0;
734         }
735         /* Slab_pad_check fixes things up after itself */
736         slab_pad_check(s, page);
737         return 1;
738 }
739
740 /*
741  * Determine if a certain object on a page is on the freelist. Must hold the
742  * slab lock to guarantee that the chains are in a consistent state.
743  */
744 static int on_freelist(struct kmem_cache *s, struct page *page, void *search)
745 {
746         int nr = 0;
747         void *fp = page->freelist;
748         void *object = NULL;
749
750         while (fp && nr <= s->objects) {
751                 if (fp == search)
752                         return 1;
753                 if (!check_valid_pointer(s, page, fp)) {
754                         if (object) {
755                                 object_err(s, page, object,
756                                         "Freechain corrupt");
757                                 set_freepointer(s, object, NULL);
758                                 break;
759                         } else {
760                                 slab_err(s, page, "Freepointer corrupt");
761                                 page->freelist = NULL;
762                                 page->inuse = s->objects;
763                                 slab_fix(s, "Freelist cleared");
764                                 return 0;
765                         }
766                         break;
767                 }
768                 object = fp;
769                 fp = get_freepointer(s, object);
770                 nr++;
771         }
772
773         if (page->inuse != s->objects - nr) {
774                 slab_err(s, page, "Wrong object count. Counter is %d but "
775                         "counted were %d", page->inuse, s->objects - nr);
776                 page->inuse = s->objects - nr;
777                 slab_fix(s, "Object count adjusted.");
778         }
779         return search == NULL;
780 }
781
782 static void trace(struct kmem_cache *s, struct page *page, void *object, int alloc)
783 {
784         if (s->flags & SLAB_TRACE) {
785                 printk(KERN_INFO "TRACE %s %s 0x%p inuse=%d fp=0x%p\n",
786                         s->name,
787                         alloc ? "alloc" : "free",
788                         object, page->inuse,
789                         page->freelist);
790
791                 if (!alloc)
792                         print_section("Object", (void *)object, s->objsize);
793
794                 dump_stack();
795         }
796 }
797
798 /*
799  * Tracking of fully allocated slabs for debugging purposes.
800  */
801 static void add_full(struct kmem_cache_node *n, struct page *page)
802 {
803         spin_lock(&n->list_lock);
804         list_add(&page->lru, &n->full);
805         spin_unlock(&n->list_lock);
806 }
807
808 static void remove_full(struct kmem_cache *s, struct page *page)
809 {
810         struct kmem_cache_node *n;
811
812         if (!(s->flags & SLAB_STORE_USER))
813                 return;
814
815         n = get_node(s, page_to_nid(page));
816
817         spin_lock(&n->list_lock);
818         list_del(&page->lru);
819         spin_unlock(&n->list_lock);
820 }
821
822 static void setup_object_debug(struct kmem_cache *s, struct page *page,
823                                                                 void *object)
824 {
825         if (!(s->flags & (SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)))
826                 return;
827
828         init_object(s, object, 0);
829         init_tracking(s, object);
830 }
831
832 static int alloc_debug_processing(struct kmem_cache *s, struct page *page,
833                                                 void *object, void *addr)
834 {
835         if (!check_slab(s, page))
836                 goto bad;
837
838         if (object && !on_freelist(s, page, object)) {
839                 object_err(s, page, object, "Object already allocated");
840                 goto bad;
841         }
842
843         if (!check_valid_pointer(s, page, object)) {
844                 object_err(s, page, object, "Freelist Pointer check fails");
845                 goto bad;
846         }
847
848         if (object && !check_object(s, page, object, 0))
849                 goto bad;
850
851         /* Success perform special debug activities for allocs */
852         if (s->flags & SLAB_STORE_USER)
853                 set_track(s, object, TRACK_ALLOC, addr);
854         trace(s, page, object, 1);
855         init_object(s, object, 1);
856         return 1;
857
858 bad:
859         if (PageSlab(page)) {
860                 /*
861                  * If this is a slab page then lets do the best we can
862                  * to avoid issues in the future. Marking all objects
863                  * as used avoids touching the remaining objects.
864                  */
865                 slab_fix(s, "Marking all objects used");
866                 page->inuse = s->objects;
867                 page->freelist = NULL;
868                 /* Fix up fields that may be corrupted */
869                 page->offset = s->offset / sizeof(void *);
870         }
871         return 0;
872 }
873
874 static int free_debug_processing(struct kmem_cache *s, struct page *page,
875                                                 void *object, void *addr)
876 {
877         if (!check_slab(s, page))
878                 goto fail;
879
880         if (!check_valid_pointer(s, page, object)) {
881                 slab_err(s, page, "Invalid object pointer 0x%p", object);
882                 goto fail;
883         }
884
885         if (on_freelist(s, page, object)) {
886                 object_err(s, page, object, "Object already free");
887                 goto fail;
888         }
889
890         if (!check_object(s, page, object, 1))
891                 return 0;
892
893         if (unlikely(s != page->slab)) {
894                 if (!PageSlab(page))
895                         slab_err(s, page, "Attempt to free object(0x%p) "
896                                 "outside of slab", object);
897                 else
898                 if (!page->slab) {
899                         printk(KERN_ERR
900                                 "SLUB <none>: no slab for object 0x%p.\n",
901                                                 object);
902                         dump_stack();
903                 }
904                 else
905                         object_err(s, page, object,
906                                         "page slab pointer corrupt.");
907                 goto fail;
908         }
909
910         /* Special debug activities for freeing objects */
911         if (!SlabFrozen(page) && !page->freelist)
912                 remove_full(s, page);
913         if (s->flags & SLAB_STORE_USER)
914                 set_track(s, object, TRACK_FREE, addr);
915         trace(s, page, object, 0);
916         init_object(s, object, 0);
917         return 1;
918
919 fail:
920         slab_fix(s, "Object at 0x%p not freed", object);
921         return 0;
922 }
923
924 static int __init setup_slub_debug(char *str)
925 {
926         slub_debug = DEBUG_DEFAULT_FLAGS;
927         if (*str++ != '=' || !*str)
928                 /*
929                  * No options specified. Switch on full debugging.
930                  */
931                 goto out;
932
933         if (*str == ',')
934                 /*
935                  * No options but restriction on slabs. This means full
936                  * debugging for slabs matching a pattern.
937                  */
938                 goto check_slabs;
939
940         slub_debug = 0;
941         if (*str == '-')
942                 /*
943                  * Switch off all debugging measures.
944                  */
945                 goto out;
946
947         /*
948          * Determine which debug features should be switched on
949          */
950         for ( ;*str && *str != ','; str++) {
951                 switch (tolower(*str)) {
952                 case 'f':
953                         slub_debug |= SLAB_DEBUG_FREE;
954                         break;
955                 case 'z':
956                         slub_debug |= SLAB_RED_ZONE;
957                         break;
958                 case 'p':
959                         slub_debug |= SLAB_POISON;
960                         break;
961                 case 'u':
962                         slub_debug |= SLAB_STORE_USER;
963                         break;
964                 case 't':
965                         slub_debug |= SLAB_TRACE;
966                         break;
967                 default:
968                         printk(KERN_ERR "slub_debug option '%c' "
969                                 "unknown. skipped\n",*str);
970                 }
971         }
972
973 check_slabs:
974         if (*str == ',')
975                 slub_debug_slabs = str + 1;
976 out:
977         return 1;
978 }
979
980 __setup("slub_debug", setup_slub_debug);
981
982 static void kmem_cache_open_debug_check(struct kmem_cache *s)
983 {
984         /*
985          * The page->offset field is only 16 bit wide. This is an offset
986          * in units of words from the beginning of an object. If the slab
987          * size is bigger then we cannot move the free pointer behind the
988          * object anymore.
989          *
990          * On 32 bit platforms the limit is 256k. On 64bit platforms
991          * the limit is 512k.
992          *
993          * Debugging or ctor may create a need to move the free
994          * pointer. Fail if this happens.
995          */
996         if (s->objsize >= 65535 * sizeof(void *)) {
997                 BUG_ON(s->flags & (SLAB_RED_ZONE | SLAB_POISON |
998                                 SLAB_STORE_USER | SLAB_DESTROY_BY_RCU));
999                 BUG_ON(s->ctor);
1000         }
1001         else
1002                 /*
1003                  * Enable debugging if selected on the kernel commandline.
1004                  */
1005                 if (slub_debug && (!slub_debug_slabs ||
1006                     strncmp(slub_debug_slabs, s->name,
1007                         strlen(slub_debug_slabs)) == 0))
1008                                 s->flags |= slub_debug;
1009 }
1010 #else
1011 static inline void setup_object_debug(struct kmem_cache *s,
1012                         struct page *page, void *object) {}
1013
1014 static inline int alloc_debug_processing(struct kmem_cache *s,
1015         struct page *page, void *object, void *addr) { return 0; }
1016
1017 static inline int free_debug_processing(struct kmem_cache *s,
1018         struct page *page, void *object, void *addr) { return 0; }
1019
1020 static inline int slab_pad_check(struct kmem_cache *s, struct page *page)
1021                         { return 1; }
1022 static inline int check_object(struct kmem_cache *s, struct page *page,
1023                         void *object, int active) { return 1; }
1024 static inline void add_full(struct kmem_cache_node *n, struct page *page) {}
1025 static inline void kmem_cache_open_debug_check(struct kmem_cache *s) {}
1026 #define slub_debug 0
1027 #endif
1028 /*
1029  * Slab allocation and freeing
1030  */
1031 static struct page *allocate_slab(struct kmem_cache *s, gfp_t flags, int node)
1032 {
1033         struct page * page;
1034         int pages = 1 << s->order;
1035
1036         if (s->order)
1037                 flags |= __GFP_COMP;
1038
1039         if (s->flags & SLAB_CACHE_DMA)
1040                 flags |= SLUB_DMA;
1041
1042         if (node == -1)
1043                 page = alloc_pages(flags, s->order);
1044         else
1045                 page = alloc_pages_node(node, flags, s->order);
1046
1047         if (!page)
1048                 return NULL;
1049
1050         mod_zone_page_state(page_zone(page),
1051                 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1052                 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1053                 pages);
1054
1055         return page;
1056 }
1057
1058 static void setup_object(struct kmem_cache *s, struct page *page,
1059                                 void *object)
1060 {
1061         setup_object_debug(s, page, object);
1062         if (unlikely(s->ctor))
1063                 s->ctor(object, s, 0);
1064 }
1065
1066 static struct page *new_slab(struct kmem_cache *s, gfp_t flags, int node)
1067 {
1068         struct page *page;
1069         struct kmem_cache_node *n;
1070         void *start;
1071         void *end;
1072         void *last;
1073         void *p;
1074
1075         BUG_ON(flags & ~(GFP_DMA | GFP_LEVEL_MASK));
1076
1077         if (flags & __GFP_WAIT)
1078                 local_irq_enable();
1079
1080         page = allocate_slab(s, flags & GFP_LEVEL_MASK, node);
1081         if (!page)
1082                 goto out;
1083
1084         n = get_node(s, page_to_nid(page));
1085         if (n)
1086                 atomic_long_inc(&n->nr_slabs);
1087         page->offset = s->offset / sizeof(void *);
1088         page->slab = s;
1089         page->flags |= 1 << PG_slab;
1090         if (s->flags & (SLAB_DEBUG_FREE | SLAB_RED_ZONE | SLAB_POISON |
1091                         SLAB_STORE_USER | SLAB_TRACE))
1092                 SetSlabDebug(page);
1093
1094         start = page_address(page);
1095         end = start + s->objects * s->size;
1096
1097         if (unlikely(s->flags & SLAB_POISON))
1098                 memset(start, POISON_INUSE, PAGE_SIZE << s->order);
1099
1100         last = start;
1101         for_each_object(p, s, start) {
1102                 setup_object(s, page, last);
1103                 set_freepointer(s, last, p);
1104                 last = p;
1105         }
1106         setup_object(s, page, last);
1107         set_freepointer(s, last, NULL);
1108
1109         page->freelist = start;
1110         page->lockless_freelist = NULL;
1111         page->inuse = 0;
1112 out:
1113         if (flags & __GFP_WAIT)
1114                 local_irq_disable();
1115         return page;
1116 }
1117
1118 static void __free_slab(struct kmem_cache *s, struct page *page)
1119 {
1120         int pages = 1 << s->order;
1121
1122         if (unlikely(SlabDebug(page))) {
1123                 void *p;
1124
1125                 slab_pad_check(s, page);
1126                 for_each_object(p, s, page_address(page))
1127                         check_object(s, page, p, 0);
1128         }
1129
1130         mod_zone_page_state(page_zone(page),
1131                 (s->flags & SLAB_RECLAIM_ACCOUNT) ?
1132                 NR_SLAB_RECLAIMABLE : NR_SLAB_UNRECLAIMABLE,
1133                 - pages);
1134
1135         page->mapping = NULL;
1136         __free_pages(page, s->order);
1137 }
1138
1139 static void rcu_free_slab(struct rcu_head *h)
1140 {
1141         struct page *page;
1142
1143         page = container_of((struct list_head *)h, struct page, lru);
1144         __free_slab(page->slab, page);
1145 }
1146
1147 static void free_slab(struct kmem_cache *s, struct page *page)
1148 {
1149         if (unlikely(s->flags & SLAB_DESTROY_BY_RCU)) {
1150                 /*
1151                  * RCU free overloads the RCU head over the LRU
1152                  */
1153                 struct rcu_head *head = (void *)&page->lru;
1154
1155                 call_rcu(head, rcu_free_slab);
1156         } else
1157                 __free_slab(s, page);
1158 }
1159
1160 static void discard_slab(struct kmem_cache *s, struct page *page)
1161 {
1162         struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1163
1164         atomic_long_dec(&n->nr_slabs);
1165         reset_page_mapcount(page);
1166         ClearSlabDebug(page);
1167         __ClearPageSlab(page);
1168         free_slab(s, page);
1169 }
1170
1171 /*
1172  * Per slab locking using the pagelock
1173  */
1174 static __always_inline void slab_lock(struct page *page)
1175 {
1176         bit_spin_lock(PG_locked, &page->flags);
1177 }
1178
1179 static __always_inline void slab_unlock(struct page *page)
1180 {
1181         bit_spin_unlock(PG_locked, &page->flags);
1182 }
1183
1184 static __always_inline int slab_trylock(struct page *page)
1185 {
1186         int rc = 1;
1187
1188         rc = bit_spin_trylock(PG_locked, &page->flags);
1189         return rc;
1190 }
1191
1192 /*
1193  * Management of partially allocated slabs
1194  */
1195 static void add_partial_tail(struct kmem_cache_node *n, struct page *page)
1196 {
1197         spin_lock(&n->list_lock);
1198         n->nr_partial++;
1199         list_add_tail(&page->lru, &n->partial);
1200         spin_unlock(&n->list_lock);
1201 }
1202
1203 static void add_partial(struct kmem_cache_node *n, struct page *page)
1204 {
1205         spin_lock(&n->list_lock);
1206         n->nr_partial++;
1207         list_add(&page->lru, &n->partial);
1208         spin_unlock(&n->list_lock);
1209 }
1210
1211 static void remove_partial(struct kmem_cache *s,
1212                                                 struct page *page)
1213 {
1214         struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1215
1216         spin_lock(&n->list_lock);
1217         list_del(&page->lru);
1218         n->nr_partial--;
1219         spin_unlock(&n->list_lock);
1220 }
1221
1222 /*
1223  * Lock slab and remove from the partial list.
1224  *
1225  * Must hold list_lock.
1226  */
1227 static inline int lock_and_freeze_slab(struct kmem_cache_node *n, struct page *page)
1228 {
1229         if (slab_trylock(page)) {
1230                 list_del(&page->lru);
1231                 n->nr_partial--;
1232                 SetSlabFrozen(page);
1233                 return 1;
1234         }
1235         return 0;
1236 }
1237
1238 /*
1239  * Try to allocate a partial slab from a specific node.
1240  */
1241 static struct page *get_partial_node(struct kmem_cache_node *n)
1242 {
1243         struct page *page;
1244
1245         /*
1246          * Racy check. If we mistakenly see no partial slabs then we
1247          * just allocate an empty slab. If we mistakenly try to get a
1248          * partial slab and there is none available then get_partials()
1249          * will return NULL.
1250          */
1251         if (!n || !n->nr_partial)
1252                 return NULL;
1253
1254         spin_lock(&n->list_lock);
1255         list_for_each_entry(page, &n->partial, lru)
1256                 if (lock_and_freeze_slab(n, page))
1257                         goto out;
1258         page = NULL;
1259 out:
1260         spin_unlock(&n->list_lock);
1261         return page;
1262 }
1263
1264 /*
1265  * Get a page from somewhere. Search in increasing NUMA distances.
1266  */
1267 static struct page *get_any_partial(struct kmem_cache *s, gfp_t flags)
1268 {
1269 #ifdef CONFIG_NUMA
1270         struct zonelist *zonelist;
1271         struct zone **z;
1272         struct page *page;
1273
1274         /*
1275          * The defrag ratio allows a configuration of the tradeoffs between
1276          * inter node defragmentation and node local allocations. A lower
1277          * defrag_ratio increases the tendency to do local allocations
1278          * instead of attempting to obtain partial slabs from other nodes.
1279          *
1280          * If the defrag_ratio is set to 0 then kmalloc() always
1281          * returns node local objects. If the ratio is higher then kmalloc()
1282          * may return off node objects because partial slabs are obtained
1283          * from other nodes and filled up.
1284          *
1285          * If /sys/slab/xx/defrag_ratio is set to 100 (which makes
1286          * defrag_ratio = 1000) then every (well almost) allocation will
1287          * first attempt to defrag slab caches on other nodes. This means
1288          * scanning over all nodes to look for partial slabs which may be
1289          * expensive if we do it every time we are trying to find a slab
1290          * with available objects.
1291          */
1292         if (!s->defrag_ratio || get_cycles() % 1024 > s->defrag_ratio)
1293                 return NULL;
1294
1295         zonelist = &NODE_DATA(slab_node(current->mempolicy))
1296                                         ->node_zonelists[gfp_zone(flags)];
1297         for (z = zonelist->zones; *z; z++) {
1298                 struct kmem_cache_node *n;
1299
1300                 n = get_node(s, zone_to_nid(*z));
1301
1302                 if (n && cpuset_zone_allowed_hardwall(*z, flags) &&
1303                                 n->nr_partial > MIN_PARTIAL) {
1304                         page = get_partial_node(n);
1305                         if (page)
1306                                 return page;
1307                 }
1308         }
1309 #endif
1310         return NULL;
1311 }
1312
1313 /*
1314  * Get a partial page, lock it and return it.
1315  */
1316 static struct page *get_partial(struct kmem_cache *s, gfp_t flags, int node)
1317 {
1318         struct page *page;
1319         int searchnode = (node == -1) ? numa_node_id() : node;
1320
1321         page = get_partial_node(get_node(s, searchnode));
1322         if (page || (flags & __GFP_THISNODE))
1323                 return page;
1324
1325         return get_any_partial(s, flags);
1326 }
1327
1328 /*
1329  * Move a page back to the lists.
1330  *
1331  * Must be called with the slab lock held.
1332  *
1333  * On exit the slab lock will have been dropped.
1334  */
1335 static void unfreeze_slab(struct kmem_cache *s, struct page *page)
1336 {
1337         struct kmem_cache_node *n = get_node(s, page_to_nid(page));
1338
1339         ClearSlabFrozen(page);
1340         if (page->inuse) {
1341
1342                 if (page->freelist)
1343                         add_partial(n, page);
1344                 else if (SlabDebug(page) && (s->flags & SLAB_STORE_USER))
1345                         add_full(n, page);
1346                 slab_unlock(page);
1347
1348         } else {
1349                 if (n->nr_partial < MIN_PARTIAL) {
1350                         /*
1351                          * Adding an empty slab to the partial slabs in order
1352                          * to avoid page allocator overhead. This slab needs
1353                          * to come after the other slabs with objects in
1354                          * order to fill them up. That way the size of the
1355                          * partial list stays small. kmem_cache_shrink can
1356                          * reclaim empty slabs from the partial list.
1357                          */
1358                         add_partial_tail(n, page);
1359                         slab_unlock(page);
1360                 } else {
1361                         slab_unlock(page);
1362                         discard_slab(s, page);
1363                 }
1364         }
1365 }
1366
1367 /*
1368  * Remove the cpu slab
1369  */
1370 static void deactivate_slab(struct kmem_cache *s, struct page *page, int cpu)
1371 {
1372         /*
1373          * Merge cpu freelist into freelist. Typically we get here
1374          * because both freelists are empty. So this is unlikely
1375          * to occur.
1376          */
1377         while (unlikely(page->lockless_freelist)) {
1378                 void **object;
1379
1380                 /* Retrieve object from cpu_freelist */
1381                 object = page->lockless_freelist;
1382                 page->lockless_freelist = page->lockless_freelist[page->offset];
1383
1384                 /* And put onto the regular freelist */
1385                 object[page->offset] = page->freelist;
1386                 page->freelist = object;
1387                 page->inuse--;
1388         }
1389         s->cpu_slab[cpu] = NULL;
1390         unfreeze_slab(s, page);
1391 }
1392
1393 static void flush_slab(struct kmem_cache *s, struct page *page, int cpu)
1394 {
1395         slab_lock(page);
1396         deactivate_slab(s, page, cpu);
1397 }
1398
1399 /*
1400  * Flush cpu slab.
1401  * Called from IPI handler with interrupts disabled.
1402  */
1403 static void __flush_cpu_slab(struct kmem_cache *s, int cpu)
1404 {
1405         struct page *page = s->cpu_slab[cpu];
1406
1407         if (likely(page))
1408                 flush_slab(s, page, cpu);
1409 }
1410
1411 static void flush_cpu_slab(void *d)
1412 {
1413         struct kmem_cache *s = d;
1414         int cpu = smp_processor_id();
1415
1416         __flush_cpu_slab(s, cpu);
1417 }
1418
1419 static void flush_all(struct kmem_cache *s)
1420 {
1421 #ifdef CONFIG_SMP
1422         on_each_cpu(flush_cpu_slab, s, 1, 1);
1423 #else
1424         unsigned long flags;
1425
1426         local_irq_save(flags);
1427         flush_cpu_slab(s);
1428         local_irq_restore(flags);
1429 #endif
1430 }
1431
1432 /*
1433  * Slow path. The lockless freelist is empty or we need to perform
1434  * debugging duties.
1435  *
1436  * Interrupts are disabled.
1437  *
1438  * Processing is still very fast if new objects have been freed to the
1439  * regular freelist. In that case we simply take over the regular freelist
1440  * as the lockless freelist and zap the regular freelist.
1441  *
1442  * If that is not working then we fall back to the partial lists. We take the
1443  * first element of the freelist as the object to allocate now and move the
1444  * rest of the freelist to the lockless freelist.
1445  *
1446  * And if we were unable to get a new slab from the partial slab lists then
1447  * we need to allocate a new slab. This is slowest path since we may sleep.
1448  */
1449 static void *__slab_alloc(struct kmem_cache *s,
1450                 gfp_t gfpflags, int node, void *addr, struct page *page)
1451 {
1452         void **object;
1453         int cpu = smp_processor_id();
1454
1455         if (!page)
1456                 goto new_slab;
1457
1458         slab_lock(page);
1459         if (unlikely(node != -1 && page_to_nid(page) != node))
1460                 goto another_slab;
1461 load_freelist:
1462         object = page->freelist;
1463         if (unlikely(!object))
1464                 goto another_slab;
1465         if (unlikely(SlabDebug(page)))
1466                 goto debug;
1467
1468         object = page->freelist;
1469         page->lockless_freelist = object[page->offset];
1470         page->inuse = s->objects;
1471         page->freelist = NULL;
1472         slab_unlock(page);
1473         return object;
1474
1475 another_slab:
1476         deactivate_slab(s, page, cpu);
1477
1478 new_slab:
1479         page = get_partial(s, gfpflags, node);
1480         if (page) {
1481                 s->cpu_slab[cpu] = page;
1482                 goto load_freelist;
1483         }
1484
1485         page = new_slab(s, gfpflags, node);
1486         if (page) {
1487                 cpu = smp_processor_id();
1488                 if (s->cpu_slab[cpu]) {
1489                         /*
1490                          * Someone else populated the cpu_slab while we
1491                          * enabled interrupts, or we have gotten scheduled
1492                          * on another cpu. The page may not be on the
1493                          * requested node even if __GFP_THISNODE was
1494                          * specified. So we need to recheck.
1495                          */
1496                         if (node == -1 ||
1497                                 page_to_nid(s->cpu_slab[cpu]) == node) {
1498                                 /*
1499                                  * Current cpuslab is acceptable and we
1500                                  * want the current one since its cache hot
1501                                  */
1502                                 discard_slab(s, page);
1503                                 page = s->cpu_slab[cpu];
1504                                 slab_lock(page);
1505                                 goto load_freelist;
1506                         }
1507                         /* New slab does not fit our expectations */
1508                         flush_slab(s, s->cpu_slab[cpu], cpu);
1509                 }
1510                 slab_lock(page);
1511                 SetSlabFrozen(page);
1512                 s->cpu_slab[cpu] = page;
1513                 goto load_freelist;
1514         }
1515         return NULL;
1516 debug:
1517         object = page->freelist;
1518         if (!alloc_debug_processing(s, page, object, addr))
1519                 goto another_slab;
1520
1521         page->inuse++;
1522         page->freelist = object[page->offset];
1523         slab_unlock(page);
1524         return object;
1525 }
1526
1527 /*
1528  * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc)
1529  * have the fastpath folded into their functions. So no function call
1530  * overhead for requests that can be satisfied on the fastpath.
1531  *
1532  * The fastpath works by first checking if the lockless freelist can be used.
1533  * If not then __slab_alloc is called for slow processing.
1534  *
1535  * Otherwise we can simply pick the next object from the lockless free list.
1536  */
1537 static void __always_inline *slab_alloc(struct kmem_cache *s,
1538                                 gfp_t gfpflags, int node, void *addr)
1539 {
1540         struct page *page;
1541         void **object;
1542         unsigned long flags;
1543
1544         local_irq_save(flags);
1545         page = s->cpu_slab[smp_processor_id()];
1546         if (unlikely(!page || !page->lockless_freelist ||
1547                         (node != -1 && page_to_nid(page) != node)))
1548
1549                 object = __slab_alloc(s, gfpflags, node, addr, page);
1550
1551         else {
1552                 object = page->lockless_freelist;
1553                 page->lockless_freelist = object[page->offset];
1554         }
1555         local_irq_restore(flags);
1556         return object;
1557 }
1558
1559 void *kmem_cache_alloc(struct kmem_cache *s, gfp_t gfpflags)
1560 {
1561         return slab_alloc(s, gfpflags, -1, __builtin_return_address(0));
1562 }
1563 EXPORT_SYMBOL(kmem_cache_alloc);
1564
1565 #ifdef CONFIG_NUMA
1566 void *kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
1567 {
1568         return slab_alloc(s, gfpflags, node, __builtin_return_address(0));
1569 }
1570 EXPORT_SYMBOL(kmem_cache_alloc_node);
1571 #endif
1572
1573 /*
1574  * Slow patch handling. This may still be called frequently since objects
1575  * have a longer lifetime than the cpu slabs in most processing loads.
1576  *
1577  * So we still attempt to reduce cache line usage. Just take the slab
1578  * lock and free the item. If there is no additional partial page
1579  * handling required then we can return immediately.
1580  */
1581 static void __slab_free(struct kmem_cache *s, struct page *page,
1582                                         void *x, void *addr)
1583 {
1584         void *prior;
1585         void **object = (void *)x;
1586
1587         slab_lock(page);
1588
1589         if (unlikely(SlabDebug(page)))
1590                 goto debug;
1591 checks_ok:
1592         prior = object[page->offset] = page->freelist;
1593         page->freelist = object;
1594         page->inuse--;
1595
1596         if (unlikely(SlabFrozen(page)))
1597                 goto out_unlock;
1598
1599         if (unlikely(!page->inuse))
1600                 goto slab_empty;
1601
1602         /*
1603          * Objects left in the slab. If it
1604          * was not on the partial list before
1605          * then add it.
1606          */
1607         if (unlikely(!prior))
1608                 add_partial(get_node(s, page_to_nid(page)), page);
1609
1610 out_unlock:
1611         slab_unlock(page);
1612         return;
1613
1614 slab_empty:
1615         if (prior)
1616                 /*
1617                  * Slab still on the partial list.
1618                  */
1619                 remove_partial(s, page);
1620
1621         slab_unlock(page);
1622         discard_slab(s, page);
1623         return;
1624
1625 debug:
1626         if (!free_debug_processing(s, page, x, addr))
1627                 goto out_unlock;
1628         goto checks_ok;
1629 }
1630
1631 /*
1632  * Fastpath with forced inlining to produce a kfree and kmem_cache_free that
1633  * can perform fastpath freeing without additional function calls.
1634  *
1635  * The fastpath is only possible if we are freeing to the current cpu slab
1636  * of this processor. This typically the case if we have just allocated
1637  * the item before.
1638  *
1639  * If fastpath is not possible then fall back to __slab_free where we deal
1640  * with all sorts of special processing.
1641  */
1642 static void __always_inline slab_free(struct kmem_cache *s,
1643                         struct page *page, void *x, void *addr)
1644 {
1645         void **object = (void *)x;
1646         unsigned long flags;
1647
1648         local_irq_save(flags);
1649         if (likely(page == s->cpu_slab[smp_processor_id()] &&
1650                                                 !SlabDebug(page))) {
1651                 object[page->offset] = page->lockless_freelist;
1652                 page->lockless_freelist = object;
1653         } else
1654                 __slab_free(s, page, x, addr);
1655
1656         local_irq_restore(flags);
1657 }
1658
1659 void kmem_cache_free(struct kmem_cache *s, void *x)
1660 {
1661         struct page *page;
1662
1663         page = virt_to_head_page(x);
1664
1665         slab_free(s, page, x, __builtin_return_address(0));
1666 }
1667 EXPORT_SYMBOL(kmem_cache_free);
1668
1669 /* Figure out on which slab object the object resides */
1670 static struct page *get_object_page(const void *x)
1671 {
1672         struct page *page = virt_to_head_page(x);
1673
1674         if (!PageSlab(page))
1675                 return NULL;
1676
1677         return page;
1678 }
1679
1680 /*
1681  * Object placement in a slab is made very easy because we always start at
1682  * offset 0. If we tune the size of the object to the alignment then we can
1683  * get the required alignment by putting one properly sized object after
1684  * another.
1685  *
1686  * Notice that the allocation order determines the sizes of the per cpu
1687  * caches. Each processor has always one slab available for allocations.
1688  * Increasing the allocation order reduces the number of times that slabs
1689  * must be moved on and off the partial lists and is therefore a factor in
1690  * locking overhead.
1691  */
1692
1693 /*
1694  * Mininum / Maximum order of slab pages. This influences locking overhead
1695  * and slab fragmentation. A higher order reduces the number of partial slabs
1696  * and increases the number of allocations possible without having to
1697  * take the list_lock.
1698  */
1699 static int slub_min_order;
1700 static int slub_max_order = DEFAULT_MAX_ORDER;
1701 static int slub_min_objects = DEFAULT_MIN_OBJECTS;
1702
1703 /*
1704  * Merge control. If this is set then no merging of slab caches will occur.
1705  * (Could be removed. This was introduced to pacify the merge skeptics.)
1706  */
1707 static int slub_nomerge;
1708
1709 /*
1710  * Calculate the order of allocation given an slab object size.
1711  *
1712  * The order of allocation has significant impact on performance and other
1713  * system components. Generally order 0 allocations should be preferred since
1714  * order 0 does not cause fragmentation in the page allocator. Larger objects
1715  * be problematic to put into order 0 slabs because there may be too much
1716  * unused space left. We go to a higher order if more than 1/8th of the slab
1717  * would be wasted.
1718  *
1719  * In order to reach satisfactory performance we must ensure that a minimum
1720  * number of objects is in one slab. Otherwise we may generate too much
1721  * activity on the partial lists which requires taking the list_lock. This is
1722  * less a concern for large slabs though which are rarely used.
1723  *
1724  * slub_max_order specifies the order where we begin to stop considering the
1725  * number of objects in a slab as critical. If we reach slub_max_order then
1726  * we try to keep the page order as low as possible. So we accept more waste
1727  * of space in favor of a small page order.
1728  *
1729  * Higher order allocations also allow the placement of more objects in a
1730  * slab and thereby reduce object handling overhead. If the user has
1731  * requested a higher mininum order then we start with that one instead of
1732  * the smallest order which will fit the object.
1733  */
1734 static inline int slab_order(int size, int min_objects,
1735                                 int max_order, int fract_leftover)
1736 {
1737         int order;
1738         int rem;
1739
1740         for (order = max(slub_min_order,
1741                                 fls(min_objects * size - 1) - PAGE_SHIFT);
1742                         order <= max_order; order++) {
1743
1744                 unsigned long slab_size = PAGE_SIZE << order;
1745
1746                 if (slab_size < min_objects * size)
1747                         continue;
1748
1749                 rem = slab_size % size;
1750
1751                 if (rem <= slab_size / fract_leftover)
1752                         break;
1753
1754         }
1755
1756         return order;
1757 }
1758
1759 static inline int calculate_order(int size)
1760 {
1761         int order;
1762         int min_objects;
1763         int fraction;
1764
1765         /*
1766          * Attempt to find best configuration for a slab. This
1767          * works by first attempting to generate a layout with
1768          * the best configuration and backing off gradually.
1769          *
1770          * First we reduce the acceptable waste in a slab. Then
1771          * we reduce the minimum objects required in a slab.
1772          */
1773         min_objects = slub_min_objects;
1774         while (min_objects > 1) {
1775                 fraction = 8;
1776                 while (fraction >= 4) {
1777                         order = slab_order(size, min_objects,
1778                                                 slub_max_order, fraction);
1779                         if (order <= slub_max_order)
1780                                 return order;
1781                         fraction /= 2;
1782                 }
1783                 min_objects /= 2;
1784         }
1785
1786         /*
1787          * We were unable to place multiple objects in a slab. Now
1788          * lets see if we can place a single object there.
1789          */
1790         order = slab_order(size, 1, slub_max_order, 1);
1791         if (order <= slub_max_order)
1792                 return order;
1793
1794         /*
1795          * Doh this slab cannot be placed using slub_max_order.
1796          */
1797         order = slab_order(size, 1, MAX_ORDER, 1);
1798         if (order <= MAX_ORDER)
1799                 return order;
1800         return -ENOSYS;
1801 }
1802
1803 /*
1804  * Figure out what the alignment of the objects will be.
1805  */
1806 static unsigned long calculate_alignment(unsigned long flags,
1807                 unsigned long align, unsigned long size)
1808 {
1809         /*
1810          * If the user wants hardware cache aligned objects then
1811          * follow that suggestion if the object is sufficiently
1812          * large.
1813          *
1814          * The hardware cache alignment cannot override the
1815          * specified alignment though. If that is greater
1816          * then use it.
1817          */
1818         if ((flags & SLAB_HWCACHE_ALIGN) &&
1819                         size > cache_line_size() / 2)
1820                 return max_t(unsigned long, align, cache_line_size());
1821
1822         if (align < ARCH_SLAB_MINALIGN)
1823                 return ARCH_SLAB_MINALIGN;
1824
1825         return ALIGN(align, sizeof(void *));
1826 }
1827
1828 static void init_kmem_cache_node(struct kmem_cache_node *n)
1829 {
1830         n->nr_partial = 0;
1831         atomic_long_set(&n->nr_slabs, 0);
1832         spin_lock_init(&n->list_lock);
1833         INIT_LIST_HEAD(&n->partial);
1834         INIT_LIST_HEAD(&n->full);
1835 }
1836
1837 #ifdef CONFIG_NUMA
1838 /*
1839  * No kmalloc_node yet so do it by hand. We know that this is the first
1840  * slab on the node for this slabcache. There are no concurrent accesses
1841  * possible.
1842  *
1843  * Note that this function only works on the kmalloc_node_cache
1844  * when allocating for the kmalloc_node_cache.
1845  */
1846 static struct kmem_cache_node * __init early_kmem_cache_node_alloc(gfp_t gfpflags,
1847                                                                 int node)
1848 {
1849         struct page *page;
1850         struct kmem_cache_node *n;
1851
1852         BUG_ON(kmalloc_caches->size < sizeof(struct kmem_cache_node));
1853
1854         page = new_slab(kmalloc_caches, gfpflags | GFP_THISNODE, node);
1855
1856         BUG_ON(!page);
1857         n = page->freelist;
1858         BUG_ON(!n);
1859         page->freelist = get_freepointer(kmalloc_caches, n);
1860         page->inuse++;
1861         kmalloc_caches->node[node] = n;
1862         setup_object_debug(kmalloc_caches, page, n);
1863         init_kmem_cache_node(n);
1864         atomic_long_inc(&n->nr_slabs);
1865         add_partial(n, page);
1866
1867         /*
1868          * new_slab() disables interupts. If we do not reenable interrupts here
1869          * then bootup would continue with interrupts disabled.
1870          */
1871         local_irq_enable();
1872         return n;
1873 }
1874
1875 static void free_kmem_cache_nodes(struct kmem_cache *s)
1876 {
1877         int node;
1878
1879         for_each_online_node(node) {
1880                 struct kmem_cache_node *n = s->node[node];
1881                 if (n && n != &s->local_node)
1882                         kmem_cache_free(kmalloc_caches, n);
1883                 s->node[node] = NULL;
1884         }
1885 }
1886
1887 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1888 {
1889         int node;
1890         int local_node;
1891
1892         if (slab_state >= UP)
1893                 local_node = page_to_nid(virt_to_page(s));
1894         else
1895                 local_node = 0;
1896
1897         for_each_online_node(node) {
1898                 struct kmem_cache_node *n;
1899
1900                 if (local_node == node)
1901                         n = &s->local_node;
1902                 else {
1903                         if (slab_state == DOWN) {
1904                                 n = early_kmem_cache_node_alloc(gfpflags,
1905                                                                 node);
1906                                 continue;
1907                         }
1908                         n = kmem_cache_alloc_node(kmalloc_caches,
1909                                                         gfpflags, node);
1910
1911                         if (!n) {
1912                                 free_kmem_cache_nodes(s);
1913                                 return 0;
1914                         }
1915
1916                 }
1917                 s->node[node] = n;
1918                 init_kmem_cache_node(n);
1919         }
1920         return 1;
1921 }
1922 #else
1923 static void free_kmem_cache_nodes(struct kmem_cache *s)
1924 {
1925 }
1926
1927 static int init_kmem_cache_nodes(struct kmem_cache *s, gfp_t gfpflags)
1928 {
1929         init_kmem_cache_node(&s->local_node);
1930         return 1;
1931 }
1932 #endif
1933
1934 /*
1935  * calculate_sizes() determines the order and the distribution of data within
1936  * a slab object.
1937  */
1938 static int calculate_sizes(struct kmem_cache *s)
1939 {
1940         unsigned long flags = s->flags;
1941         unsigned long size = s->objsize;
1942         unsigned long align = s->align;
1943
1944         /*
1945          * Determine if we can poison the object itself. If the user of
1946          * the slab may touch the object after free or before allocation
1947          * then we should never poison the object itself.
1948          */
1949         if ((flags & SLAB_POISON) && !(flags & SLAB_DESTROY_BY_RCU) &&
1950                         !s->ctor)
1951                 s->flags |= __OBJECT_POISON;
1952         else
1953                 s->flags &= ~__OBJECT_POISON;
1954
1955         /*
1956          * Round up object size to the next word boundary. We can only
1957          * place the free pointer at word boundaries and this determines
1958          * the possible location of the free pointer.
1959          */
1960         size = ALIGN(size, sizeof(void *));
1961
1962 #ifdef CONFIG_SLUB_DEBUG
1963         /*
1964          * If we are Redzoning then check if there is some space between the
1965          * end of the object and the free pointer. If not then add an
1966          * additional word to have some bytes to store Redzone information.
1967          */
1968         if ((flags & SLAB_RED_ZONE) && size == s->objsize)
1969                 size += sizeof(void *);
1970 #endif
1971
1972         /*
1973          * With that we have determined the number of bytes in actual use
1974          * by the object. This is the potential offset to the free pointer.
1975          */
1976         s->inuse = size;
1977
1978         if (((flags & (SLAB_DESTROY_BY_RCU | SLAB_POISON)) ||
1979                 s->ctor)) {
1980                 /*
1981                  * Relocate free pointer after the object if it is not
1982                  * permitted to overwrite the first word of the object on
1983                  * kmem_cache_free.
1984                  *
1985                  * This is the case if we do RCU, have a constructor or
1986                  * destructor or are poisoning the objects.
1987                  */
1988                 s->offset = size;
1989                 size += sizeof(void *);
1990         }
1991
1992 #ifdef CONFIG_SLUB_DEBUG
1993         if (flags & SLAB_STORE_USER)
1994                 /*
1995                  * Need to store information about allocs and frees after
1996                  * the object.
1997                  */
1998                 size += 2 * sizeof(struct track);
1999
2000         if (flags & SLAB_RED_ZONE)
2001                 /*
2002                  * Add some empty padding so that we can catch
2003                  * overwrites from earlier objects rather than let
2004                  * tracking information or the free pointer be
2005                  * corrupted if an user writes before the start
2006                  * of the object.
2007                  */
2008                 size += sizeof(void *);
2009 #endif
2010
2011         /*
2012          * Determine the alignment based on various parameters that the
2013          * user specified and the dynamic determination of cache line size
2014          * on bootup.
2015          */
2016         align = calculate_alignment(flags, align, s->objsize);
2017
2018         /*
2019          * SLUB stores one object immediately after another beginning from
2020          * offset 0. In order to align the objects we have to simply size
2021          * each object to conform to the alignment.
2022          */
2023         size = ALIGN(size, align);
2024         s->size = size;
2025
2026         s->order = calculate_order(size);
2027         if (s->order < 0)
2028                 return 0;
2029
2030         /*
2031          * Determine the number of objects per slab
2032          */
2033         s->objects = (PAGE_SIZE << s->order) / size;
2034
2035         /*
2036          * Verify that the number of objects is within permitted limits.
2037          * The page->inuse field is only 16 bit wide! So we cannot have
2038          * more than 64k objects per slab.
2039          */
2040         if (!s->objects || s->objects > 65535)
2041                 return 0;
2042         return 1;
2043
2044 }
2045
2046 static int kmem_cache_open(struct kmem_cache *s, gfp_t gfpflags,
2047                 const char *name, size_t size,
2048                 size_t align, unsigned long flags,
2049                 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2050 {
2051         memset(s, 0, kmem_size);
2052         s->name = name;
2053         s->ctor = ctor;
2054         s->objsize = size;
2055         s->flags = flags;
2056         s->align = align;
2057         kmem_cache_open_debug_check(s);
2058
2059         if (!calculate_sizes(s))
2060                 goto error;
2061
2062         s->refcount = 1;
2063 #ifdef CONFIG_NUMA
2064         s->defrag_ratio = 100;
2065 #endif
2066
2067         if (init_kmem_cache_nodes(s, gfpflags & ~SLUB_DMA))
2068                 return 1;
2069 error:
2070         if (flags & SLAB_PANIC)
2071                 panic("Cannot create slab %s size=%lu realsize=%u "
2072                         "order=%u offset=%u flags=%lx\n",
2073                         s->name, (unsigned long)size, s->size, s->order,
2074                         s->offset, flags);
2075         return 0;
2076 }
2077
2078 /*
2079  * Check if a given pointer is valid
2080  */
2081 int kmem_ptr_validate(struct kmem_cache *s, const void *object)
2082 {
2083         struct page * page;
2084
2085         page = get_object_page(object);
2086
2087         if (!page || s != page->slab)
2088                 /* No slab or wrong slab */
2089                 return 0;
2090
2091         if (!check_valid_pointer(s, page, object))
2092                 return 0;
2093
2094         /*
2095          * We could also check if the object is on the slabs freelist.
2096          * But this would be too expensive and it seems that the main
2097          * purpose of kmem_ptr_valid is to check if the object belongs
2098          * to a certain slab.
2099          */
2100         return 1;
2101 }
2102 EXPORT_SYMBOL(kmem_ptr_validate);
2103
2104 /*
2105  * Determine the size of a slab object
2106  */
2107 unsigned int kmem_cache_size(struct kmem_cache *s)
2108 {
2109         return s->objsize;
2110 }
2111 EXPORT_SYMBOL(kmem_cache_size);
2112
2113 const char *kmem_cache_name(struct kmem_cache *s)
2114 {
2115         return s->name;
2116 }
2117 EXPORT_SYMBOL(kmem_cache_name);
2118
2119 /*
2120  * Attempt to free all slabs on a node. Return the number of slabs we
2121  * were unable to free.
2122  */
2123 static int free_list(struct kmem_cache *s, struct kmem_cache_node *n,
2124                         struct list_head *list)
2125 {
2126         int slabs_inuse = 0;
2127         unsigned long flags;
2128         struct page *page, *h;
2129
2130         spin_lock_irqsave(&n->list_lock, flags);
2131         list_for_each_entry_safe(page, h, list, lru)
2132                 if (!page->inuse) {
2133                         list_del(&page->lru);
2134                         discard_slab(s, page);
2135                 } else
2136                         slabs_inuse++;
2137         spin_unlock_irqrestore(&n->list_lock, flags);
2138         return slabs_inuse;
2139 }
2140
2141 /*
2142  * Release all resources used by a slab cache.
2143  */
2144 static int kmem_cache_close(struct kmem_cache *s)
2145 {
2146         int node;
2147
2148         flush_all(s);
2149
2150         /* Attempt to free all objects */
2151         for_each_online_node(node) {
2152                 struct kmem_cache_node *n = get_node(s, node);
2153
2154                 n->nr_partial -= free_list(s, n, &n->partial);
2155                 if (atomic_long_read(&n->nr_slabs))
2156                         return 1;
2157         }
2158         free_kmem_cache_nodes(s);
2159         return 0;
2160 }
2161
2162 /*
2163  * Close a cache and release the kmem_cache structure
2164  * (must be used for caches created using kmem_cache_create)
2165  */
2166 void kmem_cache_destroy(struct kmem_cache *s)
2167 {
2168         down_write(&slub_lock);
2169         s->refcount--;
2170         if (!s->refcount) {
2171                 list_del(&s->list);
2172                 if (kmem_cache_close(s))
2173                         WARN_ON(1);
2174                 sysfs_slab_remove(s);
2175                 kfree(s);
2176         }
2177         up_write(&slub_lock);
2178 }
2179 EXPORT_SYMBOL(kmem_cache_destroy);
2180
2181 /********************************************************************
2182  *              Kmalloc subsystem
2183  *******************************************************************/
2184
2185 struct kmem_cache kmalloc_caches[KMALLOC_SHIFT_HIGH + 1] __cacheline_aligned;
2186 EXPORT_SYMBOL(kmalloc_caches);
2187
2188 #ifdef CONFIG_ZONE_DMA
2189 static struct kmem_cache *kmalloc_caches_dma[KMALLOC_SHIFT_HIGH + 1];
2190 #endif
2191
2192 static int __init setup_slub_min_order(char *str)
2193 {
2194         get_option (&str, &slub_min_order);
2195
2196         return 1;
2197 }
2198
2199 __setup("slub_min_order=", setup_slub_min_order);
2200
2201 static int __init setup_slub_max_order(char *str)
2202 {
2203         get_option (&str, &slub_max_order);
2204
2205         return 1;
2206 }
2207
2208 __setup("slub_max_order=", setup_slub_max_order);
2209
2210 static int __init setup_slub_min_objects(char *str)
2211 {
2212         get_option (&str, &slub_min_objects);
2213
2214         return 1;
2215 }
2216
2217 __setup("slub_min_objects=", setup_slub_min_objects);
2218
2219 static int __init setup_slub_nomerge(char *str)
2220 {
2221         slub_nomerge = 1;
2222         return 1;
2223 }
2224
2225 __setup("slub_nomerge", setup_slub_nomerge);
2226
2227 static struct kmem_cache *create_kmalloc_cache(struct kmem_cache *s,
2228                 const char *name, int size, gfp_t gfp_flags)
2229 {
2230         unsigned int flags = 0;
2231
2232         if (gfp_flags & SLUB_DMA)
2233                 flags = SLAB_CACHE_DMA;
2234
2235         down_write(&slub_lock);
2236         if (!kmem_cache_open(s, gfp_flags, name, size, ARCH_KMALLOC_MINALIGN,
2237                         flags, NULL))
2238                 goto panic;
2239
2240         list_add(&s->list, &slab_caches);
2241         up_write(&slub_lock);
2242         if (sysfs_slab_add(s))
2243                 goto panic;
2244         return s;
2245
2246 panic:
2247         panic("Creation of kmalloc slab %s size=%d failed.\n", name, size);
2248 }
2249
2250 static struct kmem_cache *get_slab(size_t size, gfp_t flags)
2251 {
2252         int index = kmalloc_index(size);
2253
2254         if (!index)
2255                 return NULL;
2256
2257         /* Allocation too large? */
2258         BUG_ON(index < 0);
2259
2260 #ifdef CONFIG_ZONE_DMA
2261         if ((flags & SLUB_DMA)) {
2262                 struct kmem_cache *s;
2263                 struct kmem_cache *x;
2264                 char *text;
2265                 size_t realsize;
2266
2267                 s = kmalloc_caches_dma[index];
2268                 if (s)
2269                         return s;
2270
2271                 /* Dynamically create dma cache */
2272                 x = kmalloc(kmem_size, flags & ~SLUB_DMA);
2273                 if (!x)
2274                         panic("Unable to allocate memory for dma cache\n");
2275
2276                 if (index <= KMALLOC_SHIFT_HIGH)
2277                         realsize = 1 << index;
2278                 else {
2279                         if (index == 1)
2280                                 realsize = 96;
2281                         else
2282                                 realsize = 192;
2283                 }
2284
2285                 text = kasprintf(flags & ~SLUB_DMA, "kmalloc_dma-%d",
2286                                 (unsigned int)realsize);
2287                 s = create_kmalloc_cache(x, text, realsize, flags);
2288                 kmalloc_caches_dma[index] = s;
2289                 return s;
2290         }
2291 #endif
2292         return &kmalloc_caches[index];
2293 }
2294
2295 void *__kmalloc(size_t size, gfp_t flags)
2296 {
2297         struct kmem_cache *s = get_slab(size, flags);
2298
2299         if (s)
2300                 return slab_alloc(s, flags, -1, __builtin_return_address(0));
2301         return ZERO_SIZE_PTR;
2302 }
2303 EXPORT_SYMBOL(__kmalloc);
2304
2305 #ifdef CONFIG_NUMA
2306 void *__kmalloc_node(size_t size, gfp_t flags, int node)
2307 {
2308         struct kmem_cache *s = get_slab(size, flags);
2309
2310         if (s)
2311                 return slab_alloc(s, flags, node, __builtin_return_address(0));
2312         return ZERO_SIZE_PTR;
2313 }
2314 EXPORT_SYMBOL(__kmalloc_node);
2315 #endif
2316
2317 size_t ksize(const void *object)
2318 {
2319         struct page *page;
2320         struct kmem_cache *s;
2321
2322         if (object == ZERO_SIZE_PTR)
2323                 return 0;
2324
2325         page = get_object_page(object);
2326         BUG_ON(!page);
2327         s = page->slab;
2328         BUG_ON(!s);
2329
2330         /*
2331          * Debugging requires use of the padding between object
2332          * and whatever may come after it.
2333          */
2334         if (s->flags & (SLAB_RED_ZONE | SLAB_POISON))
2335                 return s->objsize;
2336
2337         /*
2338          * If we have the need to store the freelist pointer
2339          * back there or track user information then we can
2340          * only use the space before that information.
2341          */
2342         if (s->flags & (SLAB_DESTROY_BY_RCU | SLAB_STORE_USER))
2343                 return s->inuse;
2344
2345         /*
2346          * Else we can use all the padding etc for the allocation
2347          */
2348         return s->size;
2349 }
2350 EXPORT_SYMBOL(ksize);
2351
2352 void kfree(const void *x)
2353 {
2354         struct kmem_cache *s;
2355         struct page *page;
2356
2357         /*
2358          * This has to be an unsigned comparison. According to Linus
2359          * some gcc version treat a pointer as a signed entity. Then
2360          * this comparison would be true for all "negative" pointers
2361          * (which would cover the whole upper half of the address space).
2362          */
2363         if ((unsigned long)x <= (unsigned long)ZERO_SIZE_PTR)
2364                 return;
2365
2366         page = virt_to_head_page(x);
2367         s = page->slab;
2368
2369         slab_free(s, page, (void *)x, __builtin_return_address(0));
2370 }
2371 EXPORT_SYMBOL(kfree);
2372
2373 /*
2374  * kmem_cache_shrink removes empty slabs from the partial lists and sorts
2375  * the remaining slabs by the number of items in use. The slabs with the
2376  * most items in use come first. New allocations will then fill those up
2377  * and thus they can be removed from the partial lists.
2378  *
2379  * The slabs with the least items are placed last. This results in them
2380  * being allocated from last increasing the chance that the last objects
2381  * are freed in them.
2382  */
2383 int kmem_cache_shrink(struct kmem_cache *s)
2384 {
2385         int node;
2386         int i;
2387         struct kmem_cache_node *n;
2388         struct page *page;
2389         struct page *t;
2390         struct list_head *slabs_by_inuse =
2391                 kmalloc(sizeof(struct list_head) * s->objects, GFP_KERNEL);
2392         unsigned long flags;
2393
2394         if (!slabs_by_inuse)
2395                 return -ENOMEM;
2396
2397         flush_all(s);
2398         for_each_online_node(node) {
2399                 n = get_node(s, node);
2400
2401                 if (!n->nr_partial)
2402                         continue;
2403
2404                 for (i = 0; i < s->objects; i++)
2405                         INIT_LIST_HEAD(slabs_by_inuse + i);
2406
2407                 spin_lock_irqsave(&n->list_lock, flags);
2408
2409                 /*
2410                  * Build lists indexed by the items in use in each slab.
2411                  *
2412                  * Note that concurrent frees may occur while we hold the
2413                  * list_lock. page->inuse here is the upper limit.
2414                  */
2415                 list_for_each_entry_safe(page, t, &n->partial, lru) {
2416                         if (!page->inuse && slab_trylock(page)) {
2417                                 /*
2418                                  * Must hold slab lock here because slab_free
2419                                  * may have freed the last object and be
2420                                  * waiting to release the slab.
2421                                  */
2422                                 list_del(&page->lru);
2423                                 n->nr_partial--;
2424                                 slab_unlock(page);
2425                                 discard_slab(s, page);
2426                         } else {
2427                                 if (n->nr_partial > MAX_PARTIAL)
2428                                         list_move(&page->lru,
2429                                         slabs_by_inuse + page->inuse);
2430                         }
2431                 }
2432
2433                 if (n->nr_partial <= MAX_PARTIAL)
2434                         goto out;
2435
2436                 /*
2437                  * Rebuild the partial list with the slabs filled up most
2438                  * first and the least used slabs at the end.
2439                  */
2440                 for (i = s->objects - 1; i >= 0; i--)
2441                         list_splice(slabs_by_inuse + i, n->partial.prev);
2442
2443         out:
2444                 spin_unlock_irqrestore(&n->list_lock, flags);
2445         }
2446
2447         kfree(slabs_by_inuse);
2448         return 0;
2449 }
2450 EXPORT_SYMBOL(kmem_cache_shrink);
2451
2452 /**
2453  * krealloc - reallocate memory. The contents will remain unchanged.
2454  * @p: object to reallocate memory for.
2455  * @new_size: how many bytes of memory are required.
2456  * @flags: the type of memory to allocate.
2457  *
2458  * The contents of the object pointed to are preserved up to the
2459  * lesser of the new and old sizes.  If @p is %NULL, krealloc()
2460  * behaves exactly like kmalloc().  If @size is 0 and @p is not a
2461  * %NULL pointer, the object pointed to is freed.
2462  */
2463 void *krealloc(const void *p, size_t new_size, gfp_t flags)
2464 {
2465         void *ret;
2466         size_t ks;
2467
2468         if (unlikely(!p || p == ZERO_SIZE_PTR))
2469                 return kmalloc(new_size, flags);
2470
2471         if (unlikely(!new_size)) {
2472                 kfree(p);
2473                 return ZERO_SIZE_PTR;
2474         }
2475
2476         ks = ksize(p);
2477         if (ks >= new_size)
2478                 return (void *)p;
2479
2480         ret = kmalloc(new_size, flags);
2481         if (ret) {
2482                 memcpy(ret, p, min(new_size, ks));
2483                 kfree(p);
2484         }
2485         return ret;
2486 }
2487 EXPORT_SYMBOL(krealloc);
2488
2489 /********************************************************************
2490  *                      Basic setup of slabs
2491  *******************************************************************/
2492
2493 void __init kmem_cache_init(void)
2494 {
2495         int i;
2496         int caches = 0;
2497
2498 #ifdef CONFIG_NUMA
2499         /*
2500          * Must first have the slab cache available for the allocations of the
2501          * struct kmem_cache_node's. There is special bootstrap code in
2502          * kmem_cache_open for slab_state == DOWN.
2503          */
2504         create_kmalloc_cache(&kmalloc_caches[0], "kmem_cache_node",
2505                 sizeof(struct kmem_cache_node), GFP_KERNEL);
2506         kmalloc_caches[0].refcount = -1;
2507         caches++;
2508 #endif
2509
2510         /* Able to allocate the per node structures */
2511         slab_state = PARTIAL;
2512
2513         /* Caches that are not of the two-to-the-power-of size */
2514         if (KMALLOC_MIN_SIZE <= 64) {
2515                 create_kmalloc_cache(&kmalloc_caches[1],
2516                                 "kmalloc-96", 96, GFP_KERNEL);
2517                 caches++;
2518         }
2519         if (KMALLOC_MIN_SIZE <= 128) {
2520                 create_kmalloc_cache(&kmalloc_caches[2],
2521                                 "kmalloc-192", 192, GFP_KERNEL);
2522                 caches++;
2523         }
2524
2525         for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) {
2526                 create_kmalloc_cache(&kmalloc_caches[i],
2527                         "kmalloc", 1 << i, GFP_KERNEL);
2528                 caches++;
2529         }
2530
2531         slab_state = UP;
2532
2533         /* Provide the correct kmalloc names now that the caches are up */
2534         for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++)
2535                 kmalloc_caches[i]. name =
2536                         kasprintf(GFP_KERNEL, "kmalloc-%d", 1 << i);
2537
2538 #ifdef CONFIG_SMP
2539         register_cpu_notifier(&slab_notifier);
2540 #endif
2541
2542         kmem_size = offsetof(struct kmem_cache, cpu_slab) +
2543                                 nr_cpu_ids * sizeof(struct page *);
2544
2545         printk(KERN_INFO "SLUB: Genslabs=%d, HWalign=%d, Order=%d-%d, MinObjects=%d,"
2546                 " CPUs=%d, Nodes=%d\n",
2547                 caches, cache_line_size(),
2548                 slub_min_order, slub_max_order, slub_min_objects,
2549                 nr_cpu_ids, nr_node_ids);
2550 }
2551
2552 /*
2553  * Find a mergeable slab cache
2554  */
2555 static int slab_unmergeable(struct kmem_cache *s)
2556 {
2557         if (slub_nomerge || (s->flags & SLUB_NEVER_MERGE))
2558                 return 1;
2559
2560         if (s->ctor)
2561                 return 1;
2562
2563         /*
2564          * We may have set a slab to be unmergeable during bootstrap.
2565          */
2566         if (s->refcount < 0)
2567                 return 1;
2568
2569         return 0;
2570 }
2571
2572 static struct kmem_cache *find_mergeable(size_t size,
2573                 size_t align, unsigned long flags,
2574                 void (*ctor)(void *, struct kmem_cache *, unsigned long))
2575 {
2576         struct kmem_cache *s;
2577
2578         if (slub_nomerge || (flags & SLUB_NEVER_MERGE))
2579                 return NULL;
2580
2581         if (ctor)
2582                 return NULL;
2583
2584         size = ALIGN(size, sizeof(void *));
2585         align = calculate_alignment(flags, align, size);
2586         size = ALIGN(size, align);
2587
2588         list_for_each_entry(s, &slab_caches, list) {
2589                 if (slab_unmergeable(s))
2590                         continue;
2591
2592                 if (size > s->size)
2593                         continue;
2594
2595                 if (((flags | slub_debug) & SLUB_MERGE_SAME) !=
2596                         (s->flags & SLUB_MERGE_SAME))
2597                                 continue;
2598                 /*
2599                  * Check if alignment is compatible.
2600                  * Courtesy of Adrian Drzewiecki
2601                  */
2602                 if ((s->size & ~(align -1)) != s->size)
2603                         continue;
2604
2605                 if (s->size - size >= sizeof(void *))
2606                         continue;
2607
2608                 return s;
2609         }
2610         return NULL;
2611 }
2612
2613 struct kmem_cache *kmem_cache_create(const char *name, size_t size,
2614                 size_t align, unsigned long flags,
2615                 void (*ctor)(void *, struct kmem_cache *, unsigned long),
2616                 void (*dtor)(void *, struct kmem_cache *, unsigned long))
2617 {
2618         struct kmem_cache *s;
2619
2620         BUG_ON(dtor);
2621         down_write(&slub_lock);
2622         s = find_mergeable(size, align, flags, ctor);
2623         if (s) {
2624                 s->refcount++;
2625                 /*
2626                  * Adjust the object sizes so that we clear
2627                  * the complete object on kzalloc.
2628                  */
2629                 s->objsize = max(s->objsize, (int)size);
2630                 s->inuse = max_t(int, s->inuse, ALIGN(size, sizeof(void *)));
2631                 if (sysfs_slab_alias(s, name))
2632                         goto err;
2633         } else {
2634                 s = kmalloc(kmem_size, GFP_KERNEL);
2635                 if (s && kmem_cache_open(s, GFP_KERNEL, name,
2636                                 size, align, flags, ctor)) {
2637                         if (sysfs_slab_add(s)) {
2638                                 kfree(s);
2639                                 goto err;
2640                         }
2641                         list_add(&s->list, &slab_caches);
2642                 } else
2643                         kfree(s);
2644         }
2645         up_write(&slub_lock);
2646         return s;
2647
2648 err:
2649         up_write(&slub_lock);
2650         if (flags & SLAB_PANIC)
2651                 panic("Cannot create slabcache %s\n", name);
2652         else
2653                 s = NULL;
2654         return s;
2655 }
2656 EXPORT_SYMBOL(kmem_cache_create);
2657
2658 void *kmem_cache_zalloc(struct kmem_cache *s, gfp_t flags)
2659 {
2660         void *x;
2661
2662         x = slab_alloc(s, flags, -1, __builtin_return_address(0));
2663         if (x)
2664                 memset(x, 0, s->objsize);
2665         return x;
2666 }
2667 EXPORT_SYMBOL(kmem_cache_zalloc);
2668
2669 #ifdef CONFIG_SMP
2670 /*
2671  * Use the cpu notifier to insure that the cpu slabs are flushed when
2672  * necessary.
2673  */
2674 static int __cpuinit slab_cpuup_callback(struct notifier_block *nfb,
2675                 unsigned long action, void *hcpu)
2676 {
2677         long cpu = (long)hcpu;
2678         struct kmem_cache *s;
2679         unsigned long flags;
2680
2681         switch (action) {
2682         case CPU_UP_CANCELED:
2683         case CPU_UP_CANCELED_FROZEN:
2684         case CPU_DEAD:
2685         case CPU_DEAD_FROZEN:
2686                 down_read(&slub_lock);
2687                 list_for_each_entry(s, &slab_caches, list) {
2688                         local_irq_save(flags);
2689                         __flush_cpu_slab(s, cpu);
2690                         local_irq_restore(flags);
2691                 }
2692                 up_read(&slub_lock);
2693                 break;
2694         default:
2695                 break;
2696         }
2697         return NOTIFY_OK;
2698 }
2699
2700 static struct notifier_block __cpuinitdata slab_notifier =
2701         { &slab_cpuup_callback, NULL, 0 };
2702
2703 #endif
2704
2705 void *__kmalloc_track_caller(size_t size, gfp_t gfpflags, void *caller)
2706 {
2707         struct kmem_cache *s = get_slab(size, gfpflags);
2708
2709         if (!s)
2710                 return ZERO_SIZE_PTR;
2711
2712         return slab_alloc(s, gfpflags, -1, caller);
2713 }
2714
2715 void *__kmalloc_node_track_caller(size_t size, gfp_t gfpflags,
2716                                         int node, void *caller)
2717 {
2718         struct kmem_cache *s = get_slab(size, gfpflags);
2719
2720         if (!s)
2721                 return ZERO_SIZE_PTR;
2722
2723         return slab_alloc(s, gfpflags, node, caller);
2724 }
2725
2726 #if defined(CONFIG_SYSFS) && defined(CONFIG_SLUB_DEBUG)
2727 static int validate_slab(struct kmem_cache *s, struct page *page)
2728 {
2729         void *p;
2730         void *addr = page_address(page);
2731         DECLARE_BITMAP(map, s->objects);
2732
2733         if (!check_slab(s, page) ||
2734                         !on_freelist(s, page, NULL))
2735                 return 0;
2736
2737         /* Now we know that a valid freelist exists */
2738         bitmap_zero(map, s->objects);
2739
2740         for_each_free_object(p, s, page->freelist) {
2741                 set_bit(slab_index(p, s, addr), map);
2742                 if (!check_object(s, page, p, 0))
2743                         return 0;
2744         }
2745
2746         for_each_object(p, s, addr)
2747                 if (!test_bit(slab_index(p, s, addr), map))
2748                         if (!check_object(s, page, p, 1))
2749                                 return 0;
2750         return 1;
2751 }
2752
2753 static void validate_slab_slab(struct kmem_cache *s, struct page *page)
2754 {
2755         if (slab_trylock(page)) {
2756                 validate_slab(s, page);
2757                 slab_unlock(page);
2758         } else
2759                 printk(KERN_INFO "SLUB %s: Skipped busy slab 0x%p\n",
2760                         s->name, page);
2761
2762         if (s->flags & DEBUG_DEFAULT_FLAGS) {
2763                 if (!SlabDebug(page))
2764                         printk(KERN_ERR "SLUB %s: SlabDebug not set "
2765                                 "on slab 0x%p\n", s->name, page);
2766         } else {
2767                 if (SlabDebug(page))
2768                         printk(KERN_ERR "SLUB %s: SlabDebug set on "
2769                                 "slab 0x%p\n", s->name, page);
2770         }
2771 }
2772
2773 static int validate_slab_node(struct kmem_cache *s, struct kmem_cache_node *n)
2774 {
2775         unsigned long count = 0;
2776         struct page *page;
2777         unsigned long flags;
2778
2779         spin_lock_irqsave(&n->list_lock, flags);
2780
2781         list_for_each_entry(page, &n->partial, lru) {
2782                 validate_slab_slab(s, page);
2783                 count++;
2784         }
2785         if (count != n->nr_partial)
2786                 printk(KERN_ERR "SLUB %s: %ld partial slabs counted but "
2787                         "counter=%ld\n", s->name, count, n->nr_partial);
2788
2789         if (!(s->flags & SLAB_STORE_USER))
2790                 goto out;
2791
2792         list_for_each_entry(page, &n->full, lru) {
2793                 validate_slab_slab(s, page);
2794                 count++;
2795         }
2796         if (count != atomic_long_read(&n->nr_slabs))
2797                 printk(KERN_ERR "SLUB: %s %ld slabs counted but "
2798                         "counter=%ld\n", s->name, count,
2799                         atomic_long_read(&n->nr_slabs));
2800
2801 out:
2802         spin_unlock_irqrestore(&n->list_lock, flags);
2803         return count;
2804 }
2805
2806 static unsigned long validate_slab_cache(struct kmem_cache *s)
2807 {
2808         int node;
2809         unsigned long count = 0;
2810
2811         flush_all(s);
2812         for_each_online_node(node) {
2813                 struct kmem_cache_node *n = get_node(s, node);
2814
2815                 count += validate_slab_node(s, n);
2816         }
2817         return count;
2818 }
2819
2820 #ifdef SLUB_RESILIENCY_TEST
2821 static void resiliency_test(void)
2822 {
2823         u8 *p;
2824
2825         printk(KERN_ERR "SLUB resiliency testing\n");
2826         printk(KERN_ERR "-----------------------\n");
2827         printk(KERN_ERR "A. Corruption after allocation\n");
2828
2829         p = kzalloc(16, GFP_KERNEL);
2830         p[16] = 0x12;
2831         printk(KERN_ERR "\n1. kmalloc-16: Clobber Redzone/next pointer"
2832                         " 0x12->0x%p\n\n", p + 16);
2833
2834         validate_slab_cache(kmalloc_caches + 4);
2835
2836         /* Hmmm... The next two are dangerous */
2837         p = kzalloc(32, GFP_KERNEL);
2838         p[32 + sizeof(void *)] = 0x34;
2839         printk(KERN_ERR "\n2. kmalloc-32: Clobber next pointer/next slab"
2840                         " 0x34 -> -0x%p\n", p);
2841         printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2842
2843         validate_slab_cache(kmalloc_caches + 5);
2844         p = kzalloc(64, GFP_KERNEL);
2845         p += 64 + (get_cycles() & 0xff) * sizeof(void *);
2846         *p = 0x56;
2847         printk(KERN_ERR "\n3. kmalloc-64: corrupting random byte 0x56->0x%p\n",
2848                                                                         p);
2849         printk(KERN_ERR "If allocated object is overwritten then not detectable\n\n");
2850         validate_slab_cache(kmalloc_caches + 6);
2851
2852         printk(KERN_ERR "\nB. Corruption after free\n");
2853         p = kzalloc(128, GFP_KERNEL);
2854         kfree(p);
2855         *p = 0x78;
2856         printk(KERN_ERR "1. kmalloc-128: Clobber first word 0x78->0x%p\n\n", p);
2857         validate_slab_cache(kmalloc_caches + 7);
2858
2859         p = kzalloc(256, GFP_KERNEL);
2860         kfree(p);
2861         p[50] = 0x9a;
2862         printk(KERN_ERR "\n2. kmalloc-256: Clobber 50th byte 0x9a->0x%p\n\n", p);
2863         validate_slab_cache(kmalloc_caches + 8);
2864
2865         p = kzalloc(512, GFP_KERNEL);
2866         kfree(p);
2867         p[512] = 0xab;
2868         printk(KERN_ERR "\n3. kmalloc-512: Clobber redzone 0xab->0x%p\n\n", p);
2869         validate_slab_cache(kmalloc_caches + 9);
2870 }
2871 #else
2872 static void resiliency_test(void) {};
2873 #endif
2874
2875 /*
2876  * Generate lists of code addresses where slabcache objects are allocated
2877  * and freed.
2878  */
2879
2880 struct location {
2881         unsigned long count;
2882         void *addr;
2883         long long sum_time;
2884         long min_time;
2885         long max_time;
2886         long min_pid;
2887         long max_pid;
2888         cpumask_t cpus;
2889         nodemask_t nodes;
2890 };
2891
2892 struct loc_track {
2893         unsigned long max;
2894         unsigned long count;
2895         struct location *loc;
2896 };
2897
2898 static void free_loc_track(struct loc_track *t)
2899 {
2900         if (t->max)
2901                 free_pages((unsigned long)t->loc,
2902                         get_order(sizeof(struct location) * t->max));
2903 }
2904
2905 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags)
2906 {
2907         struct location *l;
2908         int order;
2909
2910         order = get_order(sizeof(struct location) * max);
2911
2912         l = (void *)__get_free_pages(flags, order);
2913         if (!l)
2914                 return 0;
2915
2916         if (t->count) {
2917                 memcpy(l, t->loc, sizeof(struct location) * t->count);
2918                 free_loc_track(t);
2919         }
2920         t->max = max;
2921         t->loc = l;
2922         return 1;
2923 }
2924
2925 static int add_location(struct loc_track *t, struct kmem_cache *s,
2926                                 const struct track *track)
2927 {
2928         long start, end, pos;
2929         struct location *l;
2930         void *caddr;
2931         unsigned long age = jiffies - track->when;
2932
2933         start = -1;
2934         end = t->count;
2935
2936         for ( ; ; ) {
2937                 pos = start + (end - start + 1) / 2;
2938
2939                 /*
2940                  * There is nothing at "end". If we end up there
2941                  * we need to add something to before end.
2942                  */
2943                 if (pos == end)
2944                         break;
2945
2946                 caddr = t->loc[pos].addr;
2947                 if (track->addr == caddr) {
2948
2949                         l = &t->loc[pos];
2950                         l->count++;
2951                         if (track->when) {
2952                                 l->sum_time += age;
2953                                 if (age < l->min_time)
2954                                         l->min_time = age;
2955                                 if (age > l->max_time)
2956                                         l->max_time = age;
2957
2958                                 if (track->pid < l->min_pid)
2959                                         l->min_pid = track->pid;
2960                                 if (track->pid > l->max_pid)
2961                                         l->max_pid = track->pid;
2962
2963                                 cpu_set(track->cpu, l->cpus);
2964                         }
2965                         node_set(page_to_nid(virt_to_page(track)), l->nodes);
2966                         return 1;
2967                 }
2968
2969                 if (track->addr < caddr)
2970                         end = pos;
2971                 else
2972                         start = pos;
2973         }
2974
2975         /*
2976          * Not found. Insert new tracking element.
2977          */
2978         if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC))
2979                 return 0;
2980
2981         l = t->loc + pos;
2982         if (pos < t->count)
2983                 memmove(l + 1, l,
2984                         (t->count - pos) * sizeof(struct location));
2985         t->count++;
2986         l->count = 1;
2987         l->addr = track->addr;
2988         l->sum_time = age;
2989         l->min_time = age;
2990         l->max_time = age;
2991         l->min_pid = track->pid;
2992         l->max_pid = track->pid;
2993         cpus_clear(l->cpus);
2994         cpu_set(track->cpu, l->cpus);
2995         nodes_clear(l->nodes);
2996         node_set(page_to_nid(virt_to_page(track)), l->nodes);
2997         return 1;
2998 }
2999
3000 static void process_slab(struct loc_track *t, struct kmem_cache *s,
3001                 struct page *page, enum track_item alloc)
3002 {
3003         void *addr = page_address(page);
3004         DECLARE_BITMAP(map, s->objects);
3005         void *p;
3006
3007         bitmap_zero(map, s->objects);
3008         for_each_free_object(p, s, page->freelist)
3009                 set_bit(slab_index(p, s, addr), map);
3010
3011         for_each_object(p, s, addr)
3012                 if (!test_bit(slab_index(p, s, addr), map))
3013                         add_location(t, s, get_track(s, p, alloc));
3014 }
3015
3016 static int list_locations(struct kmem_cache *s, char *buf,
3017                                         enum track_item alloc)
3018 {
3019         int n = 0;
3020         unsigned long i;
3021         struct loc_track t = { 0, 0, NULL };
3022         int node;
3023
3024         if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
3025                         GFP_KERNEL))
3026                 return sprintf(buf, "Out of memory\n");
3027
3028         /* Push back cpu slabs */
3029         flush_all(s);
3030
3031         for_each_online_node(node) {
3032                 struct kmem_cache_node *n = get_node(s, node);
3033                 unsigned long flags;
3034                 struct page *page;
3035
3036                 if (!atomic_read(&n->nr_slabs))
3037                         continue;
3038
3039                 spin_lock_irqsave(&n->list_lock, flags);
3040                 list_for_each_entry(page, &n->partial, lru)
3041                         process_slab(&t, s, page, alloc);
3042                 list_for_each_entry(page, &n->full, lru)
3043                         process_slab(&t, s, page, alloc);
3044                 spin_unlock_irqrestore(&n->list_lock, flags);
3045         }
3046
3047         for (i = 0; i < t.count; i++) {
3048                 struct location *l = &t.loc[i];
3049
3050                 if (n > PAGE_SIZE - 100)
3051                         break;
3052                 n += sprintf(buf + n, "%7ld ", l->count);
3053
3054                 if (l->addr)
3055                         n += sprint_symbol(buf + n, (unsigned long)l->addr);
3056                 else
3057                         n += sprintf(buf + n, "<not-available>");
3058
3059                 if (l->sum_time != l->min_time) {
3060                         unsigned long remainder;
3061
3062                         n += sprintf(buf + n, " age=%ld/%ld/%ld",
3063                         l->min_time,
3064                         div_long_long_rem(l->sum_time, l->count, &remainder),
3065                         l->max_time);
3066                 } else
3067                         n += sprintf(buf + n, " age=%ld",
3068                                 l->min_time);
3069
3070                 if (l->min_pid != l->max_pid)
3071                         n += sprintf(buf + n, " pid=%ld-%ld",
3072                                 l->min_pid, l->max_pid);
3073                 else
3074                         n += sprintf(buf + n, " pid=%ld",
3075                                 l->min_pid);
3076
3077                 if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
3078                                 n < PAGE_SIZE - 60) {
3079                         n += sprintf(buf + n, " cpus=");
3080                         n += cpulist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3081                                         l->cpus);
3082                 }
3083
3084                 if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
3085                                 n < PAGE_SIZE - 60) {
3086                         n += sprintf(buf + n, " nodes=");
3087                         n += nodelist_scnprintf(buf + n, PAGE_SIZE - n - 50,
3088                                         l->nodes);
3089                 }
3090
3091                 n += sprintf(buf + n, "\n");
3092         }
3093
3094         free_loc_track(&t);
3095         if (!t.count)
3096                 n += sprintf(buf, "No data\n");
3097         return n;
3098 }
3099
3100 static unsigned long count_partial(struct kmem_cache_node *n)
3101 {
3102         unsigned long flags;
3103         unsigned long x = 0;
3104         struct page *page;
3105
3106         spin_lock_irqsave(&n->list_lock, flags);
3107         list_for_each_entry(page, &n->partial, lru)
3108                 x += page->inuse;
3109         spin_unlock_irqrestore(&n->list_lock, flags);
3110         return x;
3111 }
3112
3113 enum slab_stat_type {
3114         SL_FULL,
3115         SL_PARTIAL,
3116         SL_CPU,
3117         SL_OBJECTS
3118 };
3119
3120 #define SO_FULL         (1 << SL_FULL)
3121 #define SO_PARTIAL      (1 << SL_PARTIAL)
3122 #define SO_CPU          (1 << SL_CPU)
3123 #define SO_OBJECTS      (1 << SL_OBJECTS)
3124
3125 static unsigned long slab_objects(struct kmem_cache *s,
3126                         char *buf, unsigned long flags)
3127 {
3128         unsigned long total = 0;
3129         int cpu;
3130         int node;
3131         int x;
3132         unsigned long *nodes;
3133         unsigned long *per_cpu;
3134
3135         nodes = kzalloc(2 * sizeof(unsigned long) * nr_node_ids, GFP_KERNEL);
3136         per_cpu = nodes + nr_node_ids;
3137
3138         for_each_possible_cpu(cpu) {
3139                 struct page *page = s->cpu_slab[cpu];
3140                 int node;
3141
3142                 if (page) {
3143                         node = page_to_nid(page);
3144                         if (flags & SO_CPU) {
3145                                 int x = 0;
3146
3147                                 if (flags & SO_OBJECTS)
3148                                         x = page->inuse;
3149                                 else
3150                                         x = 1;
3151                                 total += x;
3152                                 nodes[node] += x;
3153                         }
3154                         per_cpu[node]++;
3155                 }
3156         }
3157
3158         for_each_online_node(node) {
3159                 struct kmem_cache_node *n = get_node(s, node);
3160
3161                 if (flags & SO_PARTIAL) {
3162                         if (flags & SO_OBJECTS)
3163                                 x = count_partial(n);
3164                         else
3165                                 x = n->nr_partial;
3166                         total += x;
3167                         nodes[node] += x;
3168                 }
3169
3170                 if (flags & SO_FULL) {
3171                         int full_slabs = atomic_read(&n->nr_slabs)
3172                                         - per_cpu[node]
3173                                         - n->nr_partial;
3174
3175                         if (flags & SO_OBJECTS)
3176                                 x = full_slabs * s->objects;
3177                         else
3178                                 x = full_slabs;
3179                         total += x;
3180                         nodes[node] += x;
3181                 }
3182         }
3183
3184         x = sprintf(buf, "%lu", total);
3185 #ifdef CONFIG_NUMA
3186         for_each_online_node(node)
3187                 if (nodes[node])
3188                         x += sprintf(buf + x, " N%d=%lu",
3189                                         node, nodes[node]);
3190 #endif
3191         kfree(nodes);
3192         return x + sprintf(buf + x, "\n");
3193 }
3194
3195 static int any_slab_objects(struct kmem_cache *s)
3196 {
3197         int node;
3198         int cpu;
3199
3200         for_each_possible_cpu(cpu)
3201                 if (s->cpu_slab[cpu])
3202                         return 1;
3203
3204         for_each_node(node) {
3205                 struct kmem_cache_node *n = get_node(s, node);
3206
3207                 if (n->nr_partial || atomic_read(&n->nr_slabs))
3208                         return 1;
3209         }
3210         return 0;
3211 }
3212
3213 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr)
3214 #define to_slab(n) container_of(n, struct kmem_cache, kobj);
3215
3216 struct slab_attribute {
3217         struct attribute attr;
3218         ssize_t (*show)(struct kmem_cache *s, char *buf);
3219         ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count);
3220 };
3221
3222 #define SLAB_ATTR_RO(_name) \
3223         static struct slab_attribute _name##_attr = __ATTR_RO(_name)
3224
3225 #define SLAB_ATTR(_name) \
3226         static struct slab_attribute _name##_attr =  \
3227         __ATTR(_name, 0644, _name##_show, _name##_store)
3228
3229 static ssize_t slab_size_show(struct kmem_cache *s, char *buf)
3230 {
3231         return sprintf(buf, "%d\n", s->size);
3232 }
3233 SLAB_ATTR_RO(slab_size);
3234
3235 static ssize_t align_show(struct kmem_cache *s, char *buf)
3236 {
3237         return sprintf(buf, "%d\n", s->align);
3238 }
3239 SLAB_ATTR_RO(align);
3240
3241 static ssize_t object_size_show(struct kmem_cache *s, char *buf)
3242 {
3243         return sprintf(buf, "%d\n", s->objsize);
3244 }
3245 SLAB_ATTR_RO(object_size);
3246
3247 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf)
3248 {
3249         return sprintf(buf, "%d\n", s->objects);
3250 }
3251 SLAB_ATTR_RO(objs_per_slab);
3252
3253 static ssize_t order_show(struct kmem_cache *s, char *buf)
3254 {
3255         return sprintf(buf, "%d\n", s->order);
3256 }
3257 SLAB_ATTR_RO(order);
3258
3259 static ssize_t ctor_show(struct kmem_cache *s, char *buf)
3260 {
3261         if (s->ctor) {
3262                 int n = sprint_symbol(buf, (unsigned long)s->ctor);
3263
3264                 return n + sprintf(buf + n, "\n");
3265         }
3266         return 0;
3267 }
3268 SLAB_ATTR_RO(ctor);
3269
3270 static ssize_t aliases_show(struct kmem_cache *s, char *buf)
3271 {
3272         return sprintf(buf, "%d\n", s->refcount - 1);
3273 }
3274 SLAB_ATTR_RO(aliases);
3275
3276 static ssize_t slabs_show(struct kmem_cache *s, char *buf)
3277 {
3278         return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU);
3279 }
3280 SLAB_ATTR_RO(slabs);
3281
3282 static ssize_t partial_show(struct kmem_cache *s, char *buf)
3283 {
3284         return slab_objects(s, buf, SO_PARTIAL);
3285 }
3286 SLAB_ATTR_RO(partial);
3287
3288 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf)
3289 {
3290         return slab_objects(s, buf, SO_CPU);
3291 }
3292 SLAB_ATTR_RO(cpu_slabs);
3293
3294 static ssize_t objects_show(struct kmem_cache *s, char *buf)
3295 {
3296         return slab_objects(s, buf, SO_FULL|SO_PARTIAL|SO_CPU|SO_OBJECTS);
3297 }
3298 SLAB_ATTR_RO(objects);
3299
3300 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf)
3301 {
3302         return sprintf(buf, "%d\n", !!(s->flags & SLAB_DEBUG_FREE));
3303 }
3304
3305 static ssize_t sanity_checks_store(struct kmem_cache *s,
3306                                 const char *buf, size_t length)
3307 {
3308         s->flags &= ~SLAB_DEBUG_FREE;
3309         if (buf[0] == '1')
3310                 s->flags |= SLAB_DEBUG_FREE;
3311         return length;
3312 }
3313 SLAB_ATTR(sanity_checks);
3314
3315 static ssize_t trace_show(struct kmem_cache *s, char *buf)
3316 {
3317         return sprintf(buf, "%d\n", !!(s->flags & SLAB_TRACE));
3318 }
3319
3320 static ssize_t trace_store(struct kmem_cache *s, const char *buf,
3321                                                         size_t length)
3322 {
3323         s->flags &= ~SLAB_TRACE;
3324         if (buf[0] == '1')
3325                 s->flags |= SLAB_TRACE;
3326         return length;
3327 }
3328 SLAB_ATTR(trace);
3329
3330 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf)
3331 {
3332         return sprintf(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT));
3333 }
3334
3335 static ssize_t reclaim_account_store(struct kmem_cache *s,
3336                                 const char *buf, size_t length)
3337 {
3338         s->flags &= ~SLAB_RECLAIM_ACCOUNT;
3339         if (buf[0] == '1')
3340                 s->flags |= SLAB_RECLAIM_ACCOUNT;
3341         return length;
3342 }
3343 SLAB_ATTR(reclaim_account);
3344
3345 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf)
3346 {
3347         return sprintf(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN));
3348 }
3349 SLAB_ATTR_RO(hwcache_align);
3350
3351 #ifdef CONFIG_ZONE_DMA
3352 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf)
3353 {
3354         return sprintf(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA));
3355 }
3356 SLAB_ATTR_RO(cache_dma);
3357 #endif
3358
3359 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf)
3360 {
3361         return sprintf(buf, "%d\n", !!(s->flags & SLAB_DESTROY_BY_RCU));
3362 }
3363 SLAB_ATTR_RO(destroy_by_rcu);
3364
3365 static ssize_t red_zone_show(struct kmem_cache *s, char *buf)
3366 {
3367         return sprintf(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE));
3368 }
3369
3370 static ssize_t red_zone_store(struct kmem_cache *s,
3371                                 const char *buf, size_t length)
3372 {
3373         if (any_slab_objects(s))
3374                 return -EBUSY;
3375
3376         s->flags &= ~SLAB_RED_ZONE;
3377         if (buf[0] == '1')
3378                 s->flags |= SLAB_RED_ZONE;
3379         calculate_sizes(s);
3380         return length;
3381 }
3382 SLAB_ATTR(red_zone);
3383
3384 static ssize_t poison_show(struct kmem_cache *s, char *buf)
3385 {
3386         return sprintf(buf, "%d\n", !!(s->flags & SLAB_POISON));
3387 }
3388
3389 static ssize_t poison_store(struct kmem_cache *s,
3390                                 const char *buf, size_t length)
3391 {
3392         if (any_slab_objects(s))
3393                 return -EBUSY;
3394
3395         s->flags &= ~SLAB_POISON;
3396         if (buf[0] == '1')
3397                 s->flags |= SLAB_POISON;
3398         calculate_sizes(s);
3399         return length;
3400 }
3401 SLAB_ATTR(poison);
3402
3403 static ssize_t store_user_show(struct kmem_cache *s, char *buf)
3404 {
3405         return sprintf(buf, "%d\n", !!(s->flags & SLAB_STORE_USER));
3406 }
3407
3408 static ssize_t store_user_store(struct kmem_cache *s,
3409                                 const char *buf, size_t length)
3410 {
3411         if (any_slab_objects(s))
3412                 return -EBUSY;
3413
3414         s->flags &= ~SLAB_STORE_USER;
3415         if (buf[0] == '1')
3416                 s->flags |= SLAB_STORE_USER;
3417         calculate_sizes(s);
3418         return length;
3419 }
3420 SLAB_ATTR(store_user);
3421
3422 static ssize_t validate_show(struct kmem_cache *s, char *buf)
3423 {
3424         return 0;
3425 }
3426
3427 static ssize_t validate_store(struct kmem_cache *s,
3428                         const char *buf, size_t length)
3429 {
3430         if (buf[0] == '1')
3431                 validate_slab_cache(s);
3432         else
3433                 return -EINVAL;
3434         return length;
3435 }
3436 SLAB_ATTR(validate);
3437
3438 static ssize_t shrink_show(struct kmem_cache *s, char *buf)
3439 {
3440         return 0;
3441 }
3442
3443 static ssize_t shrink_store(struct kmem_cache *s,
3444                         const char *buf, size_t length)
3445 {
3446         if (buf[0] == '1') {
3447                 int rc = kmem_cache_shrink(s);
3448
3449                 if (rc)
3450                         return rc;
3451         } else
3452                 return -EINVAL;
3453         return length;
3454 }
3455 SLAB_ATTR(shrink);
3456
3457 static ssize_t alloc_calls_show(struct kmem_cache *s, char *buf)
3458 {
3459         if (!(s->flags & SLAB_STORE_USER))
3460                 return -ENOSYS;
3461         return list_locations(s, buf, TRACK_ALLOC);
3462 }
3463 SLAB_ATTR_RO(alloc_calls);
3464
3465 static ssize_t free_calls_show(struct kmem_cache *s, char *buf)
3466 {
3467         if (!(s->flags & SLAB_STORE_USER))
3468                 return -ENOSYS;
3469         return list_locations(s, buf, TRACK_FREE);
3470 }
3471 SLAB_ATTR_RO(free_calls);
3472
3473 #ifdef CONFIG_NUMA
3474 static ssize_t defrag_ratio_show(struct kmem_cache *s, char *buf)
3475 {
3476         return sprintf(buf, "%d\n", s->defrag_ratio / 10);
3477 }
3478
3479 static ssize_t defrag_ratio_store(struct kmem_cache *s,
3480                                 const char *buf, size_t length)
3481 {
3482         int n = simple_strtoul(buf, NULL, 10);
3483
3484         if (n < 100)
3485                 s->defrag_ratio = n * 10;
3486         return length;
3487 }
3488 SLAB_ATTR(defrag_ratio);
3489 #endif
3490
3491 static struct attribute * slab_attrs[] = {
3492         &slab_size_attr.attr,
3493         &object_size_attr.attr,
3494         &objs_per_slab_attr.attr,
3495         &order_attr.attr,
3496         &objects_attr.attr,
3497         &slabs_attr.attr,
3498         &partial_attr.attr,
3499         &cpu_slabs_attr.attr,
3500         &ctor_attr.attr,
3501         &aliases_attr.attr,
3502         &align_attr.attr,
3503         &sanity_checks_attr.attr,
3504         &trace_attr.attr,
3505         &hwcache_align_attr.attr,
3506         &reclaim_account_attr.attr,
3507         &destroy_by_rcu_attr.attr,
3508         &red_zone_attr.attr,
3509         &poison_attr.attr,
3510         &store_user_attr.attr,
3511         &validate_attr.attr,
3512         &shrink_attr.attr,
3513         &alloc_calls_attr.attr,
3514         &free_calls_attr.attr,
3515 #ifdef CONFIG_ZONE_DMA
3516         &cache_dma_attr.attr,
3517 #endif
3518 #ifdef CONFIG_NUMA
3519         &defrag_ratio_attr.attr,
3520 #endif
3521         NULL
3522 };
3523
3524 static struct attribute_group slab_attr_group = {
3525         .attrs = slab_attrs,
3526 };
3527
3528 static ssize_t slab_attr_show(struct kobject *kobj,
3529                                 struct attribute *attr,
3530                                 char *buf)
3531 {
3532         struct slab_attribute *attribute;
3533         struct kmem_cache *s;
3534         int err;
3535
3536         attribute = to_slab_attr(attr);
3537         s = to_slab(kobj);
3538
3539         if (!attribute->show)
3540                 return -EIO;
3541
3542         err = attribute->show(s, buf);
3543
3544         return err;
3545 }
3546
3547 static ssize_t slab_attr_store(struct kobject *kobj,
3548                                 struct attribute *attr,
3549                                 const char *buf, size_t len)
3550 {
3551         struct slab_attribute *attribute;
3552         struct kmem_cache *s;
3553         int err;
3554
3555         attribute = to_slab_attr(attr);
3556         s = to_slab(kobj);
3557
3558         if (!attribute->store)
3559                 return -EIO;
3560
3561         err = attribute->store(s, buf, len);
3562
3563         return err;
3564 }
3565
3566 static struct sysfs_ops slab_sysfs_ops = {
3567         .show = slab_attr_show,
3568         .store = slab_attr_store,
3569 };
3570
3571 static struct kobj_type slab_ktype = {
3572         .sysfs_ops = &slab_sysfs_ops,
3573 };
3574
3575 static int uevent_filter(struct kset *kset, struct kobject *kobj)
3576 {
3577         struct kobj_type *ktype = get_ktype(kobj);
3578
3579         if (ktype == &slab_ktype)
3580                 return 1;
3581         return 0;
3582 }
3583
3584 static struct kset_uevent_ops slab_uevent_ops = {
3585         .filter = uevent_filter,
3586 };
3587
3588 decl_subsys(slab, &slab_ktype, &slab_uevent_ops);
3589
3590 #define ID_STR_LENGTH 64
3591
3592 /* Create a unique string id for a slab cache:
3593  * format
3594  * :[flags-]size:[memory address of kmemcache]
3595  */
3596 static char *create_unique_id(struct kmem_cache *s)
3597 {
3598         char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL);
3599         char *p = name;
3600
3601         BUG_ON(!name);
3602
3603         *p++ = ':';
3604         /*
3605          * First flags affecting slabcache operations. We will only
3606          * get here for aliasable slabs so we do not need to support
3607          * too many flags. The flags here must cover all flags that
3608          * are matched during merging to guarantee that the id is
3609          * unique.
3610          */
3611         if (s->flags & SLAB_CACHE_DMA)
3612                 *p++ = 'd';
3613         if (s->flags & SLAB_RECLAIM_ACCOUNT)
3614                 *p++ = 'a';
3615         if (s->flags & SLAB_DEBUG_FREE)
3616                 *p++ = 'F';
3617         if (p != name + 1)
3618                 *p++ = '-';
3619         p += sprintf(p, "%07d", s->size);
3620         BUG_ON(p > name + ID_STR_LENGTH - 1);
3621         return name;
3622 }
3623
3624 static int sysfs_slab_add(struct kmem_cache *s)
3625 {
3626         int err;
3627         const char *name;
3628         int unmergeable;
3629
3630         if (slab_state < SYSFS)
3631                 /* Defer until later */
3632                 return 0;
3633
3634         unmergeable = slab_unmergeable(s);
3635         if (unmergeable) {
3636                 /*
3637                  * Slabcache can never be merged so we can use the name proper.
3638                  * This is typically the case for debug situations. In that
3639                  * case we can catch duplicate names easily.
3640                  */
3641                 sysfs_remove_link(&slab_subsys.kobj, s->name);
3642                 name = s->name;
3643         } else {
3644                 /*
3645                  * Create a unique name for the slab as a target
3646                  * for the symlinks.
3647                  */
3648                 name = create_unique_id(s);
3649         }
3650
3651         kobj_set_kset_s(s, slab_subsys);
3652         kobject_set_name(&s->kobj, name);
3653         kobject_init(&s->kobj);
3654         err = kobject_add(&s->kobj);
3655         if (err)
3656                 return err;
3657
3658         err = sysfs_create_group(&s->kobj, &slab_attr_group);
3659         if (err)
3660                 return err;
3661         kobject_uevent(&s->kobj, KOBJ_ADD);
3662         if (!unmergeable) {
3663                 /* Setup first alias */
3664                 sysfs_slab_alias(s, s->name);
3665                 kfree(name);
3666         }
3667         return 0;
3668 }
3669
3670 static void sysfs_slab_remove(struct kmem_cache *s)
3671 {
3672         kobject_uevent(&s->kobj, KOBJ_REMOVE);
3673         kobject_del(&s->kobj);
3674 }
3675
3676 /*
3677  * Need to buffer aliases during bootup until sysfs becomes
3678  * available lest we loose that information.
3679  */
3680 struct saved_alias {
3681         struct kmem_cache *s;
3682         const char *name;
3683         struct saved_alias *next;
3684 };
3685
3686 struct saved_alias *alias_list;
3687
3688 static int sysfs_slab_alias(struct kmem_cache *s, const char *name)
3689 {
3690         struct saved_alias *al;
3691
3692         if (slab_state == SYSFS) {
3693                 /*
3694                  * If we have a leftover link then remove it.
3695                  */
3696                 sysfs_remove_link(&slab_subsys.kobj, name);
3697                 return sysfs_create_link(&slab_subsys.kobj,
3698                                                 &s->kobj, name);
3699         }
3700
3701         al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL);
3702         if (!al)
3703                 return -ENOMEM;
3704
3705         al->s = s;
3706         al->name = name;
3707         al->next = alias_list;
3708         alias_list = al;
3709         return 0;
3710 }
3711
3712 static int __init slab_sysfs_init(void)
3713 {
3714         struct kmem_cache *s;
3715         int err;
3716
3717         err = subsystem_register(&slab_subsys);
3718         if (err) {
3719                 printk(KERN_ERR "Cannot register slab subsystem.\n");
3720                 return -ENOSYS;
3721         }
3722
3723         slab_state = SYSFS;
3724
3725         list_for_each_entry(s, &slab_caches, list) {
3726                 err = sysfs_slab_add(s);
3727                 BUG_ON(err);
3728         }
3729
3730         while (alias_list) {
3731                 struct saved_alias *al = alias_list;
3732
3733                 alias_list = alias_list->next;
3734                 err = sysfs_slab_alias(al->s, al->name);
3735                 BUG_ON(err);
3736                 kfree(al);
3737         }
3738
3739         resiliency_test();
3740         return 0;
3741 }
3742
3743 __initcall(slab_sysfs_init);
3744 #endif