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/bitops.h>
82 #include <linux/errno.h>
83 #include <linux/highmem.h>
84 #include <linux/string.h>
85 #include <linux/slab.h>
86 #include <asm/tlbflush.h>
87 #include <asm/pgtable.h>
88 #include <linux/cpumask.h>
89 #include <linux/cpu.h>
90 #include <linux/vmalloc.h>
91 #include <linux/hardirq.h>
92 #include <linux/spinlock.h>
93 #include <linux/types.h>
94 #include <linux/debugfs.h>
95 #include <linux/zsmalloc.h>
96 #include <linux/zpool.h>
99 * This must be power of 2 and greater than of equal to sizeof(link_free).
100 * These two conditions ensure that any 'struct link_free' itself doesn't
101 * span more than 1 page which avoids complex case of mapping 2 pages simply
102 * to restore link_free pointer values.
107 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
108 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
110 #define ZS_MAX_ZSPAGE_ORDER 2
111 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
113 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
116 * Object location (<PFN>, <obj_idx>) is encoded as
117 * as single (unsigned long) handle value.
119 * Note that object index <obj_idx> is relative to system
120 * page <PFN> it is stored in, so for each sub-page belonging
121 * to a zspage, obj_idx starts with 0.
123 * This is made more complicated by various memory models and PAE.
126 #ifndef MAX_PHYSMEM_BITS
127 #ifdef CONFIG_HIGHMEM64G
128 #define MAX_PHYSMEM_BITS 36
129 #else /* !CONFIG_HIGHMEM64G */
131 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
134 #define MAX_PHYSMEM_BITS BITS_PER_LONG
137 #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
138 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS)
139 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
141 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
142 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
143 #define ZS_MIN_ALLOC_SIZE \
144 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
145 /* each chunk includes extra space to keep handle */
146 #define ZS_MAX_ALLOC_SIZE (PAGE_SIZE + ZS_HANDLE_SIZE)
149 * On systems with 4K page size, this gives 255 size classes! There is a
151 * - Large number of size classes is potentially wasteful as free page are
152 * spread across these classes
153 * - Small number of size classes causes large internal fragmentation
154 * - Probably its better to use specific size classes (empirically
155 * determined). NOTE: all those class sizes must be set as multiple of
156 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
158 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
161 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8)
164 * We do not maintain any list for completely empty or full pages
166 enum fullness_group {
169 _ZS_NR_FULLNESS_GROUPS,
181 #ifdef CONFIG_ZSMALLOC_STAT
183 static struct dentry *zs_stat_root;
185 struct zs_size_stat {
186 unsigned long objs[NR_ZS_STAT_TYPE];
192 * number of size_classes
194 static int zs_size_classes;
197 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
199 * n = number of allocated objects
200 * N = total number of objects zspage can store
201 * f = fullness_threshold_frac
203 * Similarly, we assign zspage to:
204 * ZS_ALMOST_FULL when n > N / f
205 * ZS_EMPTY when n == 0
206 * ZS_FULL when n == N
208 * (see: fix_fullness_group())
210 static const int fullness_threshold_frac = 4;
214 * Size of objects stored in this class. Must be multiple
220 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
221 int pages_per_zspage;
223 #ifdef CONFIG_ZSMALLOC_STAT
224 struct zs_size_stat stats;
229 struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
233 * Placed within free objects to form a singly linked list.
234 * For every zspage, first_page->freelist gives head of this list.
236 * This must be power of 2 and less than or equal to ZS_ALIGN
241 * Position of next free chunk (encodes <PFN, obj_idx>)
242 * It's valid for non-allocated object
246 * Handle of allocated object.
248 unsigned long handle;
255 struct size_class **size_class;
256 struct kmem_cache *handle_cachep;
258 gfp_t flags; /* allocation flags used when growing pool */
259 atomic_long_t pages_allocated;
261 #ifdef CONFIG_ZSMALLOC_STAT
262 struct dentry *stat_dentry;
267 * A zspage's class index and fullness group
268 * are encoded in its (first)page->mapping
270 #define CLASS_IDX_BITS 28
271 #define FULLNESS_BITS 4
272 #define CLASS_IDX_MASK ((1 << CLASS_IDX_BITS) - 1)
273 #define FULLNESS_MASK ((1 << FULLNESS_BITS) - 1)
275 struct mapping_area {
276 #ifdef CONFIG_PGTABLE_MAPPING
277 struct vm_struct *vm; /* vm area for mapping object that span pages */
279 char *vm_buf; /* copy buffer for objects that span pages */
281 char *vm_addr; /* address of kmap_atomic()'ed pages */
282 enum zs_mapmode vm_mm; /* mapping mode */
285 static int create_handle_cache(struct zs_pool *pool)
287 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
289 return pool->handle_cachep ? 0 : 1;
292 static void destroy_handle_cache(struct zs_pool *pool)
294 kmem_cache_destroy(pool->handle_cachep);
297 static unsigned long alloc_handle(struct zs_pool *pool)
299 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
300 pool->flags & ~__GFP_HIGHMEM);
303 static void free_handle(struct zs_pool *pool, unsigned long handle)
305 kmem_cache_free(pool->handle_cachep, (void *)handle);
308 static void record_obj(unsigned long handle, unsigned long obj)
310 *(unsigned long *)handle = obj;
317 static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops)
319 return zs_create_pool(name, gfp);
322 static void zs_zpool_destroy(void *pool)
324 zs_destroy_pool(pool);
327 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
328 unsigned long *handle)
330 *handle = zs_malloc(pool, size);
331 return *handle ? 0 : -1;
333 static void zs_zpool_free(void *pool, unsigned long handle)
335 zs_free(pool, handle);
338 static int zs_zpool_shrink(void *pool, unsigned int pages,
339 unsigned int *reclaimed)
344 static void *zs_zpool_map(void *pool, unsigned long handle,
345 enum zpool_mapmode mm)
347 enum zs_mapmode zs_mm;
356 case ZPOOL_MM_RW: /* fallthru */
362 return zs_map_object(pool, handle, zs_mm);
364 static void zs_zpool_unmap(void *pool, unsigned long handle)
366 zs_unmap_object(pool, handle);
369 static u64 zs_zpool_total_size(void *pool)
371 return zs_get_total_pages(pool) << PAGE_SHIFT;
374 static struct zpool_driver zs_zpool_driver = {
376 .owner = THIS_MODULE,
377 .create = zs_zpool_create,
378 .destroy = zs_zpool_destroy,
379 .malloc = zs_zpool_malloc,
380 .free = zs_zpool_free,
381 .shrink = zs_zpool_shrink,
383 .unmap = zs_zpool_unmap,
384 .total_size = zs_zpool_total_size,
387 MODULE_ALIAS("zpool-zsmalloc");
388 #endif /* CONFIG_ZPOOL */
390 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
391 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
393 static int is_first_page(struct page *page)
395 return PagePrivate(page);
398 static int is_last_page(struct page *page)
400 return PagePrivate2(page);
403 static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
404 enum fullness_group *fullness)
407 BUG_ON(!is_first_page(page));
409 m = (unsigned long)page->mapping;
410 *fullness = m & FULLNESS_MASK;
411 *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
414 static void set_zspage_mapping(struct page *page, unsigned int class_idx,
415 enum fullness_group fullness)
418 BUG_ON(!is_first_page(page));
420 m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
421 (fullness & FULLNESS_MASK);
422 page->mapping = (struct address_space *)m;
426 * zsmalloc divides the pool into various size classes where each
427 * class maintains a list of zspages where each zspage is divided
428 * into equal sized chunks. Each allocation falls into one of these
429 * classes depending on its size. This function returns index of the
430 * size class which has chunk size big enough to hold the give size.
432 static int get_size_class_index(int size)
436 if (likely(size > ZS_MIN_ALLOC_SIZE))
437 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
438 ZS_SIZE_CLASS_DELTA);
444 * For each size class, zspages are divided into different groups
445 * depending on how "full" they are. This was done so that we could
446 * easily find empty or nearly empty zspages when we try to shrink
447 * the pool (not yet implemented). This function returns fullness
448 * status of the given page.
450 static enum fullness_group get_fullness_group(struct page *page)
452 int inuse, max_objects;
453 enum fullness_group fg;
454 BUG_ON(!is_first_page(page));
457 max_objects = page->objects;
461 else if (inuse == max_objects)
463 else if (inuse <= max_objects / fullness_threshold_frac)
464 fg = ZS_ALMOST_EMPTY;
472 * Each size class maintains various freelists and zspages are assigned
473 * to one of these freelists based on the number of live objects they
474 * have. This functions inserts the given zspage into the freelist
475 * identified by <class, fullness_group>.
477 static void insert_zspage(struct page *page, struct size_class *class,
478 enum fullness_group fullness)
482 BUG_ON(!is_first_page(page));
484 if (fullness >= _ZS_NR_FULLNESS_GROUPS)
487 head = &class->fullness_list[fullness];
489 list_add_tail(&page->lru, &(*head)->lru);
495 * This function removes the given zspage from the freelist identified
496 * by <class, fullness_group>.
498 static void remove_zspage(struct page *page, struct size_class *class,
499 enum fullness_group fullness)
503 BUG_ON(!is_first_page(page));
505 if (fullness >= _ZS_NR_FULLNESS_GROUPS)
508 head = &class->fullness_list[fullness];
510 if (list_empty(&(*head)->lru))
512 else if (*head == page)
513 *head = (struct page *)list_entry((*head)->lru.next,
516 list_del_init(&page->lru);
520 * Each size class maintains zspages in different fullness groups depending
521 * on the number of live objects they contain. When allocating or freeing
522 * objects, the fullness status of the page can change, say, from ALMOST_FULL
523 * to ALMOST_EMPTY when freeing an object. This function checks if such
524 * a status change has occurred for the given page and accordingly moves the
525 * page from the freelist of the old fullness group to that of the new
528 static enum fullness_group fix_fullness_group(struct zs_pool *pool,
532 struct size_class *class;
533 enum fullness_group currfg, newfg;
535 BUG_ON(!is_first_page(page));
537 get_zspage_mapping(page, &class_idx, &currfg);
538 newfg = get_fullness_group(page);
542 class = pool->size_class[class_idx];
543 remove_zspage(page, class, currfg);
544 insert_zspage(page, class, newfg);
545 set_zspage_mapping(page, class_idx, newfg);
552 * We have to decide on how many pages to link together
553 * to form a zspage for each size class. This is important
554 * to reduce wastage due to unusable space left at end of
555 * each zspage which is given as:
556 * wastage = Zp - Zp % size_class
557 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
559 * For example, for size class of 3/8 * PAGE_SIZE, we should
560 * link together 3 PAGE_SIZE sized pages to form a zspage
561 * since then we can perfectly fit in 8 such objects.
563 static int get_pages_per_zspage(int class_size)
565 int i, max_usedpc = 0;
566 /* zspage order which gives maximum used size per KB */
567 int max_usedpc_order = 1;
569 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
573 zspage_size = i * PAGE_SIZE;
574 waste = zspage_size % class_size;
575 usedpc = (zspage_size - waste) * 100 / zspage_size;
577 if (usedpc > max_usedpc) {
579 max_usedpc_order = i;
583 return max_usedpc_order;
587 * A single 'zspage' is composed of many system pages which are
588 * linked together using fields in struct page. This function finds
589 * the first/head page, given any component page of a zspage.
591 static struct page *get_first_page(struct page *page)
593 if (is_first_page(page))
596 return page->first_page;
599 static struct page *get_next_page(struct page *page)
603 if (is_last_page(page))
605 else if (is_first_page(page))
606 next = (struct page *)page_private(page);
608 next = list_entry(page->lru.next, struct page, lru);
614 * Encode <page, obj_idx> as a single handle value.
615 * On hardware platforms with physical memory starting at 0x0 the pfn
616 * could be 0 so we ensure that the handle will never be 0 by adjusting the
617 * encoded obj_idx value before encoding.
619 static void *obj_location_to_handle(struct page *page, unsigned long obj_idx)
621 unsigned long handle;
628 handle = page_to_pfn(page) << OBJ_INDEX_BITS;
629 handle |= ((obj_idx + 1) & OBJ_INDEX_MASK);
631 return (void *)handle;
635 * Decode <page, obj_idx> pair from the given object handle. We adjust the
636 * decoded obj_idx back to its original value since it was adjusted in
637 * obj_location_to_handle().
639 static void obj_to_location(unsigned long handle, struct page **page,
640 unsigned long *obj_idx)
642 *page = pfn_to_page(handle >> OBJ_INDEX_BITS);
643 *obj_idx = (handle & OBJ_INDEX_MASK) - 1;
646 static unsigned long handle_to_obj(unsigned long handle)
648 return *(unsigned long *)handle;
651 static unsigned long obj_idx_to_offset(struct page *page,
652 unsigned long obj_idx, int class_size)
654 unsigned long off = 0;
656 if (!is_first_page(page))
659 return off + obj_idx * class_size;
662 static void reset_page(struct page *page)
664 clear_bit(PG_private, &page->flags);
665 clear_bit(PG_private_2, &page->flags);
666 set_page_private(page, 0);
667 page->mapping = NULL;
668 page->freelist = NULL;
669 page_mapcount_reset(page);
672 static void free_zspage(struct page *first_page)
674 struct page *nextp, *tmp, *head_extra;
676 BUG_ON(!is_first_page(first_page));
677 BUG_ON(first_page->inuse);
679 head_extra = (struct page *)page_private(first_page);
681 reset_page(first_page);
682 __free_page(first_page);
684 /* zspage with only 1 system page */
688 list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
689 list_del(&nextp->lru);
693 reset_page(head_extra);
694 __free_page(head_extra);
697 /* Initialize a newly allocated zspage */
698 static void init_zspage(struct page *first_page, struct size_class *class)
700 unsigned long off = 0;
701 struct page *page = first_page;
703 BUG_ON(!is_first_page(first_page));
705 struct page *next_page;
706 struct link_free *link;
711 * page->index stores offset of first object starting
712 * in the page. For the first page, this is always 0,
713 * so we use first_page->index (aka ->freelist) to store
714 * head of corresponding zspage's freelist.
716 if (page != first_page)
719 vaddr = kmap_atomic(page);
720 link = (struct link_free *)vaddr + off / sizeof(*link);
722 while ((off += class->size) < PAGE_SIZE) {
723 link->next = obj_location_to_handle(page, i++);
724 link += class->size / sizeof(*link);
728 * We now come to the last (full or partial) object on this
729 * page, which must point to the first object on the next
732 next_page = get_next_page(page);
733 link->next = obj_location_to_handle(next_page, 0);
734 kunmap_atomic(vaddr);
741 * Allocate a zspage for the given size class
743 static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
746 struct page *first_page = NULL, *uninitialized_var(prev_page);
749 * Allocate individual pages and link them together as:
750 * 1. first page->private = first sub-page
751 * 2. all sub-pages are linked together using page->lru
752 * 3. each sub-page is linked to the first page using page->first_page
754 * For each size class, First/Head pages are linked together using
755 * page->lru. Also, we set PG_private to identify the first page
756 * (i.e. no other sub-page has this flag set) and PG_private_2 to
757 * identify the last page.
760 for (i = 0; i < class->pages_per_zspage; i++) {
763 page = alloc_page(flags);
767 INIT_LIST_HEAD(&page->lru);
768 if (i == 0) { /* first page */
769 SetPagePrivate(page);
770 set_page_private(page, 0);
772 first_page->inuse = 0;
775 set_page_private(first_page, (unsigned long)page);
777 page->first_page = first_page;
779 list_add(&page->lru, &prev_page->lru);
780 if (i == class->pages_per_zspage - 1) /* last page */
781 SetPagePrivate2(page);
785 init_zspage(first_page, class);
787 first_page->freelist = obj_location_to_handle(first_page, 0);
788 /* Maximum number of objects we can store in this zspage */
789 first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
791 error = 0; /* Success */
794 if (unlikely(error) && first_page) {
795 free_zspage(first_page);
802 static struct page *find_get_zspage(struct size_class *class)
807 for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
808 page = class->fullness_list[i];
816 #ifdef CONFIG_PGTABLE_MAPPING
817 static inline int __zs_cpu_up(struct mapping_area *area)
820 * Make sure we don't leak memory if a cpu UP notification
821 * and zs_init() race and both call zs_cpu_up() on the same cpu
825 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
831 static inline void __zs_cpu_down(struct mapping_area *area)
834 free_vm_area(area->vm);
838 static inline void *__zs_map_object(struct mapping_area *area,
839 struct page *pages[2], int off, int size)
841 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
842 area->vm_addr = area->vm->addr;
843 return area->vm_addr + off;
846 static inline void __zs_unmap_object(struct mapping_area *area,
847 struct page *pages[2], int off, int size)
849 unsigned long addr = (unsigned long)area->vm_addr;
851 unmap_kernel_range(addr, PAGE_SIZE * 2);
854 #else /* CONFIG_PGTABLE_MAPPING */
856 static inline int __zs_cpu_up(struct mapping_area *area)
859 * Make sure we don't leak memory if a cpu UP notification
860 * and zs_init() race and both call zs_cpu_up() on the same cpu
864 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
870 static inline void __zs_cpu_down(struct mapping_area *area)
876 static void *__zs_map_object(struct mapping_area *area,
877 struct page *pages[2], int off, int size)
881 char *buf = area->vm_buf;
883 /* disable page faults to match kmap_atomic() return conditions */
886 /* no read fastpath */
887 if (area->vm_mm == ZS_MM_WO)
890 sizes[0] = PAGE_SIZE - off;
891 sizes[1] = size - sizes[0];
893 /* copy object to per-cpu buffer */
894 addr = kmap_atomic(pages[0]);
895 memcpy(buf, addr + off, sizes[0]);
897 addr = kmap_atomic(pages[1]);
898 memcpy(buf + sizes[0], addr, sizes[1]);
904 static void __zs_unmap_object(struct mapping_area *area,
905 struct page *pages[2], int off, int size)
911 /* no write fastpath */
912 if (area->vm_mm == ZS_MM_RO)
915 buf = area->vm_buf + ZS_HANDLE_SIZE;
916 size -= ZS_HANDLE_SIZE;
917 off += ZS_HANDLE_SIZE;
919 sizes[0] = PAGE_SIZE - off;
920 sizes[1] = size - sizes[0];
922 /* copy per-cpu buffer to object */
923 addr = kmap_atomic(pages[0]);
924 memcpy(addr + off, buf, sizes[0]);
926 addr = kmap_atomic(pages[1]);
927 memcpy(addr, buf + sizes[0], sizes[1]);
931 /* enable page faults to match kunmap_atomic() return conditions */
935 #endif /* CONFIG_PGTABLE_MAPPING */
937 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
940 int ret, cpu = (long)pcpu;
941 struct mapping_area *area;
945 area = &per_cpu(zs_map_area, cpu);
946 ret = __zs_cpu_up(area);
948 return notifier_from_errno(ret);
951 case CPU_UP_CANCELED:
952 area = &per_cpu(zs_map_area, cpu);
960 static struct notifier_block zs_cpu_nb = {
961 .notifier_call = zs_cpu_notifier
964 static int zs_register_cpu_notifier(void)
966 int cpu, uninitialized_var(ret);
968 cpu_notifier_register_begin();
970 __register_cpu_notifier(&zs_cpu_nb);
971 for_each_online_cpu(cpu) {
972 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
973 if (notifier_to_errno(ret))
977 cpu_notifier_register_done();
978 return notifier_to_errno(ret);
981 static void zs_unregister_cpu_notifier(void)
985 cpu_notifier_register_begin();
987 for_each_online_cpu(cpu)
988 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
989 __unregister_cpu_notifier(&zs_cpu_nb);
991 cpu_notifier_register_done();
994 static void init_zs_size_classes(void)
998 nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
999 if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1002 zs_size_classes = nr;
1005 static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
1007 return pages_per_zspage * PAGE_SIZE / size;
1010 static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
1012 if (prev->pages_per_zspage != pages_per_zspage)
1015 if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
1016 != get_maxobj_per_zspage(size, pages_per_zspage))
1022 #ifdef CONFIG_ZSMALLOC_STAT
1024 static inline void zs_stat_inc(struct size_class *class,
1025 enum zs_stat_type type, unsigned long cnt)
1027 class->stats.objs[type] += cnt;
1030 static inline void zs_stat_dec(struct size_class *class,
1031 enum zs_stat_type type, unsigned long cnt)
1033 class->stats.objs[type] -= cnt;
1036 static inline unsigned long zs_stat_get(struct size_class *class,
1037 enum zs_stat_type type)
1039 return class->stats.objs[type];
1042 static int __init zs_stat_init(void)
1044 if (!debugfs_initialized())
1047 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
1054 static void __exit zs_stat_exit(void)
1056 debugfs_remove_recursive(zs_stat_root);
1059 static int zs_stats_size_show(struct seq_file *s, void *v)
1062 struct zs_pool *pool = s->private;
1063 struct size_class *class;
1064 int objs_per_zspage;
1065 unsigned long obj_allocated, obj_used, pages_used;
1066 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
1068 seq_printf(s, " %5s %5s %13s %10s %10s\n", "class", "size",
1069 "obj_allocated", "obj_used", "pages_used");
1071 for (i = 0; i < zs_size_classes; i++) {
1072 class = pool->size_class[i];
1074 if (class->index != i)
1077 spin_lock(&class->lock);
1078 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
1079 obj_used = zs_stat_get(class, OBJ_USED);
1080 spin_unlock(&class->lock);
1082 objs_per_zspage = get_maxobj_per_zspage(class->size,
1083 class->pages_per_zspage);
1084 pages_used = obj_allocated / objs_per_zspage *
1085 class->pages_per_zspage;
1087 seq_printf(s, " %5u %5u %10lu %10lu %10lu\n", i,
1088 class->size, obj_allocated, obj_used, pages_used);
1090 total_objs += obj_allocated;
1091 total_used_objs += obj_used;
1092 total_pages += pages_used;
1096 seq_printf(s, " %5s %5s %10lu %10lu %10lu\n", "Total", "",
1097 total_objs, total_used_objs, total_pages);
1102 static int zs_stats_size_open(struct inode *inode, struct file *file)
1104 return single_open(file, zs_stats_size_show, inode->i_private);
1107 static const struct file_operations zs_stat_size_ops = {
1108 .open = zs_stats_size_open,
1110 .llseek = seq_lseek,
1111 .release = single_release,
1114 static int zs_pool_stat_create(char *name, struct zs_pool *pool)
1116 struct dentry *entry;
1121 entry = debugfs_create_dir(name, zs_stat_root);
1123 pr_warn("debugfs dir <%s> creation failed\n", name);
1126 pool->stat_dentry = entry;
1128 entry = debugfs_create_file("obj_in_classes", S_IFREG | S_IRUGO,
1129 pool->stat_dentry, pool, &zs_stat_size_ops);
1131 pr_warn("%s: debugfs file entry <%s> creation failed\n",
1132 name, "obj_in_classes");
1139 static void zs_pool_stat_destroy(struct zs_pool *pool)
1141 debugfs_remove_recursive(pool->stat_dentry);
1144 #else /* CONFIG_ZSMALLOC_STAT */
1146 static inline void zs_stat_inc(struct size_class *class,
1147 enum zs_stat_type type, unsigned long cnt)
1151 static inline void zs_stat_dec(struct size_class *class,
1152 enum zs_stat_type type, unsigned long cnt)
1156 static inline unsigned long zs_stat_get(struct size_class *class,
1157 enum zs_stat_type type)
1162 static int __init zs_stat_init(void)
1167 static void __exit zs_stat_exit(void)
1171 static inline int zs_pool_stat_create(char *name, struct zs_pool *pool)
1176 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
1182 unsigned long zs_get_total_pages(struct zs_pool *pool)
1184 return atomic_long_read(&pool->pages_allocated);
1186 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1189 * zs_map_object - get address of allocated object from handle.
1190 * @pool: pool from which the object was allocated
1191 * @handle: handle returned from zs_malloc
1193 * Before using an object allocated from zs_malloc, it must be mapped using
1194 * this function. When done with the object, it must be unmapped using
1197 * Only one object can be mapped per cpu at a time. There is no protection
1198 * against nested mappings.
1200 * This function returns with preemption and page faults disabled.
1202 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1206 unsigned long obj, obj_idx, off;
1208 unsigned int class_idx;
1209 enum fullness_group fg;
1210 struct size_class *class;
1211 struct mapping_area *area;
1212 struct page *pages[2];
1218 * Because we use per-cpu mapping areas shared among the
1219 * pools/users, we can't allow mapping in interrupt context
1220 * because it can corrupt another users mappings.
1222 BUG_ON(in_interrupt());
1224 obj = handle_to_obj(handle);
1225 obj_to_location(obj, &page, &obj_idx);
1226 get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1227 class = pool->size_class[class_idx];
1228 off = obj_idx_to_offset(page, obj_idx, class->size);
1230 area = &get_cpu_var(zs_map_area);
1232 if (off + class->size <= PAGE_SIZE) {
1233 /* this object is contained entirely within a page */
1234 area->vm_addr = kmap_atomic(page);
1235 ret = area->vm_addr + off;
1239 /* this object spans two pages */
1241 pages[1] = get_next_page(page);
1244 ret = __zs_map_object(area, pages, off, class->size);
1246 return ret + ZS_HANDLE_SIZE;
1248 EXPORT_SYMBOL_GPL(zs_map_object);
1250 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1253 unsigned long obj, obj_idx, off;
1255 unsigned int class_idx;
1256 enum fullness_group fg;
1257 struct size_class *class;
1258 struct mapping_area *area;
1262 obj = handle_to_obj(handle);
1263 obj_to_location(obj, &page, &obj_idx);
1264 get_zspage_mapping(get_first_page(page), &class_idx, &fg);
1265 class = pool->size_class[class_idx];
1266 off = obj_idx_to_offset(page, obj_idx, class->size);
1268 area = this_cpu_ptr(&zs_map_area);
1269 if (off + class->size <= PAGE_SIZE)
1270 kunmap_atomic(area->vm_addr);
1272 struct page *pages[2];
1275 pages[1] = get_next_page(page);
1278 __zs_unmap_object(area, pages, off, class->size);
1280 put_cpu_var(zs_map_area);
1282 EXPORT_SYMBOL_GPL(zs_unmap_object);
1285 * zs_malloc - Allocate block of given size from pool.
1286 * @pool: pool to allocate from
1287 * @size: size of block to allocate
1289 * On success, handle to the allocated object is returned,
1291 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1293 unsigned long zs_malloc(struct zs_pool *pool, size_t size)
1295 unsigned long handle, obj;
1296 struct link_free *link;
1297 struct size_class *class;
1300 struct page *first_page, *m_page;
1301 unsigned long m_objidx, m_offset;
1303 if (unlikely(!size || (size + ZS_HANDLE_SIZE) > ZS_MAX_ALLOC_SIZE))
1306 handle = alloc_handle(pool);
1310 /* extra space in chunk to keep the handle */
1311 size += ZS_HANDLE_SIZE;
1312 class = pool->size_class[get_size_class_index(size)];
1314 spin_lock(&class->lock);
1315 first_page = find_get_zspage(class);
1318 spin_unlock(&class->lock);
1319 first_page = alloc_zspage(class, pool->flags);
1320 if (unlikely(!first_page)) {
1321 free_handle(pool, handle);
1325 set_zspage_mapping(first_page, class->index, ZS_EMPTY);
1326 atomic_long_add(class->pages_per_zspage,
1327 &pool->pages_allocated);
1329 spin_lock(&class->lock);
1330 zs_stat_inc(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1331 class->size, class->pages_per_zspage));
1334 obj = (unsigned long)first_page->freelist;
1335 obj_to_location(obj, &m_page, &m_objidx);
1336 m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
1338 vaddr = kmap_atomic(m_page);
1339 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1340 first_page->freelist = link->next;
1342 /* record handle in the header of allocated chunk */
1343 link->handle = handle;
1344 kunmap_atomic(vaddr);
1346 first_page->inuse++;
1347 zs_stat_inc(class, OBJ_USED, 1);
1348 /* Now move the zspage to another fullness group, if required */
1349 fix_fullness_group(pool, first_page);
1350 record_obj(handle, obj);
1351 spin_unlock(&class->lock);
1355 EXPORT_SYMBOL_GPL(zs_malloc);
1357 void zs_free(struct zs_pool *pool, unsigned long handle)
1359 struct link_free *link;
1360 struct page *first_page, *f_page;
1361 unsigned long obj, f_objidx, f_offset;
1365 struct size_class *class;
1366 enum fullness_group fullness;
1368 if (unlikely(!handle))
1371 obj = handle_to_obj(handle);
1372 free_handle(pool, handle);
1373 obj_to_location(obj, &f_page, &f_objidx);
1374 first_page = get_first_page(f_page);
1376 get_zspage_mapping(first_page, &class_idx, &fullness);
1377 class = pool->size_class[class_idx];
1378 f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
1380 spin_lock(&class->lock);
1382 /* Insert this object in containing zspage's freelist */
1383 vaddr = kmap_atomic(f_page);
1384 link = (struct link_free *)(vaddr + f_offset);
1385 link->next = first_page->freelist;
1386 kunmap_atomic(vaddr);
1387 first_page->freelist = (void *)obj;
1389 first_page->inuse--;
1390 fullness = fix_fullness_group(pool, first_page);
1392 zs_stat_dec(class, OBJ_USED, 1);
1393 if (fullness == ZS_EMPTY)
1394 zs_stat_dec(class, OBJ_ALLOCATED, get_maxobj_per_zspage(
1395 class->size, class->pages_per_zspage));
1397 spin_unlock(&class->lock);
1399 if (fullness == ZS_EMPTY) {
1400 atomic_long_sub(class->pages_per_zspage,
1401 &pool->pages_allocated);
1402 free_zspage(first_page);
1405 EXPORT_SYMBOL_GPL(zs_free);
1408 * zs_create_pool - Creates an allocation pool to work from.
1409 * @flags: allocation flags used to allocate pool metadata
1411 * This function must be called before anything when using
1412 * the zsmalloc allocator.
1414 * On success, a pointer to the newly created pool is returned,
1417 struct zs_pool *zs_create_pool(char *name, gfp_t flags)
1420 struct zs_pool *pool;
1421 struct size_class *prev_class = NULL;
1423 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
1427 pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
1429 if (!pool->size_class) {
1434 pool->name = kstrdup(name, GFP_KERNEL);
1438 if (create_handle_cache(pool))
1442 * Iterate reversly, because, size of size_class that we want to use
1443 * for merging should be larger or equal to current size.
1445 for (i = zs_size_classes - 1; i >= 0; i--) {
1447 int pages_per_zspage;
1448 struct size_class *class;
1450 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
1451 if (size > ZS_MAX_ALLOC_SIZE)
1452 size = ZS_MAX_ALLOC_SIZE;
1453 pages_per_zspage = get_pages_per_zspage(size);
1456 * size_class is used for normal zsmalloc operation such
1457 * as alloc/free for that size. Although it is natural that we
1458 * have one size_class for each size, there is a chance that we
1459 * can get more memory utilization if we use one size_class for
1460 * many different sizes whose size_class have same
1461 * characteristics. So, we makes size_class point to
1462 * previous size_class if possible.
1465 if (can_merge(prev_class, size, pages_per_zspage)) {
1466 pool->size_class[i] = prev_class;
1471 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
1477 class->pages_per_zspage = pages_per_zspage;
1478 spin_lock_init(&class->lock);
1479 pool->size_class[i] = class;
1484 pool->flags = flags;
1486 if (zs_pool_stat_create(name, pool))
1492 zs_destroy_pool(pool);
1495 EXPORT_SYMBOL_GPL(zs_create_pool);
1497 void zs_destroy_pool(struct zs_pool *pool)
1501 zs_pool_stat_destroy(pool);
1503 for (i = 0; i < zs_size_classes; i++) {
1505 struct size_class *class = pool->size_class[i];
1510 if (class->index != i)
1513 for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
1514 if (class->fullness_list[fg]) {
1515 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
1522 destroy_handle_cache(pool);
1523 kfree(pool->size_class);
1527 EXPORT_SYMBOL_GPL(zs_destroy_pool);
1529 static int __init zs_init(void)
1531 int ret = zs_register_cpu_notifier();
1536 init_zs_size_classes();
1539 zpool_register_driver(&zs_zpool_driver);
1542 ret = zs_stat_init();
1544 pr_err("zs stat initialization failed\n");
1551 zpool_unregister_driver(&zs_zpool_driver);
1554 zs_unregister_cpu_notifier();
1559 static void __exit zs_exit(void)
1562 zpool_unregister_driver(&zs_zpool_driver);
1564 zs_unregister_cpu_notifier();
1569 module_init(zs_init);
1570 module_exit(zs_exit);
1572 MODULE_LICENSE("Dual BSD/GPL");
1573 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");