mm/zpool: use prefixed module loading
[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 = 1/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         /* stats */
191         u64 pages_allocated;
192
193         struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
194 };
195
196 /*
197  * Placed within free objects to form a singly linked list.
198  * For every zspage, first_page->freelist gives head of this list.
199  *
200  * This must be power of 2 and less than or equal to ZS_ALIGN
201  */
202 struct link_free {
203         /* Handle of next free chunk (encodes <PFN, obj_idx>) */
204         void *next;
205 };
206
207 struct zs_pool {
208         struct size_class size_class[ZS_SIZE_CLASSES];
209
210         gfp_t flags;    /* allocation flags used when growing pool */
211 };
212
213 /*
214  * A zspage's class index and fullness group
215  * are encoded in its (first)page->mapping
216  */
217 #define CLASS_IDX_BITS  28
218 #define FULLNESS_BITS   4
219 #define CLASS_IDX_MASK  ((1 << CLASS_IDX_BITS) - 1)
220 #define FULLNESS_MASK   ((1 << FULLNESS_BITS) - 1)
221
222 /*
223  * By default, zsmalloc uses a copy-based object mapping method to access
224  * allocations that span two pages. However, if a particular architecture
225  * performs VM mapping faster than copying, then it should be added here
226  * so that USE_PGTABLE_MAPPING is defined. This causes zsmalloc to use
227  * page table mapping rather than copying for object mapping.
228 */
229 #if defined(CONFIG_ARM) && !defined(MODULE)
230 #define USE_PGTABLE_MAPPING
231 #endif
232
233 struct mapping_area {
234 #ifdef USE_PGTABLE_MAPPING
235         struct vm_struct *vm; /* vm area for mapping object that span pages */
236 #else
237         char *vm_buf; /* copy buffer for objects that span pages */
238 #endif
239         char *vm_addr; /* address of kmap_atomic()'ed pages */
240         enum zs_mapmode vm_mm; /* mapping mode */
241 };
242
243 /* zpool driver */
244
245 #ifdef CONFIG_ZPOOL
246
247 static void *zs_zpool_create(gfp_t gfp, struct zpool_ops *zpool_ops)
248 {
249         return zs_create_pool(gfp);
250 }
251
252 static void zs_zpool_destroy(void *pool)
253 {
254         zs_destroy_pool(pool);
255 }
256
257 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
258                         unsigned long *handle)
259 {
260         *handle = zs_malloc(pool, size);
261         return *handle ? 0 : -1;
262 }
263 static void zs_zpool_free(void *pool, unsigned long handle)
264 {
265         zs_free(pool, handle);
266 }
267
268 static int zs_zpool_shrink(void *pool, unsigned int pages,
269                         unsigned int *reclaimed)
270 {
271         return -EINVAL;
272 }
273
274 static void *zs_zpool_map(void *pool, unsigned long handle,
275                         enum zpool_mapmode mm)
276 {
277         enum zs_mapmode zs_mm;
278
279         switch (mm) {
280         case ZPOOL_MM_RO:
281                 zs_mm = ZS_MM_RO;
282                 break;
283         case ZPOOL_MM_WO:
284                 zs_mm = ZS_MM_WO;
285                 break;
286         case ZPOOL_MM_RW: /* fallthru */
287         default:
288                 zs_mm = ZS_MM_RW;
289                 break;
290         }
291
292         return zs_map_object(pool, handle, zs_mm);
293 }
294 static void zs_zpool_unmap(void *pool, unsigned long handle)
295 {
296         zs_unmap_object(pool, handle);
297 }
298
299 static u64 zs_zpool_total_size(void *pool)
300 {
301         return zs_get_total_size_bytes(pool);
302 }
303
304 static struct zpool_driver zs_zpool_driver = {
305         .type =         "zsmalloc",
306         .owner =        THIS_MODULE,
307         .create =       zs_zpool_create,
308         .destroy =      zs_zpool_destroy,
309         .malloc =       zs_zpool_malloc,
310         .free =         zs_zpool_free,
311         .shrink =       zs_zpool_shrink,
312         .map =          zs_zpool_map,
313         .unmap =        zs_zpool_unmap,
314         .total_size =   zs_zpool_total_size,
315 };
316
317 MODULE_ALIAS("zpool-zsmalloc");
318 #endif /* CONFIG_ZPOOL */
319
320 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
321 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
322
323 static int is_first_page(struct page *page)
324 {
325         return PagePrivate(page);
326 }
327
328 static int is_last_page(struct page *page)
329 {
330         return PagePrivate2(page);
331 }
332
333 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
334                                 enum fullness_group *fullness)
335 {
336         unsigned long m;
337         BUG_ON(!is_first_page(page));
338
339         m = (unsigned long)page->mapping;
340         *fullness = m & FULLNESS_MASK;
341         *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
342 }
343
344 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
345                                 enum fullness_group fullness)
346 {
347         unsigned long m;
348         BUG_ON(!is_first_page(page));
349
350         m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
351                         (fullness & FULLNESS_MASK);
352         page->mapping = (struct address_space *)m;
353 }
354
355 static int get_size_class_index(int size)
356 {
357         int idx = 0;
358
359         if (likely(size > ZS_MIN_ALLOC_SIZE))
360                 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
361                                 ZS_SIZE_CLASS_DELTA);
362
363         return idx;
364 }
365
366 static enum fullness_group get_fullness_group(struct page *page)
367 {
368         int inuse, max_objects;
369         enum fullness_group fg;
370         BUG_ON(!is_first_page(page));
371
372         inuse = page->inuse;
373         max_objects = page->objects;
374
375         if (inuse == 0)
376                 fg = ZS_EMPTY;
377         else if (inuse == max_objects)
378                 fg = ZS_FULL;
379         else if (inuse <= max_objects / fullness_threshold_frac)
380                 fg = ZS_ALMOST_EMPTY;
381         else
382                 fg = ZS_ALMOST_FULL;
383
384         return fg;
385 }
386
387 static void insert_zspage(struct page *page, struct size_class *class,
388                                 enum fullness_group fullness)
389 {
390         struct page **head;
391
392         BUG_ON(!is_first_page(page));
393
394         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
395                 return;
396
397         head = &class->fullness_list[fullness];
398         if (*head)
399                 list_add_tail(&page->lru, &(*head)->lru);
400
401         *head = page;
402 }
403
404 static void remove_zspage(struct page *page, struct size_class *class,
405                                 enum fullness_group fullness)
406 {
407         struct page **head;
408
409         BUG_ON(!is_first_page(page));
410
411         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
412                 return;
413
414         head = &class->fullness_list[fullness];
415         BUG_ON(!*head);
416         if (list_empty(&(*head)->lru))
417                 *head = NULL;
418         else if (*head == page)
419                 *head = (struct page *)list_entry((*head)->lru.next,
420                                         struct page, lru);
421
422         list_del_init(&page->lru);
423 }
424
425 static enum fullness_group fix_fullness_group(struct zs_pool *pool,
426                                                 struct page *page)
427 {
428         int class_idx;
429         struct size_class *class;
430         enum fullness_group currfg, newfg;
431
432         BUG_ON(!is_first_page(page));
433
434         get_zspage_mapping(page, &class_idx, &currfg);
435         newfg = get_fullness_group(page);
436         if (newfg == currfg)
437                 goto out;
438
439         class = &pool->size_class[class_idx];
440         remove_zspage(page, class, currfg);
441         insert_zspage(page, class, newfg);
442         set_zspage_mapping(page, class_idx, newfg);
443
444 out:
445         return newfg;
446 }
447
448 /*
449  * We have to decide on how many pages to link together
450  * to form a zspage for each size class. This is important
451  * to reduce wastage due to unusable space left at end of
452  * each zspage which is given as:
453  *      wastage = Zp - Zp % size_class
454  * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
455  *
456  * For example, for size class of 3/8 * PAGE_SIZE, we should
457  * link together 3 PAGE_SIZE sized pages to form a zspage
458  * since then we can perfectly fit in 8 such objects.
459  */
460 static int get_pages_per_zspage(int class_size)
461 {
462         int i, max_usedpc = 0;
463         /* zspage order which gives maximum used size per KB */
464         int max_usedpc_order = 1;
465
466         for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
467                 int zspage_size;
468                 int waste, usedpc;
469
470                 zspage_size = i * PAGE_SIZE;
471                 waste = zspage_size % class_size;
472                 usedpc = (zspage_size - waste) * 100 / zspage_size;
473
474                 if (usedpc > max_usedpc) {
475                         max_usedpc = usedpc;
476                         max_usedpc_order = i;
477                 }
478         }
479
480         return max_usedpc_order;
481 }
482
483 /*
484  * A single 'zspage' is composed of many system pages which are
485  * linked together using fields in struct page. This function finds
486  * the first/head page, given any component page of a zspage.
487  */
488 static struct page *get_first_page(struct page *page)
489 {
490         if (is_first_page(page))
491                 return page;
492         else
493                 return page->first_page;
494 }
495
496 static struct page *get_next_page(struct page *page)
497 {
498         struct page *next;
499
500         if (is_last_page(page))
501                 next = NULL;
502         else if (is_first_page(page))
503                 next = (struct page *)page->private;
504         else
505                 next = list_entry(page->lru.next, struct page, lru);
506
507         return next;
508 }
509
510 /*
511  * Encode <page, obj_idx> as a single handle value.
512  * On hardware platforms with physical memory starting at 0x0 the pfn
513  * could be 0 so we ensure that the handle will never be 0 by adjusting the
514  * encoded obj_idx value before encoding.
515  */
516 static void *obj_location_to_handle(struct page *page, unsigned long obj_idx)
517 {
518         unsigned long handle;
519
520         if (!page) {
521                 BUG_ON(obj_idx);
522                 return NULL;
523         }
524
525         handle = page_to_pfn(page) << OBJ_INDEX_BITS;
526         handle |= ((obj_idx + 1) & OBJ_INDEX_MASK);
527
528         return (void *)handle;
529 }
530
531 /*
532  * Decode <page, obj_idx> pair from the given object handle. We adjust the
533  * decoded obj_idx back to its original value since it was adjusted in
534  * obj_location_to_handle().
535  */
536 static void obj_handle_to_location(unsigned long handle, struct page **page,
537                                 unsigned long *obj_idx)
538 {
539         *page = pfn_to_page(handle >> OBJ_INDEX_BITS);
540         *obj_idx = (handle & OBJ_INDEX_MASK) - 1;
541 }
542
543 static unsigned long obj_idx_to_offset(struct page *page,
544                                 unsigned long obj_idx, int class_size)
545 {
546         unsigned long off = 0;
547
548         if (!is_first_page(page))
549                 off = page->index;
550
551         return off + obj_idx * class_size;
552 }
553
554 static void reset_page(struct page *page)
555 {
556         clear_bit(PG_private, &page->flags);
557         clear_bit(PG_private_2, &page->flags);
558         set_page_private(page, 0);
559         page->mapping = NULL;
560         page->freelist = NULL;
561         page_mapcount_reset(page);
562 }
563
564 static void free_zspage(struct page *first_page)
565 {
566         struct page *nextp, *tmp, *head_extra;
567
568         BUG_ON(!is_first_page(first_page));
569         BUG_ON(first_page->inuse);
570
571         head_extra = (struct page *)page_private(first_page);
572
573         reset_page(first_page);
574         __free_page(first_page);
575
576         /* zspage with only 1 system page */
577         if (!head_extra)
578                 return;
579
580         list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
581                 list_del(&nextp->lru);
582                 reset_page(nextp);
583                 __free_page(nextp);
584         }
585         reset_page(head_extra);
586         __free_page(head_extra);
587 }
588
589 /* Initialize a newly allocated zspage */
590 static void init_zspage(struct page *first_page, struct size_class *class)
591 {
592         unsigned long off = 0;
593         struct page *page = first_page;
594
595         BUG_ON(!is_first_page(first_page));
596         while (page) {
597                 struct page *next_page;
598                 struct link_free *link;
599                 unsigned int i, objs_on_page;
600
601                 /*
602                  * page->index stores offset of first object starting
603                  * in the page. For the first page, this is always 0,
604                  * so we use first_page->index (aka ->freelist) to store
605                  * head of corresponding zspage's freelist.
606                  */
607                 if (page != first_page)
608                         page->index = off;
609
610                 link = (struct link_free *)kmap_atomic(page) +
611                                                 off / sizeof(*link);
612                 objs_on_page = (PAGE_SIZE - off) / class->size;
613
614                 for (i = 1; i <= objs_on_page; i++) {
615                         off += class->size;
616                         if (off < PAGE_SIZE) {
617                                 link->next = obj_location_to_handle(page, i);
618                                 link += class->size / sizeof(*link);
619                         }
620                 }
621
622                 /*
623                  * We now come to the last (full or partial) object on this
624                  * page, which must point to the first object on the next
625                  * page (if present)
626                  */
627                 next_page = get_next_page(page);
628                 link->next = obj_location_to_handle(next_page, 0);
629                 kunmap_atomic(link);
630                 page = next_page;
631                 off = (off + class->size) % PAGE_SIZE;
632         }
633 }
634
635 /*
636  * Allocate a zspage for the given size class
637  */
638 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
639 {
640         int i, error;
641         struct page *first_page = NULL, *uninitialized_var(prev_page);
642
643         /*
644          * Allocate individual pages and link them together as:
645          * 1. first page->private = first sub-page
646          * 2. all sub-pages are linked together using page->lru
647          * 3. each sub-page is linked to the first page using page->first_page
648          *
649          * For each size class, First/Head pages are linked together using
650          * page->lru. Also, we set PG_private to identify the first page
651          * (i.e. no other sub-page has this flag set) and PG_private_2 to
652          * identify the last page.
653          */
654         error = -ENOMEM;
655         for (i = 0; i < class->pages_per_zspage; i++) {
656                 struct page *page;
657
658                 page = alloc_page(flags);
659                 if (!page)
660                         goto cleanup;
661
662                 INIT_LIST_HEAD(&page->lru);
663                 if (i == 0) {   /* first page */
664                         SetPagePrivate(page);
665                         set_page_private(page, 0);
666                         first_page = page;
667                         first_page->inuse = 0;
668                 }
669                 if (i == 1)
670                         first_page->private = (unsigned long)page;
671                 if (i >= 1)
672                         page->first_page = first_page;
673                 if (i >= 2)
674                         list_add(&page->lru, &prev_page->lru);
675                 if (i == class->pages_per_zspage - 1)   /* last page */
676                         SetPagePrivate2(page);
677                 prev_page = page;
678         }
679
680         init_zspage(first_page, class);
681
682         first_page->freelist = obj_location_to_handle(first_page, 0);
683         /* Maximum number of objects we can store in this zspage */
684         first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
685
686         error = 0; /* Success */
687
688 cleanup:
689         if (unlikely(error) && first_page) {
690                 free_zspage(first_page);
691                 first_page = NULL;
692         }
693
694         return first_page;
695 }
696
697 static struct page *find_get_zspage(struct size_class *class)
698 {
699         int i;
700         struct page *page;
701
702         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
703                 page = class->fullness_list[i];
704                 if (page)
705                         break;
706         }
707
708         return page;
709 }
710
711 #ifdef USE_PGTABLE_MAPPING
712 static inline int __zs_cpu_up(struct mapping_area *area)
713 {
714         /*
715          * Make sure we don't leak memory if a cpu UP notification
716          * and zs_init() race and both call zs_cpu_up() on the same cpu
717          */
718         if (area->vm)
719                 return 0;
720         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
721         if (!area->vm)
722                 return -ENOMEM;
723         return 0;
724 }
725
726 static inline void __zs_cpu_down(struct mapping_area *area)
727 {
728         if (area->vm)
729                 free_vm_area(area->vm);
730         area->vm = NULL;
731 }
732
733 static inline void *__zs_map_object(struct mapping_area *area,
734                                 struct page *pages[2], int off, int size)
735 {
736         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, &pages));
737         area->vm_addr = area->vm->addr;
738         return area->vm_addr + off;
739 }
740
741 static inline void __zs_unmap_object(struct mapping_area *area,
742                                 struct page *pages[2], int off, int size)
743 {
744         unsigned long addr = (unsigned long)area->vm_addr;
745
746         unmap_kernel_range(addr, PAGE_SIZE * 2);
747 }
748
749 #else /* USE_PGTABLE_MAPPING */
750
751 static inline int __zs_cpu_up(struct mapping_area *area)
752 {
753         /*
754          * Make sure we don't leak memory if a cpu UP notification
755          * and zs_init() race and both call zs_cpu_up() on the same cpu
756          */
757         if (area->vm_buf)
758                 return 0;
759         area->vm_buf = (char *)__get_free_page(GFP_KERNEL);
760         if (!area->vm_buf)
761                 return -ENOMEM;
762         return 0;
763 }
764
765 static inline void __zs_cpu_down(struct mapping_area *area)
766 {
767         if (area->vm_buf)
768                 free_page((unsigned long)area->vm_buf);
769         area->vm_buf = NULL;
770 }
771
772 static void *__zs_map_object(struct mapping_area *area,
773                         struct page *pages[2], int off, int size)
774 {
775         int sizes[2];
776         void *addr;
777         char *buf = area->vm_buf;
778
779         /* disable page faults to match kmap_atomic() return conditions */
780         pagefault_disable();
781
782         /* no read fastpath */
783         if (area->vm_mm == ZS_MM_WO)
784                 goto out;
785
786         sizes[0] = PAGE_SIZE - off;
787         sizes[1] = size - sizes[0];
788
789         /* copy object to per-cpu buffer */
790         addr = kmap_atomic(pages[0]);
791         memcpy(buf, addr + off, sizes[0]);
792         kunmap_atomic(addr);
793         addr = kmap_atomic(pages[1]);
794         memcpy(buf + sizes[0], addr, sizes[1]);
795         kunmap_atomic(addr);
796 out:
797         return area->vm_buf;
798 }
799
800 static void __zs_unmap_object(struct mapping_area *area,
801                         struct page *pages[2], int off, int size)
802 {
803         int sizes[2];
804         void *addr;
805         char *buf = area->vm_buf;
806
807         /* no write fastpath */
808         if (area->vm_mm == ZS_MM_RO)
809                 goto out;
810
811         sizes[0] = PAGE_SIZE - off;
812         sizes[1] = size - sizes[0];
813
814         /* copy per-cpu buffer to object */
815         addr = kmap_atomic(pages[0]);
816         memcpy(addr + off, buf, sizes[0]);
817         kunmap_atomic(addr);
818         addr = kmap_atomic(pages[1]);
819         memcpy(addr, buf + sizes[0], sizes[1]);
820         kunmap_atomic(addr);
821
822 out:
823         /* enable page faults to match kunmap_atomic() return conditions */
824         pagefault_enable();
825 }
826
827 #endif /* USE_PGTABLE_MAPPING */
828
829 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
830                                 void *pcpu)
831 {
832         int ret, cpu = (long)pcpu;
833         struct mapping_area *area;
834
835         switch (action) {
836         case CPU_UP_PREPARE:
837                 area = &per_cpu(zs_map_area, cpu);
838                 ret = __zs_cpu_up(area);
839                 if (ret)
840                         return notifier_from_errno(ret);
841                 break;
842         case CPU_DEAD:
843         case CPU_UP_CANCELED:
844                 area = &per_cpu(zs_map_area, cpu);
845                 __zs_cpu_down(area);
846                 break;
847         }
848
849         return NOTIFY_OK;
850 }
851
852 static struct notifier_block zs_cpu_nb = {
853         .notifier_call = zs_cpu_notifier
854 };
855
856 static void zs_exit(void)
857 {
858         int cpu;
859
860 #ifdef CONFIG_ZPOOL
861         zpool_unregister_driver(&zs_zpool_driver);
862 #endif
863
864         cpu_notifier_register_begin();
865
866         for_each_online_cpu(cpu)
867                 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
868         __unregister_cpu_notifier(&zs_cpu_nb);
869
870         cpu_notifier_register_done();
871 }
872
873 static int zs_init(void)
874 {
875         int cpu, ret;
876
877         cpu_notifier_register_begin();
878
879         __register_cpu_notifier(&zs_cpu_nb);
880         for_each_online_cpu(cpu) {
881                 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
882                 if (notifier_to_errno(ret)) {
883                         cpu_notifier_register_done();
884                         goto fail;
885                 }
886         }
887
888         cpu_notifier_register_done();
889
890 #ifdef CONFIG_ZPOOL
891         zpool_register_driver(&zs_zpool_driver);
892 #endif
893
894         return 0;
895 fail:
896         zs_exit();
897         return notifier_to_errno(ret);
898 }
899
900 /**
901  * zs_create_pool - Creates an allocation pool to work from.
902  * @flags: allocation flags used to allocate pool metadata
903  *
904  * This function must be called before anything when using
905  * the zsmalloc allocator.
906  *
907  * On success, a pointer to the newly created pool is returned,
908  * otherwise NULL.
909  */
910 struct zs_pool *zs_create_pool(gfp_t flags)
911 {
912         int i, ovhd_size;
913         struct zs_pool *pool;
914
915         ovhd_size = roundup(sizeof(*pool), PAGE_SIZE);
916         pool = kzalloc(ovhd_size, GFP_KERNEL);
917         if (!pool)
918                 return NULL;
919
920         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
921                 int size;
922                 struct size_class *class;
923
924                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
925                 if (size > ZS_MAX_ALLOC_SIZE)
926                         size = ZS_MAX_ALLOC_SIZE;
927
928                 class = &pool->size_class[i];
929                 class->size = size;
930                 class->index = i;
931                 spin_lock_init(&class->lock);
932                 class->pages_per_zspage = get_pages_per_zspage(size);
933
934         }
935
936         pool->flags = flags;
937
938         return pool;
939 }
940 EXPORT_SYMBOL_GPL(zs_create_pool);
941
942 void zs_destroy_pool(struct zs_pool *pool)
943 {
944         int i;
945
946         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
947                 int fg;
948                 struct size_class *class = &pool->size_class[i];
949
950                 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
951                         if (class->fullness_list[fg]) {
952                                 pr_info("Freeing non-empty class with size "
953                                         "%db, fullness group %d\n",
954                                         class->size, fg);
955                         }
956                 }
957         }
958         kfree(pool);
959 }
960 EXPORT_SYMBOL_GPL(zs_destroy_pool);
961
962 /**
963  * zs_malloc - Allocate block of given size from pool.
964  * @pool: pool to allocate from
965  * @size: size of block to allocate
966  *
967  * On success, handle to the allocated object is returned,
968  * otherwise 0.
969  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
970  */
971 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
972 {
973         unsigned long obj;
974         struct link_free *link;
975         int class_idx;
976         struct size_class *class;
977
978         struct page *first_page, *m_page;
979         unsigned long m_objidx, m_offset;
980
981         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
982                 return 0;
983
984         class_idx = get_size_class_index(size);
985         class = &pool->size_class[class_idx];
986         BUG_ON(class_idx != class->index);
987
988         spin_lock(&class->lock);
989         first_page = find_get_zspage(class);
990
991         if (!first_page) {
992                 spin_unlock(&class->lock);
993                 first_page = alloc_zspage(class, pool->flags);
994                 if (unlikely(!first_page))
995                         return 0;
996
997                 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
998                 spin_lock(&class->lock);
999                 class->pages_allocated += class->pages_per_zspage;
1000         }
1001
1002         obj = (unsigned long)first_page->freelist;
1003         obj_handle_to_location(obj, &m_page, &m_objidx);
1004         m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1005
1006         link = (struct link_free *)kmap_atomic(m_page) +
1007                                         m_offset / sizeof(*link);
1008         first_page->freelist = link->next;
1009         memset(link, POISON_INUSE, sizeof(*link));
1010         kunmap_atomic(link);
1011
1012         first_page->inuse++;
1013         /* Now move the zspage to another fullness group, if required */
1014         fix_fullness_group(pool, first_page);
1015         spin_unlock(&class->lock);
1016
1017         return obj;
1018 }
1019 EXPORT_SYMBOL_GPL(zs_malloc);
1020
1021 void zs_free(struct zs_pool *pool, unsigned long obj)
1022 {
1023         struct link_free *link;
1024         struct page *first_page, *f_page;
1025         unsigned long f_objidx, f_offset;
1026
1027         int class_idx;
1028         struct size_class *class;
1029         enum fullness_group fullness;
1030
1031         if (unlikely(!obj))
1032                 return;
1033
1034         obj_handle_to_location(obj, &f_page, &f_objidx);
1035         first_page = get_first_page(f_page);
1036
1037         get_zspage_mapping(first_page, &class_idx, &fullness);
1038         class = &pool->size_class[class_idx];
1039         f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1040
1041         spin_lock(&class->lock);
1042
1043         /* Insert this object in containing zspage's freelist */
1044         link = (struct link_free *)((unsigned char *)kmap_atomic(f_page)
1045                                                         + f_offset);
1046         link->next = first_page->freelist;
1047         kunmap_atomic(link);
1048         first_page->freelist = (void *)obj;
1049
1050         first_page->inuse--;
1051         fullness = fix_fullness_group(pool, first_page);
1052
1053         if (fullness == ZS_EMPTY)
1054                 class->pages_allocated -= class->pages_per_zspage;
1055
1056         spin_unlock(&class->lock);
1057
1058         if (fullness == ZS_EMPTY)
1059                 free_zspage(first_page);
1060 }
1061 EXPORT_SYMBOL_GPL(zs_free);
1062
1063 /**
1064  * zs_map_object - get address of allocated object from handle.
1065  * @pool: pool from which the object was allocated
1066  * @handle: handle returned from zs_malloc
1067  *
1068  * Before using an object allocated from zs_malloc, it must be mapped using
1069  * this function. When done with the object, it must be unmapped using
1070  * zs_unmap_object.
1071  *
1072  * Only one object can be mapped per cpu at a time. There is no protection
1073  * against nested mappings.
1074  *
1075  * This function returns with preemption and page faults disabled.
1076 */
1077 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1078                         enum zs_mapmode mm)
1079 {
1080         struct page *page;
1081         unsigned long obj_idx, off;
1082
1083         unsigned int class_idx;
1084         enum fullness_group fg;
1085         struct size_class *class;
1086         struct mapping_area *area;
1087         struct page *pages[2];
1088
1089         BUG_ON(!handle);
1090
1091         /*
1092          * Because we use per-cpu mapping areas shared among the
1093          * pools/users, we can't allow mapping in interrupt context
1094          * because it can corrupt another users mappings.
1095          */
1096         BUG_ON(in_interrupt());
1097
1098         obj_handle_to_location(handle, &page, &obj_idx);
1099         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1100         class = &pool->size_class[class_idx];
1101         off = obj_idx_to_offset(page, obj_idx, class->size);
1102
1103         area = &get_cpu_var(zs_map_area);
1104         area->vm_mm = mm;
1105         if (off + class->size <= PAGE_SIZE) {
1106                 /* this object is contained entirely within a page */
1107                 area->vm_addr = kmap_atomic(page);
1108                 return area->vm_addr + off;
1109         }
1110
1111         /* this object spans two pages */
1112         pages[0] = page;
1113         pages[1] = get_next_page(page);
1114         BUG_ON(!pages[1]);
1115
1116         return __zs_map_object(area, pages, off, class->size);
1117 }
1118 EXPORT_SYMBOL_GPL(zs_map_object);
1119
1120 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1121 {
1122         struct page *page;
1123         unsigned long obj_idx, off;
1124
1125         unsigned int class_idx;
1126         enum fullness_group fg;
1127         struct size_class *class;
1128         struct mapping_area *area;
1129
1130         BUG_ON(!handle);
1131
1132         obj_handle_to_location(handle, &page, &obj_idx);
1133         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1134         class = &pool->size_class[class_idx];
1135         off = obj_idx_to_offset(page, obj_idx, class->size);
1136
1137         area = &__get_cpu_var(zs_map_area);
1138         if (off + class->size <= PAGE_SIZE)
1139                 kunmap_atomic(area->vm_addr);
1140         else {
1141                 struct page *pages[2];
1142
1143                 pages[0] = page;
1144                 pages[1] = get_next_page(page);
1145                 BUG_ON(!pages[1]);
1146
1147                 __zs_unmap_object(area, pages, off, class->size);
1148         }
1149         put_cpu_var(zs_map_area);
1150 }
1151 EXPORT_SYMBOL_GPL(zs_unmap_object);
1152
1153 u64 zs_get_total_size_bytes(struct zs_pool *pool)
1154 {
1155         int i;
1156         u64 npages = 0;
1157
1158         for (i = 0; i < ZS_SIZE_CLASSES; i++)
1159                 npages += pool->size_class[i].pages_allocated;
1160
1161         return npages << PAGE_SHIFT;
1162 }
1163 EXPORT_SYMBOL_GPL(zs_get_total_size_bytes);
1164
1165 module_init(zs_init);
1166 module_exit(zs_exit);
1167
1168 MODULE_LICENSE("Dual BSD/GPL");
1169 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");