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.
76 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
79 * Object location (<PFN>, <obj_idx>) is encoded as
80 * a single (unsigned long) handle value.
82 * Note that object index <obj_idx> starts from 0.
84 * This is made more complicated by various memory models and PAE.
87 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
88 #ifdef MAX_PHYSMEM_BITS
89 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
92 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
95 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
99 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
102 * Head in allocated object should have OBJ_ALLOCATED_TAG
103 * to identify the object was allocated or not.
104 * It's okay to add the status bit in the least bit because
105 * header keeps handle which is 4byte-aligned address so we
106 * have room for two bit at least.
108 #define OBJ_ALLOCATED_TAG 1
112 * The second least-significant bit in the object's header identifies if the
113 * value stored at the header is a deferred handle from the last reclaim
116 * As noted above, this is valid because we have room for two bits.
118 #define OBJ_DEFERRED_HANDLE_TAG 2
119 #define OBJ_TAG_BITS 2
120 #define OBJ_TAG_MASK (OBJ_ALLOCATED_TAG | OBJ_DEFERRED_HANDLE_TAG)
122 #define OBJ_TAG_BITS 1
123 #define OBJ_TAG_MASK OBJ_ALLOCATED_TAG
124 #endif /* CONFIG_ZPOOL */
126 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
127 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
130 #define FULLNESS_BITS 2
132 #define ISOLATED_BITS 5
133 #define MAGIC_VAL_BITS 8
135 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
137 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(CONFIG_ZSMALLOC_CHAIN_SIZE, UL))
139 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
140 #define ZS_MIN_ALLOC_SIZE \
141 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
142 /* each chunk includes extra space to keep handle */
143 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
146 * On systems with 4K page size, this gives 255 size classes! There is a
148 * - Large number of size classes is potentially wasteful as free page are
149 * spread across these classes
150 * - Small number of size classes causes large internal fragmentation
151 * - Probably its better to use specific size classes (empirically
152 * determined). NOTE: all those class sizes must be set as multiple of
153 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
155 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
158 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
159 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
160 ZS_SIZE_CLASS_DELTA) + 1)
162 enum fullness_group {
170 enum class_stat_type {
180 struct zs_size_stat {
181 unsigned long objs[NR_ZS_STAT_TYPE];
184 #ifdef CONFIG_ZSMALLOC_STAT
185 static struct dentry *zs_stat_root;
189 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
191 * n = number of allocated objects
192 * N = total number of objects zspage can store
193 * f = fullness_threshold_frac
195 * Similarly, we assign zspage to:
196 * ZS_ALMOST_FULL when n > N / f
197 * ZS_EMPTY when n == 0
198 * ZS_FULL when n == N
200 * (see: fix_fullness_group())
202 static const int fullness_threshold_frac = 4;
203 static size_t huge_class_size;
206 struct list_head fullness_list[NR_ZS_FULLNESS];
208 * Size of objects stored in this class. Must be multiple
213 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
214 int pages_per_zspage;
217 struct zs_size_stat stats;
221 * Placed within free objects to form a singly linked list.
222 * For every zspage, zspage->freeobj gives head of this list.
224 * This must be power of 2 and less than or equal to ZS_ALIGN
230 * It's valid for non-allocated object
234 * Handle of allocated object.
236 unsigned long handle;
239 * Deferred handle of a reclaimed object.
241 unsigned long deferred_handle;
249 struct size_class *size_class[ZS_SIZE_CLASSES];
250 struct kmem_cache *handle_cachep;
251 struct kmem_cache *zspage_cachep;
253 atomic_long_t pages_allocated;
255 struct zs_pool_stats stats;
257 /* Compact classes */
258 struct shrinker shrinker;
261 /* List tracking the zspages in LRU order by most recently added object */
262 struct list_head lru;
264 const struct zpool_ops *zpool_ops;
267 #ifdef CONFIG_ZSMALLOC_STAT
268 struct dentry *stat_dentry;
270 #ifdef CONFIG_COMPACTION
271 struct work_struct free_work;
278 unsigned int huge:HUGE_BITS;
279 unsigned int fullness:FULLNESS_BITS;
280 unsigned int class:CLASS_BITS + 1;
281 unsigned int isolated:ISOLATED_BITS;
282 unsigned int magic:MAGIC_VAL_BITS;
285 unsigned int freeobj;
286 struct page *first_page;
287 struct list_head list; /* fullness list */
290 /* links the zspage to the lru list in the pool */
291 struct list_head lru;
295 struct zs_pool *pool;
299 struct mapping_area {
301 char *vm_buf; /* copy buffer for objects that span pages */
302 char *vm_addr; /* address of kmap_atomic()'ed pages */
303 enum zs_mapmode vm_mm; /* mapping mode */
306 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
307 static void SetZsHugePage(struct zspage *zspage)
312 static bool ZsHugePage(struct zspage *zspage)
317 static void migrate_lock_init(struct zspage *zspage);
318 static void migrate_read_lock(struct zspage *zspage);
319 static void migrate_read_unlock(struct zspage *zspage);
321 #ifdef CONFIG_COMPACTION
322 static void migrate_write_lock(struct zspage *zspage);
323 static void migrate_write_lock_nested(struct zspage *zspage);
324 static void migrate_write_unlock(struct zspage *zspage);
325 static void kick_deferred_free(struct zs_pool *pool);
326 static void init_deferred_free(struct zs_pool *pool);
327 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
329 static void migrate_write_lock(struct zspage *zspage) {}
330 static void migrate_write_lock_nested(struct zspage *zspage) {}
331 static void migrate_write_unlock(struct zspage *zspage) {}
332 static void kick_deferred_free(struct zs_pool *pool) {}
333 static void init_deferred_free(struct zs_pool *pool) {}
334 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
337 static int create_cache(struct zs_pool *pool)
339 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
341 if (!pool->handle_cachep)
344 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
346 if (!pool->zspage_cachep) {
347 kmem_cache_destroy(pool->handle_cachep);
348 pool->handle_cachep = NULL;
355 static void destroy_cache(struct zs_pool *pool)
357 kmem_cache_destroy(pool->handle_cachep);
358 kmem_cache_destroy(pool->zspage_cachep);
361 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
363 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
364 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
367 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
369 kmem_cache_free(pool->handle_cachep, (void *)handle);
372 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
374 return kmem_cache_zalloc(pool->zspage_cachep,
375 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
378 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
380 kmem_cache_free(pool->zspage_cachep, zspage);
383 /* pool->lock(which owns the handle) synchronizes races */
384 static void record_obj(unsigned long handle, unsigned long obj)
386 *(unsigned long *)handle = obj;
393 static void *zs_zpool_create(const char *name, gfp_t gfp,
394 const struct zpool_ops *zpool_ops,
398 * Ignore global gfp flags: zs_malloc() may be invoked from
399 * different contexts and its caller must provide a valid
402 struct zs_pool *pool = zs_create_pool(name);
406 pool->zpool_ops = zpool_ops;
412 static void zs_zpool_destroy(void *pool)
414 zs_destroy_pool(pool);
417 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
418 unsigned long *handle)
420 *handle = zs_malloc(pool, size, gfp);
422 if (IS_ERR_VALUE(*handle))
423 return PTR_ERR((void *)*handle);
426 static void zs_zpool_free(void *pool, unsigned long handle)
428 zs_free(pool, handle);
431 static int zs_reclaim_page(struct zs_pool *pool, unsigned int retries);
433 static int zs_zpool_shrink(void *pool, unsigned int pages,
434 unsigned int *reclaimed)
436 unsigned int total = 0;
439 while (total < pages) {
440 ret = zs_reclaim_page(pool, 8);
452 static void *zs_zpool_map(void *pool, unsigned long handle,
453 enum zpool_mapmode mm)
455 enum zs_mapmode zs_mm;
470 return zs_map_object(pool, handle, zs_mm);
472 static void zs_zpool_unmap(void *pool, unsigned long handle)
474 zs_unmap_object(pool, handle);
477 static u64 zs_zpool_total_size(void *pool)
479 return zs_get_total_pages(pool) << PAGE_SHIFT;
482 static struct zpool_driver zs_zpool_driver = {
484 .owner = THIS_MODULE,
485 .create = zs_zpool_create,
486 .destroy = zs_zpool_destroy,
487 .malloc_support_movable = true,
488 .malloc = zs_zpool_malloc,
489 .free = zs_zpool_free,
490 .shrink = zs_zpool_shrink,
492 .unmap = zs_zpool_unmap,
493 .total_size = zs_zpool_total_size,
496 MODULE_ALIAS("zpool-zsmalloc");
497 #endif /* CONFIG_ZPOOL */
499 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
500 static DEFINE_PER_CPU(struct mapping_area, zs_map_area) = {
501 .lock = INIT_LOCAL_LOCK(lock),
504 static __maybe_unused int is_first_page(struct page *page)
506 return PagePrivate(page);
509 /* Protected by pool->lock */
510 static inline int get_zspage_inuse(struct zspage *zspage)
512 return zspage->inuse;
516 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
518 zspage->inuse += val;
521 static inline struct page *get_first_page(struct zspage *zspage)
523 struct page *first_page = zspage->first_page;
525 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
529 static inline unsigned int get_first_obj_offset(struct page *page)
531 return page->page_type;
534 static inline void set_first_obj_offset(struct page *page, unsigned int offset)
536 page->page_type = offset;
539 static inline unsigned int get_freeobj(struct zspage *zspage)
541 return zspage->freeobj;
544 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
546 zspage->freeobj = obj;
549 static void get_zspage_mapping(struct zspage *zspage,
550 unsigned int *class_idx,
551 enum fullness_group *fullness)
553 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
555 *fullness = zspage->fullness;
556 *class_idx = zspage->class;
559 static struct size_class *zspage_class(struct zs_pool *pool,
560 struct zspage *zspage)
562 return pool->size_class[zspage->class];
565 static void set_zspage_mapping(struct zspage *zspage,
566 unsigned int class_idx,
567 enum fullness_group fullness)
569 zspage->class = class_idx;
570 zspage->fullness = fullness;
574 * zsmalloc divides the pool into various size classes where each
575 * class maintains a list of zspages where each zspage is divided
576 * into equal sized chunks. Each allocation falls into one of these
577 * classes depending on its size. This function returns index of the
578 * size class which has chunk size big enough to hold the given size.
580 static int get_size_class_index(int size)
584 if (likely(size > ZS_MIN_ALLOC_SIZE))
585 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
586 ZS_SIZE_CLASS_DELTA);
588 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
591 /* type can be of enum type class_stat_type or fullness_group */
592 static inline void class_stat_inc(struct size_class *class,
593 int type, unsigned long cnt)
595 class->stats.objs[type] += cnt;
598 /* type can be of enum type class_stat_type or fullness_group */
599 static inline void class_stat_dec(struct size_class *class,
600 int type, unsigned long cnt)
602 class->stats.objs[type] -= cnt;
605 /* type can be of enum type class_stat_type or fullness_group */
606 static inline unsigned long zs_stat_get(struct size_class *class,
609 return class->stats.objs[type];
612 #ifdef CONFIG_ZSMALLOC_STAT
614 static void __init zs_stat_init(void)
616 if (!debugfs_initialized()) {
617 pr_warn("debugfs not available, stat dir not created\n");
621 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
624 static void __exit zs_stat_exit(void)
626 debugfs_remove_recursive(zs_stat_root);
629 static unsigned long zs_can_compact(struct size_class *class);
631 static int zs_stats_size_show(struct seq_file *s, void *v)
634 struct zs_pool *pool = s->private;
635 struct size_class *class;
637 unsigned long class_almost_full, class_almost_empty;
638 unsigned long obj_allocated, obj_used, pages_used, freeable;
639 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
640 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
641 unsigned long total_freeable = 0;
643 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
644 "class", "size", "almost_full", "almost_empty",
645 "obj_allocated", "obj_used", "pages_used",
646 "pages_per_zspage", "freeable");
648 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
649 class = pool->size_class[i];
651 if (class->index != i)
654 spin_lock(&pool->lock);
655 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
656 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
657 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
658 obj_used = zs_stat_get(class, OBJ_USED);
659 freeable = zs_can_compact(class);
660 spin_unlock(&pool->lock);
662 objs_per_zspage = class->objs_per_zspage;
663 pages_used = obj_allocated / objs_per_zspage *
664 class->pages_per_zspage;
666 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
667 " %10lu %10lu %16d %8lu\n",
668 i, class->size, class_almost_full, class_almost_empty,
669 obj_allocated, obj_used, pages_used,
670 class->pages_per_zspage, freeable);
672 total_class_almost_full += class_almost_full;
673 total_class_almost_empty += class_almost_empty;
674 total_objs += obj_allocated;
675 total_used_objs += obj_used;
676 total_pages += pages_used;
677 total_freeable += freeable;
681 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
682 "Total", "", total_class_almost_full,
683 total_class_almost_empty, total_objs,
684 total_used_objs, total_pages, "", total_freeable);
688 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
690 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
693 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
697 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
699 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
700 &zs_stats_size_fops);
703 static void zs_pool_stat_destroy(struct zs_pool *pool)
705 debugfs_remove_recursive(pool->stat_dentry);
708 #else /* CONFIG_ZSMALLOC_STAT */
709 static void __init zs_stat_init(void)
713 static void __exit zs_stat_exit(void)
717 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
721 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
728 * For each size class, zspages are divided into different groups
729 * depending on how "full" they are. This was done so that we could
730 * easily find empty or nearly empty zspages when we try to shrink
731 * the pool (not yet implemented). This function returns fullness
732 * status of the given page.
734 static enum fullness_group get_fullness_group(struct size_class *class,
735 struct zspage *zspage)
737 int inuse, objs_per_zspage;
738 enum fullness_group fg;
740 inuse = get_zspage_inuse(zspage);
741 objs_per_zspage = class->objs_per_zspage;
745 else if (inuse == objs_per_zspage)
747 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
748 fg = ZS_ALMOST_EMPTY;
756 * Each size class maintains various freelists and zspages are assigned
757 * to one of these freelists based on the number of live objects they
758 * have. This functions inserts the given zspage into the freelist
759 * identified by <class, fullness_group>.
761 static void insert_zspage(struct size_class *class,
762 struct zspage *zspage,
763 enum fullness_group fullness)
767 class_stat_inc(class, fullness, 1);
768 head = list_first_entry_or_null(&class->fullness_list[fullness],
769 struct zspage, list);
771 * We want to see more ZS_FULL pages and less almost empty/full.
772 * Put pages with higher ->inuse first.
774 if (head && get_zspage_inuse(zspage) < get_zspage_inuse(head))
775 list_add(&zspage->list, &head->list);
777 list_add(&zspage->list, &class->fullness_list[fullness]);
781 * This function removes the given zspage from the freelist identified
782 * by <class, fullness_group>.
784 static void remove_zspage(struct size_class *class,
785 struct zspage *zspage,
786 enum fullness_group fullness)
788 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
790 list_del_init(&zspage->list);
791 class_stat_dec(class, fullness, 1);
795 * Each size class maintains zspages in different fullness groups depending
796 * on the number of live objects they contain. When allocating or freeing
797 * objects, the fullness status of the page can change, say, from ALMOST_FULL
798 * to ALMOST_EMPTY when freeing an object. This function checks if such
799 * a status change has occurred for the given page and accordingly moves the
800 * page from the freelist of the old fullness group to that of the new
803 static enum fullness_group fix_fullness_group(struct size_class *class,
804 struct zspage *zspage)
807 enum fullness_group currfg, newfg;
809 get_zspage_mapping(zspage, &class_idx, &currfg);
810 newfg = get_fullness_group(class, zspage);
814 remove_zspage(class, zspage, currfg);
815 insert_zspage(class, zspage, newfg);
816 set_zspage_mapping(zspage, class_idx, newfg);
821 static struct zspage *get_zspage(struct page *page)
823 struct zspage *zspage = (struct zspage *)page_private(page);
825 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
829 static struct page *get_next_page(struct page *page)
831 struct zspage *zspage = get_zspage(page);
833 if (unlikely(ZsHugePage(zspage)))
836 return (struct page *)page->index;
840 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
841 * @obj: the encoded object value
842 * @page: page object resides in zspage
843 * @obj_idx: object index
845 static void obj_to_location(unsigned long obj, struct page **page,
846 unsigned int *obj_idx)
848 obj >>= OBJ_TAG_BITS;
849 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
850 *obj_idx = (obj & OBJ_INDEX_MASK);
853 static void obj_to_page(unsigned long obj, struct page **page)
855 obj >>= OBJ_TAG_BITS;
856 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
860 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
861 * @page: page object resides in zspage
862 * @obj_idx: object index
864 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
868 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
869 obj |= obj_idx & OBJ_INDEX_MASK;
870 obj <<= OBJ_TAG_BITS;
875 static unsigned long handle_to_obj(unsigned long handle)
877 return *(unsigned long *)handle;
880 static bool obj_tagged(struct page *page, void *obj, unsigned long *phandle,
883 unsigned long handle;
884 struct zspage *zspage = get_zspage(page);
886 if (unlikely(ZsHugePage(zspage))) {
887 VM_BUG_ON_PAGE(!is_first_page(page), page);
888 handle = page->index;
890 handle = *(unsigned long *)obj;
895 /* Clear all tags before returning the handle */
896 *phandle = handle & ~OBJ_TAG_MASK;
900 static inline bool obj_allocated(struct page *page, void *obj, unsigned long *phandle)
902 return obj_tagged(page, obj, phandle, OBJ_ALLOCATED_TAG);
906 static bool obj_stores_deferred_handle(struct page *page, void *obj,
907 unsigned long *phandle)
909 return obj_tagged(page, obj, phandle, OBJ_DEFERRED_HANDLE_TAG);
913 static void reset_page(struct page *page)
915 __ClearPageMovable(page);
916 ClearPagePrivate(page);
917 set_page_private(page, 0);
918 page_mapcount_reset(page);
922 static int trylock_zspage(struct zspage *zspage)
924 struct page *cursor, *fail;
926 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
927 get_next_page(cursor)) {
928 if (!trylock_page(cursor)) {
936 for (cursor = get_first_page(zspage); cursor != fail; cursor =
937 get_next_page(cursor))
944 static unsigned long find_deferred_handle_obj(struct size_class *class,
945 struct page *page, int *obj_idx);
948 * Free all the deferred handles whose objects are freed in zs_free.
950 static void free_handles(struct zs_pool *pool, struct size_class *class,
951 struct zspage *zspage)
954 struct page *page = get_first_page(zspage);
955 unsigned long handle;
958 handle = find_deferred_handle_obj(class, page, &obj_idx);
960 page = get_next_page(page);
967 cache_free_handle(pool, handle);
972 static inline void free_handles(struct zs_pool *pool, struct size_class *class,
973 struct zspage *zspage) {}
976 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
977 struct zspage *zspage)
979 struct page *page, *next;
980 enum fullness_group fg;
981 unsigned int class_idx;
983 get_zspage_mapping(zspage, &class_idx, &fg);
985 assert_spin_locked(&pool->lock);
987 VM_BUG_ON(get_zspage_inuse(zspage));
988 VM_BUG_ON(fg != ZS_EMPTY);
990 /* Free all deferred handles from zs_free */
991 free_handles(pool, class, zspage);
993 next = page = get_first_page(zspage);
995 VM_BUG_ON_PAGE(!PageLocked(page), page);
996 next = get_next_page(page);
999 dec_zone_page_state(page, NR_ZSPAGES);
1002 } while (page != NULL);
1004 cache_free_zspage(pool, zspage);
1006 class_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
1007 atomic_long_sub(class->pages_per_zspage,
1008 &pool->pages_allocated);
1011 static void free_zspage(struct zs_pool *pool, struct size_class *class,
1012 struct zspage *zspage)
1014 VM_BUG_ON(get_zspage_inuse(zspage));
1015 VM_BUG_ON(list_empty(&zspage->list));
1018 * Since zs_free couldn't be sleepable, this function cannot call
1019 * lock_page. The page locks trylock_zspage got will be released
1022 if (!trylock_zspage(zspage)) {
1023 kick_deferred_free(pool);
1027 remove_zspage(class, zspage, ZS_EMPTY);
1029 list_del(&zspage->lru);
1031 __free_zspage(pool, class, zspage);
1034 /* Initialize a newly allocated zspage */
1035 static void init_zspage(struct size_class *class, struct zspage *zspage)
1037 unsigned int freeobj = 1;
1038 unsigned long off = 0;
1039 struct page *page = get_first_page(zspage);
1042 struct page *next_page;
1043 struct link_free *link;
1046 set_first_obj_offset(page, off);
1048 vaddr = kmap_atomic(page);
1049 link = (struct link_free *)vaddr + off / sizeof(*link);
1051 while ((off += class->size) < PAGE_SIZE) {
1052 link->next = freeobj++ << OBJ_TAG_BITS;
1053 link += class->size / sizeof(*link);
1057 * We now come to the last (full or partial) object on this
1058 * page, which must point to the first object on the next
1061 next_page = get_next_page(page);
1063 link->next = freeobj++ << OBJ_TAG_BITS;
1066 * Reset OBJ_TAG_BITS bit to last link to tell
1067 * whether it's allocated object or not.
1069 link->next = -1UL << OBJ_TAG_BITS;
1071 kunmap_atomic(vaddr);
1077 INIT_LIST_HEAD(&zspage->lru);
1078 zspage->under_reclaim = false;
1081 set_freeobj(zspage, 0);
1084 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1085 struct page *pages[])
1089 struct page *prev_page = NULL;
1090 int nr_pages = class->pages_per_zspage;
1093 * Allocate individual pages and link them together as:
1094 * 1. all pages are linked together using page->index
1095 * 2. each sub-page point to zspage using page->private
1097 * we set PG_private to identify the first page (i.e. no other sub-page
1098 * has this flag set).
1100 for (i = 0; i < nr_pages; i++) {
1102 set_page_private(page, (unsigned long)zspage);
1105 zspage->first_page = page;
1106 SetPagePrivate(page);
1107 if (unlikely(class->objs_per_zspage == 1 &&
1108 class->pages_per_zspage == 1))
1109 SetZsHugePage(zspage);
1111 prev_page->index = (unsigned long)page;
1118 * Allocate a zspage for the given size class
1120 static struct zspage *alloc_zspage(struct zs_pool *pool,
1121 struct size_class *class,
1125 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1126 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1131 zspage->magic = ZSPAGE_MAGIC;
1132 migrate_lock_init(zspage);
1134 for (i = 0; i < class->pages_per_zspage; i++) {
1137 page = alloc_page(gfp);
1140 dec_zone_page_state(pages[i], NR_ZSPAGES);
1141 __free_page(pages[i]);
1143 cache_free_zspage(pool, zspage);
1147 inc_zone_page_state(page, NR_ZSPAGES);
1151 create_page_chain(class, zspage, pages);
1152 init_zspage(class, zspage);
1153 zspage->pool = pool;
1158 static struct zspage *find_get_zspage(struct size_class *class)
1161 struct zspage *zspage;
1163 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1164 zspage = list_first_entry_or_null(&class->fullness_list[i],
1165 struct zspage, list);
1173 static inline int __zs_cpu_up(struct mapping_area *area)
1176 * Make sure we don't leak memory if a cpu UP notification
1177 * and zs_init() race and both call zs_cpu_up() on the same cpu
1181 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1187 static inline void __zs_cpu_down(struct mapping_area *area)
1189 kfree(area->vm_buf);
1190 area->vm_buf = NULL;
1193 static void *__zs_map_object(struct mapping_area *area,
1194 struct page *pages[2], int off, int size)
1198 char *buf = area->vm_buf;
1200 /* disable page faults to match kmap_atomic() return conditions */
1201 pagefault_disable();
1203 /* no read fastpath */
1204 if (area->vm_mm == ZS_MM_WO)
1207 sizes[0] = PAGE_SIZE - off;
1208 sizes[1] = size - sizes[0];
1210 /* copy object to per-cpu buffer */
1211 addr = kmap_atomic(pages[0]);
1212 memcpy(buf, addr + off, sizes[0]);
1213 kunmap_atomic(addr);
1214 addr = kmap_atomic(pages[1]);
1215 memcpy(buf + sizes[0], addr, sizes[1]);
1216 kunmap_atomic(addr);
1218 return area->vm_buf;
1221 static void __zs_unmap_object(struct mapping_area *area,
1222 struct page *pages[2], int off, int size)
1228 /* no write fastpath */
1229 if (area->vm_mm == ZS_MM_RO)
1233 buf = buf + ZS_HANDLE_SIZE;
1234 size -= ZS_HANDLE_SIZE;
1235 off += ZS_HANDLE_SIZE;
1237 sizes[0] = PAGE_SIZE - off;
1238 sizes[1] = size - sizes[0];
1240 /* copy per-cpu buffer to object */
1241 addr = kmap_atomic(pages[0]);
1242 memcpy(addr + off, buf, sizes[0]);
1243 kunmap_atomic(addr);
1244 addr = kmap_atomic(pages[1]);
1245 memcpy(addr, buf + sizes[0], sizes[1]);
1246 kunmap_atomic(addr);
1249 /* enable page faults to match kunmap_atomic() return conditions */
1253 static int zs_cpu_prepare(unsigned int cpu)
1255 struct mapping_area *area;
1257 area = &per_cpu(zs_map_area, cpu);
1258 return __zs_cpu_up(area);
1261 static int zs_cpu_dead(unsigned int cpu)
1263 struct mapping_area *area;
1265 area = &per_cpu(zs_map_area, cpu);
1266 __zs_cpu_down(area);
1270 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1271 int objs_per_zspage)
1273 if (prev->pages_per_zspage == pages_per_zspage &&
1274 prev->objs_per_zspage == objs_per_zspage)
1280 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1282 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1286 * zs_lookup_class_index() - Returns index of the zsmalloc &size_class
1287 * that hold objects of the provided size.
1288 * @pool: zsmalloc pool to use
1289 * @size: object size
1291 * Context: Any context.
1293 * Return: the index of the zsmalloc &size_class that hold objects of the
1296 unsigned int zs_lookup_class_index(struct zs_pool *pool, unsigned int size)
1298 struct size_class *class;
1300 class = pool->size_class[get_size_class_index(size)];
1302 return class->index;
1304 EXPORT_SYMBOL_GPL(zs_lookup_class_index);
1306 unsigned long zs_get_total_pages(struct zs_pool *pool)
1308 return atomic_long_read(&pool->pages_allocated);
1310 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1313 * zs_map_object - get address of allocated object from handle.
1314 * @pool: pool from which the object was allocated
1315 * @handle: handle returned from zs_malloc
1316 * @mm: mapping mode to use
1318 * Before using an object allocated from zs_malloc, it must be mapped using
1319 * this function. When done with the object, it must be unmapped using
1322 * Only one object can be mapped per cpu at a time. There is no protection
1323 * against nested mappings.
1325 * This function returns with preemption and page faults disabled.
1327 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1330 struct zspage *zspage;
1332 unsigned long obj, off;
1333 unsigned int obj_idx;
1335 struct size_class *class;
1336 struct mapping_area *area;
1337 struct page *pages[2];
1341 * Because we use per-cpu mapping areas shared among the
1342 * pools/users, we can't allow mapping in interrupt context
1343 * because it can corrupt another users mappings.
1345 BUG_ON(in_interrupt());
1347 /* It guarantees it can get zspage from handle safely */
1348 spin_lock(&pool->lock);
1349 obj = handle_to_obj(handle);
1350 obj_to_location(obj, &page, &obj_idx);
1351 zspage = get_zspage(page);
1355 * Move the zspage to front of pool's LRU.
1357 * Note that this is swap-specific, so by definition there are no ongoing
1358 * accesses to the memory while the page is swapped out that would make
1359 * it "hot". A new entry is hot, then ages to the tail until it gets either
1360 * written back or swaps back in.
1362 * Furthermore, map is also called during writeback. We must not put an
1363 * isolated page on the LRU mid-reclaim.
1365 * As a result, only update the LRU when the page is mapped for write
1366 * when it's first instantiated.
1368 * This is a deviation from the other backends, which perform this update
1369 * in the allocation function (zbud_alloc, z3fold_alloc).
1371 if (mm == ZS_MM_WO) {
1372 if (!list_empty(&zspage->lru))
1373 list_del(&zspage->lru);
1374 list_add(&zspage->lru, &pool->lru);
1379 * migration cannot move any zpages in this zspage. Here, pool->lock
1380 * is too heavy since callers would take some time until they calls
1381 * zs_unmap_object API so delegate the locking from class to zspage
1382 * which is smaller granularity.
1384 migrate_read_lock(zspage);
1385 spin_unlock(&pool->lock);
1387 class = zspage_class(pool, zspage);
1388 off = (class->size * obj_idx) & ~PAGE_MASK;
1390 local_lock(&zs_map_area.lock);
1391 area = this_cpu_ptr(&zs_map_area);
1393 if (off + class->size <= PAGE_SIZE) {
1394 /* this object is contained entirely within a page */
1395 area->vm_addr = kmap_atomic(page);
1396 ret = area->vm_addr + off;
1400 /* this object spans two pages */
1402 pages[1] = get_next_page(page);
1405 ret = __zs_map_object(area, pages, off, class->size);
1407 if (likely(!ZsHugePage(zspage)))
1408 ret += ZS_HANDLE_SIZE;
1412 EXPORT_SYMBOL_GPL(zs_map_object);
1414 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1416 struct zspage *zspage;
1418 unsigned long obj, off;
1419 unsigned int obj_idx;
1421 struct size_class *class;
1422 struct mapping_area *area;
1424 obj = handle_to_obj(handle);
1425 obj_to_location(obj, &page, &obj_idx);
1426 zspage = get_zspage(page);
1427 class = zspage_class(pool, zspage);
1428 off = (class->size * obj_idx) & ~PAGE_MASK;
1430 area = this_cpu_ptr(&zs_map_area);
1431 if (off + class->size <= PAGE_SIZE)
1432 kunmap_atomic(area->vm_addr);
1434 struct page *pages[2];
1437 pages[1] = get_next_page(page);
1440 __zs_unmap_object(area, pages, off, class->size);
1442 local_unlock(&zs_map_area.lock);
1444 migrate_read_unlock(zspage);
1446 EXPORT_SYMBOL_GPL(zs_unmap_object);
1449 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1450 * zsmalloc &size_class.
1451 * @pool: zsmalloc pool to use
1453 * The function returns the size of the first huge class - any object of equal
1454 * or bigger size will be stored in zspage consisting of a single physical
1457 * Context: Any context.
1459 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1461 size_t zs_huge_class_size(struct zs_pool *pool)
1463 return huge_class_size;
1465 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1467 static unsigned long obj_malloc(struct zs_pool *pool,
1468 struct zspage *zspage, unsigned long handle)
1470 int i, nr_page, offset;
1472 struct link_free *link;
1473 struct size_class *class;
1475 struct page *m_page;
1476 unsigned long m_offset;
1479 class = pool->size_class[zspage->class];
1480 handle |= OBJ_ALLOCATED_TAG;
1481 obj = get_freeobj(zspage);
1483 offset = obj * class->size;
1484 nr_page = offset >> PAGE_SHIFT;
1485 m_offset = offset & ~PAGE_MASK;
1486 m_page = get_first_page(zspage);
1488 for (i = 0; i < nr_page; i++)
1489 m_page = get_next_page(m_page);
1491 vaddr = kmap_atomic(m_page);
1492 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1493 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1494 if (likely(!ZsHugePage(zspage)))
1495 /* record handle in the header of allocated chunk */
1496 link->handle = handle;
1498 /* record handle to page->index */
1499 zspage->first_page->index = handle;
1501 kunmap_atomic(vaddr);
1502 mod_zspage_inuse(zspage, 1);
1504 obj = location_to_obj(m_page, obj);
1511 * zs_malloc - Allocate block of given size from pool.
1512 * @pool: pool to allocate from
1513 * @size: size of block to allocate
1514 * @gfp: gfp flags when allocating object
1516 * On success, handle to the allocated object is returned,
1517 * otherwise an ERR_PTR().
1518 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1520 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1522 unsigned long handle, obj;
1523 struct size_class *class;
1524 enum fullness_group newfg;
1525 struct zspage *zspage;
1527 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1528 return (unsigned long)ERR_PTR(-EINVAL);
1530 handle = cache_alloc_handle(pool, gfp);
1532 return (unsigned long)ERR_PTR(-ENOMEM);
1534 /* extra space in chunk to keep the handle */
1535 size += ZS_HANDLE_SIZE;
1536 class = pool->size_class[get_size_class_index(size)];
1538 /* pool->lock effectively protects the zpage migration */
1539 spin_lock(&pool->lock);
1540 zspage = find_get_zspage(class);
1541 if (likely(zspage)) {
1542 obj = obj_malloc(pool, zspage, handle);
1543 /* Now move the zspage to another fullness group, if required */
1544 fix_fullness_group(class, zspage);
1545 record_obj(handle, obj);
1546 class_stat_inc(class, OBJ_USED, 1);
1547 spin_unlock(&pool->lock);
1552 spin_unlock(&pool->lock);
1554 zspage = alloc_zspage(pool, class, gfp);
1556 cache_free_handle(pool, handle);
1557 return (unsigned long)ERR_PTR(-ENOMEM);
1560 spin_lock(&pool->lock);
1561 obj = obj_malloc(pool, zspage, handle);
1562 newfg = get_fullness_group(class, zspage);
1563 insert_zspage(class, zspage, newfg);
1564 set_zspage_mapping(zspage, class->index, newfg);
1565 record_obj(handle, obj);
1566 atomic_long_add(class->pages_per_zspage,
1567 &pool->pages_allocated);
1568 class_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1569 class_stat_inc(class, OBJ_USED, 1);
1571 /* We completely set up zspage so mark them as movable */
1572 SetZsPageMovable(pool, zspage);
1573 spin_unlock(&pool->lock);
1577 EXPORT_SYMBOL_GPL(zs_malloc);
1579 static void obj_free(int class_size, unsigned long obj, unsigned long *handle)
1581 struct link_free *link;
1582 struct zspage *zspage;
1583 struct page *f_page;
1584 unsigned long f_offset;
1585 unsigned int f_objidx;
1588 obj_to_location(obj, &f_page, &f_objidx);
1589 f_offset = (class_size * f_objidx) & ~PAGE_MASK;
1590 zspage = get_zspage(f_page);
1592 vaddr = kmap_atomic(f_page);
1593 link = (struct link_free *)(vaddr + f_offset);
1597 /* Stores the (deferred) handle in the object's header */
1598 *handle |= OBJ_DEFERRED_HANDLE_TAG;
1599 *handle &= ~OBJ_ALLOCATED_TAG;
1601 if (likely(!ZsHugePage(zspage)))
1602 link->deferred_handle = *handle;
1604 f_page->index = *handle;
1607 /* Insert this object in containing zspage's freelist */
1608 if (likely(!ZsHugePage(zspage)))
1609 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1612 set_freeobj(zspage, f_objidx);
1615 kunmap_atomic(vaddr);
1616 mod_zspage_inuse(zspage, -1);
1619 void zs_free(struct zs_pool *pool, unsigned long handle)
1621 struct zspage *zspage;
1622 struct page *f_page;
1624 struct size_class *class;
1625 enum fullness_group fullness;
1627 if (IS_ERR_OR_NULL((void *)handle))
1631 * The pool->lock protects the race with zpage's migration
1632 * so it's safe to get the page from handle.
1634 spin_lock(&pool->lock);
1635 obj = handle_to_obj(handle);
1636 obj_to_page(obj, &f_page);
1637 zspage = get_zspage(f_page);
1638 class = zspage_class(pool, zspage);
1640 class_stat_dec(class, OBJ_USED, 1);
1643 if (zspage->under_reclaim) {
1645 * Reclaim needs the handles during writeback. It'll free
1646 * them along with the zspage when it's done with them.
1648 * Record current deferred handle in the object's header.
1650 obj_free(class->size, obj, &handle);
1651 spin_unlock(&pool->lock);
1655 obj_free(class->size, obj, NULL);
1657 fullness = fix_fullness_group(class, zspage);
1658 if (fullness == ZS_EMPTY)
1659 free_zspage(pool, class, zspage);
1661 spin_unlock(&pool->lock);
1662 cache_free_handle(pool, handle);
1664 EXPORT_SYMBOL_GPL(zs_free);
1666 static void zs_object_copy(struct size_class *class, unsigned long dst,
1669 struct page *s_page, *d_page;
1670 unsigned int s_objidx, d_objidx;
1671 unsigned long s_off, d_off;
1672 void *s_addr, *d_addr;
1673 int s_size, d_size, size;
1676 s_size = d_size = class->size;
1678 obj_to_location(src, &s_page, &s_objidx);
1679 obj_to_location(dst, &d_page, &d_objidx);
1681 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1682 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1684 if (s_off + class->size > PAGE_SIZE)
1685 s_size = PAGE_SIZE - s_off;
1687 if (d_off + class->size > PAGE_SIZE)
1688 d_size = PAGE_SIZE - d_off;
1690 s_addr = kmap_atomic(s_page);
1691 d_addr = kmap_atomic(d_page);
1694 size = min(s_size, d_size);
1695 memcpy(d_addr + d_off, s_addr + s_off, size);
1698 if (written == class->size)
1707 * Calling kunmap_atomic(d_addr) is necessary. kunmap_atomic()
1708 * calls must occurs in reverse order of calls to kmap_atomic().
1709 * So, to call kunmap_atomic(s_addr) we should first call
1710 * kunmap_atomic(d_addr). For more details see
1711 * Documentation/mm/highmem.rst.
1713 if (s_off >= PAGE_SIZE) {
1714 kunmap_atomic(d_addr);
1715 kunmap_atomic(s_addr);
1716 s_page = get_next_page(s_page);
1717 s_addr = kmap_atomic(s_page);
1718 d_addr = kmap_atomic(d_page);
1719 s_size = class->size - written;
1723 if (d_off >= PAGE_SIZE) {
1724 kunmap_atomic(d_addr);
1725 d_page = get_next_page(d_page);
1726 d_addr = kmap_atomic(d_page);
1727 d_size = class->size - written;
1732 kunmap_atomic(d_addr);
1733 kunmap_atomic(s_addr);
1737 * Find object with a certain tag in zspage from index object and
1740 static unsigned long find_tagged_obj(struct size_class *class,
1741 struct page *page, int *obj_idx, int tag)
1743 unsigned int offset;
1744 int index = *obj_idx;
1745 unsigned long handle = 0;
1746 void *addr = kmap_atomic(page);
1748 offset = get_first_obj_offset(page);
1749 offset += class->size * index;
1751 while (offset < PAGE_SIZE) {
1752 if (obj_tagged(page, addr + offset, &handle, tag))
1755 offset += class->size;
1759 kunmap_atomic(addr);
1767 * Find alloced object in zspage from index object and
1770 static unsigned long find_alloced_obj(struct size_class *class,
1771 struct page *page, int *obj_idx)
1773 return find_tagged_obj(class, page, obj_idx, OBJ_ALLOCATED_TAG);
1778 * Find object storing a deferred handle in header in zspage from index object
1779 * and return handle.
1781 static unsigned long find_deferred_handle_obj(struct size_class *class,
1782 struct page *page, int *obj_idx)
1784 return find_tagged_obj(class, page, obj_idx, OBJ_DEFERRED_HANDLE_TAG);
1788 struct zs_compact_control {
1789 /* Source spage for migration which could be a subpage of zspage */
1790 struct page *s_page;
1791 /* Destination page for migration which should be a first page
1793 struct page *d_page;
1794 /* Starting object index within @s_page which used for live object
1795 * in the subpage. */
1799 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1800 struct zs_compact_control *cc)
1802 unsigned long used_obj, free_obj;
1803 unsigned long handle;
1804 struct page *s_page = cc->s_page;
1805 struct page *d_page = cc->d_page;
1806 int obj_idx = cc->obj_idx;
1810 handle = find_alloced_obj(class, s_page, &obj_idx);
1812 s_page = get_next_page(s_page);
1819 /* Stop if there is no more space */
1820 if (zspage_full(class, get_zspage(d_page))) {
1825 used_obj = handle_to_obj(handle);
1826 free_obj = obj_malloc(pool, get_zspage(d_page), handle);
1827 zs_object_copy(class, free_obj, used_obj);
1829 record_obj(handle, free_obj);
1830 obj_free(class->size, used_obj, NULL);
1833 /* Remember last position in this iteration */
1834 cc->s_page = s_page;
1835 cc->obj_idx = obj_idx;
1840 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1843 struct zspage *zspage;
1844 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1847 fg[0] = ZS_ALMOST_FULL;
1848 fg[1] = ZS_ALMOST_EMPTY;
1851 for (i = 0; i < 2; i++) {
1852 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1853 struct zspage, list);
1855 remove_zspage(class, zspage, fg[i]);
1864 * putback_zspage - add @zspage into right class's fullness list
1865 * @class: destination class
1866 * @zspage: target page
1868 * Return @zspage's fullness_group
1870 static enum fullness_group putback_zspage(struct size_class *class,
1871 struct zspage *zspage)
1873 enum fullness_group fullness;
1875 fullness = get_fullness_group(class, zspage);
1876 insert_zspage(class, zspage, fullness);
1877 set_zspage_mapping(zspage, class->index, fullness);
1882 #if defined(CONFIG_ZPOOL) || defined(CONFIG_COMPACTION)
1884 * To prevent zspage destroy during migration, zspage freeing should
1885 * hold locks of all pages in the zspage.
1887 static void lock_zspage(struct zspage *zspage)
1889 struct page *curr_page, *page;
1892 * Pages we haven't locked yet can be migrated off the list while we're
1893 * trying to lock them, so we need to be careful and only attempt to
1894 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1895 * may no longer belong to the zspage. This means that we may wait for
1896 * the wrong page to unlock, so we must take a reference to the page
1897 * prior to waiting for it to unlock outside migrate_read_lock().
1900 migrate_read_lock(zspage);
1901 page = get_first_page(zspage);
1902 if (trylock_page(page))
1905 migrate_read_unlock(zspage);
1906 wait_on_page_locked(page);
1911 while ((page = get_next_page(curr_page))) {
1912 if (trylock_page(page)) {
1916 migrate_read_unlock(zspage);
1917 wait_on_page_locked(page);
1919 migrate_read_lock(zspage);
1922 migrate_read_unlock(zspage);
1924 #endif /* defined(CONFIG_ZPOOL) || defined(CONFIG_COMPACTION) */
1928 * Unlocks all the pages of the zspage.
1930 * pool->lock must be held before this function is called
1931 * to prevent the underlying pages from migrating.
1933 static void unlock_zspage(struct zspage *zspage)
1935 struct page *page = get_first_page(zspage);
1939 } while ((page = get_next_page(page)) != NULL);
1941 #endif /* CONFIG_ZPOOL */
1943 static void migrate_lock_init(struct zspage *zspage)
1945 rwlock_init(&zspage->lock);
1948 static void migrate_read_lock(struct zspage *zspage) __acquires(&zspage->lock)
1950 read_lock(&zspage->lock);
1953 static void migrate_read_unlock(struct zspage *zspage) __releases(&zspage->lock)
1955 read_unlock(&zspage->lock);
1958 #ifdef CONFIG_COMPACTION
1959 static void migrate_write_lock(struct zspage *zspage)
1961 write_lock(&zspage->lock);
1964 static void migrate_write_lock_nested(struct zspage *zspage)
1966 write_lock_nested(&zspage->lock, SINGLE_DEPTH_NESTING);
1969 static void migrate_write_unlock(struct zspage *zspage)
1971 write_unlock(&zspage->lock);
1974 /* Number of isolated subpage for *page migration* in this zspage */
1975 static void inc_zspage_isolation(struct zspage *zspage)
1980 static void dec_zspage_isolation(struct zspage *zspage)
1982 VM_BUG_ON(zspage->isolated == 0);
1986 static const struct movable_operations zsmalloc_mops;
1988 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1989 struct page *newpage, struct page *oldpage)
1992 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1995 page = get_first_page(zspage);
1997 if (page == oldpage)
1998 pages[idx] = newpage;
2002 } while ((page = get_next_page(page)) != NULL);
2004 create_page_chain(class, zspage, pages);
2005 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
2006 if (unlikely(ZsHugePage(zspage)))
2007 newpage->index = oldpage->index;
2008 __SetPageMovable(newpage, &zsmalloc_mops);
2011 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
2013 struct zspage *zspage;
2016 * Page is locked so zspage couldn't be destroyed. For detail, look at
2017 * lock_zspage in free_zspage.
2019 VM_BUG_ON_PAGE(PageIsolated(page), page);
2021 zspage = get_zspage(page);
2022 migrate_write_lock(zspage);
2023 inc_zspage_isolation(zspage);
2024 migrate_write_unlock(zspage);
2029 static int zs_page_migrate(struct page *newpage, struct page *page,
2030 enum migrate_mode mode)
2032 struct zs_pool *pool;
2033 struct size_class *class;
2034 struct zspage *zspage;
2036 void *s_addr, *d_addr, *addr;
2037 unsigned int offset;
2038 unsigned long handle;
2039 unsigned long old_obj, new_obj;
2040 unsigned int obj_idx;
2043 * We cannot support the _NO_COPY case here, because copy needs to
2044 * happen under the zs lock, which does not work with
2045 * MIGRATE_SYNC_NO_COPY workflow.
2047 if (mode == MIGRATE_SYNC_NO_COPY)
2050 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2052 /* The page is locked, so this pointer must remain valid */
2053 zspage = get_zspage(page);
2054 pool = zspage->pool;
2057 * The pool's lock protects the race between zpage migration
2060 spin_lock(&pool->lock);
2061 class = zspage_class(pool, zspage);
2063 /* the migrate_write_lock protects zpage access via zs_map_object */
2064 migrate_write_lock(zspage);
2066 offset = get_first_obj_offset(page);
2067 s_addr = kmap_atomic(page);
2070 * Here, any user cannot access all objects in the zspage so let's move.
2072 d_addr = kmap_atomic(newpage);
2073 memcpy(d_addr, s_addr, PAGE_SIZE);
2074 kunmap_atomic(d_addr);
2076 for (addr = s_addr + offset; addr < s_addr + PAGE_SIZE;
2077 addr += class->size) {
2078 if (obj_allocated(page, addr, &handle)) {
2080 old_obj = handle_to_obj(handle);
2081 obj_to_location(old_obj, &dummy, &obj_idx);
2082 new_obj = (unsigned long)location_to_obj(newpage,
2084 record_obj(handle, new_obj);
2087 kunmap_atomic(s_addr);
2089 replace_sub_page(class, zspage, newpage, page);
2091 * Since we complete the data copy and set up new zspage structure,
2092 * it's okay to release the pool's lock.
2094 spin_unlock(&pool->lock);
2095 dec_zspage_isolation(zspage);
2096 migrate_write_unlock(zspage);
2099 if (page_zone(newpage) != page_zone(page)) {
2100 dec_zone_page_state(page, NR_ZSPAGES);
2101 inc_zone_page_state(newpage, NR_ZSPAGES);
2107 return MIGRATEPAGE_SUCCESS;
2110 static void zs_page_putback(struct page *page)
2112 struct zspage *zspage;
2114 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2116 zspage = get_zspage(page);
2117 migrate_write_lock(zspage);
2118 dec_zspage_isolation(zspage);
2119 migrate_write_unlock(zspage);
2122 static const struct movable_operations zsmalloc_mops = {
2123 .isolate_page = zs_page_isolate,
2124 .migrate_page = zs_page_migrate,
2125 .putback_page = zs_page_putback,
2129 * Caller should hold page_lock of all pages in the zspage
2130 * In here, we cannot use zspage meta data.
2132 static void async_free_zspage(struct work_struct *work)
2135 struct size_class *class;
2136 unsigned int class_idx;
2137 enum fullness_group fullness;
2138 struct zspage *zspage, *tmp;
2139 LIST_HEAD(free_pages);
2140 struct zs_pool *pool = container_of(work, struct zs_pool,
2143 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2144 class = pool->size_class[i];
2145 if (class->index != i)
2148 spin_lock(&pool->lock);
2149 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2150 spin_unlock(&pool->lock);
2153 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2154 list_del(&zspage->list);
2155 lock_zspage(zspage);
2157 get_zspage_mapping(zspage, &class_idx, &fullness);
2158 VM_BUG_ON(fullness != ZS_EMPTY);
2159 class = pool->size_class[class_idx];
2160 spin_lock(&pool->lock);
2162 list_del(&zspage->lru);
2164 __free_zspage(pool, class, zspage);
2165 spin_unlock(&pool->lock);
2169 static void kick_deferred_free(struct zs_pool *pool)
2171 schedule_work(&pool->free_work);
2174 static void zs_flush_migration(struct zs_pool *pool)
2176 flush_work(&pool->free_work);
2179 static void init_deferred_free(struct zs_pool *pool)
2181 INIT_WORK(&pool->free_work, async_free_zspage);
2184 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2186 struct page *page = get_first_page(zspage);
2189 WARN_ON(!trylock_page(page));
2190 __SetPageMovable(page, &zsmalloc_mops);
2192 } while ((page = get_next_page(page)) != NULL);
2195 static inline void zs_flush_migration(struct zs_pool *pool) { }
2200 * Based on the number of unused allocated objects calculate
2201 * and return the number of pages that we can free.
2203 static unsigned long zs_can_compact(struct size_class *class)
2205 unsigned long obj_wasted;
2206 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2207 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2209 if (obj_allocated <= obj_used)
2212 obj_wasted = obj_allocated - obj_used;
2213 obj_wasted /= class->objs_per_zspage;
2215 return obj_wasted * class->pages_per_zspage;
2218 static unsigned long __zs_compact(struct zs_pool *pool,
2219 struct size_class *class)
2221 struct zs_compact_control cc;
2222 struct zspage *src_zspage;
2223 struct zspage *dst_zspage = NULL;
2224 unsigned long pages_freed = 0;
2227 * protect the race between zpage migration and zs_free
2228 * as well as zpage allocation/free
2230 spin_lock(&pool->lock);
2231 while ((src_zspage = isolate_zspage(class, true))) {
2232 /* protect someone accessing the zspage(i.e., zs_map_object) */
2233 migrate_write_lock(src_zspage);
2235 if (!zs_can_compact(class))
2239 cc.s_page = get_first_page(src_zspage);
2241 while ((dst_zspage = isolate_zspage(class, false))) {
2242 migrate_write_lock_nested(dst_zspage);
2244 cc.d_page = get_first_page(dst_zspage);
2246 * If there is no more space in dst_page, resched
2247 * and see if anyone had allocated another zspage.
2249 if (!migrate_zspage(pool, class, &cc))
2252 putback_zspage(class, dst_zspage);
2253 migrate_write_unlock(dst_zspage);
2255 if (spin_is_contended(&pool->lock))
2259 /* Stop if we couldn't find slot */
2260 if (dst_zspage == NULL)
2263 putback_zspage(class, dst_zspage);
2264 migrate_write_unlock(dst_zspage);
2266 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2267 migrate_write_unlock(src_zspage);
2268 free_zspage(pool, class, src_zspage);
2269 pages_freed += class->pages_per_zspage;
2271 migrate_write_unlock(src_zspage);
2272 spin_unlock(&pool->lock);
2274 spin_lock(&pool->lock);
2278 putback_zspage(class, src_zspage);
2279 migrate_write_unlock(src_zspage);
2282 spin_unlock(&pool->lock);
2287 unsigned long zs_compact(struct zs_pool *pool)
2290 struct size_class *class;
2291 unsigned long pages_freed = 0;
2293 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2294 class = pool->size_class[i];
2295 if (class->index != i)
2297 pages_freed += __zs_compact(pool, class);
2299 atomic_long_add(pages_freed, &pool->stats.pages_compacted);
2303 EXPORT_SYMBOL_GPL(zs_compact);
2305 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2307 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2309 EXPORT_SYMBOL_GPL(zs_pool_stats);
2311 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2312 struct shrink_control *sc)
2314 unsigned long pages_freed;
2315 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2319 * Compact classes and calculate compaction delta.
2320 * Can run concurrently with a manually triggered
2321 * (by user) compaction.
2323 pages_freed = zs_compact(pool);
2325 return pages_freed ? pages_freed : SHRINK_STOP;
2328 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2329 struct shrink_control *sc)
2332 struct size_class *class;
2333 unsigned long pages_to_free = 0;
2334 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2337 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2338 class = pool->size_class[i];
2339 if (class->index != i)
2342 pages_to_free += zs_can_compact(class);
2345 return pages_to_free;
2348 static void zs_unregister_shrinker(struct zs_pool *pool)
2350 unregister_shrinker(&pool->shrinker);
2353 static int zs_register_shrinker(struct zs_pool *pool)
2355 pool->shrinker.scan_objects = zs_shrinker_scan;
2356 pool->shrinker.count_objects = zs_shrinker_count;
2357 pool->shrinker.batch = 0;
2358 pool->shrinker.seeks = DEFAULT_SEEKS;
2360 return register_shrinker(&pool->shrinker, "mm-zspool:%s",
2364 static int calculate_zspage_chain_size(int class_size)
2366 int i, min_waste = INT_MAX;
2369 if (is_power_of_2(class_size))
2372 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
2375 waste = (i * PAGE_SIZE) % class_size;
2376 if (waste < min_waste) {
2386 * zs_create_pool - Creates an allocation pool to work from.
2387 * @name: pool name to be created
2389 * This function must be called before anything when using
2390 * the zsmalloc allocator.
2392 * On success, a pointer to the newly created pool is returned,
2395 struct zs_pool *zs_create_pool(const char *name)
2398 struct zs_pool *pool;
2399 struct size_class *prev_class = NULL;
2401 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2405 init_deferred_free(pool);
2406 spin_lock_init(&pool->lock);
2408 pool->name = kstrdup(name, GFP_KERNEL);
2412 if (create_cache(pool))
2416 * Iterate reversely, because, size of size_class that we want to use
2417 * for merging should be larger or equal to current size.
2419 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2421 int pages_per_zspage;
2422 int objs_per_zspage;
2423 struct size_class *class;
2426 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2427 if (size > ZS_MAX_ALLOC_SIZE)
2428 size = ZS_MAX_ALLOC_SIZE;
2429 pages_per_zspage = calculate_zspage_chain_size(size);
2430 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2433 * We iterate from biggest down to smallest classes,
2434 * so huge_class_size holds the size of the first huge
2435 * class. Any object bigger than or equal to that will
2436 * endup in the huge class.
2438 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2440 huge_class_size = size;
2442 * The object uses ZS_HANDLE_SIZE bytes to store the
2443 * handle. We need to subtract it, because zs_malloc()
2444 * unconditionally adds handle size before it performs
2445 * size class search - so object may be smaller than
2446 * huge class size, yet it still can end up in the huge
2447 * class because it grows by ZS_HANDLE_SIZE extra bytes
2448 * right before class lookup.
2450 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2454 * size_class is used for normal zsmalloc operation such
2455 * as alloc/free for that size. Although it is natural that we
2456 * have one size_class for each size, there is a chance that we
2457 * can get more memory utilization if we use one size_class for
2458 * many different sizes whose size_class have same
2459 * characteristics. So, we makes size_class point to
2460 * previous size_class if possible.
2463 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2464 pool->size_class[i] = prev_class;
2469 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2475 class->pages_per_zspage = pages_per_zspage;
2476 class->objs_per_zspage = objs_per_zspage;
2477 pool->size_class[i] = class;
2478 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2480 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2485 /* debug only, don't abort if it fails */
2486 zs_pool_stat_create(pool, name);
2489 * Not critical since shrinker is only used to trigger internal
2490 * defragmentation of the pool which is pretty optional thing. If
2491 * registration fails we still can use the pool normally and user can
2492 * trigger compaction manually. Thus, ignore return code.
2494 zs_register_shrinker(pool);
2497 INIT_LIST_HEAD(&pool->lru);
2503 zs_destroy_pool(pool);
2506 EXPORT_SYMBOL_GPL(zs_create_pool);
2508 void zs_destroy_pool(struct zs_pool *pool)
2512 zs_unregister_shrinker(pool);
2513 zs_flush_migration(pool);
2514 zs_pool_stat_destroy(pool);
2516 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2518 struct size_class *class = pool->size_class[i];
2523 if (class->index != i)
2526 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2527 if (!list_empty(&class->fullness_list[fg])) {
2528 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2535 destroy_cache(pool);
2539 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2542 static void restore_freelist(struct zs_pool *pool, struct size_class *class,
2543 struct zspage *zspage)
2545 unsigned int obj_idx = 0;
2546 unsigned long handle, off = 0; /* off is within-page offset */
2547 struct page *page = get_first_page(zspage);
2548 struct link_free *prev_free = NULL;
2549 void *prev_page_vaddr = NULL;
2551 /* in case no free object found */
2552 set_freeobj(zspage, (unsigned int)(-1UL));
2555 void *vaddr = kmap_atomic(page);
2556 struct page *next_page;
2558 while (off < PAGE_SIZE) {
2559 void *obj_addr = vaddr + off;
2561 /* skip allocated object */
2562 if (obj_allocated(page, obj_addr, &handle)) {
2568 /* free deferred handle from reclaim attempt */
2569 if (obj_stores_deferred_handle(page, obj_addr, &handle))
2570 cache_free_handle(pool, handle);
2573 prev_free->next = obj_idx << OBJ_TAG_BITS;
2574 else /* first free object found */
2575 set_freeobj(zspage, obj_idx);
2577 prev_free = (struct link_free *)vaddr + off / sizeof(*prev_free);
2578 /* if last free object in a previous page, need to unmap */
2579 if (prev_page_vaddr) {
2580 kunmap_atomic(prev_page_vaddr);
2581 prev_page_vaddr = NULL;
2589 * Handle the last (full or partial) object on this page.
2591 next_page = get_next_page(page);
2593 if (!prev_free || prev_page_vaddr) {
2595 * There is no free object in this page, so we can safely
2598 kunmap_atomic(vaddr);
2600 /* update prev_page_vaddr since prev_free is on this page */
2601 prev_page_vaddr = vaddr;
2603 } else { /* this is the last page */
2606 * Reset OBJ_TAG_BITS bit to last link to tell
2607 * whether it's allocated object or not.
2609 prev_free->next = -1UL << OBJ_TAG_BITS;
2612 /* unmap previous page (if not done yet) */
2613 if (prev_page_vaddr) {
2614 kunmap_atomic(prev_page_vaddr);
2615 prev_page_vaddr = NULL;
2618 kunmap_atomic(vaddr);
2626 static int zs_reclaim_page(struct zs_pool *pool, unsigned int retries)
2628 int i, obj_idx, ret = 0;
2629 unsigned long handle;
2630 struct zspage *zspage;
2632 enum fullness_group fullness;
2634 /* Lock LRU and fullness list */
2635 spin_lock(&pool->lock);
2636 if (list_empty(&pool->lru)) {
2637 spin_unlock(&pool->lock);
2641 for (i = 0; i < retries; i++) {
2642 struct size_class *class;
2644 zspage = list_last_entry(&pool->lru, struct zspage, lru);
2645 list_del(&zspage->lru);
2647 /* zs_free may free objects, but not the zspage and handles */
2648 zspage->under_reclaim = true;
2650 class = zspage_class(pool, zspage);
2651 fullness = get_fullness_group(class, zspage);
2653 /* Lock out object allocations and object compaction */
2654 remove_zspage(class, zspage, fullness);
2656 spin_unlock(&pool->lock);
2659 /* Lock backing pages into place */
2660 lock_zspage(zspage);
2663 page = get_first_page(zspage);
2665 handle = find_alloced_obj(class, page, &obj_idx);
2667 page = get_next_page(page);
2675 * This will write the object and call zs_free.
2677 * zs_free will free the object, but the
2678 * under_reclaim flag prevents it from freeing
2679 * the zspage altogether. This is necessary so
2680 * that we can continue working with the
2681 * zspage potentially after the last object
2684 ret = pool->zpool_ops->evict(pool->zpool, handle);
2692 /* For freeing the zspage, or putting it back in the pool and LRU list. */
2693 spin_lock(&pool->lock);
2694 zspage->under_reclaim = false;
2696 if (!get_zspage_inuse(zspage)) {
2698 * Fullness went stale as zs_free() won't touch it
2699 * while the page is removed from the pool. Fix it
2700 * up for the check in __free_zspage().
2702 zspage->fullness = ZS_EMPTY;
2704 __free_zspage(pool, class, zspage);
2705 spin_unlock(&pool->lock);
2710 * Eviction fails on one of the handles, so we need to restore zspage.
2711 * We need to rebuild its freelist (and free stored deferred handles),
2712 * put it back to the correct size class, and add it to the LRU list.
2714 restore_freelist(pool, class, zspage);
2715 putback_zspage(class, zspage);
2716 list_add(&zspage->lru, &pool->lru);
2717 unlock_zspage(zspage);
2720 spin_unlock(&pool->lock);
2723 #endif /* CONFIG_ZPOOL */
2725 static int __init zs_init(void)
2729 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2730 zs_cpu_prepare, zs_cpu_dead);
2735 zpool_register_driver(&zs_zpool_driver);
2746 static void __exit zs_exit(void)
2749 zpool_unregister_driver(&zs_zpool_driver);
2751 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2756 module_init(zs_init);
2757 module_exit(zs_exit);
2759 MODULE_LICENSE("Dual BSD/GPL");
2760 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");