xref: /openbmc/linux/mm/swapfile.c (revision 00cde0429bc50792ed8786e909e70141acf3741a)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *  linux/mm/swapfile.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
61da177e4SLinus Torvalds  *  Swap reorganised 29.12.95, Stephen Tweedie
71da177e4SLinus Torvalds  */
81da177e4SLinus Torvalds 
9c97ab271SChristoph Hellwig #include <linux/blkdev.h>
101da177e4SLinus Torvalds #include <linux/mm.h>
116e84f315SIngo Molnar #include <linux/sched/mm.h>
1229930025SIngo Molnar #include <linux/sched/task.h>
131da177e4SLinus Torvalds #include <linux/hugetlb.h>
141da177e4SLinus Torvalds #include <linux/mman.h>
151da177e4SLinus Torvalds #include <linux/slab.h>
161da177e4SLinus Torvalds #include <linux/kernel_stat.h>
171da177e4SLinus Torvalds #include <linux/swap.h>
181da177e4SLinus Torvalds #include <linux/vmalloc.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/namei.h>
21072441e2SHugh Dickins #include <linux/shmem_fs.h>
22e41d12f5SChristoph Hellwig #include <linux/blk-cgroup.h>
2320137a49SHugh Dickins #include <linux/random.h>
241da177e4SLinus Torvalds #include <linux/writeback.h>
251da177e4SLinus Torvalds #include <linux/proc_fs.h>
261da177e4SLinus Torvalds #include <linux/seq_file.h>
271da177e4SLinus Torvalds #include <linux/init.h>
285ad64688SHugh Dickins #include <linux/ksm.h>
291da177e4SLinus Torvalds #include <linux/rmap.h>
301da177e4SLinus Torvalds #include <linux/security.h>
311da177e4SLinus Torvalds #include <linux/backing-dev.h>
32fc0abb14SIngo Molnar #include <linux/mutex.h>
33c59ede7bSRandy.Dunlap #include <linux/capability.h>
341da177e4SLinus Torvalds #include <linux/syscalls.h>
358a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
3666d7dd51SKay Sievers #include <linux/poll.h>
3772788c38SDavid Rientjes #include <linux/oom.h>
3838b5faf4SDan Magenheimer #include <linux/swapfile.h>
39f981c595SMel Gorman #include <linux/export.h>
4067afa38eSTim Chen #include <linux/swap_slots.h>
41155b5f88SHuang Ying #include <linux/sort.h>
4263d8620eSMiaohe Lin #include <linux/completion.h>
4307f44ac3SKefeng Wang #include <linux/suspend.h>
4442c06a0eSJohannes Weiner #include <linux/zswap.h>
451da177e4SLinus Torvalds 
461da177e4SLinus Torvalds #include <asm/tlbflush.h>
471da177e4SLinus Torvalds #include <linux/swapops.h>
485d1ea48bSJohannes Weiner #include <linux/swap_cgroup.h>
49*00cde042SZhangPeng #include "internal.h"
50014bb1deSNeilBrown #include "swap.h"
511da177e4SLinus Torvalds 
52570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
53570a335bSHugh Dickins 				 unsigned char);
54570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *);
55570a335bSHugh Dickins 
56633423a0SChristoph Hellwig static DEFINE_SPINLOCK(swap_lock);
577c363b8cSAdrian Bunk static unsigned int nr_swapfiles;
58ec8acf20SShaohua Li atomic_long_t nr_swap_pages;
59fb0fec50SChris Wilson /*
60fb0fec50SChris Wilson  * Some modules use swappable objects and may try to swap them out under
61fb0fec50SChris Wilson  * memory pressure (via the shrinker). Before doing so, they may wish to
62fb0fec50SChris Wilson  * check to see if any swap space is available.
63fb0fec50SChris Wilson  */
64fb0fec50SChris Wilson EXPORT_SYMBOL_GPL(nr_swap_pages);
65ec8acf20SShaohua Li /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
661da177e4SLinus Torvalds long total_swap_pages;
67a2468cc9SAaron Lu static int least_priority = -1;
68be45a490SPeter Xu unsigned long swapfile_maximum_size;
695154e607SPeter Xu #ifdef CONFIG_MIGRATION
705154e607SPeter Xu bool swap_migration_ad_supported;
715154e607SPeter Xu #endif	/* CONFIG_MIGRATION */
721da177e4SLinus Torvalds 
731da177e4SLinus Torvalds static const char Bad_file[] = "Bad swap file entry ";
741da177e4SLinus Torvalds static const char Unused_file[] = "Unused swap file entry ";
751da177e4SLinus Torvalds static const char Bad_offset[] = "Bad swap offset entry ";
761da177e4SLinus Torvalds static const char Unused_offset[] = "Unused swap offset entry ";
771da177e4SLinus Torvalds 
78adfab836SDan Streetman /*
79adfab836SDan Streetman  * all active swap_info_structs
80adfab836SDan Streetman  * protected with swap_lock, and ordered by priority.
81adfab836SDan Streetman  */
82633423a0SChristoph Hellwig static PLIST_HEAD(swap_active_head);
8318ab4d4cSDan Streetman 
8418ab4d4cSDan Streetman /*
8518ab4d4cSDan Streetman  * all available (active, not full) swap_info_structs
8618ab4d4cSDan Streetman  * protected with swap_avail_lock, ordered by priority.
87e2e3fdc7SMatthew Wilcox (Oracle)  * This is used by folio_alloc_swap() instead of swap_active_head
8818ab4d4cSDan Streetman  * because swap_active_head includes all swap_info_structs,
89e2e3fdc7SMatthew Wilcox (Oracle)  * but folio_alloc_swap() doesn't need to look at full ones.
9018ab4d4cSDan Streetman  * This uses its own lock instead of swap_lock because when a
9118ab4d4cSDan Streetman  * swap_info_struct changes between not-full/full, it needs to
9218ab4d4cSDan Streetman  * add/remove itself to/from this list, but the swap_info_struct->lock
9318ab4d4cSDan Streetman  * is held and the locking order requires swap_lock to be taken
9418ab4d4cSDan Streetman  * before any swap_info_struct->lock.
9518ab4d4cSDan Streetman  */
96bfc6b1caSColin Ian King static struct plist_head *swap_avail_heads;
9718ab4d4cSDan Streetman static DEFINE_SPINLOCK(swap_avail_lock);
981da177e4SLinus Torvalds 
9942c06a0eSJohannes Weiner static struct swap_info_struct *swap_info[MAX_SWAPFILES];
1001da177e4SLinus Torvalds 
101fc0abb14SIngo Molnar static DEFINE_MUTEX(swapon_mutex);
1021da177e4SLinus Torvalds 
10366d7dd51SKay Sievers static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
10466d7dd51SKay Sievers /* Activity counter to indicate that a swapon or swapoff has occurred */
10566d7dd51SKay Sievers static atomic_t proc_poll_event = ATOMIC_INIT(0);
10666d7dd51SKay Sievers 
10781a0298bSHuang Ying atomic_t nr_rotate_swap = ATOMIC_INIT(0);
10881a0298bSHuang Ying 
109c10d38ccSDaniel Jordan static struct swap_info_struct *swap_type_to_swap_info(int type)
110c10d38ccSDaniel Jordan {
111a4b45114SHuang Ying 	if (type >= MAX_SWAPFILES)
112c10d38ccSDaniel Jordan 		return NULL;
113c10d38ccSDaniel Jordan 
114a4b45114SHuang Ying 	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
115c10d38ccSDaniel Jordan }
116c10d38ccSDaniel Jordan 
1178d69aaeeSHugh Dickins static inline unsigned char swap_count(unsigned char ent)
118355cfa73SKAMEZAWA Hiroyuki {
119955c97f0SDaniel Jordan 	return ent & ~SWAP_HAS_CACHE;	/* may include COUNT_CONTINUED flag */
120355cfa73SKAMEZAWA Hiroyuki }
121355cfa73SKAMEZAWA Hiroyuki 
122bcd49e86SHuang Ying /* Reclaim the swap entry anyway if possible */
123bcd49e86SHuang Ying #define TTRS_ANYWAY		0x1
124bcd49e86SHuang Ying /*
125bcd49e86SHuang Ying  * Reclaim the swap entry if there are no more mappings of the
126bcd49e86SHuang Ying  * corresponding page
127bcd49e86SHuang Ying  */
128bcd49e86SHuang Ying #define TTRS_UNMAPPED		0x2
129bcd49e86SHuang Ying /* Reclaim the swap entry if swap is getting full*/
130bcd49e86SHuang Ying #define TTRS_FULL		0x4
131bcd49e86SHuang Ying 
132efa90a98SHugh Dickins /* returns 1 if swap entry is freed */
133bcd49e86SHuang Ying static int __try_to_reclaim_swap(struct swap_info_struct *si,
134bcd49e86SHuang Ying 				 unsigned long offset, unsigned long flags)
135c9e44410SKAMEZAWA Hiroyuki {
136efa90a98SHugh Dickins 	swp_entry_t entry = swp_entry(si->type, offset);
1372c3f6194SMatthew Wilcox (Oracle) 	struct folio *folio;
138c9e44410SKAMEZAWA Hiroyuki 	int ret = 0;
139c9e44410SKAMEZAWA Hiroyuki 
1402c3f6194SMatthew Wilcox (Oracle) 	folio = filemap_get_folio(swap_address_space(entry), offset);
14166dabbb6SChristoph Hellwig 	if (IS_ERR(folio))
142c9e44410SKAMEZAWA Hiroyuki 		return 0;
143c9e44410SKAMEZAWA Hiroyuki 	/*
144bcd49e86SHuang Ying 	 * When this function is called from scan_swap_map_slots() and it's
1452c3f6194SMatthew Wilcox (Oracle) 	 * called by vmscan.c at reclaiming folios. So we hold a folio lock
146bcd49e86SHuang Ying 	 * here. We have to use trylock for avoiding deadlock. This is a special
1472c3f6194SMatthew Wilcox (Oracle) 	 * case and you should use folio_free_swap() with explicit folio_lock()
148c9e44410SKAMEZAWA Hiroyuki 	 * in usual operations.
149c9e44410SKAMEZAWA Hiroyuki 	 */
1502c3f6194SMatthew Wilcox (Oracle) 	if (folio_trylock(folio)) {
151bcd49e86SHuang Ying 		if ((flags & TTRS_ANYWAY) ||
1522c3f6194SMatthew Wilcox (Oracle) 		    ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) ||
1539202d527SMatthew Wilcox (Oracle) 		    ((flags & TTRS_FULL) && mem_cgroup_swap_full(folio)))
1542c3f6194SMatthew Wilcox (Oracle) 			ret = folio_free_swap(folio);
1552c3f6194SMatthew Wilcox (Oracle) 		folio_unlock(folio);
156c9e44410SKAMEZAWA Hiroyuki 	}
1572c3f6194SMatthew Wilcox (Oracle) 	folio_put(folio);
158c9e44410SKAMEZAWA Hiroyuki 	return ret;
159c9e44410SKAMEZAWA Hiroyuki }
160355cfa73SKAMEZAWA Hiroyuki 
1614efaceb1SAaron Lu static inline struct swap_extent *first_se(struct swap_info_struct *sis)
1624efaceb1SAaron Lu {
1634efaceb1SAaron Lu 	struct rb_node *rb = rb_first(&sis->swap_extent_root);
1644efaceb1SAaron Lu 	return rb_entry(rb, struct swap_extent, rb_node);
1654efaceb1SAaron Lu }
1664efaceb1SAaron Lu 
1674efaceb1SAaron Lu static inline struct swap_extent *next_se(struct swap_extent *se)
1684efaceb1SAaron Lu {
1694efaceb1SAaron Lu 	struct rb_node *rb = rb_next(&se->rb_node);
1704efaceb1SAaron Lu 	return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
1714efaceb1SAaron Lu }
1724efaceb1SAaron Lu 
1731da177e4SLinus Torvalds /*
1746a6ba831SHugh Dickins  * swapon tell device that all the old swap contents can be discarded,
1756a6ba831SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1766a6ba831SHugh Dickins  */
1776a6ba831SHugh Dickins static int discard_swap(struct swap_info_struct *si)
1786a6ba831SHugh Dickins {
1796a6ba831SHugh Dickins 	struct swap_extent *se;
1809625a5f2SHugh Dickins 	sector_t start_block;
1819625a5f2SHugh Dickins 	sector_t nr_blocks;
1826a6ba831SHugh Dickins 	int err = 0;
1836a6ba831SHugh Dickins 
1846a6ba831SHugh Dickins 	/* Do not discard the swap header page! */
1854efaceb1SAaron Lu 	se = first_se(si);
1869625a5f2SHugh Dickins 	start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
1879625a5f2SHugh Dickins 	nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
1889625a5f2SHugh Dickins 	if (nr_blocks) {
1899625a5f2SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
19044abff2cSChristoph Hellwig 				nr_blocks, GFP_KERNEL);
1919625a5f2SHugh Dickins 		if (err)
1929625a5f2SHugh Dickins 			return err;
1939625a5f2SHugh Dickins 		cond_resched();
1946a6ba831SHugh Dickins 	}
1956a6ba831SHugh Dickins 
1964efaceb1SAaron Lu 	for (se = next_se(se); se; se = next_se(se)) {
1979625a5f2SHugh Dickins 		start_block = se->start_block << (PAGE_SHIFT - 9);
1989625a5f2SHugh Dickins 		nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
1999625a5f2SHugh Dickins 
2006a6ba831SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
20144abff2cSChristoph Hellwig 				nr_blocks, GFP_KERNEL);
2026a6ba831SHugh Dickins 		if (err)
2036a6ba831SHugh Dickins 			break;
2046a6ba831SHugh Dickins 
2056a6ba831SHugh Dickins 		cond_resched();
2066a6ba831SHugh Dickins 	}
2076a6ba831SHugh Dickins 	return err;		/* That will often be -EOPNOTSUPP */
2086a6ba831SHugh Dickins }
2096a6ba831SHugh Dickins 
2104efaceb1SAaron Lu static struct swap_extent *
2114efaceb1SAaron Lu offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
2124efaceb1SAaron Lu {
2134efaceb1SAaron Lu 	struct swap_extent *se;
2144efaceb1SAaron Lu 	struct rb_node *rb;
2154efaceb1SAaron Lu 
2164efaceb1SAaron Lu 	rb = sis->swap_extent_root.rb_node;
2174efaceb1SAaron Lu 	while (rb) {
2184efaceb1SAaron Lu 		se = rb_entry(rb, struct swap_extent, rb_node);
2194efaceb1SAaron Lu 		if (offset < se->start_page)
2204efaceb1SAaron Lu 			rb = rb->rb_left;
2214efaceb1SAaron Lu 		else if (offset >= se->start_page + se->nr_pages)
2224efaceb1SAaron Lu 			rb = rb->rb_right;
2234efaceb1SAaron Lu 		else
2244efaceb1SAaron Lu 			return se;
2254efaceb1SAaron Lu 	}
2264efaceb1SAaron Lu 	/* It *must* be present */
2274efaceb1SAaron Lu 	BUG();
2284efaceb1SAaron Lu }
2294efaceb1SAaron Lu 
230caf6912fSJens Axboe sector_t swap_page_sector(struct page *page)
231caf6912fSJens Axboe {
232caf6912fSJens Axboe 	struct swap_info_struct *sis = page_swap_info(page);
233caf6912fSJens Axboe 	struct swap_extent *se;
234caf6912fSJens Axboe 	sector_t sector;
235caf6912fSJens Axboe 	pgoff_t offset;
236caf6912fSJens Axboe 
237caf6912fSJens Axboe 	offset = __page_file_index(page);
238caf6912fSJens Axboe 	se = offset_to_swap_extent(sis, offset);
239caf6912fSJens Axboe 	sector = se->start_block + (offset - se->start_page);
240caf6912fSJens Axboe 	return sector << (PAGE_SHIFT - 9);
241caf6912fSJens Axboe }
242caf6912fSJens Axboe 
2437992fde7SHugh Dickins /*
2447992fde7SHugh Dickins  * swap allocation tell device that a cluster of swap can now be discarded,
2457992fde7SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
2467992fde7SHugh Dickins  */
2477992fde7SHugh Dickins static void discard_swap_cluster(struct swap_info_struct *si,
2487992fde7SHugh Dickins 				 pgoff_t start_page, pgoff_t nr_pages)
2497992fde7SHugh Dickins {
2504efaceb1SAaron Lu 	struct swap_extent *se = offset_to_swap_extent(si, start_page);
2517992fde7SHugh Dickins 
2527992fde7SHugh Dickins 	while (nr_pages) {
2537992fde7SHugh Dickins 		pgoff_t offset = start_page - se->start_page;
2547992fde7SHugh Dickins 		sector_t start_block = se->start_block + offset;
255858a2990SHugh Dickins 		sector_t nr_blocks = se->nr_pages - offset;
2567992fde7SHugh Dickins 
2577992fde7SHugh Dickins 		if (nr_blocks > nr_pages)
2587992fde7SHugh Dickins 			nr_blocks = nr_pages;
2597992fde7SHugh Dickins 		start_page += nr_blocks;
2607992fde7SHugh Dickins 		nr_pages -= nr_blocks;
2617992fde7SHugh Dickins 
2627992fde7SHugh Dickins 		start_block <<= PAGE_SHIFT - 9;
2637992fde7SHugh Dickins 		nr_blocks <<= PAGE_SHIFT - 9;
2647992fde7SHugh Dickins 		if (blkdev_issue_discard(si->bdev, start_block,
26544abff2cSChristoph Hellwig 					nr_blocks, GFP_NOIO))
2667992fde7SHugh Dickins 			break;
2677992fde7SHugh Dickins 
2684efaceb1SAaron Lu 		se = next_se(se);
2697992fde7SHugh Dickins 	}
2707992fde7SHugh Dickins }
2717992fde7SHugh Dickins 
27238d8b4e6SHuang Ying #ifdef CONFIG_THP_SWAP
27338d8b4e6SHuang Ying #define SWAPFILE_CLUSTER	HPAGE_PMD_NR
274a448f2d0SHuang Ying 
275a448f2d0SHuang Ying #define swap_entry_size(size)	(size)
27638d8b4e6SHuang Ying #else
277048c27fdSHugh Dickins #define SWAPFILE_CLUSTER	256
278a448f2d0SHuang Ying 
279a448f2d0SHuang Ying /*
280a448f2d0SHuang Ying  * Define swap_entry_size() as constant to let compiler to optimize
281a448f2d0SHuang Ying  * out some code if !CONFIG_THP_SWAP
282a448f2d0SHuang Ying  */
283a448f2d0SHuang Ying #define swap_entry_size(size)	1
28438d8b4e6SHuang Ying #endif
285048c27fdSHugh Dickins #define LATENCY_LIMIT		256
286048c27fdSHugh Dickins 
2872a8f9449SShaohua Li static inline void cluster_set_flag(struct swap_cluster_info *info,
2882a8f9449SShaohua Li 	unsigned int flag)
2892a8f9449SShaohua Li {
2902a8f9449SShaohua Li 	info->flags = flag;
2912a8f9449SShaohua Li }
2922a8f9449SShaohua Li 
2932a8f9449SShaohua Li static inline unsigned int cluster_count(struct swap_cluster_info *info)
2942a8f9449SShaohua Li {
2952a8f9449SShaohua Li 	return info->data;
2962a8f9449SShaohua Li }
2972a8f9449SShaohua Li 
2982a8f9449SShaohua Li static inline void cluster_set_count(struct swap_cluster_info *info,
2992a8f9449SShaohua Li 				     unsigned int c)
3002a8f9449SShaohua Li {
3012a8f9449SShaohua Li 	info->data = c;
3022a8f9449SShaohua Li }
3032a8f9449SShaohua Li 
3042a8f9449SShaohua Li static inline void cluster_set_count_flag(struct swap_cluster_info *info,
3052a8f9449SShaohua Li 					 unsigned int c, unsigned int f)
3062a8f9449SShaohua Li {
3072a8f9449SShaohua Li 	info->flags = f;
3082a8f9449SShaohua Li 	info->data = c;
3092a8f9449SShaohua Li }
3102a8f9449SShaohua Li 
3112a8f9449SShaohua Li static inline unsigned int cluster_next(struct swap_cluster_info *info)
3122a8f9449SShaohua Li {
3132a8f9449SShaohua Li 	return info->data;
3142a8f9449SShaohua Li }
3152a8f9449SShaohua Li 
3162a8f9449SShaohua Li static inline void cluster_set_next(struct swap_cluster_info *info,
3172a8f9449SShaohua Li 				    unsigned int n)
3182a8f9449SShaohua Li {
3192a8f9449SShaohua Li 	info->data = n;
3202a8f9449SShaohua Li }
3212a8f9449SShaohua Li 
3222a8f9449SShaohua Li static inline void cluster_set_next_flag(struct swap_cluster_info *info,
3232a8f9449SShaohua Li 					 unsigned int n, unsigned int f)
3242a8f9449SShaohua Li {
3252a8f9449SShaohua Li 	info->flags = f;
3262a8f9449SShaohua Li 	info->data = n;
3272a8f9449SShaohua Li }
3282a8f9449SShaohua Li 
3292a8f9449SShaohua Li static inline bool cluster_is_free(struct swap_cluster_info *info)
3302a8f9449SShaohua Li {
3312a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_FREE;
3322a8f9449SShaohua Li }
3332a8f9449SShaohua Li 
3342a8f9449SShaohua Li static inline bool cluster_is_null(struct swap_cluster_info *info)
3352a8f9449SShaohua Li {
3362a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_NEXT_NULL;
3372a8f9449SShaohua Li }
3382a8f9449SShaohua Li 
3392a8f9449SShaohua Li static inline void cluster_set_null(struct swap_cluster_info *info)
3402a8f9449SShaohua Li {
3412a8f9449SShaohua Li 	info->flags = CLUSTER_FLAG_NEXT_NULL;
3422a8f9449SShaohua Li 	info->data = 0;
3432a8f9449SShaohua Li }
3442a8f9449SShaohua Li 
345e0709829SHuang Ying static inline bool cluster_is_huge(struct swap_cluster_info *info)
346e0709829SHuang Ying {
34733ee011eSHuang Ying 	if (IS_ENABLED(CONFIG_THP_SWAP))
348e0709829SHuang Ying 		return info->flags & CLUSTER_FLAG_HUGE;
34933ee011eSHuang Ying 	return false;
350e0709829SHuang Ying }
351e0709829SHuang Ying 
352e0709829SHuang Ying static inline void cluster_clear_huge(struct swap_cluster_info *info)
353e0709829SHuang Ying {
354e0709829SHuang Ying 	info->flags &= ~CLUSTER_FLAG_HUGE;
355e0709829SHuang Ying }
356e0709829SHuang Ying 
357235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
358235b6217SHuang, Ying 						     unsigned long offset)
359235b6217SHuang, Ying {
360235b6217SHuang, Ying 	struct swap_cluster_info *ci;
361235b6217SHuang, Ying 
362235b6217SHuang, Ying 	ci = si->cluster_info;
363235b6217SHuang, Ying 	if (ci) {
364235b6217SHuang, Ying 		ci += offset / SWAPFILE_CLUSTER;
365235b6217SHuang, Ying 		spin_lock(&ci->lock);
366235b6217SHuang, Ying 	}
367235b6217SHuang, Ying 	return ci;
368235b6217SHuang, Ying }
369235b6217SHuang, Ying 
370235b6217SHuang, Ying static inline void unlock_cluster(struct swap_cluster_info *ci)
371235b6217SHuang, Ying {
372235b6217SHuang, Ying 	if (ci)
373235b6217SHuang, Ying 		spin_unlock(&ci->lock);
374235b6217SHuang, Ying }
375235b6217SHuang, Ying 
37659d98bf3SHuang Ying /*
37759d98bf3SHuang Ying  * Determine the locking method in use for this device.  Return
37859d98bf3SHuang Ying  * swap_cluster_info if SSD-style cluster-based locking is in place.
37959d98bf3SHuang Ying  */
380235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster_or_swap_info(
38159d98bf3SHuang Ying 		struct swap_info_struct *si, unsigned long offset)
382235b6217SHuang, Ying {
383235b6217SHuang, Ying 	struct swap_cluster_info *ci;
384235b6217SHuang, Ying 
38559d98bf3SHuang Ying 	/* Try to use fine-grained SSD-style locking if available: */
386235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
38759d98bf3SHuang Ying 	/* Otherwise, fall back to traditional, coarse locking: */
388235b6217SHuang, Ying 	if (!ci)
389235b6217SHuang, Ying 		spin_lock(&si->lock);
390235b6217SHuang, Ying 
391235b6217SHuang, Ying 	return ci;
392235b6217SHuang, Ying }
393235b6217SHuang, Ying 
394235b6217SHuang, Ying static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
395235b6217SHuang, Ying 					       struct swap_cluster_info *ci)
396235b6217SHuang, Ying {
397235b6217SHuang, Ying 	if (ci)
398235b6217SHuang, Ying 		unlock_cluster(ci);
399235b6217SHuang, Ying 	else
400235b6217SHuang, Ying 		spin_unlock(&si->lock);
401235b6217SHuang, Ying }
402235b6217SHuang, Ying 
4036b534915SHuang Ying static inline bool cluster_list_empty(struct swap_cluster_list *list)
4046b534915SHuang Ying {
4056b534915SHuang Ying 	return cluster_is_null(&list->head);
4066b534915SHuang Ying }
4076b534915SHuang Ying 
4086b534915SHuang Ying static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
4096b534915SHuang Ying {
4106b534915SHuang Ying 	return cluster_next(&list->head);
4116b534915SHuang Ying }
4126b534915SHuang Ying 
4136b534915SHuang Ying static void cluster_list_init(struct swap_cluster_list *list)
4146b534915SHuang Ying {
4156b534915SHuang Ying 	cluster_set_null(&list->head);
4166b534915SHuang Ying 	cluster_set_null(&list->tail);
4176b534915SHuang Ying }
4186b534915SHuang Ying 
4196b534915SHuang Ying static void cluster_list_add_tail(struct swap_cluster_list *list,
4206b534915SHuang Ying 				  struct swap_cluster_info *ci,
4216b534915SHuang Ying 				  unsigned int idx)
4226b534915SHuang Ying {
4236b534915SHuang Ying 	if (cluster_list_empty(list)) {
4246b534915SHuang Ying 		cluster_set_next_flag(&list->head, idx, 0);
4256b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4266b534915SHuang Ying 	} else {
427235b6217SHuang, Ying 		struct swap_cluster_info *ci_tail;
4286b534915SHuang Ying 		unsigned int tail = cluster_next(&list->tail);
4296b534915SHuang Ying 
430235b6217SHuang, Ying 		/*
431235b6217SHuang, Ying 		 * Nested cluster lock, but both cluster locks are
432235b6217SHuang, Ying 		 * only acquired when we held swap_info_struct->lock
433235b6217SHuang, Ying 		 */
434235b6217SHuang, Ying 		ci_tail = ci + tail;
435235b6217SHuang, Ying 		spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
436235b6217SHuang, Ying 		cluster_set_next(ci_tail, idx);
4370ef017d1SHuang Ying 		spin_unlock(&ci_tail->lock);
4386b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4396b534915SHuang Ying 	}
4406b534915SHuang Ying }
4416b534915SHuang Ying 
4426b534915SHuang Ying static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
4436b534915SHuang Ying 					   struct swap_cluster_info *ci)
4446b534915SHuang Ying {
4456b534915SHuang Ying 	unsigned int idx;
4466b534915SHuang Ying 
4476b534915SHuang Ying 	idx = cluster_next(&list->head);
4486b534915SHuang Ying 	if (cluster_next(&list->tail) == idx) {
4496b534915SHuang Ying 		cluster_set_null(&list->head);
4506b534915SHuang Ying 		cluster_set_null(&list->tail);
4516b534915SHuang Ying 	} else
4526b534915SHuang Ying 		cluster_set_next_flag(&list->head,
4536b534915SHuang Ying 				      cluster_next(&ci[idx]), 0);
4546b534915SHuang Ying 
4556b534915SHuang Ying 	return idx;
4566b534915SHuang Ying }
4576b534915SHuang Ying 
458815c2c54SShaohua Li /* Add a cluster to discard list and schedule it to do discard */
459815c2c54SShaohua Li static void swap_cluster_schedule_discard(struct swap_info_struct *si,
460815c2c54SShaohua Li 		unsigned int idx)
461815c2c54SShaohua Li {
462815c2c54SShaohua Li 	/*
463bb243f7dSMiaohe Lin 	 * If scan_swap_map_slots() can't find a free cluster, it will check
464815c2c54SShaohua Li 	 * si->swap_map directly. To make sure the discarding cluster isn't
465bb243f7dSMiaohe Lin 	 * taken by scan_swap_map_slots(), mark the swap entries bad (occupied).
466bb243f7dSMiaohe Lin 	 * It will be cleared after discard
467815c2c54SShaohua Li 	 */
468815c2c54SShaohua Li 	memset(si->swap_map + idx * SWAPFILE_CLUSTER,
469815c2c54SShaohua Li 			SWAP_MAP_BAD, SWAPFILE_CLUSTER);
470815c2c54SShaohua Li 
4716b534915SHuang Ying 	cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
472815c2c54SShaohua Li 
473815c2c54SShaohua Li 	schedule_work(&si->discard_work);
474815c2c54SShaohua Li }
475815c2c54SShaohua Li 
47638d8b4e6SHuang Ying static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
47738d8b4e6SHuang Ying {
47838d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
47938d8b4e6SHuang Ying 
48038d8b4e6SHuang Ying 	cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
48138d8b4e6SHuang Ying 	cluster_list_add_tail(&si->free_clusters, ci, idx);
48238d8b4e6SHuang Ying }
48338d8b4e6SHuang Ying 
484815c2c54SShaohua Li /*
485815c2c54SShaohua Li  * Doing discard actually. After a cluster discard is finished, the cluster
486815c2c54SShaohua Li  * will be added to free cluster list. caller should hold si->lock.
487815c2c54SShaohua Li */
488815c2c54SShaohua Li static void swap_do_scheduled_discard(struct swap_info_struct *si)
489815c2c54SShaohua Li {
490235b6217SHuang, Ying 	struct swap_cluster_info *info, *ci;
491815c2c54SShaohua Li 	unsigned int idx;
492815c2c54SShaohua Li 
493815c2c54SShaohua Li 	info = si->cluster_info;
494815c2c54SShaohua Li 
4956b534915SHuang Ying 	while (!cluster_list_empty(&si->discard_clusters)) {
4966b534915SHuang Ying 		idx = cluster_list_del_first(&si->discard_clusters, info);
497815c2c54SShaohua Li 		spin_unlock(&si->lock);
498815c2c54SShaohua Li 
499815c2c54SShaohua Li 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
500815c2c54SShaohua Li 				SWAPFILE_CLUSTER);
501815c2c54SShaohua Li 
502815c2c54SShaohua Li 		spin_lock(&si->lock);
503235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
50438d8b4e6SHuang Ying 		__free_cluster(si, idx);
505815c2c54SShaohua Li 		memset(si->swap_map + idx * SWAPFILE_CLUSTER,
506815c2c54SShaohua Li 				0, SWAPFILE_CLUSTER);
507235b6217SHuang, Ying 		unlock_cluster(ci);
508815c2c54SShaohua Li 	}
509815c2c54SShaohua Li }
510815c2c54SShaohua Li 
511815c2c54SShaohua Li static void swap_discard_work(struct work_struct *work)
512815c2c54SShaohua Li {
513815c2c54SShaohua Li 	struct swap_info_struct *si;
514815c2c54SShaohua Li 
515815c2c54SShaohua Li 	si = container_of(work, struct swap_info_struct, discard_work);
516815c2c54SShaohua Li 
517815c2c54SShaohua Li 	spin_lock(&si->lock);
518815c2c54SShaohua Li 	swap_do_scheduled_discard(si);
519815c2c54SShaohua Li 	spin_unlock(&si->lock);
520815c2c54SShaohua Li }
521815c2c54SShaohua Li 
52263d8620eSMiaohe Lin static void swap_users_ref_free(struct percpu_ref *ref)
52363d8620eSMiaohe Lin {
52463d8620eSMiaohe Lin 	struct swap_info_struct *si;
52563d8620eSMiaohe Lin 
52663d8620eSMiaohe Lin 	si = container_of(ref, struct swap_info_struct, users);
52763d8620eSMiaohe Lin 	complete(&si->comp);
52863d8620eSMiaohe Lin }
52963d8620eSMiaohe Lin 
53038d8b4e6SHuang Ying static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
53138d8b4e6SHuang Ying {
53238d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
53338d8b4e6SHuang Ying 
53438d8b4e6SHuang Ying 	VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
53538d8b4e6SHuang Ying 	cluster_list_del_first(&si->free_clusters, ci);
53638d8b4e6SHuang Ying 	cluster_set_count_flag(ci + idx, 0, 0);
53738d8b4e6SHuang Ying }
53838d8b4e6SHuang Ying 
53938d8b4e6SHuang Ying static void free_cluster(struct swap_info_struct *si, unsigned long idx)
54038d8b4e6SHuang Ying {
54138d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info + idx;
54238d8b4e6SHuang Ying 
54338d8b4e6SHuang Ying 	VM_BUG_ON(cluster_count(ci) != 0);
54438d8b4e6SHuang Ying 	/*
54538d8b4e6SHuang Ying 	 * If the swap is discardable, prepare discard the cluster
54638d8b4e6SHuang Ying 	 * instead of free it immediately. The cluster will be freed
54738d8b4e6SHuang Ying 	 * after discard.
54838d8b4e6SHuang Ying 	 */
54938d8b4e6SHuang Ying 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
55038d8b4e6SHuang Ying 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
55138d8b4e6SHuang Ying 		swap_cluster_schedule_discard(si, idx);
55238d8b4e6SHuang Ying 		return;
55338d8b4e6SHuang Ying 	}
55438d8b4e6SHuang Ying 
55538d8b4e6SHuang Ying 	__free_cluster(si, idx);
55638d8b4e6SHuang Ying }
55738d8b4e6SHuang Ying 
5582a8f9449SShaohua Li /*
5592a8f9449SShaohua Li  * The cluster corresponding to page_nr will be used. The cluster will be
5602a8f9449SShaohua Li  * removed from free cluster list and its usage counter will be increased.
5612a8f9449SShaohua Li  */
5622a8f9449SShaohua Li static void inc_cluster_info_page(struct swap_info_struct *p,
5632a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5642a8f9449SShaohua Li {
5652a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5662a8f9449SShaohua Li 
5672a8f9449SShaohua Li 	if (!cluster_info)
5682a8f9449SShaohua Li 		return;
56938d8b4e6SHuang Ying 	if (cluster_is_free(&cluster_info[idx]))
57038d8b4e6SHuang Ying 		alloc_cluster(p, idx);
5712a8f9449SShaohua Li 
5722a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
5732a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5742a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) + 1);
5752a8f9449SShaohua Li }
5762a8f9449SShaohua Li 
5772a8f9449SShaohua Li /*
5782a8f9449SShaohua Li  * The cluster corresponding to page_nr decreases one usage. If the usage
5792a8f9449SShaohua Li  * counter becomes 0, which means no page in the cluster is in using, we can
5802a8f9449SShaohua Li  * optionally discard the cluster and add it to free cluster list.
5812a8f9449SShaohua Li  */
5822a8f9449SShaohua Li static void dec_cluster_info_page(struct swap_info_struct *p,
5832a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5842a8f9449SShaohua Li {
5852a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5862a8f9449SShaohua Li 
5872a8f9449SShaohua Li 	if (!cluster_info)
5882a8f9449SShaohua Li 		return;
5892a8f9449SShaohua Li 
5902a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
5912a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5922a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) - 1);
5932a8f9449SShaohua Li 
59438d8b4e6SHuang Ying 	if (cluster_count(&cluster_info[idx]) == 0)
59538d8b4e6SHuang Ying 		free_cluster(p, idx);
5962a8f9449SShaohua Li }
5972a8f9449SShaohua Li 
5982a8f9449SShaohua Li /*
599bb243f7dSMiaohe Lin  * It's possible scan_swap_map_slots() uses a free cluster in the middle of free
6002a8f9449SShaohua Li  * cluster list. Avoiding such abuse to avoid list corruption.
6012a8f9449SShaohua Li  */
602ebc2a1a6SShaohua Li static bool
603ebc2a1a6SShaohua Li scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
6042a8f9449SShaohua Li 	unsigned long offset)
6052a8f9449SShaohua Li {
606ebc2a1a6SShaohua Li 	struct percpu_cluster *percpu_cluster;
607ebc2a1a6SShaohua Li 	bool conflict;
608ebc2a1a6SShaohua Li 
6092a8f9449SShaohua Li 	offset /= SWAPFILE_CLUSTER;
6106b534915SHuang Ying 	conflict = !cluster_list_empty(&si->free_clusters) &&
6116b534915SHuang Ying 		offset != cluster_list_first(&si->free_clusters) &&
6122a8f9449SShaohua Li 		cluster_is_free(&si->cluster_info[offset]);
613ebc2a1a6SShaohua Li 
614ebc2a1a6SShaohua Li 	if (!conflict)
615ebc2a1a6SShaohua Li 		return false;
616ebc2a1a6SShaohua Li 
617ebc2a1a6SShaohua Li 	percpu_cluster = this_cpu_ptr(si->percpu_cluster);
618ebc2a1a6SShaohua Li 	cluster_set_null(&percpu_cluster->index);
619ebc2a1a6SShaohua Li 	return true;
620ebc2a1a6SShaohua Li }
621ebc2a1a6SShaohua Li 
622ebc2a1a6SShaohua Li /*
623ebc2a1a6SShaohua Li  * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
624ebc2a1a6SShaohua Li  * might involve allocating a new cluster for current CPU too.
625ebc2a1a6SShaohua Li  */
62636005baeSTim Chen static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
627ebc2a1a6SShaohua Li 	unsigned long *offset, unsigned long *scan_base)
628ebc2a1a6SShaohua Li {
629ebc2a1a6SShaohua Li 	struct percpu_cluster *cluster;
630235b6217SHuang, Ying 	struct swap_cluster_info *ci;
631235b6217SHuang, Ying 	unsigned long tmp, max;
632ebc2a1a6SShaohua Li 
633ebc2a1a6SShaohua Li new_cluster:
634ebc2a1a6SShaohua Li 	cluster = this_cpu_ptr(si->percpu_cluster);
635ebc2a1a6SShaohua Li 	if (cluster_is_null(&cluster->index)) {
6366b534915SHuang Ying 		if (!cluster_list_empty(&si->free_clusters)) {
6376b534915SHuang Ying 			cluster->index = si->free_clusters.head;
638ebc2a1a6SShaohua Li 			cluster->next = cluster_next(&cluster->index) *
639ebc2a1a6SShaohua Li 					SWAPFILE_CLUSTER;
6406b534915SHuang Ying 		} else if (!cluster_list_empty(&si->discard_clusters)) {
641ebc2a1a6SShaohua Li 			/*
642ebc2a1a6SShaohua Li 			 * we don't have free cluster but have some clusters in
64349070588SHuang Ying 			 * discarding, do discard now and reclaim them, then
64449070588SHuang Ying 			 * reread cluster_next_cpu since we dropped si->lock
645ebc2a1a6SShaohua Li 			 */
646ebc2a1a6SShaohua Li 			swap_do_scheduled_discard(si);
64749070588SHuang Ying 			*scan_base = this_cpu_read(*si->cluster_next_cpu);
64849070588SHuang Ying 			*offset = *scan_base;
649ebc2a1a6SShaohua Li 			goto new_cluster;
650ebc2a1a6SShaohua Li 		} else
65136005baeSTim Chen 			return false;
652ebc2a1a6SShaohua Li 	}
653ebc2a1a6SShaohua Li 
654ebc2a1a6SShaohua Li 	/*
655ebc2a1a6SShaohua Li 	 * Other CPUs can use our cluster if they can't find a free cluster,
656ebc2a1a6SShaohua Li 	 * check if there is still free entry in the cluster
657ebc2a1a6SShaohua Li 	 */
658ebc2a1a6SShaohua Li 	tmp = cluster->next;
659235b6217SHuang, Ying 	max = min_t(unsigned long, si->max,
660235b6217SHuang, Ying 		    (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
6617b9e2de1SWei Yang 	if (tmp < max) {
662235b6217SHuang, Ying 		ci = lock_cluster(si, tmp);
663235b6217SHuang, Ying 		while (tmp < max) {
6640fd0e19eSWei Yang 			if (!si->swap_map[tmp])
665ebc2a1a6SShaohua Li 				break;
666ebc2a1a6SShaohua Li 			tmp++;
667ebc2a1a6SShaohua Li 		}
668235b6217SHuang, Ying 		unlock_cluster(ci);
6697b9e2de1SWei Yang 	}
6700fd0e19eSWei Yang 	if (tmp >= max) {
671ebc2a1a6SShaohua Li 		cluster_set_null(&cluster->index);
672ebc2a1a6SShaohua Li 		goto new_cluster;
673ebc2a1a6SShaohua Li 	}
674ebc2a1a6SShaohua Li 	cluster->next = tmp + 1;
675ebc2a1a6SShaohua Li 	*offset = tmp;
676ebc2a1a6SShaohua Li 	*scan_base = tmp;
677fdff1debSWei Yang 	return true;
6782a8f9449SShaohua Li }
6792a8f9449SShaohua Li 
680a2468cc9SAaron Lu static void __del_from_avail_list(struct swap_info_struct *p)
681a2468cc9SAaron Lu {
682a2468cc9SAaron Lu 	int nid;
683a2468cc9SAaron Lu 
6846fe7d6b9SRongwei Wang 	assert_spin_locked(&p->lock);
685a2468cc9SAaron Lu 	for_each_node(nid)
686a2468cc9SAaron Lu 		plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
687a2468cc9SAaron Lu }
688a2468cc9SAaron Lu 
689a2468cc9SAaron Lu static void del_from_avail_list(struct swap_info_struct *p)
690a2468cc9SAaron Lu {
691a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
692a2468cc9SAaron Lu 	__del_from_avail_list(p);
693a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
694a2468cc9SAaron Lu }
695a2468cc9SAaron Lu 
69638d8b4e6SHuang Ying static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
69738d8b4e6SHuang Ying 			     unsigned int nr_entries)
69838d8b4e6SHuang Ying {
69938d8b4e6SHuang Ying 	unsigned int end = offset + nr_entries - 1;
70038d8b4e6SHuang Ying 
70138d8b4e6SHuang Ying 	if (offset == si->lowest_bit)
70238d8b4e6SHuang Ying 		si->lowest_bit += nr_entries;
70338d8b4e6SHuang Ying 	if (end == si->highest_bit)
704a449bf58SQian Cai 		WRITE_ONCE(si->highest_bit, si->highest_bit - nr_entries);
705c8945306SMiaohe Lin 	WRITE_ONCE(si->inuse_pages, si->inuse_pages + nr_entries);
70638d8b4e6SHuang Ying 	if (si->inuse_pages == si->pages) {
70738d8b4e6SHuang Ying 		si->lowest_bit = si->max;
70838d8b4e6SHuang Ying 		si->highest_bit = 0;
709a2468cc9SAaron Lu 		del_from_avail_list(si);
71038d8b4e6SHuang Ying 	}
71138d8b4e6SHuang Ying }
71238d8b4e6SHuang Ying 
713a2468cc9SAaron Lu static void add_to_avail_list(struct swap_info_struct *p)
714a2468cc9SAaron Lu {
715a2468cc9SAaron Lu 	int nid;
716a2468cc9SAaron Lu 
717a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
71867490031SMa Wupeng 	for_each_node(nid)
719a2468cc9SAaron Lu 		plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
720a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
721a2468cc9SAaron Lu }
722a2468cc9SAaron Lu 
72338d8b4e6SHuang Ying static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
72438d8b4e6SHuang Ying 			    unsigned int nr_entries)
72538d8b4e6SHuang Ying {
7263852f676SJoonsoo Kim 	unsigned long begin = offset;
72738d8b4e6SHuang Ying 	unsigned long end = offset + nr_entries - 1;
72838d8b4e6SHuang Ying 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
72938d8b4e6SHuang Ying 
73038d8b4e6SHuang Ying 	if (offset < si->lowest_bit)
73138d8b4e6SHuang Ying 		si->lowest_bit = offset;
73238d8b4e6SHuang Ying 	if (end > si->highest_bit) {
73338d8b4e6SHuang Ying 		bool was_full = !si->highest_bit;
73438d8b4e6SHuang Ying 
735a449bf58SQian Cai 		WRITE_ONCE(si->highest_bit, end);
736a2468cc9SAaron Lu 		if (was_full && (si->flags & SWP_WRITEOK))
737a2468cc9SAaron Lu 			add_to_avail_list(si);
73838d8b4e6SHuang Ying 	}
73938d8b4e6SHuang Ying 	atomic_long_add(nr_entries, &nr_swap_pages);
740c8945306SMiaohe Lin 	WRITE_ONCE(si->inuse_pages, si->inuse_pages - nr_entries);
74138d8b4e6SHuang Ying 	if (si->flags & SWP_BLKDEV)
74238d8b4e6SHuang Ying 		swap_slot_free_notify =
74338d8b4e6SHuang Ying 			si->bdev->bd_disk->fops->swap_slot_free_notify;
74438d8b4e6SHuang Ying 	else
74538d8b4e6SHuang Ying 		swap_slot_free_notify = NULL;
74638d8b4e6SHuang Ying 	while (offset <= end) {
7478a84802eSSteven Price 		arch_swap_invalidate_page(si->type, offset);
74842c06a0eSJohannes Weiner 		zswap_invalidate(si->type, offset);
74938d8b4e6SHuang Ying 		if (swap_slot_free_notify)
75038d8b4e6SHuang Ying 			swap_slot_free_notify(si->bdev, offset);
75138d8b4e6SHuang Ying 		offset++;
75238d8b4e6SHuang Ying 	}
7533852f676SJoonsoo Kim 	clear_shadow_from_swap_cache(si->type, begin, end);
75438d8b4e6SHuang Ying }
75538d8b4e6SHuang Ying 
75649070588SHuang Ying static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
75749070588SHuang Ying {
75849070588SHuang Ying 	unsigned long prev;
75949070588SHuang Ying 
76049070588SHuang Ying 	if (!(si->flags & SWP_SOLIDSTATE)) {
76149070588SHuang Ying 		si->cluster_next = next;
76249070588SHuang Ying 		return;
76349070588SHuang Ying 	}
76449070588SHuang Ying 
76549070588SHuang Ying 	prev = this_cpu_read(*si->cluster_next_cpu);
76649070588SHuang Ying 	/*
76749070588SHuang Ying 	 * Cross the swap address space size aligned trunk, choose
76849070588SHuang Ying 	 * another trunk randomly to avoid lock contention on swap
76949070588SHuang Ying 	 * address space if possible.
77049070588SHuang Ying 	 */
77149070588SHuang Ying 	if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=
77249070588SHuang Ying 	    (next >> SWAP_ADDRESS_SPACE_SHIFT)) {
77349070588SHuang Ying 		/* No free swap slots available */
77449070588SHuang Ying 		if (si->highest_bit <= si->lowest_bit)
77549070588SHuang Ying 			return;
776e8a533cbSJason A. Donenfeld 		next = get_random_u32_inclusive(si->lowest_bit, si->highest_bit);
77749070588SHuang Ying 		next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
77849070588SHuang Ying 		next = max_t(unsigned int, next, si->lowest_bit);
77949070588SHuang Ying 	}
78049070588SHuang Ying 	this_cpu_write(*si->cluster_next_cpu, next);
78149070588SHuang Ying }
78249070588SHuang Ying 
7834b9ae842SMiaohe Lin static bool swap_offset_available_and_locked(struct swap_info_struct *si,
7844b9ae842SMiaohe Lin 					     unsigned long offset)
7854b9ae842SMiaohe Lin {
7864b9ae842SMiaohe Lin 	if (data_race(!si->swap_map[offset])) {
7874b9ae842SMiaohe Lin 		spin_lock(&si->lock);
7884b9ae842SMiaohe Lin 		return true;
7894b9ae842SMiaohe Lin 	}
7904b9ae842SMiaohe Lin 
7914b9ae842SMiaohe Lin 	if (vm_swap_full() && READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
7924b9ae842SMiaohe Lin 		spin_lock(&si->lock);
7934b9ae842SMiaohe Lin 		return true;
7944b9ae842SMiaohe Lin 	}
7954b9ae842SMiaohe Lin 
7964b9ae842SMiaohe Lin 	return false;
7974b9ae842SMiaohe Lin }
7984b9ae842SMiaohe Lin 
79936005baeSTim Chen static int scan_swap_map_slots(struct swap_info_struct *si,
80036005baeSTim Chen 			       unsigned char usage, int nr,
80136005baeSTim Chen 			       swp_entry_t slots[])
8021da177e4SLinus Torvalds {
803235b6217SHuang, Ying 	struct swap_cluster_info *ci;
804ebebbbe9SHugh Dickins 	unsigned long offset;
805c60aa176SHugh Dickins 	unsigned long scan_base;
8067992fde7SHugh Dickins 	unsigned long last_in_cluster = 0;
807048c27fdSHugh Dickins 	int latency_ration = LATENCY_LIMIT;
80836005baeSTim Chen 	int n_ret = 0;
809ed43af10SHuang Ying 	bool scanned_many = false;
81036005baeSTim Chen 
8117dfad418SHugh Dickins 	/*
8127dfad418SHugh Dickins 	 * We try to cluster swap pages by allocating them sequentially
8137dfad418SHugh Dickins 	 * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
8147dfad418SHugh Dickins 	 * way, however, we resort to first-free allocation, starting
8157dfad418SHugh Dickins 	 * a new cluster.  This prevents us from scattering swap pages
8167dfad418SHugh Dickins 	 * all over the entire swap partition, so that we reduce
8177dfad418SHugh Dickins 	 * overall disk seek times between swap pages.  -- sct
8187dfad418SHugh Dickins 	 * But we do now try to find an empty cluster.  -Andrea
819c60aa176SHugh Dickins 	 * And we let swap pages go all over an SSD partition.  Hugh
8201da177e4SLinus Torvalds 	 */
8217dfad418SHugh Dickins 
82252b7efdbSHugh Dickins 	si->flags += SWP_SCANNING;
82349070588SHuang Ying 	/*
82449070588SHuang Ying 	 * Use percpu scan base for SSD to reduce lock contention on
82549070588SHuang Ying 	 * cluster and swap cache.  For HDD, sequential access is more
82649070588SHuang Ying 	 * important.
82749070588SHuang Ying 	 */
82849070588SHuang Ying 	if (si->flags & SWP_SOLIDSTATE)
82949070588SHuang Ying 		scan_base = this_cpu_read(*si->cluster_next_cpu);
83049070588SHuang Ying 	else
83149070588SHuang Ying 		scan_base = si->cluster_next;
83249070588SHuang Ying 	offset = scan_base;
833ebebbbe9SHugh Dickins 
834ebc2a1a6SShaohua Li 	/* SSD algorithm */
835ebc2a1a6SShaohua Li 	if (si->cluster_info) {
836bd2d18daSWei Yang 		if (!scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
83736005baeSTim Chen 			goto scan;
838f4eaf51aSWei Yang 	} else if (unlikely(!si->cluster_nr--)) {
839ebc2a1a6SShaohua Li 		if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
840ebc2a1a6SShaohua Li 			si->cluster_nr = SWAPFILE_CLUSTER - 1;
8412a8f9449SShaohua Li 			goto checks;
8422a8f9449SShaohua Li 		}
8432a8f9449SShaohua Li 
844ec8acf20SShaohua Li 		spin_unlock(&si->lock);
8457dfad418SHugh Dickins 
846c60aa176SHugh Dickins 		/*
847c60aa176SHugh Dickins 		 * If seek is expensive, start searching for new cluster from
848c60aa176SHugh Dickins 		 * start of partition, to minimize the span of allocated swap.
84950088c44SChen Yucong 		 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
85050088c44SChen Yucong 		 * case, just handled by scan_swap_map_try_ssd_cluster() above.
851c60aa176SHugh Dickins 		 */
852c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
8537dfad418SHugh Dickins 		last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
8547dfad418SHugh Dickins 
8557dfad418SHugh Dickins 		/* Locate the first empty (unaligned) cluster */
8567dfad418SHugh Dickins 		for (; last_in_cluster <= si->highest_bit; offset++) {
8571da177e4SLinus Torvalds 			if (si->swap_map[offset])
8587dfad418SHugh Dickins 				last_in_cluster = offset + SWAPFILE_CLUSTER;
8597dfad418SHugh Dickins 			else if (offset == last_in_cluster) {
860ec8acf20SShaohua Li 				spin_lock(&si->lock);
861ebebbbe9SHugh Dickins 				offset -= SWAPFILE_CLUSTER - 1;
862ebebbbe9SHugh Dickins 				si->cluster_next = offset;
863ebebbbe9SHugh Dickins 				si->cluster_nr = SWAPFILE_CLUSTER - 1;
864ebebbbe9SHugh Dickins 				goto checks;
8657dfad418SHugh Dickins 			}
866048c27fdSHugh Dickins 			if (unlikely(--latency_ration < 0)) {
867048c27fdSHugh Dickins 				cond_resched();
868048c27fdSHugh Dickins 				latency_ration = LATENCY_LIMIT;
869048c27fdSHugh Dickins 			}
8707dfad418SHugh Dickins 		}
871ebebbbe9SHugh Dickins 
872c60aa176SHugh Dickins 		offset = scan_base;
873ec8acf20SShaohua Li 		spin_lock(&si->lock);
874ebebbbe9SHugh Dickins 		si->cluster_nr = SWAPFILE_CLUSTER - 1;
8757dfad418SHugh Dickins 	}
8767dfad418SHugh Dickins 
877ebebbbe9SHugh Dickins checks:
878ebc2a1a6SShaohua Li 	if (si->cluster_info) {
87936005baeSTim Chen 		while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
88036005baeSTim Chen 		/* take a break if we already got some slots */
88136005baeSTim Chen 			if (n_ret)
88236005baeSTim Chen 				goto done;
88336005baeSTim Chen 			if (!scan_swap_map_try_ssd_cluster(si, &offset,
88436005baeSTim Chen 							&scan_base))
88536005baeSTim Chen 				goto scan;
88636005baeSTim Chen 		}
887ebc2a1a6SShaohua Li 	}
888ebebbbe9SHugh Dickins 	if (!(si->flags & SWP_WRITEOK))
88952b7efdbSHugh Dickins 		goto no_page;
8907dfad418SHugh Dickins 	if (!si->highest_bit)
8917dfad418SHugh Dickins 		goto no_page;
892ebebbbe9SHugh Dickins 	if (offset > si->highest_bit)
893c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
894c9e44410SKAMEZAWA Hiroyuki 
895235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
896b73d7fceSHugh Dickins 	/* reuse swap entry of cache-only swap if not busy. */
897b73d7fceSHugh Dickins 	if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
898c9e44410SKAMEZAWA Hiroyuki 		int swap_was_freed;
899235b6217SHuang, Ying 		unlock_cluster(ci);
900ec8acf20SShaohua Li 		spin_unlock(&si->lock);
901bcd49e86SHuang Ying 		swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
902ec8acf20SShaohua Li 		spin_lock(&si->lock);
903c9e44410SKAMEZAWA Hiroyuki 		/* entry was freed successfully, try to use this again */
904c9e44410SKAMEZAWA Hiroyuki 		if (swap_was_freed)
905c9e44410SKAMEZAWA Hiroyuki 			goto checks;
906c9e44410SKAMEZAWA Hiroyuki 		goto scan; /* check next one */
907c9e44410SKAMEZAWA Hiroyuki 	}
908c9e44410SKAMEZAWA Hiroyuki 
909235b6217SHuang, Ying 	if (si->swap_map[offset]) {
910235b6217SHuang, Ying 		unlock_cluster(ci);
91136005baeSTim Chen 		if (!n_ret)
912ebebbbe9SHugh Dickins 			goto scan;
91336005baeSTim Chen 		else
91436005baeSTim Chen 			goto done;
915235b6217SHuang, Ying 	}
916a449bf58SQian Cai 	WRITE_ONCE(si->swap_map[offset], usage);
9172872bb2dSHuang Ying 	inc_cluster_info_page(si, si->cluster_info, offset);
9182872bb2dSHuang Ying 	unlock_cluster(ci);
919ebebbbe9SHugh Dickins 
92038d8b4e6SHuang Ying 	swap_range_alloc(si, offset, 1);
92136005baeSTim Chen 	slots[n_ret++] = swp_entry(si->type, offset);
9227992fde7SHugh Dickins 
92336005baeSTim Chen 	/* got enough slots or reach max slots? */
92436005baeSTim Chen 	if ((n_ret == nr) || (offset >= si->highest_bit))
92536005baeSTim Chen 		goto done;
92636005baeSTim Chen 
92736005baeSTim Chen 	/* search for next available slot */
92836005baeSTim Chen 
92936005baeSTim Chen 	/* time to take a break? */
93036005baeSTim Chen 	if (unlikely(--latency_ration < 0)) {
93136005baeSTim Chen 		if (n_ret)
93236005baeSTim Chen 			goto done;
93336005baeSTim Chen 		spin_unlock(&si->lock);
93436005baeSTim Chen 		cond_resched();
93536005baeSTim Chen 		spin_lock(&si->lock);
93636005baeSTim Chen 		latency_ration = LATENCY_LIMIT;
93736005baeSTim Chen 	}
93836005baeSTim Chen 
93936005baeSTim Chen 	/* try to get more slots in cluster */
94036005baeSTim Chen 	if (si->cluster_info) {
94136005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
94236005baeSTim Chen 			goto checks;
943f4eaf51aSWei Yang 	} else if (si->cluster_nr && !si->swap_map[++offset]) {
94436005baeSTim Chen 		/* non-ssd case, still more slots in cluster? */
94536005baeSTim Chen 		--si->cluster_nr;
94636005baeSTim Chen 		goto checks;
94736005baeSTim Chen 	}
94836005baeSTim Chen 
949ed43af10SHuang Ying 	/*
950ed43af10SHuang Ying 	 * Even if there's no free clusters available (fragmented),
951ed43af10SHuang Ying 	 * try to scan a little more quickly with lock held unless we
952ed43af10SHuang Ying 	 * have scanned too many slots already.
953ed43af10SHuang Ying 	 */
954ed43af10SHuang Ying 	if (!scanned_many) {
955ed43af10SHuang Ying 		unsigned long scan_limit;
956ed43af10SHuang Ying 
957ed43af10SHuang Ying 		if (offset < scan_base)
958ed43af10SHuang Ying 			scan_limit = scan_base;
959ed43af10SHuang Ying 		else
960ed43af10SHuang Ying 			scan_limit = si->highest_bit;
961ed43af10SHuang Ying 		for (; offset <= scan_limit && --latency_ration > 0;
962ed43af10SHuang Ying 		     offset++) {
963ed43af10SHuang Ying 			if (!si->swap_map[offset])
964ed43af10SHuang Ying 				goto checks;
965ed43af10SHuang Ying 		}
966ed43af10SHuang Ying 	}
967ed43af10SHuang Ying 
96836005baeSTim Chen done:
96949070588SHuang Ying 	set_cluster_next(si, offset + 1);
97036005baeSTim Chen 	si->flags -= SWP_SCANNING;
97136005baeSTim Chen 	return n_ret;
9727dfad418SHugh Dickins 
973ebebbbe9SHugh Dickins scan:
974ec8acf20SShaohua Li 	spin_unlock(&si->lock);
975a449bf58SQian Cai 	while (++offset <= READ_ONCE(si->highest_bit)) {
976048c27fdSHugh Dickins 		if (unlikely(--latency_ration < 0)) {
977048c27fdSHugh Dickins 			cond_resched();
978048c27fdSHugh Dickins 			latency_ration = LATENCY_LIMIT;
979ed43af10SHuang Ying 			scanned_many = true;
980048c27fdSHugh Dickins 		}
981de1ccfb6SChen Wandun 		if (swap_offset_available_and_locked(si, offset))
982de1ccfb6SChen Wandun 			goto checks;
98352b7efdbSHugh Dickins 	}
984c60aa176SHugh Dickins 	offset = si->lowest_bit;
985a5998061SJamie Liu 	while (offset < scan_base) {
986c60aa176SHugh Dickins 		if (unlikely(--latency_ration < 0)) {
987c60aa176SHugh Dickins 			cond_resched();
988c60aa176SHugh Dickins 			latency_ration = LATENCY_LIMIT;
989ed43af10SHuang Ying 			scanned_many = true;
990c60aa176SHugh Dickins 		}
991de1ccfb6SChen Wandun 		if (swap_offset_available_and_locked(si, offset))
992de1ccfb6SChen Wandun 			goto checks;
993a5998061SJamie Liu 		offset++;
994c60aa176SHugh Dickins 	}
995ec8acf20SShaohua Li 	spin_lock(&si->lock);
9967dfad418SHugh Dickins 
9977dfad418SHugh Dickins no_page:
99852b7efdbSHugh Dickins 	si->flags -= SWP_SCANNING;
99936005baeSTim Chen 	return n_ret;
10001da177e4SLinus Torvalds }
10011da177e4SLinus Torvalds 
100238d8b4e6SHuang Ying static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
100338d8b4e6SHuang Ying {
100438d8b4e6SHuang Ying 	unsigned long idx;
100538d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
1006661c7566SMiaohe Lin 	unsigned long offset;
100738d8b4e6SHuang Ying 
1008fe5266d5SHuang Ying 	/*
1009fe5266d5SHuang Ying 	 * Should not even be attempting cluster allocations when huge
1010fe5266d5SHuang Ying 	 * page swap is disabled.  Warn and fail the allocation.
1011fe5266d5SHuang Ying 	 */
1012fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP)) {
1013fe5266d5SHuang Ying 		VM_WARN_ON_ONCE(1);
1014fe5266d5SHuang Ying 		return 0;
1015fe5266d5SHuang Ying 	}
1016fe5266d5SHuang Ying 
101738d8b4e6SHuang Ying 	if (cluster_list_empty(&si->free_clusters))
101838d8b4e6SHuang Ying 		return 0;
101938d8b4e6SHuang Ying 
102038d8b4e6SHuang Ying 	idx = cluster_list_first(&si->free_clusters);
102138d8b4e6SHuang Ying 	offset = idx * SWAPFILE_CLUSTER;
102238d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
102338d8b4e6SHuang Ying 	alloc_cluster(si, idx);
1024e0709829SHuang Ying 	cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
102538d8b4e6SHuang Ying 
1026661c7566SMiaohe Lin 	memset(si->swap_map + offset, SWAP_HAS_CACHE, SWAPFILE_CLUSTER);
102738d8b4e6SHuang Ying 	unlock_cluster(ci);
102838d8b4e6SHuang Ying 	swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
102938d8b4e6SHuang Ying 	*slot = swp_entry(si->type, offset);
103038d8b4e6SHuang Ying 
103138d8b4e6SHuang Ying 	return 1;
103238d8b4e6SHuang Ying }
103338d8b4e6SHuang Ying 
103438d8b4e6SHuang Ying static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
103538d8b4e6SHuang Ying {
103638d8b4e6SHuang Ying 	unsigned long offset = idx * SWAPFILE_CLUSTER;
103738d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
103838d8b4e6SHuang Ying 
103938d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
1040979aafa5SHuang Ying 	memset(si->swap_map + offset, 0, SWAPFILE_CLUSTER);
104138d8b4e6SHuang Ying 	cluster_set_count_flag(ci, 0, 0);
104238d8b4e6SHuang Ying 	free_cluster(si, idx);
104338d8b4e6SHuang Ying 	unlock_cluster(ci);
104438d8b4e6SHuang Ying 	swap_range_free(si, offset, SWAPFILE_CLUSTER);
104538d8b4e6SHuang Ying }
104638d8b4e6SHuang Ying 
10475d5e8f19SHuang Ying int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_size)
10481da177e4SLinus Torvalds {
10495d5e8f19SHuang Ying 	unsigned long size = swap_entry_size(entry_size);
1050adfab836SDan Streetman 	struct swap_info_struct *si, *next;
105136005baeSTim Chen 	long avail_pgs;
105236005baeSTim Chen 	int n_ret = 0;
1053a2468cc9SAaron Lu 	int node;
10541da177e4SLinus Torvalds 
105538d8b4e6SHuang Ying 	/* Only single cluster request supported */
10565d5e8f19SHuang Ying 	WARN_ON_ONCE(n_goal > 1 && size == SWAPFILE_CLUSTER);
105738d8b4e6SHuang Ying 
1058b50da6e9SZhaoyang Huang 	spin_lock(&swap_avail_lock);
1059b50da6e9SZhaoyang Huang 
10605d5e8f19SHuang Ying 	avail_pgs = atomic_long_read(&nr_swap_pages) / size;
1061b50da6e9SZhaoyang Huang 	if (avail_pgs <= 0) {
1062b50da6e9SZhaoyang Huang 		spin_unlock(&swap_avail_lock);
1063fb4f88dcSHugh Dickins 		goto noswap;
1064b50da6e9SZhaoyang Huang 	}
106536005baeSTim Chen 
106608d3090fSWei Yang 	n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
106736005baeSTim Chen 
10685d5e8f19SHuang Ying 	atomic_long_sub(n_goal * size, &nr_swap_pages);
10691da177e4SLinus Torvalds 
107018ab4d4cSDan Streetman start_over:
1071a2468cc9SAaron Lu 	node = numa_node_id();
1072a2468cc9SAaron Lu 	plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
107318ab4d4cSDan Streetman 		/* requeue si to after same-priority siblings */
1074a2468cc9SAaron Lu 		plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
107518ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
1076ec8acf20SShaohua Li 		spin_lock(&si->lock);
1077adfab836SDan Streetman 		if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
107818ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
1079a2468cc9SAaron Lu 			if (plist_node_empty(&si->avail_lists[node])) {
1080ec8acf20SShaohua Li 				spin_unlock(&si->lock);
108118ab4d4cSDan Streetman 				goto nextsi;
108218ab4d4cSDan Streetman 			}
108318ab4d4cSDan Streetman 			WARN(!si->highest_bit,
108418ab4d4cSDan Streetman 			     "swap_info %d in list but !highest_bit\n",
108518ab4d4cSDan Streetman 			     si->type);
108618ab4d4cSDan Streetman 			WARN(!(si->flags & SWP_WRITEOK),
108718ab4d4cSDan Streetman 			     "swap_info %d in list but !SWP_WRITEOK\n",
108818ab4d4cSDan Streetman 			     si->type);
1089a2468cc9SAaron Lu 			__del_from_avail_list(si);
109018ab4d4cSDan Streetman 			spin_unlock(&si->lock);
109118ab4d4cSDan Streetman 			goto nextsi;
1092ec8acf20SShaohua Li 		}
10935d5e8f19SHuang Ying 		if (size == SWAPFILE_CLUSTER) {
109441663430SGao Xiang 			if (si->flags & SWP_BLKDEV)
109538d8b4e6SHuang Ying 				n_ret = swap_alloc_cluster(si, swp_entries);
1096f0eea189SHuang Ying 		} else
109736005baeSTim Chen 			n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
109836005baeSTim Chen 						    n_goal, swp_entries);
1099ec8acf20SShaohua Li 		spin_unlock(&si->lock);
11005d5e8f19SHuang Ying 		if (n_ret || size == SWAPFILE_CLUSTER)
110136005baeSTim Chen 			goto check_out;
11027717fc1aSLonglong Xia 		cond_resched();
110336005baeSTim Chen 
110418ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
110518ab4d4cSDan Streetman nextsi:
1106adfab836SDan Streetman 		/*
1107adfab836SDan Streetman 		 * if we got here, it's likely that si was almost full before,
1108bb243f7dSMiaohe Lin 		 * and since scan_swap_map_slots() can drop the si->lock,
1109bb243f7dSMiaohe Lin 		 * multiple callers probably all tried to get a page from the
1110bb243f7dSMiaohe Lin 		 * same si and it filled up before we could get one; or, the si
1111bb243f7dSMiaohe Lin 		 * filled up between us dropping swap_avail_lock and taking
1112bb243f7dSMiaohe Lin 		 * si->lock. Since we dropped the swap_avail_lock, the
1113bb243f7dSMiaohe Lin 		 * swap_avail_head list may have been modified; so if next is
1114bb243f7dSMiaohe Lin 		 * still in the swap_avail_head list then try it, otherwise
1115bb243f7dSMiaohe Lin 		 * start over if we have not gotten any slots.
1116adfab836SDan Streetman 		 */
1117a2468cc9SAaron Lu 		if (plist_node_empty(&next->avail_lists[node]))
111818ab4d4cSDan Streetman 			goto start_over;
1119fb4f88dcSHugh Dickins 	}
1120fb4f88dcSHugh Dickins 
112118ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
112218ab4d4cSDan Streetman 
112336005baeSTim Chen check_out:
112436005baeSTim Chen 	if (n_ret < n_goal)
11255d5e8f19SHuang Ying 		atomic_long_add((long)(n_goal - n_ret) * size,
112638d8b4e6SHuang Ying 				&nr_swap_pages);
1127fb4f88dcSHugh Dickins noswap:
112836005baeSTim Chen 	return n_ret;
112936005baeSTim Chen }
113036005baeSTim Chen 
1131afba72b1SMiaohe Lin static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
11321da177e4SLinus Torvalds {
11331da177e4SLinus Torvalds 	struct swap_info_struct *p;
1134eb085574SHuang Ying 	unsigned long offset;
11351da177e4SLinus Torvalds 
11361da177e4SLinus Torvalds 	if (!entry.val)
11371da177e4SLinus Torvalds 		goto out;
1138eb085574SHuang Ying 	p = swp_swap_info(entry);
1139c10d38ccSDaniel Jordan 	if (!p)
11401da177e4SLinus Torvalds 		goto bad_nofile;
1141a449bf58SQian Cai 	if (data_race(!(p->flags & SWP_USED)))
11421da177e4SLinus Torvalds 		goto bad_device;
11431da177e4SLinus Torvalds 	offset = swp_offset(entry);
11441da177e4SLinus Torvalds 	if (offset >= p->max)
11451da177e4SLinus Torvalds 		goto bad_offset;
1146afba72b1SMiaohe Lin 	if (data_race(!p->swap_map[swp_offset(entry)]))
1147afba72b1SMiaohe Lin 		goto bad_free;
11481da177e4SLinus Torvalds 	return p;
11491da177e4SLinus Torvalds 
1150afba72b1SMiaohe Lin bad_free:
1151afba72b1SMiaohe Lin 	pr_err("%s: %s%08lx\n", __func__, Unused_offset, entry.val);
1152afba72b1SMiaohe Lin 	goto out;
11531da177e4SLinus Torvalds bad_offset:
1154cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
11551da177e4SLinus Torvalds 	goto out;
11561da177e4SLinus Torvalds bad_device:
1157cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Unused_file, entry.val);
11581da177e4SLinus Torvalds 	goto out;
11591da177e4SLinus Torvalds bad_nofile:
1160cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
11611da177e4SLinus Torvalds out:
11621da177e4SLinus Torvalds 	return NULL;
11631da177e4SLinus Torvalds }
11641da177e4SLinus Torvalds 
11657c00bafeSTim Chen static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
11667c00bafeSTim Chen 					struct swap_info_struct *q)
11677c00bafeSTim Chen {
11687c00bafeSTim Chen 	struct swap_info_struct *p;
11697c00bafeSTim Chen 
11707c00bafeSTim Chen 	p = _swap_info_get(entry);
11717c00bafeSTim Chen 
11727c00bafeSTim Chen 	if (p != q) {
11737c00bafeSTim Chen 		if (q != NULL)
11747c00bafeSTim Chen 			spin_unlock(&q->lock);
11757c00bafeSTim Chen 		if (p != NULL)
11767c00bafeSTim Chen 			spin_lock(&p->lock);
11777c00bafeSTim Chen 	}
11787c00bafeSTim Chen 	return p;
11797c00bafeSTim Chen }
11807c00bafeSTim Chen 
1181b32d5f32SHuang Ying static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1182b32d5f32SHuang Ying 					      unsigned long offset,
1183b32d5f32SHuang Ying 					      unsigned char usage)
1184235b6217SHuang, Ying {
11858d69aaeeSHugh Dickins 	unsigned char count;
11868d69aaeeSHugh Dickins 	unsigned char has_cache;
1187235b6217SHuang, Ying 
1188355cfa73SKAMEZAWA Hiroyuki 	count = p->swap_map[offset];
1189235b6217SHuang, Ying 
1190253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
1191253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
1192253d553bSHugh Dickins 
1193253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
1194253d553bSHugh Dickins 		VM_BUG_ON(!has_cache);
1195253d553bSHugh Dickins 		has_cache = 0;
1196aaa46865SHugh Dickins 	} else if (count == SWAP_MAP_SHMEM) {
1197aaa46865SHugh Dickins 		/*
1198aaa46865SHugh Dickins 		 * Or we could insist on shmem.c using a special
1199aaa46865SHugh Dickins 		 * swap_shmem_free() and free_shmem_swap_and_cache()...
1200aaa46865SHugh Dickins 		 */
1201aaa46865SHugh Dickins 		count = 0;
1202570a335bSHugh Dickins 	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1203570a335bSHugh Dickins 		if (count == COUNT_CONTINUED) {
1204570a335bSHugh Dickins 			if (swap_count_continued(p, offset, count))
1205570a335bSHugh Dickins 				count = SWAP_MAP_MAX | COUNT_CONTINUED;
1206570a335bSHugh Dickins 			else
1207570a335bSHugh Dickins 				count = SWAP_MAP_MAX;
1208570a335bSHugh Dickins 		} else
1209253d553bSHugh Dickins 			count--;
1210570a335bSHugh Dickins 	}
1211253d553bSHugh Dickins 
1212253d553bSHugh Dickins 	usage = count | has_cache;
1213a449bf58SQian Cai 	if (usage)
1214a449bf58SQian Cai 		WRITE_ONCE(p->swap_map[offset], usage);
1215a449bf58SQian Cai 	else
1216a449bf58SQian Cai 		WRITE_ONCE(p->swap_map[offset], SWAP_HAS_CACHE);
1217253d553bSHugh Dickins 
1218b32d5f32SHuang Ying 	return usage;
1219b32d5f32SHuang Ying }
1220b32d5f32SHuang Ying 
1221eb085574SHuang Ying /*
1222a95722a0SHuang Ying  * When we get a swap entry, if there aren't some other ways to
1223a95722a0SHuang Ying  * prevent swapoff, such as the folio in swap cache is locked, page
1224a95722a0SHuang Ying  * table lock is held, etc., the swap entry may become invalid because
1225a95722a0SHuang Ying  * of swapoff.  Then, we need to enclose all swap related functions
1226a95722a0SHuang Ying  * with get_swap_device() and put_swap_device(), unless the swap
1227a95722a0SHuang Ying  * functions call get/put_swap_device() by themselves.
1228a95722a0SHuang Ying  *
1229eb085574SHuang Ying  * Check whether swap entry is valid in the swap device.  If so,
1230eb085574SHuang Ying  * return pointer to swap_info_struct, and keep the swap entry valid
1231eb085574SHuang Ying  * via preventing the swap device from being swapoff, until
1232eb085574SHuang Ying  * put_swap_device() is called.  Otherwise return NULL.
1233eb085574SHuang Ying  *
1234eb085574SHuang Ying  * Notice that swapoff or swapoff+swapon can still happen before the
123563d8620eSMiaohe Lin  * percpu_ref_tryget_live() in get_swap_device() or after the
123663d8620eSMiaohe Lin  * percpu_ref_put() in put_swap_device() if there isn't any other way
1237a95722a0SHuang Ying  * to prevent swapoff.  The caller must be prepared for that.  For
1238a95722a0SHuang Ying  * example, the following situation is possible.
1239eb085574SHuang Ying  *
1240eb085574SHuang Ying  *   CPU1				CPU2
1241eb085574SHuang Ying  *   do_swap_page()
1242eb085574SHuang Ying  *     ...				swapoff+swapon
1243eb085574SHuang Ying  *     __read_swap_cache_async()
1244eb085574SHuang Ying  *       swapcache_prepare()
1245eb085574SHuang Ying  *         __swap_duplicate()
1246eb085574SHuang Ying  *           // check swap_map
1247eb085574SHuang Ying  *     // verify PTE not changed
1248eb085574SHuang Ying  *
1249eb085574SHuang Ying  * In __swap_duplicate(), the swap_map need to be checked before
1250eb085574SHuang Ying  * changing partly because the specified swap entry may be for another
1251eb085574SHuang Ying  * swap device which has been swapoff.  And in do_swap_page(), after
1252eb085574SHuang Ying  * the page is read from the swap device, the PTE is verified not
1253eb085574SHuang Ying  * changed with the page table locked to check whether the swap device
1254eb085574SHuang Ying  * has been swapoff or swapoff+swapon.
1255eb085574SHuang Ying  */
1256eb085574SHuang Ying struct swap_info_struct *get_swap_device(swp_entry_t entry)
1257eb085574SHuang Ying {
1258eb085574SHuang Ying 	struct swap_info_struct *si;
1259eb085574SHuang Ying 	unsigned long offset;
1260eb085574SHuang Ying 
1261eb085574SHuang Ying 	if (!entry.val)
1262eb085574SHuang Ying 		goto out;
1263eb085574SHuang Ying 	si = swp_swap_info(entry);
1264eb085574SHuang Ying 	if (!si)
1265eb085574SHuang Ying 		goto bad_nofile;
126663d8620eSMiaohe Lin 	if (!percpu_ref_tryget_live(&si->users))
126763d8620eSMiaohe Lin 		goto out;
126863d8620eSMiaohe Lin 	/*
126963d8620eSMiaohe Lin 	 * Guarantee the si->users are checked before accessing other
127063d8620eSMiaohe Lin 	 * fields of swap_info_struct.
127163d8620eSMiaohe Lin 	 *
127263d8620eSMiaohe Lin 	 * Paired with the spin_unlock() after setup_swap_info() in
127363d8620eSMiaohe Lin 	 * enable_swap_info().
127463d8620eSMiaohe Lin 	 */
127563d8620eSMiaohe Lin 	smp_rmb();
1276eb085574SHuang Ying 	offset = swp_offset(entry);
1277eb085574SHuang Ying 	if (offset >= si->max)
127863d8620eSMiaohe Lin 		goto put_out;
1279eb085574SHuang Ying 
1280eb085574SHuang Ying 	return si;
1281eb085574SHuang Ying bad_nofile:
1282eb085574SHuang Ying 	pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1283eb085574SHuang Ying out:
1284eb085574SHuang Ying 	return NULL;
128563d8620eSMiaohe Lin put_out:
128623b230baSMiaohe Lin 	pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
128763d8620eSMiaohe Lin 	percpu_ref_put(&si->users);
1288eb085574SHuang Ying 	return NULL;
1289eb085574SHuang Ying }
1290eb085574SHuang Ying 
1291b32d5f32SHuang Ying static unsigned char __swap_entry_free(struct swap_info_struct *p,
129233e16272SWei Yang 				       swp_entry_t entry)
1293b32d5f32SHuang Ying {
1294b32d5f32SHuang Ying 	struct swap_cluster_info *ci;
1295b32d5f32SHuang Ying 	unsigned long offset = swp_offset(entry);
129633e16272SWei Yang 	unsigned char usage;
1297b32d5f32SHuang Ying 
1298b32d5f32SHuang Ying 	ci = lock_cluster_or_swap_info(p, offset);
129933e16272SWei Yang 	usage = __swap_entry_free_locked(p, offset, 1);
13007c00bafeSTim Chen 	unlock_cluster_or_swap_info(p, ci);
130110e364daSHuang Ying 	if (!usage)
130210e364daSHuang Ying 		free_swap_slot(entry);
1303235b6217SHuang, Ying 
13047c00bafeSTim Chen 	return usage;
13057c00bafeSTim Chen }
13067c00bafeSTim Chen 
13077c00bafeSTim Chen static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
13087c00bafeSTim Chen {
13097c00bafeSTim Chen 	struct swap_cluster_info *ci;
13107c00bafeSTim Chen 	unsigned long offset = swp_offset(entry);
13117c00bafeSTim Chen 	unsigned char count;
13127c00bafeSTim Chen 
1313235b6217SHuang, Ying 	ci = lock_cluster(p, offset);
13147c00bafeSTim Chen 	count = p->swap_map[offset];
13157c00bafeSTim Chen 	VM_BUG_ON(count != SWAP_HAS_CACHE);
13167c00bafeSTim Chen 	p->swap_map[offset] = 0;
13172a8f9449SShaohua Li 	dec_cluster_info_page(p, p->cluster_info, offset);
1318235b6217SHuang, Ying 	unlock_cluster(ci);
13197c00bafeSTim Chen 
132038d8b4e6SHuang Ying 	mem_cgroup_uncharge_swap(entry, 1);
132138d8b4e6SHuang Ying 	swap_range_free(p, offset, 1);
13221da177e4SLinus Torvalds }
1323253d553bSHugh Dickins 
13241da177e4SLinus Torvalds /*
13251da177e4SLinus Torvalds  * Caller has made sure that the swap device corresponding to entry
13261da177e4SLinus Torvalds  * is still around or has not been recycled.
13271da177e4SLinus Torvalds  */
13281da177e4SLinus Torvalds void swap_free(swp_entry_t entry)
13291da177e4SLinus Torvalds {
13301da177e4SLinus Torvalds 	struct swap_info_struct *p;
13311da177e4SLinus Torvalds 
1332235b6217SHuang, Ying 	p = _swap_info_get(entry);
133310e364daSHuang Ying 	if (p)
133433e16272SWei Yang 		__swap_entry_free(p, entry);
13351da177e4SLinus Torvalds }
13361da177e4SLinus Torvalds 
13371da177e4SLinus Torvalds /*
1338cb4b86baSKAMEZAWA Hiroyuki  * Called after dropping swapcache to decrease refcnt to swap entries.
1339cb4b86baSKAMEZAWA Hiroyuki  */
13404081f744SMatthew Wilcox (Oracle) void put_swap_folio(struct folio *folio, swp_entry_t entry)
134138d8b4e6SHuang Ying {
134238d8b4e6SHuang Ying 	unsigned long offset = swp_offset(entry);
134338d8b4e6SHuang Ying 	unsigned long idx = offset / SWAPFILE_CLUSTER;
134438d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
134538d8b4e6SHuang Ying 	struct swap_info_struct *si;
134638d8b4e6SHuang Ying 	unsigned char *map;
1347a3aea839SHuang Ying 	unsigned int i, free_entries = 0;
1348a3aea839SHuang Ying 	unsigned char val;
13494081f744SMatthew Wilcox (Oracle) 	int size = swap_entry_size(folio_nr_pages(folio));
1350fe5266d5SHuang Ying 
1351a3aea839SHuang Ying 	si = _swap_info_get(entry);
135238d8b4e6SHuang Ying 	if (!si)
135338d8b4e6SHuang Ying 		return;
135438d8b4e6SHuang Ying 
1355c2343d27SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1356a448f2d0SHuang Ying 	if (size == SWAPFILE_CLUSTER) {
1357e0709829SHuang Ying 		VM_BUG_ON(!cluster_is_huge(ci));
135838d8b4e6SHuang Ying 		map = si->swap_map + offset;
135938d8b4e6SHuang Ying 		for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1360a3aea839SHuang Ying 			val = map[i];
1361a3aea839SHuang Ying 			VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1362a3aea839SHuang Ying 			if (val == SWAP_HAS_CACHE)
1363a3aea839SHuang Ying 				free_entries++;
136438d8b4e6SHuang Ying 		}
1365e0709829SHuang Ying 		cluster_clear_huge(ci);
1366a3aea839SHuang Ying 		if (free_entries == SWAPFILE_CLUSTER) {
1367c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1368a3aea839SHuang Ying 			spin_lock(&si->lock);
136938d8b4e6SHuang Ying 			mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
137038d8b4e6SHuang Ying 			swap_free_cluster(si, idx);
137138d8b4e6SHuang Ying 			spin_unlock(&si->lock);
1372a448f2d0SHuang Ying 			return;
1373a448f2d0SHuang Ying 		}
1374a448f2d0SHuang Ying 	}
1375a448f2d0SHuang Ying 	for (i = 0; i < size; i++, entry.val++) {
1376c2343d27SHuang Ying 		if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1377c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1378a3aea839SHuang Ying 			free_swap_slot(entry);
1379c2343d27SHuang Ying 			if (i == size - 1)
1380c2343d27SHuang Ying 				return;
1381c2343d27SHuang Ying 			lock_cluster_or_swap_info(si, offset);
1382a3aea839SHuang Ying 		}
1383a3aea839SHuang Ying 	}
1384c2343d27SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
138538d8b4e6SHuang Ying }
138659807685SHuang Ying 
1387fe5266d5SHuang Ying #ifdef CONFIG_THP_SWAP
138859807685SHuang Ying int split_swap_cluster(swp_entry_t entry)
138959807685SHuang Ying {
139059807685SHuang Ying 	struct swap_info_struct *si;
139159807685SHuang Ying 	struct swap_cluster_info *ci;
139259807685SHuang Ying 	unsigned long offset = swp_offset(entry);
139359807685SHuang Ying 
139459807685SHuang Ying 	si = _swap_info_get(entry);
139559807685SHuang Ying 	if (!si)
139659807685SHuang Ying 		return -EBUSY;
139759807685SHuang Ying 	ci = lock_cluster(si, offset);
139859807685SHuang Ying 	cluster_clear_huge(ci);
139959807685SHuang Ying 	unlock_cluster(ci);
140059807685SHuang Ying 	return 0;
140159807685SHuang Ying }
1402fe5266d5SHuang Ying #endif
140338d8b4e6SHuang Ying 
1404155b5f88SHuang Ying static int swp_entry_cmp(const void *ent1, const void *ent2)
1405155b5f88SHuang Ying {
1406155b5f88SHuang Ying 	const swp_entry_t *e1 = ent1, *e2 = ent2;
1407155b5f88SHuang Ying 
1408155b5f88SHuang Ying 	return (int)swp_type(*e1) - (int)swp_type(*e2);
1409155b5f88SHuang Ying }
1410155b5f88SHuang Ying 
14117c00bafeSTim Chen void swapcache_free_entries(swp_entry_t *entries, int n)
14127c00bafeSTim Chen {
14137c00bafeSTim Chen 	struct swap_info_struct *p, *prev;
14147c00bafeSTim Chen 	int i;
14157c00bafeSTim Chen 
14167c00bafeSTim Chen 	if (n <= 0)
14177c00bafeSTim Chen 		return;
14187c00bafeSTim Chen 
14197c00bafeSTim Chen 	prev = NULL;
14207c00bafeSTim Chen 	p = NULL;
1421155b5f88SHuang Ying 
1422155b5f88SHuang Ying 	/*
1423155b5f88SHuang Ying 	 * Sort swap entries by swap device, so each lock is only taken once.
1424155b5f88SHuang Ying 	 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1425155b5f88SHuang Ying 	 * so low that it isn't necessary to optimize further.
1426155b5f88SHuang Ying 	 */
1427155b5f88SHuang Ying 	if (nr_swapfiles > 1)
1428155b5f88SHuang Ying 		sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
14297c00bafeSTim Chen 	for (i = 0; i < n; ++i) {
14307c00bafeSTim Chen 		p = swap_info_get_cont(entries[i], prev);
1431235b6217SHuang, Ying 		if (p)
14327c00bafeSTim Chen 			swap_entry_free(p, entries[i]);
14337c00bafeSTim Chen 		prev = p;
14347c00bafeSTim Chen 	}
14357c00bafeSTim Chen 	if (p)
14367c00bafeSTim Chen 		spin_unlock(&p->lock);
1437cb4b86baSKAMEZAWA Hiroyuki }
1438cb4b86baSKAMEZAWA Hiroyuki 
1439eb085574SHuang Ying int __swap_count(swp_entry_t entry)
1440aa8d22a1SMinchan Kim {
1441f9f956b5SHuang Ying 	struct swap_info_struct *si = swp_swap_info(entry);
1442aa8d22a1SMinchan Kim 	pgoff_t offset = swp_offset(entry);
1443aa8d22a1SMinchan Kim 
1444f9f956b5SHuang Ying 	return swap_count(si->swap_map[offset]);
1445aa8d22a1SMinchan Kim }
1446aa8d22a1SMinchan Kim 
144714d01ee9SMatthew Wilcox (Oracle) /*
144814d01ee9SMatthew Wilcox (Oracle)  * How many references to @entry are currently swapped out?
144914d01ee9SMatthew Wilcox (Oracle)  * This does not give an exact answer when swap count is continued,
145014d01ee9SMatthew Wilcox (Oracle)  * but does include the high COUNT_CONTINUED flag to allow for that.
145114d01ee9SMatthew Wilcox (Oracle)  */
14523ecdeb0fSHuang Ying int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1453322b8afeSHuang Ying {
1454322b8afeSHuang Ying 	pgoff_t offset = swp_offset(entry);
1455322b8afeSHuang Ying 	struct swap_cluster_info *ci;
145614d01ee9SMatthew Wilcox (Oracle) 	int count;
1457322b8afeSHuang Ying 
1458322b8afeSHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1459322b8afeSHuang Ying 	count = swap_count(si->swap_map[offset]);
1460322b8afeSHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1461322b8afeSHuang Ying 	return count;
1462322b8afeSHuang Ying }
1463322b8afeSHuang Ying 
14641da177e4SLinus Torvalds /*
14658334b962SMinchan Kim  * How many references to @entry are currently swapped out?
14668334b962SMinchan Kim  * This considers COUNT_CONTINUED so it returns exact answer.
14678334b962SMinchan Kim  */
14688334b962SMinchan Kim int swp_swapcount(swp_entry_t entry)
14698334b962SMinchan Kim {
14708334b962SMinchan Kim 	int count, tmp_count, n;
14718334b962SMinchan Kim 	struct swap_info_struct *p;
1472235b6217SHuang, Ying 	struct swap_cluster_info *ci;
14738334b962SMinchan Kim 	struct page *page;
14748334b962SMinchan Kim 	pgoff_t offset;
14758334b962SMinchan Kim 	unsigned char *map;
14768334b962SMinchan Kim 
1477235b6217SHuang, Ying 	p = _swap_info_get(entry);
14788334b962SMinchan Kim 	if (!p)
14798334b962SMinchan Kim 		return 0;
14808334b962SMinchan Kim 
1481235b6217SHuang, Ying 	offset = swp_offset(entry);
1482235b6217SHuang, Ying 
1483235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
1484235b6217SHuang, Ying 
1485235b6217SHuang, Ying 	count = swap_count(p->swap_map[offset]);
14868334b962SMinchan Kim 	if (!(count & COUNT_CONTINUED))
14878334b962SMinchan Kim 		goto out;
14888334b962SMinchan Kim 
14898334b962SMinchan Kim 	count &= ~COUNT_CONTINUED;
14908334b962SMinchan Kim 	n = SWAP_MAP_MAX + 1;
14918334b962SMinchan Kim 
14928334b962SMinchan Kim 	page = vmalloc_to_page(p->swap_map + offset);
14938334b962SMinchan Kim 	offset &= ~PAGE_MASK;
14948334b962SMinchan Kim 	VM_BUG_ON(page_private(page) != SWP_CONTINUED);
14958334b962SMinchan Kim 
14968334b962SMinchan Kim 	do {
1497a8ae4991SGeliang Tang 		page = list_next_entry(page, lru);
14988334b962SMinchan Kim 		map = kmap_atomic(page);
14998334b962SMinchan Kim 		tmp_count = map[offset];
15008334b962SMinchan Kim 		kunmap_atomic(map);
15018334b962SMinchan Kim 
15028334b962SMinchan Kim 		count += (tmp_count & ~COUNT_CONTINUED) * n;
15038334b962SMinchan Kim 		n *= (SWAP_CONT_MAX + 1);
15048334b962SMinchan Kim 	} while (tmp_count & COUNT_CONTINUED);
15058334b962SMinchan Kim out:
1506235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
15078334b962SMinchan Kim 	return count;
15088334b962SMinchan Kim }
15098334b962SMinchan Kim 
1510e0709829SHuang Ying static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1511e0709829SHuang Ying 					 swp_entry_t entry)
1512e0709829SHuang Ying {
1513e0709829SHuang Ying 	struct swap_cluster_info *ci;
1514e0709829SHuang Ying 	unsigned char *map = si->swap_map;
1515e0709829SHuang Ying 	unsigned long roffset = swp_offset(entry);
1516e0709829SHuang Ying 	unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1517e0709829SHuang Ying 	int i;
1518e0709829SHuang Ying 	bool ret = false;
1519e0709829SHuang Ying 
1520e0709829SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1521e0709829SHuang Ying 	if (!ci || !cluster_is_huge(ci)) {
1522afa4711eSHuang Ying 		if (swap_count(map[roffset]))
1523e0709829SHuang Ying 			ret = true;
1524e0709829SHuang Ying 		goto unlock_out;
1525e0709829SHuang Ying 	}
1526e0709829SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1527afa4711eSHuang Ying 		if (swap_count(map[offset + i])) {
1528e0709829SHuang Ying 			ret = true;
1529e0709829SHuang Ying 			break;
1530e0709829SHuang Ying 		}
1531e0709829SHuang Ying 	}
1532e0709829SHuang Ying unlock_out:
1533e0709829SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1534e0709829SHuang Ying 	return ret;
1535e0709829SHuang Ying }
1536e0709829SHuang Ying 
15372397f780SMatthew Wilcox (Oracle) static bool folio_swapped(struct folio *folio)
1538e0709829SHuang Ying {
153914d01ee9SMatthew Wilcox (Oracle) 	swp_entry_t entry = folio_swap_entry(folio);
154014d01ee9SMatthew Wilcox (Oracle) 	struct swap_info_struct *si = _swap_info_get(entry);
154114d01ee9SMatthew Wilcox (Oracle) 
154214d01ee9SMatthew Wilcox (Oracle) 	if (!si)
154314d01ee9SMatthew Wilcox (Oracle) 		return false;
1544e0709829SHuang Ying 
15452397f780SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!folio_test_large(folio)))
154614d01ee9SMatthew Wilcox (Oracle) 		return swap_swapcount(si, entry) != 0;
1547e0709829SHuang Ying 
1548e0709829SHuang Ying 	return swap_page_trans_huge_swapped(si, entry);
1549e0709829SHuang Ying }
1550ba3c4ce6SHuang Ying 
1551bdb0ed54SMatthew Wilcox (Oracle) /**
1552bdb0ed54SMatthew Wilcox (Oracle)  * folio_free_swap() - Free the swap space used for this folio.
1553bdb0ed54SMatthew Wilcox (Oracle)  * @folio: The folio to remove.
1554bdb0ed54SMatthew Wilcox (Oracle)  *
1555bdb0ed54SMatthew Wilcox (Oracle)  * If swap is getting full, or if there are no more mappings of this folio,
1556bdb0ed54SMatthew Wilcox (Oracle)  * then call folio_free_swap to free its swap space.
1557bdb0ed54SMatthew Wilcox (Oracle)  *
1558bdb0ed54SMatthew Wilcox (Oracle)  * Return: true if we were able to release the swap space.
15591da177e4SLinus Torvalds  */
1560bdb0ed54SMatthew Wilcox (Oracle) bool folio_free_swap(struct folio *folio)
15611da177e4SLinus Torvalds {
15622397f780SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
15631da177e4SLinus Torvalds 
15642397f780SMatthew Wilcox (Oracle) 	if (!folio_test_swapcache(folio))
1565bdb0ed54SMatthew Wilcox (Oracle) 		return false;
15662397f780SMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio))
1567bdb0ed54SMatthew Wilcox (Oracle) 		return false;
15682397f780SMatthew Wilcox (Oracle) 	if (folio_swapped(folio))
1569bdb0ed54SMatthew Wilcox (Oracle) 		return false;
15701da177e4SLinus Torvalds 
1571b73d7fceSHugh Dickins 	/*
1572b73d7fceSHugh Dickins 	 * Once hibernation has begun to create its image of memory,
1573bdb0ed54SMatthew Wilcox (Oracle) 	 * there's a danger that one of the calls to folio_free_swap()
1574b73d7fceSHugh Dickins 	 * - most probably a call from __try_to_reclaim_swap() while
1575b73d7fceSHugh Dickins 	 * hibernation is allocating its own swap pages for the image,
1576b73d7fceSHugh Dickins 	 * but conceivably even a call from memory reclaim - will free
1577bdb0ed54SMatthew Wilcox (Oracle) 	 * the swap from a folio which has already been recorded in the
1578bdb0ed54SMatthew Wilcox (Oracle) 	 * image as a clean swapcache folio, and then reuse its swap for
1579b73d7fceSHugh Dickins 	 * another page of the image.  On waking from hibernation, the
1580bdb0ed54SMatthew Wilcox (Oracle) 	 * original folio might be freed under memory pressure, then
1581b73d7fceSHugh Dickins 	 * later read back in from swap, now with the wrong data.
1582b73d7fceSHugh Dickins 	 *
15832de1a7e4SSeth Jennings 	 * Hibernation suspends storage while it is writing the image
1584f90ac398SMel Gorman 	 * to disk so check that here.
1585b73d7fceSHugh Dickins 	 */
1586f90ac398SMel Gorman 	if (pm_suspended_storage())
1587bdb0ed54SMatthew Wilcox (Oracle) 		return false;
1588b73d7fceSHugh Dickins 
158975fa68a5SMatthew Wilcox (Oracle) 	delete_from_swap_cache(folio);
15902397f780SMatthew Wilcox (Oracle) 	folio_set_dirty(folio);
1591bdb0ed54SMatthew Wilcox (Oracle) 	return true;
159268a22394SRik van Riel }
159368a22394SRik van Riel 
159468a22394SRik van Riel /*
15951da177e4SLinus Torvalds  * Free the swap entry like above, but also try to
15961da177e4SLinus Torvalds  * free the page cache entry if it is the last user.
15971da177e4SLinus Torvalds  */
15982509ef26SHugh Dickins int free_swap_and_cache(swp_entry_t entry)
15991da177e4SLinus Torvalds {
16001da177e4SLinus Torvalds 	struct swap_info_struct *p;
16017c00bafeSTim Chen 	unsigned char count;
16021da177e4SLinus Torvalds 
1603a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
16042509ef26SHugh Dickins 		return 1;
16050697212aSChristoph Lameter 
16067c00bafeSTim Chen 	p = _swap_info_get(entry);
16071da177e4SLinus Torvalds 	if (p) {
160833e16272SWei Yang 		count = __swap_entry_free(p, entry);
1609e0709829SHuang Ying 		if (count == SWAP_HAS_CACHE &&
1610bcd49e86SHuang Ying 		    !swap_page_trans_huge_swapped(p, entry))
1611bcd49e86SHuang Ying 			__try_to_reclaim_swap(p, swp_offset(entry),
1612bcd49e86SHuang Ying 					      TTRS_UNMAPPED | TTRS_FULL);
16131da177e4SLinus Torvalds 	}
16142509ef26SHugh Dickins 	return p != NULL;
16151da177e4SLinus Torvalds }
16161da177e4SLinus Torvalds 
1617b0cb1a19SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
1618bb243f7dSMiaohe Lin 
1619bb243f7dSMiaohe Lin swp_entry_t get_swap_page_of_type(int type)
1620bb243f7dSMiaohe Lin {
1621bb243f7dSMiaohe Lin 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1622bb243f7dSMiaohe Lin 	swp_entry_t entry = {0};
1623bb243f7dSMiaohe Lin 
1624bb243f7dSMiaohe Lin 	if (!si)
1625bb243f7dSMiaohe Lin 		goto fail;
1626bb243f7dSMiaohe Lin 
1627bb243f7dSMiaohe Lin 	/* This is called for allocating swap entry, not cache */
1628bb243f7dSMiaohe Lin 	spin_lock(&si->lock);
1629bb243f7dSMiaohe Lin 	if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry))
1630bb243f7dSMiaohe Lin 		atomic_long_dec(&nr_swap_pages);
1631bb243f7dSMiaohe Lin 	spin_unlock(&si->lock);
1632bb243f7dSMiaohe Lin fail:
1633bb243f7dSMiaohe Lin 	return entry;
1634bb243f7dSMiaohe Lin }
1635bb243f7dSMiaohe Lin 
1636f577eb30SRafael J. Wysocki /*
1637915bae9eSRafael J. Wysocki  * Find the swap type that corresponds to given device (if any).
1638f577eb30SRafael J. Wysocki  *
1639915bae9eSRafael J. Wysocki  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1640915bae9eSRafael J. Wysocki  * from 0, in which the swap header is expected to be located.
1641915bae9eSRafael J. Wysocki  *
1642915bae9eSRafael J. Wysocki  * This is needed for the suspend to disk (aka swsusp).
1643f577eb30SRafael J. Wysocki  */
164421bd9005SChristoph Hellwig int swap_type_of(dev_t device, sector_t offset)
1645f577eb30SRafael J. Wysocki {
1646efa90a98SHugh Dickins 	int type;
1647f577eb30SRafael J. Wysocki 
164821bd9005SChristoph Hellwig 	if (!device)
164921bd9005SChristoph Hellwig 		return -1;
1650915bae9eSRafael J. Wysocki 
1651f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1652efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
1653efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1654f577eb30SRafael J. Wysocki 
1655915bae9eSRafael J. Wysocki 		if (!(sis->flags & SWP_WRITEOK))
1656f577eb30SRafael J. Wysocki 			continue;
1657b6b5bce3SRafael J. Wysocki 
165821bd9005SChristoph Hellwig 		if (device == sis->bdev->bd_dev) {
16594efaceb1SAaron Lu 			struct swap_extent *se = first_se(sis);
1660915bae9eSRafael J. Wysocki 
1661915bae9eSRafael J. Wysocki 			if (se->start_block == offset) {
1662f577eb30SRafael J. Wysocki 				spin_unlock(&swap_lock);
1663efa90a98SHugh Dickins 				return type;
1664f577eb30SRafael J. Wysocki 			}
1665f577eb30SRafael J. Wysocki 		}
1666915bae9eSRafael J. Wysocki 	}
1667f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
166821bd9005SChristoph Hellwig 	return -ENODEV;
166921bd9005SChristoph Hellwig }
1670915bae9eSRafael J. Wysocki 
167121bd9005SChristoph Hellwig int find_first_swap(dev_t *device)
167221bd9005SChristoph Hellwig {
167321bd9005SChristoph Hellwig 	int type;
167421bd9005SChristoph Hellwig 
167521bd9005SChristoph Hellwig 	spin_lock(&swap_lock);
167621bd9005SChristoph Hellwig 	for (type = 0; type < nr_swapfiles; type++) {
167721bd9005SChristoph Hellwig 		struct swap_info_struct *sis = swap_info[type];
167821bd9005SChristoph Hellwig 
167921bd9005SChristoph Hellwig 		if (!(sis->flags & SWP_WRITEOK))
168021bd9005SChristoph Hellwig 			continue;
168121bd9005SChristoph Hellwig 		*device = sis->bdev->bd_dev;
168221bd9005SChristoph Hellwig 		spin_unlock(&swap_lock);
168321bd9005SChristoph Hellwig 		return type;
168421bd9005SChristoph Hellwig 	}
168521bd9005SChristoph Hellwig 	spin_unlock(&swap_lock);
1686f577eb30SRafael J. Wysocki 	return -ENODEV;
1687f577eb30SRafael J. Wysocki }
1688f577eb30SRafael J. Wysocki 
1689f577eb30SRafael J. Wysocki /*
169073c34b6aSHugh Dickins  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
169173c34b6aSHugh Dickins  * corresponding to given index in swap_info (swap type).
169273c34b6aSHugh Dickins  */
169373c34b6aSHugh Dickins sector_t swapdev_block(int type, pgoff_t offset)
169473c34b6aSHugh Dickins {
1695c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1696f885056aSChristoph Hellwig 	struct swap_extent *se;
169773c34b6aSHugh Dickins 
1698c10d38ccSDaniel Jordan 	if (!si || !(si->flags & SWP_WRITEOK))
169973c34b6aSHugh Dickins 		return 0;
1700f885056aSChristoph Hellwig 	se = offset_to_swap_extent(si, offset);
1701f885056aSChristoph Hellwig 	return se->start_block + (offset - se->start_page);
170273c34b6aSHugh Dickins }
170373c34b6aSHugh Dickins 
170473c34b6aSHugh Dickins /*
1705f577eb30SRafael J. Wysocki  * Return either the total number of swap pages of given type, or the number
1706f577eb30SRafael J. Wysocki  * of free pages of that type (depending on @free)
1707f577eb30SRafael J. Wysocki  *
1708f577eb30SRafael J. Wysocki  * This is needed for software suspend
1709f577eb30SRafael J. Wysocki  */
1710f577eb30SRafael J. Wysocki unsigned int count_swap_pages(int type, int free)
1711f577eb30SRafael J. Wysocki {
1712f577eb30SRafael J. Wysocki 	unsigned int n = 0;
1713f577eb30SRafael J. Wysocki 
1714f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1715efa90a98SHugh Dickins 	if ((unsigned int)type < nr_swapfiles) {
1716efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1717efa90a98SHugh Dickins 
1718ec8acf20SShaohua Li 		spin_lock(&sis->lock);
1719efa90a98SHugh Dickins 		if (sis->flags & SWP_WRITEOK) {
1720efa90a98SHugh Dickins 			n = sis->pages;
1721f577eb30SRafael J. Wysocki 			if (free)
1722efa90a98SHugh Dickins 				n -= sis->inuse_pages;
1723efa90a98SHugh Dickins 		}
1724ec8acf20SShaohua Li 		spin_unlock(&sis->lock);
1725f577eb30SRafael J. Wysocki 	}
1726f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1727f577eb30SRafael J. Wysocki 	return n;
1728f577eb30SRafael J. Wysocki }
172973c34b6aSHugh Dickins #endif /* CONFIG_HIBERNATION */
1730f577eb30SRafael J. Wysocki 
17319f8bdb3fSHugh Dickins static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1732179ef71cSCyrill Gorcunov {
1733099dd687SPeter Xu 	return pte_same(pte_swp_clear_flags(pte), swp_pte);
1734179ef71cSCyrill Gorcunov }
1735179ef71cSCyrill Gorcunov 
17361da177e4SLinus Torvalds /*
173772866f6fSHugh Dickins  * No need to decide whether this PTE shares the swap entry with others,
173872866f6fSHugh Dickins  * just let do_wp_page work it out if a write is requested later - to
173972866f6fSHugh Dickins  * force COW, vm_page_prot omits write permission from any private vma.
17401da177e4SLinus Torvalds  */
1741044d66c1SHugh Dickins static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
1742f102cd8bSMatthew Wilcox (Oracle) 		unsigned long addr, swp_entry_t entry, struct folio *folio)
17431da177e4SLinus Torvalds {
1744f102cd8bSMatthew Wilcox (Oracle) 	struct page *page = folio_file_page(folio, swp_offset(entry));
17459e16b7fbSHugh Dickins 	struct page *swapcache;
1746044d66c1SHugh Dickins 	spinlock_t *ptl;
1747c33c7948SRyan Roberts 	pte_t *pte, new_pte, old_pte;
17486b970599SKefeng Wang 	bool hwposioned = false;
1749044d66c1SHugh Dickins 	int ret = 1;
1750044d66c1SHugh Dickins 
17519e16b7fbSHugh Dickins 	swapcache = page;
17529e16b7fbSHugh Dickins 	page = ksm_might_need_to_copy(page, vma, addr);
17539e16b7fbSHugh Dickins 	if (unlikely(!page))
17549e16b7fbSHugh Dickins 		return -ENOMEM;
17556b970599SKefeng Wang 	else if (unlikely(PTR_ERR(page) == -EHWPOISON))
17566b970599SKefeng Wang 		hwposioned = true;
17579e16b7fbSHugh Dickins 
1758044d66c1SHugh Dickins 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
1759c33c7948SRyan Roberts 	if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte),
1760c33c7948SRyan Roberts 						swp_entry_to_pte(entry)))) {
1761044d66c1SHugh Dickins 		ret = 0;
1762044d66c1SHugh Dickins 		goto out;
1763044d66c1SHugh Dickins 	}
17648a9f3ccdSBalbir Singh 
1765c33c7948SRyan Roberts 	old_pte = ptep_get(pte);
1766c33c7948SRyan Roberts 
17676b970599SKefeng Wang 	if (unlikely(hwposioned || !PageUptodate(page))) {
17686b970599SKefeng Wang 		swp_entry_t swp_entry;
17699f186f9eSMiaohe Lin 
17709f186f9eSMiaohe Lin 		dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
17716b970599SKefeng Wang 		if (hwposioned) {
17726b970599SKefeng Wang 			swp_entry = make_hwpoison_entry(swapcache);
17736b970599SKefeng Wang 			page = swapcache;
17746b970599SKefeng Wang 		} else {
1775af19487fSAxel Rasmussen 			swp_entry = make_poisoned_swp_entry();
17766b970599SKefeng Wang 		}
17776b970599SKefeng Wang 		new_pte = swp_entry_to_pte(swp_entry);
17789f186f9eSMiaohe Lin 		ret = 0;
17796b970599SKefeng Wang 		goto setpte;
17809f186f9eSMiaohe Lin 	}
17819f186f9eSMiaohe Lin 
1782b53e24c4SPeter Collingbourne 	/*
1783b53e24c4SPeter Collingbourne 	 * Some architectures may have to restore extra metadata to the page
1784b53e24c4SPeter Collingbourne 	 * when reading from swap. This metadata may be indexed by swap entry
1785b53e24c4SPeter Collingbourne 	 * so this must be called before swap_free().
1786b53e24c4SPeter Collingbourne 	 */
1787b53e24c4SPeter Collingbourne 	arch_swap_restore(entry, page_folio(page));
1788b53e24c4SPeter Collingbourne 
178978fbe906SDavid Hildenbrand 	/* See do_swap_page() */
179078fbe906SDavid Hildenbrand 	BUG_ON(!PageAnon(page) && PageMappedToDisk(page));
179178fbe906SDavid Hildenbrand 	BUG_ON(PageAnon(page) && PageAnonExclusive(page));
179278fbe906SDavid Hildenbrand 
1793b084d435SKAMEZAWA Hiroyuki 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1794d559db08SKAMEZAWA Hiroyuki 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
17951da177e4SLinus Torvalds 	get_page(page);
179600501b53SJohannes Weiner 	if (page == swapcache) {
17971493a191SDavid Hildenbrand 		rmap_t rmap_flags = RMAP_NONE;
17981493a191SDavid Hildenbrand 
17991493a191SDavid Hildenbrand 		/*
18001493a191SDavid Hildenbrand 		 * See do_swap_page(): PageWriteback() would be problematic.
18011493a191SDavid Hildenbrand 		 * However, we do a wait_on_page_writeback() just before this
18021493a191SDavid Hildenbrand 		 * call and have the page locked.
18031493a191SDavid Hildenbrand 		 */
18041493a191SDavid Hildenbrand 		VM_BUG_ON_PAGE(PageWriteback(page), page);
1805c33c7948SRyan Roberts 		if (pte_swp_exclusive(old_pte))
18061493a191SDavid Hildenbrand 			rmap_flags |= RMAP_EXCLUSIVE;
18071493a191SDavid Hildenbrand 
18081493a191SDavid Hildenbrand 		page_add_anon_rmap(page, vma, addr, rmap_flags);
180900501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
181040f2bbf7SDavid Hildenbrand 		page_add_new_anon_rmap(page, vma, addr);
1811b518154eSJoonsoo Kim 		lru_cache_add_inactive_or_unevictable(page, vma);
181200501b53SJohannes Weiner 	}
181314a762ddSMiaohe Lin 	new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
1814c33c7948SRyan Roberts 	if (pte_swp_soft_dirty(old_pte))
181514a762ddSMiaohe Lin 		new_pte = pte_mksoft_dirty(new_pte);
1816c33c7948SRyan Roberts 	if (pte_swp_uffd_wp(old_pte))
181714a762ddSMiaohe Lin 		new_pte = pte_mkuffd_wp(new_pte);
18186b970599SKefeng Wang setpte:
181914a762ddSMiaohe Lin 	set_pte_at(vma->vm_mm, addr, pte, new_pte);
18201da177e4SLinus Torvalds 	swap_free(entry);
1821044d66c1SHugh Dickins out:
1822d850fa72SHugh Dickins 	if (pte)
1823044d66c1SHugh Dickins 		pte_unmap_unlock(pte, ptl);
18249e16b7fbSHugh Dickins 	if (page != swapcache) {
18259e16b7fbSHugh Dickins 		unlock_page(page);
18269e16b7fbSHugh Dickins 		put_page(page);
18279e16b7fbSHugh Dickins 	}
1828044d66c1SHugh Dickins 	return ret;
18291da177e4SLinus Torvalds }
18301da177e4SLinus Torvalds 
18311da177e4SLinus Torvalds static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
18321da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
183310a9c496SChristoph Hellwig 			unsigned int type)
18341da177e4SLinus Torvalds {
1835d850fa72SHugh Dickins 	pte_t *pte = NULL;
1836b56a2d8aSVineeth Remanan Pillai 	struct swap_info_struct *si;
18371da177e4SLinus Torvalds 
1838b56a2d8aSVineeth Remanan Pillai 	si = swap_info[type];
18391da177e4SLinus Torvalds 	do {
1840f102cd8bSMatthew Wilcox (Oracle) 		struct folio *folio;
1841f102cd8bSMatthew Wilcox (Oracle) 		unsigned long offset;
18423f79b187SKairui Song 		unsigned char swp_count;
1843d850fa72SHugh Dickins 		swp_entry_t entry;
1844d850fa72SHugh Dickins 		int ret;
1845c33c7948SRyan Roberts 		pte_t ptent;
1846f102cd8bSMatthew Wilcox (Oracle) 
1847d850fa72SHugh Dickins 		if (!pte++) {
1848d850fa72SHugh Dickins 			pte = pte_offset_map(pmd, addr);
1849d850fa72SHugh Dickins 			if (!pte)
1850d850fa72SHugh Dickins 				break;
1851d850fa72SHugh Dickins 		}
18521da177e4SLinus Torvalds 
1853c33c7948SRyan Roberts 		ptent = ptep_get_lockless(pte);
1854c33c7948SRyan Roberts 
1855c33c7948SRyan Roberts 		if (!is_swap_pte(ptent))
1856b56a2d8aSVineeth Remanan Pillai 			continue;
1857b56a2d8aSVineeth Remanan Pillai 
1858c33c7948SRyan Roberts 		entry = pte_to_swp_entry(ptent);
1859b56a2d8aSVineeth Remanan Pillai 		if (swp_type(entry) != type)
1860b56a2d8aSVineeth Remanan Pillai 			continue;
1861b56a2d8aSVineeth Remanan Pillai 
1862b56a2d8aSVineeth Remanan Pillai 		offset = swp_offset(entry);
1863044d66c1SHugh Dickins 		pte_unmap(pte);
1864d850fa72SHugh Dickins 		pte = NULL;
1865d850fa72SHugh Dickins 
1866f102cd8bSMatthew Wilcox (Oracle) 		folio = swap_cache_get_folio(entry, vma, addr);
1867f102cd8bSMatthew Wilcox (Oracle) 		if (!folio) {
1868f102cd8bSMatthew Wilcox (Oracle) 			struct page *page;
18698c63ca5bSWill Deacon 			struct vm_fault vmf = {
18708c63ca5bSWill Deacon 				.vma = vma,
18718c63ca5bSWill Deacon 				.address = addr,
1872824ddc60SNadav Amit 				.real_address = addr,
18738c63ca5bSWill Deacon 				.pmd = pmd,
18748c63ca5bSWill Deacon 			};
18758c63ca5bSWill Deacon 
1876ebc5951eSAndrea Righi 			page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
1877ebc5951eSAndrea Righi 						&vmf);
1878f102cd8bSMatthew Wilcox (Oracle) 			if (page)
1879f102cd8bSMatthew Wilcox (Oracle) 				folio = page_folio(page);
1880ebc5951eSAndrea Righi 		}
1881f102cd8bSMatthew Wilcox (Oracle) 		if (!folio) {
18823f79b187SKairui Song 			swp_count = READ_ONCE(si->swap_map[offset]);
18833f79b187SKairui Song 			if (swp_count == 0 || swp_count == SWAP_MAP_BAD)
1884d850fa72SHugh Dickins 				continue;
1885b56a2d8aSVineeth Remanan Pillai 			return -ENOMEM;
18861da177e4SLinus Torvalds 		}
1887b56a2d8aSVineeth Remanan Pillai 
1888f102cd8bSMatthew Wilcox (Oracle) 		folio_lock(folio);
1889f102cd8bSMatthew Wilcox (Oracle) 		folio_wait_writeback(folio);
1890f102cd8bSMatthew Wilcox (Oracle) 		ret = unuse_pte(vma, pmd, addr, entry, folio);
1891b56a2d8aSVineeth Remanan Pillai 		if (ret < 0) {
1892f102cd8bSMatthew Wilcox (Oracle) 			folio_unlock(folio);
1893f102cd8bSMatthew Wilcox (Oracle) 			folio_put(folio);
1894d850fa72SHugh Dickins 			return ret;
1895b56a2d8aSVineeth Remanan Pillai 		}
1896b56a2d8aSVineeth Remanan Pillai 
1897f102cd8bSMatthew Wilcox (Oracle) 		folio_free_swap(folio);
1898f102cd8bSMatthew Wilcox (Oracle) 		folio_unlock(folio);
1899f102cd8bSMatthew Wilcox (Oracle) 		folio_put(folio);
1900d850fa72SHugh Dickins 	} while (addr += PAGE_SIZE, addr != end);
1901b56a2d8aSVineeth Remanan Pillai 
1902d850fa72SHugh Dickins 	if (pte)
1903d850fa72SHugh Dickins 		pte_unmap(pte);
1904d850fa72SHugh Dickins 	return 0;
19051da177e4SLinus Torvalds }
19061da177e4SLinus Torvalds 
19071da177e4SLinus Torvalds static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
19081da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
190910a9c496SChristoph Hellwig 				unsigned int type)
19101da177e4SLinus Torvalds {
19111da177e4SLinus Torvalds 	pmd_t *pmd;
19121da177e4SLinus Torvalds 	unsigned long next;
19138a9f3ccdSBalbir Singh 	int ret;
19141da177e4SLinus Torvalds 
19151da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
19161da177e4SLinus Torvalds 	do {
1917dc644a07SHugh Dickins 		cond_resched();
19181da177e4SLinus Torvalds 		next = pmd_addr_end(addr, end);
191910a9c496SChristoph Hellwig 		ret = unuse_pte_range(vma, pmd, addr, next, type);
19208a9f3ccdSBalbir Singh 		if (ret)
19218a9f3ccdSBalbir Singh 			return ret;
19221da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
19231da177e4SLinus Torvalds 	return 0;
19241da177e4SLinus Torvalds }
19251da177e4SLinus Torvalds 
1926c2febafcSKirill A. Shutemov static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
19271da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
192810a9c496SChristoph Hellwig 				unsigned int type)
19291da177e4SLinus Torvalds {
19301da177e4SLinus Torvalds 	pud_t *pud;
19311da177e4SLinus Torvalds 	unsigned long next;
19328a9f3ccdSBalbir Singh 	int ret;
19331da177e4SLinus Torvalds 
1934c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
19351da177e4SLinus Torvalds 	do {
19361da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
19371da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
19381da177e4SLinus Torvalds 			continue;
193910a9c496SChristoph Hellwig 		ret = unuse_pmd_range(vma, pud, addr, next, type);
19408a9f3ccdSBalbir Singh 		if (ret)
19418a9f3ccdSBalbir Singh 			return ret;
19421da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
19431da177e4SLinus Torvalds 	return 0;
19441da177e4SLinus Torvalds }
19451da177e4SLinus Torvalds 
1946c2febafcSKirill A. Shutemov static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
1947c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
194810a9c496SChristoph Hellwig 				unsigned int type)
1949c2febafcSKirill A. Shutemov {
1950c2febafcSKirill A. Shutemov 	p4d_t *p4d;
1951c2febafcSKirill A. Shutemov 	unsigned long next;
1952c2febafcSKirill A. Shutemov 	int ret;
1953c2febafcSKirill A. Shutemov 
1954c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
1955c2febafcSKirill A. Shutemov 	do {
1956c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1957c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
1958c2febafcSKirill A. Shutemov 			continue;
195910a9c496SChristoph Hellwig 		ret = unuse_pud_range(vma, p4d, addr, next, type);
1960c2febafcSKirill A. Shutemov 		if (ret)
1961c2febafcSKirill A. Shutemov 			return ret;
1962c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
1963c2febafcSKirill A. Shutemov 	return 0;
1964c2febafcSKirill A. Shutemov }
1965c2febafcSKirill A. Shutemov 
196610a9c496SChristoph Hellwig static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
19671da177e4SLinus Torvalds {
19681da177e4SLinus Torvalds 	pgd_t *pgd;
19691da177e4SLinus Torvalds 	unsigned long addr, end, next;
19708a9f3ccdSBalbir Singh 	int ret;
19711da177e4SLinus Torvalds 
19721da177e4SLinus Torvalds 	addr = vma->vm_start;
19731da177e4SLinus Torvalds 	end = vma->vm_end;
19741da177e4SLinus Torvalds 
19751da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
19761da177e4SLinus Torvalds 	do {
19771da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
19781da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
19791da177e4SLinus Torvalds 			continue;
198010a9c496SChristoph Hellwig 		ret = unuse_p4d_range(vma, pgd, addr, next, type);
19818a9f3ccdSBalbir Singh 		if (ret)
19828a9f3ccdSBalbir Singh 			return ret;
19831da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
19841da177e4SLinus Torvalds 	return 0;
19851da177e4SLinus Torvalds }
19861da177e4SLinus Torvalds 
198710a9c496SChristoph Hellwig static int unuse_mm(struct mm_struct *mm, unsigned int type)
19881da177e4SLinus Torvalds {
19891da177e4SLinus Torvalds 	struct vm_area_struct *vma;
19908a9f3ccdSBalbir Singh 	int ret = 0;
1991208c09dbSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
19921da177e4SLinus Torvalds 
1993d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
1994208c09dbSLiam R. Howlett 	for_each_vma(vmi, vma) {
1995b56a2d8aSVineeth Remanan Pillai 		if (vma->anon_vma) {
199610a9c496SChristoph Hellwig 			ret = unuse_vma(vma, type);
1997b56a2d8aSVineeth Remanan Pillai 			if (ret)
19981da177e4SLinus Torvalds 				break;
1999b56a2d8aSVineeth Remanan Pillai 		}
2000208c09dbSLiam R. Howlett 
2001dc644a07SHugh Dickins 		cond_resched();
20021da177e4SLinus Torvalds 	}
2003d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
2004b56a2d8aSVineeth Remanan Pillai 	return ret;
20051da177e4SLinus Torvalds }
20061da177e4SLinus Torvalds 
20071da177e4SLinus Torvalds /*
20083c3115adSMiaohe Lin  * Scan swap_map from current position to next entry still in use.
20093c3115adSMiaohe Lin  * Return 0 if there are no inuse entries after prev till end of
20103c3115adSMiaohe Lin  * the map.
20111da177e4SLinus Torvalds  */
20126eb396dcSHugh Dickins static unsigned int find_next_to_unuse(struct swap_info_struct *si,
201310a9c496SChristoph Hellwig 					unsigned int prev)
20141da177e4SLinus Torvalds {
2015b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
20168d69aaeeSHugh Dickins 	unsigned char count;
20171da177e4SLinus Torvalds 
20181da177e4SLinus Torvalds 	/*
20195d337b91SHugh Dickins 	 * No need for swap_lock here: we're just looking
20201da177e4SLinus Torvalds 	 * for whether an entry is in use, not modifying it; false
20211da177e4SLinus Torvalds 	 * hits are okay, and sys_swapoff() has already prevented new
20225d337b91SHugh Dickins 	 * allocations from this area (while holding swap_lock).
20231da177e4SLinus Torvalds 	 */
2024b56a2d8aSVineeth Remanan Pillai 	for (i = prev + 1; i < si->max; i++) {
20254db0c3c2SJason Low 		count = READ_ONCE(si->swap_map[i]);
2026355cfa73SKAMEZAWA Hiroyuki 		if (count && swap_count(count) != SWAP_MAP_BAD)
20271da177e4SLinus Torvalds 			break;
2028dc644a07SHugh Dickins 		if ((i % LATENCY_LIMIT) == 0)
2029dc644a07SHugh Dickins 			cond_resched();
20301da177e4SLinus Torvalds 	}
2031b56a2d8aSVineeth Remanan Pillai 
2032b56a2d8aSVineeth Remanan Pillai 	if (i == si->max)
2033b56a2d8aSVineeth Remanan Pillai 		i = 0;
2034b56a2d8aSVineeth Remanan Pillai 
20351da177e4SLinus Torvalds 	return i;
20361da177e4SLinus Torvalds }
20371da177e4SLinus Torvalds 
203810a9c496SChristoph Hellwig static int try_to_unuse(unsigned int type)
20391da177e4SLinus Torvalds {
2040b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *prev_mm;
2041b56a2d8aSVineeth Remanan Pillai 	struct mm_struct *mm;
2042b56a2d8aSVineeth Remanan Pillai 	struct list_head *p;
2043b56a2d8aSVineeth Remanan Pillai 	int retval = 0;
2044efa90a98SHugh Dickins 	struct swap_info_struct *si = swap_info[type];
2045000085b9SMatthew Wilcox (Oracle) 	struct folio *folio;
20461da177e4SLinus Torvalds 	swp_entry_t entry;
2047b56a2d8aSVineeth Remanan Pillai 	unsigned int i;
20481da177e4SLinus Torvalds 
204921820948SQian Cai 	if (!READ_ONCE(si->inuse_pages))
2050b56a2d8aSVineeth Remanan Pillai 		return 0;
20511da177e4SLinus Torvalds 
2052b56a2d8aSVineeth Remanan Pillai retry:
205310a9c496SChristoph Hellwig 	retval = shmem_unuse(type);
2054b56a2d8aSVineeth Remanan Pillai 	if (retval)
205510a9c496SChristoph Hellwig 		return retval;
2056b56a2d8aSVineeth Remanan Pillai 
2057b56a2d8aSVineeth Remanan Pillai 	prev_mm = &init_mm;
2058b56a2d8aSVineeth Remanan Pillai 	mmget(prev_mm);
2059b56a2d8aSVineeth Remanan Pillai 
2060b56a2d8aSVineeth Remanan Pillai 	spin_lock(&mmlist_lock);
2061b56a2d8aSVineeth Remanan Pillai 	p = &init_mm.mmlist;
206221820948SQian Cai 	while (READ_ONCE(si->inuse_pages) &&
206364165b1aSHugh Dickins 	       !signal_pending(current) &&
206464165b1aSHugh Dickins 	       (p = p->next) != &init_mm.mmlist) {
20651da177e4SLinus Torvalds 
20661da177e4SLinus Torvalds 		mm = list_entry(p, struct mm_struct, mmlist);
2067388f7934SVegard Nossum 		if (!mmget_not_zero(mm))
20681da177e4SLinus Torvalds 			continue;
20691da177e4SLinus Torvalds 		spin_unlock(&mmlist_lock);
20701da177e4SLinus Torvalds 		mmput(prev_mm);
20711da177e4SLinus Torvalds 		prev_mm = mm;
207210a9c496SChristoph Hellwig 		retval = unuse_mm(mm, type);
20731da177e4SLinus Torvalds 		if (retval) {
2074b56a2d8aSVineeth Remanan Pillai 			mmput(prev_mm);
207510a9c496SChristoph Hellwig 			return retval;
20761da177e4SLinus Torvalds 		}
20771da177e4SLinus Torvalds 
20781da177e4SLinus Torvalds 		/*
20791da177e4SLinus Torvalds 		 * Make sure that we aren't completely killing
20801da177e4SLinus Torvalds 		 * interactive performance.
20811da177e4SLinus Torvalds 		 */
20821da177e4SLinus Torvalds 		cond_resched();
2083b56a2d8aSVineeth Remanan Pillai 		spin_lock(&mmlist_lock);
208438b5faf4SDan Magenheimer 	}
2085b56a2d8aSVineeth Remanan Pillai 	spin_unlock(&mmlist_lock);
2086b56a2d8aSVineeth Remanan Pillai 
2087b56a2d8aSVineeth Remanan Pillai 	mmput(prev_mm);
2088b56a2d8aSVineeth Remanan Pillai 
2089b56a2d8aSVineeth Remanan Pillai 	i = 0;
209021820948SQian Cai 	while (READ_ONCE(si->inuse_pages) &&
209164165b1aSHugh Dickins 	       !signal_pending(current) &&
209210a9c496SChristoph Hellwig 	       (i = find_next_to_unuse(si, i)) != 0) {
2093b56a2d8aSVineeth Remanan Pillai 
2094b56a2d8aSVineeth Remanan Pillai 		entry = swp_entry(type, i);
2095000085b9SMatthew Wilcox (Oracle) 		folio = filemap_get_folio(swap_address_space(entry), i);
209666dabbb6SChristoph Hellwig 		if (IS_ERR(folio))
2097b56a2d8aSVineeth Remanan Pillai 			continue;
2098b56a2d8aSVineeth Remanan Pillai 
2099b56a2d8aSVineeth Remanan Pillai 		/*
2100000085b9SMatthew Wilcox (Oracle) 		 * It is conceivable that a racing task removed this folio from
2101000085b9SMatthew Wilcox (Oracle) 		 * swap cache just before we acquired the page lock. The folio
2102b56a2d8aSVineeth Remanan Pillai 		 * might even be back in swap cache on another swap area. But
2103000085b9SMatthew Wilcox (Oracle) 		 * that is okay, folio_free_swap() only removes stale folios.
2104b56a2d8aSVineeth Remanan Pillai 		 */
2105000085b9SMatthew Wilcox (Oracle) 		folio_lock(folio);
2106000085b9SMatthew Wilcox (Oracle) 		folio_wait_writeback(folio);
2107000085b9SMatthew Wilcox (Oracle) 		folio_free_swap(folio);
2108000085b9SMatthew Wilcox (Oracle) 		folio_unlock(folio);
2109000085b9SMatthew Wilcox (Oracle) 		folio_put(folio);
21101da177e4SLinus Torvalds 	}
21111da177e4SLinus Torvalds 
2112b56a2d8aSVineeth Remanan Pillai 	/*
2113b56a2d8aSVineeth Remanan Pillai 	 * Lets check again to see if there are still swap entries in the map.
2114b56a2d8aSVineeth Remanan Pillai 	 * If yes, we would need to do retry the unuse logic again.
2115b56a2d8aSVineeth Remanan Pillai 	 * Under global memory pressure, swap entries can be reinserted back
2116b56a2d8aSVineeth Remanan Pillai 	 * into process space after the mmlist loop above passes over them.
2117dd862debSHugh Dickins 	 *
2118e2e3fdc7SMatthew Wilcox (Oracle) 	 * Limit the number of retries? No: when mmget_not_zero()
2119e2e3fdc7SMatthew Wilcox (Oracle) 	 * above fails, that mm is likely to be freeing swap from
2120e2e3fdc7SMatthew Wilcox (Oracle) 	 * exit_mmap(), which proceeds at its own independent pace;
2121e2e3fdc7SMatthew Wilcox (Oracle) 	 * and even shmem_writepage() could have been preempted after
2122e2e3fdc7SMatthew Wilcox (Oracle) 	 * folio_alloc_swap(), temporarily hiding that swap.  It's easy
2123e2e3fdc7SMatthew Wilcox (Oracle) 	 * and robust (though cpu-intensive) just to keep retrying.
2124b56a2d8aSVineeth Remanan Pillai 	 */
212521820948SQian Cai 	if (READ_ONCE(si->inuse_pages)) {
212664165b1aSHugh Dickins 		if (!signal_pending(current))
2127b56a2d8aSVineeth Remanan Pillai 			goto retry;
212810a9c496SChristoph Hellwig 		return -EINTR;
212964165b1aSHugh Dickins 	}
213010a9c496SChristoph Hellwig 
213110a9c496SChristoph Hellwig 	return 0;
21321da177e4SLinus Torvalds }
21331da177e4SLinus Torvalds 
21341da177e4SLinus Torvalds /*
21355d337b91SHugh Dickins  * After a successful try_to_unuse, if no swap is now in use, we know
21365d337b91SHugh Dickins  * we can empty the mmlist.  swap_lock must be held on entry and exit.
21375d337b91SHugh Dickins  * Note that mmlist_lock nests inside swap_lock, and an mm must be
21381da177e4SLinus Torvalds  * added to the mmlist just after page_duplicate - before would be racy.
21391da177e4SLinus Torvalds  */
21401da177e4SLinus Torvalds static void drain_mmlist(void)
21411da177e4SLinus Torvalds {
21421da177e4SLinus Torvalds 	struct list_head *p, *next;
2143efa90a98SHugh Dickins 	unsigned int type;
21441da177e4SLinus Torvalds 
2145efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++)
2146efa90a98SHugh Dickins 		if (swap_info[type]->inuse_pages)
21471da177e4SLinus Torvalds 			return;
21481da177e4SLinus Torvalds 	spin_lock(&mmlist_lock);
21491da177e4SLinus Torvalds 	list_for_each_safe(p, next, &init_mm.mmlist)
21501da177e4SLinus Torvalds 		list_del_init(p);
21511da177e4SLinus Torvalds 	spin_unlock(&mmlist_lock);
21521da177e4SLinus Torvalds }
21531da177e4SLinus Torvalds 
21541da177e4SLinus Torvalds /*
21551da177e4SLinus Torvalds  * Free all of a swapdev's extent information
21561da177e4SLinus Torvalds  */
21571da177e4SLinus Torvalds static void destroy_swap_extents(struct swap_info_struct *sis)
21581da177e4SLinus Torvalds {
21594efaceb1SAaron Lu 	while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
21604efaceb1SAaron Lu 		struct rb_node *rb = sis->swap_extent_root.rb_node;
21614efaceb1SAaron Lu 		struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
21621da177e4SLinus Torvalds 
21634efaceb1SAaron Lu 		rb_erase(rb, &sis->swap_extent_root);
21641da177e4SLinus Torvalds 		kfree(se);
21651da177e4SLinus Torvalds 	}
216662c230bcSMel Gorman 
2167bc4ae27dSOmar Sandoval 	if (sis->flags & SWP_ACTIVATED) {
216862c230bcSMel Gorman 		struct file *swap_file = sis->swap_file;
216962c230bcSMel Gorman 		struct address_space *mapping = swap_file->f_mapping;
217062c230bcSMel Gorman 
2171bc4ae27dSOmar Sandoval 		sis->flags &= ~SWP_ACTIVATED;
2172bc4ae27dSOmar Sandoval 		if (mapping->a_ops->swap_deactivate)
217362c230bcSMel Gorman 			mapping->a_ops->swap_deactivate(swap_file);
217462c230bcSMel Gorman 	}
21751da177e4SLinus Torvalds }
21761da177e4SLinus Torvalds 
21771da177e4SLinus Torvalds /*
21781da177e4SLinus Torvalds  * Add a block range (and the corresponding page range) into this swapdev's
21794efaceb1SAaron Lu  * extent tree.
21801da177e4SLinus Torvalds  *
218111d31886SHugh Dickins  * This function rather assumes that it is called in ascending page order.
21821da177e4SLinus Torvalds  */
2183a509bc1aSMel Gorman int
21841da177e4SLinus Torvalds add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
21851da177e4SLinus Torvalds 		unsigned long nr_pages, sector_t start_block)
21861da177e4SLinus Torvalds {
21874efaceb1SAaron Lu 	struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
21881da177e4SLinus Torvalds 	struct swap_extent *se;
21891da177e4SLinus Torvalds 	struct swap_extent *new_se;
21901da177e4SLinus Torvalds 
21914efaceb1SAaron Lu 	/*
21924efaceb1SAaron Lu 	 * place the new node at the right most since the
21934efaceb1SAaron Lu 	 * function is called in ascending page order.
21944efaceb1SAaron Lu 	 */
21954efaceb1SAaron Lu 	while (*link) {
21964efaceb1SAaron Lu 		parent = *link;
21974efaceb1SAaron Lu 		link = &parent->rb_right;
21984efaceb1SAaron Lu 	}
21994efaceb1SAaron Lu 
22004efaceb1SAaron Lu 	if (parent) {
22014efaceb1SAaron Lu 		se = rb_entry(parent, struct swap_extent, rb_node);
220211d31886SHugh Dickins 		BUG_ON(se->start_page + se->nr_pages != start_page);
220311d31886SHugh Dickins 		if (se->start_block + se->nr_pages == start_block) {
22041da177e4SLinus Torvalds 			/* Merge it */
22051da177e4SLinus Torvalds 			se->nr_pages += nr_pages;
22061da177e4SLinus Torvalds 			return 0;
22071da177e4SLinus Torvalds 		}
22081da177e4SLinus Torvalds 	}
22091da177e4SLinus Torvalds 
22104efaceb1SAaron Lu 	/* No merge, insert a new extent. */
22111da177e4SLinus Torvalds 	new_se = kmalloc(sizeof(*se), GFP_KERNEL);
22121da177e4SLinus Torvalds 	if (new_se == NULL)
22131da177e4SLinus Torvalds 		return -ENOMEM;
22141da177e4SLinus Torvalds 	new_se->start_page = start_page;
22151da177e4SLinus Torvalds 	new_se->nr_pages = nr_pages;
22161da177e4SLinus Torvalds 	new_se->start_block = start_block;
22171da177e4SLinus Torvalds 
22184efaceb1SAaron Lu 	rb_link_node(&new_se->rb_node, parent, link);
22194efaceb1SAaron Lu 	rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
222053092a74SHugh Dickins 	return 1;
22211da177e4SLinus Torvalds }
2222aa8aa8a3SOmar Sandoval EXPORT_SYMBOL_GPL(add_swap_extent);
22231da177e4SLinus Torvalds 
22241da177e4SLinus Torvalds /*
22251da177e4SLinus Torvalds  * A `swap extent' is a simple thing which maps a contiguous range of pages
2226ff351f4bSMiaohe Lin  * onto a contiguous range of disk blocks.  A rbtree of swap extents is
2227ff351f4bSMiaohe Lin  * built at swapon time and is then used at swap_writepage/swap_readpage
22281da177e4SLinus Torvalds  * time for locating where on disk a page belongs.
22291da177e4SLinus Torvalds  *
22301da177e4SLinus Torvalds  * If the swapfile is an S_ISBLK block device, a single extent is installed.
22311da177e4SLinus Torvalds  * This is done so that the main operating code can treat S_ISBLK and S_ISREG
22321da177e4SLinus Torvalds  * swap files identically.
22331da177e4SLinus Torvalds  *
22341da177e4SLinus Torvalds  * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
2235ff351f4bSMiaohe Lin  * extent rbtree operates in PAGE_SIZE disk blocks.  Both S_ISREG and S_ISBLK
22361da177e4SLinus Torvalds  * swapfiles are handled *identically* after swapon time.
22371da177e4SLinus Torvalds  *
22381da177e4SLinus Torvalds  * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
2239ff351f4bSMiaohe Lin  * and will parse them into a rbtree, in PAGE_SIZE chunks.  If some stray
2240ff351f4bSMiaohe Lin  * blocks are found which do not fall within the PAGE_SIZE alignment
22411da177e4SLinus Torvalds  * requirements, they are simply tossed out - we will never use those blocks
22421da177e4SLinus Torvalds  * for swapping.
22431da177e4SLinus Torvalds  *
22441638045cSDarrick J. Wong  * For all swap devices we set S_SWAPFILE across the life of the swapon.  This
22451638045cSDarrick J. Wong  * prevents users from writing to the swap device, which will corrupt memory.
22461da177e4SLinus Torvalds  *
22471da177e4SLinus Torvalds  * The amount of disk space which a single swap extent represents varies.
22481da177e4SLinus Torvalds  * Typically it is in the 1-4 megabyte range.  So we can have hundreds of
2249ff351f4bSMiaohe Lin  * extents in the rbtree. - akpm.
22501da177e4SLinus Torvalds  */
225153092a74SHugh Dickins static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
22521da177e4SLinus Torvalds {
225362c230bcSMel Gorman 	struct file *swap_file = sis->swap_file;
225462c230bcSMel Gorman 	struct address_space *mapping = swap_file->f_mapping;
225562c230bcSMel Gorman 	struct inode *inode = mapping->host;
22561da177e4SLinus Torvalds 	int ret;
22571da177e4SLinus Torvalds 
22581da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
22591da177e4SLinus Torvalds 		ret = add_swap_extent(sis, 0, sis->max, 0);
226053092a74SHugh Dickins 		*span = sis->pages;
2261a509bc1aSMel Gorman 		return ret;
22621da177e4SLinus Torvalds 	}
22631da177e4SLinus Torvalds 
226462c230bcSMel Gorman 	if (mapping->a_ops->swap_activate) {
2265a509bc1aSMel Gorman 		ret = mapping->a_ops->swap_activate(sis, swap_file, span);
22664b60c0ffSNeilBrown 		if (ret < 0)
22674b60c0ffSNeilBrown 			return ret;
2268bc4ae27dSOmar Sandoval 		sis->flags |= SWP_ACTIVATED;
2269e1209d3aSNeilBrown 		if ((sis->flags & SWP_FS_OPS) &&
2270e1209d3aSNeilBrown 		    sio_pool_init() != 0) {
2271e1209d3aSNeilBrown 			destroy_swap_extents(sis);
2272e1209d3aSNeilBrown 			return -ENOMEM;
227362c230bcSMel Gorman 		}
22749625a5f2SHugh Dickins 		return ret;
2275a509bc1aSMel Gorman 	}
2276a509bc1aSMel Gorman 
2277a509bc1aSMel Gorman 	return generic_swapfile_activate(sis, swap_file, span);
22781da177e4SLinus Torvalds }
22791da177e4SLinus Torvalds 
2280a2468cc9SAaron Lu static int swap_node(struct swap_info_struct *p)
2281a2468cc9SAaron Lu {
2282a2468cc9SAaron Lu 	struct block_device *bdev;
2283a2468cc9SAaron Lu 
2284a2468cc9SAaron Lu 	if (p->bdev)
2285a2468cc9SAaron Lu 		bdev = p->bdev;
2286a2468cc9SAaron Lu 	else
2287a2468cc9SAaron Lu 		bdev = p->swap_file->f_inode->i_sb->s_bdev;
2288a2468cc9SAaron Lu 
2289a2468cc9SAaron Lu 	return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
2290a2468cc9SAaron Lu }
2291a2468cc9SAaron Lu 
2292eb085574SHuang Ying static void setup_swap_info(struct swap_info_struct *p, int prio,
22932a8f9449SShaohua Li 			    unsigned char *swap_map,
22942a8f9449SShaohua Li 			    struct swap_cluster_info *cluster_info)
229540531542SCesar Eduardo Barros {
2296a2468cc9SAaron Lu 	int i;
2297a2468cc9SAaron Lu 
229840531542SCesar Eduardo Barros 	if (prio >= 0)
229940531542SCesar Eduardo Barros 		p->prio = prio;
230040531542SCesar Eduardo Barros 	else
230140531542SCesar Eduardo Barros 		p->prio = --least_priority;
230218ab4d4cSDan Streetman 	/*
230318ab4d4cSDan Streetman 	 * the plist prio is negated because plist ordering is
230418ab4d4cSDan Streetman 	 * low-to-high, while swap ordering is high-to-low
230518ab4d4cSDan Streetman 	 */
230618ab4d4cSDan Streetman 	p->list.prio = -p->prio;
2307a2468cc9SAaron Lu 	for_each_node(i) {
2308a2468cc9SAaron Lu 		if (p->prio >= 0)
2309a2468cc9SAaron Lu 			p->avail_lists[i].prio = -p->prio;
2310a2468cc9SAaron Lu 		else {
2311a2468cc9SAaron Lu 			if (swap_node(p) == i)
2312a2468cc9SAaron Lu 				p->avail_lists[i].prio = 1;
2313a2468cc9SAaron Lu 			else
2314a2468cc9SAaron Lu 				p->avail_lists[i].prio = -p->prio;
2315a2468cc9SAaron Lu 		}
2316a2468cc9SAaron Lu 	}
231740531542SCesar Eduardo Barros 	p->swap_map = swap_map;
23182a8f9449SShaohua Li 	p->cluster_info = cluster_info;
2319eb085574SHuang Ying }
2320eb085574SHuang Ying 
2321eb085574SHuang Ying static void _enable_swap_info(struct swap_info_struct *p)
2322eb085574SHuang Ying {
232363d8620eSMiaohe Lin 	p->flags |= SWP_WRITEOK;
2324ec8acf20SShaohua Li 	atomic_long_add(p->pages, &nr_swap_pages);
232540531542SCesar Eduardo Barros 	total_swap_pages += p->pages;
232640531542SCesar Eduardo Barros 
2327adfab836SDan Streetman 	assert_spin_locked(&swap_lock);
2328adfab836SDan Streetman 	/*
232918ab4d4cSDan Streetman 	 * both lists are plists, and thus priority ordered.
233018ab4d4cSDan Streetman 	 * swap_active_head needs to be priority ordered for swapoff(),
233118ab4d4cSDan Streetman 	 * which on removal of any swap_info_struct with an auto-assigned
233218ab4d4cSDan Streetman 	 * (i.e. negative) priority increments the auto-assigned priority
233318ab4d4cSDan Streetman 	 * of any lower-priority swap_info_structs.
2334e2e3fdc7SMatthew Wilcox (Oracle) 	 * swap_avail_head needs to be priority ordered for folio_alloc_swap(),
233518ab4d4cSDan Streetman 	 * which allocates swap pages from the highest available priority
233618ab4d4cSDan Streetman 	 * swap_info_struct.
2337adfab836SDan Streetman 	 */
233818ab4d4cSDan Streetman 	plist_add(&p->list, &swap_active_head);
2339c70699e5SMa Wupeng 
2340c70699e5SMa Wupeng 	/* add to available list iff swap device is not full */
2341c70699e5SMa Wupeng 	if (p->highest_bit)
2342a2468cc9SAaron Lu 		add_to_avail_list(p);
2343cf0cac0aSCesar Eduardo Barros }
2344cf0cac0aSCesar Eduardo Barros 
2345cf0cac0aSCesar Eduardo Barros static void enable_swap_info(struct swap_info_struct *p, int prio,
2346cf0cac0aSCesar Eduardo Barros 				unsigned char *swap_map,
234742c06a0eSJohannes Weiner 				struct swap_cluster_info *cluster_info)
2348cf0cac0aSCesar Eduardo Barros {
234942c06a0eSJohannes Weiner 	zswap_swapon(p->type);
235042c06a0eSJohannes Weiner 
2351cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2352ec8acf20SShaohua Li 	spin_lock(&p->lock);
2353eb085574SHuang Ying 	setup_swap_info(p, prio, swap_map, cluster_info);
2354eb085574SHuang Ying 	spin_unlock(&p->lock);
2355eb085574SHuang Ying 	spin_unlock(&swap_lock);
2356eb085574SHuang Ying 	/*
235763d8620eSMiaohe Lin 	 * Finished initializing swap device, now it's safe to reference it.
2358eb085574SHuang Ying 	 */
235963d8620eSMiaohe Lin 	percpu_ref_resurrect(&p->users);
2360eb085574SHuang Ying 	spin_lock(&swap_lock);
2361eb085574SHuang Ying 	spin_lock(&p->lock);
2362eb085574SHuang Ying 	_enable_swap_info(p);
2363ec8acf20SShaohua Li 	spin_unlock(&p->lock);
2364cf0cac0aSCesar Eduardo Barros 	spin_unlock(&swap_lock);
2365cf0cac0aSCesar Eduardo Barros }
2366cf0cac0aSCesar Eduardo Barros 
2367cf0cac0aSCesar Eduardo Barros static void reinsert_swap_info(struct swap_info_struct *p)
2368cf0cac0aSCesar Eduardo Barros {
2369cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2370ec8acf20SShaohua Li 	spin_lock(&p->lock);
2371eb085574SHuang Ying 	setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2372eb085574SHuang Ying 	_enable_swap_info(p);
2373ec8acf20SShaohua Li 	spin_unlock(&p->lock);
237440531542SCesar Eduardo Barros 	spin_unlock(&swap_lock);
237540531542SCesar Eduardo Barros }
237640531542SCesar Eduardo Barros 
237767afa38eSTim Chen bool has_usable_swap(void)
237867afa38eSTim Chen {
237967afa38eSTim Chen 	bool ret = true;
238067afa38eSTim Chen 
238167afa38eSTim Chen 	spin_lock(&swap_lock);
238267afa38eSTim Chen 	if (plist_head_empty(&swap_active_head))
238367afa38eSTim Chen 		ret = false;
238467afa38eSTim Chen 	spin_unlock(&swap_lock);
238567afa38eSTim Chen 	return ret;
238667afa38eSTim Chen }
238767afa38eSTim Chen 
2388c4ea37c2SHeiko Carstens SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
23891da177e4SLinus Torvalds {
23901da177e4SLinus Torvalds 	struct swap_info_struct *p = NULL;
23918d69aaeeSHugh Dickins 	unsigned char *swap_map;
23922a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info;
23931da177e4SLinus Torvalds 	struct file *swap_file, *victim;
23941da177e4SLinus Torvalds 	struct address_space *mapping;
23951da177e4SLinus Torvalds 	struct inode *inode;
239691a27b2aSJeff Layton 	struct filename *pathname;
2397adfab836SDan Streetman 	int err, found = 0;
23985b808a23SKrzysztof Kozlowski 	unsigned int old_block_size;
23991da177e4SLinus Torvalds 
24001da177e4SLinus Torvalds 	if (!capable(CAP_SYS_ADMIN))
24011da177e4SLinus Torvalds 		return -EPERM;
24021da177e4SLinus Torvalds 
2403191c5424SAl Viro 	BUG_ON(!current->mm);
2404191c5424SAl Viro 
24051da177e4SLinus Torvalds 	pathname = getname(specialfile);
24061da177e4SLinus Torvalds 	if (IS_ERR(pathname))
2407f58b59c1SXiaotian Feng 		return PTR_ERR(pathname);
24081da177e4SLinus Torvalds 
2409669abf4eSJeff Layton 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
24101da177e4SLinus Torvalds 	err = PTR_ERR(victim);
24111da177e4SLinus Torvalds 	if (IS_ERR(victim))
24121da177e4SLinus Torvalds 		goto out;
24131da177e4SLinus Torvalds 
24141da177e4SLinus Torvalds 	mapping = victim->f_mapping;
24155d337b91SHugh Dickins 	spin_lock(&swap_lock);
241618ab4d4cSDan Streetman 	plist_for_each_entry(p, &swap_active_head, list) {
241722c6f8fdSHugh Dickins 		if (p->flags & SWP_WRITEOK) {
2418adfab836SDan Streetman 			if (p->swap_file->f_mapping == mapping) {
2419adfab836SDan Streetman 				found = 1;
24201da177e4SLinus Torvalds 				break;
24211da177e4SLinus Torvalds 			}
24221da177e4SLinus Torvalds 		}
2423adfab836SDan Streetman 	}
2424adfab836SDan Streetman 	if (!found) {
24251da177e4SLinus Torvalds 		err = -EINVAL;
24265d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24271da177e4SLinus Torvalds 		goto out_dput;
24281da177e4SLinus Torvalds 	}
2429191c5424SAl Viro 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
24301da177e4SLinus Torvalds 		vm_unacct_memory(p->pages);
24311da177e4SLinus Torvalds 	else {
24321da177e4SLinus Torvalds 		err = -ENOMEM;
24335d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24341da177e4SLinus Torvalds 		goto out_dput;
24351da177e4SLinus Torvalds 	}
2436ec8acf20SShaohua Li 	spin_lock(&p->lock);
24376fe7d6b9SRongwei Wang 	del_from_avail_list(p);
243878ecba08SHugh Dickins 	if (p->prio < 0) {
2439adfab836SDan Streetman 		struct swap_info_struct *si = p;
2440a2468cc9SAaron Lu 		int nid;
2441adfab836SDan Streetman 
244218ab4d4cSDan Streetman 		plist_for_each_entry_continue(si, &swap_active_head, list) {
2443adfab836SDan Streetman 			si->prio++;
244418ab4d4cSDan Streetman 			si->list.prio--;
2445a2468cc9SAaron Lu 			for_each_node(nid) {
2446a2468cc9SAaron Lu 				if (si->avail_lists[nid].prio != 1)
2447a2468cc9SAaron Lu 					si->avail_lists[nid].prio--;
2448a2468cc9SAaron Lu 			}
2449adfab836SDan Streetman 		}
245078ecba08SHugh Dickins 		least_priority++;
245178ecba08SHugh Dickins 	}
245218ab4d4cSDan Streetman 	plist_del(&p->list, &swap_active_head);
2453ec8acf20SShaohua Li 	atomic_long_sub(p->pages, &nr_swap_pages);
24541da177e4SLinus Torvalds 	total_swap_pages -= p->pages;
24551da177e4SLinus Torvalds 	p->flags &= ~SWP_WRITEOK;
2456ec8acf20SShaohua Li 	spin_unlock(&p->lock);
24575d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2458fb4f88dcSHugh Dickins 
2459039939a6STim Chen 	disable_swap_slots_cache_lock();
2460039939a6STim Chen 
2461e1e12d2fSDavid Rientjes 	set_current_oom_origin();
246210a9c496SChristoph Hellwig 	err = try_to_unuse(p->type);
2463e1e12d2fSDavid Rientjes 	clear_current_oom_origin();
24641da177e4SLinus Torvalds 
24651da177e4SLinus Torvalds 	if (err) {
24661da177e4SLinus Torvalds 		/* re-insert swap space back into swap_list */
2467cf0cac0aSCesar Eduardo Barros 		reinsert_swap_info(p);
2468039939a6STim Chen 		reenable_swap_slots_cache_unlock();
24691da177e4SLinus Torvalds 		goto out_dput;
24701da177e4SLinus Torvalds 	}
247152b7efdbSHugh Dickins 
2472039939a6STim Chen 	reenable_swap_slots_cache_unlock();
2473039939a6STim Chen 
2474eb085574SHuang Ying 	/*
247563d8620eSMiaohe Lin 	 * Wait for swap operations protected by get/put_swap_device()
247663d8620eSMiaohe Lin 	 * to complete.
247763d8620eSMiaohe Lin 	 *
247863d8620eSMiaohe Lin 	 * We need synchronize_rcu() here to protect the accessing to
247963d8620eSMiaohe Lin 	 * the swap cache data structure.
2480eb085574SHuang Ying 	 */
248163d8620eSMiaohe Lin 	percpu_ref_kill(&p->users);
2482eb085574SHuang Ying 	synchronize_rcu();
248363d8620eSMiaohe Lin 	wait_for_completion(&p->comp);
2484eb085574SHuang Ying 
2485815c2c54SShaohua Li 	flush_work(&p->discard_work);
2486815c2c54SShaohua Li 
24874cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2488570a335bSHugh Dickins 	if (p->flags & SWP_CONTINUED)
2489570a335bSHugh Dickins 		free_swap_count_continuations(p);
2490570a335bSHugh Dickins 
249110f0d2a5SChristoph Hellwig 	if (!p->bdev || !bdev_nonrot(p->bdev))
249281a0298bSHuang Ying 		atomic_dec(&nr_rotate_swap);
249381a0298bSHuang Ying 
2494fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
24955d337b91SHugh Dickins 	spin_lock(&swap_lock);
2496ec8acf20SShaohua Li 	spin_lock(&p->lock);
24971da177e4SLinus Torvalds 	drain_mmlist();
24985d337b91SHugh Dickins 
2499bb243f7dSMiaohe Lin 	/* wait for anyone still in scan_swap_map_slots */
25005d337b91SHugh Dickins 	p->highest_bit = 0;		/* cuts scans short */
25015d337b91SHugh Dickins 	while (p->flags >= SWP_SCANNING) {
2502ec8acf20SShaohua Li 		spin_unlock(&p->lock);
25035d337b91SHugh Dickins 		spin_unlock(&swap_lock);
250413e4b57fSNishanth Aravamudan 		schedule_timeout_uninterruptible(1);
25055d337b91SHugh Dickins 		spin_lock(&swap_lock);
2506ec8acf20SShaohua Li 		spin_lock(&p->lock);
25075d337b91SHugh Dickins 	}
25085d337b91SHugh Dickins 
25091da177e4SLinus Torvalds 	swap_file = p->swap_file;
25105b808a23SKrzysztof Kozlowski 	old_block_size = p->old_block_size;
25111da177e4SLinus Torvalds 	p->swap_file = NULL;
25121da177e4SLinus Torvalds 	p->max = 0;
25131da177e4SLinus Torvalds 	swap_map = p->swap_map;
25141da177e4SLinus Torvalds 	p->swap_map = NULL;
25152a8f9449SShaohua Li 	cluster_info = p->cluster_info;
25162a8f9449SShaohua Li 	p->cluster_info = NULL;
2517ec8acf20SShaohua Li 	spin_unlock(&p->lock);
25185d337b91SHugh Dickins 	spin_unlock(&swap_lock);
25198a84802eSSteven Price 	arch_swap_invalidate_area(p->type);
252042c06a0eSJohannes Weiner 	zswap_swapoff(p->type);
2521fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
2522ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2523ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
252449070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
252549070588SHuang Ying 	p->cluster_next_cpu = NULL;
25261da177e4SLinus Torvalds 	vfree(swap_map);
252754f180d3SHuang Ying 	kvfree(cluster_info);
25282de1a7e4SSeth Jennings 	/* Destroy swap account information */
2529adfab836SDan Streetman 	swap_cgroup_swapoff(p->type);
25304b3ef9daSHuang, Ying 	exit_swap_address_space(p->type);
253127a7faa0SKAMEZAWA Hiroyuki 
25321da177e4SLinus Torvalds 	inode = mapping->host;
25331da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
25341da177e4SLinus Torvalds 		struct block_device *bdev = I_BDEV(inode);
25351638045cSDarrick J. Wong 
25365b808a23SKrzysztof Kozlowski 		set_blocksize(bdev, old_block_size);
25372736e8eeSChristoph Hellwig 		blkdev_put(bdev, p);
25381638045cSDarrick J. Wong 	}
25391638045cSDarrick J. Wong 
25405955102cSAl Viro 	inode_lock(inode);
25411da177e4SLinus Torvalds 	inode->i_flags &= ~S_SWAPFILE;
25425955102cSAl Viro 	inode_unlock(inode);
25431da177e4SLinus Torvalds 	filp_close(swap_file, NULL);
2544f893ab41SWeijie Yang 
2545f893ab41SWeijie Yang 	/*
2546f893ab41SWeijie Yang 	 * Clear the SWP_USED flag after all resources are freed so that swapon
2547f893ab41SWeijie Yang 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2548f893ab41SWeijie Yang 	 * not hold p->lock after we cleared its SWP_WRITEOK.
2549f893ab41SWeijie Yang 	 */
2550f893ab41SWeijie Yang 	spin_lock(&swap_lock);
2551f893ab41SWeijie Yang 	p->flags = 0;
2552f893ab41SWeijie Yang 	spin_unlock(&swap_lock);
2553f893ab41SWeijie Yang 
25541da177e4SLinus Torvalds 	err = 0;
255566d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
255666d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
25571da177e4SLinus Torvalds 
25581da177e4SLinus Torvalds out_dput:
25591da177e4SLinus Torvalds 	filp_close(victim, NULL);
25601da177e4SLinus Torvalds out:
2561f58b59c1SXiaotian Feng 	putname(pathname);
25621da177e4SLinus Torvalds 	return err;
25631da177e4SLinus Torvalds }
25641da177e4SLinus Torvalds 
25651da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
25669dd95748SAl Viro static __poll_t swaps_poll(struct file *file, poll_table *wait)
256766d7dd51SKay Sievers {
2568f1514638SKay Sievers 	struct seq_file *seq = file->private_data;
256966d7dd51SKay Sievers 
257066d7dd51SKay Sievers 	poll_wait(file, &proc_poll_wait, wait);
257166d7dd51SKay Sievers 
2572f1514638SKay Sievers 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
2573f1514638SKay Sievers 		seq->poll_event = atomic_read(&proc_poll_event);
2574a9a08845SLinus Torvalds 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
257566d7dd51SKay Sievers 	}
257666d7dd51SKay Sievers 
2577a9a08845SLinus Torvalds 	return EPOLLIN | EPOLLRDNORM;
257866d7dd51SKay Sievers }
257966d7dd51SKay Sievers 
25801da177e4SLinus Torvalds /* iterator */
25811da177e4SLinus Torvalds static void *swap_start(struct seq_file *swap, loff_t *pos)
25821da177e4SLinus Torvalds {
2583efa90a98SHugh Dickins 	struct swap_info_struct *si;
2584efa90a98SHugh Dickins 	int type;
25851da177e4SLinus Torvalds 	loff_t l = *pos;
25861da177e4SLinus Torvalds 
2587fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
25881da177e4SLinus Torvalds 
2589881e4aabSSuleiman Souhlal 	if (!l)
2590881e4aabSSuleiman Souhlal 		return SEQ_START_TOKEN;
2591881e4aabSSuleiman Souhlal 
2592c10d38ccSDaniel Jordan 	for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2593efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
25941da177e4SLinus Torvalds 			continue;
2595881e4aabSSuleiman Souhlal 		if (!--l)
2596efa90a98SHugh Dickins 			return si;
25971da177e4SLinus Torvalds 	}
25981da177e4SLinus Torvalds 
25991da177e4SLinus Torvalds 	return NULL;
26001da177e4SLinus Torvalds }
26011da177e4SLinus Torvalds 
26021da177e4SLinus Torvalds static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
26031da177e4SLinus Torvalds {
2604efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
2605efa90a98SHugh Dickins 	int type;
26061da177e4SLinus Torvalds 
2607881e4aabSSuleiman Souhlal 	if (v == SEQ_START_TOKEN)
2608efa90a98SHugh Dickins 		type = 0;
2609efa90a98SHugh Dickins 	else
2610efa90a98SHugh Dickins 		type = si->type + 1;
2611881e4aabSSuleiman Souhlal 
261210c8d69fSVasily Averin 	++(*pos);
2613c10d38ccSDaniel Jordan 	for (; (si = swap_type_to_swap_info(type)); type++) {
2614efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
26151da177e4SLinus Torvalds 			continue;
2616efa90a98SHugh Dickins 		return si;
26171da177e4SLinus Torvalds 	}
26181da177e4SLinus Torvalds 
26191da177e4SLinus Torvalds 	return NULL;
26201da177e4SLinus Torvalds }
26211da177e4SLinus Torvalds 
26221da177e4SLinus Torvalds static void swap_stop(struct seq_file *swap, void *v)
26231da177e4SLinus Torvalds {
2624fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
26251da177e4SLinus Torvalds }
26261da177e4SLinus Torvalds 
26271da177e4SLinus Torvalds static int swap_show(struct seq_file *swap, void *v)
26281da177e4SLinus Torvalds {
2629efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
26301da177e4SLinus Torvalds 	struct file *file;
26311da177e4SLinus Torvalds 	int len;
2632642929a2SRafael Aquini 	unsigned long bytes, inuse;
26331da177e4SLinus Torvalds 
2634efa90a98SHugh Dickins 	if (si == SEQ_START_TOKEN) {
26356f793940SRandy Dunlap 		seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2636881e4aabSSuleiman Souhlal 		return 0;
2637881e4aabSSuleiman Souhlal 	}
26381da177e4SLinus Torvalds 
2639*00cde042SZhangPeng 	bytes = K(si->pages);
2640*00cde042SZhangPeng 	inuse = K(READ_ONCE(si->inuse_pages));
26416f793940SRandy Dunlap 
2642efa90a98SHugh Dickins 	file = si->swap_file;
26432726d566SMiklos Szeredi 	len = seq_file_path(swap, file, " \t\n\\");
2644642929a2SRafael Aquini 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
26451da177e4SLinus Torvalds 			len < 40 ? 40 - len : 1, " ",
2646496ad9aaSAl Viro 			S_ISBLK(file_inode(file)->i_mode) ?
26471da177e4SLinus Torvalds 				"partition" : "file\t",
26486f793940SRandy Dunlap 			bytes, bytes < 10000000 ? "\t" : "",
26496f793940SRandy Dunlap 			inuse, inuse < 10000000 ? "\t" : "",
2650efa90a98SHugh Dickins 			si->prio);
26511da177e4SLinus Torvalds 	return 0;
26521da177e4SLinus Torvalds }
26531da177e4SLinus Torvalds 
265415ad7cdcSHelge Deller static const struct seq_operations swaps_op = {
26551da177e4SLinus Torvalds 	.start =	swap_start,
26561da177e4SLinus Torvalds 	.next =		swap_next,
26571da177e4SLinus Torvalds 	.stop =		swap_stop,
26581da177e4SLinus Torvalds 	.show =		swap_show
26591da177e4SLinus Torvalds };
26601da177e4SLinus Torvalds 
26611da177e4SLinus Torvalds static int swaps_open(struct inode *inode, struct file *file)
26621da177e4SLinus Torvalds {
2663f1514638SKay Sievers 	struct seq_file *seq;
266466d7dd51SKay Sievers 	int ret;
266566d7dd51SKay Sievers 
266666d7dd51SKay Sievers 	ret = seq_open(file, &swaps_op);
2667f1514638SKay Sievers 	if (ret)
266866d7dd51SKay Sievers 		return ret;
266966d7dd51SKay Sievers 
2670f1514638SKay Sievers 	seq = file->private_data;
2671f1514638SKay Sievers 	seq->poll_event = atomic_read(&proc_poll_event);
2672f1514638SKay Sievers 	return 0;
26731da177e4SLinus Torvalds }
26741da177e4SLinus Torvalds 
267597a32539SAlexey Dobriyan static const struct proc_ops swaps_proc_ops = {
2676d919b33dSAlexey Dobriyan 	.proc_flags	= PROC_ENTRY_PERMANENT,
267797a32539SAlexey Dobriyan 	.proc_open	= swaps_open,
267897a32539SAlexey Dobriyan 	.proc_read	= seq_read,
267997a32539SAlexey Dobriyan 	.proc_lseek	= seq_lseek,
268097a32539SAlexey Dobriyan 	.proc_release	= seq_release,
268197a32539SAlexey Dobriyan 	.proc_poll	= swaps_poll,
26821da177e4SLinus Torvalds };
26831da177e4SLinus Torvalds 
26841da177e4SLinus Torvalds static int __init procswaps_init(void)
26851da177e4SLinus Torvalds {
268697a32539SAlexey Dobriyan 	proc_create("swaps", 0, NULL, &swaps_proc_ops);
26871da177e4SLinus Torvalds 	return 0;
26881da177e4SLinus Torvalds }
26891da177e4SLinus Torvalds __initcall(procswaps_init);
26901da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
26911da177e4SLinus Torvalds 
26921796316aSJan Beulich #ifdef MAX_SWAPFILES_CHECK
26931796316aSJan Beulich static int __init max_swapfiles_check(void)
26941796316aSJan Beulich {
26951796316aSJan Beulich 	MAX_SWAPFILES_CHECK();
26961796316aSJan Beulich 	return 0;
26971796316aSJan Beulich }
26981796316aSJan Beulich late_initcall(max_swapfiles_check);
26991796316aSJan Beulich #endif
27001796316aSJan Beulich 
270153cbb243SCesar Eduardo Barros static struct swap_info_struct *alloc_swap_info(void)
27021da177e4SLinus Torvalds {
27031da177e4SLinus Torvalds 	struct swap_info_struct *p;
2704b11a76b3SQian Cai 	struct swap_info_struct *defer = NULL;
27051da177e4SLinus Torvalds 	unsigned int type;
2706a2468cc9SAaron Lu 	int i;
2707efa90a98SHugh Dickins 
270896008744SGustavo A. R. Silva 	p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2709efa90a98SHugh Dickins 	if (!p)
271053cbb243SCesar Eduardo Barros 		return ERR_PTR(-ENOMEM);
2711efa90a98SHugh Dickins 
271263d8620eSMiaohe Lin 	if (percpu_ref_init(&p->users, swap_users_ref_free,
271363d8620eSMiaohe Lin 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
271463d8620eSMiaohe Lin 		kvfree(p);
271563d8620eSMiaohe Lin 		return ERR_PTR(-ENOMEM);
271663d8620eSMiaohe Lin 	}
271763d8620eSMiaohe Lin 
27185d337b91SHugh Dickins 	spin_lock(&swap_lock);
2719efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2720efa90a98SHugh Dickins 		if (!(swap_info[type]->flags & SWP_USED))
27211da177e4SLinus Torvalds 			break;
2722efa90a98SHugh Dickins 	}
27230697212aSChristoph Lameter 	if (type >= MAX_SWAPFILES) {
27245d337b91SHugh Dickins 		spin_unlock(&swap_lock);
272563d8620eSMiaohe Lin 		percpu_ref_exit(&p->users);
2726873d7bcfSVasily Averin 		kvfree(p);
2727730c0581SCesar Eduardo Barros 		return ERR_PTR(-EPERM);
27281da177e4SLinus Torvalds 	}
2729efa90a98SHugh Dickins 	if (type >= nr_swapfiles) {
2730efa90a98SHugh Dickins 		p->type = type;
2731efa90a98SHugh Dickins 		/*
2732a4b45114SHuang Ying 		 * Publish the swap_info_struct after initializing it.
2733a4b45114SHuang Ying 		 * Note that kvzalloc() above zeroes all its fields.
2734efa90a98SHugh Dickins 		 */
2735a4b45114SHuang Ying 		smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
2736a4b45114SHuang Ying 		nr_swapfiles++;
2737efa90a98SHugh Dickins 	} else {
2738b11a76b3SQian Cai 		defer = p;
2739efa90a98SHugh Dickins 		p = swap_info[type];
2740efa90a98SHugh Dickins 		/*
2741efa90a98SHugh Dickins 		 * Do not memset this entry: a racing procfs swap_next()
2742efa90a98SHugh Dickins 		 * would be relying on p->type to remain valid.
2743efa90a98SHugh Dickins 		 */
2744efa90a98SHugh Dickins 	}
27454efaceb1SAaron Lu 	p->swap_extent_root = RB_ROOT;
274618ab4d4cSDan Streetman 	plist_node_init(&p->list, 0);
2747a2468cc9SAaron Lu 	for_each_node(i)
2748a2468cc9SAaron Lu 		plist_node_init(&p->avail_lists[i], 0);
27491da177e4SLinus Torvalds 	p->flags = SWP_USED;
27505d337b91SHugh Dickins 	spin_unlock(&swap_lock);
275163d8620eSMiaohe Lin 	if (defer) {
275263d8620eSMiaohe Lin 		percpu_ref_exit(&defer->users);
2753b11a76b3SQian Cai 		kvfree(defer);
275463d8620eSMiaohe Lin 	}
2755ec8acf20SShaohua Li 	spin_lock_init(&p->lock);
27562628bd6fSHuang Ying 	spin_lock_init(&p->cont_lock);
275763d8620eSMiaohe Lin 	init_completion(&p->comp);
2758efa90a98SHugh Dickins 
275953cbb243SCesar Eduardo Barros 	return p;
276053cbb243SCesar Eduardo Barros }
276153cbb243SCesar Eduardo Barros 
27624d0e1e10SCesar Eduardo Barros static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
27634d0e1e10SCesar Eduardo Barros {
27644d0e1e10SCesar Eduardo Barros 	int error;
27654d0e1e10SCesar Eduardo Barros 
27664d0e1e10SCesar Eduardo Barros 	if (S_ISBLK(inode->i_mode)) {
2767ef16e1d9SChristoph Hellwig 		p->bdev = blkdev_get_by_dev(inode->i_rdev,
276805bdb996SChristoph Hellwig 				BLK_OPEN_READ | BLK_OPEN_WRITE, p, NULL);
2769ef16e1d9SChristoph Hellwig 		if (IS_ERR(p->bdev)) {
2770ef16e1d9SChristoph Hellwig 			error = PTR_ERR(p->bdev);
27714d0e1e10SCesar Eduardo Barros 			p->bdev = NULL;
27726f179af8SHugh Dickins 			return error;
27734d0e1e10SCesar Eduardo Barros 		}
27744d0e1e10SCesar Eduardo Barros 		p->old_block_size = block_size(p->bdev);
27754d0e1e10SCesar Eduardo Barros 		error = set_blocksize(p->bdev, PAGE_SIZE);
27764d0e1e10SCesar Eduardo Barros 		if (error < 0)
277787ade72aSCesar Eduardo Barros 			return error;
277812d2966dSNaohiro Aota 		/*
277912d2966dSNaohiro Aota 		 * Zoned block devices contain zones that have a sequential
278012d2966dSNaohiro Aota 		 * write only restriction.  Hence zoned block devices are not
278112d2966dSNaohiro Aota 		 * suitable for swapping.  Disallow them here.
278212d2966dSNaohiro Aota 		 */
27839964e674SChristoph Hellwig 		if (bdev_is_zoned(p->bdev))
278412d2966dSNaohiro Aota 			return -EINVAL;
27854d0e1e10SCesar Eduardo Barros 		p->flags |= SWP_BLKDEV;
27864d0e1e10SCesar Eduardo Barros 	} else if (S_ISREG(inode->i_mode)) {
27874d0e1e10SCesar Eduardo Barros 		p->bdev = inode->i_sb->s_bdev;
27881638045cSDarrick J. Wong 	}
27891638045cSDarrick J. Wong 
27904d0e1e10SCesar Eduardo Barros 	return 0;
27914d0e1e10SCesar Eduardo Barros }
27924d0e1e10SCesar Eduardo Barros 
2793377eeaa8SAndi Kleen 
2794377eeaa8SAndi Kleen /*
2795377eeaa8SAndi Kleen  * Find out how many pages are allowed for a single swap device. There
2796377eeaa8SAndi Kleen  * are two limiting factors:
2797377eeaa8SAndi Kleen  * 1) the number of bits for the swap offset in the swp_entry_t type, and
2798377eeaa8SAndi Kleen  * 2) the number of bits in the swap pte, as defined by the different
2799377eeaa8SAndi Kleen  * architectures.
2800377eeaa8SAndi Kleen  *
2801377eeaa8SAndi Kleen  * In order to find the largest possible bit mask, a swap entry with
2802377eeaa8SAndi Kleen  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2803377eeaa8SAndi Kleen  * decoded to a swp_entry_t again, and finally the swap offset is
2804377eeaa8SAndi Kleen  * extracted.
2805377eeaa8SAndi Kleen  *
2806377eeaa8SAndi Kleen  * This will mask all the bits from the initial ~0UL mask that can't
2807377eeaa8SAndi Kleen  * be encoded in either the swp_entry_t or the architecture definition
2808377eeaa8SAndi Kleen  * of a swap pte.
2809377eeaa8SAndi Kleen  */
2810377eeaa8SAndi Kleen unsigned long generic_max_swapfile_size(void)
2811377eeaa8SAndi Kleen {
2812377eeaa8SAndi Kleen 	return swp_offset(pte_to_swp_entry(
2813377eeaa8SAndi Kleen 			swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2814377eeaa8SAndi Kleen }
2815377eeaa8SAndi Kleen 
2816377eeaa8SAndi Kleen /* Can be overridden by an architecture for additional checks. */
2817be45a490SPeter Xu __weak unsigned long arch_max_swapfile_size(void)
2818377eeaa8SAndi Kleen {
2819377eeaa8SAndi Kleen 	return generic_max_swapfile_size();
2820377eeaa8SAndi Kleen }
2821377eeaa8SAndi Kleen 
2822ca8bd38bSCesar Eduardo Barros static unsigned long read_swap_header(struct swap_info_struct *p,
2823ca8bd38bSCesar Eduardo Barros 					union swap_header *swap_header,
2824ca8bd38bSCesar Eduardo Barros 					struct inode *inode)
2825ca8bd38bSCesar Eduardo Barros {
2826ca8bd38bSCesar Eduardo Barros 	int i;
2827ca8bd38bSCesar Eduardo Barros 	unsigned long maxpages;
2828ca8bd38bSCesar Eduardo Barros 	unsigned long swapfilepages;
2829d6bbbd29SRaymond Jennings 	unsigned long last_page;
2830ca8bd38bSCesar Eduardo Barros 
2831ca8bd38bSCesar Eduardo Barros 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2832465c47fdSAndrew Morton 		pr_err("Unable to find swap-space signature\n");
283338719025SCesar Eduardo Barros 		return 0;
2834ca8bd38bSCesar Eduardo Barros 	}
2835ca8bd38bSCesar Eduardo Barros 
2836041711ceSZhen Lei 	/* swap partition endianness hack... */
2837ca8bd38bSCesar Eduardo Barros 	if (swab32(swap_header->info.version) == 1) {
2838ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.version);
2839ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.last_page);
2840ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.nr_badpages);
2841dd111be6SJann Horn 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2842dd111be6SJann Horn 			return 0;
2843ca8bd38bSCesar Eduardo Barros 		for (i = 0; i < swap_header->info.nr_badpages; i++)
2844ca8bd38bSCesar Eduardo Barros 			swab32s(&swap_header->info.badpages[i]);
2845ca8bd38bSCesar Eduardo Barros 	}
2846ca8bd38bSCesar Eduardo Barros 	/* Check the swap header's sub-version */
2847ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.version != 1) {
2848465c47fdSAndrew Morton 		pr_warn("Unable to handle swap header version %d\n",
2849ca8bd38bSCesar Eduardo Barros 			swap_header->info.version);
285038719025SCesar Eduardo Barros 		return 0;
2851ca8bd38bSCesar Eduardo Barros 	}
2852ca8bd38bSCesar Eduardo Barros 
2853ca8bd38bSCesar Eduardo Barros 	p->lowest_bit  = 1;
2854ca8bd38bSCesar Eduardo Barros 	p->cluster_next = 1;
2855ca8bd38bSCesar Eduardo Barros 	p->cluster_nr = 0;
2856ca8bd38bSCesar Eduardo Barros 
2857be45a490SPeter Xu 	maxpages = swapfile_maximum_size;
2858d6bbbd29SRaymond Jennings 	last_page = swap_header->info.last_page;
2859a06ad633STom Abraham 	if (!last_page) {
2860a06ad633STom Abraham 		pr_warn("Empty swap-file\n");
2861a06ad633STom Abraham 		return 0;
2862a06ad633STom Abraham 	}
2863d6bbbd29SRaymond Jennings 	if (last_page > maxpages) {
2864465c47fdSAndrew Morton 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2865*00cde042SZhangPeng 			K(maxpages), K(last_page));
2866d6bbbd29SRaymond Jennings 	}
2867d6bbbd29SRaymond Jennings 	if (maxpages > last_page) {
2868d6bbbd29SRaymond Jennings 		maxpages = last_page + 1;
2869ca8bd38bSCesar Eduardo Barros 		/* p->max is an unsigned int: don't overflow it */
2870ca8bd38bSCesar Eduardo Barros 		if ((unsigned int)maxpages == 0)
2871ca8bd38bSCesar Eduardo Barros 			maxpages = UINT_MAX;
2872ca8bd38bSCesar Eduardo Barros 	}
2873ca8bd38bSCesar Eduardo Barros 	p->highest_bit = maxpages - 1;
2874ca8bd38bSCesar Eduardo Barros 
2875ca8bd38bSCesar Eduardo Barros 	if (!maxpages)
287638719025SCesar Eduardo Barros 		return 0;
2877ca8bd38bSCesar Eduardo Barros 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2878ca8bd38bSCesar Eduardo Barros 	if (swapfilepages && maxpages > swapfilepages) {
2879465c47fdSAndrew Morton 		pr_warn("Swap area shorter than signature indicates\n");
288038719025SCesar Eduardo Barros 		return 0;
2881ca8bd38bSCesar Eduardo Barros 	}
2882ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
288338719025SCesar Eduardo Barros 		return 0;
2884ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
288538719025SCesar Eduardo Barros 		return 0;
2886ca8bd38bSCesar Eduardo Barros 
2887ca8bd38bSCesar Eduardo Barros 	return maxpages;
2888ca8bd38bSCesar Eduardo Barros }
2889ca8bd38bSCesar Eduardo Barros 
28904b3ef9daSHuang, Ying #define SWAP_CLUSTER_INFO_COLS						\
2891235b6217SHuang, Ying 	DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
28924b3ef9daSHuang, Ying #define SWAP_CLUSTER_SPACE_COLS						\
28934b3ef9daSHuang, Ying 	DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
28944b3ef9daSHuang, Ying #define SWAP_CLUSTER_COLS						\
28954b3ef9daSHuang, Ying 	max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
2896235b6217SHuang, Ying 
2897915d4d7bSCesar Eduardo Barros static int setup_swap_map_and_extents(struct swap_info_struct *p,
2898915d4d7bSCesar Eduardo Barros 					union swap_header *swap_header,
2899915d4d7bSCesar Eduardo Barros 					unsigned char *swap_map,
29002a8f9449SShaohua Li 					struct swap_cluster_info *cluster_info,
2901915d4d7bSCesar Eduardo Barros 					unsigned long maxpages,
2902915d4d7bSCesar Eduardo Barros 					sector_t *span)
2903915d4d7bSCesar Eduardo Barros {
2904235b6217SHuang, Ying 	unsigned int j, k;
2905915d4d7bSCesar Eduardo Barros 	unsigned int nr_good_pages;
2906915d4d7bSCesar Eduardo Barros 	int nr_extents;
29072a8f9449SShaohua Li 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2908235b6217SHuang, Ying 	unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
2909235b6217SHuang, Ying 	unsigned long i, idx;
2910915d4d7bSCesar Eduardo Barros 
2911915d4d7bSCesar Eduardo Barros 	nr_good_pages = maxpages - 1;	/* omit header page */
2912915d4d7bSCesar Eduardo Barros 
29136b534915SHuang Ying 	cluster_list_init(&p->free_clusters);
29146b534915SHuang Ying 	cluster_list_init(&p->discard_clusters);
29152a8f9449SShaohua Li 
2916915d4d7bSCesar Eduardo Barros 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
2917915d4d7bSCesar Eduardo Barros 		unsigned int page_nr = swap_header->info.badpages[i];
2918bdb8e3f6SCesar Eduardo Barros 		if (page_nr == 0 || page_nr > swap_header->info.last_page)
2919bdb8e3f6SCesar Eduardo Barros 			return -EINVAL;
2920915d4d7bSCesar Eduardo Barros 		if (page_nr < maxpages) {
2921915d4d7bSCesar Eduardo Barros 			swap_map[page_nr] = SWAP_MAP_BAD;
2922915d4d7bSCesar Eduardo Barros 			nr_good_pages--;
29232a8f9449SShaohua Li 			/*
29242a8f9449SShaohua Li 			 * Haven't marked the cluster free yet, no list
29252a8f9449SShaohua Li 			 * operation involved
29262a8f9449SShaohua Li 			 */
29272a8f9449SShaohua Li 			inc_cluster_info_page(p, cluster_info, page_nr);
2928915d4d7bSCesar Eduardo Barros 		}
2929915d4d7bSCesar Eduardo Barros 	}
2930915d4d7bSCesar Eduardo Barros 
29312a8f9449SShaohua Li 	/* Haven't marked the cluster free yet, no list operation involved */
29322a8f9449SShaohua Li 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
29332a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, i);
29342a8f9449SShaohua Li 
2935915d4d7bSCesar Eduardo Barros 	if (nr_good_pages) {
2936915d4d7bSCesar Eduardo Barros 		swap_map[0] = SWAP_MAP_BAD;
29372a8f9449SShaohua Li 		/*
29382a8f9449SShaohua Li 		 * Not mark the cluster free yet, no list
29392a8f9449SShaohua Li 		 * operation involved
29402a8f9449SShaohua Li 		 */
29412a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, 0);
2942915d4d7bSCesar Eduardo Barros 		p->max = maxpages;
2943915d4d7bSCesar Eduardo Barros 		p->pages = nr_good_pages;
2944915d4d7bSCesar Eduardo Barros 		nr_extents = setup_swap_extents(p, span);
2945bdb8e3f6SCesar Eduardo Barros 		if (nr_extents < 0)
2946bdb8e3f6SCesar Eduardo Barros 			return nr_extents;
2947915d4d7bSCesar Eduardo Barros 		nr_good_pages = p->pages;
2948915d4d7bSCesar Eduardo Barros 	}
2949915d4d7bSCesar Eduardo Barros 	if (!nr_good_pages) {
2950465c47fdSAndrew Morton 		pr_warn("Empty swap-file\n");
2951bdb8e3f6SCesar Eduardo Barros 		return -EINVAL;
2952915d4d7bSCesar Eduardo Barros 	}
2953915d4d7bSCesar Eduardo Barros 
29542a8f9449SShaohua Li 	if (!cluster_info)
29552a8f9449SShaohua Li 		return nr_extents;
29562a8f9449SShaohua Li 
2957235b6217SHuang, Ying 
29584b3ef9daSHuang, Ying 	/*
29594b3ef9daSHuang, Ying 	 * Reduce false cache line sharing between cluster_info and
29604b3ef9daSHuang, Ying 	 * sharing same address space.
29614b3ef9daSHuang, Ying 	 */
2962235b6217SHuang, Ying 	for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
2963235b6217SHuang, Ying 		j = (k + col) % SWAP_CLUSTER_COLS;
2964235b6217SHuang, Ying 		for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
2965235b6217SHuang, Ying 			idx = i * SWAP_CLUSTER_COLS + j;
2966235b6217SHuang, Ying 			if (idx >= nr_clusters)
2967235b6217SHuang, Ying 				continue;
2968235b6217SHuang, Ying 			if (cluster_count(&cluster_info[idx]))
2969235b6217SHuang, Ying 				continue;
29702a8f9449SShaohua Li 			cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
29716b534915SHuang Ying 			cluster_list_add_tail(&p->free_clusters, cluster_info,
29726b534915SHuang Ying 					      idx);
29732a8f9449SShaohua Li 		}
29742a8f9449SShaohua Li 	}
2975915d4d7bSCesar Eduardo Barros 	return nr_extents;
2976915d4d7bSCesar Eduardo Barros }
2977915d4d7bSCesar Eduardo Barros 
297853cbb243SCesar Eduardo Barros SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
297953cbb243SCesar Eduardo Barros {
298053cbb243SCesar Eduardo Barros 	struct swap_info_struct *p;
298191a27b2aSJeff Layton 	struct filename *name;
298253cbb243SCesar Eduardo Barros 	struct file *swap_file = NULL;
298353cbb243SCesar Eduardo Barros 	struct address_space *mapping;
298451cc3a66SHugh Dickins 	struct dentry *dentry;
298540531542SCesar Eduardo Barros 	int prio;
298653cbb243SCesar Eduardo Barros 	int error;
298753cbb243SCesar Eduardo Barros 	union swap_header *swap_header;
2988915d4d7bSCesar Eduardo Barros 	int nr_extents;
298953cbb243SCesar Eduardo Barros 	sector_t span;
299053cbb243SCesar Eduardo Barros 	unsigned long maxpages;
299153cbb243SCesar Eduardo Barros 	unsigned char *swap_map = NULL;
29922a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info = NULL;
299353cbb243SCesar Eduardo Barros 	struct page *page = NULL;
299453cbb243SCesar Eduardo Barros 	struct inode *inode = NULL;
29957cbf3192SOmar Sandoval 	bool inced_nr_rotate_swap = false;
299653cbb243SCesar Eduardo Barros 
2997d15cab97SHugh Dickins 	if (swap_flags & ~SWAP_FLAGS_VALID)
2998d15cab97SHugh Dickins 		return -EINVAL;
2999d15cab97SHugh Dickins 
300053cbb243SCesar Eduardo Barros 	if (!capable(CAP_SYS_ADMIN))
300153cbb243SCesar Eduardo Barros 		return -EPERM;
300253cbb243SCesar Eduardo Barros 
3003a2468cc9SAaron Lu 	if (!swap_avail_heads)
3004a2468cc9SAaron Lu 		return -ENOMEM;
3005a2468cc9SAaron Lu 
300653cbb243SCesar Eduardo Barros 	p = alloc_swap_info();
30072542e513SCesar Eduardo Barros 	if (IS_ERR(p))
30082542e513SCesar Eduardo Barros 		return PTR_ERR(p);
300953cbb243SCesar Eduardo Barros 
3010815c2c54SShaohua Li 	INIT_WORK(&p->discard_work, swap_discard_work);
3011815c2c54SShaohua Li 
30121da177e4SLinus Torvalds 	name = getname(specialfile);
30131da177e4SLinus Torvalds 	if (IS_ERR(name)) {
30147de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(name);
30151da177e4SLinus Torvalds 		name = NULL;
3016bd69010bSCesar Eduardo Barros 		goto bad_swap;
30171da177e4SLinus Torvalds 	}
3018669abf4eSJeff Layton 	swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
30191da177e4SLinus Torvalds 	if (IS_ERR(swap_file)) {
30207de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(swap_file);
30211da177e4SLinus Torvalds 		swap_file = NULL;
3022bd69010bSCesar Eduardo Barros 		goto bad_swap;
30231da177e4SLinus Torvalds 	}
30241da177e4SLinus Torvalds 
30251da177e4SLinus Torvalds 	p->swap_file = swap_file;
30261da177e4SLinus Torvalds 	mapping = swap_file->f_mapping;
302751cc3a66SHugh Dickins 	dentry = swap_file->f_path.dentry;
30282130781eSCesar Eduardo Barros 	inode = mapping->host;
30296f179af8SHugh Dickins 
30304d0e1e10SCesar Eduardo Barros 	error = claim_swapfile(p, inode);
30314d0e1e10SCesar Eduardo Barros 	if (unlikely(error))
30321da177e4SLinus Torvalds 		goto bad_swap;
30331da177e4SLinus Torvalds 
3034d795a90eSNaohiro Aota 	inode_lock(inode);
303551cc3a66SHugh Dickins 	if (d_unlinked(dentry) || cant_mount(dentry)) {
303651cc3a66SHugh Dickins 		error = -ENOENT;
303751cc3a66SHugh Dickins 		goto bad_swap_unlock_inode;
303851cc3a66SHugh Dickins 	}
3039d795a90eSNaohiro Aota 	if (IS_SWAPFILE(inode)) {
3040d795a90eSNaohiro Aota 		error = -EBUSY;
3041d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
3042d795a90eSNaohiro Aota 	}
3043d795a90eSNaohiro Aota 
30441da177e4SLinus Torvalds 	/*
30451da177e4SLinus Torvalds 	 * Read the swap header.
30461da177e4SLinus Torvalds 	 */
30477e0a1265SMatthew Wilcox (Oracle) 	if (!mapping->a_ops->read_folio) {
30481da177e4SLinus Torvalds 		error = -EINVAL;
3049d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30501da177e4SLinus Torvalds 	}
3051090d2b18SPekka Enberg 	page = read_mapping_page(mapping, 0, swap_file);
30521da177e4SLinus Torvalds 	if (IS_ERR(page)) {
30531da177e4SLinus Torvalds 		error = PTR_ERR(page);
3054d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30551da177e4SLinus Torvalds 	}
305681e33971SHugh Dickins 	swap_header = kmap(page);
30571da177e4SLinus Torvalds 
3058ca8bd38bSCesar Eduardo Barros 	maxpages = read_swap_header(p, swap_header, inode);
3059ca8bd38bSCesar Eduardo Barros 	if (unlikely(!maxpages)) {
30601da177e4SLinus Torvalds 		error = -EINVAL;
3061d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30621da177e4SLinus Torvalds 	}
30631da177e4SLinus Torvalds 
30641da177e4SLinus Torvalds 	/* OK, set up the swap map and apply the bad block list */
3065803d0c83SCesar Eduardo Barros 	swap_map = vzalloc(maxpages);
306678ecba08SHugh Dickins 	if (!swap_map) {
30671da177e4SLinus Torvalds 		error = -ENOMEM;
3068d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30691da177e4SLinus Torvalds 	}
3070f0571429SMinchan Kim 
307136d25489SChristoph Hellwig 	if (p->bdev && bdev_stable_writes(p->bdev))
3072f0571429SMinchan Kim 		p->flags |= SWP_STABLE_WRITES;
3073f0571429SMinchan Kim 
30743222d8c2SChristoph Hellwig 	if (p->bdev && bdev_synchronous(p->bdev))
3075539a6feaSMinchan Kim 		p->flags |= SWP_SYNCHRONOUS_IO;
3076539a6feaSMinchan Kim 
307710f0d2a5SChristoph Hellwig 	if (p->bdev && bdev_nonrot(p->bdev)) {
30786f179af8SHugh Dickins 		int cpu;
3079235b6217SHuang, Ying 		unsigned long ci, nr_cluster;
30806f179af8SHugh Dickins 
30812a8f9449SShaohua Li 		p->flags |= SWP_SOLIDSTATE;
308249070588SHuang Ying 		p->cluster_next_cpu = alloc_percpu(unsigned int);
308349070588SHuang Ying 		if (!p->cluster_next_cpu) {
308449070588SHuang Ying 			error = -ENOMEM;
308549070588SHuang Ying 			goto bad_swap_unlock_inode;
308649070588SHuang Ying 		}
30872a8f9449SShaohua Li 		/*
30882a8f9449SShaohua Li 		 * select a random position to start with to help wear leveling
30892a8f9449SShaohua Li 		 * SSD
30902a8f9449SShaohua Li 		 */
309149070588SHuang Ying 		for_each_possible_cpu(cpu) {
309249070588SHuang Ying 			per_cpu(*p->cluster_next_cpu, cpu) =
3093e8a533cbSJason A. Donenfeld 				get_random_u32_inclusive(1, p->highest_bit);
309449070588SHuang Ying 		}
3095235b6217SHuang, Ying 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
30962a8f9449SShaohua Li 
3097778e1cddSKees Cook 		cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
309854f180d3SHuang Ying 					GFP_KERNEL);
30992a8f9449SShaohua Li 		if (!cluster_info) {
31002a8f9449SShaohua Li 			error = -ENOMEM;
3101d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
31022a8f9449SShaohua Li 		}
3103235b6217SHuang, Ying 
3104235b6217SHuang, Ying 		for (ci = 0; ci < nr_cluster; ci++)
3105235b6217SHuang, Ying 			spin_lock_init(&((cluster_info + ci)->lock));
3106235b6217SHuang, Ying 
3107ebc2a1a6SShaohua Li 		p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3108ebc2a1a6SShaohua Li 		if (!p->percpu_cluster) {
3109ebc2a1a6SShaohua Li 			error = -ENOMEM;
3110d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
3111ebc2a1a6SShaohua Li 		}
31126f179af8SHugh Dickins 		for_each_possible_cpu(cpu) {
3113ebc2a1a6SShaohua Li 			struct percpu_cluster *cluster;
31146f179af8SHugh Dickins 			cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3115ebc2a1a6SShaohua Li 			cluster_set_null(&cluster->index);
3116ebc2a1a6SShaohua Li 		}
31177cbf3192SOmar Sandoval 	} else {
311881a0298bSHuang Ying 		atomic_inc(&nr_rotate_swap);
31197cbf3192SOmar Sandoval 		inced_nr_rotate_swap = true;
31207cbf3192SOmar Sandoval 	}
31211da177e4SLinus Torvalds 
31221421ef3cSCesar Eduardo Barros 	error = swap_cgroup_swapon(p->type, maxpages);
31231421ef3cSCesar Eduardo Barros 	if (error)
3124d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
31251421ef3cSCesar Eduardo Barros 
3126915d4d7bSCesar Eduardo Barros 	nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
31272a8f9449SShaohua Li 		cluster_info, maxpages, &span);
3128915d4d7bSCesar Eduardo Barros 	if (unlikely(nr_extents < 0)) {
312953092a74SHugh Dickins 		error = nr_extents;
3130d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
313153092a74SHugh Dickins 	}
31321da177e4SLinus Torvalds 
313370200574SChristoph Hellwig 	if ((swap_flags & SWAP_FLAG_DISCARD) &&
313470200574SChristoph Hellwig 	    p->bdev && bdev_max_discard_sectors(p->bdev)) {
3135dcf6b7ddSRafael Aquini 		/*
3136dcf6b7ddSRafael Aquini 		 * When discard is enabled for swap with no particular
3137dcf6b7ddSRafael Aquini 		 * policy flagged, we set all swap discard flags here in
3138dcf6b7ddSRafael Aquini 		 * order to sustain backward compatibility with older
3139dcf6b7ddSRafael Aquini 		 * swapon(8) releases.
3140dcf6b7ddSRafael Aquini 		 */
3141dcf6b7ddSRafael Aquini 		p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3142dcf6b7ddSRafael Aquini 			     SWP_PAGE_DISCARD);
3143dcf6b7ddSRafael Aquini 
3144dcf6b7ddSRafael Aquini 		/*
3145dcf6b7ddSRafael Aquini 		 * By flagging sys_swapon, a sysadmin can tell us to
3146dcf6b7ddSRafael Aquini 		 * either do single-time area discards only, or to just
3147dcf6b7ddSRafael Aquini 		 * perform discards for released swap page-clusters.
3148dcf6b7ddSRafael Aquini 		 * Now it's time to adjust the p->flags accordingly.
3149dcf6b7ddSRafael Aquini 		 */
3150dcf6b7ddSRafael Aquini 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3151dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_PAGE_DISCARD;
3152dcf6b7ddSRafael Aquini 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3153dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_AREA_DISCARD;
3154dcf6b7ddSRafael Aquini 
3155dcf6b7ddSRafael Aquini 		/* issue a swapon-time discard if it's still required */
3156dcf6b7ddSRafael Aquini 		if (p->flags & SWP_AREA_DISCARD) {
3157dcf6b7ddSRafael Aquini 			int err = discard_swap(p);
3158dcf6b7ddSRafael Aquini 			if (unlikely(err))
3159465c47fdSAndrew Morton 				pr_err("swapon: discard_swap(%p): %d\n",
3160dcf6b7ddSRafael Aquini 					p, err);
3161dcf6b7ddSRafael Aquini 		}
3162dcf6b7ddSRafael Aquini 	}
31636a6ba831SHugh Dickins 
31644b3ef9daSHuang, Ying 	error = init_swap_address_space(p->type, maxpages);
31654b3ef9daSHuang, Ying 	if (error)
3166d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
31674b3ef9daSHuang, Ying 
3168dc617f29SDarrick J. Wong 	/*
3169dc617f29SDarrick J. Wong 	 * Flush any pending IO and dirty mappings before we start using this
3170dc617f29SDarrick J. Wong 	 * swap device.
3171dc617f29SDarrick J. Wong 	 */
3172dc617f29SDarrick J. Wong 	inode->i_flags |= S_SWAPFILE;
3173dc617f29SDarrick J. Wong 	error = inode_drain_writes(inode);
3174dc617f29SDarrick J. Wong 	if (error) {
3175dc617f29SDarrick J. Wong 		inode->i_flags &= ~S_SWAPFILE;
3176822bca52SMiaohe Lin 		goto free_swap_address_space;
3177dc617f29SDarrick J. Wong 	}
3178dc617f29SDarrick J. Wong 
3179fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
318040531542SCesar Eduardo Barros 	prio = -1;
318178ecba08SHugh Dickins 	if (swap_flags & SWAP_FLAG_PREFER)
318240531542SCesar Eduardo Barros 		prio =
318378ecba08SHugh Dickins 		  (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
318442c06a0eSJohannes Weiner 	enable_swap_info(p, prio, swap_map, cluster_info);
3185c69dbfb8SCesar Eduardo Barros 
318642c06a0eSJohannes Weiner 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s\n",
3187*00cde042SZhangPeng 		K(p->pages), name->name, p->prio, nr_extents,
3188*00cde042SZhangPeng 		K((unsigned long long)span),
3189c69dbfb8SCesar Eduardo Barros 		(p->flags & SWP_SOLIDSTATE) ? "SS" : "",
319038b5faf4SDan Magenheimer 		(p->flags & SWP_DISCARDABLE) ? "D" : "",
3191dcf6b7ddSRafael Aquini 		(p->flags & SWP_AREA_DISCARD) ? "s" : "",
319242c06a0eSJohannes Weiner 		(p->flags & SWP_PAGE_DISCARD) ? "c" : "");
3193c69dbfb8SCesar Eduardo Barros 
3194fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
319566d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
319666d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
319766d7dd51SKay Sievers 
31981da177e4SLinus Torvalds 	error = 0;
31991da177e4SLinus Torvalds 	goto out;
3200822bca52SMiaohe Lin free_swap_address_space:
3201822bca52SMiaohe Lin 	exit_swap_address_space(p->type);
3202d795a90eSNaohiro Aota bad_swap_unlock_inode:
3203d795a90eSNaohiro Aota 	inode_unlock(inode);
32041da177e4SLinus Torvalds bad_swap:
3205ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
3206ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
320749070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
320849070588SHuang Ying 	p->cluster_next_cpu = NULL;
3209bd69010bSCesar Eduardo Barros 	if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3210f2090d2dSCesar Eduardo Barros 		set_blocksize(p->bdev, p->old_block_size);
32112736e8eeSChristoph Hellwig 		blkdev_put(p->bdev, p);
32121da177e4SLinus Torvalds 	}
3213d795a90eSNaohiro Aota 	inode = NULL;
32144cd3bb10SHugh Dickins 	destroy_swap_extents(p);
3215e8e6c2ecSCesar Eduardo Barros 	swap_cgroup_swapoff(p->type);
32165d337b91SHugh Dickins 	spin_lock(&swap_lock);
32171da177e4SLinus Torvalds 	p->swap_file = NULL;
32181da177e4SLinus Torvalds 	p->flags = 0;
32195d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32201da177e4SLinus Torvalds 	vfree(swap_map);
32218606a1a9SDarrick J. Wong 	kvfree(cluster_info);
32227cbf3192SOmar Sandoval 	if (inced_nr_rotate_swap)
32237cbf3192SOmar Sandoval 		atomic_dec(&nr_rotate_swap);
3224d795a90eSNaohiro Aota 	if (swap_file)
32251da177e4SLinus Torvalds 		filp_close(swap_file, NULL);
32261da177e4SLinus Torvalds out:
32271da177e4SLinus Torvalds 	if (page && !IS_ERR(page)) {
32281da177e4SLinus Torvalds 		kunmap(page);
322909cbfeafSKirill A. Shutemov 		put_page(page);
32301da177e4SLinus Torvalds 	}
32311da177e4SLinus Torvalds 	if (name)
32321da177e4SLinus Torvalds 		putname(name);
32331638045cSDarrick J. Wong 	if (inode)
32345955102cSAl Viro 		inode_unlock(inode);
3235039939a6STim Chen 	if (!error)
3236039939a6STim Chen 		enable_swap_slots_cache();
32371da177e4SLinus Torvalds 	return error;
32381da177e4SLinus Torvalds }
32391da177e4SLinus Torvalds 
32401da177e4SLinus Torvalds void si_swapinfo(struct sysinfo *val)
32411da177e4SLinus Torvalds {
3242efa90a98SHugh Dickins 	unsigned int type;
32431da177e4SLinus Torvalds 	unsigned long nr_to_be_unused = 0;
32441da177e4SLinus Torvalds 
32455d337b91SHugh Dickins 	spin_lock(&swap_lock);
3246efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
3247efa90a98SHugh Dickins 		struct swap_info_struct *si = swap_info[type];
3248efa90a98SHugh Dickins 
3249efa90a98SHugh Dickins 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3250c8945306SMiaohe Lin 			nr_to_be_unused += READ_ONCE(si->inuse_pages);
32511da177e4SLinus Torvalds 	}
3252ec8acf20SShaohua Li 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
32531da177e4SLinus Torvalds 	val->totalswap = total_swap_pages + nr_to_be_unused;
32545d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32551da177e4SLinus Torvalds }
32561da177e4SLinus Torvalds 
32571da177e4SLinus Torvalds /*
32581da177e4SLinus Torvalds  * Verify that a swap entry is valid and increment its swap map count.
32591da177e4SLinus Torvalds  *
3260355cfa73SKAMEZAWA Hiroyuki  * Returns error code in following case.
3261355cfa73SKAMEZAWA Hiroyuki  * - success -> 0
3262355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is invalid -> EINVAL
3263355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is migration entry -> EINVAL
3264355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but there is already one. -> EEXIST
3265355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but the entry is not used. -> ENOENT
3266570a335bSHugh Dickins  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
32671da177e4SLinus Torvalds  */
32688d69aaeeSHugh Dickins static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
32691da177e4SLinus Torvalds {
32701da177e4SLinus Torvalds 	struct swap_info_struct *p;
3271235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3272c10d38ccSDaniel Jordan 	unsigned long offset;
32738d69aaeeSHugh Dickins 	unsigned char count;
32748d69aaeeSHugh Dickins 	unsigned char has_cache;
32759d9a0334SMiaohe Lin 	int err;
32761da177e4SLinus Torvalds 
3277c07aee4fSHuang Ying 	p = swp_swap_info(entry);
3278c10d38ccSDaniel Jordan 
32791da177e4SLinus Torvalds 	offset = swp_offset(entry);
3280235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
3281355cfa73SKAMEZAWA Hiroyuki 
3282253d553bSHugh Dickins 	count = p->swap_map[offset];
3283edfe23daSShaohua Li 
3284edfe23daSShaohua Li 	/*
3285edfe23daSShaohua Li 	 * swapin_readahead() doesn't check if a swap entry is valid, so the
3286edfe23daSShaohua Li 	 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3287edfe23daSShaohua Li 	 */
3288edfe23daSShaohua Li 	if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3289edfe23daSShaohua Li 		err = -ENOENT;
3290edfe23daSShaohua Li 		goto unlock_out;
3291edfe23daSShaohua Li 	}
3292edfe23daSShaohua Li 
3293253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
3294253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
3295253d553bSHugh Dickins 	err = 0;
3296355cfa73SKAMEZAWA Hiroyuki 
3297253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
3298355cfa73SKAMEZAWA Hiroyuki 
3299355cfa73SKAMEZAWA Hiroyuki 		/* set SWAP_HAS_CACHE if there is no cache and entry is used */
3300253d553bSHugh Dickins 		if (!has_cache && count)
3301253d553bSHugh Dickins 			has_cache = SWAP_HAS_CACHE;
3302253d553bSHugh Dickins 		else if (has_cache)		/* someone else added cache */
3303253d553bSHugh Dickins 			err = -EEXIST;
3304253d553bSHugh Dickins 		else				/* no users remaining */
3305253d553bSHugh Dickins 			err = -ENOENT;
3306355cfa73SKAMEZAWA Hiroyuki 
3307355cfa73SKAMEZAWA Hiroyuki 	} else if (count || has_cache) {
3308253d553bSHugh Dickins 
3309570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3310570a335bSHugh Dickins 			count += usage;
3311570a335bSHugh Dickins 		else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3312253d553bSHugh Dickins 			err = -EINVAL;
3313570a335bSHugh Dickins 		else if (swap_count_continued(p, offset, count))
3314570a335bSHugh Dickins 			count = COUNT_CONTINUED;
3315570a335bSHugh Dickins 		else
3316570a335bSHugh Dickins 			err = -ENOMEM;
3317253d553bSHugh Dickins 	} else
3318253d553bSHugh Dickins 		err = -ENOENT;			/* unused swap entry */
3319253d553bSHugh Dickins 
3320a449bf58SQian Cai 	WRITE_ONCE(p->swap_map[offset], count | has_cache);
3321253d553bSHugh Dickins 
3322355cfa73SKAMEZAWA Hiroyuki unlock_out:
3323235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
3324253d553bSHugh Dickins 	return err;
33251da177e4SLinus Torvalds }
3326253d553bSHugh Dickins 
3327355cfa73SKAMEZAWA Hiroyuki /*
3328aaa46865SHugh Dickins  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3329aaa46865SHugh Dickins  * (in which case its reference count is never incremented).
3330aaa46865SHugh Dickins  */
3331aaa46865SHugh Dickins void swap_shmem_alloc(swp_entry_t entry)
3332aaa46865SHugh Dickins {
3333aaa46865SHugh Dickins 	__swap_duplicate(entry, SWAP_MAP_SHMEM);
3334aaa46865SHugh Dickins }
3335aaa46865SHugh Dickins 
3336aaa46865SHugh Dickins /*
333708259d58SHugh Dickins  * Increase reference count of swap entry by 1.
333808259d58SHugh Dickins  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
333908259d58SHugh Dickins  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
334008259d58SHugh Dickins  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
334108259d58SHugh Dickins  * might occur if a page table entry has got corrupted.
3342355cfa73SKAMEZAWA Hiroyuki  */
3343570a335bSHugh Dickins int swap_duplicate(swp_entry_t entry)
3344355cfa73SKAMEZAWA Hiroyuki {
3345570a335bSHugh Dickins 	int err = 0;
3346570a335bSHugh Dickins 
3347570a335bSHugh Dickins 	while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3348570a335bSHugh Dickins 		err = add_swap_count_continuation(entry, GFP_ATOMIC);
3349570a335bSHugh Dickins 	return err;
3350355cfa73SKAMEZAWA Hiroyuki }
33511da177e4SLinus Torvalds 
3352cb4b86baSKAMEZAWA Hiroyuki /*
3353355cfa73SKAMEZAWA Hiroyuki  * @entry: swap entry for which we allocate swap cache.
3354355cfa73SKAMEZAWA Hiroyuki  *
335573c34b6aSHugh Dickins  * Called when allocating swap cache for existing swap entry,
3356355cfa73SKAMEZAWA Hiroyuki  * This can return error codes. Returns 0 at success.
33573eeba135SChen Wandun  * -EEXIST means there is a swap cache.
3358355cfa73SKAMEZAWA Hiroyuki  * Note: return code is different from swap_duplicate().
3359cb4b86baSKAMEZAWA Hiroyuki  */
3360cb4b86baSKAMEZAWA Hiroyuki int swapcache_prepare(swp_entry_t entry)
3361cb4b86baSKAMEZAWA Hiroyuki {
3362253d553bSHugh Dickins 	return __swap_duplicate(entry, SWAP_HAS_CACHE);
3363cb4b86baSKAMEZAWA Hiroyuki }
3364cb4b86baSKAMEZAWA Hiroyuki 
33650bcac06fSMinchan Kim struct swap_info_struct *swp_swap_info(swp_entry_t entry)
33660bcac06fSMinchan Kim {
3367c10d38ccSDaniel Jordan 	return swap_type_to_swap_info(swp_type(entry));
33680bcac06fSMinchan Kim }
33690bcac06fSMinchan Kim 
3370f981c595SMel Gorman struct swap_info_struct *page_swap_info(struct page *page)
3371f981c595SMel Gorman {
33720bcac06fSMinchan Kim 	swp_entry_t entry = { .val = page_private(page) };
33730bcac06fSMinchan Kim 	return swp_swap_info(entry);
3374f981c595SMel Gorman }
3375f981c595SMel Gorman 
3376f981c595SMel Gorman /*
33772f52578fSMatthew Wilcox (Oracle)  * out-of-line methods to avoid include hell.
3378f981c595SMel Gorman  */
33792f52578fSMatthew Wilcox (Oracle) struct address_space *swapcache_mapping(struct folio *folio)
3380f981c595SMel Gorman {
33812f52578fSMatthew Wilcox (Oracle) 	return page_swap_info(&folio->page)->swap_file->f_mapping;
3382f981c595SMel Gorman }
33832f52578fSMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(swapcache_mapping);
3384f981c595SMel Gorman 
3385f981c595SMel Gorman pgoff_t __page_file_index(struct page *page)
3386f981c595SMel Gorman {
3387f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3388f981c595SMel Gorman 	return swp_offset(swap);
3389f981c595SMel Gorman }
3390f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_index);
3391f981c595SMel Gorman 
33921da177e4SLinus Torvalds /*
3393570a335bSHugh Dickins  * add_swap_count_continuation - called when a swap count is duplicated
3394570a335bSHugh Dickins  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3395570a335bSHugh Dickins  * page of the original vmalloc'ed swap_map, to hold the continuation count
3396570a335bSHugh Dickins  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3397570a335bSHugh Dickins  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3398570a335bSHugh Dickins  *
3399570a335bSHugh Dickins  * These continuation pages are seldom referenced: the common paths all work
3400570a335bSHugh Dickins  * on the original swap_map, only referring to a continuation page when the
3401570a335bSHugh Dickins  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3402570a335bSHugh Dickins  *
3403570a335bSHugh Dickins  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3404570a335bSHugh Dickins  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3405570a335bSHugh Dickins  * can be called after dropping locks.
3406570a335bSHugh Dickins  */
3407570a335bSHugh Dickins int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3408570a335bSHugh Dickins {
3409570a335bSHugh Dickins 	struct swap_info_struct *si;
3410235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3411570a335bSHugh Dickins 	struct page *head;
3412570a335bSHugh Dickins 	struct page *page;
3413570a335bSHugh Dickins 	struct page *list_page;
3414570a335bSHugh Dickins 	pgoff_t offset;
3415570a335bSHugh Dickins 	unsigned char count;
3416eb085574SHuang Ying 	int ret = 0;
3417570a335bSHugh Dickins 
3418570a335bSHugh Dickins 	/*
3419570a335bSHugh Dickins 	 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3420570a335bSHugh Dickins 	 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3421570a335bSHugh Dickins 	 */
3422570a335bSHugh Dickins 	page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3423570a335bSHugh Dickins 
3424eb085574SHuang Ying 	si = get_swap_device(entry);
3425570a335bSHugh Dickins 	if (!si) {
3426570a335bSHugh Dickins 		/*
3427570a335bSHugh Dickins 		 * An acceptable race has occurred since the failing
3428eb085574SHuang Ying 		 * __swap_duplicate(): the swap device may be swapoff
3429570a335bSHugh Dickins 		 */
3430570a335bSHugh Dickins 		goto outer;
3431570a335bSHugh Dickins 	}
3432eb085574SHuang Ying 	spin_lock(&si->lock);
3433570a335bSHugh Dickins 
3434570a335bSHugh Dickins 	offset = swp_offset(entry);
3435235b6217SHuang, Ying 
3436235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
3437235b6217SHuang, Ying 
3438d8aa24e0SMiaohe Lin 	count = swap_count(si->swap_map[offset]);
3439570a335bSHugh Dickins 
3440570a335bSHugh Dickins 	if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3441570a335bSHugh Dickins 		/*
3442570a335bSHugh Dickins 		 * The higher the swap count, the more likely it is that tasks
3443570a335bSHugh Dickins 		 * will race to add swap count continuation: we need to avoid
3444570a335bSHugh Dickins 		 * over-provisioning.
3445570a335bSHugh Dickins 		 */
3446570a335bSHugh Dickins 		goto out;
3447570a335bSHugh Dickins 	}
3448570a335bSHugh Dickins 
3449570a335bSHugh Dickins 	if (!page) {
3450eb085574SHuang Ying 		ret = -ENOMEM;
3451eb085574SHuang Ying 		goto out;
3452570a335bSHugh Dickins 	}
3453570a335bSHugh Dickins 
3454570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3455570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3456570a335bSHugh Dickins 
34572628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3458570a335bSHugh Dickins 	/*
3459570a335bSHugh Dickins 	 * Page allocation does not initialize the page's lru field,
3460570a335bSHugh Dickins 	 * but it does always reset its private field.
3461570a335bSHugh Dickins 	 */
3462570a335bSHugh Dickins 	if (!page_private(head)) {
3463570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3464570a335bSHugh Dickins 		INIT_LIST_HEAD(&head->lru);
3465570a335bSHugh Dickins 		set_page_private(head, SWP_CONTINUED);
3466570a335bSHugh Dickins 		si->flags |= SWP_CONTINUED;
3467570a335bSHugh Dickins 	}
3468570a335bSHugh Dickins 
3469570a335bSHugh Dickins 	list_for_each_entry(list_page, &head->lru, lru) {
3470570a335bSHugh Dickins 		unsigned char *map;
3471570a335bSHugh Dickins 
3472570a335bSHugh Dickins 		/*
3473570a335bSHugh Dickins 		 * If the previous map said no continuation, but we've found
3474570a335bSHugh Dickins 		 * a continuation page, free our allocation and use this one.
3475570a335bSHugh Dickins 		 */
3476570a335bSHugh Dickins 		if (!(count & COUNT_CONTINUED))
34772628bd6fSHuang Ying 			goto out_unlock_cont;
3478570a335bSHugh Dickins 
34799b04c5feSCong Wang 		map = kmap_atomic(list_page) + offset;
3480570a335bSHugh Dickins 		count = *map;
34819b04c5feSCong Wang 		kunmap_atomic(map);
3482570a335bSHugh Dickins 
3483570a335bSHugh Dickins 		/*
3484570a335bSHugh Dickins 		 * If this continuation count now has some space in it,
3485570a335bSHugh Dickins 		 * free our allocation and use this one.
3486570a335bSHugh Dickins 		 */
3487570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
34882628bd6fSHuang Ying 			goto out_unlock_cont;
3489570a335bSHugh Dickins 	}
3490570a335bSHugh Dickins 
3491570a335bSHugh Dickins 	list_add_tail(&page->lru, &head->lru);
3492570a335bSHugh Dickins 	page = NULL;			/* now it's attached, don't free it */
34932628bd6fSHuang Ying out_unlock_cont:
34942628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
3495570a335bSHugh Dickins out:
3496235b6217SHuang, Ying 	unlock_cluster(ci);
3497ec8acf20SShaohua Li 	spin_unlock(&si->lock);
3498eb085574SHuang Ying 	put_swap_device(si);
3499570a335bSHugh Dickins outer:
3500570a335bSHugh Dickins 	if (page)
3501570a335bSHugh Dickins 		__free_page(page);
3502eb085574SHuang Ying 	return ret;
3503570a335bSHugh Dickins }
3504570a335bSHugh Dickins 
3505570a335bSHugh Dickins /*
3506570a335bSHugh Dickins  * swap_count_continued - when the original swap_map count is incremented
3507570a335bSHugh Dickins  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3508570a335bSHugh Dickins  * into, carry if so, or else fail until a new continuation page is allocated;
3509570a335bSHugh Dickins  * when the original swap_map count is decremented from 0 with continuation,
3510570a335bSHugh Dickins  * borrow from the continuation and report whether it still holds more.
3511235b6217SHuang, Ying  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3512235b6217SHuang, Ying  * lock.
3513570a335bSHugh Dickins  */
3514570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *si,
3515570a335bSHugh Dickins 				 pgoff_t offset, unsigned char count)
3516570a335bSHugh Dickins {
3517570a335bSHugh Dickins 	struct page *head;
3518570a335bSHugh Dickins 	struct page *page;
3519570a335bSHugh Dickins 	unsigned char *map;
35202628bd6fSHuang Ying 	bool ret;
3521570a335bSHugh Dickins 
3522570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3523570a335bSHugh Dickins 	if (page_private(head) != SWP_CONTINUED) {
3524570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3525570a335bSHugh Dickins 		return false;		/* need to add count continuation */
3526570a335bSHugh Dickins 	}
3527570a335bSHugh Dickins 
35282628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3529570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3530213516acSchenqiwu 	page = list_next_entry(head, lru);
35319b04c5feSCong Wang 	map = kmap_atomic(page) + offset;
3532570a335bSHugh Dickins 
3533570a335bSHugh Dickins 	if (count == SWAP_MAP_MAX)	/* initial increment from swap_map */
3534570a335bSHugh Dickins 		goto init_map;		/* jump over SWAP_CONT_MAX checks */
3535570a335bSHugh Dickins 
3536570a335bSHugh Dickins 	if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3537570a335bSHugh Dickins 		/*
3538570a335bSHugh Dickins 		 * Think of how you add 1 to 999
3539570a335bSHugh Dickins 		 */
3540570a335bSHugh Dickins 		while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
35419b04c5feSCong Wang 			kunmap_atomic(map);
3542213516acSchenqiwu 			page = list_next_entry(page, lru);
3543570a335bSHugh Dickins 			BUG_ON(page == head);
35449b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3545570a335bSHugh Dickins 		}
3546570a335bSHugh Dickins 		if (*map == SWAP_CONT_MAX) {
35479b04c5feSCong Wang 			kunmap_atomic(map);
3548213516acSchenqiwu 			page = list_next_entry(page, lru);
35492628bd6fSHuang Ying 			if (page == head) {
35502628bd6fSHuang Ying 				ret = false;	/* add count continuation */
35512628bd6fSHuang Ying 				goto out;
35522628bd6fSHuang Ying 			}
35539b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3554570a335bSHugh Dickins init_map:		*map = 0;		/* we didn't zero the page */
3555570a335bSHugh Dickins 		}
3556570a335bSHugh Dickins 		*map += 1;
35579b04c5feSCong Wang 		kunmap_atomic(map);
3558213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
35599b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3560570a335bSHugh Dickins 			*map = COUNT_CONTINUED;
35619b04c5feSCong Wang 			kunmap_atomic(map);
3562570a335bSHugh Dickins 		}
35632628bd6fSHuang Ying 		ret = true;			/* incremented */
3564570a335bSHugh Dickins 
3565570a335bSHugh Dickins 	} else {				/* decrementing */
3566570a335bSHugh Dickins 		/*
3567570a335bSHugh Dickins 		 * Think of how you subtract 1 from 1000
3568570a335bSHugh Dickins 		 */
3569570a335bSHugh Dickins 		BUG_ON(count != COUNT_CONTINUED);
3570570a335bSHugh Dickins 		while (*map == COUNT_CONTINUED) {
35719b04c5feSCong Wang 			kunmap_atomic(map);
3572213516acSchenqiwu 			page = list_next_entry(page, lru);
3573570a335bSHugh Dickins 			BUG_ON(page == head);
35749b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3575570a335bSHugh Dickins 		}
3576570a335bSHugh Dickins 		BUG_ON(*map == 0);
3577570a335bSHugh Dickins 		*map -= 1;
3578570a335bSHugh Dickins 		if (*map == 0)
3579570a335bSHugh Dickins 			count = 0;
35809b04c5feSCong Wang 		kunmap_atomic(map);
3581213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
35829b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3583570a335bSHugh Dickins 			*map = SWAP_CONT_MAX | count;
3584570a335bSHugh Dickins 			count = COUNT_CONTINUED;
35859b04c5feSCong Wang 			kunmap_atomic(map);
3586570a335bSHugh Dickins 		}
35872628bd6fSHuang Ying 		ret = count == COUNT_CONTINUED;
3588570a335bSHugh Dickins 	}
35892628bd6fSHuang Ying out:
35902628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
35912628bd6fSHuang Ying 	return ret;
3592570a335bSHugh Dickins }
3593570a335bSHugh Dickins 
3594570a335bSHugh Dickins /*
3595570a335bSHugh Dickins  * free_swap_count_continuations - swapoff free all the continuation pages
3596570a335bSHugh Dickins  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3597570a335bSHugh Dickins  */
3598570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *si)
3599570a335bSHugh Dickins {
3600570a335bSHugh Dickins 	pgoff_t offset;
3601570a335bSHugh Dickins 
3602570a335bSHugh Dickins 	for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3603570a335bSHugh Dickins 		struct page *head;
3604570a335bSHugh Dickins 		head = vmalloc_to_page(si->swap_map + offset);
3605570a335bSHugh Dickins 		if (page_private(head)) {
36060d576d20SGeliang Tang 			struct page *page, *next;
36070d576d20SGeliang Tang 
36080d576d20SGeliang Tang 			list_for_each_entry_safe(page, next, &head->lru, lru) {
36090d576d20SGeliang Tang 				list_del(&page->lru);
3610570a335bSHugh Dickins 				__free_page(page);
3611570a335bSHugh Dickins 			}
3612570a335bSHugh Dickins 		}
3613570a335bSHugh Dickins 	}
3614570a335bSHugh Dickins }
3615a2468cc9SAaron Lu 
36162cf85583STejun Heo #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
36173e4fb13aSKefeng Wang void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
36182cf85583STejun Heo {
36192cf85583STejun Heo 	struct swap_info_struct *si, *next;
36203e4fb13aSKefeng Wang 	int nid = folio_nid(folio);
36216caa6a07SJohannes Weiner 
36223e4fb13aSKefeng Wang 	if (!(gfp & __GFP_IO))
36232cf85583STejun Heo 		return;
36242cf85583STejun Heo 
36252cf85583STejun Heo 	if (!blk_cgroup_congested())
36262cf85583STejun Heo 		return;
36272cf85583STejun Heo 
36282cf85583STejun Heo 	/*
36292cf85583STejun Heo 	 * We've already scheduled a throttle, avoid taking the global swap
36302cf85583STejun Heo 	 * lock.
36312cf85583STejun Heo 	 */
3632f05837edSChristoph Hellwig 	if (current->throttle_disk)
36332cf85583STejun Heo 		return;
36342cf85583STejun Heo 
36352cf85583STejun Heo 	spin_lock(&swap_avail_lock);
36366caa6a07SJohannes Weiner 	plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
36376caa6a07SJohannes Weiner 				  avail_lists[nid]) {
36382cf85583STejun Heo 		if (si->bdev) {
3639de185b56SChristoph Hellwig 			blkcg_schedule_throttle(si->bdev->bd_disk, true);
36402cf85583STejun Heo 			break;
36412cf85583STejun Heo 		}
36422cf85583STejun Heo 	}
36432cf85583STejun Heo 	spin_unlock(&swap_avail_lock);
36442cf85583STejun Heo }
36452cf85583STejun Heo #endif
36462cf85583STejun Heo 
3647a2468cc9SAaron Lu static int __init swapfile_init(void)
3648a2468cc9SAaron Lu {
3649a2468cc9SAaron Lu 	int nid;
3650a2468cc9SAaron Lu 
3651a2468cc9SAaron Lu 	swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3652a2468cc9SAaron Lu 					 GFP_KERNEL);
3653a2468cc9SAaron Lu 	if (!swap_avail_heads) {
3654a2468cc9SAaron Lu 		pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3655a2468cc9SAaron Lu 		return -ENOMEM;
3656a2468cc9SAaron Lu 	}
3657a2468cc9SAaron Lu 
3658a2468cc9SAaron Lu 	for_each_node(nid)
3659a2468cc9SAaron Lu 		plist_head_init(&swap_avail_heads[nid]);
3660a2468cc9SAaron Lu 
3661be45a490SPeter Xu 	swapfile_maximum_size = arch_max_swapfile_size();
3662be45a490SPeter Xu 
36635154e607SPeter Xu #ifdef CONFIG_MIGRATION
36645154e607SPeter Xu 	if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
36655154e607SPeter Xu 		swap_migration_ad_supported = true;
36665154e607SPeter Xu #endif	/* CONFIG_MIGRATION */
36675154e607SPeter Xu 
3668a2468cc9SAaron Lu 	return 0;
3669a2468cc9SAaron Lu }
3670a2468cc9SAaron Lu subsys_initcall(swapfile_init);
3671