1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
6 * Swap reorganised 29.12.95, Stephen Tweedie
9 #include <linux/blkdev.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>
47 #include <asm/tlbflush.h>
48 #include <linux/swapops.h>
49 #include <linux/swap_cgroup.h>
53 static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
55 static void free_swap_count_continuations(struct swap_info_struct *);
57 static DEFINE_SPINLOCK(swap_lock);
58 static unsigned int nr_swapfiles;
59 atomic_long_t nr_swap_pages;
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.
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 */
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 ";
80 * all active swap_info_structs
81 * protected with swap_lock, and ordered by priority.
83 static PLIST_HEAD(swap_active_head);
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.
97 static struct plist_head *swap_avail_heads;
98 static DEFINE_SPINLOCK(swap_avail_lock);
100 static struct swap_info_struct *swap_info[MAX_SWAPFILES];
102 static DEFINE_MUTEX(swapon_mutex);
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);
108 atomic_t nr_rotate_swap = ATOMIC_INIT(0);
110 static struct swap_info_struct *swap_type_to_swap_info(int type)
112 if (type >= MAX_SWAPFILES)
115 return READ_ONCE(swap_info[type]); /* rcu_dereference() */
118 static inline unsigned char swap_count(unsigned char ent)
120 return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */
123 /* Reclaim the swap entry anyway if possible */
124 #define TTRS_ANYWAY 0x1
126 * Reclaim the swap entry if there are no more mappings of the
129 #define TTRS_UNMAPPED 0x2
130 /* Reclaim the swap entry if swap is getting full*/
131 #define TTRS_FULL 0x4
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.
138 static int __try_to_reclaim_swap(struct swap_info_struct *si,
139 unsigned long offset, unsigned long flags)
141 swp_entry_t entry = swp_entry(si->type, offset);
145 folio = filemap_get_folio(swap_address_space(entry), offset);
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.
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);
162 ret = ret ? folio_nr_pages(folio) : -folio_nr_pages(folio);
167 static inline struct swap_extent *first_se(struct swap_info_struct *sis)
169 struct rb_node *rb = rb_first(&sis->swap_extent_root);
170 return rb_entry(rb, struct swap_extent, rb_node);
173 static inline struct swap_extent *next_se(struct swap_extent *se)
175 struct rb_node *rb = rb_next(&se->rb_node);
176 return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
180 * swapon tell device that all the old swap contents can be discarded,
181 * to allow the swap device to optimize its wear-levelling.
183 static int discard_swap(struct swap_info_struct *si)
185 struct swap_extent *se;
186 sector_t start_block;
190 /* Do not discard the swap header page! */
192 start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
193 nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
195 err = blkdev_issue_discard(si->bdev, start_block,
196 nr_blocks, GFP_KERNEL);
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);
206 err = blkdev_issue_discard(si->bdev, start_block,
207 nr_blocks, GFP_KERNEL);
213 return err; /* That will often be -EOPNOTSUPP */
216 static struct swap_extent *
217 offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
219 struct swap_extent *se;
222 rb = sis->swap_extent_root.rb_node;
224 se = rb_entry(rb, struct swap_extent, rb_node);
225 if (offset < se->start_page)
227 else if (offset >= se->start_page + se->nr_pages)
232 /* It *must* be present */
236 sector_t swap_folio_sector(struct folio *folio)
238 struct swap_info_struct *sis = swp_swap_info(folio->swap);
239 struct swap_extent *se;
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);
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.
253 static void discard_swap_cluster(struct swap_info_struct *si,
254 pgoff_t start_page, pgoff_t nr_pages)
256 struct swap_extent *se = offset_to_swap_extent(si, start_page);
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;
263 if (nr_blocks > nr_pages)
264 nr_blocks = nr_pages;
265 start_page += nr_blocks;
266 nr_pages -= nr_blocks;
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))
278 #ifdef CONFIG_THP_SWAP
279 #define SWAPFILE_CLUSTER HPAGE_PMD_NR
281 #define swap_entry_order(order) (order)
283 #define SWAPFILE_CLUSTER 256
286 * Define swap_entry_order() as constant to let compiler to optimize
287 * out some code if !CONFIG_THP_SWAP
289 #define swap_entry_order(order) 0
291 #define LATENCY_LIMIT 256
293 static inline void cluster_set_flag(struct swap_cluster_info *info,
299 static inline unsigned int cluster_count(struct swap_cluster_info *info)
304 static inline void cluster_set_count(struct swap_cluster_info *info,
310 static inline void cluster_set_count_flag(struct swap_cluster_info *info,
311 unsigned int c, unsigned int f)
317 static inline unsigned int cluster_next(struct swap_cluster_info *info)
322 static inline void cluster_set_next(struct swap_cluster_info *info,
328 static inline void cluster_set_next_flag(struct swap_cluster_info *info,
329 unsigned int n, unsigned int f)
335 static inline bool cluster_is_free(struct swap_cluster_info *info)
337 return info->flags & CLUSTER_FLAG_FREE;
340 static inline bool cluster_is_null(struct swap_cluster_info *info)
342 return info->flags & CLUSTER_FLAG_NEXT_NULL;
345 static inline void cluster_set_null(struct swap_cluster_info *info)
347 info->flags = CLUSTER_FLAG_NEXT_NULL;
351 static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
352 unsigned long offset)
354 struct swap_cluster_info *ci;
356 ci = si->cluster_info;
358 ci += offset / SWAPFILE_CLUSTER;
359 spin_lock(&ci->lock);
364 static inline void unlock_cluster(struct swap_cluster_info *ci)
367 spin_unlock(&ci->lock);
371 * Determine the locking method in use for this device. Return
372 * swap_cluster_info if SSD-style cluster-based locking is in place.
374 static inline struct swap_cluster_info *lock_cluster_or_swap_info(
375 struct swap_info_struct *si, unsigned long offset)
377 struct swap_cluster_info *ci;
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: */
383 spin_lock(&si->lock);
388 static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
389 struct swap_cluster_info *ci)
394 spin_unlock(&si->lock);
397 static inline bool cluster_list_empty(struct swap_cluster_list *list)
399 return cluster_is_null(&list->head);
402 static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
404 return cluster_next(&list->head);
407 static void cluster_list_init(struct swap_cluster_list *list)
409 cluster_set_null(&list->head);
410 cluster_set_null(&list->tail);
413 static void cluster_list_add_tail(struct swap_cluster_list *list,
414 struct swap_cluster_info *ci,
417 if (cluster_list_empty(list)) {
418 cluster_set_next_flag(&list->head, idx, 0);
419 cluster_set_next_flag(&list->tail, idx, 0);
421 struct swap_cluster_info *ci_tail;
422 unsigned int tail = cluster_next(&list->tail);
425 * Nested cluster lock, but both cluster locks are
426 * only acquired when we held swap_info_struct->lock
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);
436 static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
437 struct swap_cluster_info *ci)
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);
446 cluster_set_next_flag(&list->head,
447 cluster_next(&ci[idx]), 0);
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,
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
462 memset(si->swap_map + idx * SWAPFILE_CLUSTER,
463 SWAP_MAP_BAD, SWAPFILE_CLUSTER);
465 cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
467 schedule_work(&si->discard_work);
470 static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
472 struct swap_cluster_info *ci = si->cluster_info;
474 cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
475 cluster_list_add_tail(&si->free_clusters, ci, idx);
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.
482 static void swap_do_scheduled_discard(struct swap_info_struct *si)
484 struct swap_cluster_info *info, *ci;
487 info = si->cluster_info;
489 while (!cluster_list_empty(&si->discard_clusters)) {
490 idx = cluster_list_del_first(&si->discard_clusters, info);
491 spin_unlock(&si->lock);
493 discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
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);
505 static void swap_discard_work(struct work_struct *work)
507 struct swap_info_struct *si;
509 si = container_of(work, struct swap_info_struct, discard_work);
511 spin_lock(&si->lock);
512 swap_do_scheduled_discard(si);
513 spin_unlock(&si->lock);
516 static void swap_users_ref_free(struct percpu_ref *ref)
518 struct swap_info_struct *si;
520 si = container_of(ref, struct swap_info_struct, users);
524 static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
526 struct swap_cluster_info *ci = si->cluster_info;
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);
533 static void free_cluster(struct swap_info_struct *si, unsigned long idx)
535 struct swap_cluster_info *ci = si->cluster_info + idx;
537 VM_BUG_ON(cluster_count(ci) != 0);
539 * If the swap is discardable, prepare discard the cluster
540 * instead of free it immediately. The cluster will be freed
543 if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
544 (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
545 swap_cluster_schedule_discard(si, idx);
549 __free_cluster(si, idx);
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
557 static void add_cluster_info_page(struct swap_info_struct *p,
558 struct swap_cluster_info *cluster_info, unsigned long page_nr,
561 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
565 if (cluster_is_free(&cluster_info[idx]))
566 alloc_cluster(p, idx);
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);
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.
577 static void inc_cluster_info_page(struct swap_info_struct *p,
578 struct swap_cluster_info *cluster_info, unsigned long page_nr)
580 add_cluster_info_page(p, cluster_info, page_nr, 1);
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.
588 static void dec_cluster_info_page(struct swap_info_struct *p,
589 struct swap_cluster_info *cluster_info, unsigned long page_nr)
591 unsigned long idx = page_nr / SWAPFILE_CLUSTER;
596 VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
597 cluster_set_count(&cluster_info[idx],
598 cluster_count(&cluster_info[idx]) - 1);
600 if (cluster_count(&cluster_info[idx]) == 0)
601 free_cluster(p, idx);
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.
609 scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
610 unsigned long offset, int order)
612 struct percpu_cluster *percpu_cluster;
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]);
623 percpu_cluster = this_cpu_ptr(si->percpu_cluster);
624 percpu_cluster->next[order] = SWAP_NEXT_INVALID;
628 static inline bool swap_range_empty(char *swap_map, unsigned int start,
629 unsigned int nr_pages)
633 for (i = 0; i < nr_pages; i++) {
634 if (swap_map[start + i])
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
646 static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
647 unsigned long *offset, unsigned long *scan_base, int order)
649 unsigned int nr_pages = 1 << order;
650 struct percpu_cluster *cluster;
651 struct swap_cluster_info *ci;
652 unsigned int tmp, max;
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) *
661 } else if (!cluster_list_empty(&si->discard_clusters)) {
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
667 swap_do_scheduled_discard(si);
668 *scan_base = this_cpu_read(*si->cluster_next_cpu);
669 *offset = *scan_base;
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
680 max = min_t(unsigned long, si->max, ALIGN(tmp + 1, SWAPFILE_CLUSTER));
682 ci = lock_cluster(si, tmp);
684 if (swap_range_empty(si->swap_map, tmp, nr_pages))
691 cluster->next[order] = SWAP_NEXT_INVALID;
697 cluster->next[order] = tmp < max ? tmp : SWAP_NEXT_INVALID;
701 static void __del_from_avail_list(struct swap_info_struct *p)
705 assert_spin_locked(&p->lock);
707 plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
710 static void del_from_avail_list(struct swap_info_struct *p)
712 spin_lock(&swap_avail_lock);
713 __del_from_avail_list(p);
714 spin_unlock(&swap_avail_lock);
717 static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
718 unsigned int nr_entries)
720 unsigned int end = offset + nr_entries - 1;
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;
730 del_from_avail_list(si);
734 static void add_to_avail_list(struct swap_info_struct *p)
738 spin_lock(&swap_avail_lock);
740 plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
741 spin_unlock(&swap_avail_lock);
744 static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
745 unsigned int nr_entries)
747 unsigned long begin = offset;
748 unsigned long end = offset + nr_entries - 1;
749 void (*swap_slot_free_notify)(struct block_device *, unsigned long);
751 if (offset < si->lowest_bit)
752 si->lowest_bit = offset;
753 if (end > si->highest_bit) {
754 bool was_full = !si->highest_bit;
756 WRITE_ONCE(si->highest_bit, end);
757 if (was_full && (si->flags & SWP_WRITEOK))
758 add_to_avail_list(si);
760 if (si->flags & SWP_BLKDEV)
761 swap_slot_free_notify =
762 si->bdev->bd_disk->fops->swap_slot_free_notify;
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);
771 clear_shadow_from_swap_cache(si->type, begin, end);
774 * Make sure that try_to_unuse() observes si->inuse_pages reaching 0
775 * only after the above cleanups are done.
778 atomic_long_add(nr_entries, &nr_swap_pages);
779 WRITE_ONCE(si->inuse_pages, si->inuse_pages - nr_entries);
782 static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
786 if (!(si->flags & SWP_SOLIDSTATE)) {
787 si->cluster_next = next;
791 prev = this_cpu_read(*si->cluster_next_cpu);
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.
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)
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);
806 this_cpu_write(*si->cluster_next_cpu, next);
809 static bool swap_offset_available_and_locked(struct swap_info_struct *si,
810 unsigned long offset)
812 if (data_race(!si->swap_map[offset])) {
813 spin_lock(&si->lock);
817 if (vm_swap_full() && READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
818 spin_lock(&si->lock);
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)
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;
836 bool scanned_many = false;
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
851 * Should not even be attempting large allocations when huge
852 * page swap is disabled. Warn and fail the allocation.
854 if (!IS_ENABLED(CONFIG_THP_SWAP) ||
855 nr_pages > SWAPFILE_CLUSTER) {
861 * Swapfile is not block device or not using clusters so unable
862 * to allocate large entries.
864 if (!(si->flags & SWP_BLKDEV) || !si->cluster_info)
868 si->flags += SWP_SCANNING;
870 * Use percpu scan base for SSD to reduce lock contention on
871 * cluster and swap cache. For HDD, sequential access is more
874 if (si->flags & SWP_SOLIDSTATE)
875 scan_base = this_cpu_read(*si->cluster_next_cpu);
877 scan_base = si->cluster_next;
881 if (si->cluster_info) {
882 if (!scan_swap_map_try_ssd_cluster(si, &offset, &scan_base, order)) {
887 } else if (unlikely(!si->cluster_nr--)) {
888 if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
889 si->cluster_nr = SWAPFILE_CLUSTER - 1;
893 spin_unlock(&si->lock);
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.
901 scan_base = offset = si->lowest_bit;
902 last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
904 /* Locate the first empty (unaligned) cluster */
905 for (; last_in_cluster <= 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;
915 if (unlikely(--latency_ration < 0)) {
917 latency_ration = LATENCY_LIMIT;
922 spin_lock(&si->lock);
923 si->cluster_nr = SWAPFILE_CLUSTER - 1;
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 */
932 if (!scan_swap_map_try_ssd_cluster(si, &offset,
933 &scan_base, order)) {
940 if (!(si->flags & SWP_WRITEOK))
942 if (!si->highest_bit)
944 if (offset > si->highest_bit)
945 scan_base = offset = si->lowest_bit;
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) {
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)
958 goto scan; /* check next one */
961 if (si->swap_map[offset]) {
968 memset(si->swap_map + offset, usage, nr_pages);
969 add_cluster_info_page(si, si->cluster_info, offset, nr_pages);
972 swap_range_alloc(si, offset, nr_pages);
973 slots[n_ret++] = swp_entry(si->type, offset);
975 /* got enough slots or reach max slots? */
976 if ((n_ret == nr) || (offset >= si->highest_bit))
979 /* search for next available slot */
981 /* time to take a break? */
982 if (unlikely(--latency_ration < 0)) {
985 spin_unlock(&si->lock);
987 spin_lock(&si->lock);
988 latency_ration = LATENCY_LIMIT;
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))
997 } else if (si->cluster_nr && !si->swap_map[++offset]) {
998 /* non-ssd case, still more slots in cluster? */
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.
1008 if (!scanned_many) {
1009 unsigned long scan_limit;
1011 if (offset < scan_base)
1012 scan_limit = scan_base;
1014 scan_limit = si->highest_bit;
1015 for (; offset <= scan_limit && --latency_ration > 0;
1017 if (!si->swap_map[offset])
1024 set_cluster_next(si, offset + 1);
1025 si->flags -= SWP_SCANNING;
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)) {
1034 latency_ration = LATENCY_LIMIT;
1035 scanned_many = true;
1037 if (swap_offset_available_and_locked(si, offset))
1040 offset = si->lowest_bit;
1041 while (offset < scan_base) {
1042 if (unlikely(--latency_ration < 0)) {
1044 latency_ration = LATENCY_LIMIT;
1045 scanned_many = true;
1047 if (swap_offset_available_and_locked(si, offset))
1051 spin_lock(&si->lock);
1054 si->flags -= SWP_SCANNING;
1058 static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
1060 unsigned long offset = idx * SWAPFILE_CLUSTER;
1061 struct swap_cluster_info *ci;
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);
1068 swap_range_free(si, offset, SWAPFILE_CLUSTER);
1071 int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_order)
1073 int order = swap_entry_order(entry_order);
1074 unsigned long size = 1 << order;
1075 struct swap_info_struct *si, *next;
1080 spin_lock(&swap_avail_lock);
1082 avail_pgs = atomic_long_read(&nr_swap_pages) / size;
1083 if (avail_pgs <= 0) {
1084 spin_unlock(&swap_avail_lock);
1088 n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
1090 atomic_long_sub(n_goal * size, &nr_swap_pages);
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);
1105 WARN(!si->highest_bit,
1106 "swap_info %d in list but !highest_bit\n",
1108 WARN(!(si->flags & SWP_WRITEOK),
1109 "swap_info %d in list but !SWP_WRITEOK\n",
1111 __del_from_avail_list(si);
1112 spin_unlock(&si->lock);
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)
1122 spin_lock(&swap_avail_lock);
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.
1135 if (plist_node_empty(&next->avail_lists[node]))
1139 spin_unlock(&swap_avail_lock);
1143 atomic_long_add((long)(n_goal - n_ret) * size,
1149 static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
1151 struct swap_info_struct *p;
1152 unsigned long offset;
1156 p = swp_swap_info(entry);
1159 if (data_race(!(p->flags & SWP_USED)))
1161 offset = swp_offset(entry);
1162 if (offset >= p->max)
1164 if (data_race(!p->swap_map[swp_offset(entry)]))
1169 pr_err("%s: %s%08lx\n", __func__, Unused_offset, entry.val);
1172 pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
1175 pr_err("%s: %s%08lx\n", __func__, Unused_file, entry.val);
1178 pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1183 static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
1184 struct swap_info_struct *q)
1186 struct swap_info_struct *p;
1188 p = _swap_info_get(entry);
1192 spin_unlock(&q->lock);
1194 spin_lock(&p->lock);
1199 static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1200 unsigned long offset,
1201 unsigned char usage)
1203 unsigned char count;
1204 unsigned char has_cache;
1206 count = p->swap_map[offset];
1208 has_cache = count & SWAP_HAS_CACHE;
1209 count &= ~SWAP_HAS_CACHE;
1211 if (usage == SWAP_HAS_CACHE) {
1212 VM_BUG_ON(!has_cache);
1214 } else if (count == SWAP_MAP_SHMEM) {
1216 * Or we could insist on shmem.c using a special
1217 * swap_shmem_free() and free_shmem_swap_and_cache()...
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;
1225 count = SWAP_MAP_MAX;
1230 usage = count | has_cache;
1232 WRITE_ONCE(p->swap_map[offset], usage);
1234 WRITE_ONCE(p->swap_map[offset], SWAP_HAS_CACHE);
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, page
1242 * table lock is held, etc., the swap entry may become invalid because
1243 * of swapoff. Then, we need to enclose all swap related functions
1244 * with get_swap_device() and put_swap_device(), unless the swap
1245 * functions call get/put_swap_device() by themselves.
1247 * Note that when only holding the PTL, swapoff might succeed immediately
1248 * after freeing a swap entry. Therefore, immediately after
1249 * __swap_entry_free(), the swap info might become stale and should not
1250 * be touched without a prior get_swap_device().
1252 * Check whether swap entry is valid in the swap device. If so,
1253 * return pointer to swap_info_struct, and keep the swap entry valid
1254 * via preventing the swap device from being swapoff, until
1255 * put_swap_device() is called. Otherwise return NULL.
1257 * Notice that swapoff or swapoff+swapon can still happen before the
1258 * percpu_ref_tryget_live() in get_swap_device() or after the
1259 * percpu_ref_put() in put_swap_device() if there isn't any other way
1260 * to prevent swapoff. The caller must be prepared for that. For
1261 * example, the following situation is possible.
1265 * ... swapoff+swapon
1266 * __read_swap_cache_async()
1267 * swapcache_prepare()
1268 * __swap_duplicate()
1270 * // verify PTE not changed
1272 * In __swap_duplicate(), the swap_map need to be checked before
1273 * changing partly because the specified swap entry may be for another
1274 * swap device which has been swapoff. And in do_swap_page(), after
1275 * the page is read from the swap device, the PTE is verified not
1276 * changed with the page table locked to check whether the swap device
1277 * has been swapoff or swapoff+swapon.
1279 struct swap_info_struct *get_swap_device(swp_entry_t entry)
1281 struct swap_info_struct *si;
1282 unsigned long offset;
1286 si = swp_swap_info(entry);
1289 if (!percpu_ref_tryget_live(&si->users))
1292 * Guarantee the si->users are checked before accessing other
1293 * fields of swap_info_struct.
1295 * Paired with the spin_unlock() after setup_swap_info() in
1296 * enable_swap_info().
1299 offset = swp_offset(entry);
1300 if (offset >= si->max)
1305 pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1309 pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
1310 percpu_ref_put(&si->users);
1314 static unsigned char __swap_entry_free(struct swap_info_struct *p,
1317 struct swap_cluster_info *ci;
1318 unsigned long offset = swp_offset(entry);
1319 unsigned char usage;
1321 ci = lock_cluster_or_swap_info(p, offset);
1322 usage = __swap_entry_free_locked(p, offset, 1);
1323 unlock_cluster_or_swap_info(p, ci);
1325 free_swap_slot(entry);
1330 static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
1332 struct swap_cluster_info *ci;
1333 unsigned long offset = swp_offset(entry);
1334 unsigned char count;
1336 ci = lock_cluster(p, offset);
1337 count = p->swap_map[offset];
1338 VM_BUG_ON(count != SWAP_HAS_CACHE);
1339 p->swap_map[offset] = 0;
1340 dec_cluster_info_page(p, p->cluster_info, offset);
1343 mem_cgroup_uncharge_swap(entry, 1);
1344 swap_range_free(p, offset, 1);
1348 * Caller has made sure that the swap device corresponding to entry
1349 * is still around or has not been recycled.
1351 void swap_free(swp_entry_t entry)
1353 struct swap_info_struct *p;
1355 p = _swap_info_get(entry);
1357 __swap_entry_free(p, entry);
1361 * Called after dropping swapcache to decrease refcnt to swap entries.
1363 void put_swap_folio(struct folio *folio, swp_entry_t entry)
1365 unsigned long offset = swp_offset(entry);
1366 unsigned long idx = offset / SWAPFILE_CLUSTER;
1367 struct swap_cluster_info *ci;
1368 struct swap_info_struct *si;
1370 unsigned int i, free_entries = 0;
1372 int size = 1 << swap_entry_order(folio_order(folio));
1374 si = _swap_info_get(entry);
1378 ci = lock_cluster_or_swap_info(si, offset);
1379 if (size == SWAPFILE_CLUSTER) {
1380 map = si->swap_map + offset;
1381 for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1383 VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1384 if (val == SWAP_HAS_CACHE)
1387 if (free_entries == SWAPFILE_CLUSTER) {
1388 unlock_cluster_or_swap_info(si, ci);
1389 spin_lock(&si->lock);
1390 mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
1391 swap_free_cluster(si, idx);
1392 spin_unlock(&si->lock);
1396 for (i = 0; i < size; i++, entry.val++) {
1397 if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1398 unlock_cluster_or_swap_info(si, ci);
1399 free_swap_slot(entry);
1402 lock_cluster_or_swap_info(si, offset);
1405 unlock_cluster_or_swap_info(si, ci);
1408 static int swp_entry_cmp(const void *ent1, const void *ent2)
1410 const swp_entry_t *e1 = ent1, *e2 = ent2;
1412 return (int)swp_type(*e1) - (int)swp_type(*e2);
1415 void swapcache_free_entries(swp_entry_t *entries, int n)
1417 struct swap_info_struct *p, *prev;
1427 * Sort swap entries by swap device, so each lock is only taken once.
1428 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1429 * so low that it isn't necessary to optimize further.
1431 if (nr_swapfiles > 1)
1432 sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
1433 for (i = 0; i < n; ++i) {
1434 p = swap_info_get_cont(entries[i], prev);
1436 swap_entry_free(p, entries[i]);
1440 spin_unlock(&p->lock);
1443 int __swap_count(swp_entry_t entry)
1445 struct swap_info_struct *si = swp_swap_info(entry);
1446 pgoff_t offset = swp_offset(entry);
1448 return swap_count(si->swap_map[offset]);
1452 * How many references to @entry are currently swapped out?
1453 * This does not give an exact answer when swap count is continued,
1454 * but does include the high COUNT_CONTINUED flag to allow for that.
1456 int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1458 pgoff_t offset = swp_offset(entry);
1459 struct swap_cluster_info *ci;
1462 ci = lock_cluster_or_swap_info(si, offset);
1463 count = swap_count(si->swap_map[offset]);
1464 unlock_cluster_or_swap_info(si, ci);
1469 * How many references to @entry are currently swapped out?
1470 * This considers COUNT_CONTINUED so it returns exact answer.
1472 int swp_swapcount(swp_entry_t entry)
1474 int count, tmp_count, n;
1475 struct swap_info_struct *p;
1476 struct swap_cluster_info *ci;
1481 p = _swap_info_get(entry);
1485 offset = swp_offset(entry);
1487 ci = lock_cluster_or_swap_info(p, offset);
1489 count = swap_count(p->swap_map[offset]);
1490 if (!(count & COUNT_CONTINUED))
1493 count &= ~COUNT_CONTINUED;
1494 n = SWAP_MAP_MAX + 1;
1496 page = vmalloc_to_page(p->swap_map + offset);
1497 offset &= ~PAGE_MASK;
1498 VM_BUG_ON(page_private(page) != SWP_CONTINUED);
1501 page = list_next_entry(page, lru);
1502 map = kmap_local_page(page);
1503 tmp_count = map[offset];
1506 count += (tmp_count & ~COUNT_CONTINUED) * n;
1507 n *= (SWAP_CONT_MAX + 1);
1508 } while (tmp_count & COUNT_CONTINUED);
1510 unlock_cluster_or_swap_info(p, ci);
1514 static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1515 swp_entry_t entry, int order)
1517 struct swap_cluster_info *ci;
1518 unsigned char *map = si->swap_map;
1519 unsigned int nr_pages = 1 << order;
1520 unsigned long roffset = swp_offset(entry);
1521 unsigned long offset = round_down(roffset, nr_pages);
1525 ci = lock_cluster_or_swap_info(si, offset);
1526 if (!ci || nr_pages == 1) {
1527 if (swap_count(map[roffset]))
1531 for (i = 0; i < nr_pages; i++) {
1532 if (swap_count(map[offset + i])) {
1538 unlock_cluster_or_swap_info(si, ci);
1542 static bool folio_swapped(struct folio *folio)
1544 swp_entry_t entry = folio->swap;
1545 struct swap_info_struct *si = _swap_info_get(entry);
1550 if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!folio_test_large(folio)))
1551 return swap_swapcount(si, entry) != 0;
1553 return swap_page_trans_huge_swapped(si, entry, folio_order(folio));
1557 * folio_free_swap() - Free the swap space used for this folio.
1558 * @folio: The folio to remove.
1560 * If swap is getting full, or if there are no more mappings of this folio,
1561 * then call folio_free_swap to free its swap space.
1563 * Return: true if we were able to release the swap space.
1565 bool folio_free_swap(struct folio *folio)
1567 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1569 if (!folio_test_swapcache(folio))
1571 if (folio_test_writeback(folio))
1573 if (folio_swapped(folio))
1577 * Once hibernation has begun to create its image of memory,
1578 * there's a danger that one of the calls to folio_free_swap()
1579 * - most probably a call from __try_to_reclaim_swap() while
1580 * hibernation is allocating its own swap pages for the image,
1581 * but conceivably even a call from memory reclaim - will free
1582 * the swap from a folio which has already been recorded in the
1583 * image as a clean swapcache folio, and then reuse its swap for
1584 * another page of the image. On waking from hibernation, the
1585 * original folio might be freed under memory pressure, then
1586 * later read back in from swap, now with the wrong data.
1588 * Hibernation suspends storage while it is writing the image
1589 * to disk so check that here.
1591 if (pm_suspended_storage())
1594 delete_from_swap_cache(folio);
1595 folio_set_dirty(folio);
1600 * free_swap_and_cache_nr() - Release reference on range of swap entries and
1601 * reclaim their cache if no more references remain.
1602 * @entry: First entry of range.
1603 * @nr: Number of entries in range.
1605 * For each swap entry in the contiguous range, release a reference. If any swap
1606 * entries become free, try to reclaim their underlying folios, if present. The
1607 * offset range is defined by [entry.offset, entry.offset + nr).
1609 void free_swap_and_cache_nr(swp_entry_t entry, int nr)
1611 const unsigned long start_offset = swp_offset(entry);
1612 const unsigned long end_offset = start_offset + nr;
1613 unsigned int type = swp_type(entry);
1614 struct swap_info_struct *si;
1615 bool any_only_cache = false;
1616 unsigned long offset;
1617 unsigned char count;
1619 if (non_swap_entry(entry))
1622 si = get_swap_device(entry);
1626 if (WARN_ON(end_offset > si->max))
1630 * First free all entries in the range.
1632 for (offset = start_offset; offset < end_offset; offset++) {
1633 if (data_race(si->swap_map[offset])) {
1634 count = __swap_entry_free(si, swp_entry(type, offset));
1635 if (count == SWAP_HAS_CACHE)
1636 any_only_cache = true;
1643 * Short-circuit the below loop if none of the entries had their
1644 * reference drop to zero.
1646 if (!any_only_cache)
1650 * Now go back over the range trying to reclaim the swap cache. This is
1651 * more efficient for large folios because we will only try to reclaim
1652 * the swap once per folio in the common case. If we do
1653 * __swap_entry_free() and __try_to_reclaim_swap() in the same loop, the
1654 * latter will get a reference and lock the folio for every individual
1655 * page but will only succeed once the swap slot for every subpage is
1658 for (offset = start_offset; offset < end_offset; offset += nr) {
1660 if (READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
1662 * Folios are always naturally aligned in swap so
1663 * advance forward to the next boundary. Zero means no
1664 * folio was found for the swap entry, so advance by 1
1665 * in this case. Negative value means folio was found
1666 * but could not be reclaimed. Here we can still advance
1667 * to the next boundary.
1669 nr = __try_to_reclaim_swap(si, offset,
1670 TTRS_UNMAPPED | TTRS_FULL);
1675 nr = ALIGN(offset + 1, nr) - offset;
1680 put_swap_device(si);
1683 #ifdef CONFIG_HIBERNATION
1685 swp_entry_t get_swap_page_of_type(int type)
1687 struct swap_info_struct *si = swap_type_to_swap_info(type);
1688 swp_entry_t entry = {0};
1693 /* This is called for allocating swap entry, not cache */
1694 spin_lock(&si->lock);
1695 if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0))
1696 atomic_long_dec(&nr_swap_pages);
1697 spin_unlock(&si->lock);
1703 * Find the swap type that corresponds to given device (if any).
1705 * @offset - number of the PAGE_SIZE-sized block of the device, starting
1706 * from 0, in which the swap header is expected to be located.
1708 * This is needed for the suspend to disk (aka swsusp).
1710 int swap_type_of(dev_t device, sector_t offset)
1717 spin_lock(&swap_lock);
1718 for (type = 0; type < nr_swapfiles; type++) {
1719 struct swap_info_struct *sis = swap_info[type];
1721 if (!(sis->flags & SWP_WRITEOK))
1724 if (device == sis->bdev->bd_dev) {
1725 struct swap_extent *se = first_se(sis);
1727 if (se->start_block == offset) {
1728 spin_unlock(&swap_lock);
1733 spin_unlock(&swap_lock);
1737 int find_first_swap(dev_t *device)
1741 spin_lock(&swap_lock);
1742 for (type = 0; type < nr_swapfiles; type++) {
1743 struct swap_info_struct *sis = swap_info[type];
1745 if (!(sis->flags & SWP_WRITEOK))
1747 *device = sis->bdev->bd_dev;
1748 spin_unlock(&swap_lock);
1751 spin_unlock(&swap_lock);
1756 * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
1757 * corresponding to given index in swap_info (swap type).
1759 sector_t swapdev_block(int type, pgoff_t offset)
1761 struct swap_info_struct *si = swap_type_to_swap_info(type);
1762 struct swap_extent *se;
1764 if (!si || !(si->flags & SWP_WRITEOK))
1766 se = offset_to_swap_extent(si, offset);
1767 return se->start_block + (offset - se->start_page);
1771 * Return either the total number of swap pages of given type, or the number
1772 * of free pages of that type (depending on @free)
1774 * This is needed for software suspend
1776 unsigned int count_swap_pages(int type, int free)
1780 spin_lock(&swap_lock);
1781 if ((unsigned int)type < nr_swapfiles) {
1782 struct swap_info_struct *sis = swap_info[type];
1784 spin_lock(&sis->lock);
1785 if (sis->flags & SWP_WRITEOK) {
1788 n -= sis->inuse_pages;
1790 spin_unlock(&sis->lock);
1792 spin_unlock(&swap_lock);
1795 #endif /* CONFIG_HIBERNATION */
1797 static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1799 return pte_same(pte_swp_clear_flags(pte), swp_pte);
1803 * No need to decide whether this PTE shares the swap entry with others,
1804 * just let do_wp_page work it out if a write is requested later - to
1805 * force COW, vm_page_prot omits write permission from any private vma.
1807 static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1808 unsigned long addr, swp_entry_t entry, struct folio *folio)
1811 struct folio *swapcache;
1813 pte_t *pte, new_pte, old_pte;
1814 bool hwpoisoned = false;
1818 folio = ksm_might_need_to_copy(folio, vma, addr);
1819 if (unlikely(!folio))
1821 else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
1826 page = folio_file_page(folio, swp_offset(entry));
1827 if (PageHWPoison(page))
1830 pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1831 if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte),
1832 swp_entry_to_pte(entry)))) {
1837 old_pte = ptep_get(pte);
1839 if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) {
1840 swp_entry_t swp_entry;
1842 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1844 swp_entry = make_hwpoison_entry(page);
1846 swp_entry = make_poisoned_swp_entry();
1848 new_pte = swp_entry_to_pte(swp_entry);
1854 * Some architectures may have to restore extra metadata to the page
1855 * when reading from swap. This metadata may be indexed by swap entry
1856 * so this must be called before swap_free().
1858 arch_swap_restore(folio_swap(entry, folio), folio);
1860 dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1861 inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
1863 if (folio == swapcache) {
1864 rmap_t rmap_flags = RMAP_NONE;
1867 * See do_swap_page(): writeback would be problematic.
1868 * However, we do a folio_wait_writeback() just before this
1869 * call and have the folio locked.
1871 VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio);
1872 if (pte_swp_exclusive(old_pte))
1873 rmap_flags |= RMAP_EXCLUSIVE;
1875 folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags);
1876 } else { /* ksm created a completely new copy */
1877 folio_add_new_anon_rmap(folio, vma, addr);
1878 folio_add_lru_vma(folio, vma);
1880 new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
1881 if (pte_swp_soft_dirty(old_pte))
1882 new_pte = pte_mksoft_dirty(new_pte);
1883 if (pte_swp_uffd_wp(old_pte))
1884 new_pte = pte_mkuffd_wp(new_pte);
1886 set_pte_at(vma->vm_mm, addr, pte, new_pte);
1890 pte_unmap_unlock(pte, ptl);
1891 if (folio != swapcache) {
1892 folio_unlock(folio);
1898 static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
1899 unsigned long addr, unsigned long end,
1903 struct swap_info_struct *si;
1905 si = swap_info[type];
1907 struct folio *folio;
1908 unsigned long offset;
1909 unsigned char swp_count;
1915 pte = pte_offset_map(pmd, addr);
1920 ptent = ptep_get_lockless(pte);
1922 if (!is_swap_pte(ptent))
1925 entry = pte_to_swp_entry(ptent);
1926 if (swp_type(entry) != type)
1929 offset = swp_offset(entry);
1933 folio = swap_cache_get_folio(entry, vma, addr);
1936 struct vm_fault vmf = {
1939 .real_address = addr,
1943 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
1946 folio = page_folio(page);
1949 swp_count = READ_ONCE(si->swap_map[offset]);
1950 if (swp_count == 0 || swp_count == SWAP_MAP_BAD)
1956 folio_wait_writeback(folio);
1957 ret = unuse_pte(vma, pmd, addr, entry, folio);
1959 folio_unlock(folio);
1964 folio_free_swap(folio);
1965 folio_unlock(folio);
1967 } while (addr += PAGE_SIZE, addr != end);
1974 static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
1975 unsigned long addr, unsigned long end,
1982 pmd = pmd_offset(pud, addr);
1985 next = pmd_addr_end(addr, end);
1986 ret = unuse_pte_range(vma, pmd, addr, next, type);
1989 } while (pmd++, addr = next, addr != end);
1993 static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
1994 unsigned long addr, unsigned long end,
2001 pud = pud_offset(p4d, addr);
2003 next = pud_addr_end(addr, end);
2004 if (pud_none_or_clear_bad(pud))
2006 ret = unuse_pmd_range(vma, pud, addr, next, type);
2009 } while (pud++, addr = next, addr != end);
2013 static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
2014 unsigned long addr, unsigned long end,
2021 p4d = p4d_offset(pgd, addr);
2023 next = p4d_addr_end(addr, end);
2024 if (p4d_none_or_clear_bad(p4d))
2026 ret = unuse_pud_range(vma, p4d, addr, next, type);
2029 } while (p4d++, addr = next, addr != end);
2033 static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
2036 unsigned long addr, end, next;
2039 addr = vma->vm_start;
2042 pgd = pgd_offset(vma->vm_mm, addr);
2044 next = pgd_addr_end(addr, end);
2045 if (pgd_none_or_clear_bad(pgd))
2047 ret = unuse_p4d_range(vma, pgd, addr, next, type);
2050 } while (pgd++, addr = next, addr != end);
2054 static int unuse_mm(struct mm_struct *mm, unsigned int type)
2056 struct vm_area_struct *vma;
2058 VMA_ITERATOR(vmi, mm, 0);
2061 for_each_vma(vmi, vma) {
2062 if (vma->anon_vma) {
2063 ret = unuse_vma(vma, type);
2070 mmap_read_unlock(mm);
2075 * Scan swap_map from current position to next entry still in use.
2076 * Return 0 if there are no inuse entries after prev till end of
2079 static unsigned int find_next_to_unuse(struct swap_info_struct *si,
2083 unsigned char count;
2086 * No need for swap_lock here: we're just looking
2087 * for whether an entry is in use, not modifying it; false
2088 * hits are okay, and sys_swapoff() has already prevented new
2089 * allocations from this area (while holding swap_lock).
2091 for (i = prev + 1; i < si->max; i++) {
2092 count = READ_ONCE(si->swap_map[i]);
2093 if (count && swap_count(count) != SWAP_MAP_BAD)
2095 if ((i % LATENCY_LIMIT) == 0)
2105 static int try_to_unuse(unsigned int type)
2107 struct mm_struct *prev_mm;
2108 struct mm_struct *mm;
2109 struct list_head *p;
2111 struct swap_info_struct *si = swap_info[type];
2112 struct folio *folio;
2116 if (!READ_ONCE(si->inuse_pages))
2120 retval = shmem_unuse(type);
2127 spin_lock(&mmlist_lock);
2128 p = &init_mm.mmlist;
2129 while (READ_ONCE(si->inuse_pages) &&
2130 !signal_pending(current) &&
2131 (p = p->next) != &init_mm.mmlist) {
2133 mm = list_entry(p, struct mm_struct, mmlist);
2134 if (!mmget_not_zero(mm))
2136 spin_unlock(&mmlist_lock);
2139 retval = unuse_mm(mm, type);
2146 * Make sure that we aren't completely killing
2147 * interactive performance.
2150 spin_lock(&mmlist_lock);
2152 spin_unlock(&mmlist_lock);
2157 while (READ_ONCE(si->inuse_pages) &&
2158 !signal_pending(current) &&
2159 (i = find_next_to_unuse(si, i)) != 0) {
2161 entry = swp_entry(type, i);
2162 folio = filemap_get_folio(swap_address_space(entry), i);
2167 * It is conceivable that a racing task removed this folio from
2168 * swap cache just before we acquired the page lock. The folio
2169 * might even be back in swap cache on another swap area. But
2170 * that is okay, folio_free_swap() only removes stale folios.
2173 folio_wait_writeback(folio);
2174 folio_free_swap(folio);
2175 folio_unlock(folio);
2180 * Lets check again to see if there are still swap entries in the map.
2181 * If yes, we would need to do retry the unuse logic again.
2182 * Under global memory pressure, swap entries can be reinserted back
2183 * into process space after the mmlist loop above passes over them.
2185 * Limit the number of retries? No: when mmget_not_zero()
2186 * above fails, that mm is likely to be freeing swap from
2187 * exit_mmap(), which proceeds at its own independent pace;
2188 * and even shmem_writepage() could have been preempted after
2189 * folio_alloc_swap(), temporarily hiding that swap. It's easy
2190 * and robust (though cpu-intensive) just to keep retrying.
2192 if (READ_ONCE(si->inuse_pages)) {
2193 if (!signal_pending(current))
2200 * Make sure that further cleanups after try_to_unuse() returns happen
2201 * after swap_range_free() reduces si->inuse_pages to 0.
2208 * After a successful try_to_unuse, if no swap is now in use, we know
2209 * we can empty the mmlist. swap_lock must be held on entry and exit.
2210 * Note that mmlist_lock nests inside swap_lock, and an mm must be
2211 * added to the mmlist just after page_duplicate - before would be racy.
2213 static void drain_mmlist(void)
2215 struct list_head *p, *next;
2218 for (type = 0; type < nr_swapfiles; type++)
2219 if (swap_info[type]->inuse_pages)
2221 spin_lock(&mmlist_lock);
2222 list_for_each_safe(p, next, &init_mm.mmlist)
2224 spin_unlock(&mmlist_lock);
2228 * Free all of a swapdev's extent information
2230 static void destroy_swap_extents(struct swap_info_struct *sis)
2232 while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
2233 struct rb_node *rb = sis->swap_extent_root.rb_node;
2234 struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
2236 rb_erase(rb, &sis->swap_extent_root);
2240 if (sis->flags & SWP_ACTIVATED) {
2241 struct file *swap_file = sis->swap_file;
2242 struct address_space *mapping = swap_file->f_mapping;
2244 sis->flags &= ~SWP_ACTIVATED;
2245 if (mapping->a_ops->swap_deactivate)
2246 mapping->a_ops->swap_deactivate(swap_file);
2251 * Add a block range (and the corresponding page range) into this swapdev's
2254 * This function rather assumes that it is called in ascending page order.
2257 add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
2258 unsigned long nr_pages, sector_t start_block)
2260 struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
2261 struct swap_extent *se;
2262 struct swap_extent *new_se;
2265 * place the new node at the right most since the
2266 * function is called in ascending page order.
2270 link = &parent->rb_right;
2274 se = rb_entry(parent, struct swap_extent, rb_node);
2275 BUG_ON(se->start_page + se->nr_pages != start_page);
2276 if (se->start_block + se->nr_pages == start_block) {
2278 se->nr_pages += nr_pages;
2283 /* No merge, insert a new extent. */
2284 new_se = kmalloc(sizeof(*se), GFP_KERNEL);
2287 new_se->start_page = start_page;
2288 new_se->nr_pages = nr_pages;
2289 new_se->start_block = start_block;
2291 rb_link_node(&new_se->rb_node, parent, link);
2292 rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
2295 EXPORT_SYMBOL_GPL(add_swap_extent);
2298 * A `swap extent' is a simple thing which maps a contiguous range of pages
2299 * onto a contiguous range of disk blocks. A rbtree of swap extents is
2300 * built at swapon time and is then used at swap_writepage/swap_read_folio
2301 * time for locating where on disk a page belongs.
2303 * If the swapfile is an S_ISBLK block device, a single extent is installed.
2304 * This is done so that the main operating code can treat S_ISBLK and S_ISREG
2305 * swap files identically.
2307 * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
2308 * extent rbtree operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
2309 * swapfiles are handled *identically* after swapon time.
2311 * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
2312 * and will parse them into a rbtree, in PAGE_SIZE chunks. If some stray
2313 * blocks are found which do not fall within the PAGE_SIZE alignment
2314 * requirements, they are simply tossed out - we will never use those blocks
2317 * For all swap devices we set S_SWAPFILE across the life of the swapon. This
2318 * prevents users from writing to the swap device, which will corrupt memory.
2320 * The amount of disk space which a single swap extent represents varies.
2321 * Typically it is in the 1-4 megabyte range. So we can have hundreds of
2322 * extents in the rbtree. - akpm.
2324 static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
2326 struct file *swap_file = sis->swap_file;
2327 struct address_space *mapping = swap_file->f_mapping;
2328 struct inode *inode = mapping->host;
2331 if (S_ISBLK(inode->i_mode)) {
2332 ret = add_swap_extent(sis, 0, sis->max, 0);
2337 if (mapping->a_ops->swap_activate) {
2338 ret = mapping->a_ops->swap_activate(sis, swap_file, span);
2341 sis->flags |= SWP_ACTIVATED;
2342 if ((sis->flags & SWP_FS_OPS) &&
2343 sio_pool_init() != 0) {
2344 destroy_swap_extents(sis);
2350 return generic_swapfile_activate(sis, swap_file, span);
2353 static int swap_node(struct swap_info_struct *p)
2355 struct block_device *bdev;
2360 bdev = p->swap_file->f_inode->i_sb->s_bdev;
2362 return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2365 static void setup_swap_info(struct swap_info_struct *p, int prio,
2366 unsigned char *swap_map,
2367 struct swap_cluster_info *cluster_info)
2374 p->prio = --least_priority;
2376 * the plist prio is negated because plist ordering is
2377 * low-to-high, while swap ordering is high-to-low
2379 p->list.prio = -p->prio;
2382 p->avail_lists[i].prio = -p->prio;
2384 if (swap_node(p) == i)
2385 p->avail_lists[i].prio = 1;
2387 p->avail_lists[i].prio = -p->prio;
2390 p->swap_map = swap_map;
2391 p->cluster_info = cluster_info;
2394 static void _enable_swap_info(struct swap_info_struct *p)
2396 p->flags |= SWP_WRITEOK;
2397 atomic_long_add(p->pages, &nr_swap_pages);
2398 total_swap_pages += p->pages;
2400 assert_spin_locked(&swap_lock);
2402 * both lists are plists, and thus priority ordered.
2403 * swap_active_head needs to be priority ordered for swapoff(),
2404 * which on removal of any swap_info_struct with an auto-assigned
2405 * (i.e. negative) priority increments the auto-assigned priority
2406 * of any lower-priority swap_info_structs.
2407 * swap_avail_head needs to be priority ordered for folio_alloc_swap(),
2408 * which allocates swap pages from the highest available priority
2411 plist_add(&p->list, &swap_active_head);
2413 /* add to available list iff swap device is not full */
2415 add_to_avail_list(p);
2418 static void enable_swap_info(struct swap_info_struct *p, int prio,
2419 unsigned char *swap_map,
2420 struct swap_cluster_info *cluster_info)
2422 spin_lock(&swap_lock);
2423 spin_lock(&p->lock);
2424 setup_swap_info(p, prio, swap_map, cluster_info);
2425 spin_unlock(&p->lock);
2426 spin_unlock(&swap_lock);
2428 * Finished initializing swap device, now it's safe to reference it.
2430 percpu_ref_resurrect(&p->users);
2431 spin_lock(&swap_lock);
2432 spin_lock(&p->lock);
2433 _enable_swap_info(p);
2434 spin_unlock(&p->lock);
2435 spin_unlock(&swap_lock);
2438 static void reinsert_swap_info(struct swap_info_struct *p)
2440 spin_lock(&swap_lock);
2441 spin_lock(&p->lock);
2442 setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2443 _enable_swap_info(p);
2444 spin_unlock(&p->lock);
2445 spin_unlock(&swap_lock);
2448 bool has_usable_swap(void)
2452 spin_lock(&swap_lock);
2453 if (plist_head_empty(&swap_active_head))
2455 spin_unlock(&swap_lock);
2459 SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
2461 struct swap_info_struct *p = NULL;
2462 unsigned char *swap_map;
2463 struct swap_cluster_info *cluster_info;
2464 struct file *swap_file, *victim;
2465 struct address_space *mapping;
2466 struct inode *inode;
2467 struct filename *pathname;
2469 unsigned int old_block_size;
2471 if (!capable(CAP_SYS_ADMIN))
2474 BUG_ON(!current->mm);
2476 pathname = getname(specialfile);
2477 if (IS_ERR(pathname))
2478 return PTR_ERR(pathname);
2480 victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
2481 err = PTR_ERR(victim);
2485 mapping = victim->f_mapping;
2486 spin_lock(&swap_lock);
2487 plist_for_each_entry(p, &swap_active_head, list) {
2488 if (p->flags & SWP_WRITEOK) {
2489 if (p->swap_file->f_mapping == mapping) {
2497 spin_unlock(&swap_lock);
2500 if (!security_vm_enough_memory_mm(current->mm, p->pages))
2501 vm_unacct_memory(p->pages);
2504 spin_unlock(&swap_lock);
2507 spin_lock(&p->lock);
2508 del_from_avail_list(p);
2510 struct swap_info_struct *si = p;
2513 plist_for_each_entry_continue(si, &swap_active_head, list) {
2516 for_each_node(nid) {
2517 if (si->avail_lists[nid].prio != 1)
2518 si->avail_lists[nid].prio--;
2523 plist_del(&p->list, &swap_active_head);
2524 atomic_long_sub(p->pages, &nr_swap_pages);
2525 total_swap_pages -= p->pages;
2526 p->flags &= ~SWP_WRITEOK;
2527 spin_unlock(&p->lock);
2528 spin_unlock(&swap_lock);
2530 disable_swap_slots_cache_lock();
2532 set_current_oom_origin();
2533 err = try_to_unuse(p->type);
2534 clear_current_oom_origin();
2537 /* re-insert swap space back into swap_list */
2538 reinsert_swap_info(p);
2539 reenable_swap_slots_cache_unlock();
2543 reenable_swap_slots_cache_unlock();
2546 * Wait for swap operations protected by get/put_swap_device()
2549 * We need synchronize_rcu() here to protect the accessing to
2550 * the swap cache data structure.
2552 percpu_ref_kill(&p->users);
2554 wait_for_completion(&p->comp);
2556 flush_work(&p->discard_work);
2558 destroy_swap_extents(p);
2559 if (p->flags & SWP_CONTINUED)
2560 free_swap_count_continuations(p);
2562 if (!p->bdev || !bdev_nonrot(p->bdev))
2563 atomic_dec(&nr_rotate_swap);
2565 mutex_lock(&swapon_mutex);
2566 spin_lock(&swap_lock);
2567 spin_lock(&p->lock);
2570 /* wait for anyone still in scan_swap_map_slots */
2571 p->highest_bit = 0; /* cuts scans short */
2572 while (p->flags >= SWP_SCANNING) {
2573 spin_unlock(&p->lock);
2574 spin_unlock(&swap_lock);
2575 schedule_timeout_uninterruptible(1);
2576 spin_lock(&swap_lock);
2577 spin_lock(&p->lock);
2580 swap_file = p->swap_file;
2581 old_block_size = p->old_block_size;
2582 p->swap_file = NULL;
2584 swap_map = p->swap_map;
2586 cluster_info = p->cluster_info;
2587 p->cluster_info = NULL;
2588 spin_unlock(&p->lock);
2589 spin_unlock(&swap_lock);
2590 arch_swap_invalidate_area(p->type);
2591 zswap_swapoff(p->type);
2592 mutex_unlock(&swapon_mutex);
2593 free_percpu(p->percpu_cluster);
2594 p->percpu_cluster = NULL;
2595 free_percpu(p->cluster_next_cpu);
2596 p->cluster_next_cpu = NULL;
2598 kvfree(cluster_info);
2599 /* Destroy swap account information */
2600 swap_cgroup_swapoff(p->type);
2601 exit_swap_address_space(p->type);
2603 inode = mapping->host;
2605 set_blocksize(p->bdev, old_block_size);
2607 p->bdev_file = NULL;
2611 inode->i_flags &= ~S_SWAPFILE;
2612 inode_unlock(inode);
2613 filp_close(swap_file, NULL);
2616 * Clear the SWP_USED flag after all resources are freed so that swapon
2617 * can reuse this swap_info in alloc_swap_info() safely. It is ok to
2618 * not hold p->lock after we cleared its SWP_WRITEOK.
2620 spin_lock(&swap_lock);
2622 spin_unlock(&swap_lock);
2625 atomic_inc(&proc_poll_event);
2626 wake_up_interruptible(&proc_poll_wait);
2629 filp_close(victim, NULL);
2635 #ifdef CONFIG_PROC_FS
2636 static __poll_t swaps_poll(struct file *file, poll_table *wait)
2638 struct seq_file *seq = file->private_data;
2640 poll_wait(file, &proc_poll_wait, wait);
2642 if (seq->poll_event != atomic_read(&proc_poll_event)) {
2643 seq->poll_event = atomic_read(&proc_poll_event);
2644 return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
2647 return EPOLLIN | EPOLLRDNORM;
2651 static void *swap_start(struct seq_file *swap, loff_t *pos)
2653 struct swap_info_struct *si;
2657 mutex_lock(&swapon_mutex);
2660 return SEQ_START_TOKEN;
2662 for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2663 if (!(si->flags & SWP_USED) || !si->swap_map)
2672 static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
2674 struct swap_info_struct *si = v;
2677 if (v == SEQ_START_TOKEN)
2680 type = si->type + 1;
2683 for (; (si = swap_type_to_swap_info(type)); type++) {
2684 if (!(si->flags & SWP_USED) || !si->swap_map)
2692 static void swap_stop(struct seq_file *swap, void *v)
2694 mutex_unlock(&swapon_mutex);
2697 static int swap_show(struct seq_file *swap, void *v)
2699 struct swap_info_struct *si = v;
2702 unsigned long bytes, inuse;
2704 if (si == SEQ_START_TOKEN) {
2705 seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2709 bytes = K(si->pages);
2710 inuse = K(READ_ONCE(si->inuse_pages));
2712 file = si->swap_file;
2713 len = seq_file_path(swap, file, " \t\n\\");
2714 seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
2715 len < 40 ? 40 - len : 1, " ",
2716 S_ISBLK(file_inode(file)->i_mode) ?
2717 "partition" : "file\t",
2718 bytes, bytes < 10000000 ? "\t" : "",
2719 inuse, inuse < 10000000 ? "\t" : "",
2724 static const struct seq_operations swaps_op = {
2725 .start = swap_start,
2731 static int swaps_open(struct inode *inode, struct file *file)
2733 struct seq_file *seq;
2736 ret = seq_open(file, &swaps_op);
2740 seq = file->private_data;
2741 seq->poll_event = atomic_read(&proc_poll_event);
2745 static const struct proc_ops swaps_proc_ops = {
2746 .proc_flags = PROC_ENTRY_PERMANENT,
2747 .proc_open = swaps_open,
2748 .proc_read = seq_read,
2749 .proc_lseek = seq_lseek,
2750 .proc_release = seq_release,
2751 .proc_poll = swaps_poll,
2754 static int __init procswaps_init(void)
2756 proc_create("swaps", 0, NULL, &swaps_proc_ops);
2759 __initcall(procswaps_init);
2760 #endif /* CONFIG_PROC_FS */
2762 #ifdef MAX_SWAPFILES_CHECK
2763 static int __init max_swapfiles_check(void)
2765 MAX_SWAPFILES_CHECK();
2768 late_initcall(max_swapfiles_check);
2771 static struct swap_info_struct *alloc_swap_info(void)
2773 struct swap_info_struct *p;
2774 struct swap_info_struct *defer = NULL;
2778 p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2780 return ERR_PTR(-ENOMEM);
2782 if (percpu_ref_init(&p->users, swap_users_ref_free,
2783 PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
2785 return ERR_PTR(-ENOMEM);
2788 spin_lock(&swap_lock);
2789 for (type = 0; type < nr_swapfiles; type++) {
2790 if (!(swap_info[type]->flags & SWP_USED))
2793 if (type >= MAX_SWAPFILES) {
2794 spin_unlock(&swap_lock);
2795 percpu_ref_exit(&p->users);
2797 return ERR_PTR(-EPERM);
2799 if (type >= nr_swapfiles) {
2802 * Publish the swap_info_struct after initializing it.
2803 * Note that kvzalloc() above zeroes all its fields.
2805 smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
2809 p = swap_info[type];
2811 * Do not memset this entry: a racing procfs swap_next()
2812 * would be relying on p->type to remain valid.
2815 p->swap_extent_root = RB_ROOT;
2816 plist_node_init(&p->list, 0);
2818 plist_node_init(&p->avail_lists[i], 0);
2819 p->flags = SWP_USED;
2820 spin_unlock(&swap_lock);
2822 percpu_ref_exit(&defer->users);
2825 spin_lock_init(&p->lock);
2826 spin_lock_init(&p->cont_lock);
2827 init_completion(&p->comp);
2832 static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
2836 if (S_ISBLK(inode->i_mode)) {
2837 p->bdev_file = bdev_file_open_by_dev(inode->i_rdev,
2838 BLK_OPEN_READ | BLK_OPEN_WRITE, p, NULL);
2839 if (IS_ERR(p->bdev_file)) {
2840 error = PTR_ERR(p->bdev_file);
2841 p->bdev_file = NULL;
2844 p->bdev = file_bdev(p->bdev_file);
2845 p->old_block_size = block_size(p->bdev);
2846 error = set_blocksize(p->bdev, PAGE_SIZE);
2850 * Zoned block devices contain zones that have a sequential
2851 * write only restriction. Hence zoned block devices are not
2852 * suitable for swapping. Disallow them here.
2854 if (bdev_is_zoned(p->bdev))
2856 p->flags |= SWP_BLKDEV;
2857 } else if (S_ISREG(inode->i_mode)) {
2858 p->bdev = inode->i_sb->s_bdev;
2866 * Find out how many pages are allowed for a single swap device. There
2867 * are two limiting factors:
2868 * 1) the number of bits for the swap offset in the swp_entry_t type, and
2869 * 2) the number of bits in the swap pte, as defined by the different
2872 * In order to find the largest possible bit mask, a swap entry with
2873 * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2874 * decoded to a swp_entry_t again, and finally the swap offset is
2877 * This will mask all the bits from the initial ~0UL mask that can't
2878 * be encoded in either the swp_entry_t or the architecture definition
2881 unsigned long generic_max_swapfile_size(void)
2883 return swp_offset(pte_to_swp_entry(
2884 swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2887 /* Can be overridden by an architecture for additional checks. */
2888 __weak unsigned long arch_max_swapfile_size(void)
2890 return generic_max_swapfile_size();
2893 static unsigned long read_swap_header(struct swap_info_struct *p,
2894 union swap_header *swap_header,
2895 struct inode *inode)
2898 unsigned long maxpages;
2899 unsigned long swapfilepages;
2900 unsigned long last_page;
2902 if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2903 pr_err("Unable to find swap-space signature\n");
2907 /* swap partition endianness hack... */
2908 if (swab32(swap_header->info.version) == 1) {
2909 swab32s(&swap_header->info.version);
2910 swab32s(&swap_header->info.last_page);
2911 swab32s(&swap_header->info.nr_badpages);
2912 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2914 for (i = 0; i < swap_header->info.nr_badpages; i++)
2915 swab32s(&swap_header->info.badpages[i]);
2917 /* Check the swap header's sub-version */
2918 if (swap_header->info.version != 1) {
2919 pr_warn("Unable to handle swap header version %d\n",
2920 swap_header->info.version);
2925 p->cluster_next = 1;
2928 maxpages = swapfile_maximum_size;
2929 last_page = swap_header->info.last_page;
2931 pr_warn("Empty swap-file\n");
2934 if (last_page > maxpages) {
2935 pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2936 K(maxpages), K(last_page));
2938 if (maxpages > last_page) {
2939 maxpages = last_page + 1;
2940 /* p->max is an unsigned int: don't overflow it */
2941 if ((unsigned int)maxpages == 0)
2942 maxpages = UINT_MAX;
2944 p->highest_bit = maxpages - 1;
2948 swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2949 if (swapfilepages && maxpages > swapfilepages) {
2950 pr_warn("Swap area shorter than signature indicates\n");
2953 if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
2955 if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2961 #define SWAP_CLUSTER_INFO_COLS \
2962 DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
2963 #define SWAP_CLUSTER_SPACE_COLS \
2964 DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
2965 #define SWAP_CLUSTER_COLS \
2966 max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
2968 static int setup_swap_map_and_extents(struct swap_info_struct *p,
2969 union swap_header *swap_header,
2970 unsigned char *swap_map,
2971 struct swap_cluster_info *cluster_info,
2972 unsigned long maxpages,
2976 unsigned int nr_good_pages;
2978 unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2979 unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
2980 unsigned long i, idx;
2982 nr_good_pages = maxpages - 1; /* omit header page */
2984 cluster_list_init(&p->free_clusters);
2985 cluster_list_init(&p->discard_clusters);
2987 for (i = 0; i < swap_header->info.nr_badpages; i++) {
2988 unsigned int page_nr = swap_header->info.badpages[i];
2989 if (page_nr == 0 || page_nr > swap_header->info.last_page)
2991 if (page_nr < maxpages) {
2992 swap_map[page_nr] = SWAP_MAP_BAD;
2995 * Haven't marked the cluster free yet, no list
2996 * operation involved
2998 inc_cluster_info_page(p, cluster_info, page_nr);
3002 /* Haven't marked the cluster free yet, no list operation involved */
3003 for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
3004 inc_cluster_info_page(p, cluster_info, i);
3006 if (nr_good_pages) {
3007 swap_map[0] = SWAP_MAP_BAD;
3009 * Not mark the cluster free yet, no list
3010 * operation involved
3012 inc_cluster_info_page(p, cluster_info, 0);
3014 p->pages = nr_good_pages;
3015 nr_extents = setup_swap_extents(p, span);
3018 nr_good_pages = p->pages;
3020 if (!nr_good_pages) {
3021 pr_warn("Empty swap-file\n");
3030 * Reduce false cache line sharing between cluster_info and
3031 * sharing same address space.
3033 for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
3034 j = (k + col) % SWAP_CLUSTER_COLS;
3035 for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
3036 idx = i * SWAP_CLUSTER_COLS + j;
3037 if (idx >= nr_clusters)
3039 if (cluster_count(&cluster_info[idx]))
3041 cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
3042 cluster_list_add_tail(&p->free_clusters, cluster_info,
3049 SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
3051 struct swap_info_struct *p;
3052 struct filename *name;
3053 struct file *swap_file = NULL;
3054 struct address_space *mapping;
3055 struct dentry *dentry;
3058 union swap_header *swap_header;
3061 unsigned long maxpages;
3062 unsigned char *swap_map = NULL;
3063 struct swap_cluster_info *cluster_info = NULL;
3064 struct page *page = NULL;
3065 struct inode *inode = NULL;
3066 bool inced_nr_rotate_swap = false;
3068 if (swap_flags & ~SWAP_FLAGS_VALID)
3071 if (!capable(CAP_SYS_ADMIN))
3074 if (!swap_avail_heads)
3077 p = alloc_swap_info();
3081 INIT_WORK(&p->discard_work, swap_discard_work);
3083 name = getname(specialfile);
3085 error = PTR_ERR(name);
3089 swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
3090 if (IS_ERR(swap_file)) {
3091 error = PTR_ERR(swap_file);
3096 p->swap_file = swap_file;
3097 mapping = swap_file->f_mapping;
3098 dentry = swap_file->f_path.dentry;
3099 inode = mapping->host;
3101 error = claim_swapfile(p, inode);
3102 if (unlikely(error))
3106 if (d_unlinked(dentry) || cant_mount(dentry)) {
3108 goto bad_swap_unlock_inode;
3110 if (IS_SWAPFILE(inode)) {
3112 goto bad_swap_unlock_inode;
3116 * Read the swap header.
3118 if (!mapping->a_ops->read_folio) {
3120 goto bad_swap_unlock_inode;
3122 page = read_mapping_page(mapping, 0, swap_file);
3124 error = PTR_ERR(page);
3125 goto bad_swap_unlock_inode;
3127 swap_header = kmap(page);
3129 maxpages = read_swap_header(p, swap_header, inode);
3130 if (unlikely(!maxpages)) {
3132 goto bad_swap_unlock_inode;
3135 /* OK, set up the swap map and apply the bad block list */
3136 swap_map = vzalloc(maxpages);
3139 goto bad_swap_unlock_inode;
3142 if (p->bdev && bdev_stable_writes(p->bdev))
3143 p->flags |= SWP_STABLE_WRITES;
3145 if (p->bdev && bdev_synchronous(p->bdev))
3146 p->flags |= SWP_SYNCHRONOUS_IO;
3148 if (p->bdev && bdev_nonrot(p->bdev)) {
3150 unsigned long ci, nr_cluster;
3152 p->flags |= SWP_SOLIDSTATE;
3153 p->cluster_next_cpu = alloc_percpu(unsigned int);
3154 if (!p->cluster_next_cpu) {
3156 goto bad_swap_unlock_inode;
3159 * select a random position to start with to help wear leveling
3162 for_each_possible_cpu(cpu) {
3163 per_cpu(*p->cluster_next_cpu, cpu) =
3164 get_random_u32_inclusive(1, p->highest_bit);
3166 nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
3168 cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
3170 if (!cluster_info) {
3172 goto bad_swap_unlock_inode;
3175 for (ci = 0; ci < nr_cluster; ci++)
3176 spin_lock_init(&((cluster_info + ci)->lock));
3178 p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3179 if (!p->percpu_cluster) {
3181 goto bad_swap_unlock_inode;
3183 for_each_possible_cpu(cpu) {
3184 struct percpu_cluster *cluster;
3186 cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3187 for (i = 0; i < SWAP_NR_ORDERS; i++)
3188 cluster->next[i] = SWAP_NEXT_INVALID;
3191 atomic_inc(&nr_rotate_swap);
3192 inced_nr_rotate_swap = true;
3195 error = swap_cgroup_swapon(p->type, maxpages);
3197 goto bad_swap_unlock_inode;
3199 nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
3200 cluster_info, maxpages, &span);
3201 if (unlikely(nr_extents < 0)) {
3203 goto bad_swap_unlock_inode;
3206 if ((swap_flags & SWAP_FLAG_DISCARD) &&
3207 p->bdev && bdev_max_discard_sectors(p->bdev)) {
3209 * When discard is enabled for swap with no particular
3210 * policy flagged, we set all swap discard flags here in
3211 * order to sustain backward compatibility with older
3212 * swapon(8) releases.
3214 p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3218 * By flagging sys_swapon, a sysadmin can tell us to
3219 * either do single-time area discards only, or to just
3220 * perform discards for released swap page-clusters.
3221 * Now it's time to adjust the p->flags accordingly.
3223 if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3224 p->flags &= ~SWP_PAGE_DISCARD;
3225 else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3226 p->flags &= ~SWP_AREA_DISCARD;
3228 /* issue a swapon-time discard if it's still required */
3229 if (p->flags & SWP_AREA_DISCARD) {
3230 int err = discard_swap(p);
3232 pr_err("swapon: discard_swap(%p): %d\n",
3237 error = init_swap_address_space(p->type, maxpages);
3239 goto bad_swap_unlock_inode;
3241 error = zswap_swapon(p->type, maxpages);
3243 goto free_swap_address_space;
3246 * Flush any pending IO and dirty mappings before we start using this
3249 inode->i_flags |= S_SWAPFILE;
3250 error = inode_drain_writes(inode);
3252 inode->i_flags &= ~S_SWAPFILE;
3253 goto free_swap_zswap;
3256 mutex_lock(&swapon_mutex);
3258 if (swap_flags & SWAP_FLAG_PREFER)
3260 (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
3261 enable_swap_info(p, prio, swap_map, cluster_info);
3263 pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n",
3264 K(p->pages), name->name, p->prio, nr_extents,
3265 K((unsigned long long)span),
3266 (p->flags & SWP_SOLIDSTATE) ? "SS" : "",
3267 (p->flags & SWP_DISCARDABLE) ? "D" : "",
3268 (p->flags & SWP_AREA_DISCARD) ? "s" : "",
3269 (p->flags & SWP_PAGE_DISCARD) ? "c" : "");
3271 mutex_unlock(&swapon_mutex);
3272 atomic_inc(&proc_poll_event);
3273 wake_up_interruptible(&proc_poll_wait);
3278 zswap_swapoff(p->type);
3279 free_swap_address_space:
3280 exit_swap_address_space(p->type);
3281 bad_swap_unlock_inode:
3282 inode_unlock(inode);
3284 free_percpu(p->percpu_cluster);
3285 p->percpu_cluster = NULL;
3286 free_percpu(p->cluster_next_cpu);
3287 p->cluster_next_cpu = NULL;
3289 set_blocksize(p->bdev, p->old_block_size);
3291 p->bdev_file = NULL;
3294 destroy_swap_extents(p);
3295 swap_cgroup_swapoff(p->type);
3296 spin_lock(&swap_lock);
3297 p->swap_file = NULL;
3299 spin_unlock(&swap_lock);
3301 kvfree(cluster_info);
3302 if (inced_nr_rotate_swap)
3303 atomic_dec(&nr_rotate_swap);
3305 filp_close(swap_file, NULL);
3307 if (page && !IS_ERR(page)) {
3314 inode_unlock(inode);
3316 enable_swap_slots_cache();
3320 void si_swapinfo(struct sysinfo *val)
3323 unsigned long nr_to_be_unused = 0;
3325 spin_lock(&swap_lock);
3326 for (type = 0; type < nr_swapfiles; type++) {
3327 struct swap_info_struct *si = swap_info[type];
3329 if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3330 nr_to_be_unused += READ_ONCE(si->inuse_pages);
3332 val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
3333 val->totalswap = total_swap_pages + nr_to_be_unused;
3334 spin_unlock(&swap_lock);
3338 * Verify that a swap entry is valid and increment its swap map count.
3340 * Returns error code in following case.
3342 * - swp_entry is invalid -> EINVAL
3343 * - swp_entry is migration entry -> EINVAL
3344 * - swap-cache reference is requested but there is already one. -> EEXIST
3345 * - swap-cache reference is requested but the entry is not used. -> ENOENT
3346 * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
3348 static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
3350 struct swap_info_struct *p;
3351 struct swap_cluster_info *ci;
3352 unsigned long offset;
3353 unsigned char count;
3354 unsigned char has_cache;
3357 p = swp_swap_info(entry);
3359 offset = swp_offset(entry);
3360 ci = lock_cluster_or_swap_info(p, offset);
3362 count = p->swap_map[offset];
3365 * swapin_readahead() doesn't check if a swap entry is valid, so the
3366 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3368 if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3373 has_cache = count & SWAP_HAS_CACHE;
3374 count &= ~SWAP_HAS_CACHE;
3377 if (usage == SWAP_HAS_CACHE) {
3379 /* set SWAP_HAS_CACHE if there is no cache and entry is used */
3380 if (!has_cache && count)
3381 has_cache = SWAP_HAS_CACHE;
3382 else if (has_cache) /* someone else added cache */
3384 else /* no users remaining */
3387 } else if (count || has_cache) {
3389 if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3391 else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3393 else if (swap_count_continued(p, offset, count))
3394 count = COUNT_CONTINUED;
3398 err = -ENOENT; /* unused swap entry */
3401 WRITE_ONCE(p->swap_map[offset], count | has_cache);
3404 unlock_cluster_or_swap_info(p, ci);
3409 * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3410 * (in which case its reference count is never incremented).
3412 void swap_shmem_alloc(swp_entry_t entry)
3414 __swap_duplicate(entry, SWAP_MAP_SHMEM);
3418 * Increase reference count of swap entry by 1.
3419 * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
3420 * but could not be atomically allocated. Returns 0, just as if it succeeded,
3421 * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
3422 * might occur if a page table entry has got corrupted.
3424 int swap_duplicate(swp_entry_t entry)
3428 while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3429 err = add_swap_count_continuation(entry, GFP_ATOMIC);
3434 * @entry: swap entry for which we allocate swap cache.
3436 * Called when allocating swap cache for existing swap entry,
3437 * This can return error codes. Returns 0 at success.
3438 * -EEXIST means there is a swap cache.
3439 * Note: return code is different from swap_duplicate().
3441 int swapcache_prepare(swp_entry_t entry)
3443 return __swap_duplicate(entry, SWAP_HAS_CACHE);
3446 void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry)
3448 struct swap_cluster_info *ci;
3449 unsigned long offset = swp_offset(entry);
3450 unsigned char usage;
3452 ci = lock_cluster_or_swap_info(si, offset);
3453 usage = __swap_entry_free_locked(si, offset, SWAP_HAS_CACHE);
3454 unlock_cluster_or_swap_info(si, ci);
3456 free_swap_slot(entry);
3459 struct swap_info_struct *swp_swap_info(swp_entry_t entry)
3461 return swap_type_to_swap_info(swp_type(entry));
3465 * out-of-line methods to avoid include hell.
3467 struct address_space *swapcache_mapping(struct folio *folio)
3469 return swp_swap_info(folio->swap)->swap_file->f_mapping;
3471 EXPORT_SYMBOL_GPL(swapcache_mapping);
3473 pgoff_t __page_file_index(struct page *page)
3475 swp_entry_t swap = page_swap_entry(page);
3476 return swp_offset(swap);
3478 EXPORT_SYMBOL_GPL(__page_file_index);
3481 * add_swap_count_continuation - called when a swap count is duplicated
3482 * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3483 * page of the original vmalloc'ed swap_map, to hold the continuation count
3484 * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
3485 * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3487 * These continuation pages are seldom referenced: the common paths all work
3488 * on the original swap_map, only referring to a continuation page when the
3489 * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3491 * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3492 * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3493 * can be called after dropping locks.
3495 int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3497 struct swap_info_struct *si;
3498 struct swap_cluster_info *ci;
3501 struct page *list_page;
3503 unsigned char count;
3507 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3508 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3510 page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3512 si = get_swap_device(entry);
3515 * An acceptable race has occurred since the failing
3516 * __swap_duplicate(): the swap device may be swapoff
3520 spin_lock(&si->lock);
3522 offset = swp_offset(entry);
3524 ci = lock_cluster(si, offset);
3526 count = swap_count(si->swap_map[offset]);
3528 if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3530 * The higher the swap count, the more likely it is that tasks
3531 * will race to add swap count continuation: we need to avoid
3532 * over-provisioning.
3542 head = vmalloc_to_page(si->swap_map + offset);
3543 offset &= ~PAGE_MASK;
3545 spin_lock(&si->cont_lock);
3547 * Page allocation does not initialize the page's lru field,
3548 * but it does always reset its private field.
3550 if (!page_private(head)) {
3551 BUG_ON(count & COUNT_CONTINUED);
3552 INIT_LIST_HEAD(&head->lru);
3553 set_page_private(head, SWP_CONTINUED);
3554 si->flags |= SWP_CONTINUED;
3557 list_for_each_entry(list_page, &head->lru, lru) {
3561 * If the previous map said no continuation, but we've found
3562 * a continuation page, free our allocation and use this one.
3564 if (!(count & COUNT_CONTINUED))
3565 goto out_unlock_cont;
3567 map = kmap_local_page(list_page) + offset;
3572 * If this continuation count now has some space in it,
3573 * free our allocation and use this one.
3575 if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
3576 goto out_unlock_cont;
3579 list_add_tail(&page->lru, &head->lru);
3580 page = NULL; /* now it's attached, don't free it */
3582 spin_unlock(&si->cont_lock);
3585 spin_unlock(&si->lock);
3586 put_swap_device(si);
3594 * swap_count_continued - when the original swap_map count is incremented
3595 * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3596 * into, carry if so, or else fail until a new continuation page is allocated;
3597 * when the original swap_map count is decremented from 0 with continuation,
3598 * borrow from the continuation and report whether it still holds more.
3599 * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3602 static bool swap_count_continued(struct swap_info_struct *si,
3603 pgoff_t offset, unsigned char count)
3610 head = vmalloc_to_page(si->swap_map + offset);
3611 if (page_private(head) != SWP_CONTINUED) {
3612 BUG_ON(count & COUNT_CONTINUED);
3613 return false; /* need to add count continuation */
3616 spin_lock(&si->cont_lock);
3617 offset &= ~PAGE_MASK;
3618 page = list_next_entry(head, lru);
3619 map = kmap_local_page(page) + offset;
3621 if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
3622 goto init_map; /* jump over SWAP_CONT_MAX checks */
3624 if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3626 * Think of how you add 1 to 999
3628 while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
3630 page = list_next_entry(page, lru);
3631 BUG_ON(page == head);
3632 map = kmap_local_page(page) + offset;
3634 if (*map == SWAP_CONT_MAX) {
3636 page = list_next_entry(page, lru);
3638 ret = false; /* add count continuation */
3641 map = kmap_local_page(page) + offset;
3642 init_map: *map = 0; /* we didn't zero the page */
3646 while ((page = list_prev_entry(page, lru)) != head) {
3647 map = kmap_local_page(page) + offset;
3648 *map = COUNT_CONTINUED;
3651 ret = true; /* incremented */
3653 } else { /* decrementing */
3655 * Think of how you subtract 1 from 1000
3657 BUG_ON(count != COUNT_CONTINUED);
3658 while (*map == COUNT_CONTINUED) {
3660 page = list_next_entry(page, lru);
3661 BUG_ON(page == head);
3662 map = kmap_local_page(page) + offset;
3669 while ((page = list_prev_entry(page, lru)) != head) {
3670 map = kmap_local_page(page) + offset;
3671 *map = SWAP_CONT_MAX | count;
3672 count = COUNT_CONTINUED;
3675 ret = count == COUNT_CONTINUED;
3678 spin_unlock(&si->cont_lock);
3683 * free_swap_count_continuations - swapoff free all the continuation pages
3684 * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3686 static void free_swap_count_continuations(struct swap_info_struct *si)
3690 for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3692 head = vmalloc_to_page(si->swap_map + offset);
3693 if (page_private(head)) {
3694 struct page *page, *next;
3696 list_for_each_entry_safe(page, next, &head->lru, lru) {
3697 list_del(&page->lru);
3704 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
3705 void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
3707 struct swap_info_struct *si, *next;
3708 int nid = folio_nid(folio);
3710 if (!(gfp & __GFP_IO))
3713 if (!blk_cgroup_congested())
3717 * We've already scheduled a throttle, avoid taking the global swap
3720 if (current->throttle_disk)
3723 spin_lock(&swap_avail_lock);
3724 plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
3727 blkcg_schedule_throttle(si->bdev->bd_disk, true);
3731 spin_unlock(&swap_avail_lock);
3735 static int __init swapfile_init(void)
3739 swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3741 if (!swap_avail_heads) {
3742 pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3747 plist_head_init(&swap_avail_heads[nid]);
3749 swapfile_maximum_size = arch_max_swapfile_size();
3751 #ifdef CONFIG_MIGRATION
3752 if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
3753 swap_migration_ad_supported = true;
3754 #endif /* CONFIG_MIGRATION */
3758 subsys_initcall(swapfile_init);