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