zsmalloc: fix obj_to_head use page_private(page) as value but not pointer
[firefly-linux-kernel-4.4.55.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->first_page: points to the first component (0-order) page
20  *      page->index (union with page->freelist): offset of the first object
21  *              starting in this page. For the first page, this is
22  *              always 0, so we use this field (aka freelist) to point
23  *              to the first free object in zspage.
24  *      page->lru: links together all component pages (except the first page)
25  *              of a zspage
26  *
27  *      For _first_ page only:
28  *
29  *      page->private (union with page->first_page): refers to the
30  *              component page after the first page
31  *              If the page is first_page for huge object, it stores handle.
32  *              Look at size_class->huge.
33  *      page->freelist: points to the first free object in zspage.
34  *              Free objects are linked together using in-place
35  *              metadata.
36  *      page->objects: maximum number of objects we can store in this
37  *              zspage (class->zspage_order * PAGE_SIZE / class->size)
38  *      page->lru: links together first pages of various zspages.
39  *              Basically forming list of zspages in a fullness group.
40  *      page->mapping: class index and fullness group of the zspage
41  *      page->inuse: the number of objects that are used in this zspage
42  *
43  * Usage of struct page flags:
44  *      PG_private: identifies the first component page
45  *      PG_private2: identifies the last component page
46  *
47  */
48
49 #include <linux/module.h>
50 #include <linux/kernel.h>
51 #include <linux/sched.h>
52 #include <linux/bitops.h>
53 #include <linux/errno.h>
54 #include <linux/highmem.h>
55 #include <linux/string.h>
56 #include <linux/slab.h>
57 #include <asm/tlbflush.h>
58 #include <asm/pgtable.h>
59 #include <linux/cpumask.h>
60 #include <linux/cpu.h>
61 #include <linux/vmalloc.h>
62 #include <linux/hardirq.h>
63 #include <linux/spinlock.h>
64 #include <linux/types.h>
65 #include <linux/debugfs.h>
66 #include <linux/zsmalloc.h>
67 #include <linux/zpool.h>
68
69 /*
70  * This must be power of 2 and greater than of equal to sizeof(link_free).
71  * These two conditions ensure that any 'struct link_free' itself doesn't
72  * span more than 1 page which avoids complex case of mapping 2 pages simply
73  * to restore link_free pointer values.
74  */
75 #define ZS_ALIGN                8
76
77 /*
78  * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
79  * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
80  */
81 #define ZS_MAX_ZSPAGE_ORDER 2
82 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
83
84 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
85
86 /*
87  * Object location (<PFN>, <obj_idx>) is encoded as
88  * as single (unsigned long) handle value.
89  *
90  * Note that object index <obj_idx> is relative to system
91  * page <PFN> it is stored in, so for each sub-page belonging
92  * to a zspage, obj_idx starts with 0.
93  *
94  * This is made more complicated by various memory models and PAE.
95  */
96
97 #ifndef MAX_PHYSMEM_BITS
98 #ifdef CONFIG_HIGHMEM64G
99 #define MAX_PHYSMEM_BITS 36
100 #else /* !CONFIG_HIGHMEM64G */
101 /*
102  * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
103  * be PAGE_SHIFT
104  */
105 #define MAX_PHYSMEM_BITS BITS_PER_LONG
106 #endif
107 #endif
108 #define _PFN_BITS               (MAX_PHYSMEM_BITS - PAGE_SHIFT)
109
110 /*
111  * Memory for allocating for handle keeps object position by
112  * encoding <page, obj_idx> and the encoded value has a room
113  * in least bit(ie, look at obj_to_location).
114  * We use the bit to synchronize between object access by
115  * user and migration.
116  */
117 #define HANDLE_PIN_BIT  0
118
119 /*
120  * Head in allocated object should have OBJ_ALLOCATED_TAG
121  * to identify the object was allocated or not.
122  * It's okay to add the status bit in the least bit because
123  * header keeps handle which is 4byte-aligned address so we
124  * have room for two bit at least.
125  */
126 #define OBJ_ALLOCATED_TAG 1
127 #define OBJ_TAG_BITS 1
128 #define OBJ_INDEX_BITS  (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
129 #define OBJ_INDEX_MASK  ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
130
131 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
132 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
133 #define ZS_MIN_ALLOC_SIZE \
134         MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
135 /* each chunk includes extra space to keep handle */
136 #define ZS_MAX_ALLOC_SIZE       PAGE_SIZE
137
138 /*
139  * On systems with 4K page size, this gives 255 size classes! There is a
140  * trader-off here:
141  *  - Large number of size classes is potentially wasteful as free page are
142  *    spread across these classes
143  *  - Small number of size classes causes large internal fragmentation
144  *  - Probably its better to use specific size classes (empirically
145  *    determined). NOTE: all those class sizes must be set as multiple of
146  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
147  *
148  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
149  *  (reason above)
150  */
151 #define ZS_SIZE_CLASS_DELTA     (PAGE_SIZE >> 8)
152
153 /*
154  * We do not maintain any list for completely empty or full pages
155  */
156 enum fullness_group {
157         ZS_ALMOST_FULL,
158         ZS_ALMOST_EMPTY,
159         _ZS_NR_FULLNESS_GROUPS,
160
161         ZS_EMPTY,
162         ZS_FULL
163 };
164
165 enum zs_stat_type {
166         OBJ_ALLOCATED,
167         OBJ_USED,
168         CLASS_ALMOST_FULL,
169         CLASS_ALMOST_EMPTY,
170         NR_ZS_STAT_TYPE,
171 };
172
173 struct zs_size_stat {
174         unsigned long objs[NR_ZS_STAT_TYPE];
175 };
176
177 #ifdef CONFIG_ZSMALLOC_STAT
178 static struct dentry *zs_stat_root;
179 #endif
180
181 /*
182  * number of size_classes
183  */
184 static int zs_size_classes;
185
186 /*
187  * We assign a page to ZS_ALMOST_EMPTY fullness group when:
188  *      n <= N / f, where
189  * n = number of allocated objects
190  * N = total number of objects zspage can store
191  * f = fullness_threshold_frac
192  *
193  * Similarly, we assign zspage to:
194  *      ZS_ALMOST_FULL  when n > N / f
195  *      ZS_EMPTY        when n == 0
196  *      ZS_FULL         when n == N
197  *
198  * (see: fix_fullness_group())
199  */
200 static const int fullness_threshold_frac = 4;
201
202 struct size_class {
203         spinlock_t lock;
204         struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
205         /*
206          * Size of objects stored in this class. Must be multiple
207          * of ZS_ALIGN.
208          */
209         int size;
210         unsigned int index;
211
212         /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
213         int pages_per_zspage;
214         struct zs_size_stat stats;
215
216         /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
217         bool huge;
218 };
219
220 /*
221  * Placed within free objects to form a singly linked list.
222  * For every zspage, first_page->freelist gives head of this list.
223  *
224  * This must be power of 2 and less than or equal to ZS_ALIGN
225  */
226 struct link_free {
227         union {
228                 /*
229                  * Position of next free chunk (encodes <PFN, obj_idx>)
230                  * It's valid for non-allocated object
231                  */
232                 void *next;
233                 /*
234                  * Handle of allocated object.
235                  */
236                 unsigned long handle;
237         };
238 };
239
240 struct zs_pool {
241         const char *name;
242
243         struct size_class **size_class;
244         struct kmem_cache *handle_cachep;
245
246         gfp_t flags;    /* allocation flags used when growing pool */
247         atomic_long_t pages_allocated;
248
249         struct zs_pool_stats stats;
250
251         /* Compact classes */
252         struct shrinker shrinker;
253         /*
254          * To signify that register_shrinker() was successful
255          * and unregister_shrinker() will not Oops.
256          */
257         bool shrinker_enabled;
258 #ifdef CONFIG_ZSMALLOC_STAT
259         struct dentry *stat_dentry;
260 #endif
261 };
262
263 /*
264  * A zspage's class index and fullness group
265  * are encoded in its (first)page->mapping
266  */
267 #define CLASS_IDX_BITS  28
268 #define FULLNESS_BITS   4
269 #define CLASS_IDX_MASK  ((1 << CLASS_IDX_BITS) - 1)
270 #define FULLNESS_MASK   ((1 << FULLNESS_BITS) - 1)
271
272 struct mapping_area {
273 #ifdef CONFIG_PGTABLE_MAPPING
274         struct vm_struct *vm; /* vm area for mapping object that span pages */
275 #else
276         char *vm_buf; /* copy buffer for objects that span pages */
277 #endif
278         char *vm_addr; /* address of kmap_atomic()'ed pages */
279         enum zs_mapmode vm_mm; /* mapping mode */
280         bool huge;
281 };
282
283 static int create_handle_cache(struct zs_pool *pool)
284 {
285         pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
286                                         0, 0, NULL);
287         return pool->handle_cachep ? 0 : 1;
288 }
289
290 static void destroy_handle_cache(struct zs_pool *pool)
291 {
292         kmem_cache_destroy(pool->handle_cachep);
293 }
294
295 static unsigned long alloc_handle(struct zs_pool *pool)
296 {
297         return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
298                 pool->flags & ~__GFP_HIGHMEM);
299 }
300
301 static void free_handle(struct zs_pool *pool, unsigned long handle)
302 {
303         kmem_cache_free(pool->handle_cachep, (void *)handle);
304 }
305
306 static void record_obj(unsigned long handle, unsigned long obj)
307 {
308         *(unsigned long *)handle = obj;
309 }
310
311 /* zpool driver */
312
313 #ifdef CONFIG_ZPOOL
314
315 static void *zs_zpool_create(const char *name, gfp_t gfp,
316                              const struct zpool_ops *zpool_ops,
317                              struct zpool *zpool)
318 {
319         return zs_create_pool(name, gfp);
320 }
321
322 static void zs_zpool_destroy(void *pool)
323 {
324         zs_destroy_pool(pool);
325 }
326
327 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
328                         unsigned long *handle)
329 {
330         *handle = zs_malloc(pool, size);
331         return *handle ? 0 : -1;
332 }
333 static void zs_zpool_free(void *pool, unsigned long handle)
334 {
335         zs_free(pool, handle);
336 }
337
338 static int zs_zpool_shrink(void *pool, unsigned int pages,
339                         unsigned int *reclaimed)
340 {
341         return -EINVAL;
342 }
343
344 static void *zs_zpool_map(void *pool, unsigned long handle,
345                         enum zpool_mapmode mm)
346 {
347         enum zs_mapmode zs_mm;
348
349         switch (mm) {
350         case ZPOOL_MM_RO:
351                 zs_mm = ZS_MM_RO;
352                 break;
353         case ZPOOL_MM_WO:
354                 zs_mm = ZS_MM_WO;
355                 break;
356         case ZPOOL_MM_RW: /* fallthru */
357         default:
358                 zs_mm = ZS_MM_RW;
359                 break;
360         }
361
362         return zs_map_object(pool, handle, zs_mm);
363 }
364 static void zs_zpool_unmap(void *pool, unsigned long handle)
365 {
366         zs_unmap_object(pool, handle);
367 }
368
369 static u64 zs_zpool_total_size(void *pool)
370 {
371         return zs_get_total_pages(pool) << PAGE_SHIFT;
372 }
373
374 static struct zpool_driver zs_zpool_driver = {
375         .type =         "zsmalloc",
376         .owner =        THIS_MODULE,
377         .create =       zs_zpool_create,
378         .destroy =      zs_zpool_destroy,
379         .malloc =       zs_zpool_malloc,
380         .free =         zs_zpool_free,
381         .shrink =       zs_zpool_shrink,
382         .map =          zs_zpool_map,
383         .unmap =        zs_zpool_unmap,
384         .total_size =   zs_zpool_total_size,
385 };
386
387 MODULE_ALIAS("zpool-zsmalloc");
388 #endif /* CONFIG_ZPOOL */
389
390 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
391 {
392         return pages_per_zspage * PAGE_SIZE / size;
393 }
394
395 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
396 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
397
398 static int is_first_page(struct page *page)
399 {
400         return PagePrivate(page);
401 }
402
403 static int is_last_page(struct page *page)
404 {
405         return PagePrivate2(page);
406 }
407
408 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
409                                 enum fullness_group *fullness)
410 {
411         unsigned long m;
412         BUG_ON(!is_first_page(page));
413
414         m = (unsigned long)page->mapping;
415         *fullness = m & FULLNESS_MASK;
416         *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
417 }
418
419 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
420                                 enum fullness_group fullness)
421 {
422         unsigned long m;
423         BUG_ON(!is_first_page(page));
424
425         m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
426                         (fullness & FULLNESS_MASK);
427         page->mapping = (struct address_space *)m;
428 }
429
430 /*
431  * zsmalloc divides the pool into various size classes where each
432  * class maintains a list of zspages where each zspage is divided
433  * into equal sized chunks. Each allocation falls into one of these
434  * classes depending on its size. This function returns index of the
435  * size class which has chunk size big enough to hold the give size.
436  */
437 static int get_size_class_index(int size)
438 {
439         int idx = 0;
440
441         if (likely(size > ZS_MIN_ALLOC_SIZE))
442                 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
443                                 ZS_SIZE_CLASS_DELTA);
444
445         return min(zs_size_classes - 1, idx);
446 }
447
448 static inline void zs_stat_inc(struct size_class *class,
449                                 enum zs_stat_type type, unsigned long cnt)
450 {
451         class->stats.objs[type] += cnt;
452 }
453
454 static inline void zs_stat_dec(struct size_class *class,
455                                 enum zs_stat_type type, unsigned long cnt)
456 {
457         class->stats.objs[type] -= cnt;
458 }
459
460 static inline unsigned long zs_stat_get(struct size_class *class,
461                                 enum zs_stat_type type)
462 {
463         return class->stats.objs[type];
464 }
465
466 #ifdef CONFIG_ZSMALLOC_STAT
467
468 static int __init zs_stat_init(void)
469 {
470         if (!debugfs_initialized())
471                 return -ENODEV;
472
473         zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
474         if (!zs_stat_root)
475                 return -ENOMEM;
476
477         return 0;
478 }
479
480 static void __exit zs_stat_exit(void)
481 {
482         debugfs_remove_recursive(zs_stat_root);
483 }
484
485 static int zs_stats_size_show(struct seq_file *s, void *v)
486 {
487         int i;
488         struct zs_pool *pool = s->private;
489         struct size_class *class;
490         int objs_per_zspage;
491         unsigned long class_almost_full, class_almost_empty;
492         unsigned long obj_allocated, obj_used, pages_used;
493         unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
494         unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
495
496         seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s\n",
497                         "class", "size", "almost_full", "almost_empty",
498                         "obj_allocated", "obj_used", "pages_used",
499                         "pages_per_zspage");
500
501         for (i = 0; i < zs_size_classes; i++) {
502                 class = pool->size_class[i];
503
504                 if (class->index != i)
505                         continue;
506
507                 spin_lock(&class->lock);
508                 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
509                 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
510                 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
511                 obj_used = zs_stat_get(class, OBJ_USED);
512                 spin_unlock(&class->lock);
513
514                 objs_per_zspage = get_maxobj_per_zspage(class->size,
515                                 class->pages_per_zspage);
516                 pages_used = obj_allocated / objs_per_zspage *
517                                 class->pages_per_zspage;
518
519                 seq_printf(s, " %5u %5u %11lu %12lu %13lu %10lu %10lu %16d\n",
520                         i, class->size, class_almost_full, class_almost_empty,
521                         obj_allocated, obj_used, pages_used,
522                         class->pages_per_zspage);
523
524                 total_class_almost_full += class_almost_full;
525                 total_class_almost_empty += class_almost_empty;
526                 total_objs += obj_allocated;
527                 total_used_objs += obj_used;
528                 total_pages += pages_used;
529         }
530
531         seq_puts(s, "\n");
532         seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu\n",
533                         "Total", "", total_class_almost_full,
534                         total_class_almost_empty, total_objs,
535                         total_used_objs, total_pages);
536
537         return 0;
538 }
539
540 static int zs_stats_size_open(struct inode *inode, struct file *file)
541 {
542         return single_open(file, zs_stats_size_show, inode->i_private);
543 }
544
545 static const struct file_operations zs_stat_size_ops = {
546         .open           = zs_stats_size_open,
547         .read           = seq_read,
548         .llseek         = seq_lseek,
549         .release        = single_release,
550 };
551
552 static int zs_pool_stat_create(const char *name, struct zs_pool *pool)
553 {
554         struct dentry *entry;
555
556         if (!zs_stat_root)
557                 return -ENODEV;
558
559         entry = debugfs_create_dir(name, zs_stat_root);
560         if (!entry) {
561                 pr_warn("debugfs dir <%s> creation failed\n", name);
562                 return -ENOMEM;
563         }
564         pool->stat_dentry = entry;
565
566         entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
567                         pool->stat_dentry, pool, &zs_stat_size_ops);
568         if (!entry) {
569                 pr_warn("%s: debugfs file entry <%s> creation failed\n",
570                                 name, "classes");
571                 return -ENOMEM;
572         }
573
574         return 0;
575 }
576
577 static void zs_pool_stat_destroy(struct zs_pool *pool)
578 {
579         debugfs_remove_recursive(pool->stat_dentry);
580 }
581
582 #else /* CONFIG_ZSMALLOC_STAT */
583 static int __init zs_stat_init(void)
584 {
585         return 0;
586 }
587
588 static void __exit zs_stat_exit(void)
589 {
590 }
591
592 static inline int zs_pool_stat_create(const char *name, struct zs_pool *pool)
593 {
594         return 0;
595 }
596
597 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
598 {
599 }
600 #endif
601
602
603 /*
604  * For each size class, zspages are divided into different groups
605  * depending on how "full" they are. This was done so that we could
606  * easily find empty or nearly empty zspages when we try to shrink
607  * the pool (not yet implemented). This function returns fullness
608  * status of the given page.
609  */
610 static enum fullness_group get_fullness_group(struct page *page)
611 {
612         int inuse, max_objects;
613         enum fullness_group fg;
614         BUG_ON(!is_first_page(page));
615
616         inuse = page->inuse;
617         max_objects = page->objects;
618
619         if (inuse == 0)
620                 fg = ZS_EMPTY;
621         else if (inuse == max_objects)
622                 fg = ZS_FULL;
623         else if (inuse <= 3 * max_objects / fullness_threshold_frac)
624                 fg = ZS_ALMOST_EMPTY;
625         else
626                 fg = ZS_ALMOST_FULL;
627
628         return fg;
629 }
630
631 /*
632  * Each size class maintains various freelists and zspages are assigned
633  * to one of these freelists based on the number of live objects they
634  * have. This functions inserts the given zspage into the freelist
635  * identified by <class, fullness_group>.
636  */
637 static void insert_zspage(struct page *page, struct size_class *class,
638                                 enum fullness_group fullness)
639 {
640         struct page **head;
641
642         BUG_ON(!is_first_page(page));
643
644         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
645                 return;
646
647         zs_stat_inc(class, fullness == ZS_ALMOST_EMPTY ?
648                         CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
649
650         head = &class->fullness_list[fullness];
651         if (!*head) {
652                 *head = page;
653                 return;
654         }
655
656         /*
657          * We want to see more ZS_FULL pages and less almost
658          * empty/full. Put pages with higher ->inuse first.
659          */
660         list_add_tail(&page->lru, &(*head)->lru);
661         if (page->inuse >= (*head)->inuse)
662                 *head = page;
663 }
664
665 /*
666  * This function removes the given zspage from the freelist identified
667  * by <class, fullness_group>.
668  */
669 static void remove_zspage(struct page *page, struct size_class *class,
670                                 enum fullness_group fullness)
671 {
672         struct page **head;
673
674         BUG_ON(!is_first_page(page));
675
676         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
677                 return;
678
679         head = &class->fullness_list[fullness];
680         BUG_ON(!*head);
681         if (list_empty(&(*head)->lru))
682                 *head = NULL;
683         else if (*head == page)
684                 *head = (struct page *)list_entry((*head)->lru.next,
685                                         struct page, lru);
686
687         list_del_init(&page->lru);
688         zs_stat_dec(class, fullness == ZS_ALMOST_EMPTY ?
689                         CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
690 }
691
692 /*
693  * Each size class maintains zspages in different fullness groups depending
694  * on the number of live objects they contain. When allocating or freeing
695  * objects, the fullness status of the page can change, say, from ALMOST_FULL
696  * to ALMOST_EMPTY when freeing an object. This function checks if such
697  * a status change has occurred for the given page and accordingly moves the
698  * page from the freelist of the old fullness group to that of the new
699  * fullness group.
700  */
701 static enum fullness_group fix_fullness_group(struct size_class *class,
702                                                 struct page *page)
703 {
704         int class_idx;
705         enum fullness_group currfg, newfg;
706
707         BUG_ON(!is_first_page(page));
708
709         get_zspage_mapping(page, &class_idx, &currfg);
710         newfg = get_fullness_group(page);
711         if (newfg == currfg)
712                 goto out;
713
714         remove_zspage(page, class, currfg);
715         insert_zspage(page, class, newfg);
716         set_zspage_mapping(page, class_idx, newfg);
717
718 out:
719         return newfg;
720 }
721
722 /*
723  * We have to decide on how many pages to link together
724  * to form a zspage for each size class. This is important
725  * to reduce wastage due to unusable space left at end of
726  * each zspage which is given as:
727  *     wastage = Zp % class_size
728  *     usage = Zp - wastage
729  * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
730  *
731  * For example, for size class of 3/8 * PAGE_SIZE, we should
732  * link together 3 PAGE_SIZE sized pages to form a zspage
733  * since then we can perfectly fit in 8 such objects.
734  */
735 static int get_pages_per_zspage(int class_size)
736 {
737         int i, max_usedpc = 0;
738         /* zspage order which gives maximum used size per KB */
739         int max_usedpc_order = 1;
740
741         for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
742                 int zspage_size;
743                 int waste, usedpc;
744
745                 zspage_size = i * PAGE_SIZE;
746                 waste = zspage_size % class_size;
747                 usedpc = (zspage_size - waste) * 100 / zspage_size;
748
749                 if (usedpc > max_usedpc) {
750                         max_usedpc = usedpc;
751                         max_usedpc_order = i;
752                 }
753         }
754
755         return max_usedpc_order;
756 }
757
758 /*
759  * A single 'zspage' is composed of many system pages which are
760  * linked together using fields in struct page. This function finds
761  * the first/head page, given any component page of a zspage.
762  */
763 static struct page *get_first_page(struct page *page)
764 {
765         if (is_first_page(page))
766                 return page;
767         else
768                 return page->first_page;
769 }
770
771 static struct page *get_next_page(struct page *page)
772 {
773         struct page *next;
774
775         if (is_last_page(page))
776                 next = NULL;
777         else if (is_first_page(page))
778                 next = (struct page *)page_private(page);
779         else
780                 next = list_entry(page->lru.next, struct page, lru);
781
782         return next;
783 }
784
785 /*
786  * Encode <page, obj_idx> as a single handle value.
787  * We use the least bit of handle for tagging.
788  */
789 static void *location_to_obj(struct page *page, unsigned long obj_idx)
790 {
791         unsigned long obj;
792
793         if (!page) {
794                 BUG_ON(obj_idx);
795                 return NULL;
796         }
797
798         obj = page_to_pfn(page) << OBJ_INDEX_BITS;
799         obj |= ((obj_idx) & OBJ_INDEX_MASK);
800         obj <<= OBJ_TAG_BITS;
801
802         return (void *)obj;
803 }
804
805 /*
806  * Decode <page, obj_idx> pair from the given object handle. We adjust the
807  * decoded obj_idx back to its original value since it was adjusted in
808  * location_to_obj().
809  */
810 static void obj_to_location(unsigned long obj, struct page **page,
811                                 unsigned long *obj_idx)
812 {
813         obj >>= OBJ_TAG_BITS;
814         *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
815         *obj_idx = (obj & OBJ_INDEX_MASK);
816 }
817
818 static unsigned long handle_to_obj(unsigned long handle)
819 {
820         return *(unsigned long *)handle;
821 }
822
823 static unsigned long obj_to_head(struct size_class *class, struct page *page,
824                         void *obj)
825 {
826         if (class->huge) {
827                 VM_BUG_ON(!is_first_page(page));
828                 return page_private(page);
829         } else
830                 return *(unsigned long *)obj;
831 }
832
833 static unsigned long obj_idx_to_offset(struct page *page,
834                                 unsigned long obj_idx, int class_size)
835 {
836         unsigned long off = 0;
837
838         if (!is_first_page(page))
839                 off = page->index;
840
841         return off + obj_idx * class_size;
842 }
843
844 static inline int trypin_tag(unsigned long handle)
845 {
846         unsigned long *ptr = (unsigned long *)handle;
847
848         return !test_and_set_bit_lock(HANDLE_PIN_BIT, ptr);
849 }
850
851 static void pin_tag(unsigned long handle)
852 {
853         while (!trypin_tag(handle));
854 }
855
856 static void unpin_tag(unsigned long handle)
857 {
858         unsigned long *ptr = (unsigned long *)handle;
859
860         clear_bit_unlock(HANDLE_PIN_BIT, ptr);
861 }
862
863 static void reset_page(struct page *page)
864 {
865         clear_bit(PG_private, &page->flags);
866         clear_bit(PG_private_2, &page->flags);
867         set_page_private(page, 0);
868         page->mapping = NULL;
869         page->freelist = NULL;
870         page_mapcount_reset(page);
871 }
872
873 static void free_zspage(struct page *first_page)
874 {
875         struct page *nextp, *tmp, *head_extra;
876
877         BUG_ON(!is_first_page(first_page));
878         BUG_ON(first_page->inuse);
879
880         head_extra = (struct page *)page_private(first_page);
881
882         reset_page(first_page);
883         __free_page(first_page);
884
885         /* zspage with only 1 system page */
886         if (!head_extra)
887                 return;
888
889         list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
890                 list_del(&nextp->lru);
891                 reset_page(nextp);
892                 __free_page(nextp);
893         }
894         reset_page(head_extra);
895         __free_page(head_extra);
896 }
897
898 /* Initialize a newly allocated zspage */
899 static void init_zspage(struct page *first_page, struct size_class *class)
900 {
901         unsigned long off = 0;
902         struct page *page = first_page;
903
904         BUG_ON(!is_first_page(first_page));
905         while (page) {
906                 struct page *next_page;
907                 struct link_free *link;
908                 unsigned int i = 1;
909                 void *vaddr;
910
911                 /*
912                  * page->index stores offset of first object starting
913                  * in the page. For the first page, this is always 0,
914                  * so we use first_page->index (aka ->freelist) to store
915                  * head of corresponding zspage's freelist.
916                  */
917                 if (page != first_page)
918                         page->index = off;
919
920                 vaddr = kmap_atomic(page);
921                 link = (struct link_free *)vaddr + off / sizeof(*link);
922
923                 while ((off += class->size) < PAGE_SIZE) {
924                         link->next = location_to_obj(page, i++);
925                         link += class->size / sizeof(*link);
926                 }
927
928                 /*
929                  * We now come to the last (full or partial) object on this
930                  * page, which must point to the first object on the next
931                  * page (if present)
932                  */
933                 next_page = get_next_page(page);
934                 link->next = location_to_obj(next_page, 0);
935                 kunmap_atomic(vaddr);
936                 page = next_page;
937                 off %= PAGE_SIZE;
938         }
939 }
940
941 /*
942  * Allocate a zspage for the given size class
943  */
944 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
945 {
946         int i, error;
947         struct page *first_page = NULL, *uninitialized_var(prev_page);
948
949         /*
950          * Allocate individual pages and link them together as:
951          * 1. first page->private = first sub-page
952          * 2. all sub-pages are linked together using page->lru
953          * 3. each sub-page is linked to the first page using page->first_page
954          *
955          * For each size class, First/Head pages are linked together using
956          * page->lru. Also, we set PG_private to identify the first page
957          * (i.e. no other sub-page has this flag set) and PG_private_2 to
958          * identify the last page.
959          */
960         error = -ENOMEM;
961         for (i = 0; i < class->pages_per_zspage; i++) {
962                 struct page *page;
963
964                 page = alloc_page(flags);
965                 if (!page)
966                         goto cleanup;
967
968                 INIT_LIST_HEAD(&page->lru);
969                 if (i == 0) {   /* first page */
970                         SetPagePrivate(page);
971                         set_page_private(page, 0);
972                         first_page = page;
973                         first_page->inuse = 0;
974                 }
975                 if (i == 1)
976                         set_page_private(first_page, (unsigned long)page);
977                 if (i >= 1)
978                         page->first_page = first_page;
979                 if (i >= 2)
980                         list_add(&page->lru, &prev_page->lru);
981                 if (i == class->pages_per_zspage - 1)   /* last page */
982                         SetPagePrivate2(page);
983                 prev_page = page;
984         }
985
986         init_zspage(first_page, class);
987
988         first_page->freelist = location_to_obj(first_page, 0);
989         /* Maximum number of objects we can store in this zspage */
990         first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
991
992         error = 0; /* Success */
993
994 cleanup:
995         if (unlikely(error) && first_page) {
996                 free_zspage(first_page);
997                 first_page = NULL;
998         }
999
1000         return first_page;
1001 }
1002
1003 static struct page *find_get_zspage(struct size_class *class)
1004 {
1005         int i;
1006         struct page *page;
1007
1008         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1009                 page = class->fullness_list[i];
1010                 if (page)
1011                         break;
1012         }
1013
1014         return page;
1015 }
1016
1017 #ifdef CONFIG_PGTABLE_MAPPING
1018 static inline int __zs_cpu_up(struct mapping_area *area)
1019 {
1020         /*
1021          * Make sure we don't leak memory if a cpu UP notification
1022          * and zs_init() race and both call zs_cpu_up() on the same cpu
1023          */
1024         if (area->vm)
1025                 return 0;
1026         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1027         if (!area->vm)
1028                 return -ENOMEM;
1029         return 0;
1030 }
1031
1032 static inline void __zs_cpu_down(struct mapping_area *area)
1033 {
1034         if (area->vm)
1035                 free_vm_area(area->vm);
1036         area->vm = NULL;
1037 }
1038
1039 static inline void *__zs_map_object(struct mapping_area *area,
1040                                 struct page *pages[2], int off, int size)
1041 {
1042         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1043         area->vm_addr = area->vm->addr;
1044         return area->vm_addr + off;
1045 }
1046
1047 static inline void __zs_unmap_object(struct mapping_area *area,
1048                                 struct page *pages[2], int off, int size)
1049 {
1050         unsigned long addr = (unsigned long)area->vm_addr;
1051
1052         unmap_kernel_range(addr, PAGE_SIZE * 2);
1053 }
1054
1055 #else /* CONFIG_PGTABLE_MAPPING */
1056
1057 static inline int __zs_cpu_up(struct mapping_area *area)
1058 {
1059         /*
1060          * Make sure we don't leak memory if a cpu UP notification
1061          * and zs_init() race and both call zs_cpu_up() on the same cpu
1062          */
1063         if (area->vm_buf)
1064                 return 0;
1065         area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1066         if (!area->vm_buf)
1067                 return -ENOMEM;
1068         return 0;
1069 }
1070
1071 static inline void __zs_cpu_down(struct mapping_area *area)
1072 {
1073         kfree(area->vm_buf);
1074         area->vm_buf = NULL;
1075 }
1076
1077 static void *__zs_map_object(struct mapping_area *area,
1078                         struct page *pages[2], int off, int size)
1079 {
1080         int sizes[2];
1081         void *addr;
1082         char *buf = area->vm_buf;
1083
1084         /* disable page faults to match kmap_atomic() return conditions */
1085         pagefault_disable();
1086
1087         /* no read fastpath */
1088         if (area->vm_mm == ZS_MM_WO)
1089                 goto out;
1090
1091         sizes[0] = PAGE_SIZE - off;
1092         sizes[1] = size - sizes[0];
1093
1094         /* copy object to per-cpu buffer */
1095         addr = kmap_atomic(pages[0]);
1096         memcpy(buf, addr + off, sizes[0]);
1097         kunmap_atomic(addr);
1098         addr = kmap_atomic(pages[1]);
1099         memcpy(buf + sizes[0], addr, sizes[1]);
1100         kunmap_atomic(addr);
1101 out:
1102         return area->vm_buf;
1103 }
1104
1105 static void __zs_unmap_object(struct mapping_area *area,
1106                         struct page *pages[2], int off, int size)
1107 {
1108         int sizes[2];
1109         void *addr;
1110         char *buf;
1111
1112         /* no write fastpath */
1113         if (area->vm_mm == ZS_MM_RO)
1114                 goto out;
1115
1116         buf = area->vm_buf;
1117         if (!area->huge) {
1118                 buf = buf + ZS_HANDLE_SIZE;
1119                 size -= ZS_HANDLE_SIZE;
1120                 off += ZS_HANDLE_SIZE;
1121         }
1122
1123         sizes[0] = PAGE_SIZE - off;
1124         sizes[1] = size - sizes[0];
1125
1126         /* copy per-cpu buffer to object */
1127         addr = kmap_atomic(pages[0]);
1128         memcpy(addr + off, buf, sizes[0]);
1129         kunmap_atomic(addr);
1130         addr = kmap_atomic(pages[1]);
1131         memcpy(addr, buf + sizes[0], sizes[1]);
1132         kunmap_atomic(addr);
1133
1134 out:
1135         /* enable page faults to match kunmap_atomic() return conditions */
1136         pagefault_enable();
1137 }
1138
1139 #endif /* CONFIG_PGTABLE_MAPPING */
1140
1141 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
1142                                 void *pcpu)
1143 {
1144         int ret, cpu = (long)pcpu;
1145         struct mapping_area *area;
1146
1147         switch (action) {
1148         case CPU_UP_PREPARE:
1149                 area = &per_cpu(zs_map_area, cpu);
1150                 ret = __zs_cpu_up(area);
1151                 if (ret)
1152                         return notifier_from_errno(ret);
1153                 break;
1154         case CPU_DEAD:
1155         case CPU_UP_CANCELED:
1156                 area = &per_cpu(zs_map_area, cpu);
1157                 __zs_cpu_down(area);
1158                 break;
1159         }
1160
1161         return NOTIFY_OK;
1162 }
1163
1164 static struct notifier_block zs_cpu_nb = {
1165         .notifier_call = zs_cpu_notifier
1166 };
1167
1168 static int zs_register_cpu_notifier(void)
1169 {
1170         int cpu, uninitialized_var(ret);
1171
1172         cpu_notifier_register_begin();
1173
1174         __register_cpu_notifier(&zs_cpu_nb);
1175         for_each_online_cpu(cpu) {
1176                 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1177                 if (notifier_to_errno(ret))
1178                         break;
1179         }
1180
1181         cpu_notifier_register_done();
1182         return notifier_to_errno(ret);
1183 }
1184
1185 static void zs_unregister_cpu_notifier(void)
1186 {
1187         int cpu;
1188
1189         cpu_notifier_register_begin();
1190
1191         for_each_online_cpu(cpu)
1192                 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1193         __unregister_cpu_notifier(&zs_cpu_nb);
1194
1195         cpu_notifier_register_done();
1196 }
1197
1198 static void init_zs_size_classes(void)
1199 {
1200         int nr;
1201
1202         nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
1203         if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1204                 nr += 1;
1205
1206         zs_size_classes = nr;
1207 }
1208
1209 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1210 {
1211         if (prev->pages_per_zspage != pages_per_zspage)
1212                 return false;
1213
1214         if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1215                 != get_maxobj_per_zspage(size, pages_per_zspage))
1216                 return false;
1217
1218         return true;
1219 }
1220
1221 static bool zspage_full(struct page *page)
1222 {
1223         BUG_ON(!is_first_page(page));
1224
1225         return page->inuse == page->objects;
1226 }
1227
1228 unsigned long zs_get_total_pages(struct zs_pool *pool)
1229 {
1230         return atomic_long_read(&pool->pages_allocated);
1231 }
1232 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1233
1234 /**
1235  * zs_map_object - get address of allocated object from handle.
1236  * @pool: pool from which the object was allocated
1237  * @handle: handle returned from zs_malloc
1238  *
1239  * Before using an object allocated from zs_malloc, it must be mapped using
1240  * this function. When done with the object, it must be unmapped using
1241  * zs_unmap_object.
1242  *
1243  * Only one object can be mapped per cpu at a time. There is no protection
1244  * against nested mappings.
1245  *
1246  * This function returns with preemption and page faults disabled.
1247  */
1248 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1249                         enum zs_mapmode mm)
1250 {
1251         struct page *page;
1252         unsigned long obj, obj_idx, off;
1253
1254         unsigned int class_idx;
1255         enum fullness_group fg;
1256         struct size_class *class;
1257         struct mapping_area *area;
1258         struct page *pages[2];
1259         void *ret;
1260
1261         BUG_ON(!handle);
1262
1263         /*
1264          * Because we use per-cpu mapping areas shared among the
1265          * pools/users, we can't allow mapping in interrupt context
1266          * because it can corrupt another users mappings.
1267          */
1268         BUG_ON(in_interrupt());
1269
1270         /* From now on, migration cannot move the object */
1271         pin_tag(handle);
1272
1273         obj = handle_to_obj(handle);
1274         obj_to_location(obj, &page, &obj_idx);
1275         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1276         class = pool->size_class[class_idx];
1277         off = obj_idx_to_offset(page, obj_idx, class->size);
1278
1279         area = &get_cpu_var(zs_map_area);
1280         area->vm_mm = mm;
1281         if (off + class->size <= PAGE_SIZE) {
1282                 /* this object is contained entirely within a page */
1283                 area->vm_addr = kmap_atomic(page);
1284                 ret = area->vm_addr + off;
1285                 goto out;
1286         }
1287
1288         /* this object spans two pages */
1289         pages[0] = page;
1290         pages[1] = get_next_page(page);
1291         BUG_ON(!pages[1]);
1292
1293         ret = __zs_map_object(area, pages, off, class->size);
1294 out:
1295         if (!class->huge)
1296                 ret += ZS_HANDLE_SIZE;
1297
1298         return ret;
1299 }
1300 EXPORT_SYMBOL_GPL(zs_map_object);
1301
1302 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1303 {
1304         struct page *page;
1305         unsigned long obj, obj_idx, off;
1306
1307         unsigned int class_idx;
1308         enum fullness_group fg;
1309         struct size_class *class;
1310         struct mapping_area *area;
1311
1312         BUG_ON(!handle);
1313
1314         obj = handle_to_obj(handle);
1315         obj_to_location(obj, &page, &obj_idx);
1316         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1317         class = pool->size_class[class_idx];
1318         off = obj_idx_to_offset(page, obj_idx, class->size);
1319
1320         area = this_cpu_ptr(&zs_map_area);
1321         if (off + class->size <= PAGE_SIZE)
1322                 kunmap_atomic(area->vm_addr);
1323         else {
1324                 struct page *pages[2];
1325
1326                 pages[0] = page;
1327                 pages[1] = get_next_page(page);
1328                 BUG_ON(!pages[1]);
1329
1330                 __zs_unmap_object(area, pages, off, class->size);
1331         }
1332         put_cpu_var(zs_map_area);
1333         unpin_tag(handle);
1334 }
1335 EXPORT_SYMBOL_GPL(zs_unmap_object);
1336
1337 static unsigned long obj_malloc(struct page *first_page,
1338                 struct size_class *class, unsigned long handle)
1339 {
1340         unsigned long obj;
1341         struct link_free *link;
1342
1343         struct page *m_page;
1344         unsigned long m_objidx, m_offset;
1345         void *vaddr;
1346
1347         handle |= OBJ_ALLOCATED_TAG;
1348         obj = (unsigned long)first_page->freelist;
1349         obj_to_location(obj, &m_page, &m_objidx);
1350         m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1351
1352         vaddr = kmap_atomic(m_page);
1353         link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1354         first_page->freelist = link->next;
1355         if (!class->huge)
1356                 /* record handle in the header of allocated chunk */
1357                 link->handle = handle;
1358         else
1359                 /* record handle in first_page->private */
1360                 set_page_private(first_page, handle);
1361         kunmap_atomic(vaddr);
1362         first_page->inuse++;
1363         zs_stat_inc(class, OBJ_USED, 1);
1364
1365         return obj;
1366 }
1367
1368
1369 /**
1370  * zs_malloc - Allocate block of given size from pool.
1371  * @pool: pool to allocate from
1372  * @size: size of block to allocate
1373  *
1374  * On success, handle to the allocated object is returned,
1375  * otherwise 0.
1376  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1377  */
1378 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1379 {
1380         unsigned long handle, obj;
1381         struct size_class *class;
1382         struct page *first_page;
1383
1384         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1385                 return 0;
1386
1387         handle = alloc_handle(pool);
1388         if (!handle)
1389                 return 0;
1390
1391         /* extra space in chunk to keep the handle */
1392         size += ZS_HANDLE_SIZE;
1393         class = pool->size_class[get_size_class_index(size)];
1394
1395         spin_lock(&class->lock);
1396         first_page = find_get_zspage(class);
1397
1398         if (!first_page) {
1399                 spin_unlock(&class->lock);
1400                 first_page = alloc_zspage(class, pool->flags);
1401                 if (unlikely(!first_page)) {
1402                         free_handle(pool, handle);
1403                         return 0;
1404                 }
1405
1406                 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1407                 atomic_long_add(class->pages_per_zspage,
1408                                         &pool->pages_allocated);
1409
1410                 spin_lock(&class->lock);
1411                 zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1412                                 class->size, class->pages_per_zspage));
1413         }
1414
1415         obj = obj_malloc(first_page, class, handle);
1416         /* Now move the zspage to another fullness group, if required */
1417         fix_fullness_group(class, first_page);
1418         record_obj(handle, obj);
1419         spin_unlock(&class->lock);
1420
1421         return handle;
1422 }
1423 EXPORT_SYMBOL_GPL(zs_malloc);
1424
1425 static void obj_free(struct zs_pool *pool, struct size_class *class,
1426                         unsigned long obj)
1427 {
1428         struct link_free *link;
1429         struct page *first_page, *f_page;
1430         unsigned long f_objidx, f_offset;
1431         void *vaddr;
1432         int class_idx;
1433         enum fullness_group fullness;
1434
1435         BUG_ON(!obj);
1436
1437         obj &= ~OBJ_ALLOCATED_TAG;
1438         obj_to_location(obj, &f_page, &f_objidx);
1439         first_page = get_first_page(f_page);
1440
1441         get_zspage_mapping(first_page, &class_idx, &fullness);
1442         f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1443
1444         vaddr = kmap_atomic(f_page);
1445
1446         /* Insert this object in containing zspage's freelist */
1447         link = (struct link_free *)(vaddr + f_offset);
1448         link->next = first_page->freelist;
1449         if (class->huge)
1450                 set_page_private(first_page, 0);
1451         kunmap_atomic(vaddr);
1452         first_page->freelist = (void *)obj;
1453         first_page->inuse--;
1454         zs_stat_dec(class, OBJ_USED, 1);
1455 }
1456
1457 void zs_free(struct zs_pool *pool, unsigned long handle)
1458 {
1459         struct page *first_page, *f_page;
1460         unsigned long obj, f_objidx;
1461         int class_idx;
1462         struct size_class *class;
1463         enum fullness_group fullness;
1464
1465         if (unlikely(!handle))
1466                 return;
1467
1468         pin_tag(handle);
1469         obj = handle_to_obj(handle);
1470         obj_to_location(obj, &f_page, &f_objidx);
1471         first_page = get_first_page(f_page);
1472
1473         get_zspage_mapping(first_page, &class_idx, &fullness);
1474         class = pool->size_class[class_idx];
1475
1476         spin_lock(&class->lock);
1477         obj_free(pool, class, obj);
1478         fullness = fix_fullness_group(class, first_page);
1479         if (fullness == ZS_EMPTY) {
1480                 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1481                                 class->size, class->pages_per_zspage));
1482                 atomic_long_sub(class->pages_per_zspage,
1483                                 &pool->pages_allocated);
1484                 free_zspage(first_page);
1485         }
1486         spin_unlock(&class->lock);
1487         unpin_tag(handle);
1488
1489         free_handle(pool, handle);
1490 }
1491 EXPORT_SYMBOL_GPL(zs_free);
1492
1493 static void zs_object_copy(unsigned long dst, unsigned long src,
1494                                 struct size_class *class)
1495 {
1496         struct page *s_page, *d_page;
1497         unsigned long s_objidx, d_objidx;
1498         unsigned long s_off, d_off;
1499         void *s_addr, *d_addr;
1500         int s_size, d_size, size;
1501         int written = 0;
1502
1503         s_size = d_size = class->size;
1504
1505         obj_to_location(src, &s_page, &s_objidx);
1506         obj_to_location(dst, &d_page, &d_objidx);
1507
1508         s_off = obj_idx_to_offset(s_page, s_objidx, class->size);
1509         d_off = obj_idx_to_offset(d_page, d_objidx, class->size);
1510
1511         if (s_off + class->size > PAGE_SIZE)
1512                 s_size = PAGE_SIZE - s_off;
1513
1514         if (d_off + class->size > PAGE_SIZE)
1515                 d_size = PAGE_SIZE - d_off;
1516
1517         s_addr = kmap_atomic(s_page);
1518         d_addr = kmap_atomic(d_page);
1519
1520         while (1) {
1521                 size = min(s_size, d_size);
1522                 memcpy(d_addr + d_off, s_addr + s_off, size);
1523                 written += size;
1524
1525                 if (written == class->size)
1526                         break;
1527
1528                 s_off += size;
1529                 s_size -= size;
1530                 d_off += size;
1531                 d_size -= size;
1532
1533                 if (s_off >= PAGE_SIZE) {
1534                         kunmap_atomic(d_addr);
1535                         kunmap_atomic(s_addr);
1536                         s_page = get_next_page(s_page);
1537                         BUG_ON(!s_page);
1538                         s_addr = kmap_atomic(s_page);
1539                         d_addr = kmap_atomic(d_page);
1540                         s_size = class->size - written;
1541                         s_off = 0;
1542                 }
1543
1544                 if (d_off >= PAGE_SIZE) {
1545                         kunmap_atomic(d_addr);
1546                         d_page = get_next_page(d_page);
1547                         BUG_ON(!d_page);
1548                         d_addr = kmap_atomic(d_page);
1549                         d_size = class->size - written;
1550                         d_off = 0;
1551                 }
1552         }
1553
1554         kunmap_atomic(d_addr);
1555         kunmap_atomic(s_addr);
1556 }
1557
1558 /*
1559  * Find alloced object in zspage from index object and
1560  * return handle.
1561  */
1562 static unsigned long find_alloced_obj(struct page *page, int index,
1563                                         struct size_class *class)
1564 {
1565         unsigned long head;
1566         int offset = 0;
1567         unsigned long handle = 0;
1568         void *addr = kmap_atomic(page);
1569
1570         if (!is_first_page(page))
1571                 offset = page->index;
1572         offset += class->size * index;
1573
1574         while (offset < PAGE_SIZE) {
1575                 head = obj_to_head(class, page, addr + offset);
1576                 if (head & OBJ_ALLOCATED_TAG) {
1577                         handle = head & ~OBJ_ALLOCATED_TAG;
1578                         if (trypin_tag(handle))
1579                                 break;
1580                         handle = 0;
1581                 }
1582
1583                 offset += class->size;
1584                 index++;
1585         }
1586
1587         kunmap_atomic(addr);
1588         return handle;
1589 }
1590
1591 struct zs_compact_control {
1592         /* Source page for migration which could be a subpage of zspage. */
1593         struct page *s_page;
1594         /* Destination page for migration which should be a first page
1595          * of zspage. */
1596         struct page *d_page;
1597          /* Starting object index within @s_page which used for live object
1598           * in the subpage. */
1599         int index;
1600 };
1601
1602 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1603                                 struct zs_compact_control *cc)
1604 {
1605         unsigned long used_obj, free_obj;
1606         unsigned long handle;
1607         struct page *s_page = cc->s_page;
1608         struct page *d_page = cc->d_page;
1609         unsigned long index = cc->index;
1610         int ret = 0;
1611
1612         while (1) {
1613                 handle = find_alloced_obj(s_page, index, class);
1614                 if (!handle) {
1615                         s_page = get_next_page(s_page);
1616                         if (!s_page)
1617                                 break;
1618                         index = 0;
1619                         continue;
1620                 }
1621
1622                 /* Stop if there is no more space */
1623                 if (zspage_full(d_page)) {
1624                         unpin_tag(handle);
1625                         ret = -ENOMEM;
1626                         break;
1627                 }
1628
1629                 used_obj = handle_to_obj(handle);
1630                 free_obj = obj_malloc(d_page, class, handle);
1631                 zs_object_copy(free_obj, used_obj, class);
1632                 index++;
1633                 record_obj(handle, free_obj);
1634                 unpin_tag(handle);
1635                 obj_free(pool, class, used_obj);
1636         }
1637
1638         /* Remember last position in this iteration */
1639         cc->s_page = s_page;
1640         cc->index = index;
1641
1642         return ret;
1643 }
1644
1645 static struct page *isolate_target_page(struct size_class *class)
1646 {
1647         int i;
1648         struct page *page;
1649
1650         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1651                 page = class->fullness_list[i];
1652                 if (page) {
1653                         remove_zspage(page, class, i);
1654                         break;
1655                 }
1656         }
1657
1658         return page;
1659 }
1660
1661 /*
1662  * putback_zspage - add @first_page into right class's fullness list
1663  * @pool: target pool
1664  * @class: destination class
1665  * @first_page: target page
1666  *
1667  * Return @fist_page's fullness_group
1668  */
1669 static enum fullness_group putback_zspage(struct zs_pool *pool,
1670                         struct size_class *class,
1671                         struct page *first_page)
1672 {
1673         enum fullness_group fullness;
1674
1675         BUG_ON(!is_first_page(first_page));
1676
1677         fullness = get_fullness_group(first_page);
1678         insert_zspage(first_page, class, fullness);
1679         set_zspage_mapping(first_page, class->index, fullness);
1680
1681         if (fullness == ZS_EMPTY) {
1682                 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1683                         class->size, class->pages_per_zspage));
1684                 atomic_long_sub(class->pages_per_zspage,
1685                                 &pool->pages_allocated);
1686
1687                 free_zspage(first_page);
1688         }
1689
1690         return fullness;
1691 }
1692
1693 static struct page *isolate_source_page(struct size_class *class)
1694 {
1695         int i;
1696         struct page *page = NULL;
1697
1698         for (i = ZS_ALMOST_EMPTY; i >= ZS_ALMOST_FULL; i--) {
1699                 page = class->fullness_list[i];
1700                 if (!page)
1701                         continue;
1702
1703                 remove_zspage(page, class, i);
1704                 break;
1705         }
1706
1707         return page;
1708 }
1709
1710 /*
1711  *
1712  * Based on the number of unused allocated objects calculate
1713  * and return the number of pages that we can free.
1714  */
1715 static unsigned long zs_can_compact(struct size_class *class)
1716 {
1717         unsigned long obj_wasted;
1718
1719         obj_wasted = zs_stat_get(class, OBJ_ALLOCATED) -
1720                 zs_stat_get(class, OBJ_USED);
1721
1722         obj_wasted /= get_maxobj_per_zspage(class->size,
1723                         class->pages_per_zspage);
1724
1725         return obj_wasted * class->pages_per_zspage;
1726 }
1727
1728 static void __zs_compact(struct zs_pool *pool, struct size_class *class)
1729 {
1730         struct zs_compact_control cc;
1731         struct page *src_page;
1732         struct page *dst_page = NULL;
1733
1734         spin_lock(&class->lock);
1735         while ((src_page = isolate_source_page(class))) {
1736
1737                 BUG_ON(!is_first_page(src_page));
1738
1739                 if (!zs_can_compact(class))
1740                         break;
1741
1742                 cc.index = 0;
1743                 cc.s_page = src_page;
1744
1745                 while ((dst_page = isolate_target_page(class))) {
1746                         cc.d_page = dst_page;
1747                         /*
1748                          * If there is no more space in dst_page, resched
1749                          * and see if anyone had allocated another zspage.
1750                          */
1751                         if (!migrate_zspage(pool, class, &cc))
1752                                 break;
1753
1754                         putback_zspage(pool, class, dst_page);
1755                 }
1756
1757                 /* Stop if we couldn't find slot */
1758                 if (dst_page == NULL)
1759                         break;
1760
1761                 putback_zspage(pool, class, dst_page);
1762                 if (putback_zspage(pool, class, src_page) == ZS_EMPTY)
1763                         pool->stats.pages_compacted += class->pages_per_zspage;
1764                 spin_unlock(&class->lock);
1765                 cond_resched();
1766                 spin_lock(&class->lock);
1767         }
1768
1769         if (src_page)
1770                 putback_zspage(pool, class, src_page);
1771
1772         spin_unlock(&class->lock);
1773 }
1774
1775 unsigned long zs_compact(struct zs_pool *pool)
1776 {
1777         int i;
1778         struct size_class *class;
1779
1780         for (i = zs_size_classes - 1; i >= 0; i--) {
1781                 class = pool->size_class[i];
1782                 if (!class)
1783                         continue;
1784                 if (class->index != i)
1785                         continue;
1786                 __zs_compact(pool, class);
1787         }
1788
1789         return pool->stats.pages_compacted;
1790 }
1791 EXPORT_SYMBOL_GPL(zs_compact);
1792
1793 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
1794 {
1795         memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
1796 }
1797 EXPORT_SYMBOL_GPL(zs_pool_stats);
1798
1799 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
1800                 struct shrink_control *sc)
1801 {
1802         unsigned long pages_freed;
1803         struct zs_pool *pool = container_of(shrinker, struct zs_pool,
1804                         shrinker);
1805
1806         pages_freed = pool->stats.pages_compacted;
1807         /*
1808          * Compact classes and calculate compaction delta.
1809          * Can run concurrently with a manually triggered
1810          * (by user) compaction.
1811          */
1812         pages_freed = zs_compact(pool) - pages_freed;
1813
1814         return pages_freed ? pages_freed : SHRINK_STOP;
1815 }
1816
1817 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
1818                 struct shrink_control *sc)
1819 {
1820         int i;
1821         struct size_class *class;
1822         unsigned long pages_to_free = 0;
1823         struct zs_pool *pool = container_of(shrinker, struct zs_pool,
1824                         shrinker);
1825
1826         if (!pool->shrinker_enabled)
1827                 return 0;
1828
1829         for (i = zs_size_classes - 1; i >= 0; i--) {
1830                 class = pool->size_class[i];
1831                 if (!class)
1832                         continue;
1833                 if (class->index != i)
1834                         continue;
1835
1836                 pages_to_free += zs_can_compact(class);
1837         }
1838
1839         return pages_to_free;
1840 }
1841
1842 static void zs_unregister_shrinker(struct zs_pool *pool)
1843 {
1844         if (pool->shrinker_enabled) {
1845                 unregister_shrinker(&pool->shrinker);
1846                 pool->shrinker_enabled = false;
1847         }
1848 }
1849
1850 static int zs_register_shrinker(struct zs_pool *pool)
1851 {
1852         pool->shrinker.scan_objects = zs_shrinker_scan;
1853         pool->shrinker.count_objects = zs_shrinker_count;
1854         pool->shrinker.batch = 0;
1855         pool->shrinker.seeks = DEFAULT_SEEKS;
1856
1857         return register_shrinker(&pool->shrinker);
1858 }
1859
1860 /**
1861  * zs_create_pool - Creates an allocation pool to work from.
1862  * @flags: allocation flags used to allocate pool metadata
1863  *
1864  * This function must be called before anything when using
1865  * the zsmalloc allocator.
1866  *
1867  * On success, a pointer to the newly created pool is returned,
1868  * otherwise NULL.
1869  */
1870 struct zs_pool *zs_create_pool(const char *name, gfp_t flags)
1871 {
1872         int i;
1873         struct zs_pool *pool;
1874         struct size_class *prev_class = NULL;
1875
1876         pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1877         if (!pool)
1878                 return NULL;
1879
1880         pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1881                         GFP_KERNEL);
1882         if (!pool->size_class) {
1883                 kfree(pool);
1884                 return NULL;
1885         }
1886
1887         pool->name = kstrdup(name, GFP_KERNEL);
1888         if (!pool->name)
1889                 goto err;
1890
1891         if (create_handle_cache(pool))
1892                 goto err;
1893
1894         /*
1895          * Iterate reversly, because, size of size_class that we want to use
1896          * for merging should be larger or equal to current size.
1897          */
1898         for (i = zs_size_classes - 1; i >= 0; i--) {
1899                 int size;
1900                 int pages_per_zspage;
1901                 struct size_class *class;
1902
1903                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
1904                 if (size > ZS_MAX_ALLOC_SIZE)
1905                         size = ZS_MAX_ALLOC_SIZE;
1906                 pages_per_zspage = get_pages_per_zspage(size);
1907
1908                 /*
1909                  * size_class is used for normal zsmalloc operation such
1910                  * as alloc/free for that size. Although it is natural that we
1911                  * have one size_class for each size, there is a chance that we
1912                  * can get more memory utilization if we use one size_class for
1913                  * many different sizes whose size_class have same
1914                  * characteristics. So, we makes size_class point to
1915                  * previous size_class if possible.
1916                  */
1917                 if (prev_class) {
1918                         if (can_merge(prev_class, size, pages_per_zspage)) {
1919                                 pool->size_class[i] = prev_class;
1920                                 continue;
1921                         }
1922                 }
1923
1924                 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1925                 if (!class)
1926                         goto err;
1927
1928                 class->size = size;
1929                 class->index = i;
1930                 class->pages_per_zspage = pages_per_zspage;
1931                 if (pages_per_zspage == 1 &&
1932                         get_maxobj_per_zspage(size, pages_per_zspage) == 1)
1933                         class->huge = true;
1934                 spin_lock_init(&class->lock);
1935                 pool->size_class[i] = class;
1936
1937                 prev_class = class;
1938         }
1939
1940         pool->flags = flags;
1941
1942         if (zs_pool_stat_create(name, pool))
1943                 goto err;
1944
1945         /*
1946          * Not critical, we still can use the pool
1947          * and user can trigger compaction manually.
1948          */
1949         if (zs_register_shrinker(pool) == 0)
1950                 pool->shrinker_enabled = true;
1951         return pool;
1952
1953 err:
1954         zs_destroy_pool(pool);
1955         return NULL;
1956 }
1957 EXPORT_SYMBOL_GPL(zs_create_pool);
1958
1959 void zs_destroy_pool(struct zs_pool *pool)
1960 {
1961         int i;
1962
1963         zs_unregister_shrinker(pool);
1964         zs_pool_stat_destroy(pool);
1965
1966         for (i = 0; i < zs_size_classes; i++) {
1967                 int fg;
1968                 struct size_class *class = pool->size_class[i];
1969
1970                 if (!class)
1971                         continue;
1972
1973                 if (class->index != i)
1974                         continue;
1975
1976                 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
1977                         if (class->fullness_list[fg]) {
1978                                 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
1979                                         class->size, fg);
1980                         }
1981                 }
1982                 kfree(class);
1983         }
1984
1985         destroy_handle_cache(pool);
1986         kfree(pool->size_class);
1987         kfree(pool->name);
1988         kfree(pool);
1989 }
1990 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1991
1992 static int __init zs_init(void)
1993 {
1994         int ret = zs_register_cpu_notifier();
1995
1996         if (ret)
1997                 goto notifier_fail;
1998
1999         init_zs_size_classes();
2000
2001 #ifdef CONFIG_ZPOOL
2002         zpool_register_driver(&zs_zpool_driver);
2003 #endif
2004
2005         ret = zs_stat_init();
2006         if (ret) {
2007                 pr_err("zs stat initialization failed\n");
2008                 goto stat_fail;
2009         }
2010         return 0;
2011
2012 stat_fail:
2013 #ifdef CONFIG_ZPOOL
2014         zpool_unregister_driver(&zs_zpool_driver);
2015 #endif
2016 notifier_fail:
2017         zs_unregister_cpu_notifier();
2018
2019         return ret;
2020 }
2021
2022 static void __exit zs_exit(void)
2023 {
2024 #ifdef CONFIG_ZPOOL
2025         zpool_unregister_driver(&zs_zpool_driver);
2026 #endif
2027         zs_unregister_cpu_notifier();
2028
2029         zs_stat_exit();
2030 }
2031
2032 module_init(zs_init);
2033 module_exit(zs_exit);
2034
2035 MODULE_LICENSE("Dual BSD/GPL");
2036 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");