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