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