1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * linux/mm/swap_state.c 4 * 5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 6 * Swap reorganised 29.12.95, Stephen Tweedie 7 * 8 * Rewritten to use page cache, (C) 1998 Stephen Tweedie 9 */ 10 #include <linux/mm.h> 11 #include <linux/gfp.h> 12 #include <linux/kernel_stat.h> 13 #include <linux/mempolicy.h> 14 #include <linux/swap.h> 15 #include <linux/leafops.h> 16 #include <linux/init.h> 17 #include <linux/pagemap.h> 18 #include <linux/folio_batch.h> 19 #include <linux/backing-dev.h> 20 #include <linux/blk_plug.h> 21 #include <linux/migrate.h> 22 #include <linux/vmalloc.h> 23 #include <linux/huge_mm.h> 24 #include <linux/shmem_fs.h> 25 #include <linux/sysctl.h> 26 #include <linux/swap_ops.h> 27 #include "internal.h" 28 #include "swap_table.h" 29 #include "swap.h" 30 31 /* Swap readahead cluster size, as a power of 2 pages. */ 32 static int page_cluster; 33 static const int page_cluster_max = 31; 34 35 /* 36 * swapper_space is a fiction, retained to simplify the path through 37 * vmscan's shrink_folio_list. 38 */ 39 static const struct address_space_operations swap_aops = { 40 .dirty_folio = noop_dirty_folio, 41 #ifdef CONFIG_MIGRATION 42 .migrate_folio = migrate_folio, 43 #endif 44 }; 45 46 struct address_space swap_space __read_mostly = { 47 .a_ops = &swap_aops, 48 }; 49 50 static bool enable_vma_readahead __read_mostly = true; 51 52 #define SWAP_RA_ORDER_CEILING 5 53 54 #define SWAP_RA_WIN_SHIFT (PAGE_SHIFT / 2) 55 #define SWAP_RA_HITS_MASK ((1UL << SWAP_RA_WIN_SHIFT) - 1) 56 #define SWAP_RA_HITS_MAX SWAP_RA_HITS_MASK 57 #define SWAP_RA_WIN_MASK (~PAGE_MASK & ~SWAP_RA_HITS_MASK) 58 59 #define SWAP_RA_HITS(v) ((v) & SWAP_RA_HITS_MASK) 60 #define SWAP_RA_WIN(v) (((v) & SWAP_RA_WIN_MASK) >> SWAP_RA_WIN_SHIFT) 61 #define SWAP_RA_ADDR(v) ((v) & PAGE_MASK) 62 63 #define SWAP_RA_VAL(addr, win, hits) \ 64 (((addr) & PAGE_MASK) | \ 65 (((win) << SWAP_RA_WIN_SHIFT) & SWAP_RA_WIN_MASK) | \ 66 ((hits) & SWAP_RA_HITS_MASK)) 67 68 /* Initial readahead hits is 4 to start up with a small window */ 69 #define GET_SWAP_RA_VAL(vma) \ 70 (atomic_long_read(&(vma)->swap_readahead_info) ? : 4) 71 72 static atomic_t swapin_readahead_hits = ATOMIC_INIT(4); 73 74 void show_swap_cache_info(void) 75 { 76 printk("%lu pages in swap cache\n", total_swapcache_pages()); 77 printk("Free swap = %ldkB\n", K(get_nr_swap_pages())); 78 printk("Total swap = %lukB\n", K(total_swap_pages)); 79 } 80 81 /** 82 * swap_cache_get_folio - Looks up a folio in the swap cache. 83 * @entry: swap entry used for the lookup. 84 * 85 * A found folio will be returned unlocked and with its refcount increased. 86 * 87 * Context: Caller must ensure @entry is valid and protect the swap device 88 * with reference count or locks. 89 * Return: Returns the found folio on success, NULL otherwise. The caller 90 * must lock and check if the folio still matches the swap entry before 91 * use (e.g., folio_matches_swap_entry). 92 */ 93 struct folio *swap_cache_get_folio(swp_entry_t entry) 94 { 95 unsigned long swp_tb; 96 struct folio *folio; 97 98 for (;;) { 99 swp_tb = swap_table_get(__swap_entry_to_cluster(entry), 100 swp_cluster_offset(entry)); 101 if (!swp_tb_is_folio(swp_tb)) 102 return NULL; 103 folio = swp_tb_to_folio(swp_tb); 104 if (likely(folio_try_get(folio))) 105 return folio; 106 } 107 108 return NULL; 109 } 110 111 /** 112 * swap_cache_has_folio - Check if a swap slot has cache. 113 * @entry: swap entry indicating the slot. 114 * 115 * Context: Caller must ensure @entry is valid and protect the swap 116 * device with reference count or locks. 117 */ 118 bool swap_cache_has_folio(swp_entry_t entry) 119 { 120 unsigned long swp_tb; 121 122 swp_tb = swap_table_get(__swap_entry_to_cluster(entry), 123 swp_cluster_offset(entry)); 124 return swp_tb_is_folio(swp_tb); 125 } 126 127 /** 128 * swap_cache_get_shadow - Looks up a shadow in the swap cache. 129 * @entry: swap entry used for the lookup. 130 * 131 * Context: Caller must ensure @entry is valid and protect the swap device 132 * with reference count or locks. 133 * Return: Returns either NULL or an XA_VALUE (shadow). 134 */ 135 void *swap_cache_get_shadow(swp_entry_t entry) 136 { 137 unsigned long swp_tb; 138 139 swp_tb = swap_table_get(__swap_entry_to_cluster(entry), 140 swp_cluster_offset(entry)); 141 if (swp_tb_is_shadow(swp_tb)) 142 return swp_tb_to_shadow(swp_tb); 143 return NULL; 144 } 145 146 /** 147 * __swap_cache_add_check - Check if a range is suitable for adding a folio. 148 * @ci: The locked swap cluster 149 * @targ_entry: The target swap entry to check, will be rounded down by @nr 150 * @nr: Number of slots to check, must be a power of 2 151 * @shadowp: Returns the shadow value if one exists in the range 152 * @memcg_id: Returns the memory cgroup id, NULL to ignore cgroup check 153 * 154 * Check if all slots covered by given range have a swap count >= 1. 155 * Retrieves the shadow if there is one. If @memcg_id is not NULL, also 156 * checks if all slots belong to the same cgroup and return the cgroup 157 * private id. 158 * 159 * Context: Caller must lock the cluster. 160 * Return: 0 if success, error code if failed. 161 */ 162 static int __swap_cache_add_check(struct swap_cluster_info *ci, 163 swp_entry_t targ_entry, 164 unsigned long nr, void **shadowp, 165 unsigned short *memcg_id) 166 { 167 unsigned int ci_off, ci_end; 168 unsigned long old_tb; 169 bool is_zero; 170 171 lockdep_assert_held(&ci->lock); 172 173 /* 174 * If the target slot is not swapped out or already cached, return 175 * -ENOENT or -EEXIST. If the batch is not suitable, could be a 176 * race with concurrent free or cache add, return -EBUSY. 177 */ 178 if (unlikely(!ci->table)) 179 return -ENOENT; 180 ci_off = swp_cluster_offset(targ_entry); 181 old_tb = __swap_table_get(ci, ci_off); 182 if (swp_tb_is_folio(old_tb)) 183 return -EEXIST; 184 if (!__swp_tb_get_count(old_tb)) 185 return -ENOENT; 186 if (shadowp && swp_tb_is_shadow(old_tb)) 187 *shadowp = swp_tb_to_shadow(old_tb); 188 if (memcg_id) 189 *memcg_id = __swap_cgroup_get(ci, ci_off); 190 191 if (nr == 1) 192 return 0; 193 194 is_zero = __swap_table_test_zero(ci, ci_off); 195 ci_off = round_down(ci_off, nr); 196 ci_end = ci_off + nr; 197 do { 198 old_tb = __swap_table_get(ci, ci_off); 199 if (unlikely(swp_tb_is_folio(old_tb) || 200 !__swp_tb_get_count(old_tb) || 201 is_zero != __swap_table_test_zero(ci, ci_off) || 202 (memcg_id && *memcg_id != __swap_cgroup_get(ci, ci_off)))) 203 return -EBUSY; 204 } while (++ci_off < ci_end); 205 206 return 0; 207 } 208 209 static void __swap_cache_do_add_folio(struct swap_cluster_info *ci, 210 struct folio *folio, swp_entry_t entry) 211 { 212 unsigned int ci_off = swp_cluster_offset(entry), ci_end; 213 unsigned long nr_pages = folio_nr_pages(folio); 214 unsigned long pfn = folio_pfn(folio); 215 unsigned long old_tb; 216 217 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 218 VM_WARN_ON_ONCE_FOLIO(folio_test_swapcache(folio), folio); 219 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapbacked(folio), folio); 220 221 ci_end = ci_off + nr_pages; 222 do { 223 old_tb = __swap_table_get(ci, ci_off); 224 VM_WARN_ON_ONCE(swp_tb_is_folio(old_tb)); 225 __swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb))); 226 } while (++ci_off < ci_end); 227 228 folio_ref_add(folio, nr_pages); 229 folio_set_swapcache(folio); 230 folio->swap = entry; 231 } 232 233 /** 234 * __swap_cache_add_folio - Add a folio to the swap cache and update stats. 235 * @ci: The locked swap cluster. 236 * @folio: The folio to be added. 237 * @entry: The swap entry corresponding to the folio. 238 * 239 * Unconditionally add a folio to the swap cache. The caller must ensure 240 * all slots are usable and have no conflicts. This assigns entry to 241 * @folio->swap, increases folio refcount by the number of pages, and 242 * updates swap cache stats. 243 * 244 * Context: Caller must ensure the folio is locked and lock the cluster 245 * that holds the entries. 246 */ 247 void __swap_cache_add_folio(struct swap_cluster_info *ci, 248 struct folio *folio, swp_entry_t entry) 249 { 250 unsigned long nr_pages = folio_nr_pages(folio); 251 252 __swap_cache_do_add_folio(ci, folio, entry); 253 node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); 254 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); 255 } 256 257 static void __swap_cache_do_del_folio(struct swap_cluster_info *ci, 258 struct folio *folio, 259 swp_entry_t entry, void *shadow) 260 { 261 unsigned long old_tb; 262 struct swap_info_struct *si; 263 unsigned int ci_start, ci_off, ci_end; 264 bool folio_swapped = false, need_free = false; 265 unsigned long nr_pages = folio_nr_pages(folio); 266 267 VM_WARN_ON_ONCE(__swap_entry_to_cluster(entry) != ci); 268 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 269 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); 270 VM_WARN_ON_ONCE_FOLIO(folio_test_writeback(folio), folio); 271 272 si = __swap_entry_to_info(entry); 273 ci_start = swp_cluster_offset(entry); 274 ci_end = ci_start + nr_pages; 275 ci_off = ci_start; 276 do { 277 old_tb = __swap_table_get(ci, ci_off); 278 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || 279 swp_tb_to_folio(old_tb) != folio); 280 if (__swp_tb_get_count(old_tb)) 281 folio_swapped = true; 282 else 283 need_free = true; 284 /* If shadow is NULL, we set an empty shadow. */ 285 __swap_table_set(ci, ci_off, shadow_to_swp_tb(shadow, 286 __swp_tb_get_flags(old_tb))); 287 } while (++ci_off < ci_end); 288 289 folio->swap.val = 0; 290 folio_clear_swapcache(folio); 291 292 if (!folio_swapped) { 293 __swap_cluster_free_entries(si, ci, ci_start, nr_pages); 294 } else if (need_free) { 295 ci_off = ci_start; 296 do { 297 if (!__swp_tb_get_count(__swap_table_get(ci, ci_off))) 298 __swap_cluster_free_entries(si, ci, ci_off, 1); 299 } while (++ci_off < ci_end); 300 } 301 } 302 303 /** 304 * __swap_cache_del_folio - Removes a folio from the swap cache. 305 * @ci: The locked swap cluster. 306 * @folio: The folio. 307 * @entry: The first swap entry that the folio corresponds to. 308 * @shadow: shadow value to be filled in the swap cache. 309 * @swapout: whether this folio is being reclaimed after swapout. 310 * 311 * Removes a folio from the swap cache and fills a shadow in place. 312 * This won't put the folio's refcount. The caller has to do that. 313 * 314 * Context: Caller must ensure the folio is locked and in the swap cache 315 * using the index of @entry, and lock the cluster that holds the entries. 316 * If @swapout is set, the folio should be in reclaim path and IRQs 317 * should be disabled. 318 */ 319 void __swap_cache_del_folio(struct swap_cluster_info *ci, struct folio *folio, 320 swp_entry_t entry, void *shadow, bool swapout) 321 { 322 unsigned long nr_pages = folio_nr_pages(folio); 323 324 node_stat_mod_folio(folio, NR_FILE_PAGES, -nr_pages); 325 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, -nr_pages); 326 327 if (swapout) 328 __memcg1_swapout(folio, ci); 329 330 __swap_cache_do_del_folio(ci, folio, entry, shadow); 331 } 332 333 /** 334 * swap_cache_del_folio - Removes a folio from the swap cache. 335 * @folio: The folio. 336 * 337 * Same as __swap_cache_del_folio, but handles lock and refcount. The 338 * caller must ensure the folio is either clean or has a swap count 339 * equal to zero, or it may cause data loss. 340 * 341 * Context: Caller must ensure the folio is locked and in the swap cache. 342 */ 343 void swap_cache_del_folio(struct folio *folio) 344 { 345 struct swap_cluster_info *ci; 346 swp_entry_t entry = folio->swap; 347 348 ci = swap_cluster_lock(__swap_entry_to_info(entry), swp_offset(entry)); 349 __swap_cache_del_folio(ci, folio, entry, NULL, false); 350 swap_cluster_unlock(ci); 351 352 folio_ref_sub(folio, folio_nr_pages(folio)); 353 } 354 355 /** 356 * __swap_cache_replace_folio - Replace a folio in the swap cache. 357 * @ci: The locked swap cluster. 358 * @old: The old folio to be replaced. 359 * @new: The new folio. 360 * 361 * Replace an existing folio in the swap cache with a new folio. The 362 * caller is responsible for setting up the new folio's flag and swap 363 * entries. Replacement will take the new folio's swap entry value as 364 * the starting offset to override all slots covered by the new folio. 365 * 366 * Context: Caller must ensure both folios are locked, and lock the 367 * cluster that holds the old folio to be replaced. 368 */ 369 void __swap_cache_replace_folio(struct swap_cluster_info *ci, 370 struct folio *old, struct folio *new) 371 { 372 swp_entry_t entry = new->swap; 373 unsigned long nr_pages = folio_nr_pages(new); 374 unsigned int ci_off = swp_cluster_offset(entry); 375 unsigned int ci_end = ci_off + nr_pages; 376 unsigned long pfn = folio_pfn(new); 377 unsigned long old_tb; 378 379 VM_WARN_ON_ONCE(!folio_test_swapcache(old) || !folio_test_swapcache(new)); 380 VM_WARN_ON_ONCE(!folio_test_locked(old) || !folio_test_locked(new)); 381 VM_WARN_ON_ONCE(!entry.val); 382 383 /* Swap cache still stores N entries instead of a high-order entry */ 384 do { 385 old_tb = __swap_table_get(ci, ci_off); 386 WARN_ON_ONCE(!swp_tb_is_folio(old_tb) || swp_tb_to_folio(old_tb) != old); 387 __swap_table_set(ci, ci_off, pfn_to_swp_tb(pfn, __swp_tb_get_flags(old_tb))); 388 } while (++ci_off < ci_end); 389 390 /* 391 * If the old folio is partially replaced (e.g., splitting a large 392 * folio, the old folio is shrunk, and new split sub folios replace 393 * the shrunk part), ensure the new folio doesn't overlap it. 394 */ 395 if (IS_ENABLED(CONFIG_DEBUG_VM) && 396 folio_order(old) != folio_order(new)) { 397 ci_off = swp_cluster_offset(old->swap); 398 ci_end = ci_off + folio_nr_pages(old); 399 do { 400 WARN_ON_ONCE(swp_tb_to_folio(__swap_table_get(ci, ci_off)) != old); 401 } while (++ci_off < ci_end); 402 } 403 } 404 405 /* 406 * Try to allocate a folio of given order in the swap cache. 407 * 408 * This helper resolves the potential races of swap allocation 409 * and prepares a folio to be used for swap IO. May return following 410 * value: 411 * 412 * -ENOMEM / -EBUSY: Order is too large or in conflict with sub slot, 413 * caller should shrink the order and retry 414 * -ENOENT / -EEXIST: Target swap entry is unavailable or cached, the caller 415 * should abort or try to use the cached folio instead 416 */ 417 static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci, 418 swp_entry_t targ_entry, gfp_t gfp, 419 unsigned int order, struct vm_fault *vmf, 420 struct mempolicy *mpol, pgoff_t ilx) 421 { 422 int err; 423 swp_entry_t entry; 424 struct folio *folio; 425 void *shadow = NULL; 426 unsigned short memcg_id; 427 unsigned long address, nr_pages = 1UL << order; 428 struct vm_area_struct *vma = vmf ? vmf->vma : NULL; 429 430 VM_WARN_ON_ONCE(nr_pages > SWAPFILE_CLUSTER); 431 entry.val = round_down(targ_entry.val, nr_pages); 432 433 /* Check if the slot and range are available, skip allocation if not */ 434 spin_lock(&ci->lock); 435 err = __swap_cache_add_check(ci, targ_entry, nr_pages, NULL, NULL); 436 spin_unlock(&ci->lock); 437 if (unlikely(err)) 438 return ERR_PTR(err); 439 440 /* 441 * Limit THP gfp. The limitation is a no-op for typical 442 * GFP_HIGHUSER_MOVABLE but matters for shmem. 443 */ 444 if (order) 445 gfp = thp_shmem_limit_gfp_mask(vma_thp_gfp_mask(vma), gfp); 446 447 if (mpol || !vmf) { 448 folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id()); 449 } else { 450 address = round_down(vmf->address, PAGE_SIZE << order); 451 folio = vma_alloc_folio(gfp, order, vmf->vma, address); 452 } 453 if (unlikely(!folio)) 454 return ERR_PTR(-ENOMEM); 455 456 /* Double check the range is still not in conflict */ 457 spin_lock(&ci->lock); 458 err = __swap_cache_add_check(ci, targ_entry, nr_pages, &shadow, &memcg_id); 459 if (unlikely(err)) { 460 spin_unlock(&ci->lock); 461 folio_put(folio); 462 return ERR_PTR(err); 463 } 464 465 __folio_set_locked(folio); 466 __folio_set_swapbacked(folio); 467 __swap_cache_do_add_folio(ci, folio, entry); 468 spin_unlock(&ci->lock); 469 470 if (mem_cgroup_swapin_charge_folio(folio, memcg_id, 471 vmf ? vmf->vma->vm_mm : NULL, gfp)) { 472 spin_lock(&ci->lock); 473 __swap_cache_do_del_folio(ci, folio, entry, shadow); 474 spin_unlock(&ci->lock); 475 folio_unlock(folio); 476 /* nr_pages refs from swap cache, 1 from allocation */ 477 folio_put_refs(folio, nr_pages + 1); 478 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK_CHARGE); 479 return ERR_PTR(-ENOMEM); 480 } 481 482 if (order > 1 && folio_memcg_alloc_deferred(folio)) { 483 spin_lock(&ci->lock); 484 __swap_cache_do_del_folio(ci, folio, entry, shadow); 485 spin_unlock(&ci->lock); 486 folio_unlock(folio); 487 /* nr_pages refs from swap cache, 1 from allocation */ 488 folio_put_refs(folio, nr_pages + 1); 489 return ERR_PTR(-ENOMEM); 490 } 491 492 /* memsw uncharges swap when folio is added to swap cache */ 493 memcg1_swapin(folio); 494 if (shadow) 495 workingset_refault(folio, shadow); 496 497 node_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages); 498 lruvec_stat_mod_folio(folio, NR_SWAPCACHE, nr_pages); 499 500 return folio; 501 } 502 503 /** 504 * __swap_cache_alloc_folio - Allocate folio for swapped out slot in swap cache. 505 * @targ_entry: swap entry indicating the target slot 506 * @gfp: memory allocation flags 507 * @orders: allocation orders, must be non zero 508 * @vmf: fault information 509 * @mpol: NUMA memory allocation policy to be applied 510 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE 511 * 512 * Allocate a folio in the swap cache for one swap slot, typically before 513 * doing IO (e.g. swap in or zswap writeback). The swap slot indicated by 514 * @targ_entry must have a non-zero swap count (swapped out). 515 * 516 * The returned folio is locked and is NOT on the LRU. The caller must either 517 * add it to the LRU with folio_add_lru() so page reclaim can find it, or free 518 * it directly once done; a folio left off the LRU is unreclaimable and leaks. 519 * 520 * Context: Caller must protect the swap device with reference count or locks. 521 * Return: Returns the folio if allocation succeeded and folio is in the swap 522 * cache. Returns error code if failed due to race, OOM or invalid arguments. 523 */ 524 struct folio *__swap_cache_alloc_folio(swp_entry_t targ_entry, gfp_t gfp, 525 unsigned long orders, struct vm_fault *vmf, 526 struct mempolicy *mpol, pgoff_t ilx) 527 { 528 int order, err; 529 struct folio *ret; 530 struct swap_cluster_info *ci; 531 532 ci = __swap_entry_to_cluster(targ_entry); 533 order = highest_order(orders); 534 535 /* orders must be non-zero, and must not exceed cluster size. */ 536 if (WARN_ON_ONCE(!orders || (1UL << order) > SWAPFILE_CLUSTER)) 537 return ERR_PTR(-EINVAL); 538 539 do { 540 ret = __swap_cache_alloc(ci, targ_entry, gfp, order, 541 vmf, mpol, ilx); 542 if (!IS_ERR(ret)) 543 break; 544 err = PTR_ERR(ret); 545 if (!order || (err && err != -EBUSY && err != -ENOMEM)) 546 break; 547 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK); 548 order = next_order(&orders, order); 549 } while (orders); 550 551 return ret; 552 } 553 554 /** 555 * swap_writeback_dropbehind_folio - drop a dropbehind swap cache folio 556 * @folio: the off-LRU folio whose writeback has completed 557 * 558 * Context: task context, with the reference taken by folio_end_writeback() 559 * donated to us. 560 */ 561 void swap_writeback_dropbehind_folio(struct folio *folio) 562 { 563 struct mem_cgroup *memcg; 564 565 folio_lock(folio); 566 567 /* The folio was allocated off the LRU and nothing re-adds it here. */ 568 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio); 569 570 rcu_read_lock(); 571 memcg = folio_memcg(folio); 572 if (!mem_cgroup_tryget(memcg)) 573 memcg = NULL; 574 rcu_read_unlock(); 575 576 /* 577 * Gate remove_mapping_set_shadow() on folio_test_swapcache(): a racing 578 * swapin may have freed the swap slot (folio_free_swap()) and dropped the 579 * folio from the cache, and it must not run on a non-swapcache folio (it 580 * would trip __remove_mapping()'s mapping == folio_mapping() check). 581 */ 582 if (!folio_test_swapcache(folio) || folio_test_writeback(folio) || 583 !remove_mapping_set_shadow(swap_address_space(folio->swap), folio, 584 memcg)) { 585 /* Raced: the folio is now owned by the swapin; put it back. */ 586 folio_clear_dropbehind(folio); 587 folio_add_lru(folio); 588 } 589 590 mem_cgroup_put(memcg); 591 592 folio_unlock(folio); 593 folio_put(folio); 594 } 595 596 /* 597 * If we are the only user, then try to free up the swap cache. 598 * 599 * Its ok to check the swapcache flag without the folio lock 600 * here because we are going to recheck again inside 601 * folio_free_swap() _with_ the lock. 602 * - Marcelo 603 */ 604 void free_swap_cache(struct folio *folio) 605 { 606 if (folio_test_swapcache(folio) && !folio_mapped(folio) && 607 folio_trylock(folio)) { 608 folio_free_swap(folio); 609 folio_unlock(folio); 610 } 611 } 612 613 /* 614 * Freeing a folio and also freeing any swap cache associated with 615 * this folio if it is the last user. 616 */ 617 void free_folio_and_swap_cache(struct folio *folio) 618 { 619 free_swap_cache(folio); 620 if (!is_huge_zero_folio(folio)) 621 folio_put(folio); 622 } 623 624 /* 625 * Passed an array of pages, drop them all from swapcache and then release 626 * them. They are removed from the LRU and freed if this is their last use. 627 */ 628 void free_pages_and_swap_cache(struct encoded_page **pages, int nr) 629 { 630 struct folio_batch folios; 631 unsigned int refs[FOLIO_BATCH_SIZE]; 632 633 folio_batch_init(&folios); 634 for (int i = 0; i < nr; i++) { 635 struct folio *folio = page_folio(encoded_page_ptr(pages[i])); 636 637 free_swap_cache(folio); 638 refs[folios.nr] = 1; 639 if (unlikely(encoded_page_flags(pages[i]) & 640 ENCODED_PAGE_BIT_NR_PAGES_NEXT)) 641 refs[folios.nr] = encoded_nr_pages(pages[++i]); 642 643 if (folio_batch_add(&folios, folio) == 0) 644 folios_put_refs(&folios, refs); 645 } 646 if (folios.nr) 647 folios_put_refs(&folios, refs); 648 } 649 650 static inline bool swap_use_vma_readahead(void) 651 { 652 return READ_ONCE(enable_vma_readahead) && !atomic_read(&nr_rotate_swap); 653 } 654 655 /** 656 * swap_update_readahead - Update the readahead statistics of VMA or globally. 657 * @folio: the swap cache folio that just got hit. 658 * @vma: the VMA that should be updated, could be NULL for global update. 659 * @addr: the addr that triggered the swapin, ignored if @vma is NULL. 660 */ 661 void swap_update_readahead(struct folio *folio, struct vm_area_struct *vma, 662 unsigned long addr) 663 { 664 bool readahead, vma_ra = swap_use_vma_readahead(); 665 666 /* 667 * At the moment, we don't support PG_readahead for anon THP 668 * so let's bail out rather than confusing the readahead stat. 669 */ 670 if (unlikely(folio_test_large(folio))) 671 return; 672 673 readahead = folio_test_clear_readahead(folio); 674 if (vma && vma_ra) { 675 unsigned long ra_val; 676 int win, hits; 677 678 ra_val = GET_SWAP_RA_VAL(vma); 679 win = SWAP_RA_WIN(ra_val); 680 hits = SWAP_RA_HITS(ra_val); 681 if (readahead) 682 hits = min_t(int, hits + 1, SWAP_RA_HITS_MAX); 683 atomic_long_set(&vma->swap_readahead_info, 684 SWAP_RA_VAL(addr, win, hits)); 685 } 686 687 if (readahead) { 688 count_vm_event(SWAP_RA_HIT); 689 if (!vma || !vma_ra) 690 atomic_inc(&swapin_readahead_hits); 691 } 692 } 693 694 static struct folio *swap_cache_read_folio(struct swap_io_ctx *ctx, 695 swp_entry_t entry, gfp_t gfp, struct mempolicy *mpol, 696 pgoff_t ilx, bool readahead) 697 { 698 struct folio *folio; 699 700 do { 701 folio = swap_cache_get_folio(entry); 702 if (folio) 703 return folio; 704 folio = __swap_cache_alloc_folio(entry, gfp, BIT(0), NULL, mpol, ilx); 705 } while (PTR_ERR(folio) == -EEXIST); 706 707 if (IS_ERR_OR_NULL(folio)) 708 return NULL; 709 710 folio_add_lru(folio); 711 swap_read_folio(ctx, folio); 712 if (readahead) { 713 folio_set_readahead(folio); 714 count_vm_event(SWAP_RA); 715 } 716 717 return folio; 718 } 719 720 /** 721 * swapin_sync - swap-in one or multiple entries skipping readahead. 722 * @entry: swap entry indicating the target slot 723 * @gfp: memory allocation flags 724 * @orders: allocation orders 725 * @vmf: fault information 726 * @mpol: NUMA memory allocation policy to be applied 727 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE 728 * 729 * This allocates a folio suitable for given @orders, or returns the 730 * existing folio in the swap cache for @entry. This initiates the IO, too, 731 * if needed. @entry is rounded down if @orders allow large allocation. 732 * 733 * Context: Caller must ensure @entry is valid and pin the swap device with refcount. 734 * Return: Returns the folio on success, error code if failed. 735 */ 736 struct folio *swapin_sync(swp_entry_t entry, gfp_t gfp, unsigned long orders, 737 struct vm_fault *vmf, struct mempolicy *mpol, pgoff_t ilx) 738 { 739 struct swap_io_ctx ctx = {}; 740 struct folio *folio; 741 742 do { 743 folio = swap_cache_get_folio(entry); 744 if (folio) 745 return folio; 746 folio = __swap_cache_alloc_folio(entry, gfp, orders, vmf, mpol, ilx); 747 } while (PTR_ERR(folio) == -EEXIST); 748 749 if (IS_ERR(folio)) 750 return folio; 751 752 folio_add_lru(folio); 753 swap_read_folio(&ctx, folio); 754 swap_read_submit(&ctx); 755 return folio; 756 } 757 758 /* 759 * Locate a page of swap in physical memory, reserving swap cache space 760 * and reading the disk if it is not already cached. 761 * A failure return means that either the page allocation failed or that 762 * the swap entry is no longer in use. 763 */ 764 struct folio *read_swap_cache_async(struct swap_io_ctx *ctx, swp_entry_t entry, 765 gfp_t gfp_mask, struct vm_area_struct *vma, unsigned long addr) 766 { 767 struct swap_info_struct *si; 768 struct mempolicy *mpol; 769 pgoff_t ilx; 770 struct folio *folio; 771 772 si = get_swap_device(entry); 773 if (IS_ERR_OR_NULL(si)) 774 return NULL; 775 776 mpol = get_vma_policy(vma, addr, 0, &ilx); 777 folio = swap_cache_read_folio(ctx, entry, gfp_mask, mpol, ilx, false); 778 mpol_cond_put(mpol); 779 780 put_swap_device(si); 781 return folio; 782 } 783 784 static struct folio *swap_cache_read_folio_sync(swp_entry_t entry, gfp_t gfp, 785 struct mempolicy *mpol, pgoff_t ilx) 786 { 787 struct swap_io_ctx ctx = {}; 788 struct folio *folio; 789 790 folio = swap_cache_read_folio(&ctx, entry, gfp, mpol, ilx, false); 791 swap_read_submit(&ctx); 792 return folio; 793 } 794 795 static unsigned int __swapin_nr_pages(unsigned long prev_offset, 796 unsigned long offset, 797 int hits, 798 int max_pages, 799 int prev_win) 800 { 801 unsigned int pages, last_ra; 802 803 /* 804 * This heuristic has been found to work well on both sequential and 805 * random loads, swapping to hard disk or to SSD: please don't ask 806 * what the "+ 2" means, it just happens to work well, that's all. 807 */ 808 pages = hits + 2; 809 if (pages == 2) { 810 /* 811 * We can have no readahead hits to judge by: but must not get 812 * stuck here forever, so check for an adjacent offset instead 813 * (and don't even bother to check whether swap type is same). 814 */ 815 if (offset != prev_offset + 1 && offset != prev_offset - 1) 816 pages = 1; 817 } else { 818 unsigned int roundup = 4; 819 while (roundup < pages) 820 roundup <<= 1; 821 pages = roundup; 822 } 823 824 if (pages > max_pages) 825 pages = max_pages; 826 827 /* Don't shrink readahead too fast */ 828 last_ra = prev_win / 2; 829 if (pages < last_ra) 830 pages = last_ra; 831 832 return pages; 833 } 834 835 static unsigned long swapin_nr_pages(unsigned long offset) 836 { 837 static unsigned long prev_offset; 838 unsigned int hits, pages, max_pages; 839 static atomic_t last_readahead_pages; 840 841 max_pages = 1 << READ_ONCE(page_cluster); 842 if (max_pages <= 1) 843 return 1; 844 845 hits = atomic_xchg(&swapin_readahead_hits, 0); 846 pages = __swapin_nr_pages(READ_ONCE(prev_offset), offset, hits, 847 max_pages, 848 atomic_read(&last_readahead_pages)); 849 if (!hits) 850 WRITE_ONCE(prev_offset, offset); 851 atomic_set(&last_readahead_pages, pages); 852 853 return pages; 854 } 855 856 /** 857 * swap_cluster_readahead - swap in pages in hope we need them soon 858 * @entry: swap entry of this memory 859 * @gfp_mask: memory allocation flags 860 * @mpol: NUMA memory allocation policy to be applied 861 * @ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE 862 * 863 * Returns the struct folio for entry and addr, after queueing swapin. 864 * 865 * Primitive swap readahead code. We simply read an aligned block of 866 * (1 << page_cluster) entries in the swap area. This method is chosen 867 * because it doesn't cost us any seek time. We also make sure to queue 868 * the 'original' request together with the readahead ones... 869 * 870 * Note: it is intentional that the same NUMA policy and interleave index 871 * are used for every page of the readahead: neighbouring pages on swap 872 * are fairly likely to have been swapped out from the same node. 873 */ 874 struct folio *swap_cluster_readahead(swp_entry_t entry, gfp_t gfp_mask, 875 struct mempolicy *mpol, pgoff_t ilx) 876 { 877 struct folio *folio; 878 unsigned long entry_offset = swp_offset(entry); 879 unsigned long offset = entry_offset; 880 unsigned long start_offset, end_offset; 881 unsigned long mask; 882 struct swap_info_struct *si = __swap_entry_to_info(entry); 883 struct swap_io_ctx ctx = {}; 884 struct blk_plug plug; 885 swp_entry_t ra_entry; 886 887 mask = swapin_nr_pages(offset) - 1; 888 if (!mask) 889 goto skip; 890 891 /* Read a page_cluster sized and aligned cluster around offset. */ 892 start_offset = offset & ~mask; 893 end_offset = offset | mask; 894 if (!start_offset) /* First page is swap header. */ 895 start_offset++; 896 if (end_offset >= si->max) 897 end_offset = si->max - 1; 898 899 blk_start_plug(&plug); 900 for (offset = start_offset; offset <= end_offset ; offset++) { 901 /* Ok, do the async read-ahead now */ 902 ra_entry = swp_entry(swp_type(entry), offset); 903 folio = swap_cache_read_folio(&ctx, ra_entry, gfp_mask, mpol, 904 ilx, offset != entry_offset); 905 if (!folio) 906 continue; 907 folio_put(folio); 908 } 909 blk_finish_plug(&plug); 910 swap_read_submit(&ctx); 911 skip: 912 return swap_cache_read_folio_sync(entry, gfp_mask, mpol, ilx); 913 } 914 915 static int swap_vma_ra_win(struct vm_fault *vmf, unsigned long *start, 916 unsigned long *end) 917 { 918 struct vm_area_struct *vma = vmf->vma; 919 unsigned long ra_val; 920 unsigned long faddr, prev_faddr, left, right; 921 unsigned int max_win, hits, prev_win, win; 922 923 max_win = 1 << min(READ_ONCE(page_cluster), SWAP_RA_ORDER_CEILING); 924 if (max_win == 1) 925 return 1; 926 927 faddr = vmf->address; 928 ra_val = GET_SWAP_RA_VAL(vma); 929 prev_faddr = SWAP_RA_ADDR(ra_val); 930 prev_win = SWAP_RA_WIN(ra_val); 931 hits = SWAP_RA_HITS(ra_val); 932 win = __swapin_nr_pages(PFN_DOWN(prev_faddr), PFN_DOWN(faddr), hits, 933 max_win, prev_win); 934 atomic_long_set(&vma->swap_readahead_info, SWAP_RA_VAL(faddr, win, 0)); 935 if (win == 1) 936 return 1; 937 938 if (faddr == prev_faddr + PAGE_SIZE) 939 left = faddr; 940 else if (prev_faddr == faddr + PAGE_SIZE) 941 left = faddr - (win << PAGE_SHIFT) + PAGE_SIZE; 942 else 943 left = faddr - (((win - 1) / 2) << PAGE_SHIFT); 944 right = left + (win << PAGE_SHIFT); 945 if ((long)left < 0) 946 left = 0; 947 *start = max3(left, vma->vm_start, faddr & PMD_MASK); 948 *end = min3(right, vma->vm_end, (faddr & PMD_MASK) + PMD_SIZE); 949 950 return win; 951 } 952 953 /** 954 * swap_vma_readahead - swap in pages in hope we need them soon 955 * @targ_entry: swap entry of the targeted memory 956 * @gfp_mask: memory allocation flags 957 * @mpol: NUMA memory allocation policy to be applied 958 * @targ_ilx: NUMA interleave index, for use only when MPOL_INTERLEAVE 959 * @vmf: fault information 960 * 961 * Returns the struct folio for entry and addr, after queueing swapin. 962 * 963 * Primitive swap readahead code. We simply read in a few pages whose 964 * virtual addresses are around the fault address in the same vma. 965 * 966 * Caller must hold read mmap_lock if vmf->vma is not NULL. 967 * 968 */ 969 static struct folio *swap_vma_readahead(swp_entry_t targ_entry, gfp_t gfp_mask, 970 struct mempolicy *mpol, pgoff_t targ_ilx, struct vm_fault *vmf) 971 { 972 struct swap_io_ctx ctx = {}; 973 struct blk_plug plug; 974 struct folio *folio; 975 pte_t *pte = NULL, pentry; 976 int win; 977 unsigned long start, end, addr; 978 pgoff_t ilx = targ_ilx; 979 980 win = swap_vma_ra_win(vmf, &start, &end); 981 if (win == 1) 982 goto skip; 983 984 ilx = targ_ilx - PFN_DOWN(vmf->address - start); 985 986 blk_start_plug(&plug); 987 for (addr = start; addr < end; ilx++, addr += PAGE_SIZE) { 988 struct swap_info_struct *si = NULL; 989 softleaf_t entry; 990 991 if (!pte++) { 992 pte = pte_offset_map(vmf->pmd, addr); 993 if (!pte) 994 break; 995 } 996 pentry = ptep_get_lockless(pte); 997 entry = softleaf_from_pte(pentry); 998 999 if (!softleaf_is_swap(entry)) 1000 continue; 1001 pte_unmap(pte); 1002 pte = NULL; 1003 /* 1004 * Readahead entry may come from a device that we are not 1005 * holding a reference to, try to grab a reference, or skip. 1006 */ 1007 if (swp_type(entry) != swp_type(targ_entry)) { 1008 si = get_swap_device(entry); 1009 if (IS_ERR_OR_NULL(si)) 1010 continue; 1011 } 1012 folio = swap_cache_read_folio(&ctx, entry, gfp_mask, mpol, ilx, 1013 addr != vmf->address); 1014 if (si) 1015 put_swap_device(si); 1016 if (!folio) 1017 continue; 1018 folio_put(folio); 1019 } 1020 if (pte) 1021 pte_unmap(pte); 1022 blk_finish_plug(&plug); 1023 swap_read_submit(&ctx); 1024 skip: 1025 /* The folio was likely read above, so no need for plugging here */ 1026 return swap_cache_read_folio_sync(targ_entry, gfp_mask, mpol, targ_ilx); 1027 } 1028 1029 /** 1030 * swapin_readahead - swap in pages in hope we need them soon 1031 * @entry: swap entry of this memory 1032 * @gfp_mask: memory allocation flags 1033 * @vmf: fault information 1034 * 1035 * Returns the struct folio for entry and addr, after queueing swapin. 1036 * 1037 * It's a main entry function for swap readahead. By the configuration, 1038 * it will read ahead blocks by cluster-based(ie, physical disk based) 1039 * or vma-based(ie, virtual address based on faulty address) readahead. 1040 */ 1041 struct folio *swapin_readahead(swp_entry_t entry, gfp_t gfp_mask, 1042 struct vm_fault *vmf) 1043 { 1044 struct mempolicy *mpol; 1045 pgoff_t ilx; 1046 struct folio *folio; 1047 1048 mpol = get_vma_policy(vmf->vma, vmf->address, 0, &ilx); 1049 folio = swap_use_vma_readahead() ? 1050 swap_vma_readahead(entry, gfp_mask, mpol, ilx, vmf) : 1051 swap_cluster_readahead(entry, gfp_mask, mpol, ilx); 1052 mpol_cond_put(mpol); 1053 1054 return folio; 1055 } 1056 1057 static const struct ctl_table swap_readahead_sysctl_table[] = { 1058 { 1059 .procname = "page-cluster", 1060 .data = &page_cluster, 1061 .maxlen = sizeof(int), 1062 .mode = 0644, 1063 .proc_handler = proc_dointvec_minmax, 1064 .extra1 = SYSCTL_ZERO, 1065 .extra2 = (void *)&page_cluster_max, 1066 } 1067 }; 1068 1069 static void __init swap_readahead_setup(void) 1070 { 1071 unsigned long megs = PAGES_TO_MB(totalram_pages()); 1072 1073 /* Use a smaller cluster for small-memory machines */ 1074 if (megs < 16) 1075 page_cluster = 2; 1076 else 1077 page_cluster = 3; 1078 /* 1079 * Right now other parts of the system means that we 1080 * _really_ don't want to cluster much more 1081 */ 1082 1083 register_sysctl_init("vm", swap_readahead_sysctl_table); 1084 } 1085 1086 #ifdef CONFIG_SYSFS 1087 static ssize_t vma_ra_enabled_show(struct kobject *kobj, 1088 struct kobj_attribute *attr, char *buf) 1089 { 1090 return sysfs_emit(buf, "%s\n", str_true_false(enable_vma_readahead)); 1091 } 1092 static ssize_t vma_ra_enabled_store(struct kobject *kobj, 1093 struct kobj_attribute *attr, 1094 const char *buf, size_t count) 1095 { 1096 ssize_t ret; 1097 1098 ret = kstrtobool(buf, &enable_vma_readahead); 1099 if (ret) 1100 return ret; 1101 1102 return count; 1103 } 1104 static struct kobj_attribute vma_ra_enabled_attr = __ATTR_RW(vma_ra_enabled); 1105 1106 static struct attribute *swap_attrs[] = { 1107 &vma_ra_enabled_attr.attr, 1108 NULL, 1109 }; 1110 1111 static const struct attribute_group swap_attr_group = { 1112 .attrs = swap_attrs, 1113 }; 1114 1115 static int __init swap_sysfs_init(void) 1116 { 1117 int err; 1118 struct kobject *swap_kobj; 1119 1120 swap_kobj = kobject_create_and_add("swap", mm_kobj); 1121 if (!swap_kobj) { 1122 pr_err("failed to create swap kobject\n"); 1123 return -ENOMEM; 1124 } 1125 err = sysfs_create_group(swap_kobj, &swap_attr_group); 1126 if (err) { 1127 pr_err("failed to register swap group\n"); 1128 goto delete_obj; 1129 } 1130 /* Swap cache writeback is LRU based, no tags for it */ 1131 mapping_set_no_writeback_tags(&swap_space); 1132 return 0; 1133 1134 delete_obj: 1135 kobject_put(swap_kobj); 1136 return err; 1137 } 1138 #else 1139 static int __init swap_sysfs_init(void) 1140 { 1141 return 0; 1142 } 1143 #endif 1144 1145 static int __init swap_init(void) 1146 { 1147 swap_readahead_setup(); 1148 1149 return swap_sysfs_init(); 1150 } 1151 subsys_initcall(swap_init); 1152