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