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