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