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/types.h>
50 #include <linux/debugfs.h>
51 #include <linux/zsmalloc.h>
52 #include <linux/zpool.h>
53 #include <linux/mount.h>
54 #include <linux/migrate.h>
55 #include <linux/wait.h>
56 #include <linux/pagemap.h>
58 #define ZSPAGE_MAGIC 0x58
61 * This must be power of 2 and greater than of equal to sizeof(link_free).
62 * These two conditions ensure that any 'struct link_free' itself doesn't
63 * span more than 1 page which avoids complex case of mapping 2 pages simply
64 * to restore link_free pointer values.
69 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
70 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
72 #define ZS_MAX_ZSPAGE_ORDER 2
73 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
75 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
78 * Object location (<PFN>, <obj_idx>) is encoded as
79 * as single (unsigned long) handle value.
81 * Note that object index <obj_idx> starts from 0.
83 * This is made more complicated by various memory models and PAE.
86 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
87 #ifdef MAX_PHYSMEM_BITS
88 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
91 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
94 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
98 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
101 * Memory for allocating for handle keeps object position by
102 * encoding <page, obj_idx> and the encoded value has a room
103 * in least bit(ie, look at obj_to_location).
104 * We use the bit to synchronize between object access by
105 * user and migration.
107 #define HANDLE_PIN_BIT 0
110 * Head in allocated object should have OBJ_ALLOCATED_TAG
111 * to identify the object was allocated or not.
112 * It's okay to add the status bit in the least bit because
113 * header keeps handle which is 4byte-aligned address so we
114 * have room for two bit at least.
116 #define OBJ_ALLOCATED_TAG 1
117 #define OBJ_TAG_BITS 1
118 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
119 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
121 #define FULLNESS_BITS 2
123 #define ISOLATED_BITS 3
124 #define MAGIC_VAL_BITS 8
126 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
127 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
128 #define ZS_MIN_ALLOC_SIZE \
129 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
130 /* each chunk includes extra space to keep handle */
131 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
134 * On systems with 4K page size, this gives 255 size classes! There is a
136 * - Large number of size classes is potentially wasteful as free page are
137 * spread across these classes
138 * - Small number of size classes causes large internal fragmentation
139 * - Probably its better to use specific size classes (empirically
140 * determined). NOTE: all those class sizes must be set as multiple of
141 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
143 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
146 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
147 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
148 ZS_SIZE_CLASS_DELTA) + 1)
150 enum fullness_group {
168 struct zs_size_stat {
169 unsigned long objs[NR_ZS_STAT_TYPE];
172 #ifdef CONFIG_ZSMALLOC_STAT
173 static struct dentry *zs_stat_root;
176 #ifdef CONFIG_COMPACTION
177 static struct vfsmount *zsmalloc_mnt;
181 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
183 * n = number of allocated objects
184 * N = total number of objects zspage can store
185 * f = fullness_threshold_frac
187 * Similarly, we assign zspage to:
188 * ZS_ALMOST_FULL when n > N / f
189 * ZS_EMPTY when n == 0
190 * ZS_FULL when n == N
192 * (see: fix_fullness_group())
194 static const int fullness_threshold_frac = 4;
198 struct list_head fullness_list[NR_ZS_FULLNESS];
200 * Size of objects stored in this class. Must be multiple
205 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
206 int pages_per_zspage;
209 struct zs_size_stat stats;
212 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
213 static void SetPageHugeObject(struct page *page)
215 SetPageOwnerPriv1(page);
218 static void ClearPageHugeObject(struct page *page)
220 ClearPageOwnerPriv1(page);
223 static int PageHugeObject(struct page *page)
225 return PageOwnerPriv1(page);
229 * Placed within free objects to form a singly linked list.
230 * For every zspage, zspage->freeobj gives head of this list.
232 * This must be power of 2 and less than or equal to ZS_ALIGN
238 * It's valid for non-allocated object
242 * Handle of allocated object.
244 unsigned long handle;
251 struct size_class *size_class[ZS_SIZE_CLASSES];
252 struct kmem_cache *handle_cachep;
253 struct kmem_cache *zspage_cachep;
255 atomic_long_t pages_allocated;
257 struct zs_pool_stats stats;
259 /* Compact classes */
260 struct shrinker shrinker;
262 * To signify that register_shrinker() was successful
263 * and unregister_shrinker() will not Oops.
265 bool shrinker_enabled;
266 #ifdef CONFIG_ZSMALLOC_STAT
267 struct dentry *stat_dentry;
269 #ifdef CONFIG_COMPACTION
271 struct work_struct free_work;
272 /* A wait queue for when migration races with async_free_zspage() */
273 struct wait_queue_head migration_wait;
274 atomic_long_t isolated_pages;
281 unsigned int fullness:FULLNESS_BITS;
282 unsigned int class:CLASS_BITS + 1;
283 unsigned int isolated:ISOLATED_BITS;
284 unsigned int magic:MAGIC_VAL_BITS;
287 unsigned int freeobj;
288 struct page *first_page;
289 struct list_head list; /* fullness list */
290 #ifdef CONFIG_COMPACTION
295 struct mapping_area {
296 #ifdef CONFIG_PGTABLE_MAPPING
297 struct vm_struct *vm; /* vm area for mapping object that span pages */
299 char *vm_buf; /* copy buffer for objects that span pages */
301 char *vm_addr; /* address of kmap_atomic()'ed pages */
302 enum zs_mapmode vm_mm; /* mapping mode */
305 #ifdef CONFIG_COMPACTION
306 static int zs_register_migration(struct zs_pool *pool);
307 static void zs_unregister_migration(struct zs_pool *pool);
308 static void migrate_lock_init(struct zspage *zspage);
309 static void migrate_read_lock(struct zspage *zspage);
310 static void migrate_read_unlock(struct zspage *zspage);
311 static void kick_deferred_free(struct zs_pool *pool);
312 static void init_deferred_free(struct zs_pool *pool);
313 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
315 static int zsmalloc_mount(void) { return 0; }
316 static void zsmalloc_unmount(void) {}
317 static int zs_register_migration(struct zs_pool *pool) { return 0; }
318 static void zs_unregister_migration(struct zs_pool *pool) {}
319 static void migrate_lock_init(struct zspage *zspage) {}
320 static void migrate_read_lock(struct zspage *zspage) {}
321 static void migrate_read_unlock(struct zspage *zspage) {}
322 static void kick_deferred_free(struct zs_pool *pool) {}
323 static void init_deferred_free(struct zs_pool *pool) {}
324 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
327 static int create_cache(struct zs_pool *pool)
329 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
331 if (!pool->handle_cachep)
334 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
336 if (!pool->zspage_cachep) {
337 kmem_cache_destroy(pool->handle_cachep);
338 pool->handle_cachep = NULL;
345 static void destroy_cache(struct zs_pool *pool)
347 kmem_cache_destroy(pool->handle_cachep);
348 kmem_cache_destroy(pool->zspage_cachep);
351 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
353 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
354 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
357 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
359 kmem_cache_free(pool->handle_cachep, (void *)handle);
362 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
364 return kmem_cache_alloc(pool->zspage_cachep,
365 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
368 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
370 kmem_cache_free(pool->zspage_cachep, zspage);
373 static void record_obj(unsigned long handle, unsigned long obj)
376 * lsb of @obj represents handle lock while other bits
377 * represent object value the handle is pointing so
378 * updating shouldn't do store tearing.
380 WRITE_ONCE(*(unsigned long *)handle, obj);
387 static void *zs_zpool_create(const char *name, gfp_t gfp,
388 const struct zpool_ops *zpool_ops,
392 * Ignore global gfp flags: zs_malloc() may be invoked from
393 * different contexts and its caller must provide a valid
396 return zs_create_pool(name);
399 static void zs_zpool_destroy(void *pool)
401 zs_destroy_pool(pool);
404 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
405 unsigned long *handle)
407 *handle = zs_malloc(pool, size, gfp);
408 return *handle ? 0 : -1;
410 static void zs_zpool_free(void *pool, unsigned long handle)
412 zs_free(pool, handle);
415 static int zs_zpool_shrink(void *pool, unsigned int pages,
416 unsigned int *reclaimed)
421 static void *zs_zpool_map(void *pool, unsigned long handle,
422 enum zpool_mapmode mm)
424 enum zs_mapmode zs_mm;
433 case ZPOOL_MM_RW: /* fallthru */
439 return zs_map_object(pool, handle, zs_mm);
441 static void zs_zpool_unmap(void *pool, unsigned long handle)
443 zs_unmap_object(pool, handle);
446 static u64 zs_zpool_total_size(void *pool)
448 return zs_get_total_pages(pool) << PAGE_SHIFT;
451 static struct zpool_driver zs_zpool_driver = {
453 .owner = THIS_MODULE,
454 .create = zs_zpool_create,
455 .destroy = zs_zpool_destroy,
456 .malloc = zs_zpool_malloc,
457 .free = zs_zpool_free,
458 .shrink = zs_zpool_shrink,
460 .unmap = zs_zpool_unmap,
461 .total_size = zs_zpool_total_size,
464 MODULE_ALIAS("zpool-zsmalloc");
465 #endif /* CONFIG_ZPOOL */
467 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
468 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
470 static bool is_zspage_isolated(struct zspage *zspage)
472 return zspage->isolated;
475 static __maybe_unused int is_first_page(struct page *page)
477 return PagePrivate(page);
480 /* Protected by class->lock */
481 static inline int get_zspage_inuse(struct zspage *zspage)
483 return zspage->inuse;
486 static inline void set_zspage_inuse(struct zspage *zspage, int val)
491 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
493 zspage->inuse += val;
496 static inline struct page *get_first_page(struct zspage *zspage)
498 struct page *first_page = zspage->first_page;
500 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
504 static inline int get_first_obj_offset(struct page *page)
509 static inline void set_first_obj_offset(struct page *page, int offset)
511 page->units = offset;
514 static inline unsigned int get_freeobj(struct zspage *zspage)
516 return zspage->freeobj;
519 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
521 zspage->freeobj = obj;
524 static void get_zspage_mapping(struct zspage *zspage,
525 unsigned int *class_idx,
526 enum fullness_group *fullness)
528 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
530 *fullness = zspage->fullness;
531 *class_idx = zspage->class;
534 static void set_zspage_mapping(struct zspage *zspage,
535 unsigned int class_idx,
536 enum fullness_group fullness)
538 zspage->class = class_idx;
539 zspage->fullness = fullness;
543 * zsmalloc divides the pool into various size classes where each
544 * class maintains a list of zspages where each zspage is divided
545 * into equal sized chunks. Each allocation falls into one of these
546 * classes depending on its size. This function returns index of the
547 * size class which has chunk size big enough to hold the give size.
549 static int get_size_class_index(int size)
553 if (likely(size > ZS_MIN_ALLOC_SIZE))
554 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
555 ZS_SIZE_CLASS_DELTA);
557 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
560 /* type can be of enum type zs_stat_type or fullness_group */
561 static inline void zs_stat_inc(struct size_class *class,
562 int type, unsigned long cnt)
564 class->stats.objs[type] += cnt;
567 /* type can be of enum type zs_stat_type or fullness_group */
568 static inline void zs_stat_dec(struct size_class *class,
569 int type, unsigned long cnt)
571 class->stats.objs[type] -= cnt;
574 /* type can be of enum type zs_stat_type or fullness_group */
575 static inline unsigned long zs_stat_get(struct size_class *class,
578 return class->stats.objs[type];
581 #ifdef CONFIG_ZSMALLOC_STAT
583 static void __init zs_stat_init(void)
585 if (!debugfs_initialized()) {
586 pr_warn("debugfs not available, stat dir not created\n");
590 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
592 pr_warn("debugfs 'zsmalloc' stat dir creation failed\n");
595 static void __exit zs_stat_exit(void)
597 debugfs_remove_recursive(zs_stat_root);
600 static unsigned long zs_can_compact(struct size_class *class);
602 static int zs_stats_size_show(struct seq_file *s, void *v)
605 struct zs_pool *pool = s->private;
606 struct size_class *class;
608 unsigned long class_almost_full, class_almost_empty;
609 unsigned long obj_allocated, obj_used, pages_used, freeable;
610 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
611 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
612 unsigned long total_freeable = 0;
614 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
615 "class", "size", "almost_full", "almost_empty",
616 "obj_allocated", "obj_used", "pages_used",
617 "pages_per_zspage", "freeable");
619 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
620 class = pool->size_class[i];
622 if (class->index != i)
625 spin_lock(&class->lock);
626 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
627 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
628 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
629 obj_used = zs_stat_get(class, OBJ_USED);
630 freeable = zs_can_compact(class);
631 spin_unlock(&class->lock);
633 objs_per_zspage = class->objs_per_zspage;
634 pages_used = obj_allocated / objs_per_zspage *
635 class->pages_per_zspage;
637 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
638 " %10lu %10lu %16d %8lu\n",
639 i, class->size, class_almost_full, class_almost_empty,
640 obj_allocated, obj_used, pages_used,
641 class->pages_per_zspage, freeable);
643 total_class_almost_full += class_almost_full;
644 total_class_almost_empty += class_almost_empty;
645 total_objs += obj_allocated;
646 total_used_objs += obj_used;
647 total_pages += pages_used;
648 total_freeable += freeable;
652 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
653 "Total", "", total_class_almost_full,
654 total_class_almost_empty, total_objs,
655 total_used_objs, total_pages, "", total_freeable);
660 static int zs_stats_size_open(struct inode *inode, struct file *file)
662 return single_open(file, zs_stats_size_show, inode->i_private);
665 static const struct file_operations zs_stat_size_ops = {
666 .open = zs_stats_size_open,
669 .release = single_release,
672 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
674 struct dentry *entry;
677 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
681 entry = debugfs_create_dir(name, zs_stat_root);
683 pr_warn("debugfs dir <%s> creation failed\n", name);
686 pool->stat_dentry = entry;
688 entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
689 pool->stat_dentry, pool, &zs_stat_size_ops);
691 pr_warn("%s: debugfs file entry <%s> creation failed\n",
693 debugfs_remove_recursive(pool->stat_dentry);
694 pool->stat_dentry = NULL;
698 static void zs_pool_stat_destroy(struct zs_pool *pool)
700 debugfs_remove_recursive(pool->stat_dentry);
703 #else /* CONFIG_ZSMALLOC_STAT */
704 static void __init zs_stat_init(void)
708 static void __exit zs_stat_exit(void)
712 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
716 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
723 * For each size class, zspages are divided into different groups
724 * depending on how "full" they are. This was done so that we could
725 * easily find empty or nearly empty zspages when we try to shrink
726 * the pool (not yet implemented). This function returns fullness
727 * status of the given page.
729 static enum fullness_group get_fullness_group(struct size_class *class,
730 struct zspage *zspage)
732 int inuse, objs_per_zspage;
733 enum fullness_group fg;
735 inuse = get_zspage_inuse(zspage);
736 objs_per_zspage = class->objs_per_zspage;
740 else if (inuse == objs_per_zspage)
742 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
743 fg = ZS_ALMOST_EMPTY;
751 * Each size class maintains various freelists and zspages are assigned
752 * to one of these freelists based on the number of live objects they
753 * have. This functions inserts the given zspage into the freelist
754 * identified by <class, fullness_group>.
756 static void insert_zspage(struct size_class *class,
757 struct zspage *zspage,
758 enum fullness_group fullness)
762 zs_stat_inc(class, fullness, 1);
763 head = list_first_entry_or_null(&class->fullness_list[fullness],
764 struct zspage, list);
766 * We want to see more ZS_FULL pages and less almost empty/full.
767 * Put pages with higher ->inuse first.
770 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
771 list_add(&zspage->list, &head->list);
775 list_add(&zspage->list, &class->fullness_list[fullness]);
779 * This function removes the given zspage from the freelist identified
780 * by <class, fullness_group>.
782 static void remove_zspage(struct size_class *class,
783 struct zspage *zspage,
784 enum fullness_group fullness)
786 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
787 VM_BUG_ON(is_zspage_isolated(zspage));
789 list_del_init(&zspage->list);
790 zs_stat_dec(class, fullness, 1);
794 * Each size class maintains zspages in different fullness groups depending
795 * on the number of live objects they contain. When allocating or freeing
796 * objects, the fullness status of the page can change, say, from ALMOST_FULL
797 * to ALMOST_EMPTY when freeing an object. This function checks if such
798 * a status change has occurred for the given page and accordingly moves the
799 * page from the freelist of the old fullness group to that of the new
802 static enum fullness_group fix_fullness_group(struct size_class *class,
803 struct zspage *zspage)
806 enum fullness_group currfg, newfg;
808 get_zspage_mapping(zspage, &class_idx, &currfg);
809 newfg = get_fullness_group(class, zspage);
813 if (!is_zspage_isolated(zspage)) {
814 remove_zspage(class, zspage, currfg);
815 insert_zspage(class, zspage, newfg);
818 set_zspage_mapping(zspage, class_idx, newfg);
825 * We have to decide on how many pages to link together
826 * to form a zspage for each size class. This is important
827 * to reduce wastage due to unusable space left at end of
828 * each zspage which is given as:
829 * wastage = Zp % class_size
830 * usage = Zp - wastage
831 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
833 * For example, for size class of 3/8 * PAGE_SIZE, we should
834 * link together 3 PAGE_SIZE sized pages to form a zspage
835 * since then we can perfectly fit in 8 such objects.
837 static int get_pages_per_zspage(int class_size)
839 int i, max_usedpc = 0;
840 /* zspage order which gives maximum used size per KB */
841 int max_usedpc_order = 1;
843 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
847 zspage_size = i * PAGE_SIZE;
848 waste = zspage_size % class_size;
849 usedpc = (zspage_size - waste) * 100 / zspage_size;
851 if (usedpc > max_usedpc) {
853 max_usedpc_order = i;
857 return max_usedpc_order;
860 static struct zspage *get_zspage(struct page *page)
862 struct zspage *zspage = (struct zspage *)page->private;
864 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
868 static struct page *get_next_page(struct page *page)
870 if (unlikely(PageHugeObject(page)))
873 return page->freelist;
877 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
878 * @page: page object resides in zspage
879 * @obj_idx: object index
881 static void obj_to_location(unsigned long obj, struct page **page,
882 unsigned int *obj_idx)
884 obj >>= OBJ_TAG_BITS;
885 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
886 *obj_idx = (obj & OBJ_INDEX_MASK);
890 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
891 * @page: page object resides in zspage
892 * @obj_idx: object index
894 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
898 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
899 obj |= obj_idx & OBJ_INDEX_MASK;
900 obj <<= OBJ_TAG_BITS;
905 static unsigned long handle_to_obj(unsigned long handle)
907 return *(unsigned long *)handle;
910 static unsigned long obj_to_head(struct page *page, void *obj)
912 if (unlikely(PageHugeObject(page))) {
913 VM_BUG_ON_PAGE(!is_first_page(page), page);
916 return *(unsigned long *)obj;
919 static inline int testpin_tag(unsigned long handle)
921 return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
924 static inline int trypin_tag(unsigned long handle)
926 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
929 static void pin_tag(unsigned long handle)
931 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
934 static void unpin_tag(unsigned long handle)
936 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
939 static void reset_page(struct page *page)
941 __ClearPageMovable(page);
942 ClearPagePrivate(page);
943 set_page_private(page, 0);
944 page_mapcount_reset(page);
945 ClearPageHugeObject(page);
946 page->freelist = NULL;
950 * To prevent zspage destroy during migration, zspage freeing should
951 * hold locks of all pages in the zspage.
953 void lock_zspage(struct zspage *zspage)
955 struct page *curr_page, *page;
958 * Pages we haven't locked yet can be migrated off the list while we're
959 * trying to lock them, so we need to be careful and only attempt to
960 * lock each page under migrate_read_lock(). Otherwise, the page we lock
961 * may no longer belong to the zspage. This means that we may wait for
962 * the wrong page to unlock, so we must take a reference to the page
963 * prior to waiting for it to unlock outside migrate_read_lock().
966 migrate_read_lock(zspage);
967 page = get_first_page(zspage);
968 if (trylock_page(page))
971 migrate_read_unlock(zspage);
972 wait_on_page_locked(page);
977 while ((page = get_next_page(curr_page))) {
978 if (trylock_page(page)) {
982 migrate_read_unlock(zspage);
983 wait_on_page_locked(page);
985 migrate_read_lock(zspage);
988 migrate_read_unlock(zspage);
991 int trylock_zspage(struct zspage *zspage)
993 struct page *cursor, *fail;
995 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
996 get_next_page(cursor)) {
997 if (!trylock_page(cursor)) {
1005 for (cursor = get_first_page(zspage); cursor != fail; cursor =
1006 get_next_page(cursor))
1007 unlock_page(cursor);
1012 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
1013 struct zspage *zspage)
1015 struct page *page, *next;
1016 enum fullness_group fg;
1017 unsigned int class_idx;
1019 get_zspage_mapping(zspage, &class_idx, &fg);
1021 assert_spin_locked(&class->lock);
1023 VM_BUG_ON(get_zspage_inuse(zspage));
1024 VM_BUG_ON(fg != ZS_EMPTY);
1026 next = page = get_first_page(zspage);
1028 VM_BUG_ON_PAGE(!PageLocked(page), page);
1029 next = get_next_page(page);
1032 dec_zone_page_state(page, NR_ZSPAGES);
1035 } while (page != NULL);
1037 cache_free_zspage(pool, zspage);
1039 zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
1040 atomic_long_sub(class->pages_per_zspage,
1041 &pool->pages_allocated);
1044 static void free_zspage(struct zs_pool *pool, struct size_class *class,
1045 struct zspage *zspage)
1047 VM_BUG_ON(get_zspage_inuse(zspage));
1048 VM_BUG_ON(list_empty(&zspage->list));
1050 if (!trylock_zspage(zspage)) {
1051 kick_deferred_free(pool);
1055 remove_zspage(class, zspage, ZS_EMPTY);
1056 __free_zspage(pool, class, zspage);
1059 /* Initialize a newly allocated zspage */
1060 static void init_zspage(struct size_class *class, struct zspage *zspage)
1062 unsigned int freeobj = 1;
1063 unsigned long off = 0;
1064 struct page *page = get_first_page(zspage);
1067 struct page *next_page;
1068 struct link_free *link;
1071 set_first_obj_offset(page, off);
1073 vaddr = kmap_atomic(page);
1074 link = (struct link_free *)vaddr + off / sizeof(*link);
1076 while ((off += class->size) < PAGE_SIZE) {
1077 link->next = freeobj++ << OBJ_TAG_BITS;
1078 link += class->size / sizeof(*link);
1082 * We now come to the last (full or partial) object on this
1083 * page, which must point to the first object on the next
1086 next_page = get_next_page(page);
1088 link->next = freeobj++ << OBJ_TAG_BITS;
1091 * Reset OBJ_TAG_BITS bit to last link to tell
1092 * whether it's allocated object or not.
1094 link->next = -1 << OBJ_TAG_BITS;
1096 kunmap_atomic(vaddr);
1101 set_freeobj(zspage, 0);
1104 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1105 struct page *pages[])
1109 struct page *prev_page = NULL;
1110 int nr_pages = class->pages_per_zspage;
1113 * Allocate individual pages and link them together as:
1114 * 1. all pages are linked together using page->freelist
1115 * 2. each sub-page point to zspage using page->private
1117 * we set PG_private to identify the first page (i.e. no other sub-page
1118 * has this flag set).
1120 for (i = 0; i < nr_pages; i++) {
1122 set_page_private(page, (unsigned long)zspage);
1123 page->freelist = NULL;
1125 zspage->first_page = page;
1126 SetPagePrivate(page);
1127 if (unlikely(class->objs_per_zspage == 1 &&
1128 class->pages_per_zspage == 1))
1129 SetPageHugeObject(page);
1131 prev_page->freelist = page;
1138 * Allocate a zspage for the given size class
1140 static struct zspage *alloc_zspage(struct zs_pool *pool,
1141 struct size_class *class,
1145 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1146 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1151 memset(zspage, 0, sizeof(struct zspage));
1152 zspage->magic = ZSPAGE_MAGIC;
1153 migrate_lock_init(zspage);
1155 for (i = 0; i < class->pages_per_zspage; i++) {
1158 page = alloc_page(gfp);
1161 dec_zone_page_state(pages[i], NR_ZSPAGES);
1162 __free_page(pages[i]);
1164 cache_free_zspage(pool, zspage);
1168 inc_zone_page_state(page, NR_ZSPAGES);
1172 create_page_chain(class, zspage, pages);
1173 init_zspage(class, zspage);
1178 static struct zspage *find_get_zspage(struct size_class *class)
1181 struct zspage *zspage;
1183 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1184 zspage = list_first_entry_or_null(&class->fullness_list[i],
1185 struct zspage, list);
1193 #ifdef CONFIG_PGTABLE_MAPPING
1194 static inline int __zs_cpu_up(struct mapping_area *area)
1197 * Make sure we don't leak memory if a cpu UP notification
1198 * and zs_init() race and both call zs_cpu_up() on the same cpu
1202 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1208 static inline void __zs_cpu_down(struct mapping_area *area)
1211 free_vm_area(area->vm);
1215 static inline void *__zs_map_object(struct mapping_area *area,
1216 struct page *pages[2], int off, int size)
1218 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1219 area->vm_addr = area->vm->addr;
1220 return area->vm_addr + off;
1223 static inline void __zs_unmap_object(struct mapping_area *area,
1224 struct page *pages[2], int off, int size)
1226 unsigned long addr = (unsigned long)area->vm_addr;
1228 unmap_kernel_range(addr, PAGE_SIZE * 2);
1231 #else /* CONFIG_PGTABLE_MAPPING */
1233 static inline int __zs_cpu_up(struct mapping_area *area)
1236 * Make sure we don't leak memory if a cpu UP notification
1237 * and zs_init() race and both call zs_cpu_up() on the same cpu
1241 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1247 static inline void __zs_cpu_down(struct mapping_area *area)
1249 kfree(area->vm_buf);
1250 area->vm_buf = NULL;
1253 static void *__zs_map_object(struct mapping_area *area,
1254 struct page *pages[2], int off, int size)
1258 char *buf = area->vm_buf;
1260 /* disable page faults to match kmap_atomic() return conditions */
1261 pagefault_disable();
1263 /* no read fastpath */
1264 if (area->vm_mm == ZS_MM_WO)
1267 sizes[0] = PAGE_SIZE - off;
1268 sizes[1] = size - sizes[0];
1270 /* copy object to per-cpu buffer */
1271 addr = kmap_atomic(pages[0]);
1272 memcpy(buf, addr + off, sizes[0]);
1273 kunmap_atomic(addr);
1274 addr = kmap_atomic(pages[1]);
1275 memcpy(buf + sizes[0], addr, sizes[1]);
1276 kunmap_atomic(addr);
1278 return area->vm_buf;
1281 static void __zs_unmap_object(struct mapping_area *area,
1282 struct page *pages[2], int off, int size)
1288 /* no write fastpath */
1289 if (area->vm_mm == ZS_MM_RO)
1293 buf = buf + ZS_HANDLE_SIZE;
1294 size -= ZS_HANDLE_SIZE;
1295 off += ZS_HANDLE_SIZE;
1297 sizes[0] = PAGE_SIZE - off;
1298 sizes[1] = size - sizes[0];
1300 /* copy per-cpu buffer to object */
1301 addr = kmap_atomic(pages[0]);
1302 memcpy(addr + off, buf, sizes[0]);
1303 kunmap_atomic(addr);
1304 addr = kmap_atomic(pages[1]);
1305 memcpy(addr, buf + sizes[0], sizes[1]);
1306 kunmap_atomic(addr);
1309 /* enable page faults to match kunmap_atomic() return conditions */
1313 #endif /* CONFIG_PGTABLE_MAPPING */
1315 static int zs_cpu_prepare(unsigned int cpu)
1317 struct mapping_area *area;
1319 area = &per_cpu(zs_map_area, cpu);
1320 return __zs_cpu_up(area);
1323 static int zs_cpu_dead(unsigned int cpu)
1325 struct mapping_area *area;
1327 area = &per_cpu(zs_map_area, cpu);
1328 __zs_cpu_down(area);
1332 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1333 int objs_per_zspage)
1335 if (prev->pages_per_zspage == pages_per_zspage &&
1336 prev->objs_per_zspage == objs_per_zspage)
1342 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1344 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1347 unsigned long zs_get_total_pages(struct zs_pool *pool)
1349 return atomic_long_read(&pool->pages_allocated);
1351 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1354 * zs_map_object - get address of allocated object from handle.
1355 * @pool: pool from which the object was allocated
1356 * @handle: handle returned from zs_malloc
1358 * Before using an object allocated from zs_malloc, it must be mapped using
1359 * this function. When done with the object, it must be unmapped using
1362 * Only one object can be mapped per cpu at a time. There is no protection
1363 * against nested mappings.
1365 * This function returns with preemption and page faults disabled.
1367 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1370 struct zspage *zspage;
1372 unsigned long obj, off;
1373 unsigned int obj_idx;
1375 unsigned int class_idx;
1376 enum fullness_group fg;
1377 struct size_class *class;
1378 struct mapping_area *area;
1379 struct page *pages[2];
1383 * Because we use per-cpu mapping areas shared among the
1384 * pools/users, we can't allow mapping in interrupt context
1385 * because it can corrupt another users mappings.
1387 BUG_ON(in_interrupt());
1389 /* From now on, migration cannot move the object */
1392 obj = handle_to_obj(handle);
1393 obj_to_location(obj, &page, &obj_idx);
1394 zspage = get_zspage(page);
1396 /* migration cannot move any subpage in this zspage */
1397 migrate_read_lock(zspage);
1399 get_zspage_mapping(zspage, &class_idx, &fg);
1400 class = pool->size_class[class_idx];
1401 off = (class->size * obj_idx) & ~PAGE_MASK;
1403 area = &get_cpu_var(zs_map_area);
1405 if (off + class->size <= PAGE_SIZE) {
1406 /* this object is contained entirely within a page */
1407 area->vm_addr = kmap_atomic(page);
1408 ret = area->vm_addr + off;
1412 /* this object spans two pages */
1414 pages[1] = get_next_page(page);
1417 ret = __zs_map_object(area, pages, off, class->size);
1419 if (likely(!PageHugeObject(page)))
1420 ret += ZS_HANDLE_SIZE;
1424 EXPORT_SYMBOL_GPL(zs_map_object);
1426 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1428 struct zspage *zspage;
1430 unsigned long obj, off;
1431 unsigned int obj_idx;
1433 unsigned int class_idx;
1434 enum fullness_group fg;
1435 struct size_class *class;
1436 struct mapping_area *area;
1438 obj = handle_to_obj(handle);
1439 obj_to_location(obj, &page, &obj_idx);
1440 zspage = get_zspage(page);
1441 get_zspage_mapping(zspage, &class_idx, &fg);
1442 class = pool->size_class[class_idx];
1443 off = (class->size * obj_idx) & ~PAGE_MASK;
1445 area = this_cpu_ptr(&zs_map_area);
1446 if (off + class->size <= PAGE_SIZE)
1447 kunmap_atomic(area->vm_addr);
1449 struct page *pages[2];
1452 pages[1] = get_next_page(page);
1455 __zs_unmap_object(area, pages, off, class->size);
1457 put_cpu_var(zs_map_area);
1459 migrate_read_unlock(zspage);
1462 EXPORT_SYMBOL_GPL(zs_unmap_object);
1464 static unsigned long obj_malloc(struct size_class *class,
1465 struct zspage *zspage, unsigned long handle)
1467 int i, nr_page, offset;
1469 struct link_free *link;
1471 struct page *m_page;
1472 unsigned long m_offset;
1475 handle |= OBJ_ALLOCATED_TAG;
1476 obj = get_freeobj(zspage);
1478 offset = obj * class->size;
1479 nr_page = offset >> PAGE_SHIFT;
1480 m_offset = offset & ~PAGE_MASK;
1481 m_page = get_first_page(zspage);
1483 for (i = 0; i < nr_page; i++)
1484 m_page = get_next_page(m_page);
1486 vaddr = kmap_atomic(m_page);
1487 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1488 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1489 if (likely(!PageHugeObject(m_page)))
1490 /* record handle in the header of allocated chunk */
1491 link->handle = handle;
1493 /* record handle to page->index */
1494 zspage->first_page->index = handle;
1496 kunmap_atomic(vaddr);
1497 mod_zspage_inuse(zspage, 1);
1498 zs_stat_inc(class, OBJ_USED, 1);
1500 obj = location_to_obj(m_page, obj);
1507 * zs_malloc - Allocate block of given size from pool.
1508 * @pool: pool to allocate from
1509 * @size: size of block to allocate
1510 * @gfp: gfp flags when allocating object
1512 * On success, handle to the allocated object is returned,
1514 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1516 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1518 unsigned long handle, obj;
1519 struct size_class *class;
1520 enum fullness_group newfg;
1521 struct zspage *zspage;
1523 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1526 handle = cache_alloc_handle(pool, gfp);
1530 /* extra space in chunk to keep the handle */
1531 size += ZS_HANDLE_SIZE;
1532 class = pool->size_class[get_size_class_index(size)];
1534 spin_lock(&class->lock);
1535 zspage = find_get_zspage(class);
1536 if (likely(zspage)) {
1537 obj = obj_malloc(class, zspage, handle);
1538 /* Now move the zspage to another fullness group, if required */
1539 fix_fullness_group(class, zspage);
1540 record_obj(handle, obj);
1541 spin_unlock(&class->lock);
1546 spin_unlock(&class->lock);
1548 zspage = alloc_zspage(pool, class, gfp);
1550 cache_free_handle(pool, handle);
1554 spin_lock(&class->lock);
1555 obj = obj_malloc(class, zspage, handle);
1556 newfg = get_fullness_group(class, zspage);
1557 insert_zspage(class, zspage, newfg);
1558 set_zspage_mapping(zspage, class->index, newfg);
1559 record_obj(handle, obj);
1560 atomic_long_add(class->pages_per_zspage,
1561 &pool->pages_allocated);
1562 zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1564 /* We completely set up zspage so mark them as movable */
1565 SetZsPageMovable(pool, zspage);
1566 spin_unlock(&class->lock);
1570 EXPORT_SYMBOL_GPL(zs_malloc);
1572 static void obj_free(struct size_class *class, unsigned long obj)
1574 struct link_free *link;
1575 struct zspage *zspage;
1576 struct page *f_page;
1577 unsigned long f_offset;
1578 unsigned int f_objidx;
1581 obj &= ~OBJ_ALLOCATED_TAG;
1582 obj_to_location(obj, &f_page, &f_objidx);
1583 f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1584 zspage = get_zspage(f_page);
1586 vaddr = kmap_atomic(f_page);
1588 /* Insert this object in containing zspage's freelist */
1589 link = (struct link_free *)(vaddr + f_offset);
1590 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1591 kunmap_atomic(vaddr);
1592 set_freeobj(zspage, f_objidx);
1593 mod_zspage_inuse(zspage, -1);
1594 zs_stat_dec(class, OBJ_USED, 1);
1597 void zs_free(struct zs_pool *pool, unsigned long handle)
1599 struct zspage *zspage;
1600 struct page *f_page;
1602 unsigned int f_objidx;
1604 struct size_class *class;
1605 enum fullness_group fullness;
1608 if (unlikely(!handle))
1612 obj = handle_to_obj(handle);
1613 obj_to_location(obj, &f_page, &f_objidx);
1614 zspage = get_zspage(f_page);
1616 migrate_read_lock(zspage);
1618 get_zspage_mapping(zspage, &class_idx, &fullness);
1619 class = pool->size_class[class_idx];
1621 spin_lock(&class->lock);
1622 obj_free(class, obj);
1623 fullness = fix_fullness_group(class, zspage);
1624 if (fullness != ZS_EMPTY) {
1625 migrate_read_unlock(zspage);
1629 isolated = is_zspage_isolated(zspage);
1630 migrate_read_unlock(zspage);
1631 /* If zspage is isolated, zs_page_putback will free the zspage */
1632 if (likely(!isolated))
1633 free_zspage(pool, class, zspage);
1636 spin_unlock(&class->lock);
1638 cache_free_handle(pool, handle);
1640 EXPORT_SYMBOL_GPL(zs_free);
1642 static void zs_object_copy(struct size_class *class, unsigned long dst,
1645 struct page *s_page, *d_page;
1646 unsigned int s_objidx, d_objidx;
1647 unsigned long s_off, d_off;
1648 void *s_addr, *d_addr;
1649 int s_size, d_size, size;
1652 s_size = d_size = class->size;
1654 obj_to_location(src, &s_page, &s_objidx);
1655 obj_to_location(dst, &d_page, &d_objidx);
1657 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1658 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1660 if (s_off + class->size > PAGE_SIZE)
1661 s_size = PAGE_SIZE - s_off;
1663 if (d_off + class->size > PAGE_SIZE)
1664 d_size = PAGE_SIZE - d_off;
1666 s_addr = kmap_atomic(s_page);
1667 d_addr = kmap_atomic(d_page);
1670 size = min(s_size, d_size);
1671 memcpy(d_addr + d_off, s_addr + s_off, size);
1674 if (written == class->size)
1682 if (s_off >= PAGE_SIZE) {
1683 kunmap_atomic(d_addr);
1684 kunmap_atomic(s_addr);
1685 s_page = get_next_page(s_page);
1686 s_addr = kmap_atomic(s_page);
1687 d_addr = kmap_atomic(d_page);
1688 s_size = class->size - written;
1692 if (d_off >= PAGE_SIZE) {
1693 kunmap_atomic(d_addr);
1694 d_page = get_next_page(d_page);
1695 d_addr = kmap_atomic(d_page);
1696 d_size = class->size - written;
1701 kunmap_atomic(d_addr);
1702 kunmap_atomic(s_addr);
1706 * Find alloced object in zspage from index object and
1709 static unsigned long find_alloced_obj(struct size_class *class,
1710 struct page *page, int *obj_idx)
1714 int index = *obj_idx;
1715 unsigned long handle = 0;
1716 void *addr = kmap_atomic(page);
1718 offset = get_first_obj_offset(page);
1719 offset += class->size * index;
1721 while (offset < PAGE_SIZE) {
1722 head = obj_to_head(page, addr + offset);
1723 if (head & OBJ_ALLOCATED_TAG) {
1724 handle = head & ~OBJ_ALLOCATED_TAG;
1725 if (trypin_tag(handle))
1730 offset += class->size;
1734 kunmap_atomic(addr);
1741 struct zs_compact_control {
1742 /* Source spage for migration which could be a subpage of zspage */
1743 struct page *s_page;
1744 /* Destination page for migration which should be a first page
1746 struct page *d_page;
1747 /* Starting object index within @s_page which used for live object
1748 * in the subpage. */
1752 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1753 struct zs_compact_control *cc)
1755 unsigned long used_obj, free_obj;
1756 unsigned long handle;
1757 struct page *s_page = cc->s_page;
1758 struct page *d_page = cc->d_page;
1759 int obj_idx = cc->obj_idx;
1763 handle = find_alloced_obj(class, s_page, &obj_idx);
1765 s_page = get_next_page(s_page);
1772 /* Stop if there is no more space */
1773 if (zspage_full(class, get_zspage(d_page))) {
1779 used_obj = handle_to_obj(handle);
1780 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1781 zs_object_copy(class, free_obj, used_obj);
1784 * record_obj updates handle's value to free_obj and it will
1785 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1786 * breaks synchronization using pin_tag(e,g, zs_free) so
1787 * let's keep the lock bit.
1789 free_obj |= BIT(HANDLE_PIN_BIT);
1790 record_obj(handle, free_obj);
1792 obj_free(class, used_obj);
1795 /* Remember last position in this iteration */
1796 cc->s_page = s_page;
1797 cc->obj_idx = obj_idx;
1802 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1805 struct zspage *zspage;
1806 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1809 fg[0] = ZS_ALMOST_FULL;
1810 fg[1] = ZS_ALMOST_EMPTY;
1813 for (i = 0; i < 2; i++) {
1814 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1815 struct zspage, list);
1817 VM_BUG_ON(is_zspage_isolated(zspage));
1818 remove_zspage(class, zspage, fg[i]);
1827 * putback_zspage - add @zspage into right class's fullness list
1828 * @class: destination class
1829 * @zspage: target page
1831 * Return @zspage's fullness_group
1833 static enum fullness_group putback_zspage(struct size_class *class,
1834 struct zspage *zspage)
1836 enum fullness_group fullness;
1838 VM_BUG_ON(is_zspage_isolated(zspage));
1840 fullness = get_fullness_group(class, zspage);
1841 insert_zspage(class, zspage, fullness);
1842 set_zspage_mapping(zspage, class->index, fullness);
1847 #ifdef CONFIG_COMPACTION
1848 static struct dentry *zs_mount(struct file_system_type *fs_type,
1849 int flags, const char *dev_name, void *data)
1851 static const struct dentry_operations ops = {
1852 .d_dname = simple_dname,
1855 return mount_pseudo(fs_type, "zsmalloc:", NULL, &ops, ZSMALLOC_MAGIC);
1858 static struct file_system_type zsmalloc_fs = {
1861 .kill_sb = kill_anon_super,
1864 static int zsmalloc_mount(void)
1868 zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1869 if (IS_ERR(zsmalloc_mnt))
1870 ret = PTR_ERR(zsmalloc_mnt);
1875 static void zsmalloc_unmount(void)
1877 kern_unmount(zsmalloc_mnt);
1880 static void migrate_lock_init(struct zspage *zspage)
1882 rwlock_init(&zspage->lock);
1885 static void migrate_read_lock(struct zspage *zspage)
1887 read_lock(&zspage->lock);
1890 static void migrate_read_unlock(struct zspage *zspage)
1892 read_unlock(&zspage->lock);
1895 static void migrate_write_lock(struct zspage *zspage)
1897 write_lock(&zspage->lock);
1900 static void migrate_write_unlock(struct zspage *zspage)
1902 write_unlock(&zspage->lock);
1905 /* Number of isolated subpage for *page migration* in this zspage */
1906 static void inc_zspage_isolation(struct zspage *zspage)
1911 static void dec_zspage_isolation(struct zspage *zspage)
1916 static void putback_zspage_deferred(struct zs_pool *pool,
1917 struct size_class *class,
1918 struct zspage *zspage)
1920 enum fullness_group fg;
1922 fg = putback_zspage(class, zspage);
1924 schedule_work(&pool->free_work);
1928 static inline void zs_pool_dec_isolated(struct zs_pool *pool)
1930 VM_BUG_ON(atomic_long_read(&pool->isolated_pages) <= 0);
1931 atomic_long_dec(&pool->isolated_pages);
1933 * Checking pool->destroying must happen after atomic_long_dec()
1934 * for pool->isolated_pages above. Paired with the smp_mb() in
1935 * zs_unregister_migration().
1937 smp_mb__after_atomic();
1938 if (atomic_long_read(&pool->isolated_pages) == 0 && pool->destroying)
1939 wake_up_all(&pool->migration_wait);
1942 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1943 struct page *newpage, struct page *oldpage)
1946 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1949 page = get_first_page(zspage);
1951 if (page == oldpage)
1952 pages[idx] = newpage;
1956 } while ((page = get_next_page(page)) != NULL);
1958 create_page_chain(class, zspage, pages);
1959 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1960 if (unlikely(PageHugeObject(oldpage)))
1961 newpage->index = oldpage->index;
1962 __SetPageMovable(newpage, page_mapping(oldpage));
1965 bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1967 struct zs_pool *pool;
1968 struct size_class *class;
1970 enum fullness_group fullness;
1971 struct zspage *zspage;
1972 struct address_space *mapping;
1975 * Page is locked so zspage couldn't be destroyed. For detail, look at
1976 * lock_zspage in free_zspage.
1978 VM_BUG_ON_PAGE(!PageMovable(page), page);
1979 VM_BUG_ON_PAGE(PageIsolated(page), page);
1981 zspage = get_zspage(page);
1984 * Without class lock, fullness could be stale while class_idx is okay
1985 * because class_idx is constant unless page is freed so we should get
1986 * fullness again under class lock.
1988 get_zspage_mapping(zspage, &class_idx, &fullness);
1989 mapping = page_mapping(page);
1990 pool = mapping->private_data;
1991 class = pool->size_class[class_idx];
1993 spin_lock(&class->lock);
1994 if (get_zspage_inuse(zspage) == 0) {
1995 spin_unlock(&class->lock);
1999 /* zspage is isolated for object migration */
2000 if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2001 spin_unlock(&class->lock);
2006 * If this is first time isolation for the zspage, isolate zspage from
2007 * size_class to prevent further object allocation from the zspage.
2009 if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2010 get_zspage_mapping(zspage, &class_idx, &fullness);
2011 atomic_long_inc(&pool->isolated_pages);
2012 remove_zspage(class, zspage, fullness);
2015 inc_zspage_isolation(zspage);
2016 spin_unlock(&class->lock);
2021 int zs_page_migrate(struct address_space *mapping, struct page *newpage,
2022 struct page *page, enum migrate_mode mode)
2024 struct zs_pool *pool;
2025 struct size_class *class;
2027 enum fullness_group fullness;
2028 struct zspage *zspage;
2030 void *s_addr, *d_addr, *addr;
2032 unsigned long handle, head;
2033 unsigned long old_obj, new_obj;
2034 unsigned int obj_idx;
2038 * We cannot support the _NO_COPY case here, because copy needs to
2039 * happen under the zs lock, which does not work with
2040 * MIGRATE_SYNC_NO_COPY workflow.
2042 if (mode == MIGRATE_SYNC_NO_COPY)
2045 VM_BUG_ON_PAGE(!PageMovable(page), page);
2046 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2048 zspage = get_zspage(page);
2050 /* Concurrent compactor cannot migrate any subpage in zspage */
2051 migrate_write_lock(zspage);
2052 get_zspage_mapping(zspage, &class_idx, &fullness);
2053 pool = mapping->private_data;
2054 class = pool->size_class[class_idx];
2055 offset = get_first_obj_offset(page);
2057 spin_lock(&class->lock);
2058 if (!get_zspage_inuse(zspage)) {
2060 * Set "offset" to end of the page so that every loops
2061 * skips unnecessary object scanning.
2067 s_addr = kmap_atomic(page);
2068 while (pos < PAGE_SIZE) {
2069 head = obj_to_head(page, s_addr + pos);
2070 if (head & OBJ_ALLOCATED_TAG) {
2071 handle = head & ~OBJ_ALLOCATED_TAG;
2072 if (!trypin_tag(handle))
2079 * Here, any user cannot access all objects in the zspage so let's move.
2081 d_addr = kmap_atomic(newpage);
2082 memcpy(d_addr, s_addr, PAGE_SIZE);
2083 kunmap_atomic(d_addr);
2085 for (addr = s_addr + offset; addr < s_addr + pos;
2086 addr += class->size) {
2087 head = obj_to_head(page, addr);
2088 if (head & OBJ_ALLOCATED_TAG) {
2089 handle = head & ~OBJ_ALLOCATED_TAG;
2090 if (!testpin_tag(handle))
2093 old_obj = handle_to_obj(handle);
2094 obj_to_location(old_obj, &dummy, &obj_idx);
2095 new_obj = (unsigned long)location_to_obj(newpage,
2097 new_obj |= BIT(HANDLE_PIN_BIT);
2098 record_obj(handle, new_obj);
2102 replace_sub_page(class, zspage, newpage, page);
2105 dec_zspage_isolation(zspage);
2108 * Page migration is done so let's putback isolated zspage to
2109 * the list if @page is final isolated subpage in the zspage.
2111 if (!is_zspage_isolated(zspage)) {
2113 * We cannot race with zs_destroy_pool() here because we wait
2114 * for isolation to hit zero before we start destroying.
2115 * Also, we ensure that everyone can see pool->destroying before
2118 putback_zspage_deferred(pool, class, zspage);
2119 zs_pool_dec_isolated(pool);
2122 if (page_zone(newpage) != page_zone(page)) {
2123 dec_zone_page_state(page, NR_ZSPAGES);
2124 inc_zone_page_state(newpage, NR_ZSPAGES);
2131 ret = MIGRATEPAGE_SUCCESS;
2133 for (addr = s_addr + offset; addr < s_addr + pos;
2134 addr += class->size) {
2135 head = obj_to_head(page, addr);
2136 if (head & OBJ_ALLOCATED_TAG) {
2137 handle = head & ~OBJ_ALLOCATED_TAG;
2138 if (!testpin_tag(handle))
2143 kunmap_atomic(s_addr);
2144 spin_unlock(&class->lock);
2145 migrate_write_unlock(zspage);
2150 void zs_page_putback(struct page *page)
2152 struct zs_pool *pool;
2153 struct size_class *class;
2155 enum fullness_group fg;
2156 struct address_space *mapping;
2157 struct zspage *zspage;
2159 VM_BUG_ON_PAGE(!PageMovable(page), page);
2160 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2162 zspage = get_zspage(page);
2163 get_zspage_mapping(zspage, &class_idx, &fg);
2164 mapping = page_mapping(page);
2165 pool = mapping->private_data;
2166 class = pool->size_class[class_idx];
2168 spin_lock(&class->lock);
2169 dec_zspage_isolation(zspage);
2170 if (!is_zspage_isolated(zspage)) {
2172 * Due to page_lock, we cannot free zspage immediately
2175 putback_zspage_deferred(pool, class, zspage);
2176 zs_pool_dec_isolated(pool);
2178 spin_unlock(&class->lock);
2181 const struct address_space_operations zsmalloc_aops = {
2182 .isolate_page = zs_page_isolate,
2183 .migratepage = zs_page_migrate,
2184 .putback_page = zs_page_putback,
2187 static int zs_register_migration(struct zs_pool *pool)
2189 pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2190 if (IS_ERR(pool->inode)) {
2195 pool->inode->i_mapping->private_data = pool;
2196 pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2200 static bool pool_isolated_are_drained(struct zs_pool *pool)
2202 return atomic_long_read(&pool->isolated_pages) == 0;
2205 /* Function for resolving migration */
2206 static void wait_for_isolated_drain(struct zs_pool *pool)
2210 * We're in the process of destroying the pool, so there are no
2211 * active allocations. zs_page_isolate() fails for completely free
2212 * zspages, so we need only wait for the zs_pool's isolated
2213 * count to hit zero.
2215 wait_event(pool->migration_wait,
2216 pool_isolated_are_drained(pool));
2219 static void zs_unregister_migration(struct zs_pool *pool)
2221 pool->destroying = true;
2223 * We need a memory barrier here to ensure global visibility of
2224 * pool->destroying. Thus pool->isolated pages will either be 0 in which
2225 * case we don't care, or it will be > 0 and pool->destroying will
2226 * ensure that we wake up once isolation hits 0.
2229 wait_for_isolated_drain(pool); /* This can block */
2230 flush_work(&pool->free_work);
2235 * Caller should hold page_lock of all pages in the zspage
2236 * In here, we cannot use zspage meta data.
2238 static void async_free_zspage(struct work_struct *work)
2241 struct size_class *class;
2242 unsigned int class_idx;
2243 enum fullness_group fullness;
2244 struct zspage *zspage, *tmp;
2245 LIST_HEAD(free_pages);
2246 struct zs_pool *pool = container_of(work, struct zs_pool,
2249 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2250 class = pool->size_class[i];
2251 if (class->index != i)
2254 spin_lock(&class->lock);
2255 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2256 spin_unlock(&class->lock);
2260 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2261 list_del(&zspage->list);
2262 lock_zspage(zspage);
2264 get_zspage_mapping(zspage, &class_idx, &fullness);
2265 VM_BUG_ON(fullness != ZS_EMPTY);
2266 class = pool->size_class[class_idx];
2267 spin_lock(&class->lock);
2268 __free_zspage(pool, pool->size_class[class_idx], zspage);
2269 spin_unlock(&class->lock);
2273 static void kick_deferred_free(struct zs_pool *pool)
2275 schedule_work(&pool->free_work);
2278 static void init_deferred_free(struct zs_pool *pool)
2280 INIT_WORK(&pool->free_work, async_free_zspage);
2283 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2285 struct page *page = get_first_page(zspage);
2288 WARN_ON(!trylock_page(page));
2289 __SetPageMovable(page, pool->inode->i_mapping);
2291 } while ((page = get_next_page(page)) != NULL);
2297 * Based on the number of unused allocated objects calculate
2298 * and return the number of pages that we can free.
2300 static unsigned long zs_can_compact(struct size_class *class)
2302 unsigned long obj_wasted;
2303 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2304 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2306 if (obj_allocated <= obj_used)
2309 obj_wasted = obj_allocated - obj_used;
2310 obj_wasted /= class->objs_per_zspage;
2312 return obj_wasted * class->pages_per_zspage;
2315 static unsigned long __zs_compact(struct zs_pool *pool,
2316 struct size_class *class)
2318 struct zs_compact_control cc;
2319 struct zspage *src_zspage;
2320 struct zspage *dst_zspage = NULL;
2321 unsigned long pages_freed = 0;
2323 spin_lock(&class->lock);
2324 while ((src_zspage = isolate_zspage(class, true))) {
2326 if (!zs_can_compact(class))
2330 cc.s_page = get_first_page(src_zspage);
2332 while ((dst_zspage = isolate_zspage(class, false))) {
2333 cc.d_page = get_first_page(dst_zspage);
2335 * If there is no more space in dst_page, resched
2336 * and see if anyone had allocated another zspage.
2338 if (!migrate_zspage(pool, class, &cc))
2341 putback_zspage(class, dst_zspage);
2344 /* Stop if we couldn't find slot */
2345 if (dst_zspage == NULL)
2348 putback_zspage(class, dst_zspage);
2349 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2350 free_zspage(pool, class, src_zspage);
2351 pages_freed += class->pages_per_zspage;
2353 spin_unlock(&class->lock);
2355 spin_lock(&class->lock);
2359 putback_zspage(class, src_zspage);
2361 spin_unlock(&class->lock);
2366 unsigned long zs_compact(struct zs_pool *pool)
2369 struct size_class *class;
2370 unsigned long pages_freed = 0;
2372 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2373 class = pool->size_class[i];
2376 if (class->index != i)
2378 pages_freed += __zs_compact(pool, class);
2380 atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2384 EXPORT_SYMBOL_GPL(zs_compact);
2386 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2388 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2390 EXPORT_SYMBOL_GPL(zs_pool_stats);
2392 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2393 struct shrink_control *sc)
2395 unsigned long pages_freed;
2396 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2400 * Compact classes and calculate compaction delta.
2401 * Can run concurrently with a manually triggered
2402 * (by user) compaction.
2404 pages_freed = zs_compact(pool);
2406 return pages_freed ? pages_freed : SHRINK_STOP;
2409 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2410 struct shrink_control *sc)
2413 struct size_class *class;
2414 unsigned long pages_to_free = 0;
2415 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2418 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2419 class = pool->size_class[i];
2422 if (class->index != i)
2425 pages_to_free += zs_can_compact(class);
2428 return pages_to_free;
2431 static void zs_unregister_shrinker(struct zs_pool *pool)
2433 if (pool->shrinker_enabled) {
2434 unregister_shrinker(&pool->shrinker);
2435 pool->shrinker_enabled = false;
2439 static int zs_register_shrinker(struct zs_pool *pool)
2441 pool->shrinker.scan_objects = zs_shrinker_scan;
2442 pool->shrinker.count_objects = zs_shrinker_count;
2443 pool->shrinker.batch = 0;
2444 pool->shrinker.seeks = DEFAULT_SEEKS;
2446 return register_shrinker(&pool->shrinker);
2450 * zs_create_pool - Creates an allocation pool to work from.
2451 * @name: pool name to be created
2453 * This function must be called before anything when using
2454 * the zsmalloc allocator.
2456 * On success, a pointer to the newly created pool is returned,
2459 struct zs_pool *zs_create_pool(const char *name)
2462 struct zs_pool *pool;
2463 struct size_class *prev_class = NULL;
2465 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2469 init_deferred_free(pool);
2471 pool->name = kstrdup(name, GFP_KERNEL);
2475 #ifdef CONFIG_COMPACTION
2476 init_waitqueue_head(&pool->migration_wait);
2479 if (create_cache(pool))
2483 * Iterate reversely, because, size of size_class that we want to use
2484 * for merging should be larger or equal to current size.
2486 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2488 int pages_per_zspage;
2489 int objs_per_zspage;
2490 struct size_class *class;
2493 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2494 if (size > ZS_MAX_ALLOC_SIZE)
2495 size = ZS_MAX_ALLOC_SIZE;
2496 pages_per_zspage = get_pages_per_zspage(size);
2497 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2500 * size_class is used for normal zsmalloc operation such
2501 * as alloc/free for that size. Although it is natural that we
2502 * have one size_class for each size, there is a chance that we
2503 * can get more memory utilization if we use one size_class for
2504 * many different sizes whose size_class have same
2505 * characteristics. So, we makes size_class point to
2506 * previous size_class if possible.
2509 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2510 pool->size_class[i] = prev_class;
2515 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2521 class->pages_per_zspage = pages_per_zspage;
2522 class->objs_per_zspage = objs_per_zspage;
2523 spin_lock_init(&class->lock);
2524 pool->size_class[i] = class;
2525 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2527 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2532 /* debug only, don't abort if it fails */
2533 zs_pool_stat_create(pool, name);
2535 if (zs_register_migration(pool))
2539 * Not critical, we still can use the pool
2540 * and user can trigger compaction manually.
2542 if (zs_register_shrinker(pool) == 0)
2543 pool->shrinker_enabled = true;
2547 zs_destroy_pool(pool);
2550 EXPORT_SYMBOL_GPL(zs_create_pool);
2552 void zs_destroy_pool(struct zs_pool *pool)
2556 zs_unregister_shrinker(pool);
2557 zs_unregister_migration(pool);
2558 zs_pool_stat_destroy(pool);
2560 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2562 struct size_class *class = pool->size_class[i];
2567 if (class->index != i)
2570 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2571 if (!list_empty(&class->fullness_list[fg])) {
2572 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2579 destroy_cache(pool);
2583 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2585 static int __init zs_init(void)
2589 ret = zsmalloc_mount();
2593 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2594 zs_cpu_prepare, zs_cpu_dead);
2599 zpool_register_driver(&zs_zpool_driver);
2612 static void __exit zs_exit(void)
2615 zpool_unregister_driver(&zs_zpool_driver);
2618 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2623 module_init(zs_init);
2624 module_exit(zs_exit);
2626 MODULE_LICENSE("Dual BSD/GPL");
2627 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");