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