mm, oom:dump_tasks add rss detailed information printing
[linux-block.git] / mm / zswap.c
CommitLineData
c942fddf 1// SPDX-License-Identifier: GPL-2.0-or-later
2b281117
SJ
2/*
3 * zswap.c - zswap driver file
4 *
42c06a0e 5 * zswap is a cache that takes pages that are in the process
2b281117
SJ
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.
10 *
11 * Copyright (C) 2012 Seth Jennings <sjenning@linux.vnet.ibm.com>
2b281117
SJ
12*/
13
14#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15
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>
2b281117
SJ
23#include <linux/rbtree.h>
24#include <linux/swap.h>
25#include <linux/crypto.h>
1ec3b5fe 26#include <linux/scatterlist.h>
ddc1a5cb 27#include <linux/mempolicy.h>
2b281117 28#include <linux/mempool.h>
12d79d64 29#include <linux/zpool.h>
1ec3b5fe 30#include <crypto/acompress.h>
42c06a0e 31#include <linux/zswap.h>
2b281117
SJ
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>
45190f01 37#include <linux/workqueue.h>
2b281117 38
014bb1de 39#include "swap.h"
e0228d59 40#include "internal.h"
014bb1de 41
2b281117
SJ
42/*********************************
43* statistics
44**********************************/
12d79d64 45/* Total bytes used by the compressed storage */
f6498b77 46u64 zswap_pool_total_size;
2b281117 47/* The number of compressed pages currently stored in zswap */
f6498b77 48atomic_t zswap_stored_pages = ATOMIC_INIT(0);
a85f878b
SD
49/* The number of same-value filled pages currently stored in zswap */
50static atomic_t zswap_same_filled_pages = ATOMIC_INIT(0);
2b281117
SJ
51
52/*
53 * The statistics below are not protected from concurrent access for
54 * performance reasons so they may not be a 100% accurate. However,
55 * they do provide useful information on roughly how many times a
56 * certain event is occurring.
57*/
58
59/* Pool limit was hit (see zswap_max_pool_percent) */
60static u64 zswap_pool_limit_hit;
61/* Pages written back when pool limit was reached */
62static u64 zswap_written_back_pages;
63/* Store failed due to a reclaim failure after pool limit was reached */
64static u64 zswap_reject_reclaim_fail;
cb61dad8
NP
65/* Store failed due to compression algorithm failure */
66static u64 zswap_reject_compress_fail;
2b281117
SJ
67/* Compressed page was too big for the allocator to (optimally) store */
68static u64 zswap_reject_compress_poor;
69/* Store failed because underlying allocator could not get memory */
70static u64 zswap_reject_alloc_fail;
71/* Store failed because the entry metadata could not be allocated (rare) */
72static u64 zswap_reject_kmemcache_fail;
73/* Duplicate store was encountered (rare) */
74static u64 zswap_duplicate_entry;
75
45190f01
VW
76/* Shrinker work queue */
77static struct workqueue_struct *shrink_wq;
78/* Pool limit was hit, we need to calm down */
79static bool zswap_pool_reached_full;
80
2b281117
SJ
81/*********************************
82* tunables
83**********************************/
c00ed16a 84
bae21db8
DS
85#define ZSWAP_PARAM_UNSET ""
86
141fdeec
LS
87static int zswap_setup(void);
88
bb8b93b5
MS
89/* Enable/disable zswap */
90static bool zswap_enabled = IS_ENABLED(CONFIG_ZSWAP_DEFAULT_ON);
d7b028f5
DS
91static int zswap_enabled_param_set(const char *,
92 const struct kernel_param *);
83aed6cd 93static const struct kernel_param_ops zswap_enabled_param_ops = {
d7b028f5
DS
94 .set = zswap_enabled_param_set,
95 .get = param_get_bool,
96};
97module_param_cb(enabled, &zswap_enabled_param_ops, &zswap_enabled, 0644);
2b281117 98
90b0fc26 99/* Crypto compressor to use */
bb8b93b5 100static char *zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
90b0fc26
DS
101static int zswap_compressor_param_set(const char *,
102 const struct kernel_param *);
83aed6cd 103static const struct kernel_param_ops zswap_compressor_param_ops = {
90b0fc26 104 .set = zswap_compressor_param_set,
c99b42c3
DS
105 .get = param_get_charp,
106 .free = param_free_charp,
90b0fc26
DS
107};
108module_param_cb(compressor, &zswap_compressor_param_ops,
c99b42c3 109 &zswap_compressor, 0644);
2b281117 110
90b0fc26 111/* Compressed storage zpool to use */
bb8b93b5 112static char *zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
90b0fc26 113static int zswap_zpool_param_set(const char *, const struct kernel_param *);
83aed6cd 114static const struct kernel_param_ops zswap_zpool_param_ops = {
c99b42c3
DS
115 .set = zswap_zpool_param_set,
116 .get = param_get_charp,
117 .free = param_free_charp,
90b0fc26 118};
c99b42c3 119module_param_cb(zpool, &zswap_zpool_param_ops, &zswap_zpool_type, 0644);
12d79d64 120
90b0fc26
DS
121/* The maximum percentage of memory that the compressed pool can occupy */
122static unsigned int zswap_max_pool_percent = 20;
123module_param_named(max_pool_percent, zswap_max_pool_percent, uint, 0644);
60105e12 124
45190f01
VW
125/* The threshold for accepting new pages after the max_pool_percent was hit */
126static unsigned int zswap_accept_thr_percent = 90; /* of max pool size */
127module_param_named(accept_threshold_percent, zswap_accept_thr_percent,
128 uint, 0644);
129
cb325ddd
MS
130/*
131 * Enable/disable handling same-value filled pages (enabled by default).
132 * If disabled every page is considered non-same-value filled.
133 */
a85f878b
SD
134static bool zswap_same_filled_pages_enabled = true;
135module_param_named(same_filled_pages_enabled, zswap_same_filled_pages_enabled,
136 bool, 0644);
137
cb325ddd
MS
138/* Enable/disable handling non-same-value filled pages (enabled by default) */
139static bool zswap_non_same_filled_pages_enabled = true;
140module_param_named(non_same_filled_pages_enabled, zswap_non_same_filled_pages_enabled,
141 bool, 0644);
142
b9c91c43
YA
143static bool zswap_exclusive_loads_enabled = IS_ENABLED(
144 CONFIG_ZSWAP_EXCLUSIVE_LOADS_DEFAULT_ON);
145module_param_named(exclusive_loads, zswap_exclusive_loads_enabled, bool, 0644);
146
b8cf32dc
YA
147/* Number of zpools in zswap_pool (empirically determined for scalability) */
148#define ZSWAP_NR_ZPOOLS 32
149
2b281117 150/*********************************
f1c54846 151* data structures
2b281117 152**********************************/
2b281117 153
1ec3b5fe
BS
154struct crypto_acomp_ctx {
155 struct crypto_acomp *acomp;
156 struct acomp_req *req;
157 struct crypto_wait wait;
158 u8 *dstmem;
159 struct mutex *mutex;
160};
161
f999f38b
DC
162/*
163 * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock.
164 * The only case where lru_lock is not acquired while holding tree.lock is
165 * when a zswap_entry is taken off the lru for writeback, in that case it
166 * needs to be verified that it's still valid in the tree.
167 */
f1c54846 168struct zswap_pool {
b8cf32dc 169 struct zpool *zpools[ZSWAP_NR_ZPOOLS];
1ec3b5fe 170 struct crypto_acomp_ctx __percpu *acomp_ctx;
f1c54846
DS
171 struct kref kref;
172 struct list_head list;
45190f01
VW
173 struct work_struct release_work;
174 struct work_struct shrink_work;
cab7a7e5 175 struct hlist_node node;
f1c54846 176 char tfm_name[CRYPTO_MAX_ALG_NAME];
f999f38b
DC
177 struct list_head lru;
178 spinlock_t lru_lock;
2b281117
SJ
179};
180
2b281117
SJ
181/*
182 * struct zswap_entry
183 *
184 * This structure contains the metadata for tracking a single compressed
185 * page within zswap.
186 *
187 * rbnode - links the entry into red-black tree for the appropriate swap type
97157d89 188 * swpentry - associated swap entry, the offset indexes into the red-black tree
2b281117
SJ
189 * refcount - the number of outstanding reference to the entry. This is needed
190 * to protect against premature freeing of the entry by code
6b452516 191 * concurrent calls to load, invalidate, and writeback. The lock
2b281117
SJ
192 * for the zswap_tree structure that contains the entry must
193 * be held while changing the refcount. Since the lock must
194 * be held, there is no reason to also make refcount atomic.
2b281117 195 * length - the length in bytes of the compressed page data. Needed during
f999f38b
DC
196 * decompression. For a same value filled page length is 0, and both
197 * pool and lru are invalid and must be ignored.
f1c54846
DS
198 * pool - the zswap_pool the entry's data is in
199 * handle - zpool allocation handle that stores the compressed page data
a85f878b 200 * value - value of the same-value filled pages which have same content
97157d89 201 * objcg - the obj_cgroup that the compressed memory is charged to
f999f38b 202 * lru - handle to the pool's lru used to evict pages.
2b281117
SJ
203 */
204struct zswap_entry {
205 struct rb_node rbnode;
0bb48849 206 swp_entry_t swpentry;
2b281117
SJ
207 int refcount;
208 unsigned int length;
f1c54846 209 struct zswap_pool *pool;
a85f878b
SD
210 union {
211 unsigned long handle;
212 unsigned long value;
213 };
f4840ccf 214 struct obj_cgroup *objcg;
f999f38b 215 struct list_head lru;
2b281117
SJ
216};
217
2b281117
SJ
218/*
219 * The tree lock in the zswap_tree struct protects a few things:
220 * - the rbtree
221 * - the refcount field of each entry in the tree
222 */
223struct zswap_tree {
224 struct rb_root rbroot;
225 spinlock_t lock;
2b281117
SJ
226};
227
228static struct zswap_tree *zswap_trees[MAX_SWAPFILES];
229
f1c54846
DS
230/* RCU-protected iteration */
231static LIST_HEAD(zswap_pools);
232/* protects zswap_pools list modification */
233static DEFINE_SPINLOCK(zswap_pools_lock);
32a4e169
DS
234/* pool counter to provide unique names to zpool */
235static atomic_t zswap_pools_count = ATOMIC_INIT(0);
f1c54846 236
9021ccec
LS
237enum zswap_init_type {
238 ZSWAP_UNINIT,
239 ZSWAP_INIT_SUCCEED,
240 ZSWAP_INIT_FAILED
241};
90b0fc26 242
9021ccec 243static enum zswap_init_type zswap_init_state;
90b0fc26 244
141fdeec
LS
245/* used to ensure the integrity of initialization */
246static DEFINE_MUTEX(zswap_init_lock);
d7b028f5 247
ae3d89a7
DS
248/* init completed, but couldn't create the initial pool */
249static bool zswap_has_pool;
250
f1c54846
DS
251/*********************************
252* helpers and fwd declarations
253**********************************/
254
255#define zswap_pool_debug(msg, p) \
256 pr_debug("%s pool %s/%s\n", msg, (p)->tfm_name, \
b8cf32dc 257 zpool_get_type((p)->zpools[0]))
f1c54846 258
0bb48849 259static int zswap_writeback_entry(struct zswap_entry *entry,
ff9d5ba2 260 struct zswap_tree *tree);
f1c54846
DS
261static int zswap_pool_get(struct zswap_pool *pool);
262static void zswap_pool_put(struct zswap_pool *pool);
263
f1c54846
DS
264static bool zswap_is_full(void)
265{
ca79b0c2
AK
266 return totalram_pages() * zswap_max_pool_percent / 100 <
267 DIV_ROUND_UP(zswap_pool_total_size, PAGE_SIZE);
f1c54846
DS
268}
269
45190f01
VW
270static bool zswap_can_accept(void)
271{
272 return totalram_pages() * zswap_accept_thr_percent / 100 *
273 zswap_max_pool_percent / 100 >
274 DIV_ROUND_UP(zswap_pool_total_size, PAGE_SIZE);
275}
276
f1c54846
DS
277static void zswap_update_total_size(void)
278{
279 struct zswap_pool *pool;
280 u64 total = 0;
b8cf32dc 281 int i;
f1c54846
DS
282
283 rcu_read_lock();
284
285 list_for_each_entry_rcu(pool, &zswap_pools, list)
b8cf32dc
YA
286 for (i = 0; i < ZSWAP_NR_ZPOOLS; i++)
287 total += zpool_get_total_size(pool->zpools[i]);
f1c54846
DS
288
289 rcu_read_unlock();
290
291 zswap_pool_total_size = total;
292}
293
2b281117
SJ
294/*********************************
295* zswap entry functions
296**********************************/
297static struct kmem_cache *zswap_entry_cache;
298
2b281117
SJ
299static struct zswap_entry *zswap_entry_cache_alloc(gfp_t gfp)
300{
301 struct zswap_entry *entry;
302 entry = kmem_cache_alloc(zswap_entry_cache, gfp);
303 if (!entry)
304 return NULL;
305 entry->refcount = 1;
0ab0abcf 306 RB_CLEAR_NODE(&entry->rbnode);
2b281117
SJ
307 return entry;
308}
309
310static void zswap_entry_cache_free(struct zswap_entry *entry)
311{
312 kmem_cache_free(zswap_entry_cache, entry);
313}
314
2b281117
SJ
315/*********************************
316* rbtree functions
317**********************************/
318static struct zswap_entry *zswap_rb_search(struct rb_root *root, pgoff_t offset)
319{
320 struct rb_node *node = root->rb_node;
321 struct zswap_entry *entry;
0bb48849 322 pgoff_t entry_offset;
2b281117
SJ
323
324 while (node) {
325 entry = rb_entry(node, struct zswap_entry, rbnode);
0bb48849
DC
326 entry_offset = swp_offset(entry->swpentry);
327 if (entry_offset > offset)
2b281117 328 node = node->rb_left;
0bb48849 329 else if (entry_offset < offset)
2b281117
SJ
330 node = node->rb_right;
331 else
332 return entry;
333 }
334 return NULL;
335}
336
337/*
338 * In the case that a entry with the same offset is found, a pointer to
339 * the existing entry is stored in dupentry and the function returns -EEXIST
340 */
341static int zswap_rb_insert(struct rb_root *root, struct zswap_entry *entry,
342 struct zswap_entry **dupentry)
343{
344 struct rb_node **link = &root->rb_node, *parent = NULL;
345 struct zswap_entry *myentry;
0bb48849 346 pgoff_t myentry_offset, entry_offset = swp_offset(entry->swpentry);
2b281117
SJ
347
348 while (*link) {
349 parent = *link;
350 myentry = rb_entry(parent, struct zswap_entry, rbnode);
0bb48849
DC
351 myentry_offset = swp_offset(myentry->swpentry);
352 if (myentry_offset > entry_offset)
2b281117 353 link = &(*link)->rb_left;
0bb48849 354 else if (myentry_offset < entry_offset)
2b281117
SJ
355 link = &(*link)->rb_right;
356 else {
357 *dupentry = myentry;
358 return -EEXIST;
359 }
360 }
361 rb_link_node(&entry->rbnode, parent, link);
362 rb_insert_color(&entry->rbnode, root);
363 return 0;
364}
365
18a93707 366static bool zswap_rb_erase(struct rb_root *root, struct zswap_entry *entry)
0ab0abcf
WY
367{
368 if (!RB_EMPTY_NODE(&entry->rbnode)) {
369 rb_erase(&entry->rbnode, root);
370 RB_CLEAR_NODE(&entry->rbnode);
18a93707 371 return true;
0ab0abcf 372 }
18a93707 373 return false;
0ab0abcf
WY
374}
375
b8cf32dc
YA
376static struct zpool *zswap_find_zpool(struct zswap_entry *entry)
377{
378 int i = 0;
379
380 if (ZSWAP_NR_ZPOOLS > 1)
381 i = hash_ptr(entry, ilog2(ZSWAP_NR_ZPOOLS));
382
383 return entry->pool->zpools[i];
384}
385
0ab0abcf 386/*
12d79d64 387 * Carries out the common pattern of freeing and entry's zpool allocation,
0ab0abcf
WY
388 * freeing the entry itself, and decrementing the number of stored pages.
389 */
60105e12 390static void zswap_free_entry(struct zswap_entry *entry)
0ab0abcf 391{
f4840ccf
JW
392 if (entry->objcg) {
393 obj_cgroup_uncharge_zswap(entry->objcg, entry->length);
394 obj_cgroup_put(entry->objcg);
395 }
a85f878b
SD
396 if (!entry->length)
397 atomic_dec(&zswap_same_filled_pages);
398 else {
35499e2b
DC
399 spin_lock(&entry->pool->lru_lock);
400 list_del(&entry->lru);
401 spin_unlock(&entry->pool->lru_lock);
b8cf32dc 402 zpool_free(zswap_find_zpool(entry), entry->handle);
a85f878b
SD
403 zswap_pool_put(entry->pool);
404 }
0ab0abcf
WY
405 zswap_entry_cache_free(entry);
406 atomic_dec(&zswap_stored_pages);
f1c54846 407 zswap_update_total_size();
0ab0abcf
WY
408}
409
410/* caller must hold the tree lock */
411static void zswap_entry_get(struct zswap_entry *entry)
412{
413 entry->refcount++;
414}
415
416/* caller must hold the tree lock
417* remove from the tree and free it, if nobody reference the entry
418*/
419static void zswap_entry_put(struct zswap_tree *tree,
420 struct zswap_entry *entry)
421{
422 int refcount = --entry->refcount;
423
73108957 424 WARN_ON_ONCE(refcount < 0);
0ab0abcf 425 if (refcount == 0) {
73108957 426 WARN_ON_ONCE(!RB_EMPTY_NODE(&entry->rbnode));
60105e12 427 zswap_free_entry(entry);
0ab0abcf
WY
428 }
429}
430
431/* caller must hold the tree lock */
432static struct zswap_entry *zswap_entry_find_get(struct rb_root *root,
433 pgoff_t offset)
434{
b0c9865f 435 struct zswap_entry *entry;
0ab0abcf
WY
436
437 entry = zswap_rb_search(root, offset);
438 if (entry)
439 zswap_entry_get(entry);
440
441 return entry;
442}
443
2b281117
SJ
444/*********************************
445* per-cpu code
446**********************************/
447static DEFINE_PER_CPU(u8 *, zswap_dstmem);
1ec3b5fe
BS
448/*
449 * If users dynamically change the zpool type and compressor at runtime, i.e.
450 * zswap is running, zswap can have more than one zpool on one cpu, but they
451 * are sharing dtsmem. So we need this mutex to be per-cpu.
452 */
453static DEFINE_PER_CPU(struct mutex *, zswap_mutex);
2b281117 454
ad7ed770 455static int zswap_dstmem_prepare(unsigned int cpu)
2b281117 456{
1ec3b5fe 457 struct mutex *mutex;
2b281117
SJ
458 u8 *dst;
459
ad7ed770 460 dst = kmalloc_node(PAGE_SIZE * 2, GFP_KERNEL, cpu_to_node(cpu));
2b2695f5 461 if (!dst)
ad7ed770 462 return -ENOMEM;
2b2695f5 463
1ec3b5fe
BS
464 mutex = kmalloc_node(sizeof(*mutex), GFP_KERNEL, cpu_to_node(cpu));
465 if (!mutex) {
466 kfree(dst);
467 return -ENOMEM;
468 }
469
470 mutex_init(mutex);
ad7ed770 471 per_cpu(zswap_dstmem, cpu) = dst;
1ec3b5fe 472 per_cpu(zswap_mutex, cpu) = mutex;
ad7ed770 473 return 0;
2b281117
SJ
474}
475
ad7ed770 476static int zswap_dstmem_dead(unsigned int cpu)
2b281117 477{
1ec3b5fe 478 struct mutex *mutex;
ad7ed770 479 u8 *dst;
2b281117 480
1ec3b5fe
BS
481 mutex = per_cpu(zswap_mutex, cpu);
482 kfree(mutex);
483 per_cpu(zswap_mutex, cpu) = NULL;
484
ad7ed770
SAS
485 dst = per_cpu(zswap_dstmem, cpu);
486 kfree(dst);
487 per_cpu(zswap_dstmem, cpu) = NULL;
f1c54846 488
f1c54846 489 return 0;
f1c54846
DS
490}
491
cab7a7e5 492static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node)
f1c54846 493{
cab7a7e5 494 struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
1ec3b5fe
BS
495 struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
496 struct crypto_acomp *acomp;
497 struct acomp_req *req;
498
499 acomp = crypto_alloc_acomp_node(pool->tfm_name, 0, 0, cpu_to_node(cpu));
500 if (IS_ERR(acomp)) {
501 pr_err("could not alloc crypto acomp %s : %ld\n",
502 pool->tfm_name, PTR_ERR(acomp));
503 return PTR_ERR(acomp);
504 }
505 acomp_ctx->acomp = acomp;
f1c54846 506
1ec3b5fe
BS
507 req = acomp_request_alloc(acomp_ctx->acomp);
508 if (!req) {
509 pr_err("could not alloc crypto acomp_request %s\n",
510 pool->tfm_name);
511 crypto_free_acomp(acomp_ctx->acomp);
cab7a7e5
SAS
512 return -ENOMEM;
513 }
1ec3b5fe
BS
514 acomp_ctx->req = req;
515
516 crypto_init_wait(&acomp_ctx->wait);
517 /*
518 * if the backend of acomp is async zip, crypto_req_done() will wakeup
519 * crypto_wait_req(); if the backend of acomp is scomp, the callback
520 * won't be called, crypto_wait_req() will return without blocking.
521 */
522 acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
523 crypto_req_done, &acomp_ctx->wait);
524
525 acomp_ctx->mutex = per_cpu(zswap_mutex, cpu);
526 acomp_ctx->dstmem = per_cpu(zswap_dstmem, cpu);
527
2b281117 528 return 0;
2b281117
SJ
529}
530
cab7a7e5 531static int zswap_cpu_comp_dead(unsigned int cpu, struct hlist_node *node)
f1c54846 532{
cab7a7e5 533 struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
1ec3b5fe
BS
534 struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
535
536 if (!IS_ERR_OR_NULL(acomp_ctx)) {
537 if (!IS_ERR_OR_NULL(acomp_ctx->req))
538 acomp_request_free(acomp_ctx->req);
539 if (!IS_ERR_OR_NULL(acomp_ctx->acomp))
540 crypto_free_acomp(acomp_ctx->acomp);
541 }
f1c54846 542
cab7a7e5 543 return 0;
f1c54846
DS
544}
545
2b281117 546/*********************************
f1c54846 547* pool functions
2b281117 548**********************************/
f1c54846
DS
549
550static struct zswap_pool *__zswap_pool_current(void)
2b281117 551{
f1c54846
DS
552 struct zswap_pool *pool;
553
554 pool = list_first_or_null_rcu(&zswap_pools, typeof(*pool), list);
ae3d89a7
DS
555 WARN_ONCE(!pool && zswap_has_pool,
556 "%s: no page storage pool!\n", __func__);
f1c54846
DS
557
558 return pool;
559}
560
561static struct zswap_pool *zswap_pool_current(void)
562{
563 assert_spin_locked(&zswap_pools_lock);
564
565 return __zswap_pool_current();
566}
567
568static struct zswap_pool *zswap_pool_current_get(void)
569{
570 struct zswap_pool *pool;
571
572 rcu_read_lock();
573
574 pool = __zswap_pool_current();
ae3d89a7 575 if (!zswap_pool_get(pool))
f1c54846
DS
576 pool = NULL;
577
578 rcu_read_unlock();
579
580 return pool;
581}
582
583static struct zswap_pool *zswap_pool_last_get(void)
584{
585 struct zswap_pool *pool, *last = NULL;
586
587 rcu_read_lock();
588
589 list_for_each_entry_rcu(pool, &zswap_pools, list)
590 last = pool;
ae3d89a7
DS
591 WARN_ONCE(!last && zswap_has_pool,
592 "%s: no page storage pool!\n", __func__);
593 if (!zswap_pool_get(last))
f1c54846
DS
594 last = NULL;
595
596 rcu_read_unlock();
597
598 return last;
599}
600
8bc8b228 601/* type and compressor must be null-terminated */
f1c54846
DS
602static struct zswap_pool *zswap_pool_find_get(char *type, char *compressor)
603{
604 struct zswap_pool *pool;
605
606 assert_spin_locked(&zswap_pools_lock);
607
608 list_for_each_entry_rcu(pool, &zswap_pools, list) {
8bc8b228 609 if (strcmp(pool->tfm_name, compressor))
f1c54846 610 continue;
b8cf32dc
YA
611 /* all zpools share the same type */
612 if (strcmp(zpool_get_type(pool->zpools[0]), type))
f1c54846
DS
613 continue;
614 /* if we can't get it, it's about to be destroyed */
615 if (!zswap_pool_get(pool))
616 continue;
617 return pool;
618 }
619
620 return NULL;
621}
622
18a93707
YA
623/*
624 * If the entry is still valid in the tree, drop the initial ref and remove it
625 * from the tree. This function must be called with an additional ref held,
626 * otherwise it may race with another invalidation freeing the entry.
627 */
418fd29d
DC
628static void zswap_invalidate_entry(struct zswap_tree *tree,
629 struct zswap_entry *entry)
630{
18a93707
YA
631 if (zswap_rb_erase(&tree->rbroot, entry))
632 zswap_entry_put(tree, entry);
418fd29d
DC
633}
634
f999f38b
DC
635static int zswap_reclaim_entry(struct zswap_pool *pool)
636{
f999f38b
DC
637 struct zswap_entry *entry;
638 struct zswap_tree *tree;
639 pgoff_t swpoffset;
640 int ret;
641
642 /* Get an entry off the LRU */
643 spin_lock(&pool->lru_lock);
644 if (list_empty(&pool->lru)) {
645 spin_unlock(&pool->lru_lock);
646 return -EINVAL;
647 }
648 entry = list_last_entry(&pool->lru, struct zswap_entry, lru);
649 list_del_init(&entry->lru);
f999f38b
DC
650 /*
651 * Once the lru lock is dropped, the entry might get freed. The
652 * swpoffset is copied to the stack, and entry isn't deref'd again
653 * until the entry is verified to still be alive in the tree.
654 */
0bb48849
DC
655 swpoffset = swp_offset(entry->swpentry);
656 tree = zswap_trees[swp_type(entry->swpentry)];
f999f38b
DC
657 spin_unlock(&pool->lru_lock);
658
659 /* Check for invalidate() race */
660 spin_lock(&tree->lock);
661 if (entry != zswap_rb_search(&tree->rbroot, swpoffset)) {
662 ret = -EAGAIN;
663 goto unlock;
664 }
665 /* Hold a reference to prevent a free during writeback */
666 zswap_entry_get(entry);
667 spin_unlock(&tree->lock);
668
0bb48849 669 ret = zswap_writeback_entry(entry, tree);
f999f38b
DC
670
671 spin_lock(&tree->lock);
672 if (ret) {
673 /* Writeback failed, put entry back on LRU */
674 spin_lock(&pool->lru_lock);
675 list_move(&entry->lru, &pool->lru);
676 spin_unlock(&pool->lru_lock);
ff9d5ba2 677 goto put_unlock;
f999f38b
DC
678 }
679
418fd29d
DC
680 /*
681 * Writeback started successfully, the page now belongs to the
682 * swapcache. Drop the entry from zswap - unless invalidate already
683 * took it out while we had the tree->lock released for IO.
684 */
18a93707 685 zswap_invalidate_entry(tree, entry);
ff9d5ba2
DC
686
687put_unlock:
f999f38b
DC
688 /* Drop local reference */
689 zswap_entry_put(tree, entry);
690unlock:
691 spin_unlock(&tree->lock);
692 return ret ? -EAGAIN : 0;
693}
694
45190f01
VW
695static void shrink_worker(struct work_struct *w)
696{
697 struct zswap_pool *pool = container_of(w, typeof(*pool),
698 shrink_work);
e0228d59
DC
699 int ret, failures = 0;
700
701 do {
35499e2b 702 ret = zswap_reclaim_entry(pool);
e0228d59
DC
703 if (ret) {
704 zswap_reject_reclaim_fail++;
705 if (ret != -EAGAIN)
706 break;
707 if (++failures == MAX_RECLAIM_RETRIES)
708 break;
709 }
710 cond_resched();
711 } while (!zswap_can_accept());
45190f01
VW
712 zswap_pool_put(pool);
713}
714
f1c54846
DS
715static struct zswap_pool *zswap_pool_create(char *type, char *compressor)
716{
b8cf32dc 717 int i;
f1c54846 718 struct zswap_pool *pool;
32a4e169 719 char name[38]; /* 'zswap' + 32 char (max) num + \0 */
d0164adc 720 gfp_t gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
cab7a7e5 721 int ret;
f1c54846 722
bae21db8
DS
723 if (!zswap_has_pool) {
724 /* if either are unset, pool initialization failed, and we
725 * need both params to be set correctly before trying to
726 * create a pool.
727 */
728 if (!strcmp(type, ZSWAP_PARAM_UNSET))
729 return NULL;
730 if (!strcmp(compressor, ZSWAP_PARAM_UNSET))
731 return NULL;
732 }
733
f1c54846 734 pool = kzalloc(sizeof(*pool), GFP_KERNEL);
f4ae0ce0 735 if (!pool)
f1c54846 736 return NULL;
f1c54846 737
b8cf32dc
YA
738 for (i = 0; i < ZSWAP_NR_ZPOOLS; i++) {
739 /* unique name for each pool specifically required by zsmalloc */
740 snprintf(name, 38, "zswap%x",
741 atomic_inc_return(&zswap_pools_count));
32a4e169 742
b8cf32dc
YA
743 pool->zpools[i] = zpool_create_pool(type, name, gfp);
744 if (!pool->zpools[i]) {
745 pr_err("%s zpool not available\n", type);
746 goto error;
747 }
f1c54846 748 }
b8cf32dc 749 pr_debug("using %s zpool\n", zpool_get_type(pool->zpools[0]));
f1c54846 750
79cd4202 751 strscpy(pool->tfm_name, compressor, sizeof(pool->tfm_name));
1ec3b5fe
BS
752
753 pool->acomp_ctx = alloc_percpu(*pool->acomp_ctx);
754 if (!pool->acomp_ctx) {
f1c54846
DS
755 pr_err("percpu alloc failed\n");
756 goto error;
757 }
758
cab7a7e5
SAS
759 ret = cpuhp_state_add_instance(CPUHP_MM_ZSWP_POOL_PREPARE,
760 &pool->node);
761 if (ret)
f1c54846
DS
762 goto error;
763 pr_debug("using %s compressor\n", pool->tfm_name);
764
765 /* being the current pool takes 1 ref; this func expects the
766 * caller to always add the new pool as the current pool
767 */
768 kref_init(&pool->kref);
769 INIT_LIST_HEAD(&pool->list);
f999f38b
DC
770 INIT_LIST_HEAD(&pool->lru);
771 spin_lock_init(&pool->lru_lock);
45190f01 772 INIT_WORK(&pool->shrink_work, shrink_worker);
f1c54846
DS
773
774 zswap_pool_debug("created", pool);
775
776 return pool;
777
778error:
1ec3b5fe
BS
779 if (pool->acomp_ctx)
780 free_percpu(pool->acomp_ctx);
b8cf32dc
YA
781 while (i--)
782 zpool_destroy_pool(pool->zpools[i]);
f1c54846
DS
783 kfree(pool);
784 return NULL;
785}
786
141fdeec 787static struct zswap_pool *__zswap_pool_create_fallback(void)
f1c54846 788{
bae21db8
DS
789 bool has_comp, has_zpool;
790
1ec3b5fe 791 has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
bb8b93b5
MS
792 if (!has_comp && strcmp(zswap_compressor,
793 CONFIG_ZSWAP_COMPRESSOR_DEFAULT)) {
f1c54846 794 pr_err("compressor %s not available, using default %s\n",
bb8b93b5 795 zswap_compressor, CONFIG_ZSWAP_COMPRESSOR_DEFAULT);
c99b42c3 796 param_free_charp(&zswap_compressor);
bb8b93b5 797 zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
1ec3b5fe 798 has_comp = crypto_has_acomp(zswap_compressor, 0, 0);
f1c54846 799 }
bae21db8
DS
800 if (!has_comp) {
801 pr_err("default compressor %s not available\n",
802 zswap_compressor);
803 param_free_charp(&zswap_compressor);
804 zswap_compressor = ZSWAP_PARAM_UNSET;
805 }
806
807 has_zpool = zpool_has_pool(zswap_zpool_type);
bb8b93b5
MS
808 if (!has_zpool && strcmp(zswap_zpool_type,
809 CONFIG_ZSWAP_ZPOOL_DEFAULT)) {
f1c54846 810 pr_err("zpool %s not available, using default %s\n",
bb8b93b5 811 zswap_zpool_type, CONFIG_ZSWAP_ZPOOL_DEFAULT);
c99b42c3 812 param_free_charp(&zswap_zpool_type);
bb8b93b5 813 zswap_zpool_type = CONFIG_ZSWAP_ZPOOL_DEFAULT;
bae21db8 814 has_zpool = zpool_has_pool(zswap_zpool_type);
f1c54846 815 }
bae21db8
DS
816 if (!has_zpool) {
817 pr_err("default zpool %s not available\n",
818 zswap_zpool_type);
819 param_free_charp(&zswap_zpool_type);
820 zswap_zpool_type = ZSWAP_PARAM_UNSET;
821 }
822
823 if (!has_comp || !has_zpool)
824 return NULL;
f1c54846
DS
825
826 return zswap_pool_create(zswap_zpool_type, zswap_compressor);
827}
828
829static void zswap_pool_destroy(struct zswap_pool *pool)
830{
b8cf32dc
YA
831 int i;
832
f1c54846
DS
833 zswap_pool_debug("destroying", pool);
834
cab7a7e5 835 cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
1ec3b5fe 836 free_percpu(pool->acomp_ctx);
b8cf32dc
YA
837 for (i = 0; i < ZSWAP_NR_ZPOOLS; i++)
838 zpool_destroy_pool(pool->zpools[i]);
f1c54846
DS
839 kfree(pool);
840}
841
842static int __must_check zswap_pool_get(struct zswap_pool *pool)
843{
ae3d89a7
DS
844 if (!pool)
845 return 0;
846
f1c54846
DS
847 return kref_get_unless_zero(&pool->kref);
848}
849
200867af 850static void __zswap_pool_release(struct work_struct *work)
f1c54846 851{
45190f01
VW
852 struct zswap_pool *pool = container_of(work, typeof(*pool),
853 release_work);
200867af
DS
854
855 synchronize_rcu();
f1c54846
DS
856
857 /* nobody should have been able to get a kref... */
858 WARN_ON(kref_get_unless_zero(&pool->kref));
859
860 /* pool is now off zswap_pools list and has no references. */
861 zswap_pool_destroy(pool);
862}
863
864static void __zswap_pool_empty(struct kref *kref)
865{
866 struct zswap_pool *pool;
867
868 pool = container_of(kref, typeof(*pool), kref);
869
870 spin_lock(&zswap_pools_lock);
871
872 WARN_ON(pool == zswap_pool_current());
873
874 list_del_rcu(&pool->list);
200867af 875
45190f01
VW
876 INIT_WORK(&pool->release_work, __zswap_pool_release);
877 schedule_work(&pool->release_work);
f1c54846
DS
878
879 spin_unlock(&zswap_pools_lock);
880}
881
882static void zswap_pool_put(struct zswap_pool *pool)
883{
884 kref_put(&pool->kref, __zswap_pool_empty);
2b281117
SJ
885}
886
90b0fc26
DS
887/*********************************
888* param callbacks
889**********************************/
890
141fdeec
LS
891static bool zswap_pool_changed(const char *s, const struct kernel_param *kp)
892{
893 /* no change required */
894 if (!strcmp(s, *(char **)kp->arg) && zswap_has_pool)
895 return false;
896 return true;
897}
898
c99b42c3 899/* val must be a null-terminated string */
90b0fc26
DS
900static int __zswap_param_set(const char *val, const struct kernel_param *kp,
901 char *type, char *compressor)
902{
903 struct zswap_pool *pool, *put_pool = NULL;
c99b42c3 904 char *s = strstrip((char *)val);
141fdeec
LS
905 int ret = 0;
906 bool new_pool = false;
90b0fc26 907
141fdeec 908 mutex_lock(&zswap_init_lock);
9021ccec
LS
909 switch (zswap_init_state) {
910 case ZSWAP_UNINIT:
911 /* if this is load-time (pre-init) param setting,
912 * don't create a pool; that's done during init.
913 */
141fdeec
LS
914 ret = param_set_charp(s, kp);
915 break;
9021ccec 916 case ZSWAP_INIT_SUCCEED:
141fdeec 917 new_pool = zswap_pool_changed(s, kp);
9021ccec
LS
918 break;
919 case ZSWAP_INIT_FAILED:
d7b028f5 920 pr_err("can't set param, initialization failed\n");
141fdeec 921 ret = -ENODEV;
d7b028f5 922 }
141fdeec 923 mutex_unlock(&zswap_init_lock);
d7b028f5 924
141fdeec
LS
925 /* no need to create a new pool, return directly */
926 if (!new_pool)
927 return ret;
90b0fc26
DS
928
929 if (!type) {
c99b42c3
DS
930 if (!zpool_has_pool(s)) {
931 pr_err("zpool %s not available\n", s);
90b0fc26
DS
932 return -ENOENT;
933 }
c99b42c3 934 type = s;
90b0fc26 935 } else if (!compressor) {
1ec3b5fe 936 if (!crypto_has_acomp(s, 0, 0)) {
c99b42c3 937 pr_err("compressor %s not available\n", s);
90b0fc26
DS
938 return -ENOENT;
939 }
c99b42c3
DS
940 compressor = s;
941 } else {
942 WARN_ON(1);
943 return -EINVAL;
90b0fc26
DS
944 }
945
946 spin_lock(&zswap_pools_lock);
947
948 pool = zswap_pool_find_get(type, compressor);
949 if (pool) {
950 zswap_pool_debug("using existing", pool);
fd5bb66c 951 WARN_ON(pool == zswap_pool_current());
90b0fc26 952 list_del_rcu(&pool->list);
90b0fc26
DS
953 }
954
fd5bb66c
DS
955 spin_unlock(&zswap_pools_lock);
956
957 if (!pool)
958 pool = zswap_pool_create(type, compressor);
959
90b0fc26 960 if (pool)
c99b42c3 961 ret = param_set_charp(s, kp);
90b0fc26
DS
962 else
963 ret = -EINVAL;
964
fd5bb66c
DS
965 spin_lock(&zswap_pools_lock);
966
90b0fc26
DS
967 if (!ret) {
968 put_pool = zswap_pool_current();
969 list_add_rcu(&pool->list, &zswap_pools);
ae3d89a7 970 zswap_has_pool = true;
90b0fc26
DS
971 } else if (pool) {
972 /* add the possibly pre-existing pool to the end of the pools
973 * list; if it's new (and empty) then it'll be removed and
974 * destroyed by the put after we drop the lock
975 */
976 list_add_tail_rcu(&pool->list, &zswap_pools);
977 put_pool = pool;
fd5bb66c
DS
978 }
979
980 spin_unlock(&zswap_pools_lock);
981
982 if (!zswap_has_pool && !pool) {
ae3d89a7
DS
983 /* if initial pool creation failed, and this pool creation also
984 * failed, maybe both compressor and zpool params were bad.
985 * Allow changing this param, so pool creation will succeed
986 * when the other param is changed. We already verified this
1ec3b5fe 987 * param is ok in the zpool_has_pool() or crypto_has_acomp()
ae3d89a7
DS
988 * checks above.
989 */
990 ret = param_set_charp(s, kp);
90b0fc26
DS
991 }
992
90b0fc26
DS
993 /* drop the ref from either the old current pool,
994 * or the new pool we failed to add
995 */
996 if (put_pool)
997 zswap_pool_put(put_pool);
998
999 return ret;
1000}
1001
1002static int zswap_compressor_param_set(const char *val,
1003 const struct kernel_param *kp)
1004{
1005 return __zswap_param_set(val, kp, zswap_zpool_type, NULL);
1006}
1007
1008static int zswap_zpool_param_set(const char *val,
1009 const struct kernel_param *kp)
1010{
1011 return __zswap_param_set(val, kp, NULL, zswap_compressor);
1012}
1013
d7b028f5
DS
1014static int zswap_enabled_param_set(const char *val,
1015 const struct kernel_param *kp)
1016{
141fdeec
LS
1017 int ret = -ENODEV;
1018
1019 /* if this is load-time (pre-init) param setting, only set param. */
1020 if (system_state != SYSTEM_RUNNING)
1021 return param_set_bool(val, kp);
1022
1023 mutex_lock(&zswap_init_lock);
9021ccec
LS
1024 switch (zswap_init_state) {
1025 case ZSWAP_UNINIT:
141fdeec
LS
1026 if (zswap_setup())
1027 break;
1028 fallthrough;
9021ccec 1029 case ZSWAP_INIT_SUCCEED:
141fdeec 1030 if (!zswap_has_pool)
9021ccec 1031 pr_err("can't enable, no pool configured\n");
141fdeec
LS
1032 else
1033 ret = param_set_bool(val, kp);
1034 break;
9021ccec 1035 case ZSWAP_INIT_FAILED:
d7b028f5 1036 pr_err("can't enable, initialization failed\n");
ae3d89a7 1037 }
141fdeec 1038 mutex_unlock(&zswap_init_lock);
d7b028f5 1039
141fdeec 1040 return ret;
d7b028f5
DS
1041}
1042
2b281117
SJ
1043/*********************************
1044* writeback code
1045**********************************/
2b281117
SJ
1046/*
1047 * Attempts to free an entry by adding a page to the swap cache,
1048 * decompressing the entry data into the page, and issuing a
1049 * bio write to write the page back to the swap device.
1050 *
1051 * This can be thought of as a "resumed writeback" of the page
1052 * to the swap device. We are basically resuming the same swap
42c06a0e 1053 * writeback path that was intercepted with the zswap_store()
2b281117
SJ
1054 * in the first place. After the page has been decompressed into
1055 * the swap cache, the compressed version stored by zswap can be
1056 * freed.
1057 */
0bb48849 1058static int zswap_writeback_entry(struct zswap_entry *entry,
ff9d5ba2 1059 struct zswap_tree *tree)
2b281117 1060{
0bb48849 1061 swp_entry_t swpentry = entry->swpentry;
2b281117 1062 struct page *page;
ddc1a5cb 1063 struct mempolicy *mpol;
1ec3b5fe
BS
1064 struct scatterlist input, output;
1065 struct crypto_acomp_ctx *acomp_ctx;
b8cf32dc 1066 struct zpool *pool = zswap_find_zpool(entry);
98804a94 1067 bool page_was_allocated;
fc6697a8 1068 u8 *src, *tmp = NULL;
2b281117 1069 unsigned int dlen;
0ab0abcf 1070 int ret;
2b281117
SJ
1071 struct writeback_control wbc = {
1072 .sync_mode = WB_SYNC_NONE,
1073 };
1074
fc6697a8 1075 if (!zpool_can_sleep_mapped(pool)) {
8d9b6370 1076 tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
fc6697a8
TT
1077 if (!tmp)
1078 return -ENOMEM;
1079 }
1080
2b281117 1081 /* try to allocate swap cache page */
ddc1a5cb
HD
1082 mpol = get_task_policy(current);
1083 page = __read_swap_cache_async(swpentry, GFP_KERNEL, mpol,
1084 NO_INTERLEAVE_INDEX, &page_was_allocated);
98804a94 1085 if (!page) {
2b281117
SJ
1086 ret = -ENOMEM;
1087 goto fail;
98804a94 1088 }
2b281117 1089
98804a94
JW
1090 /* Found an existing page, we raced with load/swapin */
1091 if (!page_was_allocated) {
09cbfeaf 1092 put_page(page);
2b281117
SJ
1093 ret = -EEXIST;
1094 goto fail;
98804a94 1095 }
2b281117 1096
98804a94
JW
1097 /*
1098 * Page is locked, and the swapcache is now secured against
1099 * concurrent swapping to and from the slot. Verify that the
1100 * swap entry hasn't been invalidated and recycled behind our
1101 * backs (our zswap_entry reference doesn't prevent that), to
1102 * avoid overwriting a new swap page with old compressed data.
1103 */
1104 spin_lock(&tree->lock);
1105 if (zswap_rb_search(&tree->rbroot, swp_offset(entry->swpentry)) != entry) {
04fc7816 1106 spin_unlock(&tree->lock);
98804a94
JW
1107 delete_from_swap_cache(page_folio(page));
1108 ret = -ENOMEM;
1109 goto fail;
1110 }
1111 spin_unlock(&tree->lock);
04fc7816 1112
98804a94
JW
1113 /* decompress */
1114 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1115 dlen = PAGE_SIZE;
fc6697a8 1116
98804a94
JW
1117 src = zpool_map_handle(pool, entry->handle, ZPOOL_MM_RO);
1118 if (!zpool_can_sleep_mapped(pool)) {
1119 memcpy(tmp, src, entry->length);
1120 src = tmp;
1121 zpool_unmap_handle(pool, entry->handle);
1122 }
6b3379e8 1123
98804a94
JW
1124 mutex_lock(acomp_ctx->mutex);
1125 sg_init_one(&input, src, entry->length);
1126 sg_init_table(&output, 1);
1127 sg_set_page(&output, page, PAGE_SIZE, 0);
1128 acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, dlen);
1129 ret = crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait);
1130 dlen = acomp_ctx->req->dlen;
1131 mutex_unlock(acomp_ctx->mutex);
6b3379e8 1132
98804a94
JW
1133 if (!zpool_can_sleep_mapped(pool))
1134 kfree(tmp);
1135 else
1136 zpool_unmap_handle(pool, entry->handle);
2b281117 1137
98804a94
JW
1138 BUG_ON(ret);
1139 BUG_ON(dlen != PAGE_SIZE);
1140
1141 /* page is up to date */
1142 SetPageUptodate(page);
2b281117 1143
b349acc7
WY
1144 /* move it to the tail of the inactive list after end_writeback */
1145 SetPageReclaim(page);
1146
2b281117 1147 /* start writeback */
cf1e3fe4 1148 __swap_writepage(page, &wbc);
09cbfeaf 1149 put_page(page);
2b281117
SJ
1150 zswap_written_back_pages++;
1151
6b3379e8 1152 return ret;
98804a94 1153
6b3379e8
JW
1154fail:
1155 if (!zpool_can_sleep_mapped(pool))
1156 kfree(tmp);
0ab0abcf
WY
1157
1158 /*
98804a94
JW
1159 * If we get here because the page is already in swapcache, a
1160 * load may be happening concurrently. It is safe and okay to
1161 * not free the entry. It is also okay to return !0.
1162 */
2b281117
SJ
1163 return ret;
1164}
1165
a85f878b
SD
1166static int zswap_is_page_same_filled(void *ptr, unsigned long *value)
1167{
a85f878b 1168 unsigned long *page;
62bf1258
TS
1169 unsigned long val;
1170 unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
a85f878b
SD
1171
1172 page = (unsigned long *)ptr;
62bf1258
TS
1173 val = page[0];
1174
1175 if (val != page[last_pos])
1176 return 0;
1177
1178 for (pos = 1; pos < last_pos; pos++) {
1179 if (val != page[pos])
a85f878b
SD
1180 return 0;
1181 }
62bf1258
TS
1182
1183 *value = val;
1184
a85f878b
SD
1185 return 1;
1186}
1187
1188static void zswap_fill_page(void *ptr, unsigned long value)
1189{
1190 unsigned long *page;
1191
1192 page = (unsigned long *)ptr;
1193 memset_l(page, value, PAGE_SIZE / sizeof(unsigned long));
1194}
1195
34f4c198 1196bool zswap_store(struct folio *folio)
2b281117 1197{
3d2c9087 1198 swp_entry_t swp = folio->swap;
42c06a0e
JW
1199 int type = swp_type(swp);
1200 pgoff_t offset = swp_offset(swp);
34f4c198 1201 struct page *page = &folio->page;
2b281117
SJ
1202 struct zswap_tree *tree = zswap_trees[type];
1203 struct zswap_entry *entry, *dupentry;
1ec3b5fe
BS
1204 struct scatterlist input, output;
1205 struct crypto_acomp_ctx *acomp_ctx;
f4840ccf
JW
1206 struct obj_cgroup *objcg = NULL;
1207 struct zswap_pool *pool;
b8cf32dc 1208 struct zpool *zpool;
0bb48849 1209 unsigned int dlen = PAGE_SIZE;
a85f878b 1210 unsigned long handle, value;
2b281117
SJ
1211 char *buf;
1212 u8 *src, *dst;
d2fcd82b 1213 gfp_t gfp;
42c06a0e
JW
1214 int ret;
1215
34f4c198
MWO
1216 VM_WARN_ON_ONCE(!folio_test_locked(folio));
1217 VM_WARN_ON_ONCE(!folio_test_swapcache(folio));
2b281117 1218
34f4c198
MWO
1219 /* Large folios aren't supported */
1220 if (folio_test_large(folio))
42c06a0e 1221 return false;
7ba71669 1222
42c06a0e
JW
1223 if (!zswap_enabled || !tree)
1224 return false;
2b281117 1225
ca56489c
DC
1226 /*
1227 * If this is a duplicate, it must be removed before attempting to store
1228 * it, otherwise, if the store fails the old page won't be removed from
1229 * the tree, and it might be written back overriding the new data.
1230 */
1231 spin_lock(&tree->lock);
1232 dupentry = zswap_rb_search(&tree->rbroot, offset);
1233 if (dupentry) {
1234 zswap_duplicate_entry++;
1235 zswap_invalidate_entry(tree, dupentry);
1236 }
1237 spin_unlock(&tree->lock);
1238
0bdf0efa
NP
1239 /*
1240 * XXX: zswap reclaim does not work with cgroups yet. Without a
1241 * cgroup-aware entry LRU, we will push out entries system-wide based on
1242 * local cgroup limits.
1243 */
074e3e26 1244 objcg = get_obj_cgroup_from_folio(folio);
42c06a0e 1245 if (objcg && !obj_cgroup_may_zswap(objcg))
0bdf0efa 1246 goto reject;
f4840ccf 1247
2b281117
SJ
1248 /* reclaim space if needed */
1249 if (zswap_is_full()) {
1250 zswap_pool_limit_hit++;
45190f01 1251 zswap_pool_reached_full = true;
f4840ccf 1252 goto shrink;
45190f01 1253 }
16e536ef 1254
45190f01 1255 if (zswap_pool_reached_full) {
42c06a0e 1256 if (!zswap_can_accept())
e0228d59 1257 goto shrink;
42c06a0e 1258 else
45190f01 1259 zswap_pool_reached_full = false;
2b281117
SJ
1260 }
1261
1262 /* allocate entry */
1263 entry = zswap_entry_cache_alloc(GFP_KERNEL);
1264 if (!entry) {
1265 zswap_reject_kmemcache_fail++;
2b281117
SJ
1266 goto reject;
1267 }
1268
a85f878b
SD
1269 if (zswap_same_filled_pages_enabled) {
1270 src = kmap_atomic(page);
1271 if (zswap_is_page_same_filled(src, &value)) {
1272 kunmap_atomic(src);
0bb48849 1273 entry->swpentry = swp_entry(type, offset);
a85f878b
SD
1274 entry->length = 0;
1275 entry->value = value;
1276 atomic_inc(&zswap_same_filled_pages);
1277 goto insert_entry;
1278 }
1279 kunmap_atomic(src);
1280 }
1281
42c06a0e 1282 if (!zswap_non_same_filled_pages_enabled)
cb325ddd 1283 goto freepage;
cb325ddd 1284
f1c54846
DS
1285 /* if entry is successfully added, it keeps the reference */
1286 entry->pool = zswap_pool_current_get();
42c06a0e 1287 if (!entry->pool)
f1c54846 1288 goto freepage;
f1c54846 1289
2b281117 1290 /* compress */
1ec3b5fe
BS
1291 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1292
1293 mutex_lock(acomp_ctx->mutex);
1294
1295 dst = acomp_ctx->dstmem;
1296 sg_init_table(&input, 1);
1297 sg_set_page(&input, page, PAGE_SIZE, 0);
1298
1299 /* zswap_dstmem is of size (PAGE_SIZE * 2). Reflect same in sg_list */
1300 sg_init_one(&output, dst, PAGE_SIZE * 2);
1301 acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen);
1302 /*
1303 * it maybe looks a little bit silly that we send an asynchronous request,
1304 * then wait for its completion synchronously. This makes the process look
1305 * synchronous in fact.
1306 * Theoretically, acomp supports users send multiple acomp requests in one
1307 * acomp instance, then get those requests done simultaneously. but in this
42c06a0e 1308 * case, zswap actually does store and load page by page, there is no
1ec3b5fe 1309 * existing method to send the second page before the first page is done
42c06a0e 1310 * in one thread doing zwap.
1ec3b5fe
BS
1311 * but in different threads running on different cpu, we have different
1312 * acomp instance, so multiple threads can do (de)compression in parallel.
1313 */
1314 ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait);
1315 dlen = acomp_ctx->req->dlen;
1316
cb61dad8
NP
1317 if (ret) {
1318 zswap_reject_compress_fail++;
f1c54846 1319 goto put_dstmem;
cb61dad8 1320 }
2b281117
SJ
1321
1322 /* store */
b8cf32dc 1323 zpool = zswap_find_zpool(entry);
d2fcd82b 1324 gfp = __GFP_NORETRY | __GFP_NOWARN | __GFP_KSWAPD_RECLAIM;
b8cf32dc 1325 if (zpool_malloc_support_movable(zpool))
d2fcd82b 1326 gfp |= __GFP_HIGHMEM | __GFP_MOVABLE;
b8cf32dc 1327 ret = zpool_malloc(zpool, dlen, gfp, &handle);
2b281117
SJ
1328 if (ret == -ENOSPC) {
1329 zswap_reject_compress_poor++;
f1c54846 1330 goto put_dstmem;
2b281117
SJ
1331 }
1332 if (ret) {
1333 zswap_reject_alloc_fail++;
f1c54846 1334 goto put_dstmem;
2b281117 1335 }
b8cf32dc 1336 buf = zpool_map_handle(zpool, handle, ZPOOL_MM_WO);
0bb48849 1337 memcpy(buf, dst, dlen);
b8cf32dc 1338 zpool_unmap_handle(zpool, handle);
1ec3b5fe 1339 mutex_unlock(acomp_ctx->mutex);
2b281117
SJ
1340
1341 /* populate entry */
0bb48849 1342 entry->swpentry = swp_entry(type, offset);
2b281117
SJ
1343 entry->handle = handle;
1344 entry->length = dlen;
1345
a85f878b 1346insert_entry:
f4840ccf
JW
1347 entry->objcg = objcg;
1348 if (objcg) {
1349 obj_cgroup_charge_zswap(objcg, entry->length);
1350 /* Account before objcg ref is moved to tree */
1351 count_objcg_event(objcg, ZSWPOUT);
1352 }
1353
2b281117
SJ
1354 /* map */
1355 spin_lock(&tree->lock);
ca56489c
DC
1356 /*
1357 * A duplicate entry should have been removed at the beginning of this
1358 * function. Since the swap entry should be pinned, if a duplicate is
1359 * found again here it means that something went wrong in the swap
1360 * cache.
1361 */
42c06a0e 1362 while (zswap_rb_insert(&tree->rbroot, entry, &dupentry) == -EEXIST) {
ca56489c 1363 WARN_ON(1);
42c06a0e 1364 zswap_duplicate_entry++;
56c67049 1365 zswap_invalidate_entry(tree, dupentry);
42c06a0e 1366 }
35499e2b 1367 if (entry->length) {
f999f38b
DC
1368 spin_lock(&entry->pool->lru_lock);
1369 list_add(&entry->lru, &entry->pool->lru);
1370 spin_unlock(&entry->pool->lru_lock);
1371 }
2b281117
SJ
1372 spin_unlock(&tree->lock);
1373
1374 /* update stats */
1375 atomic_inc(&zswap_stored_pages);
f1c54846 1376 zswap_update_total_size();
f6498b77 1377 count_vm_event(ZSWPOUT);
2b281117 1378
42c06a0e 1379 return true;
2b281117 1380
f1c54846 1381put_dstmem:
1ec3b5fe 1382 mutex_unlock(acomp_ctx->mutex);
f1c54846
DS
1383 zswap_pool_put(entry->pool);
1384freepage:
2b281117
SJ
1385 zswap_entry_cache_free(entry);
1386reject:
f4840ccf
JW
1387 if (objcg)
1388 obj_cgroup_put(objcg);
42c06a0e 1389 return false;
f4840ccf
JW
1390
1391shrink:
1392 pool = zswap_pool_last_get();
969d63e1
JW
1393 if (pool && !queue_work(shrink_wq, &pool->shrink_work))
1394 zswap_pool_put(pool);
f4840ccf 1395 goto reject;
2b281117
SJ
1396}
1397
ca54f6d8 1398bool zswap_load(struct folio *folio)
2b281117 1399{
3d2c9087 1400 swp_entry_t swp = folio->swap;
42c06a0e
JW
1401 int type = swp_type(swp);
1402 pgoff_t offset = swp_offset(swp);
ca54f6d8 1403 struct page *page = &folio->page;
2b281117
SJ
1404 struct zswap_tree *tree = zswap_trees[type];
1405 struct zswap_entry *entry;
1ec3b5fe
BS
1406 struct scatterlist input, output;
1407 struct crypto_acomp_ctx *acomp_ctx;
fc6697a8 1408 u8 *src, *dst, *tmp;
b8cf32dc 1409 struct zpool *zpool;
2b281117 1410 unsigned int dlen;
42c06a0e
JW
1411 bool ret;
1412
ca54f6d8 1413 VM_WARN_ON_ONCE(!folio_test_locked(folio));
2b281117
SJ
1414
1415 /* find */
1416 spin_lock(&tree->lock);
0ab0abcf 1417 entry = zswap_entry_find_get(&tree->rbroot, offset);
2b281117 1418 if (!entry) {
2b281117 1419 spin_unlock(&tree->lock);
42c06a0e 1420 return false;
2b281117 1421 }
2b281117
SJ
1422 spin_unlock(&tree->lock);
1423
a85f878b
SD
1424 if (!entry->length) {
1425 dst = kmap_atomic(page);
1426 zswap_fill_page(dst, entry->value);
1427 kunmap_atomic(dst);
42c06a0e 1428 ret = true;
f6498b77 1429 goto stats;
a85f878b
SD
1430 }
1431
b8cf32dc
YA
1432 zpool = zswap_find_zpool(entry);
1433 if (!zpool_can_sleep_mapped(zpool)) {
8d9b6370 1434 tmp = kmalloc(entry->length, GFP_KERNEL);
fc6697a8 1435 if (!tmp) {
42c06a0e 1436 ret = false;
fc6697a8
TT
1437 goto freeentry;
1438 }
1439 }
1440
2b281117
SJ
1441 /* decompress */
1442 dlen = PAGE_SIZE;
b8cf32dc 1443 src = zpool_map_handle(zpool, entry->handle, ZPOOL_MM_RO);
1ec3b5fe 1444
b8cf32dc 1445 if (!zpool_can_sleep_mapped(zpool)) {
fc6697a8
TT
1446 memcpy(tmp, src, entry->length);
1447 src = tmp;
b8cf32dc 1448 zpool_unmap_handle(zpool, entry->handle);
fc6697a8
TT
1449 }
1450
1ec3b5fe
BS
1451 acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
1452 mutex_lock(acomp_ctx->mutex);
1453 sg_init_one(&input, src, entry->length);
1454 sg_init_table(&output, 1);
1455 sg_set_page(&output, page, PAGE_SIZE, 0);
1456 acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, dlen);
42c06a0e
JW
1457 if (crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait))
1458 WARN_ON(1);
1ec3b5fe
BS
1459 mutex_unlock(acomp_ctx->mutex);
1460
b8cf32dc
YA
1461 if (zpool_can_sleep_mapped(zpool))
1462 zpool_unmap_handle(zpool, entry->handle);
fc6697a8
TT
1463 else
1464 kfree(tmp);
1465
42c06a0e 1466 ret = true;
f6498b77
JW
1467stats:
1468 count_vm_event(ZSWPIN);
f4840ccf
JW
1469 if (entry->objcg)
1470 count_objcg_event(entry->objcg, ZSWPIN);
a85f878b 1471freeentry:
2b281117 1472 spin_lock(&tree->lock);
42c06a0e 1473 if (ret && zswap_exclusive_loads_enabled) {
b9c91c43 1474 zswap_invalidate_entry(tree, entry);
ca54f6d8 1475 folio_mark_dirty(folio);
35499e2b 1476 } else if (entry->length) {
f999f38b
DC
1477 spin_lock(&entry->pool->lru_lock);
1478 list_move(&entry->lru, &entry->pool->lru);
1479 spin_unlock(&entry->pool->lru_lock);
b9c91c43 1480 }
18a93707 1481 zswap_entry_put(tree, entry);
2b281117
SJ
1482 spin_unlock(&tree->lock);
1483
fc6697a8 1484 return ret;
2b281117
SJ
1485}
1486
42c06a0e 1487void zswap_invalidate(int type, pgoff_t offset)
2b281117
SJ
1488{
1489 struct zswap_tree *tree = zswap_trees[type];
1490 struct zswap_entry *entry;
2b281117
SJ
1491
1492 /* find */
1493 spin_lock(&tree->lock);
1494 entry = zswap_rb_search(&tree->rbroot, offset);
1495 if (!entry) {
1496 /* entry was written back */
1497 spin_unlock(&tree->lock);
1498 return;
1499 }
b9c91c43 1500 zswap_invalidate_entry(tree, entry);
2b281117 1501 spin_unlock(&tree->lock);
2b281117
SJ
1502}
1503
42c06a0e
JW
1504void zswap_swapon(int type)
1505{
1506 struct zswap_tree *tree;
1507
1508 tree = kzalloc(sizeof(*tree), GFP_KERNEL);
1509 if (!tree) {
1510 pr_err("alloc failed, zswap disabled for swap type %d\n", type);
1511 return;
1512 }
1513
1514 tree->rbroot = RB_ROOT;
1515 spin_lock_init(&tree->lock);
1516 zswap_trees[type] = tree;
1517}
1518
1519void zswap_swapoff(int type)
2b281117
SJ
1520{
1521 struct zswap_tree *tree = zswap_trees[type];
0bd42136 1522 struct zswap_entry *entry, *n;
2b281117
SJ
1523
1524 if (!tree)
1525 return;
1526
1527 /* walk the tree and free everything */
1528 spin_lock(&tree->lock);
0ab0abcf 1529 rbtree_postorder_for_each_entry_safe(entry, n, &tree->rbroot, rbnode)
60105e12 1530 zswap_free_entry(entry);
2b281117
SJ
1531 tree->rbroot = RB_ROOT;
1532 spin_unlock(&tree->lock);
aa9bca05
WY
1533 kfree(tree);
1534 zswap_trees[type] = NULL;
2b281117
SJ
1535}
1536
2b281117
SJ
1537/*********************************
1538* debugfs functions
1539**********************************/
1540#ifdef CONFIG_DEBUG_FS
1541#include <linux/debugfs.h>
1542
1543static struct dentry *zswap_debugfs_root;
1544
141fdeec 1545static int zswap_debugfs_init(void)
2b281117
SJ
1546{
1547 if (!debugfs_initialized())
1548 return -ENODEV;
1549
1550 zswap_debugfs_root = debugfs_create_dir("zswap", NULL);
2b281117 1551
0825a6f9
JP
1552 debugfs_create_u64("pool_limit_hit", 0444,
1553 zswap_debugfs_root, &zswap_pool_limit_hit);
1554 debugfs_create_u64("reject_reclaim_fail", 0444,
1555 zswap_debugfs_root, &zswap_reject_reclaim_fail);
1556 debugfs_create_u64("reject_alloc_fail", 0444,
1557 zswap_debugfs_root, &zswap_reject_alloc_fail);
1558 debugfs_create_u64("reject_kmemcache_fail", 0444,
1559 zswap_debugfs_root, &zswap_reject_kmemcache_fail);
cb61dad8
NP
1560 debugfs_create_u64("reject_compress_fail", 0444,
1561 zswap_debugfs_root, &zswap_reject_compress_fail);
0825a6f9
JP
1562 debugfs_create_u64("reject_compress_poor", 0444,
1563 zswap_debugfs_root, &zswap_reject_compress_poor);
1564 debugfs_create_u64("written_back_pages", 0444,
1565 zswap_debugfs_root, &zswap_written_back_pages);
1566 debugfs_create_u64("duplicate_entry", 0444,
1567 zswap_debugfs_root, &zswap_duplicate_entry);
1568 debugfs_create_u64("pool_total_size", 0444,
1569 zswap_debugfs_root, &zswap_pool_total_size);
1570 debugfs_create_atomic_t("stored_pages", 0444,
1571 zswap_debugfs_root, &zswap_stored_pages);
a85f878b 1572 debugfs_create_atomic_t("same_filled_pages", 0444,
0825a6f9 1573 zswap_debugfs_root, &zswap_same_filled_pages);
2b281117
SJ
1574
1575 return 0;
1576}
2b281117 1577#else
141fdeec 1578static int zswap_debugfs_init(void)
2b281117
SJ
1579{
1580 return 0;
1581}
2b281117
SJ
1582#endif
1583
1584/*********************************
1585* module init and exit
1586**********************************/
141fdeec 1587static int zswap_setup(void)
2b281117 1588{
f1c54846 1589 struct zswap_pool *pool;
ad7ed770 1590 int ret;
60105e12 1591
b7919122
LS
1592 zswap_entry_cache = KMEM_CACHE(zswap_entry, 0);
1593 if (!zswap_entry_cache) {
2b281117 1594 pr_err("entry cache creation failed\n");
f1c54846 1595 goto cache_fail;
2b281117 1596 }
f1c54846 1597
ad7ed770
SAS
1598 ret = cpuhp_setup_state(CPUHP_MM_ZSWP_MEM_PREPARE, "mm/zswap:prepare",
1599 zswap_dstmem_prepare, zswap_dstmem_dead);
1600 if (ret) {
f1c54846
DS
1601 pr_err("dstmem alloc failed\n");
1602 goto dstmem_fail;
2b281117 1603 }
f1c54846 1604
cab7a7e5
SAS
1605 ret = cpuhp_setup_state_multi(CPUHP_MM_ZSWP_POOL_PREPARE,
1606 "mm/zswap_pool:prepare",
1607 zswap_cpu_comp_prepare,
1608 zswap_cpu_comp_dead);
1609 if (ret)
1610 goto hp_fail;
1611
f1c54846 1612 pool = __zswap_pool_create_fallback();
ae3d89a7
DS
1613 if (pool) {
1614 pr_info("loaded using pool %s/%s\n", pool->tfm_name,
b8cf32dc 1615 zpool_get_type(pool->zpools[0]));
ae3d89a7
DS
1616 list_add(&pool->list, &zswap_pools);
1617 zswap_has_pool = true;
1618 } else {
f1c54846 1619 pr_err("pool creation failed\n");
ae3d89a7 1620 zswap_enabled = false;
2b281117 1621 }
60105e12 1622
45190f01
VW
1623 shrink_wq = create_workqueue("zswap-shrink");
1624 if (!shrink_wq)
1625 goto fallback_fail;
1626
2b281117
SJ
1627 if (zswap_debugfs_init())
1628 pr_warn("debugfs initialization failed\n");
9021ccec 1629 zswap_init_state = ZSWAP_INIT_SUCCEED;
2b281117 1630 return 0;
f1c54846 1631
45190f01 1632fallback_fail:
38aeb071
DC
1633 if (pool)
1634 zswap_pool_destroy(pool);
cab7a7e5 1635hp_fail:
ad7ed770 1636 cpuhp_remove_state(CPUHP_MM_ZSWP_MEM_PREPARE);
f1c54846 1637dstmem_fail:
b7919122 1638 kmem_cache_destroy(zswap_entry_cache);
f1c54846 1639cache_fail:
d7b028f5 1640 /* if built-in, we aren't unloaded on failure; don't allow use */
9021ccec 1641 zswap_init_state = ZSWAP_INIT_FAILED;
d7b028f5 1642 zswap_enabled = false;
2b281117
SJ
1643 return -ENOMEM;
1644}
141fdeec
LS
1645
1646static int __init zswap_init(void)
1647{
1648 if (!zswap_enabled)
1649 return 0;
1650 return zswap_setup();
1651}
2b281117 1652/* must be late so crypto has time to come up */
141fdeec 1653late_initcall(zswap_init);
2b281117 1654
68386da8 1655MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
2b281117 1656MODULE_DESCRIPTION("Compressed cache for swap pages");