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 <linux/pgtable.h>
43 #include <asm/tlbflush.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/pseudo_fs.h>
56 #include <linux/migrate.h>
57 #include <linux/wait.h>
58 #include <linux/pagemap.h>
60 #include <linux/local_lock.h>
62 #define ZSPAGE_MAGIC 0x58
65 * This must be power of 2 and greater than or equal to sizeof(link_free).
66 * These two conditions ensure that any 'struct link_free' itself doesn't
67 * span more than 1 page which avoids complex case of mapping 2 pages simply
68 * to restore link_free pointer values.
73 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
74 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
76 #define ZS_MAX_ZSPAGE_ORDER 2
77 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
79 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
81 #ifdef CONFIG_PREEMPT_RT
83 struct zsmalloc_handle {
88 #define ZS_HANDLE_ALLOC_SIZE (sizeof(struct zsmalloc_handle))
92 #define ZS_HANDLE_ALLOC_SIZE (sizeof(unsigned long))
96 * Object location (<PFN>, <obj_idx>) is encoded as
97 * a single (unsigned long) handle value.
99 * Note that object index <obj_idx> starts from 0.
101 * This is made more complicated by various memory models and PAE.
104 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
105 #ifdef MAX_PHYSMEM_BITS
106 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
109 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
112 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
116 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
119 * Memory for allocating for handle keeps object position by
120 * encoding <page, obj_idx> and the encoded value has a room
121 * in least bit(ie, look at obj_to_location).
122 * We use the bit to synchronize between object access by
123 * user and migration.
125 #define HANDLE_PIN_BIT 0
128 * Head in allocated object should have OBJ_ALLOCATED_TAG
129 * to identify the object was allocated or not.
130 * It's okay to add the status bit in the least bit because
131 * header keeps handle which is 4byte-aligned address so we
132 * have room for two bit at least.
134 #define OBJ_ALLOCATED_TAG 1
135 #define OBJ_TAG_BITS 1
136 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
137 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
139 #define FULLNESS_BITS 2
141 #define ISOLATED_BITS 3
142 #define MAGIC_VAL_BITS 8
144 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
145 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
146 #define ZS_MIN_ALLOC_SIZE \
147 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
148 /* each chunk includes extra space to keep handle */
149 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
152 * On systems with 4K page size, this gives 255 size classes! There is a
154 * - Large number of size classes is potentially wasteful as free page are
155 * spread across these classes
156 * - Small number of size classes causes large internal fragmentation
157 * - Probably its better to use specific size classes (empirically
158 * determined). NOTE: all those class sizes must be set as multiple of
159 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
161 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
164 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
165 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
166 ZS_SIZE_CLASS_DELTA) + 1)
168 enum fullness_group {
186 struct zs_size_stat {
187 unsigned long objs[NR_ZS_STAT_TYPE];
190 #ifdef CONFIG_ZSMALLOC_STAT
191 static struct dentry *zs_stat_root;
194 #ifdef CONFIG_COMPACTION
195 static struct vfsmount *zsmalloc_mnt;
199 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
201 * n = number of allocated objects
202 * N = total number of objects zspage can store
203 * f = fullness_threshold_frac
205 * Similarly, we assign zspage to:
206 * ZS_ALMOST_FULL when n > N / f
207 * ZS_EMPTY when n == 0
208 * ZS_FULL when n == N
210 * (see: fix_fullness_group())
212 static const int fullness_threshold_frac = 4;
213 static size_t huge_class_size;
217 struct list_head fullness_list[NR_ZS_FULLNESS];
219 * Size of objects stored in this class. Must be multiple
224 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
225 int pages_per_zspage;
228 struct zs_size_stat stats;
231 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
232 static void SetPageHugeObject(struct page *page)
234 SetPageOwnerPriv1(page);
237 static void ClearPageHugeObject(struct page *page)
239 ClearPageOwnerPriv1(page);
242 static int PageHugeObject(struct page *page)
244 return PageOwnerPriv1(page);
248 * Placed within free objects to form a singly linked list.
249 * For every zspage, zspage->freeobj gives head of this list.
251 * This must be power of 2 and less than or equal to ZS_ALIGN
257 * It's valid for non-allocated object
261 * Handle of allocated object.
263 unsigned long handle;
270 struct size_class *size_class[ZS_SIZE_CLASSES];
271 struct kmem_cache *handle_cachep;
272 struct kmem_cache *zspage_cachep;
274 atomic_long_t pages_allocated;
276 struct zs_pool_stats stats;
278 /* Compact classes */
279 struct shrinker shrinker;
281 #ifdef CONFIG_ZSMALLOC_STAT
282 struct dentry *stat_dentry;
284 #ifdef CONFIG_COMPACTION
286 struct work_struct free_work;
287 /* A wait queue for when migration races with async_free_zspage() */
288 struct wait_queue_head migration_wait;
289 atomic_long_t isolated_pages;
296 unsigned int fullness:FULLNESS_BITS;
297 unsigned int class:CLASS_BITS + 1;
298 unsigned int isolated:ISOLATED_BITS;
299 unsigned int magic:MAGIC_VAL_BITS;
302 unsigned int freeobj;
303 struct page *first_page;
304 struct list_head list; /* fullness list */
305 #ifdef CONFIG_COMPACTION
310 struct mapping_area {
312 char *vm_buf; /* copy buffer for objects that span pages */
313 char *vm_addr; /* address of kmap_atomic()'ed pages */
314 enum zs_mapmode vm_mm; /* mapping mode */
317 #ifdef CONFIG_COMPACTION
318 static int zs_register_migration(struct zs_pool *pool);
319 static void zs_unregister_migration(struct zs_pool *pool);
320 static void migrate_lock_init(struct zspage *zspage);
321 static void migrate_read_lock(struct zspage *zspage);
322 static void migrate_read_unlock(struct zspage *zspage);
323 static void kick_deferred_free(struct zs_pool *pool);
324 static void init_deferred_free(struct zs_pool *pool);
325 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
327 static int zsmalloc_mount(void) { return 0; }
328 static void zsmalloc_unmount(void) {}
329 static int zs_register_migration(struct zs_pool *pool) { return 0; }
330 static void zs_unregister_migration(struct zs_pool *pool) {}
331 static void migrate_lock_init(struct zspage *zspage) {}
332 static void migrate_read_lock(struct zspage *zspage) {}
333 static void migrate_read_unlock(struct zspage *zspage) {}
334 static void kick_deferred_free(struct zs_pool *pool) {}
335 static void init_deferred_free(struct zs_pool *pool) {}
336 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
339 static int create_cache(struct zs_pool *pool)
341 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_ALLOC_SIZE,
343 if (!pool->handle_cachep)
346 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
348 if (!pool->zspage_cachep) {
349 kmem_cache_destroy(pool->handle_cachep);
350 pool->handle_cachep = NULL;
357 static void destroy_cache(struct zs_pool *pool)
359 kmem_cache_destroy(pool->handle_cachep);
360 kmem_cache_destroy(pool->zspage_cachep);
363 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
367 p = kmem_cache_alloc(pool->handle_cachep,
368 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
369 #ifdef CONFIG_PREEMPT_RT
371 struct zsmalloc_handle *zh = p;
373 spin_lock_init(&zh->lock);
376 return (unsigned long)p;
379 #ifdef CONFIG_PREEMPT_RT
380 static struct zsmalloc_handle *zs_get_pure_handle(unsigned long handle)
382 return (void *)(handle & ~((1 << OBJ_TAG_BITS) - 1));
386 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
388 kmem_cache_free(pool->handle_cachep, (void *)handle);
391 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
393 return kmem_cache_zalloc(pool->zspage_cachep,
394 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
397 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
399 kmem_cache_free(pool->zspage_cachep, zspage);
402 static void record_obj(unsigned long handle, unsigned long obj)
404 #ifdef CONFIG_PREEMPT_RT
405 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
407 WRITE_ONCE(zh->addr, obj);
410 * lsb of @obj represents handle lock while other bits
411 * represent object value the handle is pointing so
412 * updating shouldn't do store tearing.
414 WRITE_ONCE(*(unsigned long *)handle, obj);
422 static void *zs_zpool_create(const char *name, gfp_t gfp,
423 const struct zpool_ops *zpool_ops,
427 * Ignore global gfp flags: zs_malloc() may be invoked from
428 * different contexts and its caller must provide a valid
431 return zs_create_pool(name);
434 static void zs_zpool_destroy(void *pool)
436 zs_destroy_pool(pool);
439 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
440 unsigned long *handle)
442 *handle = zs_malloc(pool, size, gfp);
443 return *handle ? 0 : -1;
445 static void zs_zpool_free(void *pool, unsigned long handle)
447 zs_free(pool, handle);
450 static void *zs_zpool_map(void *pool, unsigned long handle,
451 enum zpool_mapmode mm)
453 enum zs_mapmode zs_mm;
468 return zs_map_object(pool, handle, zs_mm);
470 static void zs_zpool_unmap(void *pool, unsigned long handle)
472 zs_unmap_object(pool, handle);
475 static u64 zs_zpool_total_size(void *pool)
477 return zs_get_total_pages(pool) << PAGE_SHIFT;
480 static struct zpool_driver zs_zpool_driver = {
482 .owner = THIS_MODULE,
483 .create = zs_zpool_create,
484 .destroy = zs_zpool_destroy,
485 .malloc_support_movable = true,
486 .malloc = zs_zpool_malloc,
487 .free = zs_zpool_free,
489 .unmap = zs_zpool_unmap,
490 .total_size = zs_zpool_total_size,
493 MODULE_ALIAS("zpool-zsmalloc");
494 #endif /* CONFIG_ZPOOL */
496 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
497 static DEFINE_PER_CPU(struct mapping_area, zs_map_area) = {
498 .lock = INIT_LOCAL_LOCK(lock),
501 static bool is_zspage_isolated(struct zspage *zspage)
503 return zspage->isolated;
506 static __maybe_unused int is_first_page(struct page *page)
508 return PagePrivate(page);
511 /* Protected by class->lock */
512 static inline int get_zspage_inuse(struct zspage *zspage)
514 return zspage->inuse;
518 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
520 zspage->inuse += val;
523 static inline struct page *get_first_page(struct zspage *zspage)
525 struct page *first_page = zspage->first_page;
527 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
531 static inline int get_first_obj_offset(struct page *page)
536 static inline void set_first_obj_offset(struct page *page, int offset)
538 page->units = offset;
541 static inline unsigned int get_freeobj(struct zspage *zspage)
543 return zspage->freeobj;
546 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
548 zspage->freeobj = obj;
551 static void get_zspage_mapping(struct zspage *zspage,
552 unsigned int *class_idx,
553 enum fullness_group *fullness)
555 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
557 *fullness = zspage->fullness;
558 *class_idx = zspage->class;
561 static void set_zspage_mapping(struct zspage *zspage,
562 unsigned int class_idx,
563 enum fullness_group fullness)
565 zspage->class = class_idx;
566 zspage->fullness = fullness;
570 * zsmalloc divides the pool into various size classes where each
571 * class maintains a list of zspages where each zspage is divided
572 * into equal sized chunks. Each allocation falls into one of these
573 * classes depending on its size. This function returns index of the
574 * size class which has chunk size big enough to hold the given size.
576 static int get_size_class_index(int size)
580 if (likely(size > ZS_MIN_ALLOC_SIZE))
581 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
582 ZS_SIZE_CLASS_DELTA);
584 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
587 /* type can be of enum type zs_stat_type or fullness_group */
588 static inline void zs_stat_inc(struct size_class *class,
589 int type, unsigned long cnt)
591 class->stats.objs[type] += cnt;
594 /* type can be of enum type zs_stat_type or fullness_group */
595 static inline void zs_stat_dec(struct size_class *class,
596 int type, unsigned long cnt)
598 class->stats.objs[type] -= cnt;
601 /* type can be of enum type zs_stat_type or fullness_group */
602 static inline unsigned long zs_stat_get(struct size_class *class,
605 return class->stats.objs[type];
608 #ifdef CONFIG_ZSMALLOC_STAT
610 static void __init zs_stat_init(void)
612 if (!debugfs_initialized()) {
613 pr_warn("debugfs not available, stat dir not created\n");
617 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
620 static void __exit zs_stat_exit(void)
622 debugfs_remove_recursive(zs_stat_root);
625 static unsigned long zs_can_compact(struct size_class *class);
627 static int zs_stats_size_show(struct seq_file *s, void *v)
630 struct zs_pool *pool = s->private;
631 struct size_class *class;
633 unsigned long class_almost_full, class_almost_empty;
634 unsigned long obj_allocated, obj_used, pages_used, freeable;
635 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
636 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
637 unsigned long total_freeable = 0;
639 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
640 "class", "size", "almost_full", "almost_empty",
641 "obj_allocated", "obj_used", "pages_used",
642 "pages_per_zspage", "freeable");
644 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
645 class = pool->size_class[i];
647 if (class->index != i)
650 spin_lock(&class->lock);
651 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
652 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
653 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
654 obj_used = zs_stat_get(class, OBJ_USED);
655 freeable = zs_can_compact(class);
656 spin_unlock(&class->lock);
658 objs_per_zspage = class->objs_per_zspage;
659 pages_used = obj_allocated / objs_per_zspage *
660 class->pages_per_zspage;
662 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
663 " %10lu %10lu %16d %8lu\n",
664 i, class->size, class_almost_full, class_almost_empty,
665 obj_allocated, obj_used, pages_used,
666 class->pages_per_zspage, freeable);
668 total_class_almost_full += class_almost_full;
669 total_class_almost_empty += class_almost_empty;
670 total_objs += obj_allocated;
671 total_used_objs += obj_used;
672 total_pages += pages_used;
673 total_freeable += freeable;
677 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
678 "Total", "", total_class_almost_full,
679 total_class_almost_empty, total_objs,
680 total_used_objs, total_pages, "", total_freeable);
684 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
686 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
689 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
693 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
695 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
696 &zs_stats_size_fops);
699 static void zs_pool_stat_destroy(struct zs_pool *pool)
701 debugfs_remove_recursive(pool->stat_dentry);
704 #else /* CONFIG_ZSMALLOC_STAT */
705 static void __init zs_stat_init(void)
709 static void __exit zs_stat_exit(void)
713 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
717 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
724 * For each size class, zspages are divided into different groups
725 * depending on how "full" they are. This was done so that we could
726 * easily find empty or nearly empty zspages when we try to shrink
727 * the pool (not yet implemented). This function returns fullness
728 * status of the given page.
730 static enum fullness_group get_fullness_group(struct size_class *class,
731 struct zspage *zspage)
733 int inuse, objs_per_zspage;
734 enum fullness_group fg;
736 inuse = get_zspage_inuse(zspage);
737 objs_per_zspage = class->objs_per_zspage;
741 else if (inuse == objs_per_zspage)
743 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
744 fg = ZS_ALMOST_EMPTY;
752 * Each size class maintains various freelists and zspages are assigned
753 * to one of these freelists based on the number of live objects they
754 * have. This functions inserts the given zspage into the freelist
755 * identified by <class, fullness_group>.
757 static void insert_zspage(struct size_class *class,
758 struct zspage *zspage,
759 enum fullness_group fullness)
763 zs_stat_inc(class, fullness, 1);
764 head = list_first_entry_or_null(&class->fullness_list[fullness],
765 struct zspage, list);
767 * We want to see more ZS_FULL pages and less almost empty/full.
768 * Put pages with higher ->inuse first.
770 if (head && get_zspage_inuse(zspage) < get_zspage_inuse(head))
771 list_add(&zspage->list, &head->list);
773 list_add(&zspage->list, &class->fullness_list[fullness]);
777 * This function removes the given zspage from the freelist identified
778 * by <class, fullness_group>.
780 static void remove_zspage(struct size_class *class,
781 struct zspage *zspage,
782 enum fullness_group fullness)
784 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
785 VM_BUG_ON(is_zspage_isolated(zspage));
787 list_del_init(&zspage->list);
788 zs_stat_dec(class, fullness, 1);
792 * Each size class maintains zspages in different fullness groups depending
793 * on the number of live objects they contain. When allocating or freeing
794 * objects, the fullness status of the page can change, say, from ALMOST_FULL
795 * to ALMOST_EMPTY when freeing an object. This function checks if such
796 * a status change has occurred for the given page and accordingly moves the
797 * page from the freelist of the old fullness group to that of the new
800 static enum fullness_group fix_fullness_group(struct size_class *class,
801 struct zspage *zspage)
804 enum fullness_group currfg, newfg;
806 get_zspage_mapping(zspage, &class_idx, &currfg);
807 newfg = get_fullness_group(class, zspage);
811 if (!is_zspage_isolated(zspage)) {
812 remove_zspage(class, zspage, currfg);
813 insert_zspage(class, zspage, newfg);
816 set_zspage_mapping(zspage, class_idx, newfg);
823 * We have to decide on how many pages to link together
824 * to form a zspage for each size class. This is important
825 * to reduce wastage due to unusable space left at end of
826 * each zspage which is given as:
827 * wastage = Zp % class_size
828 * usage = Zp - wastage
829 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
831 * For example, for size class of 3/8 * PAGE_SIZE, we should
832 * link together 3 PAGE_SIZE sized pages to form a zspage
833 * since then we can perfectly fit in 8 such objects.
835 static int get_pages_per_zspage(int class_size)
837 int i, max_usedpc = 0;
838 /* zspage order which gives maximum used size per KB */
839 int max_usedpc_order = 1;
841 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
845 zspage_size = i * PAGE_SIZE;
846 waste = zspage_size % class_size;
847 usedpc = (zspage_size - waste) * 100 / zspage_size;
849 if (usedpc > max_usedpc) {
851 max_usedpc_order = i;
855 return max_usedpc_order;
858 static struct zspage *get_zspage(struct page *page)
860 struct zspage *zspage = (struct zspage *)page_private(page);
862 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
866 static struct page *get_next_page(struct page *page)
868 if (unlikely(PageHugeObject(page)))
871 return page->freelist;
875 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
876 * @obj: the encoded object value
877 * @page: page object resides in zspage
878 * @obj_idx: object index
880 static void obj_to_location(unsigned long obj, struct page **page,
881 unsigned int *obj_idx)
883 obj >>= OBJ_TAG_BITS;
884 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
885 *obj_idx = (obj & OBJ_INDEX_MASK);
889 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
890 * @page: page object resides in zspage
891 * @obj_idx: object index
893 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
897 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
898 obj |= obj_idx & OBJ_INDEX_MASK;
899 obj <<= OBJ_TAG_BITS;
904 static unsigned long handle_to_obj(unsigned long handle)
906 #ifdef CONFIG_PREEMPT_RT
907 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
911 return *(unsigned long *)handle;
915 static unsigned long obj_to_head(struct page *page, void *obj)
917 if (unlikely(PageHugeObject(page))) {
918 VM_BUG_ON_PAGE(!is_first_page(page), page);
921 return *(unsigned long *)obj;
924 static inline int testpin_tag(unsigned long handle)
926 #ifdef CONFIG_PREEMPT_RT
927 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
929 return spin_is_locked(&zh->lock);
931 return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
935 static inline int trypin_tag(unsigned long handle)
937 #ifdef CONFIG_PREEMPT_RT
938 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
940 return spin_trylock(&zh->lock);
942 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
946 static void pin_tag(unsigned long handle) __acquires(bitlock)
948 #ifdef CONFIG_PREEMPT_RT
949 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
951 return spin_lock(&zh->lock);
953 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
957 static void unpin_tag(unsigned long handle) __releases(bitlock)
959 #ifdef CONFIG_PREEMPT_RT
960 struct zsmalloc_handle *zh = zs_get_pure_handle(handle);
962 return spin_unlock(&zh->lock);
964 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
968 static void reset_page(struct page *page)
970 __ClearPageMovable(page);
971 ClearPagePrivate(page);
972 set_page_private(page, 0);
973 page_mapcount_reset(page);
974 ClearPageHugeObject(page);
975 page->freelist = NULL;
978 static int trylock_zspage(struct zspage *zspage)
980 struct page *cursor, *fail;
982 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
983 get_next_page(cursor)) {
984 if (!trylock_page(cursor)) {
992 for (cursor = get_first_page(zspage); cursor != fail; cursor =
993 get_next_page(cursor))
999 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
1000 struct zspage *zspage)
1002 struct page *page, *next;
1003 enum fullness_group fg;
1004 unsigned int class_idx;
1006 get_zspage_mapping(zspage, &class_idx, &fg);
1008 assert_spin_locked(&class->lock);
1010 VM_BUG_ON(get_zspage_inuse(zspage));
1011 VM_BUG_ON(fg != ZS_EMPTY);
1013 next = page = get_first_page(zspage);
1015 VM_BUG_ON_PAGE(!PageLocked(page), page);
1016 next = get_next_page(page);
1019 dec_zone_page_state(page, NR_ZSPAGES);
1022 } while (page != NULL);
1024 cache_free_zspage(pool, zspage);
1026 zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
1027 atomic_long_sub(class->pages_per_zspage,
1028 &pool->pages_allocated);
1031 static void free_zspage(struct zs_pool *pool, struct size_class *class,
1032 struct zspage *zspage)
1034 VM_BUG_ON(get_zspage_inuse(zspage));
1035 VM_BUG_ON(list_empty(&zspage->list));
1037 if (!trylock_zspage(zspage)) {
1038 kick_deferred_free(pool);
1042 remove_zspage(class, zspage, ZS_EMPTY);
1043 __free_zspage(pool, class, zspage);
1046 /* Initialize a newly allocated zspage */
1047 static void init_zspage(struct size_class *class, struct zspage *zspage)
1049 unsigned int freeobj = 1;
1050 unsigned long off = 0;
1051 struct page *page = get_first_page(zspage);
1054 struct page *next_page;
1055 struct link_free *link;
1058 set_first_obj_offset(page, off);
1060 vaddr = kmap_atomic(page);
1061 link = (struct link_free *)vaddr + off / sizeof(*link);
1063 while ((off += class->size) < PAGE_SIZE) {
1064 link->next = freeobj++ << OBJ_TAG_BITS;
1065 link += class->size / sizeof(*link);
1069 * We now come to the last (full or partial) object on this
1070 * page, which must point to the first object on the next
1073 next_page = get_next_page(page);
1075 link->next = freeobj++ << OBJ_TAG_BITS;
1078 * Reset OBJ_TAG_BITS bit to last link to tell
1079 * whether it's allocated object or not.
1081 link->next = -1UL << OBJ_TAG_BITS;
1083 kunmap_atomic(vaddr);
1088 set_freeobj(zspage, 0);
1091 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1092 struct page *pages[])
1096 struct page *prev_page = NULL;
1097 int nr_pages = class->pages_per_zspage;
1100 * Allocate individual pages and link them together as:
1101 * 1. all pages are linked together using page->freelist
1102 * 2. each sub-page point to zspage using page->private
1104 * we set PG_private to identify the first page (i.e. no other sub-page
1105 * has this flag set).
1107 for (i = 0; i < nr_pages; i++) {
1109 set_page_private(page, (unsigned long)zspage);
1110 page->freelist = NULL;
1112 zspage->first_page = page;
1113 SetPagePrivate(page);
1114 if (unlikely(class->objs_per_zspage == 1 &&
1115 class->pages_per_zspage == 1))
1116 SetPageHugeObject(page);
1118 prev_page->freelist = page;
1125 * Allocate a zspage for the given size class
1127 static struct zspage *alloc_zspage(struct zs_pool *pool,
1128 struct size_class *class,
1132 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1133 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1138 zspage->magic = ZSPAGE_MAGIC;
1139 migrate_lock_init(zspage);
1141 for (i = 0; i < class->pages_per_zspage; i++) {
1144 page = alloc_page(gfp);
1147 dec_zone_page_state(pages[i], NR_ZSPAGES);
1148 __free_page(pages[i]);
1150 cache_free_zspage(pool, zspage);
1154 inc_zone_page_state(page, NR_ZSPAGES);
1158 create_page_chain(class, zspage, pages);
1159 init_zspage(class, zspage);
1164 static struct zspage *find_get_zspage(struct size_class *class)
1167 struct zspage *zspage;
1169 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1170 zspage = list_first_entry_or_null(&class->fullness_list[i],
1171 struct zspage, list);
1179 static inline int __zs_cpu_up(struct mapping_area *area)
1182 * Make sure we don't leak memory if a cpu UP notification
1183 * and zs_init() race and both call zs_cpu_up() on the same cpu
1187 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1193 static inline void __zs_cpu_down(struct mapping_area *area)
1195 kfree(area->vm_buf);
1196 area->vm_buf = NULL;
1199 static void *__zs_map_object(struct mapping_area *area,
1200 struct page *pages[2], int off, int size)
1204 char *buf = area->vm_buf;
1206 /* disable page faults to match kmap_atomic() return conditions */
1207 pagefault_disable();
1209 /* no read fastpath */
1210 if (area->vm_mm == ZS_MM_WO)
1213 sizes[0] = PAGE_SIZE - off;
1214 sizes[1] = size - sizes[0];
1216 /* copy object to per-cpu buffer */
1217 addr = kmap_atomic(pages[0]);
1218 memcpy(buf, addr + off, sizes[0]);
1219 kunmap_atomic(addr);
1220 addr = kmap_atomic(pages[1]);
1221 memcpy(buf + sizes[0], addr, sizes[1]);
1222 kunmap_atomic(addr);
1224 return area->vm_buf;
1227 static void __zs_unmap_object(struct mapping_area *area,
1228 struct page *pages[2], int off, int size)
1234 /* no write fastpath */
1235 if (area->vm_mm == ZS_MM_RO)
1239 buf = buf + ZS_HANDLE_SIZE;
1240 size -= ZS_HANDLE_SIZE;
1241 off += ZS_HANDLE_SIZE;
1243 sizes[0] = PAGE_SIZE - off;
1244 sizes[1] = size - sizes[0];
1246 /* copy per-cpu buffer to object */
1247 addr = kmap_atomic(pages[0]);
1248 memcpy(addr + off, buf, sizes[0]);
1249 kunmap_atomic(addr);
1250 addr = kmap_atomic(pages[1]);
1251 memcpy(addr, buf + sizes[0], sizes[1]);
1252 kunmap_atomic(addr);
1255 /* enable page faults to match kunmap_atomic() return conditions */
1259 static int zs_cpu_prepare(unsigned int cpu)
1261 struct mapping_area *area;
1263 area = &per_cpu(zs_map_area, cpu);
1264 return __zs_cpu_up(area);
1267 static int zs_cpu_dead(unsigned int cpu)
1269 struct mapping_area *area;
1271 area = &per_cpu(zs_map_area, cpu);
1272 __zs_cpu_down(area);
1276 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1277 int objs_per_zspage)
1279 if (prev->pages_per_zspage == pages_per_zspage &&
1280 prev->objs_per_zspage == objs_per_zspage)
1286 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1288 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1291 unsigned long zs_get_total_pages(struct zs_pool *pool)
1293 return atomic_long_read(&pool->pages_allocated);
1295 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1298 * zs_map_object - get address of allocated object from handle.
1299 * @pool: pool from which the object was allocated
1300 * @handle: handle returned from zs_malloc
1301 * @mm: mapping mode to use
1303 * Before using an object allocated from zs_malloc, it must be mapped using
1304 * this function. When done with the object, it must be unmapped using
1307 * Only one object can be mapped per cpu at a time. There is no protection
1308 * against nested mappings.
1310 * This function returns with preemption and page faults disabled.
1312 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1315 struct zspage *zspage;
1317 unsigned long obj, off;
1318 unsigned int obj_idx;
1320 unsigned int class_idx;
1321 enum fullness_group fg;
1322 struct size_class *class;
1323 struct mapping_area *area;
1324 struct page *pages[2];
1328 * Because we use per-cpu mapping areas shared among the
1329 * pools/users, we can't allow mapping in interrupt context
1330 * because it can corrupt another users mappings.
1332 BUG_ON(in_interrupt());
1334 /* From now on, migration cannot move the object */
1337 obj = handle_to_obj(handle);
1338 obj_to_location(obj, &page, &obj_idx);
1339 zspage = get_zspage(page);
1341 /* migration cannot move any subpage in this zspage */
1342 migrate_read_lock(zspage);
1344 get_zspage_mapping(zspage, &class_idx, &fg);
1345 class = pool->size_class[class_idx];
1346 off = (class->size * obj_idx) & ~PAGE_MASK;
1348 local_lock(&zs_map_area.lock);
1349 area = this_cpu_ptr(&zs_map_area);
1351 if (off + class->size <= PAGE_SIZE) {
1352 /* this object is contained entirely within a page */
1353 area->vm_addr = kmap_atomic(page);
1354 ret = area->vm_addr + off;
1358 /* this object spans two pages */
1360 pages[1] = get_next_page(page);
1363 ret = __zs_map_object(area, pages, off, class->size);
1365 if (likely(!PageHugeObject(page)))
1366 ret += ZS_HANDLE_SIZE;
1370 EXPORT_SYMBOL_GPL(zs_map_object);
1372 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1374 struct zspage *zspage;
1376 unsigned long obj, off;
1377 unsigned int obj_idx;
1379 unsigned int class_idx;
1380 enum fullness_group fg;
1381 struct size_class *class;
1382 struct mapping_area *area;
1384 obj = handle_to_obj(handle);
1385 obj_to_location(obj, &page, &obj_idx);
1386 zspage = get_zspage(page);
1387 get_zspage_mapping(zspage, &class_idx, &fg);
1388 class = pool->size_class[class_idx];
1389 off = (class->size * obj_idx) & ~PAGE_MASK;
1391 area = this_cpu_ptr(&zs_map_area);
1392 if (off + class->size <= PAGE_SIZE)
1393 kunmap_atomic(area->vm_addr);
1395 struct page *pages[2];
1398 pages[1] = get_next_page(page);
1401 __zs_unmap_object(area, pages, off, class->size);
1403 local_unlock(&zs_map_area.lock);
1405 migrate_read_unlock(zspage);
1408 EXPORT_SYMBOL_GPL(zs_unmap_object);
1411 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1412 * zsmalloc &size_class.
1413 * @pool: zsmalloc pool to use
1415 * The function returns the size of the first huge class - any object of equal
1416 * or bigger size will be stored in zspage consisting of a single physical
1419 * Context: Any context.
1421 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1423 size_t zs_huge_class_size(struct zs_pool *pool)
1425 return huge_class_size;
1427 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1429 static unsigned long obj_malloc(struct size_class *class,
1430 struct zspage *zspage, unsigned long handle)
1432 int i, nr_page, offset;
1434 struct link_free *link;
1436 struct page *m_page;
1437 unsigned long m_offset;
1440 handle |= OBJ_ALLOCATED_TAG;
1441 obj = get_freeobj(zspage);
1443 offset = obj * class->size;
1444 nr_page = offset >> PAGE_SHIFT;
1445 m_offset = offset & ~PAGE_MASK;
1446 m_page = get_first_page(zspage);
1448 for (i = 0; i < nr_page; i++)
1449 m_page = get_next_page(m_page);
1451 vaddr = kmap_atomic(m_page);
1452 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1453 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1454 if (likely(!PageHugeObject(m_page)))
1455 /* record handle in the header of allocated chunk */
1456 link->handle = handle;
1458 /* record handle to page->index */
1459 zspage->first_page->index = handle;
1461 kunmap_atomic(vaddr);
1462 mod_zspage_inuse(zspage, 1);
1463 zs_stat_inc(class, OBJ_USED, 1);
1465 obj = location_to_obj(m_page, obj);
1472 * zs_malloc - Allocate block of given size from pool.
1473 * @pool: pool to allocate from
1474 * @size: size of block to allocate
1475 * @gfp: gfp flags when allocating object
1477 * On success, handle to the allocated object is returned,
1479 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1481 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1483 unsigned long handle, obj;
1484 struct size_class *class;
1485 enum fullness_group newfg;
1486 struct zspage *zspage;
1488 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1491 handle = cache_alloc_handle(pool, gfp);
1495 /* extra space in chunk to keep the handle */
1496 size += ZS_HANDLE_SIZE;
1497 class = pool->size_class[get_size_class_index(size)];
1499 spin_lock(&class->lock);
1500 zspage = find_get_zspage(class);
1501 if (likely(zspage)) {
1502 obj = obj_malloc(class, zspage, handle);
1503 /* Now move the zspage to another fullness group, if required */
1504 fix_fullness_group(class, zspage);
1505 record_obj(handle, obj);
1506 spin_unlock(&class->lock);
1511 spin_unlock(&class->lock);
1513 zspage = alloc_zspage(pool, class, gfp);
1515 cache_free_handle(pool, handle);
1519 spin_lock(&class->lock);
1520 obj = obj_malloc(class, zspage, handle);
1521 newfg = get_fullness_group(class, zspage);
1522 insert_zspage(class, zspage, newfg);
1523 set_zspage_mapping(zspage, class->index, newfg);
1524 record_obj(handle, obj);
1525 atomic_long_add(class->pages_per_zspage,
1526 &pool->pages_allocated);
1527 zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1529 /* We completely set up zspage so mark them as movable */
1530 SetZsPageMovable(pool, zspage);
1531 spin_unlock(&class->lock);
1535 EXPORT_SYMBOL_GPL(zs_malloc);
1537 static void obj_free(struct size_class *class, unsigned long obj)
1539 struct link_free *link;
1540 struct zspage *zspage;
1541 struct page *f_page;
1542 unsigned long f_offset;
1543 unsigned int f_objidx;
1546 obj_to_location(obj, &f_page, &f_objidx);
1547 f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1548 zspage = get_zspage(f_page);
1550 vaddr = kmap_atomic(f_page);
1552 /* Insert this object in containing zspage's freelist */
1553 link = (struct link_free *)(vaddr + f_offset);
1554 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1555 kunmap_atomic(vaddr);
1556 set_freeobj(zspage, f_objidx);
1557 mod_zspage_inuse(zspage, -1);
1558 zs_stat_dec(class, OBJ_USED, 1);
1561 void zs_free(struct zs_pool *pool, unsigned long handle)
1563 struct zspage *zspage;
1564 struct page *f_page;
1566 unsigned int f_objidx;
1568 struct size_class *class;
1569 enum fullness_group fullness;
1572 if (unlikely(!handle))
1576 obj = handle_to_obj(handle);
1577 obj_to_location(obj, &f_page, &f_objidx);
1578 zspage = get_zspage(f_page);
1580 migrate_read_lock(zspage);
1582 get_zspage_mapping(zspage, &class_idx, &fullness);
1583 class = pool->size_class[class_idx];
1585 spin_lock(&class->lock);
1586 obj_free(class, obj);
1587 fullness = fix_fullness_group(class, zspage);
1588 if (fullness != ZS_EMPTY) {
1589 migrate_read_unlock(zspage);
1593 isolated = is_zspage_isolated(zspage);
1594 migrate_read_unlock(zspage);
1595 /* If zspage is isolated, zs_page_putback will free the zspage */
1596 if (likely(!isolated))
1597 free_zspage(pool, class, zspage);
1600 spin_unlock(&class->lock);
1602 cache_free_handle(pool, handle);
1604 EXPORT_SYMBOL_GPL(zs_free);
1606 static void zs_object_copy(struct size_class *class, unsigned long dst,
1609 struct page *s_page, *d_page;
1610 unsigned int s_objidx, d_objidx;
1611 unsigned long s_off, d_off;
1612 void *s_addr, *d_addr;
1613 int s_size, d_size, size;
1616 s_size = d_size = class->size;
1618 obj_to_location(src, &s_page, &s_objidx);
1619 obj_to_location(dst, &d_page, &d_objidx);
1621 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1622 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1624 if (s_off + class->size > PAGE_SIZE)
1625 s_size = PAGE_SIZE - s_off;
1627 if (d_off + class->size > PAGE_SIZE)
1628 d_size = PAGE_SIZE - d_off;
1630 s_addr = kmap_atomic(s_page);
1631 d_addr = kmap_atomic(d_page);
1634 size = min(s_size, d_size);
1635 memcpy(d_addr + d_off, s_addr + s_off, size);
1638 if (written == class->size)
1646 if (s_off >= PAGE_SIZE) {
1647 kunmap_atomic(d_addr);
1648 kunmap_atomic(s_addr);
1649 s_page = get_next_page(s_page);
1650 s_addr = kmap_atomic(s_page);
1651 d_addr = kmap_atomic(d_page);
1652 s_size = class->size - written;
1656 if (d_off >= PAGE_SIZE) {
1657 kunmap_atomic(d_addr);
1658 d_page = get_next_page(d_page);
1659 d_addr = kmap_atomic(d_page);
1660 d_size = class->size - written;
1665 kunmap_atomic(d_addr);
1666 kunmap_atomic(s_addr);
1670 * Find alloced object in zspage from index object and
1673 static unsigned long find_alloced_obj(struct size_class *class,
1674 struct page *page, int *obj_idx)
1678 int index = *obj_idx;
1679 unsigned long handle = 0;
1680 void *addr = kmap_atomic(page);
1682 offset = get_first_obj_offset(page);
1683 offset += class->size * index;
1685 while (offset < PAGE_SIZE) {
1686 head = obj_to_head(page, addr + offset);
1687 if (head & OBJ_ALLOCATED_TAG) {
1688 handle = head & ~OBJ_ALLOCATED_TAG;
1689 if (trypin_tag(handle))
1694 offset += class->size;
1698 kunmap_atomic(addr);
1705 struct zs_compact_control {
1706 /* Source spage for migration which could be a subpage of zspage */
1707 struct page *s_page;
1708 /* Destination page for migration which should be a first page
1710 struct page *d_page;
1711 /* Starting object index within @s_page which used for live object
1712 * in the subpage. */
1716 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1717 struct zs_compact_control *cc)
1719 unsigned long used_obj, free_obj;
1720 unsigned long handle;
1721 struct page *s_page = cc->s_page;
1722 struct page *d_page = cc->d_page;
1723 int obj_idx = cc->obj_idx;
1727 handle = find_alloced_obj(class, s_page, &obj_idx);
1729 s_page = get_next_page(s_page);
1736 /* Stop if there is no more space */
1737 if (zspage_full(class, get_zspage(d_page))) {
1743 used_obj = handle_to_obj(handle);
1744 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1745 zs_object_copy(class, free_obj, used_obj);
1748 * record_obj updates handle's value to free_obj and it will
1749 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1750 * breaks synchronization using pin_tag(e,g, zs_free) so
1751 * let's keep the lock bit.
1753 free_obj |= BIT(HANDLE_PIN_BIT);
1754 record_obj(handle, free_obj);
1756 obj_free(class, used_obj);
1759 /* Remember last position in this iteration */
1760 cc->s_page = s_page;
1761 cc->obj_idx = obj_idx;
1766 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1769 struct zspage *zspage;
1770 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1773 fg[0] = ZS_ALMOST_FULL;
1774 fg[1] = ZS_ALMOST_EMPTY;
1777 for (i = 0; i < 2; i++) {
1778 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1779 struct zspage, list);
1781 VM_BUG_ON(is_zspage_isolated(zspage));
1782 remove_zspage(class, zspage, fg[i]);
1791 * putback_zspage - add @zspage into right class's fullness list
1792 * @class: destination class
1793 * @zspage: target page
1795 * Return @zspage's fullness_group
1797 static enum fullness_group putback_zspage(struct size_class *class,
1798 struct zspage *zspage)
1800 enum fullness_group fullness;
1802 VM_BUG_ON(is_zspage_isolated(zspage));
1804 fullness = get_fullness_group(class, zspage);
1805 insert_zspage(class, zspage, fullness);
1806 set_zspage_mapping(zspage, class->index, fullness);
1811 #ifdef CONFIG_COMPACTION
1813 * To prevent zspage destroy during migration, zspage freeing should
1814 * hold locks of all pages in the zspage.
1816 static void lock_zspage(struct zspage *zspage)
1818 struct page *curr_page, *page;
1821 * Pages we haven't locked yet can be migrated off the list while we're
1822 * trying to lock them, so we need to be careful and only attempt to
1823 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1824 * may no longer belong to the zspage. This means that we may wait for
1825 * the wrong page to unlock, so we must take a reference to the page
1826 * prior to waiting for it to unlock outside migrate_read_lock().
1829 migrate_read_lock(zspage);
1830 page = get_first_page(zspage);
1831 if (trylock_page(page))
1834 migrate_read_unlock(zspage);
1835 wait_on_page_locked(page);
1840 while ((page = get_next_page(curr_page))) {
1841 if (trylock_page(page)) {
1845 migrate_read_unlock(zspage);
1846 wait_on_page_locked(page);
1848 migrate_read_lock(zspage);
1851 migrate_read_unlock(zspage);
1854 static int zs_init_fs_context(struct fs_context *fc)
1856 return init_pseudo(fc, ZSMALLOC_MAGIC) ? 0 : -ENOMEM;
1859 static struct file_system_type zsmalloc_fs = {
1861 .init_fs_context = zs_init_fs_context,
1862 .kill_sb = kill_anon_super,
1865 static int zsmalloc_mount(void)
1869 zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1870 if (IS_ERR(zsmalloc_mnt))
1871 ret = PTR_ERR(zsmalloc_mnt);
1876 static void zsmalloc_unmount(void)
1878 kern_unmount(zsmalloc_mnt);
1881 static void migrate_lock_init(struct zspage *zspage)
1883 rwlock_init(&zspage->lock);
1886 static void migrate_read_lock(struct zspage *zspage) __acquires(&zspage->lock)
1888 read_lock(&zspage->lock);
1891 static void migrate_read_unlock(struct zspage *zspage) __releases(&zspage->lock)
1893 read_unlock(&zspage->lock);
1896 static void migrate_write_lock(struct zspage *zspage)
1898 write_lock(&zspage->lock);
1901 static void migrate_write_unlock(struct zspage *zspage)
1903 write_unlock(&zspage->lock);
1906 /* Number of isolated subpage for *page migration* in this zspage */
1907 static void inc_zspage_isolation(struct zspage *zspage)
1912 static void dec_zspage_isolation(struct zspage *zspage)
1917 static void putback_zspage_deferred(struct zs_pool *pool,
1918 struct size_class *class,
1919 struct zspage *zspage)
1921 enum fullness_group fg;
1923 fg = putback_zspage(class, zspage);
1925 schedule_work(&pool->free_work);
1929 static inline void zs_pool_dec_isolated(struct zs_pool *pool)
1931 VM_BUG_ON(atomic_long_read(&pool->isolated_pages) <= 0);
1932 atomic_long_dec(&pool->isolated_pages);
1934 * Checking pool->destroying must happen after atomic_long_dec()
1935 * for pool->isolated_pages above. Paired with the smp_mb() in
1936 * zs_unregister_migration().
1938 smp_mb__after_atomic();
1939 if (atomic_long_read(&pool->isolated_pages) == 0 && pool->destroying)
1940 wake_up_all(&pool->migration_wait);
1943 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1944 struct page *newpage, struct page *oldpage)
1947 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1950 page = get_first_page(zspage);
1952 if (page == oldpage)
1953 pages[idx] = newpage;
1957 } while ((page = get_next_page(page)) != NULL);
1959 create_page_chain(class, zspage, pages);
1960 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1961 if (unlikely(PageHugeObject(oldpage)))
1962 newpage->index = oldpage->index;
1963 __SetPageMovable(newpage, page_mapping(oldpage));
1966 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1968 struct zs_pool *pool;
1969 struct size_class *class;
1971 enum fullness_group fullness;
1972 struct zspage *zspage;
1973 struct address_space *mapping;
1976 * Page is locked so zspage couldn't be destroyed. For detail, look at
1977 * lock_zspage in free_zspage.
1979 VM_BUG_ON_PAGE(!PageMovable(page), page);
1980 VM_BUG_ON_PAGE(PageIsolated(page), page);
1982 zspage = get_zspage(page);
1985 * Without class lock, fullness could be stale while class_idx is okay
1986 * because class_idx is constant unless page is freed so we should get
1987 * fullness again under class lock.
1989 get_zspage_mapping(zspage, &class_idx, &fullness);
1990 mapping = page_mapping(page);
1991 pool = mapping->private_data;
1992 class = pool->size_class[class_idx];
1994 spin_lock(&class->lock);
1995 if (get_zspage_inuse(zspage) == 0) {
1996 spin_unlock(&class->lock);
2000 /* zspage is isolated for object migration */
2001 if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2002 spin_unlock(&class->lock);
2007 * If this is first time isolation for the zspage, isolate zspage from
2008 * size_class to prevent further object allocation from the zspage.
2010 if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2011 get_zspage_mapping(zspage, &class_idx, &fullness);
2012 atomic_long_inc(&pool->isolated_pages);
2013 remove_zspage(class, zspage, fullness);
2016 inc_zspage_isolation(zspage);
2017 spin_unlock(&class->lock);
2022 static int zs_page_migrate(struct address_space *mapping, struct page *newpage,
2023 struct page *page, enum migrate_mode mode)
2025 struct zs_pool *pool;
2026 struct size_class *class;
2028 enum fullness_group fullness;
2029 struct zspage *zspage;
2031 void *s_addr, *d_addr, *addr;
2033 unsigned long handle, head;
2034 unsigned long old_obj, new_obj;
2035 unsigned int obj_idx;
2039 * We cannot support the _NO_COPY case here, because copy needs to
2040 * happen under the zs lock, which does not work with
2041 * MIGRATE_SYNC_NO_COPY workflow.
2043 if (mode == MIGRATE_SYNC_NO_COPY)
2046 VM_BUG_ON_PAGE(!PageMovable(page), page);
2047 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2049 zspage = get_zspage(page);
2051 /* Concurrent compactor cannot migrate any subpage in zspage */
2052 migrate_write_lock(zspage);
2053 get_zspage_mapping(zspage, &class_idx, &fullness);
2054 pool = mapping->private_data;
2055 class = pool->size_class[class_idx];
2056 offset = get_first_obj_offset(page);
2058 spin_lock(&class->lock);
2059 if (!get_zspage_inuse(zspage)) {
2061 * Set "offset" to end of the page so that every loops
2062 * skips unnecessary object scanning.
2068 s_addr = kmap_atomic(page);
2069 while (pos < PAGE_SIZE) {
2070 head = obj_to_head(page, s_addr + pos);
2071 if (head & OBJ_ALLOCATED_TAG) {
2072 handle = head & ~OBJ_ALLOCATED_TAG;
2073 if (!trypin_tag(handle))
2080 * Here, any user cannot access all objects in the zspage so let's move.
2082 d_addr = kmap_atomic(newpage);
2083 memcpy(d_addr, s_addr, PAGE_SIZE);
2084 kunmap_atomic(d_addr);
2086 for (addr = s_addr + offset; addr < s_addr + pos;
2087 addr += class->size) {
2088 head = obj_to_head(page, addr);
2089 if (head & OBJ_ALLOCATED_TAG) {
2090 handle = head & ~OBJ_ALLOCATED_TAG;
2091 BUG_ON(!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 BUG_ON(!testpin_tag(handle));
2142 kunmap_atomic(s_addr);
2143 spin_unlock(&class->lock);
2144 migrate_write_unlock(zspage);
2149 static void zs_page_putback(struct page *page)
2151 struct zs_pool *pool;
2152 struct size_class *class;
2154 enum fullness_group fg;
2155 struct address_space *mapping;
2156 struct zspage *zspage;
2158 VM_BUG_ON_PAGE(!PageMovable(page), page);
2159 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2161 zspage = get_zspage(page);
2162 get_zspage_mapping(zspage, &class_idx, &fg);
2163 mapping = page_mapping(page);
2164 pool = mapping->private_data;
2165 class = pool->size_class[class_idx];
2167 spin_lock(&class->lock);
2168 dec_zspage_isolation(zspage);
2169 if (!is_zspage_isolated(zspage)) {
2171 * Due to page_lock, we cannot free zspage immediately
2174 putback_zspage_deferred(pool, class, zspage);
2175 zs_pool_dec_isolated(pool);
2177 spin_unlock(&class->lock);
2180 static const struct address_space_operations zsmalloc_aops = {
2181 .isolate_page = zs_page_isolate,
2182 .migratepage = zs_page_migrate,
2183 .putback_page = zs_page_putback,
2186 static int zs_register_migration(struct zs_pool *pool)
2188 pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2189 if (IS_ERR(pool->inode)) {
2194 pool->inode->i_mapping->private_data = pool;
2195 pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2199 static bool pool_isolated_are_drained(struct zs_pool *pool)
2201 return atomic_long_read(&pool->isolated_pages) == 0;
2204 /* Function for resolving migration */
2205 static void wait_for_isolated_drain(struct zs_pool *pool)
2209 * We're in the process of destroying the pool, so there are no
2210 * active allocations. zs_page_isolate() fails for completely free
2211 * zspages, so we need only wait for the zs_pool's isolated
2212 * count to hit zero.
2214 wait_event(pool->migration_wait,
2215 pool_isolated_are_drained(pool));
2218 static void zs_unregister_migration(struct zs_pool *pool)
2220 pool->destroying = true;
2222 * We need a memory barrier here to ensure global visibility of
2223 * pool->destroying. Thus pool->isolated pages will either be 0 in which
2224 * case we don't care, or it will be > 0 and pool->destroying will
2225 * ensure that we wake up once isolation hits 0.
2228 wait_for_isolated_drain(pool); /* This can block */
2229 flush_work(&pool->free_work);
2234 * Caller should hold page_lock of all pages in the zspage
2235 * In here, we cannot use zspage meta data.
2237 static void async_free_zspage(struct work_struct *work)
2240 struct size_class *class;
2241 unsigned int class_idx;
2242 enum fullness_group fullness;
2243 struct zspage *zspage, *tmp;
2244 LIST_HEAD(free_pages);
2245 struct zs_pool *pool = container_of(work, struct zs_pool,
2248 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2249 class = pool->size_class[i];
2250 if (class->index != i)
2253 spin_lock(&class->lock);
2254 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2255 spin_unlock(&class->lock);
2259 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2260 list_del(&zspage->list);
2261 lock_zspage(zspage);
2263 get_zspage_mapping(zspage, &class_idx, &fullness);
2264 VM_BUG_ON(fullness != ZS_EMPTY);
2265 class = pool->size_class[class_idx];
2266 spin_lock(&class->lock);
2267 __free_zspage(pool, class, zspage);
2268 spin_unlock(&class->lock);
2272 static void kick_deferred_free(struct zs_pool *pool)
2274 schedule_work(&pool->free_work);
2277 static void init_deferred_free(struct zs_pool *pool)
2279 INIT_WORK(&pool->free_work, async_free_zspage);
2282 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2284 struct page *page = get_first_page(zspage);
2287 WARN_ON(!trylock_page(page));
2288 __SetPageMovable(page, pool->inode->i_mapping);
2290 } while ((page = get_next_page(page)) != NULL);
2296 * Based on the number of unused allocated objects calculate
2297 * and return the number of pages that we can free.
2299 static unsigned long zs_can_compact(struct size_class *class)
2301 unsigned long obj_wasted;
2302 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2303 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2305 if (obj_allocated <= obj_used)
2308 obj_wasted = obj_allocated - obj_used;
2309 obj_wasted /= class->objs_per_zspage;
2311 return obj_wasted * class->pages_per_zspage;
2314 static unsigned long __zs_compact(struct zs_pool *pool,
2315 struct size_class *class)
2317 struct zs_compact_control cc;
2318 struct zspage *src_zspage;
2319 struct zspage *dst_zspage = NULL;
2320 unsigned long pages_freed = 0;
2322 spin_lock(&class->lock);
2323 while ((src_zspage = isolate_zspage(class, true))) {
2325 if (!zs_can_compact(class))
2329 cc.s_page = get_first_page(src_zspage);
2331 while ((dst_zspage = isolate_zspage(class, false))) {
2332 cc.d_page = get_first_page(dst_zspage);
2334 * If there is no more space in dst_page, resched
2335 * and see if anyone had allocated another zspage.
2337 if (!migrate_zspage(pool, class, &cc))
2340 putback_zspage(class, dst_zspage);
2343 /* Stop if we couldn't find slot */
2344 if (dst_zspage == NULL)
2347 putback_zspage(class, dst_zspage);
2348 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2349 free_zspage(pool, class, src_zspage);
2350 pages_freed += class->pages_per_zspage;
2352 spin_unlock(&class->lock);
2354 spin_lock(&class->lock);
2358 putback_zspage(class, src_zspage);
2360 spin_unlock(&class->lock);
2365 unsigned long zs_compact(struct zs_pool *pool)
2368 struct size_class *class;
2369 unsigned long pages_freed = 0;
2371 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2372 class = pool->size_class[i];
2375 if (class->index != i)
2377 pages_freed += __zs_compact(pool, class);
2379 atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2383 EXPORT_SYMBOL_GPL(zs_compact);
2385 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2387 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2389 EXPORT_SYMBOL_GPL(zs_pool_stats);
2391 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2392 struct shrink_control *sc)
2394 unsigned long pages_freed;
2395 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2399 * Compact classes and calculate compaction delta.
2400 * Can run concurrently with a manually triggered
2401 * (by user) compaction.
2403 pages_freed = zs_compact(pool);
2405 return pages_freed ? pages_freed : SHRINK_STOP;
2408 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2409 struct shrink_control *sc)
2412 struct size_class *class;
2413 unsigned long pages_to_free = 0;
2414 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2417 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2418 class = pool->size_class[i];
2421 if (class->index != i)
2424 pages_to_free += zs_can_compact(class);
2427 return pages_to_free;
2430 static void zs_unregister_shrinker(struct zs_pool *pool)
2432 unregister_shrinker(&pool->shrinker);
2435 static int zs_register_shrinker(struct zs_pool *pool)
2437 pool->shrinker.scan_objects = zs_shrinker_scan;
2438 pool->shrinker.count_objects = zs_shrinker_count;
2439 pool->shrinker.batch = 0;
2440 pool->shrinker.seeks = DEFAULT_SEEKS;
2442 return register_shrinker(&pool->shrinker);
2446 * zs_create_pool - Creates an allocation pool to work from.
2447 * @name: pool name to be created
2449 * This function must be called before anything when using
2450 * the zsmalloc allocator.
2452 * On success, a pointer to the newly created pool is returned,
2455 struct zs_pool *zs_create_pool(const char *name)
2458 struct zs_pool *pool;
2459 struct size_class *prev_class = NULL;
2461 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2465 init_deferred_free(pool);
2467 pool->name = kstrdup(name, GFP_KERNEL);
2471 #ifdef CONFIG_COMPACTION
2472 init_waitqueue_head(&pool->migration_wait);
2475 if (create_cache(pool))
2479 * Iterate reversely, because, size of size_class that we want to use
2480 * for merging should be larger or equal to current size.
2482 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2484 int pages_per_zspage;
2485 int objs_per_zspage;
2486 struct size_class *class;
2489 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2490 if (size > ZS_MAX_ALLOC_SIZE)
2491 size = ZS_MAX_ALLOC_SIZE;
2492 pages_per_zspage = get_pages_per_zspage(size);
2493 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2496 * We iterate from biggest down to smallest classes,
2497 * so huge_class_size holds the size of the first huge
2498 * class. Any object bigger than or equal to that will
2499 * endup in the huge class.
2501 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2503 huge_class_size = size;
2505 * The object uses ZS_HANDLE_SIZE bytes to store the
2506 * handle. We need to subtract it, because zs_malloc()
2507 * unconditionally adds handle size before it performs
2508 * size class search - so object may be smaller than
2509 * huge class size, yet it still can end up in the huge
2510 * class because it grows by ZS_HANDLE_SIZE extra bytes
2511 * right before class lookup.
2513 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2517 * size_class is used for normal zsmalloc operation such
2518 * as alloc/free for that size. Although it is natural that we
2519 * have one size_class for each size, there is a chance that we
2520 * can get more memory utilization if we use one size_class for
2521 * many different sizes whose size_class have same
2522 * characteristics. So, we makes size_class point to
2523 * previous size_class if possible.
2526 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2527 pool->size_class[i] = prev_class;
2532 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2538 class->pages_per_zspage = pages_per_zspage;
2539 class->objs_per_zspage = objs_per_zspage;
2540 spin_lock_init(&class->lock);
2541 pool->size_class[i] = class;
2542 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2544 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2549 /* debug only, don't abort if it fails */
2550 zs_pool_stat_create(pool, name);
2552 if (zs_register_migration(pool))
2556 * Not critical since shrinker is only used to trigger internal
2557 * defragmentation of the pool which is pretty optional thing. If
2558 * registration fails we still can use the pool normally and user can
2559 * trigger compaction manually. Thus, ignore return code.
2561 zs_register_shrinker(pool);
2566 zs_destroy_pool(pool);
2569 EXPORT_SYMBOL_GPL(zs_create_pool);
2571 void zs_destroy_pool(struct zs_pool *pool)
2575 zs_unregister_shrinker(pool);
2576 zs_unregister_migration(pool);
2577 zs_pool_stat_destroy(pool);
2579 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2581 struct size_class *class = pool->size_class[i];
2586 if (class->index != i)
2589 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2590 if (!list_empty(&class->fullness_list[fg])) {
2591 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2598 destroy_cache(pool);
2602 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2604 static int __init zs_init(void)
2608 ret = zsmalloc_mount();
2612 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2613 zs_cpu_prepare, zs_cpu_dead);
2618 zpool_register_driver(&zs_zpool_driver);
2631 static void __exit zs_exit(void)
2634 zpool_unregister_driver(&zs_zpool_driver);
2637 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2642 module_init(zs_init);
2643 module_exit(zs_exit);
2645 MODULE_LICENSE("Dual BSD/GPL");
2646 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");