zsmalloc: merge size_class to reduce fragmentation
[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
599                 /*
600                  * page->index stores offset of first object starting
601                  * in the page. For the first page, this is always 0,
602                  * so we use first_page->index (aka ->freelist) to store
603                  * head of corresponding zspage's freelist.
604                  */
605                 if (page != first_page)
606                         page->index = off;
607
608                 link = (struct link_free *)kmap_atomic(page) +
609                                                 off / sizeof(*link);
610
611                 while ((off += class->size) < PAGE_SIZE) {
612                         link->next = obj_location_to_handle(page, i++);
613                         link += class->size / sizeof(*link);
614                 }
615
616                 /*
617                  * We now come to the last (full or partial) object on this
618                  * page, which must point to the first object on the next
619                  * page (if present)
620                  */
621                 next_page = get_next_page(page);
622                 link->next = obj_location_to_handle(next_page, 0);
623                 kunmap_atomic(link);
624                 page = next_page;
625                 off %= PAGE_SIZE;
626         }
627 }
628
629 /*
630  * Allocate a zspage for the given size class
631  */
632 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
633 {
634         int i, error;
635         struct page *first_page = NULL, *uninitialized_var(prev_page);
636
637         /*
638          * Allocate individual pages and link them together as:
639          * 1. first page->private = first sub-page
640          * 2. all sub-pages are linked together using page->lru
641          * 3. each sub-page is linked to the first page using page->first_page
642          *
643          * For each size class, First/Head pages are linked together using
644          * page->lru. Also, we set PG_private to identify the first page
645          * (i.e. no other sub-page has this flag set) and PG_private_2 to
646          * identify the last page.
647          */
648         error = -ENOMEM;
649         for (i = 0; i < class->pages_per_zspage; i++) {
650                 struct page *page;
651
652                 page = alloc_page(flags);
653                 if (!page)
654                         goto cleanup;
655
656                 INIT_LIST_HEAD(&page->lru);
657                 if (i == 0) {   /* first page */
658                         SetPagePrivate(page);
659                         set_page_private(page, 0);
660                         first_page = page;
661                         first_page->inuse = 0;
662                 }
663                 if (i == 1)
664                         first_page->private = (unsigned long)page;
665                 if (i >= 1)
666                         page->first_page = first_page;
667                 if (i >= 2)
668                         list_add(&page->lru, &prev_page->lru);
669                 if (i == class->pages_per_zspage - 1)   /* last page */
670                         SetPagePrivate2(page);
671                 prev_page = page;
672         }
673
674         init_zspage(first_page, class);
675
676         first_page->freelist = obj_location_to_handle(first_page, 0);
677         /* Maximum number of objects we can store in this zspage */
678         first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
679
680         error = 0; /* Success */
681
682 cleanup:
683         if (unlikely(error) && first_page) {
684                 free_zspage(first_page);
685                 first_page = NULL;
686         }
687
688         return first_page;
689 }
690
691 static struct page *find_get_zspage(struct size_class *class)
692 {
693         int i;
694         struct page *page;
695
696         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
697                 page = class->fullness_list[i];
698                 if (page)
699                         break;
700         }
701
702         return page;
703 }
704
705 #ifdef USE_PGTABLE_MAPPING
706 static inline int __zs_cpu_up(struct mapping_area *area)
707 {
708         /*
709          * Make sure we don't leak memory if a cpu UP notification
710          * and zs_init() race and both call zs_cpu_up() on the same cpu
711          */
712         if (area->vm)
713                 return 0;
714         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
715         if (!area->vm)
716                 return -ENOMEM;
717         return 0;
718 }
719
720 static inline void __zs_cpu_down(struct mapping_area *area)
721 {
722         if (area->vm)
723                 free_vm_area(area->vm);
724         area->vm = NULL;
725 }
726
727 static inline void *__zs_map_object(struct mapping_area *area,
728                                 struct page *pages[2], int off, int size)
729 {
730         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, &pages));
731         area->vm_addr = area->vm->addr;
732         return area->vm_addr + off;
733 }
734
735 static inline void __zs_unmap_object(struct mapping_area *area,
736                                 struct page *pages[2], int off, int size)
737 {
738         unsigned long addr = (unsigned long)area->vm_addr;
739
740         unmap_kernel_range(addr, PAGE_SIZE * 2);
741 }
742
743 #else /* USE_PGTABLE_MAPPING */
744
745 static inline int __zs_cpu_up(struct mapping_area *area)
746 {
747         /*
748          * Make sure we don't leak memory if a cpu UP notification
749          * and zs_init() race and both call zs_cpu_up() on the same cpu
750          */
751         if (area->vm_buf)
752                 return 0;
753         area->vm_buf = (char *)__get_free_page(GFP_KERNEL);
754         if (!area->vm_buf)
755                 return -ENOMEM;
756         return 0;
757 }
758
759 static inline void __zs_cpu_down(struct mapping_area *area)
760 {
761         if (area->vm_buf)
762                 free_page((unsigned long)area->vm_buf);
763         area->vm_buf = NULL;
764 }
765
766 static void *__zs_map_object(struct mapping_area *area,
767                         struct page *pages[2], int off, int size)
768 {
769         int sizes[2];
770         void *addr;
771         char *buf = area->vm_buf;
772
773         /* disable page faults to match kmap_atomic() return conditions */
774         pagefault_disable();
775
776         /* no read fastpath */
777         if (area->vm_mm == ZS_MM_WO)
778                 goto out;
779
780         sizes[0] = PAGE_SIZE - off;
781         sizes[1] = size - sizes[0];
782
783         /* copy object to per-cpu buffer */
784         addr = kmap_atomic(pages[0]);
785         memcpy(buf, addr + off, sizes[0]);
786         kunmap_atomic(addr);
787         addr = kmap_atomic(pages[1]);
788         memcpy(buf + sizes[0], addr, sizes[1]);
789         kunmap_atomic(addr);
790 out:
791         return area->vm_buf;
792 }
793
794 static void __zs_unmap_object(struct mapping_area *area,
795                         struct page *pages[2], int off, int size)
796 {
797         int sizes[2];
798         void *addr;
799         char *buf = area->vm_buf;
800
801         /* no write fastpath */
802         if (area->vm_mm == ZS_MM_RO)
803                 goto out;
804
805         sizes[0] = PAGE_SIZE - off;
806         sizes[1] = size - sizes[0];
807
808         /* copy per-cpu buffer to object */
809         addr = kmap_atomic(pages[0]);
810         memcpy(addr + off, buf, sizes[0]);
811         kunmap_atomic(addr);
812         addr = kmap_atomic(pages[1]);
813         memcpy(addr, buf + sizes[0], sizes[1]);
814         kunmap_atomic(addr);
815
816 out:
817         /* enable page faults to match kunmap_atomic() return conditions */
818         pagefault_enable();
819 }
820
821 #endif /* USE_PGTABLE_MAPPING */
822
823 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
824                                 void *pcpu)
825 {
826         int ret, cpu = (long)pcpu;
827         struct mapping_area *area;
828
829         switch (action) {
830         case CPU_UP_PREPARE:
831                 area = &per_cpu(zs_map_area, cpu);
832                 ret = __zs_cpu_up(area);
833                 if (ret)
834                         return notifier_from_errno(ret);
835                 break;
836         case CPU_DEAD:
837         case CPU_UP_CANCELED:
838                 area = &per_cpu(zs_map_area, cpu);
839                 __zs_cpu_down(area);
840                 break;
841         }
842
843         return NOTIFY_OK;
844 }
845
846 static struct notifier_block zs_cpu_nb = {
847         .notifier_call = zs_cpu_notifier
848 };
849
850 static void zs_exit(void)
851 {
852         int cpu;
853
854 #ifdef CONFIG_ZPOOL
855         zpool_unregister_driver(&zs_zpool_driver);
856 #endif
857
858         cpu_notifier_register_begin();
859
860         for_each_online_cpu(cpu)
861                 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
862         __unregister_cpu_notifier(&zs_cpu_nb);
863
864         cpu_notifier_register_done();
865 }
866
867 static int zs_init(void)
868 {
869         int cpu, ret;
870
871         cpu_notifier_register_begin();
872
873         __register_cpu_notifier(&zs_cpu_nb);
874         for_each_online_cpu(cpu) {
875                 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
876                 if (notifier_to_errno(ret)) {
877                         cpu_notifier_register_done();
878                         goto fail;
879                 }
880         }
881
882         cpu_notifier_register_done();
883
884 #ifdef CONFIG_ZPOOL
885         zpool_register_driver(&zs_zpool_driver);
886 #endif
887
888         return 0;
889 fail:
890         zs_exit();
891         return notifier_to_errno(ret);
892 }
893
894 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
895 {
896         return pages_per_zspage * PAGE_SIZE / size;
897 }
898
899 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
900 {
901         if (prev->pages_per_zspage != pages_per_zspage)
902                 return false;
903
904         if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
905                 != get_maxobj_per_zspage(size, pages_per_zspage))
906                 return false;
907
908         return true;
909 }
910
911 /**
912  * zs_create_pool - Creates an allocation pool to work from.
913  * @flags: allocation flags used to allocate pool metadata
914  *
915  * This function must be called before anything when using
916  * the zsmalloc allocator.
917  *
918  * On success, a pointer to the newly created pool is returned,
919  * otherwise NULL.
920  */
921 struct zs_pool *zs_create_pool(gfp_t flags)
922 {
923         int i, ovhd_size;
924         struct zs_pool *pool;
925
926         ovhd_size = roundup(sizeof(*pool), PAGE_SIZE);
927         pool = kzalloc(ovhd_size, GFP_KERNEL);
928         if (!pool)
929                 return NULL;
930
931         /*
932          * Iterate reversly, because, size of size_class that we want to use
933          * for merging should be larger or equal to current size.
934          */
935         for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
936                 int size;
937                 int pages_per_zspage;
938                 struct size_class *class;
939                 struct size_class *prev_class;
940
941                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
942                 if (size > ZS_MAX_ALLOC_SIZE)
943                         size = ZS_MAX_ALLOC_SIZE;
944                 pages_per_zspage = get_pages_per_zspage(size);
945
946                 /*
947                  * size_class is used for normal zsmalloc operation such
948                  * as alloc/free for that size. Although it is natural that we
949                  * have one size_class for each size, there is a chance that we
950                  * can get more memory utilization if we use one size_class for
951                  * many different sizes whose size_class have same
952                  * characteristics. So, we makes size_class point to
953                  * previous size_class if possible.
954                  */
955                 if (i < ZS_SIZE_CLASSES - 1) {
956                         prev_class = pool->size_class[i + 1];
957                         if (can_merge(prev_class, size, pages_per_zspage)) {
958                                 pool->size_class[i] = prev_class;
959                                 continue;
960                         }
961                 }
962
963                 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
964                 if (!class)
965                         goto err;
966
967                 class->size = size;
968                 class->index = i;
969                 class->pages_per_zspage = pages_per_zspage;
970                 spin_lock_init(&class->lock);
971                 pool->size_class[i] = class;
972         }
973
974         pool->flags = flags;
975
976         return pool;
977
978 err:
979         zs_destroy_pool(pool);
980         return NULL;
981 }
982 EXPORT_SYMBOL_GPL(zs_create_pool);
983
984 void zs_destroy_pool(struct zs_pool *pool)
985 {
986         int i;
987
988         for (i = 0; i < ZS_SIZE_CLASSES; i++) {
989                 int fg;
990                 struct size_class *class = pool->size_class[i];
991
992                 if (!class)
993                         continue;
994
995                 if (class->index != i)
996                         continue;
997
998                 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
999                         if (class->fullness_list[fg]) {
1000                                 pr_info("Freeing non-empty class with size "
1001                                         "%db, fullness group %d\n",
1002                                         class->size, fg);
1003                         }
1004                 }
1005                 kfree(class);
1006         }
1007         kfree(pool);
1008 }
1009 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1010
1011 /**
1012  * zs_malloc - Allocate block of given size from pool.
1013  * @pool: pool to allocate from
1014  * @size: size of block to allocate
1015  *
1016  * On success, handle to the allocated object is returned,
1017  * otherwise 0.
1018  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1019  */
1020 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1021 {
1022         unsigned long obj;
1023         struct link_free *link;
1024         struct size_class *class;
1025
1026         struct page *first_page, *m_page;
1027         unsigned long m_objidx, m_offset;
1028
1029         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1030                 return 0;
1031
1032         class = pool->size_class[get_size_class_index(size)];
1033
1034         spin_lock(&class->lock);
1035         first_page = find_get_zspage(class);
1036
1037         if (!first_page) {
1038                 spin_unlock(&class->lock);
1039                 first_page = alloc_zspage(class, pool->flags);
1040                 if (unlikely(!first_page))
1041                         return 0;
1042
1043                 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1044                 atomic_long_add(class->pages_per_zspage,
1045                                         &pool->pages_allocated);
1046                 spin_lock(&class->lock);
1047         }
1048
1049         obj = (unsigned long)first_page->freelist;
1050         obj_handle_to_location(obj, &m_page, &m_objidx);
1051         m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1052
1053         link = (struct link_free *)kmap_atomic(m_page) +
1054                                         m_offset / sizeof(*link);
1055         first_page->freelist = link->next;
1056         memset(link, POISON_INUSE, sizeof(*link));
1057         kunmap_atomic(link);
1058
1059         first_page->inuse++;
1060         /* Now move the zspage to another fullness group, if required */
1061         fix_fullness_group(pool, first_page);
1062         spin_unlock(&class->lock);
1063
1064         return obj;
1065 }
1066 EXPORT_SYMBOL_GPL(zs_malloc);
1067
1068 void zs_free(struct zs_pool *pool, unsigned long obj)
1069 {
1070         struct link_free *link;
1071         struct page *first_page, *f_page;
1072         unsigned long f_objidx, f_offset;
1073
1074         int class_idx;
1075         struct size_class *class;
1076         enum fullness_group fullness;
1077
1078         if (unlikely(!obj))
1079                 return;
1080
1081         obj_handle_to_location(obj, &f_page, &f_objidx);
1082         first_page = get_first_page(f_page);
1083
1084         get_zspage_mapping(first_page, &class_idx, &fullness);
1085         class = pool->size_class[class_idx];
1086         f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1087
1088         spin_lock(&class->lock);
1089
1090         /* Insert this object in containing zspage's freelist */
1091         link = (struct link_free *)((unsigned char *)kmap_atomic(f_page)
1092                                                         + f_offset);
1093         link->next = first_page->freelist;
1094         kunmap_atomic(link);
1095         first_page->freelist = (void *)obj;
1096
1097         first_page->inuse--;
1098         fullness = fix_fullness_group(pool, first_page);
1099         spin_unlock(&class->lock);
1100
1101         if (fullness == ZS_EMPTY) {
1102                 atomic_long_sub(class->pages_per_zspage,
1103                                 &pool->pages_allocated);
1104                 free_zspage(first_page);
1105         }
1106 }
1107 EXPORT_SYMBOL_GPL(zs_free);
1108
1109 /**
1110  * zs_map_object - get address of allocated object from handle.
1111  * @pool: pool from which the object was allocated
1112  * @handle: handle returned from zs_malloc
1113  *
1114  * Before using an object allocated from zs_malloc, it must be mapped using
1115  * this function. When done with the object, it must be unmapped using
1116  * zs_unmap_object.
1117  *
1118  * Only one object can be mapped per cpu at a time. There is no protection
1119  * against nested mappings.
1120  *
1121  * This function returns with preemption and page faults disabled.
1122 */
1123 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1124                         enum zs_mapmode mm)
1125 {
1126         struct page *page;
1127         unsigned long obj_idx, off;
1128
1129         unsigned int class_idx;
1130         enum fullness_group fg;
1131         struct size_class *class;
1132         struct mapping_area *area;
1133         struct page *pages[2];
1134
1135         BUG_ON(!handle);
1136
1137         /*
1138          * Because we use per-cpu mapping areas shared among the
1139          * pools/users, we can't allow mapping in interrupt context
1140          * because it can corrupt another users mappings.
1141          */
1142         BUG_ON(in_interrupt());
1143
1144         obj_handle_to_location(handle, &page, &obj_idx);
1145         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1146         class = pool->size_class[class_idx];
1147         off = obj_idx_to_offset(page, obj_idx, class->size);
1148
1149         area = &get_cpu_var(zs_map_area);
1150         area->vm_mm = mm;
1151         if (off + class->size <= PAGE_SIZE) {
1152                 /* this object is contained entirely within a page */
1153                 area->vm_addr = kmap_atomic(page);
1154                 return area->vm_addr + off;
1155         }
1156
1157         /* this object spans two pages */
1158         pages[0] = page;
1159         pages[1] = get_next_page(page);
1160         BUG_ON(!pages[1]);
1161
1162         return __zs_map_object(area, pages, off, class->size);
1163 }
1164 EXPORT_SYMBOL_GPL(zs_map_object);
1165
1166 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1167 {
1168         struct page *page;
1169         unsigned long obj_idx, off;
1170
1171         unsigned int class_idx;
1172         enum fullness_group fg;
1173         struct size_class *class;
1174         struct mapping_area *area;
1175
1176         BUG_ON(!handle);
1177
1178         obj_handle_to_location(handle, &page, &obj_idx);
1179         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1180         class = pool->size_class[class_idx];
1181         off = obj_idx_to_offset(page, obj_idx, class->size);
1182
1183         area = &__get_cpu_var(zs_map_area);
1184         if (off + class->size <= PAGE_SIZE)
1185                 kunmap_atomic(area->vm_addr);
1186         else {
1187                 struct page *pages[2];
1188
1189                 pages[0] = page;
1190                 pages[1] = get_next_page(page);
1191                 BUG_ON(!pages[1]);
1192
1193                 __zs_unmap_object(area, pages, off, class->size);
1194         }
1195         put_cpu_var(zs_map_area);
1196 }
1197 EXPORT_SYMBOL_GPL(zs_unmap_object);
1198
1199 unsigned long zs_get_total_pages(struct zs_pool *pool)
1200 {
1201         return atomic_long_read(&pool->pages_allocated);
1202 }
1203 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1204
1205 module_init(zs_init);
1206 module_exit(zs_exit);
1207
1208 MODULE_LICENSE("Dual BSD/GPL");
1209 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");