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 < 0 || 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 /** 2142 * swap_alloc_hibernation_slot() - Allocate a swap slot for hibernation. 2143 * @type: swap device type index to allocate from. 2144 * 2145 * The caller must ensure the swap device is stable, either by pinning 2146 * it (SWP_HIBERNATION) or by freezing user-space. 2147 * 2148 * Return: a valid swp_entry_t on success, or an empty entry (val == 0) 2149 * on failure. 2150 */ 2151 swp_entry_t swap_alloc_hibernation_slot(int type) 2152 { 2153 struct swap_info_struct *pcp_si, *si = swap_type_to_info(type); 2154 unsigned long pcp_offset, offset = SWAP_ENTRY_INVALID; 2155 struct swap_cluster_info *ci; 2156 swp_entry_t entry = {0}; 2157 2158 if (!si) 2159 goto fail; 2160 2161 /* 2162 * Try the local cluster first if it matches the device. If 2163 * not, try grab a new cluster and override local cluster. 2164 */ 2165 local_lock(&percpu_swap_cluster.lock); 2166 pcp_si = this_cpu_read(percpu_swap_cluster.si[0]); 2167 pcp_offset = this_cpu_read(percpu_swap_cluster.offset[0]); 2168 if (pcp_si == si && pcp_offset) { 2169 ci = swap_cluster_lock(si, pcp_offset); 2170 if (cluster_is_usable(ci, 0)) 2171 offset = alloc_swap_scan_cluster(si, ci, NULL, pcp_offset); 2172 else 2173 swap_cluster_unlock(ci); 2174 } 2175 if (!offset) 2176 offset = cluster_alloc_swap_entry(si, NULL); 2177 local_unlock(&percpu_swap_cluster.lock); 2178 if (offset) 2179 entry = swp_entry(si->type, offset); 2180 2181 fail: 2182 return entry; 2183 } 2184 2185 /** 2186 * swap_free_hibernation_slot() - Free a swap slot allocated for hibernation. 2187 * @entry: swap entry to free. 2188 * 2189 * The caller must ensure the swap device is stable. 2190 */ 2191 void swap_free_hibernation_slot(swp_entry_t entry) 2192 { 2193 struct swap_info_struct *si = __swap_entry_to_info(entry); 2194 struct swap_cluster_info *ci; 2195 pgoff_t offset = swp_offset(entry); 2196 2197 ci = swap_cluster_lock(si, offset); 2198 __swap_cluster_put_entry(ci, offset % SWAPFILE_CLUSTER); 2199 __swap_cluster_free_entries(si, ci, offset % SWAPFILE_CLUSTER, 1); 2200 swap_cluster_unlock(ci); 2201 2202 /* In theory readahead might add it to the swap cache by accident */ 2203 __try_to_reclaim_swap(si, offset, TTRS_ANYWAY); 2204 } 2205 2206 static int __find_hibernation_swap_type(dev_t device, sector_t offset) 2207 { 2208 int type; 2209 2210 lockdep_assert_held(&swap_lock); 2211 2212 if (!device) 2213 return -EINVAL; 2214 2215 for (type = 0; type < nr_swapfiles; type++) { 2216 struct swap_info_struct *sis = swap_info[type]; 2217 2218 if (!(sis->flags & SWP_WRITEOK)) 2219 continue; 2220 2221 if (device == sis->bdev->bd_dev) { 2222 struct swap_extent *se = first_se(sis); 2223 2224 if (se->start_block == offset) 2225 return type; 2226 } 2227 } 2228 return -ENODEV; 2229 } 2230 2231 /** 2232 * pin_hibernation_swap_type - Pin the swap device for hibernation 2233 * @device: Block device containing the resume image 2234 * @offset: Offset identifying the swap area 2235 * 2236 * Locate the swap device for @device/@offset and mark it as pinned 2237 * for hibernation. While pinned, swapoff() is prevented. 2238 * 2239 * Only one uswsusp context may pin a swap device at a time. 2240 * If already pinned, this function returns -EBUSY. 2241 * 2242 * Return: 2243 * >= 0 on success (swap type). 2244 * -EINVAL if @device is invalid. 2245 * -ENODEV if the swap device is not found. 2246 * -EBUSY if the device is already pinned for hibernation. 2247 */ 2248 int pin_hibernation_swap_type(dev_t device, sector_t offset) 2249 { 2250 int type; 2251 struct swap_info_struct *si; 2252 2253 spin_lock(&swap_lock); 2254 2255 type = __find_hibernation_swap_type(device, offset); 2256 if (type < 0) { 2257 spin_unlock(&swap_lock); 2258 return type; 2259 } 2260 2261 si = swap_type_to_info(type); 2262 if (WARN_ON_ONCE(!si)) { 2263 spin_unlock(&swap_lock); 2264 return -ENODEV; 2265 } 2266 2267 /* 2268 * hibernate_acquire() prevents concurrent hibernation sessions. 2269 * This check additionally guards against double-pinning within 2270 * the same session. 2271 */ 2272 if (WARN_ON_ONCE(si->flags & SWP_HIBERNATION)) { 2273 spin_unlock(&swap_lock); 2274 return -EBUSY; 2275 } 2276 2277 si->flags |= SWP_HIBERNATION; 2278 2279 spin_unlock(&swap_lock); 2280 return type; 2281 } 2282 2283 /** 2284 * unpin_hibernation_swap_type - Unpin the swap device for hibernation 2285 * @type: Swap type previously returned by pin_hibernation_swap_type() 2286 * 2287 * Clear the hibernation pin on the given swap device, allowing 2288 * swapoff() to proceed normally. 2289 * 2290 * If @type does not refer to a valid swap device, this function 2291 * does nothing. 2292 */ 2293 void unpin_hibernation_swap_type(int type) 2294 { 2295 struct swap_info_struct *si; 2296 2297 spin_lock(&swap_lock); 2298 si = swap_type_to_info(type); 2299 if (!si) { 2300 spin_unlock(&swap_lock); 2301 return; 2302 } 2303 si->flags &= ~SWP_HIBERNATION; 2304 spin_unlock(&swap_lock); 2305 } 2306 2307 /** 2308 * find_hibernation_swap_type - Find swap type for hibernation 2309 * @device: Block device containing the resume image 2310 * @offset: Offset within the device identifying the swap area 2311 * 2312 * Locate the swap device corresponding to @device and @offset. 2313 * 2314 * Unlike pin_hibernation_swap_type(), this function only performs a 2315 * lookup and does not mark the swap device as pinned for hibernation. 2316 * 2317 * This is safe in the sysfs-based hibernation path where user space 2318 * is already frozen and swapoff() cannot run concurrently. 2319 * 2320 * Return: 2321 * A non-negative swap type on success. 2322 * -EINVAL if @device is invalid. 2323 * -ENODEV if no matching swap device is found. 2324 */ 2325 int find_hibernation_swap_type(dev_t device, sector_t offset) 2326 { 2327 int type; 2328 2329 spin_lock(&swap_lock); 2330 type = __find_hibernation_swap_type(device, offset); 2331 spin_unlock(&swap_lock); 2332 2333 return type; 2334 } 2335 2336 int find_first_swap(dev_t *device) 2337 { 2338 int type; 2339 2340 spin_lock(&swap_lock); 2341 for (type = 0; type < nr_swapfiles; type++) { 2342 struct swap_info_struct *sis = swap_info[type]; 2343 2344 if (!(sis->flags & SWP_WRITEOK)) 2345 continue; 2346 *device = sis->bdev->bd_dev; 2347 spin_unlock(&swap_lock); 2348 return type; 2349 } 2350 spin_unlock(&swap_lock); 2351 return -ENODEV; 2352 } 2353 2354 /* 2355 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev 2356 * corresponding to given index in swap_info (swap type). 2357 */ 2358 sector_t swapdev_block(int type, pgoff_t offset) 2359 { 2360 struct swap_info_struct *si = swap_type_to_info(type); 2361 struct swap_extent *se; 2362 2363 if (!si || !(si->flags & SWP_WRITEOK)) 2364 return 0; 2365 se = offset_to_swap_extent(si, offset); 2366 return se->start_block + (offset - se->start_page); 2367 } 2368 2369 /* 2370 * Return either the total number of swap pages of given type, or the number 2371 * of free pages of that type (depending on @free) 2372 * 2373 * This is needed for software suspend 2374 */ 2375 unsigned int count_swap_pages(int type, int free) 2376 { 2377 unsigned int n = 0; 2378 2379 spin_lock(&swap_lock); 2380 if ((unsigned int)type < nr_swapfiles) { 2381 struct swap_info_struct *sis = swap_info[type]; 2382 2383 spin_lock(&sis->lock); 2384 if (sis->flags & SWP_WRITEOK) { 2385 n = sis->pages; 2386 if (free) 2387 n -= swap_usage_in_pages(sis); 2388 } 2389 spin_unlock(&sis->lock); 2390 } 2391 spin_unlock(&swap_lock); 2392 return n; 2393 } 2394 #endif /* CONFIG_HIBERNATION */ 2395 2396 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte) 2397 { 2398 return pte_same(pte_swp_clear_flags(pte), swp_pte); 2399 } 2400 2401 /* 2402 * No need to decide whether this PTE shares the swap entry with others, 2403 * just let do_wp_page work it out if a write is requested later - to 2404 * force COW, vm_page_prot omits write permission from any private vma. 2405 */ 2406 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd, 2407 unsigned long addr, swp_entry_t entry, struct folio *folio) 2408 { 2409 struct page *page; 2410 struct folio *swapcache; 2411 spinlock_t *ptl; 2412 pte_t *pte, new_pte, old_pte; 2413 bool hwpoisoned = false; 2414 int ret = 1; 2415 2416 /* 2417 * If the folio is removed from swap cache by others, continue to 2418 * unuse other PTEs. try_to_unuse may try again if we missed this one. 2419 */ 2420 if (!folio_matches_swap_entry(folio, entry)) 2421 return 0; 2422 2423 swapcache = folio; 2424 folio = ksm_might_need_to_copy(folio, vma, addr); 2425 if (unlikely(!folio)) 2426 return -ENOMEM; 2427 else if (unlikely(folio == ERR_PTR(-EHWPOISON))) { 2428 hwpoisoned = true; 2429 folio = swapcache; 2430 } 2431 2432 page = folio_file_page(folio, swp_offset(entry)); 2433 if (PageHWPoison(page)) 2434 hwpoisoned = true; 2435 2436 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); 2437 if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte), 2438 swp_entry_to_pte(entry)))) { 2439 ret = 0; 2440 goto out; 2441 } 2442 2443 old_pte = ptep_get(pte); 2444 2445 if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) { 2446 swp_entry_t swp_entry; 2447 2448 dec_mm_counter(vma->vm_mm, MM_SWAPENTS); 2449 if (hwpoisoned) { 2450 swp_entry = make_hwpoison_entry(page); 2451 } else { 2452 swp_entry = make_poisoned_swp_entry(); 2453 } 2454 new_pte = swp_entry_to_pte(swp_entry); 2455 ret = 0; 2456 goto setpte; 2457 } 2458 2459 /* 2460 * Some architectures may have to restore extra metadata to the page 2461 * when reading from swap. This metadata may be indexed by swap entry 2462 * so this must be called before folio_put_swap(). 2463 */ 2464 arch_swap_restore(folio_swap(entry, folio), folio); 2465 2466 dec_mm_counter(vma->vm_mm, MM_SWAPENTS); 2467 inc_mm_counter(vma->vm_mm, MM_ANONPAGES); 2468 folio_get(folio); 2469 if (folio == swapcache) { 2470 rmap_t rmap_flags = RMAP_NONE; 2471 2472 /* 2473 * See do_swap_page(): writeback would be problematic. 2474 * However, we do a folio_wait_writeback() just before this 2475 * call and have the folio locked. 2476 */ 2477 VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio); 2478 if (pte_swp_exclusive(old_pte)) 2479 rmap_flags |= RMAP_EXCLUSIVE; 2480 /* 2481 * We currently only expect small !anon folios, which are either 2482 * fully exclusive or fully shared. If we ever get large folios 2483 * here, we have to be careful. 2484 */ 2485 if (!folio_test_anon(folio)) { 2486 VM_WARN_ON_ONCE(folio_test_large(folio)); 2487 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 2488 folio_add_new_anon_rmap(folio, vma, addr, rmap_flags); 2489 } else { 2490 folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags); 2491 } 2492 } else { /* ksm created a completely new copy */ 2493 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE); 2494 folio_add_lru_vma(folio, vma); 2495 } 2496 new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot)); 2497 if (pte_swp_soft_dirty(old_pte)) 2498 new_pte = pte_mksoft_dirty(new_pte); 2499 if (pte_swp_uffd_wp(old_pte)) 2500 new_pte = pte_mkuffd_wp(new_pte); 2501 setpte: 2502 set_pte_at(vma->vm_mm, addr, pte, new_pte); 2503 folio_put_swap(swapcache, folio_file_page(swapcache, swp_offset(entry))); 2504 out: 2505 if (pte) 2506 pte_unmap_unlock(pte, ptl); 2507 if (folio != swapcache) { 2508 folio_unlock(folio); 2509 folio_put(folio); 2510 } 2511 return ret; 2512 } 2513 2514 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd, 2515 unsigned long addr, unsigned long end, 2516 unsigned int type) 2517 { 2518 pte_t *pte = NULL; 2519 2520 do { 2521 struct folio *folio; 2522 unsigned long swp_tb; 2523 softleaf_t entry; 2524 int ret; 2525 pte_t ptent; 2526 2527 if (!pte++) { 2528 pte = pte_offset_map(pmd, addr); 2529 if (!pte) 2530 break; 2531 } 2532 2533 ptent = ptep_get_lockless(pte); 2534 entry = softleaf_from_pte(ptent); 2535 2536 if (!softleaf_is_swap(entry)) 2537 continue; 2538 if (swp_type(entry) != type) 2539 continue; 2540 2541 pte_unmap(pte); 2542 pte = NULL; 2543 2544 folio = swap_cache_get_folio(entry); 2545 if (!folio) { 2546 struct vm_fault vmf = { 2547 .vma = vma, 2548 .address = addr, 2549 .real_address = addr, 2550 .pmd = pmd, 2551 }; 2552 2553 folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, 2554 &vmf); 2555 } 2556 if (!folio) { 2557 swp_tb = swap_table_get(__swap_entry_to_cluster(entry), 2558 swp_cluster_offset(entry)); 2559 if (swp_tb_get_count(swp_tb) <= 0) 2560 continue; 2561 return -ENOMEM; 2562 } 2563 2564 folio_lock(folio); 2565 folio_wait_writeback(folio); 2566 ret = unuse_pte(vma, pmd, addr, entry, folio); 2567 if (ret < 0) { 2568 folio_unlock(folio); 2569 folio_put(folio); 2570 return ret; 2571 } 2572 2573 folio_free_swap(folio); 2574 folio_unlock(folio); 2575 folio_put(folio); 2576 } while (addr += PAGE_SIZE, addr != end); 2577 2578 if (pte) 2579 pte_unmap(pte); 2580 return 0; 2581 } 2582 2583 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud, 2584 unsigned long addr, unsigned long end, 2585 unsigned int type) 2586 { 2587 pmd_t *pmd; 2588 unsigned long next; 2589 int ret; 2590 2591 pmd = pmd_offset(pud, addr); 2592 do { 2593 cond_resched(); 2594 next = pmd_addr_end(addr, end); 2595 ret = unuse_pte_range(vma, pmd, addr, next, type); 2596 if (ret) 2597 return ret; 2598 } while (pmd++, addr = next, addr != end); 2599 return 0; 2600 } 2601 2602 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d, 2603 unsigned long addr, unsigned long end, 2604 unsigned int type) 2605 { 2606 pud_t *pud; 2607 unsigned long next; 2608 int ret; 2609 2610 pud = pud_offset(p4d, addr); 2611 do { 2612 next = pud_addr_end(addr, end); 2613 if (pud_none_or_clear_bad(pud)) 2614 continue; 2615 ret = unuse_pmd_range(vma, pud, addr, next, type); 2616 if (ret) 2617 return ret; 2618 } while (pud++, addr = next, addr != end); 2619 return 0; 2620 } 2621 2622 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd, 2623 unsigned long addr, unsigned long end, 2624 unsigned int type) 2625 { 2626 p4d_t *p4d; 2627 unsigned long next; 2628 int ret; 2629 2630 p4d = p4d_offset(pgd, addr); 2631 do { 2632 next = p4d_addr_end(addr, end); 2633 if (p4d_none_or_clear_bad(p4d)) 2634 continue; 2635 ret = unuse_pud_range(vma, p4d, addr, next, type); 2636 if (ret) 2637 return ret; 2638 } while (p4d++, addr = next, addr != end); 2639 return 0; 2640 } 2641 2642 static int unuse_vma(struct vm_area_struct *vma, unsigned int type) 2643 { 2644 pgd_t *pgd; 2645 unsigned long addr, end, next; 2646 int ret; 2647 2648 addr = vma->vm_start; 2649 end = vma->vm_end; 2650 2651 pgd = pgd_offset(vma->vm_mm, addr); 2652 do { 2653 next = pgd_addr_end(addr, end); 2654 if (pgd_none_or_clear_bad(pgd)) 2655 continue; 2656 ret = unuse_p4d_range(vma, pgd, addr, next, type); 2657 if (ret) 2658 return ret; 2659 } while (pgd++, addr = next, addr != end); 2660 return 0; 2661 } 2662 2663 static int unuse_mm(struct mm_struct *mm, unsigned int type) 2664 { 2665 struct vm_area_struct *vma; 2666 int ret = 0; 2667 VMA_ITERATOR(vmi, mm, 0); 2668 2669 mmap_read_lock(mm); 2670 if (check_stable_address_space(mm)) 2671 goto unlock; 2672 for_each_vma(vmi, vma) { 2673 if (vma->anon_vma && !is_vm_hugetlb_page(vma)) { 2674 ret = unuse_vma(vma, type); 2675 if (ret) 2676 break; 2677 } 2678 2679 cond_resched(); 2680 } 2681 unlock: 2682 mmap_read_unlock(mm); 2683 return ret; 2684 } 2685 2686 /* 2687 * Scan swap table from current position to next entry still in use. 2688 * Return 0 if there are no inuse entries after prev till end of 2689 * the map. 2690 */ 2691 static unsigned int find_next_to_unuse(struct swap_info_struct *si, 2692 unsigned int prev) 2693 { 2694 unsigned int i; 2695 unsigned long swp_tb; 2696 2697 /* 2698 * No need for swap_lock here: we're just looking 2699 * for whether an entry is in use, not modifying it; false 2700 * hits are okay, and sys_swapoff() has already prevented new 2701 * allocations from this area (while holding swap_lock). 2702 */ 2703 for (i = prev + 1; i < si->max; i++) { 2704 swp_tb = swap_table_get(__swap_offset_to_cluster(si, i), 2705 i % SWAPFILE_CLUSTER); 2706 if (!swp_tb_is_null(swp_tb) && !swp_tb_is_bad(swp_tb)) 2707 break; 2708 if ((i % LATENCY_LIMIT) == 0) 2709 cond_resched(); 2710 } 2711 2712 if (i == si->max) 2713 i = 0; 2714 2715 return i; 2716 } 2717 2718 static int try_to_unuse(unsigned int type) 2719 { 2720 struct mm_struct *prev_mm; 2721 struct mm_struct *mm; 2722 struct list_head *p; 2723 int retval = 0; 2724 struct swap_info_struct *si = swap_info[type]; 2725 struct folio *folio; 2726 swp_entry_t entry; 2727 unsigned int i; 2728 2729 if (!swap_usage_in_pages(si)) 2730 goto success; 2731 2732 retry: 2733 retval = shmem_unuse(type); 2734 if (retval) 2735 return retval; 2736 2737 prev_mm = &init_mm; 2738 mmget(prev_mm); 2739 2740 spin_lock(&mmlist_lock); 2741 p = &init_mm.mmlist; 2742 while (swap_usage_in_pages(si) && 2743 !signal_pending(current) && 2744 (p = p->next) != &init_mm.mmlist) { 2745 2746 mm = list_entry(p, struct mm_struct, mmlist); 2747 if (!mmget_not_zero(mm)) 2748 continue; 2749 spin_unlock(&mmlist_lock); 2750 mmput(prev_mm); 2751 prev_mm = mm; 2752 retval = unuse_mm(mm, type); 2753 if (retval) { 2754 mmput(prev_mm); 2755 return retval; 2756 } 2757 2758 /* 2759 * Make sure that we aren't completely killing 2760 * interactive performance. 2761 */ 2762 cond_resched(); 2763 spin_lock(&mmlist_lock); 2764 } 2765 spin_unlock(&mmlist_lock); 2766 2767 mmput(prev_mm); 2768 2769 i = 0; 2770 while (swap_usage_in_pages(si) && 2771 !signal_pending(current) && 2772 (i = find_next_to_unuse(si, i)) != 0) { 2773 2774 entry = swp_entry(type, i); 2775 folio = swap_cache_get_folio(entry); 2776 if (!folio) 2777 continue; 2778 2779 /* 2780 * It is conceivable that a racing task removed this folio from 2781 * swap cache just before we acquired the page lock. The folio 2782 * might even be back in swap cache on another swap area. But 2783 * that is okay, folio_free_swap() only removes stale folios. 2784 */ 2785 folio_lock(folio); 2786 folio_wait_writeback(folio); 2787 folio_free_swap(folio); 2788 folio_unlock(folio); 2789 folio_put(folio); 2790 } 2791 2792 /* 2793 * Lets check again to see if there are still swap entries in the map. 2794 * If yes, we would need to do retry the unuse logic again. 2795 * Under global memory pressure, swap entries can be reinserted back 2796 * into process space after the mmlist loop above passes over them. 2797 * 2798 * Limit the number of retries? No: when mmget_not_zero() 2799 * above fails, that mm is likely to be freeing swap from 2800 * exit_mmap(), which proceeds at its own independent pace; 2801 * and even shmem_writeout() could have been preempted after 2802 * folio_alloc_swap(), temporarily hiding that swap. It's easy 2803 * and robust (though cpu-intensive) just to keep retrying. 2804 */ 2805 if (swap_usage_in_pages(si)) { 2806 if (!signal_pending(current)) 2807 goto retry; 2808 return -EINTR; 2809 } 2810 2811 success: 2812 /* 2813 * Make sure that further cleanups after try_to_unuse() returns happen 2814 * after swap_range_free() reduces si->inuse_pages to 0. 2815 */ 2816 smp_mb(); 2817 return 0; 2818 } 2819 2820 /* 2821 * After a successful try_to_unuse, if no swap is now in use, we know 2822 * we can empty the mmlist. swap_lock must be held on entry and exit. 2823 * Note that mmlist_lock nests inside swap_lock, and an mm must be 2824 * added to the mmlist just after page_duplicate - before would be racy. 2825 */ 2826 static void drain_mmlist(void) 2827 { 2828 struct list_head *p, *next; 2829 unsigned int type; 2830 2831 for (type = 0; type < nr_swapfiles; type++) 2832 if (swap_usage_in_pages(swap_info[type])) 2833 return; 2834 spin_lock(&mmlist_lock); 2835 list_for_each_safe(p, next, &init_mm.mmlist) 2836 list_del_init(p); 2837 spin_unlock(&mmlist_lock); 2838 } 2839 2840 /* 2841 * Free all of a swapdev's extent information 2842 */ 2843 static void destroy_swap_extents(struct swap_info_struct *sis, 2844 struct file *swap_file) 2845 { 2846 while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) { 2847 struct rb_node *rb = sis->swap_extent_root.rb_node; 2848 struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node); 2849 2850 rb_erase(rb, &sis->swap_extent_root); 2851 kfree(se); 2852 } 2853 2854 if (sis->flags & SWP_ACTIVATED) { 2855 struct address_space *mapping = swap_file->f_mapping; 2856 2857 sis->flags &= ~SWP_ACTIVATED; 2858 if (mapping->a_ops->swap_deactivate) 2859 mapping->a_ops->swap_deactivate(swap_file); 2860 } 2861 } 2862 2863 /* 2864 * Add a block range (and the corresponding page range) into this swapdev's 2865 * extent tree. 2866 * 2867 * This function rather assumes that it is called in ascending page order. 2868 */ 2869 int 2870 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page, 2871 unsigned long nr_pages, sector_t start_block) 2872 { 2873 struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL; 2874 struct swap_extent *se; 2875 struct swap_extent *new_se; 2876 2877 /* 2878 * place the new node at the right most since the 2879 * function is called in ascending page order. 2880 */ 2881 while (*link) { 2882 parent = *link; 2883 link = &parent->rb_right; 2884 } 2885 2886 if (parent) { 2887 se = rb_entry(parent, struct swap_extent, rb_node); 2888 BUG_ON(se->start_page + se->nr_pages != start_page); 2889 if (se->start_block + se->nr_pages == start_block) { 2890 /* Merge it */ 2891 se->nr_pages += nr_pages; 2892 return 0; 2893 } 2894 } 2895 2896 /* No merge, insert a new extent. */ 2897 new_se = kmalloc_obj(*se); 2898 if (new_se == NULL) 2899 return -ENOMEM; 2900 new_se->start_page = start_page; 2901 new_se->nr_pages = nr_pages; 2902 new_se->start_block = start_block; 2903 2904 rb_link_node(&new_se->rb_node, parent, link); 2905 rb_insert_color(&new_se->rb_node, &sis->swap_extent_root); 2906 return 1; 2907 } 2908 EXPORT_SYMBOL_GPL(add_swap_extent); 2909 2910 /* 2911 * A `swap extent' is a simple thing which maps a contiguous range of pages 2912 * onto a contiguous range of disk blocks. A rbtree of swap extents is 2913 * built at swapon time and is then used at swap_writepage/swap_read_folio 2914 * time for locating where on disk a page belongs. 2915 * 2916 * If the swapfile is an S_ISBLK block device, a single extent is installed. 2917 * This is done so that the main operating code can treat S_ISBLK and S_ISREG 2918 * swap files identically. 2919 * 2920 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap 2921 * extent rbtree operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK 2922 * swapfiles are handled *identically* after swapon time. 2923 * 2924 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks 2925 * and will parse them into a rbtree, in PAGE_SIZE chunks. If some stray 2926 * blocks are found which do not fall within the PAGE_SIZE alignment 2927 * requirements, they are simply tossed out - we will never use those blocks 2928 * for swapping. 2929 * 2930 * For all swap devices we set S_SWAPFILE across the life of the swapon. This 2931 * prevents users from writing to the swap device, which will corrupt memory. 2932 * 2933 * The amount of disk space which a single swap extent represents varies. 2934 * Typically it is in the 1-4 megabyte range. So we can have hundreds of 2935 * extents in the rbtree. - akpm. 2936 */ 2937 static int setup_swap_extents(struct swap_info_struct *sis, 2938 struct file *swap_file, sector_t *span) 2939 { 2940 struct address_space *mapping = swap_file->f_mapping; 2941 struct inode *inode = mapping->host; 2942 int ret; 2943 2944 if (S_ISBLK(inode->i_mode)) { 2945 ret = add_swap_extent(sis, 0, sis->max, 0); 2946 *span = sis->pages; 2947 return ret; 2948 } 2949 2950 if (mapping->a_ops->swap_activate) { 2951 ret = mapping->a_ops->swap_activate(sis, swap_file, span); 2952 if (ret < 0) 2953 return ret; 2954 sis->flags |= SWP_ACTIVATED; 2955 if ((sis->flags & SWP_FS_OPS) && 2956 sio_pool_init() != 0) { 2957 destroy_swap_extents(sis, swap_file); 2958 return -ENOMEM; 2959 } 2960 return ret; 2961 } 2962 2963 return generic_swapfile_activate(sis, swap_file, span); 2964 } 2965 2966 static void _enable_swap_info(struct swap_info_struct *si) 2967 { 2968 atomic_long_add(si->pages, &nr_swap_pages); 2969 total_swap_pages += si->pages; 2970 2971 assert_spin_locked(&swap_lock); 2972 2973 plist_add(&si->list, &swap_active_head); 2974 2975 /* Add back to available list */ 2976 add_to_avail_list(si, true); 2977 } 2978 2979 /* 2980 * Called after the swap device is ready, resurrect its percpu ref, it's now 2981 * safe to reference it. Add it to the list to expose it to the allocator. 2982 */ 2983 static void enable_swap_info(struct swap_info_struct *si) 2984 { 2985 percpu_ref_resurrect(&si->users); 2986 spin_lock(&swap_lock); 2987 spin_lock(&si->lock); 2988 _enable_swap_info(si); 2989 spin_unlock(&si->lock); 2990 spin_unlock(&swap_lock); 2991 } 2992 2993 static void reinsert_swap_info(struct swap_info_struct *si) 2994 { 2995 spin_lock(&swap_lock); 2996 spin_lock(&si->lock); 2997 _enable_swap_info(si); 2998 spin_unlock(&si->lock); 2999 spin_unlock(&swap_lock); 3000 } 3001 3002 /* 3003 * Called after clearing SWP_WRITEOK, ensures cluster_alloc_range 3004 * see the updated flags, so there will be no more allocations. 3005 */ 3006 static void wait_for_allocation(struct swap_info_struct *si) 3007 { 3008 unsigned long offset; 3009 unsigned long end = ALIGN(si->max, SWAPFILE_CLUSTER); 3010 struct swap_cluster_info *ci; 3011 3012 BUG_ON(si->flags & SWP_WRITEOK); 3013 3014 for (offset = 0; offset < end; offset += SWAPFILE_CLUSTER) { 3015 ci = swap_cluster_lock(si, offset); 3016 swap_cluster_unlock(ci); 3017 } 3018 } 3019 3020 static void free_swap_cluster_info(struct swap_cluster_info *cluster_info, 3021 unsigned long maxpages) 3022 { 3023 struct swap_cluster_info *ci; 3024 int i, nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); 3025 3026 if (!cluster_info) 3027 return; 3028 for (i = 0; i < nr_clusters; i++) { 3029 ci = cluster_info + i; 3030 /* Cluster with bad marks count will have a remaining table */ 3031 spin_lock(&ci->lock); 3032 if (cluster_table_is_alloced(ci)) { 3033 swap_cluster_assert_empty(ci, 0, SWAPFILE_CLUSTER, true); 3034 swap_cluster_free_table(ci); 3035 } 3036 spin_unlock(&ci->lock); 3037 } 3038 kvfree(cluster_info); 3039 } 3040 3041 /* 3042 * Called after swap device's reference count is dead, so 3043 * neither scan nor allocation will use it. 3044 */ 3045 static void flush_percpu_swap_cluster(struct swap_info_struct *si) 3046 { 3047 int cpu, i; 3048 struct swap_info_struct **pcp_si; 3049 3050 for_each_possible_cpu(cpu) { 3051 pcp_si = per_cpu_ptr(percpu_swap_cluster.si, cpu); 3052 /* 3053 * Invalidate the percpu swap cluster cache, si->users 3054 * is dead, so no new user will point to it, just flush 3055 * any existing user. 3056 */ 3057 for (i = 0; i < SWAP_NR_ORDERS; i++) 3058 cmpxchg(&pcp_si[i], si, NULL); 3059 } 3060 } 3061 3062 3063 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile) 3064 { 3065 struct swap_info_struct *p = NULL; 3066 struct swap_cluster_info *cluster_info; 3067 struct file *swap_file, *victim; 3068 struct address_space *mapping; 3069 struct inode *inode; 3070 unsigned int maxpages; 3071 int err, found = 0; 3072 3073 if (!capable(CAP_SYS_ADMIN)) 3074 return -EPERM; 3075 3076 BUG_ON(!current->mm); 3077 3078 CLASS(filename, pathname)(specialfile); 3079 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0); 3080 if (IS_ERR(victim)) 3081 return PTR_ERR(victim); 3082 3083 mapping = victim->f_mapping; 3084 spin_lock(&swap_lock); 3085 plist_for_each_entry(p, &swap_active_head, list) { 3086 if (p->flags & SWP_WRITEOK) { 3087 if (p->swap_file->f_mapping == mapping) { 3088 found = 1; 3089 break; 3090 } 3091 } 3092 } 3093 if (!found) { 3094 err = -EINVAL; 3095 spin_unlock(&swap_lock); 3096 goto out_dput; 3097 } 3098 3099 /* Refuse swapoff while the device is pinned for hibernation */ 3100 if (p->flags & SWP_HIBERNATION) { 3101 err = -EBUSY; 3102 spin_unlock(&swap_lock); 3103 goto out_dput; 3104 } 3105 3106 if (!security_vm_enough_memory_mm(current->mm, p->pages)) 3107 vm_unacct_memory(p->pages); 3108 else { 3109 err = -ENOMEM; 3110 spin_unlock(&swap_lock); 3111 goto out_dput; 3112 } 3113 spin_lock(&p->lock); 3114 del_from_avail_list(p, true); 3115 plist_del(&p->list, &swap_active_head); 3116 atomic_long_sub(p->pages, &nr_swap_pages); 3117 total_swap_pages -= p->pages; 3118 spin_unlock(&p->lock); 3119 spin_unlock(&swap_lock); 3120 3121 wait_for_allocation(p); 3122 3123 set_current_oom_origin(); 3124 err = try_to_unuse(p->type); 3125 clear_current_oom_origin(); 3126 3127 if (err) { 3128 /* re-insert swap space back into swap_list */ 3129 reinsert_swap_info(p); 3130 goto out_dput; 3131 } 3132 3133 /* 3134 * Wait for swap operations protected by get/put_swap_device() 3135 * to complete. Because of synchronize_rcu() here, all swap 3136 * operations protected by RCU reader side lock (including any 3137 * spinlock) will be waited too. This makes it easy to 3138 * prevent folio_test_swapcache() and the following swap cache 3139 * operations from racing with swapoff. 3140 */ 3141 percpu_ref_kill(&p->users); 3142 synchronize_rcu(); 3143 wait_for_completion(&p->comp); 3144 3145 flush_work(&p->discard_work); 3146 flush_work(&p->reclaim_work); 3147 flush_percpu_swap_cluster(p); 3148 3149 destroy_swap_extents(p, p->swap_file); 3150 3151 if (!(p->flags & SWP_SOLIDSTATE)) 3152 atomic_dec(&nr_rotate_swap); 3153 3154 mutex_lock(&swapon_mutex); 3155 spin_lock(&swap_lock); 3156 spin_lock(&p->lock); 3157 drain_mmlist(); 3158 3159 swap_file = p->swap_file; 3160 p->swap_file = NULL; 3161 maxpages = p->max; 3162 cluster_info = p->cluster_info; 3163 p->max = 0; 3164 p->cluster_info = NULL; 3165 spin_unlock(&p->lock); 3166 spin_unlock(&swap_lock); 3167 arch_swap_invalidate_area(p->type); 3168 zswap_swapoff(p->type); 3169 mutex_unlock(&swapon_mutex); 3170 kfree(p->global_cluster); 3171 p->global_cluster = NULL; 3172 free_swap_cluster_info(cluster_info, maxpages); 3173 3174 inode = mapping->host; 3175 3176 inode_lock(inode); 3177 inode->i_flags &= ~S_SWAPFILE; 3178 inode_unlock(inode); 3179 filp_close(swap_file, NULL); 3180 3181 /* 3182 * Clear the SWP_USED flag after all resources are freed so that swapon 3183 * can reuse this swap_info in alloc_swap_info() safely. It is ok to 3184 * not hold p->lock after we cleared its SWP_WRITEOK. 3185 */ 3186 spin_lock(&swap_lock); 3187 p->flags = 0; 3188 spin_unlock(&swap_lock); 3189 3190 err = 0; 3191 atomic_inc(&proc_poll_event); 3192 wake_up_interruptible(&proc_poll_wait); 3193 3194 out_dput: 3195 filp_close(victim, NULL); 3196 return err; 3197 } 3198 3199 #ifdef CONFIG_PROC_FS 3200 static __poll_t swaps_poll(struct file *file, poll_table *wait) 3201 { 3202 struct seq_file *seq = file->private_data; 3203 3204 poll_wait(file, &proc_poll_wait, wait); 3205 3206 if (seq->poll_event != atomic_read(&proc_poll_event)) { 3207 seq->poll_event = atomic_read(&proc_poll_event); 3208 return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI; 3209 } 3210 3211 return EPOLLIN | EPOLLRDNORM; 3212 } 3213 3214 /* iterator */ 3215 static void *swap_start(struct seq_file *swap, loff_t *pos) 3216 { 3217 struct swap_info_struct *si; 3218 int type; 3219 loff_t l = *pos; 3220 3221 mutex_lock(&swapon_mutex); 3222 3223 if (!l) 3224 return SEQ_START_TOKEN; 3225 3226 for (type = 0; (si = swap_type_to_info(type)); type++) { 3227 if (!(si->swap_file)) 3228 continue; 3229 if (!--l) 3230 return si; 3231 } 3232 3233 return NULL; 3234 } 3235 3236 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos) 3237 { 3238 struct swap_info_struct *si = v; 3239 int type; 3240 3241 if (v == SEQ_START_TOKEN) 3242 type = 0; 3243 else 3244 type = si->type + 1; 3245 3246 ++(*pos); 3247 for (; (si = swap_type_to_info(type)); type++) { 3248 if (!(si->swap_file)) 3249 continue; 3250 return si; 3251 } 3252 3253 return NULL; 3254 } 3255 3256 static void swap_stop(struct seq_file *swap, void *v) 3257 { 3258 mutex_unlock(&swapon_mutex); 3259 } 3260 3261 static int swap_show(struct seq_file *swap, void *v) 3262 { 3263 struct swap_info_struct *si = v; 3264 struct file *file; 3265 int len; 3266 unsigned long bytes, inuse; 3267 3268 if (si == SEQ_START_TOKEN) { 3269 seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n"); 3270 return 0; 3271 } 3272 3273 bytes = K(si->pages); 3274 inuse = K(swap_usage_in_pages(si)); 3275 3276 file = si->swap_file; 3277 len = seq_file_path(swap, file, " \t\n\\"); 3278 seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n", 3279 len < 40 ? 40 - len : 1, " ", 3280 S_ISBLK(file_inode(file)->i_mode) ? 3281 "partition" : "file\t", 3282 bytes, bytes < 10000000 ? "\t" : "", 3283 inuse, inuse < 10000000 ? "\t" : "", 3284 si->prio); 3285 return 0; 3286 } 3287 3288 static const struct seq_operations swaps_op = { 3289 .start = swap_start, 3290 .next = swap_next, 3291 .stop = swap_stop, 3292 .show = swap_show 3293 }; 3294 3295 static int swaps_open(struct inode *inode, struct file *file) 3296 { 3297 struct seq_file *seq; 3298 int ret; 3299 3300 ret = seq_open(file, &swaps_op); 3301 if (ret) 3302 return ret; 3303 3304 seq = file->private_data; 3305 seq->poll_event = atomic_read(&proc_poll_event); 3306 return 0; 3307 } 3308 3309 static const struct proc_ops swaps_proc_ops = { 3310 .proc_flags = PROC_ENTRY_PERMANENT, 3311 .proc_open = swaps_open, 3312 .proc_read = seq_read, 3313 .proc_lseek = seq_lseek, 3314 .proc_release = seq_release, 3315 .proc_poll = swaps_poll, 3316 }; 3317 3318 static int __init procswaps_init(void) 3319 { 3320 proc_create("swaps", 0, NULL, &swaps_proc_ops); 3321 return 0; 3322 } 3323 __initcall(procswaps_init); 3324 #endif /* CONFIG_PROC_FS */ 3325 3326 #ifdef MAX_SWAPFILES_CHECK 3327 static int __init max_swapfiles_check(void) 3328 { 3329 MAX_SWAPFILES_CHECK(); 3330 return 0; 3331 } 3332 late_initcall(max_swapfiles_check); 3333 #endif 3334 3335 static struct swap_info_struct *alloc_swap_info(void) 3336 { 3337 struct swap_info_struct *p; 3338 struct swap_info_struct *defer = NULL; 3339 unsigned int type; 3340 3341 p = kvzalloc_obj(struct swap_info_struct); 3342 if (!p) 3343 return ERR_PTR(-ENOMEM); 3344 3345 if (percpu_ref_init(&p->users, swap_users_ref_free, 3346 PERCPU_REF_INIT_DEAD, GFP_KERNEL)) { 3347 kvfree(p); 3348 return ERR_PTR(-ENOMEM); 3349 } 3350 3351 spin_lock(&swap_lock); 3352 for (type = 0; type < nr_swapfiles; type++) { 3353 if (!(swap_info[type]->flags & SWP_USED)) 3354 break; 3355 } 3356 if (type >= MAX_SWAPFILES) { 3357 spin_unlock(&swap_lock); 3358 percpu_ref_exit(&p->users); 3359 kvfree(p); 3360 return ERR_PTR(-EPERM); 3361 } 3362 if (type >= nr_swapfiles) { 3363 p->type = type; 3364 /* 3365 * Publish the swap_info_struct after initializing it. 3366 * Note that kvzalloc() above zeroes all its fields. 3367 */ 3368 smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */ 3369 nr_swapfiles++; 3370 } else { 3371 defer = p; 3372 p = swap_info[type]; 3373 /* 3374 * Do not memset this entry: a racing procfs swap_next() 3375 * would be relying on p->type to remain valid. 3376 */ 3377 } 3378 p->swap_extent_root = RB_ROOT; 3379 plist_node_init(&p->list, 0); 3380 plist_node_init(&p->avail_list, 0); 3381 p->flags = SWP_USED; 3382 spin_unlock(&swap_lock); 3383 if (defer) { 3384 percpu_ref_exit(&defer->users); 3385 kvfree(defer); 3386 } 3387 spin_lock_init(&p->lock); 3388 atomic_long_set(&p->inuse_pages, SWAP_USAGE_OFFLIST_BIT); 3389 init_completion(&p->comp); 3390 3391 return p; 3392 } 3393 3394 static int claim_swapfile(struct swap_info_struct *si, struct inode *inode) 3395 { 3396 if (S_ISBLK(inode->i_mode)) { 3397 si->bdev = I_BDEV(inode); 3398 /* 3399 * Zoned block devices contain zones that have a sequential 3400 * write only restriction. Hence zoned block devices are not 3401 * suitable for swapping. Disallow them here. 3402 */ 3403 if (bdev_is_zoned(si->bdev)) 3404 return -EINVAL; 3405 si->flags |= SWP_BLKDEV; 3406 } else if (S_ISREG(inode->i_mode)) { 3407 si->bdev = inode->i_sb->s_bdev; 3408 } 3409 3410 return 0; 3411 } 3412 3413 3414 /* 3415 * Find out how many pages are allowed for a single swap device. There 3416 * are two limiting factors: 3417 * 1) the number of bits for the swap offset in the swp_entry_t type, and 3418 * 2) the number of bits in the swap pte, as defined by the different 3419 * architectures. 3420 * 3421 * In order to find the largest possible bit mask, a swap entry with 3422 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte, 3423 * decoded to a swp_entry_t again, and finally the swap offset is 3424 * extracted. 3425 * 3426 * This will mask all the bits from the initial ~0UL mask that can't 3427 * be encoded in either the swp_entry_t or the architecture definition 3428 * of a swap pte. 3429 */ 3430 unsigned long generic_max_swapfile_size(void) 3431 { 3432 swp_entry_t entry = swp_entry(0, ~0UL); 3433 const pte_t pte = softleaf_to_pte(entry); 3434 3435 /* 3436 * Since the PTE can be an invalid softleaf entry (e.g. the none PTE), 3437 * we need to do this manually. 3438 */ 3439 entry = __pte_to_swp_entry(pte); 3440 entry = swp_entry(__swp_type(entry), __swp_offset(entry)); 3441 3442 return swp_offset(entry) + 1; 3443 } 3444 3445 /* Can be overridden by an architecture for additional checks. */ 3446 __weak unsigned long arch_max_swapfile_size(void) 3447 { 3448 return generic_max_swapfile_size(); 3449 } 3450 3451 static unsigned long read_swap_header(struct swap_info_struct *si, 3452 union swap_header *swap_header, 3453 struct inode *inode) 3454 { 3455 int i; 3456 unsigned long maxpages; 3457 unsigned long swapfilepages; 3458 unsigned long last_page; 3459 3460 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) { 3461 pr_err("Unable to find swap-space signature\n"); 3462 return 0; 3463 } 3464 3465 /* swap partition endianness hack... */ 3466 if (swab32(swap_header->info.version) == 1) { 3467 swab32s(&swap_header->info.version); 3468 swab32s(&swap_header->info.last_page); 3469 swab32s(&swap_header->info.nr_badpages); 3470 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES) 3471 return 0; 3472 for (i = 0; i < swap_header->info.nr_badpages; i++) 3473 swab32s(&swap_header->info.badpages[i]); 3474 } 3475 /* Check the swap header's sub-version */ 3476 if (swap_header->info.version != 1) { 3477 pr_warn("Unable to handle swap header version %d\n", 3478 swap_header->info.version); 3479 return 0; 3480 } 3481 3482 maxpages = swapfile_maximum_size; 3483 last_page = swap_header->info.last_page; 3484 if (!last_page) { 3485 pr_warn("Empty swap-file\n"); 3486 return 0; 3487 } 3488 if (last_page > maxpages) { 3489 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n", 3490 K(maxpages), K(last_page)); 3491 } 3492 if (maxpages > last_page) { 3493 maxpages = last_page + 1; 3494 /* p->max is an unsigned int: don't overflow it */ 3495 if ((unsigned int)maxpages == 0) 3496 maxpages = UINT_MAX; 3497 } 3498 3499 if (!maxpages) 3500 return 0; 3501 swapfilepages = i_size_read(inode) >> PAGE_SHIFT; 3502 if (swapfilepages && maxpages > swapfilepages) { 3503 pr_warn("Swap area shorter than signature indicates\n"); 3504 return 0; 3505 } 3506 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode)) 3507 return 0; 3508 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES) 3509 return 0; 3510 3511 return maxpages; 3512 } 3513 3514 static int setup_swap_clusters_info(struct swap_info_struct *si, 3515 union swap_header *swap_header, 3516 unsigned long maxpages) 3517 { 3518 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER); 3519 struct swap_cluster_info *cluster_info; 3520 int err = -ENOMEM; 3521 unsigned long i; 3522 3523 cluster_info = kvzalloc_objs(*cluster_info, nr_clusters); 3524 if (!cluster_info) 3525 goto err; 3526 3527 for (i = 0; i < nr_clusters; i++) 3528 spin_lock_init(&cluster_info[i].lock); 3529 3530 if (!(si->flags & SWP_SOLIDSTATE)) { 3531 si->global_cluster = kmalloc_obj(*si->global_cluster); 3532 if (!si->global_cluster) 3533 goto err; 3534 for (i = 0; i < SWAP_NR_ORDERS; i++) 3535 si->global_cluster->next[i] = SWAP_ENTRY_INVALID; 3536 spin_lock_init(&si->global_cluster_lock); 3537 } 3538 3539 /* 3540 * Mark unusable pages (header page, bad pages, and the EOF part of 3541 * the last cluster) as unavailable. The clusters aren't marked free 3542 * yet, so no list operations are involved yet. 3543 */ 3544 err = swap_cluster_setup_bad_slot(si, cluster_info, 0, false); 3545 if (err) 3546 goto err; 3547 for (i = 0; i < swap_header->info.nr_badpages; i++) { 3548 unsigned int page_nr = swap_header->info.badpages[i]; 3549 3550 if (!page_nr || page_nr > swap_header->info.last_page) { 3551 pr_warn("Bad slot offset is out of border: %d (last_page: %d)\n", 3552 page_nr, swap_header->info.last_page); 3553 err = -EINVAL; 3554 goto err; 3555 } 3556 err = swap_cluster_setup_bad_slot(si, cluster_info, page_nr, false); 3557 if (err) 3558 goto err; 3559 } 3560 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++) { 3561 err = swap_cluster_setup_bad_slot(si, cluster_info, i, true); 3562 if (err) 3563 goto err; 3564 } 3565 3566 INIT_LIST_HEAD(&si->free_clusters); 3567 INIT_LIST_HEAD(&si->full_clusters); 3568 INIT_LIST_HEAD(&si->discard_clusters); 3569 3570 for (i = 0; i < SWAP_NR_ORDERS; i++) { 3571 INIT_LIST_HEAD(&si->nonfull_clusters[i]); 3572 INIT_LIST_HEAD(&si->frag_clusters[i]); 3573 } 3574 3575 for (i = 0; i < nr_clusters; i++) { 3576 struct swap_cluster_info *ci = &cluster_info[i]; 3577 3578 if (ci->count) { 3579 ci->flags = CLUSTER_FLAG_NONFULL; 3580 list_add_tail(&ci->list, &si->nonfull_clusters[0]); 3581 } else { 3582 ci->flags = CLUSTER_FLAG_FREE; 3583 list_add_tail(&ci->list, &si->free_clusters); 3584 } 3585 } 3586 3587 si->cluster_info = cluster_info; 3588 return 0; 3589 err: 3590 free_swap_cluster_info(cluster_info, maxpages); 3591 return err; 3592 } 3593 3594 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags) 3595 { 3596 struct swap_info_struct *si; 3597 struct file *swap_file = NULL; 3598 struct address_space *mapping; 3599 struct dentry *dentry; 3600 int prio; 3601 int error; 3602 union swap_header *swap_header; 3603 int nr_extents; 3604 sector_t span; 3605 unsigned long maxpages; 3606 struct folio *folio = NULL; 3607 struct inode *inode = NULL; 3608 bool inced_nr_rotate_swap = false; 3609 3610 if (swap_flags & ~SWAP_FLAGS_VALID) 3611 return -EINVAL; 3612 3613 if (!capable(CAP_SYS_ADMIN)) 3614 return -EPERM; 3615 3616 /* 3617 * Allocate or reuse existing !SWP_USED swap_info. The returned 3618 * si will stay in a dying status, so nothing will access its content 3619 * until enable_swap_info resurrects its percpu ref and expose it. 3620 */ 3621 si = alloc_swap_info(); 3622 if (IS_ERR(si)) 3623 return PTR_ERR(si); 3624 3625 INIT_WORK(&si->discard_work, swap_discard_work); 3626 INIT_WORK(&si->reclaim_work, swap_reclaim_work); 3627 3628 CLASS(filename, name)(specialfile); 3629 swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0); 3630 if (IS_ERR(swap_file)) { 3631 error = PTR_ERR(swap_file); 3632 swap_file = NULL; 3633 goto bad_swap; 3634 } 3635 3636 mapping = swap_file->f_mapping; 3637 dentry = swap_file->f_path.dentry; 3638 inode = mapping->host; 3639 3640 error = claim_swapfile(si, inode); 3641 if (unlikely(error)) 3642 goto bad_swap; 3643 3644 inode_lock(inode); 3645 if (d_unlinked(dentry) || cant_mount(dentry)) { 3646 error = -ENOENT; 3647 goto bad_swap_unlock_inode; 3648 } 3649 if (IS_SWAPFILE(inode)) { 3650 error = -EBUSY; 3651 goto bad_swap_unlock_inode; 3652 } 3653 3654 /* 3655 * The swap subsystem needs a major overhaul to support this. 3656 * It doesn't work yet so just disable it for now. 3657 */ 3658 if (mapping_min_folio_order(mapping) > 0) { 3659 error = -EINVAL; 3660 goto bad_swap_unlock_inode; 3661 } 3662 3663 /* 3664 * Read the swap header. 3665 */ 3666 if (!mapping->a_ops->read_folio) { 3667 error = -EINVAL; 3668 goto bad_swap_unlock_inode; 3669 } 3670 folio = read_mapping_folio(mapping, 0, swap_file); 3671 if (IS_ERR(folio)) { 3672 error = PTR_ERR(folio); 3673 goto bad_swap_unlock_inode; 3674 } 3675 swap_header = kmap_local_folio(folio, 0); 3676 3677 maxpages = read_swap_header(si, swap_header, inode); 3678 if (unlikely(!maxpages)) { 3679 error = -EINVAL; 3680 goto bad_swap_unlock_inode; 3681 } 3682 3683 si->max = maxpages; 3684 si->pages = maxpages - 1; 3685 nr_extents = setup_swap_extents(si, swap_file, &span); 3686 if (nr_extents < 0) { 3687 error = nr_extents; 3688 goto bad_swap_unlock_inode; 3689 } 3690 if (si->pages != si->max - 1) { 3691 pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max); 3692 error = -EINVAL; 3693 goto bad_swap_unlock_inode; 3694 } 3695 3696 maxpages = si->max; 3697 3698 /* Set up the swap cluster info */ 3699 error = setup_swap_clusters_info(si, swap_header, maxpages); 3700 if (error) 3701 goto bad_swap_unlock_inode; 3702 3703 if (si->bdev && bdev_stable_writes(si->bdev)) 3704 si->flags |= SWP_STABLE_WRITES; 3705 3706 if (si->bdev && bdev_synchronous(si->bdev)) 3707 si->flags |= SWP_SYNCHRONOUS_IO; 3708 3709 if (si->bdev && !bdev_rot(si->bdev)) { 3710 si->flags |= SWP_SOLIDSTATE; 3711 } else { 3712 atomic_inc(&nr_rotate_swap); 3713 inced_nr_rotate_swap = true; 3714 } 3715 3716 if ((swap_flags & SWAP_FLAG_DISCARD) && 3717 si->bdev && bdev_max_discard_sectors(si->bdev)) { 3718 /* 3719 * When discard is enabled for swap with no particular 3720 * policy flagged, we set all swap discard flags here in 3721 * order to sustain backward compatibility with older 3722 * swapon(8) releases. 3723 */ 3724 si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD | 3725 SWP_PAGE_DISCARD); 3726 3727 /* 3728 * By flagging sys_swapon, a sysadmin can tell us to 3729 * either do single-time area discards only, or to just 3730 * perform discards for released swap page-clusters. 3731 * Now it's time to adjust the p->flags accordingly. 3732 */ 3733 if (swap_flags & SWAP_FLAG_DISCARD_ONCE) 3734 si->flags &= ~SWP_PAGE_DISCARD; 3735 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES) 3736 si->flags &= ~SWP_AREA_DISCARD; 3737 3738 /* issue a swapon-time discard if it's still required */ 3739 if (si->flags & SWP_AREA_DISCARD) { 3740 int err = discard_swap(si); 3741 if (unlikely(err)) 3742 pr_err("swapon: discard_swap(%p): %d\n", 3743 si, err); 3744 } 3745 } 3746 3747 error = zswap_swapon(si->type, maxpages); 3748 if (error) 3749 goto bad_swap_unlock_inode; 3750 3751 /* 3752 * Flush any pending IO and dirty mappings before we start using this 3753 * swap device. 3754 */ 3755 inode->i_flags |= S_SWAPFILE; 3756 error = inode_drain_writes(inode); 3757 if (error) { 3758 inode->i_flags &= ~S_SWAPFILE; 3759 goto free_swap_zswap; 3760 } 3761 3762 mutex_lock(&swapon_mutex); 3763 prio = DEF_SWAP_PRIO; 3764 if (swap_flags & SWAP_FLAG_PREFER) 3765 prio = swap_flags & SWAP_FLAG_PRIO_MASK; 3766 3767 /* 3768 * The plist prio is negated because plist ordering is 3769 * low-to-high, while swap ordering is high-to-low 3770 */ 3771 si->prio = prio; 3772 si->list.prio = -si->prio; 3773 si->avail_list.prio = -si->prio; 3774 si->swap_file = swap_file; 3775 3776 /* Sets SWP_WRITEOK, resurrect the percpu ref, expose the swap device */ 3777 enable_swap_info(si); 3778 3779 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n", 3780 K(si->pages), name->name, si->prio, nr_extents, 3781 K((unsigned long long)span), 3782 (si->flags & SWP_SOLIDSTATE) ? "SS" : "", 3783 (si->flags & SWP_DISCARDABLE) ? "D" : "", 3784 (si->flags & SWP_AREA_DISCARD) ? "s" : "", 3785 (si->flags & SWP_PAGE_DISCARD) ? "c" : ""); 3786 3787 mutex_unlock(&swapon_mutex); 3788 atomic_inc(&proc_poll_event); 3789 wake_up_interruptible(&proc_poll_wait); 3790 3791 error = 0; 3792 goto out; 3793 free_swap_zswap: 3794 zswap_swapoff(si->type); 3795 bad_swap_unlock_inode: 3796 inode_unlock(inode); 3797 bad_swap: 3798 kfree(si->global_cluster); 3799 si->global_cluster = NULL; 3800 inode = NULL; 3801 destroy_swap_extents(si, swap_file); 3802 free_swap_cluster_info(si->cluster_info, si->max); 3803 si->cluster_info = NULL; 3804 /* 3805 * Clear the SWP_USED flag after all resources are freed so 3806 * alloc_swap_info can reuse this si safely. 3807 */ 3808 spin_lock(&swap_lock); 3809 si->flags = 0; 3810 spin_unlock(&swap_lock); 3811 if (inced_nr_rotate_swap) 3812 atomic_dec(&nr_rotate_swap); 3813 if (swap_file) 3814 filp_close(swap_file, NULL); 3815 out: 3816 if (!IS_ERR_OR_NULL(folio)) 3817 folio_release_kmap(folio, swap_header); 3818 if (inode) 3819 inode_unlock(inode); 3820 return error; 3821 } 3822 3823 void si_swapinfo(struct sysinfo *val) 3824 { 3825 unsigned int type; 3826 unsigned long nr_to_be_unused = 0; 3827 3828 spin_lock(&swap_lock); 3829 for (type = 0; type < nr_swapfiles; type++) { 3830 struct swap_info_struct *si = swap_info[type]; 3831 3832 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK)) 3833 nr_to_be_unused += swap_usage_in_pages(si); 3834 } 3835 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused; 3836 val->totalswap = total_swap_pages + nr_to_be_unused; 3837 spin_unlock(&swap_lock); 3838 } 3839 3840 /* 3841 * swap_dup_entry_direct() - Increase reference count of a swap entry by one. 3842 * @entry: first swap entry from which we want to increase the refcount. 3843 * 3844 * Returns 0 for success, or -ENOMEM if the extend table is required 3845 * but could not be atomically allocated. Returns -EINVAL if the swap 3846 * entry is invalid, which might occur if a page table entry has got 3847 * corrupted. 3848 * 3849 * Context: Caller must ensure there is no race condition on the reference 3850 * owner. e.g., locking the PTL of a PTE containing the entry being increased. 3851 * Also the swap entry must have a count >= 1. Otherwise folio_dup_swap should 3852 * be used. 3853 */ 3854 int swap_dup_entry_direct(swp_entry_t entry) 3855 { 3856 struct swap_info_struct *si; 3857 3858 si = swap_entry_to_info(entry); 3859 if (WARN_ON_ONCE(!si)) { 3860 pr_err("%s%08lx\n", Bad_file, entry.val); 3861 return -EINVAL; 3862 } 3863 3864 /* 3865 * The caller must be increasing the swap count from a direct 3866 * reference of the swap slot (e.g. a swap entry in page table). 3867 * So the swap count must be >= 1. 3868 */ 3869 VM_WARN_ON_ONCE(!swap_entry_swapped(si, entry)); 3870 3871 return swap_dup_entries_cluster(si, swp_offset(entry), 1); 3872 } 3873 3874 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP) 3875 static bool __has_usable_swap(void) 3876 { 3877 return !plist_head_empty(&swap_active_head); 3878 } 3879 3880 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp) 3881 { 3882 struct swap_info_struct *si; 3883 3884 if (!(gfp & __GFP_IO)) 3885 return; 3886 3887 if (!__has_usable_swap()) 3888 return; 3889 3890 if (!blk_cgroup_congested()) 3891 return; 3892 3893 /* 3894 * We've already scheduled a throttle, avoid taking the global swap 3895 * lock. 3896 */ 3897 if (current->throttle_disk) 3898 return; 3899 3900 spin_lock(&swap_avail_lock); 3901 plist_for_each_entry(si, &swap_avail_head, avail_list) { 3902 if (si->bdev) { 3903 blkcg_schedule_throttle(si->bdev->bd_disk, true); 3904 break; 3905 } 3906 } 3907 spin_unlock(&swap_avail_lock); 3908 } 3909 #endif 3910 3911 static int __init swapfile_init(void) 3912 { 3913 swapfile_maximum_size = arch_max_swapfile_size(); 3914 3915 /* 3916 * Once a cluster is freed, it's swap table content is read 3917 * only, and all swap cache readers (swap_cache_*) verifies 3918 * the content before use. So it's safe to use RCU slab here. 3919 */ 3920 if (!SWP_TABLE_USE_PAGE) 3921 swap_table_cachep = kmem_cache_create("swap_table", 3922 sizeof(struct swap_table), 3923 0, SLAB_PANIC | SLAB_TYPESAFE_BY_RCU, NULL); 3924 3925 #ifdef CONFIG_MIGRATION 3926 if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS)) 3927 swap_migration_ad_supported = true; 3928 #endif /* CONFIG_MIGRATION */ 3929 3930 return 0; 3931 } 3932 subsys_initcall(swapfile_init); 3933