1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * linux/mm/swapfile.c 4 * 5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds 6 * Swap reorganised 29.12.95, Stephen Tweedie 7 */ 8 9 #include <linux/blkdev.h> 10 #include <linux/mm.h> 11 #include <linux/sched/mm.h> 12 #include <linux/sched/task.h> 13 #include <linux/hugetlb.h> 14 #include <linux/mman.h> 15 #include <linux/slab.h> 16 #include <linux/kernel_stat.h> 17 #include <linux/swap.h> 18 #include <linux/vmalloc.h> 19 #include <linux/pagemap.h> 20 #include <linux/namei.h> 21 #include <linux/shmem_fs.h> 22 #include <linux/blk-cgroup.h> 23 #include <linux/random.h> 24 #include <linux/writeback.h> 25 #include <linux/proc_fs.h> 26 #include <linux/seq_file.h> 27 #include <linux/init.h> 28 #include <linux/ksm.h> 29 #include <linux/rmap.h> 30 #include <linux/security.h> 31 #include <linux/backing-dev.h> 32 #include <linux/mutex.h> 33 #include <linux/capability.h> 34 #include <linux/syscalls.h> 35 #include <linux/memcontrol.h> 36 #include <linux/poll.h> 37 #include <linux/oom.h> 38 #include <linux/swapfile.h> 39 #include <linux/export.h> 40 #include <linux/sort.h> 41 #include <linux/completion.h> 42 #include <linux/suspend.h> 43 #include <linux/zswap.h> 44 #include <linux/plist.h> 45 46 #include <asm/tlbflush.h> 47 #include <linux/leafops.h> 48 #include "swap_table.h" 49 #include "internal.h" 50 #include "swap.h" 51 52 static void swap_range_alloc(struct swap_info_struct *si, 53 unsigned int nr_entries); 54 static bool folio_swapcache_freeable(struct folio *folio); 55 static void move_cluster(struct swap_info_struct *si, 56 struct swap_cluster_info *ci, struct list_head *list, 57 enum swap_cluster_flags new_flags); 58 59 /* 60 * Protects the swap_info array, and the SWP_USED flag. swap_info contains 61 * lazily allocated & freed swap device info struts, and SWP_USED indicates 62 * which device is used, ~SWP_USED devices and can be reused. 63 * 64 * Also protects swap_active_head total_swap_pages, and the SWP_WRITEOK flag. 65 */ 66 static DEFINE_SPINLOCK(swap_lock); 67 static unsigned int nr_swapfiles; 68 atomic_long_t nr_swap_pages; 69 /* 70 * Some modules use swappable objects and may try to swap them out under 71 * memory pressure (via the shrinker). Before doing so, they may wish to 72 * check to see if any swap space is available. 73 */ 74 EXPORT_SYMBOL_GPL(nr_swap_pages); 75 /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */ 76 long total_swap_pages; 77 #define DEF_SWAP_PRIO -1 78 unsigned long swapfile_maximum_size; 79 #ifdef CONFIG_MIGRATION 80 bool swap_migration_ad_supported; 81 #endif /* CONFIG_MIGRATION */ 82 83 static const char Bad_file[] = "Bad swap file entry "; 84 static const char Bad_offset[] = "Bad swap offset entry "; 85 86 /* 87 * all active swap_info_structs 88 * protected with swap_lock, and ordered by priority. 89 */ 90 static PLIST_HEAD(swap_active_head); 91 92 /* 93 * all available (active, not full) swap_info_structs 94 * protected with swap_avail_lock, ordered by priority. 95 * This is used by folio_alloc_swap() instead of swap_active_head 96 * because swap_active_head includes all swap_info_structs, 97 * but folio_alloc_swap() doesn't need to look at full ones. 98 * This uses its own lock instead of swap_lock because when a 99 * swap_info_struct changes between not-full/full, it needs to 100 * add/remove itself to/from this list, but the swap_info_struct->lock 101 * is held and the locking order requires swap_lock to be taken 102 * before any swap_info_struct->lock. 103 */ 104 static PLIST_HEAD(swap_avail_head); 105 static DEFINE_SPINLOCK(swap_avail_lock); 106 107 struct swap_info_struct *swap_info[MAX_SWAPFILES]; 108 109 static struct kmem_cache *swap_table_cachep; 110 111 /* Protects si->swap_file for /proc/swaps usage */ 112 static DEFINE_MUTEX(swapon_mutex); 113 114 static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait); 115 /* Activity counter to indicate that a swapon or swapoff has occurred */ 116 static atomic_t proc_poll_event = ATOMIC_INIT(0); 117 118 atomic_t nr_rotate_swap = ATOMIC_INIT(0); 119 120 struct percpu_swap_cluster { 121 struct swap_info_struct *si[SWAP_NR_ORDERS]; 122 unsigned long offset[SWAP_NR_ORDERS]; 123 local_lock_t lock; 124 }; 125 126 static DEFINE_PER_CPU(struct percpu_swap_cluster, percpu_swap_cluster) = { 127 .si = { NULL }, 128 .offset = { SWAP_ENTRY_INVALID }, 129 .lock = INIT_LOCAL_LOCK(), 130 }; 131 132 /* May return NULL on invalid type, caller must check for NULL return */ 133 static struct swap_info_struct *swap_type_to_info(int type) 134 { 135 if (type >= MAX_SWAPFILES) 136 return NULL; 137 return READ_ONCE(swap_info[type]); /* rcu_dereference() */ 138 } 139 140 /* May return NULL on invalid entry, caller must check for NULL return */ 141 static struct swap_info_struct *swap_entry_to_info(swp_entry_t entry) 142 { 143 return swap_type_to_info(swp_type(entry)); 144 } 145 146 /* 147 * Use the second highest bit of inuse_pages counter as the indicator 148 * if one swap device is on the available plist, so the atomic can 149 * still be updated arithmetically while having special data embedded. 150 * 151 * inuse_pages counter is the only thing indicating if a device should 152 * be on avail_lists or not (except swapon / swapoff). By embedding the 153 * off-list bit in the atomic counter, updates no longer need any lock 154 * to check the list status. 155 * 156 * This bit will be set if the device is not on the plist and not 157 * usable, will be cleared if the device is on the plist. 158 */ 159 #define SWAP_USAGE_OFFLIST_BIT (1UL << (BITS_PER_TYPE(atomic_t) - 2)) 160 #define SWAP_USAGE_COUNTER_MASK (~SWAP_USAGE_OFFLIST_BIT) 161 static long swap_usage_in_pages(struct swap_info_struct *si) 162 { 163 return atomic_long_read(&si->inuse_pages) & SWAP_USAGE_COUNTER_MASK; 164 } 165 166 /* Reclaim the swap entry anyway if possible */ 167 #define TTRS_ANYWAY 0x1 168 /* 169 * Reclaim the swap entry if there are no more mappings of the 170 * corresponding page 171 */ 172 #define TTRS_UNMAPPED 0x2 173 /* Reclaim the swap entry if swap is getting full */ 174 #define TTRS_FULL 0x4 175 176 static bool swap_only_has_cache(struct swap_cluster_info *ci, 177 unsigned long offset, int nr_pages) 178 { 179 unsigned int ci_off = offset % SWAPFILE_CLUSTER; 180 unsigned int ci_end = ci_off + nr_pages; 181 unsigned long swp_tb; 182 183 do { 184 swp_tb = __swap_table_get(ci, ci_off); 185 VM_WARN_ON_ONCE(!swp_tb_is_folio(swp_tb)); 186 if (swp_tb_get_count(swp_tb)) 187 return false; 188 } while (++ci_off < ci_end); 189 190 return true; 191 } 192 193 /* 194 * returns number of pages in the folio that backs the swap entry. If positive, 195 * the folio was reclaimed. If negative, the folio was not reclaimed. If 0, no 196 * folio was associated with the swap entry. 197 */ 198 static int __try_to_reclaim_swap(struct swap_info_struct *si, 199 unsigned long offset, unsigned long flags) 200 { 201 const swp_entry_t entry = swp_entry(si->type, offset); 202 struct swap_cluster_info *ci; 203 struct folio *folio; 204 int ret, nr_pages; 205 bool need_reclaim; 206 207 again: 208 folio = swap_cache_get_folio(entry); 209 if (!folio) 210 return 0; 211 212 nr_pages = folio_nr_pages(folio); 213 ret = -nr_pages; 214 215 /* 216 * We hold a folio lock here. We have to use trylock for 217 * avoiding deadlock. This is a special case and you should 218 * use folio_free_swap() with explicit folio_lock() in usual 219 * operations. 220 */ 221 if (!folio_trylock(folio)) 222 goto out; 223 224 /* 225 * Offset could point to the middle of a large folio, or folio 226 * may no longer point to the expected offset before it's locked. 227 */ 228 if (!folio_matches_swap_entry(folio, entry)) { 229 folio_unlock(folio); 230 folio_put(folio); 231 goto again; 232 } 233 offset = swp_offset(folio->swap); 234 235 need_reclaim = ((flags & TTRS_ANYWAY) || 236 ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) || 237 ((flags & TTRS_FULL) && mem_cgroup_swap_full(folio))); 238 if (!need_reclaim || !folio_swapcache_freeable(folio)) 239 goto out_unlock; 240 241 /* 242 * It's safe to delete the folio from swap cache only if the folio 243 * is in swap cache with swap count == 0. The slots have no page table 244 * reference or pending writeback, and can't be allocated to others. 245 */ 246 ci = swap_cluster_lock(si, offset); 247 need_reclaim = swap_only_has_cache(ci, offset, nr_pages); 248 swap_cluster_unlock(ci); 249 if (!need_reclaim) 250 goto out_unlock; 251 252 swap_cache_del_folio(folio); 253 folio_set_dirty(folio); 254 ret = nr_pages; 255 out_unlock: 256 folio_unlock(folio); 257 out: 258 folio_put(folio); 259 return ret; 260 } 261 262 static inline struct swap_extent *first_se(struct swap_info_struct *sis) 263 { 264 struct rb_node *rb = rb_first(&sis->swap_extent_root); 265 return rb_entry(rb, struct swap_extent, rb_node); 266 } 267 268 static inline struct swap_extent *next_se(struct swap_extent *se) 269 { 270 struct rb_node *rb = rb_next(&se->rb_node); 271 return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL; 272 } 273 274 /* 275 * swapon tell device that all the old swap contents can be discarded, 276 * to allow the swap device to optimize its wear-levelling. 277 */ 278 static int discard_swap(struct swap_info_struct *si) 279 { 280 struct swap_extent *se; 281 sector_t start_block; 282 sector_t nr_blocks; 283 int err = 0; 284 285 /* Do not discard the swap header page! */ 286 se = first_se(si); 287 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9); 288 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9); 289 if (nr_blocks) { 290 err = blkdev_issue_discard(si->bdev, start_block, 291 nr_blocks, GFP_KERNEL); 292 if (err) 293 return err; 294 cond_resched(); 295 } 296 297 for (se = next_se(se); se; se = next_se(se)) { 298 start_block = se->start_block << (PAGE_SHIFT - 9); 299 nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9); 300 301 err = blkdev_issue_discard(si->bdev, start_block, 302 nr_blocks, GFP_KERNEL); 303 if (err) 304 break; 305 306 cond_resched(); 307 } 308 return err; /* That will often be -EOPNOTSUPP */ 309 } 310 311 static struct swap_extent * 312 offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset) 313 { 314 struct swap_extent *se; 315 struct rb_node *rb; 316 317 rb = sis->swap_extent_root.rb_node; 318 while (rb) { 319 se = rb_entry(rb, struct swap_extent, rb_node); 320 if (offset < se->start_page) 321 rb = rb->rb_left; 322 else if (offset >= se->start_page + se->nr_pages) 323 rb = rb->rb_right; 324 else 325 return se; 326 } 327 /* It *must* be present */ 328 BUG(); 329 } 330 331 sector_t swap_folio_sector(struct folio *folio) 332 { 333 struct swap_info_struct *sis = __swap_entry_to_info(folio->swap); 334 struct swap_extent *se; 335 sector_t sector; 336 pgoff_t offset; 337 338 offset = swp_offset(folio->swap); 339 se = offset_to_swap_extent(sis, offset); 340 sector = se->start_block + (offset - se->start_page); 341 return sector << (PAGE_SHIFT - 9); 342 } 343 344 /* 345 * swap allocation tell device that a cluster of swap can now be discarded, 346 * to allow the swap device to optimize its wear-levelling. 347 */ 348 static void discard_swap_cluster(struct swap_info_struct *si, 349 pgoff_t start_page, pgoff_t nr_pages) 350 { 351 struct swap_extent *se = offset_to_swap_extent(si, start_page); 352 353 while (nr_pages) { 354 pgoff_t offset = start_page - se->start_page; 355 sector_t start_block = se->start_block + offset; 356 sector_t nr_blocks = se->nr_pages - offset; 357 358 if (nr_blocks > nr_pages) 359 nr_blocks = nr_pages; 360 start_page += nr_blocks; 361 nr_pages -= nr_blocks; 362 363 start_block <<= PAGE_SHIFT - 9; 364 nr_blocks <<= PAGE_SHIFT - 9; 365 if (blkdev_issue_discard(si->bdev, start_block, 366 nr_blocks, GFP_NOIO)) 367 break; 368 369 se = next_se(se); 370 } 371 } 372 373 #define LATENCY_LIMIT 256 374 375 static inline bool cluster_is_empty(struct swap_cluster_info *info) 376 { 377 return info->count == 0; 378 } 379 380 static inline bool cluster_is_discard(struct swap_cluster_info *info) 381 { 382 return info->flags == CLUSTER_FLAG_DISCARD; 383 } 384 385 static inline bool cluster_table_is_alloced(struct swap_cluster_info *ci) 386 { 387 return rcu_dereference_protected(ci->table, lockdep_is_held(&ci->lock)); 388 } 389 390 static inline bool cluster_is_usable(struct swap_cluster_info *ci, int order) 391 { 392 if (unlikely(ci->flags > CLUSTER_FLAG_USABLE)) 393 return false; 394 if (!cluster_table_is_alloced(ci)) 395 return false; 396 if (!order) 397 return true; 398 return cluster_is_empty(ci) || order == ci->order; 399 } 400 401 static inline unsigned int cluster_index(struct swap_info_struct *si, 402 struct swap_cluster_info *ci) 403 { 404 return ci - si->cluster_info; 405 } 406 407 static inline unsigned int cluster_offset(struct swap_info_struct *si, 408 struct swap_cluster_info *ci) 409 { 410 return cluster_index(si, ci) * SWAPFILE_CLUSTER; 411 } 412 413 static void swap_cluster_free_table_folio_rcu_cb(struct rcu_head *head) 414 { 415 struct folio *folio; 416 417 folio = page_folio(container_of(head, struct page, rcu_head)); 418 folio_put(folio); 419 } 420 421 static void swap_cluster_free_table(struct swap_cluster_info *ci) 422 { 423 struct swap_table *table; 424 425 #ifdef CONFIG_MEMCG 426 kfree(ci->memcg_table); 427 ci->memcg_table = NULL; 428 #endif 429 430 #if !SWAP_TABLE_HAS_ZEROFLAG 431 kfree(ci->zero_bitmap); 432 ci->zero_bitmap = NULL; 433 #endif 434 435 table = (struct swap_table *)rcu_access_pointer(ci->table); 436 if (!table) 437 return; 438 439 rcu_assign_pointer(ci->table, NULL); 440 if (!SWP_TABLE_USE_PAGE) { 441 kmem_cache_free(swap_table_cachep, table); 442 return; 443 } 444 445 call_rcu(&(folio_page(virt_to_folio(table), 0)->rcu_head), 446 swap_cluster_free_table_folio_rcu_cb); 447 } 448 449 static int swap_cluster_alloc_table(struct swap_cluster_info *ci, gfp_t gfp) 450 { 451 struct swap_table *table = NULL; 452 struct folio *folio; 453 454 /* The cluster must be empty and not on any list during allocation. */ 455 VM_WARN_ON_ONCE(ci->flags || !cluster_is_empty(ci)); 456 if (rcu_access_pointer(ci->table)) 457 return 0; 458 459 if (SWP_TABLE_USE_PAGE) { 460 folio = folio_alloc(gfp | __GFP_ZERO, 0); 461 if (folio) 462 table = folio_address(folio); 463 } else { 464 table = kmem_cache_zalloc(swap_table_cachep, gfp); 465 } 466 if (!table) 467 return -ENOMEM; 468 469 rcu_assign_pointer(ci->table, table); 470 471 #ifdef CONFIG_MEMCG 472 if (!mem_cgroup_disabled()) { 473 VM_WARN_ON_ONCE(ci->memcg_table); 474 ci->memcg_table = kzalloc_obj(*ci->memcg_table, gfp); 475 if (!ci->memcg_table) { 476 swap_cluster_free_table(ci); 477 return -ENOMEM; 478 } 479 } 480 #endif 481 482 #if !SWAP_TABLE_HAS_ZEROFLAG 483 VM_WARN_ON_ONCE(ci->zero_bitmap); 484 ci->zero_bitmap = bitmap_zalloc(SWAPFILE_CLUSTER, gfp); 485 if (!ci->zero_bitmap) { 486 swap_cluster_free_table(ci); 487 return -ENOMEM; 488 } 489 #endif 490 return 0; 491 } 492 493 /* 494 * Sanity check to ensure nothing leaked, and the specified range is empty. 495 * One special case is that bad slots can't be freed, so check the number of 496 * bad slots for swapoff, and non-swapoff path must never free bad slots. 497 */ 498 static void swap_cluster_assert_empty(struct swap_cluster_info *ci, 499 unsigned int ci_off, unsigned int nr, 500 bool swapoff) 501 { 502 unsigned int ci_end = ci_off + nr; 503 unsigned long swp_tb; 504 int bad_slots = 0; 505 506 if (!IS_ENABLED(CONFIG_DEBUG_VM) && !swapoff) 507 return; 508 509 do { 510 swp_tb = __swap_table_get(ci, ci_off); 511 if (swp_tb_is_bad(swp_tb)) 512 bad_slots++; 513 else 514 WARN_ON_ONCE(!swp_tb_is_null(swp_tb)); 515 WARN_ON_ONCE(__swap_cgroup_get(ci, ci_off)); 516 } while (++ci_off < ci_end); 517 518 WARN_ON_ONCE(bad_slots != (swapoff ? ci->count : 0)); 519 WARN_ON_ONCE(nr == SWAPFILE_CLUSTER && ci->extend_table); 520 } 521 522 /* 523 * Allocate swap table for one cluster. Attempt an atomic allocation first, 524 * then fallback to sleeping allocation. 525 */ 526 static struct swap_cluster_info * 527 swap_cluster_populate(struct swap_info_struct *si, 528 struct swap_cluster_info *ci) 529 { 530 int ret; 531 532 /* 533 * Only cluster isolation from the allocator does table allocation. 534 * Swap allocator uses percpu clusters and holds the local lock. 535 */ 536 lockdep_assert_held(&this_cpu_ptr(&percpu_swap_cluster)->lock); 537 if (!(si->flags & SWP_SOLIDSTATE)) 538 lockdep_assert_held(&si->global_cluster_lock); 539 lockdep_assert_held(&ci->lock); 540 541 if (!swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | 542 __GFP_NOWARN)) 543 return ci; 544 545 /* 546 * Try a sleep allocation. Each isolated free cluster may cause 547 * a sleep allocation, but there is a limited number of them, so 548 * the potential recursive allocation is limited. 549 */ 550 spin_unlock(&ci->lock); 551 if (!(si->flags & SWP_SOLIDSTATE)) 552 spin_unlock(&si->global_cluster_lock); 553 local_unlock(&percpu_swap_cluster.lock); 554 555 ret = swap_cluster_alloc_table(ci, __GFP_HIGH | __GFP_NOMEMALLOC | 556 GFP_KERNEL); 557 558 /* 559 * Back to atomic context. We might have migrated to a new CPU with a 560 * usable percpu cluster. But just keep using the isolated cluster to 561 * make things easier. Migration indicates a slight change of workload 562 * so using a new free cluster might not be a bad idea, and the worst 563 * could happen with ignoring the percpu cluster is fragmentation, 564 * which is acceptable since this fallback and race is rare. 565 */ 566 local_lock(&percpu_swap_cluster.lock); 567 if (!(si->flags & SWP_SOLIDSTATE)) 568 spin_lock(&si->global_cluster_lock); 569 spin_lock(&ci->lock); 570 571 if (ret) { 572 move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); 573 spin_unlock(&ci->lock); 574 return NULL; 575 } 576 return ci; 577 } 578 579 static void move_cluster(struct swap_info_struct *si, 580 struct swap_cluster_info *ci, struct list_head *list, 581 enum swap_cluster_flags new_flags) 582 { 583 VM_WARN_ON(ci->flags == new_flags); 584 585 BUILD_BUG_ON(1 << sizeof(ci->flags) * BITS_PER_BYTE < CLUSTER_FLAG_MAX); 586 lockdep_assert_held(&ci->lock); 587 588 spin_lock(&si->lock); 589 if (ci->flags == CLUSTER_FLAG_NONE) 590 list_add_tail(&ci->list, list); 591 else 592 list_move_tail(&ci->list, list); 593 spin_unlock(&si->lock); 594 ci->flags = new_flags; 595 } 596 597 /* Add a cluster to discard list and schedule it to do discard */ 598 static void swap_cluster_schedule_discard(struct swap_info_struct *si, 599 struct swap_cluster_info *ci) 600 { 601 VM_BUG_ON(ci->flags == CLUSTER_FLAG_FREE); 602 move_cluster(si, ci, &si->discard_clusters, CLUSTER_FLAG_DISCARD); 603 schedule_work(&si->discard_work); 604 } 605 606 static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci) 607 { 608 swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, false); 609 swap_cluster_free_table(ci); 610 move_cluster(si, ci, &si->free_clusters, CLUSTER_FLAG_FREE); 611 ci->order = 0; 612 } 613 614 /* 615 * Isolate and lock the first cluster that is not contented on a list, 616 * clean its flag before taken off-list. Cluster flag must be in sync 617 * with list status, so cluster updaters can always know the cluster 618 * list status without touching si lock. 619 * 620 * Note it's possible that all clusters on a list are contented so 621 * this returns NULL for an non-empty list. 622 */ 623 static struct swap_cluster_info *isolate_lock_cluster( 624 struct swap_info_struct *si, struct list_head *list) 625 { 626 struct swap_cluster_info *ci, *found = NULL; 627 u8 flags = CLUSTER_FLAG_NONE; 628 629 spin_lock(&si->lock); 630 list_for_each_entry(ci, list, list) { 631 if (!spin_trylock(&ci->lock)) 632 continue; 633 634 /* We may only isolate and clear flags of following lists */ 635 VM_BUG_ON(!ci->flags); 636 VM_BUG_ON(ci->flags > CLUSTER_FLAG_USABLE && 637 ci->flags != CLUSTER_FLAG_FULL); 638 639 list_del(&ci->list); 640 flags = ci->flags; 641 ci->flags = CLUSTER_FLAG_NONE; 642 found = ci; 643 break; 644 } 645 spin_unlock(&si->lock); 646 647 /* Cluster's table is freed when and only when it's on the free list. */ 648 if (found && flags == CLUSTER_FLAG_FREE) { 649 VM_WARN_ON_ONCE(list != &si->free_clusters); 650 VM_WARN_ON_ONCE(cluster_table_is_alloced(found)); 651 return swap_cluster_populate(si, found); 652 } 653 654 return found; 655 } 656 657 /* 658 * Doing discard actually. After a cluster discard is finished, the cluster 659 * will be added to free cluster list. Discard cluster is a bit special as 660 * they don't participate in allocation or reclaim, so clusters marked as 661 * CLUSTER_FLAG_DISCARD must remain off-list or on discard list. 662 */ 663 static bool swap_do_scheduled_discard(struct swap_info_struct *si) 664 { 665 struct swap_cluster_info *ci; 666 bool ret = false; 667 unsigned int idx; 668 669 spin_lock(&si->lock); 670 while (!list_empty(&si->discard_clusters)) { 671 ci = list_first_entry(&si->discard_clusters, struct swap_cluster_info, list); 672 /* 673 * Delete the cluster from list to prepare for discard, but keep 674 * the CLUSTER_FLAG_DISCARD flag, percpu_swap_cluster could be 675 * pointing to it, or ran into by relocate_cluster. 676 */ 677 list_del(&ci->list); 678 idx = cluster_index(si, ci); 679 spin_unlock(&si->lock); 680 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER, 681 SWAPFILE_CLUSTER); 682 683 spin_lock(&ci->lock); 684 /* 685 * Discard is done, clear its flags as it's off-list, then 686 * return the cluster to allocation list. 687 */ 688 ci->flags = CLUSTER_FLAG_NONE; 689 __free_cluster(si, ci); 690 spin_unlock(&ci->lock); 691 ret = true; 692 spin_lock(&si->lock); 693 } 694 spin_unlock(&si->lock); 695 return ret; 696 } 697 698 static void swap_discard_work(struct work_struct *work) 699 { 700 struct swap_info_struct *si; 701 702 si = container_of(work, struct swap_info_struct, discard_work); 703 704 swap_do_scheduled_discard(si); 705 } 706 707 static void swap_users_ref_free(struct percpu_ref *ref) 708 { 709 struct swap_info_struct *si; 710 711 si = container_of(ref, struct swap_info_struct, users); 712 complete(&si->comp); 713 } 714 715 /* 716 * Must be called after freeing if ci->count == 0, moves the cluster to free 717 * or discard list. 718 */ 719 static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci) 720 { 721 VM_BUG_ON(ci->count != 0); 722 VM_BUG_ON(ci->flags == CLUSTER_FLAG_FREE); 723 lockdep_assert_held(&ci->lock); 724 725 /* 726 * If the swap is discardable, prepare discard the cluster 727 * instead of free it immediately. The cluster will be freed 728 * after discard. 729 */ 730 if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) == 731 (SWP_WRITEOK | SWP_PAGE_DISCARD)) { 732 swap_cluster_schedule_discard(si, ci); 733 return; 734 } 735 736 __free_cluster(si, ci); 737 } 738 739 /* 740 * Must be called after freeing if ci->count != 0, moves the cluster to 741 * nonfull list. 742 */ 743 static void partial_free_cluster(struct swap_info_struct *si, 744 struct swap_cluster_info *ci) 745 { 746 VM_BUG_ON(!ci->count || ci->count == SWAPFILE_CLUSTER); 747 lockdep_assert_held(&ci->lock); 748 749 if (ci->flags != CLUSTER_FLAG_NONFULL) 750 move_cluster(si, ci, &si->nonfull_clusters[ci->order], 751 CLUSTER_FLAG_NONFULL); 752 } 753 754 /* 755 * Must be called after allocation, moves the cluster to full or frag list. 756 * Note: allocation doesn't acquire si lock, and may drop the ci lock for 757 * reclaim, so the cluster could be any where when called. 758 */ 759 static void relocate_cluster(struct swap_info_struct *si, 760 struct swap_cluster_info *ci) 761 { 762 lockdep_assert_held(&ci->lock); 763 764 /* Discard cluster must remain off-list or on discard list */ 765 if (cluster_is_discard(ci)) 766 return; 767 768 if (!ci->count) { 769 if (ci->flags != CLUSTER_FLAG_FREE) 770 free_cluster(si, ci); 771 } else if (ci->count != SWAPFILE_CLUSTER) { 772 if (ci->flags != CLUSTER_FLAG_FRAG) 773 move_cluster(si, ci, &si->frag_clusters[ci->order], 774 CLUSTER_FLAG_FRAG); 775 } else { 776 if (ci->flags != CLUSTER_FLAG_FULL) 777 move_cluster(si, ci, &si->full_clusters, 778 CLUSTER_FLAG_FULL); 779 } 780 } 781 782 /* 783 * The cluster corresponding to @offset will be accounted as having one bad 784 * slot. The cluster will not be added to the free cluster list, and its 785 * usage counter will be increased by 1. Only used for initialization. 786 */ 787 static int swap_cluster_setup_bad_slot(struct swap_info_struct *si, 788 struct swap_cluster_info *cluster_info, 789 unsigned int offset, bool mask) 790 { 791 unsigned int ci_off = offset % SWAPFILE_CLUSTER; 792 unsigned long idx = offset / SWAPFILE_CLUSTER; 793 struct swap_cluster_info *ci; 794 int ret = 0; 795 796 /* si->max may got shrunk by swap swap_activate() */ 797 if (offset >= si->max && !mask) { 798 pr_debug("Ignoring bad slot %u (max: %u)\n", offset, si->max); 799 return 0; 800 } 801 /* 802 * Account it, skip header slot: si->pages is initiated as 803 * si->max - 1. Also skip the masking of last cluster, 804 * si->pages doesn't include that part. 805 */ 806 if (offset && !mask) 807 si->pages -= 1; 808 if (!si->pages) { 809 pr_warn("Empty swap-file\n"); 810 return -EINVAL; 811 } 812 813 ci = cluster_info + idx; 814 /* Need to allocate swap table first for initial bad slot marking. */ 815 if (!ci->count && swap_cluster_alloc_table(ci, GFP_KERNEL)) 816 return -ENOMEM; 817 spin_lock(&ci->lock); 818 /* Check for duplicated bad swap slots. */ 819 if (__swap_table_xchg(ci, ci_off, SWP_TB_BAD) != SWP_TB_NULL) { 820 pr_warn("Duplicated bad slot offset %d\n", offset); 821 ret = -EINVAL; 822 } else { 823 ci->count++; 824 } 825 spin_unlock(&ci->lock); 826 827 WARN_ON(ci->count > SWAPFILE_CLUSTER); 828 WARN_ON(ci->flags); 829 830 return ret; 831 } 832 833 /* 834 * Reclaim drops the ci lock, so the cluster may become unusable (freed or 835 * stolen by a lower order). @usable will be set to false if that happens. 836 */ 837 static bool cluster_reclaim_range(struct swap_info_struct *si, 838 struct swap_cluster_info *ci, 839 unsigned long start, unsigned int order, 840 bool *usable) 841 { 842 unsigned int nr_pages = 1 << order; 843 unsigned long offset = start, end = start + nr_pages; 844 unsigned long swp_tb; 845 846 spin_unlock(&ci->lock); 847 do { 848 swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER); 849 if (swp_tb_get_count(swp_tb)) 850 break; 851 if (swp_tb_is_folio(swp_tb)) 852 if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY) < 0) 853 break; 854 } while (++offset < end); 855 spin_lock(&ci->lock); 856 857 /* 858 * We just dropped ci->lock so cluster could be used by another 859 * order or got freed, check if it's still usable or empty. 860 */ 861 if (!cluster_is_usable(ci, order)) { 862 *usable = false; 863 return false; 864 } 865 *usable = true; 866 867 /* Fast path, no need to scan if the whole cluster is empty */ 868 if (cluster_is_empty(ci)) 869 return true; 870 871 /* 872 * Recheck the range no matter reclaim succeeded or not, the slot 873 * could have been be freed while we are not holding the lock. 874 */ 875 for (offset = start; offset < end; offset++) { 876 swp_tb = __swap_table_get(ci, offset % SWAPFILE_CLUSTER); 877 if (!swp_tb_is_null(swp_tb)) 878 return false; 879 } 880 881 return true; 882 } 883 884 static bool cluster_scan_range(struct swap_info_struct *si, 885 struct swap_cluster_info *ci, 886 unsigned long offset, unsigned int nr_pages, 887 bool *need_reclaim) 888 { 889 unsigned int ci_off = offset % SWAPFILE_CLUSTER; 890 unsigned int ci_end = ci_off + nr_pages; 891 unsigned long swp_tb; 892 893 do { 894 swp_tb = __swap_table_get(ci, ci_off); 895 if (swp_tb_is_null(swp_tb)) 896 continue; 897 if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) { 898 if (!vm_swap_full()) 899 return false; 900 *need_reclaim = true; 901 continue; 902 } 903 /* Slot with zero count can only be NULL or folio */ 904 VM_WARN_ON(!swp_tb_get_count(swp_tb)); 905 return false; 906 } while (++ci_off < ci_end); 907 908 return true; 909 } 910 911 static bool __swap_cluster_alloc_entries(struct swap_info_struct *si, 912 struct swap_cluster_info *ci, 913 struct folio *folio, 914 unsigned int ci_off) 915 { 916 unsigned int order; 917 unsigned long nr_pages; 918 919 lockdep_assert_held(&ci->lock); 920 921 if (!(si->flags & SWP_WRITEOK)) 922 return false; 923 924 /* 925 * All mm swap allocation starts with a folio (folio_alloc_swap), 926 * it's also the only allocation path for large orders allocation. 927 * Such swap slots starts with count == 0 and will be increased 928 * upon folio unmap. 929 * 930 * Else, it's a exclusive order 0 allocation for hibernation. 931 * The slot starts with count == 1 and never increases. 932 */ 933 if (likely(folio)) { 934 order = folio_order(folio); 935 nr_pages = 1 << order; 936 swap_cluster_assert_empty(ci, ci_off, nr_pages, false); 937 __swap_cache_add_folio(ci, folio, swp_entry(si->type, 938 ci_off + cluster_offset(si, ci))); 939 } else if (IS_ENABLED(CONFIG_HIBERNATION)) { 940 order = 0; 941 nr_pages = 1; 942 swap_cluster_assert_empty(ci, ci_off, 1, false); 943 /* Fake shadow placeholder with no flag, hibernation does not use the zeromap */ 944 __swap_table_set(ci, ci_off, __swp_tb_mk_count(shadow_to_swp_tb(NULL, 0), 1)); 945 } else { 946 /* Allocation without folio is only possible with hibernation */ 947 WARN_ON_ONCE(1); 948 return false; 949 } 950 951 /* 952 * The first allocation in a cluster makes the 953 * cluster exclusive to this order 954 */ 955 if (cluster_is_empty(ci)) 956 ci->order = order; 957 ci->count += nr_pages; 958 swap_range_alloc(si, nr_pages); 959 960 return true; 961 } 962 963 /* Try use a new cluster for current CPU and allocate from it. */ 964 static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, 965 struct swap_cluster_info *ci, 966 struct folio *folio, unsigned long offset) 967 { 968 unsigned int next = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID; 969 unsigned long start = ALIGN_DOWN(offset, SWAPFILE_CLUSTER); 970 unsigned int order = likely(folio) ? folio_order(folio) : 0; 971 unsigned long end = start + SWAPFILE_CLUSTER; 972 unsigned int nr_pages = 1 << order; 973 bool need_reclaim, ret, usable; 974 975 lockdep_assert_held(&ci->lock); 976 VM_WARN_ON(!cluster_is_usable(ci, order)); 977 978 if (end < nr_pages || ci->count + nr_pages > SWAPFILE_CLUSTER) 979 goto out; 980 981 for (end -= nr_pages; offset <= end; offset += nr_pages) { 982 need_reclaim = false; 983 if (!cluster_scan_range(si, ci, offset, nr_pages, &need_reclaim)) 984 continue; 985 if (need_reclaim) { 986 ret = cluster_reclaim_range(si, ci, offset, order, &usable); 987 if (!usable) 988 goto out; 989 if (cluster_is_empty(ci)) 990 offset = start; 991 /* Reclaim failed but cluster is usable, try next */ 992 if (!ret) 993 continue; 994 } 995 if (!__swap_cluster_alloc_entries(si, ci, folio, offset % SWAPFILE_CLUSTER)) 996 break; 997 found = offset; 998 offset += nr_pages; 999 if (ci->count < SWAPFILE_CLUSTER && offset <= end) 1000 next = offset; 1001 break; 1002 } 1003 out: 1004 relocate_cluster(si, ci); 1005 swap_cluster_unlock(ci); 1006 if (si->flags & SWP_SOLIDSTATE) { 1007 this_cpu_write(percpu_swap_cluster.offset[order], next); 1008 this_cpu_write(percpu_swap_cluster.si[order], si); 1009 } else { 1010 si->global_cluster->next[order] = next; 1011 } 1012 return found; 1013 } 1014 1015 static unsigned int alloc_swap_scan_list(struct swap_info_struct *si, 1016 struct list_head *list, 1017 struct folio *folio, 1018 bool scan_all) 1019 { 1020 unsigned int found = SWAP_ENTRY_INVALID; 1021 1022 do { 1023 struct swap_cluster_info *ci = isolate_lock_cluster(si, list); 1024 unsigned long offset; 1025 1026 if (!ci) 1027 break; 1028 offset = cluster_offset(si, ci); 1029 found = alloc_swap_scan_cluster(si, ci, folio, offset); 1030 if (found) 1031 break; 1032 } while (scan_all); 1033 1034 return found; 1035 } 1036 1037 static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force) 1038 { 1039 long to_scan = 1; 1040 unsigned long offset, end; 1041 struct swap_cluster_info *ci; 1042 unsigned long swp_tb; 1043 int nr_reclaim; 1044 1045 if (force) 1046 to_scan = swap_usage_in_pages(si) / SWAPFILE_CLUSTER; 1047 1048 while ((ci = isolate_lock_cluster(si, &si->full_clusters))) { 1049 offset = cluster_offset(si, ci); 1050 end = min(si->max, offset + SWAPFILE_CLUSTER); 1051 to_scan--; 1052 1053 while (offset < end) { 1054 swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER); 1055 if (swp_tb_is_folio(swp_tb) && !__swp_tb_get_count(swp_tb)) { 1056 spin_unlock(&ci->lock); 1057 nr_reclaim = __try_to_reclaim_swap(si, offset, 1058 TTRS_ANYWAY); 1059 spin_lock(&ci->lock); 1060 if (nr_reclaim) { 1061 offset += abs(nr_reclaim); 1062 continue; 1063 } 1064 } 1065 offset++; 1066 } 1067 1068 /* in case no swap cache is reclaimed */ 1069 if (ci->flags == CLUSTER_FLAG_NONE) 1070 relocate_cluster(si, ci); 1071 1072 swap_cluster_unlock(ci); 1073 if (to_scan <= 0) 1074 break; 1075 cond_resched(); 1076 } 1077 } 1078 1079 static void swap_reclaim_work(struct work_struct *work) 1080 { 1081 struct swap_info_struct *si; 1082 1083 si = container_of(work, struct swap_info_struct, reclaim_work); 1084 1085 swap_reclaim_full_clusters(si, true); 1086 } 1087 1088 /* 1089 * Try to allocate swap entries with specified order and try set a new 1090 * cluster for current CPU too. 1091 */ 1092 static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, 1093 struct folio *folio) 1094 { 1095 struct swap_cluster_info *ci; 1096 unsigned int order = likely(folio) ? folio_order(folio) : 0; 1097 unsigned int offset = SWAP_ENTRY_INVALID, found = SWAP_ENTRY_INVALID; 1098 1099 /* 1100 * Swapfile is not block device so unable 1101 * to allocate large entries. 1102 */ 1103 if (order && !(si->flags & SWP_BLKDEV)) 1104 return 0; 1105 1106 if (!(si->flags & SWP_SOLIDSTATE)) { 1107 /* Serialize HDD SWAP allocation for each device. */ 1108 spin_lock(&si->global_cluster_lock); 1109 offset = si->global_cluster->next[order]; 1110 if (offset == SWAP_ENTRY_INVALID) 1111 goto new_cluster; 1112 1113 ci = swap_cluster_lock(si, offset); 1114 /* Cluster could have been used by another order */ 1115 if (cluster_is_usable(ci, order)) { 1116 if (cluster_is_empty(ci)) 1117 offset = cluster_offset(si, ci); 1118 found = alloc_swap_scan_cluster(si, ci, folio, offset); 1119 } else { 1120 swap_cluster_unlock(ci); 1121 } 1122 if (found) 1123 goto done; 1124 } 1125 1126 new_cluster: 1127 /* 1128 * If the device need discard, prefer new cluster over nonfull 1129 * to spread out the writes. 1130 */ 1131 if (si->flags & SWP_PAGE_DISCARD) { 1132 found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); 1133 if (found) 1134 goto done; 1135 } 1136 1137 if (order < PMD_ORDER) { 1138 found = alloc_swap_scan_list(si, &si->nonfull_clusters[order], folio, true); 1139 if (found) 1140 goto done; 1141 } 1142 1143 if (!(si->flags & SWP_PAGE_DISCARD)) { 1144 found = alloc_swap_scan_list(si, &si->free_clusters, folio, false); 1145 if (found) 1146 goto done; 1147 } 1148 1149 /* Try reclaim full clusters if free and nonfull lists are drained */ 1150 if (vm_swap_full()) 1151 swap_reclaim_full_clusters(si, false); 1152 1153 if (order < PMD_ORDER) { 1154 /* 1155 * Scan only one fragment cluster is good enough. Order 0 1156 * allocation will surely success, and large allocation 1157 * failure is not critical. Scanning one cluster still 1158 * keeps the list rotated and reclaimed (for clean swap cache). 1159 */ 1160 found = alloc_swap_scan_list(si, &si->frag_clusters[order], folio, false); 1161 if (found) 1162 goto done; 1163 } 1164 1165 if (order) 1166 goto done; 1167 1168 /* Order 0 stealing from higher order */ 1169 for (int o = 1; o < SWAP_NR_ORDERS; o++) { 1170 /* 1171 * Clusters here have at least one usable slots and can't fail order 0 1172 * allocation, but reclaim may drop si->lock and race with another user. 1173 */ 1174 found = alloc_swap_scan_list(si, &si->frag_clusters[o], folio, true); 1175 if (found) 1176 goto done; 1177 1178 found = alloc_swap_scan_list(si, &si->nonfull_clusters[o], folio, true); 1179 if (found) 1180 goto done; 1181 } 1182 done: 1183 if (!(si->flags & SWP_SOLIDSTATE)) 1184 spin_unlock(&si->global_cluster_lock); 1185 1186 return found; 1187 } 1188 1189 /* SWAP_USAGE_OFFLIST_BIT can only be set by this helper. */ 1190 static void del_from_avail_list(struct swap_info_struct *si, bool swapoff) 1191 { 1192 unsigned long pages; 1193 1194 spin_lock(&swap_avail_lock); 1195 1196 if (swapoff) { 1197 /* 1198 * Forcefully remove it. Clear the SWP_WRITEOK flags for 1199 * swapoff here so it's synchronized by both si->lock and 1200 * swap_avail_lock, to ensure the result can be seen by 1201 * add_to_avail_list. 1202 */ 1203 lockdep_assert_held(&si->lock); 1204 si->flags &= ~SWP_WRITEOK; 1205 atomic_long_or(SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages); 1206 } else { 1207 /* 1208 * If not called by swapoff, take it off-list only if it's 1209 * full and SWAP_USAGE_OFFLIST_BIT is not set (strictly 1210 * si->inuse_pages == pages), any concurrent slot freeing, 1211 * or device already removed from plist by someone else 1212 * will make this return false. 1213 */ 1214 pages = si->pages; 1215 if (!atomic_long_try_cmpxchg(&si->inuse_pages, &pages, 1216 pages | SWAP_USAGE_OFFLIST_BIT)) 1217 goto skip; 1218 } 1219 1220 plist_del(&si->avail_list, &swap_avail_head); 1221 1222 skip: 1223 spin_unlock(&swap_avail_lock); 1224 } 1225 1226 /* SWAP_USAGE_OFFLIST_BIT can only be cleared by this helper. */ 1227 static void add_to_avail_list(struct swap_info_struct *si, bool swapon) 1228 { 1229 long val; 1230 unsigned long pages; 1231 1232 spin_lock(&swap_avail_lock); 1233 1234 /* Corresponding to SWP_WRITEOK clearing in del_from_avail_list */ 1235 if (swapon) { 1236 lockdep_assert_held(&si->lock); 1237 si->flags |= SWP_WRITEOK; 1238 } else { 1239 if (!(READ_ONCE(si->flags) & SWP_WRITEOK)) 1240 goto skip; 1241 } 1242 1243 if (!(atomic_long_read(&si->inuse_pages) & SWAP_USAGE_OFFLIST_BIT)) 1244 goto skip; 1245 1246 val = atomic_long_fetch_and_relaxed(~SWAP_USAGE_OFFLIST_BIT, &si->inuse_pages); 1247 1248 /* 1249 * When device is full and device is on the plist, only one updater will 1250 * see (inuse_pages == si->pages) and will call del_from_avail_list. If 1251 * that updater happen to be here, just skip adding. 1252 */ 1253 pages = si->pages; 1254 if (val == pages) { 1255 /* Just like the cmpxchg in del_from_avail_list */ 1256 if (atomic_long_try_cmpxchg(&si->inuse_pages, &pages, 1257 pages | SWAP_USAGE_OFFLIST_BIT)) 1258 goto skip; 1259 } 1260 1261 plist_add(&si->avail_list, &swap_avail_head); 1262 1263 skip: 1264 spin_unlock(&swap_avail_lock); 1265 } 1266 1267 /* 1268 * swap_usage_add / swap_usage_sub of each slot are serialized by ci->lock 1269 * within each cluster, so the total contribution to the global counter should 1270 * always be positive and cannot exceed the total number of usable slots. 1271 */ 1272 static bool swap_usage_add(struct swap_info_struct *si, unsigned int nr_entries) 1273 { 1274 long val = atomic_long_add_return_relaxed(nr_entries, &si->inuse_pages); 1275 1276 /* 1277 * If device is full, and SWAP_USAGE_OFFLIST_BIT is not set, 1278 * remove it from the plist. 1279 */ 1280 if (unlikely(val == si->pages)) { 1281 del_from_avail_list(si, false); 1282 return true; 1283 } 1284 1285 return false; 1286 } 1287 1288 static void swap_usage_sub(struct swap_info_struct *si, unsigned int nr_entries) 1289 { 1290 long val = atomic_long_sub_return_relaxed(nr_entries, &si->inuse_pages); 1291 1292 /* 1293 * If device is not full, and SWAP_USAGE_OFFLIST_BIT is set, 1294 * add it to the plist. 1295 */ 1296 if (unlikely(val & SWAP_USAGE_OFFLIST_BIT)) 1297 add_to_avail_list(si, false); 1298 } 1299 1300 static void swap_range_alloc(struct swap_info_struct *si, 1301 unsigned int nr_entries) 1302 { 1303 if (swap_usage_add(si, nr_entries)) { 1304 if (vm_swap_full()) 1305 schedule_work(&si->reclaim_work); 1306 } 1307 atomic_long_sub(nr_entries, &nr_swap_pages); 1308 } 1309 1310 static void swap_range_free(struct swap_info_struct *si, unsigned long offset, 1311 unsigned int nr_entries) 1312 { 1313 unsigned long end = offset + nr_entries - 1; 1314 void (*swap_slot_free_notify)(struct block_device *, unsigned long); 1315 unsigned int i; 1316 1317 for (i = 0; i < nr_entries; i++) 1318 zswap_invalidate(swp_entry(si->type, offset + i)); 1319 1320 if (si->flags & SWP_BLKDEV) 1321 swap_slot_free_notify = 1322 si->bdev->bd_disk->fops->swap_slot_free_notify; 1323 else 1324 swap_slot_free_notify = NULL; 1325 while (offset <= end) { 1326 arch_swap_invalidate_page(si->type, offset); 1327 if (swap_slot_free_notify) 1328 swap_slot_free_notify(si->bdev, offset); 1329 offset++; 1330 } 1331 1332 /* 1333 * Make sure that try_to_unuse() observes si->inuse_pages reaching 0 1334 * only after the above cleanups are done. 1335 */ 1336 smp_wmb(); 1337 atomic_long_add(nr_entries, &nr_swap_pages); 1338 swap_usage_sub(si, nr_entries); 1339 } 1340 1341 static bool get_swap_device_info(struct swap_info_struct *si) 1342 { 1343 if (!percpu_ref_tryget_live(&si->users)) 1344 return false; 1345 /* 1346 * Guarantee the si->users are checked before accessing other 1347 * fields of swap_info_struct, and si->flags (SWP_WRITEOK) is 1348 * up to dated. 1349 * 1350 * Paired with the spin_unlock() after setup_swap_info() in 1351 * enable_swap_info(), and smp_wmb() in swapoff. 1352 */ 1353 smp_rmb(); 1354 return true; 1355 } 1356 1357 /* 1358 * Fast path try to get swap entries with specified order from current 1359 * CPU's swap entry pool (a cluster). 1360 */ 1361 static bool swap_alloc_fast(struct folio *folio) 1362 { 1363 unsigned int order = folio_order(folio); 1364 struct swap_cluster_info *ci; 1365 struct swap_info_struct *si; 1366 unsigned int offset; 1367 1368 /* 1369 * Once allocated, swap_info_struct will never be completely freed, 1370 * so checking it's liveness by get_swap_device_info is enough. 1371 */ 1372 si = this_cpu_read(percpu_swap_cluster.si[order]); 1373 offset = this_cpu_read(percpu_swap_cluster.offset[order]); 1374 if (!si || !offset || !get_swap_device_info(si)) 1375 return false; 1376 1377 ci = swap_cluster_lock(si, offset); 1378 if (cluster_is_usable(ci, order)) { 1379 if (cluster_is_empty(ci)) 1380 offset = cluster_offset(si, ci); 1381 alloc_swap_scan_cluster(si, ci, folio, offset); 1382 } else { 1383 swap_cluster_unlock(ci); 1384 } 1385 1386 put_swap_device(si); 1387 return folio_test_swapcache(folio); 1388 } 1389 1390 /* Rotate the device and switch to a new cluster */ 1391 static void swap_alloc_slow(struct folio *folio) 1392 { 1393 struct swap_info_struct *si, *next; 1394 1395 spin_lock(&swap_avail_lock); 1396 start_over: 1397 plist_for_each_entry_safe(si, next, &swap_avail_head, avail_list) { 1398 /* Rotate the device and switch to a new cluster */ 1399 plist_requeue(&si->avail_list, &swap_avail_head); 1400 spin_unlock(&swap_avail_lock); 1401 if (get_swap_device_info(si)) { 1402 cluster_alloc_swap_entry(si, folio); 1403 put_swap_device(si); 1404 if (folio_test_swapcache(folio)) 1405 return; 1406 if (folio_test_large(folio)) 1407 return; 1408 } 1409 1410 spin_lock(&swap_avail_lock); 1411 /* 1412 * if we got here, it's likely that si was almost full before, 1413 * multiple callers probably all tried to get a page from the 1414 * same si and it filled up before we could get one; or, the si 1415 * filled up between us dropping swap_avail_lock. 1416 * Since we dropped the swap_avail_lock, the swap_avail_list 1417 * may have been modified; so if next is still in the 1418 * swap_avail_head list then try it, otherwise start over if we 1419 * have not gotten any slots. 1420 */ 1421 if (plist_node_empty(&next->avail_list)) 1422 goto start_over; 1423 } 1424 spin_unlock(&swap_avail_lock); 1425 } 1426 1427 /* 1428 * Discard pending clusters in a synchronized way when under high pressure. 1429 * Return: true if any cluster is discarded. 1430 */ 1431 static bool swap_sync_discard(void) 1432 { 1433 bool ret = false; 1434 struct swap_info_struct *si, *next; 1435 1436 spin_lock(&swap_lock); 1437 start_over: 1438 plist_for_each_entry_safe(si, next, &swap_active_head, list) { 1439 spin_unlock(&swap_lock); 1440 if (get_swap_device_info(si)) { 1441 if (si->flags & SWP_PAGE_DISCARD) 1442 ret = swap_do_scheduled_discard(si); 1443 put_swap_device(si); 1444 } 1445 if (ret) 1446 return true; 1447 1448 spin_lock(&swap_lock); 1449 if (plist_node_empty(&next->list)) 1450 goto start_over; 1451 } 1452 spin_unlock(&swap_lock); 1453 1454 return false; 1455 } 1456 1457 static int swap_extend_table_alloc(struct swap_info_struct *si, 1458 struct swap_cluster_info *ci, 1459 unsigned int ci_off, gfp_t gfp) 1460 { 1461 int count; 1462 void *table; 1463 1464 table = kzalloc(sizeof(ci->extend_table[0]) * SWAPFILE_CLUSTER, gfp); 1465 if (!table) 1466 return -ENOMEM; 1467 1468 spin_lock(&ci->lock); 1469 /* 1470 * Extend table allocation requires releasing ci lock first so it's 1471 * possible that the slot has been freed, no longer overflowed, or 1472 * a concurrent extend table allocation has already succeeded, so 1473 * the allocation is no longer needed. 1474 */ 1475 if (!cluster_table_is_alloced(ci)) 1476 goto out_free; 1477 count = swp_tb_get_count(__swap_table_get(ci, ci_off)); 1478 if (count < (SWP_TB_COUNT_MAX - 1)) 1479 goto out_free; 1480 if (ci->extend_table) 1481 goto out_free; 1482 1483 ci->extend_table = table; 1484 spin_unlock(&ci->lock); 1485 return 0; 1486 1487 out_free: 1488 spin_unlock(&ci->lock); 1489 kfree(table); 1490 return 0; 1491 } 1492 1493 int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp) 1494 { 1495 int ret; 1496 struct swap_info_struct *si; 1497 struct swap_cluster_info *ci; 1498 unsigned long offset = swp_offset(entry); 1499 1500 si = get_swap_device(entry); 1501 if (!si) 1502 return 0; 1503 1504 ci = __swap_offset_to_cluster(si, offset); 1505 ret = swap_extend_table_alloc(si, ci, swp_cluster_offset(entry), gfp); 1506 1507 put_swap_device(si); 1508 return ret; 1509 } 1510 1511 static void swap_extend_table_try_free(struct swap_cluster_info *ci) 1512 { 1513 unsigned long i; 1514 bool can_free = true; 1515 1516 if (!ci->extend_table) 1517 return; 1518 1519 for (i = 0; i < SWAPFILE_CLUSTER; i++) { 1520 if (ci->extend_table[i]) 1521 can_free = false; 1522 } 1523 1524 if (can_free) { 1525 kfree(ci->extend_table); 1526 ci->extend_table = NULL; 1527 } 1528 } 1529 1530 /* Decrease the swap count of one slot, without freeing it */ 1531 static void __swap_cluster_put_entry(struct swap_cluster_info *ci, 1532 unsigned int ci_off) 1533 { 1534 int count; 1535 unsigned long swp_tb; 1536 1537 lockdep_assert_held(&ci->lock); 1538 swp_tb = __swap_table_get(ci, ci_off); 1539 count = __swp_tb_get_count(swp_tb); 1540 1541 VM_WARN_ON_ONCE(count <= 0); 1542 VM_WARN_ON_ONCE(count > SWP_TB_COUNT_MAX); 1543 1544 if (count == SWP_TB_COUNT_MAX) { 1545 count = ci->extend_table[ci_off]; 1546 /* Overflow starts with SWP_TB_COUNT_MAX */ 1547 VM_WARN_ON_ONCE(count < SWP_TB_COUNT_MAX); 1548 count--; 1549 if (count == (SWP_TB_COUNT_MAX - 1)) { 1550 ci->extend_table[ci_off] = 0; 1551 __swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, count)); 1552 } else { 1553 ci->extend_table[ci_off] = count; 1554 } 1555 } else { 1556 __swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, --count)); 1557 } 1558 1559 /* 1560 * `SWP_TB_COUNT_MAX - 1` triggers extend table allocation. If the 1561 * count was above that, then the extend table is no longer needed, 1562 * so free it. And if we just put the count value from MAX - 1, it's 1563 * also possible that a pending dup just attached an extend table. 1564 */ 1565 if (unlikely(count == SWP_TB_COUNT_MAX - 2 || count == SWP_TB_COUNT_MAX - 1)) 1566 swap_extend_table_try_free(ci); 1567 } 1568 1569 /** 1570 * swap_put_entries_cluster - Decrease the swap count of slots within one cluster 1571 * @si: The swap device. 1572 * @offset: start offset of slots. 1573 * @nr: number of slots. 1574 * @reclaim_cache: if true, also reclaim the swap cache if slots are freed. 1575 * 1576 * This helper decreases the swap count of a set of slots and tries to 1577 * batch free them. Also reclaims the swap cache if @reclaim_cache is true. 1578 * 1579 * Context: The specified slots must be pinned by existing swap count or swap 1580 * cache reference, so they won't be released until this helper returns. 1581 */ 1582 static void swap_put_entries_cluster(struct swap_info_struct *si, 1583 pgoff_t offset, int nr, 1584 bool reclaim_cache) 1585 { 1586 struct swap_cluster_info *ci; 1587 unsigned int ci_off, ci_end; 1588 pgoff_t end = offset + nr; 1589 bool need_reclaim = false; 1590 unsigned int nr_reclaimed; 1591 unsigned long swp_tb; 1592 int ci_batch = -1; 1593 1594 ci = swap_cluster_lock(si, offset); 1595 ci_off = offset % SWAPFILE_CLUSTER; 1596 ci_end = ci_off + nr; 1597 do { 1598 swp_tb = __swap_table_get(ci, ci_off); 1599 if (swp_tb_get_count(swp_tb) == 1) { 1600 /* count == 1 and non-cached slots will be batch freed. */ 1601 if (!swp_tb_is_folio(swp_tb)) { 1602 if (ci_batch == -1) 1603 ci_batch = ci_off; 1604 continue; 1605 } 1606 /* count will be 0 after put, slot can be reclaimed */ 1607 need_reclaim = true; 1608 } 1609 /* 1610 * A count != 1 or cached slot can't be freed. Put its swap 1611 * count and then free the interrupted pending batch. Cached 1612 * slots will be freed when folio is removed from swap cache 1613 * (__swap_cache_del_folio). 1614 */ 1615 __swap_cluster_put_entry(ci, ci_off); 1616 if (ci_batch != -1) { 1617 __swap_cluster_free_entries(si, ci, ci_batch, ci_off - ci_batch); 1618 ci_batch = -1; 1619 } 1620 } while (++ci_off < ci_end); 1621 1622 if (ci_batch != -1) 1623 __swap_cluster_free_entries(si, ci, ci_batch, ci_off - ci_batch); 1624 swap_cluster_unlock(ci); 1625 1626 if (!need_reclaim || !reclaim_cache) 1627 return; 1628 1629 do { 1630 nr_reclaimed = __try_to_reclaim_swap(si, offset, 1631 TTRS_UNMAPPED | TTRS_FULL); 1632 offset++; 1633 if (nr_reclaimed) 1634 offset = round_up(offset, abs(nr_reclaimed)); 1635 } while (offset < end); 1636 } 1637 1638 /* Increase the swap count of one slot. */ 1639 static int __swap_cluster_dup_entry(struct swap_cluster_info *ci, 1640 unsigned int ci_off) 1641 { 1642 int count; 1643 unsigned long swp_tb; 1644 1645 lockdep_assert_held(&ci->lock); 1646 swp_tb = __swap_table_get(ci, ci_off); 1647 /* Bad or special slots can't be handled */ 1648 if (WARN_ON_ONCE(swp_tb_is_bad(swp_tb))) 1649 return -EINVAL; 1650 count = __swp_tb_get_count(swp_tb); 1651 /* Must be either cached or have a count already */ 1652 if (WARN_ON_ONCE(!count && !swp_tb_is_folio(swp_tb))) 1653 return -ENOENT; 1654 1655 if (likely(count < (SWP_TB_COUNT_MAX - 1))) { 1656 __swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, count + 1)); 1657 VM_WARN_ON_ONCE(ci->extend_table && ci->extend_table[ci_off]); 1658 } else if (count == (SWP_TB_COUNT_MAX - 1)) { 1659 if (ci->extend_table) { 1660 VM_WARN_ON_ONCE(ci->extend_table[ci_off]); 1661 ci->extend_table[ci_off] = SWP_TB_COUNT_MAX; 1662 __swap_table_set(ci, ci_off, __swp_tb_mk_count(swp_tb, SWP_TB_COUNT_MAX)); 1663 } else { 1664 return -ENOMEM; 1665 } 1666 } else if (count == SWP_TB_COUNT_MAX) { 1667 VM_WARN_ON_ONCE(ci->extend_table[ci_off] >= 1668 type_max(typeof(ci->extend_table[0]))); 1669 ++ci->extend_table[ci_off]; 1670 } else { 1671 /* Never happens unless counting went wrong */ 1672 WARN_ON_ONCE(1); 1673 } 1674 1675 return 0; 1676 } 1677 1678 /** 1679 * swap_dup_entries_cluster: Increase the swap count of slots within one cluster. 1680 * @si: The swap device. 1681 * @offset: start offset of slots. 1682 * @nr: number of slots. 1683 * 1684 * Context: The specified slots must be pinned by existing swap count or swap 1685 * cache reference, so they won't be released until this helper returns. 1686 * Return: 0 on success. -ENOMEM if the swap count maxed out (SWP_TB_COUNT_MAX) 1687 * and failed to allocate an extended table, -EINVAL if any entry is bad entry. 1688 */ 1689 static int swap_dup_entries_cluster(struct swap_info_struct *si, 1690 pgoff_t offset, int nr) 1691 { 1692 int err; 1693 struct swap_cluster_info *ci; 1694 unsigned int ci_start, ci_off, ci_end; 1695 1696 ci_start = offset % SWAPFILE_CLUSTER; 1697 ci_end = ci_start + nr; 1698 ci_off = ci_start; 1699 ci = swap_cluster_lock(si, offset); 1700 restart: 1701 do { 1702 err = __swap_cluster_dup_entry(ci, ci_off); 1703 if (unlikely(err)) { 1704 if (err == -ENOMEM) { 1705 spin_unlock(&ci->lock); 1706 err = swap_extend_table_alloc(si, ci, ci_off, GFP_ATOMIC); 1707 spin_lock(&ci->lock); 1708 if (!err) 1709 goto restart; 1710 } 1711 goto failed; 1712 } 1713 } while (++ci_off < ci_end); 1714 swap_cluster_unlock(ci); 1715 return 0; 1716 failed: 1717 while (ci_off-- > ci_start) 1718 __swap_cluster_put_entry(ci, ci_off); 1719 swap_extend_table_try_free(ci); 1720 swap_cluster_unlock(ci); 1721 return err; 1722 } 1723 1724 /** 1725 * folio_alloc_swap - allocate swap space for a folio 1726 * @folio: folio we want to move to swap 1727 * 1728 * Allocate swap space for the folio and add the folio to the 1729 * swap cache. 1730 * 1731 * Context: Caller needs to hold the folio lock. 1732 * Return: Whether the folio was added to the swap cache. 1733 */ 1734 int folio_alloc_swap(struct folio *folio) 1735 { 1736 unsigned int order = folio_order(folio); 1737 unsigned int size = 1 << order; 1738 1739 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 1740 VM_BUG_ON_FOLIO(!folio_test_uptodate(folio), folio); 1741 1742 if (order) { 1743 /* 1744 * Reject large allocation when THP_SWAP is disabled, 1745 * the caller should split the folio and try again. 1746 */ 1747 if (!IS_ENABLED(CONFIG_THP_SWAP)) 1748 return -EAGAIN; 1749 1750 /* 1751 * Allocation size should never exceed cluster size 1752 * (HPAGE_PMD_SIZE). 1753 */ 1754 if (size > SWAPFILE_CLUSTER) { 1755 VM_WARN_ON_ONCE(1); 1756 return -EINVAL; 1757 } 1758 } 1759 1760 again: 1761 local_lock(&percpu_swap_cluster.lock); 1762 if (!swap_alloc_fast(folio)) 1763 swap_alloc_slow(folio); 1764 local_unlock(&percpu_swap_cluster.lock); 1765 1766 if (!order && unlikely(!folio_test_swapcache(folio))) { 1767 if (swap_sync_discard()) 1768 goto again; 1769 } 1770 1771 /* Need to call this even if allocation failed, for MEMCG_SWAP_FAIL. */ 1772 if (unlikely(mem_cgroup_try_charge_swap(folio))) 1773 swap_cache_del_folio(folio); 1774 1775 if (unlikely(!folio_test_swapcache(folio))) 1776 return -ENOMEM; 1777 1778 return 0; 1779 } 1780 1781 /** 1782 * folio_dup_swap() - Increase swap count of swap entries of a folio. 1783 * @folio: folio with swap entries bounded. 1784 * @subpage: if not NULL, only increase the swap count of this subpage. 1785 * 1786 * Typically called when the folio is unmapped and have its swap entry to 1787 * take its place: Swap entries allocated to a folio has count == 0 and pinned 1788 * by swap cache. The swap cache pin doesn't increase the swap count. This 1789 * helper sets the initial count == 1 and increases the count as the folio is 1790 * unmapped and swap entries referencing the slots are generated to replace 1791 * the folio. 1792 * 1793 * Context: Caller must ensure the folio is locked and in the swap cache. 1794 * NOTE: The caller also has to ensure there is no raced call to 1795 * swap_put_entries_direct on its swap entry before this helper returns, or 1796 * the swap count may underflow. 1797 */ 1798 int folio_dup_swap(struct folio *folio, struct page *subpage) 1799 { 1800 swp_entry_t entry = folio->swap; 1801 unsigned long nr_pages = folio_nr_pages(folio); 1802 1803 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 1804 VM_WARN_ON_FOLIO(!folio_test_swapcache(folio), folio); 1805 1806 if (subpage) { 1807 entry.val += folio_page_idx(folio, subpage); 1808 nr_pages = 1; 1809 } 1810 1811 return swap_dup_entries_cluster(swap_entry_to_info(entry), 1812 swp_offset(entry), nr_pages); 1813 } 1814 1815 /** 1816 * folio_put_swap() - Decrease swap count of swap entries of a folio. 1817 * @folio: folio with swap entries bounded, must be in swap cache and locked. 1818 * @subpage: if not NULL, only decrease the swap count of this subpage. 1819 * 1820 * This won't free the swap slots even if swap count drops to zero, they are 1821 * still pinned by the swap cache. User may call folio_free_swap to free them. 1822 * Context: Caller must ensure the folio is locked and in the swap cache. 1823 */ 1824 void folio_put_swap(struct folio *folio, struct page *subpage) 1825 { 1826 swp_entry_t entry = folio->swap; 1827 unsigned long nr_pages = folio_nr_pages(folio); 1828 struct swap_info_struct *si = __swap_entry_to_info(entry); 1829 1830 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 1831 VM_WARN_ON_FOLIO(!folio_test_swapcache(folio), folio); 1832 1833 if (subpage) { 1834 entry.val += folio_page_idx(folio, subpage); 1835 nr_pages = 1; 1836 } 1837 1838 swap_put_entries_cluster(si, swp_offset(entry), nr_pages, false); 1839 } 1840 1841 /* 1842 * When we get a swap entry, if there aren't some other ways to 1843 * prevent swapoff, such as the folio in swap cache is locked, RCU 1844 * reader side is locked, etc., the swap entry may become invalid 1845 * because of swapoff. Then, we need to enclose all swap related 1846 * functions with get_swap_device() and put_swap_device(), unless the 1847 * swap functions call get/put_swap_device() by themselves. 1848 * 1849 * RCU reader side lock (including any spinlock) is sufficient to 1850 * prevent swapoff, because synchronize_rcu() is called in swapoff() 1851 * before freeing data structures. 1852 * 1853 * Check whether swap entry is valid in the swap device. If so, 1854 * return pointer to swap_info_struct, and keep the swap entry valid 1855 * via preventing the swap device from being swapoff, until 1856 * put_swap_device() is called. Otherwise return NULL. 1857 * 1858 * Notice that swapoff or swapoff+swapon can still happen before the 1859 * percpu_ref_tryget_live() in get_swap_device() or after the 1860 * percpu_ref_put() in put_swap_device() if there isn't any other way 1861 * to prevent swapoff. The caller must be prepared for that. For 1862 * example, the following situation is possible. 1863 * 1864 * CPU1 CPU2 1865 * do_swap_page() 1866 * ... swapoff+swapon 1867 * swap_cache_alloc_folio() 1868 * // check swap_map 1869 * // verify PTE not changed 1870 * 1871 * In __swap_duplicate(), the swap_map need to be checked before 1872 * changing partly because the specified swap entry may be for another 1873 * swap device which has been swapoff. And in do_swap_page(), after 1874 * the page is read from the swap device, the PTE is verified not 1875 * changed with the page table locked to check whether the swap device 1876 * has been swapoff or swapoff+swapon. 1877 */ 1878 struct swap_info_struct *get_swap_device(swp_entry_t entry) 1879 { 1880 struct swap_info_struct *si; 1881 unsigned long offset; 1882 1883 if (!entry.val) 1884 goto out; 1885 si = swap_entry_to_info(entry); 1886 if (!si) 1887 goto bad_nofile; 1888 if (!get_swap_device_info(si)) 1889 goto out; 1890 offset = swp_offset(entry); 1891 if (offset >= si->max) 1892 goto put_out; 1893 1894 return si; 1895 bad_nofile: 1896 pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val); 1897 out: 1898 return NULL; 1899 put_out: 1900 pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val); 1901 percpu_ref_put(&si->users); 1902 return NULL; 1903 } 1904 1905 /* 1906 * Free a set of swap slots after their swap count dropped to zero, or will be 1907 * zero after putting the last ref (saves one __swap_cluster_put_entry call). 1908 */ 1909 void __swap_cluster_free_entries(struct swap_info_struct *si, 1910 struct swap_cluster_info *ci, 1911 unsigned int ci_start, unsigned int nr_pages) 1912 { 1913 unsigned long old_tb; 1914 unsigned short batch_id = 0, id_cur; 1915 unsigned int ci_off = ci_start, ci_end = ci_start + nr_pages; 1916 unsigned long ci_head = cluster_offset(si, ci); 1917 unsigned int batch_off = ci_off; 1918 1919 VM_WARN_ON(ci->count < nr_pages); 1920 1921 ci->count -= nr_pages; 1922 do { 1923 old_tb = __swap_table_get(ci, ci_off); 1924 /* 1925 * Freeing is done after release of the last swap count 1926 * ref, or after swap cache is dropped 1927 */ 1928 VM_WARN_ON(!swp_tb_is_shadow(old_tb) || __swp_tb_get_count(old_tb) > 1); 1929 1930 /* Resetting the slot to NULL also clears the inline flags. */ 1931 __swap_table_set(ci, ci_off, null_to_swp_tb()); 1932 if (!SWAP_TABLE_HAS_ZEROFLAG) 1933 __swap_table_clear_zero(ci, ci_off); 1934 1935 /* 1936 * Uncharge swap slots by memcg in batches. Consecutive 1937 * slots with the same cgroup id are uncharged together. 1938 */ 1939 id_cur = __swap_cgroup_clear(ci, ci_off, 1); 1940 if (batch_id != id_cur) { 1941 if (batch_id) 1942 mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off); 1943 batch_id = id_cur; 1944 batch_off = ci_off; 1945 } 1946 } while (++ci_off < ci_end); 1947 1948 if (batch_id) 1949 mem_cgroup_uncharge_swap(batch_id, ci_off - batch_off); 1950 1951 swap_range_free(si, ci_head + ci_start, nr_pages); 1952 swap_cluster_assert_empty(ci, ci_start, nr_pages, false); 1953 1954 if (!ci->count) 1955 free_cluster(si, ci); 1956 else 1957 partial_free_cluster(si, ci); 1958 } 1959 1960 int __swap_count(swp_entry_t entry) 1961 { 1962 struct swap_cluster_info *ci = __swap_entry_to_cluster(entry); 1963 unsigned int ci_off = swp_cluster_offset(entry); 1964 1965 return swp_tb_get_count(__swap_table_get(ci, ci_off)); 1966 } 1967 1968 /** 1969 * swap_entry_swapped - Check if the swap entry is swapped. 1970 * @si: the swap device. 1971 * @entry: the swap entry. 1972 */ 1973 bool swap_entry_swapped(struct swap_info_struct *si, swp_entry_t entry) 1974 { 1975 pgoff_t offset = swp_offset(entry); 1976 struct swap_cluster_info *ci; 1977 unsigned long swp_tb; 1978 1979 ci = swap_cluster_lock(si, offset); 1980 swp_tb = swap_table_get(ci, offset % SWAPFILE_CLUSTER); 1981 swap_cluster_unlock(ci); 1982 1983 return swp_tb_get_count(swp_tb) > 0; 1984 } 1985 1986 /* 1987 * How many references to @entry are currently swapped out? 1988 * This returns exact answer. 1989 */ 1990 int swp_swapcount(swp_entry_t entry) 1991 { 1992 struct swap_info_struct *si; 1993 struct swap_cluster_info *ci; 1994 unsigned long swp_tb; 1995 int count; 1996 1997 si = get_swap_device(entry); 1998 if (!si) 1999 return 0; 2000 2001 ci = swap_cluster_lock(si, swp_offset(entry)); 2002 swp_tb = __swap_table_get(ci, swp_cluster_offset(entry)); 2003 count = swp_tb_get_count(swp_tb); 2004 if (count == SWP_TB_COUNT_MAX) 2005 count = ci->extend_table[swp_cluster_offset(entry)]; 2006 swap_cluster_unlock(ci); 2007 put_swap_device(si); 2008 2009 return count < 0 ? 0 : count; 2010 } 2011 2012 /* 2013 * folio_maybe_swapped - Test if a folio covers any swap slot with count > 0. 2014 * 2015 * Check if a folio is swapped. Holding the folio lock ensures the folio won't 2016 * go from not-swapped to swapped because the initial swap count increment can 2017 * only be done by folio_dup_swap, which also locks the folio. But a concurrent 2018 * decrease of swap count is possible through swap_put_entries_direct, so this 2019 * may return a false positive. 2020 * 2021 * Context: Caller must ensure the folio is locked and in the swap cache. 2022 */ 2023 static bool folio_maybe_swapped(struct folio *folio) 2024 { 2025 swp_entry_t entry = folio->swap; 2026 struct swap_cluster_info *ci; 2027 unsigned int ci_off, ci_end; 2028 bool ret = false; 2029 2030 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 2031 VM_WARN_ON_ONCE_FOLIO(!folio_test_swapcache(folio), folio); 2032 2033 ci = __swap_entry_to_cluster(entry); 2034 ci_off = swp_cluster_offset(entry); 2035 ci_end = ci_off + folio_nr_pages(folio); 2036 /* 2037 * Extra locking not needed, folio lock ensures its swap entries 2038 * won't be released, the backing data won't be gone either. 2039 */ 2040 rcu_read_lock(); 2041 do { 2042 if (__swp_tb_get_count(__swap_table_get(ci, ci_off))) { 2043 ret = true; 2044 break; 2045 } 2046 } while (++ci_off < ci_end); 2047 rcu_read_unlock(); 2048 2049 return ret; 2050 } 2051 2052 static bool folio_swapcache_freeable(struct folio *folio) 2053 { 2054 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2055 2056 if (!folio_test_swapcache(folio)) 2057 return false; 2058 if (folio_test_writeback(folio)) 2059 return false; 2060 2061 /* 2062 * Once hibernation has begun to create its image of memory, 2063 * there's a danger that one of the calls to folio_free_swap() 2064 * - most probably a call from __try_to_reclaim_swap() while 2065 * hibernation is allocating its own swap pages for the image, 2066 * but conceivably even a call from memory reclaim - will free 2067 * the swap from a folio which has already been recorded in the 2068 * image as a clean swapcache folio, and then reuse its swap for 2069 * another page of the image. On waking from hibernation, the 2070 * original folio might be freed under memory pressure, then 2071 * later read back in from swap, now with the wrong data. 2072 * 2073 * Hibernation suspends storage while it is writing the image 2074 * to disk so check that here. 2075 */ 2076 if (pm_suspended_storage()) 2077 return false; 2078 2079 return true; 2080 } 2081 2082 /** 2083 * folio_free_swap() - Free the swap space used for this folio. 2084 * @folio: The folio to remove. 2085 * 2086 * If swap is getting full, or if there are no more mappings of this folio, 2087 * then call folio_free_swap to free its swap space. 2088 * 2089 * Return: true if we were able to release the swap space. 2090 */ 2091 bool folio_free_swap(struct folio *folio) 2092 { 2093 if (!folio_swapcache_freeable(folio)) 2094 return false; 2095 if (folio_maybe_swapped(folio)) 2096 return false; 2097 2098 swap_cache_del_folio(folio); 2099 folio_set_dirty(folio); 2100 return true; 2101 } 2102 2103 /** 2104 * swap_put_entries_direct() - Release reference on range of swap entries and 2105 * reclaim their cache if no more references remain. 2106 * @entry: First entry of range. 2107 * @nr: Number of entries in range. 2108 * 2109 * For each swap entry in the contiguous range, release a reference. If any swap 2110 * entries become free, try to reclaim their underlying folios, if present. The 2111 * offset range is defined by [entry.offset, entry.offset + nr). 2112 * 2113 * Context: Caller must ensure there is no race condition on the reference 2114 * owner. e.g., locking the PTL of a PTE containing the entry being released. 2115 */ 2116 void swap_put_entries_direct(swp_entry_t entry, int nr) 2117 { 2118 const unsigned long start_offset = swp_offset(entry); 2119 const unsigned long end_offset = start_offset + nr; 2120 unsigned long offset, cluster_end; 2121 struct swap_info_struct *si; 2122 2123 si = get_swap_device(entry); 2124 if (WARN_ON_ONCE(!si)) 2125 return; 2126 if (WARN_ON_ONCE(end_offset > si->max)) 2127 goto out; 2128 2129 /* Put entries and reclaim cache in each cluster */ 2130 offset = start_offset; 2131 do { 2132 cluster_end = min(round_up(offset + 1, SWAPFILE_CLUSTER), end_offset); 2133 swap_put_entries_cluster(si, offset, cluster_end - offset, true); 2134 offset = cluster_end; 2135 } while (offset < end_offset); 2136 out: 2137 put_swap_device(si); 2138 } 2139 2140 #ifdef CONFIG_HIBERNATION 2141 /* Allocate a slot for hibernation */ 2142 swp_entry_t swap_alloc_hibernation_slot(int type) 2143 { 2144 struct swap_info_struct *pcp_si, *si = swap_type_to_info(type); 2145 unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID; 2146 struct swap_cluster_info *ci; 2147 swp_entry_t entry = {0}; 2148 2149 if (!si) 2150 goto fail; 2151 2152 /* This is called for allocating swap entry, not cache */ 2153 if (get_swap_device_info(si)) { 2154 if (si->flags & SWP_WRITEOK) { 2155 /* 2156 * Try the local cluster first if it matches the device. If 2157 * not, try grab a new cluster and override local cluster. 2158 */ 2159 local_lock(&percpu_swap_cluster.lock); 2160 pcp_si = this_cpu_read(percpu_swap_cluster.si[0]); 2161 pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]); 2162 if (pcp_si == si && pcp_offset) { 2163 ci = swap_cluster_lock(si, pcp_offset); 2164 if (cluster_is_usable(ci, 0)) 2165 offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset); 2166 else 2167 swap_cluster_unlock(ci); 2168 } 2169 if (!offset) 2170 offset = cluster_alloc_swap_entry(si, NULL); 2171 local_unlock(&percpu_swap_cluster.lock); 2172 if (offset) 2173 entry = swp_entry(si->type, offset); 2174 } 2175 put_swap_device(si); 2176 } 2177 fail: 2178 return entry; 2179 } 2180 2181 /* Free a slot allocated by swap_alloc_hibernation_slot */ 2182 void swap_free_hibernation_slot(swp_entry_t entry) 2183 { 2184 struct swap_info_struct *si; 2185 struct swap_cluster_info *ci; 2186 pgoff_t offset = swp_offset(entry); 2187 2188 si = get_swap_device(entry); 2189 if (WARN_ON(!si)) 2190 return; 2191 2192 ci = swap_cluster_lock(si, offset); 2193 __swap_cluster_put_entry(ci, offset % SWAPFILE_CLUSTER); 2194 __swap_cluster_free_entries(si, ci, offset % SWAPFILE_CLUSTER, 1); 2195 swap_cluster_unlock(ci); 2196 2197 /* In theory readahead might add it to the swap cache by accident */ 2198 __try_to_reclaim_swap(si, offset, TTRS_ANYWAY); 2199 put_swap_device(si); 2200 } 2201 2202 /* 2203 * Find the swap type that corresponds to given device (if any). 2204 * 2205 * @offset - number of the PAGE_SIZE-sized block of the device, starting 2206 * from 0, in which the swap header is expected to be located. 2207 * 2208 * This is needed for the suspend to disk (aka swsusp). 2209 */ 2210 int swap_type_of(dev_t device, sector_t offset) 2211 { 2212 int type; 2213 2214 if (!device) 2215 return -1; 2216 2217 spin_lock(&swap_lock); 2218 for (type = 0; type < nr_swapfiles; type++) { 2219 struct swap_info_struct *sis = swap_info[type]; 2220 2221 if (!(sis->flags & SWP_WRITEOK)) 2222 continue; 2223 2224 if (device == sis->bdev->bd_dev) { 2225 struct swap_extent *se = first_se(sis); 2226 2227 if (se->start_block == offset) { 2228 spin_unlock(&swap_lock); 2229 return type; 2230 } 2231 } 2232 } 2233 spin_unlock(&swap_lock); 2234 return -ENODEV; 2235 } 2236 2237 int find_first_swap(dev_t *device) 2238 { 2239 int type; 2240 2241 spin_lock(&swap_lock); 2242 for (type = 0; type < nr_swapfiles; type++) { 2243 struct swap_info_struct *sis = swap_info[type]; 2244 2245 if (!(sis->flags & SWP_WRITEOK)) 2246 continue; 2247 *device = sis->bdev->bd_dev; 2248 spin_unlock(&swap_lock); 2249 return type; 2250 } 2251 spin_unlock(&swap_lock); 2252 return -ENODEV; 2253 } 2254 2255 /* 2256 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev 2257 * corresponding to given index in swap_info (swap type). 2258 */ 2259 sector_t swapdev_block(int type, pgoff_t offset) 2260 { 2261 struct swap_info_struct *si = swap_type_to_info(type); 2262 struct swap_extent *se; 2263 2264 if (!si || !(si->flags & SWP_WRITEOK)) 2265 return 0; 2266 se = offset_to_swap_extent(si, offset); 2267 return se->start_block + (offset - se->start_page); 2268 } 2269 2270 /* 2271 * Return either the total number of swap pages of given type, or the number 2272 * of free pages of that type (depending on @free) 2273 * 2274 * This is needed for software suspend 2275 */ 2276 unsigned int count_swap_pages(int type, int free) 2277 { 2278 unsigned int n = 0; 2279 2280 spin_lock(&swap_lock); 2281 if ((unsigned int)type < nr_swapfiles) { 2282 struct swap_info_struct *sis = swap_info[type]; 2283 2284 spin_lock(&sis->lock); 2285 if (sis->flags & SWP_WRITEOK) { 2286 n = sis->pages; 2287 if (free) 2288 n -= swap_usage_in_pages(sis); 2289 } 2290 spin_unlock(&sis->lock); 2291 } 2292 spin_unlock(&swap_lock); 2293 return n; 2294 } 2295 #endif /* CONFIG_HIBERNATION */ 2296 2297 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte) 2298 { 2299 return pte_same(pte_swp_clear_flags(pte), swp_pte); 2300 } 2301 2302 /* 2303 * No need to decide whether this PTE shares the swap entry with others, 2304 * just let do_wp_page work it out if a write is requested later - to 2305 * force COW, vm_page_prot omits write permission from any private vma. 2306 */ 2307 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd, 2308 unsigned long addr, swp_entry_t entry, struct folio *folio) 2309 { 2310 struct page *page; 2311 struct folio *swapcache; 2312 spinlock_t *ptl; 2313 pte_t *pte, new_pte, old_pte; 2314 bool hwpoisoned = false; 2315 int ret = 1; 2316 2317 /* 2318 * If the folio is removed from swap cache by others, continue to 2319 * unuse other PTEs. try_to_unuse may try again if we missed this one. 2320 */ 2321 if (!folio_matches_swap_entry(folio, entry)) 2322 return 0; 2323 2324 swapcache = folio; 2325 folio = ksm_might_need_to_copy(folio, vma, addr); 2326 if (unlikely(!folio)) 2327 return -ENOMEM; 2328 else if (unlikely(folio == ERR_PTR(-EHWPOISON))) { 2329 hwpoisoned = true; 2330 folio = swapcache; 2331 } 2332 2333 page = folio_file_page(folio, swp_offset(entry)); 2334 if (PageHWPoison(page)) 2335 hwpoisoned = true; 2336 2337 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 2338 if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte), 2339 swp_entry_to_pte(entry)))) { 2340 ret = 0; 2341 goto out; 2342 } 2343 2344 old_pte = ptep_get(pte); 2345 2346 if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) { 2347 swp_entry_t swp_entry; 2348 2349 dec_mm_counter(vma->vm_mm, MM_SWAPENTS); 2350 if (hwpoisoned) { 2351 swp_entry = make_hwpoison_entry(page); 2352 } else { 2353 swp_entry = make_poisoned_swp_entry(); 2354 } 2355 new_pte = swp_entry_to_pte(swp_entry); 2356 ret = 0; 2357 goto setpte; 2358 } 2359 2360 /* 2361 * Some architectures may have to restore extra metadata to the page 2362 * when reading from swap. This metadata may be indexed by swap entry 2363 * so this must be called before folio_put_swap(). 2364 */ 2365 arch_swap_restore(folio_swap(entry, folio), folio); 2366 2367 dec_mm_counter(vma->vm_mm, MM_SWAPENTS); 2368 inc_mm_counter(vma->vm_mm, MM_ANONPAGES); 2369 folio_get(folio); 2370 if (folio == swapcache) { 2371 rmap_t rmap_flags = RMAP_NONE; 2372 2373 /* 2374 * See do_swap_page(): writeback would be problematic. 2375 * However, we do a folio_wait_writeback() just before this 2376 * call and have the folio locked. 2377 */ 2378 VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio); 2379 if (pte_swp_exclusive(old_pte)) 2380 rmap_flags |= RMAP_EXCLUSIVE; 2381 /* 2382 * We currently only expect small !anon folios, which are either 2383 * fully exclusive or fully shared. If we ever get large folios 2384 * here, we have to be careful. 2385 */ 2386 if (!folio_test_anon(folio)) { 2387 VM_WARN_ON_ONCE(folio_test_large(folio)); 2388 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 2389 folio_add_new_anon_rmap(folio, vma, addr, rmap_flags); 2390 } else { 2391 folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags); 2392 } 2393 } else { /* ksm created a completely new copy */ 2394 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); 2395 folio_add_lru_vma(folio, vma); 2396 } 2397 new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot)); 2398 if (pte_swp_soft_dirty(old_pte)) 2399 new_pte = pte_mksoft_dirty(new_pte); 2400 if (pte_swp_uffd_wp(old_pte)) 2401 new_pte = pte_mkuffd_wp(new_pte); 2402 setpte: 2403 set_pte_at(vma->vm_mm, addr, pte, new_pte); 2404 folio_put_swap(swapcache, folio_file_page(swapcache, swp_offset(entry))); 2405 out: 2406 if (pte) 2407 pte_unmap_unlock(pte, ptl); 2408 if (folio != swapcache) { 2409 folio_unlock(folio); 2410 folio_put(folio); 2411 } 2412 return ret; 2413 } 2414 2415 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd, 2416 unsigned long addr, unsigned long end, 2417 unsigned int type) 2418 { 2419 pte_t *pte = NULL; 2420 2421 do { 2422 struct folio *folio; 2423 unsigned long swp_tb; 2424 softleaf_t entry; 2425 int ret; 2426 pte_t ptent; 2427 2428 if (!pte++) { 2429 pte = pte_offset_map(pmd, addr); 2430 if (!pte) 2431 break; 2432 } 2433 2434 ptent = ptep_get_lockless(pte); 2435 entry = softleaf_from_pte(ptent); 2436 2437 if (!softleaf_is_swap(entry)) 2438 continue; 2439 if (swp_type(entry) != type) 2440 continue; 2441 2442 pte_unmap(pte); 2443 pte = NULL; 2444 2445 folio = swap_cache_get_folio(entry); 2446 if (!folio) { 2447 struct vm_fault vmf = { 2448 .vma = vma, 2449 .address = addr, 2450 .real_address = addr, 2451 .pmd = pmd, 2452 }; 2453 2454 folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, 2455 &vmf); 2456 } 2457 if (!folio) { 2458 swp_tb = swap_table_get(__swap_entry_to_cluster(entry), 2459 swp_cluster_offset(entry)); 2460 if (swp_tb_get_count(swp_tb) <= 0) 2461 continue; 2462 return -ENOMEM; 2463 } 2464 2465 folio_lock(folio); 2466 folio_wait_writeback(folio); 2467 ret = unuse_pte(vma, pmd, addr, entry, folio); 2468 if (ret < 0) { 2469 folio_unlock(folio); 2470 folio_put(folio); 2471 return ret; 2472 } 2473 2474 folio_free_swap(folio); 2475 folio_unlock(folio); 2476 folio_put(folio); 2477 } while (addr += PAGE_SIZE, addr != end); 2478 2479 if (pte) 2480 pte_unmap(pte); 2481 return 0; 2482 } 2483 2484 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud, 2485 unsigned long addr, unsigned long end, 2486 unsigned int type) 2487 { 2488 pmd_t *pmd; 2489 unsigned long next; 2490 int ret; 2491 2492 pmd = pmd_offset(pud, addr); 2493 do { 2494 cond_resched(); 2495 next = pmd_addr_end(addr, end); 2496 ret = unuse_pte_range(vma, pmd, addr, next, type); 2497 if (ret) 2498 return ret; 2499 } while (pmd++, addr = next, addr != end); 2500 return 0; 2501 } 2502 2503 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d, 2504 unsigned long addr, unsigned long end, 2505 unsigned int type) 2506 { 2507 pud_t *pud; 2508 unsigned long next; 2509 int ret; 2510 2511 pud = pud_offset(p4d, addr); 2512 do { 2513 next = pud_addr_end(addr, end); 2514 if (pud_none_or_clear_bad(pud)) 2515 continue; 2516 ret = unuse_pmd_range(vma, pud, addr, next, type); 2517 if (ret) 2518 return ret; 2519 } while (pud++, addr = next, addr != end); 2520 return 0; 2521 } 2522 2523 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd, 2524 unsigned long addr, unsigned long end, 2525 unsigned int type) 2526 { 2527 p4d_t *p4d; 2528 unsigned long next; 2529 int ret; 2530 2531 p4d = p4d_offset(pgd, addr); 2532 do { 2533 next = p4d_addr_end(addr, end); 2534 if (p4d_none_or_clear_bad(p4d)) 2535 continue; 2536 ret = unuse_pud_range(vma, p4d, addr, next, type); 2537 if (ret) 2538 return ret; 2539 } while (p4d++, addr = next, addr != end); 2540 return 0; 2541 } 2542 2543 static int unuse_vma(struct vm_area_struct *vma, unsigned int type) 2544 { 2545 pgd_t *pgd; 2546 unsigned long addr, end, next; 2547 int ret; 2548 2549 addr = vma->vm_start; 2550 end = vma->vm_end; 2551 2552 pgd = pgd_offset(vma->vm_mm, addr); 2553 do { 2554 next = pgd_addr_end(addr, end); 2555 if (pgd_none_or_clear_bad(pgd)) 2556 continue; 2557 ret = unuse_p4d_range(vma, pgd, addr, next, type); 2558 if (ret) 2559 return ret; 2560 } while (pgd++, addr = next, addr != end); 2561 return 0; 2562 } 2563 2564 static int unuse_mm(struct mm_struct *mm, unsigned int type) 2565 { 2566 struct vm_area_struct *vma; 2567 int ret = 0; 2568 VMA_ITERATOR(vmi, mm, 0); 2569 2570 mmap_read_lock(mm); 2571 if (check_stable_address_space(mm)) 2572 goto unlock; 2573 for_each_vma(vmi, vma) { 2574 if (vma->anon_vma && !is_vm_hugetlb_page(vma)) { 2575 ret = unuse_vma(vma, type); 2576 if (ret) 2577 break; 2578 } 2579 2580 cond_resched(); 2581 } 2582 unlock: 2583 mmap_read_unlock(mm); 2584 return ret; 2585 } 2586 2587 /* 2588 * Scan swap table from current position to next entry still in use. 2589 * Return 0 if there are no inuse entries after prev till end of 2590 * the map. 2591 */ 2592 static unsigned int find_next_to_unuse(struct swap_info_struct *si, 2593 unsigned int prev) 2594 { 2595 unsigned int i; 2596 unsigned long swp_tb; 2597 2598 /* 2599 * No need for swap_lock here: we're just looking 2600 * for whether an entry is in use, not modifying it; false 2601 * hits are okay, and sys_swapoff() has already prevented new 2602 * allocations from this area (while holding swap_lock). 2603 */ 2604 for (i = prev + 1; i < si->max; i++) { 2605 swp_tb = swap_table_get(__swap_offset_to_cluster(si, i), 2606 i % SWAPFILE_CLUSTER); 2607 if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb)) 2608 break; 2609 if ((i % LATENCY_LIMIT) == 0) 2610 cond_resched(); 2611 } 2612 2613 if (i == si->max) 2614 i = 0; 2615 2616 return i; 2617 } 2618 2619 static int try_to_unuse(unsigned int type) 2620 { 2621 struct mm_struct *prev_mm; 2622 struct mm_struct *mm; 2623 struct list_head *p; 2624 int retval = 0; 2625 struct swap_info_struct *si = swap_info[type]; 2626 struct folio *folio; 2627 swp_entry_t entry; 2628 unsigned int i; 2629 2630 if (!swap_usage_in_pages(si)) 2631 goto success; 2632 2633 retry: 2634 retval = shmem_unuse(type); 2635 if (retval) 2636 return retval; 2637 2638 prev_mm = &init_mm; 2639 mmget(prev_mm); 2640 2641 spin_lock(&mmlist_lock); 2642 p = &init_mm.mmlist; 2643 while (swap_usage_in_pages(si) && 2644 !signal_pending(current) && 2645 (p = p->next) != &init_mm.mmlist) { 2646 2647 mm = list_entry(p, struct mm_struct, mmlist); 2648 if (!mmget_not_zero(mm)) 2649 continue; 2650 spin_unlock(&mmlist_lock); 2651 mmput(prev_mm); 2652 prev_mm = mm; 2653 retval = unuse_mm(mm, type); 2654 if (retval) { 2655 mmput(prev_mm); 2656 return retval; 2657 } 2658 2659 /* 2660 * Make sure that we aren't completely killing 2661 * interactive performance. 2662 */ 2663 cond_resched(); 2664 spin_lock(&mmlist_lock); 2665 } 2666 spin_unlock(&mmlist_lock); 2667 2668 mmput(prev_mm); 2669 2670 i = 0; 2671 while (swap_usage_in_pages(si) && 2672 !signal_pending(current) && 2673 (i = find_next_to_unuse(si, i)) != 0) { 2674 2675 entry = swp_entry(type, i); 2676 folio = swap_cache_get_folio(entry); 2677 if (!folio) 2678 continue; 2679 2680 /* 2681 * It is conceivable that a racing task removed this folio from 2682 * swap cache just before we acquired the page lock. The folio 2683 * might even be back in swap cache on another swap area. But 2684 * that is okay, folio_free_swap() only removes stale folios. 2685 */ 2686 folio_lock(folio); 2687 folio_wait_writeback(folio); 2688 folio_free_swap(folio); 2689 folio_unlock(folio); 2690 folio_put(folio); 2691 } 2692 2693 /* 2694 * Lets check again to see if there are still swap entries in the map. 2695 * If yes, we would need to do retry the unuse logic again. 2696 * Under global memory pressure, swap entries can be reinserted back 2697 * into process space after the mmlist loop above passes over them. 2698 * 2699 * Limit the number of retries? No: when mmget_not_zero() 2700 * above fails, that mm is likely to be freeing swap from 2701 * exit_mmap(), which proceeds at its own independent pace; 2702 * and even shmem_writeout() could have been preempted after 2703 * folio_alloc_swap(), temporarily hiding that swap. It's easy 2704 * and robust (though cpu-intensive) just to keep retrying. 2705 */ 2706 if (swap_usage_in_pages(si)) { 2707 if (!signal_pending(current)) 2708 goto retry; 2709 return -EINTR; 2710 } 2711 2712 success: 2713 /* 2714 * Make sure that further cleanups after try_to_unuse() returns happen 2715 * after swap_range_free() reduces si->inuse_pages to 0. 2716 */ 2717 smp_mb(); 2718 return 0; 2719 } 2720 2721 /* 2722 * After a successful try_to_unuse, if no swap is now in use, we know 2723 * we can empty the mmlist. swap_lock must be held on entry and exit. 2724 * Note that mmlist_lock nests inside swap_lock, and an mm must be 2725 * added to the mmlist just after page_duplicate - before would be racy. 2726 */ 2727 static void drain_mmlist(void) 2728 { 2729 struct list_head *p, *next; 2730 unsigned int type; 2731 2732 for (type = 0; type < nr_swapfiles; type++) 2733 if (swap_usage_in_pages(swap_info[type])) 2734 return; 2735 spin_lock(&mmlist_lock); 2736 list_for_each_safe(p, next, &init_mm.mmlist) 2737 list_del_init(p); 2738 spin_unlock(&mmlist_lock); 2739 } 2740 2741 /* 2742 * Free all of a swapdev's extent information 2743 */ 2744 static void destroy_swap_extents(struct swap_info_struct *sis, 2745 struct file *swap_file) 2746 { 2747 while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) { 2748 struct rb_node *rb = sis->swap_extent_root.rb_node; 2749 struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node); 2750 2751 rb_erase(rb, &sis->swap_extent_root); 2752 kfree(se); 2753 } 2754 2755 if (sis->flags & SWP_ACTIVATED) { 2756 struct address_space *mapping = swap_file->f_mapping; 2757 2758 sis->flags &= ~SWP_ACTIVATED; 2759 if (mapping->a_ops->swap_deactivate) 2760 mapping->a_ops->swap_deactivate(swap_file); 2761 } 2762 } 2763 2764 /* 2765 * Add a block range (and the corresponding page range) into this swapdev's 2766 * extent tree. 2767 * 2768 * This function rather assumes that it is called in ascending page order. 2769 */ 2770 int 2771 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, 2772 unsigned long nr_pages, sector_t start_block) 2773 { 2774 struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL; 2775 struct swap_extent *se; 2776 struct swap_extent *new_se; 2777 2778 /* 2779 * place the new node at the right most since the 2780 * function is called in ascending page order. 2781 */ 2782 while (*link) { 2783 parent = *link; 2784 link = &parent->rb_right; 2785 } 2786 2787 if (parent) { 2788 se = rb_entry(parent, struct swap_extent, rb_node); 2789 BUG_ON(se->start_page + se->nr_pages != start_page); 2790 if (se->start_block + se->nr_pages == start_block) { 2791 /* Merge it */ 2792 se->nr_pages += nr_pages; 2793 return 0; 2794 } 2795 } 2796 2797 /* No merge, insert a new extent. */ 2798 new_se = kmalloc_obj(*se); 2799 if (new_se == NULL) 2800 return -ENOMEM; 2801 new_se->start_page = start_page; 2802 new_se->nr_pages = nr_pages; 2803 new_se->start_block = start_block; 2804 2805 rb_link_node(&new_se->rb_node, parent, link); 2806 rb_insert_color(&new_se->rb_node, &sis->swap_extent_root); 2807 return 1; 2808 } 2809 EXPORT_SYMBOL_GPL(add_swap_extent); 2810 2811 /* 2812 * A `swap extent' is a simple thing which maps a contiguous range of pages 2813 * onto a contiguous range of disk blocks. A rbtree of swap extents is 2814 * built at swapon time and is then used at swap_writepage/swap_read_folio 2815 * time for locating where on disk a page belongs. 2816 * 2817 * If the swapfile is an S_ISBLK block device, a single extent is installed. 2818 * This is done so that the main operating code can treat S_ISBLK and S_ISREG 2819 * swap files identically. 2820 * 2821 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap 2822 * extent rbtree operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK 2823 * swapfiles are handled *identically* after swapon time. 2824 * 2825 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks 2826 * and will parse them into a rbtree, in PAGE_SIZE chunks. If some stray 2827 * blocks are found which do not fall within the PAGE_SIZE alignment 2828 * requirements, they are simply tossed out - we will never use those blocks 2829 * for swapping. 2830 * 2831 * For all swap devices we set S_SWAPFILE across the life of the swapon. This 2832 * prevents users from writing to the swap device, which will corrupt memory. 2833 * 2834 * The amount of disk space which a single swap extent represents varies. 2835 * Typically it is in the 1-4 megabyte range. So we can have hundreds of 2836 * extents in the rbtree. - akpm. 2837 */ 2838 static int setup_swap_extents(struct swap_info_struct *sis, 2839 struct file *swap_file, sector_t *span) 2840 { 2841 struct address_space *mapping = swap_file->f_mapping; 2842 struct inode *inode = mapping->host; 2843 int ret; 2844 2845 if (S_ISBLK(inode->i_mode)) { 2846 ret = add_swap_extent(sis, 0, sis->max, 0); 2847 *span = sis->pages; 2848 return ret; 2849 } 2850 2851 if (mapping->a_ops->swap_activate) { 2852 ret = mapping->a_ops->swap_activate(sis, swap_file, span); 2853 if (ret < 0) 2854 return ret; 2855 sis->flags |= SWP_ACTIVATED; 2856 if ((sis->flags & SWP_FS_OPS) && 2857 sio_pool_init() != 0) { 2858 destroy_swap_extents(sis, swap_file); 2859 return -ENOMEM; 2860 } 2861 return ret; 2862 } 2863 2864 return generic_swapfile_activate(sis, swap_file, span); 2865 } 2866 2867 static void _enable_swap_info(struct swap_info_struct *si) 2868 { 2869 atomic_long_add(si->pages, &nr_swap_pages); 2870 total_swap_pages += si->pages; 2871 2872 assert_spin_locked(&swap_lock); 2873 2874 plist_add(&si->list, &swap_active_head); 2875 2876 /* Add back to available list */ 2877 add_to_avail_list(si, true); 2878 } 2879 2880 /* 2881 * Called after the swap device is ready, resurrect its percpu ref, it's now 2882 * safe to reference it. Add it to the list to expose it to the allocator. 2883 */ 2884 static void enable_swap_info(struct swap_info_struct *si) 2885 { 2886 percpu_ref_resurrect(&si->users); 2887 spin_lock(&swap_lock); 2888 spin_lock(&si->lock); 2889 _enable_swap_info(si); 2890 spin_unlock(&si->lock); 2891 spin_unlock(&swap_lock); 2892 } 2893 2894 static void reinsert_swap_info(struct swap_info_struct *si) 2895 { 2896 spin_lock(&swap_lock); 2897 spin_lock(&si->lock); 2898 _enable_swap_info(si); 2899 spin_unlock(&si->lock); 2900 spin_unlock(&swap_lock); 2901 } 2902 2903 /* 2904 * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range 2905 * see the updated flags, so there will be no more allocations. 2906 */ 2907 static void wait_for_allocation(struct swap_info_struct *si) 2908 { 2909 unsigned long offset; 2910 unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER); 2911 struct swap_cluster_info *ci; 2912 2913 BUG_ON(si->flags & SWP_WRITEOK); 2914 2915 for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) { 2916 ci = swap_cluster_lock(si, offset); 2917 swap_cluster_unlock(ci); 2918 } 2919 } 2920 2921 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info, 2922 unsigned long maxpages) 2923 { 2924 struct swap_cluster_info *ci; 2925 int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); 2926 2927 if (!cluster_info) 2928 return; 2929 for (i = 0; i < nr_clusters; i++) { 2930 ci = cluster_info + i; 2931 /* Cluster with bad marks count will have a remaining table */ 2932 spin_lock(&ci->lock); 2933 if (cluster_table_is_alloced(ci)) { 2934 swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true); 2935 swap_cluster_free_table(ci); 2936 } 2937 spin_unlock(&ci->lock); 2938 } 2939 kvfree(cluster_info); 2940 } 2941 2942 /* 2943 * Called after swap device's reference count is dead, so 2944 * neither scan nor allocation will use it. 2945 */ 2946 static void flush_percpu_swap_cluster(struct swap_info_struct *si) 2947 { 2948 int cpu, i; 2949 struct swap_info_struct **pcp_si; 2950 2951 for_each_possible_cpu(cpu) { 2952 pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu); 2953 /* 2954 * Invalidate the percpu swap cluster cache, si->users 2955 * is dead, so no new user will point to it, just flush 2956 * any existing user. 2957 */ 2958 for (i = 0; i < SWAP_NR_ORDERS; i++) 2959 cmpxchg(&pcp_si[i], si, NULL); 2960 } 2961 } 2962 2963 2964 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) 2965 { 2966 struct swap_info_struct *p = NULL; 2967 struct swap_cluster_info *cluster_info; 2968 struct file *swap_file, *victim; 2969 struct address_space *mapping; 2970 struct inode *inode; 2971 unsigned int maxpages; 2972 int err, found = 0; 2973 2974 if (!capable(CAP_SYS_ADMIN)) 2975 return -EPERM; 2976 2977 BUG_ON(!current->mm); 2978 2979 CLASS(filename, pathname)(specialfile); 2980 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0); 2981 if (IS_ERR(victim)) 2982 return PTR_ERR(victim); 2983 2984 mapping = victim->f_mapping; 2985 spin_lock(&swap_lock); 2986 plist_for_each_entry(p, &swap_active_head, list) { 2987 if (p->flags & SWP_WRITEOK) { 2988 if (p->swap_file->f_mapping == mapping) { 2989 found = 1; 2990 break; 2991 } 2992 } 2993 } 2994 if (!found) { 2995 err = -EINVAL; 2996 spin_unlock(&swap_lock); 2997 goto out_dput; 2998 } 2999 if (!security_vm_enough_memory_mm(current->mm, p->pages)) 3000 vm_unacct_memory(p->pages); 3001 else { 3002 err = -ENOMEM; 3003 spin_unlock(&swap_lock); 3004 goto out_dput; 3005 } 3006 spin_lock(&p->lock); 3007 del_from_avail_list(p, true); 3008 plist_del(&p->list, &swap_active_head); 3009 atomic_long_sub(p->pages, &nr_swap_pages); 3010 total_swap_pages -= p->pages; 3011 spin_unlock(&p->lock); 3012 spin_unlock(&swap_lock); 3013 3014 wait_for_allocation(p); 3015 3016 set_current_oom_origin(); 3017 err = try_to_unuse(p->type); 3018 clear_current_oom_origin(); 3019 3020 if (err) { 3021 /* re-insert swap space back into swap_list */ 3022 reinsert_swap_info(p); 3023 goto out_dput; 3024 } 3025 3026 /* 3027 * Wait for swap operations protected by get/put_swap_device() 3028 * to complete. Because of synchronize_rcu() here, all swap 3029 * operations protected by RCU reader side lock (including any 3030 * spinlock) will be waited too. This makes it easy to 3031 * prevent folio_test_swapcache() and the following swap cache 3032 * operations from racing with swapoff. 3033 */ 3034 percpu_ref_kill(&p->users); 3035 synchronize_rcu(); 3036 wait_for_completion(&p->comp); 3037 3038 flush_work(&p->discard_work); 3039 flush_work(&p->reclaim_work); 3040 flush_percpu_swap_cluster(p); 3041 3042 destroy_swap_extents(p, p->swap_file); 3043 3044 if (!(p->flags & SWP_SOLIDSTATE)) 3045 atomic_dec(&nr_rotate_swap); 3046 3047 mutex_lock(&swapon_mutex); 3048 spin_lock(&swap_lock); 3049 spin_lock(&p->lock); 3050 drain_mmlist(); 3051 3052 swap_file = p->swap_file; 3053 p->swap_file = NULL; 3054 maxpages = p->max; 3055 cluster_info = p->cluster_info; 3056 p->max = 0; 3057 p->cluster_info = NULL; 3058 spin_unlock(&p->lock); 3059 spin_unlock(&swap_lock); 3060 arch_swap_invalidate_area(p->type); 3061 zswap_swapoff(p->type); 3062 mutex_unlock(&swapon_mutex); 3063 kfree(p->global_cluster); 3064 p->global_cluster = NULL; 3065 free_swap_cluster_info(cluster_info, maxpages); 3066 3067 inode = mapping->host; 3068 3069 inode_lock(inode); 3070 inode->i_flags &= ~S_SWAPFILE; 3071 inode_unlock(inode); 3072 filp_close(swap_file, NULL); 3073 3074 /* 3075 * Clear the SWP_USED flag after all resources are freed so that swapon 3076 * can reuse this swap_info in alloc_swap_info() safely. It is ok to 3077 * not hold p->lock after we cleared its SWP_WRITEOK. 3078 */ 3079 spin_lock(&swap_lock); 3080 p->flags = 0; 3081 spin_unlock(&swap_lock); 3082 3083 err = 0; 3084 atomic_inc(&proc_poll_event); 3085 wake_up_interruptible(&proc_poll_wait); 3086 3087 out_dput: 3088 filp_close(victim, NULL); 3089 return err; 3090 } 3091 3092 #ifdef CONFIG_PROC_FS 3093 static __poll_t swaps_poll(struct file *file, poll_table *wait) 3094 { 3095 struct seq_file *seq = file->private_data; 3096 3097 poll_wait(file, &proc_poll_wait, wait); 3098 3099 if (seq->poll_event != atomic_read(&proc_poll_event)) { 3100 seq->poll_event = atomic_read(&proc_poll_event); 3101 return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI; 3102 } 3103 3104 return EPOLLIN | EPOLLRDNORM; 3105 } 3106 3107 /* iterator */ 3108 static void *swap_start(struct seq_file *swap, loff_t *pos) 3109 { 3110 struct swap_info_struct *si; 3111 int type; 3112 loff_t l = *pos; 3113 3114 mutex_lock(&swapon_mutex); 3115 3116 if (!l) 3117 return SEQ_START_TOKEN; 3118 3119 for (type = 0; (si = swap_type_to_info(type)); type++) { 3120 if (!(si->swap_file)) 3121 continue; 3122 if (!--l) 3123 return si; 3124 } 3125 3126 return NULL; 3127 } 3128 3129 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos) 3130 { 3131 struct swap_info_struct *si = v; 3132 int type; 3133 3134 if (v == SEQ_START_TOKEN) 3135 type = 0; 3136 else 3137 type = si->type + 1; 3138 3139 ++(*pos); 3140 for (; (si = swap_type_to_info(type)); type++) { 3141 if (!(si->swap_file)) 3142 continue; 3143 return si; 3144 } 3145 3146 return NULL; 3147 } 3148 3149 static void swap_stop(struct seq_file *swap, void *v) 3150 { 3151 mutex_unlock(&swapon_mutex); 3152 } 3153 3154 static int swap_show(struct seq_file *swap, void *v) 3155 { 3156 struct swap_info_struct *si = v; 3157 struct file *file; 3158 int len; 3159 unsigned long bytes, inuse; 3160 3161 if (si == SEQ_START_TOKEN) { 3162 seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n"); 3163 return 0; 3164 } 3165 3166 bytes = K(si->pages); 3167 inuse = K(swap_usage_in_pages(si)); 3168 3169 file = si->swap_file; 3170 len = seq_file_path(swap, file, " \t\n\\"); 3171 seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n", 3172 len < 40 ? 40 - len : 1, " ", 3173 S_ISBLK(file_inode(file)->i_mode) ? 3174 "partition" : "file\t", 3175 bytes, bytes < 10000000 ? "\t" : "", 3176 inuse, inuse < 10000000 ? "\t" : "", 3177 si->prio); 3178 return 0; 3179 } 3180 3181 static const struct seq_operations swaps_op = { 3182 .start = swap_start, 3183 .next = swap_next, 3184 .stop = swap_stop, 3185 .show = swap_show 3186 }; 3187 3188 static int swaps_open(struct inode *inode, struct file *file) 3189 { 3190 struct seq_file *seq; 3191 int ret; 3192 3193 ret = seq_open(file, &swaps_op); 3194 if (ret) 3195 return ret; 3196 3197 seq = file->private_data; 3198 seq->poll_event = atomic_read(&proc_poll_event); 3199 return 0; 3200 } 3201 3202 static const struct proc_ops swaps_proc_ops = { 3203 .proc_flags = PROC_ENTRY_PERMANENT, 3204 .proc_open = swaps_open, 3205 .proc_read = seq_read, 3206 .proc_lseek = seq_lseek, 3207 .proc_release = seq_release, 3208 .proc_poll = swaps_poll, 3209 }; 3210 3211 static int __init procswaps_init(void) 3212 { 3213 proc_create("swaps", 0, NULL, &swaps_proc_ops); 3214 return 0; 3215 } 3216 __initcall(procswaps_init); 3217 #endif /* CONFIG_PROC_FS */ 3218 3219 #ifdef MAX_SWAPFILES_CHECK 3220 static int __init max_swapfiles_check(void) 3221 { 3222 MAX_SWAPFILES_CHECK(); 3223 return 0; 3224 } 3225 late_initcall(max_swapfiles_check); 3226 #endif 3227 3228 static struct swap_info_struct *alloc_swap_info(void) 3229 { 3230 struct swap_info_struct *p; 3231 struct swap_info_struct *defer = NULL; 3232 unsigned int type; 3233 3234 p = kvzalloc_obj(struct swap_info_struct); 3235 if (!p) 3236 return ERR_PTR(-ENOMEM); 3237 3238 if (percpu_ref_init(&p->users, swap_users_ref_free, 3239 PERCPU_REF_INIT_DEAD, GFP_KERNEL)) { 3240 kvfree(p); 3241 return ERR_PTR(-ENOMEM); 3242 } 3243 3244 spin_lock(&swap_lock); 3245 for (type = 0; type < nr_swapfiles; type++) { 3246 if (!(swap_info[type]->flags & SWP_USED)) 3247 break; 3248 } 3249 if (type >= MAX_SWAPFILES) { 3250 spin_unlock(&swap_lock); 3251 percpu_ref_exit(&p->users); 3252 kvfree(p); 3253 return ERR_PTR(-EPERM); 3254 } 3255 if (type >= nr_swapfiles) { 3256 p->type = type; 3257 /* 3258 * Publish the swap_info_struct after initializing it. 3259 * Note that kvzalloc() above zeroes all its fields. 3260 */ 3261 smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */ 3262 nr_swapfiles++; 3263 } else { 3264 defer = p; 3265 p = swap_info[type]; 3266 /* 3267 * Do not memset this entry: a racing procfs swap_next() 3268 * would be relying on p->type to remain valid. 3269 */ 3270 } 3271 p->swap_extent_root = RB_ROOT; 3272 plist_node_init(&p->list, 0); 3273 plist_node_init(&p->avail_list, 0); 3274 p->flags = SWP_USED; 3275 spin_unlock(&swap_lock); 3276 if (defer) { 3277 percpu_ref_exit(&defer->users); 3278 kvfree(defer); 3279 } 3280 spin_lock_init(&p->lock); 3281 atomic_long_set(&p->inuse_pages, SWAP_USAGE_OFFLIST_BIT); 3282 init_completion(&p->comp); 3283 3284 return p; 3285 } 3286 3287 static int claim_swapfile(struct swap_info_struct *si, struct inode *inode) 3288 { 3289 if (S_ISBLK(inode->i_mode)) { 3290 si->bdev = I_BDEV(inode); 3291 /* 3292 * Zoned block devices contain zones that have a sequential 3293 * write only restriction. Hence zoned block devices are not 3294 * suitable for swapping. Disallow them here. 3295 */ 3296 if (bdev_is_zoned(si->bdev)) 3297 return -EINVAL; 3298 si->flags |= SWP_BLKDEV; 3299 } else if (S_ISREG(inode->i_mode)) { 3300 si->bdev = inode->i_sb->s_bdev; 3301 } 3302 3303 return 0; 3304 } 3305 3306 3307 /* 3308 * Find out how many pages are allowed for a single swap device. There 3309 * are two limiting factors: 3310 * 1) the number of bits for the swap offset in the swp_entry_t type, and 3311 * 2) the number of bits in the swap pte, as defined by the different 3312 * architectures. 3313 * 3314 * In order to find the largest possible bit mask, a swap entry with 3315 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte, 3316 * decoded to a swp_entry_t again, and finally the swap offset is 3317 * extracted. 3318 * 3319 * This will mask all the bits from the initial ~0UL mask that can't 3320 * be encoded in either the swp_entry_t or the architecture definition 3321 * of a swap pte. 3322 */ 3323 unsigned long generic_max_swapfile_size(void) 3324 { 3325 swp_entry_t entry = swp_entry(0, ~0UL); 3326 const pte_t pte = softleaf_to_pte(entry); 3327 3328 /* 3329 * Since the PTE can be an invalid softleaf entry (e.g. the none PTE), 3330 * we need to do this manually. 3331 */ 3332 entry = __pte_to_swp_entry(pte); 3333 entry = swp_entry(__swp_type(entry), __swp_offset(entry)); 3334 3335 return swp_offset(entry) + 1; 3336 } 3337 3338 /* Can be overridden by an architecture for additional checks. */ 3339 __weak unsigned long arch_max_swapfile_size(void) 3340 { 3341 return generic_max_swapfile_size(); 3342 } 3343 3344 static unsigned long read_swap_header(struct swap_info_struct *si, 3345 union swap_header *swap_header, 3346 struct inode *inode) 3347 { 3348 int i; 3349 unsigned long maxpages; 3350 unsigned long swapfilepages; 3351 unsigned long last_page; 3352 3353 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) { 3354 pr_err("Unable to find swap-space signature\n"); 3355 return 0; 3356 } 3357 3358 /* swap partition endianness hack... */ 3359 if (swab32(swap_header->info.version) == 1) { 3360 swab32s(&swap_header->info.version); 3361 swab32s(&swap_header->info.last_page); 3362 swab32s(&swap_header->info.nr_badpages); 3363 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES) 3364 return 0; 3365 for (i = 0; i < swap_header->info.nr_badpages; i++) 3366 swab32s(&swap_header->info.badpages[i]); 3367 } 3368 /* Check the swap header's sub-version */ 3369 if (swap_header->info.version != 1) { 3370 pr_warn("Unable to handle swap header version %d\n", 3371 swap_header->info.version); 3372 return 0; 3373 } 3374 3375 maxpages = swapfile_maximum_size; 3376 last_page = swap_header->info.last_page; 3377 if (!last_page) { 3378 pr_warn("Empty swap-file\n"); 3379 return 0; 3380 } 3381 if (last_page > maxpages) { 3382 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n", 3383 K(maxpages), K(last_page)); 3384 } 3385 if (maxpages > last_page) { 3386 maxpages = last_page + 1; 3387 /* p->max is an unsigned int: don't overflow it */ 3388 if ((unsigned int)maxpages == 0) 3389 maxpages = UINT_MAX; 3390 } 3391 3392 if (!maxpages) 3393 return 0; 3394 swapfilepages = i_size_read(inode) >> PAGE_SHIFT; 3395 if (swapfilepages && maxpages > swapfilepages) { 3396 pr_warn("Swap area shorter than signature indicates\n"); 3397 return 0; 3398 } 3399 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode)) 3400 return 0; 3401 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES) 3402 return 0; 3403 3404 return maxpages; 3405 } 3406 3407 static int setup_swap_clusters_info(struct swap_info_struct *si, 3408 union swap_header *swap_header, 3409 unsigned long maxpages) 3410 { 3411 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); 3412 struct swap_cluster_info *cluster_info; 3413 int err = -ENOMEM; 3414 unsigned long i; 3415 3416 cluster_info = kvzalloc_objs(*cluster_info, nr_clusters); 3417 if (!cluster_info) 3418 goto err; 3419 3420 for (i = 0; i < nr_clusters; i++) 3421 spin_lock_init(&cluster_info[i].lock); 3422 3423 if (!(si->flags & SWP_SOLIDSTATE)) { 3424 si->global_cluster = kmalloc_obj(*si->global_cluster); 3425 if (!si->global_cluster) 3426 goto err; 3427 for (i = 0; i < SWAP_NR_ORDERS; i++) 3428 si->global_cluster->next[i] = SWAP_ENTRY_INVALID; 3429 spin_lock_init(&si->global_cluster_lock); 3430 } 3431 3432 /* 3433 * Mark unusable pages (header page, bad pages, and the EOF part of 3434 * the last cluster) as unavailable. The clusters aren't marked free 3435 * yet, so no list operations are involved yet. 3436 */ 3437 err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false); 3438 if (err) 3439 goto err; 3440 for (i = 0; i < swap_header->info.nr_badpages; i++) { 3441 unsigned int page_nr = swap_header->info.badpages[i]; 3442 3443 if (!page_nr || page_nr > swap_header->info.last_page) { 3444 pr_warn("Bad slot offset is out of border: %d (last_page: %d)\n", 3445 page_nr, swap_header->info.last_page); 3446 err = -EINVAL; 3447 goto err; 3448 } 3449 err = swap_cluster_setup_bad_slot(si, cluster_info, page_nr, false); 3450 if (err) 3451 goto err; 3452 } 3453 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) { 3454 err = swap_cluster_setup_bad_slot(si, cluster_info, i, true); 3455 if (err) 3456 goto err; 3457 } 3458 3459 INIT_LIST_HEAD(&si->free_clusters); 3460 INIT_LIST_HEAD(&si->full_clusters); 3461 INIT_LIST_HEAD(&si->discard_clusters); 3462 3463 for (i = 0; i < SWAP_NR_ORDERS; i++) { 3464 INIT_LIST_HEAD(&si->nonfull_clusters[i]); 3465 INIT_LIST_HEAD(&si->frag_clusters[i]); 3466 } 3467 3468 for (i = 0; i < nr_clusters; i++) { 3469 struct swap_cluster_info *ci = &cluster_info[i]; 3470 3471 if (ci->count) { 3472 ci->flags = CLUSTER_FLAG_NONFULL; 3473 list_add_tail(&ci->list, &si->nonfull_clusters[0]); 3474 } else { 3475 ci->flags = CLUSTER_FLAG_FREE; 3476 list_add_tail(&ci->list, &si->free_clusters); 3477 } 3478 } 3479 3480 si->cluster_info = cluster_info; 3481 return 0; 3482 err: 3483 free_swap_cluster_info(cluster_info, maxpages); 3484 return err; 3485 } 3486 3487 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) 3488 { 3489 struct swap_info_struct *si; 3490 struct file *swap_file = NULL; 3491 struct address_space *mapping; 3492 struct dentry *dentry; 3493 int prio; 3494 int error; 3495 union swap_header *swap_header; 3496 int nr_extents; 3497 sector_t span; 3498 unsigned long maxpages; 3499 struct folio *folio = NULL; 3500 struct inode *inode = NULL; 3501 bool inced_nr_rotate_swap = false; 3502 3503 if (swap_flags & ~SWAP_FLAGS_VALID) 3504 return -EINVAL; 3505 3506 if (!capable(CAP_SYS_ADMIN)) 3507 return -EPERM; 3508 3509 /* 3510 * Allocate or reuse existing !SWP_USED swap_info. The returned 3511 * si will stay in a dying status, so nothing will access its content 3512 * until enable_swap_info resurrects its percpu ref and expose it. 3513 */ 3514 si = alloc_swap_info(); 3515 if (IS_ERR(si)) 3516 return PTR_ERR(si); 3517 3518 INIT_WORK(&si->discard_work, swap_discard_work); 3519 INIT_WORK(&si->reclaim_work, swap_reclaim_work); 3520 3521 CLASS(filename, name)(specialfile); 3522 swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0); 3523 if (IS_ERR(swap_file)) { 3524 error = PTR_ERR(swap_file); 3525 swap_file = NULL; 3526 goto bad_swap; 3527 } 3528 3529 mapping = swap_file->f_mapping; 3530 dentry = swap_file->f_path.dentry; 3531 inode = mapping->host; 3532 3533 error = claim_swapfile(si, inode); 3534 if (unlikely(error)) 3535 goto bad_swap; 3536 3537 inode_lock(inode); 3538 if (d_unlinked(dentry) || cant_mount(dentry)) { 3539 error = -ENOENT; 3540 goto bad_swap_unlock_inode; 3541 } 3542 if (IS_SWAPFILE(inode)) { 3543 error = -EBUSY; 3544 goto bad_swap_unlock_inode; 3545 } 3546 3547 /* 3548 * The swap subsystem needs a major overhaul to support this. 3549 * It doesn't work yet so just disable it for now. 3550 */ 3551 if (mapping_min_folio_order(mapping) > 0) { 3552 error = -EINVAL; 3553 goto bad_swap_unlock_inode; 3554 } 3555 3556 /* 3557 * Read the swap header. 3558 */ 3559 if (!mapping->a_ops->read_folio) { 3560 error = -EINVAL; 3561 goto bad_swap_unlock_inode; 3562 } 3563 folio = read_mapping_folio(mapping, 0, swap_file); 3564 if (IS_ERR(folio)) { 3565 error = PTR_ERR(folio); 3566 goto bad_swap_unlock_inode; 3567 } 3568 swap_header = kmap_local_folio(folio, 0); 3569 3570 maxpages = read_swap_header(si, swap_header, inode); 3571 if (unlikely(!maxpages)) { 3572 error = -EINVAL; 3573 goto bad_swap_unlock_inode; 3574 } 3575 3576 si->max = maxpages; 3577 si->pages = maxpages - 1; 3578 nr_extents = setup_swap_extents(si, swap_file, &span); 3579 if (nr_extents < 0) { 3580 error = nr_extents; 3581 goto bad_swap_unlock_inode; 3582 } 3583 if (si->pages != si->max - 1) { 3584 pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max); 3585 error = -EINVAL; 3586 goto bad_swap_unlock_inode; 3587 } 3588 3589 maxpages = si->max; 3590 3591 /* Set up the swap cluster info */ 3592 error = setup_swap_clusters_info(si, swap_header, maxpages); 3593 if (error) 3594 goto bad_swap_unlock_inode; 3595 3596 if (si->bdev && bdev_stable_writes(si->bdev)) 3597 si->flags |= SWP_STABLE_WRITES; 3598 3599 if (si->bdev && bdev_synchronous(si->bdev)) 3600 si->flags |= SWP_SYNCHRONOUS_IO; 3601 3602 if (si->bdev && !bdev_rot(si->bdev)) { 3603 si->flags |= SWP_SOLIDSTATE; 3604 } else { 3605 atomic_inc(&nr_rotate_swap); 3606 inced_nr_rotate_swap = true; 3607 } 3608 3609 if ((swap_flags & SWAP_FLAG_DISCARD) && 3610 si->bdev && bdev_max_discard_sectors(si->bdev)) { 3611 /* 3612 * When discard is enabled for swap with no particular 3613 * policy flagged, we set all swap discard flags here in 3614 * order to sustain backward compatibility with older 3615 * swapon(8) releases. 3616 */ 3617 si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD | 3618 SWP_PAGE_DISCARD); 3619 3620 /* 3621 * By flagging sys_swapon, a sysadmin can tell us to 3622 * either do single-time area discards only, or to just 3623 * perform discards for released swap page-clusters. 3624 * Now it's time to adjust the p->flags accordingly. 3625 */ 3626 if (swap_flags & SWAP_FLAG_DISCARD_ONCE) 3627 si->flags &= ~SWP_PAGE_DISCARD; 3628 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES) 3629 si->flags &= ~SWP_AREA_DISCARD; 3630 3631 /* issue a swapon-time discard if it's still required */ 3632 if (si->flags & SWP_AREA_DISCARD) { 3633 int err = discard_swap(si); 3634 if (unlikely(err)) 3635 pr_err("swapon: discard_swap(%p): %d\n", 3636 si, err); 3637 } 3638 } 3639 3640 error = zswap_swapon(si->type, maxpages); 3641 if (error) 3642 goto bad_swap_unlock_inode; 3643 3644 /* 3645 * Flush any pending IO and dirty mappings before we start using this 3646 * swap device. 3647 */ 3648 inode->i_flags |= S_SWAPFILE; 3649 error = inode_drain_writes(inode); 3650 if (error) { 3651 inode->i_flags &= ~S_SWAPFILE; 3652 goto free_swap_zswap; 3653 } 3654 3655 mutex_lock(&swapon_mutex); 3656 prio = DEF_SWAP_PRIO; 3657 if (swap_flags & SWAP_FLAG_PREFER) 3658 prio = swap_flags & SWAP_FLAG_PRIO_MASK; 3659 3660 /* 3661 * The plist prio is negated because plist ordering is 3662 * low-to-high, while swap ordering is high-to-low 3663 */ 3664 si->prio = prio; 3665 si->list.prio = -si->prio; 3666 si->avail_list.prio = -si->prio; 3667 si->swap_file = swap_file; 3668 3669 /* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */ 3670 enable_swap_info(si); 3671 3672 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", 3673 K(si->pages), name->name, si->prio, nr_extents, 3674 K((unsigned long long)span), 3675 (si->flags & SWP_SOLIDSTATE) ? "SS" : "", 3676 (si->flags & SWP_DISCARDABLE) ? "D" : "", 3677 (si->flags & SWP_AREA_DISCARD) ? "s" : "", 3678 (si->flags & SWP_PAGE_DISCARD) ? "c" : ""); 3679 3680 mutex_unlock(&swapon_mutex); 3681 atomic_inc(&proc_poll_event); 3682 wake_up_interruptible(&proc_poll_wait); 3683 3684 error = 0; 3685 goto out; 3686 free_swap_zswap: 3687 zswap_swapoff(si->type); 3688 bad_swap_unlock_inode: 3689 inode_unlock(inode); 3690 bad_swap: 3691 kfree(si->global_cluster); 3692 si->global_cluster = NULL; 3693 inode = NULL; 3694 destroy_swap_extents(si, swap_file); 3695 free_swap_cluster_info(si->cluster_info, si->max); 3696 si->cluster_info = NULL; 3697 /* 3698 * Clear the SWP_USED flag after all resources are freed so 3699 * alloc_swap_info can reuse this si safely. 3700 */ 3701 spin_lock(&swap_lock); 3702 si->flags = 0; 3703 spin_unlock(&swap_lock); 3704 if (inced_nr_rotate_swap) 3705 atomic_dec(&nr_rotate_swap); 3706 if (swap_file) 3707 filp_close(swap_file, NULL); 3708 out: 3709 if (!IS_ERR_OR_NULL(folio)) 3710 folio_release_kmap(folio, swap_header); 3711 if (inode) 3712 inode_unlock(inode); 3713 return error; 3714 } 3715 3716 void si_swapinfo(struct sysinfo *val) 3717 { 3718 unsigned int type; 3719 unsigned long nr_to_be_unused = 0; 3720 3721 spin_lock(&swap_lock); 3722 for (type = 0; type < nr_swapfiles; type++) { 3723 struct swap_info_struct *si = swap_info[type]; 3724 3725 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK)) 3726 nr_to_be_unused += swap_usage_in_pages(si); 3727 } 3728 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused; 3729 val->totalswap = total_swap_pages + nr_to_be_unused; 3730 spin_unlock(&swap_lock); 3731 } 3732 3733 /* 3734 * swap_dup_entry_direct() - Increase reference count of a swap entry by one. 3735 * @entry: first swap entry from which we want to increase the refcount. 3736 * 3737 * Returns 0 for success, or -ENOMEM if the extend table is required 3738 * but could not be atomically allocated. Returns -EINVAL if the swap 3739 * entry is invalid, which might occur if a page table entry has got 3740 * corrupted. 3741 * 3742 * Context: Caller must ensure there is no race condition on the reference 3743 * owner. e.g., locking the PTL of a PTE containing the entry being increased. 3744 * Also the swap entry must have a count >= 1. Otherwise folio_dup_swap should 3745 * be used. 3746 */ 3747 int swap_dup_entry_direct(swp_entry_t entry) 3748 { 3749 struct swap_info_struct *si; 3750 3751 si = swap_entry_to_info(entry); 3752 if (WARN_ON_ONCE(!si)) { 3753 pr_err("%s%08lx\n", Bad_file, entry.val); 3754 return -EINVAL; 3755 } 3756 3757 /* 3758 * The caller must be increasing the swap count from a direct 3759 * reference of the swap slot (e.g. a swap entry in page table). 3760 * So the swap count must be >= 1. 3761 */ 3762 VM_WARN_ON_ONCE(!swap_entry_swapped(si, entry)); 3763 3764 return swap_dup_entries_cluster(si, swp_offset(entry), 1); 3765 } 3766 3767 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP) 3768 static bool __has_usable_swap(void) 3769 { 3770 return !plist_head_empty(&swap_active_head); 3771 } 3772 3773 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp) 3774 { 3775 struct swap_info_struct *si; 3776 3777 if (!(gfp & __GFP_IO)) 3778 return; 3779 3780 if (!__has_usable_swap()) 3781 return; 3782 3783 if (!blk_cgroup_congested()) 3784 return; 3785 3786 /* 3787 * We've already scheduled a throttle, avoid taking the global swap 3788 * lock. 3789 */ 3790 if (current->throttle_disk) 3791 return; 3792 3793 spin_lock(&swap_avail_lock); 3794 plist_for_each_entry(si, &swap_avail_head, avail_list) { 3795 if (si->bdev) { 3796 blkcg_schedule_throttle(si->bdev->bd_disk, true); 3797 break; 3798 } 3799 } 3800 spin_unlock(&swap_avail_lock); 3801 } 3802 #endif 3803 3804 static int __init swapfile_init(void) 3805 { 3806 swapfile_maximum_size = arch_max_swapfile_size(); 3807 3808 /* 3809 * Once a cluster is freed, it's swap table content is read 3810 * only, and all swap cache readers (swap_cache_*) verifies 3811 * the content before use. So it's safe to use RCU slab here. 3812 */ 3813 if (!SWP_TABLE_USE_PAGE) 3814 swap_table_cachep = kmem_cache_create("swap_table", 3815 sizeof(struct swap_table), 3816 0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL); 3817 3818 #ifdef CONFIG_MIGRATION 3819 if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS)) 3820 swap_migration_ad_supported = true; 3821 #endif /* CONFIG_MIGRATION */ 3822 3823 return 0; 3824 } 3825 subsys_initcall(swapfile_init); 3826