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