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