zsmalloc: record handle in page->private for huge object
[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  * 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  *              If the page is first_page for huge object, it stores handle.
61  *              Look at size_class->huge.
62  *      page->freelist: points to the first free object in zspage.
63  *              Free objects are linked together using in-place
64  *              metadata.
65  *      page->objects: maximum number of objects we can store in this
66  *              zspage (class->zspage_order * PAGE_SIZE / class->size)
67  *      page->lru: links together first pages of various zspages.
68  *              Basically forming list of zspages in a fullness group.
69  *      page->mapping: class index and fullness group of the zspage
70  *
71  * Usage of struct page flags:
72  *      PG_private: identifies the first component page
73  *      PG_private2: identifies the last component page
74  *
75  */
76
77 #ifdef CONFIG_ZSMALLOC_DEBUG
78 #define DEBUG
79 #endif
80
81 #include <linux/module.h>
82 #include <linux/kernel.h>
83 #include <linux/sched.h>
84 #include <linux/bitops.h>
85 #include <linux/errno.h>
86 #include <linux/highmem.h>
87 #include <linux/string.h>
88 #include <linux/slab.h>
89 #include <asm/tlbflush.h>
90 #include <asm/pgtable.h>
91 #include <linux/cpumask.h>
92 #include <linux/cpu.h>
93 #include <linux/vmalloc.h>
94 #include <linux/hardirq.h>
95 #include <linux/spinlock.h>
96 #include <linux/types.h>
97 #include <linux/debugfs.h>
98 #include <linux/zsmalloc.h>
99 #include <linux/zpool.h>
100
101 /*
102  * This must be power of 2 and greater than of equal to sizeof(link_free).
103  * These two conditions ensure that any 'struct link_free' itself doesn't
104  * span more than 1 page which avoids complex case of mapping 2 pages simply
105  * to restore link_free pointer values.
106  */
107 #define ZS_ALIGN                8
108
109 /*
110  * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
111  * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
112  */
113 #define ZS_MAX_ZSPAGE_ORDER 2
114 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
115
116 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
117
118 /*
119  * Object location (<PFN>, <obj_idx>) is encoded as
120  * as single (unsigned long) handle value.
121  *
122  * Note that object index <obj_idx> is relative to system
123  * page <PFN> it is stored in, so for each sub-page belonging
124  * to a zspage, obj_idx starts with 0.
125  *
126  * This is made more complicated by various memory models and PAE.
127  */
128
129 #ifndef MAX_PHYSMEM_BITS
130 #ifdef CONFIG_HIGHMEM64G
131 #define MAX_PHYSMEM_BITS 36
132 #else /* !CONFIG_HIGHMEM64G */
133 /*
134  * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
135  * be PAGE_SHIFT
136  */
137 #define MAX_PHYSMEM_BITS BITS_PER_LONG
138 #endif
139 #endif
140 #define _PFN_BITS               (MAX_PHYSMEM_BITS - PAGE_SHIFT)
141
142 /*
143  * Memory for allocating for handle keeps object position by
144  * encoding <page, obj_idx> and the encoded value has a room
145  * in least bit(ie, look at obj_to_location).
146  * We use the bit to synchronize between object access by
147  * user and migration.
148  */
149 #define HANDLE_PIN_BIT  0
150
151 /*
152  * Head in allocated object should have OBJ_ALLOCATED_TAG
153  * to identify the object was allocated or not.
154  * It's okay to add the status bit in the least bit because
155  * header keeps handle which is 4byte-aligned address so we
156  * have room for two bit at least.
157  */
158 #define OBJ_ALLOCATED_TAG 1
159 #define OBJ_TAG_BITS 1
160 #define OBJ_INDEX_BITS  (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
161 #define OBJ_INDEX_MASK  ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
162
163 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
164 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
165 #define ZS_MIN_ALLOC_SIZE \
166         MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
167 /* each chunk includes extra space to keep handle */
168 #define ZS_MAX_ALLOC_SIZE       PAGE_SIZE
169
170 /*
171  * On systems with 4K page size, this gives 255 size classes! There is a
172  * trader-off here:
173  *  - Large number of size classes is potentially wasteful as free page are
174  *    spread across these classes
175  *  - Small number of size classes causes large internal fragmentation
176  *  - Probably its better to use specific size classes (empirically
177  *    determined). NOTE: all those class sizes must be set as multiple of
178  *    ZS_ALIGN to make sure link_free itself never has to span 2 pages.
179  *
180  *  ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
181  *  (reason above)
182  */
183 #define ZS_SIZE_CLASS_DELTA     (PAGE_SIZE >> 8)
184
185 /*
186  * We do not maintain any list for completely empty or full pages
187  */
188 enum fullness_group {
189         ZS_ALMOST_FULL,
190         ZS_ALMOST_EMPTY,
191         _ZS_NR_FULLNESS_GROUPS,
192
193         ZS_EMPTY,
194         ZS_FULL
195 };
196
197 enum zs_stat_type {
198         OBJ_ALLOCATED,
199         OBJ_USED,
200         NR_ZS_STAT_TYPE,
201 };
202
203 #ifdef CONFIG_ZSMALLOC_STAT
204
205 static struct dentry *zs_stat_root;
206
207 struct zs_size_stat {
208         unsigned long objs[NR_ZS_STAT_TYPE];
209 };
210
211 #endif
212
213 /*
214  * number of size_classes
215  */
216 static int zs_size_classes;
217
218 /*
219  * We assign a page to ZS_ALMOST_EMPTY fullness group when:
220  *      n <= N / f, where
221  * n = number of allocated objects
222  * N = total number of objects zspage can store
223  * f = fullness_threshold_frac
224  *
225  * Similarly, we assign zspage to:
226  *      ZS_ALMOST_FULL  when n > N / f
227  *      ZS_EMPTY        when n == 0
228  *      ZS_FULL         when n == N
229  *
230  * (see: fix_fullness_group())
231  */
232 static const int fullness_threshold_frac = 4;
233
234 struct size_class {
235         /*
236          * Size of objects stored in this class. Must be multiple
237          * of ZS_ALIGN.
238          */
239         int size;
240         unsigned int index;
241
242         /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
243         int pages_per_zspage;
244         /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
245         bool huge;
246
247 #ifdef CONFIG_ZSMALLOC_STAT
248         struct zs_size_stat stats;
249 #endif
250
251         spinlock_t lock;
252
253         struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
254 };
255
256 /*
257  * Placed within free objects to form a singly linked list.
258  * For every zspage, first_page->freelist gives head of this list.
259  *
260  * This must be power of 2 and less than or equal to ZS_ALIGN
261  */
262 struct link_free {
263         union {
264                 /*
265                  * Position of next free chunk (encodes <PFN, obj_idx>)
266                  * It's valid for non-allocated object
267                  */
268                 void *next;
269                 /*
270                  * Handle of allocated object.
271                  */
272                 unsigned long handle;
273         };
274 };
275
276 struct zs_pool {
277         char *name;
278
279         struct size_class **size_class;
280         struct kmem_cache *handle_cachep;
281
282         gfp_t flags;    /* allocation flags used when growing pool */
283         atomic_long_t pages_allocated;
284
285 #ifdef CONFIG_ZSMALLOC_STAT
286         struct dentry *stat_dentry;
287 #endif
288 };
289
290 /*
291  * A zspage's class index and fullness group
292  * are encoded in its (first)page->mapping
293  */
294 #define CLASS_IDX_BITS  28
295 #define FULLNESS_BITS   4
296 #define CLASS_IDX_MASK  ((1 << CLASS_IDX_BITS) - 1)
297 #define FULLNESS_MASK   ((1 << FULLNESS_BITS) - 1)
298
299 struct mapping_area {
300 #ifdef CONFIG_PGTABLE_MAPPING
301         struct vm_struct *vm; /* vm area for mapping object that span pages */
302 #else
303         char *vm_buf; /* copy buffer for objects that span pages */
304 #endif
305         char *vm_addr; /* address of kmap_atomic()'ed pages */
306         enum zs_mapmode vm_mm; /* mapping mode */
307         bool huge;
308 };
309
310 static int create_handle_cache(struct zs_pool *pool)
311 {
312         pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
313                                         0, 0, NULL);
314         return pool->handle_cachep ? 0 : 1;
315 }
316
317 static void destroy_handle_cache(struct zs_pool *pool)
318 {
319         kmem_cache_destroy(pool->handle_cachep);
320 }
321
322 static unsigned long alloc_handle(struct zs_pool *pool)
323 {
324         return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
325                 pool->flags & ~__GFP_HIGHMEM);
326 }
327
328 static void free_handle(struct zs_pool *pool, unsigned long handle)
329 {
330         kmem_cache_free(pool->handle_cachep, (void *)handle);
331 }
332
333 static void record_obj(unsigned long handle, unsigned long obj)
334 {
335         *(unsigned long *)handle = obj;
336 }
337
338 /* zpool driver */
339
340 #ifdef CONFIG_ZPOOL
341
342 static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops)
343 {
344         return zs_create_pool(name, gfp);
345 }
346
347 static void zs_zpool_destroy(void *pool)
348 {
349         zs_destroy_pool(pool);
350 }
351
352 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
353                         unsigned long *handle)
354 {
355         *handle = zs_malloc(pool, size);
356         return *handle ? 0 : -1;
357 }
358 static void zs_zpool_free(void *pool, unsigned long handle)
359 {
360         zs_free(pool, handle);
361 }
362
363 static int zs_zpool_shrink(void *pool, unsigned int pages,
364                         unsigned int *reclaimed)
365 {
366         return -EINVAL;
367 }
368
369 static void *zs_zpool_map(void *pool, unsigned long handle,
370                         enum zpool_mapmode mm)
371 {
372         enum zs_mapmode zs_mm;
373
374         switch (mm) {
375         case ZPOOL_MM_RO:
376                 zs_mm = ZS_MM_RO;
377                 break;
378         case ZPOOL_MM_WO:
379                 zs_mm = ZS_MM_WO;
380                 break;
381         case ZPOOL_MM_RW: /* fallthru */
382         default:
383                 zs_mm = ZS_MM_RW;
384                 break;
385         }
386
387         return zs_map_object(pool, handle, zs_mm);
388 }
389 static void zs_zpool_unmap(void *pool, unsigned long handle)
390 {
391         zs_unmap_object(pool, handle);
392 }
393
394 static u64 zs_zpool_total_size(void *pool)
395 {
396         return zs_get_total_pages(pool) << PAGE_SHIFT;
397 }
398
399 static struct zpool_driver zs_zpool_driver = {
400         .type =         "zsmalloc",
401         .owner =        THIS_MODULE,
402         .create =       zs_zpool_create,
403         .destroy =      zs_zpool_destroy,
404         .malloc =       zs_zpool_malloc,
405         .free =         zs_zpool_free,
406         .shrink =       zs_zpool_shrink,
407         .map =          zs_zpool_map,
408         .unmap =        zs_zpool_unmap,
409         .total_size =   zs_zpool_total_size,
410 };
411
412 MODULE_ALIAS("zpool-zsmalloc");
413 #endif /* CONFIG_ZPOOL */
414
415 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
416 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
417
418 static int is_first_page(struct page *page)
419 {
420         return PagePrivate(page);
421 }
422
423 static int is_last_page(struct page *page)
424 {
425         return PagePrivate2(page);
426 }
427
428 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
429                                 enum fullness_group *fullness)
430 {
431         unsigned long m;
432         BUG_ON(!is_first_page(page));
433
434         m = (unsigned long)page->mapping;
435         *fullness = m & FULLNESS_MASK;
436         *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
437 }
438
439 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
440                                 enum fullness_group fullness)
441 {
442         unsigned long m;
443         BUG_ON(!is_first_page(page));
444
445         m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
446                         (fullness & FULLNESS_MASK);
447         page->mapping = (struct address_space *)m;
448 }
449
450 /*
451  * zsmalloc divides the pool into various size classes where each
452  * class maintains a list of zspages where each zspage is divided
453  * into equal sized chunks. Each allocation falls into one of these
454  * classes depending on its size. This function returns index of the
455  * size class which has chunk size big enough to hold the give size.
456  */
457 static int get_size_class_index(int size)
458 {
459         int idx = 0;
460
461         if (likely(size > ZS_MIN_ALLOC_SIZE))
462                 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
463                                 ZS_SIZE_CLASS_DELTA);
464
465         return min(zs_size_classes - 1, idx);
466 }
467
468 /*
469  * For each size class, zspages are divided into different groups
470  * depending on how "full" they are. This was done so that we could
471  * easily find empty or nearly empty zspages when we try to shrink
472  * the pool (not yet implemented). This function returns fullness
473  * status of the given page.
474  */
475 static enum fullness_group get_fullness_group(struct page *page)
476 {
477         int inuse, max_objects;
478         enum fullness_group fg;
479         BUG_ON(!is_first_page(page));
480
481         inuse = page->inuse;
482         max_objects = page->objects;
483
484         if (inuse == 0)
485                 fg = ZS_EMPTY;
486         else if (inuse == max_objects)
487                 fg = ZS_FULL;
488         else if (inuse <= 3 * max_objects / fullness_threshold_frac)
489                 fg = ZS_ALMOST_EMPTY;
490         else
491                 fg = ZS_ALMOST_FULL;
492
493         return fg;
494 }
495
496 /*
497  * Each size class maintains various freelists and zspages are assigned
498  * to one of these freelists based on the number of live objects they
499  * have. This functions inserts the given zspage into the freelist
500  * identified by <class, fullness_group>.
501  */
502 static void insert_zspage(struct page *page, struct size_class *class,
503                                 enum fullness_group fullness)
504 {
505         struct page **head;
506
507         BUG_ON(!is_first_page(page));
508
509         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
510                 return;
511
512         head = &class->fullness_list[fullness];
513         if (*head)
514                 list_add_tail(&page->lru, &(*head)->lru);
515
516         *head = page;
517 }
518
519 /*
520  * This function removes the given zspage from the freelist identified
521  * by <class, fullness_group>.
522  */
523 static void remove_zspage(struct page *page, struct size_class *class,
524                                 enum fullness_group fullness)
525 {
526         struct page **head;
527
528         BUG_ON(!is_first_page(page));
529
530         if (fullness >= _ZS_NR_FULLNESS_GROUPS)
531                 return;
532
533         head = &class->fullness_list[fullness];
534         BUG_ON(!*head);
535         if (list_empty(&(*head)->lru))
536                 *head = NULL;
537         else if (*head == page)
538                 *head = (struct page *)list_entry((*head)->lru.next,
539                                         struct page, lru);
540
541         list_del_init(&page->lru);
542 }
543
544 /*
545  * Each size class maintains zspages in different fullness groups depending
546  * on the number of live objects they contain. When allocating or freeing
547  * objects, the fullness status of the page can change, say, from ALMOST_FULL
548  * to ALMOST_EMPTY when freeing an object. This function checks if such
549  * a status change has occurred for the given page and accordingly moves the
550  * page from the freelist of the old fullness group to that of the new
551  * fullness group.
552  */
553 static enum fullness_group fix_fullness_group(struct size_class *class,
554                                                 struct page *page)
555 {
556         int class_idx;
557         enum fullness_group currfg, newfg;
558
559         BUG_ON(!is_first_page(page));
560
561         get_zspage_mapping(page, &class_idx, &currfg);
562         newfg = get_fullness_group(page);
563         if (newfg == currfg)
564                 goto out;
565
566         remove_zspage(page, class, currfg);
567         insert_zspage(page, class, newfg);
568         set_zspage_mapping(page, class_idx, newfg);
569
570 out:
571         return newfg;
572 }
573
574 /*
575  * We have to decide on how many pages to link together
576  * to form a zspage for each size class. This is important
577  * to reduce wastage due to unusable space left at end of
578  * each zspage which is given as:
579  *      wastage = Zp - Zp % size_class
580  * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
581  *
582  * For example, for size class of 3/8 * PAGE_SIZE, we should
583  * link together 3 PAGE_SIZE sized pages to form a zspage
584  * since then we can perfectly fit in 8 such objects.
585  */
586 static int get_pages_per_zspage(int class_size)
587 {
588         int i, max_usedpc = 0;
589         /* zspage order which gives maximum used size per KB */
590         int max_usedpc_order = 1;
591
592         for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
593                 int zspage_size;
594                 int waste, usedpc;
595
596                 zspage_size = i * PAGE_SIZE;
597                 waste = zspage_size % class_size;
598                 usedpc = (zspage_size - waste) * 100 / zspage_size;
599
600                 if (usedpc > max_usedpc) {
601                         max_usedpc = usedpc;
602                         max_usedpc_order = i;
603                 }
604         }
605
606         return max_usedpc_order;
607 }
608
609 /*
610  * A single 'zspage' is composed of many system pages which are
611  * linked together using fields in struct page. This function finds
612  * the first/head page, given any component page of a zspage.
613  */
614 static struct page *get_first_page(struct page *page)
615 {
616         if (is_first_page(page))
617                 return page;
618         else
619                 return page->first_page;
620 }
621
622 static struct page *get_next_page(struct page *page)
623 {
624         struct page *next;
625
626         if (is_last_page(page))
627                 next = NULL;
628         else if (is_first_page(page))
629                 next = (struct page *)page_private(page);
630         else
631                 next = list_entry(page->lru.next, struct page, lru);
632
633         return next;
634 }
635
636 /*
637  * Encode <page, obj_idx> as a single handle value.
638  * We use the least bit of handle for tagging.
639  */
640 static void *location_to_obj(struct page *page, unsigned long obj_idx)
641 {
642         unsigned long obj;
643
644         if (!page) {
645                 BUG_ON(obj_idx);
646                 return NULL;
647         }
648
649         obj = page_to_pfn(page) << OBJ_INDEX_BITS;
650         obj |= ((obj_idx) & OBJ_INDEX_MASK);
651         obj <<= OBJ_TAG_BITS;
652
653         return (void *)obj;
654 }
655
656 /*
657  * Decode <page, obj_idx> pair from the given object handle. We adjust the
658  * decoded obj_idx back to its original value since it was adjusted in
659  * location_to_obj().
660  */
661 static void obj_to_location(unsigned long obj, struct page **page,
662                                 unsigned long *obj_idx)
663 {
664         obj >>= OBJ_TAG_BITS;
665         *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
666         *obj_idx = (obj & OBJ_INDEX_MASK);
667 }
668
669 static unsigned long handle_to_obj(unsigned long handle)
670 {
671         return *(unsigned long *)handle;
672 }
673
674 static unsigned long obj_to_head(struct size_class *class, struct page *page,
675                         void *obj)
676 {
677         if (class->huge) {
678                 VM_BUG_ON(!is_first_page(page));
679                 return *(unsigned long *)page_private(page);
680         } else
681                 return *(unsigned long *)obj;
682 }
683
684 static unsigned long obj_idx_to_offset(struct page *page,
685                                 unsigned long obj_idx, int class_size)
686 {
687         unsigned long off = 0;
688
689         if (!is_first_page(page))
690                 off = page->index;
691
692         return off + obj_idx * class_size;
693 }
694
695 static inline int trypin_tag(unsigned long handle)
696 {
697         unsigned long *ptr = (unsigned long *)handle;
698
699         return !test_and_set_bit_lock(HANDLE_PIN_BIT, ptr);
700 }
701
702 static void pin_tag(unsigned long handle)
703 {
704         while (!trypin_tag(handle));
705 }
706
707 static void unpin_tag(unsigned long handle)
708 {
709         unsigned long *ptr = (unsigned long *)handle;
710
711         clear_bit_unlock(HANDLE_PIN_BIT, ptr);
712 }
713
714 static void reset_page(struct page *page)
715 {
716         clear_bit(PG_private, &page->flags);
717         clear_bit(PG_private_2, &page->flags);
718         set_page_private(page, 0);
719         page->mapping = NULL;
720         page->freelist = NULL;
721         page_mapcount_reset(page);
722 }
723
724 static void free_zspage(struct page *first_page)
725 {
726         struct page *nextp, *tmp, *head_extra;
727
728         BUG_ON(!is_first_page(first_page));
729         BUG_ON(first_page->inuse);
730
731         head_extra = (struct page *)page_private(first_page);
732
733         reset_page(first_page);
734         __free_page(first_page);
735
736         /* zspage with only 1 system page */
737         if (!head_extra)
738                 return;
739
740         list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
741                 list_del(&nextp->lru);
742                 reset_page(nextp);
743                 __free_page(nextp);
744         }
745         reset_page(head_extra);
746         __free_page(head_extra);
747 }
748
749 /* Initialize a newly allocated zspage */
750 static void init_zspage(struct page *first_page, struct size_class *class)
751 {
752         unsigned long off = 0;
753         struct page *page = first_page;
754
755         BUG_ON(!is_first_page(first_page));
756         while (page) {
757                 struct page *next_page;
758                 struct link_free *link;
759                 unsigned int i = 1;
760                 void *vaddr;
761
762                 /*
763                  * page->index stores offset of first object starting
764                  * in the page. For the first page, this is always 0,
765                  * so we use first_page->index (aka ->freelist) to store
766                  * head of corresponding zspage's freelist.
767                  */
768                 if (page != first_page)
769                         page->index = off;
770
771                 vaddr = kmap_atomic(page);
772                 link = (struct link_free *)vaddr + off / sizeof(*link);
773
774                 while ((off += class->size) < PAGE_SIZE) {
775                         link->next = location_to_obj(page, i++);
776                         link += class->size / sizeof(*link);
777                 }
778
779                 /*
780                  * We now come to the last (full or partial) object on this
781                  * page, which must point to the first object on the next
782                  * page (if present)
783                  */
784                 next_page = get_next_page(page);
785                 link->next = location_to_obj(next_page, 0);
786                 kunmap_atomic(vaddr);
787                 page = next_page;
788                 off %= PAGE_SIZE;
789         }
790 }
791
792 /*
793  * Allocate a zspage for the given size class
794  */
795 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
796 {
797         int i, error;
798         struct page *first_page = NULL, *uninitialized_var(prev_page);
799
800         /*
801          * Allocate individual pages and link them together as:
802          * 1. first page->private = first sub-page
803          * 2. all sub-pages are linked together using page->lru
804          * 3. each sub-page is linked to the first page using page->first_page
805          *
806          * For each size class, First/Head pages are linked together using
807          * page->lru. Also, we set PG_private to identify the first page
808          * (i.e. no other sub-page has this flag set) and PG_private_2 to
809          * identify the last page.
810          */
811         error = -ENOMEM;
812         for (i = 0; i < class->pages_per_zspage; i++) {
813                 struct page *page;
814
815                 page = alloc_page(flags);
816                 if (!page)
817                         goto cleanup;
818
819                 INIT_LIST_HEAD(&page->lru);
820                 if (i == 0) {   /* first page */
821                         SetPagePrivate(page);
822                         set_page_private(page, 0);
823                         first_page = page;
824                         first_page->inuse = 0;
825                 }
826                 if (i == 1)
827                         set_page_private(first_page, (unsigned long)page);
828                 if (i >= 1)
829                         page->first_page = first_page;
830                 if (i >= 2)
831                         list_add(&page->lru, &prev_page->lru);
832                 if (i == class->pages_per_zspage - 1)   /* last page */
833                         SetPagePrivate2(page);
834                 prev_page = page;
835         }
836
837         init_zspage(first_page, class);
838
839         first_page->freelist = location_to_obj(first_page, 0);
840         /* Maximum number of objects we can store in this zspage */
841         first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
842
843         error = 0; /* Success */
844
845 cleanup:
846         if (unlikely(error) && first_page) {
847                 free_zspage(first_page);
848                 first_page = NULL;
849         }
850
851         return first_page;
852 }
853
854 static struct page *find_get_zspage(struct size_class *class)
855 {
856         int i;
857         struct page *page;
858
859         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
860                 page = class->fullness_list[i];
861                 if (page)
862                         break;
863         }
864
865         return page;
866 }
867
868 #ifdef CONFIG_PGTABLE_MAPPING
869 static inline int __zs_cpu_up(struct mapping_area *area)
870 {
871         /*
872          * Make sure we don't leak memory if a cpu UP notification
873          * and zs_init() race and both call zs_cpu_up() on the same cpu
874          */
875         if (area->vm)
876                 return 0;
877         area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
878         if (!area->vm)
879                 return -ENOMEM;
880         return 0;
881 }
882
883 static inline void __zs_cpu_down(struct mapping_area *area)
884 {
885         if (area->vm)
886                 free_vm_area(area->vm);
887         area->vm = NULL;
888 }
889
890 static inline void *__zs_map_object(struct mapping_area *area,
891                                 struct page *pages[2], int off, int size)
892 {
893         BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
894         area->vm_addr = area->vm->addr;
895         return area->vm_addr + off;
896 }
897
898 static inline void __zs_unmap_object(struct mapping_area *area,
899                                 struct page *pages[2], int off, int size)
900 {
901         unsigned long addr = (unsigned long)area->vm_addr;
902
903         unmap_kernel_range(addr, PAGE_SIZE * 2);
904 }
905
906 #else /* CONFIG_PGTABLE_MAPPING */
907
908 static inline int __zs_cpu_up(struct mapping_area *area)
909 {
910         /*
911          * Make sure we don't leak memory if a cpu UP notification
912          * and zs_init() race and both call zs_cpu_up() on the same cpu
913          */
914         if (area->vm_buf)
915                 return 0;
916         area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
917         if (!area->vm_buf)
918                 return -ENOMEM;
919         return 0;
920 }
921
922 static inline void __zs_cpu_down(struct mapping_area *area)
923 {
924         kfree(area->vm_buf);
925         area->vm_buf = NULL;
926 }
927
928 static void *__zs_map_object(struct mapping_area *area,
929                         struct page *pages[2], int off, int size)
930 {
931         int sizes[2];
932         void *addr;
933         char *buf = area->vm_buf;
934
935         /* disable page faults to match kmap_atomic() return conditions */
936         pagefault_disable();
937
938         /* no read fastpath */
939         if (area->vm_mm == ZS_MM_WO)
940                 goto out;
941
942         sizes[0] = PAGE_SIZE - off;
943         sizes[1] = size - sizes[0];
944
945         /* copy object to per-cpu buffer */
946         addr = kmap_atomic(pages[0]);
947         memcpy(buf, addr + off, sizes[0]);
948         kunmap_atomic(addr);
949         addr = kmap_atomic(pages[1]);
950         memcpy(buf + sizes[0], addr, sizes[1]);
951         kunmap_atomic(addr);
952 out:
953         return area->vm_buf;
954 }
955
956 static void __zs_unmap_object(struct mapping_area *area,
957                         struct page *pages[2], int off, int size)
958 {
959         int sizes[2];
960         void *addr;
961         char *buf;
962
963         /* no write fastpath */
964         if (area->vm_mm == ZS_MM_RO)
965                 goto out;
966
967         buf = area->vm_buf;
968         if (!area->huge) {
969                 buf = buf + ZS_HANDLE_SIZE;
970                 size -= ZS_HANDLE_SIZE;
971                 off += ZS_HANDLE_SIZE;
972         }
973
974         sizes[0] = PAGE_SIZE - off;
975         sizes[1] = size - sizes[0];
976
977         /* copy per-cpu buffer to object */
978         addr = kmap_atomic(pages[0]);
979         memcpy(addr + off, buf, sizes[0]);
980         kunmap_atomic(addr);
981         addr = kmap_atomic(pages[1]);
982         memcpy(addr, buf + sizes[0], sizes[1]);
983         kunmap_atomic(addr);
984
985 out:
986         /* enable page faults to match kunmap_atomic() return conditions */
987         pagefault_enable();
988 }
989
990 #endif /* CONFIG_PGTABLE_MAPPING */
991
992 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
993                                 void *pcpu)
994 {
995         int ret, cpu = (long)pcpu;
996         struct mapping_area *area;
997
998         switch (action) {
999         case CPU_UP_PREPARE:
1000                 area = &per_cpu(zs_map_area, cpu);
1001                 ret = __zs_cpu_up(area);
1002                 if (ret)
1003                         return notifier_from_errno(ret);
1004                 break;
1005         case CPU_DEAD:
1006         case CPU_UP_CANCELED:
1007                 area = &per_cpu(zs_map_area, cpu);
1008                 __zs_cpu_down(area);
1009                 break;
1010         }
1011
1012         return NOTIFY_OK;
1013 }
1014
1015 static struct notifier_block zs_cpu_nb = {
1016         .notifier_call = zs_cpu_notifier
1017 };
1018
1019 static int zs_register_cpu_notifier(void)
1020 {
1021         int cpu, uninitialized_var(ret);
1022
1023         cpu_notifier_register_begin();
1024
1025         __register_cpu_notifier(&zs_cpu_nb);
1026         for_each_online_cpu(cpu) {
1027                 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1028                 if (notifier_to_errno(ret))
1029                         break;
1030         }
1031
1032         cpu_notifier_register_done();
1033         return notifier_to_errno(ret);
1034 }
1035
1036 static void zs_unregister_cpu_notifier(void)
1037 {
1038         int cpu;
1039
1040         cpu_notifier_register_begin();
1041
1042         for_each_online_cpu(cpu)
1043                 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1044         __unregister_cpu_notifier(&zs_cpu_nb);
1045
1046         cpu_notifier_register_done();
1047 }
1048
1049 static void init_zs_size_classes(void)
1050 {
1051         int nr;
1052
1053         nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
1054         if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1055                 nr += 1;
1056
1057         zs_size_classes = nr;
1058 }
1059
1060 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
1061 {
1062         return pages_per_zspage * PAGE_SIZE / size;
1063 }
1064
1065 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1066 {
1067         if (prev->pages_per_zspage != pages_per_zspage)
1068                 return false;
1069
1070         if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1071                 != get_maxobj_per_zspage(size, pages_per_zspage))
1072                 return false;
1073
1074         return true;
1075 }
1076
1077 static bool zspage_full(struct page *page)
1078 {
1079         BUG_ON(!is_first_page(page));
1080
1081         return page->inuse == page->objects;
1082 }
1083
1084 #ifdef CONFIG_ZSMALLOC_STAT
1085
1086 static inline void zs_stat_inc(struct size_class *class,
1087                                 enum zs_stat_type type, unsigned long cnt)
1088 {
1089         class->stats.objs[type] += cnt;
1090 }
1091
1092 static inline void zs_stat_dec(struct size_class *class,
1093                                 enum zs_stat_type type, unsigned long cnt)
1094 {
1095         class->stats.objs[type] -= cnt;
1096 }
1097
1098 static inline unsigned long zs_stat_get(struct size_class *class,
1099                                 enum zs_stat_type type)
1100 {
1101         return class->stats.objs[type];
1102 }
1103
1104 static int __init zs_stat_init(void)
1105 {
1106         if (!debugfs_initialized())
1107                 return -ENODEV;
1108
1109         zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
1110         if (!zs_stat_root)
1111                 return -ENOMEM;
1112
1113         return 0;
1114 }
1115
1116 static void __exit zs_stat_exit(void)
1117 {
1118         debugfs_remove_recursive(zs_stat_root);
1119 }
1120
1121 static int zs_stats_size_show(struct seq_file *s, void *v)
1122 {
1123         int i;
1124         struct zs_pool *pool = s->private;
1125         struct size_class *class;
1126         int objs_per_zspage;
1127         unsigned long obj_allocated, obj_used, pages_used;
1128         unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
1129
1130         seq_printf(s, " %5s %5s %13s %10s %10s\n", "class", "size",
1131                                 "obj_allocated", "obj_used", "pages_used");
1132
1133         for (i = 0; i < zs_size_classes; i++) {
1134                 class = pool->size_class[i];
1135
1136                 if (class->index != i)
1137                         continue;
1138
1139                 spin_lock(&class->lock);
1140                 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
1141                 obj_used = zs_stat_get(class, OBJ_USED);
1142                 spin_unlock(&class->lock);
1143
1144                 objs_per_zspage = get_maxobj_per_zspage(class->size,
1145                                 class->pages_per_zspage);
1146                 pages_used = obj_allocated / objs_per_zspage *
1147                                 class->pages_per_zspage;
1148
1149                 seq_printf(s, " %5u %5u    %10lu %10lu %10lu\n", i,
1150                         class->size, obj_allocated, obj_used, pages_used);
1151
1152                 total_objs += obj_allocated;
1153                 total_used_objs += obj_used;
1154                 total_pages += pages_used;
1155         }
1156
1157         seq_puts(s, "\n");
1158         seq_printf(s, " %5s %5s    %10lu %10lu %10lu\n", "Total", "",
1159                         total_objs, total_used_objs, total_pages);
1160
1161         return 0;
1162 }
1163
1164 static int zs_stats_size_open(struct inode *inode, struct file *file)
1165 {
1166         return single_open(file, zs_stats_size_show, inode->i_private);
1167 }
1168
1169 static const struct file_operations zs_stat_size_ops = {
1170         .open           = zs_stats_size_open,
1171         .read           = seq_read,
1172         .llseek         = seq_lseek,
1173         .release        = single_release,
1174 };
1175
1176 static int zs_pool_stat_create(char *name, struct zs_pool *pool)
1177 {
1178         struct dentry *entry;
1179
1180         if (!zs_stat_root)
1181                 return -ENODEV;
1182
1183         entry = debugfs_create_dir(name, zs_stat_root);
1184         if (!entry) {
1185                 pr_warn("debugfs dir <%s> creation failed\n", name);
1186                 return -ENOMEM;
1187         }
1188         pool->stat_dentry = entry;
1189
1190         entry = debugfs_create_file("obj_in_classes", S_IFREG | S_IRUGO,
1191                         pool->stat_dentry, pool, &zs_stat_size_ops);
1192         if (!entry) {
1193                 pr_warn("%s: debugfs file entry <%s> creation failed\n",
1194                                 name, "obj_in_classes");
1195                 return -ENOMEM;
1196         }
1197
1198         return 0;
1199 }
1200
1201 static void zs_pool_stat_destroy(struct zs_pool *pool)
1202 {
1203         debugfs_remove_recursive(pool->stat_dentry);
1204 }
1205
1206 #else /* CONFIG_ZSMALLOC_STAT */
1207
1208 static inline void zs_stat_inc(struct size_class *class,
1209                                 enum zs_stat_type type, unsigned long cnt)
1210 {
1211 }
1212
1213 static inline void zs_stat_dec(struct size_class *class,
1214                                 enum zs_stat_type type, unsigned long cnt)
1215 {
1216 }
1217
1218 static inline unsigned long zs_stat_get(struct size_class *class,
1219                                 enum zs_stat_type type)
1220 {
1221         return 0;
1222 }
1223
1224 static int __init zs_stat_init(void)
1225 {
1226         return 0;
1227 }
1228
1229 static void __exit zs_stat_exit(void)
1230 {
1231 }
1232
1233 static inline int zs_pool_stat_create(char *name, struct zs_pool *pool)
1234 {
1235         return 0;
1236 }
1237
1238 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
1239 {
1240 }
1241
1242 #endif
1243
1244 unsigned long zs_get_total_pages(struct zs_pool *pool)
1245 {
1246         return atomic_long_read(&pool->pages_allocated);
1247 }
1248 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1249
1250 /**
1251  * zs_map_object - get address of allocated object from handle.
1252  * @pool: pool from which the object was allocated
1253  * @handle: handle returned from zs_malloc
1254  *
1255  * Before using an object allocated from zs_malloc, it must be mapped using
1256  * this function. When done with the object, it must be unmapped using
1257  * zs_unmap_object.
1258  *
1259  * Only one object can be mapped per cpu at a time. There is no protection
1260  * against nested mappings.
1261  *
1262  * This function returns with preemption and page faults disabled.
1263  */
1264 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1265                         enum zs_mapmode mm)
1266 {
1267         struct page *page;
1268         unsigned long obj, obj_idx, off;
1269
1270         unsigned int class_idx;
1271         enum fullness_group fg;
1272         struct size_class *class;
1273         struct mapping_area *area;
1274         struct page *pages[2];
1275         void *ret;
1276
1277         BUG_ON(!handle);
1278
1279         /*
1280          * Because we use per-cpu mapping areas shared among the
1281          * pools/users, we can't allow mapping in interrupt context
1282          * because it can corrupt another users mappings.
1283          */
1284         BUG_ON(in_interrupt());
1285
1286         /* From now on, migration cannot move the object */
1287         pin_tag(handle);
1288
1289         obj = handle_to_obj(handle);
1290         obj_to_location(obj, &page, &obj_idx);
1291         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1292         class = pool->size_class[class_idx];
1293         off = obj_idx_to_offset(page, obj_idx, class->size);
1294
1295         area = &get_cpu_var(zs_map_area);
1296         area->vm_mm = mm;
1297         if (off + class->size <= PAGE_SIZE) {
1298                 /* this object is contained entirely within a page */
1299                 area->vm_addr = kmap_atomic(page);
1300                 ret = area->vm_addr + off;
1301                 goto out;
1302         }
1303
1304         /* this object spans two pages */
1305         pages[0] = page;
1306         pages[1] = get_next_page(page);
1307         BUG_ON(!pages[1]);
1308
1309         ret = __zs_map_object(area, pages, off, class->size);
1310 out:
1311         if (!class->huge)
1312                 ret += ZS_HANDLE_SIZE;
1313
1314         return ret;
1315 }
1316 EXPORT_SYMBOL_GPL(zs_map_object);
1317
1318 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1319 {
1320         struct page *page;
1321         unsigned long obj, obj_idx, off;
1322
1323         unsigned int class_idx;
1324         enum fullness_group fg;
1325         struct size_class *class;
1326         struct mapping_area *area;
1327
1328         BUG_ON(!handle);
1329
1330         obj = handle_to_obj(handle);
1331         obj_to_location(obj, &page, &obj_idx);
1332         get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1333         class = pool->size_class[class_idx];
1334         off = obj_idx_to_offset(page, obj_idx, class->size);
1335
1336         area = this_cpu_ptr(&zs_map_area);
1337         if (off + class->size <= PAGE_SIZE)
1338                 kunmap_atomic(area->vm_addr);
1339         else {
1340                 struct page *pages[2];
1341
1342                 pages[0] = page;
1343                 pages[1] = get_next_page(page);
1344                 BUG_ON(!pages[1]);
1345
1346                 __zs_unmap_object(area, pages, off, class->size);
1347         }
1348         put_cpu_var(zs_map_area);
1349         unpin_tag(handle);
1350 }
1351 EXPORT_SYMBOL_GPL(zs_unmap_object);
1352
1353 static unsigned long obj_malloc(struct page *first_page,
1354                 struct size_class *class, unsigned long handle)
1355 {
1356         unsigned long obj;
1357         struct link_free *link;
1358
1359         struct page *m_page;
1360         unsigned long m_objidx, m_offset;
1361         void *vaddr;
1362
1363         handle |= OBJ_ALLOCATED_TAG;
1364         obj = (unsigned long)first_page->freelist;
1365         obj_to_location(obj, &m_page, &m_objidx);
1366         m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1367
1368         vaddr = kmap_atomic(m_page);
1369         link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1370         first_page->freelist = link->next;
1371         if (!class->huge)
1372                 /* record handle in the header of allocated chunk */
1373                 link->handle = handle;
1374         else
1375                 /* record handle in first_page->private */
1376                 set_page_private(first_page, handle);
1377         kunmap_atomic(vaddr);
1378         first_page->inuse++;
1379         zs_stat_inc(class, OBJ_USED, 1);
1380
1381         return obj;
1382 }
1383
1384
1385 /**
1386  * zs_malloc - Allocate block of given size from pool.
1387  * @pool: pool to allocate from
1388  * @size: size of block to allocate
1389  *
1390  * On success, handle to the allocated object is returned,
1391  * otherwise 0.
1392  * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1393  */
1394 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1395 {
1396         unsigned long handle, obj;
1397         struct size_class *class;
1398         struct page *first_page;
1399
1400         if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1401                 return 0;
1402
1403         handle = alloc_handle(pool);
1404         if (!handle)
1405                 return 0;
1406
1407         /* extra space in chunk to keep the handle */
1408         size += ZS_HANDLE_SIZE;
1409         class = pool->size_class[get_size_class_index(size)];
1410         /* In huge class size, we store the handle into first_page->private */
1411         if (class->huge) {
1412                 size -= ZS_HANDLE_SIZE;
1413                 class = pool->size_class[get_size_class_index(size)];
1414         }
1415
1416         spin_lock(&class->lock);
1417         first_page = find_get_zspage(class);
1418
1419         if (!first_page) {
1420                 spin_unlock(&class->lock);
1421                 first_page = alloc_zspage(class, pool->flags);
1422                 if (unlikely(!first_page)) {
1423                         free_handle(pool, handle);
1424                         return 0;
1425                 }
1426
1427                 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1428                 atomic_long_add(class->pages_per_zspage,
1429                                         &pool->pages_allocated);
1430
1431                 spin_lock(&class->lock);
1432                 zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1433                                 class->size, class->pages_per_zspage));
1434         }
1435
1436         obj = obj_malloc(first_page, class, handle);
1437         /* Now move the zspage to another fullness group, if required */
1438         fix_fullness_group(class, first_page);
1439         record_obj(handle, obj);
1440         spin_unlock(&class->lock);
1441
1442         return handle;
1443 }
1444 EXPORT_SYMBOL_GPL(zs_malloc);
1445
1446 static void obj_free(struct zs_pool *pool, struct size_class *class,
1447                         unsigned long obj)
1448 {
1449         struct link_free *link;
1450         struct page *first_page, *f_page;
1451         unsigned long f_objidx, f_offset;
1452         void *vaddr;
1453         int class_idx;
1454         enum fullness_group fullness;
1455
1456         BUG_ON(!obj);
1457
1458         obj &= ~OBJ_ALLOCATED_TAG;
1459         obj_to_location(obj, &f_page, &f_objidx);
1460         first_page = get_first_page(f_page);
1461
1462         get_zspage_mapping(first_page, &class_idx, &fullness);
1463         f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1464
1465         vaddr = kmap_atomic(f_page);
1466
1467         /* Insert this object in containing zspage's freelist */
1468         link = (struct link_free *)(vaddr + f_offset);
1469         link->next = first_page->freelist;
1470         if (class->huge)
1471                 set_page_private(first_page, 0);
1472         kunmap_atomic(vaddr);
1473         first_page->freelist = (void *)obj;
1474         first_page->inuse--;
1475         zs_stat_dec(class, OBJ_USED, 1);
1476 }
1477
1478 void zs_free(struct zs_pool *pool, unsigned long handle)
1479 {
1480         struct page *first_page, *f_page;
1481         unsigned long obj, f_objidx;
1482         int class_idx;
1483         struct size_class *class;
1484         enum fullness_group fullness;
1485
1486         if (unlikely(!handle))
1487                 return;
1488
1489         pin_tag(handle);
1490         obj = handle_to_obj(handle);
1491         obj_to_location(obj, &f_page, &f_objidx);
1492         first_page = get_first_page(f_page);
1493
1494         get_zspage_mapping(first_page, &class_idx, &fullness);
1495         class = pool->size_class[class_idx];
1496
1497         spin_lock(&class->lock);
1498         obj_free(pool, class, obj);
1499         fullness = fix_fullness_group(class, first_page);
1500         if (fullness == ZS_EMPTY) {
1501                 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1502                                 class->size, class->pages_per_zspage));
1503                 atomic_long_sub(class->pages_per_zspage,
1504                                 &pool->pages_allocated);
1505                 free_zspage(first_page);
1506         }
1507         spin_unlock(&class->lock);
1508         unpin_tag(handle);
1509
1510         free_handle(pool, handle);
1511 }
1512 EXPORT_SYMBOL_GPL(zs_free);
1513
1514 static void zs_object_copy(unsigned long src, unsigned long dst,
1515                                 struct size_class *class)
1516 {
1517         struct page *s_page, *d_page;
1518         unsigned long s_objidx, d_objidx;
1519         unsigned long s_off, d_off;
1520         void *s_addr, *d_addr;
1521         int s_size, d_size, size;
1522         int written = 0;
1523
1524         s_size = d_size = class->size;
1525
1526         obj_to_location(src, &s_page, &s_objidx);
1527         obj_to_location(dst, &d_page, &d_objidx);
1528
1529         s_off = obj_idx_to_offset(s_page, s_objidx, class->size);
1530         d_off = obj_idx_to_offset(d_page, d_objidx, class->size);
1531
1532         if (s_off + class->size > PAGE_SIZE)
1533                 s_size = PAGE_SIZE - s_off;
1534
1535         if (d_off + class->size > PAGE_SIZE)
1536                 d_size = PAGE_SIZE - d_off;
1537
1538         s_addr = kmap_atomic(s_page);
1539         d_addr = kmap_atomic(d_page);
1540
1541         while (1) {
1542                 size = min(s_size, d_size);
1543                 memcpy(d_addr + d_off, s_addr + s_off, size);
1544                 written += size;
1545
1546                 if (written == class->size)
1547                         break;
1548
1549                 if (s_off + size >= PAGE_SIZE) {
1550                         kunmap_atomic(d_addr);
1551                         kunmap_atomic(s_addr);
1552                         s_page = get_next_page(s_page);
1553                         BUG_ON(!s_page);
1554                         s_addr = kmap_atomic(s_page);
1555                         d_addr = kmap_atomic(d_page);
1556                         s_size = class->size - written;
1557                         s_off = 0;
1558                 } else {
1559                         s_off += size;
1560                         s_size -= size;
1561                 }
1562
1563                 if (d_off + size >= PAGE_SIZE) {
1564                         kunmap_atomic(d_addr);
1565                         d_page = get_next_page(d_page);
1566                         BUG_ON(!d_page);
1567                         d_addr = kmap_atomic(d_page);
1568                         d_size = class->size - written;
1569                         d_off = 0;
1570                 } else {
1571                         d_off += size;
1572                         d_size -= size;
1573                 }
1574         }
1575
1576         kunmap_atomic(d_addr);
1577         kunmap_atomic(s_addr);
1578 }
1579
1580 /*
1581  * Find alloced object in zspage from index object and
1582  * return handle.
1583  */
1584 static unsigned long find_alloced_obj(struct page *page, int index,
1585                                         struct size_class *class)
1586 {
1587         unsigned long head;
1588         int offset = 0;
1589         unsigned long handle = 0;
1590         void *addr = kmap_atomic(page);
1591
1592         if (!is_first_page(page))
1593                 offset = page->index;
1594         offset += class->size * index;
1595
1596         while (offset < PAGE_SIZE) {
1597                 head = obj_to_head(class, page, addr + offset);
1598                 if (head & OBJ_ALLOCATED_TAG) {
1599                         handle = head & ~OBJ_ALLOCATED_TAG;
1600                         if (trypin_tag(handle))
1601                                 break;
1602                         handle = 0;
1603                 }
1604
1605                 offset += class->size;
1606                 index++;
1607         }
1608
1609         kunmap_atomic(addr);
1610         return handle;
1611 }
1612
1613 struct zs_compact_control {
1614         /* Source page for migration which could be a subpage of zspage. */
1615         struct page *s_page;
1616         /* Destination page for migration which should be a first page
1617          * of zspage. */
1618         struct page *d_page;
1619          /* Starting object index within @s_page which used for live object
1620           * in the subpage. */
1621         int index;
1622         /* how many of objects are migrated */
1623         int nr_migrated;
1624 };
1625
1626 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1627                                 struct zs_compact_control *cc)
1628 {
1629         unsigned long used_obj, free_obj;
1630         unsigned long handle;
1631         struct page *s_page = cc->s_page;
1632         struct page *d_page = cc->d_page;
1633         unsigned long index = cc->index;
1634         int nr_migrated = 0;
1635         int ret = 0;
1636
1637         while (1) {
1638                 handle = find_alloced_obj(s_page, index, class);
1639                 if (!handle) {
1640                         s_page = get_next_page(s_page);
1641                         if (!s_page)
1642                                 break;
1643                         index = 0;
1644                         continue;
1645                 }
1646
1647                 /* Stop if there is no more space */
1648                 if (zspage_full(d_page)) {
1649                         unpin_tag(handle);
1650                         ret = -ENOMEM;
1651                         break;
1652                 }
1653
1654                 used_obj = handle_to_obj(handle);
1655                 free_obj = obj_malloc(d_page, class, handle);
1656                 zs_object_copy(used_obj, free_obj, class);
1657                 index++;
1658                 record_obj(handle, free_obj);
1659                 unpin_tag(handle);
1660                 obj_free(pool, class, used_obj);
1661                 nr_migrated++;
1662         }
1663
1664         /* Remember last position in this iteration */
1665         cc->s_page = s_page;
1666         cc->index = index;
1667         cc->nr_migrated = nr_migrated;
1668
1669         return ret;
1670 }
1671
1672 static struct page *alloc_target_page(struct size_class *class)
1673 {
1674         int i;
1675         struct page *page;
1676
1677         for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1678                 page = class->fullness_list[i];
1679                 if (page) {
1680                         remove_zspage(page, class, i);
1681                         break;
1682                 }
1683         }
1684
1685         return page;
1686 }
1687
1688 static void putback_zspage(struct zs_pool *pool, struct size_class *class,
1689                                 struct page *first_page)
1690 {
1691         int class_idx;
1692         enum fullness_group fullness;
1693
1694         BUG_ON(!is_first_page(first_page));
1695
1696         get_zspage_mapping(first_page, &class_idx, &fullness);
1697         insert_zspage(first_page, class, fullness);
1698         fullness = fix_fullness_group(class, first_page);
1699         if (fullness == ZS_EMPTY) {
1700                 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1701                         class->size, class->pages_per_zspage));
1702                 atomic_long_sub(class->pages_per_zspage,
1703                                 &pool->pages_allocated);
1704
1705                 free_zspage(first_page);
1706         }
1707 }
1708
1709 static struct page *isolate_source_page(struct size_class *class)
1710 {
1711         struct page *page;
1712
1713         page = class->fullness_list[ZS_ALMOST_EMPTY];
1714         if (page)
1715                 remove_zspage(page, class, ZS_ALMOST_EMPTY);
1716
1717         return page;
1718 }
1719
1720 static unsigned long __zs_compact(struct zs_pool *pool,
1721                                 struct size_class *class)
1722 {
1723         int nr_to_migrate;
1724         struct zs_compact_control cc;
1725         struct page *src_page;
1726         struct page *dst_page = NULL;
1727         unsigned long nr_total_migrated = 0;
1728
1729         cond_resched();
1730
1731         spin_lock(&class->lock);
1732         while ((src_page = isolate_source_page(class))) {
1733
1734                 BUG_ON(!is_first_page(src_page));
1735
1736                 /* The goal is to migrate all live objects in source page */
1737                 nr_to_migrate = src_page->inuse;
1738                 cc.index = 0;
1739                 cc.s_page = src_page;
1740
1741                 while ((dst_page = alloc_target_page(class))) {
1742                         cc.d_page = dst_page;
1743                         /*
1744                          * If there is no more space in dst_page, try to
1745                          * allocate another zspage.
1746                          */
1747                         if (!migrate_zspage(pool, class, &cc))
1748                                 break;
1749
1750                         putback_zspage(pool, class, dst_page);
1751                         nr_total_migrated += cc.nr_migrated;
1752                         nr_to_migrate -= cc.nr_migrated;
1753                 }
1754
1755                 /* Stop if we couldn't find slot */
1756                 if (dst_page == NULL)
1757                         break;
1758
1759                 putback_zspage(pool, class, dst_page);
1760                 putback_zspage(pool, class, src_page);
1761                 spin_unlock(&class->lock);
1762                 nr_total_migrated += cc.nr_migrated;
1763                 cond_resched();
1764                 spin_lock(&class->lock);
1765         }
1766
1767         if (src_page)
1768                 putback_zspage(pool, class, src_page);
1769
1770         spin_unlock(&class->lock);
1771
1772         return nr_total_migrated;
1773 }
1774
1775 unsigned long zs_compact(struct zs_pool *pool)
1776 {
1777         int i;
1778         unsigned long nr_migrated = 0;
1779         struct size_class *class;
1780
1781         for (i = zs_size_classes - 1; i >= 0; i--) {
1782                 class = pool->size_class[i];
1783                 if (!class)
1784                         continue;
1785                 if (class->index != i)
1786                         continue;
1787                 nr_migrated += __zs_compact(pool, class);
1788         }
1789
1790         synchronize_rcu();
1791
1792         return nr_migrated;
1793 }
1794 EXPORT_SYMBOL_GPL(zs_compact);
1795
1796 /**
1797  * zs_create_pool - Creates an allocation pool to work from.
1798  * @flags: allocation flags used to allocate pool metadata
1799  *
1800  * This function must be called before anything when using
1801  * the zsmalloc allocator.
1802  *
1803  * On success, a pointer to the newly created pool is returned,
1804  * otherwise NULL.
1805  */
1806 struct zs_pool *zs_create_pool(char *name, gfp_t flags)
1807 {
1808         int i;
1809         struct zs_pool *pool;
1810         struct size_class *prev_class = NULL;
1811
1812         pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1813         if (!pool)
1814                 return NULL;
1815
1816         pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1817                         GFP_KERNEL);
1818         if (!pool->size_class) {
1819                 kfree(pool);
1820                 return NULL;
1821         }
1822
1823         pool->name = kstrdup(name, GFP_KERNEL);
1824         if (!pool->name)
1825                 goto err;
1826
1827         if (create_handle_cache(pool))
1828                 goto err;
1829
1830         /*
1831          * Iterate reversly, because, size of size_class that we want to use
1832          * for merging should be larger or equal to current size.
1833          */
1834         for (i = zs_size_classes - 1; i >= 0; i--) {
1835                 int size;
1836                 int pages_per_zspage;
1837                 struct size_class *class;
1838
1839                 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
1840                 if (size > ZS_MAX_ALLOC_SIZE)
1841                         size = ZS_MAX_ALLOC_SIZE;
1842                 pages_per_zspage = get_pages_per_zspage(size);
1843
1844                 /*
1845                  * size_class is used for normal zsmalloc operation such
1846                  * as alloc/free for that size. Although it is natural that we
1847                  * have one size_class for each size, there is a chance that we
1848                  * can get more memory utilization if we use one size_class for
1849                  * many different sizes whose size_class have same
1850                  * characteristics. So, we makes size_class point to
1851                  * previous size_class if possible.
1852                  */
1853                 if (prev_class) {
1854                         if (can_merge(prev_class, size, pages_per_zspage)) {
1855                                 pool->size_class[i] = prev_class;
1856                                 continue;
1857                         }
1858                 }
1859
1860                 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1861                 if (!class)
1862                         goto err;
1863
1864                 class->size = size;
1865                 class->index = i;
1866                 class->pages_per_zspage = pages_per_zspage;
1867                 if (pages_per_zspage == 1 &&
1868                         get_maxobj_per_zspage(size, pages_per_zspage) == 1)
1869                         class->huge = true;
1870                 spin_lock_init(&class->lock);
1871                 pool->size_class[i] = class;
1872
1873                 prev_class = class;
1874         }
1875
1876         pool->flags = flags;
1877
1878         if (zs_pool_stat_create(name, pool))
1879                 goto err;
1880
1881         return pool;
1882
1883 err:
1884         zs_destroy_pool(pool);
1885         return NULL;
1886 }
1887 EXPORT_SYMBOL_GPL(zs_create_pool);
1888
1889 void zs_destroy_pool(struct zs_pool *pool)
1890 {
1891         int i;
1892
1893         zs_pool_stat_destroy(pool);
1894
1895         for (i = 0; i < zs_size_classes; i++) {
1896                 int fg;
1897                 struct size_class *class = pool->size_class[i];
1898
1899                 if (!class)
1900                         continue;
1901
1902                 if (class->index != i)
1903                         continue;
1904
1905                 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
1906                         if (class->fullness_list[fg]) {
1907                                 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
1908                                         class->size, fg);
1909                         }
1910                 }
1911                 kfree(class);
1912         }
1913
1914         destroy_handle_cache(pool);
1915         kfree(pool->size_class);
1916         kfree(pool->name);
1917         kfree(pool);
1918 }
1919 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1920
1921 static int __init zs_init(void)
1922 {
1923         int ret = zs_register_cpu_notifier();
1924
1925         if (ret)
1926                 goto notifier_fail;
1927
1928         init_zs_size_classes();
1929
1930 #ifdef CONFIG_ZPOOL
1931         zpool_register_driver(&zs_zpool_driver);
1932 #endif
1933
1934         ret = zs_stat_init();
1935         if (ret) {
1936                 pr_err("zs stat initialization failed\n");
1937                 goto stat_fail;
1938         }
1939         return 0;
1940
1941 stat_fail:
1942 #ifdef CONFIG_ZPOOL
1943         zpool_unregister_driver(&zs_zpool_driver);
1944 #endif
1945 notifier_fail:
1946         zs_unregister_cpu_notifier();
1947
1948         return ret;
1949 }
1950
1951 static void __exit zs_exit(void)
1952 {
1953 #ifdef CONFIG_ZPOOL
1954         zpool_unregister_driver(&zs_zpool_driver);
1955 #endif
1956         zs_unregister_cpu_notifier();
1957
1958         zs_stat_exit();
1959 }
1960
1961 module_init(zs_init);
1962 module_exit(zs_exit);
1963
1964 MODULE_LICENSE("Dual BSD/GPL");
1965 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");