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