OSDN Git Service

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