Merge branch 'linux-3.10.y' of git://git.kernel.org/pub/scm/linux/kernel/git/stable...
[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 /*
16  * This allocator is designed for use with zcache and zram. Thus, the
17  * allocator is supposed to work well under low memory conditions. In
18  * particular, it never attempts higher order page allocation which is
19  * very likely to fail under memory pressure. On the other hand, if we
20  * just use single (0-order) pages, it would suffer from very high
21  * fragmentation -- any object of size PAGE_SIZE/2 or larger would occupy
22  * an entire page. This was one of the major issues with its predecessor
23  * (xvmalloc).
24  *
25  * To overcome these issues, zsmalloc allocates a bunch of 0-order pages
26  * and links them together using various 'struct page' fields. These linked
27  * pages act as a single higher-order page i.e. an object can span 0-order
28  * page boundaries. The code refers to these linked pages as a single entity
29  * called zspage.
30  *
31  * Following is how we use various fields and flags of underlying
32  * struct page(s) to form a zspage.
33  *
34  * Usage of struct page fields:
35  *      page->first_page: points to the first component (0-order) page
36  *      page->index (union with page->freelist): offset of the first object
37  *              starting in this page. For the first page, this is
38  *              always 0, so we use this field (aka freelist) to point
39  *              to the first free object in zspage.
40  *      page->lru: links together all component pages (except the first page)
41  *              of a zspage
42  *
43  *      For _first_ page only:
44  *
45  *      page->private (union with page->first_page): refers to the
46  *              component page after the first page
47  *      page->freelist: points to the first free object in zspage.
48  *              Free objects are linked together using in-place
49  *              metadata.
50  *      page->objects: maximum number of objects we can store in this
51  *              zspage (class->zspage_order * PAGE_SIZE / class->size)
52  *      page->lru: links together first pages of various zspages.
53  *              Basically forming list of zspages in a fullness group.
54  *      page->mapping: class index and fullness group of the zspage
55  *
56  * Usage of struct page flags:
57  *      PG_private: identifies the first component page
58  *      PG_private2: identifies the last component page
59  *
60  */
61
62 #ifdef CONFIG_ZSMALLOC_DEBUG
63 #define DEBUG
64 #endif
65
66 #include <linux/module.h>
67 #include <linux/kernel.h>
68 #include <linux/bitops.h>
69 #include <linux/errno.h>
70 #include <linux/highmem.h>
71 #include <linux/init.h>
72 #include <linux/string.h>
73 #include <linux/slab.h>
74 #include <asm/tlbflush.h>
75 #include <asm/pgtable.h>
76 #include <linux/cpumask.h>
77 #include <linux/cpu.h>
78 #include <linux/vmalloc.h>
79 #include <linux/hardirq.h>
80 #include <linux/spinlock.h>
81 #include <linux/types.h>
82 #include <linux/zsmalloc.h>
83 #include <linux/zpool.h>
84
85 /*
86  * This must be power of 2 and greater than of equal to sizeof(link_free).
87  * These two conditions ensure that any 'struct link_free' itself doesn't
88  * span more than 1 page which avoids complex case of mapping 2 pages simply
89  * to restore link_free pointer values.
90  */
91 #define ZS_ALIGN                8
92
93 /*
94  * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
95  * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
96  */
97 #define ZS_MAX_ZSPAGE_ORDER 2
98 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
99
100 /*
101  * Object location (<PFN>, <obj_idx>) is encoded as
102  * as single (void *) handle value.
103  *
104  * Note that object index <obj_idx> is relative to system
105  * page <PFN> it is stored in, so for each sub-page belonging
106  * to a zspage, obj_idx starts with 0.
107  *
108  * This is made more complicated by various memory models and PAE.
109  */
110
111 #ifndef MAX_PHYSMEM_BITS
112 #ifdef CONFIG_HIGHMEM64G
113 #define MAX_PHYSMEM_BITS 36
114 #else /* !CONFIG_HIGHMEM64G */
115 /*
116  * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
117  * be PAGE_SHIFT
118  */
119 #define MAX_PHYSMEM_BITS BITS_PER_LONG
120 #endif
121 #endif
122 #define _PFN_BITS               (MAX_PHYSMEM_BITS - PAGE_SHIFT)
123 #define OBJ_INDEX_BITS  (BITS_PER_LONG - _PFN_BITS)
124 #define OBJ_INDEX_MASK  ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
125
126 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
127 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
128 #define ZS_MIN_ALLOC_SIZE \
129         MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
130 #define ZS_MAX_ALLOC_SIZE       PAGE_SIZE
131
132 /*
133  * On systems with 4K page size, this gives 255 size classes! There is a
134  * trader-off here:
135  *  - Large number of size classes is potentially wasteful as free page are
136  *    spread across these classes
137  *  - Small number of size classes causes large internal fragmentation
138  *  - Probably its better to use specific size classes (empirically
139  *    determined). NOTE: all those class sizes must be set as multiple of
140  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
141  *
142  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
143  *  (reason above)
144  */
145 #define ZS_SIZE_CLASS_DELTA     (PAGE_SIZE >> 8)
146 #define ZS_SIZE_CLASSES         ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / \
147                                         ZS_SIZE_CLASS_DELTA + 1)
148
149 /*
150  * We do not maintain any list for completely empty or full pages
151  */
152 enum fullness_group {
153         ZS_ALMOST_FULL,
154         ZS_ALMOST_EMPTY,
155         _ZS_NR_FULLNESS_GROUPS,
156
157         ZS_EMPTY,
158         ZS_FULL
159 };
160
161 /*
162  * We assign a page to ZS_ALMOST_EMPTY fullness group when:
163  *      n <= N / f, where
164  * n = number of allocated objects
165  * N = total number of objects zspage can store
166  * f = fullness_threshold_frac
167  *
168  * Similarly, we assign zspage to:
169  *      ZS_ALMOST_FULL  when n > N / f
170  *      ZS_EMPTY        when n == 0
171  *      ZS_FULL         when n == N
172  *
173  * (see: fix_fullness_group())
174  */
175 static const int fullness_threshold_frac = 4;
176
177 struct size_class {
178         /*
179          * Size of objects stored in this class. Must be multiple
180          * of ZS_ALIGN.
181          */
182         int size;
183         unsigned int index;
184
185         /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
186         int pages_per_zspage;
187
188         spinlock_t lock;
189
190         struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
191 };
192
193 /*
194  * Placed within free objects to form a singly linked list.
195  * For every zspage, first_page->freelist gives head of this list.
196  *
197  * This must be power of 2 and less than or equal to ZS_ALIGN
198  */
199 struct link_free {
200         /* Handle of next free chunk (encodes <PFN, obj_idx>) */
201         void *next;
202 };
203
204 struct zs_pool {
205         struct size_class *size_class[ZS_SIZE_CLASSES];
206
207         gfp_t flags;    /* allocation flags used when growing pool */
208         atomic_long_t pages_allocated;
209 };
210
211 /*
212  * A zspage's class index and fullness group
213  * are encoded in its (first)page->mapping
214  */
215 #define CLASS_IDX_BITS  28
216 #define FULLNESS_BITS   4
217 #define CLASS_IDX_MASK  ((1 << CLASS_IDX_BITS) - 1)
218 #define FULLNESS_MASK   ((1 << FULLNESS_BITS) - 1)
219
220 /*
221  * By default, zsmalloc uses a copy-based object mapping method to access
222  * allocations that span two pages. However, if a particular architecture
223  * performs VM mapping faster than copying, then it should be added here
224  * so that USE_PGTABLE_MAPPING is defined. This causes zsmalloc to use
225  * page table mapping rather than copying for object mapping.
226 */
227 #if defined(CONFIG_ARM) && !defined(MODULE)
228 #define USE_PGTABLE_MAPPING
229 #endif
230
231 struct mapping_area {
232 #ifdef USE_PGTABLE_MAPPING
233         struct vm_struct *vm; /* vm area for mapping object that span pages */
234 #else
235         char *vm_buf; /* copy buffer for objects that span pages */
236 #endif
237         char *vm_addr; /* address of kmap_atomic()'ed pages */
238         enum zs_mapmode vm_mm; /* mapping mode */
239 };
240
241 /* zpool driver */
242
243 #ifdef CONFIG_ZPOOL
244
245 static void *zs_zpool_create(gfp_t gfp, struct zpool_ops *zpool_ops)
246 {
247         return zs_create_pool(gfp);
248 }
249
250 static void zs_zpool_destroy(void *pool)
251 {
252         zs_destroy_pool(pool);
253 }
254
255 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
256                         unsigned long *handle)
257 {
258         *handle = zs_malloc(pool, size);
259         return *handle ? 0 : -1;
260 }
261 static void zs_zpool_free(void *pool, unsigned long handle)
262 {
263         zs_free(pool, handle);
264 }
265
266 static int zs_zpool_shrink(void *pool, unsigned int pages,
267                         unsigned int *reclaimed)
268 {
269         return -EINVAL;
270 }
271
272 static void *zs_zpool_map(void *pool, unsigned long handle,
273                         enum zpool_mapmode mm)
274 {
275         enum zs_mapmode zs_mm;
276
277         switch (mm) {
278         case ZPOOL_MM_RO:
279                 zs_mm = ZS_MM_RO;
280                 break;
281         case ZPOOL_MM_WO:
282                 zs_mm = ZS_MM_WO;
283                 break;
284         case ZPOOL_MM_RW: /* fallthru */
285         default:
286                 zs_mm = ZS_MM_RW;
287                 break;
288         }
289
290         return zs_map_object(pool, handle, zs_mm);
291 }
292 static void zs_zpool_unmap(void *pool, unsigned long handle)
293 {
294         zs_unmap_object(pool, handle);
295 }
296
297 static u64 zs_zpool_total_size(void *pool)
298 {
299         return zs_get_total_pages(pool) << PAGE_SHIFT;
300 }
301
302 static struct zpool_driver zs_zpool_driver = {
303         .type =         "zsmalloc",
304         .owner =        THIS_MODULE,
305         .create =       zs_zpool_create,
306         .destroy =      zs_zpool_destroy,
307         .malloc =       zs_zpool_malloc,
308         .free =         zs_zpool_free,
309         .shrink =       zs_zpool_shrink,
310         .map =          zs_zpool_map,
311         .unmap =        zs_zpool_unmap,
312         .total_size =   zs_zpool_total_size,
313 };
314
315 MODULE_ALIAS("zpool-zsmalloc");
316 #endif /* CONFIG_ZPOOL */
317
318 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
319 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
320
321 static int is_first_page(struct page *page)
322 {
323         return PagePrivate(page);
324 }
325
326 static int is_last_page(struct page *page)
327 {
328         return PagePrivate2(page);
329 }
330
331 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
332                                 enum fullness_group *fullness)
333 {
334         unsigned long m;
335         BUG_ON(!is_first_page(page));
336
337         m = (unsigned long)page->mapping;
338         *fullness = m & FULLNESS_MASK;
339         *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
340 }
341
342 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
343                                 enum fullness_group fullness)
344 {
345         unsigned long m;
346         BUG_ON(!is_first_page(page));
347
348         m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
349                         (fullness & FULLNESS_MASK);
350         page->mapping = (struct address_space *)m;
351 }
352
353 static int get_size_class_index(int size)
354 {
355         int idx = 0;
356
357         if (likely(size > ZS_MIN_ALLOC_SIZE))
358                 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
359                                 ZS_SIZE_CLASS_DELTA);
360
361         return idx;
362 }
363
364 static enum fullness_group get_fullness_group(struct page *page)
365 {
366         int inuse, max_objects;
367         enum fullness_group fg;
368         BUG_ON(!is_first_page(page));
369
370         inuse = page->inuse;
371         max_objects = page->objects;
372
373         if (inuse == 0)
374                 fg = ZS_EMPTY;
375         else if (inuse == max_objects)
376                 fg = ZS_FULL;
377         else if (inuse <= max_objects / fullness_threshold_frac)
378                 fg = ZS_ALMOST_EMPTY;
379         else
380                 fg = ZS_ALMOST_FULL;
381
382         return fg;
383 }
384
385 static void insert_zspage(struct page *page, struct size_class *class,
386                                 enum fullness_group fullness)
387 {
388         struct page **head;
389
390         BUG_ON(!is_first_page(page));
391
392         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
393                 return;
394
395         head = &class->fullness_list[fullness];
396         if (*head)
397                 list_add_tail(&page->lru, &(*head)->lru);
398
399         *head = page;
400 }
401
402 static void remove_zspage(struct page *page, struct size_class *class,
403                                 enum fullness_group fullness)
404 {
405         struct page **head;
406
407         BUG_ON(!is_first_page(page));
408
409         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
410                 return;
411
412         head = &class->fullness_list[fullness];
413         BUG_ON(!*head);
414         if (list_empty(&(*head)->lru))
415                 *head = NULL;
416         else if (*head == page)
417                 *head = (struct page *)list_entry((*head)->lru.next,
418                                         struct page, lru);
419
420         list_del_init(&page->lru);
421 }
422
423 static enum fullness_group fix_fullness_group(struct zs_pool *pool,
424                                                 struct page *page)
425 {
426         int class_idx;
427         struct size_class *class;
428         enum fullness_group currfg, newfg;
429
430         BUG_ON(!is_first_page(page));
431
432         get_zspage_mapping(page, &class_idx, &currfg);
433         newfg = get_fullness_group(page);
434         if (newfg == currfg)
435                 goto out;
436
437         class = pool->size_class[class_idx];
438         remove_zspage(page, class, currfg);
439         insert_zspage(page, class, newfg);
440         set_zspage_mapping(page, class_idx, newfg);
441
442 out:
443         return newfg;
444 }
445
446 /*
447  * We have to decide on how many pages to link together
448  * to form a zspage for each size class. This is important
449  * to reduce wastage due to unusable space left at end of
450  * each zspage which is given as:
451  *      wastage = Zp - Zp % size_class
452  * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
453  *
454  * For example, for size class of 3/8 * PAGE_SIZE, we should
455  * link together 3 PAGE_SIZE sized pages to form a zspage
456  * since then we can perfectly fit in 8 such objects.
457  */
458 static int get_pages_per_zspage(int class_size)
459 {
460         int i, max_usedpc = 0;
461         /* zspage order which gives maximum used size per KB */
462         int max_usedpc_order = 1;
463
464         for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
465                 int zspage_size;
466                 int waste, usedpc;
467
468                 zspage_size = i * PAGE_SIZE;
469                 waste = zspage_size % class_size;
470                 usedpc = (zspage_size - waste) * 100 / zspage_size;
471
472                 if (usedpc > max_usedpc) {
473                         max_usedpc = usedpc;
474                         max_usedpc_order = i;
475                 }
476         }
477
478         return max_usedpc_order;
479 }
480
481 /*
482  * A single 'zspage' is composed of many system pages which are
483  * linked together using fields in struct page. This function finds
484  * the first/head page, given any component page of a zspage.
485  */
486 static struct page *get_first_page(struct page *page)
487 {
488         if (is_first_page(page))
489                 return page;
490         else
491                 return page->first_page;
492 }
493
494 static struct page *get_next_page(struct page *page)
495 {
496         struct page *next;
497
498         if (is_last_page(page))
499                 next = NULL;
500         else if (is_first_page(page))
501                 next = (struct page *)page->private;
502         else
503                 next = list_entry(page->lru.next, struct page, lru);
504
505         return next;
506 }
507
508 /*
509  * Encode <page, obj_idx> as a single handle value.
510  * On hardware platforms with physical memory starting at 0x0 the pfn
511  * could be 0 so we ensure that the handle will never be 0 by adjusting the
512  * encoded obj_idx value before encoding.
513  */
514 static void *obj_location_to_handle(struct page *page, unsigned long obj_idx)
515 {
516         unsigned long handle;
517
518         if (!page) {
519                 BUG_ON(obj_idx);
520                 return NULL;
521         }
522
523         handle = page_to_pfn(page) << OBJ_INDEX_BITS;
524         handle |= ((obj_idx + 1) & OBJ_INDEX_MASK);
525
526         return (void *)handle;
527 }
528
529 /*
530  * Decode <page, obj_idx> pair from the given object handle. We adjust the
531  * decoded obj_idx back to its original value since it was adjusted in
532  * obj_location_to_handle().
533  */
534 static void obj_handle_to_location(unsigned long handle, struct page **page,
535                                 unsigned long *obj_idx)
536 {
537         *page = pfn_to_page(handle >> OBJ_INDEX_BITS);
538         *obj_idx = (handle & OBJ_INDEX_MASK) - 1;
539 }
540
541 static unsigned long obj_idx_to_offset(struct page *page,
542                                 unsigned long obj_idx, int class_size)
543 {
544         unsigned long off = 0;
545
546         if (!is_first_page(page))
547                 off = page->index;
548
549         return off + obj_idx * class_size;
550 }
551
552 static void reset_page(struct page *page)
553 {
554         clear_bit(PG_private, &page->flags);
555         clear_bit(PG_private_2, &page->flags);
556         set_page_private(page, 0);
557         page->mapping = NULL;
558         page->freelist = NULL;
559         page_mapcount_reset(page);
560 }
561
562 static void free_zspage(struct page *first_page)
563 {
564         struct page *nextp, *tmp, *head_extra;
565
566         BUG_ON(!is_first_page(first_page));
567         BUG_ON(first_page->inuse);
568
569         head_extra = (struct page *)page_private(first_page);
570
571         reset_page(first_page);
572         __free_page(first_page);
573
574         /* zspage with only 1 system page */
575         if (!head_extra)
576                 return;
577
578         list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
579                 list_del(&nextp->lru);
580                 reset_page(nextp);
581                 __free_page(nextp);
582         }
583         reset_page(head_extra);
584         __free_page(head_extra);
585 }
586
587 /* Initialize a newly allocated zspage */
588 static void init_zspage(struct page *first_page, struct size_class *class)
589 {
590         unsigned long off = 0;
591         struct page *page = first_page;
592
593         BUG_ON(!is_first_page(first_page));
594         while (page) {
595                 struct page *next_page;
596                 struct link_free *link;
597                 unsigned int i = 1;
598                 void *vaddr;
599
600                 /*
601                  * page->index stores offset of first object starting
602                  * in the page. For the first page, this is always 0,
603                  * so we use first_page->index (aka ->freelist) to store
604                  * head of corresponding zspage's freelist.
605                  */
606                 if (page != first_page)
607                         page->index = off;
608
609                 vaddr = kmap_atomic(page);
610                 link = (struct link_free *)vaddr + off / sizeof(*link);
611
612                 while ((off += class->size) < PAGE_SIZE) {
613                         link->next = obj_location_to_handle(page, i++);
614                         link += class->size / sizeof(*link);
615                 }
616
617                 /*
618                  * We now come to the last (full or partial) object on this
619                  * page, which must point to the first object on the next
620                  * page (if present)
621                  */
622                 next_page = get_next_page(page);
623                 link->next = obj_location_to_handle(next_page, 0);
624                 kunmap_atomic(vaddr);
625                 page = next_page;
626                 off %= PAGE_SIZE;
627         }
628 }
629
630 /*
631  * Allocate a zspage for the given size class
632  */
633 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
634 {
635         int i, error;
636         struct page *first_page = NULL, *uninitialized_var(prev_page);
637
638         /*
639          * Allocate individual pages and link them together as:
640          * 1. first page->private = first sub-page
641          * 2. all sub-pages are linked together using page->lru
642          * 3. each sub-page is linked to the first page using page->first_page
643          *
644          * For each size class, First/Head pages are linked together using
645          * page->lru. Also, we set PG_private to identify the first page
646          * (i.e. no other sub-page has this flag set) and PG_private_2 to
647          * identify the last page.
648          */
649         error = -ENOMEM;
650         for (i = 0; i < class->pages_per_zspage; i++) {
651                 struct page *page;
652
653                 page = alloc_page(flags);
654                 if (!page)
655                         goto cleanup;
656
657                 INIT_LIST_HEAD(&page->lru);
658                 if (i == 0) {   /* first page */
659                         SetPagePrivate(page);
660                         set_page_private(page, 0);
661                         first_page = page;
662                         first_page->inuse = 0;
663                 }
664                 if (i == 1)
665                         first_page->private = (unsigned long)page;
666                 if (i >= 1)
667                         page->first_page = first_page;
668                 if (i >= 2)
669                         list_add(&page->lru, &prev_page->lru);
670                 if (i == class->pages_per_zspage - 1)   /* last page */
671                         SetPagePrivate2(page);
672                 prev_page = page;
673         }
674
675         init_zspage(first_page, class);
676
677         first_page->freelist = obj_location_to_handle(first_page, 0);
678         /* Maximum number of objects we can store in this zspage */
679         first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
680
681         error = 0; /* Success */
682
683 cleanup:
684         if (unlikely(error) && first_page) {
685                 free_zspage(first_page);
686                 first_page = NULL;
687         }
688
689         return first_page;
690 }
691
692 static struct page *find_get_zspage(struct size_class *class)
693 {
694         int i;
695         struct page *page;
696
697         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
698                 page = class->fullness_list[i];
699                 if (page)
700                         break;
701         }
702
703         return page;
704 }
705
706 #ifdef USE_PGTABLE_MAPPING
707 static inline int __zs_cpu_up(struct mapping_area *area)
708 {
709         /*
710          * Make sure we don't leak memory if a cpu UP notification
711          * and zs_init() race and both call zs_cpu_up() on the same cpu
712          */
713         if (area->vm)
714                 return 0;
715         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
716         if (!area->vm)
717                 return -ENOMEM;
718         return 0;
719 }
720
721 static inline void __zs_cpu_down(struct mapping_area *area)
722 {
723         if (area->vm)
724                 free_vm_area(area->vm);
725         area->vm = NULL;
726 }
727
728 static inline void *__zs_map_object(struct mapping_area *area,
729                                 struct page *pages[2], int off, int size)
730 {
731         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, &pages));
732         area->vm_addr = area->vm->addr;
733         return area->vm_addr + off;
734 }
735
736 static inline void __zs_unmap_object(struct mapping_area *area,
737                                 struct page *pages[2], int off, int size)
738 {
739         unsigned long addr = (unsigned long)area->vm_addr;
740
741         unmap_kernel_range(addr, PAGE_SIZE * 2);
742 }
743
744 #else /* USE_PGTABLE_MAPPING */
745
746 static inline int __zs_cpu_up(struct mapping_area *area)
747 {
748         /*
749          * Make sure we don't leak memory if a cpu UP notification
750          * and zs_init() race and both call zs_cpu_up() on the same cpu
751          */
752         if (area->vm_buf)
753                 return 0;
754         area->vm_buf = (char *)__get_free_page(GFP_KERNEL);
755         if (!area->vm_buf)
756                 return -ENOMEM;
757         return 0;
758 }
759
760 static inline void __zs_cpu_down(struct mapping_area *area)
761 {
762         if (area->vm_buf)
763                 free_page((unsigned long)area->vm_buf);
764         area->vm_buf = NULL;
765 }
766
767 static void *__zs_map_object(struct mapping_area *area,
768                         struct page *pages[2], int off, int size)
769 {
770         int sizes[2];
771         void *addr;
772         char *buf = area->vm_buf;
773
774         /* disable page faults to match kmap_atomic() return conditions */
775         pagefault_disable();
776
777         /* no read fastpath */
778         if (area->vm_mm == ZS_MM_WO)
779                 goto out;
780
781         sizes[0] = PAGE_SIZE - off;
782         sizes[1] = size - sizes[0];
783
784         /* copy object to per-cpu buffer */
785         addr = kmap_atomic(pages[0]);
786         memcpy(buf, addr + off, sizes[0]);
787         kunmap_atomic(addr);
788         addr = kmap_atomic(pages[1]);
789         memcpy(buf + sizes[0], addr, sizes[1]);
790         kunmap_atomic(addr);
791 out:
792         return area->vm_buf;
793 }
794
795 static void __zs_unmap_object(struct mapping_area *area,
796                         struct page *pages[2], int off, int size)
797 {
798         int sizes[2];
799         void *addr;
800         char *buf = area->vm_buf;
801
802         /* no write fastpath */
803         if (area->vm_mm == ZS_MM_RO)
804                 goto out;
805
806         sizes[0] = PAGE_SIZE - off;
807         sizes[1] = size - sizes[0];
808
809         /* copy per-cpu buffer to object */
810         addr = kmap_atomic(pages[0]);
811         memcpy(addr + off, buf, sizes[0]);
812         kunmap_atomic(addr);
813         addr = kmap_atomic(pages[1]);
814         memcpy(addr, buf + sizes[0], sizes[1]);
815         kunmap_atomic(addr);
816
817 out:
818         /* enable page faults to match kunmap_atomic() return conditions */
819         pagefault_enable();
820 }
821
822 #endif /* USE_PGTABLE_MAPPING */
823
824 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
825                                 void *pcpu)
826 {
827         int ret, cpu = (long)pcpu;
828         struct mapping_area *area;
829
830         switch (action) {
831         case CPU_UP_PREPARE:
832                 area = &per_cpu(zs_map_area, cpu);
833                 ret = __zs_cpu_up(area);
834                 if (ret)
835                         return notifier_from_errno(ret);
836                 break;
837         case CPU_DEAD:
838         case CPU_UP_CANCELED:
839                 area = &per_cpu(zs_map_area, cpu);
840                 __zs_cpu_down(area);
841                 break;
842         }
843
844         return NOTIFY_OK;
845 }
846
847 static struct notifier_block zs_cpu_nb = {
848         .notifier_call = zs_cpu_notifier
849 };
850
851 static void zs_unregister_cpu_notifier(void)
852 {
853         int cpu;
854
855         cpu_notifier_register_begin();
856
857         for_each_online_cpu(cpu)
858                 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
859         __unregister_cpu_notifier(&zs_cpu_nb);
860
861         cpu_notifier_register_done();
862 }
863
864 static int zs_register_cpu_notifier(void)
865 {
866         int cpu, uninitialized_var(ret);
867
868         cpu_notifier_register_begin();
869
870         __register_cpu_notifier(&zs_cpu_nb);
871         for_each_online_cpu(cpu) {
872                 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
873                 if (notifier_to_errno(ret))
874                         break;
875         }
876
877         cpu_notifier_register_done();
878         return notifier_to_errno(ret);
879 }
880
881 static void __exit zs_exit(void)
882 {
883 #ifdef CONFIG_ZPOOL
884         zpool_unregister_driver(&zs_zpool_driver);
885 #endif
886         zs_unregister_cpu_notifier();
887 }
888
889 static int __init zs_init(void)
890 {
891         int ret = zs_register_cpu_notifier();
892
893         if (ret) {
894                 zs_unregister_cpu_notifier();
895                 return ret;
896         }
897
898 #ifdef CONFIG_ZPOOL
899         zpool_register_driver(&zs_zpool_driver);
900 #endif
901         return 0;
902 }
903
904 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
905 {
906         return pages_per_zspage * PAGE_SIZE / size;
907 }
908
909 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
910 {
911         if (prev->pages_per_zspage != pages_per_zspage)
912                 return false;
913
914         if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
915                 != get_maxobj_per_zspage(size, pages_per_zspage))
916                 return false;
917
918         return true;
919 }
920
921 /**
922  * zs_create_pool - Creates an allocation pool to work from.
923  * @flags: allocation flags used to allocate pool metadata
924  *
925  * This function must be called before anything when using
926  * the zsmalloc allocator.
927  *
928  * On success, a pointer to the newly created pool is returned,
929  * otherwise NULL.
930  */
931 struct zs_pool *zs_create_pool(gfp_t flags)
932 {
933         int i, ovhd_size;
934         struct zs_pool *pool;
935
936         ovhd_size = roundup(sizeof(*pool), PAGE_SIZE);
937         pool = kzalloc(ovhd_size, GFP_KERNEL);
938         if (!pool)
939                 return NULL;
940
941         /*
942          * Iterate reversly, because, size of size_class that we want to use
943          * for merging should be larger or equal to current size.
944          */
945         for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
946                 int size;
947                 int pages_per_zspage;
948                 struct size_class *class;
949                 struct size_class *prev_class;
950
951                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
952                 if (size > ZS_MAX_ALLOC_SIZE)
953                         size = ZS_MAX_ALLOC_SIZE;
954                 pages_per_zspage = get_pages_per_zspage(size);
955
956                 /*
957                  * size_class is used for normal zsmalloc operation such
958                  * as alloc/free for that size. Although it is natural that we
959                  * have one size_class for each size, there is a chance that we
960                  * can get more memory utilization if we use one size_class for
961                  * many different sizes whose size_class have same
962                  * characteristics. So, we makes size_class point to
963                  * previous size_class if possible.
964                  */
965                 if (i < ZS_SIZE_CLASSES - 1) {
966                         prev_class = pool->size_class[i + 1];
967                         if (can_merge(prev_class, size, pages_per_zspage)) {
968                                 pool->size_class[i] = prev_class;
969                                 continue;
970                         }
971                 }
972
973                 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
974                 if (!class)
975                         goto err;
976
977                 class->size = size;
978                 class->index = i;
979                 class->pages_per_zspage = pages_per_zspage;
980                 spin_lock_init(&class->lock);
981                 pool->size_class[i] = class;
982         }
983
984         pool->flags = flags;
985
986         return pool;
987
988 err:
989         zs_destroy_pool(pool);
990         return NULL;
991 }
992 EXPORT_SYMBOL_GPL(zs_create_pool);
993
994 void zs_destroy_pool(struct zs_pool *pool)
995 {
996         int i;
997
998         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
999                 int fg;
1000                 struct size_class *class = pool->size_class[i];
1001
1002                 if (!class)
1003                         continue;
1004
1005                 if (class->index != i)
1006                         continue;
1007
1008                 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
1009                         if (class->fullness_list[fg]) {
1010                                 pr_info("Freeing non-empty class with size "
1011                                         "%db, fullness group %d\n",
1012                                         class->size, fg);
1013                         }
1014                 }
1015                 kfree(class);
1016         }
1017         kfree(pool);
1018 }
1019 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1020
1021 /**
1022  * zs_malloc - Allocate block of given size from pool.
1023  * @pool: pool to allocate from
1024  * @size: size of block to allocate
1025  *
1026  * On success, handle to the allocated object is returned,
1027  * otherwise 0.
1028  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1029  */
1030 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1031 {
1032         unsigned long obj;
1033         struct link_free *link;
1034         struct size_class *class;
1035         void *vaddr;
1036
1037         struct page *first_page, *m_page;
1038         unsigned long m_objidx, m_offset;
1039
1040         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1041                 return 0;
1042
1043         class = pool->size_class[get_size_class_index(size)];
1044
1045         spin_lock(&class->lock);
1046         first_page = find_get_zspage(class);
1047
1048         if (!first_page) {
1049                 spin_unlock(&class->lock);
1050                 first_page = alloc_zspage(class, pool->flags);
1051                 if (unlikely(!first_page))
1052                         return 0;
1053
1054                 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1055                 atomic_long_add(class->pages_per_zspage,
1056                                         &pool->pages_allocated);
1057                 spin_lock(&class->lock);
1058         }
1059
1060         obj = (unsigned long)first_page->freelist;
1061         obj_handle_to_location(obj, &m_page, &m_objidx);
1062         m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1063
1064         vaddr = kmap_atomic(m_page);
1065         link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1066         first_page->freelist = link->next;
1067         memset(link, POISON_INUSE, sizeof(*link));
1068         kunmap_atomic(vaddr);
1069
1070         first_page->inuse++;
1071         /* Now move the zspage to another fullness group, if required */
1072         fix_fullness_group(pool, first_page);
1073         spin_unlock(&class->lock);
1074
1075         return obj;
1076 }
1077 EXPORT_SYMBOL_GPL(zs_malloc);
1078
1079 void zs_free(struct zs_pool *pool, unsigned long obj)
1080 {
1081         struct link_free *link;
1082         struct page *first_page, *f_page;
1083         unsigned long f_objidx, f_offset;
1084         void *vaddr;
1085
1086         int class_idx;
1087         struct size_class *class;
1088         enum fullness_group fullness;
1089
1090         if (unlikely(!obj))
1091                 return;
1092
1093         obj_handle_to_location(obj, &f_page, &f_objidx);
1094         first_page = get_first_page(f_page);
1095
1096         get_zspage_mapping(first_page, &class_idx, &fullness);
1097         class = pool->size_class[class_idx];
1098         f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1099
1100         spin_lock(&class->lock);
1101
1102         /* Insert this object in containing zspage's freelist */
1103         vaddr = kmap_atomic(f_page);
1104         link = (struct link_free *)(vaddr + f_offset);
1105         link->next = first_page->freelist;
1106         kunmap_atomic(vaddr);
1107         first_page->freelist = (void *)obj;
1108
1109         first_page->inuse--;
1110         fullness = fix_fullness_group(pool, first_page);
1111         spin_unlock(&class->lock);
1112
1113         if (fullness == ZS_EMPTY) {
1114                 atomic_long_sub(class->pages_per_zspage,
1115                                 &pool->pages_allocated);
1116                 free_zspage(first_page);
1117         }
1118 }
1119 EXPORT_SYMBOL_GPL(zs_free);
1120
1121 /**
1122  * zs_map_object - get address of allocated object from handle.
1123  * @pool: pool from which the object was allocated
1124  * @handle: handle returned from zs_malloc
1125  *
1126  * Before using an object allocated from zs_malloc, it must be mapped using
1127  * this function. When done with the object, it must be unmapped using
1128  * zs_unmap_object.
1129  *
1130  * Only one object can be mapped per cpu at a time. There is no protection
1131  * against nested mappings.
1132  *
1133  * This function returns with preemption and page faults disabled.
1134 */
1135 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1136                         enum zs_mapmode mm)
1137 {
1138         struct page *page;
1139         unsigned long obj_idx, off;
1140
1141         unsigned int class_idx;
1142         enum fullness_group fg;
1143         struct size_class *class;
1144         struct mapping_area *area;
1145         struct page *pages[2];
1146
1147         BUG_ON(!handle);
1148
1149         /*
1150          * Because we use per-cpu mapping areas shared among the
1151          * pools/users, we can't allow mapping in interrupt context
1152          * because it can corrupt another users mappings.
1153          */
1154         BUG_ON(in_interrupt());
1155
1156         obj_handle_to_location(handle, &page, &obj_idx);
1157         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1158         class = pool->size_class[class_idx];
1159         off = obj_idx_to_offset(page, obj_idx, class->size);
1160
1161         area = &get_cpu_var(zs_map_area);
1162         area->vm_mm = mm;
1163         if (off + class->size <= PAGE_SIZE) {
1164                 /* this object is contained entirely within a page */
1165                 area->vm_addr = kmap_atomic(page);
1166                 return area->vm_addr + off;
1167         }
1168
1169         /* this object spans two pages */
1170         pages[0] = page;
1171         pages[1] = get_next_page(page);
1172         BUG_ON(!pages[1]);
1173
1174         return __zs_map_object(area, pages, off, class->size);
1175 }
1176 EXPORT_SYMBOL_GPL(zs_map_object);
1177
1178 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1179 {
1180         struct page *page;
1181         unsigned long obj_idx, off;
1182
1183         unsigned int class_idx;
1184         enum fullness_group fg;
1185         struct size_class *class;
1186         struct mapping_area *area;
1187
1188         BUG_ON(!handle);
1189
1190         obj_handle_to_location(handle, &page, &obj_idx);
1191         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1192         class = pool->size_class[class_idx];
1193         off = obj_idx_to_offset(page, obj_idx, class->size);
1194
1195         area = &__get_cpu_var(zs_map_area);
1196         if (off + class->size <= PAGE_SIZE)
1197                 kunmap_atomic(area->vm_addr);
1198         else {
1199                 struct page *pages[2];
1200
1201                 pages[0] = page;
1202                 pages[1] = get_next_page(page);
1203                 BUG_ON(!pages[1]);
1204
1205                 __zs_unmap_object(area, pages, off, class->size);
1206         }
1207         put_cpu_var(zs_map_area);
1208 }
1209 EXPORT_SYMBOL_GPL(zs_unmap_object);
1210
1211 unsigned long zs_get_total_pages(struct zs_pool *pool)
1212 {
1213         return atomic_long_read(&pool->pages_allocated);
1214 }
1215 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1216
1217 module_init(zs_init);
1218 module_exit(zs_exit);
1219
1220 MODULE_LICENSE("Dual BSD/GPL");
1221 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");