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