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