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