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