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