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->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->page_type: 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
40 #include <linux/module.h>
41 #include <linux/kernel.h>
42 #include <linux/sched.h>
43 #include <linux/bitops.h>
44 #include <linux/errno.h>
45 #include <linux/highmem.h>
46 #include <linux/string.h>
47 #include <linux/slab.h>
48 #include <linux/pgtable.h>
49 #include <asm/tlbflush.h>
50 #include <linux/cpumask.h>
51 #include <linux/cpu.h>
52 #include <linux/vmalloc.h>
53 #include <linux/preempt.h>
54 #include <linux/spinlock.h>
55 #include <linux/shrinker.h>
56 #include <linux/types.h>
57 #include <linux/debugfs.h>
58 #include <linux/zsmalloc.h>
59 #include <linux/zpool.h>
60 #include <linux/migrate.h>
61 #include <linux/wait.h>
62 #include <linux/pagemap.h>
64 #include <linux/local_lock.h>
66 #define ZSPAGE_MAGIC 0x58
69 * This must be power of 2 and greater than or equal to sizeof(link_free).
70 * These two conditions ensure that any 'struct link_free' itself doesn't
71 * span more than 1 page which avoids complex case of mapping 2 pages simply
72 * to restore link_free pointer values.
77 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
78 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
80 #define ZS_MAX_ZSPAGE_ORDER 2
81 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
83 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
86 * Object location (<PFN>, <obj_idx>) is encoded as
87 * a single (unsigned long) handle value.
89 * Note that object index <obj_idx> starts from 0.
91 * This is made more complicated by various memory models and PAE.
94 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
95 #ifdef MAX_PHYSMEM_BITS
96 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
99 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
102 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
106 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
109 * Head in allocated object should have OBJ_ALLOCATED_TAG
110 * to identify the object was allocated or not.
111 * It's okay to add the status bit in the least bit because
112 * header keeps handle which is 4byte-aligned address so we
113 * have room for two bit at least.
115 #define OBJ_ALLOCATED_TAG 1
116 #define OBJ_TAG_BITS 1
117 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
118 #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 {
158 enum class_stat_type {
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;
177 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
179 * n = number of allocated objects
180 * N = total number of objects zspage can store
181 * f = fullness_threshold_frac
183 * Similarly, we assign zspage to:
184 * ZS_ALMOST_FULL when n > N / f
185 * ZS_EMPTY when n == 0
186 * ZS_FULL when n == N
188 * (see: fix_fullness_group())
190 static const int fullness_threshold_frac = 4;
191 static size_t huge_class_size;
194 struct list_head fullness_list[NR_ZS_FULLNESS];
196 * Size of objects stored in this class. Must be multiple
201 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
202 int pages_per_zspage;
205 struct zs_size_stat stats;
209 * Placed within free objects to form a singly linked list.
210 * For every zspage, zspage->freeobj gives head of this list.
212 * This must be power of 2 and less than or equal to ZS_ALIGN
218 * It's valid for non-allocated object
222 * Handle of allocated object.
224 unsigned long handle;
231 struct size_class *size_class[ZS_SIZE_CLASSES];
232 struct kmem_cache *handle_cachep;
233 struct kmem_cache *zspage_cachep;
235 atomic_long_t pages_allocated;
237 struct zs_pool_stats stats;
239 /* Compact classes */
240 struct shrinker shrinker;
243 /* List tracking the zspages in LRU order by most recently added object */
244 struct list_head lru;
246 const struct zpool_ops *zpool_ops;
249 #ifdef CONFIG_ZSMALLOC_STAT
250 struct dentry *stat_dentry;
252 #ifdef CONFIG_COMPACTION
253 struct work_struct free_work;
260 unsigned int huge:HUGE_BITS;
261 unsigned int fullness:FULLNESS_BITS;
262 unsigned int class:CLASS_BITS + 1;
263 unsigned int isolated:ISOLATED_BITS;
264 unsigned int magic:MAGIC_VAL_BITS;
267 unsigned int freeobj;
268 struct page *first_page;
269 struct list_head list; /* fullness list */
272 /* links the zspage to the lru list in the pool */
273 struct list_head lru;
276 struct zs_pool *pool;
277 #ifdef CONFIG_COMPACTION
282 struct mapping_area {
284 char *vm_buf; /* copy buffer for objects that span pages */
285 char *vm_addr; /* address of kmap_atomic()'ed pages */
286 enum zs_mapmode vm_mm; /* mapping mode */
289 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
290 static void SetZsHugePage(struct zspage *zspage)
295 static bool ZsHugePage(struct zspage *zspage)
300 #ifdef CONFIG_COMPACTION
301 static void migrate_lock_init(struct zspage *zspage);
302 static void migrate_read_lock(struct zspage *zspage);
303 static void migrate_read_unlock(struct zspage *zspage);
304 static void migrate_write_lock(struct zspage *zspage);
305 static void migrate_write_lock_nested(struct zspage *zspage);
306 static void migrate_write_unlock(struct zspage *zspage);
307 static void kick_deferred_free(struct zs_pool *pool);
308 static void init_deferred_free(struct zs_pool *pool);
309 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
311 static void migrate_lock_init(struct zspage *zspage) {}
312 static void migrate_read_lock(struct zspage *zspage) {}
313 static void migrate_read_unlock(struct zspage *zspage) {}
314 static void migrate_write_lock(struct zspage *zspage) {}
315 static void migrate_write_lock_nested(struct zspage *zspage) {}
316 static void migrate_write_unlock(struct zspage *zspage) {}
317 static void kick_deferred_free(struct zs_pool *pool) {}
318 static void init_deferred_free(struct zs_pool *pool) {}
319 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
322 static int create_cache(struct zs_pool *pool)
324 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
326 if (!pool->handle_cachep)
329 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
331 if (!pool->zspage_cachep) {
332 kmem_cache_destroy(pool->handle_cachep);
333 pool->handle_cachep = NULL;
340 static void destroy_cache(struct zs_pool *pool)
342 kmem_cache_destroy(pool->handle_cachep);
343 kmem_cache_destroy(pool->zspage_cachep);
346 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
348 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
349 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
352 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
354 kmem_cache_free(pool->handle_cachep, (void *)handle);
357 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
359 return kmem_cache_zalloc(pool->zspage_cachep,
360 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
363 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
365 kmem_cache_free(pool->zspage_cachep, zspage);
368 /* pool->lock(which owns the handle) synchronizes races */
369 static void record_obj(unsigned long handle, unsigned long obj)
371 *(unsigned long *)handle = obj;
378 static void *zs_zpool_create(const char *name, gfp_t gfp,
379 const struct zpool_ops *zpool_ops,
383 * Ignore global gfp flags: zs_malloc() may be invoked from
384 * different contexts and its caller must provide a valid
387 struct zs_pool *pool = zs_create_pool(name);
391 pool->zpool_ops = zpool_ops;
397 static void zs_zpool_destroy(void *pool)
399 zs_destroy_pool(pool);
402 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
403 unsigned long *handle)
405 *handle = zs_malloc(pool, size, gfp);
407 if (IS_ERR_VALUE(*handle))
408 return PTR_ERR((void *)*handle);
411 static void zs_zpool_free(void *pool, unsigned long handle)
413 zs_free(pool, handle);
416 static void *zs_zpool_map(void *pool, unsigned long handle,
417 enum zpool_mapmode mm)
419 enum zs_mapmode zs_mm;
434 return zs_map_object(pool, handle, zs_mm);
436 static void zs_zpool_unmap(void *pool, unsigned long handle)
438 zs_unmap_object(pool, handle);
441 static u64 zs_zpool_total_size(void *pool)
443 return zs_get_total_pages(pool) << PAGE_SHIFT;
446 static struct zpool_driver zs_zpool_driver = {
448 .owner = THIS_MODULE,
449 .create = zs_zpool_create,
450 .destroy = zs_zpool_destroy,
451 .malloc_support_movable = true,
452 .malloc = zs_zpool_malloc,
453 .free = zs_zpool_free,
455 .unmap = zs_zpool_unmap,
456 .total_size = zs_zpool_total_size,
459 MODULE_ALIAS("zpool-zsmalloc");
460 #endif /* CONFIG_ZPOOL */
462 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
463 static DEFINE_PER_CPU(struct mapping_area, zs_map_area) = {
464 .lock = INIT_LOCAL_LOCK(lock),
467 static __maybe_unused int is_first_page(struct page *page)
469 return PagePrivate(page);
472 /* Protected by pool->lock */
473 static inline int get_zspage_inuse(struct zspage *zspage)
475 return zspage->inuse;
479 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
481 zspage->inuse += val;
484 static inline struct page *get_first_page(struct zspage *zspage)
486 struct page *first_page = zspage->first_page;
488 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
492 static inline unsigned int get_first_obj_offset(struct page *page)
494 return page->page_type;
497 static inline void set_first_obj_offset(struct page *page, unsigned int offset)
499 page->page_type = offset;
502 static inline unsigned int get_freeobj(struct zspage *zspage)
504 return zspage->freeobj;
507 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
509 zspage->freeobj = obj;
512 static void get_zspage_mapping(struct zspage *zspage,
513 unsigned int *class_idx,
514 enum fullness_group *fullness)
516 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
518 *fullness = zspage->fullness;
519 *class_idx = zspage->class;
522 static struct size_class *zspage_class(struct zs_pool *pool,
523 struct zspage *zspage)
525 return pool->size_class[zspage->class];
528 static void set_zspage_mapping(struct zspage *zspage,
529 unsigned int class_idx,
530 enum fullness_group fullness)
532 zspage->class = class_idx;
533 zspage->fullness = fullness;
537 * zsmalloc divides the pool into various size classes where each
538 * class maintains a list of zspages where each zspage is divided
539 * into equal sized chunks. Each allocation falls into one of these
540 * classes depending on its size. This function returns index of the
541 * size class which has chunk size big enough to hold the given size.
543 static int get_size_class_index(int size)
547 if (likely(size > ZS_MIN_ALLOC_SIZE))
548 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
549 ZS_SIZE_CLASS_DELTA);
551 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
554 /* type can be of enum type class_stat_type or fullness_group */
555 static inline void class_stat_inc(struct size_class *class,
556 int type, unsigned long cnt)
558 class->stats.objs[type] += cnt;
561 /* type can be of enum type class_stat_type or fullness_group */
562 static inline void class_stat_dec(struct size_class *class,
563 int type, unsigned long cnt)
565 class->stats.objs[type] -= cnt;
568 /* type can be of enum type class_stat_type or fullness_group */
569 static inline unsigned long zs_stat_get(struct size_class *class,
572 return class->stats.objs[type];
575 #ifdef CONFIG_ZSMALLOC_STAT
577 static void __init zs_stat_init(void)
579 if (!debugfs_initialized()) {
580 pr_warn("debugfs not available, stat dir not created\n");
584 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
587 static void __exit zs_stat_exit(void)
589 debugfs_remove_recursive(zs_stat_root);
592 static unsigned long zs_can_compact(struct size_class *class);
594 static int zs_stats_size_show(struct seq_file *s, void *v)
597 struct zs_pool *pool = s->private;
598 struct size_class *class;
600 unsigned long class_almost_full, class_almost_empty;
601 unsigned long obj_allocated, obj_used, pages_used, freeable;
602 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
603 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
604 unsigned long total_freeable = 0;
606 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
607 "class", "size", "almost_full", "almost_empty",
608 "obj_allocated", "obj_used", "pages_used",
609 "pages_per_zspage", "freeable");
611 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
612 class = pool->size_class[i];
614 if (class->index != i)
617 spin_lock(&pool->lock);
618 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
619 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
620 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
621 obj_used = zs_stat_get(class, OBJ_USED);
622 freeable = zs_can_compact(class);
623 spin_unlock(&pool->lock);
625 objs_per_zspage = class->objs_per_zspage;
626 pages_used = obj_allocated / objs_per_zspage *
627 class->pages_per_zspage;
629 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
630 " %10lu %10lu %16d %8lu\n",
631 i, class->size, class_almost_full, class_almost_empty,
632 obj_allocated, obj_used, pages_used,
633 class->pages_per_zspage, freeable);
635 total_class_almost_full += class_almost_full;
636 total_class_almost_empty += class_almost_empty;
637 total_objs += obj_allocated;
638 total_used_objs += obj_used;
639 total_pages += pages_used;
640 total_freeable += freeable;
644 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
645 "Total", "", total_class_almost_full,
646 total_class_almost_empty, total_objs,
647 total_used_objs, total_pages, "", total_freeable);
651 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
653 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
656 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
660 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
662 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
663 &zs_stats_size_fops);
666 static void zs_pool_stat_destroy(struct zs_pool *pool)
668 debugfs_remove_recursive(pool->stat_dentry);
671 #else /* CONFIG_ZSMALLOC_STAT */
672 static void __init zs_stat_init(void)
676 static void __exit zs_stat_exit(void)
680 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
684 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
691 * For each size class, zspages are divided into different groups
692 * depending on how "full" they are. This was done so that we could
693 * easily find empty or nearly empty zspages when we try to shrink
694 * the pool (not yet implemented). This function returns fullness
695 * status of the given page.
697 static enum fullness_group get_fullness_group(struct size_class *class,
698 struct zspage *zspage)
700 int inuse, objs_per_zspage;
701 enum fullness_group fg;
703 inuse = get_zspage_inuse(zspage);
704 objs_per_zspage = class->objs_per_zspage;
708 else if (inuse == objs_per_zspage)
710 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
711 fg = ZS_ALMOST_EMPTY;
719 * Each size class maintains various freelists and zspages are assigned
720 * to one of these freelists based on the number of live objects they
721 * have. This functions inserts the given zspage into the freelist
722 * identified by <class, fullness_group>.
724 static void insert_zspage(struct size_class *class,
725 struct zspage *zspage,
726 enum fullness_group fullness)
730 class_stat_inc(class, fullness, 1);
731 head = list_first_entry_or_null(&class->fullness_list[fullness],
732 struct zspage, list);
734 * We want to see more ZS_FULL pages and less almost empty/full.
735 * Put pages with higher ->inuse first.
737 if (head && get_zspage_inuse(zspage) < get_zspage_inuse(head))
738 list_add(&zspage->list, &head->list);
740 list_add(&zspage->list, &class->fullness_list[fullness]);
744 * This function removes the given zspage from the freelist identified
745 * by <class, fullness_group>.
747 static void remove_zspage(struct size_class *class,
748 struct zspage *zspage,
749 enum fullness_group fullness)
751 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
753 list_del_init(&zspage->list);
754 class_stat_dec(class, fullness, 1);
758 * Each size class maintains zspages in different fullness groups depending
759 * on the number of live objects they contain. When allocating or freeing
760 * objects, the fullness status of the page can change, say, from ALMOST_FULL
761 * to ALMOST_EMPTY when freeing an object. This function checks if such
762 * a status change has occurred for the given page and accordingly moves the
763 * page from the freelist of the old fullness group to that of the new
766 static enum fullness_group fix_fullness_group(struct size_class *class,
767 struct zspage *zspage)
770 enum fullness_group currfg, newfg;
772 get_zspage_mapping(zspage, &class_idx, &currfg);
773 newfg = get_fullness_group(class, zspage);
777 remove_zspage(class, zspage, currfg);
778 insert_zspage(class, zspage, newfg);
779 set_zspage_mapping(zspage, class_idx, newfg);
785 * We have to decide on how many pages to link together
786 * to form a zspage for each size class. This is important
787 * to reduce wastage due to unusable space left at end of
788 * each zspage which is given as:
789 * wastage = Zp % class_size
790 * usage = Zp - wastage
791 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
793 * For example, for size class of 3/8 * PAGE_SIZE, we should
794 * link together 3 PAGE_SIZE sized pages to form a zspage
795 * since then we can perfectly fit in 8 such objects.
797 static int get_pages_per_zspage(int class_size)
799 int i, max_usedpc = 0;
800 /* zspage order which gives maximum used size per KB */
801 int max_usedpc_order = 1;
803 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
807 zspage_size = i * PAGE_SIZE;
808 waste = zspage_size % class_size;
809 usedpc = (zspage_size - waste) * 100 / zspage_size;
811 if (usedpc > max_usedpc) {
813 max_usedpc_order = i;
817 return max_usedpc_order;
820 static struct zspage *get_zspage(struct page *page)
822 struct zspage *zspage = (struct zspage *)page_private(page);
824 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
828 static struct page *get_next_page(struct page *page)
830 struct zspage *zspage = get_zspage(page);
832 if (unlikely(ZsHugePage(zspage)))
835 return (struct page *)page->index;
839 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
840 * @obj: the encoded object value
841 * @page: page object resides in zspage
842 * @obj_idx: object index
844 static void obj_to_location(unsigned long obj, struct page **page,
845 unsigned int *obj_idx)
847 obj >>= OBJ_TAG_BITS;
848 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
849 *obj_idx = (obj & OBJ_INDEX_MASK);
852 static void obj_to_page(unsigned long obj, struct page **page)
854 obj >>= OBJ_TAG_BITS;
855 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
859 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
860 * @page: page object resides in zspage
861 * @obj_idx: object index
863 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
867 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
868 obj |= obj_idx & OBJ_INDEX_MASK;
869 obj <<= OBJ_TAG_BITS;
874 static unsigned long handle_to_obj(unsigned long handle)
876 return *(unsigned long *)handle;
879 static bool obj_allocated(struct page *page, void *obj, unsigned long *phandle)
881 unsigned long handle;
882 struct zspage *zspage = get_zspage(page);
884 if (unlikely(ZsHugePage(zspage))) {
885 VM_BUG_ON_PAGE(!is_first_page(page), page);
886 handle = page->index;
888 handle = *(unsigned long *)obj;
890 if (!(handle & OBJ_ALLOCATED_TAG))
893 *phandle = handle & ~OBJ_ALLOCATED_TAG;
897 static void reset_page(struct page *page)
899 __ClearPageMovable(page);
900 ClearPagePrivate(page);
901 set_page_private(page, 0);
902 page_mapcount_reset(page);
906 static int trylock_zspage(struct zspage *zspage)
908 struct page *cursor, *fail;
910 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
911 get_next_page(cursor)) {
912 if (!trylock_page(cursor)) {
920 for (cursor = get_first_page(zspage); cursor != fail; cursor =
921 get_next_page(cursor))
927 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
928 struct zspage *zspage)
930 struct page *page, *next;
931 enum fullness_group fg;
932 unsigned int class_idx;
934 get_zspage_mapping(zspage, &class_idx, &fg);
936 assert_spin_locked(&pool->lock);
938 VM_BUG_ON(get_zspage_inuse(zspage));
939 VM_BUG_ON(fg != ZS_EMPTY);
941 next = page = get_first_page(zspage);
943 VM_BUG_ON_PAGE(!PageLocked(page), page);
944 next = get_next_page(page);
947 dec_zone_page_state(page, NR_ZSPAGES);
950 } while (page != NULL);
952 cache_free_zspage(pool, zspage);
954 class_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
955 atomic_long_sub(class->pages_per_zspage,
956 &pool->pages_allocated);
959 static void free_zspage(struct zs_pool *pool, struct size_class *class,
960 struct zspage *zspage)
962 VM_BUG_ON(get_zspage_inuse(zspage));
963 VM_BUG_ON(list_empty(&zspage->list));
966 * Since zs_free couldn't be sleepable, this function cannot call
967 * lock_page. The page locks trylock_zspage got will be released
970 if (!trylock_zspage(zspage)) {
971 kick_deferred_free(pool);
975 remove_zspage(class, zspage, ZS_EMPTY);
977 list_del(&zspage->lru);
979 __free_zspage(pool, class, zspage);
982 /* Initialize a newly allocated zspage */
983 static void init_zspage(struct size_class *class, struct zspage *zspage)
985 unsigned int freeobj = 1;
986 unsigned long off = 0;
987 struct page *page = get_first_page(zspage);
990 struct page *next_page;
991 struct link_free *link;
994 set_first_obj_offset(page, off);
996 vaddr = kmap_atomic(page);
997 link = (struct link_free *)vaddr + off / sizeof(*link);
999 while ((off += class->size) < PAGE_SIZE) {
1000 link->next = freeobj++ << OBJ_TAG_BITS;
1001 link += class->size / sizeof(*link);
1005 * We now come to the last (full or partial) object on this
1006 * page, which must point to the first object on the next
1009 next_page = get_next_page(page);
1011 link->next = freeobj++ << OBJ_TAG_BITS;
1014 * Reset OBJ_TAG_BITS bit to last link to tell
1015 * whether it's allocated object or not.
1017 link->next = -1UL << OBJ_TAG_BITS;
1019 kunmap_atomic(vaddr);
1025 INIT_LIST_HEAD(&zspage->lru);
1028 set_freeobj(zspage, 0);
1031 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1032 struct page *pages[])
1036 struct page *prev_page = NULL;
1037 int nr_pages = class->pages_per_zspage;
1040 * Allocate individual pages and link them together as:
1041 * 1. all pages are linked together using page->index
1042 * 2. each sub-page point to zspage using page->private
1044 * we set PG_private to identify the first page (i.e. no other sub-page
1045 * has this flag set).
1047 for (i = 0; i < nr_pages; i++) {
1049 set_page_private(page, (unsigned long)zspage);
1052 zspage->first_page = page;
1053 SetPagePrivate(page);
1054 if (unlikely(class->objs_per_zspage == 1 &&
1055 class->pages_per_zspage == 1))
1056 SetZsHugePage(zspage);
1058 prev_page->index = (unsigned long)page;
1065 * Allocate a zspage for the given size class
1067 static struct zspage *alloc_zspage(struct zs_pool *pool,
1068 struct size_class *class,
1072 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1073 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1078 zspage->magic = ZSPAGE_MAGIC;
1079 migrate_lock_init(zspage);
1081 for (i = 0; i < class->pages_per_zspage; i++) {
1084 page = alloc_page(gfp);
1087 dec_zone_page_state(pages[i], NR_ZSPAGES);
1088 __free_page(pages[i]);
1090 cache_free_zspage(pool, zspage);
1094 inc_zone_page_state(page, NR_ZSPAGES);
1098 create_page_chain(class, zspage, pages);
1099 init_zspage(class, zspage);
1100 zspage->pool = pool;
1105 static struct zspage *find_get_zspage(struct size_class *class)
1108 struct zspage *zspage;
1110 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1111 zspage = list_first_entry_or_null(&class->fullness_list[i],
1112 struct zspage, list);
1120 static inline int __zs_cpu_up(struct mapping_area *area)
1123 * Make sure we don't leak memory if a cpu UP notification
1124 * and zs_init() race and both call zs_cpu_up() on the same cpu
1128 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1134 static inline void __zs_cpu_down(struct mapping_area *area)
1136 kfree(area->vm_buf);
1137 area->vm_buf = NULL;
1140 static void *__zs_map_object(struct mapping_area *area,
1141 struct page *pages[2], int off, int size)
1145 char *buf = area->vm_buf;
1147 /* disable page faults to match kmap_atomic() return conditions */
1148 pagefault_disable();
1150 /* no read fastpath */
1151 if (area->vm_mm == ZS_MM_WO)
1154 sizes[0] = PAGE_SIZE - off;
1155 sizes[1] = size - sizes[0];
1157 /* copy object to per-cpu buffer */
1158 addr = kmap_atomic(pages[0]);
1159 memcpy(buf, addr + off, sizes[0]);
1160 kunmap_atomic(addr);
1161 addr = kmap_atomic(pages[1]);
1162 memcpy(buf + sizes[0], addr, sizes[1]);
1163 kunmap_atomic(addr);
1165 return area->vm_buf;
1168 static void __zs_unmap_object(struct mapping_area *area,
1169 struct page *pages[2], int off, int size)
1175 /* no write fastpath */
1176 if (area->vm_mm == ZS_MM_RO)
1180 buf = buf + ZS_HANDLE_SIZE;
1181 size -= ZS_HANDLE_SIZE;
1182 off += ZS_HANDLE_SIZE;
1184 sizes[0] = PAGE_SIZE - off;
1185 sizes[1] = size - sizes[0];
1187 /* copy per-cpu buffer to object */
1188 addr = kmap_atomic(pages[0]);
1189 memcpy(addr + off, buf, sizes[0]);
1190 kunmap_atomic(addr);
1191 addr = kmap_atomic(pages[1]);
1192 memcpy(addr, buf + sizes[0], sizes[1]);
1193 kunmap_atomic(addr);
1196 /* enable page faults to match kunmap_atomic() return conditions */
1200 static int zs_cpu_prepare(unsigned int cpu)
1202 struct mapping_area *area;
1204 area = &per_cpu(zs_map_area, cpu);
1205 return __zs_cpu_up(area);
1208 static int zs_cpu_dead(unsigned int cpu)
1210 struct mapping_area *area;
1212 area = &per_cpu(zs_map_area, cpu);
1213 __zs_cpu_down(area);
1217 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1218 int objs_per_zspage)
1220 if (prev->pages_per_zspage == pages_per_zspage &&
1221 prev->objs_per_zspage == objs_per_zspage)
1227 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1229 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1233 * zs_lookup_class_index() - Returns index of the zsmalloc &size_class
1234 * that hold objects of the provided size.
1235 * @pool: zsmalloc pool to use
1236 * @size: object size
1238 * Context: Any context.
1240 * Return: the index of the zsmalloc &size_class that hold objects of the
1243 unsigned int zs_lookup_class_index(struct zs_pool *pool, unsigned int size)
1245 struct size_class *class;
1247 class = pool->size_class[get_size_class_index(size)];
1249 return class->index;
1251 EXPORT_SYMBOL_GPL(zs_lookup_class_index);
1253 unsigned long zs_get_total_pages(struct zs_pool *pool)
1255 return atomic_long_read(&pool->pages_allocated);
1257 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1260 * zs_map_object - get address of allocated object from handle.
1261 * @pool: pool from which the object was allocated
1262 * @handle: handle returned from zs_malloc
1263 * @mm: mapping mode to use
1265 * Before using an object allocated from zs_malloc, it must be mapped using
1266 * this function. When done with the object, it must be unmapped using
1269 * Only one object can be mapped per cpu at a time. There is no protection
1270 * against nested mappings.
1272 * This function returns with preemption and page faults disabled.
1274 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1277 struct zspage *zspage;
1279 unsigned long obj, off;
1280 unsigned int obj_idx;
1282 struct size_class *class;
1283 struct mapping_area *area;
1284 struct page *pages[2];
1288 * Because we use per-cpu mapping areas shared among the
1289 * pools/users, we can't allow mapping in interrupt context
1290 * because it can corrupt another users mappings.
1292 BUG_ON(in_interrupt());
1294 /* It guarantees it can get zspage from handle safely */
1295 spin_lock(&pool->lock);
1296 obj = handle_to_obj(handle);
1297 obj_to_location(obj, &page, &obj_idx);
1298 zspage = get_zspage(page);
1302 * Move the zspage to front of pool's LRU.
1304 * Note that this is swap-specific, so by definition there are no ongoing
1305 * accesses to the memory while the page is swapped out that would make
1306 * it "hot". A new entry is hot, then ages to the tail until it gets either
1307 * written back or swaps back in.
1309 * Furthermore, map is also called during writeback. We must not put an
1310 * isolated page on the LRU mid-reclaim.
1312 * As a result, only update the LRU when the page is mapped for write
1313 * when it's first instantiated.
1315 * This is a deviation from the other backends, which perform this update
1316 * in the allocation function (zbud_alloc, z3fold_alloc).
1318 if (mm == ZS_MM_WO) {
1319 if (!list_empty(&zspage->lru))
1320 list_del(&zspage->lru);
1321 list_add(&zspage->lru, &pool->lru);
1326 * migration cannot move any zpages in this zspage. Here, pool->lock
1327 * is too heavy since callers would take some time until they calls
1328 * zs_unmap_object API so delegate the locking from class to zspage
1329 * which is smaller granularity.
1331 migrate_read_lock(zspage);
1332 spin_unlock(&pool->lock);
1334 class = zspage_class(pool, zspage);
1335 off = (class->size * obj_idx) & ~PAGE_MASK;
1337 local_lock(&zs_map_area.lock);
1338 area = this_cpu_ptr(&zs_map_area);
1340 if (off + class->size <= PAGE_SIZE) {
1341 /* this object is contained entirely within a page */
1342 area->vm_addr = kmap_atomic(page);
1343 ret = area->vm_addr + off;
1347 /* this object spans two pages */
1349 pages[1] = get_next_page(page);
1352 ret = __zs_map_object(area, pages, off, class->size);
1354 if (likely(!ZsHugePage(zspage)))
1355 ret += ZS_HANDLE_SIZE;
1359 EXPORT_SYMBOL_GPL(zs_map_object);
1361 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1363 struct zspage *zspage;
1365 unsigned long obj, off;
1366 unsigned int obj_idx;
1368 struct size_class *class;
1369 struct mapping_area *area;
1371 obj = handle_to_obj(handle);
1372 obj_to_location(obj, &page, &obj_idx);
1373 zspage = get_zspage(page);
1374 class = zspage_class(pool, zspage);
1375 off = (class->size * obj_idx) & ~PAGE_MASK;
1377 area = this_cpu_ptr(&zs_map_area);
1378 if (off + class->size <= PAGE_SIZE)
1379 kunmap_atomic(area->vm_addr);
1381 struct page *pages[2];
1384 pages[1] = get_next_page(page);
1387 __zs_unmap_object(area, pages, off, class->size);
1389 local_unlock(&zs_map_area.lock);
1391 migrate_read_unlock(zspage);
1393 EXPORT_SYMBOL_GPL(zs_unmap_object);
1396 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1397 * zsmalloc &size_class.
1398 * @pool: zsmalloc pool to use
1400 * The function returns the size of the first huge class - any object of equal
1401 * or bigger size will be stored in zspage consisting of a single physical
1404 * Context: Any context.
1406 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1408 size_t zs_huge_class_size(struct zs_pool *pool)
1410 return huge_class_size;
1412 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1414 static unsigned long obj_malloc(struct zs_pool *pool,
1415 struct zspage *zspage, unsigned long handle)
1417 int i, nr_page, offset;
1419 struct link_free *link;
1420 struct size_class *class;
1422 struct page *m_page;
1423 unsigned long m_offset;
1426 class = pool->size_class[zspage->class];
1427 handle |= OBJ_ALLOCATED_TAG;
1428 obj = get_freeobj(zspage);
1430 offset = obj * class->size;
1431 nr_page = offset >> PAGE_SHIFT;
1432 m_offset = offset & ~PAGE_MASK;
1433 m_page = get_first_page(zspage);
1435 for (i = 0; i < nr_page; i++)
1436 m_page = get_next_page(m_page);
1438 vaddr = kmap_atomic(m_page);
1439 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1440 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1441 if (likely(!ZsHugePage(zspage)))
1442 /* record handle in the header of allocated chunk */
1443 link->handle = handle;
1445 /* record handle to page->index */
1446 zspage->first_page->index = handle;
1448 kunmap_atomic(vaddr);
1449 mod_zspage_inuse(zspage, 1);
1451 obj = location_to_obj(m_page, obj);
1458 * zs_malloc - Allocate block of given size from pool.
1459 * @pool: pool to allocate from
1460 * @size: size of block to allocate
1461 * @gfp: gfp flags when allocating object
1463 * On success, handle to the allocated object is returned,
1464 * otherwise an ERR_PTR().
1465 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1467 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1469 unsigned long handle, obj;
1470 struct size_class *class;
1471 enum fullness_group newfg;
1472 struct zspage *zspage;
1474 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1475 return (unsigned long)ERR_PTR(-EINVAL);
1477 handle = cache_alloc_handle(pool, gfp);
1479 return (unsigned long)ERR_PTR(-ENOMEM);
1481 /* extra space in chunk to keep the handle */
1482 size += ZS_HANDLE_SIZE;
1483 class = pool->size_class[get_size_class_index(size)];
1485 /* pool->lock effectively protects the zpage migration */
1486 spin_lock(&pool->lock);
1487 zspage = find_get_zspage(class);
1488 if (likely(zspage)) {
1489 obj = obj_malloc(pool, zspage, handle);
1490 /* Now move the zspage to another fullness group, if required */
1491 fix_fullness_group(class, zspage);
1492 record_obj(handle, obj);
1493 class_stat_inc(class, OBJ_USED, 1);
1494 spin_unlock(&pool->lock);
1499 spin_unlock(&pool->lock);
1501 zspage = alloc_zspage(pool, class, gfp);
1503 cache_free_handle(pool, handle);
1504 return (unsigned long)ERR_PTR(-ENOMEM);
1507 spin_lock(&pool->lock);
1508 obj = obj_malloc(pool, zspage, handle);
1509 newfg = get_fullness_group(class, zspage);
1510 insert_zspage(class, zspage, newfg);
1511 set_zspage_mapping(zspage, class->index, newfg);
1512 record_obj(handle, obj);
1513 atomic_long_add(class->pages_per_zspage,
1514 &pool->pages_allocated);
1515 class_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1516 class_stat_inc(class, OBJ_USED, 1);
1518 /* We completely set up zspage so mark them as movable */
1519 SetZsPageMovable(pool, zspage);
1520 spin_unlock(&pool->lock);
1524 EXPORT_SYMBOL_GPL(zs_malloc);
1526 static void obj_free(int class_size, unsigned long obj)
1528 struct link_free *link;
1529 struct zspage *zspage;
1530 struct page *f_page;
1531 unsigned long f_offset;
1532 unsigned int f_objidx;
1535 obj_to_location(obj, &f_page, &f_objidx);
1536 f_offset = (class_size * f_objidx) & ~PAGE_MASK;
1537 zspage = get_zspage(f_page);
1539 vaddr = kmap_atomic(f_page);
1541 /* Insert this object in containing zspage's freelist */
1542 link = (struct link_free *)(vaddr + f_offset);
1543 if (likely(!ZsHugePage(zspage)))
1544 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1547 kunmap_atomic(vaddr);
1548 set_freeobj(zspage, f_objidx);
1549 mod_zspage_inuse(zspage, -1);
1552 void zs_free(struct zs_pool *pool, unsigned long handle)
1554 struct zspage *zspage;
1555 struct page *f_page;
1557 struct size_class *class;
1558 enum fullness_group fullness;
1560 if (IS_ERR_OR_NULL((void *)handle))
1564 * The pool->lock protects the race with zpage's migration
1565 * so it's safe to get the page from handle.
1567 spin_lock(&pool->lock);
1568 obj = handle_to_obj(handle);
1569 obj_to_page(obj, &f_page);
1570 zspage = get_zspage(f_page);
1571 class = zspage_class(pool, zspage);
1573 obj_free(class->size, obj);
1574 class_stat_dec(class, OBJ_USED, 1);
1575 fullness = fix_fullness_group(class, zspage);
1576 if (fullness != ZS_EMPTY)
1579 free_zspage(pool, class, zspage);
1581 spin_unlock(&pool->lock);
1582 cache_free_handle(pool, handle);
1584 EXPORT_SYMBOL_GPL(zs_free);
1586 static void zs_object_copy(struct size_class *class, unsigned long dst,
1589 struct page *s_page, *d_page;
1590 unsigned int s_objidx, d_objidx;
1591 unsigned long s_off, d_off;
1592 void *s_addr, *d_addr;
1593 int s_size, d_size, size;
1596 s_size = d_size = class->size;
1598 obj_to_location(src, &s_page, &s_objidx);
1599 obj_to_location(dst, &d_page, &d_objidx);
1601 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1602 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1604 if (s_off + class->size > PAGE_SIZE)
1605 s_size = PAGE_SIZE - s_off;
1607 if (d_off + class->size > PAGE_SIZE)
1608 d_size = PAGE_SIZE - d_off;
1610 s_addr = kmap_atomic(s_page);
1611 d_addr = kmap_atomic(d_page);
1614 size = min(s_size, d_size);
1615 memcpy(d_addr + d_off, s_addr + s_off, size);
1618 if (written == class->size)
1627 * Calling kunmap_atomic(d_addr) is necessary. kunmap_atomic()
1628 * calls must occurs in reverse order of calls to kmap_atomic().
1629 * So, to call kunmap_atomic(s_addr) we should first call
1630 * kunmap_atomic(d_addr). For more details see
1631 * Documentation/mm/highmem.rst.
1633 if (s_off >= PAGE_SIZE) {
1634 kunmap_atomic(d_addr);
1635 kunmap_atomic(s_addr);
1636 s_page = get_next_page(s_page);
1637 s_addr = kmap_atomic(s_page);
1638 d_addr = kmap_atomic(d_page);
1639 s_size = class->size - written;
1643 if (d_off >= PAGE_SIZE) {
1644 kunmap_atomic(d_addr);
1645 d_page = get_next_page(d_page);
1646 d_addr = kmap_atomic(d_page);
1647 d_size = class->size - written;
1652 kunmap_atomic(d_addr);
1653 kunmap_atomic(s_addr);
1657 * Find alloced object in zspage from index object and
1660 static unsigned long find_alloced_obj(struct size_class *class,
1661 struct page *page, int *obj_idx)
1663 unsigned int offset;
1664 int index = *obj_idx;
1665 unsigned long handle = 0;
1666 void *addr = kmap_atomic(page);
1668 offset = get_first_obj_offset(page);
1669 offset += class->size * index;
1671 while (offset < PAGE_SIZE) {
1672 if (obj_allocated(page, addr + offset, &handle))
1675 offset += class->size;
1679 kunmap_atomic(addr);
1686 struct zs_compact_control {
1687 /* Source spage for migration which could be a subpage of zspage */
1688 struct page *s_page;
1689 /* Destination page for migration which should be a first page
1691 struct page *d_page;
1692 /* Starting object index within @s_page which used for live object
1693 * in the subpage. */
1697 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1698 struct zs_compact_control *cc)
1700 unsigned long used_obj, free_obj;
1701 unsigned long handle;
1702 struct page *s_page = cc->s_page;
1703 struct page *d_page = cc->d_page;
1704 int obj_idx = cc->obj_idx;
1708 handle = find_alloced_obj(class, s_page, &obj_idx);
1710 s_page = get_next_page(s_page);
1717 /* Stop if there is no more space */
1718 if (zspage_full(class, get_zspage(d_page))) {
1723 used_obj = handle_to_obj(handle);
1724 free_obj = obj_malloc(pool, get_zspage(d_page), handle);
1725 zs_object_copy(class, free_obj, used_obj);
1727 record_obj(handle, free_obj);
1728 obj_free(class->size, used_obj);
1731 /* Remember last position in this iteration */
1732 cc->s_page = s_page;
1733 cc->obj_idx = obj_idx;
1738 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1741 struct zspage *zspage;
1742 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1745 fg[0] = ZS_ALMOST_FULL;
1746 fg[1] = ZS_ALMOST_EMPTY;
1749 for (i = 0; i < 2; i++) {
1750 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1751 struct zspage, list);
1753 remove_zspage(class, zspage, fg[i]);
1762 * putback_zspage - add @zspage into right class's fullness list
1763 * @class: destination class
1764 * @zspage: target page
1766 * Return @zspage's fullness_group
1768 static enum fullness_group putback_zspage(struct size_class *class,
1769 struct zspage *zspage)
1771 enum fullness_group fullness;
1773 fullness = get_fullness_group(class, zspage);
1774 insert_zspage(class, zspage, fullness);
1775 set_zspage_mapping(zspage, class->index, fullness);
1780 #ifdef CONFIG_COMPACTION
1782 * To prevent zspage destroy during migration, zspage freeing should
1783 * hold locks of all pages in the zspage.
1785 static void lock_zspage(struct zspage *zspage)
1787 struct page *curr_page, *page;
1790 * Pages we haven't locked yet can be migrated off the list while we're
1791 * trying to lock them, so we need to be careful and only attempt to
1792 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1793 * may no longer belong to the zspage. This means that we may wait for
1794 * the wrong page to unlock, so we must take a reference to the page
1795 * prior to waiting for it to unlock outside migrate_read_lock().
1798 migrate_read_lock(zspage);
1799 page = get_first_page(zspage);
1800 if (trylock_page(page))
1803 migrate_read_unlock(zspage);
1804 wait_on_page_locked(page);
1809 while ((page = get_next_page(curr_page))) {
1810 if (trylock_page(page)) {
1814 migrate_read_unlock(zspage);
1815 wait_on_page_locked(page);
1817 migrate_read_lock(zspage);
1820 migrate_read_unlock(zspage);
1823 static void migrate_lock_init(struct zspage *zspage)
1825 rwlock_init(&zspage->lock);
1828 static void migrate_read_lock(struct zspage *zspage) __acquires(&zspage->lock)
1830 read_lock(&zspage->lock);
1833 static void migrate_read_unlock(struct zspage *zspage) __releases(&zspage->lock)
1835 read_unlock(&zspage->lock);
1838 static void migrate_write_lock(struct zspage *zspage)
1840 write_lock(&zspage->lock);
1843 static void migrate_write_lock_nested(struct zspage *zspage)
1845 write_lock_nested(&zspage->lock, SINGLE_DEPTH_NESTING);
1848 static void migrate_write_unlock(struct zspage *zspage)
1850 write_unlock(&zspage->lock);
1853 /* Number of isolated subpage for *page migration* in this zspage */
1854 static void inc_zspage_isolation(struct zspage *zspage)
1859 static void dec_zspage_isolation(struct zspage *zspage)
1861 VM_BUG_ON(zspage->isolated == 0);
1865 static const struct movable_operations zsmalloc_mops;
1867 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1868 struct page *newpage, struct page *oldpage)
1871 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1874 page = get_first_page(zspage);
1876 if (page == oldpage)
1877 pages[idx] = newpage;
1881 } while ((page = get_next_page(page)) != NULL);
1883 create_page_chain(class, zspage, pages);
1884 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1885 if (unlikely(ZsHugePage(zspage)))
1886 newpage->index = oldpage->index;
1887 __SetPageMovable(newpage, &zsmalloc_mops);
1890 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1892 struct zspage *zspage;
1895 * Page is locked so zspage couldn't be destroyed. For detail, look at
1896 * lock_zspage in free_zspage.
1898 VM_BUG_ON_PAGE(!PageMovable(page), page);
1899 VM_BUG_ON_PAGE(PageIsolated(page), page);
1901 zspage = get_zspage(page);
1902 migrate_write_lock(zspage);
1903 inc_zspage_isolation(zspage);
1904 migrate_write_unlock(zspage);
1909 static int zs_page_migrate(struct page *newpage, struct page *page,
1910 enum migrate_mode mode)
1912 struct zs_pool *pool;
1913 struct size_class *class;
1914 struct zspage *zspage;
1916 void *s_addr, *d_addr, *addr;
1917 unsigned int offset;
1918 unsigned long handle;
1919 unsigned long old_obj, new_obj;
1920 unsigned int obj_idx;
1923 * We cannot support the _NO_COPY case here, because copy needs to
1924 * happen under the zs lock, which does not work with
1925 * MIGRATE_SYNC_NO_COPY workflow.
1927 if (mode == MIGRATE_SYNC_NO_COPY)
1930 VM_BUG_ON_PAGE(!PageMovable(page), page);
1931 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1933 /* The page is locked, so this pointer must remain valid */
1934 zspage = get_zspage(page);
1935 pool = zspage->pool;
1938 * The pool's lock protects the race between zpage migration
1941 spin_lock(&pool->lock);
1942 class = zspage_class(pool, zspage);
1944 /* the migrate_write_lock protects zpage access via zs_map_object */
1945 migrate_write_lock(zspage);
1947 offset = get_first_obj_offset(page);
1948 s_addr = kmap_atomic(page);
1951 * Here, any user cannot access all objects in the zspage so let's move.
1953 d_addr = kmap_atomic(newpage);
1954 memcpy(d_addr, s_addr, PAGE_SIZE);
1955 kunmap_atomic(d_addr);
1957 for (addr = s_addr + offset; addr < s_addr + PAGE_SIZE;
1958 addr += class->size) {
1959 if (obj_allocated(page, addr, &handle)) {
1961 old_obj = handle_to_obj(handle);
1962 obj_to_location(old_obj, &dummy, &obj_idx);
1963 new_obj = (unsigned long)location_to_obj(newpage,
1965 record_obj(handle, new_obj);
1968 kunmap_atomic(s_addr);
1970 replace_sub_page(class, zspage, newpage, page);
1972 * Since we complete the data copy and set up new zspage structure,
1973 * it's okay to release the pool's lock.
1975 spin_unlock(&pool->lock);
1976 dec_zspage_isolation(zspage);
1977 migrate_write_unlock(zspage);
1980 if (page_zone(newpage) != page_zone(page)) {
1981 dec_zone_page_state(page, NR_ZSPAGES);
1982 inc_zone_page_state(newpage, NR_ZSPAGES);
1988 return MIGRATEPAGE_SUCCESS;
1991 static void zs_page_putback(struct page *page)
1993 struct zspage *zspage;
1995 VM_BUG_ON_PAGE(!PageMovable(page), page);
1996 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1998 zspage = get_zspage(page);
1999 migrate_write_lock(zspage);
2000 dec_zspage_isolation(zspage);
2001 migrate_write_unlock(zspage);
2004 static const struct movable_operations zsmalloc_mops = {
2005 .isolate_page = zs_page_isolate,
2006 .migrate_page = zs_page_migrate,
2007 .putback_page = zs_page_putback,
2011 * Caller should hold page_lock of all pages in the zspage
2012 * In here, we cannot use zspage meta data.
2014 static void async_free_zspage(struct work_struct *work)
2017 struct size_class *class;
2018 unsigned int class_idx;
2019 enum fullness_group fullness;
2020 struct zspage *zspage, *tmp;
2021 LIST_HEAD(free_pages);
2022 struct zs_pool *pool = container_of(work, struct zs_pool,
2025 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2026 class = pool->size_class[i];
2027 if (class->index != i)
2030 spin_lock(&pool->lock);
2031 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2032 spin_unlock(&pool->lock);
2035 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2036 list_del(&zspage->list);
2037 lock_zspage(zspage);
2039 get_zspage_mapping(zspage, &class_idx, &fullness);
2040 VM_BUG_ON(fullness != ZS_EMPTY);
2041 class = pool->size_class[class_idx];
2042 spin_lock(&pool->lock);
2044 list_del(&zspage->lru);
2046 __free_zspage(pool, class, zspage);
2047 spin_unlock(&pool->lock);
2051 static void kick_deferred_free(struct zs_pool *pool)
2053 schedule_work(&pool->free_work);
2056 static void zs_flush_migration(struct zs_pool *pool)
2058 flush_work(&pool->free_work);
2061 static void init_deferred_free(struct zs_pool *pool)
2063 INIT_WORK(&pool->free_work, async_free_zspage);
2066 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2068 struct page *page = get_first_page(zspage);
2071 WARN_ON(!trylock_page(page));
2072 __SetPageMovable(page, &zsmalloc_mops);
2074 } while ((page = get_next_page(page)) != NULL);
2077 static inline void zs_flush_migration(struct zs_pool *pool) { }
2082 * Based on the number of unused allocated objects calculate
2083 * and return the number of pages that we can free.
2085 static unsigned long zs_can_compact(struct size_class *class)
2087 unsigned long obj_wasted;
2088 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2089 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2091 if (obj_allocated <= obj_used)
2094 obj_wasted = obj_allocated - obj_used;
2095 obj_wasted /= class->objs_per_zspage;
2097 return obj_wasted * class->pages_per_zspage;
2100 static unsigned long __zs_compact(struct zs_pool *pool,
2101 struct size_class *class)
2103 struct zs_compact_control cc;
2104 struct zspage *src_zspage;
2105 struct zspage *dst_zspage = NULL;
2106 unsigned long pages_freed = 0;
2109 * protect the race between zpage migration and zs_free
2110 * as well as zpage allocation/free
2112 spin_lock(&pool->lock);
2113 while ((src_zspage = isolate_zspage(class, true))) {
2114 /* protect someone accessing the zspage(i.e., zs_map_object) */
2115 migrate_write_lock(src_zspage);
2117 if (!zs_can_compact(class))
2121 cc.s_page = get_first_page(src_zspage);
2123 while ((dst_zspage = isolate_zspage(class, false))) {
2124 migrate_write_lock_nested(dst_zspage);
2126 cc.d_page = get_first_page(dst_zspage);
2128 * If there is no more space in dst_page, resched
2129 * and see if anyone had allocated another zspage.
2131 if (!migrate_zspage(pool, class, &cc))
2134 putback_zspage(class, dst_zspage);
2135 migrate_write_unlock(dst_zspage);
2137 if (spin_is_contended(&pool->lock))
2141 /* Stop if we couldn't find slot */
2142 if (dst_zspage == NULL)
2145 putback_zspage(class, dst_zspage);
2146 migrate_write_unlock(dst_zspage);
2148 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2149 migrate_write_unlock(src_zspage);
2150 free_zspage(pool, class, src_zspage);
2151 pages_freed += class->pages_per_zspage;
2153 migrate_write_unlock(src_zspage);
2154 spin_unlock(&pool->lock);
2156 spin_lock(&pool->lock);
2160 putback_zspage(class, src_zspage);
2161 migrate_write_unlock(src_zspage);
2164 spin_unlock(&pool->lock);
2169 unsigned long zs_compact(struct zs_pool *pool)
2172 struct size_class *class;
2173 unsigned long pages_freed = 0;
2175 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2176 class = pool->size_class[i];
2177 if (class->index != i)
2179 pages_freed += __zs_compact(pool, class);
2181 atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2185 EXPORT_SYMBOL_GPL(zs_compact);
2187 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2189 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2191 EXPORT_SYMBOL_GPL(zs_pool_stats);
2193 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2194 struct shrink_control *sc)
2196 unsigned long pages_freed;
2197 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2201 * Compact classes and calculate compaction delta.
2202 * Can run concurrently with a manually triggered
2203 * (by user) compaction.
2205 pages_freed = zs_compact(pool);
2207 return pages_freed ? pages_freed : SHRINK_STOP;
2210 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2211 struct shrink_control *sc)
2214 struct size_class *class;
2215 unsigned long pages_to_free = 0;
2216 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2219 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2220 class = pool->size_class[i];
2221 if (class->index != i)
2224 pages_to_free += zs_can_compact(class);
2227 return pages_to_free;
2230 static void zs_unregister_shrinker(struct zs_pool *pool)
2232 unregister_shrinker(&pool->shrinker);
2235 static int zs_register_shrinker(struct zs_pool *pool)
2237 pool->shrinker.scan_objects = zs_shrinker_scan;
2238 pool->shrinker.count_objects = zs_shrinker_count;
2239 pool->shrinker.batch = 0;
2240 pool->shrinker.seeks = DEFAULT_SEEKS;
2242 return register_shrinker(&pool->shrinker, "mm-zspool:%s",
2247 * zs_create_pool - Creates an allocation pool to work from.
2248 * @name: pool name to be created
2250 * This function must be called before anything when using
2251 * the zsmalloc allocator.
2253 * On success, a pointer to the newly created pool is returned,
2256 struct zs_pool *zs_create_pool(const char *name)
2259 struct zs_pool *pool;
2260 struct size_class *prev_class = NULL;
2262 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2266 init_deferred_free(pool);
2267 spin_lock_init(&pool->lock);
2269 pool->name = kstrdup(name, GFP_KERNEL);
2273 if (create_cache(pool))
2277 * Iterate reversely, because, size of size_class that we want to use
2278 * for merging should be larger or equal to current size.
2280 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2282 int pages_per_zspage;
2283 int objs_per_zspage;
2284 struct size_class *class;
2287 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2288 if (size > ZS_MAX_ALLOC_SIZE)
2289 size = ZS_MAX_ALLOC_SIZE;
2290 pages_per_zspage = get_pages_per_zspage(size);
2291 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2294 * We iterate from biggest down to smallest classes,
2295 * so huge_class_size holds the size of the first huge
2296 * class. Any object bigger than or equal to that will
2297 * endup in the huge class.
2299 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2301 huge_class_size = size;
2303 * The object uses ZS_HANDLE_SIZE bytes to store the
2304 * handle. We need to subtract it, because zs_malloc()
2305 * unconditionally adds handle size before it performs
2306 * size class search - so object may be smaller than
2307 * huge class size, yet it still can end up in the huge
2308 * class because it grows by ZS_HANDLE_SIZE extra bytes
2309 * right before class lookup.
2311 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2315 * size_class is used for normal zsmalloc operation such
2316 * as alloc/free for that size. Although it is natural that we
2317 * have one size_class for each size, there is a chance that we
2318 * can get more memory utilization if we use one size_class for
2319 * many different sizes whose size_class have same
2320 * characteristics. So, we makes size_class point to
2321 * previous size_class if possible.
2324 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2325 pool->size_class[i] = prev_class;
2330 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2336 class->pages_per_zspage = pages_per_zspage;
2337 class->objs_per_zspage = objs_per_zspage;
2338 pool->size_class[i] = class;
2339 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2341 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2346 /* debug only, don't abort if it fails */
2347 zs_pool_stat_create(pool, name);
2350 * Not critical since shrinker is only used to trigger internal
2351 * defragmentation of the pool which is pretty optional thing. If
2352 * registration fails we still can use the pool normally and user can
2353 * trigger compaction manually. Thus, ignore return code.
2355 zs_register_shrinker(pool);
2358 INIT_LIST_HEAD(&pool->lru);
2364 zs_destroy_pool(pool);
2367 EXPORT_SYMBOL_GPL(zs_create_pool);
2369 void zs_destroy_pool(struct zs_pool *pool)
2373 zs_unregister_shrinker(pool);
2374 zs_flush_migration(pool);
2375 zs_pool_stat_destroy(pool);
2377 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2379 struct size_class *class = pool->size_class[i];
2384 if (class->index != i)
2387 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2388 if (!list_empty(&class->fullness_list[fg])) {
2389 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2396 destroy_cache(pool);
2400 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2402 static int __init zs_init(void)
2406 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2407 zs_cpu_prepare, zs_cpu_dead);
2412 zpool_register_driver(&zs_zpool_driver);
2423 static void __exit zs_exit(void)
2426 zpool_unregister_driver(&zs_zpool_driver);
2428 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2433 module_init(zs_init);
2434 module_exit(zs_exit);
2436 MODULE_LICENSE("Dual BSD/GPL");
2437 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");