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