1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * zswap.c - zswap driver file
5 * zswap is a backend for frontswap that takes pages that are in the process
6 * of being swapped out and attempts to compress and store them in a
7 * RAM-based memory pool. This can result in a significant I/O reduction on
8 * the swap device and, in the case where decompressing from RAM is faster
9 * than reading from the swap device, can also improve workload performance.
11 * Copyright (C) 2012 Seth Jennings <sjenning@linux.vnet.ibm.com>
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/module.h>
17 #include <linux/cpu.h>
18 #include <linux/highmem.h>
19 #include <linux/slab.h>
20 #include <linux/spinlock.h>
21 #include <linux/types.h>
22 #include <linux/atomic.h>
23 #include <linux/frontswap.h>
24 #include <linux/rbtree.h>
25 #include <linux/swap.h>
26 #include <linux/crypto.h>
27 #include <linux/scatterlist.h>
28 #include <linux/mempool.h>
29 #include <linux/zpool.h>
30 #include <crypto/acompress.h>
32 #include <linux/mm_types.h>
33 #include <linux/page-flags.h>
34 #include <linux/swapops.h>
35 #include <linux/writeback.h>
36 #include <linux/pagemap.h>
37 #include <linux/workqueue.h>
41 /*********************************
43 **********************************/
44 /* Total bytes used by the compressed storage */
45 u64 zswap_pool_total_size;
46 /* The number of compressed pages currently stored in zswap */
47 atomic_t zswap_stored_pages = ATOMIC_INIT(0);
48 /* The number of same-value filled pages currently stored in zswap */
49 static atomic_t zswap_same_filled_pages = ATOMIC_INIT(0);
52 * The statistics below are not protected from concurrent access for
53 * performance reasons so they may not be a 100% accurate. However,
54 * they do provide useful information on roughly how many times a
55 * certain event is occurring.
58 /* Pool limit was hit (see zswap_max_pool_percent) */
59 static u64 zswap_pool_limit_hit;
60 /* Pages written back when pool limit was reached */
61 static u64 zswap_written_back_pages;
62 /* Store failed due to a reclaim failure after pool limit was reached */
63 static u64 zswap_reject_reclaim_fail;
64 /* Compressed page was too big for the allocator to (optimally) store */
65 static u64 zswap_reject_compress_poor;
66 /* Store failed because underlying allocator could not get memory */
67 static u64 zswap_reject_alloc_fail;
68 /* Store failed because the entry metadata could not be allocated (rare) */
69 static u64 zswap_reject_kmemcache_fail;
70 /* Duplicate store was encountered (rare) */
71 static u64 zswap_duplicate_entry;
73 /* Shrinker work queue */
74 static struct workqueue_struct *shrink_wq;
75 /* Pool limit was hit, we need to calm down */
76 static bool zswap_pool_reached_full;
78 /*********************************
80 **********************************/
82 #define ZSWAP_PARAM_UNSET ""
84 static int zswap_setup(void);
86 /* Enable/disable zswap */
87 static bool zswap_enabled = IS_ENABLED(CONFIG_ZSWAP_DEFAULT_ON);
88 static int zswap_enabled_param_set(const char *,
89 const struct kernel_param *);
90 static const struct kernel_param_ops zswap_enabled_param_ops = {
91 .set = zswap_enabled_param_set,
92 .get = param_get_bool,
94 module_param_cb(enabled, &zswap_enabled_param_ops, &zswap_enabled, 0644);
96 /* Crypto compressor to use */
97 static char *zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
98 static int zswap_compressor_param_set(const char *,
99 const struct kernel_param *);
100 static const struct kernel_param_ops zswap_compressor_param_ops = {
101 .set = zswap_compressor_param_set,
102 .get = param_get_charp,
103 .free = param_free_charp,
105 module_param_cb(compressor, &zswap_compressor_param_ops,
106 &zswap_compressor, 0644);
108 /* Compressed storage zpool to use */
109 static char *zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
110 static int zswap_zpool_param_set(const char *, const struct kernel_param *);
111 static const struct kernel_param_ops zswap_zpool_param_ops = {
112 .set = zswap_zpool_param_set,
113 .get = param_get_charp,
114 .free = param_free_charp,
116 module_param_cb(zpool, &zswap_zpool_param_ops, &zswap_zpool_type, 0644);
118 /* The maximum percentage of memory that the compressed pool can occupy */
119 static unsigned int zswap_max_pool_percent = 20;
120 module_param_named(max_pool_percent, zswap_max_pool_percent, uint, 0644);
122 /* The threshold for accepting new pages after the max_pool_percent was hit */
123 static unsigned int zswap_accept_thr_percent = 90; /* of max pool size */
124 module_param_named(accept_threshold_percent, zswap_accept_thr_percent,
128 * Enable/disable handling same-value filled pages (enabled by default).
129 * If disabled every page is considered non-same-value filled.
131 static bool zswap_same_filled_pages_enabled = true;
132 module_param_named(same_filled_pages_enabled, zswap_same_filled_pages_enabled,
135 /* Enable/disable handling non-same-value filled pages (enabled by default) */
136 static bool zswap_non_same_filled_pages_enabled = true;
137 module_param_named(non_same_filled_pages_enabled, zswap_non_same_filled_pages_enabled,
140 /*********************************
142 **********************************/
144 struct crypto_acomp_ctx {
145 struct crypto_acomp *acomp;
146 struct acomp_req *req;
147 struct crypto_wait wait;
154 struct crypto_acomp_ctx __percpu *acomp_ctx;
156 struct list_head list;
157 struct work_struct release_work;
158 struct work_struct shrink_work;
159 struct hlist_node node;
160 char tfm_name[CRYPTO_MAX_ALG_NAME];
166 * This structure contains the metadata for tracking a single compressed
169 * rbnode - links the entry into red-black tree for the appropriate swap type
170 * offset - the swap offset for the entry. Index into the red-black tree.
171 * refcount - the number of outstanding reference to the entry. This is needed
172 * to protect against premature freeing of the entry by code
173 * concurrent calls to load, invalidate, and writeback. The lock
174 * for the zswap_tree structure that contains the entry must
175 * be held while changing the refcount. Since the lock must
176 * be held, there is no reason to also make refcount atomic.
177 * length - the length in bytes of the compressed page data. Needed during
178 * decompression. For a same value filled page length is 0.
179 * pool - the zswap_pool the entry's data is in
180 * handle - zpool allocation handle that stores the compressed page data
181 * value - value of the same-value filled pages which have same content
184 struct rb_node rbnode;
188 struct zswap_pool *pool;
190 unsigned long handle;
193 struct obj_cgroup *objcg;
196 struct zswap_header {
197 swp_entry_t swpentry;
201 * The tree lock in the zswap_tree struct protects a few things:
203 * - the refcount field of each entry in the tree
206 struct rb_root rbroot;
210 static struct zswap_tree *zswap_trees[MAX_SWAPFILES];
212 /* RCU-protected iteration */
213 static LIST_HEAD(zswap_pools);
214 /* protects zswap_pools list modification */
215 static DEFINE_SPINLOCK(zswap_pools_lock);
216 /* pool counter to provide unique names to zpool */
217 static atomic_t zswap_pools_count = ATOMIC_INIT(0);
219 enum zswap_init_type {
225 static enum zswap_init_type zswap_init_state;
227 /* used to ensure the integrity of initialization */
228 static DEFINE_MUTEX(zswap_init_lock);
230 /* init completed, but couldn't create the initial pool */
231 static bool zswap_has_pool;
233 /*********************************
234 * helpers and fwd declarations
235 **********************************/
237 #define zswap_pool_debug(msg, p) \
238 pr_debug("%s pool %s/%s\n", msg, (p)->tfm_name, \
239 zpool_get_type((p)->zpool))
241 static int zswap_writeback_entry(struct zpool *pool, unsigned long handle);
242 static int zswap_pool_get(struct zswap_pool *pool);
243 static void zswap_pool_put(struct zswap_pool *pool);
245 static const struct zpool_ops zswap_zpool_ops = {
246 .evict = zswap_writeback_entry
249 static bool zswap_is_full(void)
251 return totalram_pages() * zswap_max_pool_percent / 100 <
252 DIV_ROUND_UP(zswap_pool_total_size, PAGE_SIZE);
255 static bool zswap_can_accept(void)
257 return totalram_pages() * zswap_accept_thr_percent / 100 *
258 zswap_max_pool_percent / 100 >
259 DIV_ROUND_UP(zswap_pool_total_size, PAGE_SIZE);
262 static void zswap_update_total_size(void)
264 struct zswap_pool *pool;
269 list_for_each_entry_rcu(pool, &zswap_pools, list)
270 total += zpool_get_total_size(pool->zpool);
274 zswap_pool_total_size = total;
277 /*********************************
278 * zswap entry functions
279 **********************************/
280 static struct kmem_cache *zswap_entry_cache;
282 static struct zswap_entry *zswap_entry_cache_alloc(gfp_t gfp)
284 struct zswap_entry *entry;
285 entry = kmem_cache_alloc(zswap_entry_cache, gfp);
289 RB_CLEAR_NODE(&entry->rbnode);
293 static void zswap_entry_cache_free(struct zswap_entry *entry)
295 kmem_cache_free(zswap_entry_cache, entry);
298 /*********************************
300 **********************************/
301 static struct zswap_entry *zswap_rb_search(struct rb_root *root, pgoff_t offset)
303 struct rb_node *node = root->rb_node;
304 struct zswap_entry *entry;
307 entry = rb_entry(node, struct zswap_entry, rbnode);
308 if (entry->offset > offset)
309 node = node->rb_left;
310 else if (entry->offset < offset)
311 node = node->rb_right;
319 * In the case that a entry with the same offset is found, a pointer to
320 * the existing entry is stored in dupentry and the function returns -EEXIST
322 static int zswap_rb_insert(struct rb_root *root, struct zswap_entry *entry,
323 struct zswap_entry **dupentry)
325 struct rb_node **link = &root->rb_node, *parent = NULL;
326 struct zswap_entry *myentry;
330 myentry = rb_entry(parent, struct zswap_entry, rbnode);
331 if (myentry->offset > entry->offset)
332 link = &(*link)->rb_left;
333 else if (myentry->offset < entry->offset)
334 link = &(*link)->rb_right;
340 rb_link_node(&entry->rbnode, parent, link);
341 rb_insert_color(&entry->rbnode, root);
345 static void zswap_rb_erase(struct rb_root *root, struct zswap_entry *entry)
347 if (!RB_EMPTY_NODE(&entry->rbnode)) {
348 rb_erase(&entry->rbnode, root);
349 RB_CLEAR_NODE(&entry->rbnode);
354 * Carries out the common pattern of freeing and entry's zpool allocation,
355 * freeing the entry itself, and decrementing the number of stored pages.
357 static void zswap_free_entry(struct zswap_entry *entry)
360 obj_cgroup_uncharge_zswap(entry->objcg, entry->length);
361 obj_cgroup_put(entry->objcg);
364 atomic_dec(&zswap_same_filled_pages);
366 zpool_free(entry->pool->zpool, entry->handle);
367 zswap_pool_put(entry->pool);
369 zswap_entry_cache_free(entry);
370 atomic_dec(&zswap_stored_pages);
371 zswap_update_total_size();
374 /* caller must hold the tree lock */
375 static void zswap_entry_get(struct zswap_entry *entry)
380 /* caller must hold the tree lock
381 * remove from the tree and free it, if nobody reference the entry
383 static void zswap_entry_put(struct zswap_tree *tree,
384 struct zswap_entry *entry)
386 int refcount = --entry->refcount;
388 BUG_ON(refcount < 0);
390 zswap_rb_erase(&tree->rbroot, entry);
391 zswap_free_entry(entry);
395 /* caller must hold the tree lock */
396 static struct zswap_entry *zswap_entry_find_get(struct rb_root *root,
399 struct zswap_entry *entry;
401 entry = zswap_rb_search(root, offset);
403 zswap_entry_get(entry);
408 /*********************************
410 **********************************/
411 static DEFINE_PER_CPU(u8 *, zswap_dstmem);
413 * If users dynamically change the zpool type and compressor at runtime, i.e.
414 * zswap is running, zswap can have more than one zpool on one cpu, but they
415 * are sharing dtsmem. So we need this mutex to be per-cpu.
417 static DEFINE_PER_CPU(struct mutex *, zswap_mutex);
419 static int zswap_dstmem_prepare(unsigned int cpu)
424 dst = kmalloc_node(PAGE_SIZE * 2, GFP_KERNEL, cpu_to_node(cpu));
428 mutex = kmalloc_node(sizeof(*mutex), GFP_KERNEL, cpu_to_node(cpu));
435 per_cpu(zswap_dstmem, cpu) = dst;
436 per_cpu(zswap_mutex, cpu) = mutex;
440 static int zswap_dstmem_dead(unsigned int cpu)
445 mutex = per_cpu(zswap_mutex, cpu);
447 per_cpu(zswap_mutex, cpu) = NULL;
449 dst = per_cpu(zswap_dstmem, cpu);
451 per_cpu(zswap_dstmem, cpu) = NULL;
456 static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node)
458 struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
459 struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
460 struct crypto_acomp *acomp;
461 struct acomp_req *req;
463 acomp = crypto_alloc_acomp_node(pool->tfm_name, 0, 0, cpu_to_node(cpu));
465 pr_err("could not alloc crypto acomp %s : %ld\n",
466 pool->tfm_name, PTR_ERR(acomp));
467 return PTR_ERR(acomp);
469 acomp_ctx->acomp = acomp;
471 req = acomp_request_alloc(acomp_ctx->acomp);
473 pr_err("could not alloc crypto acomp_request %s\n",
475 crypto_free_acomp(acomp_ctx->acomp);
478 acomp_ctx->req = req;
480 crypto_init_wait(&acomp_ctx->wait);
482 * if the backend of acomp is async zip, crypto_req_done() will wakeup
483 * crypto_wait_req(); if the backend of acomp is scomp, the callback
484 * won't be called, crypto_wait_req() will return without blocking.
486 acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
487 crypto_req_done, &acomp_ctx->wait);
489 acomp_ctx->mutex = per_cpu(zswap_mutex, cpu);
490 acomp_ctx->dstmem = per_cpu(zswap_dstmem, cpu);
495 static int zswap_cpu_comp_dead(unsigned int cpu, struct hlist_node *node)
497 struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
498 struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
500 if (!IS_ERR_OR_NULL(acomp_ctx)) {
501 if (!IS_ERR_OR_NULL(acomp_ctx->req))
502 acomp_request_free(acomp_ctx->req);
503 if (!IS_ERR_OR_NULL(acomp_ctx->acomp))
504 crypto_free_acomp(acomp_ctx->acomp);
510 /*********************************
512 **********************************/
514 static struct zswap_pool *__zswap_pool_current(void)
516 struct zswap_pool *pool;
518 pool = list_first_or_null_rcu(&zswap_pools, typeof(*pool), list);
519 WARN_ONCE(!pool && zswap_has_pool,
520 "%s: no page storage pool!\n", __func__);
525 static struct zswap_pool *zswap_pool_current(void)
527 assert_spin_locked(&zswap_pools_lock);
529 return __zswap_pool_current();
532 static struct zswap_pool *zswap_pool_current_get(void)
534 struct zswap_pool *pool;
538 pool = __zswap_pool_current();
539 if (!zswap_pool_get(pool))
547 static struct zswap_pool *zswap_pool_last_get(void)
549 struct zswap_pool *pool, *last = NULL;
553 list_for_each_entry_rcu(pool, &zswap_pools, list)
555 WARN_ONCE(!last && zswap_has_pool,
556 "%s: no page storage pool!\n", __func__);
557 if (!zswap_pool_get(last))
565 /* type and compressor must be null-terminated */
566 static struct zswap_pool *zswap_pool_find_get(char *type, char *compressor)
568 struct zswap_pool *pool;
570 assert_spin_locked(&zswap_pools_lock);
572 list_for_each_entry_rcu(pool, &zswap_pools, list) {
573 if (strcmp(pool->tfm_name, compressor))
575 if (strcmp(zpool_get_type(pool->zpool), type))
577 /* if we can't get it, it's about to be destroyed */
578 if (!zswap_pool_get(pool))
586 static void shrink_worker(struct work_struct *w)
588 struct zswap_pool *pool = container_of(w, typeof(*pool),
591 if (zpool_shrink(pool->zpool, 1, NULL))
592 zswap_reject_reclaim_fail++;
593 zswap_pool_put(pool);
596 static struct zswap_pool *zswap_pool_create(char *type, char *compressor)
598 struct zswap_pool *pool;
599 char name[38]; /* 'zswap' + 32 char (max) num + \0 */
600 gfp_t gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
603 if (!zswap_has_pool) {
604 /* if either are unset, pool initialization failed, and we
605 * need both params to be set correctly before trying to
608 if (!strcmp(type, ZSWAP_PARAM_UNSET))
610 if (!strcmp(compressor, ZSWAP_PARAM_UNSET))
614 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
618 /* unique name for each pool specifically required by zsmalloc */
619 snprintf(name, 38, "zswap%x", atomic_inc_return(&zswap_pools_count));
621 pool->zpool = zpool_create_pool(type, name, gfp, &zswap_zpool_ops);
623 pr_err("%s zpool not available\n", type);
626 pr_debug("using %s zpool\n", zpool_get_type(pool->zpool));
628 strscpy(pool->tfm_name, compressor, sizeof(pool->tfm_name));
630 pool->acomp_ctx = alloc_percpu(*pool->acomp_ctx);
631 if (!pool->acomp_ctx) {
632 pr_err("percpu alloc failed\n");
636 ret = cpuhp_state_add_instance(CPUHP_MM_ZSWP_POOL_PREPARE,
640 pr_debug("using %s compressor\n", pool->tfm_name);
642 /* being the current pool takes 1 ref; this func expects the
643 * caller to always add the new pool as the current pool
645 kref_init(&pool->kref);
646 INIT_LIST_HEAD(&pool->list);
647 INIT_WORK(&pool->shrink_work, shrink_worker);
649 zswap_pool_debug("created", pool);
655 free_percpu(pool->acomp_ctx);
657 zpool_destroy_pool(pool->zpool);
662 static struct zswap_pool *__zswap_pool_create_fallback(void)
664 bool has_comp, has_zpool;
666 has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
667 if (!has_comp && strcmp(zswap_compressor,
668 CONFIG_ZSWAP_COMPRESSOR_DEFAULT)) {
669 pr_err("compressor %s not available, using default %s\n",
670 zswap_compressor, CONFIG_ZSWAP_COMPRESSOR_DEFAULT);
671 param_free_charp(&zswap_compressor);
672 zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
673 has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
676 pr_err("default compressor %s not available\n",
678 param_free_charp(&zswap_compressor);
679 zswap_compressor = ZSWAP_PARAM_UNSET;
682 has_zpool = zpool_has_pool(zswap_zpool_type);
683 if (!has_zpool && strcmp(zswap_zpool_type,
684 CONFIG_ZSWAP_ZPOOL_DEFAULT)) {
685 pr_err("zpool %s not available, using default %s\n",
686 zswap_zpool_type, CONFIG_ZSWAP_ZPOOL_DEFAULT);
687 param_free_charp(&zswap_zpool_type);
688 zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
689 has_zpool = zpool_has_pool(zswap_zpool_type);
692 pr_err("default zpool %s not available\n",
694 param_free_charp(&zswap_zpool_type);
695 zswap_zpool_type = ZSWAP_PARAM_UNSET;
698 if (!has_comp || !has_zpool)
701 return zswap_pool_create(zswap_zpool_type, zswap_compressor);
704 static void zswap_pool_destroy(struct zswap_pool *pool)
706 zswap_pool_debug("destroying", pool);
708 cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
709 free_percpu(pool->acomp_ctx);
710 zpool_destroy_pool(pool->zpool);
714 static int __must_check zswap_pool_get(struct zswap_pool *pool)
719 return kref_get_unless_zero(&pool->kref);
722 static void __zswap_pool_release(struct work_struct *work)
724 struct zswap_pool *pool = container_of(work, typeof(*pool),
729 /* nobody should have been able to get a kref... */
730 WARN_ON(kref_get_unless_zero(&pool->kref));
732 /* pool is now off zswap_pools list and has no references. */
733 zswap_pool_destroy(pool);
736 static void __zswap_pool_empty(struct kref *kref)
738 struct zswap_pool *pool;
740 pool = container_of(kref, typeof(*pool), kref);
742 spin_lock(&zswap_pools_lock);
744 WARN_ON(pool == zswap_pool_current());
746 list_del_rcu(&pool->list);
748 INIT_WORK(&pool->release_work, __zswap_pool_release);
749 schedule_work(&pool->release_work);
751 spin_unlock(&zswap_pools_lock);
754 static void zswap_pool_put(struct zswap_pool *pool)
756 kref_put(&pool->kref, __zswap_pool_empty);
759 /*********************************
761 **********************************/
763 static bool zswap_pool_changed(const char *s, const struct kernel_param *kp)
765 /* no change required */
766 if (!strcmp(s, *(char **)kp->arg) && zswap_has_pool)
771 /* val must be a null-terminated string */
772 static int __zswap_param_set(const char *val, const struct kernel_param *kp,
773 char *type, char *compressor)
775 struct zswap_pool *pool, *put_pool = NULL;
776 char *s = strstrip((char *)val);
778 bool new_pool = false;
780 mutex_lock(&zswap_init_lock);
781 switch (zswap_init_state) {
783 /* if this is load-time (pre-init) param setting,
784 * don't create a pool; that's done during init.
786 ret = param_set_charp(s, kp);
788 case ZSWAP_INIT_SUCCEED:
789 new_pool = zswap_pool_changed(s, kp);
791 case ZSWAP_INIT_FAILED:
792 pr_err("can't set param, initialization failed\n");
795 mutex_unlock(&zswap_init_lock);
797 /* no need to create a new pool, return directly */
802 if (!zpool_has_pool(s)) {
803 pr_err("zpool %s not available\n", s);
807 } else if (!compressor) {
808 if (!crypto_has_acomp(s, 0, 0)) {
809 pr_err("compressor %s not available\n", s);
818 spin_lock(&zswap_pools_lock);
820 pool = zswap_pool_find_get(type, compressor);
822 zswap_pool_debug("using existing", pool);
823 WARN_ON(pool == zswap_pool_current());
824 list_del_rcu(&pool->list);
827 spin_unlock(&zswap_pools_lock);
830 pool = zswap_pool_create(type, compressor);
833 ret = param_set_charp(s, kp);
837 spin_lock(&zswap_pools_lock);
840 put_pool = zswap_pool_current();
841 list_add_rcu(&pool->list, &zswap_pools);
842 zswap_has_pool = true;
844 /* add the possibly pre-existing pool to the end of the pools
845 * list; if it's new (and empty) then it'll be removed and
846 * destroyed by the put after we drop the lock
848 list_add_tail_rcu(&pool->list, &zswap_pools);
852 spin_unlock(&zswap_pools_lock);
854 if (!zswap_has_pool && !pool) {
855 /* if initial pool creation failed, and this pool creation also
856 * failed, maybe both compressor and zpool params were bad.
857 * Allow changing this param, so pool creation will succeed
858 * when the other param is changed. We already verified this
859 * param is ok in the zpool_has_pool() or crypto_has_acomp()
862 ret = param_set_charp(s, kp);
865 /* drop the ref from either the old current pool,
866 * or the new pool we failed to add
869 zswap_pool_put(put_pool);
874 static int zswap_compressor_param_set(const char *val,
875 const struct kernel_param *kp)
877 return __zswap_param_set(val, kp, zswap_zpool_type, NULL);
880 static int zswap_zpool_param_set(const char *val,
881 const struct kernel_param *kp)
883 return __zswap_param_set(val, kp, NULL, zswap_compressor);
886 static int zswap_enabled_param_set(const char *val,
887 const struct kernel_param *kp)
891 /* if this is load-time (pre-init) param setting, only set param. */
892 if (system_state != SYSTEM_RUNNING)
893 return param_set_bool(val, kp);
895 mutex_lock(&zswap_init_lock);
896 switch (zswap_init_state) {
901 case ZSWAP_INIT_SUCCEED:
903 pr_err("can't enable, no pool configured\n");
905 ret = param_set_bool(val, kp);
907 case ZSWAP_INIT_FAILED:
908 pr_err("can't enable, initialization failed\n");
910 mutex_unlock(&zswap_init_lock);
915 /*********************************
917 **********************************/
918 /* return enum for zswap_get_swap_cache_page */
919 enum zswap_get_swap_ret {
921 ZSWAP_SWAPCACHE_EXIST,
922 ZSWAP_SWAPCACHE_FAIL,
926 * zswap_get_swap_cache_page
928 * This is an adaption of read_swap_cache_async()
930 * This function tries to find a page with the given swap entry
931 * in the swapper_space address space (the swap cache). If the page
932 * is found, it is returned in retpage. Otherwise, a page is allocated,
933 * added to the swap cache, and returned in retpage.
935 * If success, the swap cache page is returned in retpage
936 * Returns ZSWAP_SWAPCACHE_EXIST if page was already in the swap cache
937 * Returns ZSWAP_SWAPCACHE_NEW if the new page needs to be populated,
938 * the new page is added to swapcache and locked
939 * Returns ZSWAP_SWAPCACHE_FAIL on error
941 static int zswap_get_swap_cache_page(swp_entry_t entry,
942 struct page **retpage)
944 bool page_was_allocated;
946 *retpage = __read_swap_cache_async(entry, GFP_KERNEL,
947 NULL, 0, &page_was_allocated);
948 if (page_was_allocated)
949 return ZSWAP_SWAPCACHE_NEW;
951 return ZSWAP_SWAPCACHE_FAIL;
952 return ZSWAP_SWAPCACHE_EXIST;
956 * Attempts to free an entry by adding a page to the swap cache,
957 * decompressing the entry data into the page, and issuing a
958 * bio write to write the page back to the swap device.
960 * This can be thought of as a "resumed writeback" of the page
961 * to the swap device. We are basically resuming the same swap
962 * writeback path that was intercepted with the frontswap_store()
963 * in the first place. After the page has been decompressed into
964 * the swap cache, the compressed version stored by zswap can be
967 static int zswap_writeback_entry(struct zpool *pool, unsigned long handle)
969 struct zswap_header *zhdr;
970 swp_entry_t swpentry;
971 struct zswap_tree *tree;
973 struct zswap_entry *entry;
975 struct scatterlist input, output;
976 struct crypto_acomp_ctx *acomp_ctx;
978 u8 *src, *tmp = NULL;
981 struct writeback_control wbc = {
982 .sync_mode = WB_SYNC_NONE,
985 if (!zpool_can_sleep_mapped(pool)) {
986 tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
991 /* extract swpentry from data */
992 zhdr = zpool_map_handle(pool, handle, ZPOOL_MM_RO);
993 swpentry = zhdr->swpentry; /* here */
994 tree = zswap_trees[swp_type(swpentry)];
995 offset = swp_offset(swpentry);
996 zpool_unmap_handle(pool, handle);
998 /* find and ref zswap entry */
999 spin_lock(&tree->lock);
1000 entry = zswap_entry_find_get(&tree->rbroot, offset);
1002 /* entry was invalidated */
1003 spin_unlock(&tree->lock);
1007 spin_unlock(&tree->lock);
1008 BUG_ON(offset != entry->offset);
1010 /* try to allocate swap cache page */
1011 switch (zswap_get_swap_cache_page(swpentry, &page)) {
1012 case ZSWAP_SWAPCACHE_FAIL: /* no memory or invalidate happened */
1016 case ZSWAP_SWAPCACHE_EXIST:
1017 /* page is already in the swap cache, ignore for now */
1022 case ZSWAP_SWAPCACHE_NEW: /* page is locked */
1024 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1027 zhdr = zpool_map_handle(pool, handle, ZPOOL_MM_RO);
1028 src = (u8 *)zhdr + sizeof(struct zswap_header);
1029 if (!zpool_can_sleep_mapped(pool)) {
1030 memcpy(tmp, src, entry->length);
1032 zpool_unmap_handle(pool, handle);
1035 mutex_lock(acomp_ctx->mutex);
1036 sg_init_one(&input, src, entry->length);
1037 sg_init_table(&output, 1);
1038 sg_set_page(&output, page, PAGE_SIZE, 0);
1039 acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, dlen);
1040 ret = crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait);
1041 dlen = acomp_ctx->req->dlen;
1042 mutex_unlock(acomp_ctx->mutex);
1044 if (!zpool_can_sleep_mapped(pool))
1047 zpool_unmap_handle(pool, handle);
1050 BUG_ON(dlen != PAGE_SIZE);
1052 /* page is up to date */
1053 SetPageUptodate(page);
1056 /* move it to the tail of the inactive list after end_writeback */
1057 SetPageReclaim(page);
1059 /* start writeback */
1060 __swap_writepage(page, &wbc);
1062 zswap_written_back_pages++;
1064 spin_lock(&tree->lock);
1065 /* drop local reference */
1066 zswap_entry_put(tree, entry);
1069 * There are two possible situations for entry here:
1070 * (1) refcount is 1(normal case), entry is valid and on the tree
1071 * (2) refcount is 0, entry is freed and not on the tree
1072 * because invalidate happened during writeback
1073 * search the tree and free the entry if find entry
1075 if (entry == zswap_rb_search(&tree->rbroot, offset))
1076 zswap_entry_put(tree, entry);
1077 spin_unlock(&tree->lock);
1082 if (!zpool_can_sleep_mapped(pool))
1086 * if we get here due to ZSWAP_SWAPCACHE_EXIST
1087 * a load may be happening concurrently.
1088 * it is safe and okay to not free the entry.
1089 * if we free the entry in the following put
1090 * it is also okay to return !0
1092 spin_lock(&tree->lock);
1093 zswap_entry_put(tree, entry);
1094 spin_unlock(&tree->lock);
1099 static int zswap_is_page_same_filled(void *ptr, unsigned long *value)
1101 unsigned long *page;
1103 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
1105 page = (unsigned long *)ptr;
1108 if (val != page[last_pos])
1111 for (pos = 1; pos < last_pos; pos++) {
1112 if (val != page[pos])
1121 static void zswap_fill_page(void *ptr, unsigned long value)
1123 unsigned long *page;
1125 page = (unsigned long *)ptr;
1126 memset_l(page, value, PAGE_SIZE / sizeof(unsigned long));
1129 /*********************************
1131 **********************************/
1132 /* attempts to compress and store an single page */
1133 static int zswap_frontswap_store(unsigned type, pgoff_t offset,
1136 struct zswap_tree *tree = zswap_trees[type];
1137 struct zswap_entry *entry, *dupentry;
1138 struct scatterlist input, output;
1139 struct crypto_acomp_ctx *acomp_ctx;
1140 struct obj_cgroup *objcg = NULL;
1141 struct zswap_pool *pool;
1143 unsigned int hlen, dlen = PAGE_SIZE;
1144 unsigned long handle, value;
1147 struct zswap_header zhdr = { .swpentry = swp_entry(type, offset) };
1150 /* THP isn't supported */
1151 if (PageTransHuge(page)) {
1156 if (!zswap_enabled || !tree) {
1161 objcg = get_obj_cgroup_from_page(page);
1162 if (objcg && !obj_cgroup_may_zswap(objcg))
1165 /* reclaim space if needed */
1166 if (zswap_is_full()) {
1167 zswap_pool_limit_hit++;
1168 zswap_pool_reached_full = true;
1172 if (zswap_pool_reached_full) {
1173 if (!zswap_can_accept()) {
1177 zswap_pool_reached_full = false;
1180 /* allocate entry */
1181 entry = zswap_entry_cache_alloc(GFP_KERNEL);
1183 zswap_reject_kmemcache_fail++;
1188 if (zswap_same_filled_pages_enabled) {
1189 src = kmap_atomic(page);
1190 if (zswap_is_page_same_filled(src, &value)) {
1192 entry->offset = offset;
1194 entry->value = value;
1195 atomic_inc(&zswap_same_filled_pages);
1201 if (!zswap_non_same_filled_pages_enabled) {
1206 /* if entry is successfully added, it keeps the reference */
1207 entry->pool = zswap_pool_current_get();
1214 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1216 mutex_lock(acomp_ctx->mutex);
1218 dst = acomp_ctx->dstmem;
1219 sg_init_table(&input, 1);
1220 sg_set_page(&input, page, PAGE_SIZE, 0);
1222 /* zswap_dstmem is of size (PAGE_SIZE * 2). Reflect same in sg_list */
1223 sg_init_one(&output, dst, PAGE_SIZE * 2);
1224 acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen);
1226 * it maybe looks a little bit silly that we send an asynchronous request,
1227 * then wait for its completion synchronously. This makes the process look
1228 * synchronous in fact.
1229 * Theoretically, acomp supports users send multiple acomp requests in one
1230 * acomp instance, then get those requests done simultaneously. but in this
1231 * case, frontswap actually does store and load page by page, there is no
1232 * existing method to send the second page before the first page is done
1233 * in one thread doing frontswap.
1234 * but in different threads running on different cpu, we have different
1235 * acomp instance, so multiple threads can do (de)compression in parallel.
1237 ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait);
1238 dlen = acomp_ctx->req->dlen;
1246 hlen = zpool_evictable(entry->pool->zpool) ? sizeof(zhdr) : 0;
1247 gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
1248 if (zpool_malloc_support_movable(entry->pool->zpool))
1249 gfp |= __GFP_HIGHMEM | __GFP_MOVABLE;
1250 ret = zpool_malloc(entry->pool->zpool, hlen + dlen, gfp, &handle);
1251 if (ret == -ENOSPC) {
1252 zswap_reject_compress_poor++;
1256 zswap_reject_alloc_fail++;
1259 buf = zpool_map_handle(entry->pool->zpool, handle, ZPOOL_MM_WO);
1260 memcpy(buf, &zhdr, hlen);
1261 memcpy(buf + hlen, dst, dlen);
1262 zpool_unmap_handle(entry->pool->zpool, handle);
1263 mutex_unlock(acomp_ctx->mutex);
1265 /* populate entry */
1266 entry->offset = offset;
1267 entry->handle = handle;
1268 entry->length = dlen;
1271 entry->objcg = objcg;
1273 obj_cgroup_charge_zswap(objcg, entry->length);
1274 /* Account before objcg ref is moved to tree */
1275 count_objcg_event(objcg, ZSWPOUT);
1279 spin_lock(&tree->lock);
1281 ret = zswap_rb_insert(&tree->rbroot, entry, &dupentry);
1282 if (ret == -EEXIST) {
1283 zswap_duplicate_entry++;
1284 /* remove from rbtree */
1285 zswap_rb_erase(&tree->rbroot, dupentry);
1286 zswap_entry_put(tree, dupentry);
1288 } while (ret == -EEXIST);
1289 spin_unlock(&tree->lock);
1292 atomic_inc(&zswap_stored_pages);
1293 zswap_update_total_size();
1294 count_vm_event(ZSWPOUT);
1299 mutex_unlock(acomp_ctx->mutex);
1300 zswap_pool_put(entry->pool);
1302 zswap_entry_cache_free(entry);
1305 obj_cgroup_put(objcg);
1309 pool = zswap_pool_last_get();
1311 queue_work(shrink_wq, &pool->shrink_work);
1317 * returns 0 if the page was successfully decompressed
1318 * return -1 on entry not found or error
1320 static int zswap_frontswap_load(unsigned type, pgoff_t offset,
1323 struct zswap_tree *tree = zswap_trees[type];
1324 struct zswap_entry *entry;
1325 struct scatterlist input, output;
1326 struct crypto_acomp_ctx *acomp_ctx;
1327 u8 *src, *dst, *tmp;
1332 spin_lock(&tree->lock);
1333 entry = zswap_entry_find_get(&tree->rbroot, offset);
1335 /* entry was written back */
1336 spin_unlock(&tree->lock);
1339 spin_unlock(&tree->lock);
1341 if (!entry->length) {
1342 dst = kmap_atomic(page);
1343 zswap_fill_page(dst, entry->value);
1349 if (!zpool_can_sleep_mapped(entry->pool->zpool)) {
1350 tmp = kmalloc(entry->length, GFP_KERNEL);
1359 src = zpool_map_handle(entry->pool->zpool, entry->handle, ZPOOL_MM_RO);
1360 if (zpool_evictable(entry->pool->zpool))
1361 src += sizeof(struct zswap_header);
1363 if (!zpool_can_sleep_mapped(entry->pool->zpool)) {
1364 memcpy(tmp, src, entry->length);
1366 zpool_unmap_handle(entry->pool->zpool, entry->handle);
1369 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1370 mutex_lock(acomp_ctx->mutex);
1371 sg_init_one(&input, src, entry->length);
1372 sg_init_table(&output, 1);
1373 sg_set_page(&output, page, PAGE_SIZE, 0);
1374 acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, dlen);
1375 ret = crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait);
1376 mutex_unlock(acomp_ctx->mutex);
1378 if (zpool_can_sleep_mapped(entry->pool->zpool))
1379 zpool_unmap_handle(entry->pool->zpool, entry->handle);
1385 count_vm_event(ZSWPIN);
1387 count_objcg_event(entry->objcg, ZSWPIN);
1389 spin_lock(&tree->lock);
1390 zswap_entry_put(tree, entry);
1391 spin_unlock(&tree->lock);
1396 /* frees an entry in zswap */
1397 static void zswap_frontswap_invalidate_page(unsigned type, pgoff_t offset)
1399 struct zswap_tree *tree = zswap_trees[type];
1400 struct zswap_entry *entry;
1403 spin_lock(&tree->lock);
1404 entry = zswap_rb_search(&tree->rbroot, offset);
1406 /* entry was written back */
1407 spin_unlock(&tree->lock);
1411 /* remove from rbtree */
1412 zswap_rb_erase(&tree->rbroot, entry);
1414 /* drop the initial reference from entry creation */
1415 zswap_entry_put(tree, entry);
1417 spin_unlock(&tree->lock);
1420 /* frees all zswap entries for the given swap type */
1421 static void zswap_frontswap_invalidate_area(unsigned type)
1423 struct zswap_tree *tree = zswap_trees[type];
1424 struct zswap_entry *entry, *n;
1429 /* walk the tree and free everything */
1430 spin_lock(&tree->lock);
1431 rbtree_postorder_for_each_entry_safe(entry, n, &tree->rbroot, rbnode)
1432 zswap_free_entry(entry);
1433 tree->rbroot = RB_ROOT;
1434 spin_unlock(&tree->lock);
1436 zswap_trees[type] = NULL;
1439 static void zswap_frontswap_init(unsigned type)
1441 struct zswap_tree *tree;
1443 tree = kzalloc(sizeof(*tree), GFP_KERNEL);
1445 pr_err("alloc failed, zswap disabled for swap type %d\n", type);
1449 tree->rbroot = RB_ROOT;
1450 spin_lock_init(&tree->lock);
1451 zswap_trees[type] = tree;
1454 static const struct frontswap_ops zswap_frontswap_ops = {
1455 .store = zswap_frontswap_store,
1456 .load = zswap_frontswap_load,
1457 .invalidate_page = zswap_frontswap_invalidate_page,
1458 .invalidate_area = zswap_frontswap_invalidate_area,
1459 .init = zswap_frontswap_init
1462 /*********************************
1464 **********************************/
1465 #ifdef CONFIG_DEBUG_FS
1466 #include <linux/debugfs.h>
1468 static struct dentry *zswap_debugfs_root;
1470 static int zswap_debugfs_init(void)
1472 if (!debugfs_initialized())
1475 zswap_debugfs_root = debugfs_create_dir("zswap", NULL);
1477 debugfs_create_u64("pool_limit_hit", 0444,
1478 zswap_debugfs_root, &zswap_pool_limit_hit);
1479 debugfs_create_u64("reject_reclaim_fail", 0444,
1480 zswap_debugfs_root, &zswap_reject_reclaim_fail);
1481 debugfs_create_u64("reject_alloc_fail", 0444,
1482 zswap_debugfs_root, &zswap_reject_alloc_fail);
1483 debugfs_create_u64("reject_kmemcache_fail", 0444,
1484 zswap_debugfs_root, &zswap_reject_kmemcache_fail);
1485 debugfs_create_u64("reject_compress_poor", 0444,
1486 zswap_debugfs_root, &zswap_reject_compress_poor);
1487 debugfs_create_u64("written_back_pages", 0444,
1488 zswap_debugfs_root, &zswap_written_back_pages);
1489 debugfs_create_u64("duplicate_entry", 0444,
1490 zswap_debugfs_root, &zswap_duplicate_entry);
1491 debugfs_create_u64("pool_total_size", 0444,
1492 zswap_debugfs_root, &zswap_pool_total_size);
1493 debugfs_create_atomic_t("stored_pages", 0444,
1494 zswap_debugfs_root, &zswap_stored_pages);
1495 debugfs_create_atomic_t("same_filled_pages", 0444,
1496 zswap_debugfs_root, &zswap_same_filled_pages);
1501 static int zswap_debugfs_init(void)
1507 /*********************************
1508 * module init and exit
1509 **********************************/
1510 static int zswap_setup(void)
1512 struct zswap_pool *pool;
1515 zswap_entry_cache = KMEM_CACHE(zswap_entry, 0);
1516 if (!zswap_entry_cache) {
1517 pr_err("entry cache creation failed\n");
1521 ret = cpuhp_setup_state(CPUHP_MM_ZSWP_MEM_PREPARE, "mm/zswap:prepare",
1522 zswap_dstmem_prepare, zswap_dstmem_dead);
1524 pr_err("dstmem alloc failed\n");
1528 ret = cpuhp_setup_state_multi(CPUHP_MM_ZSWP_POOL_PREPARE,
1529 "mm/zswap_pool:prepare",
1530 zswap_cpu_comp_prepare,
1531 zswap_cpu_comp_dead);
1535 pool = __zswap_pool_create_fallback();
1537 pr_info("loaded using pool %s/%s\n", pool->tfm_name,
1538 zpool_get_type(pool->zpool));
1539 list_add(&pool->list, &zswap_pools);
1540 zswap_has_pool = true;
1542 pr_err("pool creation failed\n");
1543 zswap_enabled = false;
1546 shrink_wq = create_workqueue("zswap-shrink");
1550 ret = frontswap_register_ops(&zswap_frontswap_ops);
1553 if (zswap_debugfs_init())
1554 pr_warn("debugfs initialization failed\n");
1555 zswap_init_state = ZSWAP_INIT_SUCCEED;
1559 destroy_workqueue(shrink_wq);
1562 zswap_pool_destroy(pool);
1564 cpuhp_remove_state(CPUHP_MM_ZSWP_MEM_PREPARE);
1566 kmem_cache_destroy(zswap_entry_cache);
1568 /* if built-in, we aren't unloaded on failure; don't allow use */
1569 zswap_init_state = ZSWAP_INIT_FAILED;
1570 zswap_enabled = false;
1574 static int __init zswap_init(void)
1578 return zswap_setup();
1580 /* must be late so crypto has time to come up */
1581 late_initcall(zswap_init);
1583 MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
1584 MODULE_DESCRIPTION("Compressed cache for swap pages");