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;
242 #ifdef CONFIG_ZSMALLOC_STAT
243 struct dentry *stat_dentry;
245 #ifdef CONFIG_COMPACTION
246 struct work_struct free_work;
249 atomic_t compaction_in_progress;
254 unsigned int huge:HUGE_BITS;
255 unsigned int fullness:FULLNESS_BITS;
256 unsigned int class:CLASS_BITS + 1;
257 unsigned int isolated:ISOLATED_BITS;
258 unsigned int magic:MAGIC_VAL_BITS;
261 unsigned int freeobj;
262 struct page *first_page;
263 struct list_head list; /* fullness list */
264 struct zs_pool *pool;
265 #ifdef CONFIG_COMPACTION
270 struct mapping_area {
272 char *vm_buf; /* copy buffer for objects that span pages */
273 char *vm_addr; /* address of kmap_atomic()'ed pages */
274 enum zs_mapmode vm_mm; /* mapping mode */
277 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
278 static void SetZsHugePage(struct zspage *zspage)
283 static bool ZsHugePage(struct zspage *zspage)
288 #ifdef CONFIG_COMPACTION
289 static void migrate_lock_init(struct zspage *zspage);
290 static void migrate_read_lock(struct zspage *zspage);
291 static void migrate_read_unlock(struct zspage *zspage);
292 static void migrate_write_lock(struct zspage *zspage);
293 static void migrate_write_lock_nested(struct zspage *zspage);
294 static void migrate_write_unlock(struct zspage *zspage);
295 static void kick_deferred_free(struct zs_pool *pool);
296 static void init_deferred_free(struct zs_pool *pool);
297 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
299 static void migrate_lock_init(struct zspage *zspage) {}
300 static void migrate_read_lock(struct zspage *zspage) {}
301 static void migrate_read_unlock(struct zspage *zspage) {}
302 static void migrate_write_lock(struct zspage *zspage) {}
303 static void migrate_write_lock_nested(struct zspage *zspage) {}
304 static void migrate_write_unlock(struct zspage *zspage) {}
305 static void kick_deferred_free(struct zs_pool *pool) {}
306 static void init_deferred_free(struct zs_pool *pool) {}
307 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
310 static int create_cache(struct zs_pool *pool)
312 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
314 if (!pool->handle_cachep)
317 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
319 if (!pool->zspage_cachep) {
320 kmem_cache_destroy(pool->handle_cachep);
321 pool->handle_cachep = NULL;
328 static void destroy_cache(struct zs_pool *pool)
330 kmem_cache_destroy(pool->handle_cachep);
331 kmem_cache_destroy(pool->zspage_cachep);
334 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
336 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
337 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
340 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
342 kmem_cache_free(pool->handle_cachep, (void *)handle);
345 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
347 return kmem_cache_zalloc(pool->zspage_cachep,
348 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
351 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
353 kmem_cache_free(pool->zspage_cachep, zspage);
356 /* pool->lock(which owns the handle) synchronizes races */
357 static void record_obj(unsigned long handle, unsigned long obj)
359 *(unsigned long *)handle = obj;
366 static void *zs_zpool_create(const char *name, gfp_t gfp,
367 const struct zpool_ops *zpool_ops,
371 * Ignore global gfp flags: zs_malloc() may be invoked from
372 * different contexts and its caller must provide a valid
375 return zs_create_pool(name);
378 static void zs_zpool_destroy(void *pool)
380 zs_destroy_pool(pool);
383 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
384 unsigned long *handle)
386 *handle = zs_malloc(pool, size, gfp);
388 if (IS_ERR((void *)(*handle)))
389 return PTR_ERR((void *)*handle);
392 static void zs_zpool_free(void *pool, unsigned long handle)
394 zs_free(pool, handle);
397 static void *zs_zpool_map(void *pool, unsigned long handle,
398 enum zpool_mapmode mm)
400 enum zs_mapmode zs_mm;
415 return zs_map_object(pool, handle, zs_mm);
417 static void zs_zpool_unmap(void *pool, unsigned long handle)
419 zs_unmap_object(pool, handle);
422 static u64 zs_zpool_total_size(void *pool)
424 return zs_get_total_pages(pool) << PAGE_SHIFT;
427 static struct zpool_driver zs_zpool_driver = {
429 .owner = THIS_MODULE,
430 .create = zs_zpool_create,
431 .destroy = zs_zpool_destroy,
432 .malloc_support_movable = true,
433 .malloc = zs_zpool_malloc,
434 .free = zs_zpool_free,
436 .unmap = zs_zpool_unmap,
437 .total_size = zs_zpool_total_size,
440 MODULE_ALIAS("zpool-zsmalloc");
441 #endif /* CONFIG_ZPOOL */
443 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
444 static DEFINE_PER_CPU(struct mapping_area, zs_map_area) = {
445 .lock = INIT_LOCAL_LOCK(lock),
448 static __maybe_unused int is_first_page(struct page *page)
450 return PagePrivate(page);
453 /* Protected by pool->lock */
454 static inline int get_zspage_inuse(struct zspage *zspage)
456 return zspage->inuse;
460 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
462 zspage->inuse += val;
465 static inline struct page *get_first_page(struct zspage *zspage)
467 struct page *first_page = zspage->first_page;
469 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
473 static inline unsigned int get_first_obj_offset(struct page *page)
475 return page->page_type;
478 static inline void set_first_obj_offset(struct page *page, unsigned int offset)
480 page->page_type = offset;
483 static inline unsigned int get_freeobj(struct zspage *zspage)
485 return zspage->freeobj;
488 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
490 zspage->freeobj = obj;
493 static void get_zspage_mapping(struct zspage *zspage,
494 unsigned int *class_idx,
495 enum fullness_group *fullness)
497 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
499 *fullness = zspage->fullness;
500 *class_idx = zspage->class;
503 static struct size_class *zspage_class(struct zs_pool *pool,
504 struct zspage *zspage)
506 return pool->size_class[zspage->class];
509 static void set_zspage_mapping(struct zspage *zspage,
510 unsigned int class_idx,
511 enum fullness_group fullness)
513 zspage->class = class_idx;
514 zspage->fullness = fullness;
518 * zsmalloc divides the pool into various size classes where each
519 * class maintains a list of zspages where each zspage is divided
520 * into equal sized chunks. Each allocation falls into one of these
521 * classes depending on its size. This function returns index of the
522 * size class which has chunk size big enough to hold the given size.
524 static int get_size_class_index(int size)
528 if (likely(size > ZS_MIN_ALLOC_SIZE))
529 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
530 ZS_SIZE_CLASS_DELTA);
532 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
535 /* type can be of enum type class_stat_type or fullness_group */
536 static inline void class_stat_inc(struct size_class *class,
537 int type, unsigned long cnt)
539 class->stats.objs[type] += cnt;
542 /* type can be of enum type class_stat_type or fullness_group */
543 static inline void class_stat_dec(struct size_class *class,
544 int type, unsigned long cnt)
546 class->stats.objs[type] -= cnt;
549 /* type can be of enum type class_stat_type or fullness_group */
550 static inline unsigned long zs_stat_get(struct size_class *class,
553 return class->stats.objs[type];
556 #ifdef CONFIG_ZSMALLOC_STAT
558 static void __init zs_stat_init(void)
560 if (!debugfs_initialized()) {
561 pr_warn("debugfs not available, stat dir not created\n");
565 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
568 static void __exit zs_stat_exit(void)
570 debugfs_remove_recursive(zs_stat_root);
573 static unsigned long zs_can_compact(struct size_class *class);
575 static int zs_stats_size_show(struct seq_file *s, void *v)
578 struct zs_pool *pool = s->private;
579 struct size_class *class;
581 unsigned long class_almost_full, class_almost_empty;
582 unsigned long obj_allocated, obj_used, pages_used, freeable;
583 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
584 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
585 unsigned long total_freeable = 0;
587 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
588 "class", "size", "almost_full", "almost_empty",
589 "obj_allocated", "obj_used", "pages_used",
590 "pages_per_zspage", "freeable");
592 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
593 class = pool->size_class[i];
595 if (class->index != i)
598 spin_lock(&pool->lock);
599 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
600 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
601 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
602 obj_used = zs_stat_get(class, OBJ_USED);
603 freeable = zs_can_compact(class);
604 spin_unlock(&pool->lock);
606 objs_per_zspage = class->objs_per_zspage;
607 pages_used = obj_allocated / objs_per_zspage *
608 class->pages_per_zspage;
610 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
611 " %10lu %10lu %16d %8lu\n",
612 i, class->size, class_almost_full, class_almost_empty,
613 obj_allocated, obj_used, pages_used,
614 class->pages_per_zspage, freeable);
616 total_class_almost_full += class_almost_full;
617 total_class_almost_empty += class_almost_empty;
618 total_objs += obj_allocated;
619 total_used_objs += obj_used;
620 total_pages += pages_used;
621 total_freeable += freeable;
625 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
626 "Total", "", total_class_almost_full,
627 total_class_almost_empty, total_objs,
628 total_used_objs, total_pages, "", total_freeable);
632 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
634 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
637 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
641 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
643 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
644 &zs_stats_size_fops);
647 static void zs_pool_stat_destroy(struct zs_pool *pool)
649 debugfs_remove_recursive(pool->stat_dentry);
652 #else /* CONFIG_ZSMALLOC_STAT */
653 static void __init zs_stat_init(void)
657 static void __exit zs_stat_exit(void)
661 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
665 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
672 * For each size class, zspages are divided into different groups
673 * depending on how "full" they are. This was done so that we could
674 * easily find empty or nearly empty zspages when we try to shrink
675 * the pool (not yet implemented). This function returns fullness
676 * status of the given page.
678 static enum fullness_group get_fullness_group(struct size_class *class,
679 struct zspage *zspage)
681 int inuse, objs_per_zspage;
682 enum fullness_group fg;
684 inuse = get_zspage_inuse(zspage);
685 objs_per_zspage = class->objs_per_zspage;
689 else if (inuse == objs_per_zspage)
691 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
692 fg = ZS_ALMOST_EMPTY;
700 * Each size class maintains various freelists and zspages are assigned
701 * to one of these freelists based on the number of live objects they
702 * have. This functions inserts the given zspage into the freelist
703 * identified by <class, fullness_group>.
705 static void insert_zspage(struct size_class *class,
706 struct zspage *zspage,
707 enum fullness_group fullness)
711 class_stat_inc(class, fullness, 1);
712 head = list_first_entry_or_null(&class->fullness_list[fullness],
713 struct zspage, list);
715 * We want to see more ZS_FULL pages and less almost empty/full.
716 * Put pages with higher ->inuse first.
718 if (head && get_zspage_inuse(zspage) < get_zspage_inuse(head))
719 list_add(&zspage->list, &head->list);
721 list_add(&zspage->list, &class->fullness_list[fullness]);
725 * This function removes the given zspage from the freelist identified
726 * by <class, fullness_group>.
728 static void remove_zspage(struct size_class *class,
729 struct zspage *zspage,
730 enum fullness_group fullness)
732 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
734 list_del_init(&zspage->list);
735 class_stat_dec(class, fullness, 1);
739 * Each size class maintains zspages in different fullness groups depending
740 * on the number of live objects they contain. When allocating or freeing
741 * objects, the fullness status of the page can change, say, from ALMOST_FULL
742 * to ALMOST_EMPTY when freeing an object. This function checks if such
743 * a status change has occurred for the given page and accordingly moves the
744 * page from the freelist of the old fullness group to that of the new
747 static enum fullness_group fix_fullness_group(struct size_class *class,
748 struct zspage *zspage)
751 enum fullness_group currfg, newfg;
753 get_zspage_mapping(zspage, &class_idx, &currfg);
754 newfg = get_fullness_group(class, zspage);
758 remove_zspage(class, zspage, currfg);
759 insert_zspage(class, zspage, newfg);
760 set_zspage_mapping(zspage, class_idx, newfg);
766 * We have to decide on how many pages to link together
767 * to form a zspage for each size class. This is important
768 * to reduce wastage due to unusable space left at end of
769 * each zspage which is given as:
770 * wastage = Zp % class_size
771 * usage = Zp - wastage
772 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
774 * For example, for size class of 3/8 * PAGE_SIZE, we should
775 * link together 3 PAGE_SIZE sized pages to form a zspage
776 * since then we can perfectly fit in 8 such objects.
778 static int get_pages_per_zspage(int class_size)
780 int i, max_usedpc = 0;
781 /* zspage order which gives maximum used size per KB */
782 int max_usedpc_order = 1;
784 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
788 zspage_size = i * PAGE_SIZE;
789 waste = zspage_size % class_size;
790 usedpc = (zspage_size - waste) * 100 / zspage_size;
792 if (usedpc > max_usedpc) {
794 max_usedpc_order = i;
798 return max_usedpc_order;
801 static struct zspage *get_zspage(struct page *page)
803 struct zspage *zspage = (struct zspage *)page_private(page);
805 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
809 static struct page *get_next_page(struct page *page)
811 struct zspage *zspage = get_zspage(page);
813 if (unlikely(ZsHugePage(zspage)))
816 return (struct page *)page->index;
820 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
821 * @obj: the encoded object value
822 * @page: page object resides in zspage
823 * @obj_idx: object index
825 static void obj_to_location(unsigned long obj, struct page **page,
826 unsigned int *obj_idx)
828 obj >>= OBJ_TAG_BITS;
829 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
830 *obj_idx = (obj & OBJ_INDEX_MASK);
833 static void obj_to_page(unsigned long obj, struct page **page)
835 obj >>= OBJ_TAG_BITS;
836 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
840 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
841 * @page: page object resides in zspage
842 * @obj_idx: object index
844 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
848 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
849 obj |= obj_idx & OBJ_INDEX_MASK;
850 obj <<= OBJ_TAG_BITS;
855 static unsigned long handle_to_obj(unsigned long handle)
857 return *(unsigned long *)handle;
860 static bool obj_allocated(struct page *page, void *obj, unsigned long *phandle)
862 unsigned long handle;
863 struct zspage *zspage = get_zspage(page);
865 if (unlikely(ZsHugePage(zspage))) {
866 VM_BUG_ON_PAGE(!is_first_page(page), page);
867 handle = page->index;
869 handle = *(unsigned long *)obj;
871 if (!(handle & OBJ_ALLOCATED_TAG))
874 *phandle = handle & ~OBJ_ALLOCATED_TAG;
878 static void reset_page(struct page *page)
880 __ClearPageMovable(page);
881 ClearPagePrivate(page);
882 set_page_private(page, 0);
883 page_mapcount_reset(page);
887 static int trylock_zspage(struct zspage *zspage)
889 struct page *cursor, *fail;
891 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
892 get_next_page(cursor)) {
893 if (!trylock_page(cursor)) {
901 for (cursor = get_first_page(zspage); cursor != fail; cursor =
902 get_next_page(cursor))
908 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
909 struct zspage *zspage)
911 struct page *page, *next;
912 enum fullness_group fg;
913 unsigned int class_idx;
915 get_zspage_mapping(zspage, &class_idx, &fg);
917 assert_spin_locked(&pool->lock);
919 VM_BUG_ON(get_zspage_inuse(zspage));
920 VM_BUG_ON(fg != ZS_EMPTY);
922 next = page = get_first_page(zspage);
924 VM_BUG_ON_PAGE(!PageLocked(page), page);
925 next = get_next_page(page);
928 dec_zone_page_state(page, NR_ZSPAGES);
931 } while (page != NULL);
933 cache_free_zspage(pool, zspage);
935 class_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
936 atomic_long_sub(class->pages_per_zspage,
937 &pool->pages_allocated);
940 static void free_zspage(struct zs_pool *pool, struct size_class *class,
941 struct zspage *zspage)
943 VM_BUG_ON(get_zspage_inuse(zspage));
944 VM_BUG_ON(list_empty(&zspage->list));
947 * Since zs_free couldn't be sleepable, this function cannot call
948 * lock_page. The page locks trylock_zspage got will be released
951 if (!trylock_zspage(zspage)) {
952 kick_deferred_free(pool);
956 remove_zspage(class, zspage, ZS_EMPTY);
957 __free_zspage(pool, class, zspage);
960 /* Initialize a newly allocated zspage */
961 static void init_zspage(struct size_class *class, struct zspage *zspage)
963 unsigned int freeobj = 1;
964 unsigned long off = 0;
965 struct page *page = get_first_page(zspage);
968 struct page *next_page;
969 struct link_free *link;
972 set_first_obj_offset(page, off);
974 vaddr = kmap_atomic(page);
975 link = (struct link_free *)vaddr + off / sizeof(*link);
977 while ((off += class->size) < PAGE_SIZE) {
978 link->next = freeobj++ << OBJ_TAG_BITS;
979 link += class->size / sizeof(*link);
983 * We now come to the last (full or partial) object on this
984 * page, which must point to the first object on the next
987 next_page = get_next_page(page);
989 link->next = freeobj++ << OBJ_TAG_BITS;
992 * Reset OBJ_TAG_BITS bit to last link to tell
993 * whether it's allocated object or not.
995 link->next = -1UL << OBJ_TAG_BITS;
997 kunmap_atomic(vaddr);
1002 set_freeobj(zspage, 0);
1005 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1006 struct page *pages[])
1010 struct page *prev_page = NULL;
1011 int nr_pages = class->pages_per_zspage;
1014 * Allocate individual pages and link them together as:
1015 * 1. all pages are linked together using page->index
1016 * 2. each sub-page point to zspage using page->private
1018 * we set PG_private to identify the first page (i.e. no other sub-page
1019 * has this flag set).
1021 for (i = 0; i < nr_pages; i++) {
1023 set_page_private(page, (unsigned long)zspage);
1026 zspage->first_page = page;
1027 SetPagePrivate(page);
1028 if (unlikely(class->objs_per_zspage == 1 &&
1029 class->pages_per_zspage == 1))
1030 SetZsHugePage(zspage);
1032 prev_page->index = (unsigned long)page;
1039 * Allocate a zspage for the given size class
1041 static struct zspage *alloc_zspage(struct zs_pool *pool,
1042 struct size_class *class,
1046 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1047 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1052 zspage->magic = ZSPAGE_MAGIC;
1053 migrate_lock_init(zspage);
1055 for (i = 0; i < class->pages_per_zspage; i++) {
1058 page = alloc_page(gfp);
1061 dec_zone_page_state(pages[i], NR_ZSPAGES);
1062 __free_page(pages[i]);
1064 cache_free_zspage(pool, zspage);
1068 inc_zone_page_state(page, NR_ZSPAGES);
1072 create_page_chain(class, zspage, pages);
1073 init_zspage(class, zspage);
1074 zspage->pool = pool;
1079 static struct zspage *find_get_zspage(struct size_class *class)
1082 struct zspage *zspage;
1084 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1085 zspage = list_first_entry_or_null(&class->fullness_list[i],
1086 struct zspage, list);
1094 static inline int __zs_cpu_up(struct mapping_area *area)
1097 * Make sure we don't leak memory if a cpu UP notification
1098 * and zs_init() race and both call zs_cpu_up() on the same cpu
1102 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1108 static inline void __zs_cpu_down(struct mapping_area *area)
1110 kfree(area->vm_buf);
1111 area->vm_buf = NULL;
1114 static void *__zs_map_object(struct mapping_area *area,
1115 struct page *pages[2], int off, int size)
1119 char *buf = area->vm_buf;
1121 /* disable page faults to match kmap_atomic() return conditions */
1122 pagefault_disable();
1124 /* no read fastpath */
1125 if (area->vm_mm == ZS_MM_WO)
1128 sizes[0] = PAGE_SIZE - off;
1129 sizes[1] = size - sizes[0];
1131 /* copy object to per-cpu buffer */
1132 addr = kmap_atomic(pages[0]);
1133 memcpy(buf, addr + off, sizes[0]);
1134 kunmap_atomic(addr);
1135 addr = kmap_atomic(pages[1]);
1136 memcpy(buf + sizes[0], addr, sizes[1]);
1137 kunmap_atomic(addr);
1139 return area->vm_buf;
1142 static void __zs_unmap_object(struct mapping_area *area,
1143 struct page *pages[2], int off, int size)
1149 /* no write fastpath */
1150 if (area->vm_mm == ZS_MM_RO)
1154 buf = buf + ZS_HANDLE_SIZE;
1155 size -= ZS_HANDLE_SIZE;
1156 off += ZS_HANDLE_SIZE;
1158 sizes[0] = PAGE_SIZE - off;
1159 sizes[1] = size - sizes[0];
1161 /* copy per-cpu buffer to object */
1162 addr = kmap_atomic(pages[0]);
1163 memcpy(addr + off, buf, sizes[0]);
1164 kunmap_atomic(addr);
1165 addr = kmap_atomic(pages[1]);
1166 memcpy(addr, buf + sizes[0], sizes[1]);
1167 kunmap_atomic(addr);
1170 /* enable page faults to match kunmap_atomic() return conditions */
1174 static int zs_cpu_prepare(unsigned int cpu)
1176 struct mapping_area *area;
1178 area = &per_cpu(zs_map_area, cpu);
1179 return __zs_cpu_up(area);
1182 static int zs_cpu_dead(unsigned int cpu)
1184 struct mapping_area *area;
1186 area = &per_cpu(zs_map_area, cpu);
1187 __zs_cpu_down(area);
1191 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1192 int objs_per_zspage)
1194 if (prev->pages_per_zspage == pages_per_zspage &&
1195 prev->objs_per_zspage == objs_per_zspage)
1201 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1203 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1206 unsigned long zs_get_total_pages(struct zs_pool *pool)
1208 return atomic_long_read(&pool->pages_allocated);
1210 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1213 * zs_map_object - get address of allocated object from handle.
1214 * @pool: pool from which the object was allocated
1215 * @handle: handle returned from zs_malloc
1216 * @mm: mapping mode to use
1218 * Before using an object allocated from zs_malloc, it must be mapped using
1219 * this function. When done with the object, it must be unmapped using
1222 * Only one object can be mapped per cpu at a time. There is no protection
1223 * against nested mappings.
1225 * This function returns with preemption and page faults disabled.
1227 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1230 struct zspage *zspage;
1232 unsigned long obj, off;
1233 unsigned int obj_idx;
1235 struct size_class *class;
1236 struct mapping_area *area;
1237 struct page *pages[2];
1241 * Because we use per-cpu mapping areas shared among the
1242 * pools/users, we can't allow mapping in interrupt context
1243 * because it can corrupt another users mappings.
1245 BUG_ON(in_interrupt());
1247 /* It guarantees it can get zspage from handle safely */
1248 spin_lock(&pool->lock);
1249 obj = handle_to_obj(handle);
1250 obj_to_location(obj, &page, &obj_idx);
1251 zspage = get_zspage(page);
1254 * migration cannot move any zpages in this zspage. Here, pool->lock
1255 * is too heavy since callers would take some time until they calls
1256 * zs_unmap_object API so delegate the locking from class to zspage
1257 * which is smaller granularity.
1259 migrate_read_lock(zspage);
1260 spin_unlock(&pool->lock);
1262 class = zspage_class(pool, zspage);
1263 off = (class->size * obj_idx) & ~PAGE_MASK;
1265 local_lock(&zs_map_area.lock);
1266 area = this_cpu_ptr(&zs_map_area);
1268 if (off + class->size <= PAGE_SIZE) {
1269 /* this object is contained entirely within a page */
1270 area->vm_addr = kmap_atomic(page);
1271 ret = area->vm_addr + off;
1275 /* this object spans two pages */
1277 pages[1] = get_next_page(page);
1280 ret = __zs_map_object(area, pages, off, class->size);
1282 if (likely(!ZsHugePage(zspage)))
1283 ret += ZS_HANDLE_SIZE;
1287 EXPORT_SYMBOL_GPL(zs_map_object);
1289 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1291 struct zspage *zspage;
1293 unsigned long obj, off;
1294 unsigned int obj_idx;
1296 struct size_class *class;
1297 struct mapping_area *area;
1299 obj = handle_to_obj(handle);
1300 obj_to_location(obj, &page, &obj_idx);
1301 zspage = get_zspage(page);
1302 class = zspage_class(pool, zspage);
1303 off = (class->size * obj_idx) & ~PAGE_MASK;
1305 area = this_cpu_ptr(&zs_map_area);
1306 if (off + class->size <= PAGE_SIZE)
1307 kunmap_atomic(area->vm_addr);
1309 struct page *pages[2];
1312 pages[1] = get_next_page(page);
1315 __zs_unmap_object(area, pages, off, class->size);
1317 local_unlock(&zs_map_area.lock);
1319 migrate_read_unlock(zspage);
1321 EXPORT_SYMBOL_GPL(zs_unmap_object);
1324 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1325 * zsmalloc &size_class.
1326 * @pool: zsmalloc pool to use
1328 * The function returns the size of the first huge class - any object of equal
1329 * or bigger size will be stored in zspage consisting of a single physical
1332 * Context: Any context.
1334 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1336 size_t zs_huge_class_size(struct zs_pool *pool)
1338 return huge_class_size;
1340 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1342 static unsigned long obj_malloc(struct zs_pool *pool,
1343 struct zspage *zspage, unsigned long handle)
1345 int i, nr_page, offset;
1347 struct link_free *link;
1348 struct size_class *class;
1350 struct page *m_page;
1351 unsigned long m_offset;
1354 class = pool->size_class[zspage->class];
1355 handle |= OBJ_ALLOCATED_TAG;
1356 obj = get_freeobj(zspage);
1358 offset = obj * class->size;
1359 nr_page = offset >> PAGE_SHIFT;
1360 m_offset = offset & ~PAGE_MASK;
1361 m_page = get_first_page(zspage);
1363 for (i = 0; i < nr_page; i++)
1364 m_page = get_next_page(m_page);
1366 vaddr = kmap_atomic(m_page);
1367 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1368 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1369 if (likely(!ZsHugePage(zspage)))
1370 /* record handle in the header of allocated chunk */
1371 link->handle = handle;
1373 /* record handle to page->index */
1374 zspage->first_page->index = handle;
1376 kunmap_atomic(vaddr);
1377 mod_zspage_inuse(zspage, 1);
1379 obj = location_to_obj(m_page, obj);
1386 * zs_malloc - Allocate block of given size from pool.
1387 * @pool: pool to allocate from
1388 * @size: size of block to allocate
1389 * @gfp: gfp flags when allocating object
1391 * On success, handle to the allocated object is returned,
1392 * otherwise an ERR_PTR().
1393 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1395 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1397 unsigned long handle, obj;
1398 struct size_class *class;
1399 enum fullness_group newfg;
1400 struct zspage *zspage;
1402 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1403 return (unsigned long)ERR_PTR(-EINVAL);
1405 handle = cache_alloc_handle(pool, gfp);
1407 return (unsigned long)ERR_PTR(-ENOMEM);
1409 /* extra space in chunk to keep the handle */
1410 size += ZS_HANDLE_SIZE;
1411 class = pool->size_class[get_size_class_index(size)];
1413 /* pool->lock effectively protects the zpage migration */
1414 spin_lock(&pool->lock);
1415 zspage = find_get_zspage(class);
1416 if (likely(zspage)) {
1417 obj = obj_malloc(pool, zspage, handle);
1418 /* Now move the zspage to another fullness group, if required */
1419 fix_fullness_group(class, zspage);
1420 record_obj(handle, obj);
1421 class_stat_inc(class, OBJ_USED, 1);
1422 spin_unlock(&pool->lock);
1427 spin_unlock(&pool->lock);
1429 zspage = alloc_zspage(pool, class, gfp);
1431 cache_free_handle(pool, handle);
1432 return (unsigned long)ERR_PTR(-ENOMEM);
1435 spin_lock(&pool->lock);
1436 obj = obj_malloc(pool, zspage, handle);
1437 newfg = get_fullness_group(class, zspage);
1438 insert_zspage(class, zspage, newfg);
1439 set_zspage_mapping(zspage, class->index, newfg);
1440 record_obj(handle, obj);
1441 atomic_long_add(class->pages_per_zspage,
1442 &pool->pages_allocated);
1443 class_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1444 class_stat_inc(class, OBJ_USED, 1);
1446 /* We completely set up zspage so mark them as movable */
1447 SetZsPageMovable(pool, zspage);
1448 spin_unlock(&pool->lock);
1452 EXPORT_SYMBOL_GPL(zs_malloc);
1454 static void obj_free(int class_size, unsigned long obj)
1456 struct link_free *link;
1457 struct zspage *zspage;
1458 struct page *f_page;
1459 unsigned long f_offset;
1460 unsigned int f_objidx;
1463 obj_to_location(obj, &f_page, &f_objidx);
1464 f_offset = (class_size * f_objidx) & ~PAGE_MASK;
1465 zspage = get_zspage(f_page);
1467 vaddr = kmap_atomic(f_page);
1469 /* Insert this object in containing zspage's freelist */
1470 link = (struct link_free *)(vaddr + f_offset);
1471 if (likely(!ZsHugePage(zspage)))
1472 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1475 kunmap_atomic(vaddr);
1476 set_freeobj(zspage, f_objidx);
1477 mod_zspage_inuse(zspage, -1);
1480 void zs_free(struct zs_pool *pool, unsigned long handle)
1482 struct zspage *zspage;
1483 struct page *f_page;
1485 struct size_class *class;
1486 enum fullness_group fullness;
1488 if (IS_ERR_OR_NULL((void *)handle))
1492 * The pool->lock protects the race with zpage's migration
1493 * so it's safe to get the page from handle.
1495 spin_lock(&pool->lock);
1496 obj = handle_to_obj(handle);
1497 obj_to_page(obj, &f_page);
1498 zspage = get_zspage(f_page);
1499 class = zspage_class(pool, zspage);
1501 obj_free(class->size, obj);
1502 class_stat_dec(class, OBJ_USED, 1);
1503 fullness = fix_fullness_group(class, zspage);
1504 if (fullness != ZS_EMPTY)
1507 free_zspage(pool, class, zspage);
1509 spin_unlock(&pool->lock);
1510 cache_free_handle(pool, handle);
1512 EXPORT_SYMBOL_GPL(zs_free);
1514 static void zs_object_copy(struct size_class *class, unsigned long dst,
1517 struct page *s_page, *d_page;
1518 unsigned int s_objidx, d_objidx;
1519 unsigned long s_off, d_off;
1520 void *s_addr, *d_addr;
1521 int s_size, d_size, size;
1524 s_size = d_size = class->size;
1526 obj_to_location(src, &s_page, &s_objidx);
1527 obj_to_location(dst, &d_page, &d_objidx);
1529 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1530 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1532 if (s_off + class->size > PAGE_SIZE)
1533 s_size = PAGE_SIZE - s_off;
1535 if (d_off + class->size > PAGE_SIZE)
1536 d_size = PAGE_SIZE - d_off;
1538 s_addr = kmap_atomic(s_page);
1539 d_addr = kmap_atomic(d_page);
1542 size = min(s_size, d_size);
1543 memcpy(d_addr + d_off, s_addr + s_off, size);
1546 if (written == class->size)
1555 * Calling kunmap_atomic(d_addr) is necessary. kunmap_atomic()
1556 * calls must occurs in reverse order of calls to kmap_atomic().
1557 * So, to call kunmap_atomic(s_addr) we should first call
1558 * kunmap_atomic(d_addr). For more details see
1559 * Documentation/mm/highmem.rst.
1561 if (s_off >= PAGE_SIZE) {
1562 kunmap_atomic(d_addr);
1563 kunmap_atomic(s_addr);
1564 s_page = get_next_page(s_page);
1565 s_addr = kmap_atomic(s_page);
1566 d_addr = kmap_atomic(d_page);
1567 s_size = class->size - written;
1571 if (d_off >= PAGE_SIZE) {
1572 kunmap_atomic(d_addr);
1573 d_page = get_next_page(d_page);
1574 d_addr = kmap_atomic(d_page);
1575 d_size = class->size - written;
1580 kunmap_atomic(d_addr);
1581 kunmap_atomic(s_addr);
1585 * Find alloced object in zspage from index object and
1588 static unsigned long find_alloced_obj(struct size_class *class,
1589 struct page *page, int *obj_idx)
1591 unsigned int offset;
1592 int index = *obj_idx;
1593 unsigned long handle = 0;
1594 void *addr = kmap_atomic(page);
1596 offset = get_first_obj_offset(page);
1597 offset += class->size * index;
1599 while (offset < PAGE_SIZE) {
1600 if (obj_allocated(page, addr + offset, &handle))
1603 offset += class->size;
1607 kunmap_atomic(addr);
1614 struct zs_compact_control {
1615 /* Source spage for migration which could be a subpage of zspage */
1616 struct page *s_page;
1617 /* Destination page for migration which should be a first page
1619 struct page *d_page;
1620 /* Starting object index within @s_page which used for live object
1621 * in the subpage. */
1625 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1626 struct zs_compact_control *cc)
1628 unsigned long used_obj, free_obj;
1629 unsigned long handle;
1630 struct page *s_page = cc->s_page;
1631 struct page *d_page = cc->d_page;
1632 int obj_idx = cc->obj_idx;
1636 handle = find_alloced_obj(class, s_page, &obj_idx);
1638 s_page = get_next_page(s_page);
1645 /* Stop if there is no more space */
1646 if (zspage_full(class, get_zspage(d_page))) {
1651 used_obj = handle_to_obj(handle);
1652 free_obj = obj_malloc(pool, get_zspage(d_page), handle);
1653 zs_object_copy(class, free_obj, used_obj);
1655 record_obj(handle, free_obj);
1656 obj_free(class->size, used_obj);
1659 /* Remember last position in this iteration */
1660 cc->s_page = s_page;
1661 cc->obj_idx = obj_idx;
1666 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1669 struct zspage *zspage;
1670 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1673 fg[0] = ZS_ALMOST_FULL;
1674 fg[1] = ZS_ALMOST_EMPTY;
1677 for (i = 0; i < 2; i++) {
1678 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1679 struct zspage, list);
1681 remove_zspage(class, zspage, fg[i]);
1690 * putback_zspage - add @zspage into right class's fullness list
1691 * @class: destination class
1692 * @zspage: target page
1694 * Return @zspage's fullness_group
1696 static enum fullness_group putback_zspage(struct size_class *class,
1697 struct zspage *zspage)
1699 enum fullness_group fullness;
1701 fullness = get_fullness_group(class, zspage);
1702 insert_zspage(class, zspage, fullness);
1703 set_zspage_mapping(zspage, class->index, fullness);
1708 #ifdef CONFIG_COMPACTION
1710 * To prevent zspage destroy during migration, zspage freeing should
1711 * hold locks of all pages in the zspage.
1713 static void lock_zspage(struct zspage *zspage)
1715 struct page *curr_page, *page;
1718 * Pages we haven't locked yet can be migrated off the list while we're
1719 * trying to lock them, so we need to be careful and only attempt to
1720 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1721 * may no longer belong to the zspage. This means that we may wait for
1722 * the wrong page to unlock, so we must take a reference to the page
1723 * prior to waiting for it to unlock outside migrate_read_lock().
1726 migrate_read_lock(zspage);
1727 page = get_first_page(zspage);
1728 if (trylock_page(page))
1731 migrate_read_unlock(zspage);
1732 wait_on_page_locked(page);
1737 while ((page = get_next_page(curr_page))) {
1738 if (trylock_page(page)) {
1742 migrate_read_unlock(zspage);
1743 wait_on_page_locked(page);
1745 migrate_read_lock(zspage);
1748 migrate_read_unlock(zspage);
1751 static void migrate_lock_init(struct zspage *zspage)
1753 rwlock_init(&zspage->lock);
1756 static void migrate_read_lock(struct zspage *zspage) __acquires(&zspage->lock)
1758 read_lock(&zspage->lock);
1761 static void migrate_read_unlock(struct zspage *zspage) __releases(&zspage->lock)
1763 read_unlock(&zspage->lock);
1766 static void migrate_write_lock(struct zspage *zspage)
1768 write_lock(&zspage->lock);
1771 static void migrate_write_lock_nested(struct zspage *zspage)
1773 write_lock_nested(&zspage->lock, SINGLE_DEPTH_NESTING);
1776 static void migrate_write_unlock(struct zspage *zspage)
1778 write_unlock(&zspage->lock);
1781 /* Number of isolated subpage for *page migration* in this zspage */
1782 static void inc_zspage_isolation(struct zspage *zspage)
1787 static void dec_zspage_isolation(struct zspage *zspage)
1789 VM_BUG_ON(zspage->isolated == 0);
1793 static const struct movable_operations zsmalloc_mops;
1795 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1796 struct page *newpage, struct page *oldpage)
1799 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1802 page = get_first_page(zspage);
1804 if (page == oldpage)
1805 pages[idx] = newpage;
1809 } while ((page = get_next_page(page)) != NULL);
1811 create_page_chain(class, zspage, pages);
1812 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1813 if (unlikely(ZsHugePage(zspage)))
1814 newpage->index = oldpage->index;
1815 __SetPageMovable(newpage, &zsmalloc_mops);
1818 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1820 struct zs_pool *pool;
1821 struct zspage *zspage;
1824 * Page is locked so zspage couldn't be destroyed. For detail, look at
1825 * lock_zspage in free_zspage.
1827 VM_BUG_ON_PAGE(!PageMovable(page), page);
1828 VM_BUG_ON_PAGE(PageIsolated(page), page);
1830 zspage = get_zspage(page);
1831 pool = zspage->pool;
1832 spin_lock(&pool->lock);
1833 inc_zspage_isolation(zspage);
1834 spin_unlock(&pool->lock);
1839 static int zs_page_migrate(struct page *newpage, struct page *page,
1840 enum migrate_mode mode)
1842 struct zs_pool *pool;
1843 struct size_class *class;
1844 struct zspage *zspage;
1846 void *s_addr, *d_addr, *addr;
1847 unsigned int offset;
1848 unsigned long handle;
1849 unsigned long old_obj, new_obj;
1850 unsigned int obj_idx;
1853 * We cannot support the _NO_COPY case here, because copy needs to
1854 * happen under the zs lock, which does not work with
1855 * MIGRATE_SYNC_NO_COPY workflow.
1857 if (mode == MIGRATE_SYNC_NO_COPY)
1860 VM_BUG_ON_PAGE(!PageMovable(page), page);
1861 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1863 /* The page is locked, so this pointer must remain valid */
1864 zspage = get_zspage(page);
1865 pool = zspage->pool;
1868 * The pool's lock protects the race between zpage migration
1871 spin_lock(&pool->lock);
1872 class = zspage_class(pool, zspage);
1874 /* the migrate_write_lock protects zpage access via zs_map_object */
1875 migrate_write_lock(zspage);
1877 offset = get_first_obj_offset(page);
1878 s_addr = kmap_atomic(page);
1881 * Here, any user cannot access all objects in the zspage so let's move.
1883 d_addr = kmap_atomic(newpage);
1884 memcpy(d_addr, s_addr, PAGE_SIZE);
1885 kunmap_atomic(d_addr);
1887 for (addr = s_addr + offset; addr < s_addr + PAGE_SIZE;
1888 addr += class->size) {
1889 if (obj_allocated(page, addr, &handle)) {
1891 old_obj = handle_to_obj(handle);
1892 obj_to_location(old_obj, &dummy, &obj_idx);
1893 new_obj = (unsigned long)location_to_obj(newpage,
1895 record_obj(handle, new_obj);
1898 kunmap_atomic(s_addr);
1900 replace_sub_page(class, zspage, newpage, page);
1901 dec_zspage_isolation(zspage);
1903 * Since we complete the data copy and set up new zspage structure,
1904 * it's okay to release the pool's lock.
1906 spin_unlock(&pool->lock);
1907 migrate_write_unlock(zspage);
1910 if (page_zone(newpage) != page_zone(page)) {
1911 dec_zone_page_state(page, NR_ZSPAGES);
1912 inc_zone_page_state(newpage, NR_ZSPAGES);
1918 return MIGRATEPAGE_SUCCESS;
1921 static void zs_page_putback(struct page *page)
1923 struct zs_pool *pool;
1924 struct zspage *zspage;
1926 VM_BUG_ON_PAGE(!PageMovable(page), page);
1927 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1929 zspage = get_zspage(page);
1930 pool = zspage->pool;
1931 spin_lock(&pool->lock);
1932 dec_zspage_isolation(zspage);
1933 spin_unlock(&pool->lock);
1936 static const struct movable_operations zsmalloc_mops = {
1937 .isolate_page = zs_page_isolate,
1938 .migrate_page = zs_page_migrate,
1939 .putback_page = zs_page_putback,
1943 * Caller should hold page_lock of all pages in the zspage
1944 * In here, we cannot use zspage meta data.
1946 static void async_free_zspage(struct work_struct *work)
1949 struct size_class *class;
1950 unsigned int class_idx;
1951 enum fullness_group fullness;
1952 struct zspage *zspage, *tmp;
1953 LIST_HEAD(free_pages);
1954 struct zs_pool *pool = container_of(work, struct zs_pool,
1957 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
1958 class = pool->size_class[i];
1959 if (class->index != i)
1962 spin_lock(&pool->lock);
1963 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
1964 spin_unlock(&pool->lock);
1967 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
1968 list_del(&zspage->list);
1969 lock_zspage(zspage);
1971 get_zspage_mapping(zspage, &class_idx, &fullness);
1972 VM_BUG_ON(fullness != ZS_EMPTY);
1973 class = pool->size_class[class_idx];
1974 spin_lock(&pool->lock);
1975 __free_zspage(pool, class, zspage);
1976 spin_unlock(&pool->lock);
1980 static void kick_deferred_free(struct zs_pool *pool)
1982 schedule_work(&pool->free_work);
1985 static void zs_flush_migration(struct zs_pool *pool)
1987 flush_work(&pool->free_work);
1990 static void init_deferred_free(struct zs_pool *pool)
1992 INIT_WORK(&pool->free_work, async_free_zspage);
1995 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
1997 struct page *page = get_first_page(zspage);
2000 WARN_ON(!trylock_page(page));
2001 __SetPageMovable(page, &zsmalloc_mops);
2003 } while ((page = get_next_page(page)) != NULL);
2006 static inline void zs_flush_migration(struct zs_pool *pool) { }
2011 * Based on the number of unused allocated objects calculate
2012 * and return the number of pages that we can free.
2014 static unsigned long zs_can_compact(struct size_class *class)
2016 unsigned long obj_wasted;
2017 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2018 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2020 if (obj_allocated <= obj_used)
2023 obj_wasted = obj_allocated - obj_used;
2024 obj_wasted /= class->objs_per_zspage;
2026 return obj_wasted * class->pages_per_zspage;
2029 static unsigned long __zs_compact(struct zs_pool *pool,
2030 struct size_class *class)
2032 struct zs_compact_control cc;
2033 struct zspage *src_zspage;
2034 struct zspage *dst_zspage = NULL;
2035 unsigned long pages_freed = 0;
2038 * protect the race between zpage migration and zs_free
2039 * as well as zpage allocation/free
2041 spin_lock(&pool->lock);
2042 while ((src_zspage = isolate_zspage(class, true))) {
2043 /* protect someone accessing the zspage(i.e., zs_map_object) */
2044 migrate_write_lock(src_zspage);
2046 if (!zs_can_compact(class))
2050 cc.s_page = get_first_page(src_zspage);
2052 while ((dst_zspage = isolate_zspage(class, false))) {
2053 migrate_write_lock_nested(dst_zspage);
2055 cc.d_page = get_first_page(dst_zspage);
2057 * If there is no more space in dst_page, resched
2058 * and see if anyone had allocated another zspage.
2060 if (!migrate_zspage(pool, class, &cc))
2063 putback_zspage(class, dst_zspage);
2064 migrate_write_unlock(dst_zspage);
2066 if (spin_is_contended(&pool->lock))
2070 /* Stop if we couldn't find slot */
2071 if (dst_zspage == NULL)
2074 putback_zspage(class, dst_zspage);
2075 migrate_write_unlock(dst_zspage);
2077 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2078 migrate_write_unlock(src_zspage);
2079 free_zspage(pool, class, src_zspage);
2080 pages_freed += class->pages_per_zspage;
2082 migrate_write_unlock(src_zspage);
2083 spin_unlock(&pool->lock);
2085 spin_lock(&pool->lock);
2089 putback_zspage(class, src_zspage);
2090 migrate_write_unlock(src_zspage);
2093 spin_unlock(&pool->lock);
2098 unsigned long zs_compact(struct zs_pool *pool)
2101 struct size_class *class;
2102 unsigned long pages_freed = 0;
2105 * Pool compaction is performed under pool->lock so it is basically
2106 * single-threaded. Having more than one thread in __zs_compact()
2107 * will increase pool->lock contention, which will impact other
2108 * zsmalloc operations that need pool->lock.
2110 if (atomic_xchg(&pool->compaction_in_progress, 1))
2113 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2114 class = pool->size_class[i];
2115 if (class->index != i)
2117 pages_freed += __zs_compact(pool, class);
2119 atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2120 atomic_set(&pool->compaction_in_progress, 0);
2124 EXPORT_SYMBOL_GPL(zs_compact);
2126 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2128 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2130 EXPORT_SYMBOL_GPL(zs_pool_stats);
2132 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2133 struct shrink_control *sc)
2135 unsigned long pages_freed;
2136 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2140 * Compact classes and calculate compaction delta.
2141 * Can run concurrently with a manually triggered
2142 * (by user) compaction.
2144 pages_freed = zs_compact(pool);
2146 return pages_freed ? pages_freed : SHRINK_STOP;
2149 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2150 struct shrink_control *sc)
2153 struct size_class *class;
2154 unsigned long pages_to_free = 0;
2155 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2158 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2159 class = pool->size_class[i];
2160 if (class->index != i)
2163 pages_to_free += zs_can_compact(class);
2166 return pages_to_free;
2169 static void zs_unregister_shrinker(struct zs_pool *pool)
2171 unregister_shrinker(&pool->shrinker);
2174 static int zs_register_shrinker(struct zs_pool *pool)
2176 pool->shrinker.scan_objects = zs_shrinker_scan;
2177 pool->shrinker.count_objects = zs_shrinker_count;
2178 pool->shrinker.batch = 0;
2179 pool->shrinker.seeks = DEFAULT_SEEKS;
2181 return register_shrinker(&pool->shrinker, "mm-zspool:%s",
2186 * zs_create_pool - Creates an allocation pool to work from.
2187 * @name: pool name to be created
2189 * This function must be called before anything when using
2190 * the zsmalloc allocator.
2192 * On success, a pointer to the newly created pool is returned,
2195 struct zs_pool *zs_create_pool(const char *name)
2198 struct zs_pool *pool;
2199 struct size_class *prev_class = NULL;
2201 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2205 init_deferred_free(pool);
2206 spin_lock_init(&pool->lock);
2207 atomic_set(&pool->compaction_in_progress, 0);
2209 pool->name = kstrdup(name, GFP_KERNEL);
2213 if (create_cache(pool))
2217 * Iterate reversely, because, size of size_class that we want to use
2218 * for merging should be larger or equal to current size.
2220 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2222 int pages_per_zspage;
2223 int objs_per_zspage;
2224 struct size_class *class;
2227 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2228 if (size > ZS_MAX_ALLOC_SIZE)
2229 size = ZS_MAX_ALLOC_SIZE;
2230 pages_per_zspage = get_pages_per_zspage(size);
2231 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2234 * We iterate from biggest down to smallest classes,
2235 * so huge_class_size holds the size of the first huge
2236 * class. Any object bigger than or equal to that will
2237 * endup in the huge class.
2239 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2241 huge_class_size = size;
2243 * The object uses ZS_HANDLE_SIZE bytes to store the
2244 * handle. We need to subtract it, because zs_malloc()
2245 * unconditionally adds handle size before it performs
2246 * size class search - so object may be smaller than
2247 * huge class size, yet it still can end up in the huge
2248 * class because it grows by ZS_HANDLE_SIZE extra bytes
2249 * right before class lookup.
2251 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2255 * size_class is used for normal zsmalloc operation such
2256 * as alloc/free for that size. Although it is natural that we
2257 * have one size_class for each size, there is a chance that we
2258 * can get more memory utilization if we use one size_class for
2259 * many different sizes whose size_class have same
2260 * characteristics. So, we makes size_class point to
2261 * previous size_class if possible.
2264 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2265 pool->size_class[i] = prev_class;
2270 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2276 class->pages_per_zspage = pages_per_zspage;
2277 class->objs_per_zspage = objs_per_zspage;
2278 pool->size_class[i] = class;
2279 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2281 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2286 /* debug only, don't abort if it fails */
2287 zs_pool_stat_create(pool, name);
2290 * Not critical since shrinker is only used to trigger internal
2291 * defragmentation of the pool which is pretty optional thing. If
2292 * registration fails we still can use the pool normally and user can
2293 * trigger compaction manually. Thus, ignore return code.
2295 zs_register_shrinker(pool);
2300 zs_destroy_pool(pool);
2303 EXPORT_SYMBOL_GPL(zs_create_pool);
2305 void zs_destroy_pool(struct zs_pool *pool)
2309 zs_unregister_shrinker(pool);
2310 zs_flush_migration(pool);
2311 zs_pool_stat_destroy(pool);
2313 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2315 struct size_class *class = pool->size_class[i];
2320 if (class->index != i)
2323 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2324 if (!list_empty(&class->fullness_list[fg])) {
2325 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2332 destroy_cache(pool);
2336 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2338 static int __init zs_init(void)
2342 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2343 zs_cpu_prepare, zs_cpu_dead);
2348 zpool_register_driver(&zs_zpool_driver);
2359 static void __exit zs_exit(void)
2362 zpool_unregister_driver(&zs_zpool_driver);
2364 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2369 module_init(zs_init);
2370 module_exit(zs_exit);
2372 MODULE_LICENSE("Dual BSD/GPL");
2373 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");