~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/mm/slab.c

Version: ~ [ linux-5.8 ] ~ [ linux-5.7.12 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.55 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.136 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.191 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.232 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.232 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp