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