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