GNU Linux-libre 4.14.259-gnu1
[releases.git] / mm / zsmalloc.c
1 /*
2  * zsmalloc memory allocator
3  *
4  * Copyright (C) 2011  Nitin Gupta
5  * Copyright (C) 2012, 2013 Minchan Kim
6  *
7  * This code is released using a dual license strategy: BSD/GPL
8  * You can choose the license that better fits your requirements.
9  *
10  * Released under the terms of 3-clause BSD License
11  * Released under the terms of GNU General Public License Version 2.0
12  */
13
14 /*
15  * Following is how we use various fields and flags of underlying
16  * struct page(s) to form a zspage.
17  *
18  * Usage of struct page fields:
19  *      page->private: points to zspage
20  *      page->freelist(index): links together all component pages of a zspage
21  *              For the huge page, this is always 0, so we use this field
22  *              to store handle.
23  *      page->units: first object offset in a subpage of zspage
24  *
25  * Usage of struct page flags:
26  *      PG_private: identifies the first component page
27  *      PG_owner_priv_1: identifies the huge component page
28  *
29  */
30
31 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
32
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/sched.h>
36 #include <linux/magic.h>
37 #include <linux/bitops.h>
38 #include <linux/errno.h>
39 #include <linux/highmem.h>
40 #include <linux/string.h>
41 #include <linux/slab.h>
42 #include <asm/tlbflush.h>
43 #include <asm/pgtable.h>
44 #include <linux/cpumask.h>
45 #include <linux/cpu.h>
46 #include <linux/vmalloc.h>
47 #include <linux/preempt.h>
48 #include <linux/spinlock.h>
49 #include <linux/types.h>
50 #include <linux/debugfs.h>
51 #include <linux/zsmalloc.h>
52 #include <linux/zpool.h>
53 #include <linux/mount.h>
54 #include <linux/migrate.h>
55 #include <linux/wait.h>
56 #include <linux/pagemap.h>
57
58 #define ZSPAGE_MAGIC    0x58
59
60 /*
61  * This must be power of 2 and greater than of equal to sizeof(link_free).
62  * These two conditions ensure that any 'struct link_free' itself doesn't
63  * span more than 1 page which avoids complex case of mapping 2 pages simply
64  * to restore link_free pointer values.
65  */
66 #define ZS_ALIGN                8
67
68 /*
69  * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
70  * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
71  */
72 #define ZS_MAX_ZSPAGE_ORDER 2
73 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
74
75 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
76
77 /*
78  * Object location (<PFN>, <obj_idx>) is encoded as
79  * as single (unsigned long) handle value.
80  *
81  * Note that object index <obj_idx> starts from 0.
82  *
83  * This is made more complicated by various memory models and PAE.
84  */
85
86 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
87 #ifdef MAX_PHYSMEM_BITS
88 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
89 #else
90 /*
91  * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
92  * be PAGE_SHIFT
93  */
94 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
95 #endif
96 #endif
97
98 #define _PFN_BITS               (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
99
100 /*
101  * Memory for allocating for handle keeps object position by
102  * encoding <page, obj_idx> and the encoded value has a room
103  * in least bit(ie, look at obj_to_location).
104  * We use the bit to synchronize between object access by
105  * user and migration.
106  */
107 #define HANDLE_PIN_BIT  0
108
109 /*
110  * Head in allocated object should have OBJ_ALLOCATED_TAG
111  * to identify the object was allocated or not.
112  * It's okay to add the status bit in the least bit because
113  * header keeps handle which is 4byte-aligned address so we
114  * have room for two bit at least.
115  */
116 #define OBJ_ALLOCATED_TAG 1
117 #define OBJ_TAG_BITS 1
118 #define OBJ_INDEX_BITS  (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
119 #define OBJ_INDEX_MASK  ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
120
121 #define FULLNESS_BITS   2
122 #define CLASS_BITS      8
123 #define ISOLATED_BITS   3
124 #define MAGIC_VAL_BITS  8
125
126 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
127 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
128 #define ZS_MIN_ALLOC_SIZE \
129         MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
130 /* each chunk includes extra space to keep handle */
131 #define ZS_MAX_ALLOC_SIZE       PAGE_SIZE
132
133 /*
134  * On systems with 4K page size, this gives 255 size classes! There is a
135  * trader-off here:
136  *  - Large number of size classes is potentially wasteful as free page are
137  *    spread across these classes
138  *  - Small number of size classes causes large internal fragmentation
139  *  - Probably its better to use specific size classes (empirically
140  *    determined). NOTE: all those class sizes must be set as multiple of
141  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
142  *
143  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
144  *  (reason above)
145  */
146 #define ZS_SIZE_CLASS_DELTA     (PAGE_SIZE >> CLASS_BITS)
147 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
148                                       ZS_SIZE_CLASS_DELTA) + 1)
149
150 enum fullness_group {
151         ZS_EMPTY,
152         ZS_ALMOST_EMPTY,
153         ZS_ALMOST_FULL,
154         ZS_FULL,
155         NR_ZS_FULLNESS,
156 };
157
158 enum zs_stat_type {
159         CLASS_EMPTY,
160         CLASS_ALMOST_EMPTY,
161         CLASS_ALMOST_FULL,
162         CLASS_FULL,
163         OBJ_ALLOCATED,
164         OBJ_USED,
165         NR_ZS_STAT_TYPE,
166 };
167
168 struct zs_size_stat {
169         unsigned long objs[NR_ZS_STAT_TYPE];
170 };
171
172 #ifdef CONFIG_ZSMALLOC_STAT
173 static struct dentry *zs_stat_root;
174 #endif
175
176 #ifdef CONFIG_COMPACTION
177 static struct vfsmount *zsmalloc_mnt;
178 #endif
179
180 /*
181  * We assign a page to ZS_ALMOST_EMPTY fullness group when:
182  *      n <= N / f, where
183  * n = number of allocated objects
184  * N = total number of objects zspage can store
185  * f = fullness_threshold_frac
186  *
187  * Similarly, we assign zspage to:
188  *      ZS_ALMOST_FULL  when n > N / f
189  *      ZS_EMPTY        when n == 0
190  *      ZS_FULL         when n == N
191  *
192  * (see: fix_fullness_group())
193  */
194 static const int fullness_threshold_frac = 4;
195
196 struct size_class {
197         spinlock_t lock;
198         struct list_head fullness_list[NR_ZS_FULLNESS];
199         /*
200          * Size of objects stored in this class. Must be multiple
201          * of ZS_ALIGN.
202          */
203         int size;
204         int objs_per_zspage;
205         /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
206         int pages_per_zspage;
207
208         unsigned int index;
209         struct zs_size_stat stats;
210 };
211
212 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
213 static void SetPageHugeObject(struct page *page)
214 {
215         SetPageOwnerPriv1(page);
216 }
217
218 static void ClearPageHugeObject(struct page *page)
219 {
220         ClearPageOwnerPriv1(page);
221 }
222
223 static int PageHugeObject(struct page *page)
224 {
225         return PageOwnerPriv1(page);
226 }
227
228 /*
229  * Placed within free objects to form a singly linked list.
230  * For every zspage, zspage->freeobj gives head of this list.
231  *
232  * This must be power of 2 and less than or equal to ZS_ALIGN
233  */
234 struct link_free {
235         union {
236                 /*
237                  * Free object index;
238                  * It's valid for non-allocated object
239                  */
240                 unsigned long next;
241                 /*
242                  * Handle of allocated object.
243                  */
244                 unsigned long handle;
245         };
246 };
247
248 struct zs_pool {
249         const char *name;
250
251         struct size_class *size_class[ZS_SIZE_CLASSES];
252         struct kmem_cache *handle_cachep;
253         struct kmem_cache *zspage_cachep;
254
255         atomic_long_t pages_allocated;
256
257         struct zs_pool_stats stats;
258
259         /* Compact classes */
260         struct shrinker shrinker;
261         /*
262          * To signify that register_shrinker() was successful
263          * and unregister_shrinker() will not Oops.
264          */
265         bool shrinker_enabled;
266 #ifdef CONFIG_ZSMALLOC_STAT
267         struct dentry *stat_dentry;
268 #endif
269 #ifdef CONFIG_COMPACTION
270         struct inode *inode;
271         struct work_struct free_work;
272         /* A wait queue for when migration races with async_free_zspage() */
273         struct wait_queue_head migration_wait;
274         atomic_long_t isolated_pages;
275         bool destroying;
276 #endif
277 };
278
279 struct zspage {
280         struct {
281                 unsigned int fullness:FULLNESS_BITS;
282                 unsigned int class:CLASS_BITS + 1;
283                 unsigned int isolated:ISOLATED_BITS;
284                 unsigned int magic:MAGIC_VAL_BITS;
285         };
286         unsigned int inuse;
287         unsigned int freeobj;
288         struct page *first_page;
289         struct list_head list; /* fullness list */
290 #ifdef CONFIG_COMPACTION
291         rwlock_t lock;
292 #endif
293 };
294
295 struct mapping_area {
296 #ifdef CONFIG_PGTABLE_MAPPING
297         struct vm_struct *vm; /* vm area for mapping object that span pages */
298 #else
299         char *vm_buf; /* copy buffer for objects that span pages */
300 #endif
301         char *vm_addr; /* address of kmap_atomic()'ed pages */
302         enum zs_mapmode vm_mm; /* mapping mode */
303 };
304
305 #ifdef CONFIG_COMPACTION
306 static int zs_register_migration(struct zs_pool *pool);
307 static void zs_unregister_migration(struct zs_pool *pool);
308 static void migrate_lock_init(struct zspage *zspage);
309 static void migrate_read_lock(struct zspage *zspage);
310 static void migrate_read_unlock(struct zspage *zspage);
311 static void kick_deferred_free(struct zs_pool *pool);
312 static void init_deferred_free(struct zs_pool *pool);
313 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
314 #else
315 static int zsmalloc_mount(void) { return 0; }
316 static void zsmalloc_unmount(void) {}
317 static int zs_register_migration(struct zs_pool *pool) { return 0; }
318 static void zs_unregister_migration(struct zs_pool *pool) {}
319 static void migrate_lock_init(struct zspage *zspage) {}
320 static void migrate_read_lock(struct zspage *zspage) {}
321 static void migrate_read_unlock(struct zspage *zspage) {}
322 static void kick_deferred_free(struct zs_pool *pool) {}
323 static void init_deferred_free(struct zs_pool *pool) {}
324 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
325 #endif
326
327 static int create_cache(struct zs_pool *pool)
328 {
329         pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
330                                         0, 0, NULL);
331         if (!pool->handle_cachep)
332                 return 1;
333
334         pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
335                                         0, 0, NULL);
336         if (!pool->zspage_cachep) {
337                 kmem_cache_destroy(pool->handle_cachep);
338                 pool->handle_cachep = NULL;
339                 return 1;
340         }
341
342         return 0;
343 }
344
345 static void destroy_cache(struct zs_pool *pool)
346 {
347         kmem_cache_destroy(pool->handle_cachep);
348         kmem_cache_destroy(pool->zspage_cachep);
349 }
350
351 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
352 {
353         return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
354                         gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
355 }
356
357 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
358 {
359         kmem_cache_free(pool->handle_cachep, (void *)handle);
360 }
361
362 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
363 {
364         return kmem_cache_alloc(pool->zspage_cachep,
365                         flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
366 }
367
368 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
369 {
370         kmem_cache_free(pool->zspage_cachep, zspage);
371 }
372
373 static void record_obj(unsigned long handle, unsigned long obj)
374 {
375         /*
376          * lsb of @obj represents handle lock while other bits
377          * represent object value the handle is pointing so
378          * updating shouldn't do store tearing.
379          */
380         WRITE_ONCE(*(unsigned long *)handle, obj);
381 }
382
383 /* zpool driver */
384
385 #ifdef CONFIG_ZPOOL
386
387 static void *zs_zpool_create(const char *name, gfp_t gfp,
388                              const struct zpool_ops *zpool_ops,
389                              struct zpool *zpool)
390 {
391         /*
392          * Ignore global gfp flags: zs_malloc() may be invoked from
393          * different contexts and its caller must provide a valid
394          * gfp mask.
395          */
396         return zs_create_pool(name);
397 }
398
399 static void zs_zpool_destroy(void *pool)
400 {
401         zs_destroy_pool(pool);
402 }
403
404 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
405                         unsigned long *handle)
406 {
407         *handle = zs_malloc(pool, size, gfp);
408         return *handle ? 0 : -1;
409 }
410 static void zs_zpool_free(void *pool, unsigned long handle)
411 {
412         zs_free(pool, handle);
413 }
414
415 static int zs_zpool_shrink(void *pool, unsigned int pages,
416                         unsigned int *reclaimed)
417 {
418         return -EINVAL;
419 }
420
421 static void *zs_zpool_map(void *pool, unsigned long handle,
422                         enum zpool_mapmode mm)
423 {
424         enum zs_mapmode zs_mm;
425
426         switch (mm) {
427         case ZPOOL_MM_RO:
428                 zs_mm = ZS_MM_RO;
429                 break;
430         case ZPOOL_MM_WO:
431                 zs_mm = ZS_MM_WO;
432                 break;
433         case ZPOOL_MM_RW: /* fallthru */
434         default:
435                 zs_mm = ZS_MM_RW;
436                 break;
437         }
438
439         return zs_map_object(pool, handle, zs_mm);
440 }
441 static void zs_zpool_unmap(void *pool, unsigned long handle)
442 {
443         zs_unmap_object(pool, handle);
444 }
445
446 static u64 zs_zpool_total_size(void *pool)
447 {
448         return zs_get_total_pages(pool) << PAGE_SHIFT;
449 }
450
451 static struct zpool_driver zs_zpool_driver = {
452         .type =         "zsmalloc",
453         .owner =        THIS_MODULE,
454         .create =       zs_zpool_create,
455         .destroy =      zs_zpool_destroy,
456         .malloc =       zs_zpool_malloc,
457         .free =         zs_zpool_free,
458         .shrink =       zs_zpool_shrink,
459         .map =          zs_zpool_map,
460         .unmap =        zs_zpool_unmap,
461         .total_size =   zs_zpool_total_size,
462 };
463
464 MODULE_ALIAS("zpool-zsmalloc");
465 #endif /* CONFIG_ZPOOL */
466
467 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
468 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
469
470 static bool is_zspage_isolated(struct zspage *zspage)
471 {
472         return zspage->isolated;
473 }
474
475 static __maybe_unused int is_first_page(struct page *page)
476 {
477         return PagePrivate(page);
478 }
479
480 /* Protected by class->lock */
481 static inline int get_zspage_inuse(struct zspage *zspage)
482 {
483         return zspage->inuse;
484 }
485
486 static inline void set_zspage_inuse(struct zspage *zspage, int val)
487 {
488         zspage->inuse = val;
489 }
490
491 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
492 {
493         zspage->inuse += val;
494 }
495
496 static inline struct page *get_first_page(struct zspage *zspage)
497 {
498         struct page *first_page = zspage->first_page;
499
500         VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
501         return first_page;
502 }
503
504 static inline int get_first_obj_offset(struct page *page)
505 {
506         return page->units;
507 }
508
509 static inline void set_first_obj_offset(struct page *page, int offset)
510 {
511         page->units = offset;
512 }
513
514 static inline unsigned int get_freeobj(struct zspage *zspage)
515 {
516         return zspage->freeobj;
517 }
518
519 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
520 {
521         zspage->freeobj = obj;
522 }
523
524 static void get_zspage_mapping(struct zspage *zspage,
525                                 unsigned int *class_idx,
526                                 enum fullness_group *fullness)
527 {
528         BUG_ON(zspage->magic != ZSPAGE_MAGIC);
529
530         *fullness = zspage->fullness;
531         *class_idx = zspage->class;
532 }
533
534 static void set_zspage_mapping(struct zspage *zspage,
535                                 unsigned int class_idx,
536                                 enum fullness_group fullness)
537 {
538         zspage->class = class_idx;
539         zspage->fullness = fullness;
540 }
541
542 /*
543  * zsmalloc divides the pool into various size classes where each
544  * class maintains a list of zspages where each zspage is divided
545  * into equal sized chunks. Each allocation falls into one of these
546  * classes depending on its size. This function returns index of the
547  * size class which has chunk size big enough to hold the give size.
548  */
549 static int get_size_class_index(int size)
550 {
551         int idx = 0;
552
553         if (likely(size > ZS_MIN_ALLOC_SIZE))
554                 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
555                                 ZS_SIZE_CLASS_DELTA);
556
557         return min_t(int, ZS_SIZE_CLASSES - 1, idx);
558 }
559
560 /* type can be of enum type zs_stat_type or fullness_group */
561 static inline void zs_stat_inc(struct size_class *class,
562                                 int type, unsigned long cnt)
563 {
564         class->stats.objs[type] += cnt;
565 }
566
567 /* type can be of enum type zs_stat_type or fullness_group */
568 static inline void zs_stat_dec(struct size_class *class,
569                                 int type, unsigned long cnt)
570 {
571         class->stats.objs[type] -= cnt;
572 }
573
574 /* type can be of enum type zs_stat_type or fullness_group */
575 static inline unsigned long zs_stat_get(struct size_class *class,
576                                 int type)
577 {
578         return class->stats.objs[type];
579 }
580
581 #ifdef CONFIG_ZSMALLOC_STAT
582
583 static void __init zs_stat_init(void)
584 {
585         if (!debugfs_initialized()) {
586                 pr_warn("debugfs not available, stat dir not created\n");
587                 return;
588         }
589
590         zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
591         if (!zs_stat_root)
592                 pr_warn("debugfs 'zsmalloc' stat dir creation failed\n");
593 }
594
595 static void __exit zs_stat_exit(void)
596 {
597         debugfs_remove_recursive(zs_stat_root);
598 }
599
600 static unsigned long zs_can_compact(struct size_class *class);
601
602 static int zs_stats_size_show(struct seq_file *s, void *v)
603 {
604         int i;
605         struct zs_pool *pool = s->private;
606         struct size_class *class;
607         int objs_per_zspage;
608         unsigned long class_almost_full, class_almost_empty;
609         unsigned long obj_allocated, obj_used, pages_used, freeable;
610         unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
611         unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
612         unsigned long total_freeable = 0;
613
614         seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
615                         "class", "size", "almost_full", "almost_empty",
616                         "obj_allocated", "obj_used", "pages_used",
617                         "pages_per_zspage", "freeable");
618
619         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
620                 class = pool->size_class[i];
621
622                 if (class->index != i)
623                         continue;
624
625                 spin_lock(&class->lock);
626                 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
627                 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
628                 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
629                 obj_used = zs_stat_get(class, OBJ_USED);
630                 freeable = zs_can_compact(class);
631                 spin_unlock(&class->lock);
632
633                 objs_per_zspage = class->objs_per_zspage;
634                 pages_used = obj_allocated / objs_per_zspage *
635                                 class->pages_per_zspage;
636
637                 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
638                                 " %10lu %10lu %16d %8lu\n",
639                         i, class->size, class_almost_full, class_almost_empty,
640                         obj_allocated, obj_used, pages_used,
641                         class->pages_per_zspage, freeable);
642
643                 total_class_almost_full += class_almost_full;
644                 total_class_almost_empty += class_almost_empty;
645                 total_objs += obj_allocated;
646                 total_used_objs += obj_used;
647                 total_pages += pages_used;
648                 total_freeable += freeable;
649         }
650
651         seq_puts(s, "\n");
652         seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
653                         "Total", "", total_class_almost_full,
654                         total_class_almost_empty, total_objs,
655                         total_used_objs, total_pages, "", total_freeable);
656
657         return 0;
658 }
659
660 static int zs_stats_size_open(struct inode *inode, struct file *file)
661 {
662         return single_open(file, zs_stats_size_show, inode->i_private);
663 }
664
665 static const struct file_operations zs_stat_size_ops = {
666         .open           = zs_stats_size_open,
667         .read           = seq_read,
668         .llseek         = seq_lseek,
669         .release        = single_release,
670 };
671
672 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
673 {
674         struct dentry *entry;
675
676         if (!zs_stat_root) {
677                 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
678                 return;
679         }
680
681         entry = debugfs_create_dir(name, zs_stat_root);
682         if (!entry) {
683                 pr_warn("debugfs dir <%s> creation failed\n", name);
684                 return;
685         }
686         pool->stat_dentry = entry;
687
688         entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
689                         pool->stat_dentry, pool, &zs_stat_size_ops);
690         if (!entry) {
691                 pr_warn("%s: debugfs file entry <%s> creation failed\n",
692                                 name, "classes");
693                 debugfs_remove_recursive(pool->stat_dentry);
694                 pool->stat_dentry = NULL;
695         }
696 }
697
698 static void zs_pool_stat_destroy(struct zs_pool *pool)
699 {
700         debugfs_remove_recursive(pool->stat_dentry);
701 }
702
703 #else /* CONFIG_ZSMALLOC_STAT */
704 static void __init zs_stat_init(void)
705 {
706 }
707
708 static void __exit zs_stat_exit(void)
709 {
710 }
711
712 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
713 {
714 }
715
716 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
717 {
718 }
719 #endif
720
721
722 /*
723  * For each size class, zspages are divided into different groups
724  * depending on how "full" they are. This was done so that we could
725  * easily find empty or nearly empty zspages when we try to shrink
726  * the pool (not yet implemented). This function returns fullness
727  * status of the given page.
728  */
729 static enum fullness_group get_fullness_group(struct size_class *class,
730                                                 struct zspage *zspage)
731 {
732         int inuse, objs_per_zspage;
733         enum fullness_group fg;
734
735         inuse = get_zspage_inuse(zspage);
736         objs_per_zspage = class->objs_per_zspage;
737
738         if (inuse == 0)
739                 fg = ZS_EMPTY;
740         else if (inuse == objs_per_zspage)
741                 fg = ZS_FULL;
742         else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
743                 fg = ZS_ALMOST_EMPTY;
744         else
745                 fg = ZS_ALMOST_FULL;
746
747         return fg;
748 }
749
750 /*
751  * Each size class maintains various freelists and zspages are assigned
752  * to one of these freelists based on the number of live objects they
753  * have. This functions inserts the given zspage into the freelist
754  * identified by <class, fullness_group>.
755  */
756 static void insert_zspage(struct size_class *class,
757                                 struct zspage *zspage,
758                                 enum fullness_group fullness)
759 {
760         struct zspage *head;
761
762         zs_stat_inc(class, fullness, 1);
763         head = list_first_entry_or_null(&class->fullness_list[fullness],
764                                         struct zspage, list);
765         /*
766          * We want to see more ZS_FULL pages and less almost empty/full.
767          * Put pages with higher ->inuse first.
768          */
769         if (head) {
770                 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
771                         list_add(&zspage->list, &head->list);
772                         return;
773                 }
774         }
775         list_add(&zspage->list, &class->fullness_list[fullness]);
776 }
777
778 /*
779  * This function removes the given zspage from the freelist identified
780  * by <class, fullness_group>.
781  */
782 static void remove_zspage(struct size_class *class,
783                                 struct zspage *zspage,
784                                 enum fullness_group fullness)
785 {
786         VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
787         VM_BUG_ON(is_zspage_isolated(zspage));
788
789         list_del_init(&zspage->list);
790         zs_stat_dec(class, fullness, 1);
791 }
792
793 /*
794  * Each size class maintains zspages in different fullness groups depending
795  * on the number of live objects they contain. When allocating or freeing
796  * objects, the fullness status of the page can change, say, from ALMOST_FULL
797  * to ALMOST_EMPTY when freeing an object. This function checks if such
798  * a status change has occurred for the given page and accordingly moves the
799  * page from the freelist of the old fullness group to that of the new
800  * fullness group.
801  */
802 static enum fullness_group fix_fullness_group(struct size_class *class,
803                                                 struct zspage *zspage)
804 {
805         int class_idx;
806         enum fullness_group currfg, newfg;
807
808         get_zspage_mapping(zspage, &class_idx, &currfg);
809         newfg = get_fullness_group(class, zspage);
810         if (newfg == currfg)
811                 goto out;
812
813         if (!is_zspage_isolated(zspage)) {
814                 remove_zspage(class, zspage, currfg);
815                 insert_zspage(class, zspage, newfg);
816         }
817
818         set_zspage_mapping(zspage, class_idx, newfg);
819
820 out:
821         return newfg;
822 }
823
824 /*
825  * We have to decide on how many pages to link together
826  * to form a zspage for each size class. This is important
827  * to reduce wastage due to unusable space left at end of
828  * each zspage which is given as:
829  *     wastage = Zp % class_size
830  *     usage = Zp - wastage
831  * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
832  *
833  * For example, for size class of 3/8 * PAGE_SIZE, we should
834  * link together 3 PAGE_SIZE sized pages to form a zspage
835  * since then we can perfectly fit in 8 such objects.
836  */
837 static int get_pages_per_zspage(int class_size)
838 {
839         int i, max_usedpc = 0;
840         /* zspage order which gives maximum used size per KB */
841         int max_usedpc_order = 1;
842
843         for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
844                 int zspage_size;
845                 int waste, usedpc;
846
847                 zspage_size = i * PAGE_SIZE;
848                 waste = zspage_size % class_size;
849                 usedpc = (zspage_size - waste) * 100 / zspage_size;
850
851                 if (usedpc > max_usedpc) {
852                         max_usedpc = usedpc;
853                         max_usedpc_order = i;
854                 }
855         }
856
857         return max_usedpc_order;
858 }
859
860 static struct zspage *get_zspage(struct page *page)
861 {
862         struct zspage *zspage = (struct zspage *)page->private;
863
864         BUG_ON(zspage->magic != ZSPAGE_MAGIC);
865         return zspage;
866 }
867
868 static struct page *get_next_page(struct page *page)
869 {
870         if (unlikely(PageHugeObject(page)))
871                 return NULL;
872
873         return page->freelist;
874 }
875
876 /**
877  * obj_to_location - get (<page>, <obj_idx>) from encoded object value
878  * @page: page object resides in zspage
879  * @obj_idx: object index
880  */
881 static void obj_to_location(unsigned long obj, struct page **page,
882                                 unsigned int *obj_idx)
883 {
884         obj >>= OBJ_TAG_BITS;
885         *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
886         *obj_idx = (obj & OBJ_INDEX_MASK);
887 }
888
889 /**
890  * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
891  * @page: page object resides in zspage
892  * @obj_idx: object index
893  */
894 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
895 {
896         unsigned long obj;
897
898         obj = page_to_pfn(page) << OBJ_INDEX_BITS;
899         obj |= obj_idx & OBJ_INDEX_MASK;
900         obj <<= OBJ_TAG_BITS;
901
902         return obj;
903 }
904
905 static unsigned long handle_to_obj(unsigned long handle)
906 {
907         return *(unsigned long *)handle;
908 }
909
910 static unsigned long obj_to_head(struct page *page, void *obj)
911 {
912         if (unlikely(PageHugeObject(page))) {
913                 VM_BUG_ON_PAGE(!is_first_page(page), page);
914                 return page->index;
915         } else
916                 return *(unsigned long *)obj;
917 }
918
919 static inline int testpin_tag(unsigned long handle)
920 {
921         return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
922 }
923
924 static inline int trypin_tag(unsigned long handle)
925 {
926         return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
927 }
928
929 static void pin_tag(unsigned long handle)
930 {
931         bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
932 }
933
934 static void unpin_tag(unsigned long handle)
935 {
936         bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
937 }
938
939 static void reset_page(struct page *page)
940 {
941         __ClearPageMovable(page);
942         ClearPagePrivate(page);
943         set_page_private(page, 0);
944         page_mapcount_reset(page);
945         ClearPageHugeObject(page);
946         page->freelist = NULL;
947 }
948
949 /*
950  * To prevent zspage destroy during migration, zspage freeing should
951  * hold locks of all pages in the zspage.
952  */
953 void lock_zspage(struct zspage *zspage)
954 {
955         struct page *page = get_first_page(zspage);
956
957         do {
958                 lock_page(page);
959         } while ((page = get_next_page(page)) != NULL);
960 }
961
962 int trylock_zspage(struct zspage *zspage)
963 {
964         struct page *cursor, *fail;
965
966         for (cursor = get_first_page(zspage); cursor != NULL; cursor =
967                                         get_next_page(cursor)) {
968                 if (!trylock_page(cursor)) {
969                         fail = cursor;
970                         goto unlock;
971                 }
972         }
973
974         return 1;
975 unlock:
976         for (cursor = get_first_page(zspage); cursor != fail; cursor =
977                                         get_next_page(cursor))
978                 unlock_page(cursor);
979
980         return 0;
981 }
982
983 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
984                                 struct zspage *zspage)
985 {
986         struct page *page, *next;
987         enum fullness_group fg;
988         unsigned int class_idx;
989
990         get_zspage_mapping(zspage, &class_idx, &fg);
991
992         assert_spin_locked(&class->lock);
993
994         VM_BUG_ON(get_zspage_inuse(zspage));
995         VM_BUG_ON(fg != ZS_EMPTY);
996
997         next = page = get_first_page(zspage);
998         do {
999                 VM_BUG_ON_PAGE(!PageLocked(page), page);
1000                 next = get_next_page(page);
1001                 reset_page(page);
1002                 unlock_page(page);
1003                 dec_zone_page_state(page, NR_ZSPAGES);
1004                 put_page(page);
1005                 page = next;
1006         } while (page != NULL);
1007
1008         cache_free_zspage(pool, zspage);
1009
1010         zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
1011         atomic_long_sub(class->pages_per_zspage,
1012                                         &pool->pages_allocated);
1013 }
1014
1015 static void free_zspage(struct zs_pool *pool, struct size_class *class,
1016                                 struct zspage *zspage)
1017 {
1018         VM_BUG_ON(get_zspage_inuse(zspage));
1019         VM_BUG_ON(list_empty(&zspage->list));
1020
1021         if (!trylock_zspage(zspage)) {
1022                 kick_deferred_free(pool);
1023                 return;
1024         }
1025
1026         remove_zspage(class, zspage, ZS_EMPTY);
1027         __free_zspage(pool, class, zspage);
1028 }
1029
1030 /* Initialize a newly allocated zspage */
1031 static void init_zspage(struct size_class *class, struct zspage *zspage)
1032 {
1033         unsigned int freeobj = 1;
1034         unsigned long off = 0;
1035         struct page *page = get_first_page(zspage);
1036
1037         while (page) {
1038                 struct page *next_page;
1039                 struct link_free *link;
1040                 void *vaddr;
1041
1042                 set_first_obj_offset(page, off);
1043
1044                 vaddr = kmap_atomic(page);
1045                 link = (struct link_free *)vaddr + off / sizeof(*link);
1046
1047                 while ((off += class->size) < PAGE_SIZE) {
1048                         link->next = freeobj++ << OBJ_TAG_BITS;
1049                         link += class->size / sizeof(*link);
1050                 }
1051
1052                 /*
1053                  * We now come to the last (full or partial) object on this
1054                  * page, which must point to the first object on the next
1055                  * page (if present)
1056                  */
1057                 next_page = get_next_page(page);
1058                 if (next_page) {
1059                         link->next = freeobj++ << OBJ_TAG_BITS;
1060                 } else {
1061                         /*
1062                          * Reset OBJ_TAG_BITS bit to last link to tell
1063                          * whether it's allocated object or not.
1064                          */
1065                         link->next = -1 << OBJ_TAG_BITS;
1066                 }
1067                 kunmap_atomic(vaddr);
1068                 page = next_page;
1069                 off %= PAGE_SIZE;
1070         }
1071
1072         set_freeobj(zspage, 0);
1073 }
1074
1075 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1076                                 struct page *pages[])
1077 {
1078         int i;
1079         struct page *page;
1080         struct page *prev_page = NULL;
1081         int nr_pages = class->pages_per_zspage;
1082
1083         /*
1084          * Allocate individual pages and link them together as:
1085          * 1. all pages are linked together using page->freelist
1086          * 2. each sub-page point to zspage using page->private
1087          *
1088          * we set PG_private to identify the first page (i.e. no other sub-page
1089          * has this flag set).
1090          */
1091         for (i = 0; i < nr_pages; i++) {
1092                 page = pages[i];
1093                 set_page_private(page, (unsigned long)zspage);
1094                 page->freelist = NULL;
1095                 if (i == 0) {
1096                         zspage->first_page = page;
1097                         SetPagePrivate(page);
1098                         if (unlikely(class->objs_per_zspage == 1 &&
1099                                         class->pages_per_zspage == 1))
1100                                 SetPageHugeObject(page);
1101                 } else {
1102                         prev_page->freelist = page;
1103                 }
1104                 prev_page = page;
1105         }
1106 }
1107
1108 /*
1109  * Allocate a zspage for the given size class
1110  */
1111 static struct zspage *alloc_zspage(struct zs_pool *pool,
1112                                         struct size_class *class,
1113                                         gfp_t gfp)
1114 {
1115         int i;
1116         struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1117         struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1118
1119         if (!zspage)
1120                 return NULL;
1121
1122         memset(zspage, 0, sizeof(struct zspage));
1123         zspage->magic = ZSPAGE_MAGIC;
1124         migrate_lock_init(zspage);
1125
1126         for (i = 0; i < class->pages_per_zspage; i++) {
1127                 struct page *page;
1128
1129                 page = alloc_page(gfp);
1130                 if (!page) {
1131                         while (--i >= 0) {
1132                                 dec_zone_page_state(pages[i], NR_ZSPAGES);
1133                                 __free_page(pages[i]);
1134                         }
1135                         cache_free_zspage(pool, zspage);
1136                         return NULL;
1137                 }
1138
1139                 inc_zone_page_state(page, NR_ZSPAGES);
1140                 pages[i] = page;
1141         }
1142
1143         create_page_chain(class, zspage, pages);
1144         init_zspage(class, zspage);
1145
1146         return zspage;
1147 }
1148
1149 static struct zspage *find_get_zspage(struct size_class *class)
1150 {
1151         int i;
1152         struct zspage *zspage;
1153
1154         for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1155                 zspage = list_first_entry_or_null(&class->fullness_list[i],
1156                                 struct zspage, list);
1157                 if (zspage)
1158                         break;
1159         }
1160
1161         return zspage;
1162 }
1163
1164 #ifdef CONFIG_PGTABLE_MAPPING
1165 static inline int __zs_cpu_up(struct mapping_area *area)
1166 {
1167         /*
1168          * Make sure we don't leak memory if a cpu UP notification
1169          * and zs_init() race and both call zs_cpu_up() on the same cpu
1170          */
1171         if (area->vm)
1172                 return 0;
1173         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1174         if (!area->vm)
1175                 return -ENOMEM;
1176         return 0;
1177 }
1178
1179 static inline void __zs_cpu_down(struct mapping_area *area)
1180 {
1181         if (area->vm)
1182                 free_vm_area(area->vm);
1183         area->vm = NULL;
1184 }
1185
1186 static inline void *__zs_map_object(struct mapping_area *area,
1187                                 struct page *pages[2], int off, int size)
1188 {
1189         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1190         area->vm_addr = area->vm->addr;
1191         return area->vm_addr + off;
1192 }
1193
1194 static inline void __zs_unmap_object(struct mapping_area *area,
1195                                 struct page *pages[2], int off, int size)
1196 {
1197         unsigned long addr = (unsigned long)area->vm_addr;
1198
1199         unmap_kernel_range(addr, PAGE_SIZE * 2);
1200 }
1201
1202 #else /* CONFIG_PGTABLE_MAPPING */
1203
1204 static inline int __zs_cpu_up(struct mapping_area *area)
1205 {
1206         /*
1207          * Make sure we don't leak memory if a cpu UP notification
1208          * and zs_init() race and both call zs_cpu_up() on the same cpu
1209          */
1210         if (area->vm_buf)
1211                 return 0;
1212         area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1213         if (!area->vm_buf)
1214                 return -ENOMEM;
1215         return 0;
1216 }
1217
1218 static inline void __zs_cpu_down(struct mapping_area *area)
1219 {
1220         kfree(area->vm_buf);
1221         area->vm_buf = NULL;
1222 }
1223
1224 static void *__zs_map_object(struct mapping_area *area,
1225                         struct page *pages[2], int off, int size)
1226 {
1227         int sizes[2];
1228         void *addr;
1229         char *buf = area->vm_buf;
1230
1231         /* disable page faults to match kmap_atomic() return conditions */
1232         pagefault_disable();
1233
1234         /* no read fastpath */
1235         if (area->vm_mm == ZS_MM_WO)
1236                 goto out;
1237
1238         sizes[0] = PAGE_SIZE - off;
1239         sizes[1] = size - sizes[0];
1240
1241         /* copy object to per-cpu buffer */
1242         addr = kmap_atomic(pages[0]);
1243         memcpy(buf, addr + off, sizes[0]);
1244         kunmap_atomic(addr);
1245         addr = kmap_atomic(pages[1]);
1246         memcpy(buf + sizes[0], addr, sizes[1]);
1247         kunmap_atomic(addr);
1248 out:
1249         return area->vm_buf;
1250 }
1251
1252 static void __zs_unmap_object(struct mapping_area *area,
1253                         struct page *pages[2], int off, int size)
1254 {
1255         int sizes[2];
1256         void *addr;
1257         char *buf;
1258
1259         /* no write fastpath */
1260         if (area->vm_mm == ZS_MM_RO)
1261                 goto out;
1262
1263         buf = area->vm_buf;
1264         buf = buf + ZS_HANDLE_SIZE;
1265         size -= ZS_HANDLE_SIZE;
1266         off += ZS_HANDLE_SIZE;
1267
1268         sizes[0] = PAGE_SIZE - off;
1269         sizes[1] = size - sizes[0];
1270
1271         /* copy per-cpu buffer to object */
1272         addr = kmap_atomic(pages[0]);
1273         memcpy(addr + off, buf, sizes[0]);
1274         kunmap_atomic(addr);
1275         addr = kmap_atomic(pages[1]);
1276         memcpy(addr, buf + sizes[0], sizes[1]);
1277         kunmap_atomic(addr);
1278
1279 out:
1280         /* enable page faults to match kunmap_atomic() return conditions */
1281         pagefault_enable();
1282 }
1283
1284 #endif /* CONFIG_PGTABLE_MAPPING */
1285
1286 static int zs_cpu_prepare(unsigned int cpu)
1287 {
1288         struct mapping_area *area;
1289
1290         area = &per_cpu(zs_map_area, cpu);
1291         return __zs_cpu_up(area);
1292 }
1293
1294 static int zs_cpu_dead(unsigned int cpu)
1295 {
1296         struct mapping_area *area;
1297
1298         area = &per_cpu(zs_map_area, cpu);
1299         __zs_cpu_down(area);
1300         return 0;
1301 }
1302
1303 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1304                                         int objs_per_zspage)
1305 {
1306         if (prev->pages_per_zspage == pages_per_zspage &&
1307                 prev->objs_per_zspage == objs_per_zspage)
1308                 return true;
1309
1310         return false;
1311 }
1312
1313 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1314 {
1315         return get_zspage_inuse(zspage) == class->objs_per_zspage;
1316 }
1317
1318 unsigned long zs_get_total_pages(struct zs_pool *pool)
1319 {
1320         return atomic_long_read(&pool->pages_allocated);
1321 }
1322 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1323
1324 /**
1325  * zs_map_object - get address of allocated object from handle.
1326  * @pool: pool from which the object was allocated
1327  * @handle: handle returned from zs_malloc
1328  *
1329  * Before using an object allocated from zs_malloc, it must be mapped using
1330  * this function. When done with the object, it must be unmapped using
1331  * zs_unmap_object.
1332  *
1333  * Only one object can be mapped per cpu at a time. There is no protection
1334  * against nested mappings.
1335  *
1336  * This function returns with preemption and page faults disabled.
1337  */
1338 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1339                         enum zs_mapmode mm)
1340 {
1341         struct zspage *zspage;
1342         struct page *page;
1343         unsigned long obj, off;
1344         unsigned int obj_idx;
1345
1346         unsigned int class_idx;
1347         enum fullness_group fg;
1348         struct size_class *class;
1349         struct mapping_area *area;
1350         struct page *pages[2];
1351         void *ret;
1352
1353         /*
1354          * Because we use per-cpu mapping areas shared among the
1355          * pools/users, we can't allow mapping in interrupt context
1356          * because it can corrupt another users mappings.
1357          */
1358         BUG_ON(in_interrupt());
1359
1360         /* From now on, migration cannot move the object */
1361         pin_tag(handle);
1362
1363         obj = handle_to_obj(handle);
1364         obj_to_location(obj, &page, &obj_idx);
1365         zspage = get_zspage(page);
1366
1367         /* migration cannot move any subpage in this zspage */
1368         migrate_read_lock(zspage);
1369
1370         get_zspage_mapping(zspage, &class_idx, &fg);
1371         class = pool->size_class[class_idx];
1372         off = (class->size * obj_idx) & ~PAGE_MASK;
1373
1374         area = &get_cpu_var(zs_map_area);
1375         area->vm_mm = mm;
1376         if (off + class->size <= PAGE_SIZE) {
1377                 /* this object is contained entirely within a page */
1378                 area->vm_addr = kmap_atomic(page);
1379                 ret = area->vm_addr + off;
1380                 goto out;
1381         }
1382
1383         /* this object spans two pages */
1384         pages[0] = page;
1385         pages[1] = get_next_page(page);
1386         BUG_ON(!pages[1]);
1387
1388         ret = __zs_map_object(area, pages, off, class->size);
1389 out:
1390         if (likely(!PageHugeObject(page)))
1391                 ret += ZS_HANDLE_SIZE;
1392
1393         return ret;
1394 }
1395 EXPORT_SYMBOL_GPL(zs_map_object);
1396
1397 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1398 {
1399         struct zspage *zspage;
1400         struct page *page;
1401         unsigned long obj, off;
1402         unsigned int obj_idx;
1403
1404         unsigned int class_idx;
1405         enum fullness_group fg;
1406         struct size_class *class;
1407         struct mapping_area *area;
1408
1409         obj = handle_to_obj(handle);
1410         obj_to_location(obj, &page, &obj_idx);
1411         zspage = get_zspage(page);
1412         get_zspage_mapping(zspage, &class_idx, &fg);
1413         class = pool->size_class[class_idx];
1414         off = (class->size * obj_idx) & ~PAGE_MASK;
1415
1416         area = this_cpu_ptr(&zs_map_area);
1417         if (off + class->size <= PAGE_SIZE)
1418                 kunmap_atomic(area->vm_addr);
1419         else {
1420                 struct page *pages[2];
1421
1422                 pages[0] = page;
1423                 pages[1] = get_next_page(page);
1424                 BUG_ON(!pages[1]);
1425
1426                 __zs_unmap_object(area, pages, off, class->size);
1427         }
1428         put_cpu_var(zs_map_area);
1429
1430         migrate_read_unlock(zspage);
1431         unpin_tag(handle);
1432 }
1433 EXPORT_SYMBOL_GPL(zs_unmap_object);
1434
1435 static unsigned long obj_malloc(struct size_class *class,
1436                                 struct zspage *zspage, unsigned long handle)
1437 {
1438         int i, nr_page, offset;
1439         unsigned long obj;
1440         struct link_free *link;
1441
1442         struct page *m_page;
1443         unsigned long m_offset;
1444         void *vaddr;
1445
1446         handle |= OBJ_ALLOCATED_TAG;
1447         obj = get_freeobj(zspage);
1448
1449         offset = obj * class->size;
1450         nr_page = offset >> PAGE_SHIFT;
1451         m_offset = offset & ~PAGE_MASK;
1452         m_page = get_first_page(zspage);
1453
1454         for (i = 0; i < nr_page; i++)
1455                 m_page = get_next_page(m_page);
1456
1457         vaddr = kmap_atomic(m_page);
1458         link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1459         set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1460         if (likely(!PageHugeObject(m_page)))
1461                 /* record handle in the header of allocated chunk */
1462                 link->handle = handle;
1463         else
1464                 /* record handle to page->index */
1465                 zspage->first_page->index = handle;
1466
1467         kunmap_atomic(vaddr);
1468         mod_zspage_inuse(zspage, 1);
1469         zs_stat_inc(class, OBJ_USED, 1);
1470
1471         obj = location_to_obj(m_page, obj);
1472
1473         return obj;
1474 }
1475
1476
1477 /**
1478  * zs_malloc - Allocate block of given size from pool.
1479  * @pool: pool to allocate from
1480  * @size: size of block to allocate
1481  * @gfp: gfp flags when allocating object
1482  *
1483  * On success, handle to the allocated object is returned,
1484  * otherwise 0.
1485  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1486  */
1487 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1488 {
1489         unsigned long handle, obj;
1490         struct size_class *class;
1491         enum fullness_group newfg;
1492         struct zspage *zspage;
1493
1494         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1495                 return 0;
1496
1497         handle = cache_alloc_handle(pool, gfp);
1498         if (!handle)
1499                 return 0;
1500
1501         /* extra space in chunk to keep the handle */
1502         size += ZS_HANDLE_SIZE;
1503         class = pool->size_class[get_size_class_index(size)];
1504
1505         spin_lock(&class->lock);
1506         zspage = find_get_zspage(class);
1507         if (likely(zspage)) {
1508                 obj = obj_malloc(class, zspage, handle);
1509                 /* Now move the zspage to another fullness group, if required */
1510                 fix_fullness_group(class, zspage);
1511                 record_obj(handle, obj);
1512                 spin_unlock(&class->lock);
1513
1514                 return handle;
1515         }
1516
1517         spin_unlock(&class->lock);
1518
1519         zspage = alloc_zspage(pool, class, gfp);
1520         if (!zspage) {
1521                 cache_free_handle(pool, handle);
1522                 return 0;
1523         }
1524
1525         spin_lock(&class->lock);
1526         obj = obj_malloc(class, zspage, handle);
1527         newfg = get_fullness_group(class, zspage);
1528         insert_zspage(class, zspage, newfg);
1529         set_zspage_mapping(zspage, class->index, newfg);
1530         record_obj(handle, obj);
1531         atomic_long_add(class->pages_per_zspage,
1532                                 &pool->pages_allocated);
1533         zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1534
1535         /* We completely set up zspage so mark them as movable */
1536         SetZsPageMovable(pool, zspage);
1537         spin_unlock(&class->lock);
1538
1539         return handle;
1540 }
1541 EXPORT_SYMBOL_GPL(zs_malloc);
1542
1543 static void obj_free(struct size_class *class, unsigned long obj)
1544 {
1545         struct link_free *link;
1546         struct zspage *zspage;
1547         struct page *f_page;
1548         unsigned long f_offset;
1549         unsigned int f_objidx;
1550         void *vaddr;
1551
1552         obj &= ~OBJ_ALLOCATED_TAG;
1553         obj_to_location(obj, &f_page, &f_objidx);
1554         f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1555         zspage = get_zspage(f_page);
1556
1557         vaddr = kmap_atomic(f_page);
1558
1559         /* Insert this object in containing zspage's freelist */
1560         link = (struct link_free *)(vaddr + f_offset);
1561         link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1562         kunmap_atomic(vaddr);
1563         set_freeobj(zspage, f_objidx);
1564         mod_zspage_inuse(zspage, -1);
1565         zs_stat_dec(class, OBJ_USED, 1);
1566 }
1567
1568 void zs_free(struct zs_pool *pool, unsigned long handle)
1569 {
1570         struct zspage *zspage;
1571         struct page *f_page;
1572         unsigned long obj;
1573         unsigned int f_objidx;
1574         int class_idx;
1575         struct size_class *class;
1576         enum fullness_group fullness;
1577         bool isolated;
1578
1579         if (unlikely(!handle))
1580                 return;
1581
1582         pin_tag(handle);
1583         obj = handle_to_obj(handle);
1584         obj_to_location(obj, &f_page, &f_objidx);
1585         zspage = get_zspage(f_page);
1586
1587         migrate_read_lock(zspage);
1588
1589         get_zspage_mapping(zspage, &class_idx, &fullness);
1590         class = pool->size_class[class_idx];
1591
1592         spin_lock(&class->lock);
1593         obj_free(class, obj);
1594         fullness = fix_fullness_group(class, zspage);
1595         if (fullness != ZS_EMPTY) {
1596                 migrate_read_unlock(zspage);
1597                 goto out;
1598         }
1599
1600         isolated = is_zspage_isolated(zspage);
1601         migrate_read_unlock(zspage);
1602         /* If zspage is isolated, zs_page_putback will free the zspage */
1603         if (likely(!isolated))
1604                 free_zspage(pool, class, zspage);
1605 out:
1606
1607         spin_unlock(&class->lock);
1608         unpin_tag(handle);
1609         cache_free_handle(pool, handle);
1610 }
1611 EXPORT_SYMBOL_GPL(zs_free);
1612
1613 static void zs_object_copy(struct size_class *class, unsigned long dst,
1614                                 unsigned long src)
1615 {
1616         struct page *s_page, *d_page;
1617         unsigned int s_objidx, d_objidx;
1618         unsigned long s_off, d_off;
1619         void *s_addr, *d_addr;
1620         int s_size, d_size, size;
1621         int written = 0;
1622
1623         s_size = d_size = class->size;
1624
1625         obj_to_location(src, &s_page, &s_objidx);
1626         obj_to_location(dst, &d_page, &d_objidx);
1627
1628         s_off = (class->size * s_objidx) & ~PAGE_MASK;
1629         d_off = (class->size * d_objidx) & ~PAGE_MASK;
1630
1631         if (s_off + class->size > PAGE_SIZE)
1632                 s_size = PAGE_SIZE - s_off;
1633
1634         if (d_off + class->size > PAGE_SIZE)
1635                 d_size = PAGE_SIZE - d_off;
1636
1637         s_addr = kmap_atomic(s_page);
1638         d_addr = kmap_atomic(d_page);
1639
1640         while (1) {
1641                 size = min(s_size, d_size);
1642                 memcpy(d_addr + d_off, s_addr + s_off, size);
1643                 written += size;
1644
1645                 if (written == class->size)
1646                         break;
1647
1648                 s_off += size;
1649                 s_size -= size;
1650                 d_off += size;
1651                 d_size -= size;
1652
1653                 if (s_off >= PAGE_SIZE) {
1654                         kunmap_atomic(d_addr);
1655                         kunmap_atomic(s_addr);
1656                         s_page = get_next_page(s_page);
1657                         s_addr = kmap_atomic(s_page);
1658                         d_addr = kmap_atomic(d_page);
1659                         s_size = class->size - written;
1660                         s_off = 0;
1661                 }
1662
1663                 if (d_off >= PAGE_SIZE) {
1664                         kunmap_atomic(d_addr);
1665                         d_page = get_next_page(d_page);
1666                         d_addr = kmap_atomic(d_page);
1667                         d_size = class->size - written;
1668                         d_off = 0;
1669                 }
1670         }
1671
1672         kunmap_atomic(d_addr);
1673         kunmap_atomic(s_addr);
1674 }
1675
1676 /*
1677  * Find alloced object in zspage from index object and
1678  * return handle.
1679  */
1680 static unsigned long find_alloced_obj(struct size_class *class,
1681                                         struct page *page, int *obj_idx)
1682 {
1683         unsigned long head;
1684         int offset = 0;
1685         int index = *obj_idx;
1686         unsigned long handle = 0;
1687         void *addr = kmap_atomic(page);
1688
1689         offset = get_first_obj_offset(page);
1690         offset += class->size * index;
1691
1692         while (offset < PAGE_SIZE) {
1693                 head = obj_to_head(page, addr + offset);
1694                 if (head & OBJ_ALLOCATED_TAG) {
1695                         handle = head & ~OBJ_ALLOCATED_TAG;
1696                         if (trypin_tag(handle))
1697                                 break;
1698                         handle = 0;
1699                 }
1700
1701                 offset += class->size;
1702                 index++;
1703         }
1704
1705         kunmap_atomic(addr);
1706
1707         *obj_idx = index;
1708
1709         return handle;
1710 }
1711
1712 struct zs_compact_control {
1713         /* Source spage for migration which could be a subpage of zspage */
1714         struct page *s_page;
1715         /* Destination page for migration which should be a first page
1716          * of zspage. */
1717         struct page *d_page;
1718          /* Starting object index within @s_page which used for live object
1719           * in the subpage. */
1720         int obj_idx;
1721 };
1722
1723 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1724                                 struct zs_compact_control *cc)
1725 {
1726         unsigned long used_obj, free_obj;
1727         unsigned long handle;
1728         struct page *s_page = cc->s_page;
1729         struct page *d_page = cc->d_page;
1730         int obj_idx = cc->obj_idx;
1731         int ret = 0;
1732
1733         while (1) {
1734                 handle = find_alloced_obj(class, s_page, &obj_idx);
1735                 if (!handle) {
1736                         s_page = get_next_page(s_page);
1737                         if (!s_page)
1738                                 break;
1739                         obj_idx = 0;
1740                         continue;
1741                 }
1742
1743                 /* Stop if there is no more space */
1744                 if (zspage_full(class, get_zspage(d_page))) {
1745                         unpin_tag(handle);
1746                         ret = -ENOMEM;
1747                         break;
1748                 }
1749
1750                 used_obj = handle_to_obj(handle);
1751                 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1752                 zs_object_copy(class, free_obj, used_obj);
1753                 obj_idx++;
1754                 /*
1755                  * record_obj updates handle's value to free_obj and it will
1756                  * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1757                  * breaks synchronization using pin_tag(e,g, zs_free) so
1758                  * let's keep the lock bit.
1759                  */
1760                 free_obj |= BIT(HANDLE_PIN_BIT);
1761                 record_obj(handle, free_obj);
1762                 unpin_tag(handle);
1763                 obj_free(class, used_obj);
1764         }
1765
1766         /* Remember last position in this iteration */
1767         cc->s_page = s_page;
1768         cc->obj_idx = obj_idx;
1769
1770         return ret;
1771 }
1772
1773 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1774 {
1775         int i;
1776         struct zspage *zspage;
1777         enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1778
1779         if (!source) {
1780                 fg[0] = ZS_ALMOST_FULL;
1781                 fg[1] = ZS_ALMOST_EMPTY;
1782         }
1783
1784         for (i = 0; i < 2; i++) {
1785                 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1786                                                         struct zspage, list);
1787                 if (zspage) {
1788                         VM_BUG_ON(is_zspage_isolated(zspage));
1789                         remove_zspage(class, zspage, fg[i]);
1790                         return zspage;
1791                 }
1792         }
1793
1794         return zspage;
1795 }
1796
1797 /*
1798  * putback_zspage - add @zspage into right class's fullness list
1799  * @class: destination class
1800  * @zspage: target page
1801  *
1802  * Return @zspage's fullness_group
1803  */
1804 static enum fullness_group putback_zspage(struct size_class *class,
1805                         struct zspage *zspage)
1806 {
1807         enum fullness_group fullness;
1808
1809         VM_BUG_ON(is_zspage_isolated(zspage));
1810
1811         fullness = get_fullness_group(class, zspage);
1812         insert_zspage(class, zspage, fullness);
1813         set_zspage_mapping(zspage, class->index, fullness);
1814
1815         return fullness;
1816 }
1817
1818 #ifdef CONFIG_COMPACTION
1819 static struct dentry *zs_mount(struct file_system_type *fs_type,
1820                                 int flags, const char *dev_name, void *data)
1821 {
1822         static const struct dentry_operations ops = {
1823                 .d_dname = simple_dname,
1824         };
1825
1826         return mount_pseudo(fs_type, "zsmalloc:", NULL, &ops, ZSMALLOC_MAGIC);
1827 }
1828
1829 static struct file_system_type zsmalloc_fs = {
1830         .name           = "zsmalloc",
1831         .mount          = zs_mount,
1832         .kill_sb        = kill_anon_super,
1833 };
1834
1835 static int zsmalloc_mount(void)
1836 {
1837         int ret = 0;
1838
1839         zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1840         if (IS_ERR(zsmalloc_mnt))
1841                 ret = PTR_ERR(zsmalloc_mnt);
1842
1843         return ret;
1844 }
1845
1846 static void zsmalloc_unmount(void)
1847 {
1848         kern_unmount(zsmalloc_mnt);
1849 }
1850
1851 static void migrate_lock_init(struct zspage *zspage)
1852 {
1853         rwlock_init(&zspage->lock);
1854 }
1855
1856 static void migrate_read_lock(struct zspage *zspage)
1857 {
1858         read_lock(&zspage->lock);
1859 }
1860
1861 static void migrate_read_unlock(struct zspage *zspage)
1862 {
1863         read_unlock(&zspage->lock);
1864 }
1865
1866 static void migrate_write_lock(struct zspage *zspage)
1867 {
1868         write_lock(&zspage->lock);
1869 }
1870
1871 static void migrate_write_unlock(struct zspage *zspage)
1872 {
1873         write_unlock(&zspage->lock);
1874 }
1875
1876 /* Number of isolated subpage for *page migration* in this zspage */
1877 static void inc_zspage_isolation(struct zspage *zspage)
1878 {
1879         zspage->isolated++;
1880 }
1881
1882 static void dec_zspage_isolation(struct zspage *zspage)
1883 {
1884         zspage->isolated--;
1885 }
1886
1887 static void putback_zspage_deferred(struct zs_pool *pool,
1888                                     struct size_class *class,
1889                                     struct zspage *zspage)
1890 {
1891         enum fullness_group fg;
1892
1893         fg = putback_zspage(class, zspage);
1894         if (fg == ZS_EMPTY)
1895                 schedule_work(&pool->free_work);
1896
1897 }
1898
1899 static inline void zs_pool_dec_isolated(struct zs_pool *pool)
1900 {
1901         VM_BUG_ON(atomic_long_read(&pool->isolated_pages) <= 0);
1902         atomic_long_dec(&pool->isolated_pages);
1903         /*
1904          * Checking pool->destroying must happen after atomic_long_dec()
1905          * for pool->isolated_pages above. Paired with the smp_mb() in
1906          * zs_unregister_migration().
1907          */
1908         smp_mb__after_atomic();
1909         if (atomic_long_read(&pool->isolated_pages) == 0 && pool->destroying)
1910                 wake_up_all(&pool->migration_wait);
1911 }
1912
1913 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1914                                 struct page *newpage, struct page *oldpage)
1915 {
1916         struct page *page;
1917         struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1918         int idx = 0;
1919
1920         page = get_first_page(zspage);
1921         do {
1922                 if (page == oldpage)
1923                         pages[idx] = newpage;
1924                 else
1925                         pages[idx] = page;
1926                 idx++;
1927         } while ((page = get_next_page(page)) != NULL);
1928
1929         create_page_chain(class, zspage, pages);
1930         set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1931         if (unlikely(PageHugeObject(oldpage)))
1932                 newpage->index = oldpage->index;
1933         __SetPageMovable(newpage, page_mapping(oldpage));
1934 }
1935
1936 bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1937 {
1938         struct zs_pool *pool;
1939         struct size_class *class;
1940         int class_idx;
1941         enum fullness_group fullness;
1942         struct zspage *zspage;
1943         struct address_space *mapping;
1944
1945         /*
1946          * Page is locked so zspage couldn't be destroyed. For detail, look at
1947          * lock_zspage in free_zspage.
1948          */
1949         VM_BUG_ON_PAGE(!PageMovable(page), page);
1950         VM_BUG_ON_PAGE(PageIsolated(page), page);
1951
1952         zspage = get_zspage(page);
1953
1954         /*
1955          * Without class lock, fullness could be stale while class_idx is okay
1956          * because class_idx is constant unless page is freed so we should get
1957          * fullness again under class lock.
1958          */
1959         get_zspage_mapping(zspage, &class_idx, &fullness);
1960         mapping = page_mapping(page);
1961         pool = mapping->private_data;
1962         class = pool->size_class[class_idx];
1963
1964         spin_lock(&class->lock);
1965         if (get_zspage_inuse(zspage) == 0) {
1966                 spin_unlock(&class->lock);
1967                 return false;
1968         }
1969
1970         /* zspage is isolated for object migration */
1971         if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1972                 spin_unlock(&class->lock);
1973                 return false;
1974         }
1975
1976         /*
1977          * If this is first time isolation for the zspage, isolate zspage from
1978          * size_class to prevent further object allocation from the zspage.
1979          */
1980         if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1981                 get_zspage_mapping(zspage, &class_idx, &fullness);
1982                 atomic_long_inc(&pool->isolated_pages);
1983                 remove_zspage(class, zspage, fullness);
1984         }
1985
1986         inc_zspage_isolation(zspage);
1987         spin_unlock(&class->lock);
1988
1989         return true;
1990 }
1991
1992 int zs_page_migrate(struct address_space *mapping, struct page *newpage,
1993                 struct page *page, enum migrate_mode mode)
1994 {
1995         struct zs_pool *pool;
1996         struct size_class *class;
1997         int class_idx;
1998         enum fullness_group fullness;
1999         struct zspage *zspage;
2000         struct page *dummy;
2001         void *s_addr, *d_addr, *addr;
2002         int offset, pos;
2003         unsigned long handle, head;
2004         unsigned long old_obj, new_obj;
2005         unsigned int obj_idx;
2006         int ret = -EAGAIN;
2007
2008         /*
2009          * We cannot support the _NO_COPY case here, because copy needs to
2010          * happen under the zs lock, which does not work with
2011          * MIGRATE_SYNC_NO_COPY workflow.
2012          */
2013         if (mode == MIGRATE_SYNC_NO_COPY)
2014                 return -EINVAL;
2015
2016         VM_BUG_ON_PAGE(!PageMovable(page), page);
2017         VM_BUG_ON_PAGE(!PageIsolated(page), page);
2018
2019         zspage = get_zspage(page);
2020
2021         /* Concurrent compactor cannot migrate any subpage in zspage */
2022         migrate_write_lock(zspage);
2023         get_zspage_mapping(zspage, &class_idx, &fullness);
2024         pool = mapping->private_data;
2025         class = pool->size_class[class_idx];
2026         offset = get_first_obj_offset(page);
2027
2028         spin_lock(&class->lock);
2029         if (!get_zspage_inuse(zspage)) {
2030                 /*
2031                  * Set "offset" to end of the page so that every loops
2032                  * skips unnecessary object scanning.
2033                  */
2034                 offset = PAGE_SIZE;
2035         }
2036
2037         pos = offset;
2038         s_addr = kmap_atomic(page);
2039         while (pos < PAGE_SIZE) {
2040                 head = obj_to_head(page, s_addr + pos);
2041                 if (head & OBJ_ALLOCATED_TAG) {
2042                         handle = head & ~OBJ_ALLOCATED_TAG;
2043                         if (!trypin_tag(handle))
2044                                 goto unpin_objects;
2045                 }
2046                 pos += class->size;
2047         }
2048
2049         /*
2050          * Here, any user cannot access all objects in the zspage so let's move.
2051          */
2052         d_addr = kmap_atomic(newpage);
2053         memcpy(d_addr, s_addr, PAGE_SIZE);
2054         kunmap_atomic(d_addr);
2055
2056         for (addr = s_addr + offset; addr < s_addr + pos;
2057                                         addr += class->size) {
2058                 head = obj_to_head(page, addr);
2059                 if (head & OBJ_ALLOCATED_TAG) {
2060                         handle = head & ~OBJ_ALLOCATED_TAG;
2061                         if (!testpin_tag(handle))
2062                                 BUG();
2063
2064                         old_obj = handle_to_obj(handle);
2065                         obj_to_location(old_obj, &dummy, &obj_idx);
2066                         new_obj = (unsigned long)location_to_obj(newpage,
2067                                                                 obj_idx);
2068                         new_obj |= BIT(HANDLE_PIN_BIT);
2069                         record_obj(handle, new_obj);
2070                 }
2071         }
2072
2073         replace_sub_page(class, zspage, newpage, page);
2074         get_page(newpage);
2075
2076         dec_zspage_isolation(zspage);
2077
2078         /*
2079          * Page migration is done so let's putback isolated zspage to
2080          * the list if @page is final isolated subpage in the zspage.
2081          */
2082         if (!is_zspage_isolated(zspage)) {
2083                 /*
2084                  * We cannot race with zs_destroy_pool() here because we wait
2085                  * for isolation to hit zero before we start destroying.
2086                  * Also, we ensure that everyone can see pool->destroying before
2087                  * we start waiting.
2088                  */
2089                 putback_zspage_deferred(pool, class, zspage);
2090                 zs_pool_dec_isolated(pool);
2091         }
2092
2093         if (page_zone(newpage) != page_zone(page)) {
2094                 dec_zone_page_state(page, NR_ZSPAGES);
2095                 inc_zone_page_state(newpage, NR_ZSPAGES);
2096         }
2097
2098         reset_page(page);
2099         put_page(page);
2100         page = newpage;
2101
2102         ret = MIGRATEPAGE_SUCCESS;
2103 unpin_objects:
2104         for (addr = s_addr + offset; addr < s_addr + pos;
2105                                                 addr += class->size) {
2106                 head = obj_to_head(page, addr);
2107                 if (head & OBJ_ALLOCATED_TAG) {
2108                         handle = head & ~OBJ_ALLOCATED_TAG;
2109                         if (!testpin_tag(handle))
2110                                 BUG();
2111                         unpin_tag(handle);
2112                 }
2113         }
2114         kunmap_atomic(s_addr);
2115         spin_unlock(&class->lock);
2116         migrate_write_unlock(zspage);
2117
2118         return ret;
2119 }
2120
2121 void zs_page_putback(struct page *page)
2122 {
2123         struct zs_pool *pool;
2124         struct size_class *class;
2125         int class_idx;
2126         enum fullness_group fg;
2127         struct address_space *mapping;
2128         struct zspage *zspage;
2129
2130         VM_BUG_ON_PAGE(!PageMovable(page), page);
2131         VM_BUG_ON_PAGE(!PageIsolated(page), page);
2132
2133         zspage = get_zspage(page);
2134         get_zspage_mapping(zspage, &class_idx, &fg);
2135         mapping = page_mapping(page);
2136         pool = mapping->private_data;
2137         class = pool->size_class[class_idx];
2138
2139         spin_lock(&class->lock);
2140         dec_zspage_isolation(zspage);
2141         if (!is_zspage_isolated(zspage)) {
2142                 /*
2143                  * Due to page_lock, we cannot free zspage immediately
2144                  * so let's defer.
2145                  */
2146                 putback_zspage_deferred(pool, class, zspage);
2147                 zs_pool_dec_isolated(pool);
2148         }
2149         spin_unlock(&class->lock);
2150 }
2151
2152 const struct address_space_operations zsmalloc_aops = {
2153         .isolate_page = zs_page_isolate,
2154         .migratepage = zs_page_migrate,
2155         .putback_page = zs_page_putback,
2156 };
2157
2158 static int zs_register_migration(struct zs_pool *pool)
2159 {
2160         pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2161         if (IS_ERR(pool->inode)) {
2162                 pool->inode = NULL;
2163                 return 1;
2164         }
2165
2166         pool->inode->i_mapping->private_data = pool;
2167         pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2168         return 0;
2169 }
2170
2171 static bool pool_isolated_are_drained(struct zs_pool *pool)
2172 {
2173         return atomic_long_read(&pool->isolated_pages) == 0;
2174 }
2175
2176 /* Function for resolving migration */
2177 static void wait_for_isolated_drain(struct zs_pool *pool)
2178 {
2179
2180         /*
2181          * We're in the process of destroying the pool, so there are no
2182          * active allocations. zs_page_isolate() fails for completely free
2183          * zspages, so we need only wait for the zs_pool's isolated
2184          * count to hit zero.
2185          */
2186         wait_event(pool->migration_wait,
2187                    pool_isolated_are_drained(pool));
2188 }
2189
2190 static void zs_unregister_migration(struct zs_pool *pool)
2191 {
2192         pool->destroying = true;
2193         /*
2194          * We need a memory barrier here to ensure global visibility of
2195          * pool->destroying. Thus pool->isolated pages will either be 0 in which
2196          * case we don't care, or it will be > 0 and pool->destroying will
2197          * ensure that we wake up once isolation hits 0.
2198          */
2199         smp_mb();
2200         wait_for_isolated_drain(pool); /* This can block */
2201         flush_work(&pool->free_work);
2202         iput(pool->inode);
2203 }
2204
2205 /*
2206  * Caller should hold page_lock of all pages in the zspage
2207  * In here, we cannot use zspage meta data.
2208  */
2209 static void async_free_zspage(struct work_struct *work)
2210 {
2211         int i;
2212         struct size_class *class;
2213         unsigned int class_idx;
2214         enum fullness_group fullness;
2215         struct zspage *zspage, *tmp;
2216         LIST_HEAD(free_pages);
2217         struct zs_pool *pool = container_of(work, struct zs_pool,
2218                                         free_work);
2219
2220         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2221                 class = pool->size_class[i];
2222                 if (class->index != i)
2223                         continue;
2224
2225                 spin_lock(&class->lock);
2226                 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2227                 spin_unlock(&class->lock);
2228         }
2229
2230
2231         list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2232                 list_del(&zspage->list);
2233                 lock_zspage(zspage);
2234
2235                 get_zspage_mapping(zspage, &class_idx, &fullness);
2236                 VM_BUG_ON(fullness != ZS_EMPTY);
2237                 class = pool->size_class[class_idx];
2238                 spin_lock(&class->lock);
2239                 __free_zspage(pool, pool->size_class[class_idx], zspage);
2240                 spin_unlock(&class->lock);
2241         }
2242 };
2243
2244 static void kick_deferred_free(struct zs_pool *pool)
2245 {
2246         schedule_work(&pool->free_work);
2247 }
2248
2249 static void init_deferred_free(struct zs_pool *pool)
2250 {
2251         INIT_WORK(&pool->free_work, async_free_zspage);
2252 }
2253
2254 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2255 {
2256         struct page *page = get_first_page(zspage);
2257
2258         do {
2259                 WARN_ON(!trylock_page(page));
2260                 __SetPageMovable(page, pool->inode->i_mapping);
2261                 unlock_page(page);
2262         } while ((page = get_next_page(page)) != NULL);
2263 }
2264 #endif
2265
2266 /*
2267  *
2268  * Based on the number of unused allocated objects calculate
2269  * and return the number of pages that we can free.
2270  */
2271 static unsigned long zs_can_compact(struct size_class *class)
2272 {
2273         unsigned long obj_wasted;
2274         unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2275         unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2276
2277         if (obj_allocated <= obj_used)
2278                 return 0;
2279
2280         obj_wasted = obj_allocated - obj_used;
2281         obj_wasted /= class->objs_per_zspage;
2282
2283         return obj_wasted * class->pages_per_zspage;
2284 }
2285
2286 static unsigned long __zs_compact(struct zs_pool *pool,
2287                                   struct size_class *class)
2288 {
2289         struct zs_compact_control cc;
2290         struct zspage *src_zspage;
2291         struct zspage *dst_zspage = NULL;
2292         unsigned long pages_freed = 0;
2293
2294         spin_lock(&class->lock);
2295         while ((src_zspage = isolate_zspage(class, true))) {
2296
2297                 if (!zs_can_compact(class))
2298                         break;
2299
2300                 cc.obj_idx = 0;
2301                 cc.s_page = get_first_page(src_zspage);
2302
2303                 while ((dst_zspage = isolate_zspage(class, false))) {
2304                         cc.d_page = get_first_page(dst_zspage);
2305                         /*
2306                          * If there is no more space in dst_page, resched
2307                          * and see if anyone had allocated another zspage.
2308                          */
2309                         if (!migrate_zspage(pool, class, &cc))
2310                                 break;
2311
2312                         putback_zspage(class, dst_zspage);
2313                 }
2314
2315                 /* Stop if we couldn't find slot */
2316                 if (dst_zspage == NULL)
2317                         break;
2318
2319                 putback_zspage(class, dst_zspage);
2320                 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2321                         free_zspage(pool, class, src_zspage);
2322                         pages_freed += class->pages_per_zspage;
2323                 }
2324                 spin_unlock(&class->lock);
2325                 cond_resched();
2326                 spin_lock(&class->lock);
2327         }
2328
2329         if (src_zspage)
2330                 putback_zspage(class, src_zspage);
2331
2332         spin_unlock(&class->lock);
2333
2334         return pages_freed;
2335 }
2336
2337 unsigned long zs_compact(struct zs_pool *pool)
2338 {
2339         int i;
2340         struct size_class *class;
2341         unsigned long pages_freed = 0;
2342
2343         for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2344                 class = pool->size_class[i];
2345                 if (!class)
2346                         continue;
2347                 if (class->index != i)
2348                         continue;
2349                 pages_freed += __zs_compact(pool, class);
2350         }
2351         atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2352
2353         return pages_freed;
2354 }
2355 EXPORT_SYMBOL_GPL(zs_compact);
2356
2357 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2358 {
2359         memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2360 }
2361 EXPORT_SYMBOL_GPL(zs_pool_stats);
2362
2363 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2364                 struct shrink_control *sc)
2365 {
2366         unsigned long pages_freed;
2367         struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2368                         shrinker);
2369
2370         /*
2371          * Compact classes and calculate compaction delta.
2372          * Can run concurrently with a manually triggered
2373          * (by user) compaction.
2374          */
2375         pages_freed = zs_compact(pool);
2376
2377         return pages_freed ? pages_freed : SHRINK_STOP;
2378 }
2379
2380 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2381                 struct shrink_control *sc)
2382 {
2383         int i;
2384         struct size_class *class;
2385         unsigned long pages_to_free = 0;
2386         struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2387                         shrinker);
2388
2389         for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2390                 class = pool->size_class[i];
2391                 if (!class)
2392                         continue;
2393                 if (class->index != i)
2394                         continue;
2395
2396                 pages_to_free += zs_can_compact(class);
2397         }
2398
2399         return pages_to_free;
2400 }
2401
2402 static void zs_unregister_shrinker(struct zs_pool *pool)
2403 {
2404         if (pool->shrinker_enabled) {
2405                 unregister_shrinker(&pool->shrinker);
2406                 pool->shrinker_enabled = false;
2407         }
2408 }
2409
2410 static int zs_register_shrinker(struct zs_pool *pool)
2411 {
2412         pool->shrinker.scan_objects = zs_shrinker_scan;
2413         pool->shrinker.count_objects = zs_shrinker_count;
2414         pool->shrinker.batch = 0;
2415         pool->shrinker.seeks = DEFAULT_SEEKS;
2416
2417         return register_shrinker(&pool->shrinker);
2418 }
2419
2420 /**
2421  * zs_create_pool - Creates an allocation pool to work from.
2422  * @name: pool name to be created
2423  *
2424  * This function must be called before anything when using
2425  * the zsmalloc allocator.
2426  *
2427  * On success, a pointer to the newly created pool is returned,
2428  * otherwise NULL.
2429  */
2430 struct zs_pool *zs_create_pool(const char *name)
2431 {
2432         int i;
2433         struct zs_pool *pool;
2434         struct size_class *prev_class = NULL;
2435
2436         pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2437         if (!pool)
2438                 return NULL;
2439
2440         init_deferred_free(pool);
2441
2442         pool->name = kstrdup(name, GFP_KERNEL);
2443         if (!pool->name)
2444                 goto err;
2445
2446 #ifdef CONFIG_COMPACTION
2447         init_waitqueue_head(&pool->migration_wait);
2448 #endif
2449
2450         if (create_cache(pool))
2451                 goto err;
2452
2453         /*
2454          * Iterate reversely, because, size of size_class that we want to use
2455          * for merging should be larger or equal to current size.
2456          */
2457         for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2458                 int size;
2459                 int pages_per_zspage;
2460                 int objs_per_zspage;
2461                 struct size_class *class;
2462                 int fullness = 0;
2463
2464                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2465                 if (size > ZS_MAX_ALLOC_SIZE)
2466                         size = ZS_MAX_ALLOC_SIZE;
2467                 pages_per_zspage = get_pages_per_zspage(size);
2468                 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2469
2470                 /*
2471                  * size_class is used for normal zsmalloc operation such
2472                  * as alloc/free for that size. Although it is natural that we
2473                  * have one size_class for each size, there is a chance that we
2474                  * can get more memory utilization if we use one size_class for
2475                  * many different sizes whose size_class have same
2476                  * characteristics. So, we makes size_class point to
2477                  * previous size_class if possible.
2478                  */
2479                 if (prev_class) {
2480                         if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2481                                 pool->size_class[i] = prev_class;
2482                                 continue;
2483                         }
2484                 }
2485
2486                 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2487                 if (!class)
2488                         goto err;
2489
2490                 class->size = size;
2491                 class->index = i;
2492                 class->pages_per_zspage = pages_per_zspage;
2493                 class->objs_per_zspage = objs_per_zspage;
2494                 spin_lock_init(&class->lock);
2495                 pool->size_class[i] = class;
2496                 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2497                                                         fullness++)
2498                         INIT_LIST_HEAD(&class->fullness_list[fullness]);
2499
2500                 prev_class = class;
2501         }
2502
2503         /* debug only, don't abort if it fails */
2504         zs_pool_stat_create(pool, name);
2505
2506         if (zs_register_migration(pool))
2507                 goto err;
2508
2509         /*
2510          * Not critical, we still can use the pool
2511          * and user can trigger compaction manually.
2512          */
2513         if (zs_register_shrinker(pool) == 0)
2514                 pool->shrinker_enabled = true;
2515         return pool;
2516
2517 err:
2518         zs_destroy_pool(pool);
2519         return NULL;
2520 }
2521 EXPORT_SYMBOL_GPL(zs_create_pool);
2522
2523 void zs_destroy_pool(struct zs_pool *pool)
2524 {
2525         int i;
2526
2527         zs_unregister_shrinker(pool);
2528         zs_unregister_migration(pool);
2529         zs_pool_stat_destroy(pool);
2530
2531         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2532                 int fg;
2533                 struct size_class *class = pool->size_class[i];
2534
2535                 if (!class)
2536                         continue;
2537
2538                 if (class->index != i)
2539                         continue;
2540
2541                 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2542                         if (!list_empty(&class->fullness_list[fg])) {
2543                                 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2544                                         class->size, fg);
2545                         }
2546                 }
2547                 kfree(class);
2548         }
2549
2550         destroy_cache(pool);
2551         kfree(pool->name);
2552         kfree(pool);
2553 }
2554 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2555
2556 static int __init zs_init(void)
2557 {
2558         int ret;
2559
2560         ret = zsmalloc_mount();
2561         if (ret)
2562                 goto out;
2563
2564         ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2565                                 zs_cpu_prepare, zs_cpu_dead);
2566         if (ret)
2567                 goto hp_setup_fail;
2568
2569 #ifdef CONFIG_ZPOOL
2570         zpool_register_driver(&zs_zpool_driver);
2571 #endif
2572
2573         zs_stat_init();
2574
2575         return 0;
2576
2577 hp_setup_fail:
2578         zsmalloc_unmount();
2579 out:
2580         return ret;
2581 }
2582
2583 static void __exit zs_exit(void)
2584 {
2585 #ifdef CONFIG_ZPOOL
2586         zpool_unregister_driver(&zs_zpool_driver);
2587 #endif
2588         zsmalloc_unmount();
2589         cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2590
2591         zs_stat_exit();
2592 }
2593
2594 module_init(zs_init);
2595 module_exit(zs_exit);
2596
2597 MODULE_LICENSE("Dual BSD/GPL");
2598 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");