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