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 red-black tree
179 * length - the length in bytes of the compressed page data. Needed during
180 * decompression.
181 * referenced - true if the entry recently entered the zswap pool. Unset by the
182 * writeback logic. The entry is only reclaimed by the writeback
183 * logic if referenced is unset. See comments in the shrinker
184 * section for context.
185 * pool - the zswap_pool the entry's data is in
186 * handle - zsmalloc allocation handle that stores the compressed page data
187 * objcg - the obj_cgroup that the compressed memory is charged to
188 * lru - handle to the pool's lru used to evict pages.
189 */
190 struct zswap_entry {
191 swp_entry_t swpentry;
192 unsigned int length;
193 bool referenced;
194 struct zswap_pool *pool;
195 unsigned long handle;
196 struct obj_cgroup *objcg;
197 struct list_head lru;
198 };
199
200 static struct xarray *zswap_trees[MAX_SWAPFILES];
201 static unsigned int nr_zswap_trees[MAX_SWAPFILES];
202
203 /* RCU-protected iteration */
204 static LIST_HEAD(zswap_pools);
205 /* protects zswap_pools list modification */
206 static DEFINE_SPINLOCK(zswap_pools_lock);
207 /* pool counter to provide unique names to zsmalloc */
208 static atomic_t zswap_pools_count = ATOMIC_INIT(0);
209
210 enum zswap_init_type {
211 ZSWAP_UNINIT,
212 ZSWAP_INIT_SUCCEED,
213 ZSWAP_INIT_FAILED
214 };
215
216 static enum zswap_init_type zswap_init_state;
217
218 /* used to ensure the integrity of initialization */
219 static DEFINE_MUTEX(zswap_init_lock);
220
221 /* init completed, but couldn't create the initial pool */
222 static bool zswap_has_pool;
223
224 /*********************************
225 * helpers and fwd declarations
226 **********************************/
227
228 /* 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 zwap.
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 dlen = PAGE_SIZE;
898 if (!mem_cgroup_zswap_writeback_enabled(
899 folio_memcg(page_folio(page)))) {
900 comp_ret = comp_ret ? comp_ret : -EINVAL;
901 goto unlock;
902 }
903 comp_ret = 0;
904 dlen = PAGE_SIZE;
905 dst = kmap_local_page(page);
906 mapped = true;
907 }
908
909 gfp = GFP_NOWAIT | __GFP_NORETRY | __GFP_HIGHMEM | __GFP_MOVABLE;
910 handle = zs_malloc(pool->zs_pool, dlen, gfp, page_to_nid(page));
911 if (IS_ERR_VALUE(handle)) {
912 alloc_ret = PTR_ERR((void *)handle);
913 goto unlock;
914 }
915
916 zs_obj_write(pool->zs_pool, handle, dst, dlen);
917 entry->handle = handle;
918 entry->length = dlen;
919
920 unlock:
921 if (mapped)
922 kunmap_local(dst);
923 if (comp_ret == -ENOSPC || alloc_ret == -ENOSPC)
924 zswap_reject_compress_poor++;
925 else if (comp_ret)
926 zswap_reject_compress_fail++;
927 else if (alloc_ret)
928 zswap_reject_alloc_fail++;
929
930 acomp_ctx_put_unlock(acomp_ctx);
931 return comp_ret == 0 && alloc_ret == 0;
932 }
933
zswap_decompress(struct zswap_entry * entry,struct folio * folio)934 static bool zswap_decompress(struct zswap_entry *entry, struct folio *folio)
935 {
936 struct zswap_pool *pool = entry->pool;
937 struct scatterlist input, output;
938 struct crypto_acomp_ctx *acomp_ctx;
939 int decomp_ret = 0, dlen = PAGE_SIZE;
940 u8 *src, *obj;
941
942 acomp_ctx = acomp_ctx_get_cpu_lock(pool);
943 obj = zs_obj_read_begin(pool->zs_pool, entry->handle, acomp_ctx->buffer);
944
945 /* zswap entries of length PAGE_SIZE are not compressed. */
946 if (entry->length == PAGE_SIZE) {
947 memcpy_to_folio(folio, 0, obj, entry->length);
948 goto read_done;
949 }
950
951 /*
952 * zs_obj_read_begin() might return a kmap address of highmem when
953 * acomp_ctx->buffer is not used. However, sg_init_one() does not
954 * handle highmem addresses, so copy the object to acomp_ctx->buffer.
955 */
956 if (virt_addr_valid(obj)) {
957 src = obj;
958 } else {
959 WARN_ON_ONCE(obj == acomp_ctx->buffer);
960 memcpy(acomp_ctx->buffer, obj, entry->length);
961 src = acomp_ctx->buffer;
962 }
963
964 sg_init_one(&input, src, entry->length);
965 sg_init_table(&output, 1);
966 sg_set_folio(&output, folio, PAGE_SIZE, 0);
967 acomp_request_set_params(acomp_ctx->req, &input, &output, entry->length, PAGE_SIZE);
968 decomp_ret = crypto_wait_req(crypto_acomp_decompress(acomp_ctx->req), &acomp_ctx->wait);
969 dlen = acomp_ctx->req->dlen;
970
971 read_done:
972 zs_obj_read_end(pool->zs_pool, entry->handle, obj);
973 acomp_ctx_put_unlock(acomp_ctx);
974
975 if (!decomp_ret && dlen == PAGE_SIZE)
976 return true;
977
978 zswap_decompress_fail++;
979 pr_alert_ratelimited("Decompression error from zswap (%d:%lu %s %u->%d)\n",
980 swp_type(entry->swpentry),
981 swp_offset(entry->swpentry),
982 entry->pool->tfm_name, entry->length, dlen);
983 return false;
984 }
985
986 /*********************************
987 * writeback code
988 **********************************/
989 /*
990 * Attempts to free an entry by adding a folio to the swap cache,
991 * decompressing the entry data into the folio, and issuing a
992 * bio write to write the folio back to the swap device.
993 *
994 * This can be thought of as a "resumed writeback" of the folio
995 * to the swap device. We are basically resuming the same swap
996 * writeback path that was intercepted with the zswap_store()
997 * in the first place. After the folio has been decompressed into
998 * the swap cache, the compressed version stored by zswap can be
999 * freed.
1000 */
zswap_writeback_entry(struct zswap_entry * entry,swp_entry_t swpentry)1001 static int zswap_writeback_entry(struct zswap_entry *entry,
1002 swp_entry_t swpentry)
1003 {
1004 struct xarray *tree;
1005 pgoff_t offset = swp_offset(swpentry);
1006 struct folio *folio;
1007 struct mempolicy *mpol;
1008 bool folio_was_allocated;
1009 struct swap_info_struct *si;
1010 int ret = 0;
1011
1012 /* try to allocate swap cache folio */
1013 si = get_swap_device(swpentry);
1014 if (!si)
1015 return -EEXIST;
1016
1017 mpol = get_task_policy(current);
1018 folio = __read_swap_cache_async(swpentry, GFP_KERNEL, mpol,
1019 NO_INTERLEAVE_INDEX, &folio_was_allocated, true);
1020 put_swap_device(si);
1021 if (!folio)
1022 return -ENOMEM;
1023
1024 /*
1025 * Found an existing folio, we raced with swapin or concurrent
1026 * shrinker. We generally writeback cold folios from zswap, and
1027 * swapin means the folio just became hot, so skip this folio.
1028 * For unlikely concurrent shrinker case, it will be unlinked
1029 * and freed when invalidated by the concurrent shrinker anyway.
1030 */
1031 if (!folio_was_allocated) {
1032 ret = -EEXIST;
1033 goto out;
1034 }
1035
1036 /*
1037 * folio is locked, and the swapcache is now secured against
1038 * concurrent swapping to and from the slot, and concurrent
1039 * swapoff so we can safely dereference the zswap tree here.
1040 * Verify that the swap entry hasn't been invalidated and recycled
1041 * behind our backs, to avoid overwriting a new swap folio with
1042 * old compressed data. Only when this is successful can the entry
1043 * be dereferenced.
1044 */
1045 tree = swap_zswap_tree(swpentry);
1046 if (entry != xa_load(tree, offset)) {
1047 ret = -ENOMEM;
1048 goto out;
1049 }
1050
1051 if (!zswap_decompress(entry, folio)) {
1052 ret = -EIO;
1053 goto out;
1054 }
1055
1056 xa_erase(tree, offset);
1057
1058 count_vm_event(ZSWPWB);
1059 if (entry->objcg)
1060 count_objcg_events(entry->objcg, ZSWPWB, 1);
1061
1062 zswap_entry_free(entry);
1063
1064 /* folio is up to date */
1065 folio_mark_uptodate(folio);
1066
1067 /* move it to the tail of the inactive list after end_writeback */
1068 folio_set_reclaim(folio);
1069
1070 /* start writeback */
1071 __swap_writepage(folio, NULL);
1072
1073 out:
1074 if (ret && ret != -EEXIST) {
1075 swap_cache_del_folio(folio);
1076 folio_unlock(folio);
1077 }
1078 folio_put(folio);
1079 return ret;
1080 }
1081
1082 /*********************************
1083 * shrinker functions
1084 **********************************/
1085 /*
1086 * The dynamic shrinker is modulated by the following factors:
1087 *
1088 * 1. Each zswap entry has a referenced bit, which the shrinker unsets (giving
1089 * the entry a second chance) before rotating it in the LRU list. If the
1090 * entry is considered again by the shrinker, with its referenced bit unset,
1091 * it is written back. The writeback rate as a result is dynamically
1092 * adjusted by the pool activities - if the pool is dominated by new entries
1093 * (i.e lots of recent zswapouts), these entries will be protected and
1094 * the writeback rate will slow down. On the other hand, if the pool has a
1095 * lot of stagnant entries, these entries will be reclaimed immediately,
1096 * effectively increasing the writeback rate.
1097 *
1098 * 2. Swapins counter: If we observe swapins, it is a sign that we are
1099 * overshrinking and should slow down. We maintain a swapins counter, which
1100 * is consumed and subtract from the number of eligible objects on the LRU
1101 * in zswap_shrinker_count().
1102 *
1103 * 3. Compression ratio. The better the workload compresses, the less gains we
1104 * can expect from writeback. We scale down the number of objects available
1105 * for reclaim by this ratio.
1106 */
shrink_memcg_cb(struct list_head * item,struct list_lru_one * l,void * arg)1107 static enum lru_status shrink_memcg_cb(struct list_head *item, struct list_lru_one *l,
1108 void *arg)
1109 {
1110 struct zswap_entry *entry = container_of(item, struct zswap_entry, lru);
1111 bool *encountered_page_in_swapcache = (bool *)arg;
1112 swp_entry_t swpentry;
1113 enum lru_status ret = LRU_REMOVED_RETRY;
1114 int writeback_result;
1115
1116 /*
1117 * Second chance algorithm: if the entry has its referenced bit set, give it
1118 * a second chance. Only clear the referenced bit and rotate it in the
1119 * zswap's LRU list.
1120 */
1121 if (entry->referenced) {
1122 entry->referenced = false;
1123 return LRU_ROTATE;
1124 }
1125
1126 /*
1127 * As soon as we drop the LRU lock, the entry can be freed by
1128 * a concurrent invalidation. This means the following:
1129 *
1130 * 1. We extract the swp_entry_t to the stack, allowing
1131 * zswap_writeback_entry() to pin the swap entry and
1132 * then validate the zwap entry against that swap entry's
1133 * tree using pointer value comparison. Only when that
1134 * is successful can the entry be dereferenced.
1135 *
1136 * 2. Usually, objects are taken off the LRU for reclaim. In
1137 * this case this isn't possible, because if reclaim fails
1138 * for whatever reason, we have no means of knowing if the
1139 * entry is alive to put it back on the LRU.
1140 *
1141 * So rotate it before dropping the lock. If the entry is
1142 * written back or invalidated, the free path will unlink
1143 * it. For failures, rotation is the right thing as well.
1144 *
1145 * Temporary failures, where the same entry should be tried
1146 * again immediately, almost never happen for this shrinker.
1147 * We don't do any trylocking; -ENOMEM comes closest,
1148 * but that's extremely rare and doesn't happen spuriously
1149 * either. Don't bother distinguishing this case.
1150 */
1151 list_move_tail(item, &l->list);
1152
1153 /*
1154 * Once the lru lock is dropped, the entry might get freed. The
1155 * swpentry is copied to the stack, and entry isn't deref'd again
1156 * until the entry is verified to still be alive in the tree.
1157 */
1158 swpentry = entry->swpentry;
1159
1160 /*
1161 * It's safe to drop the lock here because we return either
1162 * LRU_REMOVED_RETRY, LRU_RETRY or LRU_STOP.
1163 */
1164 spin_unlock(&l->lock);
1165
1166 writeback_result = zswap_writeback_entry(entry, swpentry);
1167
1168 if (writeback_result) {
1169 zswap_reject_reclaim_fail++;
1170 ret = LRU_RETRY;
1171
1172 /*
1173 * Encountering a page already in swap cache is a sign that we are shrinking
1174 * into the warmer region. We should terminate shrinking (if we're in the dynamic
1175 * shrinker context).
1176 */
1177 if (writeback_result == -EEXIST && encountered_page_in_swapcache) {
1178 ret = LRU_STOP;
1179 *encountered_page_in_swapcache = true;
1180 }
1181 } else {
1182 zswap_written_back_pages++;
1183 }
1184
1185 return ret;
1186 }
1187
zswap_shrinker_scan(struct shrinker * shrinker,struct shrink_control * sc)1188 static unsigned long zswap_shrinker_scan(struct shrinker *shrinker,
1189 struct shrink_control *sc)
1190 {
1191 unsigned long shrink_ret;
1192 bool encountered_page_in_swapcache = false;
1193
1194 if (!zswap_shrinker_enabled ||
1195 !mem_cgroup_zswap_writeback_enabled(sc->memcg)) {
1196 sc->nr_scanned = 0;
1197 return SHRINK_STOP;
1198 }
1199
1200 shrink_ret = list_lru_shrink_walk(&zswap_list_lru, sc, &shrink_memcg_cb,
1201 &encountered_page_in_swapcache);
1202
1203 if (encountered_page_in_swapcache)
1204 return SHRINK_STOP;
1205
1206 return shrink_ret ? shrink_ret : SHRINK_STOP;
1207 }
1208
zswap_shrinker_count(struct shrinker * shrinker,struct shrink_control * sc)1209 static unsigned long zswap_shrinker_count(struct shrinker *shrinker,
1210 struct shrink_control *sc)
1211 {
1212 struct mem_cgroup *memcg = sc->memcg;
1213 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(sc->nid));
1214 atomic_long_t *nr_disk_swapins =
1215 &lruvec->zswap_lruvec_state.nr_disk_swapins;
1216 unsigned long nr_backing, nr_stored, nr_freeable, nr_disk_swapins_cur,
1217 nr_remain;
1218
1219 if (!zswap_shrinker_enabled || !mem_cgroup_zswap_writeback_enabled(memcg))
1220 return 0;
1221
1222 /*
1223 * The shrinker resumes swap writeback, which will enter block
1224 * and may enter fs. XXX: Harmonize with vmscan.c __GFP_FS
1225 * rules (may_enter_fs()), which apply on a per-folio basis.
1226 */
1227 if (!gfp_has_io_fs(sc->gfp_mask))
1228 return 0;
1229
1230 /*
1231 * For memcg, use the cgroup-wide ZSWAP stats since we don't
1232 * have them per-node and thus per-lruvec. Careful if memcg is
1233 * runtime-disabled: we can get sc->memcg == NULL, which is ok
1234 * for the lruvec, but not for memcg_page_state().
1235 *
1236 * Without memcg, use the zswap pool-wide metrics.
1237 */
1238 if (!mem_cgroup_disabled()) {
1239 mem_cgroup_flush_stats(memcg);
1240 nr_backing = memcg_page_state(memcg, MEMCG_ZSWAP_B) >> PAGE_SHIFT;
1241 nr_stored = memcg_page_state(memcg, MEMCG_ZSWAPPED);
1242 } else {
1243 nr_backing = zswap_total_pages();
1244 nr_stored = atomic_long_read(&zswap_stored_pages);
1245 }
1246
1247 if (!nr_stored)
1248 return 0;
1249
1250 nr_freeable = list_lru_shrink_count(&zswap_list_lru, sc);
1251 if (!nr_freeable)
1252 return 0;
1253
1254 /*
1255 * Subtract from the lru size the number of pages that are recently swapped
1256 * in from disk. The idea is that had we protect the zswap's LRU by this
1257 * amount of pages, these disk swapins would not have happened.
1258 */
1259 nr_disk_swapins_cur = atomic_long_read(nr_disk_swapins);
1260 do {
1261 if (nr_freeable >= nr_disk_swapins_cur)
1262 nr_remain = 0;
1263 else
1264 nr_remain = nr_disk_swapins_cur - nr_freeable;
1265 } while (!atomic_long_try_cmpxchg(
1266 nr_disk_swapins, &nr_disk_swapins_cur, nr_remain));
1267
1268 nr_freeable -= nr_disk_swapins_cur - nr_remain;
1269 if (!nr_freeable)
1270 return 0;
1271
1272 /*
1273 * Scale the number of freeable pages by the memory saving factor.
1274 * This ensures that the better zswap compresses memory, the fewer
1275 * pages we will evict to swap (as it will otherwise incur IO for
1276 * relatively small memory saving).
1277 */
1278 return mult_frac(nr_freeable, nr_backing, nr_stored);
1279 }
1280
zswap_alloc_shrinker(void)1281 static struct shrinker *zswap_alloc_shrinker(void)
1282 {
1283 struct shrinker *shrinker;
1284
1285 shrinker =
1286 shrinker_alloc(SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE, "mm-zswap");
1287 if (!shrinker)
1288 return NULL;
1289
1290 shrinker->scan_objects = zswap_shrinker_scan;
1291 shrinker->count_objects = zswap_shrinker_count;
1292 shrinker->batch = 0;
1293 shrinker->seeks = DEFAULT_SEEKS;
1294 return shrinker;
1295 }
1296
shrink_memcg(struct mem_cgroup * memcg)1297 static int shrink_memcg(struct mem_cgroup *memcg)
1298 {
1299 int nid, shrunk = 0, scanned = 0;
1300
1301 if (!mem_cgroup_zswap_writeback_enabled(memcg))
1302 return -ENOENT;
1303
1304 /*
1305 * Skip zombies because their LRUs are reparented and we would be
1306 * reclaiming from the parent instead of the dead memcg.
1307 */
1308 if (memcg && !mem_cgroup_online(memcg))
1309 return -ENOENT;
1310
1311 for_each_node_state(nid, N_NORMAL_MEMORY) {
1312 unsigned long nr_to_walk = 1;
1313
1314 shrunk += list_lru_walk_one(&zswap_list_lru, nid, memcg,
1315 &shrink_memcg_cb, NULL, &nr_to_walk);
1316 scanned += 1 - nr_to_walk;
1317 }
1318
1319 if (!scanned)
1320 return -ENOENT;
1321
1322 return shrunk ? 0 : -EAGAIN;
1323 }
1324
shrink_worker(struct work_struct * w)1325 static void shrink_worker(struct work_struct *w)
1326 {
1327 struct mem_cgroup *memcg;
1328 int ret, failures = 0, attempts = 0;
1329 unsigned long thr;
1330
1331 /* Reclaim down to the accept threshold */
1332 thr = zswap_accept_thr_pages();
1333
1334 /*
1335 * Global reclaim will select cgroup in a round-robin fashion from all
1336 * online memcgs, but memcgs that have no pages in zswap and
1337 * writeback-disabled memcgs (memory.zswap.writeback=0) are not
1338 * candidates for shrinking.
1339 *
1340 * Shrinking will be aborted if we encounter the following
1341 * MAX_RECLAIM_RETRIES times:
1342 * - No writeback-candidate memcgs found in a memcg tree walk.
1343 * - Shrinking a writeback-candidate memcg failed.
1344 *
1345 * We save iteration cursor memcg into zswap_next_shrink,
1346 * which can be modified by the offline memcg cleaner
1347 * zswap_memcg_offline_cleanup().
1348 *
1349 * Since the offline cleaner is called only once, we cannot leave an
1350 * offline memcg reference in zswap_next_shrink.
1351 * We can rely on the cleaner only if we get online memcg under lock.
1352 *
1353 * If we get an offline memcg, we cannot determine if the cleaner has
1354 * already been called or will be called later. We must put back the
1355 * reference before returning from this function. Otherwise, the
1356 * offline memcg left in zswap_next_shrink will hold the reference
1357 * until the next run of shrink_worker().
1358 */
1359 do {
1360 /*
1361 * Start shrinking from the next memcg after zswap_next_shrink.
1362 * When the offline cleaner has already advanced the cursor,
1363 * advancing the cursor here overlooks one memcg, but this
1364 * should be negligibly rare.
1365 *
1366 * If we get an online memcg, keep the extra reference in case
1367 * the original one obtained by mem_cgroup_iter() is dropped by
1368 * zswap_memcg_offline_cleanup() while we are shrinking the
1369 * memcg.
1370 */
1371 spin_lock(&zswap_shrink_lock);
1372 do {
1373 memcg = mem_cgroup_iter(NULL, zswap_next_shrink, NULL);
1374 zswap_next_shrink = memcg;
1375 } while (memcg && !mem_cgroup_tryget_online(memcg));
1376 spin_unlock(&zswap_shrink_lock);
1377
1378 if (!memcg) {
1379 /*
1380 * Continue shrinking without incrementing failures if
1381 * we found candidate memcgs in the last tree walk.
1382 */
1383 if (!attempts && ++failures == MAX_RECLAIM_RETRIES)
1384 break;
1385
1386 attempts = 0;
1387 goto resched;
1388 }
1389
1390 ret = shrink_memcg(memcg);
1391 /* drop the extra reference */
1392 mem_cgroup_put(memcg);
1393
1394 /*
1395 * There are no writeback-candidate pages in the memcg.
1396 * This is not an issue as long as we can find another memcg
1397 * with pages in zswap. Skip this without incrementing attempts
1398 * and failures.
1399 */
1400 if (ret == -ENOENT)
1401 continue;
1402 ++attempts;
1403
1404 if (ret && ++failures == MAX_RECLAIM_RETRIES)
1405 break;
1406 resched:
1407 cond_resched();
1408 } while (zswap_total_pages() > thr);
1409 }
1410
1411 /*********************************
1412 * main API
1413 **********************************/
1414
zswap_store_page(struct page * page,struct obj_cgroup * objcg,struct zswap_pool * pool)1415 static bool zswap_store_page(struct page *page,
1416 struct obj_cgroup *objcg,
1417 struct zswap_pool *pool)
1418 {
1419 swp_entry_t page_swpentry = page_swap_entry(page);
1420 struct zswap_entry *entry, *old;
1421
1422 /* allocate entry */
1423 entry = zswap_entry_cache_alloc(GFP_KERNEL, page_to_nid(page));
1424 if (!entry) {
1425 zswap_reject_kmemcache_fail++;
1426 return false;
1427 }
1428
1429 if (!zswap_compress(page, entry, pool))
1430 goto compress_failed;
1431
1432 old = xa_store(swap_zswap_tree(page_swpentry),
1433 swp_offset(page_swpentry),
1434 entry, GFP_KERNEL);
1435 if (xa_is_err(old)) {
1436 int err = xa_err(old);
1437
1438 WARN_ONCE(err != -ENOMEM, "unexpected xarray error: %d\n", err);
1439 zswap_reject_alloc_fail++;
1440 goto store_failed;
1441 }
1442
1443 /*
1444 * We may have had an existing entry that became stale when
1445 * the folio was redirtied and now the new version is being
1446 * swapped out. Get rid of the old.
1447 */
1448 if (old)
1449 zswap_entry_free(old);
1450
1451 /*
1452 * The entry is successfully compressed and stored in the tree, there is
1453 * no further possibility of failure. Grab refs to the pool and objcg,
1454 * charge zswap memory, and increment zswap_stored_pages.
1455 * The opposite actions will be performed by zswap_entry_free()
1456 * when the entry is removed from the tree.
1457 */
1458 zswap_pool_get(pool);
1459 if (objcg) {
1460 obj_cgroup_get(objcg);
1461 obj_cgroup_charge_zswap(objcg, entry->length);
1462 }
1463 atomic_long_inc(&zswap_stored_pages);
1464 if (entry->length == PAGE_SIZE)
1465 atomic_long_inc(&zswap_stored_incompressible_pages);
1466
1467 /*
1468 * We finish initializing the entry while it's already in xarray.
1469 * This is safe because:
1470 *
1471 * 1. Concurrent stores and invalidations are excluded by folio lock.
1472 *
1473 * 2. Writeback is excluded by the entry not being on the LRU yet.
1474 * The publishing order matters to prevent writeback from seeing
1475 * an incoherent entry.
1476 */
1477 entry->pool = pool;
1478 entry->swpentry = page_swpentry;
1479 entry->objcg = objcg;
1480 entry->referenced = true;
1481 if (entry->length) {
1482 INIT_LIST_HEAD(&entry->lru);
1483 zswap_lru_add(&zswap_list_lru, entry);
1484 }
1485
1486 return true;
1487
1488 store_failed:
1489 zs_free(pool->zs_pool, entry->handle);
1490 compress_failed:
1491 zswap_entry_cache_free(entry);
1492 return false;
1493 }
1494
zswap_store(struct folio * folio)1495 bool zswap_store(struct folio *folio)
1496 {
1497 long nr_pages = folio_nr_pages(folio);
1498 swp_entry_t swp = folio->swap;
1499 struct obj_cgroup *objcg = NULL;
1500 struct mem_cgroup *memcg = NULL;
1501 struct zswap_pool *pool;
1502 bool ret = false;
1503 long index;
1504
1505 VM_WARN_ON_ONCE(!folio_test_locked(folio));
1506 VM_WARN_ON_ONCE(!folio_test_swapcache(folio));
1507
1508 if (!zswap_enabled)
1509 goto check_old;
1510
1511 objcg = get_obj_cgroup_from_folio(folio);
1512 if (objcg && !obj_cgroup_may_zswap(objcg)) {
1513 memcg = get_mem_cgroup_from_objcg(objcg);
1514 if (shrink_memcg(memcg)) {
1515 mem_cgroup_put(memcg);
1516 goto put_objcg;
1517 }
1518 mem_cgroup_put(memcg);
1519 }
1520
1521 if (zswap_check_limits())
1522 goto put_objcg;
1523
1524 pool = zswap_pool_current_get();
1525 if (!pool)
1526 goto put_objcg;
1527
1528 if (objcg) {
1529 memcg = get_mem_cgroup_from_objcg(objcg);
1530 if (memcg_list_lru_alloc(memcg, &zswap_list_lru, GFP_KERNEL)) {
1531 mem_cgroup_put(memcg);
1532 goto put_pool;
1533 }
1534 mem_cgroup_put(memcg);
1535 }
1536
1537 for (index = 0; index < nr_pages; ++index) {
1538 struct page *page = folio_page(folio, index);
1539
1540 if (!zswap_store_page(page, objcg, pool))
1541 goto put_pool;
1542 }
1543
1544 if (objcg)
1545 count_objcg_events(objcg, ZSWPOUT, nr_pages);
1546
1547 count_vm_events(ZSWPOUT, nr_pages);
1548
1549 ret = true;
1550
1551 put_pool:
1552 zswap_pool_put(pool);
1553 put_objcg:
1554 obj_cgroup_put(objcg);
1555 if (!ret && zswap_pool_reached_full)
1556 queue_work(shrink_wq, &zswap_shrink_work);
1557 check_old:
1558 /*
1559 * If the zswap store fails or zswap is disabled, we must invalidate
1560 * the possibly stale entries which were previously stored at the
1561 * offsets corresponding to each page of the folio. Otherwise,
1562 * writeback could overwrite the new data in the swapfile.
1563 */
1564 if (!ret) {
1565 unsigned type = swp_type(swp);
1566 pgoff_t offset = swp_offset(swp);
1567 struct zswap_entry *entry;
1568 struct xarray *tree;
1569
1570 for (index = 0; index < nr_pages; ++index) {
1571 tree = swap_zswap_tree(swp_entry(type, offset + index));
1572 entry = xa_erase(tree, offset + index);
1573 if (entry)
1574 zswap_entry_free(entry);
1575 }
1576 }
1577
1578 return ret;
1579 }
1580
1581 /**
1582 * zswap_load() - load a folio from zswap
1583 * @folio: folio to load
1584 *
1585 * Return: 0 on success, with the folio unlocked and marked up-to-date, or one
1586 * of the following error codes:
1587 *
1588 * -EIO: if the swapped out content was in zswap, but could not be loaded
1589 * into the page due to a decompression failure. The folio is unlocked, but
1590 * NOT marked up-to-date, so that an IO error is emitted (e.g. do_swap_page()
1591 * will SIGBUS).
1592 *
1593 * -EINVAL: if the swapped out content was in zswap, but the page belongs
1594 * to a large folio, which is not supported by zswap. The folio is unlocked,
1595 * but NOT marked up-to-date, so that an IO error is emitted (e.g.
1596 * do_swap_page() will SIGBUS).
1597 *
1598 * -ENOENT: if the swapped out content was not in zswap. The folio remains
1599 * locked on return.
1600 */
zswap_load(struct folio * folio)1601 int zswap_load(struct folio *folio)
1602 {
1603 swp_entry_t swp = folio->swap;
1604 pgoff_t offset = swp_offset(swp);
1605 bool swapcache = folio_test_swapcache(folio);
1606 struct xarray *tree = swap_zswap_tree(swp);
1607 struct zswap_entry *entry;
1608
1609 VM_WARN_ON_ONCE(!folio_test_locked(folio));
1610
1611 if (zswap_never_enabled())
1612 return -ENOENT;
1613
1614 /*
1615 * Large folios should not be swapped in while zswap is being used, as
1616 * they are not properly handled. Zswap does not properly load large
1617 * folios, and a large folio may only be partially in zswap.
1618 */
1619 if (WARN_ON_ONCE(folio_test_large(folio))) {
1620 folio_unlock(folio);
1621 return -EINVAL;
1622 }
1623
1624 entry = xa_load(tree, offset);
1625 if (!entry)
1626 return -ENOENT;
1627
1628 if (!zswap_decompress(entry, folio)) {
1629 folio_unlock(folio);
1630 return -EIO;
1631 }
1632
1633 folio_mark_uptodate(folio);
1634
1635 count_vm_event(ZSWPIN);
1636 if (entry->objcg)
1637 count_objcg_events(entry->objcg, ZSWPIN, 1);
1638
1639 /*
1640 * When reading into the swapcache, invalidate our entry. The
1641 * swapcache can be the authoritative owner of the page and
1642 * its mappings, and the pressure that results from having two
1643 * in-memory copies outweighs any benefits of caching the
1644 * compression work.
1645 *
1646 * (Most swapins go through the swapcache. The notable
1647 * exception is the singleton fault on SWP_SYNCHRONOUS_IO
1648 * files, which reads into a private page and may free it if
1649 * the fault fails. We remain the primary owner of the entry.)
1650 */
1651 if (swapcache) {
1652 folio_mark_dirty(folio);
1653 xa_erase(tree, offset);
1654 zswap_entry_free(entry);
1655 }
1656
1657 folio_unlock(folio);
1658 return 0;
1659 }
1660
zswap_invalidate(swp_entry_t swp)1661 void zswap_invalidate(swp_entry_t swp)
1662 {
1663 pgoff_t offset = swp_offset(swp);
1664 struct xarray *tree = swap_zswap_tree(swp);
1665 struct zswap_entry *entry;
1666
1667 if (xa_empty(tree))
1668 return;
1669
1670 entry = xa_erase(tree, offset);
1671 if (entry)
1672 zswap_entry_free(entry);
1673 }
1674
zswap_swapon(int type,unsigned long nr_pages)1675 int zswap_swapon(int type, unsigned long nr_pages)
1676 {
1677 struct xarray *trees, *tree;
1678 unsigned int nr, i;
1679
1680 nr = DIV_ROUND_UP(nr_pages, ZSWAP_ADDRESS_SPACE_PAGES);
1681 trees = kvcalloc(nr, sizeof(*tree), GFP_KERNEL);
1682 if (!trees) {
1683 pr_err("alloc failed, zswap disabled for swap type %d\n", type);
1684 return -ENOMEM;
1685 }
1686
1687 for (i = 0; i < nr; i++)
1688 xa_init(trees + i);
1689
1690 nr_zswap_trees[type] = nr;
1691 zswap_trees[type] = trees;
1692 return 0;
1693 }
1694
zswap_swapoff(int type)1695 void zswap_swapoff(int type)
1696 {
1697 struct xarray *trees = zswap_trees[type];
1698 unsigned int i;
1699
1700 if (!trees)
1701 return;
1702
1703 /* try_to_unuse() invalidated all the entries already */
1704 for (i = 0; i < nr_zswap_trees[type]; i++)
1705 WARN_ON_ONCE(!xa_empty(trees + i));
1706
1707 kvfree(trees);
1708 nr_zswap_trees[type] = 0;
1709 zswap_trees[type] = NULL;
1710 }
1711
1712 /*********************************
1713 * debugfs functions
1714 **********************************/
1715 #ifdef CONFIG_DEBUG_FS
1716 #include <linux/debugfs.h>
1717
1718 static struct dentry *zswap_debugfs_root;
1719
debugfs_get_total_size(void * data,u64 * val)1720 static int debugfs_get_total_size(void *data, u64 *val)
1721 {
1722 *val = zswap_total_pages() * PAGE_SIZE;
1723 return 0;
1724 }
1725 DEFINE_DEBUGFS_ATTRIBUTE(total_size_fops, debugfs_get_total_size, NULL, "%llu\n");
1726
debugfs_get_stored_pages(void * data,u64 * val)1727 static int debugfs_get_stored_pages(void *data, u64 *val)
1728 {
1729 *val = atomic_long_read(&zswap_stored_pages);
1730 return 0;
1731 }
1732 DEFINE_DEBUGFS_ATTRIBUTE(stored_pages_fops, debugfs_get_stored_pages, NULL, "%llu\n");
1733
debugfs_get_stored_incompressible_pages(void * data,u64 * val)1734 static int debugfs_get_stored_incompressible_pages(void *data, u64 *val)
1735 {
1736 *val = atomic_long_read(&zswap_stored_incompressible_pages);
1737 return 0;
1738 }
1739 DEFINE_DEBUGFS_ATTRIBUTE(stored_incompressible_pages_fops,
1740 debugfs_get_stored_incompressible_pages, NULL, "%llu\n");
1741
zswap_debugfs_init(void)1742 static int zswap_debugfs_init(void)
1743 {
1744 if (!debugfs_initialized())
1745 return -ENODEV;
1746
1747 zswap_debugfs_root = debugfs_create_dir("zswap", NULL);
1748
1749 debugfs_create_u64("pool_limit_hit", 0444,
1750 zswap_debugfs_root, &zswap_pool_limit_hit);
1751 debugfs_create_u64("reject_reclaim_fail", 0444,
1752 zswap_debugfs_root, &zswap_reject_reclaim_fail);
1753 debugfs_create_u64("reject_alloc_fail", 0444,
1754 zswap_debugfs_root, &zswap_reject_alloc_fail);
1755 debugfs_create_u64("reject_kmemcache_fail", 0444,
1756 zswap_debugfs_root, &zswap_reject_kmemcache_fail);
1757 debugfs_create_u64("reject_compress_fail", 0444,
1758 zswap_debugfs_root, &zswap_reject_compress_fail);
1759 debugfs_create_u64("reject_compress_poor", 0444,
1760 zswap_debugfs_root, &zswap_reject_compress_poor);
1761 debugfs_create_u64("decompress_fail", 0444,
1762 zswap_debugfs_root, &zswap_decompress_fail);
1763 debugfs_create_u64("written_back_pages", 0444,
1764 zswap_debugfs_root, &zswap_written_back_pages);
1765 debugfs_create_file("pool_total_size", 0444,
1766 zswap_debugfs_root, NULL, &total_size_fops);
1767 debugfs_create_file("stored_pages", 0444,
1768 zswap_debugfs_root, NULL, &stored_pages_fops);
1769 debugfs_create_file("stored_incompressible_pages", 0444,
1770 zswap_debugfs_root, NULL,
1771 &stored_incompressible_pages_fops);
1772
1773 return 0;
1774 }
1775 #else
zswap_debugfs_init(void)1776 static int zswap_debugfs_init(void)
1777 {
1778 return 0;
1779 }
1780 #endif
1781
1782 /*********************************
1783 * module init and exit
1784 **********************************/
zswap_setup(void)1785 static int zswap_setup(void)
1786 {
1787 struct zswap_pool *pool;
1788 int ret;
1789
1790 zswap_entry_cache = KMEM_CACHE(zswap_entry, 0);
1791 if (!zswap_entry_cache) {
1792 pr_err("entry cache creation failed\n");
1793 goto cache_fail;
1794 }
1795
1796 ret = cpuhp_setup_state_multi(CPUHP_MM_ZSWP_POOL_PREPARE,
1797 "mm/zswap_pool:prepare",
1798 zswap_cpu_comp_prepare,
1799 zswap_cpu_comp_dead);
1800 if (ret)
1801 goto hp_fail;
1802
1803 shrink_wq = alloc_workqueue("zswap-shrink",
1804 WQ_UNBOUND|WQ_MEM_RECLAIM, 1);
1805 if (!shrink_wq)
1806 goto shrink_wq_fail;
1807
1808 zswap_shrinker = zswap_alloc_shrinker();
1809 if (!zswap_shrinker)
1810 goto shrinker_fail;
1811 if (list_lru_init_memcg(&zswap_list_lru, zswap_shrinker))
1812 goto lru_fail;
1813 shrinker_register(zswap_shrinker);
1814
1815 INIT_WORK(&zswap_shrink_work, shrink_worker);
1816
1817 pool = __zswap_pool_create_fallback();
1818 if (pool) {
1819 pr_info("loaded using pool %s\n", pool->tfm_name);
1820 list_add(&pool->list, &zswap_pools);
1821 zswap_has_pool = true;
1822 static_branch_enable(&zswap_ever_enabled);
1823 } else {
1824 pr_err("pool creation failed\n");
1825 zswap_enabled = false;
1826 }
1827
1828 if (zswap_debugfs_init())
1829 pr_warn("debugfs initialization failed\n");
1830 zswap_init_state = ZSWAP_INIT_SUCCEED;
1831 return 0;
1832
1833 lru_fail:
1834 shrinker_free(zswap_shrinker);
1835 shrinker_fail:
1836 destroy_workqueue(shrink_wq);
1837 shrink_wq_fail:
1838 cpuhp_remove_multi_state(CPUHP_MM_ZSWP_POOL_PREPARE);
1839 hp_fail:
1840 kmem_cache_destroy(zswap_entry_cache);
1841 cache_fail:
1842 /* if built-in, we aren't unloaded on failure; don't allow use */
1843 zswap_init_state = ZSWAP_INIT_FAILED;
1844 zswap_enabled = false;
1845 return -ENOMEM;
1846 }
1847
zswap_init(void)1848 static int __init zswap_init(void)
1849 {
1850 if (!zswap_enabled)
1851 return 0;
1852 return zswap_setup();
1853 }
1854 /* must be late so crypto has time to come up */
1855 late_initcall(zswap_init);
1856
1857 MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
1858 MODULE_DESCRIPTION("Compressed cache for swap pages");
1859