USB: serial: ir-usb: fix link-speed handling
[linux/fpc-iii.git] / mm / zsmalloc.c
blobe4cca3f5331ec133f5d385afda62b880fec6104d
1 /*
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
22 * to store handle.
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_private2: identifies the last component page
28 * PG_owner_priv_1: indentifies the huge component page
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
34 #include <linux/module.h>
35 #include <linux/kernel.h>
36 #include <linux/sched.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/types.h>
50 #include <linux/debugfs.h>
51 #include <linux/zsmalloc.h>
52 #include <linux/zpool.h>
53 #include <linux/mount.h>
54 #include <linux/migrate.h>
55 #include <linux/wait.h>
56 #include <linux/pagemap.h>
58 #define ZSPAGE_MAGIC 0x58
61 * This must be power of 2 and greater than of equal to sizeof(link_free).
62 * These two conditions ensure that any 'struct link_free' itself doesn't
63 * span more than 1 page which avoids complex case of mapping 2 pages simply
64 * to restore link_free pointer values.
66 #define ZS_ALIGN 8
69 * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
70 * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
72 #define ZS_MAX_ZSPAGE_ORDER 2
73 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
75 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
78 * Object location (<PFN>, <obj_idx>) is encoded as
79 * as single (unsigned long) handle value.
81 * Note that object index <obj_idx> starts from 0.
83 * This is made more complicated by various memory models and PAE.
86 #ifndef MAX_PHYSMEM_BITS
87 #ifdef CONFIG_HIGHMEM64G
88 #define MAX_PHYSMEM_BITS 36
89 #else /* !CONFIG_HIGHMEM64G */
91 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
92 * be PAGE_SHIFT
94 #define MAX_PHYSMEM_BITS BITS_PER_LONG
95 #endif
96 #endif
97 #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
100 * Memory for allocating for handle keeps object position by
101 * encoding <page, obj_idx> and the encoded value has a room
102 * in least bit(ie, look at obj_to_location).
103 * We use the bit to synchronize between object access by
104 * user and migration.
106 #define HANDLE_PIN_BIT 0
109 * Head in allocated object should have OBJ_ALLOCATED_TAG
110 * to identify the object was allocated or not.
111 * It's okay to add the status bit in the least bit because
112 * header keeps handle which is 4byte-aligned address so we
113 * have room for two bit at least.
115 #define OBJ_ALLOCATED_TAG 1
116 #define OBJ_TAG_BITS 1
117 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
118 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
120 #define MAX(a, b) ((a) >= (b) ? (a) : (b))
121 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
122 #define ZS_MIN_ALLOC_SIZE \
123 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
124 /* each chunk includes extra space to keep handle */
125 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
128 * On systems with 4K page size, this gives 255 size classes! There is a
129 * trader-off here:
130 * - Large number of size classes is potentially wasteful as free page are
131 * spread across these classes
132 * - Small number of size classes causes large internal fragmentation
133 * - Probably its better to use specific size classes (empirically
134 * determined). NOTE: all those class sizes must be set as multiple of
135 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
137 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
138 * (reason above)
140 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
142 enum fullness_group {
143 ZS_EMPTY,
144 ZS_ALMOST_EMPTY,
145 ZS_ALMOST_FULL,
146 ZS_FULL,
147 NR_ZS_FULLNESS,
150 enum zs_stat_type {
151 CLASS_EMPTY,
152 CLASS_ALMOST_EMPTY,
153 CLASS_ALMOST_FULL,
154 CLASS_FULL,
155 OBJ_ALLOCATED,
156 OBJ_USED,
157 NR_ZS_STAT_TYPE,
160 struct zs_size_stat {
161 unsigned long objs[NR_ZS_STAT_TYPE];
164 #ifdef CONFIG_ZSMALLOC_STAT
165 static struct dentry *zs_stat_root;
166 #endif
168 #ifdef CONFIG_COMPACTION
169 static struct vfsmount *zsmalloc_mnt;
170 #endif
173 * number of size_classes
175 static int zs_size_classes;
178 * We assign a page to ZS_ALMOST_EMPTY fullness group when:
179 * n <= N / f, where
180 * n = number of allocated objects
181 * N = total number of objects zspage can store
182 * f = fullness_threshold_frac
184 * Similarly, we assign zspage to:
185 * ZS_ALMOST_FULL when n > N / f
186 * ZS_EMPTY when n == 0
187 * ZS_FULL when n == N
189 * (see: fix_fullness_group())
191 static const int fullness_threshold_frac = 4;
193 struct size_class {
194 spinlock_t lock;
195 struct list_head fullness_list[NR_ZS_FULLNESS];
197 * Size of objects stored in this class. Must be multiple
198 * of ZS_ALIGN.
200 int size;
201 int objs_per_zspage;
202 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
203 int pages_per_zspage;
205 unsigned int index;
206 struct zs_size_stat stats;
209 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
210 static void SetPageHugeObject(struct page *page)
212 SetPageOwnerPriv1(page);
215 static void ClearPageHugeObject(struct page *page)
217 ClearPageOwnerPriv1(page);
220 static int PageHugeObject(struct page *page)
222 return PageOwnerPriv1(page);
226 * Placed within free objects to form a singly linked list.
227 * For every zspage, zspage->freeobj gives head of this list.
229 * This must be power of 2 and less than or equal to ZS_ALIGN
231 struct link_free {
232 union {
234 * Free object index;
235 * It's valid for non-allocated object
237 unsigned long next;
239 * Handle of allocated object.
241 unsigned long handle;
245 struct zs_pool {
246 const char *name;
248 struct size_class **size_class;
249 struct kmem_cache *handle_cachep;
250 struct kmem_cache *zspage_cachep;
252 atomic_long_t pages_allocated;
254 struct zs_pool_stats stats;
256 /* Compact classes */
257 struct shrinker shrinker;
259 * To signify that register_shrinker() was successful
260 * and unregister_shrinker() will not Oops.
262 bool shrinker_enabled;
263 #ifdef CONFIG_ZSMALLOC_STAT
264 struct dentry *stat_dentry;
265 #endif
266 #ifdef CONFIG_COMPACTION
267 struct inode *inode;
268 struct work_struct free_work;
269 /* A wait queue for when migration races with async_free_zspage() */
270 wait_queue_head_t migration_wait;
271 atomic_long_t isolated_pages;
272 bool destroying;
273 #endif
277 * A zspage's class index and fullness group
278 * are encoded in its (first)page->mapping
280 #define FULLNESS_BITS 2
281 #define CLASS_BITS 8
282 #define ISOLATED_BITS 3
283 #define MAGIC_VAL_BITS 8
285 struct zspage {
286 struct {
287 unsigned int fullness:FULLNESS_BITS;
288 unsigned int class:CLASS_BITS + 1;
289 unsigned int isolated:ISOLATED_BITS;
290 unsigned int magic:MAGIC_VAL_BITS;
292 unsigned int inuse;
293 unsigned int freeobj;
294 struct page *first_page;
295 struct list_head list; /* fullness list */
296 #ifdef CONFIG_COMPACTION
297 rwlock_t lock;
298 #endif
301 struct mapping_area {
302 #ifdef CONFIG_PGTABLE_MAPPING
303 struct vm_struct *vm; /* vm area for mapping object that span pages */
304 #else
305 char *vm_buf; /* copy buffer for objects that span pages */
306 #endif
307 char *vm_addr; /* address of kmap_atomic()'ed pages */
308 enum zs_mapmode vm_mm; /* mapping mode */
311 #ifdef CONFIG_COMPACTION
312 static int zs_register_migration(struct zs_pool *pool);
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);
320 #else
321 static int zsmalloc_mount(void) { return 0; }
322 static void zsmalloc_unmount(void) {}
323 static int zs_register_migration(struct zs_pool *pool) { return 0; }
324 static void zs_unregister_migration(struct zs_pool *pool) {}
325 static void migrate_lock_init(struct zspage *zspage) {}
326 static void migrate_read_lock(struct zspage *zspage) {}
327 static void migrate_read_unlock(struct zspage *zspage) {}
328 static void kick_deferred_free(struct zs_pool *pool) {}
329 static void init_deferred_free(struct zs_pool *pool) {}
330 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage) {}
331 #endif
333 static int create_cache(struct zs_pool *pool)
335 pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
336 0, 0, NULL);
337 if (!pool->handle_cachep)
338 return 1;
340 pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
341 0, 0, NULL);
342 if (!pool->zspage_cachep) {
343 kmem_cache_destroy(pool->handle_cachep);
344 pool->handle_cachep = NULL;
345 return 1;
348 return 0;
351 static void destroy_cache(struct zs_pool *pool)
353 kmem_cache_destroy(pool->handle_cachep);
354 kmem_cache_destroy(pool->zspage_cachep);
357 static unsigned long cache_alloc_handle(struct zs_pool *pool, gfp_t gfp)
359 return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
360 gfp & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
363 static void cache_free_handle(struct zs_pool *pool, unsigned long handle)
365 kmem_cache_free(pool->handle_cachep, (void *)handle);
368 static struct zspage *cache_alloc_zspage(struct zs_pool *pool, gfp_t flags)
370 return kmem_cache_alloc(pool->zspage_cachep,
371 flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE));
374 static void cache_free_zspage(struct zs_pool *pool, struct zspage *zspage)
376 kmem_cache_free(pool->zspage_cachep, zspage);
379 static void record_obj(unsigned long handle, unsigned long obj)
382 * lsb of @obj represents handle lock while other bits
383 * represent object value the handle is pointing so
384 * updating shouldn't do store tearing.
386 WRITE_ONCE(*(unsigned long *)handle, obj);
389 /* zpool driver */
391 #ifdef CONFIG_ZPOOL
393 static void *zs_zpool_create(const char *name, gfp_t gfp,
394 const struct zpool_ops *zpool_ops,
395 struct zpool *zpool)
398 * Ignore global gfp flags: zs_malloc() may be invoked from
399 * different contexts and its caller must provide a valid
400 * gfp mask.
402 return zs_create_pool(name);
405 static void zs_zpool_destroy(void *pool)
407 zs_destroy_pool(pool);
410 static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
411 unsigned long *handle)
413 *handle = zs_malloc(pool, size, gfp);
414 return *handle ? 0 : -1;
416 static void zs_zpool_free(void *pool, unsigned long handle)
418 zs_free(pool, handle);
421 static int zs_zpool_shrink(void *pool, unsigned int pages,
422 unsigned int *reclaimed)
424 return -EINVAL;
427 static void *zs_zpool_map(void *pool, unsigned long handle,
428 enum zpool_mapmode mm)
430 enum zs_mapmode zs_mm;
432 switch (mm) {
433 case ZPOOL_MM_RO:
434 zs_mm = ZS_MM_RO;
435 break;
436 case ZPOOL_MM_WO:
437 zs_mm = ZS_MM_WO;
438 break;
439 case ZPOOL_MM_RW: /* fallthru */
440 default:
441 zs_mm = ZS_MM_RW;
442 break;
445 return zs_map_object(pool, handle, zs_mm);
447 static void zs_zpool_unmap(void *pool, unsigned long handle)
449 zs_unmap_object(pool, handle);
452 static u64 zs_zpool_total_size(void *pool)
454 return zs_get_total_pages(pool) << PAGE_SHIFT;
457 static struct zpool_driver zs_zpool_driver = {
458 .type = "zsmalloc",
459 .owner = THIS_MODULE,
460 .create = zs_zpool_create,
461 .destroy = zs_zpool_destroy,
462 .malloc = zs_zpool_malloc,
463 .free = zs_zpool_free,
464 .shrink = zs_zpool_shrink,
465 .map = zs_zpool_map,
466 .unmap = zs_zpool_unmap,
467 .total_size = zs_zpool_total_size,
470 MODULE_ALIAS("zpool-zsmalloc");
471 #endif /* CONFIG_ZPOOL */
473 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
474 static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
476 static bool is_zspage_isolated(struct zspage *zspage)
478 return zspage->isolated;
481 static __maybe_unused int is_first_page(struct page *page)
483 return PagePrivate(page);
486 /* Protected by class->lock */
487 static inline int get_zspage_inuse(struct zspage *zspage)
489 return zspage->inuse;
492 static inline void set_zspage_inuse(struct zspage *zspage, int val)
494 zspage->inuse = val;
497 static inline void mod_zspage_inuse(struct zspage *zspage, int val)
499 zspage->inuse += val;
502 static inline struct page *get_first_page(struct zspage *zspage)
504 struct page *first_page = zspage->first_page;
506 VM_BUG_ON_PAGE(!is_first_page(first_page), first_page);
507 return first_page;
510 static inline int get_first_obj_offset(struct page *page)
512 return page->units;
515 static inline void set_first_obj_offset(struct page *page, int offset)
517 page->units = offset;
520 static inline unsigned int get_freeobj(struct zspage *zspage)
522 return zspage->freeobj;
525 static inline void set_freeobj(struct zspage *zspage, unsigned int obj)
527 zspage->freeobj = obj;
530 static void get_zspage_mapping(struct zspage *zspage,
531 unsigned int *class_idx,
532 enum fullness_group *fullness)
534 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
536 *fullness = zspage->fullness;
537 *class_idx = zspage->class;
540 static void set_zspage_mapping(struct zspage *zspage,
541 unsigned int class_idx,
542 enum fullness_group fullness)
544 zspage->class = class_idx;
545 zspage->fullness = fullness;
549 * zsmalloc divides the pool into various size classes where each
550 * class maintains a list of zspages where each zspage is divided
551 * into equal sized chunks. Each allocation falls into one of these
552 * classes depending on its size. This function returns index of the
553 * size class which has chunk size big enough to hold the give size.
555 static int get_size_class_index(int size)
557 int idx = 0;
559 if (likely(size > ZS_MIN_ALLOC_SIZE))
560 idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
561 ZS_SIZE_CLASS_DELTA);
563 return min(zs_size_classes - 1, idx);
566 /* type can be of enum type zs_stat_type or fullness_group */
567 static inline void zs_stat_inc(struct size_class *class,
568 int type, unsigned long cnt)
570 class->stats.objs[type] += cnt;
573 /* type can be of enum type zs_stat_type or fullness_group */
574 static inline void zs_stat_dec(struct size_class *class,
575 int type, unsigned long cnt)
577 class->stats.objs[type] -= cnt;
580 /* type can be of enum type zs_stat_type or fullness_group */
581 static inline unsigned long zs_stat_get(struct size_class *class,
582 int type)
584 return class->stats.objs[type];
587 #ifdef CONFIG_ZSMALLOC_STAT
589 static void __init zs_stat_init(void)
591 if (!debugfs_initialized()) {
592 pr_warn("debugfs not available, stat dir not created\n");
593 return;
596 zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
597 if (!zs_stat_root)
598 pr_warn("debugfs 'zsmalloc' stat dir creation failed\n");
601 static void __exit zs_stat_exit(void)
603 debugfs_remove_recursive(zs_stat_root);
606 static unsigned long zs_can_compact(struct size_class *class);
608 static int zs_stats_size_show(struct seq_file *s, void *v)
610 int i;
611 struct zs_pool *pool = s->private;
612 struct size_class *class;
613 int objs_per_zspage;
614 unsigned long class_almost_full, class_almost_empty;
615 unsigned long obj_allocated, obj_used, pages_used, freeable;
616 unsigned long total_class_almost_full = 0, total_class_almost_empty = 0;
617 unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
618 unsigned long total_freeable = 0;
620 seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s %8s\n",
621 "class", "size", "almost_full", "almost_empty",
622 "obj_allocated", "obj_used", "pages_used",
623 "pages_per_zspage", "freeable");
625 for (i = 0; i < zs_size_classes; i++) {
626 class = pool->size_class[i];
628 if (class->index != i)
629 continue;
631 spin_lock(&class->lock);
632 class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
633 class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
634 obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
635 obj_used = zs_stat_get(class, OBJ_USED);
636 freeable = zs_can_compact(class);
637 spin_unlock(&class->lock);
639 objs_per_zspage = class->objs_per_zspage;
640 pages_used = obj_allocated / objs_per_zspage *
641 class->pages_per_zspage;
643 seq_printf(s, " %5u %5u %11lu %12lu %13lu"
644 " %10lu %10lu %16d %8lu\n",
645 i, class->size, class_almost_full, class_almost_empty,
646 obj_allocated, obj_used, pages_used,
647 class->pages_per_zspage, freeable);
649 total_class_almost_full += class_almost_full;
650 total_class_almost_empty += class_almost_empty;
651 total_objs += obj_allocated;
652 total_used_objs += obj_used;
653 total_pages += pages_used;
654 total_freeable += freeable;
657 seq_puts(s, "\n");
658 seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu %16s %8lu\n",
659 "Total", "", total_class_almost_full,
660 total_class_almost_empty, total_objs,
661 total_used_objs, total_pages, "", total_freeable);
663 return 0;
666 static int zs_stats_size_open(struct inode *inode, struct file *file)
668 return single_open(file, zs_stats_size_show, inode->i_private);
671 static const struct file_operations zs_stat_size_ops = {
672 .open = zs_stats_size_open,
673 .read = seq_read,
674 .llseek = seq_lseek,
675 .release = single_release,
678 static void zs_pool_stat_create(struct zs_pool *pool, const char *name)
680 struct dentry *entry;
682 if (!zs_stat_root) {
683 pr_warn("no root stat dir, not creating <%s> stat dir\n", name);
684 return;
687 entry = debugfs_create_dir(name, zs_stat_root);
688 if (!entry) {
689 pr_warn("debugfs dir <%s> creation failed\n", name);
690 return;
692 pool->stat_dentry = entry;
694 entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
695 pool->stat_dentry, pool, &zs_stat_size_ops);
696 if (!entry) {
697 pr_warn("%s: debugfs file entry <%s> creation failed\n",
698 name, "classes");
699 debugfs_remove_recursive(pool->stat_dentry);
700 pool->stat_dentry = NULL;
704 static void zs_pool_stat_destroy(struct zs_pool *pool)
706 debugfs_remove_recursive(pool->stat_dentry);
709 #else /* CONFIG_ZSMALLOC_STAT */
710 static void __init zs_stat_init(void)
714 static void __exit zs_stat_exit(void)
718 static inline void zs_pool_stat_create(struct zs_pool *pool, const char *name)
722 static inline void zs_pool_stat_destroy(struct zs_pool *pool)
725 #endif
729 * For each size class, zspages are divided into different groups
730 * depending on how "full" they are. This was done so that we could
731 * easily find empty or nearly empty zspages when we try to shrink
732 * the pool (not yet implemented). This function returns fullness
733 * status of the given page.
735 static enum fullness_group get_fullness_group(struct size_class *class,
736 struct zspage *zspage)
738 int inuse, objs_per_zspage;
739 enum fullness_group fg;
741 inuse = get_zspage_inuse(zspage);
742 objs_per_zspage = class->objs_per_zspage;
744 if (inuse == 0)
745 fg = ZS_EMPTY;
746 else if (inuse == objs_per_zspage)
747 fg = ZS_FULL;
748 else if (inuse <= 3 * objs_per_zspage / fullness_threshold_frac)
749 fg = ZS_ALMOST_EMPTY;
750 else
751 fg = ZS_ALMOST_FULL;
753 return fg;
757 * Each size class maintains various freelists and zspages are assigned
758 * to one of these freelists based on the number of live objects they
759 * have. This functions inserts the given zspage into the freelist
760 * identified by <class, fullness_group>.
762 static void insert_zspage(struct size_class *class,
763 struct zspage *zspage,
764 enum fullness_group fullness)
766 struct zspage *head;
768 zs_stat_inc(class, fullness, 1);
769 head = list_first_entry_or_null(&class->fullness_list[fullness],
770 struct zspage, list);
772 * We want to see more ZS_FULL pages and less almost empty/full.
773 * Put pages with higher ->inuse first.
775 if (head) {
776 if (get_zspage_inuse(zspage) < get_zspage_inuse(head)) {
777 list_add(&zspage->list, &head->list);
778 return;
781 list_add(&zspage->list, &class->fullness_list[fullness]);
785 * This function removes the given zspage from the freelist identified
786 * by <class, fullness_group>.
788 static void remove_zspage(struct size_class *class,
789 struct zspage *zspage,
790 enum fullness_group fullness)
792 VM_BUG_ON(list_empty(&class->fullness_list[fullness]));
793 VM_BUG_ON(is_zspage_isolated(zspage));
795 list_del_init(&zspage->list);
796 zs_stat_dec(class, fullness, 1);
800 * Each size class maintains zspages in different fullness groups depending
801 * on the number of live objects they contain. When allocating or freeing
802 * objects, the fullness status of the page can change, say, from ALMOST_FULL
803 * to ALMOST_EMPTY when freeing an object. This function checks if such
804 * a status change has occurred for the given page and accordingly moves the
805 * page from the freelist of the old fullness group to that of the new
806 * fullness group.
808 static enum fullness_group fix_fullness_group(struct size_class *class,
809 struct zspage *zspage)
811 int class_idx;
812 enum fullness_group currfg, newfg;
814 get_zspage_mapping(zspage, &class_idx, &currfg);
815 newfg = get_fullness_group(class, zspage);
816 if (newfg == currfg)
817 goto out;
819 if (!is_zspage_isolated(zspage)) {
820 remove_zspage(class, zspage, currfg);
821 insert_zspage(class, zspage, newfg);
824 set_zspage_mapping(zspage, class_idx, newfg);
826 out:
827 return newfg;
831 * We have to decide on how many pages to link together
832 * to form a zspage for each size class. This is important
833 * to reduce wastage due to unusable space left at end of
834 * each zspage which is given as:
835 * wastage = Zp % class_size
836 * usage = Zp - wastage
837 * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
839 * For example, for size class of 3/8 * PAGE_SIZE, we should
840 * link together 3 PAGE_SIZE sized pages to form a zspage
841 * since then we can perfectly fit in 8 such objects.
843 static int get_pages_per_zspage(int class_size)
845 int i, max_usedpc = 0;
846 /* zspage order which gives maximum used size per KB */
847 int max_usedpc_order = 1;
849 for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
850 int zspage_size;
851 int waste, usedpc;
853 zspage_size = i * PAGE_SIZE;
854 waste = zspage_size % class_size;
855 usedpc = (zspage_size - waste) * 100 / zspage_size;
857 if (usedpc > max_usedpc) {
858 max_usedpc = usedpc;
859 max_usedpc_order = i;
863 return max_usedpc_order;
866 static struct zspage *get_zspage(struct page *page)
868 struct zspage *zspage = (struct zspage *)page->private;
870 BUG_ON(zspage->magic != ZSPAGE_MAGIC);
871 return zspage;
874 static struct page *get_next_page(struct page *page)
876 if (unlikely(PageHugeObject(page)))
877 return NULL;
879 return page->freelist;
883 * obj_to_location - get (<page>, <obj_idx>) from encoded object value
884 * @page: page object resides in zspage
885 * @obj_idx: object index
887 static void obj_to_location(unsigned long obj, struct page **page,
888 unsigned int *obj_idx)
890 obj >>= OBJ_TAG_BITS;
891 *page = pfn_to_page(obj >> OBJ_INDEX_BITS);
892 *obj_idx = (obj & OBJ_INDEX_MASK);
896 * location_to_obj - get obj value encoded from (<page>, <obj_idx>)
897 * @page: page object resides in zspage
898 * @obj_idx: object index
900 static unsigned long location_to_obj(struct page *page, unsigned int obj_idx)
902 unsigned long obj;
904 obj = page_to_pfn(page) << OBJ_INDEX_BITS;
905 obj |= obj_idx & OBJ_INDEX_MASK;
906 obj <<= OBJ_TAG_BITS;
908 return obj;
911 static unsigned long handle_to_obj(unsigned long handle)
913 return *(unsigned long *)handle;
916 static unsigned long obj_to_head(struct page *page, void *obj)
918 if (unlikely(PageHugeObject(page))) {
919 VM_BUG_ON_PAGE(!is_first_page(page), page);
920 return page->index;
921 } else
922 return *(unsigned long *)obj;
925 static inline int testpin_tag(unsigned long handle)
927 return bit_spin_is_locked(HANDLE_PIN_BIT, (unsigned long *)handle);
930 static inline int trypin_tag(unsigned long handle)
932 return bit_spin_trylock(HANDLE_PIN_BIT, (unsigned long *)handle);
935 static void pin_tag(unsigned long handle)
937 bit_spin_lock(HANDLE_PIN_BIT, (unsigned long *)handle);
940 static void unpin_tag(unsigned long handle)
942 bit_spin_unlock(HANDLE_PIN_BIT, (unsigned long *)handle);
945 static void reset_page(struct page *page)
947 __ClearPageMovable(page);
948 ClearPagePrivate(page);
949 ClearPagePrivate2(page);
950 set_page_private(page, 0);
951 page_mapcount_reset(page);
952 ClearPageHugeObject(page);
953 page->freelist = NULL;
957 * To prevent zspage destroy during migration, zspage freeing should
958 * hold locks of all pages in the zspage.
960 void lock_zspage(struct zspage *zspage)
962 struct page *page = get_first_page(zspage);
964 do {
965 lock_page(page);
966 } while ((page = get_next_page(page)) != NULL);
969 int trylock_zspage(struct zspage *zspage)
971 struct page *cursor, *fail;
973 for (cursor = get_first_page(zspage); cursor != NULL; cursor =
974 get_next_page(cursor)) {
975 if (!trylock_page(cursor)) {
976 fail = cursor;
977 goto unlock;
981 return 1;
982 unlock:
983 for (cursor = get_first_page(zspage); cursor != fail; cursor =
984 get_next_page(cursor))
985 unlock_page(cursor);
987 return 0;
990 static void __free_zspage(struct zs_pool *pool, struct size_class *class,
991 struct zspage *zspage)
993 struct page *page, *next;
994 enum fullness_group fg;
995 unsigned int class_idx;
997 get_zspage_mapping(zspage, &class_idx, &fg);
999 assert_spin_locked(&class->lock);
1001 VM_BUG_ON(get_zspage_inuse(zspage));
1002 VM_BUG_ON(fg != ZS_EMPTY);
1004 next = page = get_first_page(zspage);
1005 do {
1006 VM_BUG_ON_PAGE(!PageLocked(page), page);
1007 next = get_next_page(page);
1008 reset_page(page);
1009 unlock_page(page);
1010 dec_zone_page_state(page, NR_ZSPAGES);
1011 put_page(page);
1012 page = next;
1013 } while (page != NULL);
1015 cache_free_zspage(pool, zspage);
1017 zs_stat_dec(class, OBJ_ALLOCATED, class->objs_per_zspage);
1018 atomic_long_sub(class->pages_per_zspage,
1019 &pool->pages_allocated);
1022 static void free_zspage(struct zs_pool *pool, struct size_class *class,
1023 struct zspage *zspage)
1025 VM_BUG_ON(get_zspage_inuse(zspage));
1026 VM_BUG_ON(list_empty(&zspage->list));
1028 if (!trylock_zspage(zspage)) {
1029 kick_deferred_free(pool);
1030 return;
1033 remove_zspage(class, zspage, ZS_EMPTY);
1034 __free_zspage(pool, class, zspage);
1037 /* Initialize a newly allocated zspage */
1038 static void init_zspage(struct size_class *class, struct zspage *zspage)
1040 unsigned int freeobj = 1;
1041 unsigned long off = 0;
1042 struct page *page = get_first_page(zspage);
1044 while (page) {
1045 struct page *next_page;
1046 struct link_free *link;
1047 void *vaddr;
1049 set_first_obj_offset(page, off);
1051 vaddr = kmap_atomic(page);
1052 link = (struct link_free *)vaddr + off / sizeof(*link);
1054 while ((off += class->size) < PAGE_SIZE) {
1055 link->next = freeobj++ << OBJ_TAG_BITS;
1056 link += class->size / sizeof(*link);
1060 * We now come to the last (full or partial) object on this
1061 * page, which must point to the first object on the next
1062 * page (if present)
1064 next_page = get_next_page(page);
1065 if (next_page) {
1066 link->next = freeobj++ << OBJ_TAG_BITS;
1067 } else {
1069 * Reset OBJ_TAG_BITS bit to last link to tell
1070 * whether it's allocated object or not.
1072 link->next = -1 << OBJ_TAG_BITS;
1074 kunmap_atomic(vaddr);
1075 page = next_page;
1076 off %= PAGE_SIZE;
1079 set_freeobj(zspage, 0);
1082 static void create_page_chain(struct size_class *class, struct zspage *zspage,
1083 struct page *pages[])
1085 int i;
1086 struct page *page;
1087 struct page *prev_page = NULL;
1088 int nr_pages = class->pages_per_zspage;
1091 * Allocate individual pages and link them together as:
1092 * 1. all pages are linked together using page->freelist
1093 * 2. each sub-page point to zspage using page->private
1095 * we set PG_private to identify the first page (i.e. no other sub-page
1096 * has this flag set) and PG_private_2 to identify the last page.
1098 for (i = 0; i < nr_pages; i++) {
1099 page = pages[i];
1100 set_page_private(page, (unsigned long)zspage);
1101 page->freelist = NULL;
1102 if (i == 0) {
1103 zspage->first_page = page;
1104 SetPagePrivate(page);
1105 if (unlikely(class->objs_per_zspage == 1 &&
1106 class->pages_per_zspage == 1))
1107 SetPageHugeObject(page);
1108 } else {
1109 prev_page->freelist = page;
1111 if (i == nr_pages - 1)
1112 SetPagePrivate2(page);
1113 prev_page = 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,
1122 gfp_t gfp)
1124 int i;
1125 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE];
1126 struct zspage *zspage = cache_alloc_zspage(pool, gfp);
1128 if (!zspage)
1129 return NULL;
1131 memset(zspage, 0, sizeof(struct zspage));
1132 zspage->magic = ZSPAGE_MAGIC;
1133 migrate_lock_init(zspage);
1135 for (i = 0; i < class->pages_per_zspage; i++) {
1136 struct page *page;
1138 page = alloc_page(gfp);
1139 if (!page) {
1140 while (--i >= 0) {
1141 dec_zone_page_state(pages[i], NR_ZSPAGES);
1142 __free_page(pages[i]);
1144 cache_free_zspage(pool, zspage);
1145 return NULL;
1148 inc_zone_page_state(page, NR_ZSPAGES);
1149 pages[i] = page;
1152 create_page_chain(class, zspage, pages);
1153 init_zspage(class, zspage);
1155 return zspage;
1158 static struct zspage *find_get_zspage(struct size_class *class)
1160 int i;
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);
1166 if (zspage)
1167 break;
1170 return zspage;
1173 #ifdef CONFIG_PGTABLE_MAPPING
1174 static inline int __zs_cpu_up(struct mapping_area *area)
1177 * Make sure we don't leak memory if a cpu UP notification
1178 * and zs_init() race and both call zs_cpu_up() on the same cpu
1180 if (area->vm)
1181 return 0;
1182 area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
1183 if (!area->vm)
1184 return -ENOMEM;
1185 return 0;
1188 static inline void __zs_cpu_down(struct mapping_area *area)
1190 if (area->vm)
1191 free_vm_area(area->vm);
1192 area->vm = NULL;
1195 static inline void *__zs_map_object(struct mapping_area *area,
1196 struct page *pages[2], int off, int size)
1198 BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
1199 area->vm_addr = area->vm->addr;
1200 return area->vm_addr + off;
1203 static inline void __zs_unmap_object(struct mapping_area *area,
1204 struct page *pages[2], int off, int size)
1206 unsigned long addr = (unsigned long)area->vm_addr;
1208 unmap_kernel_range(addr, PAGE_SIZE * 2);
1211 #else /* CONFIG_PGTABLE_MAPPING */
1213 static inline int __zs_cpu_up(struct mapping_area *area)
1216 * Make sure we don't leak memory if a cpu UP notification
1217 * and zs_init() race and both call zs_cpu_up() on the same cpu
1219 if (area->vm_buf)
1220 return 0;
1221 area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
1222 if (!area->vm_buf)
1223 return -ENOMEM;
1224 return 0;
1227 static inline void __zs_cpu_down(struct mapping_area *area)
1229 kfree(area->vm_buf);
1230 area->vm_buf = NULL;
1233 static void *__zs_map_object(struct mapping_area *area,
1234 struct page *pages[2], int off, int size)
1236 int sizes[2];
1237 void *addr;
1238 char *buf = area->vm_buf;
1240 /* disable page faults to match kmap_atomic() return conditions */
1241 pagefault_disable();
1243 /* no read fastpath */
1244 if (area->vm_mm == ZS_MM_WO)
1245 goto out;
1247 sizes[0] = PAGE_SIZE - off;
1248 sizes[1] = size - sizes[0];
1250 /* copy object to per-cpu buffer */
1251 addr = kmap_atomic(pages[0]);
1252 memcpy(buf, addr + off, sizes[0]);
1253 kunmap_atomic(addr);
1254 addr = kmap_atomic(pages[1]);
1255 memcpy(buf + sizes[0], addr, sizes[1]);
1256 kunmap_atomic(addr);
1257 out:
1258 return area->vm_buf;
1261 static void __zs_unmap_object(struct mapping_area *area,
1262 struct page *pages[2], int off, int size)
1264 int sizes[2];
1265 void *addr;
1266 char *buf;
1268 /* no write fastpath */
1269 if (area->vm_mm == ZS_MM_RO)
1270 goto out;
1272 buf = area->vm_buf;
1273 buf = buf + ZS_HANDLE_SIZE;
1274 size -= ZS_HANDLE_SIZE;
1275 off += ZS_HANDLE_SIZE;
1277 sizes[0] = PAGE_SIZE - off;
1278 sizes[1] = size - sizes[0];
1280 /* copy per-cpu buffer to object */
1281 addr = kmap_atomic(pages[0]);
1282 memcpy(addr + off, buf, sizes[0]);
1283 kunmap_atomic(addr);
1284 addr = kmap_atomic(pages[1]);
1285 memcpy(addr, buf + sizes[0], sizes[1]);
1286 kunmap_atomic(addr);
1288 out:
1289 /* enable page faults to match kunmap_atomic() return conditions */
1290 pagefault_enable();
1293 #endif /* CONFIG_PGTABLE_MAPPING */
1295 static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
1296 void *pcpu)
1298 int ret, cpu = (long)pcpu;
1299 struct mapping_area *area;
1301 switch (action) {
1302 case CPU_UP_PREPARE:
1303 area = &per_cpu(zs_map_area, cpu);
1304 ret = __zs_cpu_up(area);
1305 if (ret)
1306 return notifier_from_errno(ret);
1307 break;
1308 case CPU_DEAD:
1309 case CPU_UP_CANCELED:
1310 area = &per_cpu(zs_map_area, cpu);
1311 __zs_cpu_down(area);
1312 break;
1315 return NOTIFY_OK;
1318 static struct notifier_block zs_cpu_nb = {
1319 .notifier_call = zs_cpu_notifier
1322 static int zs_register_cpu_notifier(void)
1324 int cpu, uninitialized_var(ret);
1326 cpu_notifier_register_begin();
1328 __register_cpu_notifier(&zs_cpu_nb);
1329 for_each_online_cpu(cpu) {
1330 ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
1331 if (notifier_to_errno(ret))
1332 break;
1335 cpu_notifier_register_done();
1336 return notifier_to_errno(ret);
1339 static void zs_unregister_cpu_notifier(void)
1341 int cpu;
1343 cpu_notifier_register_begin();
1345 for_each_online_cpu(cpu)
1346 zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
1347 __unregister_cpu_notifier(&zs_cpu_nb);
1349 cpu_notifier_register_done();
1352 static void __init init_zs_size_classes(void)
1354 int nr;
1356 nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
1357 if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
1358 nr += 1;
1360 zs_size_classes = nr;
1363 static bool can_merge(struct size_class *prev, int pages_per_zspage,
1364 int objs_per_zspage)
1366 if (prev->pages_per_zspage == pages_per_zspage &&
1367 prev->objs_per_zspage == objs_per_zspage)
1368 return true;
1370 return false;
1373 static bool zspage_full(struct size_class *class, struct zspage *zspage)
1375 return get_zspage_inuse(zspage) == class->objs_per_zspage;
1378 unsigned long zs_get_total_pages(struct zs_pool *pool)
1380 return atomic_long_read(&pool->pages_allocated);
1382 EXPORT_SYMBOL_GPL(zs_get_total_pages);
1385 * zs_map_object - get address of allocated object from handle.
1386 * @pool: pool from which the object was allocated
1387 * @handle: handle returned from zs_malloc
1389 * Before using an object allocated from zs_malloc, it must be mapped using
1390 * this function. When done with the object, it must be unmapped using
1391 * zs_unmap_object.
1393 * Only one object can be mapped per cpu at a time. There is no protection
1394 * against nested mappings.
1396 * This function returns with preemption and page faults disabled.
1398 void *zs_map_object(struct zs_pool *pool, unsigned long handle,
1399 enum zs_mapmode mm)
1401 struct zspage *zspage;
1402 struct page *page;
1403 unsigned long obj, off;
1404 unsigned int obj_idx;
1406 unsigned int class_idx;
1407 enum fullness_group fg;
1408 struct size_class *class;
1409 struct mapping_area *area;
1410 struct page *pages[2];
1411 void *ret;
1414 * Because we use per-cpu mapping areas shared among the
1415 * pools/users, we can't allow mapping in interrupt context
1416 * because it can corrupt another users mappings.
1418 BUG_ON(in_interrupt());
1420 /* From now on, migration cannot move the object */
1421 pin_tag(handle);
1423 obj = handle_to_obj(handle);
1424 obj_to_location(obj, &page, &obj_idx);
1425 zspage = get_zspage(page);
1427 /* migration cannot move any subpage in this zspage */
1428 migrate_read_lock(zspage);
1430 get_zspage_mapping(zspage, &class_idx, &fg);
1431 class = pool->size_class[class_idx];
1432 off = (class->size * obj_idx) & ~PAGE_MASK;
1434 area = &get_cpu_var(zs_map_area);
1435 area->vm_mm = mm;
1436 if (off + class->size <= PAGE_SIZE) {
1437 /* this object is contained entirely within a page */
1438 area->vm_addr = kmap_atomic(page);
1439 ret = area->vm_addr + off;
1440 goto out;
1443 /* this object spans two pages */
1444 pages[0] = page;
1445 pages[1] = get_next_page(page);
1446 BUG_ON(!pages[1]);
1448 ret = __zs_map_object(area, pages, off, class->size);
1449 out:
1450 if (likely(!PageHugeObject(page)))
1451 ret += ZS_HANDLE_SIZE;
1453 return ret;
1455 EXPORT_SYMBOL_GPL(zs_map_object);
1457 void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
1459 struct zspage *zspage;
1460 struct page *page;
1461 unsigned long obj, off;
1462 unsigned int obj_idx;
1464 unsigned int class_idx;
1465 enum fullness_group fg;
1466 struct size_class *class;
1467 struct mapping_area *area;
1469 obj = handle_to_obj(handle);
1470 obj_to_location(obj, &page, &obj_idx);
1471 zspage = get_zspage(page);
1472 get_zspage_mapping(zspage, &class_idx, &fg);
1473 class = pool->size_class[class_idx];
1474 off = (class->size * obj_idx) & ~PAGE_MASK;
1476 area = this_cpu_ptr(&zs_map_area);
1477 if (off + class->size <= PAGE_SIZE)
1478 kunmap_atomic(area->vm_addr);
1479 else {
1480 struct page *pages[2];
1482 pages[0] = page;
1483 pages[1] = get_next_page(page);
1484 BUG_ON(!pages[1]);
1486 __zs_unmap_object(area, pages, off, class->size);
1488 put_cpu_var(zs_map_area);
1490 migrate_read_unlock(zspage);
1491 unpin_tag(handle);
1493 EXPORT_SYMBOL_GPL(zs_unmap_object);
1495 static unsigned long obj_malloc(struct size_class *class,
1496 struct zspage *zspage, unsigned long handle)
1498 int i, nr_page, offset;
1499 unsigned long obj;
1500 struct link_free *link;
1502 struct page *m_page;
1503 unsigned long m_offset;
1504 void *vaddr;
1506 handle |= OBJ_ALLOCATED_TAG;
1507 obj = get_freeobj(zspage);
1509 offset = obj * class->size;
1510 nr_page = offset >> PAGE_SHIFT;
1511 m_offset = offset & ~PAGE_MASK;
1512 m_page = get_first_page(zspage);
1514 for (i = 0; i < nr_page; i++)
1515 m_page = get_next_page(m_page);
1517 vaddr = kmap_atomic(m_page);
1518 link = (struct link_free *)vaddr + m_offset / sizeof(*link);
1519 set_freeobj(zspage, link->next >> OBJ_TAG_BITS);
1520 if (likely(!PageHugeObject(m_page)))
1521 /* record handle in the header of allocated chunk */
1522 link->handle = handle;
1523 else
1524 /* record handle to page->index */
1525 zspage->first_page->index = handle;
1527 kunmap_atomic(vaddr);
1528 mod_zspage_inuse(zspage, 1);
1529 zs_stat_inc(class, OBJ_USED, 1);
1531 obj = location_to_obj(m_page, obj);
1533 return obj;
1538 * zs_malloc - Allocate block of given size from pool.
1539 * @pool: pool to allocate from
1540 * @size: size of block to allocate
1541 * @gfp: gfp flags when allocating object
1543 * On success, handle to the allocated object is returned,
1544 * otherwise 0.
1545 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1547 unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp)
1549 unsigned long handle, obj;
1550 struct size_class *class;
1551 enum fullness_group newfg;
1552 struct zspage *zspage;
1554 if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
1555 return 0;
1557 handle = cache_alloc_handle(pool, gfp);
1558 if (!handle)
1559 return 0;
1561 /* extra space in chunk to keep the handle */
1562 size += ZS_HANDLE_SIZE;
1563 class = pool->size_class[get_size_class_index(size)];
1565 spin_lock(&class->lock);
1566 zspage = find_get_zspage(class);
1567 if (likely(zspage)) {
1568 obj = obj_malloc(class, zspage, handle);
1569 /* Now move the zspage to another fullness group, if required */
1570 fix_fullness_group(class, zspage);
1571 record_obj(handle, obj);
1572 spin_unlock(&class->lock);
1574 return handle;
1577 spin_unlock(&class->lock);
1579 zspage = alloc_zspage(pool, class, gfp);
1580 if (!zspage) {
1581 cache_free_handle(pool, handle);
1582 return 0;
1585 spin_lock(&class->lock);
1586 obj = obj_malloc(class, zspage, handle);
1587 newfg = get_fullness_group(class, zspage);
1588 insert_zspage(class, zspage, newfg);
1589 set_zspage_mapping(zspage, class->index, newfg);
1590 record_obj(handle, obj);
1591 atomic_long_add(class->pages_per_zspage,
1592 &pool->pages_allocated);
1593 zs_stat_inc(class, OBJ_ALLOCATED, class->objs_per_zspage);
1595 /* We completely set up zspage so mark them as movable */
1596 SetZsPageMovable(pool, zspage);
1597 spin_unlock(&class->lock);
1599 return handle;
1601 EXPORT_SYMBOL_GPL(zs_malloc);
1603 static void obj_free(struct size_class *class, unsigned long obj)
1605 struct link_free *link;
1606 struct zspage *zspage;
1607 struct page *f_page;
1608 unsigned long f_offset;
1609 unsigned int f_objidx;
1610 void *vaddr;
1612 obj &= ~OBJ_ALLOCATED_TAG;
1613 obj_to_location(obj, &f_page, &f_objidx);
1614 f_offset = (class->size * f_objidx) & ~PAGE_MASK;
1615 zspage = get_zspage(f_page);
1617 vaddr = kmap_atomic(f_page);
1619 /* Insert this object in containing zspage's freelist */
1620 link = (struct link_free *)(vaddr + f_offset);
1621 link->next = get_freeobj(zspage) << OBJ_TAG_BITS;
1622 kunmap_atomic(vaddr);
1623 set_freeobj(zspage, f_objidx);
1624 mod_zspage_inuse(zspage, -1);
1625 zs_stat_dec(class, OBJ_USED, 1);
1628 void zs_free(struct zs_pool *pool, unsigned long handle)
1630 struct zspage *zspage;
1631 struct page *f_page;
1632 unsigned long obj;
1633 unsigned int f_objidx;
1634 int class_idx;
1635 struct size_class *class;
1636 enum fullness_group fullness;
1637 bool isolated;
1639 if (unlikely(!handle))
1640 return;
1642 pin_tag(handle);
1643 obj = handle_to_obj(handle);
1644 obj_to_location(obj, &f_page, &f_objidx);
1645 zspage = get_zspage(f_page);
1647 migrate_read_lock(zspage);
1649 get_zspage_mapping(zspage, &class_idx, &fullness);
1650 class = pool->size_class[class_idx];
1652 spin_lock(&class->lock);
1653 obj_free(class, obj);
1654 fullness = fix_fullness_group(class, zspage);
1655 if (fullness != ZS_EMPTY) {
1656 migrate_read_unlock(zspage);
1657 goto out;
1660 isolated = is_zspage_isolated(zspage);
1661 migrate_read_unlock(zspage);
1662 /* If zspage is isolated, zs_page_putback will free the zspage */
1663 if (likely(!isolated))
1664 free_zspage(pool, class, zspage);
1665 out:
1667 spin_unlock(&class->lock);
1668 unpin_tag(handle);
1669 cache_free_handle(pool, handle);
1671 EXPORT_SYMBOL_GPL(zs_free);
1673 static void zs_object_copy(struct size_class *class, unsigned long dst,
1674 unsigned long src)
1676 struct page *s_page, *d_page;
1677 unsigned int s_objidx, d_objidx;
1678 unsigned long s_off, d_off;
1679 void *s_addr, *d_addr;
1680 int s_size, d_size, size;
1681 int written = 0;
1683 s_size = d_size = class->size;
1685 obj_to_location(src, &s_page, &s_objidx);
1686 obj_to_location(dst, &d_page, &d_objidx);
1688 s_off = (class->size * s_objidx) & ~PAGE_MASK;
1689 d_off = (class->size * d_objidx) & ~PAGE_MASK;
1691 if (s_off + class->size > PAGE_SIZE)
1692 s_size = PAGE_SIZE - s_off;
1694 if (d_off + class->size > PAGE_SIZE)
1695 d_size = PAGE_SIZE - d_off;
1697 s_addr = kmap_atomic(s_page);
1698 d_addr = kmap_atomic(d_page);
1700 while (1) {
1701 size = min(s_size, d_size);
1702 memcpy(d_addr + d_off, s_addr + s_off, size);
1703 written += size;
1705 if (written == class->size)
1706 break;
1708 s_off += size;
1709 s_size -= size;
1710 d_off += size;
1711 d_size -= size;
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;
1720 s_off = 0;
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;
1728 d_off = 0;
1732 kunmap_atomic(d_addr);
1733 kunmap_atomic(s_addr);
1737 * Find alloced object in zspage from index object and
1738 * return handle.
1740 static unsigned long find_alloced_obj(struct size_class *class,
1741 struct page *page, int *obj_idx)
1743 unsigned long head;
1744 int offset = 0;
1745 int index = *obj_idx;
1746 unsigned long handle = 0;
1747 void *addr = kmap_atomic(page);
1749 offset = get_first_obj_offset(page);
1750 offset += class->size * index;
1752 while (offset < PAGE_SIZE) {
1753 head = obj_to_head(page, addr + offset);
1754 if (head & OBJ_ALLOCATED_TAG) {
1755 handle = head & ~OBJ_ALLOCATED_TAG;
1756 if (trypin_tag(handle))
1757 break;
1758 handle = 0;
1761 offset += class->size;
1762 index++;
1765 kunmap_atomic(addr);
1767 *obj_idx = index;
1769 return handle;
1772 struct zs_compact_control {
1773 /* Source spage for migration which could be a subpage of zspage */
1774 struct page *s_page;
1775 /* Destination page for migration which should be a first page
1776 * of zspage. */
1777 struct page *d_page;
1778 /* Starting object index within @s_page which used for live object
1779 * in the subpage. */
1780 int obj_idx;
1783 static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
1784 struct zs_compact_control *cc)
1786 unsigned long used_obj, free_obj;
1787 unsigned long handle;
1788 struct page *s_page = cc->s_page;
1789 struct page *d_page = cc->d_page;
1790 int obj_idx = cc->obj_idx;
1791 int ret = 0;
1793 while (1) {
1794 handle = find_alloced_obj(class, s_page, &obj_idx);
1795 if (!handle) {
1796 s_page = get_next_page(s_page);
1797 if (!s_page)
1798 break;
1799 obj_idx = 0;
1800 continue;
1803 /* Stop if there is no more space */
1804 if (zspage_full(class, get_zspage(d_page))) {
1805 unpin_tag(handle);
1806 ret = -ENOMEM;
1807 break;
1810 used_obj = handle_to_obj(handle);
1811 free_obj = obj_malloc(class, get_zspage(d_page), handle);
1812 zs_object_copy(class, free_obj, used_obj);
1813 obj_idx++;
1815 * record_obj updates handle's value to free_obj and it will
1816 * invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
1817 * breaks synchronization using pin_tag(e,g, zs_free) so
1818 * let's keep the lock bit.
1820 free_obj |= BIT(HANDLE_PIN_BIT);
1821 record_obj(handle, free_obj);
1822 unpin_tag(handle);
1823 obj_free(class, used_obj);
1826 /* Remember last position in this iteration */
1827 cc->s_page = s_page;
1828 cc->obj_idx = obj_idx;
1830 return ret;
1833 static struct zspage *isolate_zspage(struct size_class *class, bool source)
1835 int i;
1836 struct zspage *zspage;
1837 enum fullness_group fg[2] = {ZS_ALMOST_EMPTY, ZS_ALMOST_FULL};
1839 if (!source) {
1840 fg[0] = ZS_ALMOST_FULL;
1841 fg[1] = ZS_ALMOST_EMPTY;
1844 for (i = 0; i < 2; i++) {
1845 zspage = list_first_entry_or_null(&class->fullness_list[fg[i]],
1846 struct zspage, list);
1847 if (zspage) {
1848 VM_BUG_ON(is_zspage_isolated(zspage));
1849 remove_zspage(class, zspage, fg[i]);
1850 return zspage;
1854 return zspage;
1858 * putback_zspage - add @zspage into right class's fullness list
1859 * @class: destination class
1860 * @zspage: target page
1862 * Return @zspage's fullness_group
1864 static enum fullness_group putback_zspage(struct size_class *class,
1865 struct zspage *zspage)
1867 enum fullness_group fullness;
1869 VM_BUG_ON(is_zspage_isolated(zspage));
1871 fullness = get_fullness_group(class, zspage);
1872 insert_zspage(class, zspage, fullness);
1873 set_zspage_mapping(zspage, class->index, fullness);
1875 return fullness;
1878 #ifdef CONFIG_COMPACTION
1879 static struct dentry *zs_mount(struct file_system_type *fs_type,
1880 int flags, const char *dev_name, void *data)
1882 static const struct dentry_operations ops = {
1883 .d_dname = simple_dname,
1886 return mount_pseudo(fs_type, "zsmalloc:", NULL, &ops, ZSMALLOC_MAGIC);
1889 static struct file_system_type zsmalloc_fs = {
1890 .name = "zsmalloc",
1891 .mount = zs_mount,
1892 .kill_sb = kill_anon_super,
1895 static int zsmalloc_mount(void)
1897 int ret = 0;
1899 zsmalloc_mnt = kern_mount(&zsmalloc_fs);
1900 if (IS_ERR(zsmalloc_mnt))
1901 ret = PTR_ERR(zsmalloc_mnt);
1903 return ret;
1906 static void zsmalloc_unmount(void)
1908 kern_unmount(zsmalloc_mnt);
1911 static void migrate_lock_init(struct zspage *zspage)
1913 rwlock_init(&zspage->lock);
1916 static void migrate_read_lock(struct zspage *zspage)
1918 read_lock(&zspage->lock);
1921 static void migrate_read_unlock(struct zspage *zspage)
1923 read_unlock(&zspage->lock);
1926 static void migrate_write_lock(struct zspage *zspage)
1928 write_lock(&zspage->lock);
1931 static void migrate_write_unlock(struct zspage *zspage)
1933 write_unlock(&zspage->lock);
1936 /* Number of isolated subpage for *page migration* in this zspage */
1937 static void inc_zspage_isolation(struct zspage *zspage)
1939 zspage->isolated++;
1942 static void dec_zspage_isolation(struct zspage *zspage)
1944 zspage->isolated--;
1947 static void putback_zspage_deferred(struct zs_pool *pool,
1948 struct size_class *class,
1949 struct zspage *zspage)
1951 enum fullness_group fg;
1953 fg = putback_zspage(class, zspage);
1954 if (fg == ZS_EMPTY)
1955 schedule_work(&pool->free_work);
1959 static inline void zs_pool_dec_isolated(struct zs_pool *pool)
1961 VM_BUG_ON(atomic_long_read(&pool->isolated_pages) <= 0);
1962 atomic_long_dec(&pool->isolated_pages);
1964 * There's no possibility of racing, since wait_for_isolated_drain()
1965 * checks the isolated count under &class->lock after enqueuing
1966 * on migration_wait.
1968 if (atomic_long_read(&pool->isolated_pages) == 0 && pool->destroying)
1969 wake_up_all(&pool->migration_wait);
1972 static void replace_sub_page(struct size_class *class, struct zspage *zspage,
1973 struct page *newpage, struct page *oldpage)
1975 struct page *page;
1976 struct page *pages[ZS_MAX_PAGES_PER_ZSPAGE] = {NULL, };
1977 int idx = 0;
1979 page = get_first_page(zspage);
1980 do {
1981 if (page == oldpage)
1982 pages[idx] = newpage;
1983 else
1984 pages[idx] = page;
1985 idx++;
1986 } while ((page = get_next_page(page)) != NULL);
1988 create_page_chain(class, zspage, pages);
1989 set_first_obj_offset(newpage, get_first_obj_offset(oldpage));
1990 if (unlikely(PageHugeObject(oldpage)))
1991 newpage->index = oldpage->index;
1992 __SetPageMovable(newpage, page_mapping(oldpage));
1995 bool zs_page_isolate(struct page *page, isolate_mode_t mode)
1997 struct zs_pool *pool;
1998 struct size_class *class;
1999 int class_idx;
2000 enum fullness_group fullness;
2001 struct zspage *zspage;
2002 struct address_space *mapping;
2005 * Page is locked so zspage couldn't be destroyed. For detail, look at
2006 * lock_zspage in free_zspage.
2008 VM_BUG_ON_PAGE(!PageMovable(page), page);
2009 VM_BUG_ON_PAGE(PageIsolated(page), page);
2011 zspage = get_zspage(page);
2014 * Without class lock, fullness could be stale while class_idx is okay
2015 * because class_idx is constant unless page is freed so we should get
2016 * fullness again under class lock.
2018 get_zspage_mapping(zspage, &class_idx, &fullness);
2019 mapping = page_mapping(page);
2020 pool = mapping->private_data;
2021 class = pool->size_class[class_idx];
2023 spin_lock(&class->lock);
2024 if (get_zspage_inuse(zspage) == 0) {
2025 spin_unlock(&class->lock);
2026 return false;
2029 /* zspage is isolated for object migration */
2030 if (list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2031 spin_unlock(&class->lock);
2032 return false;
2036 * If this is first time isolation for the zspage, isolate zspage from
2037 * size_class to prevent further object allocation from the zspage.
2039 if (!list_empty(&zspage->list) && !is_zspage_isolated(zspage)) {
2040 get_zspage_mapping(zspage, &class_idx, &fullness);
2041 atomic_long_inc(&pool->isolated_pages);
2042 remove_zspage(class, zspage, fullness);
2045 inc_zspage_isolation(zspage);
2046 spin_unlock(&class->lock);
2048 return true;
2051 int zs_page_migrate(struct address_space *mapping, struct page *newpage,
2052 struct page *page, enum migrate_mode mode)
2054 struct zs_pool *pool;
2055 struct size_class *class;
2056 int class_idx;
2057 enum fullness_group fullness;
2058 struct zspage *zspage;
2059 struct page *dummy;
2060 void *s_addr, *d_addr, *addr;
2061 int offset, pos;
2062 unsigned long handle, head;
2063 unsigned long old_obj, new_obj;
2064 unsigned int obj_idx;
2065 int ret = -EAGAIN;
2067 VM_BUG_ON_PAGE(!PageMovable(page), page);
2068 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2070 zspage = get_zspage(page);
2072 /* Concurrent compactor cannot migrate any subpage in zspage */
2073 migrate_write_lock(zspage);
2074 get_zspage_mapping(zspage, &class_idx, &fullness);
2075 pool = mapping->private_data;
2076 class = pool->size_class[class_idx];
2077 offset = get_first_obj_offset(page);
2079 spin_lock(&class->lock);
2080 if (!get_zspage_inuse(zspage)) {
2081 ret = -EBUSY;
2082 goto unlock_class;
2085 pos = offset;
2086 s_addr = kmap_atomic(page);
2087 while (pos < PAGE_SIZE) {
2088 head = obj_to_head(page, s_addr + pos);
2089 if (head & OBJ_ALLOCATED_TAG) {
2090 handle = head & ~OBJ_ALLOCATED_TAG;
2091 if (!trypin_tag(handle))
2092 goto unpin_objects;
2094 pos += class->size;
2098 * Here, any user cannot access all objects in the zspage so let's move.
2100 d_addr = kmap_atomic(newpage);
2101 memcpy(d_addr, s_addr, PAGE_SIZE);
2102 kunmap_atomic(d_addr);
2104 for (addr = s_addr + offset; addr < s_addr + pos;
2105 addr += class->size) {
2106 head = obj_to_head(page, addr);
2107 if (head & OBJ_ALLOCATED_TAG) {
2108 handle = head & ~OBJ_ALLOCATED_TAG;
2109 if (!testpin_tag(handle))
2110 BUG();
2112 old_obj = handle_to_obj(handle);
2113 obj_to_location(old_obj, &dummy, &obj_idx);
2114 new_obj = (unsigned long)location_to_obj(newpage,
2115 obj_idx);
2116 new_obj |= BIT(HANDLE_PIN_BIT);
2117 record_obj(handle, new_obj);
2121 replace_sub_page(class, zspage, newpage, page);
2122 get_page(newpage);
2124 dec_zspage_isolation(zspage);
2127 * Page migration is done so let's putback isolated zspage to
2128 * the list if @page is final isolated subpage in the zspage.
2130 if (!is_zspage_isolated(zspage)) {
2132 * We cannot race with zs_destroy_pool() here because we wait
2133 * for isolation to hit zero before we start destroying.
2134 * Also, we ensure that everyone can see pool->destroying before
2135 * we start waiting.
2137 putback_zspage_deferred(pool, class, zspage);
2138 zs_pool_dec_isolated(pool);
2141 if (page_zone(newpage) != page_zone(page)) {
2142 dec_zone_page_state(page, NR_ZSPAGES);
2143 inc_zone_page_state(newpage, NR_ZSPAGES);
2146 reset_page(page);
2147 put_page(page);
2148 page = newpage;
2150 ret = MIGRATEPAGE_SUCCESS;
2151 unpin_objects:
2152 for (addr = s_addr + offset; addr < s_addr + pos;
2153 addr += class->size) {
2154 head = obj_to_head(page, addr);
2155 if (head & OBJ_ALLOCATED_TAG) {
2156 handle = head & ~OBJ_ALLOCATED_TAG;
2157 if (!testpin_tag(handle))
2158 BUG();
2159 unpin_tag(handle);
2162 kunmap_atomic(s_addr);
2163 unlock_class:
2164 spin_unlock(&class->lock);
2165 migrate_write_unlock(zspage);
2167 return ret;
2170 void zs_page_putback(struct page *page)
2172 struct zs_pool *pool;
2173 struct size_class *class;
2174 int class_idx;
2175 enum fullness_group fg;
2176 struct address_space *mapping;
2177 struct zspage *zspage;
2179 VM_BUG_ON_PAGE(!PageMovable(page), page);
2180 VM_BUG_ON_PAGE(!PageIsolated(page), page);
2182 zspage = get_zspage(page);
2183 get_zspage_mapping(zspage, &class_idx, &fg);
2184 mapping = page_mapping(page);
2185 pool = mapping->private_data;
2186 class = pool->size_class[class_idx];
2188 spin_lock(&class->lock);
2189 dec_zspage_isolation(zspage);
2190 if (!is_zspage_isolated(zspage)) {
2192 * Due to page_lock, we cannot free zspage immediately
2193 * so let's defer.
2195 putback_zspage_deferred(pool, class, zspage);
2196 zs_pool_dec_isolated(pool);
2198 spin_unlock(&class->lock);
2201 const struct address_space_operations zsmalloc_aops = {
2202 .isolate_page = zs_page_isolate,
2203 .migratepage = zs_page_migrate,
2204 .putback_page = zs_page_putback,
2207 static int zs_register_migration(struct zs_pool *pool)
2209 pool->inode = alloc_anon_inode(zsmalloc_mnt->mnt_sb);
2210 if (IS_ERR(pool->inode)) {
2211 pool->inode = NULL;
2212 return 1;
2215 pool->inode->i_mapping->private_data = pool;
2216 pool->inode->i_mapping->a_ops = &zsmalloc_aops;
2217 return 0;
2220 static bool pool_isolated_are_drained(struct zs_pool *pool)
2222 return atomic_long_read(&pool->isolated_pages) == 0;
2225 /* Function for resolving migration */
2226 static void wait_for_isolated_drain(struct zs_pool *pool)
2230 * We're in the process of destroying the pool, so there are no
2231 * active allocations. zs_page_isolate() fails for completely free
2232 * zspages, so we need only wait for the zs_pool's isolated
2233 * count to hit zero.
2235 wait_event(pool->migration_wait,
2236 pool_isolated_are_drained(pool));
2239 static void zs_unregister_migration(struct zs_pool *pool)
2241 pool->destroying = true;
2243 * We need a memory barrier here to ensure global visibility of
2244 * pool->destroying. Thus pool->isolated pages will either be 0 in which
2245 * case we don't care, or it will be > 0 and pool->destroying will
2246 * ensure that we wake up once isolation hits 0.
2248 smp_mb();
2249 wait_for_isolated_drain(pool); /* This can block */
2250 flush_work(&pool->free_work);
2251 iput(pool->inode);
2255 * Caller should hold page_lock of all pages in the zspage
2256 * In here, we cannot use zspage meta data.
2258 static void async_free_zspage(struct work_struct *work)
2260 int i;
2261 struct size_class *class;
2262 unsigned int class_idx;
2263 enum fullness_group fullness;
2264 struct zspage *zspage, *tmp;
2265 LIST_HEAD(free_pages);
2266 struct zs_pool *pool = container_of(work, struct zs_pool,
2267 free_work);
2269 for (i = 0; i < zs_size_classes; i++) {
2270 class = pool->size_class[i];
2271 if (class->index != i)
2272 continue;
2274 spin_lock(&class->lock);
2275 list_splice_init(&class->fullness_list[ZS_EMPTY], &free_pages);
2276 spin_unlock(&class->lock);
2280 list_for_each_entry_safe(zspage, tmp, &free_pages, list) {
2281 list_del(&zspage->list);
2282 lock_zspage(zspage);
2284 get_zspage_mapping(zspage, &class_idx, &fullness);
2285 VM_BUG_ON(fullness != ZS_EMPTY);
2286 class = pool->size_class[class_idx];
2287 spin_lock(&class->lock);
2288 __free_zspage(pool, pool->size_class[class_idx], zspage);
2289 spin_unlock(&class->lock);
2293 static void kick_deferred_free(struct zs_pool *pool)
2295 schedule_work(&pool->free_work);
2298 static void init_deferred_free(struct zs_pool *pool)
2300 INIT_WORK(&pool->free_work, async_free_zspage);
2303 static void SetZsPageMovable(struct zs_pool *pool, struct zspage *zspage)
2305 struct page *page = get_first_page(zspage);
2307 do {
2308 WARN_ON(!trylock_page(page));
2309 __SetPageMovable(page, pool->inode->i_mapping);
2310 unlock_page(page);
2311 } while ((page = get_next_page(page)) != NULL);
2313 #endif
2317 * Based on the number of unused allocated objects calculate
2318 * and return the number of pages that we can free.
2320 static unsigned long zs_can_compact(struct size_class *class)
2322 unsigned long obj_wasted;
2323 unsigned long obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
2324 unsigned long obj_used = zs_stat_get(class, OBJ_USED);
2326 if (obj_allocated <= obj_used)
2327 return 0;
2329 obj_wasted = obj_allocated - obj_used;
2330 obj_wasted /= class->objs_per_zspage;
2332 return obj_wasted * class->pages_per_zspage;
2335 static void __zs_compact(struct zs_pool *pool, struct size_class *class)
2337 struct zs_compact_control cc;
2338 struct zspage *src_zspage;
2339 struct zspage *dst_zspage = NULL;
2341 spin_lock(&class->lock);
2342 while ((src_zspage = isolate_zspage(class, true))) {
2344 if (!zs_can_compact(class))
2345 break;
2347 cc.obj_idx = 0;
2348 cc.s_page = get_first_page(src_zspage);
2350 while ((dst_zspage = isolate_zspage(class, false))) {
2351 cc.d_page = get_first_page(dst_zspage);
2353 * If there is no more space in dst_page, resched
2354 * and see if anyone had allocated another zspage.
2356 if (!migrate_zspage(pool, class, &cc))
2357 break;
2359 putback_zspage(class, dst_zspage);
2362 /* Stop if we couldn't find slot */
2363 if (dst_zspage == NULL)
2364 break;
2366 putback_zspage(class, dst_zspage);
2367 if (putback_zspage(class, src_zspage) == ZS_EMPTY) {
2368 free_zspage(pool, class, src_zspage);
2369 pool->stats.pages_compacted += class->pages_per_zspage;
2371 spin_unlock(&class->lock);
2372 cond_resched();
2373 spin_lock(&class->lock);
2376 if (src_zspage)
2377 putback_zspage(class, src_zspage);
2379 spin_unlock(&class->lock);
2382 unsigned long zs_compact(struct zs_pool *pool)
2384 int i;
2385 struct size_class *class;
2387 for (i = zs_size_classes - 1; i >= 0; i--) {
2388 class = pool->size_class[i];
2389 if (!class)
2390 continue;
2391 if (class->index != i)
2392 continue;
2393 __zs_compact(pool, class);
2396 return pool->stats.pages_compacted;
2398 EXPORT_SYMBOL_GPL(zs_compact);
2400 void zs_pool_stats(struct zs_pool *pool, struct zs_pool_stats *stats)
2402 memcpy(stats, &pool->stats, sizeof(struct zs_pool_stats));
2404 EXPORT_SYMBOL_GPL(zs_pool_stats);
2406 static unsigned long zs_shrinker_scan(struct shrinker *shrinker,
2407 struct shrink_control *sc)
2409 unsigned long pages_freed;
2410 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2411 shrinker);
2413 pages_freed = pool->stats.pages_compacted;
2415 * Compact classes and calculate compaction delta.
2416 * Can run concurrently with a manually triggered
2417 * (by user) compaction.
2419 pages_freed = zs_compact(pool) - pages_freed;
2421 return pages_freed ? pages_freed : SHRINK_STOP;
2424 static unsigned long zs_shrinker_count(struct shrinker *shrinker,
2425 struct shrink_control *sc)
2427 int i;
2428 struct size_class *class;
2429 unsigned long pages_to_free = 0;
2430 struct zs_pool *pool = container_of(shrinker, struct zs_pool,
2431 shrinker);
2433 for (i = zs_size_classes - 1; i >= 0; i--) {
2434 class = pool->size_class[i];
2435 if (!class)
2436 continue;
2437 if (class->index != i)
2438 continue;
2440 pages_to_free += zs_can_compact(class);
2443 return pages_to_free;
2446 static void zs_unregister_shrinker(struct zs_pool *pool)
2448 if (pool->shrinker_enabled) {
2449 unregister_shrinker(&pool->shrinker);
2450 pool->shrinker_enabled = false;
2454 static int zs_register_shrinker(struct zs_pool *pool)
2456 pool->shrinker.scan_objects = zs_shrinker_scan;
2457 pool->shrinker.count_objects = zs_shrinker_count;
2458 pool->shrinker.batch = 0;
2459 pool->shrinker.seeks = DEFAULT_SEEKS;
2461 return register_shrinker(&pool->shrinker);
2465 * zs_create_pool - Creates an allocation pool to work from.
2466 * @name: pool name to be created
2468 * This function must be called before anything when using
2469 * the zsmalloc allocator.
2471 * On success, a pointer to the newly created pool is returned,
2472 * otherwise NULL.
2474 struct zs_pool *zs_create_pool(const char *name)
2476 int i;
2477 struct zs_pool *pool;
2478 struct size_class *prev_class = NULL;
2480 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2481 if (!pool)
2482 return NULL;
2484 init_deferred_free(pool);
2485 pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
2486 GFP_KERNEL);
2487 if (!pool->size_class) {
2488 kfree(pool);
2489 return NULL;
2492 pool->name = kstrdup(name, GFP_KERNEL);
2493 if (!pool->name)
2494 goto err;
2496 #ifdef CONFIG_COMPACTION
2497 init_waitqueue_head(&pool->migration_wait);
2498 #endif
2500 if (create_cache(pool))
2501 goto err;
2504 * Iterate reversly, because, size of size_class that we want to use
2505 * for merging should be larger or equal to current size.
2507 for (i = zs_size_classes - 1; i >= 0; i--) {
2508 int size;
2509 int pages_per_zspage;
2510 int objs_per_zspage;
2511 struct size_class *class;
2512 int fullness = 0;
2514 size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
2515 if (size > ZS_MAX_ALLOC_SIZE)
2516 size = ZS_MAX_ALLOC_SIZE;
2517 pages_per_zspage = get_pages_per_zspage(size);
2518 objs_per_zspage = pages_per_zspage * PAGE_SIZE / size;
2521 * size_class is used for normal zsmalloc operation such
2522 * as alloc/free for that size. Although it is natural that we
2523 * have one size_class for each size, there is a chance that we
2524 * can get more memory utilization if we use one size_class for
2525 * many different sizes whose size_class have same
2526 * characteristics. So, we makes size_class point to
2527 * previous size_class if possible.
2529 if (prev_class) {
2530 if (can_merge(prev_class, pages_per_zspage, objs_per_zspage)) {
2531 pool->size_class[i] = prev_class;
2532 continue;
2536 class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
2537 if (!class)
2538 goto err;
2540 class->size = size;
2541 class->index = i;
2542 class->pages_per_zspage = pages_per_zspage;
2543 class->objs_per_zspage = objs_per_zspage;
2544 spin_lock_init(&class->lock);
2545 pool->size_class[i] = class;
2546 for (fullness = ZS_EMPTY; fullness < NR_ZS_FULLNESS;
2547 fullness++)
2548 INIT_LIST_HEAD(&class->fullness_list[fullness]);
2550 prev_class = class;
2553 /* debug only, don't abort if it fails */
2554 zs_pool_stat_create(pool, name);
2556 if (zs_register_migration(pool))
2557 goto err;
2560 * Not critical, we still can use the pool
2561 * and user can trigger compaction manually.
2563 if (zs_register_shrinker(pool) == 0)
2564 pool->shrinker_enabled = true;
2565 return pool;
2567 err:
2568 zs_destroy_pool(pool);
2569 return NULL;
2571 EXPORT_SYMBOL_GPL(zs_create_pool);
2573 void zs_destroy_pool(struct zs_pool *pool)
2575 int i;
2577 zs_unregister_shrinker(pool);
2578 zs_unregister_migration(pool);
2579 zs_pool_stat_destroy(pool);
2581 for (i = 0; i < zs_size_classes; i++) {
2582 int fg;
2583 struct size_class *class = pool->size_class[i];
2585 if (!class)
2586 continue;
2588 if (class->index != i)
2589 continue;
2591 for (fg = ZS_EMPTY; fg < NR_ZS_FULLNESS; fg++) {
2592 if (!list_empty(&class->fullness_list[fg])) {
2593 pr_info("Freeing non-empty class with size %db, fullness group %d\n",
2594 class->size, fg);
2597 kfree(class);
2600 destroy_cache(pool);
2601 kfree(pool->size_class);
2602 kfree(pool->name);
2603 kfree(pool);
2605 EXPORT_SYMBOL_GPL(zs_destroy_pool);
2607 static int __init zs_init(void)
2609 int ret;
2611 ret = zsmalloc_mount();
2612 if (ret)
2613 goto out;
2615 ret = zs_register_cpu_notifier();
2617 if (ret)
2618 goto notifier_fail;
2620 init_zs_size_classes();
2622 #ifdef CONFIG_ZPOOL
2623 zpool_register_driver(&zs_zpool_driver);
2624 #endif
2626 zs_stat_init();
2628 return 0;
2630 notifier_fail:
2631 zs_unregister_cpu_notifier();
2632 zsmalloc_unmount();
2633 out:
2634 return ret;
2637 static void __exit zs_exit(void)
2639 #ifdef CONFIG_ZPOOL
2640 zpool_unregister_driver(&zs_zpool_driver);
2641 #endif
2642 zsmalloc_unmount();
2643 zs_unregister_cpu_notifier();
2645 zs_stat_exit();
2648 module_init(zs_init);
2649 module_exit(zs_exit);
2651 MODULE_LICENSE("Dual BSD/GPL");
2652 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");