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 * Following is how we use various fields and flags of underlying
16 * struct page(s) to form a zspage.
18 * Usage of struct page fields:
19 * page->private: points to zspage
20 * page->freelist(index): links together all component pages of a zspage
21 * For the huge page, this is always 0, so we use this field
23 * page->units: first object offset in a subpage of zspage
25 * Usage of struct page flags:
26 * PG_private: identifies the first component page
27 * PG_owner_priv_1: identifies the huge component page
31 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/sched.h>
36 #include <linux/magic.h>
37 #include <linux/bitops.h>
38 #include <linux/errno.h>
39 #include <linux/highmem.h>
40 #include <linux/string.h>
41 #include <linux/slab.h>
42 #include <asm/tlbflush.h>
43 #include <asm/pgtable.h>
44 #include <linux/cpumask.h>
45 #include <linux/cpu.h>
46 #include <linux/vmalloc.h>
47 #include <linux/preempt.h>
48 #include <linux/spinlock.h>
49 #include <linux/shrinker.h>
50 #include <linux/types.h>
51 #include <linux/debugfs.h>
52 #include <linux/zsmalloc.h>
53 #include <linux/zpool.h>
54 #include <linux/mount.h>
55 #include <linux/migrate.h>
56 #include <linux/pagemap.h>
59 #define ZSPAGE_MAGIC 0x58
62 * This must be power of 2 and greater than of equal to sizeof(link_free).
63 * These two conditions ensure that any 'struct link_free' itself doesn't
64 * span more than 1 page which avoids complex case of mapping 2 pages simply
65 * to restore link_free pointer values.
70 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
71 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
73 #define ZS_MAX_ZSPAGE_ORDER 2
74 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
76 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
79 * Object location (<PFN>, <obj_idx>) is encoded as
80 * as single (unsigned long) handle value.
82 * Note that object index <obj_idx> starts from 0.
84 * This is made more complicated by various memory models and PAE.
87 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
88 #ifdef MAX_PHYSMEM_BITS
89 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
92 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
95 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
99 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
102 * Memory for allocating for handle keeps object position by
103 * encoding <page, obj_idx> and the encoded value has a room
104 * in least bit(ie, look at obj_to_location).
105 * We use the bit to synchronize between object access by
106 * user and migration.
108 #define HANDLE_PIN_BIT 0
111 * Head in allocated object should have OBJ_ALLOCATED_TAG
112 * to identify the object was allocated or not.
113 * It's okay to add the status bit in the least bit because
114 * header keeps handle which is 4byte-aligned address so we
115 * have room for two bit at least.
117 #define OBJ_ALLOCATED_TAG 1
118 #define OBJ_TAG_BITS 1
119 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
120 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
122 #define FULLNESS_BITS 2
124 #define ISOLATED_BITS 3
125 #define MAGIC_VAL_BITS 8
127 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
128 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
129 #define ZS_MIN_ALLOC_SIZE \
130 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
131 /* each chunk includes extra space to keep handle */
132 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
135 * On systems with 4K page size, this gives 255 size classes! There is a
137 * - Large number of size classes is potentially wasteful as free page are
138 * spread across these classes
139 * - Small number of size classes causes large internal fragmentation
140 * - Probably its better to use specific size classes (empirically
141 * determined). NOTE: all those class sizes must be set as multiple of
142 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
144 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
147 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
148 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
149 ZS_SIZE_CLASS_DELTA) + 1)
151 enum fullness_group {
169 struct zs_size_stat {
170 unsigned long objs[NR_ZS_STAT_TYPE];
173 #ifdef CONFIG_ZSMALLOC_STAT
174 static struct dentry *zs_stat_root;
177 #ifdef CONFIG_COMPACTION
178 static struct vfsmount *zsmalloc_mnt;
182 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
184 * n = number of allocated objects
185 * N = total number of objects zspage can store
186 * f = fullness_threshold_frac
188 * Similarly, we assign zspage to:
189 * ZS_ALMOST_FULL when n > N / f
190 * ZS_EMPTY when n == 0
191 * ZS_FULL when n == N
193 * (see: fix_fullness_group())
195 static const int fullness_threshold_frac = 4;
196 static size_t huge_class_size;
200 struct list_head fullness_list[NR_ZS_FULLNESS];
202 * Size of objects stored in this class. Must be multiple
207 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
208 int pages_per_zspage;
211 struct zs_size_stat stats;
214 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
215 static void SetPageHugeObject(struct page *page)
217 SetPageOwnerPriv1(page);
220 static void ClearPageHugeObject(struct page *page)
222 ClearPageOwnerPriv1(page);
225 static int PageHugeObject(struct page *page)
227 return PageOwnerPriv1(page);
231 * Placed within free objects to form a singly linked list.
232 * For every zspage, zspage->freeobj gives head of this list.
234 * This must be power of 2 and less than or equal to ZS_ALIGN
240 * It's valid for non-allocated object
244 * Handle of allocated object.
246 unsigned long handle;
253 struct size_class *size_class[ZS_SIZE_CLASSES];
254 struct kmem_cache *handle_cachep;
255 struct kmem_cache *zspage_cachep;
257 atomic_long_t pages_allocated;
259 struct zs_pool_stats stats;
261 /* Compact classes */
262 struct shrinker shrinker;
264 #ifdef CONFIG_ZSMALLOC_STAT
265 struct dentry *stat_dentry;
267 #ifdef CONFIG_COMPACTION
269 struct work_struct free_work;
275 unsigned int fullness:FULLNESS_BITS;
276 unsigned int class:CLASS_BITS + 1;
277 unsigned int isolated:ISOLATED_BITS;
278 unsigned int magic:MAGIC_VAL_BITS;
281 unsigned int freeobj;
282 struct page *first_page;
283 struct list_head list; /* fullness list */
284 #ifdef CONFIG_COMPACTION
289 struct mapping_area {
290 #ifdef CONFIG_PGTABLE_MAPPING
291 struct vm_struct *vm; /* vm area for mapping object that span pages */
293 char *vm_buf; /* copy buffer for objects that span pages */
295 char *vm_addr; /* address of kmap_atomic()'ed pages */
296 enum zs_mapmode vm_mm; /* mapping mode */
299 #ifdef CONFIG_COMPACTION
300 static int zs_register_migration(struct zs_pool *pool);
301 static void zs_unregister_migration(struct zs_pool *pool);
302 static void migrate_lock_init(struct zspage *zspage);
303 static void migrate_read_lock(struct zspage *zspage);
304 static void migrate_read_unlock(struct zspage *zspage);
305 static void kick_deferred_free(struct zs_pool *pool);
306 static void init_deferred_free(struct zs_pool *pool);
307 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
309 static int zsmalloc_mount(void) { return 0; }
310 static void zsmalloc_unmount(void) {}
311 static int zs_register_migration(struct zs_pool *pool) { return 0; }
312 static void zs_unregister_migration(struct zs_pool *pool) {}
313 static void migrate_lock_init(struct zspage *zspage) {}
314 static void migrate_read_lock(struct zspage *zspage) {}
315 static void migrate_read_unlock(struct zspage *zspage) {}
316 static void kick_deferred_free(struct zs_pool *pool) {}
317 static void init_deferred_free(struct zs_pool *pool) {}
318 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
321 static int create_cache(struct zs_pool *pool)
323 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
325 if (!pool->handle_cachep)
328 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
330 if (!pool->zspage_cachep) {
331 kmem_cache_destroy(pool->handle_cachep);
332 pool->handle_cachep = NULL;
339 static void destroy_cache(struct zs_pool *pool)
341 kmem_cache_destroy(pool->handle_cachep);
342 kmem_cache_destroy(pool->zspage_cachep);
345 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
347 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
348 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
351 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
353 kmem_cache_free(pool->handle_cachep, (void *)handle);
356 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
358 return kmem_cache_alloc(pool->zspage_cachep,
359 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
362 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
364 kmem_cache_free(pool->zspage_cachep, zspage);
367 static void record_obj(unsigned long handle, unsigned long obj)
370 * lsb of @obj represents handle lock while other bits
371 * represent object value the handle is pointing so
372 * updating shouldn't do store tearing.
374 WRITE_ONCE(*(unsigned long *)handle, obj);
381 static void *zs_zpool_create(const char *name, gfp_t gfp,
382 const struct zpool_ops *zpool_ops,
386 * Ignore global gfp flags: zs_malloc() may be invoked from
387 * different contexts and its caller must provide a valid
390 return zs_create_pool(name);
393 static void zs_zpool_destroy(void *pool)
395 zs_destroy_pool(pool);
398 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
399 unsigned long *handle)
401 *handle = zs_malloc(pool, size, gfp);
402 return *handle ? 0 : -1;
404 static void zs_zpool_free(void *pool, unsigned long handle)
406 zs_free(pool, handle);
409 static void *zs_zpool_map(void *pool, unsigned long handle,
410 enum zpool_mapmode mm)
412 enum zs_mapmode zs_mm;
421 case ZPOOL_MM_RW: /* fall through */
427 return zs_map_object(pool, handle, zs_mm);
429 static void zs_zpool_unmap(void *pool, unsigned long handle)
431 zs_unmap_object(pool, handle);
434 static u64 zs_zpool_total_size(void *pool)
436 return zs_get_total_pages(pool) << PAGE_SHIFT;
439 static struct zpool_driver zs_zpool_driver = {
441 .owner = THIS_MODULE,
442 .create = zs_zpool_create,
443 .destroy = zs_zpool_destroy,
444 .malloc = zs_zpool_malloc,
445 .free = zs_zpool_free,
447 .unmap = zs_zpool_unmap,
448 .total_size = zs_zpool_total_size,
451 MODULE_ALIAS("zpool-zsmalloc");
452 #endif /* CONFIG_ZPOOL */
454 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
455 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
457 static bool is_zspage_isolated(struct zspage *zspage)
459 return zspage->isolated;
462 static __maybe_unused int is_first_page(struct page *page)
464 return PagePrivate(page);
467 /* Protected by class->lock */
468 static inline int get_zspage_inuse(struct zspage *zspage)
470 return zspage->inuse;
473 static inline void set_zspage_inuse(struct zspage *zspage, int val)
478 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
480 zspage->inuse += val;
483 static inline struct page *get_first_page(struct zspage *zspage)
485 struct page *first_page = zspage->first_page;
487 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
491 static inline int get_first_obj_offset(struct page *page)
496 static inline void set_first_obj_offset(struct page *page, int offset)
498 page->units = offset;
501 static inline unsigned int get_freeobj(struct zspage *zspage)
503 return zspage->freeobj;
506 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
508 zspage->freeobj = obj;
511 static void get_zspage_mapping(struct zspage *zspage,
512 unsigned int *class_idx,
513 enum fullness_group *fullness)
515 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
517 *fullness = zspage->fullness;
518 *class_idx = zspage->class;
521 static void set_zspage_mapping(struct zspage *zspage,
522 unsigned int class_idx,
523 enum fullness_group fullness)
525 zspage->class = class_idx;
526 zspage->fullness = fullness;
530 * zsmalloc divides the pool into various size classes where each
531 * class maintains a list of zspages where each zspage is divided
532 * into equal sized chunks. Each allocation falls into one of these
533 * classes depending on its size. This function returns index of the
534 * size class which has chunk size big enough to hold the give size.
536 static int get_size_class_index(int size)
540 if (likely(size > ZS_MIN_ALLOC_SIZE))
541 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
542 ZS_SIZE_CLASS_DELTA);
544 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
547 /* type can be of enum type zs_stat_type or fullness_group */
548 static inline void zs_stat_inc(struct size_class *class,
549 int type, unsigned long cnt)
551 class->stats.objs[type] += cnt;
554 /* type can be of enum type zs_stat_type or fullness_group */
555 static inline void zs_stat_dec(struct size_class *class,
556 int type, unsigned long cnt)
558 class->stats.objs[type] -= cnt;
561 /* type can be of enum type zs_stat_type or fullness_group */
562 static inline unsigned long zs_stat_get(struct size_class *class,
565 return class->stats.objs[type];
568 #ifdef CONFIG_ZSMALLOC_STAT
570 static void __init zs_stat_init(void)
572 if (!debugfs_initialized()) {
573 pr_warn("debugfs not available, stat dir not created\n");
577 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
580 static void __exit zs_stat_exit(void)
582 debugfs_remove_recursive(zs_stat_root);
585 static unsigned long zs_can_compact(struct size_class *class);
587 static int zs_stats_size_show(struct seq_file *s, void *v)
590 struct zs_pool *pool = s->private;
591 struct size_class *class;
593 unsigned long class_almost_full, class_almost_empty;
594 unsigned long obj_allocated, obj_used, pages_used, freeable;
595 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
596 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
597 unsigned long total_freeable = 0;
599 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
600 "class", "size", "almost_full", "almost_empty",
601 "obj_allocated", "obj_used", "pages_used",
602 "pages_per_zspage", "freeable");
604 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
605 class = pool->size_class[i];
607 if (class->index != i)
610 spin_lock(&class->lock);
611 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
612 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
613 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
614 obj_used = zs_stat_get(class, OBJ_USED);
615 freeable = zs_can_compact(class);
616 spin_unlock(&class->lock);
618 objs_per_zspage = class->objs_per_zspage;
619 pages_used = obj_allocated / objs_per_zspage *
620 class->pages_per_zspage;
622 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
623 " %10lu %10lu %16d %8lu\n",
624 i, class->size, class_almost_full, class_almost_empty,
625 obj_allocated, obj_used, pages_used,
626 class->pages_per_zspage, freeable);
628 total_class_almost_full += class_almost_full;
629 total_class_almost_empty += class_almost_empty;
630 total_objs += obj_allocated;
631 total_used_objs += obj_used;
632 total_pages += pages_used;
633 total_freeable += freeable;
637 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
638 "Total", "", total_class_almost_full,
639 total_class_almost_empty, total_objs,
640 total_used_objs, total_pages, "", total_freeable);
644 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
646 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
649 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
653 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
655 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
656 &zs_stats_size_fops);
659 static void zs_pool_stat_destroy(struct zs_pool *pool)
661 debugfs_remove_recursive(pool->stat_dentry);
664 #else /* CONFIG_ZSMALLOC_STAT */
665 static void __init zs_stat_init(void)
669 static void __exit zs_stat_exit(void)
673 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
677 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
684 * For each size class, zspages are divided into different groups
685 * depending on how "full" they are. This was done so that we could
686 * easily find empty or nearly empty zspages when we try to shrink
687 * the pool (not yet implemented). This function returns fullness
688 * status of the given page.
690 static enum fullness_group get_fullness_group(struct size_class *class,
691 struct zspage *zspage)
693 int inuse, objs_per_zspage;
694 enum fullness_group fg;
696 inuse = get_zspage_inuse(zspage);
697 objs_per_zspage = class->objs_per_zspage;
701 else if (inuse == objs_per_zspage)
703 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
704 fg = ZS_ALMOST_EMPTY;
712 * Each size class maintains various freelists and zspages are assigned
713 * to one of these freelists based on the number of live objects they
714 * have. This functions inserts the given zspage into the freelist
715 * identified by <class, fullness_group>.
717 static void insert_zspage(struct size_class *class,
718 struct zspage *zspage,
719 enum fullness_group fullness)
723 zs_stat_inc(class, fullness, 1);
724 head = list_first_entry_or_null(&class->fullness_list[fullness],
725 struct zspage, list);
727 * We want to see more ZS_FULL pages and less almost empty/full.
728 * Put pages with higher ->inuse first.
731 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
732 list_add(&zspage->list, &head->list);
736 list_add(&zspage->list, &class->fullness_list[fullness]);
740 * This function removes the given zspage from the freelist identified
741 * by <class, fullness_group>.
743 static void remove_zspage(struct size_class *class,
744 struct zspage *zspage,
745 enum fullness_group fullness)
747 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
748 VM_BUG_ON(is_zspage_isolated(zspage));
750 list_del_init(&zspage->list);
751 zs_stat_dec(class, fullness, 1);
755 * Each size class maintains zspages in different fullness groups depending
756 * on the number of live objects they contain. When allocating or freeing
757 * objects, the fullness status of the page can change, say, from ALMOST_FULL
758 * to ALMOST_EMPTY when freeing an object. This function checks if such
759 * a status change has occurred for the given page and accordingly moves the
760 * page from the freelist of the old fullness group to that of the new
763 static enum fullness_group fix_fullness_group(struct size_class *class,
764 struct zspage *zspage)
767 enum fullness_group currfg, newfg;
769 get_zspage_mapping(zspage, &class_idx, &currfg);
770 newfg = get_fullness_group(class, zspage);
774 if (!is_zspage_isolated(zspage)) {
775 remove_zspage(class, zspage, currfg);
776 insert_zspage(class, zspage, newfg);
779 set_zspage_mapping(zspage, class_idx, newfg);
786 * We have to decide on how many pages to link together
787 * to form a zspage for each size class. This is important
788 * to reduce wastage due to unusable space left at end of
789 * each zspage which is given as:
790 * wastage = Zp % class_size
791 * usage = Zp - wastage
792 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
794 * For example, for size class of 3/8 * PAGE_SIZE, we should
795 * link together 3 PAGE_SIZE sized pages to form a zspage
796 * since then we can perfectly fit in 8 such objects.
798 static int get_pages_per_zspage(int class_size)
800 int i, max_usedpc = 0;
801 /* zspage order which gives maximum used size per KB */
802 int max_usedpc_order = 1;
804 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
808 zspage_size = i * PAGE_SIZE;
809 waste = zspage_size % class_size;
810 usedpc = (zspage_size - waste) * 100 / zspage_size;
812 if (usedpc > max_usedpc) {
814 max_usedpc_order = i;
818 return max_usedpc_order;
821 static struct zspage *get_zspage(struct page *page)
823 struct zspage *zspage = (struct zspage *)page->private;
825 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
829 static struct page *get_next_page(struct page *page)
831 if (unlikely(PageHugeObject(page)))
834 return page->freelist;
838 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
839 * @obj: the encoded object value
840 * @page: page object resides in zspage
841 * @obj_idx: object index
843 static void obj_to_location(unsigned long obj, struct page **page,
844 unsigned int *obj_idx)
846 obj >>= OBJ_TAG_BITS;
847 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
848 *obj_idx = (obj & OBJ_INDEX_MASK);
852 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
853 * @page: page object resides in zspage
854 * @obj_idx: object index
856 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
860 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
861 obj |= obj_idx & OBJ_INDEX_MASK;
862 obj <<= OBJ_TAG_BITS;
867 static unsigned long handle_to_obj(unsigned long handle)
869 return *(unsigned long *)handle;
872 static unsigned long obj_to_head(struct page *page, void *obj)
874 if (unlikely(PageHugeObject(page))) {
875 VM_BUG_ON_PAGE(!is_first_page(page), page);
878 return *(unsigned long *)obj;
881 static inline int testpin_tag(unsigned long handle)
883 return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
886 static inline int trypin_tag(unsigned long handle)
888 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
891 static void pin_tag(unsigned long handle)
893 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
896 static void unpin_tag(unsigned long handle)
898 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
901 static void reset_page(struct page *page)
903 __ClearPageMovable(page);
904 ClearPagePrivate(page);
905 set_page_private(page, 0);
906 page_mapcount_reset(page);
907 ClearPageHugeObject(page);
908 page->freelist = NULL;
911 static int trylock_zspage(struct zspage *zspage)
913 struct page *cursor, *fail;
915 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
916 get_next_page(cursor)) {
917 if (!trylock_page(cursor)) {
925 for (cursor = get_first_page(zspage); cursor != fail; cursor =
926 get_next_page(cursor))
932 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
933 struct zspage *zspage)
935 struct page *page, *next;
936 enum fullness_group fg;
937 unsigned int class_idx;
939 get_zspage_mapping(zspage, &class_idx, &fg);
941 assert_spin_locked(&class->lock);
943 VM_BUG_ON(get_zspage_inuse(zspage));
944 VM_BUG_ON(fg != ZS_EMPTY);
946 next = page = get_first_page(zspage);
948 VM_BUG_ON_PAGE(!PageLocked(page), page);
949 next = get_next_page(page);
952 dec_zone_page_state(page, NR_ZSPAGES);
955 } while (page != NULL);
957 cache_free_zspage(pool, zspage);
959 zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
960 atomic_long_sub(class->pages_per_zspage,
961 &pool->pages_allocated);
964 static void free_zspage(struct zs_pool *pool, struct size_class *class,
965 struct zspage *zspage)
967 VM_BUG_ON(get_zspage_inuse(zspage));
968 VM_BUG_ON(list_empty(&zspage->list));
970 if (!trylock_zspage(zspage)) {
971 kick_deferred_free(pool);
975 remove_zspage(class, zspage, ZS_EMPTY);
976 __free_zspage(pool, class, zspage);
979 /* Initialize a newly allocated zspage */
980 static void init_zspage(struct size_class *class, struct zspage *zspage)
982 unsigned int freeobj = 1;
983 unsigned long off = 0;
984 struct page *page = get_first_page(zspage);
987 struct page *next_page;
988 struct link_free *link;
991 set_first_obj_offset(page, off);
993 vaddr = kmap_atomic(page);
994 link = (struct link_free *)vaddr + off / sizeof(*link);
996 while ((off += class->size) < PAGE_SIZE) {
997 link->next = freeobj++ << OBJ_TAG_BITS;
998 link += class->size / sizeof(*link);
1002 * We now come to the last (full or partial) object on this
1003 * page, which must point to the first object on the next
1006 next_page = get_next_page(page);
1008 link->next = freeobj++ << OBJ_TAG_BITS;
1011 * Reset OBJ_TAG_BITS bit to last link to tell
1012 * whether it's allocated object or not.
1014 link->next = -1UL << OBJ_TAG_BITS;
1016 kunmap_atomic(vaddr);
1021 set_freeobj(zspage, 0);
1024 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1025 struct page *pages[])
1029 struct page *prev_page = NULL;
1030 int nr_pages = class->pages_per_zspage;
1033 * Allocate individual pages and link them together as:
1034 * 1. all pages are linked together using page->freelist
1035 * 2. each sub-page point to zspage using page->private
1037 * we set PG_private to identify the first page (i.e. no other sub-page
1038 * has this flag set).
1040 for (i = 0; i < nr_pages; i++) {
1042 set_page_private(page, (unsigned long)zspage);
1043 page->freelist = NULL;
1045 zspage->first_page = page;
1046 SetPagePrivate(page);
1047 if (unlikely(class->objs_per_zspage == 1 &&
1048 class->pages_per_zspage == 1))
1049 SetPageHugeObject(page);
1051 prev_page->freelist = page;
1058 * Allocate a zspage for the given size class
1060 static struct zspage *alloc_zspage(struct zs_pool *pool,
1061 struct size_class *class,
1065 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1066 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1071 memset(zspage, 0, sizeof(struct zspage));
1072 zspage->magic = ZSPAGE_MAGIC;
1073 migrate_lock_init(zspage);
1075 for (i = 0; i < class->pages_per_zspage; i++) {
1078 page = alloc_page(gfp);
1081 dec_zone_page_state(pages[i], NR_ZSPAGES);
1082 __free_page(pages[i]);
1084 cache_free_zspage(pool, zspage);
1088 inc_zone_page_state(page, NR_ZSPAGES);
1092 create_page_chain(class, zspage, pages);
1093 init_zspage(class, zspage);
1098 static struct zspage *find_get_zspage(struct size_class *class)
1101 struct zspage *zspage;
1103 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1104 zspage = list_first_entry_or_null(&class->fullness_list[i],
1105 struct zspage, list);
1113 #ifdef CONFIG_PGTABLE_MAPPING
1114 static inline int __zs_cpu_up(struct mapping_area *area)
1117 * Make sure we don't leak memory if a cpu UP notification
1118 * and zs_init() race and both call zs_cpu_up() on the same cpu
1122 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1128 static inline void __zs_cpu_down(struct mapping_area *area)
1131 free_vm_area(area->vm);
1135 static inline void *__zs_map_object(struct mapping_area *area,
1136 struct page *pages[2], int off, int size)
1138 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1139 area->vm_addr = area->vm->addr;
1140 return area->vm_addr + off;
1143 static inline void __zs_unmap_object(struct mapping_area *area,
1144 struct page *pages[2], int off, int size)
1146 unsigned long addr = (unsigned long)area->vm_addr;
1148 unmap_kernel_range(addr, PAGE_SIZE * 2);
1151 #else /* CONFIG_PGTABLE_MAPPING */
1153 static inline int __zs_cpu_up(struct mapping_area *area)
1156 * Make sure we don't leak memory if a cpu UP notification
1157 * and zs_init() race and both call zs_cpu_up() on the same cpu
1161 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1167 static inline void __zs_cpu_down(struct mapping_area *area)
1169 kfree(area->vm_buf);
1170 area->vm_buf = NULL;
1173 static void *__zs_map_object(struct mapping_area *area,
1174 struct page *pages[2], int off, int size)
1178 char *buf = area->vm_buf;
1180 /* disable page faults to match kmap_atomic() return conditions */
1181 pagefault_disable();
1183 /* no read fastpath */
1184 if (area->vm_mm == ZS_MM_WO)
1187 sizes[0] = PAGE_SIZE - off;
1188 sizes[1] = size - sizes[0];
1190 /* copy object to per-cpu buffer */
1191 addr = kmap_atomic(pages[0]);
1192 memcpy(buf, addr + off, sizes[0]);
1193 kunmap_atomic(addr);
1194 addr = kmap_atomic(pages[1]);
1195 memcpy(buf + sizes[0], addr, sizes[1]);
1196 kunmap_atomic(addr);
1198 return area->vm_buf;
1201 static void __zs_unmap_object(struct mapping_area *area,
1202 struct page *pages[2], int off, int size)
1208 /* no write fastpath */
1209 if (area->vm_mm == ZS_MM_RO)
1213 buf = buf + ZS_HANDLE_SIZE;
1214 size -= ZS_HANDLE_SIZE;
1215 off += ZS_HANDLE_SIZE;
1217 sizes[0] = PAGE_SIZE - off;
1218 sizes[1] = size - sizes[0];
1220 /* copy per-cpu buffer to object */
1221 addr = kmap_atomic(pages[0]);
1222 memcpy(addr + off, buf, sizes[0]);
1223 kunmap_atomic(addr);
1224 addr = kmap_atomic(pages[1]);
1225 memcpy(addr, buf + sizes[0], sizes[1]);
1226 kunmap_atomic(addr);
1229 /* enable page faults to match kunmap_atomic() return conditions */
1233 #endif /* CONFIG_PGTABLE_MAPPING */
1235 static int zs_cpu_prepare(unsigned int cpu)
1237 struct mapping_area *area;
1239 area = &per_cpu(zs_map_area, cpu);
1240 return __zs_cpu_up(area);
1243 static int zs_cpu_dead(unsigned int cpu)
1245 struct mapping_area *area;
1247 area = &per_cpu(zs_map_area, cpu);
1248 __zs_cpu_down(area);
1252 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1253 int objs_per_zspage)
1255 if (prev->pages_per_zspage == pages_per_zspage &&
1256 prev->objs_per_zspage == objs_per_zspage)
1262 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1264 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1267 unsigned long zs_get_total_pages(struct zs_pool *pool)
1269 return atomic_long_read(&pool->pages_allocated);
1271 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1274 * zs_map_object - get address of allocated object from handle.
1275 * @pool: pool from which the object was allocated
1276 * @handle: handle returned from zs_malloc
1277 * @mm: maping mode to use
1279 * Before using an object allocated from zs_malloc, it must be mapped using
1280 * this function. When done with the object, it must be unmapped using
1283 * Only one object can be mapped per cpu at a time. There is no protection
1284 * against nested mappings.
1286 * This function returns with preemption and page faults disabled.
1288 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1291 struct zspage *zspage;
1293 unsigned long obj, off;
1294 unsigned int obj_idx;
1296 unsigned int class_idx;
1297 enum fullness_group fg;
1298 struct size_class *class;
1299 struct mapping_area *area;
1300 struct page *pages[2];
1304 * Because we use per-cpu mapping areas shared among the
1305 * pools/users, we can't allow mapping in interrupt context
1306 * because it can corrupt another users mappings.
1308 BUG_ON(in_interrupt());
1310 /* From now on, migration cannot move the object */
1313 obj = handle_to_obj(handle);
1314 obj_to_location(obj, &page, &obj_idx);
1315 zspage = get_zspage(page);
1317 /* migration cannot move any subpage in this zspage */
1318 migrate_read_lock(zspage);
1320 get_zspage_mapping(zspage, &class_idx, &fg);
1321 class = pool->size_class[class_idx];
1322 off = (class->size * obj_idx) & ~PAGE_MASK;
1324 area = &get_cpu_var(zs_map_area);
1326 if (off + class->size <= PAGE_SIZE) {
1327 /* this object is contained entirely within a page */
1328 area->vm_addr = kmap_atomic(page);
1329 ret = area->vm_addr + off;
1333 /* this object spans two pages */
1335 pages[1] = get_next_page(page);
1338 ret = __zs_map_object(area, pages, off, class->size);
1340 if (likely(!PageHugeObject(page)))
1341 ret += ZS_HANDLE_SIZE;
1345 EXPORT_SYMBOL_GPL(zs_map_object);
1347 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1349 struct zspage *zspage;
1351 unsigned long obj, off;
1352 unsigned int obj_idx;
1354 unsigned int class_idx;
1355 enum fullness_group fg;
1356 struct size_class *class;
1357 struct mapping_area *area;
1359 obj = handle_to_obj(handle);
1360 obj_to_location(obj, &page, &obj_idx);
1361 zspage = get_zspage(page);
1362 get_zspage_mapping(zspage, &class_idx, &fg);
1363 class = pool->size_class[class_idx];
1364 off = (class->size * obj_idx) & ~PAGE_MASK;
1366 area = this_cpu_ptr(&zs_map_area);
1367 if (off + class->size <= PAGE_SIZE)
1368 kunmap_atomic(area->vm_addr);
1370 struct page *pages[2];
1373 pages[1] = get_next_page(page);
1376 __zs_unmap_object(area, pages, off, class->size);
1378 put_cpu_var(zs_map_area);
1380 migrate_read_unlock(zspage);
1383 EXPORT_SYMBOL_GPL(zs_unmap_object);
1386 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1387 * zsmalloc &size_class.
1388 * @pool: zsmalloc pool to use
1390 * The function returns the size of the first huge class - any object of equal
1391 * or bigger size will be stored in zspage consisting of a single physical
1394 * Context: Any context.
1396 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1398 size_t zs_huge_class_size(struct zs_pool *pool)
1400 return huge_class_size;
1402 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1404 static unsigned long obj_malloc(struct size_class *class,
1405 struct zspage *zspage, unsigned long handle)
1407 int i, nr_page, offset;
1409 struct link_free *link;
1411 struct page *m_page;
1412 unsigned long m_offset;
1415 handle |= OBJ_ALLOCATED_TAG;
1416 obj = get_freeobj(zspage);
1418 offset = obj * class->size;
1419 nr_page = offset >> PAGE_SHIFT;
1420 m_offset = offset & ~PAGE_MASK;
1421 m_page = get_first_page(zspage);
1423 for (i = 0; i < nr_page; i++)
1424 m_page = get_next_page(m_page);
1426 vaddr = kmap_atomic(m_page);
1427 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1428 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1429 if (likely(!PageHugeObject(m_page)))
1430 /* record handle in the header of allocated chunk */
1431 link->handle = handle;
1433 /* record handle to page->index */
1434 zspage->first_page->index = handle;
1436 kunmap_atomic(vaddr);
1437 mod_zspage_inuse(zspage, 1);
1438 zs_stat_inc(class, OBJ_USED, 1);
1440 obj = location_to_obj(m_page, obj);
1447 * zs_malloc - Allocate block of given size from pool.
1448 * @pool: pool to allocate from
1449 * @size: size of block to allocate
1450 * @gfp: gfp flags when allocating object
1452 * On success, handle to the allocated object is returned,
1454 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1456 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1458 unsigned long handle, obj;
1459 struct size_class *class;
1460 enum fullness_group newfg;
1461 struct zspage *zspage;
1463 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1466 handle = cache_alloc_handle(pool, gfp);
1470 /* extra space in chunk to keep the handle */
1471 size += ZS_HANDLE_SIZE;
1472 class = pool->size_class[get_size_class_index(size)];
1474 spin_lock(&class->lock);
1475 zspage = find_get_zspage(class);
1476 if (likely(zspage)) {
1477 obj = obj_malloc(class, zspage, handle);
1478 /* Now move the zspage to another fullness group, if required */
1479 fix_fullness_group(class, zspage);
1480 record_obj(handle, obj);
1481 spin_unlock(&class->lock);
1486 spin_unlock(&class->lock);
1488 zspage = alloc_zspage(pool, class, gfp);
1490 cache_free_handle(pool, handle);
1494 spin_lock(&class->lock);
1495 obj = obj_malloc(class, zspage, handle);
1496 newfg = get_fullness_group(class, zspage);
1497 insert_zspage(class, zspage, newfg);
1498 set_zspage_mapping(zspage, class->index, newfg);
1499 record_obj(handle, obj);
1500 atomic_long_add(class->pages_per_zspage,
1501 &pool->pages_allocated);
1502 zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1504 /* We completely set up zspage so mark them as movable */
1505 SetZsPageMovable(pool, zspage);
1506 spin_unlock(&class->lock);
1510 EXPORT_SYMBOL_GPL(zs_malloc);
1512 static void obj_free(struct size_class *class, unsigned long obj)
1514 struct link_free *link;
1515 struct zspage *zspage;
1516 struct page *f_page;
1517 unsigned long f_offset;
1518 unsigned int f_objidx;
1521 obj &= ~OBJ_ALLOCATED_TAG;
1522 obj_to_location(obj, &f_page, &f_objidx);
1523 f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1524 zspage = get_zspage(f_page);
1526 vaddr = kmap_atomic(f_page);
1528 /* Insert this object in containing zspage's freelist */
1529 link = (struct link_free *)(vaddr + f_offset);
1530 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1531 kunmap_atomic(vaddr);
1532 set_freeobj(zspage, f_objidx);
1533 mod_zspage_inuse(zspage, -1);
1534 zs_stat_dec(class, OBJ_USED, 1);
1537 void zs_free(struct zs_pool *pool, unsigned long handle)
1539 struct zspage *zspage;
1540 struct page *f_page;
1542 unsigned int f_objidx;
1544 struct size_class *class;
1545 enum fullness_group fullness;
1548 if (unlikely(!handle))
1552 obj = handle_to_obj(handle);
1553 obj_to_location(obj, &f_page, &f_objidx);
1554 zspage = get_zspage(f_page);
1556 migrate_read_lock(zspage);
1558 get_zspage_mapping(zspage, &class_idx, &fullness);
1559 class = pool->size_class[class_idx];
1561 spin_lock(&class->lock);
1562 obj_free(class, obj);
1563 fullness = fix_fullness_group(class, zspage);
1564 if (fullness != ZS_EMPTY) {
1565 migrate_read_unlock(zspage);
1569 isolated = is_zspage_isolated(zspage);
1570 migrate_read_unlock(zspage);
1571 /* If zspage is isolated, zs_page_putback will free the zspage */
1572 if (likely(!isolated))
1573 free_zspage(pool, class, zspage);
1576 spin_unlock(&class->lock);
1578 cache_free_handle(pool, handle);
1580 EXPORT_SYMBOL_GPL(zs_free);
1582 static void zs_object_copy(struct size_class *class, unsigned long dst,
1585 struct page *s_page, *d_page;
1586 unsigned int s_objidx, d_objidx;
1587 unsigned long s_off, d_off;
1588 void *s_addr, *d_addr;
1589 int s_size, d_size, size;
1592 s_size = d_size = class->size;
1594 obj_to_location(src, &s_page, &s_objidx);
1595 obj_to_location(dst, &d_page, &d_objidx);
1597 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1598 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1600 if (s_off + class->size > PAGE_SIZE)
1601 s_size = PAGE_SIZE - s_off;
1603 if (d_off + class->size > PAGE_SIZE)
1604 d_size = PAGE_SIZE - d_off;
1606 s_addr = kmap_atomic(s_page);
1607 d_addr = kmap_atomic(d_page);
1610 size = min(s_size, d_size);
1611 memcpy(d_addr + d_off, s_addr + s_off, size);
1614 if (written == class->size)
1622 if (s_off >= PAGE_SIZE) {
1623 kunmap_atomic(d_addr);
1624 kunmap_atomic(s_addr);
1625 s_page = get_next_page(s_page);
1626 s_addr = kmap_atomic(s_page);
1627 d_addr = kmap_atomic(d_page);
1628 s_size = class->size - written;
1632 if (d_off >= PAGE_SIZE) {
1633 kunmap_atomic(d_addr);
1634 d_page = get_next_page(d_page);
1635 d_addr = kmap_atomic(d_page);
1636 d_size = class->size - written;
1641 kunmap_atomic(d_addr);
1642 kunmap_atomic(s_addr);
1646 * Find alloced object in zspage from index object and
1649 static unsigned long find_alloced_obj(struct size_class *class,
1650 struct page *page, int *obj_idx)
1654 int index = *obj_idx;
1655 unsigned long handle = 0;
1656 void *addr = kmap_atomic(page);
1658 offset = get_first_obj_offset(page);
1659 offset += class->size * index;
1661 while (offset < PAGE_SIZE) {
1662 head = obj_to_head(page, addr + offset);
1663 if (head & OBJ_ALLOCATED_TAG) {
1664 handle = head & ~OBJ_ALLOCATED_TAG;
1665 if (trypin_tag(handle))
1670 offset += class->size;
1674 kunmap_atomic(addr);
1681 struct zs_compact_control {
1682 /* Source spage for migration which could be a subpage of zspage */
1683 struct page *s_page;
1684 /* Destination page for migration which should be a first page
1686 struct page *d_page;
1687 /* Starting object index within @s_page which used for live object
1688 * in the subpage. */
1692 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1693 struct zs_compact_control *cc)
1695 unsigned long used_obj, free_obj;
1696 unsigned long handle;
1697 struct page *s_page = cc->s_page;
1698 struct page *d_page = cc->d_page;
1699 int obj_idx = cc->obj_idx;
1703 handle = find_alloced_obj(class, s_page, &obj_idx);
1705 s_page = get_next_page(s_page);
1712 /* Stop if there is no more space */
1713 if (zspage_full(class, get_zspage(d_page))) {
1719 used_obj = handle_to_obj(handle);
1720 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1721 zs_object_copy(class, free_obj, used_obj);
1724 * record_obj updates handle's value to free_obj and it will
1725 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1726 * breaks synchronization using pin_tag(e,g, zs_free) so
1727 * let's keep the lock bit.
1729 free_obj |= BIT(HANDLE_PIN_BIT);
1730 record_obj(handle, free_obj);
1732 obj_free(class, used_obj);
1735 /* Remember last position in this iteration */
1736 cc->s_page = s_page;
1737 cc->obj_idx = obj_idx;
1742 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1745 struct zspage *zspage;
1746 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1749 fg[0] = ZS_ALMOST_FULL;
1750 fg[1] = ZS_ALMOST_EMPTY;
1753 for (i = 0; i < 2; i++) {
1754 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1755 struct zspage, list);
1757 VM_BUG_ON(is_zspage_isolated(zspage));
1758 remove_zspage(class, zspage, fg[i]);
1767 * putback_zspage - add @zspage into right class's fullness list
1768 * @class: destination class
1769 * @zspage: target page
1771 * Return @zspage's fullness_group
1773 static enum fullness_group putback_zspage(struct size_class *class,
1774 struct zspage *zspage)
1776 enum fullness_group fullness;
1778 VM_BUG_ON(is_zspage_isolated(zspage));
1780 fullness = get_fullness_group(class, zspage);
1781 insert_zspage(class, zspage, fullness);
1782 set_zspage_mapping(zspage, class->index, fullness);
1787 #ifdef CONFIG_COMPACTION
1789 * To prevent zspage destroy during migration, zspage freeing should
1790 * hold locks of all pages in the zspage.
1792 static void lock_zspage(struct zspage *zspage)
1794 struct page *page = get_first_page(zspage);
1798 } while ((page = get_next_page(page)) != NULL);
1801 static struct dentry *zs_mount(struct file_system_type *fs_type,
1802 int flags, const char *dev_name, void *data)
1804 static const struct dentry_operations ops = {
1805 .d_dname = simple_dname,
1808 return mount_pseudo(fs_type, "zsmalloc:", NULL, &ops, ZSMALLOC_MAGIC);
1811 static struct file_system_type zsmalloc_fs = {
1814 .kill_sb = kill_anon_super,
1817 static int zsmalloc_mount(void)
1821 zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1822 if (IS_ERR(zsmalloc_mnt))
1823 ret = PTR_ERR(zsmalloc_mnt);
1828 static void zsmalloc_unmount(void)
1830 kern_unmount(zsmalloc_mnt);
1833 static void migrate_lock_init(struct zspage *zspage)
1835 rwlock_init(&zspage->lock);
1838 static void migrate_read_lock(struct zspage *zspage)
1840 read_lock(&zspage->lock);
1843 static void migrate_read_unlock(struct zspage *zspage)
1845 read_unlock(&zspage->lock);
1848 static void migrate_write_lock(struct zspage *zspage)
1850 write_lock(&zspage->lock);
1853 static void migrate_write_unlock(struct zspage *zspage)
1855 write_unlock(&zspage->lock);
1858 /* Number of isolated subpage for *page migration* in this zspage */
1859 static void inc_zspage_isolation(struct zspage *zspage)
1864 static void dec_zspage_isolation(struct zspage *zspage)
1869 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1870 struct page *newpage, struct page *oldpage)
1873 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1876 page = get_first_page(zspage);
1878 if (page == oldpage)
1879 pages[idx] = newpage;
1883 } while ((page = get_next_page(page)) != NULL);
1885 create_page_chain(class, zspage, pages);
1886 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1887 if (unlikely(PageHugeObject(oldpage)))
1888 newpage->index = oldpage->index;
1889 __SetPageMovable(newpage, page_mapping(oldpage));
1892 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1894 struct zs_pool *pool;
1895 struct size_class *class;
1897 enum fullness_group fullness;
1898 struct zspage *zspage;
1899 struct address_space *mapping;
1902 * Page is locked so zspage couldn't be destroyed. For detail, look at
1903 * lock_zspage in free_zspage.
1905 VM_BUG_ON_PAGE(!PageMovable(page), page);
1906 VM_BUG_ON_PAGE(PageIsolated(page), page);
1908 zspage = get_zspage(page);
1911 * Without class lock, fullness could be stale while class_idx is okay
1912 * because class_idx is constant unless page is freed so we should get
1913 * fullness again under class lock.
1915 get_zspage_mapping(zspage, &class_idx, &fullness);
1916 mapping = page_mapping(page);
1917 pool = mapping->private_data;
1918 class = pool->size_class[class_idx];
1920 spin_lock(&class->lock);
1921 if (get_zspage_inuse(zspage) == 0) {
1922 spin_unlock(&class->lock);
1926 /* zspage is isolated for object migration */
1927 if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1928 spin_unlock(&class->lock);
1933 * If this is first time isolation for the zspage, isolate zspage from
1934 * size_class to prevent further object allocation from the zspage.
1936 if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1937 get_zspage_mapping(zspage, &class_idx, &fullness);
1938 remove_zspage(class, zspage, fullness);
1941 inc_zspage_isolation(zspage);
1942 spin_unlock(&class->lock);
1947 static int zs_page_migrate(struct address_space *mapping, struct page *newpage,
1948 struct page *page, enum migrate_mode mode)
1950 struct zs_pool *pool;
1951 struct size_class *class;
1953 enum fullness_group fullness;
1954 struct zspage *zspage;
1956 void *s_addr, *d_addr, *addr;
1958 unsigned long handle, head;
1959 unsigned long old_obj, new_obj;
1960 unsigned int obj_idx;
1964 * We cannot support the _NO_COPY case here, because copy needs to
1965 * happen under the zs lock, which does not work with
1966 * MIGRATE_SYNC_NO_COPY workflow.
1968 if (mode == MIGRATE_SYNC_NO_COPY)
1971 VM_BUG_ON_PAGE(!PageMovable(page), page);
1972 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1974 zspage = get_zspage(page);
1976 /* Concurrent compactor cannot migrate any subpage in zspage */
1977 migrate_write_lock(zspage);
1978 get_zspage_mapping(zspage, &class_idx, &fullness);
1979 pool = mapping->private_data;
1980 class = pool->size_class[class_idx];
1981 offset = get_first_obj_offset(page);
1983 spin_lock(&class->lock);
1984 if (!get_zspage_inuse(zspage)) {
1986 * Set "offset" to end of the page so that every loops
1987 * skips unnecessary object scanning.
1993 s_addr = kmap_atomic(page);
1994 while (pos < PAGE_SIZE) {
1995 head = obj_to_head(page, s_addr + pos);
1996 if (head & OBJ_ALLOCATED_TAG) {
1997 handle = head & ~OBJ_ALLOCATED_TAG;
1998 if (!trypin_tag(handle))
2005 * Here, any user cannot access all objects in the zspage so let's move.
2007 d_addr = kmap_atomic(newpage);
2008 memcpy(d_addr, s_addr, PAGE_SIZE);
2009 kunmap_atomic(d_addr);
2011 for (addr = s_addr + offset; addr < s_addr + pos;
2012 addr += class->size) {
2013 head = obj_to_head(page, addr);
2014 if (head & OBJ_ALLOCATED_TAG) {
2015 handle = head & ~OBJ_ALLOCATED_TAG;
2016 if (!testpin_tag(handle))
2019 old_obj = handle_to_obj(handle);
2020 obj_to_location(old_obj, &dummy, &obj_idx);
2021 new_obj = (unsigned long)location_to_obj(newpage,
2023 new_obj |= BIT(HANDLE_PIN_BIT);
2024 record_obj(handle, new_obj);
2028 replace_sub_page(class, zspage, newpage, page);
2031 dec_zspage_isolation(zspage);
2034 * Page migration is done so let's putback isolated zspage to
2035 * the list if @page is final isolated subpage in the zspage.
2037 if (!is_zspage_isolated(zspage))
2038 putback_zspage(class, zspage);
2044 ret = MIGRATEPAGE_SUCCESS;
2046 for (addr = s_addr + offset; addr < s_addr + pos;
2047 addr += class->size) {
2048 head = obj_to_head(page, addr);
2049 if (head & OBJ_ALLOCATED_TAG) {
2050 handle = head & ~OBJ_ALLOCATED_TAG;
2051 if (!testpin_tag(handle))
2056 kunmap_atomic(s_addr);
2057 spin_unlock(&class->lock);
2058 migrate_write_unlock(zspage);
2063 static void zs_page_putback(struct page *page)
2065 struct zs_pool *pool;
2066 struct size_class *class;
2068 enum fullness_group fg;
2069 struct address_space *mapping;
2070 struct zspage *zspage;
2072 VM_BUG_ON_PAGE(!PageMovable(page), page);
2073 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2075 zspage = get_zspage(page);
2076 get_zspage_mapping(zspage, &class_idx, &fg);
2077 mapping = page_mapping(page);
2078 pool = mapping->private_data;
2079 class = pool->size_class[class_idx];
2081 spin_lock(&class->lock);
2082 dec_zspage_isolation(zspage);
2083 if (!is_zspage_isolated(zspage)) {
2084 fg = putback_zspage(class, zspage);
2086 * Due to page_lock, we cannot free zspage immediately
2090 schedule_work(&pool->free_work);
2092 spin_unlock(&class->lock);
2095 static const struct address_space_operations zsmalloc_aops = {
2096 .isolate_page = zs_page_isolate,
2097 .migratepage = zs_page_migrate,
2098 .putback_page = zs_page_putback,
2101 static int zs_register_migration(struct zs_pool *pool)
2103 pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2104 if (IS_ERR(pool->inode)) {
2109 pool->inode->i_mapping->private_data = pool;
2110 pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2114 static void zs_unregister_migration(struct zs_pool *pool)
2116 flush_work(&pool->free_work);
2121 * Caller should hold page_lock of all pages in the zspage
2122 * In here, we cannot use zspage meta data.
2124 static void async_free_zspage(struct work_struct *work)
2127 struct size_class *class;
2128 unsigned int class_idx;
2129 enum fullness_group fullness;
2130 struct zspage *zspage, *tmp;
2131 LIST_HEAD(free_pages);
2132 struct zs_pool *pool = container_of(work, struct zs_pool,
2135 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2136 class = pool->size_class[i];
2137 if (class->index != i)
2140 spin_lock(&class->lock);
2141 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2142 spin_unlock(&class->lock);
2146 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2147 list_del(&zspage->list);
2148 lock_zspage(zspage);
2150 get_zspage_mapping(zspage, &class_idx, &fullness);
2151 VM_BUG_ON(fullness != ZS_EMPTY);
2152 class = pool->size_class[class_idx];
2153 spin_lock(&class->lock);
2154 __free_zspage(pool, pool->size_class[class_idx], zspage);
2155 spin_unlock(&class->lock);
2159 static void kick_deferred_free(struct zs_pool *pool)
2161 schedule_work(&pool->free_work);
2164 static void init_deferred_free(struct zs_pool *pool)
2166 INIT_WORK(&pool->free_work, async_free_zspage);
2169 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2171 struct page *page = get_first_page(zspage);
2174 WARN_ON(!trylock_page(page));
2175 __SetPageMovable(page, pool->inode->i_mapping);
2177 } while ((page = get_next_page(page)) != NULL);
2183 * Based on the number of unused allocated objects calculate
2184 * and return the number of pages that we can free.
2186 static unsigned long zs_can_compact(struct size_class *class)
2188 unsigned long obj_wasted;
2189 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2190 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2192 if (obj_allocated <= obj_used)
2195 obj_wasted = obj_allocated - obj_used;
2196 obj_wasted /= class->objs_per_zspage;
2198 return obj_wasted * class->pages_per_zspage;
2201 static void __zs_compact(struct zs_pool *pool, struct size_class *class)
2203 struct zs_compact_control cc;
2204 struct zspage *src_zspage;
2205 struct zspage *dst_zspage = NULL;
2207 spin_lock(&class->lock);
2208 while ((src_zspage = isolate_zspage(class, true))) {
2210 if (!zs_can_compact(class))
2214 cc.s_page = get_first_page(src_zspage);
2216 while ((dst_zspage = isolate_zspage(class, false))) {
2217 cc.d_page = get_first_page(dst_zspage);
2219 * If there is no more space in dst_page, resched
2220 * and see if anyone had allocated another zspage.
2222 if (!migrate_zspage(pool, class, &cc))
2225 putback_zspage(class, dst_zspage);
2228 /* Stop if we couldn't find slot */
2229 if (dst_zspage == NULL)
2232 putback_zspage(class, dst_zspage);
2233 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2234 free_zspage(pool, class, src_zspage);
2235 pool->stats.pages_compacted += class->pages_per_zspage;
2237 spin_unlock(&class->lock);
2239 spin_lock(&class->lock);
2243 putback_zspage(class, src_zspage);
2245 spin_unlock(&class->lock);
2248 unsigned long zs_compact(struct zs_pool *pool)
2251 struct size_class *class;
2253 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2254 class = pool->size_class[i];
2257 if (class->index != i)
2259 __zs_compact(pool, class);
2262 return pool->stats.pages_compacted;
2264 EXPORT_SYMBOL_GPL(zs_compact);
2266 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2268 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2270 EXPORT_SYMBOL_GPL(zs_pool_stats);
2272 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2273 struct shrink_control *sc)
2275 unsigned long pages_freed;
2276 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2279 pages_freed = pool->stats.pages_compacted;
2281 * Compact classes and calculate compaction delta.
2282 * Can run concurrently with a manually triggered
2283 * (by user) compaction.
2285 pages_freed = zs_compact(pool) - pages_freed;
2287 return pages_freed ? pages_freed : SHRINK_STOP;
2290 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2291 struct shrink_control *sc)
2294 struct size_class *class;
2295 unsigned long pages_to_free = 0;
2296 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2299 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2300 class = pool->size_class[i];
2303 if (class->index != i)
2306 pages_to_free += zs_can_compact(class);
2309 return pages_to_free;
2312 static void zs_unregister_shrinker(struct zs_pool *pool)
2314 unregister_shrinker(&pool->shrinker);
2317 static int zs_register_shrinker(struct zs_pool *pool)
2319 pool->shrinker.scan_objects = zs_shrinker_scan;
2320 pool->shrinker.count_objects = zs_shrinker_count;
2321 pool->shrinker.batch = 0;
2322 pool->shrinker.seeks = DEFAULT_SEEKS;
2324 return register_shrinker(&pool->shrinker);
2328 * zs_create_pool - Creates an allocation pool to work from.
2329 * @name: pool name to be created
2331 * This function must be called before anything when using
2332 * the zsmalloc allocator.
2334 * On success, a pointer to the newly created pool is returned,
2337 struct zs_pool *zs_create_pool(const char *name)
2340 struct zs_pool *pool;
2341 struct size_class *prev_class = NULL;
2343 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2347 init_deferred_free(pool);
2349 pool->name = kstrdup(name, GFP_KERNEL);
2353 if (create_cache(pool))
2357 * Iterate reversely, because, size of size_class that we want to use
2358 * for merging should be larger or equal to current size.
2360 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2362 int pages_per_zspage;
2363 int objs_per_zspage;
2364 struct size_class *class;
2367 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2368 if (size > ZS_MAX_ALLOC_SIZE)
2369 size = ZS_MAX_ALLOC_SIZE;
2370 pages_per_zspage = get_pages_per_zspage(size);
2371 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2374 * We iterate from biggest down to smallest classes,
2375 * so huge_class_size holds the size of the first huge
2376 * class. Any object bigger than or equal to that will
2377 * endup in the huge class.
2379 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2381 huge_class_size = size;
2383 * The object uses ZS_HANDLE_SIZE bytes to store the
2384 * handle. We need to subtract it, because zs_malloc()
2385 * unconditionally adds handle size before it performs
2386 * size class search - so object may be smaller than
2387 * huge class size, yet it still can end up in the huge
2388 * class because it grows by ZS_HANDLE_SIZE extra bytes
2389 * right before class lookup.
2391 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2395 * size_class is used for normal zsmalloc operation such
2396 * as alloc/free for that size. Although it is natural that we
2397 * have one size_class for each size, there is a chance that we
2398 * can get more memory utilization if we use one size_class for
2399 * many different sizes whose size_class have same
2400 * characteristics. So, we makes size_class point to
2401 * previous size_class if possible.
2404 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2405 pool->size_class[i] = prev_class;
2410 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2416 class->pages_per_zspage = pages_per_zspage;
2417 class->objs_per_zspage = objs_per_zspage;
2418 spin_lock_init(&class->lock);
2419 pool->size_class[i] = class;
2420 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2422 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2427 /* debug only, don't abort if it fails */
2428 zs_pool_stat_create(pool, name);
2430 if (zs_register_migration(pool))
2434 * Not critical since shrinker is only used to trigger internal
2435 * defragmentation of the pool which is pretty optional thing. If
2436 * registration fails we still can use the pool normally and user can
2437 * trigger compaction manually. Thus, ignore return code.
2439 zs_register_shrinker(pool);
2444 zs_destroy_pool(pool);
2447 EXPORT_SYMBOL_GPL(zs_create_pool);
2449 void zs_destroy_pool(struct zs_pool *pool)
2453 zs_unregister_shrinker(pool);
2454 zs_unregister_migration(pool);
2455 zs_pool_stat_destroy(pool);
2457 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2459 struct size_class *class = pool->size_class[i];
2464 if (class->index != i)
2467 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2468 if (!list_empty(&class->fullness_list[fg])) {
2469 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2476 destroy_cache(pool);
2480 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2482 static int __init zs_init(void)
2486 ret = zsmalloc_mount();
2490 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2491 zs_cpu_prepare, zs_cpu_dead);
2496 zpool_register_driver(&zs_zpool_driver);
2509 static void __exit zs_exit(void)
2512 zpool_unregister_driver(&zs_zpool_driver);
2515 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2520 module_init(zs_init);
2521 module_exit(zs_exit);
2523 MODULE_LICENSE("Dual BSD/GPL");
2524 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");