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