2 * zsmalloc memory allocator
4 * Copyright (C) 2011 Nitin Gupta
5 * Copyright (C) 2012, 2013 Minchan Kim
7 * This code is released using a dual license strategy: BSD/GPL
8 * You can choose the license that better fits your requirements.
10 * Released under the terms of 3-clause BSD License
11 * Released under the terms of GNU General Public License Version 2.0
15 * Following is how we use various fields and flags of underlying
16 * struct page(s) to form a zspage.
18 * Usage of struct page fields:
19 * page->private: points to zspage
20 * page->freelist(index): links together all component pages of a zspage
21 * For the huge page, this is always 0, so we use this field
23 * page->units: first object offset in a subpage of zspage
25 * Usage of struct page flags:
26 * PG_private: identifies the first component page
27 * PG_owner_priv_1: identifies the huge component page
31 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/sched.h>
36 #include <linux/magic.h>
37 #include <linux/bitops.h>
38 #include <linux/errno.h>
39 #include <linux/highmem.h>
40 #include <linux/string.h>
41 #include <linux/slab.h>
42 #include <asm/tlbflush.h>
43 #include <asm/pgtable.h>
44 #include <linux/cpumask.h>
45 #include <linux/cpu.h>
46 #include <linux/vmalloc.h>
47 #include <linux/preempt.h>
48 #include <linux/spinlock.h>
49 #include <linux/shrinker.h>
50 #include <linux/types.h>
51 #include <linux/debugfs.h>
52 #include <linux/zsmalloc.h>
53 #include <linux/zpool.h>
54 #include <linux/mount.h>
55 #include <linux/pseudo_fs.h>
56 #include <linux/migrate.h>
57 #include <linux/pagemap.h>
60 #define ZSPAGE_MAGIC 0x58
63 * This must be power of 2 and greater than of equal to sizeof(link_free).
64 * These two conditions ensure that any 'struct link_free' itself doesn't
65 * span more than 1 page which avoids complex case of mapping 2 pages simply
66 * to restore link_free pointer values.
71 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
72 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
74 #define ZS_MAX_ZSPAGE_ORDER 2
75 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
77 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
80 * Object location (<PFN>, <obj_idx>) is encoded as
81 * as single (unsigned long) handle value.
83 * Note that object index <obj_idx> starts from 0.
85 * This is made more complicated by various memory models and PAE.
88 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
89 #ifdef MAX_PHYSMEM_BITS
90 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
93 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
96 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
100 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
103 * Memory for allocating for handle keeps object position by
104 * encoding <page, obj_idx> and the encoded value has a room
105 * in least bit(ie, look at obj_to_location).
106 * We use the bit to synchronize between object access by
107 * user and migration.
109 #define HANDLE_PIN_BIT 0
112 * Head in allocated object should have OBJ_ALLOCATED_TAG
113 * to identify the object was allocated or not.
114 * It's okay to add the status bit in the least bit because
115 * header keeps handle which is 4byte-aligned address so we
116 * have room for two bit at least.
118 #define OBJ_ALLOCATED_TAG 1
119 #define OBJ_TAG_BITS 1
120 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
121 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
123 #define FULLNESS_BITS 2
125 #define ISOLATED_BITS 3
126 #define MAGIC_VAL_BITS 8
128 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
129 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
130 #define ZS_MIN_ALLOC_SIZE \
131 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
132 /* each chunk includes extra space to keep handle */
133 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
136 * On systems with 4K page size, this gives 255 size classes! There is a
138 * - Large number of size classes is potentially wasteful as free page are
139 * spread across these classes
140 * - Small number of size classes causes large internal fragmentation
141 * - Probably its better to use specific size classes (empirically
142 * determined). NOTE: all those class sizes must be set as multiple of
143 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
145 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
148 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
149 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
150 ZS_SIZE_CLASS_DELTA) + 1)
152 enum fullness_group {
170 struct zs_size_stat {
171 unsigned long objs[NR_ZS_STAT_TYPE];
174 #ifdef CONFIG_ZSMALLOC_STAT
175 static struct dentry *zs_stat_root;
178 #ifdef CONFIG_COMPACTION
179 static struct vfsmount *zsmalloc_mnt;
183 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
185 * n = number of allocated objects
186 * N = total number of objects zspage can store
187 * f = fullness_threshold_frac
189 * Similarly, we assign zspage to:
190 * ZS_ALMOST_FULL when n > N / f
191 * ZS_EMPTY when n == 0
192 * ZS_FULL when n == N
194 * (see: fix_fullness_group())
196 static const int fullness_threshold_frac = 4;
197 static size_t huge_class_size;
201 struct list_head fullness_list[NR_ZS_FULLNESS];
203 * Size of objects stored in this class. Must be multiple
208 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
209 int pages_per_zspage;
212 struct zs_size_stat stats;
215 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
216 static void SetPageHugeObject(struct page *page)
218 SetPageOwnerPriv1(page);
221 static void ClearPageHugeObject(struct page *page)
223 ClearPageOwnerPriv1(page);
226 static int PageHugeObject(struct page *page)
228 return PageOwnerPriv1(page);
232 * Placed within free objects to form a singly linked list.
233 * For every zspage, zspage->freeobj gives head of this list.
235 * This must be power of 2 and less than or equal to ZS_ALIGN
241 * It's valid for non-allocated object
245 * Handle of allocated object.
247 unsigned long handle;
254 struct size_class *size_class[ZS_SIZE_CLASSES];
255 struct kmem_cache *handle_cachep;
256 struct kmem_cache *zspage_cachep;
258 atomic_long_t pages_allocated;
260 struct zs_pool_stats stats;
262 /* Compact classes */
263 struct shrinker shrinker;
265 #ifdef CONFIG_ZSMALLOC_STAT
266 struct dentry *stat_dentry;
268 #ifdef CONFIG_COMPACTION
270 struct work_struct free_work;
276 unsigned int fullness:FULLNESS_BITS;
277 unsigned int class:CLASS_BITS + 1;
278 unsigned int isolated:ISOLATED_BITS;
279 unsigned int magic:MAGIC_VAL_BITS;
282 unsigned int freeobj;
283 struct page *first_page;
284 struct list_head list; /* fullness list */
285 #ifdef CONFIG_COMPACTION
290 struct mapping_area {
291 #ifdef CONFIG_PGTABLE_MAPPING
292 struct vm_struct *vm; /* vm area for mapping object that span pages */
294 char *vm_buf; /* copy buffer for objects that span pages */
296 char *vm_addr; /* address of kmap_atomic()'ed pages */
297 enum zs_mapmode vm_mm; /* mapping mode */
300 #ifdef CONFIG_COMPACTION
301 static int zs_register_migration(struct zs_pool *pool);
302 static void zs_unregister_migration(struct zs_pool *pool);
303 static void migrate_lock_init(struct zspage *zspage);
304 static void migrate_read_lock(struct zspage *zspage);
305 static void migrate_read_unlock(struct zspage *zspage);
306 static void kick_deferred_free(struct zs_pool *pool);
307 static void init_deferred_free(struct zs_pool *pool);
308 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage);
310 static int zsmalloc_mount(void) { return 0; }
311 static void zsmalloc_unmount(void) {}
312 static int zs_register_migration(struct zs_pool *pool) { return 0; }
313 static void zs_unregister_migration(struct zs_pool *pool) {}
314 static void migrate_lock_init(struct zspage *zspage) {}
315 static void migrate_read_lock(struct zspage *zspage) {}
316 static void migrate_read_unlock(struct zspage *zspage) {}
317 static void kick_deferred_free(struct zs_pool *pool) {}
318 static void init_deferred_free(struct zs_pool *pool) {}
319 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
322 static int create_cache(struct zs_pool *pool)
324 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
326 if (!pool->handle_cachep)
329 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
331 if (!pool->zspage_cachep) {
332 kmem_cache_destroy(pool->handle_cachep);
333 pool->handle_cachep = NULL;
340 static void destroy_cache(struct zs_pool *pool)
342 kmem_cache_destroy(pool->handle_cachep);
343 kmem_cache_destroy(pool->zspage_cachep);
346 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
348 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
349 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
352 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
354 kmem_cache_free(pool->handle_cachep, (void *)handle);
357 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
359 return kmem_cache_alloc(pool->zspage_cachep,
360 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
363 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
365 kmem_cache_free(pool->zspage_cachep, zspage);
368 static void record_obj(unsigned long handle, unsigned long obj)
371 * lsb of @obj represents handle lock while other bits
372 * represent object value the handle is pointing so
373 * updating shouldn't do store tearing.
375 WRITE_ONCE(*(unsigned long *)handle, obj);
382 static void *zs_zpool_create(const char *name, gfp_t gfp,
383 const struct zpool_ops *zpool_ops,
387 * Ignore global gfp flags: zs_malloc() may be invoked from
388 * different contexts and its caller must provide a valid
391 return zs_create_pool(name);
394 static void zs_zpool_destroy(void *pool)
396 zs_destroy_pool(pool);
399 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
400 unsigned long *handle)
402 *handle = zs_malloc(pool, size, gfp);
403 return *handle ? 0 : -1;
405 static void zs_zpool_free(void *pool, unsigned long handle)
407 zs_free(pool, handle);
410 static void *zs_zpool_map(void *pool, unsigned long handle,
411 enum zpool_mapmode mm)
413 enum zs_mapmode zs_mm;
422 case ZPOOL_MM_RW: /* fall through */
428 return zs_map_object(pool, handle, zs_mm);
430 static void zs_zpool_unmap(void *pool, unsigned long handle)
432 zs_unmap_object(pool, handle);
435 static u64 zs_zpool_total_size(void *pool)
437 return zs_get_total_pages(pool) << PAGE_SHIFT;
440 static struct zpool_driver zs_zpool_driver = {
442 .owner = THIS_MODULE,
443 .create = zs_zpool_create,
444 .destroy = zs_zpool_destroy,
445 .malloc = zs_zpool_malloc,
446 .free = zs_zpool_free,
448 .unmap = zs_zpool_unmap,
449 .total_size = zs_zpool_total_size,
452 MODULE_ALIAS("zpool-zsmalloc");
453 #endif /* CONFIG_ZPOOL */
455 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
456 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
458 static bool is_zspage_isolated(struct zspage *zspage)
460 return zspage->isolated;
463 static __maybe_unused int is_first_page(struct page *page)
465 return PagePrivate(page);
468 /* Protected by class->lock */
469 static inline int get_zspage_inuse(struct zspage *zspage)
471 return zspage->inuse;
474 static inline void set_zspage_inuse(struct zspage *zspage, int val)
479 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
481 zspage->inuse += val;
484 static inline struct page *get_first_page(struct zspage *zspage)
486 struct page *first_page = zspage->first_page;
488 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
492 static inline int get_first_obj_offset(struct page *page)
497 static inline void set_first_obj_offset(struct page *page, int offset)
499 page->units = offset;
502 static inline unsigned int get_freeobj(struct zspage *zspage)
504 return zspage->freeobj;
507 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
509 zspage->freeobj = obj;
512 static void get_zspage_mapping(struct zspage *zspage,
513 unsigned int *class_idx,
514 enum fullness_group *fullness)
516 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
518 *fullness = zspage->fullness;
519 *class_idx = zspage->class;
522 static void set_zspage_mapping(struct zspage *zspage,
523 unsigned int class_idx,
524 enum fullness_group fullness)
526 zspage->class = class_idx;
527 zspage->fullness = fullness;
531 * zsmalloc divides the pool into various size classes where each
532 * class maintains a list of zspages where each zspage is divided
533 * into equal sized chunks. Each allocation falls into one of these
534 * classes depending on its size. This function returns index of the
535 * size class which has chunk size big enough to hold the give size.
537 static int get_size_class_index(int size)
541 if (likely(size > ZS_MIN_ALLOC_SIZE))
542 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
543 ZS_SIZE_CLASS_DELTA);
545 return min_t(int, ZS_SIZE_CLASSES - 1, idx);
548 /* type can be of enum type zs_stat_type or fullness_group */
549 static inline void zs_stat_inc(struct size_class *class,
550 int type, unsigned long cnt)
552 class->stats.objs[type] += cnt;
555 /* type can be of enum type zs_stat_type or fullness_group */
556 static inline void zs_stat_dec(struct size_class *class,
557 int type, unsigned long cnt)
559 class->stats.objs[type] -= cnt;
562 /* type can be of enum type zs_stat_type or fullness_group */
563 static inline unsigned long zs_stat_get(struct size_class *class,
566 return class->stats.objs[type];
569 #ifdef CONFIG_ZSMALLOC_STAT
571 static void __init zs_stat_init(void)
573 if (!debugfs_initialized()) {
574 pr_warn("debugfs not available, stat dir not created\n");
578 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
581 static void __exit zs_stat_exit(void)
583 debugfs_remove_recursive(zs_stat_root);
586 static unsigned long zs_can_compact(struct size_class *class);
588 static int zs_stats_size_show(struct seq_file *s, void *v)
591 struct zs_pool *pool = s->private;
592 struct size_class *class;
594 unsigned long class_almost_full, class_almost_empty;
595 unsigned long obj_allocated, obj_used, pages_used, freeable;
596 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
597 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
598 unsigned long total_freeable = 0;
600 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
601 "class", "size", "almost_full", "almost_empty",
602 "obj_allocated", "obj_used", "pages_used",
603 "pages_per_zspage", "freeable");
605 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
606 class = pool->size_class[i];
608 if (class->index != i)
611 spin_lock(&class->lock);
612 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
613 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
614 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
615 obj_used = zs_stat_get(class, OBJ_USED);
616 freeable = zs_can_compact(class);
617 spin_unlock(&class->lock);
619 objs_per_zspage = class->objs_per_zspage;
620 pages_used = obj_allocated / objs_per_zspage *
621 class->pages_per_zspage;
623 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
624 " %10lu %10lu %16d %8lu\n",
625 i, class->size, class_almost_full, class_almost_empty,
626 obj_allocated, obj_used, pages_used,
627 class->pages_per_zspage, freeable);
629 total_class_almost_full += class_almost_full;
630 total_class_almost_empty += class_almost_empty;
631 total_objs += obj_allocated;
632 total_used_objs += obj_used;
633 total_pages += pages_used;
634 total_freeable += freeable;
638 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
639 "Total", "", total_class_almost_full,
640 total_class_almost_empty, total_objs,
641 total_used_objs, total_pages, "", total_freeable);
645 DEFINE_SHOW_ATTRIBUTE(zs_stats_size);
647 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
650 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
654 pool->stat_dentry = debugfs_create_dir(name, zs_stat_root);
656 debugfs_create_file("classes", S_IFREG | 0444, pool->stat_dentry, pool,
657 &zs_stats_size_fops);
660 static void zs_pool_stat_destroy(struct zs_pool *pool)
662 debugfs_remove_recursive(pool->stat_dentry);
665 #else /* CONFIG_ZSMALLOC_STAT */
666 static void __init zs_stat_init(void)
670 static void __exit zs_stat_exit(void)
674 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
678 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
685 * For each size class, zspages are divided into different groups
686 * depending on how "full" they are. This was done so that we could
687 * easily find empty or nearly empty zspages when we try to shrink
688 * the pool (not yet implemented). This function returns fullness
689 * status of the given page.
691 static enum fullness_group get_fullness_group(struct size_class *class,
692 struct zspage *zspage)
694 int inuse, objs_per_zspage;
695 enum fullness_group fg;
697 inuse = get_zspage_inuse(zspage);
698 objs_per_zspage = class->objs_per_zspage;
702 else if (inuse == objs_per_zspage)
704 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
705 fg = ZS_ALMOST_EMPTY;
713 * Each size class maintains various freelists and zspages are assigned
714 * to one of these freelists based on the number of live objects they
715 * have. This functions inserts the given zspage into the freelist
716 * identified by <class, fullness_group>.
718 static void insert_zspage(struct size_class *class,
719 struct zspage *zspage,
720 enum fullness_group fullness)
724 zs_stat_inc(class, fullness, 1);
725 head = list_first_entry_or_null(&class->fullness_list[fullness],
726 struct zspage, list);
728 * We want to see more ZS_FULL pages and less almost empty/full.
729 * Put pages with higher ->inuse first.
732 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
733 list_add(&zspage->list, &head->list);
737 list_add(&zspage->list, &class->fullness_list[fullness]);
741 * This function removes the given zspage from the freelist identified
742 * by <class, fullness_group>.
744 static void remove_zspage(struct size_class *class,
745 struct zspage *zspage,
746 enum fullness_group fullness)
748 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
749 VM_BUG_ON(is_zspage_isolated(zspage));
751 list_del_init(&zspage->list);
752 zs_stat_dec(class, fullness, 1);
756 * Each size class maintains zspages in different fullness groups depending
757 * on the number of live objects they contain. When allocating or freeing
758 * objects, the fullness status of the page can change, say, from ALMOST_FULL
759 * to ALMOST_EMPTY when freeing an object. This function checks if such
760 * a status change has occurred for the given page and accordingly moves the
761 * page from the freelist of the old fullness group to that of the new
764 static enum fullness_group fix_fullness_group(struct size_class *class,
765 struct zspage *zspage)
768 enum fullness_group currfg, newfg;
770 get_zspage_mapping(zspage, &class_idx, &currfg);
771 newfg = get_fullness_group(class, zspage);
775 if (!is_zspage_isolated(zspage)) {
776 remove_zspage(class, zspage, currfg);
777 insert_zspage(class, zspage, newfg);
780 set_zspage_mapping(zspage, class_idx, newfg);
787 * We have to decide on how many pages to link together
788 * to form a zspage for each size class. This is important
789 * to reduce wastage due to unusable space left at end of
790 * each zspage which is given as:
791 * wastage = Zp % class_size
792 * usage = Zp - wastage
793 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
795 * For example, for size class of 3/8 * PAGE_SIZE, we should
796 * link together 3 PAGE_SIZE sized pages to form a zspage
797 * since then we can perfectly fit in 8 such objects.
799 static int get_pages_per_zspage(int class_size)
801 int i, max_usedpc = 0;
802 /* zspage order which gives maximum used size per KB */
803 int max_usedpc_order = 1;
805 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
809 zspage_size = i * PAGE_SIZE;
810 waste = zspage_size % class_size;
811 usedpc = (zspage_size - waste) * 100 / zspage_size;
813 if (usedpc > max_usedpc) {
815 max_usedpc_order = i;
819 return max_usedpc_order;
822 static struct zspage *get_zspage(struct page *page)
824 struct zspage *zspage = (struct zspage *)page->private;
826 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
830 static struct page *get_next_page(struct page *page)
832 if (unlikely(PageHugeObject(page)))
835 return page->freelist;
839 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
840 * @obj: the encoded object value
841 * @page: page object resides in zspage
842 * @obj_idx: object index
844 static void obj_to_location(unsigned long obj, struct page **page,
845 unsigned int *obj_idx)
847 obj >>= OBJ_TAG_BITS;
848 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
849 *obj_idx = (obj & OBJ_INDEX_MASK);
853 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
854 * @page: page object resides in zspage
855 * @obj_idx: object index
857 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
861 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
862 obj |= obj_idx & OBJ_INDEX_MASK;
863 obj <<= OBJ_TAG_BITS;
868 static unsigned long handle_to_obj(unsigned long handle)
870 return *(unsigned long *)handle;
873 static unsigned long obj_to_head(struct page *page, void *obj)
875 if (unlikely(PageHugeObject(page))) {
876 VM_BUG_ON_PAGE(!is_first_page(page), page);
879 return *(unsigned long *)obj;
882 static inline int testpin_tag(unsigned long handle)
884 return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
887 static inline int trypin_tag(unsigned long handle)
889 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
892 static void pin_tag(unsigned long handle)
894 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
897 static void unpin_tag(unsigned long handle)
899 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
902 static void reset_page(struct page *page)
904 __ClearPageMovable(page);
905 ClearPagePrivate(page);
906 set_page_private(page, 0);
907 page_mapcount_reset(page);
908 ClearPageHugeObject(page);
909 page->freelist = NULL;
912 static int trylock_zspage(struct zspage *zspage)
914 struct page *cursor, *fail;
916 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
917 get_next_page(cursor)) {
918 if (!trylock_page(cursor)) {
926 for (cursor = get_first_page(zspage); cursor != fail; cursor =
927 get_next_page(cursor))
933 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
934 struct zspage *zspage)
936 struct page *page, *next;
937 enum fullness_group fg;
938 unsigned int class_idx;
940 get_zspage_mapping(zspage, &class_idx, &fg);
942 assert_spin_locked(&class->lock);
944 VM_BUG_ON(get_zspage_inuse(zspage));
945 VM_BUG_ON(fg != ZS_EMPTY);
947 next = page = get_first_page(zspage);
949 VM_BUG_ON_PAGE(!PageLocked(page), page);
950 next = get_next_page(page);
953 dec_zone_page_state(page, NR_ZSPAGES);
956 } while (page != NULL);
958 cache_free_zspage(pool, zspage);
960 zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
961 atomic_long_sub(class->pages_per_zspage,
962 &pool->pages_allocated);
965 static void free_zspage(struct zs_pool *pool, struct size_class *class,
966 struct zspage *zspage)
968 VM_BUG_ON(get_zspage_inuse(zspage));
969 VM_BUG_ON(list_empty(&zspage->list));
971 if (!trylock_zspage(zspage)) {
972 kick_deferred_free(pool);
976 remove_zspage(class, zspage, ZS_EMPTY);
977 __free_zspage(pool, class, zspage);
980 /* Initialize a newly allocated zspage */
981 static void init_zspage(struct size_class *class, struct zspage *zspage)
983 unsigned int freeobj = 1;
984 unsigned long off = 0;
985 struct page *page = get_first_page(zspage);
988 struct page *next_page;
989 struct link_free *link;
992 set_first_obj_offset(page, off);
994 vaddr = kmap_atomic(page);
995 link = (struct link_free *)vaddr + off / sizeof(*link);
997 while ((off += class->size) < PAGE_SIZE) {
998 link->next = freeobj++ << OBJ_TAG_BITS;
999 link += class->size / sizeof(*link);
1003 * We now come to the last (full or partial) object on this
1004 * page, which must point to the first object on the next
1007 next_page = get_next_page(page);
1009 link->next = freeobj++ << OBJ_TAG_BITS;
1012 * Reset OBJ_TAG_BITS bit to last link to tell
1013 * whether it's allocated object or not.
1015 link->next = -1UL << OBJ_TAG_BITS;
1017 kunmap_atomic(vaddr);
1022 set_freeobj(zspage, 0);
1025 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1026 struct page *pages[])
1030 struct page *prev_page = NULL;
1031 int nr_pages = class->pages_per_zspage;
1034 * Allocate individual pages and link them together as:
1035 * 1. all pages are linked together using page->freelist
1036 * 2. each sub-page point to zspage using page->private
1038 * we set PG_private to identify the first page (i.e. no other sub-page
1039 * has this flag set).
1041 for (i = 0; i < nr_pages; i++) {
1043 set_page_private(page, (unsigned long)zspage);
1044 page->freelist = NULL;
1046 zspage->first_page = page;
1047 SetPagePrivate(page);
1048 if (unlikely(class->objs_per_zspage == 1 &&
1049 class->pages_per_zspage == 1))
1050 SetPageHugeObject(page);
1052 prev_page->freelist = page;
1059 * Allocate a zspage for the given size class
1061 static struct zspage *alloc_zspage(struct zs_pool *pool,
1062 struct size_class *class,
1066 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1067 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1072 memset(zspage, 0, sizeof(struct zspage));
1073 zspage->magic = ZSPAGE_MAGIC;
1074 migrate_lock_init(zspage);
1076 for (i = 0; i < class->pages_per_zspage; i++) {
1079 page = alloc_page(gfp);
1082 dec_zone_page_state(pages[i], NR_ZSPAGES);
1083 __free_page(pages[i]);
1085 cache_free_zspage(pool, zspage);
1089 inc_zone_page_state(page, NR_ZSPAGES);
1093 create_page_chain(class, zspage, pages);
1094 init_zspage(class, zspage);
1099 static struct zspage *find_get_zspage(struct size_class *class)
1102 struct zspage *zspage;
1104 for (i = ZS_ALMOST_FULL; i >= ZS_EMPTY; i--) {
1105 zspage = list_first_entry_or_null(&class->fullness_list[i],
1106 struct zspage, list);
1114 #ifdef CONFIG_PGTABLE_MAPPING
1115 static inline int __zs_cpu_up(struct mapping_area *area)
1118 * Make sure we don't leak memory if a cpu UP notification
1119 * and zs_init() race and both call zs_cpu_up() on the same cpu
1123 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1129 static inline void __zs_cpu_down(struct mapping_area *area)
1132 free_vm_area(area->vm);
1136 static inline void *__zs_map_object(struct mapping_area *area,
1137 struct page *pages[2], int off, int size)
1139 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1140 area->vm_addr = area->vm->addr;
1141 return area->vm_addr + off;
1144 static inline void __zs_unmap_object(struct mapping_area *area,
1145 struct page *pages[2], int off, int size)
1147 unsigned long addr = (unsigned long)area->vm_addr;
1149 unmap_kernel_range(addr, PAGE_SIZE * 2);
1152 #else /* CONFIG_PGTABLE_MAPPING */
1154 static inline int __zs_cpu_up(struct mapping_area *area)
1157 * Make sure we don't leak memory if a cpu UP notification
1158 * and zs_init() race and both call zs_cpu_up() on the same cpu
1162 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1168 static inline void __zs_cpu_down(struct mapping_area *area)
1170 kfree(area->vm_buf);
1171 area->vm_buf = NULL;
1174 static void *__zs_map_object(struct mapping_area *area,
1175 struct page *pages[2], int off, int size)
1179 char *buf = area->vm_buf;
1181 /* disable page faults to match kmap_atomic() return conditions */
1182 pagefault_disable();
1184 /* no read fastpath */
1185 if (area->vm_mm == ZS_MM_WO)
1188 sizes[0] = PAGE_SIZE - off;
1189 sizes[1] = size - sizes[0];
1191 /* copy object to per-cpu buffer */
1192 addr = kmap_atomic(pages[0]);
1193 memcpy(buf, addr + off, sizes[0]);
1194 kunmap_atomic(addr);
1195 addr = kmap_atomic(pages[1]);
1196 memcpy(buf + sizes[0], addr, sizes[1]);
1197 kunmap_atomic(addr);
1199 return area->vm_buf;
1202 static void __zs_unmap_object(struct mapping_area *area,
1203 struct page *pages[2], int off, int size)
1209 /* no write fastpath */
1210 if (area->vm_mm == ZS_MM_RO)
1214 buf = buf + ZS_HANDLE_SIZE;
1215 size -= ZS_HANDLE_SIZE;
1216 off += ZS_HANDLE_SIZE;
1218 sizes[0] = PAGE_SIZE - off;
1219 sizes[1] = size - sizes[0];
1221 /* copy per-cpu buffer to object */
1222 addr = kmap_atomic(pages[0]);
1223 memcpy(addr + off, buf, sizes[0]);
1224 kunmap_atomic(addr);
1225 addr = kmap_atomic(pages[1]);
1226 memcpy(addr, buf + sizes[0], sizes[1]);
1227 kunmap_atomic(addr);
1230 /* enable page faults to match kunmap_atomic() return conditions */
1234 #endif /* CONFIG_PGTABLE_MAPPING */
1236 static int zs_cpu_prepare(unsigned int cpu)
1238 struct mapping_area *area;
1240 area = &per_cpu(zs_map_area, cpu);
1241 return __zs_cpu_up(area);
1244 static int zs_cpu_dead(unsigned int cpu)
1246 struct mapping_area *area;
1248 area = &per_cpu(zs_map_area, cpu);
1249 __zs_cpu_down(area);
1253 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1254 int objs_per_zspage)
1256 if (prev->pages_per_zspage == pages_per_zspage &&
1257 prev->objs_per_zspage == objs_per_zspage)
1263 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1265 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1268 unsigned long zs_get_total_pages(struct zs_pool *pool)
1270 return atomic_long_read(&pool->pages_allocated);
1272 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1275 * zs_map_object - get address of allocated object from handle.
1276 * @pool: pool from which the object was allocated
1277 * @handle: handle returned from zs_malloc
1278 * @mm: maping mode to use
1280 * Before using an object allocated from zs_malloc, it must be mapped using
1281 * this function. When done with the object, it must be unmapped using
1284 * Only one object can be mapped per cpu at a time. There is no protection
1285 * against nested mappings.
1287 * This function returns with preemption and page faults disabled.
1289 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1292 struct zspage *zspage;
1294 unsigned long obj, off;
1295 unsigned int obj_idx;
1297 unsigned int class_idx;
1298 enum fullness_group fg;
1299 struct size_class *class;
1300 struct mapping_area *area;
1301 struct page *pages[2];
1305 * Because we use per-cpu mapping areas shared among the
1306 * pools/users, we can't allow mapping in interrupt context
1307 * because it can corrupt another users mappings.
1309 BUG_ON(in_interrupt());
1311 /* From now on, migration cannot move the object */
1314 obj = handle_to_obj(handle);
1315 obj_to_location(obj, &page, &obj_idx);
1316 zspage = get_zspage(page);
1318 /* migration cannot move any subpage in this zspage */
1319 migrate_read_lock(zspage);
1321 get_zspage_mapping(zspage, &class_idx, &fg);
1322 class = pool->size_class[class_idx];
1323 off = (class->size * obj_idx) & ~PAGE_MASK;
1325 area = &get_cpu_var(zs_map_area);
1327 if (off + class->size <= PAGE_SIZE) {
1328 /* this object is contained entirely within a page */
1329 area->vm_addr = kmap_atomic(page);
1330 ret = area->vm_addr + off;
1334 /* this object spans two pages */
1336 pages[1] = get_next_page(page);
1339 ret = __zs_map_object(area, pages, off, class->size);
1341 if (likely(!PageHugeObject(page)))
1342 ret += ZS_HANDLE_SIZE;
1346 EXPORT_SYMBOL_GPL(zs_map_object);
1348 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1350 struct zspage *zspage;
1352 unsigned long obj, off;
1353 unsigned int obj_idx;
1355 unsigned int class_idx;
1356 enum fullness_group fg;
1357 struct size_class *class;
1358 struct mapping_area *area;
1360 obj = handle_to_obj(handle);
1361 obj_to_location(obj, &page, &obj_idx);
1362 zspage = get_zspage(page);
1363 get_zspage_mapping(zspage, &class_idx, &fg);
1364 class = pool->size_class[class_idx];
1365 off = (class->size * obj_idx) & ~PAGE_MASK;
1367 area = this_cpu_ptr(&zs_map_area);
1368 if (off + class->size <= PAGE_SIZE)
1369 kunmap_atomic(area->vm_addr);
1371 struct page *pages[2];
1374 pages[1] = get_next_page(page);
1377 __zs_unmap_object(area, pages, off, class->size);
1379 put_cpu_var(zs_map_area);
1381 migrate_read_unlock(zspage);
1384 EXPORT_SYMBOL_GPL(zs_unmap_object);
1387 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1388 * zsmalloc &size_class.
1389 * @pool: zsmalloc pool to use
1391 * The function returns the size of the first huge class - any object of equal
1392 * or bigger size will be stored in zspage consisting of a single physical
1395 * Context: Any context.
1397 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1399 size_t zs_huge_class_size(struct zs_pool *pool)
1401 return huge_class_size;
1403 EXPORT_SYMBOL_GPL(zs_huge_class_size);
1405 static unsigned long obj_malloc(struct size_class *class,
1406 struct zspage *zspage, unsigned long handle)
1408 int i, nr_page, offset;
1410 struct link_free *link;
1412 struct page *m_page;
1413 unsigned long m_offset;
1416 handle |= OBJ_ALLOCATED_TAG;
1417 obj = get_freeobj(zspage);
1419 offset = obj * class->size;
1420 nr_page = offset >> PAGE_SHIFT;
1421 m_offset = offset & ~PAGE_MASK;
1422 m_page = get_first_page(zspage);
1424 for (i = 0; i < nr_page; i++)
1425 m_page = get_next_page(m_page);
1427 vaddr = kmap_atomic(m_page);
1428 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1429 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1430 if (likely(!PageHugeObject(m_page)))
1431 /* record handle in the header of allocated chunk */
1432 link->handle = handle;
1434 /* record handle to page->index */
1435 zspage->first_page->index = handle;
1437 kunmap_atomic(vaddr);
1438 mod_zspage_inuse(zspage, 1);
1439 zs_stat_inc(class, OBJ_USED, 1);
1441 obj = location_to_obj(m_page, obj);
1448 * zs_malloc - Allocate block of given size from pool.
1449 * @pool: pool to allocate from
1450 * @size: size of block to allocate
1451 * @gfp: gfp flags when allocating object
1453 * On success, handle to the allocated object is returned,
1455 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1457 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1459 unsigned long handle, obj;
1460 struct size_class *class;
1461 enum fullness_group newfg;
1462 struct zspage *zspage;
1464 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1467 handle = cache_alloc_handle(pool, gfp);
1471 /* extra space in chunk to keep the handle */
1472 size += ZS_HANDLE_SIZE;
1473 class = pool->size_class[get_size_class_index(size)];
1475 spin_lock(&class->lock);
1476 zspage = find_get_zspage(class);
1477 if (likely(zspage)) {
1478 obj = obj_malloc(class, zspage, handle);
1479 /* Now move the zspage to another fullness group, if required */
1480 fix_fullness_group(class, zspage);
1481 record_obj(handle, obj);
1482 spin_unlock(&class->lock);
1487 spin_unlock(&class->lock);
1489 zspage = alloc_zspage(pool, class, gfp);
1491 cache_free_handle(pool, handle);
1495 spin_lock(&class->lock);
1496 obj = obj_malloc(class, zspage, handle);
1497 newfg = get_fullness_group(class, zspage);
1498 insert_zspage(class, zspage, newfg);
1499 set_zspage_mapping(zspage, class->index, newfg);
1500 record_obj(handle, obj);
1501 atomic_long_add(class->pages_per_zspage,
1502 &pool->pages_allocated);
1503 zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1505 /* We completely set up zspage so mark them as movable */
1506 SetZsPageMovable(pool, zspage);
1507 spin_unlock(&class->lock);
1511 EXPORT_SYMBOL_GPL(zs_malloc);
1513 static void obj_free(struct size_class *class, unsigned long obj)
1515 struct link_free *link;
1516 struct zspage *zspage;
1517 struct page *f_page;
1518 unsigned long f_offset;
1519 unsigned int f_objidx;
1522 obj &= ~OBJ_ALLOCATED_TAG;
1523 obj_to_location(obj, &f_page, &f_objidx);
1524 f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1525 zspage = get_zspage(f_page);
1527 vaddr = kmap_atomic(f_page);
1529 /* Insert this object in containing zspage's freelist */
1530 link = (struct link_free *)(vaddr + f_offset);
1531 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1532 kunmap_atomic(vaddr);
1533 set_freeobj(zspage, f_objidx);
1534 mod_zspage_inuse(zspage, -1);
1535 zs_stat_dec(class, OBJ_USED, 1);
1538 void zs_free(struct zs_pool *pool, unsigned long handle)
1540 struct zspage *zspage;
1541 struct page *f_page;
1543 unsigned int f_objidx;
1545 struct size_class *class;
1546 enum fullness_group fullness;
1549 if (unlikely(!handle))
1553 obj = handle_to_obj(handle);
1554 obj_to_location(obj, &f_page, &f_objidx);
1555 zspage = get_zspage(f_page);
1557 migrate_read_lock(zspage);
1559 get_zspage_mapping(zspage, &class_idx, &fullness);
1560 class = pool->size_class[class_idx];
1562 spin_lock(&class->lock);
1563 obj_free(class, obj);
1564 fullness = fix_fullness_group(class, zspage);
1565 if (fullness != ZS_EMPTY) {
1566 migrate_read_unlock(zspage);
1570 isolated = is_zspage_isolated(zspage);
1571 migrate_read_unlock(zspage);
1572 /* If zspage is isolated, zs_page_putback will free the zspage */
1573 if (likely(!isolated))
1574 free_zspage(pool, class, zspage);
1577 spin_unlock(&class->lock);
1579 cache_free_handle(pool, handle);
1581 EXPORT_SYMBOL_GPL(zs_free);
1583 static void zs_object_copy(struct size_class *class, unsigned long dst,
1586 struct page *s_page, *d_page;
1587 unsigned int s_objidx, d_objidx;
1588 unsigned long s_off, d_off;
1589 void *s_addr, *d_addr;
1590 int s_size, d_size, size;
1593 s_size = d_size = class->size;
1595 obj_to_location(src, &s_page, &s_objidx);
1596 obj_to_location(dst, &d_page, &d_objidx);
1598 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1599 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1601 if (s_off + class->size > PAGE_SIZE)
1602 s_size = PAGE_SIZE - s_off;
1604 if (d_off + class->size > PAGE_SIZE)
1605 d_size = PAGE_SIZE - d_off;
1607 s_addr = kmap_atomic(s_page);
1608 d_addr = kmap_atomic(d_page);
1611 size = min(s_size, d_size);
1612 memcpy(d_addr + d_off, s_addr + s_off, size);
1615 if (written == class->size)
1623 if (s_off >= PAGE_SIZE) {
1624 kunmap_atomic(d_addr);
1625 kunmap_atomic(s_addr);
1626 s_page = get_next_page(s_page);
1627 s_addr = kmap_atomic(s_page);
1628 d_addr = kmap_atomic(d_page);
1629 s_size = class->size - written;
1633 if (d_off >= PAGE_SIZE) {
1634 kunmap_atomic(d_addr);
1635 d_page = get_next_page(d_page);
1636 d_addr = kmap_atomic(d_page);
1637 d_size = class->size - written;
1642 kunmap_atomic(d_addr);
1643 kunmap_atomic(s_addr);
1647 * Find alloced object in zspage from index object and
1650 static unsigned long find_alloced_obj(struct size_class *class,
1651 struct page *page, int *obj_idx)
1655 int index = *obj_idx;
1656 unsigned long handle = 0;
1657 void *addr = kmap_atomic(page);
1659 offset = get_first_obj_offset(page);
1660 offset += class->size * index;
1662 while (offset < PAGE_SIZE) {
1663 head = obj_to_head(page, addr + offset);
1664 if (head & OBJ_ALLOCATED_TAG) {
1665 handle = head & ~OBJ_ALLOCATED_TAG;
1666 if (trypin_tag(handle))
1671 offset += class->size;
1675 kunmap_atomic(addr);
1682 struct zs_compact_control {
1683 /* Source spage for migration which could be a subpage of zspage */
1684 struct page *s_page;
1685 /* Destination page for migration which should be a first page
1687 struct page *d_page;
1688 /* Starting object index within @s_page which used for live object
1689 * in the subpage. */
1693 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1694 struct zs_compact_control *cc)
1696 unsigned long used_obj, free_obj;
1697 unsigned long handle;
1698 struct page *s_page = cc->s_page;
1699 struct page *d_page = cc->d_page;
1700 int obj_idx = cc->obj_idx;
1704 handle = find_alloced_obj(class, s_page, &obj_idx);
1706 s_page = get_next_page(s_page);
1713 /* Stop if there is no more space */
1714 if (zspage_full(class, get_zspage(d_page))) {
1720 used_obj = handle_to_obj(handle);
1721 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1722 zs_object_copy(class, free_obj, used_obj);
1725 * record_obj updates handle's value to free_obj and it will
1726 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1727 * breaks synchronization using pin_tag(e,g, zs_free) so
1728 * let's keep the lock bit.
1730 free_obj |= BIT(HANDLE_PIN_BIT);
1731 record_obj(handle, free_obj);
1733 obj_free(class, used_obj);
1736 /* Remember last position in this iteration */
1737 cc->s_page = s_page;
1738 cc->obj_idx = obj_idx;
1743 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1746 struct zspage *zspage;
1747 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1750 fg[0] = ZS_ALMOST_FULL;
1751 fg[1] = ZS_ALMOST_EMPTY;
1754 for (i = 0; i < 2; i++) {
1755 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1756 struct zspage, list);
1758 VM_BUG_ON(is_zspage_isolated(zspage));
1759 remove_zspage(class, zspage, fg[i]);
1768 * putback_zspage - add @zspage into right class's fullness list
1769 * @class: destination class
1770 * @zspage: target page
1772 * Return @zspage's fullness_group
1774 static enum fullness_group putback_zspage(struct size_class *class,
1775 struct zspage *zspage)
1777 enum fullness_group fullness;
1779 VM_BUG_ON(is_zspage_isolated(zspage));
1781 fullness = get_fullness_group(class, zspage);
1782 insert_zspage(class, zspage, fullness);
1783 set_zspage_mapping(zspage, class->index, fullness);
1788 #ifdef CONFIG_COMPACTION
1790 * To prevent zspage destroy during migration, zspage freeing should
1791 * hold locks of all pages in the zspage.
1793 static void lock_zspage(struct zspage *zspage)
1795 struct page *page = get_first_page(zspage);
1799 } while ((page = get_next_page(page)) != NULL);
1802 static int zs_init_fs_context(struct fs_context *fc)
1804 return init_pseudo(fc, ZSMALLOC_MAGIC) ? 0 : -ENOMEM;
1807 static struct file_system_type zsmalloc_fs = {
1809 .init_fs_context = zs_init_fs_context,
1810 .kill_sb = kill_anon_super,
1813 static int zsmalloc_mount(void)
1817 zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1818 if (IS_ERR(zsmalloc_mnt))
1819 ret = PTR_ERR(zsmalloc_mnt);
1824 static void zsmalloc_unmount(void)
1826 kern_unmount(zsmalloc_mnt);
1829 static void migrate_lock_init(struct zspage *zspage)
1831 rwlock_init(&zspage->lock);
1834 static void migrate_read_lock(struct zspage *zspage)
1836 read_lock(&zspage->lock);
1839 static void migrate_read_unlock(struct zspage *zspage)
1841 read_unlock(&zspage->lock);
1844 static void migrate_write_lock(struct zspage *zspage)
1846 write_lock(&zspage->lock);
1849 static void migrate_write_unlock(struct zspage *zspage)
1851 write_unlock(&zspage->lock);
1854 /* Number of isolated subpage for *page migration* in this zspage */
1855 static void inc_zspage_isolation(struct zspage *zspage)
1860 static void dec_zspage_isolation(struct zspage *zspage)
1865 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1866 struct page *newpage, struct page *oldpage)
1869 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1872 page = get_first_page(zspage);
1874 if (page == oldpage)
1875 pages[idx] = newpage;
1879 } while ((page = get_next_page(page)) != NULL);
1881 create_page_chain(class, zspage, pages);
1882 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1883 if (unlikely(PageHugeObject(oldpage)))
1884 newpage->index = oldpage->index;
1885 __SetPageMovable(newpage, page_mapping(oldpage));
1888 static bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1890 struct zs_pool *pool;
1891 struct size_class *class;
1893 enum fullness_group fullness;
1894 struct zspage *zspage;
1895 struct address_space *mapping;
1898 * Page is locked so zspage couldn't be destroyed. For detail, look at
1899 * lock_zspage in free_zspage.
1901 VM_BUG_ON_PAGE(!PageMovable(page), page);
1902 VM_BUG_ON_PAGE(PageIsolated(page), page);
1904 zspage = get_zspage(page);
1907 * Without class lock, fullness could be stale while class_idx is okay
1908 * because class_idx is constant unless page is freed so we should get
1909 * fullness again under class lock.
1911 get_zspage_mapping(zspage, &class_idx, &fullness);
1912 mapping = page_mapping(page);
1913 pool = mapping->private_data;
1914 class = pool->size_class[class_idx];
1916 spin_lock(&class->lock);
1917 if (get_zspage_inuse(zspage) == 0) {
1918 spin_unlock(&class->lock);
1922 /* zspage is isolated for object migration */
1923 if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1924 spin_unlock(&class->lock);
1929 * If this is first time isolation for the zspage, isolate zspage from
1930 * size_class to prevent further object allocation from the zspage.
1932 if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
1933 get_zspage_mapping(zspage, &class_idx, &fullness);
1934 remove_zspage(class, zspage, fullness);
1937 inc_zspage_isolation(zspage);
1938 spin_unlock(&class->lock);
1943 static int zs_page_migrate(struct address_space *mapping, struct page *newpage,
1944 struct page *page, enum migrate_mode mode)
1946 struct zs_pool *pool;
1947 struct size_class *class;
1949 enum fullness_group fullness;
1950 struct zspage *zspage;
1952 void *s_addr, *d_addr, *addr;
1954 unsigned long handle, head;
1955 unsigned long old_obj, new_obj;
1956 unsigned int obj_idx;
1960 * We cannot support the _NO_COPY case here, because copy needs to
1961 * happen under the zs lock, which does not work with
1962 * MIGRATE_SYNC_NO_COPY workflow.
1964 if (mode == MIGRATE_SYNC_NO_COPY)
1967 VM_BUG_ON_PAGE(!PageMovable(page), page);
1968 VM_BUG_ON_PAGE(!PageIsolated(page), page);
1970 zspage = get_zspage(page);
1972 /* Concurrent compactor cannot migrate any subpage in zspage */
1973 migrate_write_lock(zspage);
1974 get_zspage_mapping(zspage, &class_idx, &fullness);
1975 pool = mapping->private_data;
1976 class = pool->size_class[class_idx];
1977 offset = get_first_obj_offset(page);
1979 spin_lock(&class->lock);
1980 if (!get_zspage_inuse(zspage)) {
1982 * Set "offset" to end of the page so that every loops
1983 * skips unnecessary object scanning.
1989 s_addr = kmap_atomic(page);
1990 while (pos < PAGE_SIZE) {
1991 head = obj_to_head(page, s_addr + pos);
1992 if (head & OBJ_ALLOCATED_TAG) {
1993 handle = head & ~OBJ_ALLOCATED_TAG;
1994 if (!trypin_tag(handle))
2001 * Here, any user cannot access all objects in the zspage so let's move.
2003 d_addr = kmap_atomic(newpage);
2004 memcpy(d_addr, s_addr, PAGE_SIZE);
2005 kunmap_atomic(d_addr);
2007 for (addr = s_addr + offset; addr < s_addr + pos;
2008 addr += class->size) {
2009 head = obj_to_head(page, addr);
2010 if (head & OBJ_ALLOCATED_TAG) {
2011 handle = head & ~OBJ_ALLOCATED_TAG;
2012 if (!testpin_tag(handle))
2015 old_obj = handle_to_obj(handle);
2016 obj_to_location(old_obj, &dummy, &obj_idx);
2017 new_obj = (unsigned long)location_to_obj(newpage,
2019 new_obj |= BIT(HANDLE_PIN_BIT);
2020 record_obj(handle, new_obj);
2024 replace_sub_page(class, zspage, newpage, page);
2027 dec_zspage_isolation(zspage);
2030 * Page migration is done so let's putback isolated zspage to
2031 * the list if @page is final isolated subpage in the zspage.
2033 if (!is_zspage_isolated(zspage))
2034 putback_zspage(class, zspage);
2040 ret = MIGRATEPAGE_SUCCESS;
2042 for (addr = s_addr + offset; addr < s_addr + pos;
2043 addr += class->size) {
2044 head = obj_to_head(page, addr);
2045 if (head & OBJ_ALLOCATED_TAG) {
2046 handle = head & ~OBJ_ALLOCATED_TAG;
2047 if (!testpin_tag(handle))
2052 kunmap_atomic(s_addr);
2053 spin_unlock(&class->lock);
2054 migrate_write_unlock(zspage);
2059 static void zs_page_putback(struct page *page)
2061 struct zs_pool *pool;
2062 struct size_class *class;
2064 enum fullness_group fg;
2065 struct address_space *mapping;
2066 struct zspage *zspage;
2068 VM_BUG_ON_PAGE(!PageMovable(page), page);
2069 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2071 zspage = get_zspage(page);
2072 get_zspage_mapping(zspage, &class_idx, &fg);
2073 mapping = page_mapping(page);
2074 pool = mapping->private_data;
2075 class = pool->size_class[class_idx];
2077 spin_lock(&class->lock);
2078 dec_zspage_isolation(zspage);
2079 if (!is_zspage_isolated(zspage)) {
2080 fg = putback_zspage(class, zspage);
2082 * Due to page_lock, we cannot free zspage immediately
2086 schedule_work(&pool->free_work);
2088 spin_unlock(&class->lock);
2091 static const struct address_space_operations zsmalloc_aops = {
2092 .isolate_page = zs_page_isolate,
2093 .migratepage = zs_page_migrate,
2094 .putback_page = zs_page_putback,
2097 static int zs_register_migration(struct zs_pool *pool)
2099 pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2100 if (IS_ERR(pool->inode)) {
2105 pool->inode->i_mapping->private_data = pool;
2106 pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2110 static void zs_unregister_migration(struct zs_pool *pool)
2112 flush_work(&pool->free_work);
2117 * Caller should hold page_lock of all pages in the zspage
2118 * In here, we cannot use zspage meta data.
2120 static void async_free_zspage(struct work_struct *work)
2123 struct size_class *class;
2124 unsigned int class_idx;
2125 enum fullness_group fullness;
2126 struct zspage *zspage, *tmp;
2127 LIST_HEAD(free_pages);
2128 struct zs_pool *pool = container_of(work, struct zs_pool,
2131 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2132 class = pool->size_class[i];
2133 if (class->index != i)
2136 spin_lock(&class->lock);
2137 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2138 spin_unlock(&class->lock);
2142 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2143 list_del(&zspage->list);
2144 lock_zspage(zspage);
2146 get_zspage_mapping(zspage, &class_idx, &fullness);
2147 VM_BUG_ON(fullness != ZS_EMPTY);
2148 class = pool->size_class[class_idx];
2149 spin_lock(&class->lock);
2150 __free_zspage(pool, pool->size_class[class_idx], zspage);
2151 spin_unlock(&class->lock);
2155 static void kick_deferred_free(struct zs_pool *pool)
2157 schedule_work(&pool->free_work);
2160 static void init_deferred_free(struct zs_pool *pool)
2162 INIT_WORK(&pool->free_work, async_free_zspage);
2165 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2167 struct page *page = get_first_page(zspage);
2170 WARN_ON(!trylock_page(page));
2171 __SetPageMovable(page, pool->inode->i_mapping);
2173 } while ((page = get_next_page(page)) != NULL);
2179 * Based on the number of unused allocated objects calculate
2180 * and return the number of pages that we can free.
2182 static unsigned long zs_can_compact(struct size_class *class)
2184 unsigned long obj_wasted;
2185 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2186 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2188 if (obj_allocated <= obj_used)
2191 obj_wasted = obj_allocated - obj_used;
2192 obj_wasted /= class->objs_per_zspage;
2194 return obj_wasted * class->pages_per_zspage;
2197 static void __zs_compact(struct zs_pool *pool, struct size_class *class)
2199 struct zs_compact_control cc;
2200 struct zspage *src_zspage;
2201 struct zspage *dst_zspage = NULL;
2203 spin_lock(&class->lock);
2204 while ((src_zspage = isolate_zspage(class, true))) {
2206 if (!zs_can_compact(class))
2210 cc.s_page = get_first_page(src_zspage);
2212 while ((dst_zspage = isolate_zspage(class, false))) {
2213 cc.d_page = get_first_page(dst_zspage);
2215 * If there is no more space in dst_page, resched
2216 * and see if anyone had allocated another zspage.
2218 if (!migrate_zspage(pool, class, &cc))
2221 putback_zspage(class, dst_zspage);
2224 /* Stop if we couldn't find slot */
2225 if (dst_zspage == NULL)
2228 putback_zspage(class, dst_zspage);
2229 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2230 free_zspage(pool, class, src_zspage);
2231 pool->stats.pages_compacted += class->pages_per_zspage;
2233 spin_unlock(&class->lock);
2235 spin_lock(&class->lock);
2239 putback_zspage(class, src_zspage);
2241 spin_unlock(&class->lock);
2244 unsigned long zs_compact(struct zs_pool *pool)
2247 struct size_class *class;
2249 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2250 class = pool->size_class[i];
2253 if (class->index != i)
2255 __zs_compact(pool, class);
2258 return pool->stats.pages_compacted;
2260 EXPORT_SYMBOL_GPL(zs_compact);
2262 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2264 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2266 EXPORT_SYMBOL_GPL(zs_pool_stats);
2268 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2269 struct shrink_control *sc)
2271 unsigned long pages_freed;
2272 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2275 pages_freed = pool->stats.pages_compacted;
2277 * Compact classes and calculate compaction delta.
2278 * Can run concurrently with a manually triggered
2279 * (by user) compaction.
2281 pages_freed = zs_compact(pool) - pages_freed;
2283 return pages_freed ? pages_freed : SHRINK_STOP;
2286 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2287 struct shrink_control *sc)
2290 struct size_class *class;
2291 unsigned long pages_to_free = 0;
2292 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2295 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2296 class = pool->size_class[i];
2299 if (class->index != i)
2302 pages_to_free += zs_can_compact(class);
2305 return pages_to_free;
2308 static void zs_unregister_shrinker(struct zs_pool *pool)
2310 unregister_shrinker(&pool->shrinker);
2313 static int zs_register_shrinker(struct zs_pool *pool)
2315 pool->shrinker.scan_objects = zs_shrinker_scan;
2316 pool->shrinker.count_objects = zs_shrinker_count;
2317 pool->shrinker.batch = 0;
2318 pool->shrinker.seeks = DEFAULT_SEEKS;
2320 return register_shrinker(&pool->shrinker);
2324 * zs_create_pool - Creates an allocation pool to work from.
2325 * @name: pool name to be created
2327 * This function must be called before anything when using
2328 * the zsmalloc allocator.
2330 * On success, a pointer to the newly created pool is returned,
2333 struct zs_pool *zs_create_pool(const char *name)
2336 struct zs_pool *pool;
2337 struct size_class *prev_class = NULL;
2339 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2343 init_deferred_free(pool);
2345 pool->name = kstrdup(name, GFP_KERNEL);
2349 if (create_cache(pool))
2353 * Iterate reversely, because, size of size_class that we want to use
2354 * for merging should be larger or equal to current size.
2356 for (i = ZS_SIZE_CLASSES - 1; i >= 0; i--) {
2358 int pages_per_zspage;
2359 int objs_per_zspage;
2360 struct size_class *class;
2363 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2364 if (size > ZS_MAX_ALLOC_SIZE)
2365 size = ZS_MAX_ALLOC_SIZE;
2366 pages_per_zspage = get_pages_per_zspage(size);
2367 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2370 * We iterate from biggest down to smallest classes,
2371 * so huge_class_size holds the size of the first huge
2372 * class. Any object bigger than or equal to that will
2373 * endup in the huge class.
2375 if (pages_per_zspage != 1 && objs_per_zspage != 1 &&
2377 huge_class_size = size;
2379 * The object uses ZS_HANDLE_SIZE bytes to store the
2380 * handle. We need to subtract it, because zs_malloc()
2381 * unconditionally adds handle size before it performs
2382 * size class search - so object may be smaller than
2383 * huge class size, yet it still can end up in the huge
2384 * class because it grows by ZS_HANDLE_SIZE extra bytes
2385 * right before class lookup.
2387 huge_class_size -= (ZS_HANDLE_SIZE - 1);
2391 * size_class is used for normal zsmalloc operation such
2392 * as alloc/free for that size. Although it is natural that we
2393 * have one size_class for each size, there is a chance that we
2394 * can get more memory utilization if we use one size_class for
2395 * many different sizes whose size_class have same
2396 * characteristics. So, we makes size_class point to
2397 * previous size_class if possible.
2400 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2401 pool->size_class[i] = prev_class;
2406 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2412 class->pages_per_zspage = pages_per_zspage;
2413 class->objs_per_zspage = objs_per_zspage;
2414 spin_lock_init(&class->lock);
2415 pool->size_class[i] = class;
2416 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2418 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2423 /* debug only, don't abort if it fails */
2424 zs_pool_stat_create(pool, name);
2426 if (zs_register_migration(pool))
2430 * Not critical since shrinker is only used to trigger internal
2431 * defragmentation of the pool which is pretty optional thing. If
2432 * registration fails we still can use the pool normally and user can
2433 * trigger compaction manually. Thus, ignore return code.
2435 zs_register_shrinker(pool);
2440 zs_destroy_pool(pool);
2443 EXPORT_SYMBOL_GPL(zs_create_pool);
2445 void zs_destroy_pool(struct zs_pool *pool)
2449 zs_unregister_shrinker(pool);
2450 zs_unregister_migration(pool);
2451 zs_pool_stat_destroy(pool);
2453 for (i = 0; i < ZS_SIZE_CLASSES; i++) {
2455 struct size_class *class = pool->size_class[i];
2460 if (class->index != i)
2463 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2464 if (!list_empty(&class->fullness_list[fg])) {
2465 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2472 destroy_cache(pool);
2476 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2478 static int __init zs_init(void)
2482 ret = zsmalloc_mount();
2486 ret = cpuhp_setup_state(CPUHP_MM_ZS_PREPARE, "mm/zsmalloc:prepare",
2487 zs_cpu_prepare, zs_cpu_dead);
2492 zpool_register_driver(&zs_zpool_driver);
2505 static void __exit zs_exit(void)
2508 zpool_unregister_driver(&zs_zpool_driver);
2511 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE);
2516 module_init(zs_init);
2517 module_exit(zs_exit);
2519 MODULE_LICENSE("Dual BSD/GPL");