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