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