2 * zsmalloc memory allocator
4 * Copyright (C) 2011 Nitin Gupta
5 * Copyright (C) 2012, 2013 Minchan Kim
7 * This code is released using a dual license strategy: BSD/GPL
8 * You can choose the license that better fits your requirements.
10 * Released under the terms of 3-clause BSD License
11 * Released under the terms of GNU General Public License Version 2.0
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).
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
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).
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().
44 * Following is how we use various fields and flags of underlying
45 * struct page(s) to form a zspage.
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)
56 * For _first_ page only:
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
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
69 * Usage of struct page flags:
70 * PG_private: identifies the first component page
71 * PG_private2: identifies the last component page
75 #ifdef CONFIG_ZSMALLOC_DEBUG
79 #include <linux/module.h>
80 #include <linux/kernel.h>
81 #include <linux/sched.h>
82 #include <linux/bitops.h>
83 #include <linux/errno.h>
84 #include <linux/highmem.h>
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>
91 #include <linux/vmalloc.h>
92 #include <linux/hardirq.h>
93 #include <linux/spinlock.h>
94 #include <linux/types.h>
95 #include <linux/debugfs.h>
96 #include <linux/zsmalloc.h>
97 #include <linux/zpool.h>
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.
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.
111 #define ZS_MAX_ZSPAGE_ORDER 2
112 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
114 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
117 * Object location (<PFN>, <obj_idx>) is encoded as
118 * as single (unsigned long) handle value.
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.
124 * This is made more complicated by various memory models and PAE.
127 #ifndef MAX_PHYSMEM_BITS
128 #ifdef CONFIG_HIGHMEM64G
129 #define MAX_PHYSMEM_BITS 36
130 #else /* !CONFIG_HIGHMEM64G */
132 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
135 #define MAX_PHYSMEM_BITS BITS_PER_LONG
138 #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
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.
147 #define HANDLE_PIN_BIT 0
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.
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)
159 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
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))
165 /* each chunk includes extra space to keep handle */
166 #define ZS_MAX_ALLOC_SIZE (PAGE_SIZE + ZS_HANDLE_SIZE)
169 * On systems with 4K page size, this gives 255 size classes! There is a
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.
178 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
181 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8)
184 * We do not maintain any list for completely empty or full pages
186 enum fullness_group {
189 _ZS_NR_FULLNESS_GROUPS,
201 #ifdef CONFIG_ZSMALLOC_STAT
203 static struct dentry *zs_stat_root;
205 struct zs_size_stat {
206 unsigned long objs[NR_ZS_STAT_TYPE];
212 * number of size_classes
214 static int zs_size_classes;
217 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
219 * n = number of allocated objects
220 * N = total number of objects zspage can store
221 * f = fullness_threshold_frac
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
228 * (see: fix_fullness_group())
230 static const int fullness_threshold_frac = 4;
234 * Size of objects stored in this class. Must be multiple
240 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
241 int pages_per_zspage;
243 #ifdef CONFIG_ZSMALLOC_STAT
244 struct zs_size_stat stats;
249 struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
253 * Placed within free objects to form a singly linked list.
254 * For every zspage, first_page->freelist gives head of this list.
256 * This must be power of 2 and less than or equal to ZS_ALIGN
261 * Position of next free chunk (encodes <PFN, obj_idx>)
262 * It's valid for non-allocated object
266 * Handle of allocated object.
268 unsigned long handle;
275 struct size_class **size_class;
276 struct kmem_cache *handle_cachep;
278 gfp_t flags; /* allocation flags used when growing pool */
279 atomic_long_t pages_allocated;
281 #ifdef CONFIG_ZSMALLOC_STAT
282 struct dentry *stat_dentry;
287 * A zspage's class index and fullness group
288 * are encoded in its (first)page->mapping
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)
295 struct mapping_area {
296 #ifdef CONFIG_PGTABLE_MAPPING
297 struct vm_struct *vm; /* vm area for mapping object that span pages */
299 char *vm_buf; /* copy buffer for objects that span pages */
301 char *vm_addr; /* address of kmap_atomic()'ed pages */
302 enum zs_mapmode vm_mm; /* mapping mode */
305 static int create_handle_cache(struct zs_pool *pool)
307 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
309 return pool->handle_cachep ? 0 : 1;
312 static void destroy_handle_cache(struct zs_pool *pool)
314 kmem_cache_destroy(pool->handle_cachep);
317 static unsigned long alloc_handle(struct zs_pool *pool)
319 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
320 pool->flags & ~__GFP_HIGHMEM);
323 static void free_handle(struct zs_pool *pool, unsigned long handle)
325 kmem_cache_free(pool->handle_cachep, (void *)handle);
328 static void record_obj(unsigned long handle, unsigned long obj)
330 *(unsigned long *)handle = obj;
337 static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops)
339 return zs_create_pool(name, gfp);
342 static void zs_zpool_destroy(void *pool)
344 zs_destroy_pool(pool);
347 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
348 unsigned long *handle)
350 *handle = zs_malloc(pool, size);
351 return *handle ? 0 : -1;
353 static void zs_zpool_free(void *pool, unsigned long handle)
355 zs_free(pool, handle);
358 static int zs_zpool_shrink(void *pool, unsigned int pages,
359 unsigned int *reclaimed)
364 static void *zs_zpool_map(void *pool, unsigned long handle,
365 enum zpool_mapmode mm)
367 enum zs_mapmode zs_mm;
376 case ZPOOL_MM_RW: /* fallthru */
382 return zs_map_object(pool, handle, zs_mm);
384 static void zs_zpool_unmap(void *pool, unsigned long handle)
386 zs_unmap_object(pool, handle);
389 static u64 zs_zpool_total_size(void *pool)
391 return zs_get_total_pages(pool) << PAGE_SHIFT;
394 static struct zpool_driver zs_zpool_driver = {
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,
403 .unmap = zs_zpool_unmap,
404 .total_size = zs_zpool_total_size,
407 MODULE_ALIAS("zpool-zsmalloc");
408 #endif /* CONFIG_ZPOOL */
410 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
411 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
413 static int is_first_page(struct page *page)
415 return PagePrivate(page);
418 static int is_last_page(struct page *page)
420 return PagePrivate2(page);
423 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
424 enum fullness_group *fullness)
427 BUG_ON(!is_first_page(page));
429 m = (unsigned long)page->mapping;
430 *fullness = m & FULLNESS_MASK;
431 *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
434 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
435 enum fullness_group fullness)
438 BUG_ON(!is_first_page(page));
440 m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
441 (fullness & FULLNESS_MASK);
442 page->mapping = (struct address_space *)m;
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.
452 static int get_size_class_index(int size)
456 if (likely(size > ZS_MIN_ALLOC_SIZE))
457 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
458 ZS_SIZE_CLASS_DELTA);
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.
470 static enum fullness_group get_fullness_group(struct page *page)
472 int inuse, max_objects;
473 enum fullness_group fg;
474 BUG_ON(!is_first_page(page));
477 max_objects = page->objects;
481 else if (inuse == max_objects)
483 else if (inuse <= 3 * max_objects / fullness_threshold_frac)
484 fg = ZS_ALMOST_EMPTY;
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>.
497 static void insert_zspage(struct page *page, struct size_class *class,
498 enum fullness_group fullness)
502 BUG_ON(!is_first_page(page));
504 if (fullness >= _ZS_NR_FULLNESS_GROUPS)
507 head = &class->fullness_list[fullness];
509 list_add_tail(&page->lru, &(*head)->lru);
515 * This function removes the given zspage from the freelist identified
516 * by <class, fullness_group>.
518 static void remove_zspage(struct page *page, struct size_class *class,
519 enum fullness_group fullness)
523 BUG_ON(!is_first_page(page));
525 if (fullness >= _ZS_NR_FULLNESS_GROUPS)
528 head = &class->fullness_list[fullness];
530 if (list_empty(&(*head)->lru))
532 else if (*head == page)
533 *head = (struct page *)list_entry((*head)->lru.next,
536 list_del_init(&page->lru);
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
548 static enum fullness_group fix_fullness_group(struct size_class *class,
552 enum fullness_group currfg, newfg;
554 BUG_ON(!is_first_page(page));
556 get_zspage_mapping(page, &class_idx, &currfg);
557 newfg = get_fullness_group(page);
561 remove_zspage(page, class, currfg);
562 insert_zspage(page, class, newfg);
563 set_zspage_mapping(page, class_idx, newfg);
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, ...
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.
581 static int get_pages_per_zspage(int class_size)
583 int i, max_usedpc = 0;
584 /* zspage order which gives maximum used size per KB */
585 int max_usedpc_order = 1;
587 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
591 zspage_size = i * PAGE_SIZE;
592 waste = zspage_size % class_size;
593 usedpc = (zspage_size - waste) * 100 / zspage_size;
595 if (usedpc > max_usedpc) {
597 max_usedpc_order = i;
601 return max_usedpc_order;
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.
609 static struct page *get_first_page(struct page *page)
611 if (is_first_page(page))
614 return page->first_page;
617 static struct page *get_next_page(struct page *page)
621 if (is_last_page(page))
623 else if (is_first_page(page))
624 next = (struct page *)page_private(page);
626 next = list_entry(page->lru.next, struct page, lru);
632 * Encode <page, obj_idx> as a single handle value.
633 * We use the least bit of handle for tagging.
635 static void *location_to_obj(struct page *page, unsigned long obj_idx)
644 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
645 obj |= ((obj_idx) & OBJ_INDEX_MASK);
646 obj <<= OBJ_TAG_BITS;
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
656 static void obj_to_location(unsigned long obj, struct page **page,
657 unsigned long *obj_idx)
659 obj >>= OBJ_TAG_BITS;
660 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
661 *obj_idx = (obj & OBJ_INDEX_MASK);
664 static unsigned long handle_to_obj(unsigned long handle)
666 return *(unsigned long *)handle;
669 unsigned long obj_to_head(void *obj)
671 return *(unsigned long *)obj;
674 static unsigned long obj_idx_to_offset(struct page *page,
675 unsigned long obj_idx, int class_size)
677 unsigned long off = 0;
679 if (!is_first_page(page))
682 return off + obj_idx * class_size;
685 static inline int trypin_tag(unsigned long handle)
687 unsigned long *ptr = (unsigned long *)handle;
689 return !test_and_set_bit_lock(HANDLE_PIN_BIT, ptr);
692 static void pin_tag(unsigned long handle)
694 while (!trypin_tag(handle));
697 static void unpin_tag(unsigned long handle)
699 unsigned long *ptr = (unsigned long *)handle;
701 clear_bit_unlock(HANDLE_PIN_BIT, ptr);
704 static void reset_page(struct page *page)
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;
711 page_mapcount_reset(page);
714 static void free_zspage(struct page *first_page)
716 struct page *nextp, *tmp, *head_extra;
718 BUG_ON(!is_first_page(first_page));
719 BUG_ON(first_page->inuse);
721 head_extra = (struct page *)page_private(first_page);
723 reset_page(first_page);
724 __free_page(first_page);
726 /* zspage with only 1 system page */
730 list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
731 list_del(&nextp->lru);
735 reset_page(head_extra);
736 __free_page(head_extra);
739 /* Initialize a newly allocated zspage */
740 static void init_zspage(struct page *first_page, struct size_class *class)
742 unsigned long off = 0;
743 struct page *page = first_page;
745 BUG_ON(!is_first_page(first_page));
747 struct page *next_page;
748 struct link_free *link;
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.
758 if (page != first_page)
761 vaddr = kmap_atomic(page);
762 link = (struct link_free *)vaddr + off / sizeof(*link);
764 while ((off += class->size) < PAGE_SIZE) {
765 link->next = location_to_obj(page, i++);
766 link += class->size / sizeof(*link);
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
774 next_page = get_next_page(page);
775 link->next = location_to_obj(next_page, 0);
776 kunmap_atomic(vaddr);
783 * Allocate a zspage for the given size class
785 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
788 struct page *first_page = NULL, *uninitialized_var(prev_page);
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
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.
802 for (i = 0; i < class->pages_per_zspage; i++) {
805 page = alloc_page(flags);
809 INIT_LIST_HEAD(&page->lru);
810 if (i == 0) { /* first page */
811 SetPagePrivate(page);
812 set_page_private(page, 0);
814 first_page->inuse = 0;
817 set_page_private(first_page, (unsigned long)page);
819 page->first_page = first_page;
821 list_add(&page->lru, &prev_page->lru);
822 if (i == class->pages_per_zspage - 1) /* last page */
823 SetPagePrivate2(page);
827 init_zspage(first_page, class);
829 first_page->freelist = location_to_obj(first_page, 0);
830 /* Maximum number of objects we can store in this zspage */
831 first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
833 error = 0; /* Success */
836 if (unlikely(error) && first_page) {
837 free_zspage(first_page);
844 static struct page *find_get_zspage(struct size_class *class)
849 for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
850 page = class->fullness_list[i];
858 #ifdef CONFIG_PGTABLE_MAPPING
859 static inline int __zs_cpu_up(struct mapping_area *area)
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
867 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
873 static inline void __zs_cpu_down(struct mapping_area *area)
876 free_vm_area(area->vm);
880 static inline void *__zs_map_object(struct mapping_area *area,
881 struct page *pages[2], int off, int size)
883 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
884 area->vm_addr = area->vm->addr;
885 return area->vm_addr + off;
888 static inline void __zs_unmap_object(struct mapping_area *area,
889 struct page *pages[2], int off, int size)
891 unsigned long addr = (unsigned long)area->vm_addr;
893 unmap_kernel_range(addr, PAGE_SIZE * 2);
896 #else /* CONFIG_PGTABLE_MAPPING */
898 static inline int __zs_cpu_up(struct mapping_area *area)
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
906 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
912 static inline void __zs_cpu_down(struct mapping_area *area)
918 static void *__zs_map_object(struct mapping_area *area,
919 struct page *pages[2], int off, int size)
923 char *buf = area->vm_buf;
925 /* disable page faults to match kmap_atomic() return conditions */
928 /* no read fastpath */
929 if (area->vm_mm == ZS_MM_WO)
932 sizes[0] = PAGE_SIZE - off;
933 sizes[1] = size - sizes[0];
935 /* copy object to per-cpu buffer */
936 addr = kmap_atomic(pages[0]);
937 memcpy(buf, addr + off, sizes[0]);
939 addr = kmap_atomic(pages[1]);
940 memcpy(buf + sizes[0], addr, sizes[1]);
946 static void __zs_unmap_object(struct mapping_area *area,
947 struct page *pages[2], int off, int size)
953 /* no write fastpath */
954 if (area->vm_mm == ZS_MM_RO)
957 buf = area->vm_buf + ZS_HANDLE_SIZE;
958 size -= ZS_HANDLE_SIZE;
959 off += ZS_HANDLE_SIZE;
961 sizes[0] = PAGE_SIZE - off;
962 sizes[1] = size - sizes[0];
964 /* copy per-cpu buffer to object */
965 addr = kmap_atomic(pages[0]);
966 memcpy(addr + off, buf, sizes[0]);
968 addr = kmap_atomic(pages[1]);
969 memcpy(addr, buf + sizes[0], sizes[1]);
973 /* enable page faults to match kunmap_atomic() return conditions */
977 #endif /* CONFIG_PGTABLE_MAPPING */
979 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
982 int ret, cpu = (long)pcpu;
983 struct mapping_area *area;
987 area = &per_cpu(zs_map_area, cpu);
988 ret = __zs_cpu_up(area);
990 return notifier_from_errno(ret);
993 case CPU_UP_CANCELED:
994 area = &per_cpu(zs_map_area, cpu);
1002 static struct notifier_block zs_cpu_nb = {
1003 .notifier_call = zs_cpu_notifier
1006 static int zs_register_cpu_notifier(void)
1008 int cpu, uninitialized_var(ret);
1010 cpu_notifier_register_begin();
1012 __register_cpu_notifier(&zs_cpu_nb);
1013 for_each_online_cpu(cpu) {
1014 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1015 if (notifier_to_errno(ret))
1019 cpu_notifier_register_done();
1020 return notifier_to_errno(ret);
1023 static void zs_unregister_cpu_notifier(void)
1027 cpu_notifier_register_begin();
1029 for_each_online_cpu(cpu)
1030 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1031 __unregister_cpu_notifier(&zs_cpu_nb);
1033 cpu_notifier_register_done();
1036 static void init_zs_size_classes(void)
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)
1044 zs_size_classes = nr;
1047 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
1049 return pages_per_zspage * PAGE_SIZE / size;
1052 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1054 if (prev->pages_per_zspage != pages_per_zspage)
1057 if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1058 != get_maxobj_per_zspage(size, pages_per_zspage))
1064 static bool zspage_full(struct page *page)
1066 BUG_ON(!is_first_page(page));
1068 return page->inuse == page->objects;
1071 #ifdef CONFIG_ZSMALLOC_STAT
1073 static inline void zs_stat_inc(struct size_class *class,
1074 enum zs_stat_type type, unsigned long cnt)
1076 class->stats.objs[type] += cnt;
1079 static inline void zs_stat_dec(struct size_class *class,
1080 enum zs_stat_type type, unsigned long cnt)
1082 class->stats.objs[type] -= cnt;
1085 static inline unsigned long zs_stat_get(struct size_class *class,
1086 enum zs_stat_type type)
1088 return class->stats.objs[type];
1091 static int __init zs_stat_init(void)
1093 if (!debugfs_initialized())
1096 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
1103 static void __exit zs_stat_exit(void)
1105 debugfs_remove_recursive(zs_stat_root);
1108 static int zs_stats_size_show(struct seq_file *s, void *v)
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;
1117 seq_printf(s, " %5s %5s %13s %10s %10s\n", "class", "size",
1118 "obj_allocated", "obj_used", "pages_used");
1120 for (i = 0; i < zs_size_classes; i++) {
1121 class = pool->size_class[i];
1123 if (class->index != i)
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);
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;
1136 seq_printf(s, " %5u %5u %10lu %10lu %10lu\n", i,
1137 class->size, obj_allocated, obj_used, pages_used);
1139 total_objs += obj_allocated;
1140 total_used_objs += obj_used;
1141 total_pages += pages_used;
1145 seq_printf(s, " %5s %5s %10lu %10lu %10lu\n", "Total", "",
1146 total_objs, total_used_objs, total_pages);
1151 static int zs_stats_size_open(struct inode *inode, struct file *file)
1153 return single_open(file, zs_stats_size_show, inode->i_private);
1156 static const struct file_operations zs_stat_size_ops = {
1157 .open = zs_stats_size_open,
1159 .llseek = seq_lseek,
1160 .release = single_release,
1163 static int zs_pool_stat_create(char *name, struct zs_pool *pool)
1165 struct dentry *entry;
1170 entry = debugfs_create_dir(name, zs_stat_root);
1172 pr_warn("debugfs dir <%s> creation failed\n", name);
1175 pool->stat_dentry = entry;
1177 entry = debugfs_create_file("obj_in_classes", S_IFREG | S_IRUGO,
1178 pool->stat_dentry, pool, &zs_stat_size_ops);
1180 pr_warn("%s: debugfs file entry <%s> creation failed\n",
1181 name, "obj_in_classes");
1188 static void zs_pool_stat_destroy(struct zs_pool *pool)
1190 debugfs_remove_recursive(pool->stat_dentry);
1193 #else /* CONFIG_ZSMALLOC_STAT */
1195 static inline void zs_stat_inc(struct size_class *class,
1196 enum zs_stat_type type, unsigned long cnt)
1200 static inline void zs_stat_dec(struct size_class *class,
1201 enum zs_stat_type type, unsigned long cnt)
1205 static inline unsigned long zs_stat_get(struct size_class *class,
1206 enum zs_stat_type type)
1211 static int __init zs_stat_init(void)
1216 static void __exit zs_stat_exit(void)
1220 static inline int zs_pool_stat_create(char *name, struct zs_pool *pool)
1225 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
1231 unsigned long zs_get_total_pages(struct zs_pool *pool)
1233 return atomic_long_read(&pool->pages_allocated);
1235 EXPORT_SYMBOL_GPL(zs_get_total_pages);
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
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
1246 * Only one object can be mapped per cpu at a time. There is no protection
1247 * against nested mappings.
1249 * This function returns with preemption and page faults disabled.
1251 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1255 unsigned long obj, obj_idx, off;
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];
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.
1271 BUG_ON(in_interrupt());
1273 /* From now on, migration cannot move the object */
1276 obj = handle_to_obj(handle);
1277 obj_to_location(obj, &page, &obj_idx);
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);
1282 area = &get_cpu_var(zs_map_area);
1284 if (off + class->size <= PAGE_SIZE) {
1285 /* this object is contained entirely within a page */
1286 area->vm_addr = kmap_atomic(page);
1287 ret = area->vm_addr + off;
1291 /* this object spans two pages */
1293 pages[1] = get_next_page(page);
1296 ret = __zs_map_object(area, pages, off, class->size);
1298 return ret + ZS_HANDLE_SIZE;
1300 EXPORT_SYMBOL_GPL(zs_map_object);
1302 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1305 unsigned long obj, obj_idx, off;
1307 unsigned int class_idx;
1308 enum fullness_group fg;
1309 struct size_class *class;
1310 struct mapping_area *area;
1314 obj = handle_to_obj(handle);
1315 obj_to_location(obj, &page, &obj_idx);
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);
1320 area = this_cpu_ptr(&zs_map_area);
1321 if (off + class->size <= PAGE_SIZE)
1322 kunmap_atomic(area->vm_addr);
1324 struct page *pages[2];
1327 pages[1] = get_next_page(page);
1330 __zs_unmap_object(area, pages, off, class->size);
1332 put_cpu_var(zs_map_area);
1335 EXPORT_SYMBOL_GPL(zs_unmap_object);
1337 static unsigned long obj_malloc(struct page *first_page,
1338 struct size_class *class, unsigned long handle)
1341 struct link_free *link;
1343 struct page *m_page;
1344 unsigned long m_objidx, m_offset;
1347 handle |= OBJ_ALLOCATED_TAG;
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);
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);
1366 * zs_malloc - Allocate block of given size from pool.
1367 * @pool: pool to allocate from
1368 * @size: size of block to allocate
1370 * On success, handle to the allocated object is returned,
1372 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1374 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1376 unsigned long handle, obj;
1377 struct size_class *class;
1378 struct page *first_page;
1380 if (unlikely(!size || (size + ZS_HANDLE_SIZE) > ZS_MAX_ALLOC_SIZE))
1383 handle = alloc_handle(pool);
1387 /* extra space in chunk to keep the handle */
1388 size += ZS_HANDLE_SIZE;
1389 class = pool->size_class[get_size_class_index(size)];
1391 spin_lock(&class->lock);
1392 first_page = find_get_zspage(class);
1395 spin_unlock(&class->lock);
1396 first_page = alloc_zspage(class, pool->flags);
1397 if (unlikely(!first_page)) {
1398 free_handle(pool, handle);
1402 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1403 atomic_long_add(class->pages_per_zspage,
1404 &pool->pages_allocated);
1406 spin_lock(&class->lock);
1407 zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1408 class->size, class->pages_per_zspage));
1411 obj = obj_malloc(first_page, class, handle);
1412 /* Now move the zspage to another fullness group, if required */
1413 fix_fullness_group(class, first_page);
1414 record_obj(handle, obj);
1415 spin_unlock(&class->lock);
1419 EXPORT_SYMBOL_GPL(zs_malloc);
1421 static void obj_free(struct zs_pool *pool, struct size_class *class,
1424 struct link_free *link;
1425 struct page *first_page, *f_page;
1426 unsigned long f_objidx, f_offset;
1429 enum fullness_group fullness;
1433 obj &= ~OBJ_ALLOCATED_TAG;
1434 obj_to_location(obj, &f_page, &f_objidx);
1435 first_page = get_first_page(f_page);
1437 get_zspage_mapping(first_page, &class_idx, &fullness);
1438 f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1440 vaddr = kmap_atomic(f_page);
1442 /* Insert this object in containing zspage's freelist */
1443 link = (struct link_free *)(vaddr + f_offset);
1444 link->next = first_page->freelist;
1445 kunmap_atomic(vaddr);
1446 first_page->freelist = (void *)obj;
1447 first_page->inuse--;
1448 zs_stat_dec(class, OBJ_USED, 1);
1451 void zs_free(struct zs_pool *pool, unsigned long handle)
1453 struct page *first_page, *f_page;
1454 unsigned long obj, f_objidx;
1456 struct size_class *class;
1457 enum fullness_group fullness;
1459 if (unlikely(!handle))
1463 obj = handle_to_obj(handle);
1464 obj_to_location(obj, &f_page, &f_objidx);
1465 first_page = get_first_page(f_page);
1467 get_zspage_mapping(first_page, &class_idx, &fullness);
1468 class = pool->size_class[class_idx];
1470 spin_lock(&class->lock);
1471 obj_free(pool, class, obj);
1472 fullness = fix_fullness_group(class, first_page);
1473 if (fullness == ZS_EMPTY) {
1474 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1475 class->size, class->pages_per_zspage));
1476 atomic_long_sub(class->pages_per_zspage,
1477 &pool->pages_allocated);
1478 free_zspage(first_page);
1480 spin_unlock(&class->lock);
1483 free_handle(pool, handle);
1485 EXPORT_SYMBOL_GPL(zs_free);
1487 static void zs_object_copy(unsigned long src, unsigned long dst,
1488 struct size_class *class)
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;
1497 s_size = d_size = class->size;
1499 obj_to_location(src, &s_page, &s_objidx);
1500 obj_to_location(dst, &d_page, &d_objidx);
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);
1505 if (s_off + class->size > PAGE_SIZE)
1506 s_size = PAGE_SIZE - s_off;
1508 if (d_off + class->size > PAGE_SIZE)
1509 d_size = PAGE_SIZE - d_off;
1511 s_addr = kmap_atomic(s_page);
1512 d_addr = kmap_atomic(d_page);
1515 size = min(s_size, d_size);
1516 memcpy(d_addr + d_off, s_addr + s_off, size);
1519 if (written == class->size)
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);
1527 s_addr = kmap_atomic(s_page);
1528 d_addr = kmap_atomic(d_page);
1529 s_size = class->size - written;
1536 if (d_off + size >= PAGE_SIZE) {
1537 kunmap_atomic(d_addr);
1538 d_page = get_next_page(d_page);
1540 d_addr = kmap_atomic(d_page);
1541 d_size = class->size - written;
1549 kunmap_atomic(d_addr);
1550 kunmap_atomic(s_addr);
1554 * Find alloced object in zspage from index object and
1557 static unsigned long find_alloced_obj(struct page *page, int index,
1558 struct size_class *class)
1562 unsigned long handle = 0;
1563 void *addr = kmap_atomic(page);
1565 if (!is_first_page(page))
1566 offset = page->index;
1567 offset += class->size * index;
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))
1578 offset += class->size;
1582 kunmap_atomic(addr);
1586 struct 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
1591 struct page *d_page;
1592 /* Starting object index within @s_page which used for live object
1593 * in the subpage. */
1595 /* how many of objects are migrated */
1599 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1600 struct zs_compact_control *cc)
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;
1611 handle = find_alloced_obj(s_page, index, class);
1613 s_page = get_next_page(s_page);
1620 /* Stop if there is no more space */
1621 if (zspage_full(d_page)) {
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);
1631 record_obj(handle, free_obj);
1633 obj_free(pool, class, used_obj);
1637 /* Remember last position in this iteration */
1638 cc->s_page = s_page;
1640 cc->nr_migrated = nr_migrated;
1645 static struct page *alloc_target_page(struct size_class *class)
1650 for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
1651 page = class->fullness_list[i];
1653 remove_zspage(page, class, i);
1661 static void putback_zspage(struct zs_pool *pool, struct size_class *class,
1662 struct page *first_page)
1665 enum fullness_group fullness;
1667 BUG_ON(!is_first_page(first_page));
1669 get_zspage_mapping(first_page, &class_idx, &fullness);
1670 insert_zspage(first_page, class, fullness);
1671 fullness = fix_fullness_group(class, first_page);
1672 if (fullness == ZS_EMPTY) {
1673 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1674 class->size, class->pages_per_zspage));
1675 atomic_long_sub(class->pages_per_zspage,
1676 &pool->pages_allocated);
1678 free_zspage(first_page);
1682 static struct page *isolate_source_page(struct size_class *class)
1686 page = class->fullness_list[ZS_ALMOST_EMPTY];
1688 remove_zspage(page, class, ZS_ALMOST_EMPTY);
1693 static unsigned long __zs_compact(struct zs_pool *pool,
1694 struct size_class *class)
1697 struct zs_compact_control cc;
1698 struct page *src_page;
1699 struct page *dst_page = NULL;
1700 unsigned long nr_total_migrated = 0;
1704 spin_lock(&class->lock);
1705 while ((src_page = isolate_source_page(class))) {
1707 BUG_ON(!is_first_page(src_page));
1709 /* The goal is to migrate all live objects in source page */
1710 nr_to_migrate = src_page->inuse;
1712 cc.s_page = src_page;
1714 while ((dst_page = alloc_target_page(class))) {
1715 cc.d_page = dst_page;
1717 * If there is no more space in dst_page, try to
1718 * allocate another zspage.
1720 if (!migrate_zspage(pool, class, &cc))
1723 putback_zspage(pool, class, dst_page);
1724 nr_total_migrated += cc.nr_migrated;
1725 nr_to_migrate -= cc.nr_migrated;
1728 /* Stop if we couldn't find slot */
1729 if (dst_page == NULL)
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;
1737 spin_lock(&class->lock);
1741 putback_zspage(pool, class, src_page);
1743 spin_unlock(&class->lock);
1745 return nr_total_migrated;
1748 unsigned long zs_compact(struct zs_pool *pool)
1751 unsigned long nr_migrated = 0;
1752 struct size_class *class;
1754 for (i = zs_size_classes - 1; i >= 0; i--) {
1755 class = pool->size_class[i];
1758 if (class->index != i)
1760 nr_migrated += __zs_compact(pool, class);
1767 EXPORT_SYMBOL_GPL(zs_compact);
1770 * zs_create_pool - Creates an allocation pool to work from.
1771 * @flags: allocation flags used to allocate pool metadata
1773 * This function must be called before anything when using
1774 * the zsmalloc allocator.
1776 * On success, a pointer to the newly created pool is returned,
1779 struct zs_pool *zs_create_pool(char *name, gfp_t flags)
1782 struct zs_pool *pool;
1783 struct size_class *prev_class = NULL;
1785 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1789 pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1791 if (!pool->size_class) {
1796 pool->name = kstrdup(name, GFP_KERNEL);
1800 if (create_handle_cache(pool))
1804 * Iterate reversly, because, size of size_class that we want to use
1805 * for merging should be larger or equal to current size.
1807 for (i = zs_size_classes - 1; i >= 0; i--) {
1809 int pages_per_zspage;
1810 struct size_class *class;
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);
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.
1827 if (can_merge(prev_class, size, pages_per_zspage)) {
1828 pool->size_class[i] = prev_class;
1833 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1839 class->pages_per_zspage = pages_per_zspage;
1840 spin_lock_init(&class->lock);
1841 pool->size_class[i] = class;
1846 pool->flags = flags;
1848 if (zs_pool_stat_create(name, pool))
1854 zs_destroy_pool(pool);
1857 EXPORT_SYMBOL_GPL(zs_create_pool);
1859 void zs_destroy_pool(struct zs_pool *pool)
1863 zs_pool_stat_destroy(pool);
1865 for (i = 0; i < zs_size_classes; i++) {
1867 struct size_class *class = pool->size_class[i];
1872 if (class->index != i)
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",
1884 destroy_handle_cache(pool);
1885 kfree(pool->size_class);
1889 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1891 static int __init zs_init(void)
1893 int ret = zs_register_cpu_notifier();
1898 init_zs_size_classes();
1901 zpool_register_driver(&zs_zpool_driver);
1904 ret = zs_stat_init();
1906 pr_err("zs stat initialization failed\n");
1913 zpool_unregister_driver(&zs_zpool_driver);
1916 zs_unregister_cpu_notifier();
1921 static void __exit zs_exit(void)
1924 zpool_unregister_driver(&zs_zpool_driver);
1926 zs_unregister_cpu_notifier();
1931 module_init(zs_init);
1932 module_exit(zs_exit);
1934 MODULE_LICENSE("Dual BSD/GPL");
1935 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");