]> git.karo-electronics.de Git - karo-tx-linux.git/blob - mm/slab.c
d3608d15fbe4c92968cc9a41977bf6d4d5f426d4
[karo-tx-linux.git] / mm / slab.c
1 /*
2  * linux/mm/slab.c
3  * Written by Mark Hemment, 1996/97.
4  * (markhe@nextd.demon.co.uk)
5  *
6  * kmem_cache_destroy() + some cleanup - 1999 Andrea Arcangeli
7  *
8  * Major cleanup, different bufctl logic, per-cpu arrays
9  *      (c) 2000 Manfred Spraul
10  *
11  * Cleanup, make the head arrays unconditional, preparation for NUMA
12  *      (c) 2002 Manfred Spraul
13  *
14  * An implementation of the Slab Allocator as described in outline in;
15  *      UNIX Internals: The New Frontiers by Uresh Vahalia
16  *      Pub: Prentice Hall      ISBN 0-13-101908-2
17  * or with a little more detail in;
18  *      The Slab Allocator: An Object-Caching Kernel Memory Allocator
19  *      Jeff Bonwick (Sun Microsystems).
20  *      Presented at: USENIX Summer 1994 Technical Conference
21  *
22  * The memory is organized in caches, one cache for each object type.
23  * (e.g. inode_cache, dentry_cache, buffer_head, vm_area_struct)
24  * Each cache consists out of many slabs (they are small (usually one
25  * page long) and always contiguous), and each slab contains multiple
26  * initialized objects.
27  *
28  * This means, that your constructor is used only for newly allocated
29  * slabs and you must pass objects with the same initializations to
30  * kmem_cache_free.
31  *
32  * Each cache can only support one memory type (GFP_DMA, GFP_HIGHMEM,
33  * normal). If you need a special memory type, then must create a new
34  * cache for that memory type.
35  *
36  * In order to reduce fragmentation, the slabs are sorted in 3 groups:
37  *   full slabs with 0 free objects
38  *   partial slabs
39  *   empty slabs with no allocated objects
40  *
41  * If partial slabs exist, then new allocations come from these slabs,
42  * otherwise from empty slabs or new slabs are allocated.
43  *
44  * kmem_cache_destroy() CAN CRASH if you try to allocate from the cache
45  * during kmem_cache_destroy(). The caller must prevent concurrent allocs.
46  *
47  * Each cache has a short per-cpu head array, most allocs
48  * and frees go into that array, and if that array overflows, then 1/2
49  * of the entries in the array are given back into the global cache.
50  * The head array is strictly LIFO and should improve the cache hit rates.
51  * On SMP, it additionally reduces the spinlock operations.
52  *
53  * The c_cpuarray may not be read with enabled local interrupts -
54  * it's changed with a smp_call_function().
55  *
56  * SMP synchronization:
57  *  constructors and destructors are called without any locking.
58  *  Several members in struct kmem_cache and struct slab never change, they
59  *      are accessed without any locking.
60  *  The per-cpu arrays are never accessed from the wrong cpu, no locking,
61  *      and local interrupts are disabled so slab code is preempt-safe.
62  *  The non-constant members are protected with a per-cache irq spinlock.
63  *
64  * Many thanks to Mark Hemment, who wrote another per-cpu slab patch
65  * in 2000 - many ideas in the current implementation are derived from
66  * his patch.
67  *
68  * Further notes from the original documentation:
69  *
70  * 11 April '97.  Started multi-threading - markhe
71  *      The global cache-chain is protected by the mutex 'slab_mutex'.
72  *      The sem is only needed when accessing/extending the cache-chain, which
73  *      can never happen inside an interrupt (kmem_cache_create(),
74  *      kmem_cache_shrink() and kmem_cache_reap()).
75  *
76  *      At present, each engine can be growing a cache.  This should be blocked.
77  *
78  * 15 March 2005. NUMA slab allocator.
79  *      Shai Fultheim <shai@scalex86.org>.
80  *      Shobhit Dayal <shobhit@calsoftinc.com>
81  *      Alok N Kataria <alokk@calsoftinc.com>
82  *      Christoph Lameter <christoph@lameter.com>
83  *
84  *      Modified the slab allocator to be node aware on NUMA systems.
85  *      Each node has its own list of partial, free and full slabs.
86  *      All object allocations for a node occur from node specific slab lists.
87  */
88
89 #include        <linux/slab.h>
90 #include        <linux/mm.h>
91 #include        <linux/poison.h>
92 #include        <linux/swap.h>
93 #include        <linux/cache.h>
94 #include        <linux/interrupt.h>
95 #include        <linux/init.h>
96 #include        <linux/compiler.h>
97 #include        <linux/cpuset.h>
98 #include        <linux/proc_fs.h>
99 #include        <linux/seq_file.h>
100 #include        <linux/notifier.h>
101 #include        <linux/kallsyms.h>
102 #include        <linux/cpu.h>
103 #include        <linux/sysctl.h>
104 #include        <linux/module.h>
105 #include        <linux/rcupdate.h>
106 #include        <linux/string.h>
107 #include        <linux/uaccess.h>
108 #include        <linux/nodemask.h>
109 #include        <linux/kmemleak.h>
110 #include        <linux/mempolicy.h>
111 #include        <linux/mutex.h>
112 #include        <linux/fault-inject.h>
113 #include        <linux/rtmutex.h>
114 #include        <linux/reciprocal_div.h>
115 #include        <linux/debugobjects.h>
116 #include        <linux/kmemcheck.h>
117 #include        <linux/memory.h>
118 #include        <linux/prefetch.h>
119
120 #include        <net/sock.h>
121
122 #include        <asm/cacheflush.h>
123 #include        <asm/tlbflush.h>
124 #include        <asm/page.h>
125
126 #include <trace/events/kmem.h>
127
128 #include        "internal.h"
129
130 #include        "slab.h"
131
132 /*
133  * DEBUG        - 1 for kmem_cache_create() to honour; SLAB_RED_ZONE & SLAB_POISON.
134  *                0 for faster, smaller code (especially in the critical paths).
135  *
136  * STATS        - 1 to collect stats for /proc/slabinfo.
137  *                0 for faster, smaller code (especially in the critical paths).
138  *
139  * FORCED_DEBUG - 1 enables SLAB_RED_ZONE and SLAB_POISON (if possible)
140  */
141
142 #ifdef CONFIG_DEBUG_SLAB
143 #define DEBUG           1
144 #define STATS           1
145 #define FORCED_DEBUG    1
146 #else
147 #define DEBUG           0
148 #define STATS           0
149 #define FORCED_DEBUG    0
150 #endif
151
152 /* Shouldn't this be in a header file somewhere? */
153 #define BYTES_PER_WORD          sizeof(void *)
154 #define REDZONE_ALIGN           max(BYTES_PER_WORD, __alignof__(unsigned long long))
155
156 #ifndef ARCH_KMALLOC_FLAGS
157 #define ARCH_KMALLOC_FLAGS SLAB_HWCACHE_ALIGN
158 #endif
159
160 #define FREELIST_BYTE_INDEX (((PAGE_SIZE >> BITS_PER_BYTE) \
161                                 <= SLAB_OBJ_MIN_SIZE) ? 1 : 0)
162
163 #if FREELIST_BYTE_INDEX
164 typedef unsigned char freelist_idx_t;
165 #else
166 typedef unsigned short freelist_idx_t;
167 #endif
168
169 #define SLAB_OBJ_MAX_NUM ((1 << sizeof(freelist_idx_t) * BITS_PER_BYTE) - 1)
170
171 /*
172  * true if a page was allocated from pfmemalloc reserves for network-based
173  * swap
174  */
175 static bool pfmemalloc_active __read_mostly;
176
177 /*
178  * struct array_cache
179  *
180  * Purpose:
181  * - LIFO ordering, to hand out cache-warm objects from _alloc
182  * - reduce the number of linked list operations
183  * - reduce spinlock operations
184  *
185  * The limit is stored in the per-cpu structure to reduce the data cache
186  * footprint.
187  *
188  */
189 struct array_cache {
190         unsigned int avail;
191         unsigned int limit;
192         unsigned int batchcount;
193         unsigned int touched;
194         void *entry[];  /*
195                          * Must have this definition in here for the proper
196                          * alignment of array_cache. Also simplifies accessing
197                          * the entries.
198                          *
199                          * Entries should not be directly dereferenced as
200                          * entries belonging to slabs marked pfmemalloc will
201                          * have the lower bits set SLAB_OBJ_PFMEMALLOC
202                          */
203 };
204
205 struct alien_cache {
206         spinlock_t lock;
207         struct array_cache ac;
208 };
209
210 #define SLAB_OBJ_PFMEMALLOC     1
211 static inline bool is_obj_pfmemalloc(void *objp)
212 {
213         return (unsigned long)objp & SLAB_OBJ_PFMEMALLOC;
214 }
215
216 static inline void set_obj_pfmemalloc(void **objp)
217 {
218         *objp = (void *)((unsigned long)*objp | SLAB_OBJ_PFMEMALLOC);
219         return;
220 }
221
222 static inline void clear_obj_pfmemalloc(void **objp)
223 {
224         *objp = (void *)((unsigned long)*objp & ~SLAB_OBJ_PFMEMALLOC);
225 }
226
227 /*
228  * Need this for bootstrapping a per node allocator.
229  */
230 #define NUM_INIT_LISTS (2 * MAX_NUMNODES)
231 static struct kmem_cache_node __initdata init_kmem_cache_node[NUM_INIT_LISTS];
232 #define CACHE_CACHE 0
233 #define SIZE_NODE (MAX_NUMNODES)
234
235 static int drain_freelist(struct kmem_cache *cache,
236                         struct kmem_cache_node *n, int tofree);
237 static void free_block(struct kmem_cache *cachep, void **objpp, int len,
238                         int node, struct list_head *list);
239 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list);
240 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp);
241 static void cache_reap(struct work_struct *unused);
242
243 static int slab_early_init = 1;
244
245 #define INDEX_NODE kmalloc_index(sizeof(struct kmem_cache_node))
246
247 static void kmem_cache_node_init(struct kmem_cache_node *parent)
248 {
249         INIT_LIST_HEAD(&parent->slabs_full);
250         INIT_LIST_HEAD(&parent->slabs_partial);
251         INIT_LIST_HEAD(&parent->slabs_free);
252         parent->shared = NULL;
253         parent->alien = NULL;
254         parent->colour_next = 0;
255         spin_lock_init(&parent->list_lock);
256         parent->free_objects = 0;
257         parent->free_touched = 0;
258 }
259
260 #define MAKE_LIST(cachep, listp, slab, nodeid)                          \
261         do {                                                            \
262                 INIT_LIST_HEAD(listp);                                  \
263                 list_splice(&get_node(cachep, nodeid)->slab, listp);    \
264         } while (0)
265
266 #define MAKE_ALL_LISTS(cachep, ptr, nodeid)                             \
267         do {                                                            \
268         MAKE_LIST((cachep), (&(ptr)->slabs_full), slabs_full, nodeid);  \
269         MAKE_LIST((cachep), (&(ptr)->slabs_partial), slabs_partial, nodeid); \
270         MAKE_LIST((cachep), (&(ptr)->slabs_free), slabs_free, nodeid);  \
271         } while (0)
272
273 #define CFLGS_OFF_SLAB          (0x80000000UL)
274 #define OFF_SLAB(x)     ((x)->flags & CFLGS_OFF_SLAB)
275
276 #define BATCHREFILL_LIMIT       16
277 /*
278  * Optimization question: fewer reaps means less probability for unnessary
279  * cpucache drain/refill cycles.
280  *
281  * OTOH the cpuarrays can contain lots of objects,
282  * which could lock up otherwise freeable slabs.
283  */
284 #define REAPTIMEOUT_AC          (2*HZ)
285 #define REAPTIMEOUT_NODE        (4*HZ)
286
287 #if STATS
288 #define STATS_INC_ACTIVE(x)     ((x)->num_active++)
289 #define STATS_DEC_ACTIVE(x)     ((x)->num_active--)
290 #define STATS_INC_ALLOCED(x)    ((x)->num_allocations++)
291 #define STATS_INC_GROWN(x)      ((x)->grown++)
292 #define STATS_ADD_REAPED(x,y)   ((x)->reaped += (y))
293 #define STATS_SET_HIGH(x)                                               \
294         do {                                                            \
295                 if ((x)->num_active > (x)->high_mark)                   \
296                         (x)->high_mark = (x)->num_active;               \
297         } while (0)
298 #define STATS_INC_ERR(x)        ((x)->errors++)
299 #define STATS_INC_NODEALLOCS(x) ((x)->node_allocs++)
300 #define STATS_INC_NODEFREES(x)  ((x)->node_frees++)
301 #define STATS_INC_ACOVERFLOW(x)   ((x)->node_overflow++)
302 #define STATS_SET_FREEABLE(x, i)                                        \
303         do {                                                            \
304                 if ((x)->max_freeable < i)                              \
305                         (x)->max_freeable = i;                          \
306         } while (0)
307 #define STATS_INC_ALLOCHIT(x)   atomic_inc(&(x)->allochit)
308 #define STATS_INC_ALLOCMISS(x)  atomic_inc(&(x)->allocmiss)
309 #define STATS_INC_FREEHIT(x)    atomic_inc(&(x)->freehit)
310 #define STATS_INC_FREEMISS(x)   atomic_inc(&(x)->freemiss)
311 #else
312 #define STATS_INC_ACTIVE(x)     do { } while (0)
313 #define STATS_DEC_ACTIVE(x)     do { } while (0)
314 #define STATS_INC_ALLOCED(x)    do { } while (0)
315 #define STATS_INC_GROWN(x)      do { } while (0)
316 #define STATS_ADD_REAPED(x,y)   do { (void)(y); } while (0)
317 #define STATS_SET_HIGH(x)       do { } while (0)
318 #define STATS_INC_ERR(x)        do { } while (0)
319 #define STATS_INC_NODEALLOCS(x) do { } while (0)
320 #define STATS_INC_NODEFREES(x)  do { } while (0)
321 #define STATS_INC_ACOVERFLOW(x)   do { } while (0)
322 #define STATS_SET_FREEABLE(x, i) do { } while (0)
323 #define STATS_INC_ALLOCHIT(x)   do { } while (0)
324 #define STATS_INC_ALLOCMISS(x)  do { } while (0)
325 #define STATS_INC_FREEHIT(x)    do { } while (0)
326 #define STATS_INC_FREEMISS(x)   do { } while (0)
327 #endif
328
329 #if DEBUG
330
331 /*
332  * memory layout of objects:
333  * 0            : objp
334  * 0 .. cachep->obj_offset - BYTES_PER_WORD - 1: padding. This ensures that
335  *              the end of an object is aligned with the end of the real
336  *              allocation. Catches writes behind the end of the allocation.
337  * cachep->obj_offset - BYTES_PER_WORD .. cachep->obj_offset - 1:
338  *              redzone word.
339  * cachep->obj_offset: The real object.
340  * cachep->size - 2* BYTES_PER_WORD: redzone word [BYTES_PER_WORD long]
341  * cachep->size - 1* BYTES_PER_WORD: last caller address
342  *                                      [BYTES_PER_WORD long]
343  */
344 static int obj_offset(struct kmem_cache *cachep)
345 {
346         return cachep->obj_offset;
347 }
348
349 static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
350 {
351         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
352         return (unsigned long long*) (objp + obj_offset(cachep) -
353                                       sizeof(unsigned long long));
354 }
355
356 static unsigned long long *dbg_redzone2(struct kmem_cache *cachep, void *objp)
357 {
358         BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
359         if (cachep->flags & SLAB_STORE_USER)
360                 return (unsigned long long *)(objp + cachep->size -
361                                               sizeof(unsigned long long) -
362                                               REDZONE_ALIGN);
363         return (unsigned long long *) (objp + cachep->size -
364                                        sizeof(unsigned long long));
365 }
366
367 static void **dbg_userword(struct kmem_cache *cachep, void *objp)
368 {
369         BUG_ON(!(cachep->flags & SLAB_STORE_USER));
370         return (void **)(objp + cachep->size - BYTES_PER_WORD);
371 }
372
373 #else
374
375 #define obj_offset(x)                   0
376 #define dbg_redzone1(cachep, objp)      ({BUG(); (unsigned long long *)NULL;})
377 #define dbg_redzone2(cachep, objp)      ({BUG(); (unsigned long long *)NULL;})
378 #define dbg_userword(cachep, objp)      ({BUG(); (void **)NULL;})
379
380 #endif
381
382 #ifdef CONFIG_DEBUG_SLAB_LEAK
383
384 static inline bool is_store_user_clean(struct kmem_cache *cachep)
385 {
386         return atomic_read(&cachep->store_user_clean) == 1;
387 }
388
389 static inline void set_store_user_clean(struct kmem_cache *cachep)
390 {
391         atomic_set(&cachep->store_user_clean, 1);
392 }
393
394 static inline void set_store_user_dirty(struct kmem_cache *cachep)
395 {
396         if (is_store_user_clean(cachep))
397                 atomic_set(&cachep->store_user_clean, 0);
398 }
399
400 #else
401 static inline void set_store_user_dirty(struct kmem_cache *cachep) {}
402
403 #endif
404
405 /*
406  * Do not go above this order unless 0 objects fit into the slab or
407  * overridden on the command line.
408  */
409 #define SLAB_MAX_ORDER_HI       1
410 #define SLAB_MAX_ORDER_LO       0
411 static int slab_max_order = SLAB_MAX_ORDER_LO;
412 static bool slab_max_order_set __initdata;
413
414 static inline struct kmem_cache *virt_to_cache(const void *obj)
415 {
416         struct page *page = virt_to_head_page(obj);
417         return page->slab_cache;
418 }
419
420 static inline void *index_to_obj(struct kmem_cache *cache, struct page *page,
421                                  unsigned int idx)
422 {
423         return page->s_mem + cache->size * idx;
424 }
425
426 /*
427  * We want to avoid an expensive divide : (offset / cache->size)
428  *   Using the fact that size is a constant for a particular cache,
429  *   we can replace (offset / cache->size) by
430  *   reciprocal_divide(offset, cache->reciprocal_buffer_size)
431  */
432 static inline unsigned int obj_to_index(const struct kmem_cache *cache,
433                                         const struct page *page, void *obj)
434 {
435         u32 offset = (obj - page->s_mem);
436         return reciprocal_divide(offset, cache->reciprocal_buffer_size);
437 }
438
439 #define BOOT_CPUCACHE_ENTRIES   1
440 /* internal cache of cache description objs */
441 static struct kmem_cache kmem_cache_boot = {
442         .batchcount = 1,
443         .limit = BOOT_CPUCACHE_ENTRIES,
444         .shared = 1,
445         .size = sizeof(struct kmem_cache),
446         .name = "kmem_cache",
447 };
448
449 #define BAD_ALIEN_MAGIC 0x01020304ul
450
451 static DEFINE_PER_CPU(struct delayed_work, slab_reap_work);
452
453 static inline struct array_cache *cpu_cache_get(struct kmem_cache *cachep)
454 {
455         return this_cpu_ptr(cachep->cpu_cache);
456 }
457
458 /*
459  * Calculate the number of objects and left-over bytes for a given buffer size.
460  */
461 static void cache_estimate(unsigned long gfporder, size_t buffer_size,
462                 unsigned long flags, size_t *left_over, unsigned int *num)
463 {
464         size_t slab_size = PAGE_SIZE << gfporder;
465
466         /*
467          * The slab management structure can be either off the slab or
468          * on it. For the latter case, the memory allocated for a
469          * slab is used for:
470          *
471          * - @buffer_size bytes for each object
472          * - One freelist_idx_t for each object
473          *
474          * We don't need to consider alignment of freelist because
475          * freelist will be at the end of slab page. The objects will be
476          * at the correct alignment.
477          *
478          * If the slab management structure is off the slab, then the
479          * alignment will already be calculated into the size. Because
480          * the slabs are all pages aligned, the objects will be at the
481          * correct alignment when allocated.
482          */
483         if (flags & CFLGS_OFF_SLAB) {
484                 *num = slab_size / buffer_size;
485                 *left_over = slab_size % buffer_size;
486         } else {
487                 *num = slab_size / (buffer_size + sizeof(freelist_idx_t));
488                 *left_over = slab_size %
489                         (buffer_size + sizeof(freelist_idx_t));
490         }
491 }
492
493 #if DEBUG
494 #define slab_error(cachep, msg) __slab_error(__func__, cachep, msg)
495
496 static void __slab_error(const char *function, struct kmem_cache *cachep,
497                         char *msg)
498 {
499         printk(KERN_ERR "slab error in %s(): cache `%s': %s\n",
500                function, cachep->name, msg);
501         dump_stack();
502         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
503 }
504 #endif
505
506 /*
507  * By default on NUMA we use alien caches to stage the freeing of
508  * objects allocated from other nodes. This causes massive memory
509  * inefficiencies when using fake NUMA setup to split memory into a
510  * large number of small nodes, so it can be disabled on the command
511  * line
512   */
513
514 static int use_alien_caches __read_mostly = 1;
515 static int __init noaliencache_setup(char *s)
516 {
517         use_alien_caches = 0;
518         return 1;
519 }
520 __setup("noaliencache", noaliencache_setup);
521
522 static int __init slab_max_order_setup(char *str)
523 {
524         get_option(&str, &slab_max_order);
525         slab_max_order = slab_max_order < 0 ? 0 :
526                                 min(slab_max_order, MAX_ORDER - 1);
527         slab_max_order_set = true;
528
529         return 1;
530 }
531 __setup("slab_max_order=", slab_max_order_setup);
532
533 #ifdef CONFIG_NUMA
534 /*
535  * Special reaping functions for NUMA systems called from cache_reap().
536  * These take care of doing round robin flushing of alien caches (containing
537  * objects freed on different nodes from which they were allocated) and the
538  * flushing of remote pcps by calling drain_node_pages.
539  */
540 static DEFINE_PER_CPU(unsigned long, slab_reap_node);
541
542 static void init_reap_node(int cpu)
543 {
544         int node;
545
546         node = next_node(cpu_to_mem(cpu), node_online_map);
547         if (node == MAX_NUMNODES)
548                 node = first_node(node_online_map);
549
550         per_cpu(slab_reap_node, cpu) = node;
551 }
552
553 static void next_reap_node(void)
554 {
555         int node = __this_cpu_read(slab_reap_node);
556
557         node = next_node(node, node_online_map);
558         if (unlikely(node >= MAX_NUMNODES))
559                 node = first_node(node_online_map);
560         __this_cpu_write(slab_reap_node, node);
561 }
562
563 #else
564 #define init_reap_node(cpu) do { } while (0)
565 #define next_reap_node(void) do { } while (0)
566 #endif
567
568 /*
569  * Initiate the reap timer running on the target CPU.  We run at around 1 to 2Hz
570  * via the workqueue/eventd.
571  * Add the CPU number into the expiration time to minimize the possibility of
572  * the CPUs getting into lockstep and contending for the global cache chain
573  * lock.
574  */
575 static void start_cpu_timer(int cpu)
576 {
577         struct delayed_work *reap_work = &per_cpu(slab_reap_work, cpu);
578
579         /*
580          * When this gets called from do_initcalls via cpucache_init(),
581          * init_workqueues() has already run, so keventd will be setup
582          * at that time.
583          */
584         if (keventd_up() && reap_work->work.func == NULL) {
585                 init_reap_node(cpu);
586                 INIT_DEFERRABLE_WORK(reap_work, cache_reap);
587                 schedule_delayed_work_on(cpu, reap_work,
588                                         __round_jiffies_relative(HZ, cpu));
589         }
590 }
591
592 static void init_arraycache(struct array_cache *ac, int limit, int batch)
593 {
594         /*
595          * The array_cache structures contain pointers to free object.
596          * However, when such objects are allocated or transferred to another
597          * cache the pointers are not cleared and they could be counted as
598          * valid references during a kmemleak scan. Therefore, kmemleak must
599          * not scan such objects.
600          */
601         kmemleak_no_scan(ac);
602         if (ac) {
603                 ac->avail = 0;
604                 ac->limit = limit;
605                 ac->batchcount = batch;
606                 ac->touched = 0;
607         }
608 }
609
610 static struct array_cache *alloc_arraycache(int node, int entries,
611                                             int batchcount, gfp_t gfp)
612 {
613         size_t memsize = sizeof(void *) * entries + sizeof(struct array_cache);
614         struct array_cache *ac = NULL;
615
616         ac = kmalloc_node(memsize, gfp, node);
617         init_arraycache(ac, entries, batchcount);
618         return ac;
619 }
620
621 static inline bool is_slab_pfmemalloc(struct page *page)
622 {
623         return PageSlabPfmemalloc(page);
624 }
625
626 /* Clears pfmemalloc_active if no slabs have pfmalloc set */
627 static void recheck_pfmemalloc_active(struct kmem_cache *cachep,
628                                                 struct array_cache *ac)
629 {
630         struct kmem_cache_node *n = get_node(cachep, numa_mem_id());
631         struct page *page;
632         unsigned long flags;
633
634         if (!pfmemalloc_active)
635                 return;
636
637         spin_lock_irqsave(&n->list_lock, flags);
638         list_for_each_entry(page, &n->slabs_full, lru)
639                 if (is_slab_pfmemalloc(page))
640                         goto out;
641
642         list_for_each_entry(page, &n->slabs_partial, lru)
643                 if (is_slab_pfmemalloc(page))
644                         goto out;
645
646         list_for_each_entry(page, &n->slabs_free, lru)
647                 if (is_slab_pfmemalloc(page))
648                         goto out;
649
650         pfmemalloc_active = false;
651 out:
652         spin_unlock_irqrestore(&n->list_lock, flags);
653 }
654
655 static void *__ac_get_obj(struct kmem_cache *cachep, struct array_cache *ac,
656                                                 gfp_t flags, bool force_refill)
657 {
658         int i;
659         void *objp = ac->entry[--ac->avail];
660
661         /* Ensure the caller is allowed to use objects from PFMEMALLOC slab */
662         if (unlikely(is_obj_pfmemalloc(objp))) {
663                 struct kmem_cache_node *n;
664
665                 if (gfp_pfmemalloc_allowed(flags)) {
666                         clear_obj_pfmemalloc(&objp);
667                         return objp;
668                 }
669
670                 /* The caller cannot use PFMEMALLOC objects, find another one */
671                 for (i = 0; i < ac->avail; i++) {
672                         /* If a !PFMEMALLOC object is found, swap them */
673                         if (!is_obj_pfmemalloc(ac->entry[i])) {
674                                 objp = ac->entry[i];
675                                 ac->entry[i] = ac->entry[ac->avail];
676                                 ac->entry[ac->avail] = objp;
677                                 return objp;
678                         }
679                 }
680
681                 /*
682                  * If there are empty slabs on the slabs_free list and we are
683                  * being forced to refill the cache, mark this one !pfmemalloc.
684                  */
685                 n = get_node(cachep, numa_mem_id());
686                 if (!list_empty(&n->slabs_free) && force_refill) {
687                         struct page *page = virt_to_head_page(objp);
688                         ClearPageSlabPfmemalloc(page);
689                         clear_obj_pfmemalloc(&objp);
690                         recheck_pfmemalloc_active(cachep, ac);
691                         return objp;
692                 }
693
694                 /* No !PFMEMALLOC objects available */
695                 ac->avail++;
696                 objp = NULL;
697         }
698
699         return objp;
700 }
701
702 static inline void *ac_get_obj(struct kmem_cache *cachep,
703                         struct array_cache *ac, gfp_t flags, bool force_refill)
704 {
705         void *objp;
706
707         if (unlikely(sk_memalloc_socks()))
708                 objp = __ac_get_obj(cachep, ac, flags, force_refill);
709         else
710                 objp = ac->entry[--ac->avail];
711
712         return objp;
713 }
714
715 static noinline void *__ac_put_obj(struct kmem_cache *cachep,
716                         struct array_cache *ac, void *objp)
717 {
718         if (unlikely(pfmemalloc_active)) {
719                 /* Some pfmemalloc slabs exist, check if this is one */
720                 struct page *page = virt_to_head_page(objp);
721                 if (PageSlabPfmemalloc(page))
722                         set_obj_pfmemalloc(&objp);
723         }
724
725         return objp;
726 }
727
728 static inline void ac_put_obj(struct kmem_cache *cachep, struct array_cache *ac,
729                                                                 void *objp)
730 {
731         if (unlikely(sk_memalloc_socks()))
732                 objp = __ac_put_obj(cachep, ac, objp);
733
734         ac->entry[ac->avail++] = objp;
735 }
736
737 /*
738  * Transfer objects in one arraycache to another.
739  * Locking must be handled by the caller.
740  *
741  * Return the number of entries transferred.
742  */
743 static int transfer_objects(struct array_cache *to,
744                 struct array_cache *from, unsigned int max)
745 {
746         /* Figure out how many entries to transfer */
747         int nr = min3(from->avail, max, to->limit - to->avail);
748
749         if (!nr)
750                 return 0;
751
752         memcpy(to->entry + to->avail, from->entry + from->avail -nr,
753                         sizeof(void *) *nr);
754
755         from->avail -= nr;
756         to->avail += nr;
757         return nr;
758 }
759
760 #ifndef CONFIG_NUMA
761
762 #define drain_alien_cache(cachep, alien) do { } while (0)
763 #define reap_alien(cachep, n) do { } while (0)
764
765 static inline struct alien_cache **alloc_alien_cache(int node,
766                                                 int limit, gfp_t gfp)
767 {
768         return (struct alien_cache **)BAD_ALIEN_MAGIC;
769 }
770
771 static inline void free_alien_cache(struct alien_cache **ac_ptr)
772 {
773 }
774
775 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
776 {
777         return 0;
778 }
779
780 static inline void *alternate_node_alloc(struct kmem_cache *cachep,
781                 gfp_t flags)
782 {
783         return NULL;
784 }
785
786 static inline void *____cache_alloc_node(struct kmem_cache *cachep,
787                  gfp_t flags, int nodeid)
788 {
789         return NULL;
790 }
791
792 static inline gfp_t gfp_exact_node(gfp_t flags)
793 {
794         return flags;
795 }
796
797 #else   /* CONFIG_NUMA */
798
799 static void *____cache_alloc_node(struct kmem_cache *, gfp_t, int);
800 static void *alternate_node_alloc(struct kmem_cache *, gfp_t);
801
802 static struct alien_cache *__alloc_alien_cache(int node, int entries,
803                                                 int batch, gfp_t gfp)
804 {
805         size_t memsize = sizeof(void *) * entries + sizeof(struct alien_cache);
806         struct alien_cache *alc = NULL;
807
808         alc = kmalloc_node(memsize, gfp, node);
809         init_arraycache(&alc->ac, entries, batch);
810         spin_lock_init(&alc->lock);
811         return alc;
812 }
813
814 static struct alien_cache **alloc_alien_cache(int node, int limit, gfp_t gfp)
815 {
816         struct alien_cache **alc_ptr;
817         size_t memsize = sizeof(void *) * nr_node_ids;
818         int i;
819
820         if (limit > 1)
821                 limit = 12;
822         alc_ptr = kzalloc_node(memsize, gfp, node);
823         if (!alc_ptr)
824                 return NULL;
825
826         for_each_node(i) {
827                 if (i == node || !node_online(i))
828                         continue;
829                 alc_ptr[i] = __alloc_alien_cache(node, limit, 0xbaadf00d, gfp);
830                 if (!alc_ptr[i]) {
831                         for (i--; i >= 0; i--)
832                                 kfree(alc_ptr[i]);
833                         kfree(alc_ptr);
834                         return NULL;
835                 }
836         }
837         return alc_ptr;
838 }
839
840 static void free_alien_cache(struct alien_cache **alc_ptr)
841 {
842         int i;
843
844         if (!alc_ptr)
845                 return;
846         for_each_node(i)
847             kfree(alc_ptr[i]);
848         kfree(alc_ptr);
849 }
850
851 static void __drain_alien_cache(struct kmem_cache *cachep,
852                                 struct array_cache *ac, int node,
853                                 struct list_head *list)
854 {
855         struct kmem_cache_node *n = get_node(cachep, node);
856
857         if (ac->avail) {
858                 spin_lock(&n->list_lock);
859                 /*
860                  * Stuff objects into the remote nodes shared array first.
861                  * That way we could avoid the overhead of putting the objects
862                  * into the free lists and getting them back later.
863                  */
864                 if (n->shared)
865                         transfer_objects(n->shared, ac, ac->limit);
866
867                 free_block(cachep, ac->entry, ac->avail, node, list);
868                 ac->avail = 0;
869                 spin_unlock(&n->list_lock);
870         }
871 }
872
873 /*
874  * Called from cache_reap() to regularly drain alien caches round robin.
875  */
876 static void reap_alien(struct kmem_cache *cachep, struct kmem_cache_node *n)
877 {
878         int node = __this_cpu_read(slab_reap_node);
879
880         if (n->alien) {
881                 struct alien_cache *alc = n->alien[node];
882                 struct array_cache *ac;
883
884                 if (alc) {
885                         ac = &alc->ac;
886                         if (ac->avail && spin_trylock_irq(&alc->lock)) {
887                                 LIST_HEAD(list);
888
889                                 __drain_alien_cache(cachep, ac, node, &list);
890                                 spin_unlock_irq(&alc->lock);
891                                 slabs_destroy(cachep, &list);
892                         }
893                 }
894         }
895 }
896
897 static void drain_alien_cache(struct kmem_cache *cachep,
898                                 struct alien_cache **alien)
899 {
900         int i = 0;
901         struct alien_cache *alc;
902         struct array_cache *ac;
903         unsigned long flags;
904
905         for_each_online_node(i) {
906                 alc = alien[i];
907                 if (alc) {
908                         LIST_HEAD(list);
909
910                         ac = &alc->ac;
911                         spin_lock_irqsave(&alc->lock, flags);
912                         __drain_alien_cache(cachep, ac, i, &list);
913                         spin_unlock_irqrestore(&alc->lock, flags);
914                         slabs_destroy(cachep, &list);
915                 }
916         }
917 }
918
919 static int __cache_free_alien(struct kmem_cache *cachep, void *objp,
920                                 int node, int page_node)
921 {
922         struct kmem_cache_node *n;
923         struct alien_cache *alien = NULL;
924         struct array_cache *ac;
925         LIST_HEAD(list);
926
927         n = get_node(cachep, node);
928         STATS_INC_NODEFREES(cachep);
929         if (n->alien && n->alien[page_node]) {
930                 alien = n->alien[page_node];
931                 ac = &alien->ac;
932                 spin_lock(&alien->lock);
933                 if (unlikely(ac->avail == ac->limit)) {
934                         STATS_INC_ACOVERFLOW(cachep);
935                         __drain_alien_cache(cachep, ac, page_node, &list);
936                 }
937                 ac_put_obj(cachep, ac, objp);
938                 spin_unlock(&alien->lock);
939                 slabs_destroy(cachep, &list);
940         } else {
941                 n = get_node(cachep, page_node);
942                 spin_lock(&n->list_lock);
943                 free_block(cachep, &objp, 1, page_node, &list);
944                 spin_unlock(&n->list_lock);
945                 slabs_destroy(cachep, &list);
946         }
947         return 1;
948 }
949
950 static inline int cache_free_alien(struct kmem_cache *cachep, void *objp)
951 {
952         int page_node = page_to_nid(virt_to_page(objp));
953         int node = numa_mem_id();
954         /*
955          * Make sure we are not freeing a object from another node to the array
956          * cache on this cpu.
957          */
958         if (likely(node == page_node))
959                 return 0;
960
961         return __cache_free_alien(cachep, objp, node, page_node);
962 }
963
964 /*
965  * Construct gfp mask to allocate from a specific node but do not direct reclaim
966  * or warn about failures. kswapd may still wake to reclaim in the background.
967  */
968 static inline gfp_t gfp_exact_node(gfp_t flags)
969 {
970         return (flags | __GFP_THISNODE | __GFP_NOWARN) & ~__GFP_DIRECT_RECLAIM;
971 }
972 #endif
973
974 /*
975  * Allocates and initializes node for a node on each slab cache, used for
976  * either memory or cpu hotplug.  If memory is being hot-added, the kmem_cache_node
977  * will be allocated off-node since memory is not yet online for the new node.
978  * When hotplugging memory or a cpu, existing node are not replaced if
979  * already in use.
980  *
981  * Must hold slab_mutex.
982  */
983 static int init_cache_node_node(int node)
984 {
985         struct kmem_cache *cachep;
986         struct kmem_cache_node *n;
987         const size_t memsize = sizeof(struct kmem_cache_node);
988
989         list_for_each_entry(cachep, &slab_caches, list) {
990                 /*
991                  * Set up the kmem_cache_node for cpu before we can
992                  * begin anything. Make sure some other cpu on this
993                  * node has not already allocated this
994                  */
995                 n = get_node(cachep, node);
996                 if (!n) {
997                         n = kmalloc_node(memsize, GFP_KERNEL, node);
998                         if (!n)
999                                 return -ENOMEM;
1000                         kmem_cache_node_init(n);
1001                         n->next_reap = jiffies + REAPTIMEOUT_NODE +
1002                             ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1003
1004                         /*
1005                          * The kmem_cache_nodes don't come and go as CPUs
1006                          * come and go.  slab_mutex is sufficient
1007                          * protection here.
1008                          */
1009                         cachep->node[node] = n;
1010                 }
1011
1012                 spin_lock_irq(&n->list_lock);
1013                 n->free_limit =
1014                         (1 + nr_cpus_node(node)) *
1015                         cachep->batchcount + cachep->num;
1016                 spin_unlock_irq(&n->list_lock);
1017         }
1018         return 0;
1019 }
1020
1021 static inline int slabs_tofree(struct kmem_cache *cachep,
1022                                                 struct kmem_cache_node *n)
1023 {
1024         return (n->free_objects + cachep->num - 1) / cachep->num;
1025 }
1026
1027 static void cpuup_canceled(long cpu)
1028 {
1029         struct kmem_cache *cachep;
1030         struct kmem_cache_node *n = NULL;
1031         int node = cpu_to_mem(cpu);
1032         const struct cpumask *mask = cpumask_of_node(node);
1033
1034         list_for_each_entry(cachep, &slab_caches, list) {
1035                 struct array_cache *nc;
1036                 struct array_cache *shared;
1037                 struct alien_cache **alien;
1038                 LIST_HEAD(list);
1039
1040                 n = get_node(cachep, node);
1041                 if (!n)
1042                         continue;
1043
1044                 spin_lock_irq(&n->list_lock);
1045
1046                 /* Free limit for this kmem_cache_node */
1047                 n->free_limit -= cachep->batchcount;
1048
1049                 /* cpu is dead; no one can alloc from it. */
1050                 nc = per_cpu_ptr(cachep->cpu_cache, cpu);
1051                 if (nc) {
1052                         free_block(cachep, nc->entry, nc->avail, node, &list);
1053                         nc->avail = 0;
1054                 }
1055
1056                 if (!cpumask_empty(mask)) {
1057                         spin_unlock_irq(&n->list_lock);
1058                         goto free_slab;
1059                 }
1060
1061                 shared = n->shared;
1062                 if (shared) {
1063                         free_block(cachep, shared->entry,
1064                                    shared->avail, node, &list);
1065                         n->shared = NULL;
1066                 }
1067
1068                 alien = n->alien;
1069                 n->alien = NULL;
1070
1071                 spin_unlock_irq(&n->list_lock);
1072
1073                 kfree(shared);
1074                 if (alien) {
1075                         drain_alien_cache(cachep, alien);
1076                         free_alien_cache(alien);
1077                 }
1078
1079 free_slab:
1080                 slabs_destroy(cachep, &list);
1081         }
1082         /*
1083          * In the previous loop, all the objects were freed to
1084          * the respective cache's slabs,  now we can go ahead and
1085          * shrink each nodelist to its limit.
1086          */
1087         list_for_each_entry(cachep, &slab_caches, list) {
1088                 n = get_node(cachep, node);
1089                 if (!n)
1090                         continue;
1091                 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1092         }
1093 }
1094
1095 static int cpuup_prepare(long cpu)
1096 {
1097         struct kmem_cache *cachep;
1098         struct kmem_cache_node *n = NULL;
1099         int node = cpu_to_mem(cpu);
1100         int err;
1101
1102         /*
1103          * We need to do this right in the beginning since
1104          * alloc_arraycache's are going to use this list.
1105          * kmalloc_node allows us to add the slab to the right
1106          * kmem_cache_node and not this cpu's kmem_cache_node
1107          */
1108         err = init_cache_node_node(node);
1109         if (err < 0)
1110                 goto bad;
1111
1112         /*
1113          * Now we can go ahead with allocating the shared arrays and
1114          * array caches
1115          */
1116         list_for_each_entry(cachep, &slab_caches, list) {
1117                 struct array_cache *shared = NULL;
1118                 struct alien_cache **alien = NULL;
1119
1120                 if (cachep->shared) {
1121                         shared = alloc_arraycache(node,
1122                                 cachep->shared * cachep->batchcount,
1123                                 0xbaadf00d, GFP_KERNEL);
1124                         if (!shared)
1125                                 goto bad;
1126                 }
1127                 if (use_alien_caches) {
1128                         alien = alloc_alien_cache(node, cachep->limit, GFP_KERNEL);
1129                         if (!alien) {
1130                                 kfree(shared);
1131                                 goto bad;
1132                         }
1133                 }
1134                 n = get_node(cachep, node);
1135                 BUG_ON(!n);
1136
1137                 spin_lock_irq(&n->list_lock);
1138                 if (!n->shared) {
1139                         /*
1140                          * We are serialised from CPU_DEAD or
1141                          * CPU_UP_CANCELLED by the cpucontrol lock
1142                          */
1143                         n->shared = shared;
1144                         shared = NULL;
1145                 }
1146 #ifdef CONFIG_NUMA
1147                 if (!n->alien) {
1148                         n->alien = alien;
1149                         alien = NULL;
1150                 }
1151 #endif
1152                 spin_unlock_irq(&n->list_lock);
1153                 kfree(shared);
1154                 free_alien_cache(alien);
1155         }
1156
1157         return 0;
1158 bad:
1159         cpuup_canceled(cpu);
1160         return -ENOMEM;
1161 }
1162
1163 static int cpuup_callback(struct notifier_block *nfb,
1164                                     unsigned long action, void *hcpu)
1165 {
1166         long cpu = (long)hcpu;
1167         int err = 0;
1168
1169         switch (action) {
1170         case CPU_UP_PREPARE:
1171         case CPU_UP_PREPARE_FROZEN:
1172                 mutex_lock(&slab_mutex);
1173                 err = cpuup_prepare(cpu);
1174                 mutex_unlock(&slab_mutex);
1175                 break;
1176         case CPU_ONLINE:
1177         case CPU_ONLINE_FROZEN:
1178                 start_cpu_timer(cpu);
1179                 break;
1180 #ifdef CONFIG_HOTPLUG_CPU
1181         case CPU_DOWN_PREPARE:
1182         case CPU_DOWN_PREPARE_FROZEN:
1183                 /*
1184                  * Shutdown cache reaper. Note that the slab_mutex is
1185                  * held so that if cache_reap() is invoked it cannot do
1186                  * anything expensive but will only modify reap_work
1187                  * and reschedule the timer.
1188                 */
1189                 cancel_delayed_work_sync(&per_cpu(slab_reap_work, cpu));
1190                 /* Now the cache_reaper is guaranteed to be not running. */
1191                 per_cpu(slab_reap_work, cpu).work.func = NULL;
1192                 break;
1193         case CPU_DOWN_FAILED:
1194         case CPU_DOWN_FAILED_FROZEN:
1195                 start_cpu_timer(cpu);
1196                 break;
1197         case CPU_DEAD:
1198         case CPU_DEAD_FROZEN:
1199                 /*
1200                  * Even if all the cpus of a node are down, we don't free the
1201                  * kmem_cache_node of any cache. This to avoid a race between
1202                  * cpu_down, and a kmalloc allocation from another cpu for
1203                  * memory from the node of the cpu going down.  The node
1204                  * structure is usually allocated from kmem_cache_create() and
1205                  * gets destroyed at kmem_cache_destroy().
1206                  */
1207                 /* fall through */
1208 #endif
1209         case CPU_UP_CANCELED:
1210         case CPU_UP_CANCELED_FROZEN:
1211                 mutex_lock(&slab_mutex);
1212                 cpuup_canceled(cpu);
1213                 mutex_unlock(&slab_mutex);
1214                 break;
1215         }
1216         return notifier_from_errno(err);
1217 }
1218
1219 static struct notifier_block cpucache_notifier = {
1220         &cpuup_callback, NULL, 0
1221 };
1222
1223 #if defined(CONFIG_NUMA) && defined(CONFIG_MEMORY_HOTPLUG)
1224 /*
1225  * Drains freelist for a node on each slab cache, used for memory hot-remove.
1226  * Returns -EBUSY if all objects cannot be drained so that the node is not
1227  * removed.
1228  *
1229  * Must hold slab_mutex.
1230  */
1231 static int __meminit drain_cache_node_node(int node)
1232 {
1233         struct kmem_cache *cachep;
1234         int ret = 0;
1235
1236         list_for_each_entry(cachep, &slab_caches, list) {
1237                 struct kmem_cache_node *n;
1238
1239                 n = get_node(cachep, node);
1240                 if (!n)
1241                         continue;
1242
1243                 drain_freelist(cachep, n, slabs_tofree(cachep, n));
1244
1245                 if (!list_empty(&n->slabs_full) ||
1246                     !list_empty(&n->slabs_partial)) {
1247                         ret = -EBUSY;
1248                         break;
1249                 }
1250         }
1251         return ret;
1252 }
1253
1254 static int __meminit slab_memory_callback(struct notifier_block *self,
1255                                         unsigned long action, void *arg)
1256 {
1257         struct memory_notify *mnb = arg;
1258         int ret = 0;
1259         int nid;
1260
1261         nid = mnb->status_change_nid;
1262         if (nid < 0)
1263                 goto out;
1264
1265         switch (action) {
1266         case MEM_GOING_ONLINE:
1267                 mutex_lock(&slab_mutex);
1268                 ret = init_cache_node_node(nid);
1269                 mutex_unlock(&slab_mutex);
1270                 break;
1271         case MEM_GOING_OFFLINE:
1272                 mutex_lock(&slab_mutex);
1273                 ret = drain_cache_node_node(nid);
1274                 mutex_unlock(&slab_mutex);
1275                 break;
1276         case MEM_ONLINE:
1277         case MEM_OFFLINE:
1278         case MEM_CANCEL_ONLINE:
1279         case MEM_CANCEL_OFFLINE:
1280                 break;
1281         }
1282 out:
1283         return notifier_from_errno(ret);
1284 }
1285 #endif /* CONFIG_NUMA && CONFIG_MEMORY_HOTPLUG */
1286
1287 /*
1288  * swap the static kmem_cache_node with kmalloced memory
1289  */
1290 static void __init init_list(struct kmem_cache *cachep, struct kmem_cache_node *list,
1291                                 int nodeid)
1292 {
1293         struct kmem_cache_node *ptr;
1294
1295         ptr = kmalloc_node(sizeof(struct kmem_cache_node), GFP_NOWAIT, nodeid);
1296         BUG_ON(!ptr);
1297
1298         memcpy(ptr, list, sizeof(struct kmem_cache_node));
1299         /*
1300          * Do not assume that spinlocks can be initialized via memcpy:
1301          */
1302         spin_lock_init(&ptr->list_lock);
1303
1304         MAKE_ALL_LISTS(cachep, ptr, nodeid);
1305         cachep->node[nodeid] = ptr;
1306 }
1307
1308 /*
1309  * For setting up all the kmem_cache_node for cache whose buffer_size is same as
1310  * size of kmem_cache_node.
1311  */
1312 static void __init set_up_node(struct kmem_cache *cachep, int index)
1313 {
1314         int node;
1315
1316         for_each_online_node(node) {
1317                 cachep->node[node] = &init_kmem_cache_node[index + node];
1318                 cachep->node[node]->next_reap = jiffies +
1319                     REAPTIMEOUT_NODE +
1320                     ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1321         }
1322 }
1323
1324 /*
1325  * Initialisation.  Called after the page allocator have been initialised and
1326  * before smp_init().
1327  */
1328 void __init kmem_cache_init(void)
1329 {
1330         int i;
1331
1332         BUILD_BUG_ON(sizeof(((struct page *)NULL)->lru) <
1333                                         sizeof(struct rcu_head));
1334         kmem_cache = &kmem_cache_boot;
1335
1336         if (num_possible_nodes() == 1)
1337                 use_alien_caches = 0;
1338
1339         for (i = 0; i < NUM_INIT_LISTS; i++)
1340                 kmem_cache_node_init(&init_kmem_cache_node[i]);
1341
1342         /*
1343          * Fragmentation resistance on low memory - only use bigger
1344          * page orders on machines with more than 32MB of memory if
1345          * not overridden on the command line.
1346          */
1347         if (!slab_max_order_set && totalram_pages > (32 << 20) >> PAGE_SHIFT)
1348                 slab_max_order = SLAB_MAX_ORDER_HI;
1349
1350         /* Bootstrap is tricky, because several objects are allocated
1351          * from caches that do not exist yet:
1352          * 1) initialize the kmem_cache cache: it contains the struct
1353          *    kmem_cache structures of all caches, except kmem_cache itself:
1354          *    kmem_cache is statically allocated.
1355          *    Initially an __init data area is used for the head array and the
1356          *    kmem_cache_node structures, it's replaced with a kmalloc allocated
1357          *    array at the end of the bootstrap.
1358          * 2) Create the first kmalloc cache.
1359          *    The struct kmem_cache for the new cache is allocated normally.
1360          *    An __init data area is used for the head array.
1361          * 3) Create the remaining kmalloc caches, with minimally sized
1362          *    head arrays.
1363          * 4) Replace the __init data head arrays for kmem_cache and the first
1364          *    kmalloc cache with kmalloc allocated arrays.
1365          * 5) Replace the __init data for kmem_cache_node for kmem_cache and
1366          *    the other cache's with kmalloc allocated memory.
1367          * 6) Resize the head arrays of the kmalloc caches to their final sizes.
1368          */
1369
1370         /* 1) create the kmem_cache */
1371
1372         /*
1373          * struct kmem_cache size depends on nr_node_ids & nr_cpu_ids
1374          */
1375         create_boot_cache(kmem_cache, "kmem_cache",
1376                 offsetof(struct kmem_cache, node) +
1377                                   nr_node_ids * sizeof(struct kmem_cache_node *),
1378                                   SLAB_HWCACHE_ALIGN);
1379         list_add(&kmem_cache->list, &slab_caches);
1380         slab_state = PARTIAL;
1381
1382         /*
1383          * Initialize the caches that provide memory for the  kmem_cache_node
1384          * structures first.  Without this, further allocations will bug.
1385          */
1386         kmalloc_caches[INDEX_NODE] = create_kmalloc_cache("kmalloc-node",
1387                                 kmalloc_size(INDEX_NODE), ARCH_KMALLOC_FLAGS);
1388         slab_state = PARTIAL_NODE;
1389         setup_kmalloc_cache_index_table();
1390
1391         slab_early_init = 0;
1392
1393         /* 5) Replace the bootstrap kmem_cache_node */
1394         {
1395                 int nid;
1396
1397                 for_each_online_node(nid) {
1398                         init_list(kmem_cache, &init_kmem_cache_node[CACHE_CACHE + nid], nid);
1399
1400                         init_list(kmalloc_caches[INDEX_NODE],
1401                                           &init_kmem_cache_node[SIZE_NODE + nid], nid);
1402                 }
1403         }
1404
1405         create_kmalloc_caches(ARCH_KMALLOC_FLAGS);
1406 }
1407
1408 void __init kmem_cache_init_late(void)
1409 {
1410         struct kmem_cache *cachep;
1411
1412         slab_state = UP;
1413
1414         /* 6) resize the head arrays to their final sizes */
1415         mutex_lock(&slab_mutex);
1416         list_for_each_entry(cachep, &slab_caches, list)
1417                 if (enable_cpucache(cachep, GFP_NOWAIT))
1418                         BUG();
1419         mutex_unlock(&slab_mutex);
1420
1421         /* Done! */
1422         slab_state = FULL;
1423
1424         /*
1425          * Register a cpu startup notifier callback that initializes
1426          * cpu_cache_get for all new cpus
1427          */
1428         register_cpu_notifier(&cpucache_notifier);
1429
1430 #ifdef CONFIG_NUMA
1431         /*
1432          * Register a memory hotplug callback that initializes and frees
1433          * node.
1434          */
1435         hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI);
1436 #endif
1437
1438         /*
1439          * The reap timers are started later, with a module init call: That part
1440          * of the kernel is not yet operational.
1441          */
1442 }
1443
1444 static int __init cpucache_init(void)
1445 {
1446         int cpu;
1447
1448         /*
1449          * Register the timers that return unneeded pages to the page allocator
1450          */
1451         for_each_online_cpu(cpu)
1452                 start_cpu_timer(cpu);
1453
1454         /* Done! */
1455         slab_state = FULL;
1456         return 0;
1457 }
1458 __initcall(cpucache_init);
1459
1460 static noinline void
1461 slab_out_of_memory(struct kmem_cache *cachep, gfp_t gfpflags, int nodeid)
1462 {
1463 #if DEBUG
1464         struct kmem_cache_node *n;
1465         struct page *page;
1466         unsigned long flags;
1467         int node;
1468         static DEFINE_RATELIMIT_STATE(slab_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
1469                                       DEFAULT_RATELIMIT_BURST);
1470
1471         if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slab_oom_rs))
1472                 return;
1473
1474         printk(KERN_WARNING
1475                 "SLAB: Unable to allocate memory on node %d (gfp=0x%x)\n",
1476                 nodeid, gfpflags);
1477         printk(KERN_WARNING "  cache: %s, object size: %d, order: %d\n",
1478                 cachep->name, cachep->size, cachep->gfporder);
1479
1480         for_each_kmem_cache_node(cachep, node, n) {
1481                 unsigned long active_objs = 0, num_objs = 0, free_objects = 0;
1482                 unsigned long active_slabs = 0, num_slabs = 0;
1483
1484                 spin_lock_irqsave(&n->list_lock, flags);
1485                 list_for_each_entry(page, &n->slabs_full, lru) {
1486                         active_objs += cachep->num;
1487                         active_slabs++;
1488                 }
1489                 list_for_each_entry(page, &n->slabs_partial, lru) {
1490                         active_objs += page->active;
1491                         active_slabs++;
1492                 }
1493                 list_for_each_entry(page, &n->slabs_free, lru)
1494                         num_slabs++;
1495
1496                 free_objects += n->free_objects;
1497                 spin_unlock_irqrestore(&n->list_lock, flags);
1498
1499                 num_slabs += active_slabs;
1500                 num_objs = num_slabs * cachep->num;
1501                 printk(KERN_WARNING
1502                         "  node %d: slabs: %ld/%ld, objs: %ld/%ld, free: %ld\n",
1503                         node, active_slabs, num_slabs, active_objs, num_objs,
1504                         free_objects);
1505         }
1506 #endif
1507 }
1508
1509 /*
1510  * Interface to system's page allocator. No need to hold the
1511  * kmem_cache_node ->list_lock.
1512  *
1513  * If we requested dmaable memory, we will get it. Even if we
1514  * did not request dmaable memory, we might get it, but that
1515  * would be relatively rare and ignorable.
1516  */
1517 static struct page *kmem_getpages(struct kmem_cache *cachep, gfp_t flags,
1518                                                                 int nodeid)
1519 {
1520         struct page *page;
1521         int nr_pages;
1522
1523         flags |= cachep->allocflags;
1524         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1525                 flags |= __GFP_RECLAIMABLE;
1526
1527         page = __alloc_pages_node(nodeid, flags | __GFP_NOTRACK, cachep->gfporder);
1528         if (!page) {
1529                 slab_out_of_memory(cachep, flags, nodeid);
1530                 return NULL;
1531         }
1532
1533         if (memcg_charge_slab(page, flags, cachep->gfporder, cachep)) {
1534                 __free_pages(page, cachep->gfporder);
1535                 return NULL;
1536         }
1537
1538         /* Record if ALLOC_NO_WATERMARKS was set when allocating the slab */
1539         if (page_is_pfmemalloc(page))
1540                 pfmemalloc_active = true;
1541
1542         nr_pages = (1 << cachep->gfporder);
1543         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1544                 add_zone_page_state(page_zone(page),
1545                         NR_SLAB_RECLAIMABLE, nr_pages);
1546         else
1547                 add_zone_page_state(page_zone(page),
1548                         NR_SLAB_UNRECLAIMABLE, nr_pages);
1549         __SetPageSlab(page);
1550         if (page_is_pfmemalloc(page))
1551                 SetPageSlabPfmemalloc(page);
1552
1553         if (kmemcheck_enabled && !(cachep->flags & SLAB_NOTRACK)) {
1554                 kmemcheck_alloc_shadow(page, cachep->gfporder, flags, nodeid);
1555
1556                 if (cachep->ctor)
1557                         kmemcheck_mark_uninitialized_pages(page, nr_pages);
1558                 else
1559                         kmemcheck_mark_unallocated_pages(page, nr_pages);
1560         }
1561
1562         return page;
1563 }
1564
1565 /*
1566  * Interface to system's page release.
1567  */
1568 static void kmem_freepages(struct kmem_cache *cachep, struct page *page)
1569 {
1570         const unsigned long nr_freed = (1 << cachep->gfporder);
1571
1572         kmemcheck_free_shadow(page, cachep->gfporder);
1573
1574         if (cachep->flags & SLAB_RECLAIM_ACCOUNT)
1575                 sub_zone_page_state(page_zone(page),
1576                                 NR_SLAB_RECLAIMABLE, nr_freed);
1577         else
1578                 sub_zone_page_state(page_zone(page),
1579                                 NR_SLAB_UNRECLAIMABLE, nr_freed);
1580
1581         BUG_ON(!PageSlab(page));
1582         __ClearPageSlabPfmemalloc(page);
1583         __ClearPageSlab(page);
1584         page_mapcount_reset(page);
1585         page->mapping = NULL;
1586
1587         if (current->reclaim_state)
1588                 current->reclaim_state->reclaimed_slab += nr_freed;
1589         __free_kmem_pages(page, cachep->gfporder);
1590 }
1591
1592 static void kmem_rcu_free(struct rcu_head *head)
1593 {
1594         struct kmem_cache *cachep;
1595         struct page *page;
1596
1597         page = container_of(head, struct page, rcu_head);
1598         cachep = page->slab_cache;
1599
1600         kmem_freepages(cachep, page);
1601 }
1602
1603 #if DEBUG
1604 static bool is_debug_pagealloc_cache(struct kmem_cache *cachep)
1605 {
1606         if (debug_pagealloc_enabled() && OFF_SLAB(cachep) &&
1607                 (cachep->size % PAGE_SIZE) == 0)
1608                 return true;
1609
1610         return false;
1611 }
1612
1613 #ifdef CONFIG_DEBUG_PAGEALLOC
1614 static void store_stackinfo(struct kmem_cache *cachep, unsigned long *addr,
1615                             unsigned long caller)
1616 {
1617         int size = cachep->object_size;
1618
1619         addr = (unsigned long *)&((char *)addr)[obj_offset(cachep)];
1620
1621         if (size < 5 * sizeof(unsigned long))
1622                 return;
1623
1624         *addr++ = 0x12345678;
1625         *addr++ = caller;
1626         *addr++ = smp_processor_id();
1627         size -= 3 * sizeof(unsigned long);
1628         {
1629                 unsigned long *sptr = &caller;
1630                 unsigned long svalue;
1631
1632                 while (!kstack_end(sptr)) {
1633                         svalue = *sptr++;
1634                         if (kernel_text_address(svalue)) {
1635                                 *addr++ = svalue;
1636                                 size -= sizeof(unsigned long);
1637                                 if (size <= sizeof(unsigned long))
1638                                         break;
1639                         }
1640                 }
1641
1642         }
1643         *addr++ = 0x87654321;
1644 }
1645
1646 static void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1647                                 int map, unsigned long caller)
1648 {
1649         if (!is_debug_pagealloc_cache(cachep))
1650                 return;
1651
1652         if (caller)
1653                 store_stackinfo(cachep, objp, caller);
1654
1655         kernel_map_pages(virt_to_page(objp), cachep->size / PAGE_SIZE, map);
1656 }
1657
1658 #else
1659 static inline void slab_kernel_map(struct kmem_cache *cachep, void *objp,
1660                                 int map, unsigned long caller) {}
1661
1662 #endif
1663
1664 static void poison_obj(struct kmem_cache *cachep, void *addr, unsigned char val)
1665 {
1666         int size = cachep->object_size;
1667         addr = &((char *)addr)[obj_offset(cachep)];
1668
1669         memset(addr, val, size);
1670         *(unsigned char *)(addr + size - 1) = POISON_END;
1671 }
1672
1673 static void dump_line(char *data, int offset, int limit)
1674 {
1675         int i;
1676         unsigned char error = 0;
1677         int bad_count = 0;
1678
1679         printk(KERN_ERR "%03x: ", offset);
1680         for (i = 0; i < limit; i++) {
1681                 if (data[offset + i] != POISON_FREE) {
1682                         error = data[offset + i];
1683                         bad_count++;
1684                 }
1685         }
1686         print_hex_dump(KERN_CONT, "", 0, 16, 1,
1687                         &data[offset], limit, 1);
1688
1689         if (bad_count == 1) {
1690                 error ^= POISON_FREE;
1691                 if (!(error & (error - 1))) {
1692                         printk(KERN_ERR "Single bit error detected. Probably "
1693                                         "bad RAM.\n");
1694 #ifdef CONFIG_X86
1695                         printk(KERN_ERR "Run memtest86+ or a similar memory "
1696                                         "test tool.\n");
1697 #else
1698                         printk(KERN_ERR "Run a memory test tool.\n");
1699 #endif
1700                 }
1701         }
1702 }
1703 #endif
1704
1705 #if DEBUG
1706
1707 static void print_objinfo(struct kmem_cache *cachep, void *objp, int lines)
1708 {
1709         int i, size;
1710         char *realobj;
1711
1712         if (cachep->flags & SLAB_RED_ZONE) {
1713                 printk(KERN_ERR "Redzone: 0x%llx/0x%llx.\n",
1714                         *dbg_redzone1(cachep, objp),
1715                         *dbg_redzone2(cachep, objp));
1716         }
1717
1718         if (cachep->flags & SLAB_STORE_USER) {
1719                 printk(KERN_ERR "Last user: [<%p>](%pSR)\n",
1720                        *dbg_userword(cachep, objp),
1721                        *dbg_userword(cachep, objp));
1722         }
1723         realobj = (char *)objp + obj_offset(cachep);
1724         size = cachep->object_size;
1725         for (i = 0; i < size && lines; i += 16, lines--) {
1726                 int limit;
1727                 limit = 16;
1728                 if (i + limit > size)
1729                         limit = size - i;
1730                 dump_line(realobj, i, limit);
1731         }
1732 }
1733
1734 static void check_poison_obj(struct kmem_cache *cachep, void *objp)
1735 {
1736         char *realobj;
1737         int size, i;
1738         int lines = 0;
1739
1740         if (is_debug_pagealloc_cache(cachep))
1741                 return;
1742
1743         realobj = (char *)objp + obj_offset(cachep);
1744         size = cachep->object_size;
1745
1746         for (i = 0; i < size; i++) {
1747                 char exp = POISON_FREE;
1748                 if (i == size - 1)
1749                         exp = POISON_END;
1750                 if (realobj[i] != exp) {
1751                         int limit;
1752                         /* Mismatch ! */
1753                         /* Print header */
1754                         if (lines == 0) {
1755                                 printk(KERN_ERR
1756                                         "Slab corruption (%s): %s start=%p, len=%d\n",
1757                                         print_tainted(), cachep->name, realobj, size);
1758                                 print_objinfo(cachep, objp, 0);
1759                         }
1760                         /* Hexdump the affected line */
1761                         i = (i / 16) * 16;
1762                         limit = 16;
1763                         if (i + limit > size)
1764                                 limit = size - i;
1765                         dump_line(realobj, i, limit);
1766                         i += 16;
1767                         lines++;
1768                         /* Limit to 5 lines */
1769                         if (lines > 5)
1770                                 break;
1771                 }
1772         }
1773         if (lines != 0) {
1774                 /* Print some data about the neighboring objects, if they
1775                  * exist:
1776                  */
1777                 struct page *page = virt_to_head_page(objp);
1778                 unsigned int objnr;
1779
1780                 objnr = obj_to_index(cachep, page, objp);
1781                 if (objnr) {
1782                         objp = index_to_obj(cachep, page, objnr - 1);
1783                         realobj = (char *)objp + obj_offset(cachep);
1784                         printk(KERN_ERR "Prev obj: start=%p, len=%d\n",
1785                                realobj, size);
1786                         print_objinfo(cachep, objp, 2);
1787                 }
1788                 if (objnr + 1 < cachep->num) {
1789                         objp = index_to_obj(cachep, page, objnr + 1);
1790                         realobj = (char *)objp + obj_offset(cachep);
1791                         printk(KERN_ERR "Next obj: start=%p, len=%d\n",
1792                                realobj, size);
1793                         print_objinfo(cachep, objp, 2);
1794                 }
1795         }
1796 }
1797 #endif
1798
1799 #if DEBUG
1800 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1801                                                 struct page *page)
1802 {
1803         int i;
1804         for (i = 0; i < cachep->num; i++) {
1805                 void *objp = index_to_obj(cachep, page, i);
1806
1807                 if (cachep->flags & SLAB_POISON) {
1808                         check_poison_obj(cachep, objp);
1809                         slab_kernel_map(cachep, objp, 1, 0);
1810                 }
1811                 if (cachep->flags & SLAB_RED_ZONE) {
1812                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
1813                                 slab_error(cachep, "start of a freed object "
1814                                            "was overwritten");
1815                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
1816                                 slab_error(cachep, "end of a freed object "
1817                                            "was overwritten");
1818                 }
1819         }
1820 }
1821 #else
1822 static void slab_destroy_debugcheck(struct kmem_cache *cachep,
1823                                                 struct page *page)
1824 {
1825 }
1826 #endif
1827
1828 /**
1829  * slab_destroy - destroy and release all objects in a slab
1830  * @cachep: cache pointer being destroyed
1831  * @page: page pointer being destroyed
1832  *
1833  * Destroy all the objs in a slab page, and release the mem back to the system.
1834  * Before calling the slab page must have been unlinked from the cache. The
1835  * kmem_cache_node ->list_lock is not held/needed.
1836  */
1837 static void slab_destroy(struct kmem_cache *cachep, struct page *page)
1838 {
1839         void *freelist;
1840
1841         freelist = page->freelist;
1842         slab_destroy_debugcheck(cachep, page);
1843         if (unlikely(cachep->flags & SLAB_DESTROY_BY_RCU))
1844                 call_rcu(&page->rcu_head, kmem_rcu_free);
1845         else
1846                 kmem_freepages(cachep, page);
1847
1848         /*
1849          * From now on, we don't use freelist
1850          * although actual page can be freed in rcu context
1851          */
1852         if (OFF_SLAB(cachep))
1853                 kmem_cache_free(cachep->freelist_cache, freelist);
1854 }
1855
1856 static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
1857 {
1858         struct page *page, *n;
1859
1860         list_for_each_entry_safe(page, n, list, lru) {
1861                 list_del(&page->lru);
1862                 slab_destroy(cachep, page);
1863         }
1864 }
1865
1866 /**
1867  * calculate_slab_order - calculate size (page order) of slabs
1868  * @cachep: pointer to the cache that is being created
1869  * @size: size of objects to be created in this cache.
1870  * @flags: slab allocation flags
1871  *
1872  * Also calculates the number of objects per slab.
1873  *
1874  * This could be made much more intelligent.  For now, try to avoid using
1875  * high order pages for slabs.  When the gfp() functions are more friendly
1876  * towards high-order requests, this should be changed.
1877  */
1878 static size_t calculate_slab_order(struct kmem_cache *cachep,
1879                                 size_t size, unsigned long flags)
1880 {
1881         size_t left_over = 0;
1882         int gfporder;
1883
1884         for (gfporder = 0; gfporder <= KMALLOC_MAX_ORDER; gfporder++) {
1885                 unsigned int num;
1886                 size_t remainder;
1887
1888                 cache_estimate(gfporder, size, flags, &remainder, &num);
1889                 if (!num)
1890                         continue;
1891
1892                 /* Can't handle number of objects more than SLAB_OBJ_MAX_NUM */
1893                 if (num > SLAB_OBJ_MAX_NUM)
1894                         break;
1895
1896                 if (flags & CFLGS_OFF_SLAB) {
1897                         struct kmem_cache *freelist_cache;
1898                         size_t freelist_size;
1899
1900                         freelist_size = num * sizeof(freelist_idx_t);
1901                         freelist_cache = kmalloc_slab(freelist_size, 0u);
1902                         if (!freelist_cache)
1903                                 continue;
1904
1905                         /*
1906                          * Needed to avoid possible looping condition
1907                          * in cache_grow()
1908                          */
1909                         if (OFF_SLAB(freelist_cache))
1910                                 continue;
1911
1912                         /* check if off slab has enough benefit */
1913                         if (freelist_cache->size > cachep->size / 2)
1914                                 continue;
1915                 }
1916
1917                 /* Found something acceptable - save it away */
1918                 cachep->num = num;
1919                 cachep->gfporder = gfporder;
1920                 left_over = remainder;
1921
1922                 /*
1923                  * A VFS-reclaimable slab tends to have most allocations
1924                  * as GFP_NOFS and we really don't want to have to be allocating
1925                  * higher-order pages when we are unable to shrink dcache.
1926                  */
1927                 if (flags & SLAB_RECLAIM_ACCOUNT)
1928                         break;
1929
1930                 /*
1931                  * Large number of objects is good, but very large slabs are
1932                  * currently bad for the gfp()s.
1933                  */
1934                 if (gfporder >= slab_max_order)
1935                         break;
1936
1937                 /*
1938                  * Acceptable internal fragmentation?
1939                  */
1940                 if (left_over * 8 <= (PAGE_SIZE << gfporder))
1941                         break;
1942         }
1943         return left_over;
1944 }
1945
1946 static struct array_cache __percpu *alloc_kmem_cache_cpus(
1947                 struct kmem_cache *cachep, int entries, int batchcount)
1948 {
1949         int cpu;
1950         size_t size;
1951         struct array_cache __percpu *cpu_cache;
1952
1953         size = sizeof(void *) * entries + sizeof(struct array_cache);
1954         cpu_cache = __alloc_percpu(size, sizeof(void *));
1955
1956         if (!cpu_cache)
1957                 return NULL;
1958
1959         for_each_possible_cpu(cpu) {
1960                 init_arraycache(per_cpu_ptr(cpu_cache, cpu),
1961                                 entries, batchcount);
1962         }
1963
1964         return cpu_cache;
1965 }
1966
1967 static int __init_refok setup_cpu_cache(struct kmem_cache *cachep, gfp_t gfp)
1968 {
1969         if (slab_state >= FULL)
1970                 return enable_cpucache(cachep, gfp);
1971
1972         cachep->cpu_cache = alloc_kmem_cache_cpus(cachep, 1, 1);
1973         if (!cachep->cpu_cache)
1974                 return 1;
1975
1976         if (slab_state == DOWN) {
1977                 /* Creation of first cache (kmem_cache). */
1978                 set_up_node(kmem_cache, CACHE_CACHE);
1979         } else if (slab_state == PARTIAL) {
1980                 /* For kmem_cache_node */
1981                 set_up_node(cachep, SIZE_NODE);
1982         } else {
1983                 int node;
1984
1985                 for_each_online_node(node) {
1986                         cachep->node[node] = kmalloc_node(
1987                                 sizeof(struct kmem_cache_node), gfp, node);
1988                         BUG_ON(!cachep->node[node]);
1989                         kmem_cache_node_init(cachep->node[node]);
1990                 }
1991         }
1992
1993         cachep->node[numa_mem_id()]->next_reap =
1994                         jiffies + REAPTIMEOUT_NODE +
1995                         ((unsigned long)cachep) % REAPTIMEOUT_NODE;
1996
1997         cpu_cache_get(cachep)->avail = 0;
1998         cpu_cache_get(cachep)->limit = BOOT_CPUCACHE_ENTRIES;
1999         cpu_cache_get(cachep)->batchcount = 1;
2000         cpu_cache_get(cachep)->touched = 0;
2001         cachep->batchcount = 1;
2002         cachep->limit = BOOT_CPUCACHE_ENTRIES;
2003         return 0;
2004 }
2005
2006 unsigned long kmem_cache_flags(unsigned long object_size,
2007         unsigned long flags, const char *name,
2008         void (*ctor)(void *))
2009 {
2010         return flags;
2011 }
2012
2013 struct kmem_cache *
2014 __kmem_cache_alias(const char *name, size_t size, size_t align,
2015                    unsigned long flags, void (*ctor)(void *))
2016 {
2017         struct kmem_cache *cachep;
2018
2019         cachep = find_mergeable(size, align, flags, name, ctor);
2020         if (cachep) {
2021                 cachep->refcount++;
2022
2023                 /*
2024                  * Adjust the object sizes so that we clear
2025                  * the complete object on kzalloc.
2026                  */
2027                 cachep->object_size = max_t(int, cachep->object_size, size);
2028         }
2029         return cachep;
2030 }
2031
2032 static bool set_off_slab_cache(struct kmem_cache *cachep,
2033                         size_t size, unsigned long flags)
2034 {
2035         size_t left;
2036
2037         cachep->num = 0;
2038
2039         /*
2040          * Always use on-slab management when SLAB_NOLEAKTRACE
2041          * to avoid recursive calls into kmemleak.
2042          */
2043         if (flags & SLAB_NOLEAKTRACE)
2044                 return false;
2045
2046         /*
2047          * Size is large, assume best to place the slab management obj
2048          * off-slab (should allow better packing of objs).
2049          */
2050         left = calculate_slab_order(cachep, size, flags | CFLGS_OFF_SLAB);
2051         if (!cachep->num)
2052                 return false;
2053
2054         /*
2055          * If the slab has been placed off-slab, and we have enough space then
2056          * move it on-slab. This is at the expense of any extra colouring.
2057          */
2058         if (left >= cachep->num * sizeof(freelist_idx_t))
2059                 return false;
2060
2061         cachep->colour = left / cachep->colour_off;
2062
2063         return true;
2064 }
2065
2066 static bool set_on_slab_cache(struct kmem_cache *cachep,
2067                         size_t size, unsigned long flags)
2068 {
2069         size_t left;
2070
2071         cachep->num = 0;
2072
2073         left = calculate_slab_order(cachep, size, flags);
2074         if (!cachep->num)
2075                 return false;
2076
2077         cachep->colour = left / cachep->colour_off;
2078
2079         return true;
2080 }
2081
2082 /**
2083  * __kmem_cache_create - Create a cache.
2084  * @cachep: cache management descriptor
2085  * @flags: SLAB flags
2086  *
2087  * Returns a ptr to the cache on success, NULL on failure.
2088  * Cannot be called within a int, but can be interrupted.
2089  * The @ctor is run when new pages are allocated by the cache.
2090  *
2091  * The flags are
2092  *
2093  * %SLAB_POISON - Poison the slab with a known test pattern (a5a5a5a5)
2094  * to catch references to uninitialised memory.
2095  *
2096  * %SLAB_RED_ZONE - Insert `Red' zones around the allocated memory to check
2097  * for buffer overruns.
2098  *
2099  * %SLAB_HWCACHE_ALIGN - Align the objects in this cache to a hardware
2100  * cacheline.  This can be beneficial if you're counting cycles as closely
2101  * as davem.
2102  */
2103 int
2104 __kmem_cache_create (struct kmem_cache *cachep, unsigned long flags)
2105 {
2106         size_t ralign = BYTES_PER_WORD;
2107         gfp_t gfp;
2108         int err;
2109         size_t size = cachep->size;
2110
2111 #if DEBUG
2112 #if FORCED_DEBUG
2113         /*
2114          * Enable redzoning and last user accounting, except for caches with
2115          * large objects, if the increased size would increase the object size
2116          * above the next power of two: caches with object sizes just above a
2117          * power of two have a significant amount of internal fragmentation.
2118          */
2119         if (size < 4096 || fls(size - 1) == fls(size-1 + REDZONE_ALIGN +
2120                                                 2 * sizeof(unsigned long long)))
2121                 flags |= SLAB_RED_ZONE | SLAB_STORE_USER;
2122         if (!(flags & SLAB_DESTROY_BY_RCU))
2123                 flags |= SLAB_POISON;
2124 #endif
2125 #endif
2126
2127         /*
2128          * Check that size is in terms of words.  This is needed to avoid
2129          * unaligned accesses for some archs when redzoning is used, and makes
2130          * sure any on-slab bufctl's are also correctly aligned.
2131          */
2132         if (size & (BYTES_PER_WORD - 1)) {
2133                 size += (BYTES_PER_WORD - 1);
2134                 size &= ~(BYTES_PER_WORD - 1);
2135         }
2136
2137         if (flags & SLAB_RED_ZONE) {
2138                 ralign = REDZONE_ALIGN;
2139                 /* If redzoning, ensure that the second redzone is suitably
2140                  * aligned, by adjusting the object size accordingly. */
2141                 size += REDZONE_ALIGN - 1;
2142                 size &= ~(REDZONE_ALIGN - 1);
2143         }
2144
2145         /* 3) caller mandated alignment */
2146         if (ralign < cachep->align) {
2147                 ralign = cachep->align;
2148         }
2149         /* disable debug if necessary */
2150         if (ralign > __alignof__(unsigned long long))
2151                 flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2152         /*
2153          * 4) Store it.
2154          */
2155         cachep->align = ralign;
2156         cachep->colour_off = cache_line_size();
2157         /* Offset must be a multiple of the alignment. */
2158         if (cachep->colour_off < cachep->align)
2159                 cachep->colour_off = cachep->align;
2160
2161         if (slab_is_available())
2162                 gfp = GFP_KERNEL;
2163         else
2164                 gfp = GFP_NOWAIT;
2165
2166 #if DEBUG
2167
2168         /*
2169          * Both debugging options require word-alignment which is calculated
2170          * into align above.
2171          */
2172         if (flags & SLAB_RED_ZONE) {
2173                 /* add space for red zone words */
2174                 cachep->obj_offset += sizeof(unsigned long long);
2175                 size += 2 * sizeof(unsigned long long);
2176         }
2177         if (flags & SLAB_STORE_USER) {
2178                 /* user store requires one word storage behind the end of
2179                  * the real object. But if the second red zone needs to be
2180                  * aligned to 64 bits, we must allow that much space.
2181                  */
2182                 if (flags & SLAB_RED_ZONE)
2183                         size += REDZONE_ALIGN;
2184                 else
2185                         size += BYTES_PER_WORD;
2186         }
2187 #endif
2188
2189         size = ALIGN(size, cachep->align);
2190         /*
2191          * We should restrict the number of objects in a slab to implement
2192          * byte sized index. Refer comment on SLAB_OBJ_MIN_SIZE definition.
2193          */
2194         if (FREELIST_BYTE_INDEX && size < SLAB_OBJ_MIN_SIZE)
2195                 size = ALIGN(SLAB_OBJ_MIN_SIZE, cachep->align);
2196
2197 #if DEBUG
2198         /*
2199          * To activate debug pagealloc, off-slab management is necessary
2200          * requirement. In early phase of initialization, small sized slab
2201          * doesn't get initialized so it would not be possible. So, we need
2202          * to check size >= 256. It guarantees that all necessary small
2203          * sized slab is initialized in current slab initialization sequence.
2204          */
2205         if (debug_pagealloc_enabled() && (flags & SLAB_POISON) &&
2206                 size >= 256 && cachep->object_size > cache_line_size()) {
2207                 if (size < PAGE_SIZE || size % PAGE_SIZE == 0) {
2208                         size_t tmp_size = ALIGN(size, PAGE_SIZE);
2209
2210                         if (set_off_slab_cache(cachep, tmp_size, flags)) {
2211                                 flags |= CFLGS_OFF_SLAB;
2212                                 cachep->obj_offset += tmp_size - size;
2213                                 size = tmp_size;
2214                                 goto done;
2215                         }
2216                 }
2217         }
2218 #endif
2219
2220         if (set_off_slab_cache(cachep, size, flags)) {
2221                 flags |= CFLGS_OFF_SLAB;
2222                 goto done;
2223         }
2224
2225         if (set_on_slab_cache(cachep, size, flags))
2226                 goto done;
2227
2228         return -E2BIG;
2229
2230 done:
2231         cachep->freelist_size = cachep->num * sizeof(freelist_idx_t);
2232         cachep->flags = flags;
2233         cachep->allocflags = __GFP_COMP;
2234         if (CONFIG_ZONE_DMA_FLAG && (flags & SLAB_CACHE_DMA))
2235                 cachep->allocflags |= GFP_DMA;
2236         cachep->size = size;
2237         cachep->reciprocal_buffer_size = reciprocal_value(size);
2238
2239 #if DEBUG
2240         /*
2241          * If we're going to use the generic kernel_map_pages()
2242          * poisoning, then it's going to smash the contents of
2243          * the redzone and userword anyhow, so switch them off.
2244          */
2245         if (IS_ENABLED(CONFIG_PAGE_POISONING) &&
2246                 (cachep->flags & SLAB_POISON) &&
2247                 is_debug_pagealloc_cache(cachep))
2248                 cachep->flags &= ~(SLAB_RED_ZONE | SLAB_STORE_USER);
2249 #endif
2250
2251         if (OFF_SLAB(cachep)) {
2252                 cachep->freelist_cache =
2253                         kmalloc_slab(cachep->freelist_size, 0u);
2254         }
2255
2256         err = setup_cpu_cache(cachep, gfp);
2257         if (err) {
2258                 __kmem_cache_release(cachep);
2259                 return err;
2260         }
2261
2262         return 0;
2263 }
2264
2265 #if DEBUG
2266 static void check_irq_off(void)
2267 {
2268         BUG_ON(!irqs_disabled());
2269 }
2270
2271 static void check_irq_on(void)
2272 {
2273         BUG_ON(irqs_disabled());
2274 }
2275
2276 static void check_spinlock_acquired(struct kmem_cache *cachep)
2277 {
2278 #ifdef CONFIG_SMP
2279         check_irq_off();
2280         assert_spin_locked(&get_node(cachep, numa_mem_id())->list_lock);
2281 #endif
2282 }
2283
2284 static void check_spinlock_acquired_node(struct kmem_cache *cachep, int node)
2285 {
2286 #ifdef CONFIG_SMP
2287         check_irq_off();
2288         assert_spin_locked(&get_node(cachep, node)->list_lock);
2289 #endif
2290 }
2291
2292 #else
2293 #define check_irq_off() do { } while(0)
2294 #define check_irq_on()  do { } while(0)
2295 #define check_spinlock_acquired(x) do { } while(0)
2296 #define check_spinlock_acquired_node(x, y) do { } while(0)
2297 #endif
2298
2299 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
2300                         struct array_cache *ac,
2301                         int force, int node);
2302
2303 static void do_drain(void *arg)
2304 {
2305         struct kmem_cache *cachep = arg;
2306         struct array_cache *ac;
2307         int node = numa_mem_id();
2308         struct kmem_cache_node *n;
2309         LIST_HEAD(list);
2310
2311         check_irq_off();
2312         ac = cpu_cache_get(cachep);
2313         n = get_node(cachep, node);
2314         spin_lock(&n->list_lock);
2315         free_block(cachep, ac->entry, ac->avail, node, &list);
2316         spin_unlock(&n->list_lock);
2317         slabs_destroy(cachep, &list);
2318         ac->avail = 0;
2319 }
2320
2321 static void drain_cpu_caches(struct kmem_cache *cachep)
2322 {
2323         struct kmem_cache_node *n;
2324         int node;
2325
2326         on_each_cpu(do_drain, cachep, 1);
2327         check_irq_on();
2328         for_each_kmem_cache_node(cachep, node, n)
2329                 if (n->alien)
2330                         drain_alien_cache(cachep, n->alien);
2331
2332         for_each_kmem_cache_node(cachep, node, n)
2333                 drain_array(cachep, n, n->shared, 1, node);
2334 }
2335
2336 /*
2337  * Remove slabs from the list of free slabs.
2338  * Specify the number of slabs to drain in tofree.
2339  *
2340  * Returns the actual number of slabs released.
2341  */
2342 static int drain_freelist(struct kmem_cache *cache,
2343                         struct kmem_cache_node *n, int tofree)
2344 {
2345         struct list_head *p;
2346         int nr_freed;
2347         struct page *page;
2348
2349         nr_freed = 0;
2350         while (nr_freed < tofree && !list_empty(&n->slabs_free)) {
2351
2352                 spin_lock_irq(&n->list_lock);
2353                 p = n->slabs_free.prev;
2354                 if (p == &n->slabs_free) {
2355                         spin_unlock_irq(&n->list_lock);
2356                         goto out;
2357                 }
2358
2359                 page = list_entry(p, struct page, lru);
2360                 list_del(&page->lru);
2361                 /*
2362                  * Safe to drop the lock. The slab is no longer linked
2363                  * to the cache.
2364                  */
2365                 n->free_objects -= cache->num;
2366                 spin_unlock_irq(&n->list_lock);
2367                 slab_destroy(cache, page);
2368                 nr_freed++;
2369         }
2370 out:
2371         return nr_freed;
2372 }
2373
2374 int __kmem_cache_shrink(struct kmem_cache *cachep, bool deactivate)
2375 {
2376         int ret = 0;
2377         int node;
2378         struct kmem_cache_node *n;
2379
2380         drain_cpu_caches(cachep);
2381
2382         check_irq_on();
2383         for_each_kmem_cache_node(cachep, node, n) {
2384                 drain_freelist(cachep, n, slabs_tofree(cachep, n));
2385
2386                 ret += !list_empty(&n->slabs_full) ||
2387                         !list_empty(&n->slabs_partial);
2388         }
2389         return (ret ? 1 : 0);
2390 }
2391
2392 int __kmem_cache_shutdown(struct kmem_cache *cachep)
2393 {
2394         return __kmem_cache_shrink(cachep, false);
2395 }
2396
2397 void __kmem_cache_release(struct kmem_cache *cachep)
2398 {
2399         int i;
2400         struct kmem_cache_node *n;
2401
2402         free_percpu(cachep->cpu_cache);
2403
2404         /* NUMA: free the node structures */
2405         for_each_kmem_cache_node(cachep, i, n) {
2406                 kfree(n->shared);
2407                 free_alien_cache(n->alien);
2408                 kfree(n);
2409                 cachep->node[i] = NULL;
2410         }
2411 }
2412
2413 /*
2414  * Get the memory for a slab management obj.
2415  *
2416  * For a slab cache when the slab descriptor is off-slab, the
2417  * slab descriptor can't come from the same cache which is being created,
2418  * Because if it is the case, that means we defer the creation of
2419  * the kmalloc_{dma,}_cache of size sizeof(slab descriptor) to this point.
2420  * And we eventually call down to __kmem_cache_create(), which
2421  * in turn looks up in the kmalloc_{dma,}_caches for the disired-size one.
2422  * This is a "chicken-and-egg" problem.
2423  *
2424  * So the off-slab slab descriptor shall come from the kmalloc_{dma,}_caches,
2425  * which are all initialized during kmem_cache_init().
2426  */
2427 static void *alloc_slabmgmt(struct kmem_cache *cachep,
2428                                    struct page *page, int colour_off,
2429                                    gfp_t local_flags, int nodeid)
2430 {
2431         void *freelist;
2432         void *addr = page_address(page);
2433
2434         page->s_mem = addr + colour_off;
2435         page->active = 0;
2436
2437         if (OFF_SLAB(cachep)) {
2438                 /* Slab management obj is off-slab. */
2439                 freelist = kmem_cache_alloc_node(cachep->freelist_cache,
2440                                               local_flags, nodeid);
2441                 if (!freelist)
2442                         return NULL;
2443         } else {
2444                 /* We will use last bytes at the slab for freelist */
2445                 freelist = addr + (PAGE_SIZE << cachep->gfporder) -
2446                                 cachep->freelist_size;
2447         }
2448
2449         return freelist;
2450 }
2451
2452 static inline freelist_idx_t get_free_obj(struct page *page, unsigned int idx)
2453 {
2454         return ((freelist_idx_t *)page->freelist)[idx];
2455 }
2456
2457 static inline void set_free_obj(struct page *page,
2458                                         unsigned int idx, freelist_idx_t val)
2459 {
2460         ((freelist_idx_t *)(page->freelist))[idx] = val;
2461 }
2462
2463 static void cache_init_objs_debug(struct kmem_cache *cachep, struct page *page)
2464 {
2465 #if DEBUG
2466         int i;
2467
2468         for (i = 0; i < cachep->num; i++) {
2469                 void *objp = index_to_obj(cachep, page, i);
2470
2471                 if (cachep->flags & SLAB_STORE_USER)
2472                         *dbg_userword(cachep, objp) = NULL;
2473
2474                 if (cachep->flags & SLAB_RED_ZONE) {
2475                         *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2476                         *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2477                 }
2478                 /*
2479                  * Constructors are not allowed to allocate memory from the same
2480                  * cache which they are a constructor for.  Otherwise, deadlock.
2481                  * They must also be threaded.
2482                  */
2483                 if (cachep->ctor && !(cachep->flags & SLAB_POISON))
2484                         cachep->ctor(objp + obj_offset(cachep));
2485
2486                 if (cachep->flags & SLAB_RED_ZONE) {
2487                         if (*dbg_redzone2(cachep, objp) != RED_INACTIVE)
2488                                 slab_error(cachep, "constructor overwrote the"
2489                                            " end of an object");
2490                         if (*dbg_redzone1(cachep, objp) != RED_INACTIVE)
2491                                 slab_error(cachep, "constructor overwrote the"
2492                                            " start of an object");
2493                 }
2494                 /* need to poison the objs? */
2495                 if (cachep->flags & SLAB_POISON) {
2496                         poison_obj(cachep, objp, POISON_FREE);
2497                         slab_kernel_map(cachep, objp, 0, 0);
2498                 }
2499         }
2500 #endif
2501 }
2502
2503 static void cache_init_objs(struct kmem_cache *cachep,
2504                             struct page *page)
2505 {
2506         int i;
2507
2508         cache_init_objs_debug(cachep, page);
2509
2510         for (i = 0; i < cachep->num; i++) {
2511                 /* constructor could break poison info */
2512                 if (DEBUG == 0 && cachep->ctor)
2513                         cachep->ctor(index_to_obj(cachep, page, i));
2514
2515                 set_free_obj(page, i, i);
2516         }
2517 }
2518
2519 static void kmem_flagcheck(struct kmem_cache *cachep, gfp_t flags)
2520 {
2521         if (CONFIG_ZONE_DMA_FLAG) {
2522                 if (flags & GFP_DMA)
2523                         BUG_ON(!(cachep->allocflags & GFP_DMA));
2524                 else
2525                         BUG_ON(cachep->allocflags & GFP_DMA);
2526         }
2527 }
2528
2529 static void *slab_get_obj(struct kmem_cache *cachep, struct page *page)
2530 {
2531         void *objp;
2532
2533         objp = index_to_obj(cachep, page, get_free_obj(page, page->active));
2534         page->active++;
2535
2536 #if DEBUG
2537         if (cachep->flags & SLAB_STORE_USER)
2538                 set_store_user_dirty(cachep);
2539 #endif
2540
2541         return objp;
2542 }
2543
2544 static void slab_put_obj(struct kmem_cache *cachep,
2545                         struct page *page, void *objp)
2546 {
2547         unsigned int objnr = obj_to_index(cachep, page, objp);
2548 #if DEBUG
2549         unsigned int i;
2550
2551         /* Verify double free bug */
2552         for (i = page->active; i < cachep->num; i++) {
2553                 if (get_free_obj(page, i) == objnr) {
2554                         printk(KERN_ERR "slab: double free detected in cache "
2555                                         "'%s', objp %p\n", cachep->name, objp);
2556                         BUG();
2557                 }
2558         }
2559 #endif
2560         page->active--;
2561         set_free_obj(page, page->active, objnr);
2562 }
2563
2564 /*
2565  * Map pages beginning at addr to the given cache and slab. This is required
2566  * for the slab allocator to be able to lookup the cache and slab of a
2567  * virtual address for kfree, ksize, and slab debugging.
2568  */
2569 static void slab_map_pages(struct kmem_cache *cache, struct page *page,
2570                            void *freelist)
2571 {
2572         page->slab_cache = cache;
2573         page->freelist = freelist;
2574 }
2575
2576 /*
2577  * Grow (by 1) the number of slabs within a cache.  This is called by
2578  * kmem_cache_alloc() when there are no active objs left in a cache.
2579  */
2580 static int cache_grow(struct kmem_cache *cachep,
2581                 gfp_t flags, int nodeid, struct page *page)
2582 {
2583         void *freelist;
2584         size_t offset;
2585         gfp_t local_flags;
2586         struct kmem_cache_node *n;
2587
2588         /*
2589          * Be lazy and only check for valid flags here,  keeping it out of the
2590          * critical path in kmem_cache_alloc().
2591          */
2592         if (unlikely(flags & GFP_SLAB_BUG_MASK)) {
2593                 pr_emerg("gfp: %u\n", flags & GFP_SLAB_BUG_MASK);
2594                 BUG();
2595         }
2596         local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2597
2598         /* Take the node list lock to change the colour_next on this node */
2599         check_irq_off();
2600         n = get_node(cachep, nodeid);
2601         spin_lock(&n->list_lock);
2602
2603         /* Get colour for the slab, and cal the next value. */
2604         offset = n->colour_next;
2605         n->colour_next++;
2606         if (n->colour_next >= cachep->colour)
2607                 n->colour_next = 0;
2608         spin_unlock(&n->list_lock);
2609
2610         offset *= cachep->colour_off;
2611
2612         if (gfpflags_allow_blocking(local_flags))
2613                 local_irq_enable();
2614
2615         /*
2616          * The test for missing atomic flag is performed here, rather than
2617          * the more obvious place, simply to reduce the critical path length
2618          * in kmem_cache_alloc(). If a caller is seriously mis-behaving they
2619          * will eventually be caught here (where it matters).
2620          */
2621         kmem_flagcheck(cachep, flags);
2622
2623         /*
2624          * Get mem for the objs.  Attempt to allocate a physical page from
2625          * 'nodeid'.
2626          */
2627         if (!page)
2628                 page = kmem_getpages(cachep, local_flags, nodeid);
2629         if (!page)
2630                 goto failed;
2631
2632         /* Get slab management. */
2633         freelist = alloc_slabmgmt(cachep, page, offset,
2634                         local_flags & ~GFP_CONSTRAINT_MASK, nodeid);
2635         if (!freelist)
2636                 goto opps1;
2637
2638         slab_map_pages(cachep, page, freelist);
2639
2640         cache_init_objs(cachep, page);
2641
2642         if (gfpflags_allow_blocking(local_flags))
2643                 local_irq_disable();
2644         check_irq_off();
2645         spin_lock(&n->list_lock);
2646
2647         /* Make slab active. */
2648         list_add_tail(&page->lru, &(n->slabs_free));
2649         STATS_INC_GROWN(cachep);
2650         n->free_objects += cachep->num;
2651         spin_unlock(&n->list_lock);
2652         return 1;
2653 opps1:
2654         kmem_freepages(cachep, page);
2655 failed:
2656         if (gfpflags_allow_blocking(local_flags))
2657                 local_irq_disable();
2658         return 0;
2659 }
2660
2661 #if DEBUG
2662
2663 /*
2664  * Perform extra freeing checks:
2665  * - detect bad pointers.
2666  * - POISON/RED_ZONE checking
2667  */
2668 static void kfree_debugcheck(const void *objp)
2669 {
2670         if (!virt_addr_valid(objp)) {
2671                 printk(KERN_ERR "kfree_debugcheck: out of range ptr %lxh.\n",
2672                        (unsigned long)objp);
2673                 BUG();
2674         }
2675 }
2676
2677 static inline void verify_redzone_free(struct kmem_cache *cache, void *obj)
2678 {
2679         unsigned long long redzone1, redzone2;
2680
2681         redzone1 = *dbg_redzone1(cache, obj);
2682         redzone2 = *dbg_redzone2(cache, obj);
2683
2684         /*
2685          * Redzone is ok.
2686          */
2687         if (redzone1 == RED_ACTIVE && redzone2 == RED_ACTIVE)
2688                 return;
2689
2690         if (redzone1 == RED_INACTIVE && redzone2 == RED_INACTIVE)
2691                 slab_error(cache, "double free detected");
2692         else
2693                 slab_error(cache, "memory outside object was overwritten");
2694
2695         printk(KERN_ERR "%p: redzone 1:0x%llx, redzone 2:0x%llx.\n",
2696                         obj, redzone1, redzone2);
2697 }
2698
2699 static void *cache_free_debugcheck(struct kmem_cache *cachep, void *objp,
2700                                    unsigned long caller)
2701 {
2702         unsigned int objnr;
2703         struct page *page;
2704
2705         BUG_ON(virt_to_cache(objp) != cachep);
2706
2707         objp -= obj_offset(cachep);
2708         kfree_debugcheck(objp);
2709         page = virt_to_head_page(objp);
2710
2711         if (cachep->flags & SLAB_RED_ZONE) {
2712                 verify_redzone_free(cachep, objp);
2713                 *dbg_redzone1(cachep, objp) = RED_INACTIVE;
2714                 *dbg_redzone2(cachep, objp) = RED_INACTIVE;
2715         }
2716         if (cachep->flags & SLAB_STORE_USER) {
2717                 set_store_user_dirty(cachep);
2718                 *dbg_userword(cachep, objp) = (void *)caller;
2719         }
2720
2721         objnr = obj_to_index(cachep, page, objp);
2722
2723         BUG_ON(objnr >= cachep->num);
2724         BUG_ON(objp != index_to_obj(cachep, page, objnr));
2725
2726         if (cachep->flags & SLAB_POISON) {
2727                 poison_obj(cachep, objp, POISON_FREE);
2728                 slab_kernel_map(cachep, objp, 0, caller);
2729         }
2730         return objp;
2731 }
2732
2733 #else
2734 #define kfree_debugcheck(x) do { } while(0)
2735 #define cache_free_debugcheck(x,objp,z) (objp)
2736 #endif
2737
2738 static inline void fixup_slab_list(struct kmem_cache *cachep,
2739                                 struct kmem_cache_node *n, struct page *page)
2740 {
2741         /* move slabp to correct slabp list: */
2742         list_del(&page->lru);
2743         if (page->active == cachep->num)
2744                 list_add(&page->lru, &n->slabs_full);
2745         else
2746                 list_add(&page->lru, &n->slabs_partial);
2747 }
2748
2749 static struct page *get_first_slab(struct kmem_cache_node *n)
2750 {
2751         struct page *page;
2752
2753         page = list_first_entry_or_null(&n->slabs_partial,
2754                         struct page, lru);
2755         if (!page) {
2756                 n->free_touched = 1;
2757                 page = list_first_entry_or_null(&n->slabs_free,
2758                                 struct page, lru);
2759         }
2760
2761         return page;
2762 }
2763
2764 static void *cache_alloc_refill(struct kmem_cache *cachep, gfp_t flags,
2765                                                         bool force_refill)
2766 {
2767         int batchcount;
2768         struct kmem_cache_node *n;
2769         struct array_cache *ac;
2770         int node;
2771
2772         check_irq_off();
2773         node = numa_mem_id();
2774         if (unlikely(force_refill))
2775                 goto force_grow;
2776 retry:
2777         ac = cpu_cache_get(cachep);
2778         batchcount = ac->batchcount;
2779         if (!ac->touched && batchcount > BATCHREFILL_LIMIT) {
2780                 /*
2781                  * If there was little recent activity on this cache, then
2782                  * perform only a partial refill.  Otherwise we could generate
2783                  * refill bouncing.
2784                  */
2785                 batchcount = BATCHREFILL_LIMIT;
2786         }
2787         n = get_node(cachep, node);
2788
2789         BUG_ON(ac->avail > 0 || !n);
2790         spin_lock(&n->list_lock);
2791
2792         /* See if we can refill from the shared array */
2793         if (n->shared && transfer_objects(ac, n->shared, batchcount)) {
2794                 n->shared->touched = 1;
2795                 goto alloc_done;
2796         }
2797
2798         while (batchcount > 0) {
2799                 struct page *page;
2800                 /* Get slab alloc is to come from. */
2801                 page = get_first_slab(n);
2802                 if (!page)
2803                         goto must_grow;
2804
2805                 check_spinlock_acquired(cachep);
2806
2807                 /*
2808                  * The slab was either on partial or free list so
2809                  * there must be at least one object available for
2810                  * allocation.
2811                  */
2812                 BUG_ON(page->active >= cachep->num);
2813
2814                 while (page->active < cachep->num && batchcount--) {
2815                         STATS_INC_ALLOCED(cachep);
2816                         STATS_INC_ACTIVE(cachep);
2817                         STATS_SET_HIGH(cachep);
2818
2819                         ac_put_obj(cachep, ac, slab_get_obj(cachep, page));
2820                 }
2821
2822                 fixup_slab_list(cachep, n, page);
2823         }
2824
2825 must_grow:
2826         n->free_objects -= ac->avail;
2827 alloc_done:
2828         spin_unlock(&n->list_lock);
2829
2830         if (unlikely(!ac->avail)) {
2831                 int x;
2832 force_grow:
2833                 x = cache_grow(cachep, gfp_exact_node(flags), node, NULL);
2834
2835                 /* cache_grow can reenable interrupts, then ac could change. */
2836                 ac = cpu_cache_get(cachep);
2837                 node = numa_mem_id();
2838
2839                 /* no objects in sight? abort */
2840                 if (!x && (ac->avail == 0 || force_refill))
2841                         return NULL;
2842
2843                 if (!ac->avail)         /* objects refilled by interrupt? */
2844                         goto retry;
2845         }
2846         ac->touched = 1;
2847
2848         return ac_get_obj(cachep, ac, flags, force_refill);
2849 }
2850
2851 static inline void cache_alloc_debugcheck_before(struct kmem_cache *cachep,
2852                                                 gfp_t flags)
2853 {
2854         might_sleep_if(gfpflags_allow_blocking(flags));
2855 #if DEBUG
2856         kmem_flagcheck(cachep, flags);
2857 #endif
2858 }
2859
2860 #if DEBUG
2861 static void *cache_alloc_debugcheck_after(struct kmem_cache *cachep,
2862                                 gfp_t flags, void *objp, unsigned long caller)
2863 {
2864         if (!objp)
2865                 return objp;
2866         if (cachep->flags & SLAB_POISON) {
2867                 check_poison_obj(cachep, objp);
2868                 slab_kernel_map(cachep, objp, 1, 0);
2869                 poison_obj(cachep, objp, POISON_INUSE);
2870         }
2871         if (cachep->flags & SLAB_STORE_USER)
2872                 *dbg_userword(cachep, objp) = (void *)caller;
2873
2874         if (cachep->flags & SLAB_RED_ZONE) {
2875                 if (*dbg_redzone1(cachep, objp) != RED_INACTIVE ||
2876                                 *dbg_redzone2(cachep, objp) != RED_INACTIVE) {
2877                         slab_error(cachep, "double free, or memory outside"
2878                                                 " object was overwritten");
2879                         printk(KERN_ERR
2880                                 "%p: redzone 1:0x%llx, redzone 2:0x%llx\n",
2881                                 objp, *dbg_redzone1(cachep, objp),
2882                                 *dbg_redzone2(cachep, objp));
2883                 }
2884                 *dbg_redzone1(cachep, objp) = RED_ACTIVE;
2885                 *dbg_redzone2(cachep, objp) = RED_ACTIVE;
2886         }
2887
2888         objp += obj_offset(cachep);
2889         if (cachep->ctor && cachep->flags & SLAB_POISON)
2890                 cachep->ctor(objp);
2891         if (ARCH_SLAB_MINALIGN &&
2892             ((unsigned long)objp & (ARCH_SLAB_MINALIGN-1))) {
2893                 printk(KERN_ERR "0x%p: not aligned to ARCH_SLAB_MINALIGN=%d\n",
2894                        objp, (int)ARCH_SLAB_MINALIGN);
2895         }
2896         return objp;
2897 }
2898 #else
2899 #define cache_alloc_debugcheck_after(a,b,objp,d) (objp)
2900 #endif
2901
2902 static inline void *____cache_alloc(struct kmem_cache *cachep, gfp_t flags)
2903 {
2904         void *objp;
2905         struct array_cache *ac;
2906         bool force_refill = false;
2907
2908         check_irq_off();
2909
2910         ac = cpu_cache_get(cachep);
2911         if (likely(ac->avail)) {
2912                 ac->touched = 1;
2913                 objp = ac_get_obj(cachep, ac, flags, false);
2914
2915                 /*
2916                  * Allow for the possibility all avail objects are not allowed
2917                  * by the current flags
2918                  */
2919                 if (objp) {
2920                         STATS_INC_ALLOCHIT(cachep);
2921                         goto out;
2922                 }
2923                 force_refill = true;
2924         }
2925
2926         STATS_INC_ALLOCMISS(cachep);
2927         objp = cache_alloc_refill(cachep, flags, force_refill);
2928         /*
2929          * the 'ac' may be updated by cache_alloc_refill(),
2930          * and kmemleak_erase() requires its correct value.
2931          */
2932         ac = cpu_cache_get(cachep);
2933
2934 out:
2935         /*
2936          * To avoid a false negative, if an object that is in one of the
2937          * per-CPU caches is leaked, we need to make sure kmemleak doesn't
2938          * treat the array pointers as a reference to the object.
2939          */
2940         if (objp)
2941                 kmemleak_erase(&ac->entry[ac->avail]);
2942         return objp;
2943 }
2944
2945 #ifdef CONFIG_NUMA
2946 /*
2947  * Try allocating on another node if PFA_SPREAD_SLAB is a mempolicy is set.
2948  *
2949  * If we are in_interrupt, then process context, including cpusets and
2950  * mempolicy, may not apply and should not be used for allocation policy.
2951  */
2952 static void *alternate_node_alloc(struct kmem_cache *cachep, gfp_t flags)
2953 {
2954         int nid_alloc, nid_here;
2955
2956         if (in_interrupt() || (flags & __GFP_THISNODE))
2957                 return NULL;
2958         nid_alloc = nid_here = numa_mem_id();
2959         if (cpuset_do_slab_mem_spread() && (cachep->flags & SLAB_MEM_SPREAD))
2960                 nid_alloc = cpuset_slab_spread_node();
2961         else if (current->mempolicy)
2962                 nid_alloc = mempolicy_slab_node();
2963         if (nid_alloc != nid_here)
2964                 return ____cache_alloc_node(cachep, flags, nid_alloc);
2965         return NULL;
2966 }
2967
2968 /*
2969  * Fallback function if there was no memory available and no objects on a
2970  * certain node and fall back is permitted. First we scan all the
2971  * available node for available objects. If that fails then we
2972  * perform an allocation without specifying a node. This allows the page
2973  * allocator to do its reclaim / fallback magic. We then insert the
2974  * slab into the proper nodelist and then allocate from it.
2975  */
2976 static void *fallback_alloc(struct kmem_cache *cache, gfp_t flags)
2977 {
2978         struct zonelist *zonelist;
2979         gfp_t local_flags;
2980         struct zoneref *z;
2981         struct zone *zone;
2982         enum zone_type high_zoneidx = gfp_zone(flags);
2983         void *obj = NULL;
2984         int nid;
2985         unsigned int cpuset_mems_cookie;
2986
2987         if (flags & __GFP_THISNODE)
2988                 return NULL;
2989
2990         local_flags = flags & (GFP_CONSTRAINT_MASK|GFP_RECLAIM_MASK);
2991
2992 retry_cpuset:
2993         cpuset_mems_cookie = read_mems_allowed_begin();
2994         zonelist = node_zonelist(mempolicy_slab_node(), flags);
2995
2996 retry:
2997         /*
2998          * Look through allowed nodes for objects available
2999          * from existing per node queues.
3000          */
3001         for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) {
3002                 nid = zone_to_nid(zone);
3003
3004                 if (cpuset_zone_allowed(zone, flags) &&
3005                         get_node(cache, nid) &&
3006                         get_node(cache, nid)->free_objects) {
3007                                 obj = ____cache_alloc_node(cache,
3008                                         gfp_exact_node(flags), nid);
3009                                 if (obj)
3010                                         break;
3011                 }
3012         }
3013
3014         if (!obj) {
3015                 /*
3016                  * This allocation will be performed within the constraints
3017                  * of the current cpuset / memory policy requirements.
3018                  * We may trigger various forms of reclaim on the allowed
3019                  * set and go into memory reserves if necessary.
3020                  */
3021                 struct page *page;
3022
3023                 if (gfpflags_allow_blocking(local_flags))
3024                         local_irq_enable();
3025                 kmem_flagcheck(cache, flags);
3026                 page = kmem_getpages(cache, local_flags, numa_mem_id());
3027                 if (gfpflags_allow_blocking(local_flags))
3028                         local_irq_disable();
3029                 if (page) {
3030                         /*
3031                          * Insert into the appropriate per node queues
3032                          */
3033                         nid = page_to_nid(page);
3034                         if (cache_grow(cache, flags, nid, page)) {
3035                                 obj = ____cache_alloc_node(cache,
3036                                         gfp_exact_node(flags), nid);
3037                                 if (!obj)
3038                                         /*
3039                                          * Another processor may allocate the
3040                                          * objects in the slab since we are
3041                                          * not holding any locks.
3042                                          */
3043                                         goto retry;
3044                         } else {
3045                                 /* cache_grow already freed obj */
3046                                 obj = NULL;
3047                         }
3048                 }
3049         }
3050
3051         if (unlikely(!obj && read_mems_allowed_retry(cpuset_mems_cookie)))
3052                 goto retry_cpuset;
3053         return obj;
3054 }
3055
3056 /*
3057  * A interface to enable slab creation on nodeid
3058  */
3059 static void *____cache_alloc_node(struct kmem_cache *cachep, gfp_t flags,
3060                                 int nodeid)
3061 {
3062         struct page *page;
3063         struct kmem_cache_node *n;
3064         void *obj;
3065         int x;
3066
3067         VM_BUG_ON(nodeid < 0 || nodeid >= MAX_NUMNODES);
3068         n = get_node(cachep, nodeid);
3069         BUG_ON(!n);
3070
3071 retry:
3072         check_irq_off();
3073         spin_lock(&n->list_lock);
3074         page = get_first_slab(n);
3075         if (!page)
3076                 goto must_grow;
3077
3078         check_spinlock_acquired_node(cachep, nodeid);
3079
3080         STATS_INC_NODEALLOCS(cachep);
3081         STATS_INC_ACTIVE(cachep);
3082         STATS_SET_HIGH(cachep);
3083
3084         BUG_ON(page->active == cachep->num);
3085
3086         obj = slab_get_obj(cachep, page);
3087         n->free_objects--;
3088
3089         fixup_slab_list(cachep, n, page);
3090
3091         spin_unlock(&n->list_lock);
3092         goto done;
3093
3094 must_grow:
3095         spin_unlock(&n->list_lock);
3096         x = cache_grow(cachep, gfp_exact_node(flags), nodeid, NULL);
3097         if (x)
3098                 goto retry;
3099
3100         return fallback_alloc(cachep, flags);
3101
3102 done:
3103         return obj;
3104 }
3105
3106 static __always_inline void *
3107 slab_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid,
3108                    unsigned long caller)
3109 {
3110         unsigned long save_flags;
3111         void *ptr;
3112         int slab_node = numa_mem_id();
3113
3114         flags &= gfp_allowed_mask;
3115         cachep = slab_pre_alloc_hook(cachep, flags);
3116         if (unlikely(!cachep))
3117                 return NULL;
3118
3119         cache_alloc_debugcheck_before(cachep, flags);
3120         local_irq_save(save_flags);
3121
3122         if (nodeid == NUMA_NO_NODE)
3123                 nodeid = slab_node;
3124
3125         if (unlikely(!get_node(cachep, nodeid))) {
3126                 /* Node not bootstrapped yet */
3127                 ptr = fallback_alloc(cachep, flags);
3128                 goto out;
3129         }
3130
3131         if (nodeid == slab_node) {
3132                 /*
3133                  * Use the locally cached objects if possible.
3134                  * However ____cache_alloc does not allow fallback
3135                  * to other nodes. It may fail while we still have
3136                  * objects on other nodes available.
3137                  */
3138                 ptr = ____cache_alloc(cachep, flags);
3139                 if (ptr)
3140                         goto out;
3141         }
3142         /* ___cache_alloc_node can fall back to other nodes */
3143         ptr = ____cache_alloc_node(cachep, flags, nodeid);
3144   out:
3145         local_irq_restore(save_flags);
3146         ptr = cache_alloc_debugcheck_after(cachep, flags, ptr, caller);
3147
3148         if (unlikely(flags & __GFP_ZERO) && ptr)
3149                 memset(ptr, 0, cachep->object_size);
3150
3151         slab_post_alloc_hook(cachep, flags, 1, &ptr);
3152         return ptr;
3153 }
3154
3155 static __always_inline void *
3156 __do_cache_alloc(struct kmem_cache *cache, gfp_t flags)
3157 {
3158         void *objp;
3159
3160         if (current->mempolicy || cpuset_do_slab_mem_spread()) {
3161                 objp = alternate_node_alloc(cache, flags);
3162                 if (objp)
3163                         goto out;
3164         }
3165         objp = ____cache_alloc(cache, flags);
3166
3167         /*
3168          * We may just have run out of memory on the local node.
3169          * ____cache_alloc_node() knows how to locate memory on other nodes
3170          */
3171         if (!objp)
3172                 objp = ____cache_alloc_node(cache, flags, numa_mem_id());
3173
3174   out:
3175         return objp;
3176 }
3177 #else
3178
3179 static __always_inline void *
3180 __do_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3181 {
3182         return ____cache_alloc(cachep, flags);
3183 }
3184
3185 #endif /* CONFIG_NUMA */
3186
3187 static __always_inline void *
3188 slab_alloc(struct kmem_cache *cachep, gfp_t flags, unsigned long caller)
3189 {
3190         unsigned long save_flags;
3191         void *objp;
3192
3193         flags &= gfp_allowed_mask;
3194         cachep = slab_pre_alloc_hook(cachep, flags);
3195         if (unlikely(!cachep))
3196                 return NULL;
3197
3198         cache_alloc_debugcheck_before(cachep, flags);
3199         local_irq_save(save_flags);
3200         objp = __do_cache_alloc(cachep, flags);
3201         local_irq_restore(save_flags);
3202         objp = cache_alloc_debugcheck_after(cachep, flags, objp, caller);
3203         prefetchw(objp);
3204
3205         if (unlikely(flags & __GFP_ZERO) && objp)
3206                 memset(objp, 0, cachep->object_size);
3207
3208         slab_post_alloc_hook(cachep, flags, 1, &objp);
3209         return objp;
3210 }
3211
3212 /*
3213  * Caller needs to acquire correct kmem_cache_node's list_lock
3214  * @list: List of detached free slabs should be freed by caller
3215  */
3216 static void free_block(struct kmem_cache *cachep, void **objpp,
3217                         int nr_objects, int node, struct list_head *list)
3218 {
3219         int i;
3220         struct kmem_cache_node *n = get_node(cachep, node);
3221
3222         for (i = 0; i < nr_objects; i++) {
3223                 void *objp;
3224                 struct page *page;
3225
3226                 clear_obj_pfmemalloc(&objpp[i]);
3227                 objp = objpp[i];
3228
3229                 page = virt_to_head_page(objp);
3230                 list_del(&page->lru);
3231                 check_spinlock_acquired_node(cachep, node);
3232                 slab_put_obj(cachep, page, objp);
3233                 STATS_DEC_ACTIVE(cachep);
3234                 n->free_objects++;
3235
3236                 /* fixup slab chains */
3237                 if (page->active == 0) {
3238                         if (n->free_objects > n->free_limit) {
3239                                 n->free_objects -= cachep->num;
3240                                 list_add_tail(&page->lru, list);
3241                         } else {
3242                                 list_add(&page->lru, &n->slabs_free);
3243                         }
3244                 } else {
3245                         /* Unconditionally move a slab to the end of the
3246                          * partial list on free - maximum time for the
3247                          * other objects to be freed, too.
3248                          */
3249                         list_add_tail(&page->lru, &n->slabs_partial);
3250                 }
3251         }
3252 }
3253
3254 static void cache_flusharray(struct kmem_cache *cachep, struct array_cache *ac)
3255 {
3256         int batchcount;
3257         struct kmem_cache_node *n;
3258         int node = numa_mem_id();
3259         LIST_HEAD(list);
3260
3261         batchcount = ac->batchcount;
3262
3263         check_irq_off();
3264         n = get_node(cachep, node);
3265         spin_lock(&n->list_lock);
3266         if (n->shared) {
3267                 struct array_cache *shared_array = n->shared;
3268                 int max = shared_array->limit - shared_array->avail;
3269                 if (max) {
3270                         if (batchcount > max)
3271                                 batchcount = max;
3272                         memcpy(&(shared_array->entry[shared_array->avail]),
3273                                ac->entry, sizeof(void *) * batchcount);
3274                         shared_array->avail += batchcount;
3275                         goto free_done;
3276                 }
3277         }
3278
3279         free_block(cachep, ac->entry, batchcount, node, &list);
3280 free_done:
3281 #if STATS
3282         {
3283                 int i = 0;
3284                 struct page *page;
3285
3286                 list_for_each_entry(page, &n->slabs_free, lru) {
3287                         BUG_ON(page->active);
3288
3289                         i++;
3290                 }
3291                 STATS_SET_FREEABLE(cachep, i);
3292         }
3293 #endif
3294         spin_unlock(&n->list_lock);
3295         slabs_destroy(cachep, &list);
3296         ac->avail -= batchcount;
3297         memmove(ac->entry, &(ac->entry[batchcount]), sizeof(void *)*ac->avail);
3298 }
3299
3300 /*
3301  * Release an obj back to its cache. If the obj has a constructed state, it must
3302  * be in this state _before_ it is released.  Called with disabled ints.
3303  */
3304 static inline void __cache_free(struct kmem_cache *cachep, void *objp,
3305                                 unsigned long caller)
3306 {
3307         struct array_cache *ac = cpu_cache_get(cachep);
3308
3309         check_irq_off();
3310         kmemleak_free_recursive(objp, cachep->flags);
3311         objp = cache_free_debugcheck(cachep, objp, caller);
3312
3313         kmemcheck_slab_free(cachep, objp, cachep->object_size);
3314
3315         /*
3316          * Skip calling cache_free_alien() when the platform is not numa.
3317          * This will avoid cache misses that happen while accessing slabp (which
3318          * is per page memory  reference) to get nodeid. Instead use a global
3319          * variable to skip the call, which is mostly likely to be present in
3320          * the cache.
3321          */
3322         if (nr_online_nodes > 1 && cache_free_alien(cachep, objp))
3323                 return;
3324
3325         if (ac->avail < ac->limit) {
3326                 STATS_INC_FREEHIT(cachep);
3327         } else {
3328                 STATS_INC_FREEMISS(cachep);
3329                 cache_flusharray(cachep, ac);
3330         }
3331
3332         ac_put_obj(cachep, ac, objp);
3333 }
3334
3335 /**
3336  * kmem_cache_alloc - Allocate an object
3337  * @cachep: The cache to allocate from.
3338  * @flags: See kmalloc().
3339  *
3340  * Allocate an object from this cache.  The flags are only relevant
3341  * if the cache has no available objects.
3342  */
3343 void *kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
3344 {
3345         void *ret = slab_alloc(cachep, flags, _RET_IP_);
3346
3347         trace_kmem_cache_alloc(_RET_IP_, ret,
3348                                cachep->object_size, cachep->size, flags);
3349
3350         return ret;
3351 }
3352 EXPORT_SYMBOL(kmem_cache_alloc);
3353
3354 static __always_inline void
3355 cache_alloc_debugcheck_after_bulk(struct kmem_cache *s, gfp_t flags,
3356                                   size_t size, void **p, unsigned long caller)
3357 {
3358         size_t i;
3359
3360         for (i = 0; i < size; i++)
3361                 p[i] = cache_alloc_debugcheck_after(s, flags, p[i], caller);
3362 }
3363
3364 int kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size,
3365                           void **p)
3366 {
3367         size_t i;
3368
3369         s = slab_pre_alloc_hook(s, flags);
3370         if (!s)
3371                 return 0;
3372
3373         cache_alloc_debugcheck_before(s, flags);
3374
3375         local_irq_disable();
3376         for (i = 0; i < size; i++) {
3377                 void *objp = __do_cache_alloc(s, flags);
3378
3379                 if (unlikely(!objp))
3380                         goto error;
3381                 p[i] = objp;
3382         }
3383         local_irq_enable();
3384
3385         cache_alloc_debugcheck_after_bulk(s, flags, size, p, _RET_IP_);
3386
3387         /* Clear memory outside IRQ disabled section */
3388         if (unlikely(flags & __GFP_ZERO))
3389                 for (i = 0; i < size; i++)
3390                         memset(p[i], 0, s->object_size);
3391
3392         slab_post_alloc_hook(s, flags, size, p);
3393         /* FIXME: Trace call missing. Christoph would like a bulk variant */
3394         return size;
3395 error:
3396         local_irq_enable();
3397         cache_alloc_debugcheck_after_bulk(s, flags, i, p, _RET_IP_);
3398         slab_post_alloc_hook(s, flags, i, p);
3399         __kmem_cache_free_bulk(s, i, p);
3400         return 0;
3401 }
3402 EXPORT_SYMBOL(kmem_cache_alloc_bulk);
3403
3404 #ifdef CONFIG_TRACING
3405 void *
3406 kmem_cache_alloc_trace(struct kmem_cache *cachep, gfp_t flags, size_t size)
3407 {
3408         void *ret;
3409
3410         ret = slab_alloc(cachep, flags, _RET_IP_);
3411
3412         trace_kmalloc(_RET_IP_, ret,
3413                       size, cachep->size, flags);
3414         return ret;
3415 }
3416 EXPORT_SYMBOL(kmem_cache_alloc_trace);
3417 #endif
3418
3419 #ifdef CONFIG_NUMA
3420 /**
3421  * kmem_cache_alloc_node - Allocate an object on the specified node
3422  * @cachep: The cache to allocate from.
3423  * @flags: See kmalloc().
3424  * @nodeid: node number of the target node.
3425  *
3426  * Identical to kmem_cache_alloc but it will allocate memory on the given
3427  * node, which can improve the performance for cpu bound structures.
3428  *
3429  * Fallback to other node is possible if __GFP_THISNODE is not set.
3430  */
3431 void *kmem_cache_alloc_node(struct kmem_cache *cachep, gfp_t flags, int nodeid)
3432 {
3433         void *ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3434
3435         trace_kmem_cache_alloc_node(_RET_IP_, ret,
3436                                     cachep->object_size, cachep->size,
3437                                     flags, nodeid);
3438
3439         return ret;
3440 }
3441 EXPORT_SYMBOL(kmem_cache_alloc_node);
3442
3443 #ifdef CONFIG_TRACING
3444 void *kmem_cache_alloc_node_trace(struct kmem_cache *cachep,
3445                                   gfp_t flags,
3446                                   int nodeid,
3447                                   size_t size)
3448 {
3449         void *ret;
3450
3451         ret = slab_alloc_node(cachep, flags, nodeid, _RET_IP_);
3452
3453         trace_kmalloc_node(_RET_IP_, ret,
3454                            size, cachep->size,
3455                            flags, nodeid);
3456         return ret;
3457 }
3458 EXPORT_SYMBOL(kmem_cache_alloc_node_trace);
3459 #endif
3460
3461 static __always_inline void *
3462 __do_kmalloc_node(size_t size, gfp_t flags, int node, unsigned long caller)
3463 {
3464         struct kmem_cache *cachep;
3465
3466         cachep = kmalloc_slab(size, flags);
3467         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3468                 return cachep;
3469         return kmem_cache_alloc_node_trace(cachep, flags, node, size);
3470 }
3471
3472 void *__kmalloc_node(size_t size, gfp_t flags, int node)
3473 {
3474         return __do_kmalloc_node(size, flags, node, _RET_IP_);
3475 }
3476 EXPORT_SYMBOL(__kmalloc_node);
3477
3478 void *__kmalloc_node_track_caller(size_t size, gfp_t flags,
3479                 int node, unsigned long caller)
3480 {
3481         return __do_kmalloc_node(size, flags, node, caller);
3482 }
3483 EXPORT_SYMBOL(__kmalloc_node_track_caller);
3484 #endif /* CONFIG_NUMA */
3485
3486 /**
3487  * __do_kmalloc - allocate memory
3488  * @size: how many bytes of memory are required.
3489  * @flags: the type of memory to allocate (see kmalloc).
3490  * @caller: function caller for debug tracking of the caller
3491  */
3492 static __always_inline void *__do_kmalloc(size_t size, gfp_t flags,
3493                                           unsigned long caller)
3494 {
3495         struct kmem_cache *cachep;
3496         void *ret;
3497
3498         cachep = kmalloc_slab(size, flags);
3499         if (unlikely(ZERO_OR_NULL_PTR(cachep)))
3500                 return cachep;
3501         ret = slab_alloc(cachep, flags, caller);
3502
3503         trace_kmalloc(caller, ret,
3504                       size, cachep->size, flags);
3505
3506         return ret;
3507 }
3508
3509 void *__kmalloc(size_t size, gfp_t flags)
3510 {
3511         return __do_kmalloc(size, flags, _RET_IP_);
3512 }
3513 EXPORT_SYMBOL(__kmalloc);
3514
3515 void *__kmalloc_track_caller(size_t size, gfp_t flags, unsigned long caller)
3516 {
3517         return __do_kmalloc(size, flags, caller);
3518 }
3519 EXPORT_SYMBOL(__kmalloc_track_caller);
3520
3521 /**
3522  * kmem_cache_free - Deallocate an object
3523  * @cachep: The cache the allocation was from.
3524  * @objp: The previously allocated object.
3525  *
3526  * Free an object which was previously allocated from this
3527  * cache.
3528  */
3529 void kmem_cache_free(struct kmem_cache *cachep, void *objp)
3530 {
3531         unsigned long flags;
3532         cachep = cache_from_obj(cachep, objp);
3533         if (!cachep)
3534                 return;
3535
3536         local_irq_save(flags);
3537         debug_check_no_locks_freed(objp, cachep->object_size);
3538         if (!(cachep->flags & SLAB_DEBUG_OBJECTS))
3539                 debug_check_no_obj_freed(objp, cachep->object_size);
3540         __cache_free(cachep, objp, _RET_IP_);
3541         local_irq_restore(flags);
3542
3543         trace_kmem_cache_free(_RET_IP_, objp);
3544 }
3545 EXPORT_SYMBOL(kmem_cache_free);
3546
3547 void kmem_cache_free_bulk(struct kmem_cache *orig_s, size_t size, void **p)
3548 {
3549         struct kmem_cache *s;
3550         size_t i;
3551
3552         local_irq_disable();
3553         for (i = 0; i < size; i++) {
3554                 void *objp = p[i];
3555
3556                 if (!orig_s) /* called via kfree_bulk */
3557                         s = virt_to_cache(objp);
3558                 else
3559                         s = cache_from_obj(orig_s, objp);
3560
3561                 debug_check_no_locks_freed(objp, s->object_size);
3562                 if (!(s->flags & SLAB_DEBUG_OBJECTS))
3563                         debug_check_no_obj_freed(objp, s->object_size);
3564
3565                 __cache_free(s, objp, _RET_IP_);
3566         }
3567         local_irq_enable();
3568
3569         /* FIXME: add tracing */
3570 }
3571 EXPORT_SYMBOL(kmem_cache_free_bulk);
3572
3573 /**
3574  * kfree - free previously allocated memory
3575  * @objp: pointer returned by kmalloc.
3576  *
3577  * If @objp is NULL, no operation is performed.
3578  *
3579  * Don't free memory not originally allocated by kmalloc()
3580  * or you will run into trouble.
3581  */
3582 void kfree(const void *objp)
3583 {
3584         struct kmem_cache *c;
3585         unsigned long flags;
3586
3587         trace_kfree(_RET_IP_, objp);
3588
3589         if (unlikely(ZERO_OR_NULL_PTR(objp)))
3590                 return;
3591         local_irq_save(flags);
3592         kfree_debugcheck(objp);
3593         c = virt_to_cache(objp);
3594         debug_check_no_locks_freed(objp, c->object_size);
3595
3596         debug_check_no_obj_freed(objp, c->object_size);
3597         __cache_free(c, (void *)objp, _RET_IP_);
3598         local_irq_restore(flags);
3599 }
3600 EXPORT_SYMBOL(kfree);
3601
3602 /*
3603  * This initializes kmem_cache_node or resizes various caches for all nodes.
3604  */
3605 static int alloc_kmem_cache_node(struct kmem_cache *cachep, gfp_t gfp)
3606 {
3607         int node;
3608         struct kmem_cache_node *n;
3609         struct array_cache *new_shared;
3610         struct alien_cache **new_alien = NULL;
3611
3612         for_each_online_node(node) {
3613
3614                 if (use_alien_caches) {
3615                         new_alien = alloc_alien_cache(node, cachep->limit, gfp);
3616                         if (!new_alien)
3617                                 goto fail;
3618                 }
3619
3620                 new_shared = NULL;
3621                 if (cachep->shared) {
3622                         new_shared = alloc_arraycache(node,
3623                                 cachep->shared*cachep->batchcount,
3624                                         0xbaadf00d, gfp);
3625                         if (!new_shared) {
3626                                 free_alien_cache(new_alien);
3627                                 goto fail;
3628                         }
3629                 }
3630
3631                 n = get_node(cachep, node);
3632                 if (n) {
3633                         struct array_cache *shared = n->shared;
3634                         LIST_HEAD(list);
3635
3636                         spin_lock_irq(&n->list_lock);
3637
3638                         if (shared)
3639                                 free_block(cachep, shared->entry,
3640                                                 shared->avail, node, &list);
3641
3642                         n->shared = new_shared;
3643                         if (!n->alien) {
3644                                 n->alien = new_alien;
3645                                 new_alien = NULL;
3646                         }
3647                         n->free_limit = (1 + nr_cpus_node(node)) *
3648                                         cachep->batchcount + cachep->num;
3649                         spin_unlock_irq(&n->list_lock);
3650                         slabs_destroy(cachep, &list);
3651                         kfree(shared);
3652                         free_alien_cache(new_alien);
3653                         continue;
3654                 }
3655                 n = kmalloc_node(sizeof(struct kmem_cache_node), gfp, node);
3656                 if (!n) {
3657                         free_alien_cache(new_alien);
3658                         kfree(new_shared);
3659                         goto fail;
3660                 }
3661
3662                 kmem_cache_node_init(n);
3663                 n->next_reap = jiffies + REAPTIMEOUT_NODE +
3664                                 ((unsigned long)cachep) % REAPTIMEOUT_NODE;
3665                 n->shared = new_shared;
3666                 n->alien = new_alien;
3667                 n->free_limit = (1 + nr_cpus_node(node)) *
3668                                         cachep->batchcount + cachep->num;
3669                 cachep->node[node] = n;
3670         }
3671         return 0;
3672
3673 fail:
3674         if (!cachep->list.next) {
3675                 /* Cache is not active yet. Roll back what we did */
3676                 node--;
3677                 while (node >= 0) {
3678                         n = get_node(cachep, node);
3679                         if (n) {
3680                                 kfree(n->shared);
3681                                 free_alien_cache(n->alien);
3682                                 kfree(n);
3683                                 cachep->node[node] = NULL;
3684                         }
3685                         node--;
3686                 }
3687         }
3688         return -ENOMEM;
3689 }
3690
3691 /* Always called with the slab_mutex held */
3692 static int __do_tune_cpucache(struct kmem_cache *cachep, int limit,
3693                                 int batchcount, int shared, gfp_t gfp)
3694 {
3695         struct array_cache __percpu *cpu_cache, *prev;
3696         int cpu;
3697
3698         cpu_cache = alloc_kmem_cache_cpus(cachep, limit, batchcount);
3699         if (!cpu_cache)
3700                 return -ENOMEM;
3701
3702         prev = cachep->cpu_cache;
3703         cachep->cpu_cache = cpu_cache;
3704         kick_all_cpus_sync();
3705
3706         check_irq_on();
3707         cachep->batchcount = batchcount;
3708         cachep->limit = limit;
3709         cachep->shared = shared;
3710
3711         if (!prev)
3712                 goto alloc_node;
3713
3714         for_each_online_cpu(cpu) {
3715                 LIST_HEAD(list);
3716                 int node;
3717                 struct kmem_cache_node *n;
3718                 struct array_cache *ac = per_cpu_ptr(prev, cpu);
3719
3720                 node = cpu_to_mem(cpu);
3721                 n = get_node(cachep, node);
3722                 spin_lock_irq(&n->list_lock);
3723                 free_block(cachep, ac->entry, ac->avail, node, &list);
3724                 spin_unlock_irq(&n->list_lock);
3725                 slabs_destroy(cachep, &list);
3726         }
3727         free_percpu(prev);
3728
3729 alloc_node:
3730         return alloc_kmem_cache_node(cachep, gfp);
3731 }
3732
3733 static int do_tune_cpucache(struct kmem_cache *cachep, int limit,
3734                                 int batchcount, int shared, gfp_t gfp)
3735 {
3736         int ret;
3737         struct kmem_cache *c;
3738
3739         ret = __do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3740
3741         if (slab_state < FULL)
3742                 return ret;
3743
3744         if ((ret < 0) || !is_root_cache(cachep))
3745                 return ret;
3746
3747         lockdep_assert_held(&slab_mutex);
3748         for_each_memcg_cache(c, cachep) {
3749                 /* return value determined by the root cache only */
3750                 __do_tune_cpucache(c, limit, batchcount, shared, gfp);
3751         }
3752
3753         return ret;
3754 }
3755
3756 /* Called with slab_mutex held always */
3757 static int enable_cpucache(struct kmem_cache *cachep, gfp_t gfp)
3758 {
3759         int err;
3760         int limit = 0;
3761         int shared = 0;
3762         int batchcount = 0;
3763
3764         if (!is_root_cache(cachep)) {
3765                 struct kmem_cache *root = memcg_root_cache(cachep);
3766                 limit = root->limit;
3767                 shared = root->shared;
3768                 batchcount = root->batchcount;
3769         }
3770
3771         if (limit && shared && batchcount)
3772                 goto skip_setup;
3773         /*
3774          * The head array serves three purposes:
3775          * - create a LIFO ordering, i.e. return objects that are cache-warm
3776          * - reduce the number of spinlock operations.
3777          * - reduce the number of linked list operations on the slab and
3778          *   bufctl chains: array operations are cheaper.
3779          * The numbers are guessed, we should auto-tune as described by
3780          * Bonwick.
3781          */
3782         if (cachep->size > 131072)
3783                 limit = 1;
3784         else if (cachep->size > PAGE_SIZE)
3785                 limit = 8;
3786         else if (cachep->size > 1024)
3787                 limit = 24;
3788         else if (cachep->size > 256)
3789                 limit = 54;
3790         else
3791                 limit = 120;
3792
3793         /*
3794          * CPU bound tasks (e.g. network routing) can exhibit cpu bound
3795          * allocation behaviour: Most allocs on one cpu, most free operations
3796          * on another cpu. For these cases, an efficient object passing between
3797          * cpus is necessary. This is provided by a shared array. The array
3798          * replaces Bonwick's magazine layer.
3799          * On uniprocessor, it's functionally equivalent (but less efficient)
3800          * to a larger limit. Thus disabled by default.
3801          */
3802         shared = 0;
3803         if (cachep->size <= PAGE_SIZE && num_possible_cpus() > 1)
3804                 shared = 8;
3805
3806 #if DEBUG
3807         /*
3808          * With debugging enabled, large batchcount lead to excessively long
3809          * periods with disabled local interrupts. Limit the batchcount
3810          */
3811         if (limit > 32)
3812                 limit = 32;
3813 #endif
3814         batchcount = (limit + 1) / 2;
3815 skip_setup:
3816         err = do_tune_cpucache(cachep, limit, batchcount, shared, gfp);
3817         if (err)
3818                 printk(KERN_ERR "enable_cpucache failed for %s, error %d.\n",
3819                        cachep->name, -err);
3820         return err;
3821 }
3822
3823 /*
3824  * Drain an array if it contains any elements taking the node lock only if
3825  * necessary. Note that the node listlock also protects the array_cache
3826  * if drain_array() is used on the shared array.
3827  */
3828 static void drain_array(struct kmem_cache *cachep, struct kmem_cache_node *n,
3829                          struct array_cache *ac, int force, int node)
3830 {
3831         LIST_HEAD(list);
3832         int tofree;
3833
3834         if (!ac || !ac->avail)
3835                 return;
3836         if (ac->touched && !force) {
3837                 ac->touched = 0;
3838         } else {
3839                 spin_lock_irq(&n->list_lock);
3840                 if (ac->avail) {
3841                         tofree = force ? ac->avail : (ac->limit + 4) / 5;
3842                         if (tofree > ac->avail)
3843                                 tofree = (ac->avail + 1) / 2;
3844                         free_block(cachep, ac->entry, tofree, node, &list);
3845                         ac->avail -= tofree;
3846                         memmove(ac->entry, &(ac->entry[tofree]),
3847                                 sizeof(void *) * ac->avail);
3848                 }
3849                 spin_unlock_irq(&n->list_lock);
3850                 slabs_destroy(cachep, &list);
3851         }
3852 }
3853
3854 /**
3855  * cache_reap - Reclaim memory from caches.
3856  * @w: work descriptor
3857  *
3858  * Called from workqueue/eventd every few seconds.
3859  * Purpose:
3860  * - clear the per-cpu caches for this CPU.
3861  * - return freeable pages to the main free memory pool.
3862  *
3863  * If we cannot acquire the cache chain mutex then just give up - we'll try
3864  * again on the next iteration.
3865  */
3866 static void cache_reap(struct work_struct *w)
3867 {
3868         struct kmem_cache *searchp;
3869         struct kmem_cache_node *n;
3870         int node = numa_mem_id();
3871         struct delayed_work *work = to_delayed_work(w);
3872
3873         if (!mutex_trylock(&slab_mutex))
3874                 /* Give up. Setup the next iteration. */
3875                 goto out;
3876
3877         list_for_each_entry(searchp, &slab_caches, list) {
3878                 check_irq_on();
3879
3880                 /*
3881                  * We only take the node lock if absolutely necessary and we
3882                  * have established with reasonable certainty that
3883                  * we can do some work if the lock was obtained.
3884                  */
3885                 n = get_node(searchp, node);
3886
3887                 reap_alien(searchp, n);
3888
3889                 drain_array(searchp, n, cpu_cache_get(searchp), 0, node);
3890
3891                 /*
3892                  * These are racy checks but it does not matter
3893                  * if we skip one check or scan twice.
3894                  */
3895                 if (time_after(n->next_reap, jiffies))
3896                         goto next;
3897
3898                 n->next_reap = jiffies + REAPTIMEOUT_NODE;
3899
3900                 drain_array(searchp, n, n->shared, 0, node);
3901
3902                 if (n->free_touched)
3903                         n->free_touched = 0;
3904                 else {
3905                         int freed;
3906
3907                         freed = drain_freelist(searchp, n, (n->free_limit +
3908                                 5 * searchp->num - 1) / (5 * searchp->num));
3909                         STATS_ADD_REAPED(searchp, freed);
3910                 }
3911 next:
3912                 cond_resched();
3913         }
3914         check_irq_on();
3915         mutex_unlock(&slab_mutex);
3916         next_reap_node();
3917 out:
3918         /* Set up the next iteration */
3919         schedule_delayed_work(work, round_jiffies_relative(REAPTIMEOUT_AC));
3920 }
3921
3922 #ifdef CONFIG_SLABINFO
3923 void get_slabinfo(struct kmem_cache *cachep, struct slabinfo *sinfo)
3924 {
3925         struct page *page;
3926         unsigned long active_objs;
3927         unsigned long num_objs;
3928         unsigned long active_slabs = 0;
3929         unsigned long num_slabs, free_objects = 0, shared_avail = 0;
3930         const char *name;
3931         char *error = NULL;
3932         int node;
3933         struct kmem_cache_node *n;
3934
3935         active_objs = 0;
3936         num_slabs = 0;
3937         for_each_kmem_cache_node(cachep, node, n) {
3938
3939                 check_irq_on();
3940                 spin_lock_irq(&n->list_lock);
3941
3942                 list_for_each_entry(page, &n->slabs_full, lru) {
3943                         if (page->active != cachep->num && !error)
3944                                 error = "slabs_full accounting error";
3945                         active_objs += cachep->num;
3946                         active_slabs++;
3947                 }
3948                 list_for_each_entry(page, &n->slabs_partial, lru) {
3949                         if (page->active == cachep->num && !error)
3950                                 error = "slabs_partial accounting error";
3951                         if (!page->active && !error)
3952                                 error = "slabs_partial accounting error";
3953                         active_objs += page->active;
3954                         active_slabs++;
3955                 }
3956                 list_for_each_entry(page, &n->slabs_free, lru) {
3957                         if (page->active && !error)
3958                                 error = "slabs_free accounting error";
3959                         num_slabs++;
3960                 }
3961                 free_objects += n->free_objects;
3962                 if (n->shared)
3963                         shared_avail += n->shared->avail;
3964
3965                 spin_unlock_irq(&n->list_lock);
3966         }
3967         num_slabs += active_slabs;
3968         num_objs = num_slabs * cachep->num;
3969         if (num_objs - active_objs != free_objects && !error)
3970                 error = "free_objects accounting error";
3971
3972         name = cachep->name;
3973         if (error)
3974                 printk(KERN_ERR "slab: cache %s error: %s\n", name, error);
3975
3976         sinfo->active_objs = active_objs;
3977         sinfo->num_objs = num_objs;
3978         sinfo->active_slabs = active_slabs;
3979         sinfo->num_slabs = num_slabs;
3980         sinfo->shared_avail = shared_avail;
3981         sinfo->limit = cachep->limit;
3982         sinfo->batchcount = cachep->batchcount;
3983         sinfo->shared = cachep->shared;
3984         sinfo->objects_per_slab = cachep->num;
3985         sinfo->cache_order = cachep->gfporder;
3986 }
3987
3988 void slabinfo_show_stats(struct seq_file *m, struct kmem_cache *cachep)
3989 {
3990 #if STATS
3991         {                       /* node stats */
3992                 unsigned long high = cachep->high_mark;
3993                 unsigned long allocs = cachep->num_allocations;
3994                 unsigned long grown = cachep->grown;
3995                 unsigned long reaped = cachep->reaped;
3996                 unsigned long errors = cachep->errors;
3997                 unsigned long max_freeable = cachep->max_freeable;
3998                 unsigned long node_allocs = cachep->node_allocs;
3999                 unsigned long node_frees = cachep->node_frees;
4000                 unsigned long overflows = cachep->node_overflow;
4001
4002                 seq_printf(m, " : globalstat %7lu %6lu %5lu %4lu "
4003                            "%4lu %4lu %4lu %4lu %4lu",
4004                            allocs, high, grown,
4005                            reaped, errors, max_freeable, node_allocs,
4006                            node_frees, overflows);
4007         }
4008         /* cpu stats */
4009         {
4010                 unsigned long allochit = atomic_read(&cachep->allochit);
4011                 unsigned long allocmiss = atomic_read(&cachep->allocmiss);
4012                 unsigned long freehit = atomic_read(&cachep->freehit);
4013                 unsigned long freemiss = atomic_read(&cachep->freemiss);
4014
4015                 seq_printf(m, " : cpustat %6lu %6lu %6lu %6lu",
4016                            allochit, allocmiss, freehit, freemiss);
4017         }
4018 #endif
4019 }
4020
4021 #define MAX_SLABINFO_WRITE 128
4022 /**
4023  * slabinfo_write - Tuning for the slab allocator
4024  * @file: unused
4025  * @buffer: user buffer
4026  * @count: data length
4027  * @ppos: unused
4028  */
4029 ssize_t slabinfo_write(struct file *file, const char __user *buffer,
4030                        size_t count, loff_t *ppos)
4031 {
4032         char kbuf[MAX_SLABINFO_WRITE + 1], *tmp;
4033         int limit, batchcount, shared, res;
4034         struct kmem_cache *cachep;
4035
4036         if (count > MAX_SLABINFO_WRITE)
4037                 return -EINVAL;
4038         if (copy_from_user(&kbuf, buffer, count))
4039                 return -EFAULT;
4040         kbuf[MAX_SLABINFO_WRITE] = '\0';
4041
4042         tmp = strchr(kbuf, ' ');
4043         if (!tmp)
4044                 return -EINVAL;
4045         *tmp = '\0';
4046         tmp++;
4047         if (sscanf(tmp, " %d %d %d", &limit, &batchcount, &shared) != 3)
4048                 return -EINVAL;
4049
4050         /* Find the cache in the chain of caches. */
4051         mutex_lock(&slab_mutex);
4052         res = -EINVAL;
4053         list_for_each_entry(cachep, &slab_caches, list) {
4054                 if (!strcmp(cachep->name, kbuf)) {
4055                         if (limit < 1 || batchcount < 1 ||
4056                                         batchcount > limit || shared < 0) {
4057                                 res = 0;
4058                         } else {
4059                                 res = do_tune_cpucache(cachep, limit,
4060                                                        batchcount, shared,
4061                                                        GFP_KERNEL);
4062                         }
4063                         break;
4064                 }
4065         }
4066         mutex_unlock(&slab_mutex);
4067         if (res >= 0)
4068                 res = count;
4069         return res;
4070 }
4071
4072 #ifdef CONFIG_DEBUG_SLAB_LEAK
4073
4074 static inline int add_caller(unsigned long *n, unsigned long v)
4075 {
4076         unsigned long *p;
4077         int l;
4078         if (!v)
4079                 return 1;
4080         l = n[1];
4081         p = n + 2;
4082         while (l) {
4083                 int i = l/2;
4084                 unsigned long *q = p + 2 * i;
4085                 if (*q == v) {
4086                         q[1]++;
4087                         return 1;
4088                 }
4089                 if (*q > v) {
4090                         l = i;
4091                 } else {
4092                         p = q + 2;
4093                         l -= i + 1;
4094                 }
4095         }
4096         if (++n[1] == n[0])
4097                 return 0;
4098         memmove(p + 2, p, n[1] * 2 * sizeof(unsigned long) - ((void *)p - (void *)n));
4099         p[0] = v;
4100         p[1] = 1;
4101         return 1;
4102 }
4103
4104 static void handle_slab(unsigned long *n, struct kmem_cache *c,
4105                                                 struct page *page)
4106 {
4107         void *p;
4108         int i, j;
4109         unsigned long v;
4110
4111         if (n[0] == n[1])
4112                 return;
4113         for (i = 0, p = page->s_mem; i < c->num; i++, p += c->size) {
4114                 bool active = true;
4115
4116                 for (j = page->active; j < c->num; j++) {
4117                         if (get_free_obj(page, j) == i) {
4118                                 active = false;
4119                                 break;
4120                         }
4121                 }
4122
4123                 if (!active)
4124                         continue;
4125
4126                 /*
4127                  * probe_kernel_read() is used for DEBUG_PAGEALLOC. page table
4128                  * mapping is established when actual object allocation and
4129                  * we could mistakenly access the unmapped object in the cpu
4130                  * cache.
4131                  */
4132                 if (probe_kernel_read(&v, dbg_userword(c, p), sizeof(v)))
4133                         continue;
4134
4135                 if (!add_caller(n, v))
4136                         return;
4137         }
4138 }
4139
4140 static void show_symbol(struct seq_file *m, unsigned long address)
4141 {
4142 #ifdef CONFIG_KALLSYMS
4143         unsigned long offset, size;
4144         char modname[MODULE_NAME_LEN], name[KSYM_NAME_LEN];
4145
4146         if (lookup_symbol_attrs(address, &size, &offset, modname, name) == 0) {
4147                 seq_printf(m, "%s+%#lx/%#lx", name, offset, size);
4148                 if (modname[0])
4149                         seq_printf(m, " [%s]", modname);
4150                 return;
4151         }
4152 #endif
4153         seq_printf(m, "%p", (void *)address);
4154 }
4155
4156 static int leaks_show(struct seq_file *m, void *p)
4157 {
4158         struct kmem_cache *cachep = list_entry(p, struct kmem_cache, list);
4159         struct page *page;
4160         struct kmem_cache_node *n;
4161         const char *name;
4162         unsigned long *x = m->private;
4163         int node;
4164         int i;
4165
4166         if (!(cachep->flags & SLAB_STORE_USER))
4167                 return 0;
4168         if (!(cachep->flags & SLAB_RED_ZONE))
4169                 return 0;
4170
4171         /*
4172          * Set store_user_clean and start to grab stored user information
4173          * for all objects on this cache. If some alloc/free requests comes
4174          * during the processing, information would be wrong so restart
4175          * whole processing.
4176          */
4177         do {
4178                 set_store_user_clean(cachep);
4179                 drain_cpu_caches(cachep);
4180
4181                 x[1] = 0;
4182
4183                 for_each_kmem_cache_node(cachep, node, n) {
4184
4185                         check_irq_on();
4186                         spin_lock_irq(&n->list_lock);
4187
4188                         list_for_each_entry(page, &n->slabs_full, lru)
4189                                 handle_slab(x, cachep, page);
4190                         list_for_each_entry(page, &n->slabs_partial, lru)
4191                                 handle_slab(x, cachep, page);
4192                         spin_unlock_irq(&n->list_lock);
4193                 }
4194         } while (!is_store_user_clean(cachep));
4195
4196         name = cachep->name;
4197         if (x[0] == x[1]) {
4198                 /* Increase the buffer size */
4199                 mutex_unlock(&slab_mutex);
4200                 m->private = kzalloc(x[0] * 4 * sizeof(unsigned long), GFP_KERNEL);
4201                 if (!m->private) {
4202                         /* Too bad, we are really out */
4203                         m->private = x;
4204                         mutex_lock(&slab_mutex);
4205                         return -ENOMEM;
4206                 }
4207                 *(unsigned long *)m->private = x[0] * 2;
4208                 kfree(x);
4209                 mutex_lock(&slab_mutex);
4210                 /* Now make sure this entry will be retried */
4211                 m->count = m->size;
4212                 return 0;
4213         }
4214         for (i = 0; i < x[1]; i++) {
4215                 seq_printf(m, "%s: %lu ", name, x[2*i+3]);
4216                 show_symbol(m, x[2*i+2]);
4217                 seq_putc(m, '\n');
4218         }
4219
4220         return 0;
4221 }
4222
4223 static const struct seq_operations slabstats_op = {
4224         .start = slab_start,
4225         .next = slab_next,
4226         .stop = slab_stop,
4227         .show = leaks_show,
4228 };
4229
4230 static int slabstats_open(struct inode *inode, struct file *file)
4231 {
4232         unsigned long *n;
4233
4234         n = __seq_open_private(file, &slabstats_op, PAGE_SIZE);
4235         if (!n)
4236                 return -ENOMEM;
4237
4238         *n = PAGE_SIZE / (2 * sizeof(unsigned long));
4239
4240         return 0;
4241 }
4242
4243 static const struct file_operations proc_slabstats_operations = {
4244         .open           = slabstats_open,
4245         .read           = seq_read,
4246         .llseek         = seq_lseek,
4247         .release        = seq_release_private,
4248 };
4249 #endif
4250
4251 static int __init slab_proc_init(void)
4252 {
4253 #ifdef CONFIG_DEBUG_SLAB_LEAK
4254         proc_create("slab_allocators", 0, NULL, &proc_slabstats_operations);
4255 #endif
4256         return 0;
4257 }
4258 module_init(slab_proc_init);
4259 #endif
4260
4261 /**
4262  * ksize - get the actual amount of memory allocated for a given object
4263  * @objp: Pointer to the object
4264  *
4265  * kmalloc may internally round up allocations and return more memory
4266  * than requested. ksize() can be used to determine the actual amount of
4267  * memory allocated. The caller may use this additional memory, even though
4268  * a smaller amount of memory was initially specified with the kmalloc call.
4269  * The caller must guarantee that objp points to a valid object previously
4270  * allocated with either kmalloc() or kmem_cache_alloc(). The object
4271  * must not be freed during the duration of the call.
4272  */
4273 size_t ksize(const void *objp)
4274 {
4275         BUG_ON(!objp);
4276         if (unlikely(objp == ZERO_SIZE_PTR))
4277                 return 0;
4278
4279         return virt_to_cache(objp)->object_size;
4280 }
4281 EXPORT_SYMBOL(ksize);