xref: /linux/mm/zswap.c (revision da939ef4c494246bc2102ecb628bbcc71d650410)
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/swap.h>
24 #include <linux/crypto.h>
25 #include <linux/scatterlist.h>
26 #include <linux/mempolicy.h>
27 #include <linux/mempool.h>
28 #include <crypto/acompress.h>
29 #include <linux/zswap.h>
30 #include <linux/mm_types.h>
31 #include <linux/page-flags.h>
32 #include <linux/swapops.h>
33 #include <linux/writeback.h>
34 #include <linux/pagemap.h>
35 #include <linux/workqueue.h>
36 #include <linux/list_lru.h>
37 #include <linux/zsmalloc.h>
38 
39 #include "swap.h"
40 #include "internal.h"
41 
42 /*********************************
43 * statistics
44 **********************************/
45 /* The number of pages currently stored in zswap */
46 atomic_long_t zswap_stored_pages = ATOMIC_LONG_INIT(0);
47 /* The number of incompressible pages currently stored in zswap */
48 static atomic_long_t zswap_stored_incompressible_pages = ATOMIC_LONG_INIT(0);
49 
50 /*
51  * The statistics below are not protected from concurrent access for
52  * performance reasons so they may not be a 100% accurate.  However,
53  * they do provide useful information on roughly how many times a
54  * certain event is occurring.
55 */
56 
57 /* Pool limit was hit (see zswap_max_pool_percent) */
58 static u64 zswap_pool_limit_hit;
59 /* Pages written back when pool limit was reached */
60 static u64 zswap_written_back_pages;
61 /* Store failed due to a reclaim failure after pool limit was reached */
62 static u64 zswap_reject_reclaim_fail;
63 /* Store failed due to compression algorithm failure */
64 static u64 zswap_reject_compress_fail;
65 /* Compressed page was too big for the allocator to (optimally) store */
66 static u64 zswap_reject_compress_poor;
67 /* Load or writeback failed due to decompression failure */
68 static u64 zswap_decompress_fail;
69 /* Store failed because underlying allocator could not get memory */
70 static u64 zswap_reject_alloc_fail;
71 /* Store failed because the entry metadata could not be allocated (rare) */
72 static u64 zswap_reject_kmemcache_fail;
73 
74 /* Shrinker work queue */
75 static struct workqueue_struct *shrink_wq;
76 /* Pool limit was hit, we need to calm down */
77 static bool zswap_pool_reached_full;
78 
79 /*********************************
80 * tunables
81 **********************************/
82 
83 #define ZSWAP_PARAM_UNSET ""
84 
85 static int zswap_setup(void);
86 
87 /* Enable/disable zswap */
88 static DEFINE_STATIC_KEY_MAYBE(CONFIG_ZSWAP_DEFAULT_ON, zswap_ever_enabled);
89 static bool zswap_enabled = IS_ENABLED(CONFIG_ZSWAP_DEFAULT_ON);
90 static int zswap_enabled_param_set(const char *,
91 				   const struct kernel_param *);
92 static const struct kernel_param_ops zswap_enabled_param_ops = {
93 	.set =		zswap_enabled_param_set,
94 	.get =		param_get_bool,
95 };
96 module_param_cb(enabled, &zswap_enabled_param_ops, &zswap_enabled, 0644);
97 
98 /* Crypto compressor to use */
99 static char *zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
100 static int zswap_compressor_param_set(const char *,
101 				      const struct kernel_param *);
102 static const struct kernel_param_ops zswap_compressor_param_ops = {
103 	.set =		zswap_compressor_param_set,
104 	.get =		param_get_charp,
105 	.free =		param_free_charp,
106 };
107 module_param_cb(compressor, &zswap_compressor_param_ops,
108 		&zswap_compressor, 0644);
109 
110 /* The maximum percentage of memory that the compressed pool can occupy */
111 static unsigned int zswap_max_pool_percent = 20;
112 module_param_named(max_pool_percent, zswap_max_pool_percent, uint, 0644);
113 
114 /* The threshold for accepting new pages after the max_pool_percent was hit */
115 static unsigned int zswap_accept_thr_percent = 90; /* of max pool size */
116 module_param_named(accept_threshold_percent, zswap_accept_thr_percent,
117 		   uint, 0644);
118 
119 /* Enable/disable memory pressure-based shrinker. */
120 static bool zswap_shrinker_enabled = IS_ENABLED(
121 		CONFIG_ZSWAP_SHRINKER_DEFAULT_ON);
122 module_param_named(shrinker_enabled, zswap_shrinker_enabled, bool, 0644);
123 
124 bool zswap_is_enabled(void)
125 {
126 	return zswap_enabled;
127 }
128 
129 bool zswap_never_enabled(void)
130 {
131 	return !static_branch_maybe(CONFIG_ZSWAP_DEFAULT_ON, &zswap_ever_enabled);
132 }
133 
134 /*********************************
135 * data structures
136 **********************************/
137 
138 struct crypto_acomp_ctx {
139 	struct crypto_acomp *acomp;
140 	struct acomp_req *req;
141 	struct crypto_wait wait;
142 	u8 *buffer;
143 	struct mutex mutex;
144 	bool is_sleepable;
145 };
146 
147 /*
148  * The lock ordering is zswap_tree.lock -> zswap_pool.lru_lock.
149  * The only case where lru_lock is not acquired while holding tree.lock is
150  * when a zswap_entry is taken off the lru for writeback, in that case it
151  * needs to be verified that it's still valid in the tree.
152  */
153 struct zswap_pool {
154 	struct zs_pool *zs_pool;
155 	struct crypto_acomp_ctx __percpu *acomp_ctx;
156 	struct percpu_ref ref;
157 	struct list_head list;
158 	struct work_struct release_work;
159 	struct hlist_node node;
160 	char tfm_name[CRYPTO_MAX_ALG_NAME];
161 };
162 
163 /* Global LRU lists shared by all zswap pools. */
164 static struct list_lru zswap_list_lru;
165 
166 /* The lock protects zswap_next_shrink updates. */
167 static DEFINE_SPINLOCK(zswap_shrink_lock);
168 static struct mem_cgroup *zswap_next_shrink;
169 static struct work_struct zswap_shrink_work;
170 static struct shrinker *zswap_shrinker;
171 
172 /*
173  * struct zswap_entry
174  *
175  * This structure contains the metadata for tracking a single compressed
176  * page within zswap.
177  *
178  * swpentry - associated swap entry, the offset indexes into the red-black tree
179  * length - the length in bytes of the compressed page data.  Needed during
180  *          decompression.
181  * referenced - true if the entry recently entered the zswap pool. Unset by the
182  *              writeback logic. The entry is only reclaimed by the writeback
183  *              logic if referenced is unset. See comments in the shrinker
184  *              section for context.
185  * pool - the zswap_pool the entry's data is in
186  * handle - zsmalloc allocation handle that stores the compressed page data
187  * objcg - the obj_cgroup that the compressed memory is charged to
188  * lru - handle to the pool's lru used to evict pages.
189  */
190 struct zswap_entry {
191 	swp_entry_t swpentry;
192 	unsigned int length;
193 	bool referenced;
194 	struct zswap_pool *pool;
195 	unsigned long handle;
196 	struct obj_cgroup *objcg;
197 	struct list_head lru;
198 };
199 
200 static struct xarray *zswap_trees[MAX_SWAPFILES];
201 static unsigned int nr_zswap_trees[MAX_SWAPFILES];
202 
203 /* RCU-protected iteration */
204 static LIST_HEAD(zswap_pools);
205 /* protects zswap_pools list modification */
206 static DEFINE_SPINLOCK(zswap_pools_lock);
207 /* pool counter to provide unique names to zsmalloc */
208 static atomic_t zswap_pools_count = ATOMIC_INIT(0);
209 
210 enum zswap_init_type {
211 	ZSWAP_UNINIT,
212 	ZSWAP_INIT_SUCCEED,
213 	ZSWAP_INIT_FAILED
214 };
215 
216 static enum zswap_init_type zswap_init_state;
217 
218 /* used to ensure the integrity of initialization */
219 static DEFINE_MUTEX(zswap_init_lock);
220 
221 /* init completed, but couldn't create the initial pool */
222 static bool zswap_has_pool;
223 
224 /*********************************
225 * helpers and fwd declarations
226 **********************************/
227 
228 static inline struct xarray *swap_zswap_tree(swp_entry_t swp)
229 {
230 	return &zswap_trees[swp_type(swp)][swp_offset(swp)
231 		>> SWAP_ADDRESS_SPACE_SHIFT];
232 }
233 
234 #define zswap_pool_debug(msg, p)			\
235 	pr_debug("%s pool %s\n", msg, (p)->tfm_name)
236 
237 /*********************************
238 * pool functions
239 **********************************/
240 static void __zswap_pool_empty(struct percpu_ref *ref);
241 
242 static struct zswap_pool *zswap_pool_create(char *compressor)
243 {
244 	struct zswap_pool *pool;
245 	char name[38]; /* 'zswap' + 32 char (max) num + \0 */
246 	int ret, cpu;
247 
248 	if (!zswap_has_pool && !strcmp(compressor, ZSWAP_PARAM_UNSET))
249 		return NULL;
250 
251 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
252 	if (!pool)
253 		return NULL;
254 
255 	/* unique name for each pool specifically required by zsmalloc */
256 	snprintf(name, 38, "zswap%x", atomic_inc_return(&zswap_pools_count));
257 	pool->zs_pool = zs_create_pool(name);
258 	if (!pool->zs_pool)
259 		goto error;
260 
261 	strscpy(pool->tfm_name, compressor, sizeof(pool->tfm_name));
262 
263 	pool->acomp_ctx = alloc_percpu(*pool->acomp_ctx);
264 	if (!pool->acomp_ctx) {
265 		pr_err("percpu alloc failed\n");
266 		goto error;
267 	}
268 
269 	for_each_possible_cpu(cpu)
270 		mutex_init(&per_cpu_ptr(pool->acomp_ctx, cpu)->mutex);
271 
272 	ret = cpuhp_state_add_instance(CPUHP_MM_ZSWP_POOL_PREPARE,
273 				       &pool->node);
274 	if (ret)
275 		goto error;
276 
277 	/* being the current pool takes 1 ref; this func expects the
278 	 * caller to always add the new pool as the current pool
279 	 */
280 	ret = percpu_ref_init(&pool->ref, __zswap_pool_empty,
281 			      PERCPU_REF_ALLOW_REINIT, GFP_KERNEL);
282 	if (ret)
283 		goto ref_fail;
284 	INIT_LIST_HEAD(&pool->list);
285 
286 	zswap_pool_debug("created", pool);
287 
288 	return pool;
289 
290 ref_fail:
291 	cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
292 error:
293 	if (pool->acomp_ctx)
294 		free_percpu(pool->acomp_ctx);
295 	if (pool->zs_pool)
296 		zs_destroy_pool(pool->zs_pool);
297 	kfree(pool);
298 	return NULL;
299 }
300 
301 static struct zswap_pool *__zswap_pool_create_fallback(void)
302 {
303 	if (!crypto_has_acomp(zswap_compressor, 0, 0) &&
304 	    strcmp(zswap_compressor, CONFIG_ZSWAP_COMPRESSOR_DEFAULT)) {
305 		pr_err("compressor %s not available, using default %s\n",
306 		       zswap_compressor, CONFIG_ZSWAP_COMPRESSOR_DEFAULT);
307 		param_free_charp(&zswap_compressor);
308 		zswap_compressor = CONFIG_ZSWAP_COMPRESSOR_DEFAULT;
309 	}
310 
311 	/* Default compressor should be available. Kconfig bug? */
312 	if (WARN_ON_ONCE(!crypto_has_acomp(zswap_compressor, 0, 0))) {
313 		zswap_compressor = ZSWAP_PARAM_UNSET;
314 		return NULL;
315 	}
316 
317 	return zswap_pool_create(zswap_compressor);
318 }
319 
320 static void zswap_pool_destroy(struct zswap_pool *pool)
321 {
322 	zswap_pool_debug("destroying", pool);
323 
324 	cpuhp_state_remove_instance(CPUHP_MM_ZSWP_POOL_PREPARE, &pool->node);
325 	free_percpu(pool->acomp_ctx);
326 
327 	zs_destroy_pool(pool->zs_pool);
328 	kfree(pool);
329 }
330 
331 static void __zswap_pool_release(struct work_struct *work)
332 {
333 	struct zswap_pool *pool = container_of(work, typeof(*pool),
334 						release_work);
335 
336 	synchronize_rcu();
337 
338 	/* nobody should have been able to get a ref... */
339 	WARN_ON(!percpu_ref_is_zero(&pool->ref));
340 	percpu_ref_exit(&pool->ref);
341 
342 	/* pool is now off zswap_pools list and has no references. */
343 	zswap_pool_destroy(pool);
344 }
345 
346 static struct zswap_pool *zswap_pool_current(void);
347 
348 static void __zswap_pool_empty(struct percpu_ref *ref)
349 {
350 	struct zswap_pool *pool;
351 
352 	pool = container_of(ref, typeof(*pool), ref);
353 
354 	spin_lock_bh(&zswap_pools_lock);
355 
356 	WARN_ON(pool == zswap_pool_current());
357 
358 	list_del_rcu(&pool->list);
359 
360 	INIT_WORK(&pool->release_work, __zswap_pool_release);
361 	schedule_work(&pool->release_work);
362 
363 	spin_unlock_bh(&zswap_pools_lock);
364 }
365 
366 static int __must_check zswap_pool_tryget(struct zswap_pool *pool)
367 {
368 	if (!pool)
369 		return 0;
370 
371 	return percpu_ref_tryget(&pool->ref);
372 }
373 
374 /* The caller must already have a reference. */
375 static void zswap_pool_get(struct zswap_pool *pool)
376 {
377 	percpu_ref_get(&pool->ref);
378 }
379 
380 static void zswap_pool_put(struct zswap_pool *pool)
381 {
382 	percpu_ref_put(&pool->ref);
383 }
384 
385 static struct zswap_pool *__zswap_pool_current(void)
386 {
387 	struct zswap_pool *pool;
388 
389 	pool = list_first_or_null_rcu(&zswap_pools, typeof(*pool), list);
390 	WARN_ONCE(!pool && zswap_has_pool,
391 		  "%s: no page storage pool!\n", __func__);
392 
393 	return pool;
394 }
395 
396 static struct zswap_pool *zswap_pool_current(void)
397 {
398 	assert_spin_locked(&zswap_pools_lock);
399 
400 	return __zswap_pool_current();
401 }
402 
403 static struct zswap_pool *zswap_pool_current_get(void)
404 {
405 	struct zswap_pool *pool;
406 
407 	rcu_read_lock();
408 
409 	pool = __zswap_pool_current();
410 	if (!zswap_pool_tryget(pool))
411 		pool = NULL;
412 
413 	rcu_read_unlock();
414 
415 	return pool;
416 }
417 
418 /* type and compressor must be null-terminated */
419 static struct zswap_pool *zswap_pool_find_get(char *compressor)
420 {
421 	struct zswap_pool *pool;
422 
423 	assert_spin_locked(&zswap_pools_lock);
424 
425 	list_for_each_entry_rcu(pool, &zswap_pools, list) {
426 		if (strcmp(pool->tfm_name, compressor))
427 			continue;
428 		/* if we can't get it, it's about to be destroyed */
429 		if (!zswap_pool_tryget(pool))
430 			continue;
431 		return pool;
432 	}
433 
434 	return NULL;
435 }
436 
437 static unsigned long zswap_max_pages(void)
438 {
439 	return totalram_pages() * zswap_max_pool_percent / 100;
440 }
441 
442 static unsigned long zswap_accept_thr_pages(void)
443 {
444 	return zswap_max_pages() * zswap_accept_thr_percent / 100;
445 }
446 
447 unsigned long zswap_total_pages(void)
448 {
449 	struct zswap_pool *pool;
450 	unsigned long total = 0;
451 
452 	rcu_read_lock();
453 	list_for_each_entry_rcu(pool, &zswap_pools, list)
454 		total += zs_get_total_pages(pool->zs_pool);
455 	rcu_read_unlock();
456 
457 	return total;
458 }
459 
460 static bool zswap_check_limits(void)
461 {
462 	unsigned long cur_pages = zswap_total_pages();
463 	unsigned long max_pages = zswap_max_pages();
464 
465 	if (cur_pages >= max_pages) {
466 		zswap_pool_limit_hit++;
467 		zswap_pool_reached_full = true;
468 	} else if (zswap_pool_reached_full &&
469 		   cur_pages <= zswap_accept_thr_pages()) {
470 			zswap_pool_reached_full = false;
471 	}
472 	return zswap_pool_reached_full;
473 }
474 
475 /*********************************
476 * param callbacks
477 **********************************/
478 
479 static int zswap_compressor_param_set(const char *val, const struct kernel_param *kp)
480 {
481 	struct zswap_pool *pool, *put_pool = NULL;
482 	char *s = strstrip((char *)val);
483 	bool create_pool = false;
484 	int ret = 0;
485 
486 	mutex_lock(&zswap_init_lock);
487 	switch (zswap_init_state) {
488 	case ZSWAP_UNINIT:
489 		/* Handled in zswap_setup() */
490 		ret = param_set_charp(s, kp);
491 		break;
492 	case ZSWAP_INIT_SUCCEED:
493 		if (!zswap_has_pool || strcmp(s, *(char **)kp->arg))
494 			create_pool = true;
495 		break;
496 	case ZSWAP_INIT_FAILED:
497 		pr_err("can't set param, initialization failed\n");
498 		ret = -ENODEV;
499 	}
500 	mutex_unlock(&zswap_init_lock);
501 
502 	if (!create_pool)
503 		return ret;
504 
505 	if (!crypto_has_acomp(s, 0, 0)) {
506 		pr_err("compressor %s not available\n", s);
507 		return -ENOENT;
508 	}
509 
510 	spin_lock_bh(&zswap_pools_lock);
511 
512 	pool = zswap_pool_find_get(s);
513 	if (pool) {
514 		zswap_pool_debug("using existing", pool);
515 		WARN_ON(pool == zswap_pool_current());
516 		list_del_rcu(&pool->list);
517 	}
518 
519 	spin_unlock_bh(&zswap_pools_lock);
520 
521 	if (!pool)
522 		pool = zswap_pool_create(s);
523 	else {
524 		/*
525 		 * Restore the initial ref dropped by percpu_ref_kill()
526 		 * when the pool was decommissioned and switch it again
527 		 * to percpu mode.
528 		 */
529 		percpu_ref_resurrect(&pool->ref);
530 
531 		/* Drop the ref from zswap_pool_find_get(). */
532 		zswap_pool_put(pool);
533 	}
534 
535 	if (pool)
536 		ret = param_set_charp(s, kp);
537 	else
538 		ret = -EINVAL;
539 
540 	spin_lock_bh(&zswap_pools_lock);
541 
542 	if (!ret) {
543 		put_pool = zswap_pool_current();
544 		list_add_rcu(&pool->list, &zswap_pools);
545 		zswap_has_pool = true;
546 	} else if (pool) {
547 		/*
548 		 * Add the possibly pre-existing pool to the end of the pools
549 		 * list; if it's new (and empty) then it'll be removed and
550 		 * destroyed by the put after we drop the lock
551 		 */
552 		list_add_tail_rcu(&pool->list, &zswap_pools);
553 		put_pool = pool;
554 	}
555 
556 	spin_unlock_bh(&zswap_pools_lock);
557 
558 	/*
559 	 * Drop the ref from either the old current pool,
560 	 * or the new pool we failed to add
561 	 */
562 	if (put_pool)
563 		percpu_ref_kill(&put_pool->ref);
564 
565 	return ret;
566 }
567 
568 static int zswap_enabled_param_set(const char *val,
569 				   const struct kernel_param *kp)
570 {
571 	int ret = -ENODEV;
572 
573 	/* if this is load-time (pre-init) param setting, only set param. */
574 	if (system_state != SYSTEM_RUNNING)
575 		return param_set_bool(val, kp);
576 
577 	mutex_lock(&zswap_init_lock);
578 	switch (zswap_init_state) {
579 	case ZSWAP_UNINIT:
580 		if (zswap_setup())
581 			break;
582 		fallthrough;
583 	case ZSWAP_INIT_SUCCEED:
584 		if (!zswap_has_pool)
585 			pr_err("can't enable, no pool configured\n");
586 		else
587 			ret = param_set_bool(val, kp);
588 		break;
589 	case ZSWAP_INIT_FAILED:
590 		pr_err("can't enable, initialization failed\n");
591 	}
592 	mutex_unlock(&zswap_init_lock);
593 
594 	return ret;
595 }
596 
597 /*********************************
598 * lru functions
599 **********************************/
600 
601 /* should be called under RCU */
602 #ifdef CONFIG_MEMCG
603 static inline struct mem_cgroup *mem_cgroup_from_entry(struct zswap_entry *entry)
604 {
605 	return entry->objcg ? obj_cgroup_memcg(entry->objcg) : NULL;
606 }
607 #else
608 static inline struct mem_cgroup *mem_cgroup_from_entry(struct zswap_entry *entry)
609 {
610 	return NULL;
611 }
612 #endif
613 
614 static inline int entry_to_nid(struct zswap_entry *entry)
615 {
616 	return page_to_nid(virt_to_page(entry));
617 }
618 
619 static void zswap_lru_add(struct list_lru *list_lru, struct zswap_entry *entry)
620 {
621 	int nid = entry_to_nid(entry);
622 	struct mem_cgroup *memcg;
623 
624 	/*
625 	 * Note that it is safe to use rcu_read_lock() here, even in the face of
626 	 * concurrent memcg offlining:
627 	 *
628 	 * 1. list_lru_add() is called before list_lru_one is dead. The
629 	 *    new entry will be reparented to memcg's parent's list_lru.
630 	 * 2. list_lru_add() is called after list_lru_one is dead. The
631 	 *    new entry will be added directly to memcg's parent's list_lru.
632 	 *
633 	 * Similar reasoning holds for list_lru_del().
634 	 */
635 	rcu_read_lock();
636 	memcg = mem_cgroup_from_entry(entry);
637 	/* will always succeed */
638 	list_lru_add(list_lru, &entry->lru, nid, memcg);
639 	rcu_read_unlock();
640 }
641 
642 static void zswap_lru_del(struct list_lru *list_lru, struct zswap_entry *entry)
643 {
644 	int nid = entry_to_nid(entry);
645 	struct mem_cgroup *memcg;
646 
647 	rcu_read_lock();
648 	memcg = mem_cgroup_from_entry(entry);
649 	/* will always succeed */
650 	list_lru_del(list_lru, &entry->lru, nid, memcg);
651 	rcu_read_unlock();
652 }
653 
654 void zswap_lruvec_state_init(struct lruvec *lruvec)
655 {
656 	atomic_long_set(&lruvec->zswap_lruvec_state.nr_disk_swapins, 0);
657 }
658 
659 void zswap_folio_swapin(struct folio *folio)
660 {
661 	struct lruvec *lruvec;
662 
663 	if (folio) {
664 		lruvec = folio_lruvec(folio);
665 		atomic_long_inc(&lruvec->zswap_lruvec_state.nr_disk_swapins);
666 	}
667 }
668 
669 /*
670  * This function should be called when a memcg is being offlined.
671  *
672  * Since the global shrinker shrink_worker() may hold a reference
673  * of the memcg, we must check and release the reference in
674  * zswap_next_shrink.
675  *
676  * shrink_worker() must handle the case where this function releases
677  * the reference of memcg being shrunk.
678  */
679 void zswap_memcg_offline_cleanup(struct mem_cgroup *memcg)
680 {
681 	/* lock out zswap shrinker walking memcg tree */
682 	spin_lock(&zswap_shrink_lock);
683 	if (zswap_next_shrink == memcg) {
684 		do {
685 			zswap_next_shrink = mem_cgroup_iter(NULL, zswap_next_shrink, NULL);
686 		} while (zswap_next_shrink && !mem_cgroup_online(zswap_next_shrink));
687 	}
688 	spin_unlock(&zswap_shrink_lock);
689 }
690 
691 /*********************************
692 * zswap entry functions
693 **********************************/
694 static struct kmem_cache *zswap_entry_cache;
695 
696 static struct zswap_entry *zswap_entry_cache_alloc(gfp_t gfp, int nid)
697 {
698 	struct zswap_entry *entry;
699 	entry = kmem_cache_alloc_node(zswap_entry_cache, gfp, nid);
700 	if (!entry)
701 		return NULL;
702 	return entry;
703 }
704 
705 static void zswap_entry_cache_free(struct zswap_entry *entry)
706 {
707 	kmem_cache_free(zswap_entry_cache, entry);
708 }
709 
710 /*
711  * Carries out the common pattern of freeing an entry's zsmalloc allocation,
712  * freeing the entry itself, and decrementing the number of stored pages.
713  */
714 static void zswap_entry_free(struct zswap_entry *entry)
715 {
716 	zswap_lru_del(&zswap_list_lru, entry);
717 	zs_free(entry->pool->zs_pool, entry->handle);
718 	zswap_pool_put(entry->pool);
719 	if (entry->objcg) {
720 		obj_cgroup_uncharge_zswap(entry->objcg, entry->length);
721 		obj_cgroup_put(entry->objcg);
722 	}
723 	if (entry->length == PAGE_SIZE)
724 		atomic_long_dec(&zswap_stored_incompressible_pages);
725 	zswap_entry_cache_free(entry);
726 	atomic_long_dec(&zswap_stored_pages);
727 }
728 
729 /*********************************
730 * compressed storage functions
731 **********************************/
732 static int zswap_cpu_comp_prepare(unsigned int cpu, struct hlist_node *node)
733 {
734 	struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
735 	struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
736 	struct crypto_acomp *acomp = NULL;
737 	struct acomp_req *req = NULL;
738 	u8 *buffer = NULL;
739 	int ret;
740 
741 	buffer = kmalloc_node(PAGE_SIZE, GFP_KERNEL, cpu_to_node(cpu));
742 	if (!buffer) {
743 		ret = -ENOMEM;
744 		goto fail;
745 	}
746 
747 	acomp = crypto_alloc_acomp_node(pool->tfm_name, 0, 0, cpu_to_node(cpu));
748 	if (IS_ERR(acomp)) {
749 		pr_err("could not alloc crypto acomp %s : %ld\n",
750 				pool->tfm_name, PTR_ERR(acomp));
751 		ret = PTR_ERR(acomp);
752 		goto fail;
753 	}
754 
755 	req = acomp_request_alloc(acomp);
756 	if (!req) {
757 		pr_err("could not alloc crypto acomp_request %s\n",
758 		       pool->tfm_name);
759 		ret = -ENOMEM;
760 		goto fail;
761 	}
762 
763 	/*
764 	 * Only hold the mutex after completing allocations, otherwise we may
765 	 * recurse into zswap through reclaim and attempt to hold the mutex
766 	 * again resulting in a deadlock.
767 	 */
768 	mutex_lock(&acomp_ctx->mutex);
769 	crypto_init_wait(&acomp_ctx->wait);
770 
771 	/*
772 	 * if the backend of acomp is async zip, crypto_req_done() will wakeup
773 	 * crypto_wait_req(); if the backend of acomp is scomp, the callback
774 	 * won't be called, crypto_wait_req() will return without blocking.
775 	 */
776 	acomp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
777 				   crypto_req_done, &acomp_ctx->wait);
778 
779 	acomp_ctx->buffer = buffer;
780 	acomp_ctx->acomp = acomp;
781 	acomp_ctx->is_sleepable = acomp_is_async(acomp);
782 	acomp_ctx->req = req;
783 	mutex_unlock(&acomp_ctx->mutex);
784 	return 0;
785 
786 fail:
787 	if (acomp)
788 		crypto_free_acomp(acomp);
789 	kfree(buffer);
790 	return ret;
791 }
792 
793 static int zswap_cpu_comp_dead(unsigned int cpu, struct hlist_node *node)
794 {
795 	struct zswap_pool *pool = hlist_entry(node, struct zswap_pool, node);
796 	struct crypto_acomp_ctx *acomp_ctx = per_cpu_ptr(pool->acomp_ctx, cpu);
797 	struct acomp_req *req;
798 	struct crypto_acomp *acomp;
799 	u8 *buffer;
800 
801 	if (IS_ERR_OR_NULL(acomp_ctx))
802 		return 0;
803 
804 	mutex_lock(&acomp_ctx->mutex);
805 	req = acomp_ctx->req;
806 	acomp = acomp_ctx->acomp;
807 	buffer = acomp_ctx->buffer;
808 	acomp_ctx->req = NULL;
809 	acomp_ctx->acomp = NULL;
810 	acomp_ctx->buffer = NULL;
811 	mutex_unlock(&acomp_ctx->mutex);
812 
813 	/*
814 	 * Do the actual freeing after releasing the mutex to avoid subtle
815 	 * locking dependencies causing deadlocks.
816 	 */
817 	if (!IS_ERR_OR_NULL(req))
818 		acomp_request_free(req);
819 	if (!IS_ERR_OR_NULL(acomp))
820 		crypto_free_acomp(acomp);
821 	kfree(buffer);
822 
823 	return 0;
824 }
825 
826 static struct crypto_acomp_ctx *acomp_ctx_get_cpu_lock(struct zswap_pool *pool)
827 {
828 	struct crypto_acomp_ctx *acomp_ctx;
829 
830 	for (;;) {
831 		acomp_ctx = raw_cpu_ptr(pool->acomp_ctx);
832 		mutex_lock(&acomp_ctx->mutex);
833 		if (likely(acomp_ctx->req))
834 			return acomp_ctx;
835 		/*
836 		 * It is possible that we were migrated to a different CPU after
837 		 * getting the per-CPU ctx but before the mutex was acquired. If
838 		 * the old CPU got offlined, zswap_cpu_comp_dead() could have
839 		 * already freed ctx->req (among other things) and set it to
840 		 * NULL. Just try again on the new CPU that we ended up on.
841 		 */
842 		mutex_unlock(&acomp_ctx->mutex);
843 	}
844 }
845 
846 static void acomp_ctx_put_unlock(struct crypto_acomp_ctx *acomp_ctx)
847 {
848 	mutex_unlock(&acomp_ctx->mutex);
849 }
850 
851 static bool zswap_compress(struct page *page, struct zswap_entry *entry,
852 			   struct zswap_pool *pool)
853 {
854 	struct crypto_acomp_ctx *acomp_ctx;
855 	struct scatterlist input, output;
856 	int comp_ret = 0, alloc_ret = 0;
857 	unsigned int dlen = PAGE_SIZE;
858 	unsigned long handle;
859 	gfp_t gfp;
860 	u8 *dst;
861 	bool mapped = false;
862 
863 	acomp_ctx = acomp_ctx_get_cpu_lock(pool);
864 	dst = acomp_ctx->buffer;
865 	sg_init_table(&input, 1);
866 	sg_set_page(&input, page, PAGE_SIZE, 0);
867 
868 	sg_init_one(&output, dst, PAGE_SIZE);
869 	acomp_request_set_params(acomp_ctx->req, &input, &output, PAGE_SIZE, dlen);
870 
871 	/*
872 	 * it maybe looks a little bit silly that we send an asynchronous request,
873 	 * then wait for its completion synchronously. This makes the process look
874 	 * synchronous in fact.
875 	 * Theoretically, acomp supports users send multiple acomp requests in one
876 	 * acomp instance, then get those requests done simultaneously. but in this
877 	 * case, zswap actually does store and load page by page, there is no
878 	 * existing method to send the second page before the first page is done
879 	 * in one thread doing zwap.
880 	 * but in different threads running on different cpu, we have different
881 	 * acomp instance, so multiple threads can do (de)compression in parallel.
882 	 */
883 	comp_ret = crypto_wait_req(crypto_acomp_compress(acomp_ctx->req), &acomp_ctx->wait);
884 	dlen = acomp_ctx->req->dlen;
885 
886 	/*
887 	 * If a page cannot be compressed into a size smaller than PAGE_SIZE,
888 	 * save the content as is without a compression, to keep the LRU order
889 	 * of writebacks.  If writeback is disabled, reject the page since it
890 	 * only adds metadata overhead.  swap_writeout() will put the page back
891 	 * to the active LRU list in the case.
892 	 */
893 	if (comp_ret || !dlen || dlen >= PAGE_SIZE) {
894 		dlen = PAGE_SIZE;
895 		if (!mem_cgroup_zswap_writeback_enabled(
896 					folio_memcg(page_folio(page)))) {
897 			comp_ret = comp_ret ? comp_ret : -EINVAL;
898 			goto unlock;
899 		}
900 		comp_ret = 0;
901 		dlen = PAGE_SIZE;
902 		dst = kmap_local_page(page);
903 		mapped = true;
904 	}
905 
906 	gfp = GFP_NOWAIT | __GFP_NORETRY | __GFP_HIGHMEM | __GFP_MOVABLE;
907 	handle = zs_malloc(pool->zs_pool, dlen, gfp, page_to_nid(page));
908 	if (IS_ERR_VALUE(handle)) {
909 		alloc_ret = PTR_ERR((void *)handle);
910 		goto unlock;
911 	}
912 
913 	zs_obj_write(pool->zs_pool, handle, dst, dlen);
914 	entry->handle = handle;
915 	entry->length = dlen;
916 
917 unlock:
918 	if (mapped)
919 		kunmap_local(dst);
920 	if (comp_ret == -ENOSPC || alloc_ret == -ENOSPC)
921 		zswap_reject_compress_poor++;
922 	else if (comp_ret)
923 		zswap_reject_compress_fail++;
924 	else if (alloc_ret)
925 		zswap_reject_alloc_fail++;
926 
927 	acomp_ctx_put_unlock(acomp_ctx);
928 	return comp_ret == 0 && alloc_ret == 0;
929 }
930 
931 static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio)
932 {
933 	struct zswap_pool *pool = entry->pool;
934 	struct scatterlist input, output;
935 	struct crypto_acomp_ctx *acomp_ctx;
936 	int decomp_ret = 0, dlen = PAGE_SIZE;
937 	u8 *src, *obj;
938 
939 	acomp_ctx = acomp_ctx_get_cpu_lock(pool);
940 	obj = zs_obj_read_begin(pool->zs_pool, entry->handle, acomp_ctx->buffer);
941 
942 	/* zswap entries of length PAGE_SIZE are not compressed. */
943 	if (entry->length == PAGE_SIZE) {
944 		memcpy_to_folio(folio, 0, obj, entry->length);
945 		goto read_done;
946 	}
947 
948 	/*
949 	 * zs_obj_read_begin() might return a kmap address of highmem when
950 	 * acomp_ctx->buffer is not used.  However, sg_init_one() does not
951 	 * handle highmem addresses, so copy the object to acomp_ctx->buffer.
952 	 */
953 	if (virt_addr_valid(obj)) {
954 		src = obj;
955 	} else {
956 		WARN_ON_ONCE(obj == acomp_ctx->buffer);
957 		memcpy(acomp_ctx->buffer, obj, entry->length);
958 		src = acomp_ctx->buffer;
959 	}
960 
961 	sg_init_one(&input, src, entry->length);
962 	sg_init_table(&output, 1);
963 	sg_set_folio(&output, folio, PAGE_SIZE, 0);
964 	acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, PAGE_SIZE);
965 	decomp_ret = crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait);
966 	dlen = acomp_ctx->req->dlen;
967 
968 read_done:
969 	zs_obj_read_end(pool->zs_pool, entry->handle, obj);
970 	acomp_ctx_put_unlock(acomp_ctx);
971 
972 	if (!decomp_ret && dlen == PAGE_SIZE)
973 		return true;
974 
975 	zswap_decompress_fail++;
976 	pr_alert_ratelimited("Decompression error from zswap (%d:%lu %s %u->%d)\n",
977 						swp_type(entry->swpentry),
978 						swp_offset(entry->swpentry),
979 						entry->pool->tfm_name, entry->length, dlen);
980 	return false;
981 }
982 
983 /*********************************
984 * writeback code
985 **********************************/
986 /*
987  * Attempts to free an entry by adding a folio to the swap cache,
988  * decompressing the entry data into the folio, and issuing a
989  * bio write to write the folio back to the swap device.
990  *
991  * This can be thought of as a "resumed writeback" of the folio
992  * to the swap device.  We are basically resuming the same swap
993  * writeback path that was intercepted with the zswap_store()
994  * in the first place.  After the folio has been decompressed into
995  * the swap cache, the compressed version stored by zswap can be
996  * freed.
997  */
998 static int zswap_writeback_entry(struct zswap_entry *entry,
999 				 swp_entry_t swpentry)
1000 {
1001 	struct xarray *tree;
1002 	pgoff_t offset = swp_offset(swpentry);
1003 	struct folio *folio;
1004 	struct mempolicy *mpol;
1005 	bool folio_was_allocated;
1006 	struct swap_info_struct *si;
1007 	int ret = 0;
1008 
1009 	/* try to allocate swap cache folio */
1010 	si = get_swap_device(swpentry);
1011 	if (!si)
1012 		return -EEXIST;
1013 
1014 	mpol = get_task_policy(current);
1015 	folio = __read_swap_cache_async(swpentry, GFP_KERNEL, mpol,
1016 			NO_INTERLEAVE_INDEX, &folio_was_allocated, true);
1017 	put_swap_device(si);
1018 	if (!folio)
1019 		return -ENOMEM;
1020 
1021 	/*
1022 	 * Found an existing folio, we raced with swapin or concurrent
1023 	 * shrinker. We generally writeback cold folios from zswap, and
1024 	 * swapin means the folio just became hot, so skip this folio.
1025 	 * For unlikely concurrent shrinker case, it will be unlinked
1026 	 * and freed when invalidated by the concurrent shrinker anyway.
1027 	 */
1028 	if (!folio_was_allocated) {
1029 		ret = -EEXIST;
1030 		goto out;
1031 	}
1032 
1033 	/*
1034 	 * folio is locked, and the swapcache is now secured against
1035 	 * concurrent swapping to and from the slot, and concurrent
1036 	 * swapoff so we can safely dereference the zswap tree here.
1037 	 * Verify that the swap entry hasn't been invalidated and recycled
1038 	 * behind our backs, to avoid overwriting a new swap folio with
1039 	 * old compressed data. Only when this is successful can the entry
1040 	 * be dereferenced.
1041 	 */
1042 	tree = swap_zswap_tree(swpentry);
1043 	if (entry != xa_load(tree, offset)) {
1044 		ret = -ENOMEM;
1045 		goto out;
1046 	}
1047 
1048 	if (!zswap_decompress(entry, folio)) {
1049 		ret = -EIO;
1050 		goto out;
1051 	}
1052 
1053 	xa_erase(tree, offset);
1054 
1055 	count_vm_event(ZSWPWB);
1056 	if (entry->objcg)
1057 		count_objcg_events(entry->objcg, ZSWPWB, 1);
1058 
1059 	zswap_entry_free(entry);
1060 
1061 	/* folio is up to date */
1062 	folio_mark_uptodate(folio);
1063 
1064 	/* move it to the tail of the inactive list after end_writeback */
1065 	folio_set_reclaim(folio);
1066 
1067 	/* start writeback */
1068 	__swap_writepage(folio, NULL);
1069 
1070 out:
1071 	if (ret && ret != -EEXIST) {
1072 		delete_from_swap_cache(folio);
1073 		folio_unlock(folio);
1074 	}
1075 	folio_put(folio);
1076 	return ret;
1077 }
1078 
1079 /*********************************
1080 * shrinker functions
1081 **********************************/
1082 /*
1083  * The dynamic shrinker is modulated by the following factors:
1084  *
1085  * 1. Each zswap entry has a referenced bit, which the shrinker unsets (giving
1086  *    the entry a second chance) before rotating it in the LRU list. If the
1087  *    entry is considered again by the shrinker, with its referenced bit unset,
1088  *    it is written back. The writeback rate as a result is dynamically
1089  *    adjusted by the pool activities - if the pool is dominated by new entries
1090  *    (i.e lots of recent zswapouts), these entries will be protected and
1091  *    the writeback rate will slow down. On the other hand, if the pool has a
1092  *    lot of stagnant entries, these entries will be reclaimed immediately,
1093  *    effectively increasing the writeback rate.
1094  *
1095  * 2. Swapins counter: If we observe swapins, it is a sign that we are
1096  *    overshrinking and should slow down. We maintain a swapins counter, which
1097  *    is consumed and subtract from the number of eligible objects on the LRU
1098  *    in zswap_shrinker_count().
1099  *
1100  * 3. Compression ratio. The better the workload compresses, the less gains we
1101  *    can expect from writeback. We scale down the number of objects available
1102  *    for reclaim by this ratio.
1103  */
1104 static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_one *l,
1105 				       void *arg)
1106 {
1107 	struct zswap_entry *entry = container_of(item, struct zswap_entry, lru);
1108 	bool *encountered_page_in_swapcache = (bool *)arg;
1109 	swp_entry_t swpentry;
1110 	enum lru_status ret = LRU_REMOVED_RETRY;
1111 	int writeback_result;
1112 
1113 	/*
1114 	 * Second chance algorithm: if the entry has its referenced bit set, give it
1115 	 * a second chance. Only clear the referenced bit and rotate it in the
1116 	 * zswap's LRU list.
1117 	 */
1118 	if (entry->referenced) {
1119 		entry->referenced = false;
1120 		return LRU_ROTATE;
1121 	}
1122 
1123 	/*
1124 	 * As soon as we drop the LRU lock, the entry can be freed by
1125 	 * a concurrent invalidation. This means the following:
1126 	 *
1127 	 * 1. We extract the swp_entry_t to the stack, allowing
1128 	 *    zswap_writeback_entry() to pin the swap entry and
1129 	 *    then validate the zwap entry against that swap entry's
1130 	 *    tree using pointer value comparison. Only when that
1131 	 *    is successful can the entry be dereferenced.
1132 	 *
1133 	 * 2. Usually, objects are taken off the LRU for reclaim. In
1134 	 *    this case this isn't possible, because if reclaim fails
1135 	 *    for whatever reason, we have no means of knowing if the
1136 	 *    entry is alive to put it back on the LRU.
1137 	 *
1138 	 *    So rotate it before dropping the lock. If the entry is
1139 	 *    written back or invalidated, the free path will unlink
1140 	 *    it. For failures, rotation is the right thing as well.
1141 	 *
1142 	 *    Temporary failures, where the same entry should be tried
1143 	 *    again immediately, almost never happen for this shrinker.
1144 	 *    We don't do any trylocking; -ENOMEM comes closest,
1145 	 *    but that's extremely rare and doesn't happen spuriously
1146 	 *    either. Don't bother distinguishing this case.
1147 	 */
1148 	list_move_tail(item, &l->list);
1149 
1150 	/*
1151 	 * Once the lru lock is dropped, the entry might get freed. The
1152 	 * swpentry is copied to the stack, and entry isn't deref'd again
1153 	 * until the entry is verified to still be alive in the tree.
1154 	 */
1155 	swpentry = entry->swpentry;
1156 
1157 	/*
1158 	 * It's safe to drop the lock here because we return either
1159 	 * LRU_REMOVED_RETRY, LRU_RETRY or LRU_STOP.
1160 	 */
1161 	spin_unlock(&l->lock);
1162 
1163 	writeback_result = zswap_writeback_entry(entry, swpentry);
1164 
1165 	if (writeback_result) {
1166 		zswap_reject_reclaim_fail++;
1167 		ret = LRU_RETRY;
1168 
1169 		/*
1170 		 * Encountering a page already in swap cache is a sign that we are shrinking
1171 		 * into the warmer region. We should terminate shrinking (if we're in the dynamic
1172 		 * shrinker context).
1173 		 */
1174 		if (writeback_result == -EEXIST && encountered_page_in_swapcache) {
1175 			ret = LRU_STOP;
1176 			*encountered_page_in_swapcache = true;
1177 		}
1178 	} else {
1179 		zswap_written_back_pages++;
1180 	}
1181 
1182 	return ret;
1183 }
1184 
1185 static unsigned long zswap_shrinker_scan(struct shrinker *shrinker,
1186 		struct shrink_control *sc)
1187 {
1188 	unsigned long shrink_ret;
1189 	bool encountered_page_in_swapcache = false;
1190 
1191 	if (!zswap_shrinker_enabled ||
1192 			!mem_cgroup_zswap_writeback_enabled(sc->memcg)) {
1193 		sc->nr_scanned = 0;
1194 		return SHRINK_STOP;
1195 	}
1196 
1197 	shrink_ret = list_lru_shrink_walk(&zswap_list_lru, sc, &shrink_memcg_cb,
1198 		&encountered_page_in_swapcache);
1199 
1200 	if (encountered_page_in_swapcache)
1201 		return SHRINK_STOP;
1202 
1203 	return shrink_ret ? shrink_ret : SHRINK_STOP;
1204 }
1205 
1206 static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
1207 		struct shrink_control *sc)
1208 {
1209 	struct mem_cgroup *memcg = sc->memcg;
1210 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(sc->nid));
1211 	atomic_long_t *nr_disk_swapins =
1212 		&lruvec->zswap_lruvec_state.nr_disk_swapins;
1213 	unsigned long nr_backing, nr_stored, nr_freeable, nr_disk_swapins_cur,
1214 		nr_remain;
1215 
1216 	if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
1217 		return 0;
1218 
1219 	/*
1220 	 * The shrinker resumes swap writeback, which will enter block
1221 	 * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS
1222 	 * rules (may_enter_fs()), which apply on a per-folio basis.
1223 	 */
1224 	if (!gfp_has_io_fs(sc->gfp_mask))
1225 		return 0;
1226 
1227 	/*
1228 	 * For memcg, use the cgroup-wide ZSWAP stats since we don't
1229 	 * have them per-node and thus per-lruvec. Careful if memcg is
1230 	 * runtime-disabled: we can get sc->memcg == NULL, which is ok
1231 	 * for the lruvec, but not for memcg_page_state().
1232 	 *
1233 	 * Without memcg, use the zswap pool-wide metrics.
1234 	 */
1235 	if (!mem_cgroup_disabled()) {
1236 		mem_cgroup_flush_stats(memcg);
1237 		nr_backing = memcg_page_state(memcg, MEMCG_ZSWAP_B) >> PAGE_SHIFT;
1238 		nr_stored = memcg_page_state(memcg, MEMCG_ZSWAPPED);
1239 	} else {
1240 		nr_backing = zswap_total_pages();
1241 		nr_stored = atomic_long_read(&zswap_stored_pages);
1242 	}
1243 
1244 	if (!nr_stored)
1245 		return 0;
1246 
1247 	nr_freeable = list_lru_shrink_count(&zswap_list_lru, sc);
1248 	if (!nr_freeable)
1249 		return 0;
1250 
1251 	/*
1252 	 * Subtract from the lru size the number of pages that are recently swapped
1253 	 * in from disk. The idea is that had we protect the zswap's LRU by this
1254 	 * amount of pages, these disk swapins would not have happened.
1255 	 */
1256 	nr_disk_swapins_cur = atomic_long_read(nr_disk_swapins);
1257 	do {
1258 		if (nr_freeable >= nr_disk_swapins_cur)
1259 			nr_remain = 0;
1260 		else
1261 			nr_remain = nr_disk_swapins_cur - nr_freeable;
1262 	} while (!atomic_long_try_cmpxchg(
1263 		nr_disk_swapins, &nr_disk_swapins_cur, nr_remain));
1264 
1265 	nr_freeable -= nr_disk_swapins_cur - nr_remain;
1266 	if (!nr_freeable)
1267 		return 0;
1268 
1269 	/*
1270 	 * Scale the number of freeable pages by the memory saving factor.
1271 	 * This ensures that the better zswap compresses memory, the fewer
1272 	 * pages we will evict to swap (as it will otherwise incur IO for
1273 	 * relatively small memory saving).
1274 	 */
1275 	return mult_frac(nr_freeable, nr_backing, nr_stored);
1276 }
1277 
1278 static struct shrinker *zswap_alloc_shrinker(void)
1279 {
1280 	struct shrinker *shrinker;
1281 
1282 	shrinker =
1283 		shrinker_alloc(SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE, "mm-zswap");
1284 	if (!shrinker)
1285 		return NULL;
1286 
1287 	shrinker->scan_objects = zswap_shrinker_scan;
1288 	shrinker->count_objects = zswap_shrinker_count;
1289 	shrinker->batch = 0;
1290 	shrinker->seeks = DEFAULT_SEEKS;
1291 	return shrinker;
1292 }
1293 
1294 static int shrink_memcg(struct mem_cgroup *memcg)
1295 {
1296 	int nid, shrunk = 0, scanned = 0;
1297 
1298 	if (!mem_cgroup_zswap_writeback_enabled(memcg))
1299 		return -ENOENT;
1300 
1301 	/*
1302 	 * Skip zombies because their LRUs are reparented and we would be
1303 	 * reclaiming from the parent instead of the dead memcg.
1304 	 */
1305 	if (memcg && !mem_cgroup_online(memcg))
1306 		return -ENOENT;
1307 
1308 	for_each_node_state(nid, N_NORMAL_MEMORY) {
1309 		unsigned long nr_to_walk = 1;
1310 
1311 		shrunk += list_lru_walk_one(&zswap_list_lru, nid, memcg,
1312 					    &shrink_memcg_cb, NULL, &nr_to_walk);
1313 		scanned += 1 - nr_to_walk;
1314 	}
1315 
1316 	if (!scanned)
1317 		return -ENOENT;
1318 
1319 	return shrunk ? 0 : -EAGAIN;
1320 }
1321 
1322 static void shrink_worker(struct work_struct *w)
1323 {
1324 	struct mem_cgroup *memcg;
1325 	int ret, failures = 0, attempts = 0;
1326 	unsigned long thr;
1327 
1328 	/* Reclaim down to the accept threshold */
1329 	thr = zswap_accept_thr_pages();
1330 
1331 	/*
1332 	 * Global reclaim will select cgroup in a round-robin fashion from all
1333 	 * online memcgs, but memcgs that have no pages in zswap and
1334 	 * writeback-disabled memcgs (memory.zswap.writeback=0) are not
1335 	 * candidates for shrinking.
1336 	 *
1337 	 * Shrinking will be aborted if we encounter the following
1338 	 * MAX_RECLAIM_RETRIES times:
1339 	 * - No writeback-candidate memcgs found in a memcg tree walk.
1340 	 * - Shrinking a writeback-candidate memcg failed.
1341 	 *
1342 	 * We save iteration cursor memcg into zswap_next_shrink,
1343 	 * which can be modified by the offline memcg cleaner
1344 	 * zswap_memcg_offline_cleanup().
1345 	 *
1346 	 * Since the offline cleaner is called only once, we cannot leave an
1347 	 * offline memcg reference in zswap_next_shrink.
1348 	 * We can rely on the cleaner only if we get online memcg under lock.
1349 	 *
1350 	 * If we get an offline memcg, we cannot determine if the cleaner has
1351 	 * already been called or will be called later. We must put back the
1352 	 * reference before returning from this function. Otherwise, the
1353 	 * offline memcg left in zswap_next_shrink will hold the reference
1354 	 * until the next run of shrink_worker().
1355 	 */
1356 	do {
1357 		/*
1358 		 * Start shrinking from the next memcg after zswap_next_shrink.
1359 		 * When the offline cleaner has already advanced the cursor,
1360 		 * advancing the cursor here overlooks one memcg, but this
1361 		 * should be negligibly rare.
1362 		 *
1363 		 * If we get an online memcg, keep the extra reference in case
1364 		 * the original one obtained by mem_cgroup_iter() is dropped by
1365 		 * zswap_memcg_offline_cleanup() while we are shrinking the
1366 		 * memcg.
1367 		 */
1368 		spin_lock(&zswap_shrink_lock);
1369 		do {
1370 			memcg = mem_cgroup_iter(NULL, zswap_next_shrink, NULL);
1371 			zswap_next_shrink = memcg;
1372 		} while (memcg && !mem_cgroup_tryget_online(memcg));
1373 		spin_unlock(&zswap_shrink_lock);
1374 
1375 		if (!memcg) {
1376 			/*
1377 			 * Continue shrinking without incrementing failures if
1378 			 * we found candidate memcgs in the last tree walk.
1379 			 */
1380 			if (!attempts && ++failures == MAX_RECLAIM_RETRIES)
1381 				break;
1382 
1383 			attempts = 0;
1384 			goto resched;
1385 		}
1386 
1387 		ret = shrink_memcg(memcg);
1388 		/* drop the extra reference */
1389 		mem_cgroup_put(memcg);
1390 
1391 		/*
1392 		 * There are no writeback-candidate pages in the memcg.
1393 		 * This is not an issue as long as we can find another memcg
1394 		 * with pages in zswap. Skip this without incrementing attempts
1395 		 * and failures.
1396 		 */
1397 		if (ret == -ENOENT)
1398 			continue;
1399 		++attempts;
1400 
1401 		if (ret && ++failures == MAX_RECLAIM_RETRIES)
1402 			break;
1403 resched:
1404 		cond_resched();
1405 	} while (zswap_total_pages() > thr);
1406 }
1407 
1408 /*********************************
1409 * main API
1410 **********************************/
1411 
1412 static bool zswap_store_page(struct page *page,
1413 			     struct obj_cgroup *objcg,
1414 			     struct zswap_pool *pool)
1415 {
1416 	swp_entry_t page_swpentry = page_swap_entry(page);
1417 	struct zswap_entry *entry, *old;
1418 
1419 	/* allocate entry */
1420 	entry = zswap_entry_cache_alloc(GFP_KERNEL, page_to_nid(page));
1421 	if (!entry) {
1422 		zswap_reject_kmemcache_fail++;
1423 		return false;
1424 	}
1425 
1426 	if (!zswap_compress(page, entry, pool))
1427 		goto compress_failed;
1428 
1429 	old = xa_store(swap_zswap_tree(page_swpentry),
1430 		       swp_offset(page_swpentry),
1431 		       entry, GFP_KERNEL);
1432 	if (xa_is_err(old)) {
1433 		int err = xa_err(old);
1434 
1435 		WARN_ONCE(err != -ENOMEM, "unexpected xarray error: %d\n", err);
1436 		zswap_reject_alloc_fail++;
1437 		goto store_failed;
1438 	}
1439 
1440 	/*
1441 	 * We may have had an existing entry that became stale when
1442 	 * the folio was redirtied and now the new version is being
1443 	 * swapped out. Get rid of the old.
1444 	 */
1445 	if (old)
1446 		zswap_entry_free(old);
1447 
1448 	/*
1449 	 * The entry is successfully compressed and stored in the tree, there is
1450 	 * no further possibility of failure. Grab refs to the pool and objcg,
1451 	 * charge zswap memory, and increment zswap_stored_pages.
1452 	 * The opposite actions will be performed by zswap_entry_free()
1453 	 * when the entry is removed from the tree.
1454 	 */
1455 	zswap_pool_get(pool);
1456 	if (objcg) {
1457 		obj_cgroup_get(objcg);
1458 		obj_cgroup_charge_zswap(objcg, entry->length);
1459 	}
1460 	atomic_long_inc(&zswap_stored_pages);
1461 	if (entry->length == PAGE_SIZE)
1462 		atomic_long_inc(&zswap_stored_incompressible_pages);
1463 
1464 	/*
1465 	 * We finish initializing the entry while it's already in xarray.
1466 	 * This is safe because:
1467 	 *
1468 	 * 1. Concurrent stores and invalidations are excluded by folio lock.
1469 	 *
1470 	 * 2. Writeback is excluded by the entry not being on the LRU yet.
1471 	 *    The publishing order matters to prevent writeback from seeing
1472 	 *    an incoherent entry.
1473 	 */
1474 	entry->pool = pool;
1475 	entry->swpentry = page_swpentry;
1476 	entry->objcg = objcg;
1477 	entry->referenced = true;
1478 	if (entry->length) {
1479 		INIT_LIST_HEAD(&entry->lru);
1480 		zswap_lru_add(&zswap_list_lru, entry);
1481 	}
1482 
1483 	return true;
1484 
1485 store_failed:
1486 	zs_free(pool->zs_pool, entry->handle);
1487 compress_failed:
1488 	zswap_entry_cache_free(entry);
1489 	return false;
1490 }
1491 
1492 bool zswap_store(struct folio *folio)
1493 {
1494 	long nr_pages = folio_nr_pages(folio);
1495 	swp_entry_t swp = folio->swap;
1496 	struct obj_cgroup *objcg = NULL;
1497 	struct mem_cgroup *memcg = NULL;
1498 	struct zswap_pool *pool;
1499 	bool ret = false;
1500 	long index;
1501 
1502 	VM_WARN_ON_ONCE(!folio_test_locked(folio));
1503 	VM_WARN_ON_ONCE(!folio_test_swapcache(folio));
1504 
1505 	if (!zswap_enabled)
1506 		goto check_old;
1507 
1508 	objcg = get_obj_cgroup_from_folio(folio);
1509 	if (objcg && !obj_cgroup_may_zswap(objcg)) {
1510 		memcg = get_mem_cgroup_from_objcg(objcg);
1511 		if (shrink_memcg(memcg)) {
1512 			mem_cgroup_put(memcg);
1513 			goto put_objcg;
1514 		}
1515 		mem_cgroup_put(memcg);
1516 	}
1517 
1518 	if (zswap_check_limits())
1519 		goto put_objcg;
1520 
1521 	pool = zswap_pool_current_get();
1522 	if (!pool)
1523 		goto put_objcg;
1524 
1525 	if (objcg) {
1526 		memcg = get_mem_cgroup_from_objcg(objcg);
1527 		if (memcg_list_lru_alloc(memcg, &zswap_list_lru, GFP_KERNEL)) {
1528 			mem_cgroup_put(memcg);
1529 			goto put_pool;
1530 		}
1531 		mem_cgroup_put(memcg);
1532 	}
1533 
1534 	for (index = 0; index < nr_pages; ++index) {
1535 		struct page *page = folio_page(folio, index);
1536 
1537 		if (!zswap_store_page(page, objcg, pool))
1538 			goto put_pool;
1539 	}
1540 
1541 	if (objcg)
1542 		count_objcg_events(objcg, ZSWPOUT, nr_pages);
1543 
1544 	count_vm_events(ZSWPOUT, nr_pages);
1545 
1546 	ret = true;
1547 
1548 put_pool:
1549 	zswap_pool_put(pool);
1550 put_objcg:
1551 	obj_cgroup_put(objcg);
1552 	if (!ret && zswap_pool_reached_full)
1553 		queue_work(shrink_wq, &zswap_shrink_work);
1554 check_old:
1555 	/*
1556 	 * If the zswap store fails or zswap is disabled, we must invalidate
1557 	 * the possibly stale entries which were previously stored at the
1558 	 * offsets corresponding to each page of the folio. Otherwise,
1559 	 * writeback could overwrite the new data in the swapfile.
1560 	 */
1561 	if (!ret) {
1562 		unsigned type = swp_type(swp);
1563 		pgoff_t offset = swp_offset(swp);
1564 		struct zswap_entry *entry;
1565 		struct xarray *tree;
1566 
1567 		for (index = 0; index < nr_pages; ++index) {
1568 			tree = swap_zswap_tree(swp_entry(type, offset + index));
1569 			entry = xa_erase(tree, offset + index);
1570 			if (entry)
1571 				zswap_entry_free(entry);
1572 		}
1573 	}
1574 
1575 	return ret;
1576 }
1577 
1578 /**
1579  * zswap_load() - load a folio from zswap
1580  * @folio: folio to load
1581  *
1582  * Return: 0 on success, with the folio unlocked and marked up-to-date, or one
1583  * of the following error codes:
1584  *
1585  *  -EIO: if the swapped out content was in zswap, but could not be loaded
1586  *  into the page due to a decompression failure. The folio is unlocked, but
1587  *  NOT marked up-to-date, so that an IO error is emitted (e.g. do_swap_page()
1588  *  will SIGBUS).
1589  *
1590  *  -EINVAL: if the swapped out content was in zswap, but the page belongs
1591  *  to a large folio, which is not supported by zswap. The folio is unlocked,
1592  *  but NOT marked up-to-date, so that an IO error is emitted (e.g.
1593  *  do_swap_page() will SIGBUS).
1594  *
1595  *  -ENOENT: if the swapped out content was not in zswap. The folio remains
1596  *  locked on return.
1597  */
1598 int zswap_load(struct folio *folio)
1599 {
1600 	swp_entry_t swp = folio->swap;
1601 	pgoff_t offset = swp_offset(swp);
1602 	bool swapcache = folio_test_swapcache(folio);
1603 	struct xarray *tree = swap_zswap_tree(swp);
1604 	struct zswap_entry *entry;
1605 
1606 	VM_WARN_ON_ONCE(!folio_test_locked(folio));
1607 
1608 	if (zswap_never_enabled())
1609 		return -ENOENT;
1610 
1611 	/*
1612 	 * Large folios should not be swapped in while zswap is being used, as
1613 	 * they are not properly handled. Zswap does not properly load large
1614 	 * folios, and a large folio may only be partially in zswap.
1615 	 */
1616 	if (WARN_ON_ONCE(folio_test_large(folio))) {
1617 		folio_unlock(folio);
1618 		return -EINVAL;
1619 	}
1620 
1621 	entry = xa_load(tree, offset);
1622 	if (!entry)
1623 		return -ENOENT;
1624 
1625 	if (!zswap_decompress(entry, folio)) {
1626 		folio_unlock(folio);
1627 		return -EIO;
1628 	}
1629 
1630 	folio_mark_uptodate(folio);
1631 
1632 	count_vm_event(ZSWPIN);
1633 	if (entry->objcg)
1634 		count_objcg_events(entry->objcg, ZSWPIN, 1);
1635 
1636 	/*
1637 	 * When reading into the swapcache, invalidate our entry. The
1638 	 * swapcache can be the authoritative owner of the page and
1639 	 * its mappings, and the pressure that results from having two
1640 	 * in-memory copies outweighs any benefits of caching the
1641 	 * compression work.
1642 	 *
1643 	 * (Most swapins go through the swapcache. The notable
1644 	 * exception is the singleton fault on SWP_SYNCHRONOUS_IO
1645 	 * files, which reads into a private page and may free it if
1646 	 * the fault fails. We remain the primary owner of the entry.)
1647 	 */
1648 	if (swapcache) {
1649 		folio_mark_dirty(folio);
1650 		xa_erase(tree, offset);
1651 		zswap_entry_free(entry);
1652 	}
1653 
1654 	folio_unlock(folio);
1655 	return 0;
1656 }
1657 
1658 void zswap_invalidate(swp_entry_t swp)
1659 {
1660 	pgoff_t offset = swp_offset(swp);
1661 	struct xarray *tree = swap_zswap_tree(swp);
1662 	struct zswap_entry *entry;
1663 
1664 	if (xa_empty(tree))
1665 		return;
1666 
1667 	entry = xa_erase(tree, offset);
1668 	if (entry)
1669 		zswap_entry_free(entry);
1670 }
1671 
1672 int zswap_swapon(int type, unsigned long nr_pages)
1673 {
1674 	struct xarray *trees, *tree;
1675 	unsigned int nr, i;
1676 
1677 	nr = DIV_ROUND_UP(nr_pages, SWAP_ADDRESS_SPACE_PAGES);
1678 	trees = kvcalloc(nr, sizeof(*tree), GFP_KERNEL);
1679 	if (!trees) {
1680 		pr_err("alloc failed, zswap disabled for swap type %d\n", type);
1681 		return -ENOMEM;
1682 	}
1683 
1684 	for (i = 0; i < nr; i++)
1685 		xa_init(trees + i);
1686 
1687 	nr_zswap_trees[type] = nr;
1688 	zswap_trees[type] = trees;
1689 	return 0;
1690 }
1691 
1692 void zswap_swapoff(int type)
1693 {
1694 	struct xarray *trees = zswap_trees[type];
1695 	unsigned int i;
1696 
1697 	if (!trees)
1698 		return;
1699 
1700 	/* try_to_unuse() invalidated all the entries already */
1701 	for (i = 0; i < nr_zswap_trees[type]; i++)
1702 		WARN_ON_ONCE(!xa_empty(trees + i));
1703 
1704 	kvfree(trees);
1705 	nr_zswap_trees[type] = 0;
1706 	zswap_trees[type] = NULL;
1707 }
1708 
1709 /*********************************
1710 * debugfs functions
1711 **********************************/
1712 #ifdef CONFIG_DEBUG_FS
1713 #include <linux/debugfs.h>
1714 
1715 static struct dentry *zswap_debugfs_root;
1716 
1717 static int debugfs_get_total_size(void *data, u64 *val)
1718 {
1719 	*val = zswap_total_pages() * PAGE_SIZE;
1720 	return 0;
1721 }
1722 DEFINE_DEBUGFS_ATTRIBUTE(total_size_fops, debugfs_get_total_size, NULL, "%llu\n");
1723 
1724 static int debugfs_get_stored_pages(void *data, u64 *val)
1725 {
1726 	*val = atomic_long_read(&zswap_stored_pages);
1727 	return 0;
1728 }
1729 DEFINE_DEBUGFS_ATTRIBUTE(stored_pages_fops, debugfs_get_stored_pages, NULL, "%llu\n");
1730 
1731 static int debugfs_get_stored_incompressible_pages(void *data, u64 *val)
1732 {
1733 	*val = atomic_long_read(&zswap_stored_incompressible_pages);
1734 	return 0;
1735 }
1736 DEFINE_DEBUGFS_ATTRIBUTE(stored_incompressible_pages_fops,
1737 		debugfs_get_stored_incompressible_pages, NULL, "%llu\n");
1738 
1739 static int zswap_debugfs_init(void)
1740 {
1741 	if (!debugfs_initialized())
1742 		return -ENODEV;
1743 
1744 	zswap_debugfs_root = debugfs_create_dir("zswap", NULL);
1745 
1746 	debugfs_create_u64("pool_limit_hit", 0444,
1747 			   zswap_debugfs_root, &zswap_pool_limit_hit);
1748 	debugfs_create_u64("reject_reclaim_fail", 0444,
1749 			   zswap_debugfs_root, &zswap_reject_reclaim_fail);
1750 	debugfs_create_u64("reject_alloc_fail", 0444,
1751 			   zswap_debugfs_root, &zswap_reject_alloc_fail);
1752 	debugfs_create_u64("reject_kmemcache_fail", 0444,
1753 			   zswap_debugfs_root, &zswap_reject_kmemcache_fail);
1754 	debugfs_create_u64("reject_compress_fail", 0444,
1755 			   zswap_debugfs_root, &zswap_reject_compress_fail);
1756 	debugfs_create_u64("reject_compress_poor", 0444,
1757 			   zswap_debugfs_root, &zswap_reject_compress_poor);
1758 	debugfs_create_u64("decompress_fail", 0444,
1759 			   zswap_debugfs_root, &zswap_decompress_fail);
1760 	debugfs_create_u64("written_back_pages", 0444,
1761 			   zswap_debugfs_root, &zswap_written_back_pages);
1762 	debugfs_create_file("pool_total_size", 0444,
1763 			    zswap_debugfs_root, NULL, &total_size_fops);
1764 	debugfs_create_file("stored_pages", 0444,
1765 			    zswap_debugfs_root, NULL, &stored_pages_fops);
1766 	debugfs_create_file("stored_incompressible_pages", 0444,
1767 			    zswap_debugfs_root, NULL,
1768 			    &stored_incompressible_pages_fops);
1769 
1770 	return 0;
1771 }
1772 #else
1773 static int zswap_debugfs_init(void)
1774 {
1775 	return 0;
1776 }
1777 #endif
1778 
1779 /*********************************
1780 * module init and exit
1781 **********************************/
1782 static int zswap_setup(void)
1783 {
1784 	struct zswap_pool *pool;
1785 	int ret;
1786 
1787 	zswap_entry_cache = KMEM_CACHE(zswap_entry, 0);
1788 	if (!zswap_entry_cache) {
1789 		pr_err("entry cache creation failed\n");
1790 		goto cache_fail;
1791 	}
1792 
1793 	ret = cpuhp_setup_state_multi(CPUHP_MM_ZSWP_POOL_PREPARE,
1794 				      "mm/zswap_pool:prepare",
1795 				      zswap_cpu_comp_prepare,
1796 				      zswap_cpu_comp_dead);
1797 	if (ret)
1798 		goto hp_fail;
1799 
1800 	shrink_wq = alloc_workqueue("zswap-shrink",
1801 			WQ_UNBOUND|WQ_MEM_RECLAIM, 1);
1802 	if (!shrink_wq)
1803 		goto shrink_wq_fail;
1804 
1805 	zswap_shrinker = zswap_alloc_shrinker();
1806 	if (!zswap_shrinker)
1807 		goto shrinker_fail;
1808 	if (list_lru_init_memcg(&zswap_list_lru, zswap_shrinker))
1809 		goto lru_fail;
1810 	shrinker_register(zswap_shrinker);
1811 
1812 	INIT_WORK(&zswap_shrink_work, shrink_worker);
1813 
1814 	pool = __zswap_pool_create_fallback();
1815 	if (pool) {
1816 		pr_info("loaded using pool %s\n", pool->tfm_name);
1817 		list_add(&pool->list, &zswap_pools);
1818 		zswap_has_pool = true;
1819 		static_branch_enable(&zswap_ever_enabled);
1820 	} else {
1821 		pr_err("pool creation failed\n");
1822 		zswap_enabled = false;
1823 	}
1824 
1825 	if (zswap_debugfs_init())
1826 		pr_warn("debugfs initialization failed\n");
1827 	zswap_init_state = ZSWAP_INIT_SUCCEED;
1828 	return 0;
1829 
1830 lru_fail:
1831 	shrinker_free(zswap_shrinker);
1832 shrinker_fail:
1833 	destroy_workqueue(shrink_wq);
1834 shrink_wq_fail:
1835 	cpuhp_remove_multi_state(CPUHP_MM_ZSWP_POOL_PREPARE);
1836 hp_fail:
1837 	kmem_cache_destroy(zswap_entry_cache);
1838 cache_fail:
1839 	/* if built-in, we aren't unloaded on failure; don't allow use */
1840 	zswap_init_state = ZSWAP_INIT_FAILED;
1841 	zswap_enabled = false;
1842 	return -ENOMEM;
1843 }
1844 
1845 static int __init zswap_init(void)
1846 {
1847 	if (!zswap_enabled)
1848 		return 0;
1849 	return zswap_setup();
1850 }
1851 /* must be late so crypto has time to come up */
1852 late_initcall(zswap_init);
1853 
1854 MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
1855 MODULE_DESCRIPTION("Compressed cache for swap pages");
1856