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