xref: /openbmc/linux/mm/swapfile.c (revision 14a762dd1977cf811516fd97b0262b747cac88f7)
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 
91da177e4SLinus Torvalds #include <linux/mm.h>
106e84f315SIngo Molnar #include <linux/sched/mm.h>
1129930025SIngo Molnar #include <linux/sched/task.h>
121da177e4SLinus Torvalds #include <linux/hugetlb.h>
131da177e4SLinus Torvalds #include <linux/mman.h>
141da177e4SLinus Torvalds #include <linux/slab.h>
151da177e4SLinus Torvalds #include <linux/kernel_stat.h>
161da177e4SLinus Torvalds #include <linux/swap.h>
171da177e4SLinus Torvalds #include <linux/vmalloc.h>
181da177e4SLinus Torvalds #include <linux/pagemap.h>
191da177e4SLinus Torvalds #include <linux/namei.h>
20072441e2SHugh Dickins #include <linux/shmem_fs.h>
21e41d12f5SChristoph Hellwig #include <linux/blk-cgroup.h>
2220137a49SHugh Dickins #include <linux/random.h>
231da177e4SLinus Torvalds #include <linux/writeback.h>
241da177e4SLinus Torvalds #include <linux/proc_fs.h>
251da177e4SLinus Torvalds #include <linux/seq_file.h>
261da177e4SLinus Torvalds #include <linux/init.h>
275ad64688SHugh Dickins #include <linux/ksm.h>
281da177e4SLinus Torvalds #include <linux/rmap.h>
291da177e4SLinus Torvalds #include <linux/security.h>
301da177e4SLinus Torvalds #include <linux/backing-dev.h>
31fc0abb14SIngo Molnar #include <linux/mutex.h>
32c59ede7bSRandy.Dunlap #include <linux/capability.h>
331da177e4SLinus Torvalds #include <linux/syscalls.h>
348a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
3566d7dd51SKay Sievers #include <linux/poll.h>
3672788c38SDavid Rientjes #include <linux/oom.h>
3738b5faf4SDan Magenheimer #include <linux/frontswap.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>
431da177e4SLinus Torvalds 
441da177e4SLinus Torvalds #include <asm/tlbflush.h>
451da177e4SLinus Torvalds #include <linux/swapops.h>
465d1ea48bSJohannes Weiner #include <linux/swap_cgroup.h>
47014bb1deSNeilBrown #include "swap.h"
481da177e4SLinus Torvalds 
49570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
50570a335bSHugh Dickins 				 unsigned char);
51570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *);
52570a335bSHugh Dickins 
53633423a0SChristoph Hellwig static DEFINE_SPINLOCK(swap_lock);
547c363b8cSAdrian Bunk static unsigned int nr_swapfiles;
55ec8acf20SShaohua Li atomic_long_t nr_swap_pages;
56fb0fec50SChris Wilson /*
57fb0fec50SChris Wilson  * Some modules use swappable objects and may try to swap them out under
58fb0fec50SChris Wilson  * memory pressure (via the shrinker). Before doing so, they may wish to
59fb0fec50SChris Wilson  * check to see if any swap space is available.
60fb0fec50SChris Wilson  */
61fb0fec50SChris Wilson EXPORT_SYMBOL_GPL(nr_swap_pages);
62ec8acf20SShaohua Li /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
631da177e4SLinus Torvalds long total_swap_pages;
64a2468cc9SAaron Lu static int least_priority = -1;
651da177e4SLinus Torvalds 
661da177e4SLinus Torvalds static const char Bad_file[] = "Bad swap file entry ";
671da177e4SLinus Torvalds static const char Unused_file[] = "Unused swap file entry ";
681da177e4SLinus Torvalds static const char Bad_offset[] = "Bad swap offset entry ";
691da177e4SLinus Torvalds static const char Unused_offset[] = "Unused swap offset entry ";
701da177e4SLinus Torvalds 
71adfab836SDan Streetman /*
72adfab836SDan Streetman  * all active swap_info_structs
73adfab836SDan Streetman  * protected with swap_lock, and ordered by priority.
74adfab836SDan Streetman  */
75633423a0SChristoph Hellwig static PLIST_HEAD(swap_active_head);
7618ab4d4cSDan Streetman 
7718ab4d4cSDan Streetman /*
7818ab4d4cSDan Streetman  * all available (active, not full) swap_info_structs
7918ab4d4cSDan Streetman  * protected with swap_avail_lock, ordered by priority.
80e2e3fdc7SMatthew Wilcox (Oracle)  * This is used by folio_alloc_swap() instead of swap_active_head
8118ab4d4cSDan Streetman  * because swap_active_head includes all swap_info_structs,
82e2e3fdc7SMatthew Wilcox (Oracle)  * but folio_alloc_swap() doesn't need to look at full ones.
8318ab4d4cSDan Streetman  * This uses its own lock instead of swap_lock because when a
8418ab4d4cSDan Streetman  * swap_info_struct changes between not-full/full, it needs to
8518ab4d4cSDan Streetman  * add/remove itself to/from this list, but the swap_info_struct->lock
8618ab4d4cSDan Streetman  * is held and the locking order requires swap_lock to be taken
8718ab4d4cSDan Streetman  * before any swap_info_struct->lock.
8818ab4d4cSDan Streetman  */
89bfc6b1caSColin Ian King static struct plist_head *swap_avail_heads;
9018ab4d4cSDan Streetman static DEFINE_SPINLOCK(swap_avail_lock);
911da177e4SLinus Torvalds 
9238b5faf4SDan Magenheimer struct swap_info_struct *swap_info[MAX_SWAPFILES];
931da177e4SLinus Torvalds 
94fc0abb14SIngo Molnar static DEFINE_MUTEX(swapon_mutex);
951da177e4SLinus Torvalds 
9666d7dd51SKay Sievers static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
9766d7dd51SKay Sievers /* Activity counter to indicate that a swapon or swapoff has occurred */
9866d7dd51SKay Sievers static atomic_t proc_poll_event = ATOMIC_INIT(0);
9966d7dd51SKay Sievers 
10081a0298bSHuang Ying atomic_t nr_rotate_swap = ATOMIC_INIT(0);
10181a0298bSHuang Ying 
102c10d38ccSDaniel Jordan static struct swap_info_struct *swap_type_to_swap_info(int type)
103c10d38ccSDaniel Jordan {
104a4b45114SHuang Ying 	if (type >= MAX_SWAPFILES)
105c10d38ccSDaniel Jordan 		return NULL;
106c10d38ccSDaniel Jordan 
107a4b45114SHuang Ying 	return READ_ONCE(swap_info[type]); /* rcu_dereference() */
108c10d38ccSDaniel Jordan }
109c10d38ccSDaniel Jordan 
1108d69aaeeSHugh Dickins static inline unsigned char swap_count(unsigned char ent)
111355cfa73SKAMEZAWA Hiroyuki {
112955c97f0SDaniel Jordan 	return ent & ~SWAP_HAS_CACHE;	/* may include COUNT_CONTINUED flag */
113355cfa73SKAMEZAWA Hiroyuki }
114355cfa73SKAMEZAWA Hiroyuki 
115bcd49e86SHuang Ying /* Reclaim the swap entry anyway if possible */
116bcd49e86SHuang Ying #define TTRS_ANYWAY		0x1
117bcd49e86SHuang Ying /*
118bcd49e86SHuang Ying  * Reclaim the swap entry if there are no more mappings of the
119bcd49e86SHuang Ying  * corresponding page
120bcd49e86SHuang Ying  */
121bcd49e86SHuang Ying #define TTRS_UNMAPPED		0x2
122bcd49e86SHuang Ying /* Reclaim the swap entry if swap is getting full*/
123bcd49e86SHuang Ying #define TTRS_FULL		0x4
124bcd49e86SHuang Ying 
125efa90a98SHugh Dickins /* returns 1 if swap entry is freed */
126bcd49e86SHuang Ying static int __try_to_reclaim_swap(struct swap_info_struct *si,
127bcd49e86SHuang Ying 				 unsigned long offset, unsigned long flags)
128c9e44410SKAMEZAWA Hiroyuki {
129efa90a98SHugh Dickins 	swp_entry_t entry = swp_entry(si->type, offset);
130c9e44410SKAMEZAWA Hiroyuki 	struct page *page;
131c9e44410SKAMEZAWA Hiroyuki 	int ret = 0;
132c9e44410SKAMEZAWA Hiroyuki 
133bcd49e86SHuang Ying 	page = find_get_page(swap_address_space(entry), offset);
134c9e44410SKAMEZAWA Hiroyuki 	if (!page)
135c9e44410SKAMEZAWA Hiroyuki 		return 0;
136c9e44410SKAMEZAWA Hiroyuki 	/*
137bcd49e86SHuang Ying 	 * When this function is called from scan_swap_map_slots() and it's
138bcd49e86SHuang Ying 	 * called by vmscan.c at reclaiming pages. So, we hold a lock on a page,
139bcd49e86SHuang Ying 	 * here. We have to use trylock for avoiding deadlock. This is a special
140c9e44410SKAMEZAWA Hiroyuki 	 * case and you should use try_to_free_swap() with explicit lock_page()
141c9e44410SKAMEZAWA Hiroyuki 	 * in usual operations.
142c9e44410SKAMEZAWA Hiroyuki 	 */
143c9e44410SKAMEZAWA Hiroyuki 	if (trylock_page(page)) {
144bcd49e86SHuang Ying 		if ((flags & TTRS_ANYWAY) ||
145bcd49e86SHuang Ying 		    ((flags & TTRS_UNMAPPED) && !page_mapped(page)) ||
146bcd49e86SHuang Ying 		    ((flags & TTRS_FULL) && mem_cgroup_swap_full(page)))
147c9e44410SKAMEZAWA Hiroyuki 			ret = try_to_free_swap(page);
148c9e44410SKAMEZAWA Hiroyuki 		unlock_page(page);
149c9e44410SKAMEZAWA Hiroyuki 	}
15009cbfeafSKirill A. Shutemov 	put_page(page);
151c9e44410SKAMEZAWA Hiroyuki 	return ret;
152c9e44410SKAMEZAWA Hiroyuki }
153355cfa73SKAMEZAWA Hiroyuki 
1544efaceb1SAaron Lu static inline struct swap_extent *first_se(struct swap_info_struct *sis)
1554efaceb1SAaron Lu {
1564efaceb1SAaron Lu 	struct rb_node *rb = rb_first(&sis->swap_extent_root);
1574efaceb1SAaron Lu 	return rb_entry(rb, struct swap_extent, rb_node);
1584efaceb1SAaron Lu }
1594efaceb1SAaron Lu 
1604efaceb1SAaron Lu static inline struct swap_extent *next_se(struct swap_extent *se)
1614efaceb1SAaron Lu {
1624efaceb1SAaron Lu 	struct rb_node *rb = rb_next(&se->rb_node);
1634efaceb1SAaron Lu 	return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
1644efaceb1SAaron Lu }
1654efaceb1SAaron Lu 
1661da177e4SLinus Torvalds /*
1676a6ba831SHugh Dickins  * swapon tell device that all the old swap contents can be discarded,
1686a6ba831SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
1696a6ba831SHugh Dickins  */
1706a6ba831SHugh Dickins static int discard_swap(struct swap_info_struct *si)
1716a6ba831SHugh Dickins {
1726a6ba831SHugh Dickins 	struct swap_extent *se;
1739625a5f2SHugh Dickins 	sector_t start_block;
1749625a5f2SHugh Dickins 	sector_t nr_blocks;
1756a6ba831SHugh Dickins 	int err = 0;
1766a6ba831SHugh Dickins 
1776a6ba831SHugh Dickins 	/* Do not discard the swap header page! */
1784efaceb1SAaron Lu 	se = first_se(si);
1799625a5f2SHugh Dickins 	start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
1809625a5f2SHugh Dickins 	nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
1819625a5f2SHugh Dickins 	if (nr_blocks) {
1829625a5f2SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
183dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1849625a5f2SHugh Dickins 		if (err)
1859625a5f2SHugh Dickins 			return err;
1869625a5f2SHugh Dickins 		cond_resched();
1876a6ba831SHugh Dickins 	}
1886a6ba831SHugh Dickins 
1894efaceb1SAaron Lu 	for (se = next_se(se); se; se = next_se(se)) {
1909625a5f2SHugh Dickins 		start_block = se->start_block << (PAGE_SHIFT - 9);
1919625a5f2SHugh Dickins 		nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
1929625a5f2SHugh Dickins 
1936a6ba831SHugh Dickins 		err = blkdev_issue_discard(si->bdev, start_block,
194dd3932edSChristoph Hellwig 				nr_blocks, GFP_KERNEL, 0);
1956a6ba831SHugh Dickins 		if (err)
1966a6ba831SHugh Dickins 			break;
1976a6ba831SHugh Dickins 
1986a6ba831SHugh Dickins 		cond_resched();
1996a6ba831SHugh Dickins 	}
2006a6ba831SHugh Dickins 	return err;		/* That will often be -EOPNOTSUPP */
2016a6ba831SHugh Dickins }
2026a6ba831SHugh Dickins 
2034efaceb1SAaron Lu static struct swap_extent *
2044efaceb1SAaron Lu offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
2054efaceb1SAaron Lu {
2064efaceb1SAaron Lu 	struct swap_extent *se;
2074efaceb1SAaron Lu 	struct rb_node *rb;
2084efaceb1SAaron Lu 
2094efaceb1SAaron Lu 	rb = sis->swap_extent_root.rb_node;
2104efaceb1SAaron Lu 	while (rb) {
2114efaceb1SAaron Lu 		se = rb_entry(rb, struct swap_extent, rb_node);
2124efaceb1SAaron Lu 		if (offset < se->start_page)
2134efaceb1SAaron Lu 			rb = rb->rb_left;
2144efaceb1SAaron Lu 		else if (offset >= se->start_page + se->nr_pages)
2154efaceb1SAaron Lu 			rb = rb->rb_right;
2164efaceb1SAaron Lu 		else
2174efaceb1SAaron Lu 			return se;
2184efaceb1SAaron Lu 	}
2194efaceb1SAaron Lu 	/* It *must* be present */
2204efaceb1SAaron Lu 	BUG();
2214efaceb1SAaron Lu }
2224efaceb1SAaron Lu 
223caf6912fSJens Axboe sector_t swap_page_sector(struct page *page)
224caf6912fSJens Axboe {
225caf6912fSJens Axboe 	struct swap_info_struct *sis = page_swap_info(page);
226caf6912fSJens Axboe 	struct swap_extent *se;
227caf6912fSJens Axboe 	sector_t sector;
228caf6912fSJens Axboe 	pgoff_t offset;
229caf6912fSJens Axboe 
230caf6912fSJens Axboe 	offset = __page_file_index(page);
231caf6912fSJens Axboe 	se = offset_to_swap_extent(sis, offset);
232caf6912fSJens Axboe 	sector = se->start_block + (offset - se->start_page);
233caf6912fSJens Axboe 	return sector << (PAGE_SHIFT - 9);
234caf6912fSJens Axboe }
235caf6912fSJens Axboe 
2367992fde7SHugh Dickins /*
2377992fde7SHugh Dickins  * swap allocation tell device that a cluster of swap can now be discarded,
2387992fde7SHugh Dickins  * to allow the swap device to optimize its wear-levelling.
2397992fde7SHugh Dickins  */
2407992fde7SHugh Dickins static void discard_swap_cluster(struct swap_info_struct *si,
2417992fde7SHugh Dickins 				 pgoff_t start_page, pgoff_t nr_pages)
2427992fde7SHugh Dickins {
2434efaceb1SAaron Lu 	struct swap_extent *se = offset_to_swap_extent(si, start_page);
2447992fde7SHugh Dickins 
2457992fde7SHugh Dickins 	while (nr_pages) {
2467992fde7SHugh Dickins 		pgoff_t offset = start_page - se->start_page;
2477992fde7SHugh Dickins 		sector_t start_block = se->start_block + offset;
248858a2990SHugh Dickins 		sector_t nr_blocks = se->nr_pages - offset;
2497992fde7SHugh Dickins 
2507992fde7SHugh Dickins 		if (nr_blocks > nr_pages)
2517992fde7SHugh Dickins 			nr_blocks = nr_pages;
2527992fde7SHugh Dickins 		start_page += nr_blocks;
2537992fde7SHugh Dickins 		nr_pages -= nr_blocks;
2547992fde7SHugh Dickins 
2557992fde7SHugh Dickins 		start_block <<= PAGE_SHIFT - 9;
2567992fde7SHugh Dickins 		nr_blocks <<= PAGE_SHIFT - 9;
2577992fde7SHugh Dickins 		if (blkdev_issue_discard(si->bdev, start_block,
258dd3932edSChristoph Hellwig 					nr_blocks, GFP_NOIO, 0))
2597992fde7SHugh Dickins 			break;
2607992fde7SHugh Dickins 
2614efaceb1SAaron Lu 		se = next_se(se);
2627992fde7SHugh Dickins 	}
2637992fde7SHugh Dickins }
2647992fde7SHugh Dickins 
26538d8b4e6SHuang Ying #ifdef CONFIG_THP_SWAP
26638d8b4e6SHuang Ying #define SWAPFILE_CLUSTER	HPAGE_PMD_NR
267a448f2d0SHuang Ying 
268a448f2d0SHuang Ying #define swap_entry_size(size)	(size)
26938d8b4e6SHuang Ying #else
270048c27fdSHugh Dickins #define SWAPFILE_CLUSTER	256
271a448f2d0SHuang Ying 
272a448f2d0SHuang Ying /*
273a448f2d0SHuang Ying  * Define swap_entry_size() as constant to let compiler to optimize
274a448f2d0SHuang Ying  * out some code if !CONFIG_THP_SWAP
275a448f2d0SHuang Ying  */
276a448f2d0SHuang Ying #define swap_entry_size(size)	1
27738d8b4e6SHuang Ying #endif
278048c27fdSHugh Dickins #define LATENCY_LIMIT		256
279048c27fdSHugh Dickins 
2802a8f9449SShaohua Li static inline void cluster_set_flag(struct swap_cluster_info *info,
2812a8f9449SShaohua Li 	unsigned int flag)
2822a8f9449SShaohua Li {
2832a8f9449SShaohua Li 	info->flags = flag;
2842a8f9449SShaohua Li }
2852a8f9449SShaohua Li 
2862a8f9449SShaohua Li static inline unsigned int cluster_count(struct swap_cluster_info *info)
2872a8f9449SShaohua Li {
2882a8f9449SShaohua Li 	return info->data;
2892a8f9449SShaohua Li }
2902a8f9449SShaohua Li 
2912a8f9449SShaohua Li static inline void cluster_set_count(struct swap_cluster_info *info,
2922a8f9449SShaohua Li 				     unsigned int c)
2932a8f9449SShaohua Li {
2942a8f9449SShaohua Li 	info->data = c;
2952a8f9449SShaohua Li }
2962a8f9449SShaohua Li 
2972a8f9449SShaohua Li static inline void cluster_set_count_flag(struct swap_cluster_info *info,
2982a8f9449SShaohua Li 					 unsigned int c, unsigned int f)
2992a8f9449SShaohua Li {
3002a8f9449SShaohua Li 	info->flags = f;
3012a8f9449SShaohua Li 	info->data = c;
3022a8f9449SShaohua Li }
3032a8f9449SShaohua Li 
3042a8f9449SShaohua Li static inline unsigned int cluster_next(struct swap_cluster_info *info)
3052a8f9449SShaohua Li {
3062a8f9449SShaohua Li 	return info->data;
3072a8f9449SShaohua Li }
3082a8f9449SShaohua Li 
3092a8f9449SShaohua Li static inline void cluster_set_next(struct swap_cluster_info *info,
3102a8f9449SShaohua Li 				    unsigned int n)
3112a8f9449SShaohua Li {
3122a8f9449SShaohua Li 	info->data = n;
3132a8f9449SShaohua Li }
3142a8f9449SShaohua Li 
3152a8f9449SShaohua Li static inline void cluster_set_next_flag(struct swap_cluster_info *info,
3162a8f9449SShaohua Li 					 unsigned int n, unsigned int f)
3172a8f9449SShaohua Li {
3182a8f9449SShaohua Li 	info->flags = f;
3192a8f9449SShaohua Li 	info->data = n;
3202a8f9449SShaohua Li }
3212a8f9449SShaohua Li 
3222a8f9449SShaohua Li static inline bool cluster_is_free(struct swap_cluster_info *info)
3232a8f9449SShaohua Li {
3242a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_FREE;
3252a8f9449SShaohua Li }
3262a8f9449SShaohua Li 
3272a8f9449SShaohua Li static inline bool cluster_is_null(struct swap_cluster_info *info)
3282a8f9449SShaohua Li {
3292a8f9449SShaohua Li 	return info->flags & CLUSTER_FLAG_NEXT_NULL;
3302a8f9449SShaohua Li }
3312a8f9449SShaohua Li 
3322a8f9449SShaohua Li static inline void cluster_set_null(struct swap_cluster_info *info)
3332a8f9449SShaohua Li {
3342a8f9449SShaohua Li 	info->flags = CLUSTER_FLAG_NEXT_NULL;
3352a8f9449SShaohua Li 	info->data = 0;
3362a8f9449SShaohua Li }
3372a8f9449SShaohua Li 
338e0709829SHuang Ying static inline bool cluster_is_huge(struct swap_cluster_info *info)
339e0709829SHuang Ying {
34033ee011eSHuang Ying 	if (IS_ENABLED(CONFIG_THP_SWAP))
341e0709829SHuang Ying 		return info->flags & CLUSTER_FLAG_HUGE;
34233ee011eSHuang Ying 	return false;
343e0709829SHuang Ying }
344e0709829SHuang Ying 
345e0709829SHuang Ying static inline void cluster_clear_huge(struct swap_cluster_info *info)
346e0709829SHuang Ying {
347e0709829SHuang Ying 	info->flags &= ~CLUSTER_FLAG_HUGE;
348e0709829SHuang Ying }
349e0709829SHuang Ying 
350235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
351235b6217SHuang, Ying 						     unsigned long offset)
352235b6217SHuang, Ying {
353235b6217SHuang, Ying 	struct swap_cluster_info *ci;
354235b6217SHuang, Ying 
355235b6217SHuang, Ying 	ci = si->cluster_info;
356235b6217SHuang, Ying 	if (ci) {
357235b6217SHuang, Ying 		ci += offset / SWAPFILE_CLUSTER;
358235b6217SHuang, Ying 		spin_lock(&ci->lock);
359235b6217SHuang, Ying 	}
360235b6217SHuang, Ying 	return ci;
361235b6217SHuang, Ying }
362235b6217SHuang, Ying 
363235b6217SHuang, Ying static inline void unlock_cluster(struct swap_cluster_info *ci)
364235b6217SHuang, Ying {
365235b6217SHuang, Ying 	if (ci)
366235b6217SHuang, Ying 		spin_unlock(&ci->lock);
367235b6217SHuang, Ying }
368235b6217SHuang, Ying 
36959d98bf3SHuang Ying /*
37059d98bf3SHuang Ying  * Determine the locking method in use for this device.  Return
37159d98bf3SHuang Ying  * swap_cluster_info if SSD-style cluster-based locking is in place.
37259d98bf3SHuang Ying  */
373235b6217SHuang, Ying static inline struct swap_cluster_info *lock_cluster_or_swap_info(
37459d98bf3SHuang Ying 		struct swap_info_struct *si, unsigned long offset)
375235b6217SHuang, Ying {
376235b6217SHuang, Ying 	struct swap_cluster_info *ci;
377235b6217SHuang, Ying 
37859d98bf3SHuang Ying 	/* Try to use fine-grained SSD-style locking if available: */
379235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
38059d98bf3SHuang Ying 	/* Otherwise, fall back to traditional, coarse locking: */
381235b6217SHuang, Ying 	if (!ci)
382235b6217SHuang, Ying 		spin_lock(&si->lock);
383235b6217SHuang, Ying 
384235b6217SHuang, Ying 	return ci;
385235b6217SHuang, Ying }
386235b6217SHuang, Ying 
387235b6217SHuang, Ying static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
388235b6217SHuang, Ying 					       struct swap_cluster_info *ci)
389235b6217SHuang, Ying {
390235b6217SHuang, Ying 	if (ci)
391235b6217SHuang, Ying 		unlock_cluster(ci);
392235b6217SHuang, Ying 	else
393235b6217SHuang, Ying 		spin_unlock(&si->lock);
394235b6217SHuang, Ying }
395235b6217SHuang, Ying 
3966b534915SHuang Ying static inline bool cluster_list_empty(struct swap_cluster_list *list)
3976b534915SHuang Ying {
3986b534915SHuang Ying 	return cluster_is_null(&list->head);
3996b534915SHuang Ying }
4006b534915SHuang Ying 
4016b534915SHuang Ying static inline unsigned int cluster_list_first(struct swap_cluster_list *list)
4026b534915SHuang Ying {
4036b534915SHuang Ying 	return cluster_next(&list->head);
4046b534915SHuang Ying }
4056b534915SHuang Ying 
4066b534915SHuang Ying static void cluster_list_init(struct swap_cluster_list *list)
4076b534915SHuang Ying {
4086b534915SHuang Ying 	cluster_set_null(&list->head);
4096b534915SHuang Ying 	cluster_set_null(&list->tail);
4106b534915SHuang Ying }
4116b534915SHuang Ying 
4126b534915SHuang Ying static void cluster_list_add_tail(struct swap_cluster_list *list,
4136b534915SHuang Ying 				  struct swap_cluster_info *ci,
4146b534915SHuang Ying 				  unsigned int idx)
4156b534915SHuang Ying {
4166b534915SHuang Ying 	if (cluster_list_empty(list)) {
4176b534915SHuang Ying 		cluster_set_next_flag(&list->head, idx, 0);
4186b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4196b534915SHuang Ying 	} else {
420235b6217SHuang, Ying 		struct swap_cluster_info *ci_tail;
4216b534915SHuang Ying 		unsigned int tail = cluster_next(&list->tail);
4226b534915SHuang Ying 
423235b6217SHuang, Ying 		/*
424235b6217SHuang, Ying 		 * Nested cluster lock, but both cluster locks are
425235b6217SHuang, Ying 		 * only acquired when we held swap_info_struct->lock
426235b6217SHuang, Ying 		 */
427235b6217SHuang, Ying 		ci_tail = ci + tail;
428235b6217SHuang, Ying 		spin_lock_nested(&ci_tail->lock, SINGLE_DEPTH_NESTING);
429235b6217SHuang, Ying 		cluster_set_next(ci_tail, idx);
4300ef017d1SHuang Ying 		spin_unlock(&ci_tail->lock);
4316b534915SHuang Ying 		cluster_set_next_flag(&list->tail, idx, 0);
4326b534915SHuang Ying 	}
4336b534915SHuang Ying }
4346b534915SHuang Ying 
4356b534915SHuang Ying static unsigned int cluster_list_del_first(struct swap_cluster_list *list,
4366b534915SHuang Ying 					   struct swap_cluster_info *ci)
4376b534915SHuang Ying {
4386b534915SHuang Ying 	unsigned int idx;
4396b534915SHuang Ying 
4406b534915SHuang Ying 	idx = cluster_next(&list->head);
4416b534915SHuang Ying 	if (cluster_next(&list->tail) == idx) {
4426b534915SHuang Ying 		cluster_set_null(&list->head);
4436b534915SHuang Ying 		cluster_set_null(&list->tail);
4446b534915SHuang Ying 	} else
4456b534915SHuang Ying 		cluster_set_next_flag(&list->head,
4466b534915SHuang Ying 				      cluster_next(&ci[idx]), 0);
4476b534915SHuang Ying 
4486b534915SHuang Ying 	return idx;
4496b534915SHuang Ying }
4506b534915SHuang Ying 
451815c2c54SShaohua Li /* Add a cluster to discard list and schedule it to do discard */
452815c2c54SShaohua Li static void swap_cluster_schedule_discard(struct swap_info_struct *si,
453815c2c54SShaohua Li 		unsigned int idx)
454815c2c54SShaohua Li {
455815c2c54SShaohua Li 	/*
456bb243f7dSMiaohe Lin 	 * If scan_swap_map_slots() can't find a free cluster, it will check
457815c2c54SShaohua Li 	 * si->swap_map directly. To make sure the discarding cluster isn't
458bb243f7dSMiaohe Lin 	 * taken by scan_swap_map_slots(), mark the swap entries bad (occupied).
459bb243f7dSMiaohe Lin 	 * It will be cleared after discard
460815c2c54SShaohua Li 	 */
461815c2c54SShaohua Li 	memset(si->swap_map + idx * SWAPFILE_CLUSTER,
462815c2c54SShaohua Li 			SWAP_MAP_BAD, SWAPFILE_CLUSTER);
463815c2c54SShaohua Li 
4646b534915SHuang Ying 	cluster_list_add_tail(&si->discard_clusters, si->cluster_info, idx);
465815c2c54SShaohua Li 
466815c2c54SShaohua Li 	schedule_work(&si->discard_work);
467815c2c54SShaohua Li }
468815c2c54SShaohua Li 
46938d8b4e6SHuang Ying static void __free_cluster(struct swap_info_struct *si, unsigned long idx)
47038d8b4e6SHuang Ying {
47138d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
47238d8b4e6SHuang Ying 
47338d8b4e6SHuang Ying 	cluster_set_flag(ci + idx, CLUSTER_FLAG_FREE);
47438d8b4e6SHuang Ying 	cluster_list_add_tail(&si->free_clusters, ci, idx);
47538d8b4e6SHuang Ying }
47638d8b4e6SHuang Ying 
477815c2c54SShaohua Li /*
478815c2c54SShaohua Li  * Doing discard actually. After a cluster discard is finished, the cluster
479815c2c54SShaohua Li  * will be added to free cluster list. caller should hold si->lock.
480815c2c54SShaohua Li */
481815c2c54SShaohua Li static void swap_do_scheduled_discard(struct swap_info_struct *si)
482815c2c54SShaohua Li {
483235b6217SHuang, Ying 	struct swap_cluster_info *info, *ci;
484815c2c54SShaohua Li 	unsigned int idx;
485815c2c54SShaohua Li 
486815c2c54SShaohua Li 	info = si->cluster_info;
487815c2c54SShaohua Li 
4886b534915SHuang Ying 	while (!cluster_list_empty(&si->discard_clusters)) {
4896b534915SHuang Ying 		idx = cluster_list_del_first(&si->discard_clusters, info);
490815c2c54SShaohua Li 		spin_unlock(&si->lock);
491815c2c54SShaohua Li 
492815c2c54SShaohua Li 		discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
493815c2c54SShaohua Li 				SWAPFILE_CLUSTER);
494815c2c54SShaohua Li 
495815c2c54SShaohua Li 		spin_lock(&si->lock);
496235b6217SHuang, Ying 		ci = lock_cluster(si, idx * SWAPFILE_CLUSTER);
49738d8b4e6SHuang Ying 		__free_cluster(si, idx);
498815c2c54SShaohua Li 		memset(si->swap_map + idx * SWAPFILE_CLUSTER,
499815c2c54SShaohua Li 				0, SWAPFILE_CLUSTER);
500235b6217SHuang, Ying 		unlock_cluster(ci);
501815c2c54SShaohua Li 	}
502815c2c54SShaohua Li }
503815c2c54SShaohua Li 
504815c2c54SShaohua Li static void swap_discard_work(struct work_struct *work)
505815c2c54SShaohua Li {
506815c2c54SShaohua Li 	struct swap_info_struct *si;
507815c2c54SShaohua Li 
508815c2c54SShaohua Li 	si = container_of(work, struct swap_info_struct, discard_work);
509815c2c54SShaohua Li 
510815c2c54SShaohua Li 	spin_lock(&si->lock);
511815c2c54SShaohua Li 	swap_do_scheduled_discard(si);
512815c2c54SShaohua Li 	spin_unlock(&si->lock);
513815c2c54SShaohua Li }
514815c2c54SShaohua Li 
51563d8620eSMiaohe Lin static void swap_users_ref_free(struct percpu_ref *ref)
51663d8620eSMiaohe Lin {
51763d8620eSMiaohe Lin 	struct swap_info_struct *si;
51863d8620eSMiaohe Lin 
51963d8620eSMiaohe Lin 	si = container_of(ref, struct swap_info_struct, users);
52063d8620eSMiaohe Lin 	complete(&si->comp);
52163d8620eSMiaohe Lin }
52263d8620eSMiaohe Lin 
52338d8b4e6SHuang Ying static void alloc_cluster(struct swap_info_struct *si, unsigned long idx)
52438d8b4e6SHuang Ying {
52538d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info;
52638d8b4e6SHuang Ying 
52738d8b4e6SHuang Ying 	VM_BUG_ON(cluster_list_first(&si->free_clusters) != idx);
52838d8b4e6SHuang Ying 	cluster_list_del_first(&si->free_clusters, ci);
52938d8b4e6SHuang Ying 	cluster_set_count_flag(ci + idx, 0, 0);
53038d8b4e6SHuang Ying }
53138d8b4e6SHuang Ying 
53238d8b4e6SHuang Ying static void free_cluster(struct swap_info_struct *si, unsigned long idx)
53338d8b4e6SHuang Ying {
53438d8b4e6SHuang Ying 	struct swap_cluster_info *ci = si->cluster_info + idx;
53538d8b4e6SHuang Ying 
53638d8b4e6SHuang Ying 	VM_BUG_ON(cluster_count(ci) != 0);
53738d8b4e6SHuang Ying 	/*
53838d8b4e6SHuang Ying 	 * If the swap is discardable, prepare discard the cluster
53938d8b4e6SHuang Ying 	 * instead of free it immediately. The cluster will be freed
54038d8b4e6SHuang Ying 	 * after discard.
54138d8b4e6SHuang Ying 	 */
54238d8b4e6SHuang Ying 	if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
54338d8b4e6SHuang Ying 	    (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
54438d8b4e6SHuang Ying 		swap_cluster_schedule_discard(si, idx);
54538d8b4e6SHuang Ying 		return;
54638d8b4e6SHuang Ying 	}
54738d8b4e6SHuang Ying 
54838d8b4e6SHuang Ying 	__free_cluster(si, idx);
54938d8b4e6SHuang Ying }
55038d8b4e6SHuang Ying 
5512a8f9449SShaohua Li /*
5522a8f9449SShaohua Li  * The cluster corresponding to page_nr will be used. The cluster will be
5532a8f9449SShaohua Li  * removed from free cluster list and its usage counter will be increased.
5542a8f9449SShaohua Li  */
5552a8f9449SShaohua Li static void inc_cluster_info_page(struct swap_info_struct *p,
5562a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5572a8f9449SShaohua Li {
5582a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5592a8f9449SShaohua Li 
5602a8f9449SShaohua Li 	if (!cluster_info)
5612a8f9449SShaohua Li 		return;
56238d8b4e6SHuang Ying 	if (cluster_is_free(&cluster_info[idx]))
56338d8b4e6SHuang Ying 		alloc_cluster(p, idx);
5642a8f9449SShaohua Li 
5652a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) >= SWAPFILE_CLUSTER);
5662a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5672a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) + 1);
5682a8f9449SShaohua Li }
5692a8f9449SShaohua Li 
5702a8f9449SShaohua Li /*
5712a8f9449SShaohua Li  * The cluster corresponding to page_nr decreases one usage. If the usage
5722a8f9449SShaohua Li  * counter becomes 0, which means no page in the cluster is in using, we can
5732a8f9449SShaohua Li  * optionally discard the cluster and add it to free cluster list.
5742a8f9449SShaohua Li  */
5752a8f9449SShaohua Li static void dec_cluster_info_page(struct swap_info_struct *p,
5762a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info, unsigned long page_nr)
5772a8f9449SShaohua Li {
5782a8f9449SShaohua Li 	unsigned long idx = page_nr / SWAPFILE_CLUSTER;
5792a8f9449SShaohua Li 
5802a8f9449SShaohua Li 	if (!cluster_info)
5812a8f9449SShaohua Li 		return;
5822a8f9449SShaohua Li 
5832a8f9449SShaohua Li 	VM_BUG_ON(cluster_count(&cluster_info[idx]) == 0);
5842a8f9449SShaohua Li 	cluster_set_count(&cluster_info[idx],
5852a8f9449SShaohua Li 		cluster_count(&cluster_info[idx]) - 1);
5862a8f9449SShaohua Li 
58738d8b4e6SHuang Ying 	if (cluster_count(&cluster_info[idx]) == 0)
58838d8b4e6SHuang Ying 		free_cluster(p, idx);
5892a8f9449SShaohua Li }
5902a8f9449SShaohua Li 
5912a8f9449SShaohua Li /*
592bb243f7dSMiaohe Lin  * It's possible scan_swap_map_slots() uses a free cluster in the middle of free
5932a8f9449SShaohua Li  * cluster list. Avoiding such abuse to avoid list corruption.
5942a8f9449SShaohua Li  */
595ebc2a1a6SShaohua Li static bool
596ebc2a1a6SShaohua Li scan_swap_map_ssd_cluster_conflict(struct swap_info_struct *si,
5972a8f9449SShaohua Li 	unsigned long offset)
5982a8f9449SShaohua Li {
599ebc2a1a6SShaohua Li 	struct percpu_cluster *percpu_cluster;
600ebc2a1a6SShaohua Li 	bool conflict;
601ebc2a1a6SShaohua Li 
6022a8f9449SShaohua Li 	offset /= SWAPFILE_CLUSTER;
6036b534915SHuang Ying 	conflict = !cluster_list_empty(&si->free_clusters) &&
6046b534915SHuang Ying 		offset != cluster_list_first(&si->free_clusters) &&
6052a8f9449SShaohua Li 		cluster_is_free(&si->cluster_info[offset]);
606ebc2a1a6SShaohua Li 
607ebc2a1a6SShaohua Li 	if (!conflict)
608ebc2a1a6SShaohua Li 		return false;
609ebc2a1a6SShaohua Li 
610ebc2a1a6SShaohua Li 	percpu_cluster = this_cpu_ptr(si->percpu_cluster);
611ebc2a1a6SShaohua Li 	cluster_set_null(&percpu_cluster->index);
612ebc2a1a6SShaohua Li 	return true;
613ebc2a1a6SShaohua Li }
614ebc2a1a6SShaohua Li 
615ebc2a1a6SShaohua Li /*
616ebc2a1a6SShaohua Li  * Try to get a swap entry from current cpu's swap entry pool (a cluster). This
617ebc2a1a6SShaohua Li  * might involve allocating a new cluster for current CPU too.
618ebc2a1a6SShaohua Li  */
61936005baeSTim Chen static bool scan_swap_map_try_ssd_cluster(struct swap_info_struct *si,
620ebc2a1a6SShaohua Li 	unsigned long *offset, unsigned long *scan_base)
621ebc2a1a6SShaohua Li {
622ebc2a1a6SShaohua Li 	struct percpu_cluster *cluster;
623235b6217SHuang, Ying 	struct swap_cluster_info *ci;
624235b6217SHuang, Ying 	unsigned long tmp, max;
625ebc2a1a6SShaohua Li 
626ebc2a1a6SShaohua Li new_cluster:
627ebc2a1a6SShaohua Li 	cluster = this_cpu_ptr(si->percpu_cluster);
628ebc2a1a6SShaohua Li 	if (cluster_is_null(&cluster->index)) {
6296b534915SHuang Ying 		if (!cluster_list_empty(&si->free_clusters)) {
6306b534915SHuang Ying 			cluster->index = si->free_clusters.head;
631ebc2a1a6SShaohua Li 			cluster->next = cluster_next(&cluster->index) *
632ebc2a1a6SShaohua Li 					SWAPFILE_CLUSTER;
6336b534915SHuang Ying 		} else if (!cluster_list_empty(&si->discard_clusters)) {
634ebc2a1a6SShaohua Li 			/*
635ebc2a1a6SShaohua Li 			 * we don't have free cluster but have some clusters in
63649070588SHuang Ying 			 * discarding, do discard now and reclaim them, then
63749070588SHuang Ying 			 * reread cluster_next_cpu since we dropped si->lock
638ebc2a1a6SShaohua Li 			 */
639ebc2a1a6SShaohua Li 			swap_do_scheduled_discard(si);
64049070588SHuang Ying 			*scan_base = this_cpu_read(*si->cluster_next_cpu);
64149070588SHuang Ying 			*offset = *scan_base;
642ebc2a1a6SShaohua Li 			goto new_cluster;
643ebc2a1a6SShaohua Li 		} else
64436005baeSTim Chen 			return false;
645ebc2a1a6SShaohua Li 	}
646ebc2a1a6SShaohua Li 
647ebc2a1a6SShaohua Li 	/*
648ebc2a1a6SShaohua Li 	 * Other CPUs can use our cluster if they can't find a free cluster,
649ebc2a1a6SShaohua Li 	 * check if there is still free entry in the cluster
650ebc2a1a6SShaohua Li 	 */
651ebc2a1a6SShaohua Li 	tmp = cluster->next;
652235b6217SHuang, Ying 	max = min_t(unsigned long, si->max,
653235b6217SHuang, Ying 		    (cluster_next(&cluster->index) + 1) * SWAPFILE_CLUSTER);
6547b9e2de1SWei Yang 	if (tmp < max) {
655235b6217SHuang, Ying 		ci = lock_cluster(si, tmp);
656235b6217SHuang, Ying 		while (tmp < max) {
6570fd0e19eSWei Yang 			if (!si->swap_map[tmp])
658ebc2a1a6SShaohua Li 				break;
659ebc2a1a6SShaohua Li 			tmp++;
660ebc2a1a6SShaohua Li 		}
661235b6217SHuang, Ying 		unlock_cluster(ci);
6627b9e2de1SWei Yang 	}
6630fd0e19eSWei Yang 	if (tmp >= max) {
664ebc2a1a6SShaohua Li 		cluster_set_null(&cluster->index);
665ebc2a1a6SShaohua Li 		goto new_cluster;
666ebc2a1a6SShaohua Li 	}
667ebc2a1a6SShaohua Li 	cluster->next = tmp + 1;
668ebc2a1a6SShaohua Li 	*offset = tmp;
669ebc2a1a6SShaohua Li 	*scan_base = tmp;
670fdff1debSWei Yang 	return true;
6712a8f9449SShaohua Li }
6722a8f9449SShaohua Li 
673a2468cc9SAaron Lu static void __del_from_avail_list(struct swap_info_struct *p)
674a2468cc9SAaron Lu {
675a2468cc9SAaron Lu 	int nid;
676a2468cc9SAaron Lu 
677a2468cc9SAaron Lu 	for_each_node(nid)
678a2468cc9SAaron Lu 		plist_del(&p->avail_lists[nid], &swap_avail_heads[nid]);
679a2468cc9SAaron Lu }
680a2468cc9SAaron Lu 
681a2468cc9SAaron Lu static void del_from_avail_list(struct swap_info_struct *p)
682a2468cc9SAaron Lu {
683a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
684a2468cc9SAaron Lu 	__del_from_avail_list(p);
685a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
686a2468cc9SAaron Lu }
687a2468cc9SAaron Lu 
68838d8b4e6SHuang Ying static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
68938d8b4e6SHuang Ying 			     unsigned int nr_entries)
69038d8b4e6SHuang Ying {
69138d8b4e6SHuang Ying 	unsigned int end = offset + nr_entries - 1;
69238d8b4e6SHuang Ying 
69338d8b4e6SHuang Ying 	if (offset == si->lowest_bit)
69438d8b4e6SHuang Ying 		si->lowest_bit += nr_entries;
69538d8b4e6SHuang Ying 	if (end == si->highest_bit)
696a449bf58SQian Cai 		WRITE_ONCE(si->highest_bit, si->highest_bit - nr_entries);
69738d8b4e6SHuang Ying 	si->inuse_pages += nr_entries;
69838d8b4e6SHuang Ying 	if (si->inuse_pages == si->pages) {
69938d8b4e6SHuang Ying 		si->lowest_bit = si->max;
70038d8b4e6SHuang Ying 		si->highest_bit = 0;
701a2468cc9SAaron Lu 		del_from_avail_list(si);
70238d8b4e6SHuang Ying 	}
70338d8b4e6SHuang Ying }
70438d8b4e6SHuang Ying 
705a2468cc9SAaron Lu static void add_to_avail_list(struct swap_info_struct *p)
706a2468cc9SAaron Lu {
707a2468cc9SAaron Lu 	int nid;
708a2468cc9SAaron Lu 
709a2468cc9SAaron Lu 	spin_lock(&swap_avail_lock);
710a2468cc9SAaron Lu 	for_each_node(nid) {
711a2468cc9SAaron Lu 		WARN_ON(!plist_node_empty(&p->avail_lists[nid]));
712a2468cc9SAaron Lu 		plist_add(&p->avail_lists[nid], &swap_avail_heads[nid]);
713a2468cc9SAaron Lu 	}
714a2468cc9SAaron Lu 	spin_unlock(&swap_avail_lock);
715a2468cc9SAaron Lu }
716a2468cc9SAaron Lu 
71738d8b4e6SHuang Ying static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
71838d8b4e6SHuang Ying 			    unsigned int nr_entries)
71938d8b4e6SHuang Ying {
7203852f676SJoonsoo Kim 	unsigned long begin = offset;
72138d8b4e6SHuang Ying 	unsigned long end = offset + nr_entries - 1;
72238d8b4e6SHuang Ying 	void (*swap_slot_free_notify)(struct block_device *, unsigned long);
72338d8b4e6SHuang Ying 
72438d8b4e6SHuang Ying 	if (offset < si->lowest_bit)
72538d8b4e6SHuang Ying 		si->lowest_bit = offset;
72638d8b4e6SHuang Ying 	if (end > si->highest_bit) {
72738d8b4e6SHuang Ying 		bool was_full = !si->highest_bit;
72838d8b4e6SHuang Ying 
729a449bf58SQian Cai 		WRITE_ONCE(si->highest_bit, end);
730a2468cc9SAaron Lu 		if (was_full && (si->flags & SWP_WRITEOK))
731a2468cc9SAaron Lu 			add_to_avail_list(si);
73238d8b4e6SHuang Ying 	}
73338d8b4e6SHuang Ying 	atomic_long_add(nr_entries, &nr_swap_pages);
73438d8b4e6SHuang Ying 	si->inuse_pages -= nr_entries;
73538d8b4e6SHuang Ying 	if (si->flags & SWP_BLKDEV)
73638d8b4e6SHuang Ying 		swap_slot_free_notify =
73738d8b4e6SHuang Ying 			si->bdev->bd_disk->fops->swap_slot_free_notify;
73838d8b4e6SHuang Ying 	else
73938d8b4e6SHuang Ying 		swap_slot_free_notify = NULL;
74038d8b4e6SHuang Ying 	while (offset <= end) {
7418a84802eSSteven Price 		arch_swap_invalidate_page(si->type, offset);
74238d8b4e6SHuang Ying 		frontswap_invalidate_page(si->type, offset);
74338d8b4e6SHuang Ying 		if (swap_slot_free_notify)
74438d8b4e6SHuang Ying 			swap_slot_free_notify(si->bdev, offset);
74538d8b4e6SHuang Ying 		offset++;
74638d8b4e6SHuang Ying 	}
7473852f676SJoonsoo Kim 	clear_shadow_from_swap_cache(si->type, begin, end);
74838d8b4e6SHuang Ying }
74938d8b4e6SHuang Ying 
75049070588SHuang Ying static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
75149070588SHuang Ying {
75249070588SHuang Ying 	unsigned long prev;
75349070588SHuang Ying 
75449070588SHuang Ying 	if (!(si->flags & SWP_SOLIDSTATE)) {
75549070588SHuang Ying 		si->cluster_next = next;
75649070588SHuang Ying 		return;
75749070588SHuang Ying 	}
75849070588SHuang Ying 
75949070588SHuang Ying 	prev = this_cpu_read(*si->cluster_next_cpu);
76049070588SHuang Ying 	/*
76149070588SHuang Ying 	 * Cross the swap address space size aligned trunk, choose
76249070588SHuang Ying 	 * another trunk randomly to avoid lock contention on swap
76349070588SHuang Ying 	 * address space if possible.
76449070588SHuang Ying 	 */
76549070588SHuang Ying 	if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=
76649070588SHuang Ying 	    (next >> SWAP_ADDRESS_SPACE_SHIFT)) {
76749070588SHuang Ying 		/* No free swap slots available */
76849070588SHuang Ying 		if (si->highest_bit <= si->lowest_bit)
76949070588SHuang Ying 			return;
77049070588SHuang Ying 		next = si->lowest_bit +
77149070588SHuang Ying 			prandom_u32_max(si->highest_bit - si->lowest_bit + 1);
77249070588SHuang Ying 		next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
77349070588SHuang Ying 		next = max_t(unsigned int, next, si->lowest_bit);
77449070588SHuang Ying 	}
77549070588SHuang Ying 	this_cpu_write(*si->cluster_next_cpu, next);
77649070588SHuang Ying }
77749070588SHuang Ying 
7784b9ae842SMiaohe Lin static bool swap_offset_available_and_locked(struct swap_info_struct *si,
7794b9ae842SMiaohe Lin 					     unsigned long offset)
7804b9ae842SMiaohe Lin {
7814b9ae842SMiaohe Lin 	if (data_race(!si->swap_map[offset])) {
7824b9ae842SMiaohe Lin 		spin_lock(&si->lock);
7834b9ae842SMiaohe Lin 		return true;
7844b9ae842SMiaohe Lin 	}
7854b9ae842SMiaohe Lin 
7864b9ae842SMiaohe Lin 	if (vm_swap_full() && READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
7874b9ae842SMiaohe Lin 		spin_lock(&si->lock);
7884b9ae842SMiaohe Lin 		return true;
7894b9ae842SMiaohe Lin 	}
7904b9ae842SMiaohe Lin 
7914b9ae842SMiaohe Lin 	return false;
7924b9ae842SMiaohe Lin }
7934b9ae842SMiaohe Lin 
79436005baeSTim Chen static int scan_swap_map_slots(struct swap_info_struct *si,
79536005baeSTim Chen 			       unsigned char usage, int nr,
79636005baeSTim Chen 			       swp_entry_t slots[])
7971da177e4SLinus Torvalds {
798235b6217SHuang, Ying 	struct swap_cluster_info *ci;
799ebebbbe9SHugh Dickins 	unsigned long offset;
800c60aa176SHugh Dickins 	unsigned long scan_base;
8017992fde7SHugh Dickins 	unsigned long last_in_cluster = 0;
802048c27fdSHugh Dickins 	int latency_ration = LATENCY_LIMIT;
80336005baeSTim Chen 	int n_ret = 0;
804ed43af10SHuang Ying 	bool scanned_many = false;
80536005baeSTim Chen 
8067dfad418SHugh Dickins 	/*
8077dfad418SHugh Dickins 	 * We try to cluster swap pages by allocating them sequentially
8087dfad418SHugh Dickins 	 * in swap.  Once we've allocated SWAPFILE_CLUSTER pages this
8097dfad418SHugh Dickins 	 * way, however, we resort to first-free allocation, starting
8107dfad418SHugh Dickins 	 * a new cluster.  This prevents us from scattering swap pages
8117dfad418SHugh Dickins 	 * all over the entire swap partition, so that we reduce
8127dfad418SHugh Dickins 	 * overall disk seek times between swap pages.  -- sct
8137dfad418SHugh Dickins 	 * But we do now try to find an empty cluster.  -Andrea
814c60aa176SHugh Dickins 	 * And we let swap pages go all over an SSD partition.  Hugh
8151da177e4SLinus Torvalds 	 */
8167dfad418SHugh Dickins 
81752b7efdbSHugh Dickins 	si->flags += SWP_SCANNING;
81849070588SHuang Ying 	/*
81949070588SHuang Ying 	 * Use percpu scan base for SSD to reduce lock contention on
82049070588SHuang Ying 	 * cluster and swap cache.  For HDD, sequential access is more
82149070588SHuang Ying 	 * important.
82249070588SHuang Ying 	 */
82349070588SHuang Ying 	if (si->flags & SWP_SOLIDSTATE)
82449070588SHuang Ying 		scan_base = this_cpu_read(*si->cluster_next_cpu);
82549070588SHuang Ying 	else
82649070588SHuang Ying 		scan_base = si->cluster_next;
82749070588SHuang Ying 	offset = scan_base;
828ebebbbe9SHugh Dickins 
829ebc2a1a6SShaohua Li 	/* SSD algorithm */
830ebc2a1a6SShaohua Li 	if (si->cluster_info) {
831bd2d18daSWei Yang 		if (!scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
83236005baeSTim Chen 			goto scan;
833f4eaf51aSWei Yang 	} else if (unlikely(!si->cluster_nr--)) {
834ebc2a1a6SShaohua Li 		if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
835ebc2a1a6SShaohua Li 			si->cluster_nr = SWAPFILE_CLUSTER - 1;
8362a8f9449SShaohua Li 			goto checks;
8372a8f9449SShaohua Li 		}
8382a8f9449SShaohua Li 
839ec8acf20SShaohua Li 		spin_unlock(&si->lock);
8407dfad418SHugh Dickins 
841c60aa176SHugh Dickins 		/*
842c60aa176SHugh Dickins 		 * If seek is expensive, start searching for new cluster from
843c60aa176SHugh Dickins 		 * start of partition, to minimize the span of allocated swap.
84450088c44SChen Yucong 		 * If seek is cheap, that is the SWP_SOLIDSTATE si->cluster_info
84550088c44SChen Yucong 		 * case, just handled by scan_swap_map_try_ssd_cluster() above.
846c60aa176SHugh Dickins 		 */
847c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
8487dfad418SHugh Dickins 		last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
8497dfad418SHugh Dickins 
8507dfad418SHugh Dickins 		/* Locate the first empty (unaligned) cluster */
8517dfad418SHugh Dickins 		for (; last_in_cluster <= si->highest_bit; offset++) {
8521da177e4SLinus Torvalds 			if (si->swap_map[offset])
8537dfad418SHugh Dickins 				last_in_cluster = offset + SWAPFILE_CLUSTER;
8547dfad418SHugh Dickins 			else if (offset == last_in_cluster) {
855ec8acf20SShaohua Li 				spin_lock(&si->lock);
856ebebbbe9SHugh Dickins 				offset -= SWAPFILE_CLUSTER - 1;
857ebebbbe9SHugh Dickins 				si->cluster_next = offset;
858ebebbbe9SHugh Dickins 				si->cluster_nr = SWAPFILE_CLUSTER - 1;
859ebebbbe9SHugh Dickins 				goto checks;
8607dfad418SHugh Dickins 			}
861048c27fdSHugh Dickins 			if (unlikely(--latency_ration < 0)) {
862048c27fdSHugh Dickins 				cond_resched();
863048c27fdSHugh Dickins 				latency_ration = LATENCY_LIMIT;
864048c27fdSHugh Dickins 			}
8657dfad418SHugh Dickins 		}
866ebebbbe9SHugh Dickins 
867c60aa176SHugh Dickins 		offset = scan_base;
868ec8acf20SShaohua Li 		spin_lock(&si->lock);
869ebebbbe9SHugh Dickins 		si->cluster_nr = SWAPFILE_CLUSTER - 1;
8707dfad418SHugh Dickins 	}
8717dfad418SHugh Dickins 
872ebebbbe9SHugh Dickins checks:
873ebc2a1a6SShaohua Li 	if (si->cluster_info) {
87436005baeSTim Chen 		while (scan_swap_map_ssd_cluster_conflict(si, offset)) {
87536005baeSTim Chen 		/* take a break if we already got some slots */
87636005baeSTim Chen 			if (n_ret)
87736005baeSTim Chen 				goto done;
87836005baeSTim Chen 			if (!scan_swap_map_try_ssd_cluster(si, &offset,
87936005baeSTim Chen 							&scan_base))
88036005baeSTim Chen 				goto scan;
88136005baeSTim Chen 		}
882ebc2a1a6SShaohua Li 	}
883ebebbbe9SHugh Dickins 	if (!(si->flags & SWP_WRITEOK))
88452b7efdbSHugh Dickins 		goto no_page;
8857dfad418SHugh Dickins 	if (!si->highest_bit)
8867dfad418SHugh Dickins 		goto no_page;
887ebebbbe9SHugh Dickins 	if (offset > si->highest_bit)
888c60aa176SHugh Dickins 		scan_base = offset = si->lowest_bit;
889c9e44410SKAMEZAWA Hiroyuki 
890235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
891b73d7fceSHugh Dickins 	/* reuse swap entry of cache-only swap if not busy. */
892b73d7fceSHugh Dickins 	if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
893c9e44410SKAMEZAWA Hiroyuki 		int swap_was_freed;
894235b6217SHuang, Ying 		unlock_cluster(ci);
895ec8acf20SShaohua Li 		spin_unlock(&si->lock);
896bcd49e86SHuang Ying 		swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY);
897ec8acf20SShaohua Li 		spin_lock(&si->lock);
898c9e44410SKAMEZAWA Hiroyuki 		/* entry was freed successfully, try to use this again */
899c9e44410SKAMEZAWA Hiroyuki 		if (swap_was_freed)
900c9e44410SKAMEZAWA Hiroyuki 			goto checks;
901c9e44410SKAMEZAWA Hiroyuki 		goto scan; /* check next one */
902c9e44410SKAMEZAWA Hiroyuki 	}
903c9e44410SKAMEZAWA Hiroyuki 
904235b6217SHuang, Ying 	if (si->swap_map[offset]) {
905235b6217SHuang, Ying 		unlock_cluster(ci);
90636005baeSTim Chen 		if (!n_ret)
907ebebbbe9SHugh Dickins 			goto scan;
90836005baeSTim Chen 		else
90936005baeSTim Chen 			goto done;
910235b6217SHuang, Ying 	}
911a449bf58SQian Cai 	WRITE_ONCE(si->swap_map[offset], usage);
9122872bb2dSHuang Ying 	inc_cluster_info_page(si, si->cluster_info, offset);
9132872bb2dSHuang Ying 	unlock_cluster(ci);
914ebebbbe9SHugh Dickins 
91538d8b4e6SHuang Ying 	swap_range_alloc(si, offset, 1);
91636005baeSTim Chen 	slots[n_ret++] = swp_entry(si->type, offset);
9177992fde7SHugh Dickins 
91836005baeSTim Chen 	/* got enough slots or reach max slots? */
91936005baeSTim Chen 	if ((n_ret == nr) || (offset >= si->highest_bit))
92036005baeSTim Chen 		goto done;
92136005baeSTim Chen 
92236005baeSTim Chen 	/* search for next available slot */
92336005baeSTim Chen 
92436005baeSTim Chen 	/* time to take a break? */
92536005baeSTim Chen 	if (unlikely(--latency_ration < 0)) {
92636005baeSTim Chen 		if (n_ret)
92736005baeSTim Chen 			goto done;
92836005baeSTim Chen 		spin_unlock(&si->lock);
92936005baeSTim Chen 		cond_resched();
93036005baeSTim Chen 		spin_lock(&si->lock);
93136005baeSTim Chen 		latency_ration = LATENCY_LIMIT;
93236005baeSTim Chen 	}
93336005baeSTim Chen 
93436005baeSTim Chen 	/* try to get more slots in cluster */
93536005baeSTim Chen 	if (si->cluster_info) {
93636005baeSTim Chen 		if (scan_swap_map_try_ssd_cluster(si, &offset, &scan_base))
93736005baeSTim Chen 			goto checks;
938f4eaf51aSWei Yang 	} else if (si->cluster_nr && !si->swap_map[++offset]) {
93936005baeSTim Chen 		/* non-ssd case, still more slots in cluster? */
94036005baeSTim Chen 		--si->cluster_nr;
94136005baeSTim Chen 		goto checks;
94236005baeSTim Chen 	}
94336005baeSTim Chen 
944ed43af10SHuang Ying 	/*
945ed43af10SHuang Ying 	 * Even if there's no free clusters available (fragmented),
946ed43af10SHuang Ying 	 * try to scan a little more quickly with lock held unless we
947ed43af10SHuang Ying 	 * have scanned too many slots already.
948ed43af10SHuang Ying 	 */
949ed43af10SHuang Ying 	if (!scanned_many) {
950ed43af10SHuang Ying 		unsigned long scan_limit;
951ed43af10SHuang Ying 
952ed43af10SHuang Ying 		if (offset < scan_base)
953ed43af10SHuang Ying 			scan_limit = scan_base;
954ed43af10SHuang Ying 		else
955ed43af10SHuang Ying 			scan_limit = si->highest_bit;
956ed43af10SHuang Ying 		for (; offset <= scan_limit && --latency_ration > 0;
957ed43af10SHuang Ying 		     offset++) {
958ed43af10SHuang Ying 			if (!si->swap_map[offset])
959ed43af10SHuang Ying 				goto checks;
960ed43af10SHuang Ying 		}
961ed43af10SHuang Ying 	}
962ed43af10SHuang Ying 
96336005baeSTim Chen done:
96449070588SHuang Ying 	set_cluster_next(si, offset + 1);
96536005baeSTim Chen 	si->flags -= SWP_SCANNING;
96636005baeSTim Chen 	return n_ret;
9677dfad418SHugh Dickins 
968ebebbbe9SHugh Dickins scan:
969ec8acf20SShaohua Li 	spin_unlock(&si->lock);
970a449bf58SQian Cai 	while (++offset <= READ_ONCE(si->highest_bit)) {
9714b9ae842SMiaohe Lin 		if (swap_offset_available_and_locked(si, offset))
97252b7efdbSHugh Dickins 			goto checks;
973048c27fdSHugh Dickins 		if (unlikely(--latency_ration < 0)) {
974048c27fdSHugh Dickins 			cond_resched();
975048c27fdSHugh Dickins 			latency_ration = LATENCY_LIMIT;
976ed43af10SHuang Ying 			scanned_many = true;
977048c27fdSHugh Dickins 		}
97852b7efdbSHugh Dickins 	}
979c60aa176SHugh Dickins 	offset = si->lowest_bit;
980a5998061SJamie Liu 	while (offset < scan_base) {
9814b9ae842SMiaohe Lin 		if (swap_offset_available_and_locked(si, offset))
982ebebbbe9SHugh Dickins 			goto checks;
983c60aa176SHugh Dickins 		if (unlikely(--latency_ration < 0)) {
984c60aa176SHugh Dickins 			cond_resched();
985c60aa176SHugh Dickins 			latency_ration = LATENCY_LIMIT;
986ed43af10SHuang Ying 			scanned_many = true;
987c60aa176SHugh Dickins 		}
988a5998061SJamie Liu 		offset++;
989c60aa176SHugh Dickins 	}
990ec8acf20SShaohua Li 	spin_lock(&si->lock);
9917dfad418SHugh Dickins 
9927dfad418SHugh Dickins no_page:
99352b7efdbSHugh Dickins 	si->flags -= SWP_SCANNING;
99436005baeSTim Chen 	return n_ret;
9951da177e4SLinus Torvalds }
9961da177e4SLinus Torvalds 
99738d8b4e6SHuang Ying static int swap_alloc_cluster(struct swap_info_struct *si, swp_entry_t *slot)
99838d8b4e6SHuang Ying {
99938d8b4e6SHuang Ying 	unsigned long idx;
100038d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
1001661c7566SMiaohe Lin 	unsigned long offset;
100238d8b4e6SHuang Ying 
1003fe5266d5SHuang Ying 	/*
1004fe5266d5SHuang Ying 	 * Should not even be attempting cluster allocations when huge
1005fe5266d5SHuang Ying 	 * page swap is disabled.  Warn and fail the allocation.
1006fe5266d5SHuang Ying 	 */
1007fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP)) {
1008fe5266d5SHuang Ying 		VM_WARN_ON_ONCE(1);
1009fe5266d5SHuang Ying 		return 0;
1010fe5266d5SHuang Ying 	}
1011fe5266d5SHuang Ying 
101238d8b4e6SHuang Ying 	if (cluster_list_empty(&si->free_clusters))
101338d8b4e6SHuang Ying 		return 0;
101438d8b4e6SHuang Ying 
101538d8b4e6SHuang Ying 	idx = cluster_list_first(&si->free_clusters);
101638d8b4e6SHuang Ying 	offset = idx * SWAPFILE_CLUSTER;
101738d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
101838d8b4e6SHuang Ying 	alloc_cluster(si, idx);
1019e0709829SHuang Ying 	cluster_set_count_flag(ci, SWAPFILE_CLUSTER, CLUSTER_FLAG_HUGE);
102038d8b4e6SHuang Ying 
1021661c7566SMiaohe Lin 	memset(si->swap_map + offset, SWAP_HAS_CACHE, SWAPFILE_CLUSTER);
102238d8b4e6SHuang Ying 	unlock_cluster(ci);
102338d8b4e6SHuang Ying 	swap_range_alloc(si, offset, SWAPFILE_CLUSTER);
102438d8b4e6SHuang Ying 	*slot = swp_entry(si->type, offset);
102538d8b4e6SHuang Ying 
102638d8b4e6SHuang Ying 	return 1;
102738d8b4e6SHuang Ying }
102838d8b4e6SHuang Ying 
102938d8b4e6SHuang Ying static void swap_free_cluster(struct swap_info_struct *si, unsigned long idx)
103038d8b4e6SHuang Ying {
103138d8b4e6SHuang Ying 	unsigned long offset = idx * SWAPFILE_CLUSTER;
103238d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
103338d8b4e6SHuang Ying 
103438d8b4e6SHuang Ying 	ci = lock_cluster(si, offset);
1035979aafa5SHuang Ying 	memset(si->swap_map + offset, 0, SWAPFILE_CLUSTER);
103638d8b4e6SHuang Ying 	cluster_set_count_flag(ci, 0, 0);
103738d8b4e6SHuang Ying 	free_cluster(si, idx);
103838d8b4e6SHuang Ying 	unlock_cluster(ci);
103938d8b4e6SHuang Ying 	swap_range_free(si, offset, SWAPFILE_CLUSTER);
104038d8b4e6SHuang Ying }
104138d8b4e6SHuang Ying 
10425d5e8f19SHuang Ying int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_size)
10431da177e4SLinus Torvalds {
10445d5e8f19SHuang Ying 	unsigned long size = swap_entry_size(entry_size);
1045adfab836SDan Streetman 	struct swap_info_struct *si, *next;
104636005baeSTim Chen 	long avail_pgs;
104736005baeSTim Chen 	int n_ret = 0;
1048a2468cc9SAaron Lu 	int node;
10491da177e4SLinus Torvalds 
105038d8b4e6SHuang Ying 	/* Only single cluster request supported */
10515d5e8f19SHuang Ying 	WARN_ON_ONCE(n_goal > 1 && size == SWAPFILE_CLUSTER);
105238d8b4e6SHuang Ying 
1053b50da6e9SZhaoyang Huang 	spin_lock(&swap_avail_lock);
1054b50da6e9SZhaoyang Huang 
10555d5e8f19SHuang Ying 	avail_pgs = atomic_long_read(&nr_swap_pages) / size;
1056b50da6e9SZhaoyang Huang 	if (avail_pgs <= 0) {
1057b50da6e9SZhaoyang Huang 		spin_unlock(&swap_avail_lock);
1058fb4f88dcSHugh Dickins 		goto noswap;
1059b50da6e9SZhaoyang Huang 	}
106036005baeSTim Chen 
106108d3090fSWei Yang 	n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
106236005baeSTim Chen 
10635d5e8f19SHuang Ying 	atomic_long_sub(n_goal * size, &nr_swap_pages);
10641da177e4SLinus Torvalds 
106518ab4d4cSDan Streetman start_over:
1066a2468cc9SAaron Lu 	node = numa_node_id();
1067a2468cc9SAaron Lu 	plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
106818ab4d4cSDan Streetman 		/* requeue si to after same-priority siblings */
1069a2468cc9SAaron Lu 		plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
107018ab4d4cSDan Streetman 		spin_unlock(&swap_avail_lock);
1071ec8acf20SShaohua Li 		spin_lock(&si->lock);
1072adfab836SDan Streetman 		if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
107318ab4d4cSDan Streetman 			spin_lock(&swap_avail_lock);
1074a2468cc9SAaron Lu 			if (plist_node_empty(&si->avail_lists[node])) {
1075ec8acf20SShaohua Li 				spin_unlock(&si->lock);
107618ab4d4cSDan Streetman 				goto nextsi;
107718ab4d4cSDan Streetman 			}
107818ab4d4cSDan Streetman 			WARN(!si->highest_bit,
107918ab4d4cSDan Streetman 			     "swap_info %d in list but !highest_bit\n",
108018ab4d4cSDan Streetman 			     si->type);
108118ab4d4cSDan Streetman 			WARN(!(si->flags & SWP_WRITEOK),
108218ab4d4cSDan Streetman 			     "swap_info %d in list but !SWP_WRITEOK\n",
108318ab4d4cSDan Streetman 			     si->type);
1084a2468cc9SAaron Lu 			__del_from_avail_list(si);
108518ab4d4cSDan Streetman 			spin_unlock(&si->lock);
108618ab4d4cSDan Streetman 			goto nextsi;
1087ec8acf20SShaohua Li 		}
10885d5e8f19SHuang Ying 		if (size == SWAPFILE_CLUSTER) {
108941663430SGao Xiang 			if (si->flags & SWP_BLKDEV)
109038d8b4e6SHuang Ying 				n_ret = swap_alloc_cluster(si, swp_entries);
1091f0eea189SHuang Ying 		} else
109236005baeSTim Chen 			n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
109336005baeSTim Chen 						    n_goal, swp_entries);
1094ec8acf20SShaohua Li 		spin_unlock(&si->lock);
10955d5e8f19SHuang Ying 		if (n_ret || size == SWAPFILE_CLUSTER)
109636005baeSTim Chen 			goto check_out;
109718ab4d4cSDan Streetman 		pr_debug("scan_swap_map of si %d failed to find offset\n",
109818ab4d4cSDan Streetman 			si->type);
109936005baeSTim Chen 
110018ab4d4cSDan Streetman 		spin_lock(&swap_avail_lock);
110118ab4d4cSDan Streetman nextsi:
1102adfab836SDan Streetman 		/*
1103adfab836SDan Streetman 		 * if we got here, it's likely that si was almost full before,
1104bb243f7dSMiaohe Lin 		 * and since scan_swap_map_slots() can drop the si->lock,
1105bb243f7dSMiaohe Lin 		 * multiple callers probably all tried to get a page from the
1106bb243f7dSMiaohe Lin 		 * same si and it filled up before we could get one; or, the si
1107bb243f7dSMiaohe Lin 		 * filled up between us dropping swap_avail_lock and taking
1108bb243f7dSMiaohe Lin 		 * si->lock. Since we dropped the swap_avail_lock, the
1109bb243f7dSMiaohe Lin 		 * swap_avail_head list may have been modified; so if next is
1110bb243f7dSMiaohe Lin 		 * still in the swap_avail_head list then try it, otherwise
1111bb243f7dSMiaohe Lin 		 * start over if we have not gotten any slots.
1112adfab836SDan Streetman 		 */
1113a2468cc9SAaron Lu 		if (plist_node_empty(&next->avail_lists[node]))
111418ab4d4cSDan Streetman 			goto start_over;
1115fb4f88dcSHugh Dickins 	}
1116fb4f88dcSHugh Dickins 
111718ab4d4cSDan Streetman 	spin_unlock(&swap_avail_lock);
111818ab4d4cSDan Streetman 
111936005baeSTim Chen check_out:
112036005baeSTim Chen 	if (n_ret < n_goal)
11215d5e8f19SHuang Ying 		atomic_long_add((long)(n_goal - n_ret) * size,
112238d8b4e6SHuang Ying 				&nr_swap_pages);
1123fb4f88dcSHugh Dickins noswap:
112436005baeSTim Chen 	return n_ret;
112536005baeSTim Chen }
112636005baeSTim Chen 
1127afba72b1SMiaohe Lin static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
11281da177e4SLinus Torvalds {
11291da177e4SLinus Torvalds 	struct swap_info_struct *p;
1130eb085574SHuang Ying 	unsigned long offset;
11311da177e4SLinus Torvalds 
11321da177e4SLinus Torvalds 	if (!entry.val)
11331da177e4SLinus Torvalds 		goto out;
1134eb085574SHuang Ying 	p = swp_swap_info(entry);
1135c10d38ccSDaniel Jordan 	if (!p)
11361da177e4SLinus Torvalds 		goto bad_nofile;
1137a449bf58SQian Cai 	if (data_race(!(p->flags & SWP_USED)))
11381da177e4SLinus Torvalds 		goto bad_device;
11391da177e4SLinus Torvalds 	offset = swp_offset(entry);
11401da177e4SLinus Torvalds 	if (offset >= p->max)
11411da177e4SLinus Torvalds 		goto bad_offset;
1142afba72b1SMiaohe Lin 	if (data_race(!p->swap_map[swp_offset(entry)]))
1143afba72b1SMiaohe Lin 		goto bad_free;
11441da177e4SLinus Torvalds 	return p;
11451da177e4SLinus Torvalds 
1146afba72b1SMiaohe Lin bad_free:
1147afba72b1SMiaohe Lin 	pr_err("%s: %s%08lx\n", __func__, Unused_offset, entry.val);
1148afba72b1SMiaohe Lin 	goto out;
11491da177e4SLinus Torvalds bad_offset:
1150cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
11511da177e4SLinus Torvalds 	goto out;
11521da177e4SLinus Torvalds bad_device:
1153cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Unused_file, entry.val);
11541da177e4SLinus Torvalds 	goto out;
11551da177e4SLinus Torvalds bad_nofile:
1156cf532faaSStephen Zhang 	pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
11571da177e4SLinus Torvalds out:
11581da177e4SLinus Torvalds 	return NULL;
11591da177e4SLinus Torvalds }
11601da177e4SLinus Torvalds 
11617c00bafeSTim Chen static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
11627c00bafeSTim Chen 					struct swap_info_struct *q)
11637c00bafeSTim Chen {
11647c00bafeSTim Chen 	struct swap_info_struct *p;
11657c00bafeSTim Chen 
11667c00bafeSTim Chen 	p = _swap_info_get(entry);
11677c00bafeSTim Chen 
11687c00bafeSTim Chen 	if (p != q) {
11697c00bafeSTim Chen 		if (q != NULL)
11707c00bafeSTim Chen 			spin_unlock(&q->lock);
11717c00bafeSTim Chen 		if (p != NULL)
11727c00bafeSTim Chen 			spin_lock(&p->lock);
11737c00bafeSTim Chen 	}
11747c00bafeSTim Chen 	return p;
11757c00bafeSTim Chen }
11767c00bafeSTim Chen 
1177b32d5f32SHuang Ying static unsigned char __swap_entry_free_locked(struct swap_info_struct *p,
1178b32d5f32SHuang Ying 					      unsigned long offset,
1179b32d5f32SHuang Ying 					      unsigned char usage)
1180235b6217SHuang, Ying {
11818d69aaeeSHugh Dickins 	unsigned char count;
11828d69aaeeSHugh Dickins 	unsigned char has_cache;
1183235b6217SHuang, Ying 
1184355cfa73SKAMEZAWA Hiroyuki 	count = p->swap_map[offset];
1185235b6217SHuang, Ying 
1186253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
1187253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
1188253d553bSHugh Dickins 
1189253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
1190253d553bSHugh Dickins 		VM_BUG_ON(!has_cache);
1191253d553bSHugh Dickins 		has_cache = 0;
1192aaa46865SHugh Dickins 	} else if (count == SWAP_MAP_SHMEM) {
1193aaa46865SHugh Dickins 		/*
1194aaa46865SHugh Dickins 		 * Or we could insist on shmem.c using a special
1195aaa46865SHugh Dickins 		 * swap_shmem_free() and free_shmem_swap_and_cache()...
1196aaa46865SHugh Dickins 		 */
1197aaa46865SHugh Dickins 		count = 0;
1198570a335bSHugh Dickins 	} else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
1199570a335bSHugh Dickins 		if (count == COUNT_CONTINUED) {
1200570a335bSHugh Dickins 			if (swap_count_continued(p, offset, count))
1201570a335bSHugh Dickins 				count = SWAP_MAP_MAX | COUNT_CONTINUED;
1202570a335bSHugh Dickins 			else
1203570a335bSHugh Dickins 				count = SWAP_MAP_MAX;
1204570a335bSHugh Dickins 		} else
1205253d553bSHugh Dickins 			count--;
1206570a335bSHugh Dickins 	}
1207253d553bSHugh Dickins 
1208253d553bSHugh Dickins 	usage = count | has_cache;
1209a449bf58SQian Cai 	if (usage)
1210a449bf58SQian Cai 		WRITE_ONCE(p->swap_map[offset], usage);
1211a449bf58SQian Cai 	else
1212a449bf58SQian Cai 		WRITE_ONCE(p->swap_map[offset], SWAP_HAS_CACHE);
1213253d553bSHugh Dickins 
1214b32d5f32SHuang Ying 	return usage;
1215b32d5f32SHuang Ying }
1216b32d5f32SHuang Ying 
1217eb085574SHuang Ying /*
1218eb085574SHuang Ying  * Check whether swap entry is valid in the swap device.  If so,
1219eb085574SHuang Ying  * return pointer to swap_info_struct, and keep the swap entry valid
1220eb085574SHuang Ying  * via preventing the swap device from being swapoff, until
1221eb085574SHuang Ying  * put_swap_device() is called.  Otherwise return NULL.
1222eb085574SHuang Ying  *
1223eb085574SHuang Ying  * Notice that swapoff or swapoff+swapon can still happen before the
122463d8620eSMiaohe Lin  * percpu_ref_tryget_live() in get_swap_device() or after the
122563d8620eSMiaohe Lin  * percpu_ref_put() in put_swap_device() if there isn't any other way
122663d8620eSMiaohe Lin  * to prevent swapoff, such as page lock, page table lock, etc.  The
122763d8620eSMiaohe Lin  * caller must be prepared for that.  For example, the following
122863d8620eSMiaohe Lin  * situation is possible.
1229eb085574SHuang Ying  *
1230eb085574SHuang Ying  *   CPU1				CPU2
1231eb085574SHuang Ying  *   do_swap_page()
1232eb085574SHuang Ying  *     ...				swapoff+swapon
1233eb085574SHuang Ying  *     __read_swap_cache_async()
1234eb085574SHuang Ying  *       swapcache_prepare()
1235eb085574SHuang Ying  *         __swap_duplicate()
1236eb085574SHuang Ying  *           // check swap_map
1237eb085574SHuang Ying  *     // verify PTE not changed
1238eb085574SHuang Ying  *
1239eb085574SHuang Ying  * In __swap_duplicate(), the swap_map need to be checked before
1240eb085574SHuang Ying  * changing partly because the specified swap entry may be for another
1241eb085574SHuang Ying  * swap device which has been swapoff.  And in do_swap_page(), after
1242eb085574SHuang Ying  * the page is read from the swap device, the PTE is verified not
1243eb085574SHuang Ying  * changed with the page table locked to check whether the swap device
1244eb085574SHuang Ying  * has been swapoff or swapoff+swapon.
1245eb085574SHuang Ying  */
1246eb085574SHuang Ying struct swap_info_struct *get_swap_device(swp_entry_t entry)
1247eb085574SHuang Ying {
1248eb085574SHuang Ying 	struct swap_info_struct *si;
1249eb085574SHuang Ying 	unsigned long offset;
1250eb085574SHuang Ying 
1251eb085574SHuang Ying 	if (!entry.val)
1252eb085574SHuang Ying 		goto out;
1253eb085574SHuang Ying 	si = swp_swap_info(entry);
1254eb085574SHuang Ying 	if (!si)
1255eb085574SHuang Ying 		goto bad_nofile;
125663d8620eSMiaohe Lin 	if (!percpu_ref_tryget_live(&si->users))
125763d8620eSMiaohe Lin 		goto out;
125863d8620eSMiaohe Lin 	/*
125963d8620eSMiaohe Lin 	 * Guarantee the si->users are checked before accessing other
126063d8620eSMiaohe Lin 	 * fields of swap_info_struct.
126163d8620eSMiaohe Lin 	 *
126263d8620eSMiaohe Lin 	 * Paired with the spin_unlock() after setup_swap_info() in
126363d8620eSMiaohe Lin 	 * enable_swap_info().
126463d8620eSMiaohe Lin 	 */
126563d8620eSMiaohe Lin 	smp_rmb();
1266eb085574SHuang Ying 	offset = swp_offset(entry);
1267eb085574SHuang Ying 	if (offset >= si->max)
126863d8620eSMiaohe Lin 		goto put_out;
1269eb085574SHuang Ying 
1270eb085574SHuang Ying 	return si;
1271eb085574SHuang Ying bad_nofile:
1272eb085574SHuang Ying 	pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
1273eb085574SHuang Ying out:
1274eb085574SHuang Ying 	return NULL;
127563d8620eSMiaohe Lin put_out:
127623b230baSMiaohe Lin 	pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
127763d8620eSMiaohe Lin 	percpu_ref_put(&si->users);
1278eb085574SHuang Ying 	return NULL;
1279eb085574SHuang Ying }
1280eb085574SHuang Ying 
1281b32d5f32SHuang Ying static unsigned char __swap_entry_free(struct swap_info_struct *p,
128233e16272SWei Yang 				       swp_entry_t entry)
1283b32d5f32SHuang Ying {
1284b32d5f32SHuang Ying 	struct swap_cluster_info *ci;
1285b32d5f32SHuang Ying 	unsigned long offset = swp_offset(entry);
128633e16272SWei Yang 	unsigned char usage;
1287b32d5f32SHuang Ying 
1288b32d5f32SHuang Ying 	ci = lock_cluster_or_swap_info(p, offset);
128933e16272SWei Yang 	usage = __swap_entry_free_locked(p, offset, 1);
12907c00bafeSTim Chen 	unlock_cluster_or_swap_info(p, ci);
129110e364daSHuang Ying 	if (!usage)
129210e364daSHuang Ying 		free_swap_slot(entry);
1293235b6217SHuang, Ying 
12947c00bafeSTim Chen 	return usage;
12957c00bafeSTim Chen }
12967c00bafeSTim Chen 
12977c00bafeSTim Chen static void swap_entry_free(struct swap_info_struct *p, swp_entry_t entry)
12987c00bafeSTim Chen {
12997c00bafeSTim Chen 	struct swap_cluster_info *ci;
13007c00bafeSTim Chen 	unsigned long offset = swp_offset(entry);
13017c00bafeSTim Chen 	unsigned char count;
13027c00bafeSTim Chen 
1303235b6217SHuang, Ying 	ci = lock_cluster(p, offset);
13047c00bafeSTim Chen 	count = p->swap_map[offset];
13057c00bafeSTim Chen 	VM_BUG_ON(count != SWAP_HAS_CACHE);
13067c00bafeSTim Chen 	p->swap_map[offset] = 0;
13072a8f9449SShaohua Li 	dec_cluster_info_page(p, p->cluster_info, offset);
1308235b6217SHuang, Ying 	unlock_cluster(ci);
13097c00bafeSTim Chen 
131038d8b4e6SHuang Ying 	mem_cgroup_uncharge_swap(entry, 1);
131138d8b4e6SHuang Ying 	swap_range_free(p, offset, 1);
13121da177e4SLinus Torvalds }
1313253d553bSHugh Dickins 
13141da177e4SLinus Torvalds /*
13151da177e4SLinus Torvalds  * Caller has made sure that the swap device corresponding to entry
13161da177e4SLinus Torvalds  * is still around or has not been recycled.
13171da177e4SLinus Torvalds  */
13181da177e4SLinus Torvalds void swap_free(swp_entry_t entry)
13191da177e4SLinus Torvalds {
13201da177e4SLinus Torvalds 	struct swap_info_struct *p;
13211da177e4SLinus Torvalds 
1322235b6217SHuang, Ying 	p = _swap_info_get(entry);
132310e364daSHuang Ying 	if (p)
132433e16272SWei Yang 		__swap_entry_free(p, entry);
13251da177e4SLinus Torvalds }
13261da177e4SLinus Torvalds 
13271da177e4SLinus Torvalds /*
1328cb4b86baSKAMEZAWA Hiroyuki  * Called after dropping swapcache to decrease refcnt to swap entries.
1329cb4b86baSKAMEZAWA Hiroyuki  */
1330a448f2d0SHuang Ying void put_swap_page(struct page *page, swp_entry_t entry)
133138d8b4e6SHuang Ying {
133238d8b4e6SHuang Ying 	unsigned long offset = swp_offset(entry);
133338d8b4e6SHuang Ying 	unsigned long idx = offset / SWAPFILE_CLUSTER;
133438d8b4e6SHuang Ying 	struct swap_cluster_info *ci;
133538d8b4e6SHuang Ying 	struct swap_info_struct *si;
133638d8b4e6SHuang Ying 	unsigned char *map;
1337a3aea839SHuang Ying 	unsigned int i, free_entries = 0;
1338a3aea839SHuang Ying 	unsigned char val;
13396c357848SMatthew Wilcox (Oracle) 	int size = swap_entry_size(thp_nr_pages(page));
1340fe5266d5SHuang Ying 
1341a3aea839SHuang Ying 	si = _swap_info_get(entry);
134238d8b4e6SHuang Ying 	if (!si)
134338d8b4e6SHuang Ying 		return;
134438d8b4e6SHuang Ying 
1345c2343d27SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1346a448f2d0SHuang Ying 	if (size == SWAPFILE_CLUSTER) {
1347e0709829SHuang Ying 		VM_BUG_ON(!cluster_is_huge(ci));
134838d8b4e6SHuang Ying 		map = si->swap_map + offset;
134938d8b4e6SHuang Ying 		for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1350a3aea839SHuang Ying 			val = map[i];
1351a3aea839SHuang Ying 			VM_BUG_ON(!(val & SWAP_HAS_CACHE));
1352a3aea839SHuang Ying 			if (val == SWAP_HAS_CACHE)
1353a3aea839SHuang Ying 				free_entries++;
135438d8b4e6SHuang Ying 		}
1355e0709829SHuang Ying 		cluster_clear_huge(ci);
1356a3aea839SHuang Ying 		if (free_entries == SWAPFILE_CLUSTER) {
1357c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1358a3aea839SHuang Ying 			spin_lock(&si->lock);
135938d8b4e6SHuang Ying 			mem_cgroup_uncharge_swap(entry, SWAPFILE_CLUSTER);
136038d8b4e6SHuang Ying 			swap_free_cluster(si, idx);
136138d8b4e6SHuang Ying 			spin_unlock(&si->lock);
1362a448f2d0SHuang Ying 			return;
1363a448f2d0SHuang Ying 		}
1364a448f2d0SHuang Ying 	}
1365a448f2d0SHuang Ying 	for (i = 0; i < size; i++, entry.val++) {
1366c2343d27SHuang Ying 		if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
1367c2343d27SHuang Ying 			unlock_cluster_or_swap_info(si, ci);
1368a3aea839SHuang Ying 			free_swap_slot(entry);
1369c2343d27SHuang Ying 			if (i == size - 1)
1370c2343d27SHuang Ying 				return;
1371c2343d27SHuang Ying 			lock_cluster_or_swap_info(si, offset);
1372a3aea839SHuang Ying 		}
1373a3aea839SHuang Ying 	}
1374c2343d27SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
137538d8b4e6SHuang Ying }
137659807685SHuang Ying 
1377fe5266d5SHuang Ying #ifdef CONFIG_THP_SWAP
137859807685SHuang Ying int split_swap_cluster(swp_entry_t entry)
137959807685SHuang Ying {
138059807685SHuang Ying 	struct swap_info_struct *si;
138159807685SHuang Ying 	struct swap_cluster_info *ci;
138259807685SHuang Ying 	unsigned long offset = swp_offset(entry);
138359807685SHuang Ying 
138459807685SHuang Ying 	si = _swap_info_get(entry);
138559807685SHuang Ying 	if (!si)
138659807685SHuang Ying 		return -EBUSY;
138759807685SHuang Ying 	ci = lock_cluster(si, offset);
138859807685SHuang Ying 	cluster_clear_huge(ci);
138959807685SHuang Ying 	unlock_cluster(ci);
139059807685SHuang Ying 	return 0;
139159807685SHuang Ying }
1392fe5266d5SHuang Ying #endif
139338d8b4e6SHuang Ying 
1394155b5f88SHuang Ying static int swp_entry_cmp(const void *ent1, const void *ent2)
1395155b5f88SHuang Ying {
1396155b5f88SHuang Ying 	const swp_entry_t *e1 = ent1, *e2 = ent2;
1397155b5f88SHuang Ying 
1398155b5f88SHuang Ying 	return (int)swp_type(*e1) - (int)swp_type(*e2);
1399155b5f88SHuang Ying }
1400155b5f88SHuang Ying 
14017c00bafeSTim Chen void swapcache_free_entries(swp_entry_t *entries, int n)
14027c00bafeSTim Chen {
14037c00bafeSTim Chen 	struct swap_info_struct *p, *prev;
14047c00bafeSTim Chen 	int i;
14057c00bafeSTim Chen 
14067c00bafeSTim Chen 	if (n <= 0)
14077c00bafeSTim Chen 		return;
14087c00bafeSTim Chen 
14097c00bafeSTim Chen 	prev = NULL;
14107c00bafeSTim Chen 	p = NULL;
1411155b5f88SHuang Ying 
1412155b5f88SHuang Ying 	/*
1413155b5f88SHuang Ying 	 * Sort swap entries by swap device, so each lock is only taken once.
1414155b5f88SHuang Ying 	 * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
1415155b5f88SHuang Ying 	 * so low that it isn't necessary to optimize further.
1416155b5f88SHuang Ying 	 */
1417155b5f88SHuang Ying 	if (nr_swapfiles > 1)
1418155b5f88SHuang Ying 		sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
14197c00bafeSTim Chen 	for (i = 0; i < n; ++i) {
14207c00bafeSTim Chen 		p = swap_info_get_cont(entries[i], prev);
1421235b6217SHuang, Ying 		if (p)
14227c00bafeSTim Chen 			swap_entry_free(p, entries[i]);
14237c00bafeSTim Chen 		prev = p;
14247c00bafeSTim Chen 	}
14257c00bafeSTim Chen 	if (p)
14267c00bafeSTim Chen 		spin_unlock(&p->lock);
1427cb4b86baSKAMEZAWA Hiroyuki }
1428cb4b86baSKAMEZAWA Hiroyuki 
1429cb4b86baSKAMEZAWA Hiroyuki /*
1430c475a8abSHugh Dickins  * How many references to page are currently swapped out?
1431570a335bSHugh Dickins  * This does not give an exact answer when swap count is continued,
1432570a335bSHugh Dickins  * but does include the high COUNT_CONTINUED flag to allow for that.
14331da177e4SLinus Torvalds  */
14343db3264dSMiaohe Lin static int page_swapcount(struct page *page)
14351da177e4SLinus Torvalds {
1436c475a8abSHugh Dickins 	int count = 0;
14371da177e4SLinus Torvalds 	struct swap_info_struct *p;
1438235b6217SHuang, Ying 	struct swap_cluster_info *ci;
14391da177e4SLinus Torvalds 	swp_entry_t entry;
1440235b6217SHuang, Ying 	unsigned long offset;
14411da177e4SLinus Torvalds 
14424c21e2f2SHugh Dickins 	entry.val = page_private(page);
1443235b6217SHuang, Ying 	p = _swap_info_get(entry);
14441da177e4SLinus Torvalds 	if (p) {
1445235b6217SHuang, Ying 		offset = swp_offset(entry);
1446235b6217SHuang, Ying 		ci = lock_cluster_or_swap_info(p, offset);
1447235b6217SHuang, Ying 		count = swap_count(p->swap_map[offset]);
1448235b6217SHuang, Ying 		unlock_cluster_or_swap_info(p, ci);
14491da177e4SLinus Torvalds 	}
1450c475a8abSHugh Dickins 	return count;
14511da177e4SLinus Torvalds }
14521da177e4SLinus Torvalds 
1453eb085574SHuang Ying int __swap_count(swp_entry_t entry)
1454aa8d22a1SMinchan Kim {
1455eb085574SHuang Ying 	struct swap_info_struct *si;
1456aa8d22a1SMinchan Kim 	pgoff_t offset = swp_offset(entry);
1457eb085574SHuang Ying 	int count = 0;
1458aa8d22a1SMinchan Kim 
1459eb085574SHuang Ying 	si = get_swap_device(entry);
1460eb085574SHuang Ying 	if (si) {
1461eb085574SHuang Ying 		count = swap_count(si->swap_map[offset]);
1462eb085574SHuang Ying 		put_swap_device(si);
1463eb085574SHuang Ying 	}
1464eb085574SHuang Ying 	return count;
1465aa8d22a1SMinchan Kim }
1466aa8d22a1SMinchan Kim 
1467322b8afeSHuang Ying static int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
1468322b8afeSHuang Ying {
1469322b8afeSHuang Ying 	int count = 0;
1470322b8afeSHuang Ying 	pgoff_t offset = swp_offset(entry);
1471322b8afeSHuang Ying 	struct swap_cluster_info *ci;
1472322b8afeSHuang Ying 
1473322b8afeSHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1474322b8afeSHuang Ying 	count = swap_count(si->swap_map[offset]);
1475322b8afeSHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1476322b8afeSHuang Ying 	return count;
1477322b8afeSHuang Ying }
1478322b8afeSHuang Ying 
14791da177e4SLinus Torvalds /*
14808334b962SMinchan Kim  * How many references to @entry are currently swapped out?
1481e8c26ab6STim Chen  * This does not give an exact answer when swap count is continued,
1482e8c26ab6STim Chen  * but does include the high COUNT_CONTINUED flag to allow for that.
1483e8c26ab6STim Chen  */
1484e8c26ab6STim Chen int __swp_swapcount(swp_entry_t entry)
1485e8c26ab6STim Chen {
1486e8c26ab6STim Chen 	int count = 0;
1487e8c26ab6STim Chen 	struct swap_info_struct *si;
1488e8c26ab6STim Chen 
1489eb085574SHuang Ying 	si = get_swap_device(entry);
1490eb085574SHuang Ying 	if (si) {
1491322b8afeSHuang Ying 		count = swap_swapcount(si, entry);
1492eb085574SHuang Ying 		put_swap_device(si);
1493eb085574SHuang Ying 	}
1494e8c26ab6STim Chen 	return count;
1495e8c26ab6STim Chen }
1496e8c26ab6STim Chen 
1497e8c26ab6STim Chen /*
1498e8c26ab6STim Chen  * How many references to @entry are currently swapped out?
14998334b962SMinchan Kim  * This considers COUNT_CONTINUED so it returns exact answer.
15008334b962SMinchan Kim  */
15018334b962SMinchan Kim int swp_swapcount(swp_entry_t entry)
15028334b962SMinchan Kim {
15038334b962SMinchan Kim 	int count, tmp_count, n;
15048334b962SMinchan Kim 	struct swap_info_struct *p;
1505235b6217SHuang, Ying 	struct swap_cluster_info *ci;
15068334b962SMinchan Kim 	struct page *page;
15078334b962SMinchan Kim 	pgoff_t offset;
15088334b962SMinchan Kim 	unsigned char *map;
15098334b962SMinchan Kim 
1510235b6217SHuang, Ying 	p = _swap_info_get(entry);
15118334b962SMinchan Kim 	if (!p)
15128334b962SMinchan Kim 		return 0;
15138334b962SMinchan Kim 
1514235b6217SHuang, Ying 	offset = swp_offset(entry);
1515235b6217SHuang, Ying 
1516235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
1517235b6217SHuang, Ying 
1518235b6217SHuang, Ying 	count = swap_count(p->swap_map[offset]);
15198334b962SMinchan Kim 	if (!(count & COUNT_CONTINUED))
15208334b962SMinchan Kim 		goto out;
15218334b962SMinchan Kim 
15228334b962SMinchan Kim 	count &= ~COUNT_CONTINUED;
15238334b962SMinchan Kim 	n = SWAP_MAP_MAX + 1;
15248334b962SMinchan Kim 
15258334b962SMinchan Kim 	page = vmalloc_to_page(p->swap_map + offset);
15268334b962SMinchan Kim 	offset &= ~PAGE_MASK;
15278334b962SMinchan Kim 	VM_BUG_ON(page_private(page) != SWP_CONTINUED);
15288334b962SMinchan Kim 
15298334b962SMinchan Kim 	do {
1530a8ae4991SGeliang Tang 		page = list_next_entry(page, lru);
15318334b962SMinchan Kim 		map = kmap_atomic(page);
15328334b962SMinchan Kim 		tmp_count = map[offset];
15338334b962SMinchan Kim 		kunmap_atomic(map);
15348334b962SMinchan Kim 
15358334b962SMinchan Kim 		count += (tmp_count & ~COUNT_CONTINUED) * n;
15368334b962SMinchan Kim 		n *= (SWAP_CONT_MAX + 1);
15378334b962SMinchan Kim 	} while (tmp_count & COUNT_CONTINUED);
15388334b962SMinchan Kim out:
1539235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
15408334b962SMinchan Kim 	return count;
15418334b962SMinchan Kim }
15428334b962SMinchan Kim 
1543e0709829SHuang Ying static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
1544e0709829SHuang Ying 					 swp_entry_t entry)
1545e0709829SHuang Ying {
1546e0709829SHuang Ying 	struct swap_cluster_info *ci;
1547e0709829SHuang Ying 	unsigned char *map = si->swap_map;
1548e0709829SHuang Ying 	unsigned long roffset = swp_offset(entry);
1549e0709829SHuang Ying 	unsigned long offset = round_down(roffset, SWAPFILE_CLUSTER);
1550e0709829SHuang Ying 	int i;
1551e0709829SHuang Ying 	bool ret = false;
1552e0709829SHuang Ying 
1553e0709829SHuang Ying 	ci = lock_cluster_or_swap_info(si, offset);
1554e0709829SHuang Ying 	if (!ci || !cluster_is_huge(ci)) {
1555afa4711eSHuang Ying 		if (swap_count(map[roffset]))
1556e0709829SHuang Ying 			ret = true;
1557e0709829SHuang Ying 		goto unlock_out;
1558e0709829SHuang Ying 	}
1559e0709829SHuang Ying 	for (i = 0; i < SWAPFILE_CLUSTER; i++) {
1560afa4711eSHuang Ying 		if (swap_count(map[offset + i])) {
1561e0709829SHuang Ying 			ret = true;
1562e0709829SHuang Ying 			break;
1563e0709829SHuang Ying 		}
1564e0709829SHuang Ying 	}
1565e0709829SHuang Ying unlock_out:
1566e0709829SHuang Ying 	unlock_cluster_or_swap_info(si, ci);
1567e0709829SHuang Ying 	return ret;
1568e0709829SHuang Ying }
1569e0709829SHuang Ying 
1570e0709829SHuang Ying static bool page_swapped(struct page *page)
1571e0709829SHuang Ying {
1572e0709829SHuang Ying 	swp_entry_t entry;
1573e0709829SHuang Ying 	struct swap_info_struct *si;
1574e0709829SHuang Ying 
1575fe5266d5SHuang Ying 	if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!PageTransCompound(page)))
1576e0709829SHuang Ying 		return page_swapcount(page) != 0;
1577e0709829SHuang Ying 
1578e0709829SHuang Ying 	page = compound_head(page);
1579e0709829SHuang Ying 	entry.val = page_private(page);
1580e0709829SHuang Ying 	si = _swap_info_get(entry);
1581e0709829SHuang Ying 	if (si)
1582e0709829SHuang Ying 		return swap_page_trans_huge_swapped(si, entry);
1583e0709829SHuang Ying 	return false;
1584e0709829SHuang Ying }
1585ba3c4ce6SHuang Ying 
15861da177e4SLinus Torvalds /*
1587a2c43eedSHugh Dickins  * If swap is getting full, or if there are no more mappings of this page,
1588a2c43eedSHugh Dickins  * then try_to_free_swap is called to free its swap space.
15891da177e4SLinus Torvalds  */
1590a2c43eedSHugh Dickins int try_to_free_swap(struct page *page)
15911da177e4SLinus Torvalds {
1592309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
15931da177e4SLinus Torvalds 
15941da177e4SLinus Torvalds 	if (!PageSwapCache(page))
15951da177e4SLinus Torvalds 		return 0;
15961da177e4SLinus Torvalds 	if (PageWriteback(page))
15971da177e4SLinus Torvalds 		return 0;
1598e0709829SHuang Ying 	if (page_swapped(page))
15991da177e4SLinus Torvalds 		return 0;
16001da177e4SLinus Torvalds 
1601b73d7fceSHugh Dickins 	/*
1602b73d7fceSHugh Dickins 	 * Once hibernation has begun to create its image of memory,
1603b73d7fceSHugh Dickins 	 * there's a danger that one of the calls to try_to_free_swap()
1604b73d7fceSHugh Dickins 	 * - most probably a call from __try_to_reclaim_swap() while
1605b73d7fceSHugh Dickins 	 * hibernation is allocating its own swap pages for the image,
1606b73d7fceSHugh Dickins 	 * but conceivably even a call from memory reclaim - will free
1607b73d7fceSHugh Dickins 	 * the swap from a page which has already been recorded in the
1608b73d7fceSHugh Dickins 	 * image as a clean swapcache page, and then reuse its swap for
1609b73d7fceSHugh Dickins 	 * another page of the image.  On waking from hibernation, the
1610b73d7fceSHugh Dickins 	 * original page might be freed under memory pressure, then
1611b73d7fceSHugh Dickins 	 * later read back in from swap, now with the wrong data.
1612b73d7fceSHugh Dickins 	 *
16132de1a7e4SSeth Jennings 	 * Hibernation suspends storage while it is writing the image
1614f90ac398SMel Gorman 	 * to disk so check that here.
1615b73d7fceSHugh Dickins 	 */
1616f90ac398SMel Gorman 	if (pm_suspended_storage())
1617b73d7fceSHugh Dickins 		return 0;
1618b73d7fceSHugh Dickins 
1619e0709829SHuang Ying 	page = compound_head(page);
1620a2c43eedSHugh Dickins 	delete_from_swap_cache(page);
16211da177e4SLinus Torvalds 	SetPageDirty(page);
1622a2c43eedSHugh Dickins 	return 1;
162368a22394SRik van Riel }
162468a22394SRik van Riel 
162568a22394SRik van Riel /*
16261da177e4SLinus Torvalds  * Free the swap entry like above, but also try to
16271da177e4SLinus Torvalds  * free the page cache entry if it is the last user.
16281da177e4SLinus Torvalds  */
16292509ef26SHugh Dickins int free_swap_and_cache(swp_entry_t entry)
16301da177e4SLinus Torvalds {
16311da177e4SLinus Torvalds 	struct swap_info_struct *p;
16327c00bafeSTim Chen 	unsigned char count;
16331da177e4SLinus Torvalds 
1634a7420aa5SAndi Kleen 	if (non_swap_entry(entry))
16352509ef26SHugh Dickins 		return 1;
16360697212aSChristoph Lameter 
16377c00bafeSTim Chen 	p = _swap_info_get(entry);
16381da177e4SLinus Torvalds 	if (p) {
163933e16272SWei Yang 		count = __swap_entry_free(p, entry);
1640e0709829SHuang Ying 		if (count == SWAP_HAS_CACHE &&
1641bcd49e86SHuang Ying 		    !swap_page_trans_huge_swapped(p, entry))
1642bcd49e86SHuang Ying 			__try_to_reclaim_swap(p, swp_offset(entry),
1643bcd49e86SHuang Ying 					      TTRS_UNMAPPED | TTRS_FULL);
16441da177e4SLinus Torvalds 	}
16452509ef26SHugh Dickins 	return p != NULL;
16461da177e4SLinus Torvalds }
16471da177e4SLinus Torvalds 
1648b0cb1a19SRafael J. Wysocki #ifdef CONFIG_HIBERNATION
1649bb243f7dSMiaohe Lin 
1650bb243f7dSMiaohe Lin swp_entry_t get_swap_page_of_type(int type)
1651bb243f7dSMiaohe Lin {
1652bb243f7dSMiaohe Lin 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1653bb243f7dSMiaohe Lin 	swp_entry_t entry = {0};
1654bb243f7dSMiaohe Lin 
1655bb243f7dSMiaohe Lin 	if (!si)
1656bb243f7dSMiaohe Lin 		goto fail;
1657bb243f7dSMiaohe Lin 
1658bb243f7dSMiaohe Lin 	/* This is called for allocating swap entry, not cache */
1659bb243f7dSMiaohe Lin 	spin_lock(&si->lock);
1660bb243f7dSMiaohe Lin 	if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry))
1661bb243f7dSMiaohe Lin 		atomic_long_dec(&nr_swap_pages);
1662bb243f7dSMiaohe Lin 	spin_unlock(&si->lock);
1663bb243f7dSMiaohe Lin fail:
1664bb243f7dSMiaohe Lin 	return entry;
1665bb243f7dSMiaohe Lin }
1666bb243f7dSMiaohe Lin 
1667f577eb30SRafael J. Wysocki /*
1668915bae9eSRafael J. Wysocki  * Find the swap type that corresponds to given device (if any).
1669f577eb30SRafael J. Wysocki  *
1670915bae9eSRafael J. Wysocki  * @offset - number of the PAGE_SIZE-sized block of the device, starting
1671915bae9eSRafael J. Wysocki  * from 0, in which the swap header is expected to be located.
1672915bae9eSRafael J. Wysocki  *
1673915bae9eSRafael J. Wysocki  * This is needed for the suspend to disk (aka swsusp).
1674f577eb30SRafael J. Wysocki  */
167521bd9005SChristoph Hellwig int swap_type_of(dev_t device, sector_t offset)
1676f577eb30SRafael J. Wysocki {
1677efa90a98SHugh Dickins 	int type;
1678f577eb30SRafael J. Wysocki 
167921bd9005SChristoph Hellwig 	if (!device)
168021bd9005SChristoph Hellwig 		return -1;
1681915bae9eSRafael J. Wysocki 
1682f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1683efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
1684efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1685f577eb30SRafael J. Wysocki 
1686915bae9eSRafael J. Wysocki 		if (!(sis->flags & SWP_WRITEOK))
1687f577eb30SRafael J. Wysocki 			continue;
1688b6b5bce3SRafael J. Wysocki 
168921bd9005SChristoph Hellwig 		if (device == sis->bdev->bd_dev) {
16904efaceb1SAaron Lu 			struct swap_extent *se = first_se(sis);
1691915bae9eSRafael J. Wysocki 
1692915bae9eSRafael J. Wysocki 			if (se->start_block == offset) {
1693f577eb30SRafael J. Wysocki 				spin_unlock(&swap_lock);
1694efa90a98SHugh Dickins 				return type;
1695f577eb30SRafael J. Wysocki 			}
1696f577eb30SRafael J. Wysocki 		}
1697915bae9eSRafael J. Wysocki 	}
1698f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
169921bd9005SChristoph Hellwig 	return -ENODEV;
170021bd9005SChristoph Hellwig }
1701915bae9eSRafael J. Wysocki 
170221bd9005SChristoph Hellwig int find_first_swap(dev_t *device)
170321bd9005SChristoph Hellwig {
170421bd9005SChristoph Hellwig 	int type;
170521bd9005SChristoph Hellwig 
170621bd9005SChristoph Hellwig 	spin_lock(&swap_lock);
170721bd9005SChristoph Hellwig 	for (type = 0; type < nr_swapfiles; type++) {
170821bd9005SChristoph Hellwig 		struct swap_info_struct *sis = swap_info[type];
170921bd9005SChristoph Hellwig 
171021bd9005SChristoph Hellwig 		if (!(sis->flags & SWP_WRITEOK))
171121bd9005SChristoph Hellwig 			continue;
171221bd9005SChristoph Hellwig 		*device = sis->bdev->bd_dev;
171321bd9005SChristoph Hellwig 		spin_unlock(&swap_lock);
171421bd9005SChristoph Hellwig 		return type;
171521bd9005SChristoph Hellwig 	}
171621bd9005SChristoph Hellwig 	spin_unlock(&swap_lock);
1717f577eb30SRafael J. Wysocki 	return -ENODEV;
1718f577eb30SRafael J. Wysocki }
1719f577eb30SRafael J. Wysocki 
1720f577eb30SRafael J. Wysocki /*
172173c34b6aSHugh Dickins  * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
172273c34b6aSHugh Dickins  * corresponding to given index in swap_info (swap type).
172373c34b6aSHugh Dickins  */
172473c34b6aSHugh Dickins sector_t swapdev_block(int type, pgoff_t offset)
172573c34b6aSHugh Dickins {
1726c10d38ccSDaniel Jordan 	struct swap_info_struct *si = swap_type_to_swap_info(type);
1727f885056aSChristoph Hellwig 	struct swap_extent *se;
172873c34b6aSHugh Dickins 
1729c10d38ccSDaniel Jordan 	if (!si || !(si->flags & SWP_WRITEOK))
173073c34b6aSHugh Dickins 		return 0;
1731f885056aSChristoph Hellwig 	se = offset_to_swap_extent(si, offset);
1732f885056aSChristoph Hellwig 	return se->start_block + (offset - se->start_page);
173373c34b6aSHugh Dickins }
173473c34b6aSHugh Dickins 
173573c34b6aSHugh Dickins /*
1736f577eb30SRafael J. Wysocki  * Return either the total number of swap pages of given type, or the number
1737f577eb30SRafael J. Wysocki  * of free pages of that type (depending on @free)
1738f577eb30SRafael J. Wysocki  *
1739f577eb30SRafael J. Wysocki  * This is needed for software suspend
1740f577eb30SRafael J. Wysocki  */
1741f577eb30SRafael J. Wysocki unsigned int count_swap_pages(int type, int free)
1742f577eb30SRafael J. Wysocki {
1743f577eb30SRafael J. Wysocki 	unsigned int n = 0;
1744f577eb30SRafael J. Wysocki 
1745f577eb30SRafael J. Wysocki 	spin_lock(&swap_lock);
1746efa90a98SHugh Dickins 	if ((unsigned int)type < nr_swapfiles) {
1747efa90a98SHugh Dickins 		struct swap_info_struct *sis = swap_info[type];
1748efa90a98SHugh Dickins 
1749ec8acf20SShaohua Li 		spin_lock(&sis->lock);
1750efa90a98SHugh Dickins 		if (sis->flags & SWP_WRITEOK) {
1751efa90a98SHugh Dickins 			n = sis->pages;
1752f577eb30SRafael J. Wysocki 			if (free)
1753efa90a98SHugh Dickins 				n -= sis->inuse_pages;
1754efa90a98SHugh Dickins 		}
1755ec8acf20SShaohua Li 		spin_unlock(&sis->lock);
1756f577eb30SRafael J. Wysocki 	}
1757f577eb30SRafael J. Wysocki 	spin_unlock(&swap_lock);
1758f577eb30SRafael J. Wysocki 	return n;
1759f577eb30SRafael J. Wysocki }
176073c34b6aSHugh Dickins #endif /* CONFIG_HIBERNATION */
1761f577eb30SRafael J. Wysocki 
17629f8bdb3fSHugh Dickins static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
1763179ef71cSCyrill Gorcunov {
1764099dd687SPeter Xu 	return pte_same(pte_swp_clear_flags(pte), swp_pte);
1765179ef71cSCyrill Gorcunov }
1766179ef71cSCyrill Gorcunov 
17671da177e4SLinus Torvalds /*
176872866f6fSHugh Dickins  * No need to decide whether this PTE shares the swap entry with others,
176972866f6fSHugh Dickins  * just let do_wp_page work it out if a write is requested later - to
177072866f6fSHugh Dickins  * force COW, vm_page_prot omits write permission from any private vma.
17711da177e4SLinus Torvalds  */
1772044d66c1SHugh Dickins static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
17731da177e4SLinus Torvalds 		unsigned long addr, swp_entry_t entry, struct page *page)
17741da177e4SLinus Torvalds {
17759e16b7fbSHugh Dickins 	struct page *swapcache;
1776044d66c1SHugh Dickins 	spinlock_t *ptl;
1777*14a762ddSMiaohe Lin 	pte_t *pte, new_pte;
1778044d66c1SHugh Dickins 	int ret = 1;
1779044d66c1SHugh Dickins 
17809e16b7fbSHugh Dickins 	swapcache = page;
17819e16b7fbSHugh Dickins 	page = ksm_might_need_to_copy(page, vma, addr);
17829e16b7fbSHugh Dickins 	if (unlikely(!page))
17839e16b7fbSHugh Dickins 		return -ENOMEM;
17849e16b7fbSHugh Dickins 
1785044d66c1SHugh Dickins 	pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
17869f8bdb3fSHugh Dickins 	if (unlikely(!pte_same_as_swp(*pte, swp_entry_to_pte(entry)))) {
1787044d66c1SHugh Dickins 		ret = 0;
1788044d66c1SHugh Dickins 		goto out;
1789044d66c1SHugh Dickins 	}
17908a9f3ccdSBalbir Singh 
17919f186f9eSMiaohe Lin 	if (unlikely(!PageUptodate(page))) {
17929f186f9eSMiaohe Lin 		pte_t pteval;
17939f186f9eSMiaohe Lin 
17949f186f9eSMiaohe Lin 		dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
17959f186f9eSMiaohe Lin 		pteval = swp_entry_to_pte(make_swapin_error_entry(page));
17969f186f9eSMiaohe Lin 		set_pte_at(vma->vm_mm, addr, pte, pteval);
17979f186f9eSMiaohe Lin 		swap_free(entry);
17989f186f9eSMiaohe Lin 		ret = 0;
17999f186f9eSMiaohe Lin 		goto out;
18009f186f9eSMiaohe Lin 	}
18019f186f9eSMiaohe Lin 
180278fbe906SDavid Hildenbrand 	/* See do_swap_page() */
180378fbe906SDavid Hildenbrand 	BUG_ON(!PageAnon(page) && PageMappedToDisk(page));
180478fbe906SDavid Hildenbrand 	BUG_ON(PageAnon(page) && PageAnonExclusive(page));
180578fbe906SDavid Hildenbrand 
1806b084d435SKAMEZAWA Hiroyuki 	dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
1807d559db08SKAMEZAWA Hiroyuki 	inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
18081da177e4SLinus Torvalds 	get_page(page);
180900501b53SJohannes Weiner 	if (page == swapcache) {
18101493a191SDavid Hildenbrand 		rmap_t rmap_flags = RMAP_NONE;
18111493a191SDavid Hildenbrand 
18121493a191SDavid Hildenbrand 		/*
18131493a191SDavid Hildenbrand 		 * See do_swap_page(): PageWriteback() would be problematic.
18141493a191SDavid Hildenbrand 		 * However, we do a wait_on_page_writeback() just before this
18151493a191SDavid Hildenbrand 		 * call and have the page locked.
18161493a191SDavid Hildenbrand 		 */
18171493a191SDavid Hildenbrand 		VM_BUG_ON_PAGE(PageWriteback(page), page);
18181493a191SDavid Hildenbrand 		if (pte_swp_exclusive(*pte))
18191493a191SDavid Hildenbrand 			rmap_flags |= RMAP_EXCLUSIVE;
18201493a191SDavid Hildenbrand 
18211493a191SDavid Hildenbrand 		page_add_anon_rmap(page, vma, addr, rmap_flags);
182200501b53SJohannes Weiner 	} else { /* ksm created a completely new copy */
182340f2bbf7SDavid Hildenbrand 		page_add_new_anon_rmap(page, vma, addr);
1824b518154eSJoonsoo Kim 		lru_cache_add_inactive_or_unevictable(page, vma);
182500501b53SJohannes Weiner 	}
1826*14a762ddSMiaohe Lin 	new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
1827*14a762ddSMiaohe Lin 	if (pte_swp_soft_dirty(*pte))
1828*14a762ddSMiaohe Lin 		new_pte = pte_mksoft_dirty(new_pte);
1829*14a762ddSMiaohe Lin 	if (pte_swp_uffd_wp(*pte))
1830*14a762ddSMiaohe Lin 		new_pte = pte_mkuffd_wp(new_pte);
1831*14a762ddSMiaohe Lin 	set_pte_at(vma->vm_mm, addr, pte, new_pte);
18321da177e4SLinus Torvalds 	swap_free(entry);
1833044d66c1SHugh Dickins out:
1834044d66c1SHugh Dickins 	pte_unmap_unlock(pte, ptl);
18359e16b7fbSHugh Dickins 	if (page != swapcache) {
18369e16b7fbSHugh Dickins 		unlock_page(page);
18379e16b7fbSHugh Dickins 		put_page(page);
18389e16b7fbSHugh Dickins 	}
1839044d66c1SHugh Dickins 	return ret;
18401da177e4SLinus Torvalds }
18411da177e4SLinus Torvalds 
18421da177e4SLinus Torvalds static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
18431da177e4SLinus Torvalds 			unsigned long addr, unsigned long end,
184410a9c496SChristoph Hellwig 			unsigned int type)
18451da177e4SLinus Torvalds {
1846b56a2d8aSVineeth Remanan Pillai 	struct page *page;
1847b56a2d8aSVineeth Remanan Pillai 	swp_entry_t entry;
1848705e87c0SHugh Dickins 	pte_t *pte;
1849b56a2d8aSVineeth Remanan Pillai 	struct swap_info_struct *si;
1850b56a2d8aSVineeth Remanan Pillai 	unsigned long offset;
18518a9f3ccdSBalbir Singh 	int ret = 0;
1852b56a2d8aSVineeth Remanan Pillai 	volatile unsigned char *swap_map;
18531da177e4SLinus Torvalds 
1854b56a2d8aSVineeth Remanan Pillai 	si = swap_info[type];
1855044d66c1SHugh Dickins 	pte = pte_offset_map(pmd, addr);
18561da177e4SLinus Torvalds 	do {
1857b56a2d8aSVineeth Remanan Pillai 		if (!is_swap_pte(*pte))
1858b56a2d8aSVineeth Remanan Pillai 			continue;
1859b56a2d8aSVineeth Remanan Pillai 
1860b56a2d8aSVineeth Remanan Pillai 		entry = pte_to_swp_entry(*pte);
1861b56a2d8aSVineeth Remanan Pillai 		if (swp_type(entry) != type)
1862b56a2d8aSVineeth Remanan Pillai 			continue;
1863b56a2d8aSVineeth Remanan Pillai 
1864b56a2d8aSVineeth Remanan Pillai 		offset = swp_offset(entry);
1865044d66c1SHugh Dickins 		pte_unmap(pte);
1866b56a2d8aSVineeth Remanan Pillai 		swap_map = &si->swap_map[offset];
1867ebc5951eSAndrea Righi 		page = lookup_swap_cache(entry, vma, addr);
1868ebc5951eSAndrea Righi 		if (!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);
1878ebc5951eSAndrea Righi 		}
1879b56a2d8aSVineeth Remanan Pillai 		if (!page) {
1880b56a2d8aSVineeth Remanan Pillai 			if (*swap_map == 0 || *swap_map == SWAP_MAP_BAD)
1881b56a2d8aSVineeth Remanan Pillai 				goto try_next;
1882b56a2d8aSVineeth Remanan Pillai 			return -ENOMEM;
18831da177e4SLinus Torvalds 		}
1884b56a2d8aSVineeth Remanan Pillai 
1885b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
1886b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
1887b56a2d8aSVineeth Remanan Pillai 		ret = unuse_pte(vma, pmd, addr, entry, page);
1888b56a2d8aSVineeth Remanan Pillai 		if (ret < 0) {
1889b56a2d8aSVineeth Remanan Pillai 			unlock_page(page);
1890b56a2d8aSVineeth Remanan Pillai 			put_page(page);
1891b56a2d8aSVineeth Remanan Pillai 			goto out;
1892b56a2d8aSVineeth Remanan Pillai 		}
1893b56a2d8aSVineeth Remanan Pillai 
1894b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
1895b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
1896b56a2d8aSVineeth Remanan Pillai 		put_page(page);
1897b56a2d8aSVineeth Remanan Pillai try_next:
1898b56a2d8aSVineeth Remanan Pillai 		pte = pte_offset_map(pmd, addr);
18991da177e4SLinus Torvalds 	} while (pte++, addr += PAGE_SIZE, addr != end);
1900044d66c1SHugh Dickins 	pte_unmap(pte - 1);
1901b56a2d8aSVineeth Remanan Pillai 
1902b56a2d8aSVineeth Remanan Pillai 	ret = 0;
1903044d66c1SHugh Dickins out:
19048a9f3ccdSBalbir Singh 	return ret;
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);
19191a5a9906SAndrea Arcangeli 		if (pmd_none_or_trans_huge_or_clear_bad(pmd))
19201da177e4SLinus Torvalds 			continue;
192110a9c496SChristoph Hellwig 		ret = unuse_pte_range(vma, pmd, addr, next, type);
19228a9f3ccdSBalbir Singh 		if (ret)
19238a9f3ccdSBalbir Singh 			return ret;
19241da177e4SLinus Torvalds 	} while (pmd++, addr = next, addr != end);
19251da177e4SLinus Torvalds 	return 0;
19261da177e4SLinus Torvalds }
19271da177e4SLinus Torvalds 
1928c2febafcSKirill A. Shutemov static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
19291da177e4SLinus Torvalds 				unsigned long addr, unsigned long end,
193010a9c496SChristoph Hellwig 				unsigned int type)
19311da177e4SLinus Torvalds {
19321da177e4SLinus Torvalds 	pud_t *pud;
19331da177e4SLinus Torvalds 	unsigned long next;
19348a9f3ccdSBalbir Singh 	int ret;
19351da177e4SLinus Torvalds 
1936c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
19371da177e4SLinus Torvalds 	do {
19381da177e4SLinus Torvalds 		next = pud_addr_end(addr, end);
19391da177e4SLinus Torvalds 		if (pud_none_or_clear_bad(pud))
19401da177e4SLinus Torvalds 			continue;
194110a9c496SChristoph Hellwig 		ret = unuse_pmd_range(vma, pud, addr, next, type);
19428a9f3ccdSBalbir Singh 		if (ret)
19438a9f3ccdSBalbir Singh 			return ret;
19441da177e4SLinus Torvalds 	} while (pud++, addr = next, addr != end);
19451da177e4SLinus Torvalds 	return 0;
19461da177e4SLinus Torvalds }
19471da177e4SLinus Torvalds 
1948c2febafcSKirill A. Shutemov static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
1949c2febafcSKirill A. Shutemov 				unsigned long addr, unsigned long end,
195010a9c496SChristoph Hellwig 				unsigned int type)
1951c2febafcSKirill A. Shutemov {
1952c2febafcSKirill A. Shutemov 	p4d_t *p4d;
1953c2febafcSKirill A. Shutemov 	unsigned long next;
1954c2febafcSKirill A. Shutemov 	int ret;
1955c2febafcSKirill A. Shutemov 
1956c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
1957c2febafcSKirill A. Shutemov 	do {
1958c2febafcSKirill A. Shutemov 		next = p4d_addr_end(addr, end);
1959c2febafcSKirill A. Shutemov 		if (p4d_none_or_clear_bad(p4d))
1960c2febafcSKirill A. Shutemov 			continue;
196110a9c496SChristoph Hellwig 		ret = unuse_pud_range(vma, p4d, addr, next, type);
1962c2febafcSKirill A. Shutemov 		if (ret)
1963c2febafcSKirill A. Shutemov 			return ret;
1964c2febafcSKirill A. Shutemov 	} while (p4d++, addr = next, addr != end);
1965c2febafcSKirill A. Shutemov 	return 0;
1966c2febafcSKirill A. Shutemov }
1967c2febafcSKirill A. Shutemov 
196810a9c496SChristoph Hellwig static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
19691da177e4SLinus Torvalds {
19701da177e4SLinus Torvalds 	pgd_t *pgd;
19711da177e4SLinus Torvalds 	unsigned long addr, end, next;
19728a9f3ccdSBalbir Singh 	int ret;
19731da177e4SLinus Torvalds 
19741da177e4SLinus Torvalds 	addr = vma->vm_start;
19751da177e4SLinus Torvalds 	end = vma->vm_end;
19761da177e4SLinus Torvalds 
19771da177e4SLinus Torvalds 	pgd = pgd_offset(vma->vm_mm, addr);
19781da177e4SLinus Torvalds 	do {
19791da177e4SLinus Torvalds 		next = pgd_addr_end(addr, end);
19801da177e4SLinus Torvalds 		if (pgd_none_or_clear_bad(pgd))
19811da177e4SLinus Torvalds 			continue;
198210a9c496SChristoph Hellwig 		ret = unuse_p4d_range(vma, pgd, addr, next, type);
19838a9f3ccdSBalbir Singh 		if (ret)
19848a9f3ccdSBalbir Singh 			return ret;
19851da177e4SLinus Torvalds 	} while (pgd++, addr = next, addr != end);
19861da177e4SLinus Torvalds 	return 0;
19871da177e4SLinus Torvalds }
19881da177e4SLinus Torvalds 
198910a9c496SChristoph Hellwig static int unuse_mm(struct mm_struct *mm, unsigned int type)
19901da177e4SLinus Torvalds {
19911da177e4SLinus Torvalds 	struct vm_area_struct *vma;
19928a9f3ccdSBalbir Singh 	int ret = 0;
19931da177e4SLinus Torvalds 
1994d8ed45c5SMichel Lespinasse 	mmap_read_lock(mm);
19951da177e4SLinus Torvalds 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
1996b56a2d8aSVineeth Remanan Pillai 		if (vma->anon_vma) {
199710a9c496SChristoph Hellwig 			ret = unuse_vma(vma, type);
1998b56a2d8aSVineeth Remanan Pillai 			if (ret)
19991da177e4SLinus Torvalds 				break;
2000b56a2d8aSVineeth Remanan Pillai 		}
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];
20451da177e4SLinus Torvalds 	struct page *page;
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);
2095b56a2d8aSVineeth Remanan Pillai 		page = find_get_page(swap_address_space(entry), i);
2096b56a2d8aSVineeth Remanan Pillai 		if (!page)
2097b56a2d8aSVineeth Remanan Pillai 			continue;
2098b56a2d8aSVineeth Remanan Pillai 
2099b56a2d8aSVineeth Remanan Pillai 		/*
2100b56a2d8aSVineeth Remanan Pillai 		 * It is conceivable that a racing task removed this page from
2101b56a2d8aSVineeth Remanan Pillai 		 * swap cache just before we acquired the page lock. The page
2102b56a2d8aSVineeth Remanan Pillai 		 * might even be back in swap cache on another swap area. But
2103b56a2d8aSVineeth Remanan Pillai 		 * that is okay, try_to_free_swap() only removes stale pages.
2104b56a2d8aSVineeth Remanan Pillai 		 */
2105b56a2d8aSVineeth Remanan Pillai 		lock_page(page);
2106b56a2d8aSVineeth Remanan Pillai 		wait_on_page_writeback(page);
2107b56a2d8aSVineeth Remanan Pillai 		try_to_free_swap(page);
2108b56a2d8aSVineeth Remanan Pillai 		unlock_page(page);
2109b56a2d8aSVineeth Remanan Pillai 		put_page(page);
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;
2273e1209d3aSNeilBrown 		}
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);
2339a2468cc9SAaron Lu 	add_to_avail_list(p);
2340cf0cac0aSCesar Eduardo Barros }
2341cf0cac0aSCesar Eduardo Barros 
2342cf0cac0aSCesar Eduardo Barros static void enable_swap_info(struct swap_info_struct *p, int prio,
2343cf0cac0aSCesar Eduardo Barros 				unsigned char *swap_map,
23442a8f9449SShaohua Li 				struct swap_cluster_info *cluster_info,
2345cf0cac0aSCesar Eduardo Barros 				unsigned long *frontswap_map)
2346cf0cac0aSCesar Eduardo Barros {
23471cf53c89SChristoph Hellwig 	if (IS_ENABLED(CONFIG_FRONTSWAP))
23484f89849dSMinchan Kim 		frontswap_init(p->type, frontswap_map);
2349cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2350ec8acf20SShaohua Li 	spin_lock(&p->lock);
2351eb085574SHuang Ying 	setup_swap_info(p, prio, swap_map, cluster_info);
2352eb085574SHuang Ying 	spin_unlock(&p->lock);
2353eb085574SHuang Ying 	spin_unlock(&swap_lock);
2354eb085574SHuang Ying 	/*
235563d8620eSMiaohe Lin 	 * Finished initializing swap device, now it's safe to reference it.
2356eb085574SHuang Ying 	 */
235763d8620eSMiaohe Lin 	percpu_ref_resurrect(&p->users);
2358eb085574SHuang Ying 	spin_lock(&swap_lock);
2359eb085574SHuang Ying 	spin_lock(&p->lock);
2360eb085574SHuang Ying 	_enable_swap_info(p);
2361ec8acf20SShaohua Li 	spin_unlock(&p->lock);
2362cf0cac0aSCesar Eduardo Barros 	spin_unlock(&swap_lock);
2363cf0cac0aSCesar Eduardo Barros }
2364cf0cac0aSCesar Eduardo Barros 
2365cf0cac0aSCesar Eduardo Barros static void reinsert_swap_info(struct swap_info_struct *p)
2366cf0cac0aSCesar Eduardo Barros {
2367cf0cac0aSCesar Eduardo Barros 	spin_lock(&swap_lock);
2368ec8acf20SShaohua Li 	spin_lock(&p->lock);
2369eb085574SHuang Ying 	setup_swap_info(p, p->prio, p->swap_map, p->cluster_info);
2370eb085574SHuang Ying 	_enable_swap_info(p);
2371ec8acf20SShaohua Li 	spin_unlock(&p->lock);
237240531542SCesar Eduardo Barros 	spin_unlock(&swap_lock);
237340531542SCesar Eduardo Barros }
237440531542SCesar Eduardo Barros 
237567afa38eSTim Chen bool has_usable_swap(void)
237667afa38eSTim Chen {
237767afa38eSTim Chen 	bool ret = true;
237867afa38eSTim Chen 
237967afa38eSTim Chen 	spin_lock(&swap_lock);
238067afa38eSTim Chen 	if (plist_head_empty(&swap_active_head))
238167afa38eSTim Chen 		ret = false;
238267afa38eSTim Chen 	spin_unlock(&swap_lock);
238367afa38eSTim Chen 	return ret;
238467afa38eSTim Chen }
238567afa38eSTim Chen 
2386c4ea37c2SHeiko Carstens SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
23871da177e4SLinus Torvalds {
23881da177e4SLinus Torvalds 	struct swap_info_struct *p = NULL;
23898d69aaeeSHugh Dickins 	unsigned char *swap_map;
23902a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info;
23914f89849dSMinchan Kim 	unsigned long *frontswap_map;
23921da177e4SLinus Torvalds 	struct file *swap_file, *victim;
23931da177e4SLinus Torvalds 	struct address_space *mapping;
23941da177e4SLinus Torvalds 	struct inode *inode;
239591a27b2aSJeff Layton 	struct filename *pathname;
2396adfab836SDan Streetman 	int err, found = 0;
23975b808a23SKrzysztof Kozlowski 	unsigned int old_block_size;
23981da177e4SLinus Torvalds 
23991da177e4SLinus Torvalds 	if (!capable(CAP_SYS_ADMIN))
24001da177e4SLinus Torvalds 		return -EPERM;
24011da177e4SLinus Torvalds 
2402191c5424SAl Viro 	BUG_ON(!current->mm);
2403191c5424SAl Viro 
24041da177e4SLinus Torvalds 	pathname = getname(specialfile);
24051da177e4SLinus Torvalds 	if (IS_ERR(pathname))
2406f58b59c1SXiaotian Feng 		return PTR_ERR(pathname);
24071da177e4SLinus Torvalds 
2408669abf4eSJeff Layton 	victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
24091da177e4SLinus Torvalds 	err = PTR_ERR(victim);
24101da177e4SLinus Torvalds 	if (IS_ERR(victim))
24111da177e4SLinus Torvalds 		goto out;
24121da177e4SLinus Torvalds 
24131da177e4SLinus Torvalds 	mapping = victim->f_mapping;
24145d337b91SHugh Dickins 	spin_lock(&swap_lock);
241518ab4d4cSDan Streetman 	plist_for_each_entry(p, &swap_active_head, list) {
241622c6f8fdSHugh Dickins 		if (p->flags & SWP_WRITEOK) {
2417adfab836SDan Streetman 			if (p->swap_file->f_mapping == mapping) {
2418adfab836SDan Streetman 				found = 1;
24191da177e4SLinus Torvalds 				break;
24201da177e4SLinus Torvalds 			}
24211da177e4SLinus Torvalds 		}
2422adfab836SDan Streetman 	}
2423adfab836SDan Streetman 	if (!found) {
24241da177e4SLinus Torvalds 		err = -EINVAL;
24255d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24261da177e4SLinus Torvalds 		goto out_dput;
24271da177e4SLinus Torvalds 	}
2428191c5424SAl Viro 	if (!security_vm_enough_memory_mm(current->mm, p->pages))
24291da177e4SLinus Torvalds 		vm_unacct_memory(p->pages);
24301da177e4SLinus Torvalds 	else {
24311da177e4SLinus Torvalds 		err = -ENOMEM;
24325d337b91SHugh Dickins 		spin_unlock(&swap_lock);
24331da177e4SLinus Torvalds 		goto out_dput;
24341da177e4SLinus Torvalds 	}
2435a2468cc9SAaron Lu 	del_from_avail_list(p);
2436ec8acf20SShaohua Li 	spin_lock(&p->lock);
243778ecba08SHugh Dickins 	if (p->prio < 0) {
2438adfab836SDan Streetman 		struct swap_info_struct *si = p;
2439a2468cc9SAaron Lu 		int nid;
2440adfab836SDan Streetman 
244118ab4d4cSDan Streetman 		plist_for_each_entry_continue(si, &swap_active_head, list) {
2442adfab836SDan Streetman 			si->prio++;
244318ab4d4cSDan Streetman 			si->list.prio--;
2444a2468cc9SAaron Lu 			for_each_node(nid) {
2445a2468cc9SAaron Lu 				if (si->avail_lists[nid].prio != 1)
2446a2468cc9SAaron Lu 					si->avail_lists[nid].prio--;
2447a2468cc9SAaron Lu 			}
2448adfab836SDan Streetman 		}
244978ecba08SHugh Dickins 		least_priority++;
245078ecba08SHugh Dickins 	}
245118ab4d4cSDan Streetman 	plist_del(&p->list, &swap_active_head);
2452ec8acf20SShaohua Li 	atomic_long_sub(p->pages, &nr_swap_pages);
24531da177e4SLinus Torvalds 	total_swap_pages -= p->pages;
24541da177e4SLinus Torvalds 	p->flags &= ~SWP_WRITEOK;
2455ec8acf20SShaohua Li 	spin_unlock(&p->lock);
24565d337b91SHugh Dickins 	spin_unlock(&swap_lock);
2457fb4f88dcSHugh Dickins 
2458039939a6STim Chen 	disable_swap_slots_cache_lock();
2459039939a6STim Chen 
2460e1e12d2fSDavid Rientjes 	set_current_oom_origin();
246110a9c496SChristoph Hellwig 	err = try_to_unuse(p->type);
2462e1e12d2fSDavid Rientjes 	clear_current_oom_origin();
24631da177e4SLinus Torvalds 
24641da177e4SLinus Torvalds 	if (err) {
24651da177e4SLinus Torvalds 		/* re-insert swap space back into swap_list */
2466cf0cac0aSCesar Eduardo Barros 		reinsert_swap_info(p);
2467039939a6STim Chen 		reenable_swap_slots_cache_unlock();
24681da177e4SLinus Torvalds 		goto out_dput;
24691da177e4SLinus Torvalds 	}
247052b7efdbSHugh Dickins 
2471039939a6STim Chen 	reenable_swap_slots_cache_unlock();
2472039939a6STim Chen 
2473eb085574SHuang Ying 	/*
247463d8620eSMiaohe Lin 	 * Wait for swap operations protected by get/put_swap_device()
247563d8620eSMiaohe Lin 	 * to complete.
247663d8620eSMiaohe Lin 	 *
247763d8620eSMiaohe Lin 	 * We need synchronize_rcu() here to protect the accessing to
247863d8620eSMiaohe Lin 	 * the swap cache data structure.
2479eb085574SHuang Ying 	 */
248063d8620eSMiaohe Lin 	percpu_ref_kill(&p->users);
2481eb085574SHuang Ying 	synchronize_rcu();
248263d8620eSMiaohe Lin 	wait_for_completion(&p->comp);
2483eb085574SHuang Ying 
2484815c2c54SShaohua Li 	flush_work(&p->discard_work);
2485815c2c54SShaohua Li 
24864cd3bb10SHugh Dickins 	destroy_swap_extents(p);
2487570a335bSHugh Dickins 	if (p->flags & SWP_CONTINUED)
2488570a335bSHugh Dickins 		free_swap_count_continuations(p);
2489570a335bSHugh Dickins 
249081a0298bSHuang Ying 	if (!p->bdev || !blk_queue_nonrot(bdev_get_queue(p->bdev)))
249181a0298bSHuang Ying 		atomic_dec(&nr_rotate_swap);
249281a0298bSHuang Ying 
2493fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
24945d337b91SHugh Dickins 	spin_lock(&swap_lock);
2495ec8acf20SShaohua Li 	spin_lock(&p->lock);
24961da177e4SLinus Torvalds 	drain_mmlist();
24975d337b91SHugh Dickins 
2498bb243f7dSMiaohe Lin 	/* wait for anyone still in scan_swap_map_slots */
24995d337b91SHugh Dickins 	p->highest_bit = 0;		/* cuts scans short */
25005d337b91SHugh Dickins 	while (p->flags >= SWP_SCANNING) {
2501ec8acf20SShaohua Li 		spin_unlock(&p->lock);
25025d337b91SHugh Dickins 		spin_unlock(&swap_lock);
250313e4b57fSNishanth Aravamudan 		schedule_timeout_uninterruptible(1);
25045d337b91SHugh Dickins 		spin_lock(&swap_lock);
2505ec8acf20SShaohua Li 		spin_lock(&p->lock);
25065d337b91SHugh Dickins 	}
25075d337b91SHugh Dickins 
25081da177e4SLinus Torvalds 	swap_file = p->swap_file;
25095b808a23SKrzysztof Kozlowski 	old_block_size = p->old_block_size;
25101da177e4SLinus Torvalds 	p->swap_file = NULL;
25111da177e4SLinus Torvalds 	p->max = 0;
25121da177e4SLinus Torvalds 	swap_map = p->swap_map;
25131da177e4SLinus Torvalds 	p->swap_map = NULL;
25142a8f9449SShaohua Li 	cluster_info = p->cluster_info;
25152a8f9449SShaohua Li 	p->cluster_info = NULL;
25164f89849dSMinchan Kim 	frontswap_map = frontswap_map_get(p);
2517ec8acf20SShaohua Li 	spin_unlock(&p->lock);
25185d337b91SHugh Dickins 	spin_unlock(&swap_lock);
25198a84802eSSteven Price 	arch_swap_invalidate_area(p->type);
2520adfab836SDan Streetman 	frontswap_invalidate_area(p->type);
252158e97ba6SKrzysztof Kozlowski 	frontswap_map_set(p, NULL);
2522fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
2523ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
2524ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
252549070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
252649070588SHuang Ying 	p->cluster_next_cpu = NULL;
25271da177e4SLinus Torvalds 	vfree(swap_map);
252854f180d3SHuang Ying 	kvfree(cluster_info);
252954f180d3SHuang Ying 	kvfree(frontswap_map);
25302de1a7e4SSeth Jennings 	/* Destroy swap account information */
2531adfab836SDan Streetman 	swap_cgroup_swapoff(p->type);
25324b3ef9daSHuang, Ying 	exit_swap_address_space(p->type);
253327a7faa0SKAMEZAWA Hiroyuki 
25341da177e4SLinus Torvalds 	inode = mapping->host;
25351da177e4SLinus Torvalds 	if (S_ISBLK(inode->i_mode)) {
25361da177e4SLinus Torvalds 		struct block_device *bdev = I_BDEV(inode);
25371638045cSDarrick J. Wong 
25385b808a23SKrzysztof Kozlowski 		set_blocksize(bdev, old_block_size);
2539e525fd89STejun Heo 		blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
25401638045cSDarrick J. Wong 	}
25411638045cSDarrick J. Wong 
25425955102cSAl Viro 	inode_lock(inode);
25431da177e4SLinus Torvalds 	inode->i_flags &= ~S_SWAPFILE;
25445955102cSAl Viro 	inode_unlock(inode);
25451da177e4SLinus Torvalds 	filp_close(swap_file, NULL);
2546f893ab41SWeijie Yang 
2547f893ab41SWeijie Yang 	/*
2548f893ab41SWeijie Yang 	 * Clear the SWP_USED flag after all resources are freed so that swapon
2549f893ab41SWeijie Yang 	 * can reuse this swap_info in alloc_swap_info() safely.  It is ok to
2550f893ab41SWeijie Yang 	 * not hold p->lock after we cleared its SWP_WRITEOK.
2551f893ab41SWeijie Yang 	 */
2552f893ab41SWeijie Yang 	spin_lock(&swap_lock);
2553f893ab41SWeijie Yang 	p->flags = 0;
2554f893ab41SWeijie Yang 	spin_unlock(&swap_lock);
2555f893ab41SWeijie Yang 
25561da177e4SLinus Torvalds 	err = 0;
255766d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
255866d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
25591da177e4SLinus Torvalds 
25601da177e4SLinus Torvalds out_dput:
25611da177e4SLinus Torvalds 	filp_close(victim, NULL);
25621da177e4SLinus Torvalds out:
2563f58b59c1SXiaotian Feng 	putname(pathname);
25641da177e4SLinus Torvalds 	return err;
25651da177e4SLinus Torvalds }
25661da177e4SLinus Torvalds 
25671da177e4SLinus Torvalds #ifdef CONFIG_PROC_FS
25689dd95748SAl Viro static __poll_t swaps_poll(struct file *file, poll_table *wait)
256966d7dd51SKay Sievers {
2570f1514638SKay Sievers 	struct seq_file *seq = file->private_data;
257166d7dd51SKay Sievers 
257266d7dd51SKay Sievers 	poll_wait(file, &proc_poll_wait, wait);
257366d7dd51SKay Sievers 
2574f1514638SKay Sievers 	if (seq->poll_event != atomic_read(&proc_poll_event)) {
2575f1514638SKay Sievers 		seq->poll_event = atomic_read(&proc_poll_event);
2576a9a08845SLinus Torvalds 		return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
257766d7dd51SKay Sievers 	}
257866d7dd51SKay Sievers 
2579a9a08845SLinus Torvalds 	return EPOLLIN | EPOLLRDNORM;
258066d7dd51SKay Sievers }
258166d7dd51SKay Sievers 
25821da177e4SLinus Torvalds /* iterator */
25831da177e4SLinus Torvalds static void *swap_start(struct seq_file *swap, loff_t *pos)
25841da177e4SLinus Torvalds {
2585efa90a98SHugh Dickins 	struct swap_info_struct *si;
2586efa90a98SHugh Dickins 	int type;
25871da177e4SLinus Torvalds 	loff_t l = *pos;
25881da177e4SLinus Torvalds 
2589fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
25901da177e4SLinus Torvalds 
2591881e4aabSSuleiman Souhlal 	if (!l)
2592881e4aabSSuleiman Souhlal 		return SEQ_START_TOKEN;
2593881e4aabSSuleiman Souhlal 
2594c10d38ccSDaniel Jordan 	for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
2595efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
25961da177e4SLinus Torvalds 			continue;
2597881e4aabSSuleiman Souhlal 		if (!--l)
2598efa90a98SHugh Dickins 			return si;
25991da177e4SLinus Torvalds 	}
26001da177e4SLinus Torvalds 
26011da177e4SLinus Torvalds 	return NULL;
26021da177e4SLinus Torvalds }
26031da177e4SLinus Torvalds 
26041da177e4SLinus Torvalds static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
26051da177e4SLinus Torvalds {
2606efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
2607efa90a98SHugh Dickins 	int type;
26081da177e4SLinus Torvalds 
2609881e4aabSSuleiman Souhlal 	if (v == SEQ_START_TOKEN)
2610efa90a98SHugh Dickins 		type = 0;
2611efa90a98SHugh Dickins 	else
2612efa90a98SHugh Dickins 		type = si->type + 1;
2613881e4aabSSuleiman Souhlal 
261410c8d69fSVasily Averin 	++(*pos);
2615c10d38ccSDaniel Jordan 	for (; (si = swap_type_to_swap_info(type)); type++) {
2616efa90a98SHugh Dickins 		if (!(si->flags & SWP_USED) || !si->swap_map)
26171da177e4SLinus Torvalds 			continue;
2618efa90a98SHugh Dickins 		return si;
26191da177e4SLinus Torvalds 	}
26201da177e4SLinus Torvalds 
26211da177e4SLinus Torvalds 	return NULL;
26221da177e4SLinus Torvalds }
26231da177e4SLinus Torvalds 
26241da177e4SLinus Torvalds static void swap_stop(struct seq_file *swap, void *v)
26251da177e4SLinus Torvalds {
2626fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
26271da177e4SLinus Torvalds }
26281da177e4SLinus Torvalds 
26291da177e4SLinus Torvalds static int swap_show(struct seq_file *swap, void *v)
26301da177e4SLinus Torvalds {
2631efa90a98SHugh Dickins 	struct swap_info_struct *si = v;
26321da177e4SLinus Torvalds 	struct file *file;
26331da177e4SLinus Torvalds 	int len;
2634642929a2SRafael Aquini 	unsigned long bytes, inuse;
26351da177e4SLinus Torvalds 
2636efa90a98SHugh Dickins 	if (si == SEQ_START_TOKEN) {
26376f793940SRandy Dunlap 		seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
2638881e4aabSSuleiman Souhlal 		return 0;
2639881e4aabSSuleiman Souhlal 	}
26401da177e4SLinus Torvalds 
26416f793940SRandy Dunlap 	bytes = si->pages << (PAGE_SHIFT - 10);
26426f793940SRandy Dunlap 	inuse = si->inuse_pages << (PAGE_SHIFT - 10);
26436f793940SRandy Dunlap 
2644efa90a98SHugh Dickins 	file = si->swap_file;
26452726d566SMiklos Szeredi 	len = seq_file_path(swap, file, " \t\n\\");
2646642929a2SRafael Aquini 	seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
26471da177e4SLinus Torvalds 			len < 40 ? 40 - len : 1, " ",
2648496ad9aaSAl Viro 			S_ISBLK(file_inode(file)->i_mode) ?
26491da177e4SLinus Torvalds 				"partition" : "file\t",
26506f793940SRandy Dunlap 			bytes, bytes < 10000000 ? "\t" : "",
26516f793940SRandy Dunlap 			inuse, inuse < 10000000 ? "\t" : "",
2652efa90a98SHugh Dickins 			si->prio);
26531da177e4SLinus Torvalds 	return 0;
26541da177e4SLinus Torvalds }
26551da177e4SLinus Torvalds 
265615ad7cdcSHelge Deller static const struct seq_operations swaps_op = {
26571da177e4SLinus Torvalds 	.start =	swap_start,
26581da177e4SLinus Torvalds 	.next =		swap_next,
26591da177e4SLinus Torvalds 	.stop =		swap_stop,
26601da177e4SLinus Torvalds 	.show =		swap_show
26611da177e4SLinus Torvalds };
26621da177e4SLinus Torvalds 
26631da177e4SLinus Torvalds static int swaps_open(struct inode *inode, struct file *file)
26641da177e4SLinus Torvalds {
2665f1514638SKay Sievers 	struct seq_file *seq;
266666d7dd51SKay Sievers 	int ret;
266766d7dd51SKay Sievers 
266866d7dd51SKay Sievers 	ret = seq_open(file, &swaps_op);
2669f1514638SKay Sievers 	if (ret)
267066d7dd51SKay Sievers 		return ret;
267166d7dd51SKay Sievers 
2672f1514638SKay Sievers 	seq = file->private_data;
2673f1514638SKay Sievers 	seq->poll_event = atomic_read(&proc_poll_event);
2674f1514638SKay Sievers 	return 0;
26751da177e4SLinus Torvalds }
26761da177e4SLinus Torvalds 
267797a32539SAlexey Dobriyan static const struct proc_ops swaps_proc_ops = {
2678d919b33dSAlexey Dobriyan 	.proc_flags	= PROC_ENTRY_PERMANENT,
267997a32539SAlexey Dobriyan 	.proc_open	= swaps_open,
268097a32539SAlexey Dobriyan 	.proc_read	= seq_read,
268197a32539SAlexey Dobriyan 	.proc_lseek	= seq_lseek,
268297a32539SAlexey Dobriyan 	.proc_release	= seq_release,
268397a32539SAlexey Dobriyan 	.proc_poll	= swaps_poll,
26841da177e4SLinus Torvalds };
26851da177e4SLinus Torvalds 
26861da177e4SLinus Torvalds static int __init procswaps_init(void)
26871da177e4SLinus Torvalds {
268897a32539SAlexey Dobriyan 	proc_create("swaps", 0, NULL, &swaps_proc_ops);
26891da177e4SLinus Torvalds 	return 0;
26901da177e4SLinus Torvalds }
26911da177e4SLinus Torvalds __initcall(procswaps_init);
26921da177e4SLinus Torvalds #endif /* CONFIG_PROC_FS */
26931da177e4SLinus Torvalds 
26941796316aSJan Beulich #ifdef MAX_SWAPFILES_CHECK
26951796316aSJan Beulich static int __init max_swapfiles_check(void)
26961796316aSJan Beulich {
26971796316aSJan Beulich 	MAX_SWAPFILES_CHECK();
26981796316aSJan Beulich 	return 0;
26991796316aSJan Beulich }
27001796316aSJan Beulich late_initcall(max_swapfiles_check);
27011796316aSJan Beulich #endif
27021796316aSJan Beulich 
270353cbb243SCesar Eduardo Barros static struct swap_info_struct *alloc_swap_info(void)
27041da177e4SLinus Torvalds {
27051da177e4SLinus Torvalds 	struct swap_info_struct *p;
2706b11a76b3SQian Cai 	struct swap_info_struct *defer = NULL;
27071da177e4SLinus Torvalds 	unsigned int type;
2708a2468cc9SAaron Lu 	int i;
2709efa90a98SHugh Dickins 
271096008744SGustavo A. R. Silva 	p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
2711efa90a98SHugh Dickins 	if (!p)
271253cbb243SCesar Eduardo Barros 		return ERR_PTR(-ENOMEM);
2713efa90a98SHugh Dickins 
271463d8620eSMiaohe Lin 	if (percpu_ref_init(&p->users, swap_users_ref_free,
271563d8620eSMiaohe Lin 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
271663d8620eSMiaohe Lin 		kvfree(p);
271763d8620eSMiaohe Lin 		return ERR_PTR(-ENOMEM);
271863d8620eSMiaohe Lin 	}
271963d8620eSMiaohe Lin 
27205d337b91SHugh Dickins 	spin_lock(&swap_lock);
2721efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
2722efa90a98SHugh Dickins 		if (!(swap_info[type]->flags & SWP_USED))
27231da177e4SLinus Torvalds 			break;
2724efa90a98SHugh Dickins 	}
27250697212aSChristoph Lameter 	if (type >= MAX_SWAPFILES) {
27265d337b91SHugh Dickins 		spin_unlock(&swap_lock);
272763d8620eSMiaohe Lin 		percpu_ref_exit(&p->users);
2728873d7bcfSVasily Averin 		kvfree(p);
2729730c0581SCesar Eduardo Barros 		return ERR_PTR(-EPERM);
27301da177e4SLinus Torvalds 	}
2731efa90a98SHugh Dickins 	if (type >= nr_swapfiles) {
2732efa90a98SHugh Dickins 		p->type = type;
2733efa90a98SHugh Dickins 		/*
2734a4b45114SHuang Ying 		 * Publish the swap_info_struct after initializing it.
2735a4b45114SHuang Ying 		 * Note that kvzalloc() above zeroes all its fields.
2736efa90a98SHugh Dickins 		 */
2737a4b45114SHuang Ying 		smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
2738a4b45114SHuang Ying 		nr_swapfiles++;
2739efa90a98SHugh Dickins 	} else {
2740b11a76b3SQian Cai 		defer = p;
2741efa90a98SHugh Dickins 		p = swap_info[type];
2742efa90a98SHugh Dickins 		/*
2743efa90a98SHugh Dickins 		 * Do not memset this entry: a racing procfs swap_next()
2744efa90a98SHugh Dickins 		 * would be relying on p->type to remain valid.
2745efa90a98SHugh Dickins 		 */
2746efa90a98SHugh Dickins 	}
27474efaceb1SAaron Lu 	p->swap_extent_root = RB_ROOT;
274818ab4d4cSDan Streetman 	plist_node_init(&p->list, 0);
2749a2468cc9SAaron Lu 	for_each_node(i)
2750a2468cc9SAaron Lu 		plist_node_init(&p->avail_lists[i], 0);
27511da177e4SLinus Torvalds 	p->flags = SWP_USED;
27525d337b91SHugh Dickins 	spin_unlock(&swap_lock);
275363d8620eSMiaohe Lin 	if (defer) {
275463d8620eSMiaohe Lin 		percpu_ref_exit(&defer->users);
2755b11a76b3SQian Cai 		kvfree(defer);
275663d8620eSMiaohe Lin 	}
2757ec8acf20SShaohua Li 	spin_lock_init(&p->lock);
27582628bd6fSHuang Ying 	spin_lock_init(&p->cont_lock);
275963d8620eSMiaohe Lin 	init_completion(&p->comp);
2760efa90a98SHugh Dickins 
276153cbb243SCesar Eduardo Barros 	return p;
276253cbb243SCesar Eduardo Barros }
276353cbb243SCesar Eduardo Barros 
27644d0e1e10SCesar Eduardo Barros static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
27654d0e1e10SCesar Eduardo Barros {
27664d0e1e10SCesar Eduardo Barros 	int error;
27674d0e1e10SCesar Eduardo Barros 
27684d0e1e10SCesar Eduardo Barros 	if (S_ISBLK(inode->i_mode)) {
2769ef16e1d9SChristoph Hellwig 		p->bdev = blkdev_get_by_dev(inode->i_rdev,
27706f179af8SHugh Dickins 				   FMODE_READ | FMODE_WRITE | FMODE_EXCL, p);
2771ef16e1d9SChristoph Hellwig 		if (IS_ERR(p->bdev)) {
2772ef16e1d9SChristoph Hellwig 			error = PTR_ERR(p->bdev);
27734d0e1e10SCesar Eduardo Barros 			p->bdev = NULL;
27746f179af8SHugh Dickins 			return error;
27754d0e1e10SCesar Eduardo Barros 		}
27764d0e1e10SCesar Eduardo Barros 		p->old_block_size = block_size(p->bdev);
27774d0e1e10SCesar Eduardo Barros 		error = set_blocksize(p->bdev, PAGE_SIZE);
27784d0e1e10SCesar Eduardo Barros 		if (error < 0)
277987ade72aSCesar Eduardo Barros 			return error;
278012d2966dSNaohiro Aota 		/*
278112d2966dSNaohiro Aota 		 * Zoned block devices contain zones that have a sequential
278212d2966dSNaohiro Aota 		 * write only restriction.  Hence zoned block devices are not
278312d2966dSNaohiro Aota 		 * suitable for swapping.  Disallow them here.
278412d2966dSNaohiro Aota 		 */
2785e556f6baSChristoph Hellwig 		if (blk_queue_is_zoned(p->bdev->bd_disk->queue))
278612d2966dSNaohiro Aota 			return -EINVAL;
27874d0e1e10SCesar Eduardo Barros 		p->flags |= SWP_BLKDEV;
27884d0e1e10SCesar Eduardo Barros 	} else if (S_ISREG(inode->i_mode)) {
27894d0e1e10SCesar Eduardo Barros 		p->bdev = inode->i_sb->s_bdev;
27901638045cSDarrick J. Wong 	}
27911638045cSDarrick J. Wong 
27924d0e1e10SCesar Eduardo Barros 	return 0;
27934d0e1e10SCesar Eduardo Barros }
27944d0e1e10SCesar Eduardo Barros 
2795377eeaa8SAndi Kleen 
2796377eeaa8SAndi Kleen /*
2797377eeaa8SAndi Kleen  * Find out how many pages are allowed for a single swap device. There
2798377eeaa8SAndi Kleen  * are two limiting factors:
2799377eeaa8SAndi Kleen  * 1) the number of bits for the swap offset in the swp_entry_t type, and
2800377eeaa8SAndi Kleen  * 2) the number of bits in the swap pte, as defined by the different
2801377eeaa8SAndi Kleen  * architectures.
2802377eeaa8SAndi Kleen  *
2803377eeaa8SAndi Kleen  * In order to find the largest possible bit mask, a swap entry with
2804377eeaa8SAndi Kleen  * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
2805377eeaa8SAndi Kleen  * decoded to a swp_entry_t again, and finally the swap offset is
2806377eeaa8SAndi Kleen  * extracted.
2807377eeaa8SAndi Kleen  *
2808377eeaa8SAndi Kleen  * This will mask all the bits from the initial ~0UL mask that can't
2809377eeaa8SAndi Kleen  * be encoded in either the swp_entry_t or the architecture definition
2810377eeaa8SAndi Kleen  * of a swap pte.
2811377eeaa8SAndi Kleen  */
2812377eeaa8SAndi Kleen unsigned long generic_max_swapfile_size(void)
2813377eeaa8SAndi Kleen {
2814377eeaa8SAndi Kleen 	return swp_offset(pte_to_swp_entry(
2815377eeaa8SAndi Kleen 			swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
2816377eeaa8SAndi Kleen }
2817377eeaa8SAndi Kleen 
2818377eeaa8SAndi Kleen /* Can be overridden by an architecture for additional checks. */
2819377eeaa8SAndi Kleen __weak unsigned long max_swapfile_size(void)
2820377eeaa8SAndi Kleen {
2821377eeaa8SAndi Kleen 	return generic_max_swapfile_size();
2822377eeaa8SAndi Kleen }
2823377eeaa8SAndi Kleen 
2824ca8bd38bSCesar Eduardo Barros static unsigned long read_swap_header(struct swap_info_struct *p,
2825ca8bd38bSCesar Eduardo Barros 					union swap_header *swap_header,
2826ca8bd38bSCesar Eduardo Barros 					struct inode *inode)
2827ca8bd38bSCesar Eduardo Barros {
2828ca8bd38bSCesar Eduardo Barros 	int i;
2829ca8bd38bSCesar Eduardo Barros 	unsigned long maxpages;
2830ca8bd38bSCesar Eduardo Barros 	unsigned long swapfilepages;
2831d6bbbd29SRaymond Jennings 	unsigned long last_page;
2832ca8bd38bSCesar Eduardo Barros 
2833ca8bd38bSCesar Eduardo Barros 	if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
2834465c47fdSAndrew Morton 		pr_err("Unable to find swap-space signature\n");
283538719025SCesar Eduardo Barros 		return 0;
2836ca8bd38bSCesar Eduardo Barros 	}
2837ca8bd38bSCesar Eduardo Barros 
2838041711ceSZhen Lei 	/* swap partition endianness hack... */
2839ca8bd38bSCesar Eduardo Barros 	if (swab32(swap_header->info.version) == 1) {
2840ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.version);
2841ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.last_page);
2842ca8bd38bSCesar Eduardo Barros 		swab32s(&swap_header->info.nr_badpages);
2843dd111be6SJann Horn 		if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
2844dd111be6SJann Horn 			return 0;
2845ca8bd38bSCesar Eduardo Barros 		for (i = 0; i < swap_header->info.nr_badpages; i++)
2846ca8bd38bSCesar Eduardo Barros 			swab32s(&swap_header->info.badpages[i]);
2847ca8bd38bSCesar Eduardo Barros 	}
2848ca8bd38bSCesar Eduardo Barros 	/* Check the swap header's sub-version */
2849ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.version != 1) {
2850465c47fdSAndrew Morton 		pr_warn("Unable to handle swap header version %d\n",
2851ca8bd38bSCesar Eduardo Barros 			swap_header->info.version);
285238719025SCesar Eduardo Barros 		return 0;
2853ca8bd38bSCesar Eduardo Barros 	}
2854ca8bd38bSCesar Eduardo Barros 
2855ca8bd38bSCesar Eduardo Barros 	p->lowest_bit  = 1;
2856ca8bd38bSCesar Eduardo Barros 	p->cluster_next = 1;
2857ca8bd38bSCesar Eduardo Barros 	p->cluster_nr = 0;
2858ca8bd38bSCesar Eduardo Barros 
2859377eeaa8SAndi Kleen 	maxpages = max_swapfile_size();
2860d6bbbd29SRaymond Jennings 	last_page = swap_header->info.last_page;
2861a06ad633STom Abraham 	if (!last_page) {
2862a06ad633STom Abraham 		pr_warn("Empty swap-file\n");
2863a06ad633STom Abraham 		return 0;
2864a06ad633STom Abraham 	}
2865d6bbbd29SRaymond Jennings 	if (last_page > maxpages) {
2866465c47fdSAndrew Morton 		pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
2867d6bbbd29SRaymond Jennings 			maxpages << (PAGE_SHIFT - 10),
2868d6bbbd29SRaymond Jennings 			last_page << (PAGE_SHIFT - 10));
2869d6bbbd29SRaymond Jennings 	}
2870d6bbbd29SRaymond Jennings 	if (maxpages > last_page) {
2871d6bbbd29SRaymond Jennings 		maxpages = last_page + 1;
2872ca8bd38bSCesar Eduardo Barros 		/* p->max is an unsigned int: don't overflow it */
2873ca8bd38bSCesar Eduardo Barros 		if ((unsigned int)maxpages == 0)
2874ca8bd38bSCesar Eduardo Barros 			maxpages = UINT_MAX;
2875ca8bd38bSCesar Eduardo Barros 	}
2876ca8bd38bSCesar Eduardo Barros 	p->highest_bit = maxpages - 1;
2877ca8bd38bSCesar Eduardo Barros 
2878ca8bd38bSCesar Eduardo Barros 	if (!maxpages)
287938719025SCesar Eduardo Barros 		return 0;
2880ca8bd38bSCesar Eduardo Barros 	swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
2881ca8bd38bSCesar Eduardo Barros 	if (swapfilepages && maxpages > swapfilepages) {
2882465c47fdSAndrew Morton 		pr_warn("Swap area shorter than signature indicates\n");
288338719025SCesar Eduardo Barros 		return 0;
2884ca8bd38bSCesar Eduardo Barros 	}
2885ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
288638719025SCesar Eduardo Barros 		return 0;
2887ca8bd38bSCesar Eduardo Barros 	if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
288838719025SCesar Eduardo Barros 		return 0;
2889ca8bd38bSCesar Eduardo Barros 
2890ca8bd38bSCesar Eduardo Barros 	return maxpages;
2891ca8bd38bSCesar Eduardo Barros }
2892ca8bd38bSCesar Eduardo Barros 
28934b3ef9daSHuang, Ying #define SWAP_CLUSTER_INFO_COLS						\
2894235b6217SHuang, Ying 	DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
28954b3ef9daSHuang, Ying #define SWAP_CLUSTER_SPACE_COLS						\
28964b3ef9daSHuang, Ying 	DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
28974b3ef9daSHuang, Ying #define SWAP_CLUSTER_COLS						\
28984b3ef9daSHuang, Ying 	max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
2899235b6217SHuang, Ying 
2900915d4d7bSCesar Eduardo Barros static int setup_swap_map_and_extents(struct swap_info_struct *p,
2901915d4d7bSCesar Eduardo Barros 					union swap_header *swap_header,
2902915d4d7bSCesar Eduardo Barros 					unsigned char *swap_map,
29032a8f9449SShaohua Li 					struct swap_cluster_info *cluster_info,
2904915d4d7bSCesar Eduardo Barros 					unsigned long maxpages,
2905915d4d7bSCesar Eduardo Barros 					sector_t *span)
2906915d4d7bSCesar Eduardo Barros {
2907235b6217SHuang, Ying 	unsigned int j, k;
2908915d4d7bSCesar Eduardo Barros 	unsigned int nr_good_pages;
2909915d4d7bSCesar Eduardo Barros 	int nr_extents;
29102a8f9449SShaohua Li 	unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
2911235b6217SHuang, Ying 	unsigned long col = p->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
2912235b6217SHuang, Ying 	unsigned long i, idx;
2913915d4d7bSCesar Eduardo Barros 
2914915d4d7bSCesar Eduardo Barros 	nr_good_pages = maxpages - 1;	/* omit header page */
2915915d4d7bSCesar Eduardo Barros 
29166b534915SHuang Ying 	cluster_list_init(&p->free_clusters);
29176b534915SHuang Ying 	cluster_list_init(&p->discard_clusters);
29182a8f9449SShaohua Li 
2919915d4d7bSCesar Eduardo Barros 	for (i = 0; i < swap_header->info.nr_badpages; i++) {
2920915d4d7bSCesar Eduardo Barros 		unsigned int page_nr = swap_header->info.badpages[i];
2921bdb8e3f6SCesar Eduardo Barros 		if (page_nr == 0 || page_nr > swap_header->info.last_page)
2922bdb8e3f6SCesar Eduardo Barros 			return -EINVAL;
2923915d4d7bSCesar Eduardo Barros 		if (page_nr < maxpages) {
2924915d4d7bSCesar Eduardo Barros 			swap_map[page_nr] = SWAP_MAP_BAD;
2925915d4d7bSCesar Eduardo Barros 			nr_good_pages--;
29262a8f9449SShaohua Li 			/*
29272a8f9449SShaohua Li 			 * Haven't marked the cluster free yet, no list
29282a8f9449SShaohua Li 			 * operation involved
29292a8f9449SShaohua Li 			 */
29302a8f9449SShaohua Li 			inc_cluster_info_page(p, cluster_info, page_nr);
2931915d4d7bSCesar Eduardo Barros 		}
2932915d4d7bSCesar Eduardo Barros 	}
2933915d4d7bSCesar Eduardo Barros 
29342a8f9449SShaohua Li 	/* Haven't marked the cluster free yet, no list operation involved */
29352a8f9449SShaohua Li 	for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
29362a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, i);
29372a8f9449SShaohua Li 
2938915d4d7bSCesar Eduardo Barros 	if (nr_good_pages) {
2939915d4d7bSCesar Eduardo Barros 		swap_map[0] = SWAP_MAP_BAD;
29402a8f9449SShaohua Li 		/*
29412a8f9449SShaohua Li 		 * Not mark the cluster free yet, no list
29422a8f9449SShaohua Li 		 * operation involved
29432a8f9449SShaohua Li 		 */
29442a8f9449SShaohua Li 		inc_cluster_info_page(p, cluster_info, 0);
2945915d4d7bSCesar Eduardo Barros 		p->max = maxpages;
2946915d4d7bSCesar Eduardo Barros 		p->pages = nr_good_pages;
2947915d4d7bSCesar Eduardo Barros 		nr_extents = setup_swap_extents(p, span);
2948bdb8e3f6SCesar Eduardo Barros 		if (nr_extents < 0)
2949bdb8e3f6SCesar Eduardo Barros 			return nr_extents;
2950915d4d7bSCesar Eduardo Barros 		nr_good_pages = p->pages;
2951915d4d7bSCesar Eduardo Barros 	}
2952915d4d7bSCesar Eduardo Barros 	if (!nr_good_pages) {
2953465c47fdSAndrew Morton 		pr_warn("Empty swap-file\n");
2954bdb8e3f6SCesar Eduardo Barros 		return -EINVAL;
2955915d4d7bSCesar Eduardo Barros 	}
2956915d4d7bSCesar Eduardo Barros 
29572a8f9449SShaohua Li 	if (!cluster_info)
29582a8f9449SShaohua Li 		return nr_extents;
29592a8f9449SShaohua Li 
2960235b6217SHuang, Ying 
29614b3ef9daSHuang, Ying 	/*
29624b3ef9daSHuang, Ying 	 * Reduce false cache line sharing between cluster_info and
29634b3ef9daSHuang, Ying 	 * sharing same address space.
29644b3ef9daSHuang, Ying 	 */
2965235b6217SHuang, Ying 	for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
2966235b6217SHuang, Ying 		j = (k + col) % SWAP_CLUSTER_COLS;
2967235b6217SHuang, Ying 		for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
2968235b6217SHuang, Ying 			idx = i * SWAP_CLUSTER_COLS + j;
2969235b6217SHuang, Ying 			if (idx >= nr_clusters)
2970235b6217SHuang, Ying 				continue;
2971235b6217SHuang, Ying 			if (cluster_count(&cluster_info[idx]))
2972235b6217SHuang, Ying 				continue;
29732a8f9449SShaohua Li 			cluster_set_flag(&cluster_info[idx], CLUSTER_FLAG_FREE);
29746b534915SHuang Ying 			cluster_list_add_tail(&p->free_clusters, cluster_info,
29756b534915SHuang Ying 					      idx);
29762a8f9449SShaohua Li 		}
29772a8f9449SShaohua Li 	}
2978915d4d7bSCesar Eduardo Barros 	return nr_extents;
2979915d4d7bSCesar Eduardo Barros }
2980915d4d7bSCesar Eduardo Barros 
2981dcf6b7ddSRafael Aquini /*
2982dcf6b7ddSRafael Aquini  * Helper to sys_swapon determining if a given swap
2983dcf6b7ddSRafael Aquini  * backing device queue supports DISCARD operations.
2984dcf6b7ddSRafael Aquini  */
2985dcf6b7ddSRafael Aquini static bool swap_discardable(struct swap_info_struct *si)
2986dcf6b7ddSRafael Aquini {
2987dcf6b7ddSRafael Aquini 	struct request_queue *q = bdev_get_queue(si->bdev);
2988dcf6b7ddSRafael Aquini 
2989363dc512SXu Wang 	if (!blk_queue_discard(q))
2990dcf6b7ddSRafael Aquini 		return false;
2991dcf6b7ddSRafael Aquini 
2992dcf6b7ddSRafael Aquini 	return true;
2993dcf6b7ddSRafael Aquini }
2994dcf6b7ddSRafael Aquini 
299553cbb243SCesar Eduardo Barros SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
299653cbb243SCesar Eduardo Barros {
299753cbb243SCesar Eduardo Barros 	struct swap_info_struct *p;
299891a27b2aSJeff Layton 	struct filename *name;
299953cbb243SCesar Eduardo Barros 	struct file *swap_file = NULL;
300053cbb243SCesar Eduardo Barros 	struct address_space *mapping;
300151cc3a66SHugh Dickins 	struct dentry *dentry;
300240531542SCesar Eduardo Barros 	int prio;
300353cbb243SCesar Eduardo Barros 	int error;
300453cbb243SCesar Eduardo Barros 	union swap_header *swap_header;
3005915d4d7bSCesar Eduardo Barros 	int nr_extents;
300653cbb243SCesar Eduardo Barros 	sector_t span;
300753cbb243SCesar Eduardo Barros 	unsigned long maxpages;
300853cbb243SCesar Eduardo Barros 	unsigned char *swap_map = NULL;
30092a8f9449SShaohua Li 	struct swap_cluster_info *cluster_info = NULL;
301038b5faf4SDan Magenheimer 	unsigned long *frontswap_map = NULL;
301153cbb243SCesar Eduardo Barros 	struct page *page = NULL;
301253cbb243SCesar Eduardo Barros 	struct inode *inode = NULL;
30137cbf3192SOmar Sandoval 	bool inced_nr_rotate_swap = false;
301453cbb243SCesar Eduardo Barros 
3015d15cab97SHugh Dickins 	if (swap_flags & ~SWAP_FLAGS_VALID)
3016d15cab97SHugh Dickins 		return -EINVAL;
3017d15cab97SHugh Dickins 
301853cbb243SCesar Eduardo Barros 	if (!capable(CAP_SYS_ADMIN))
301953cbb243SCesar Eduardo Barros 		return -EPERM;
302053cbb243SCesar Eduardo Barros 
3021a2468cc9SAaron Lu 	if (!swap_avail_heads)
3022a2468cc9SAaron Lu 		return -ENOMEM;
3023a2468cc9SAaron Lu 
302453cbb243SCesar Eduardo Barros 	p = alloc_swap_info();
30252542e513SCesar Eduardo Barros 	if (IS_ERR(p))
30262542e513SCesar Eduardo Barros 		return PTR_ERR(p);
302753cbb243SCesar Eduardo Barros 
3028815c2c54SShaohua Li 	INIT_WORK(&p->discard_work, swap_discard_work);
3029815c2c54SShaohua Li 
30301da177e4SLinus Torvalds 	name = getname(specialfile);
30311da177e4SLinus Torvalds 	if (IS_ERR(name)) {
30327de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(name);
30331da177e4SLinus Torvalds 		name = NULL;
3034bd69010bSCesar Eduardo Barros 		goto bad_swap;
30351da177e4SLinus Torvalds 	}
3036669abf4eSJeff Layton 	swap_file = file_open_name(name, O_RDWR|O_LARGEFILE, 0);
30371da177e4SLinus Torvalds 	if (IS_ERR(swap_file)) {
30387de7fb6bSCesar Eduardo Barros 		error = PTR_ERR(swap_file);
30391da177e4SLinus Torvalds 		swap_file = NULL;
3040bd69010bSCesar Eduardo Barros 		goto bad_swap;
30411da177e4SLinus Torvalds 	}
30421da177e4SLinus Torvalds 
30431da177e4SLinus Torvalds 	p->swap_file = swap_file;
30441da177e4SLinus Torvalds 	mapping = swap_file->f_mapping;
304551cc3a66SHugh Dickins 	dentry = swap_file->f_path.dentry;
30462130781eSCesar Eduardo Barros 	inode = mapping->host;
30476f179af8SHugh Dickins 
30484d0e1e10SCesar Eduardo Barros 	error = claim_swapfile(p, inode);
30494d0e1e10SCesar Eduardo Barros 	if (unlikely(error))
30501da177e4SLinus Torvalds 		goto bad_swap;
30511da177e4SLinus Torvalds 
3052d795a90eSNaohiro Aota 	inode_lock(inode);
305351cc3a66SHugh Dickins 	if (d_unlinked(dentry) || cant_mount(dentry)) {
305451cc3a66SHugh Dickins 		error = -ENOENT;
305551cc3a66SHugh Dickins 		goto bad_swap_unlock_inode;
305651cc3a66SHugh Dickins 	}
3057d795a90eSNaohiro Aota 	if (IS_SWAPFILE(inode)) {
3058d795a90eSNaohiro Aota 		error = -EBUSY;
3059d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
3060d795a90eSNaohiro Aota 	}
3061d795a90eSNaohiro Aota 
30621da177e4SLinus Torvalds 	/*
30631da177e4SLinus Torvalds 	 * Read the swap header.
30641da177e4SLinus Torvalds 	 */
30651da177e4SLinus Torvalds 	if (!mapping->a_ops->readpage) {
30661da177e4SLinus Torvalds 		error = -EINVAL;
3067d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30681da177e4SLinus Torvalds 	}
3069090d2b18SPekka Enberg 	page = read_mapping_page(mapping, 0, swap_file);
30701da177e4SLinus Torvalds 	if (IS_ERR(page)) {
30711da177e4SLinus Torvalds 		error = PTR_ERR(page);
3072d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30731da177e4SLinus Torvalds 	}
307481e33971SHugh Dickins 	swap_header = kmap(page);
30751da177e4SLinus Torvalds 
3076ca8bd38bSCesar Eduardo Barros 	maxpages = read_swap_header(p, swap_header, inode);
3077ca8bd38bSCesar Eduardo Barros 	if (unlikely(!maxpages)) {
30781da177e4SLinus Torvalds 		error = -EINVAL;
3079d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30801da177e4SLinus Torvalds 	}
30811da177e4SLinus Torvalds 
30821da177e4SLinus Torvalds 	/* OK, set up the swap map and apply the bad block list */
3083803d0c83SCesar Eduardo Barros 	swap_map = vzalloc(maxpages);
308478ecba08SHugh Dickins 	if (!swap_map) {
30851da177e4SLinus Torvalds 		error = -ENOMEM;
3086d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
30871da177e4SLinus Torvalds 	}
3088f0571429SMinchan Kim 
30891cb039f3SChristoph Hellwig 	if (p->bdev && blk_queue_stable_writes(p->bdev->bd_disk->queue))
3090f0571429SMinchan Kim 		p->flags |= SWP_STABLE_WRITES;
3091f0571429SMinchan Kim 
3092a8b456d0SChristoph Hellwig 	if (p->bdev && p->bdev->bd_disk->fops->rw_page)
3093539a6feaSMinchan Kim 		p->flags |= SWP_SYNCHRONOUS_IO;
3094539a6feaSMinchan Kim 
30952a8f9449SShaohua Li 	if (p->bdev && blk_queue_nonrot(bdev_get_queue(p->bdev))) {
30966f179af8SHugh Dickins 		int cpu;
3097235b6217SHuang, Ying 		unsigned long ci, nr_cluster;
30986f179af8SHugh Dickins 
30992a8f9449SShaohua Li 		p->flags |= SWP_SOLIDSTATE;
310049070588SHuang Ying 		p->cluster_next_cpu = alloc_percpu(unsigned int);
310149070588SHuang Ying 		if (!p->cluster_next_cpu) {
310249070588SHuang Ying 			error = -ENOMEM;
310349070588SHuang Ying 			goto bad_swap_unlock_inode;
310449070588SHuang Ying 		}
31052a8f9449SShaohua Li 		/*
31062a8f9449SShaohua Li 		 * select a random position to start with to help wear leveling
31072a8f9449SShaohua Li 		 * SSD
31082a8f9449SShaohua Li 		 */
310949070588SHuang Ying 		for_each_possible_cpu(cpu) {
311049070588SHuang Ying 			per_cpu(*p->cluster_next_cpu, cpu) =
311149070588SHuang Ying 				1 + prandom_u32_max(p->highest_bit);
311249070588SHuang Ying 		}
3113235b6217SHuang, Ying 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
31142a8f9449SShaohua Li 
3115778e1cddSKees Cook 		cluster_info = kvcalloc(nr_cluster, sizeof(*cluster_info),
311654f180d3SHuang Ying 					GFP_KERNEL);
31172a8f9449SShaohua Li 		if (!cluster_info) {
31182a8f9449SShaohua Li 			error = -ENOMEM;
3119d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
31202a8f9449SShaohua Li 		}
3121235b6217SHuang, Ying 
3122235b6217SHuang, Ying 		for (ci = 0; ci < nr_cluster; ci++)
3123235b6217SHuang, Ying 			spin_lock_init(&((cluster_info + ci)->lock));
3124235b6217SHuang, Ying 
3125ebc2a1a6SShaohua Li 		p->percpu_cluster = alloc_percpu(struct percpu_cluster);
3126ebc2a1a6SShaohua Li 		if (!p->percpu_cluster) {
3127ebc2a1a6SShaohua Li 			error = -ENOMEM;
3128d795a90eSNaohiro Aota 			goto bad_swap_unlock_inode;
3129ebc2a1a6SShaohua Li 		}
31306f179af8SHugh Dickins 		for_each_possible_cpu(cpu) {
3131ebc2a1a6SShaohua Li 			struct percpu_cluster *cluster;
31326f179af8SHugh Dickins 			cluster = per_cpu_ptr(p->percpu_cluster, cpu);
3133ebc2a1a6SShaohua Li 			cluster_set_null(&cluster->index);
3134ebc2a1a6SShaohua Li 		}
31357cbf3192SOmar Sandoval 	} else {
313681a0298bSHuang Ying 		atomic_inc(&nr_rotate_swap);
31377cbf3192SOmar Sandoval 		inced_nr_rotate_swap = true;
31387cbf3192SOmar Sandoval 	}
31391da177e4SLinus Torvalds 
31401421ef3cSCesar Eduardo Barros 	error = swap_cgroup_swapon(p->type, maxpages);
31411421ef3cSCesar Eduardo Barros 	if (error)
3142d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
31431421ef3cSCesar Eduardo Barros 
3144915d4d7bSCesar Eduardo Barros 	nr_extents = setup_swap_map_and_extents(p, swap_header, swap_map,
31452a8f9449SShaohua Li 		cluster_info, maxpages, &span);
3146915d4d7bSCesar Eduardo Barros 	if (unlikely(nr_extents < 0)) {
314753092a74SHugh Dickins 		error = nr_extents;
3148d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
314953092a74SHugh Dickins 	}
315038b5faf4SDan Magenheimer 	/* frontswap enabled? set up bit-per-page map for frontswap */
31518ea1d2a1SVlastimil Babka 	if (IS_ENABLED(CONFIG_FRONTSWAP))
3152778e1cddSKees Cook 		frontswap_map = kvcalloc(BITS_TO_LONGS(maxpages),
3153778e1cddSKees Cook 					 sizeof(long),
315454f180d3SHuang Ying 					 GFP_KERNEL);
31551da177e4SLinus Torvalds 
31562a8f9449SShaohua Li 	if (p->bdev && (swap_flags & SWAP_FLAG_DISCARD) && swap_discardable(p)) {
3157dcf6b7ddSRafael Aquini 		/*
3158dcf6b7ddSRafael Aquini 		 * When discard is enabled for swap with no particular
3159dcf6b7ddSRafael Aquini 		 * policy flagged, we set all swap discard flags here in
3160dcf6b7ddSRafael Aquini 		 * order to sustain backward compatibility with older
3161dcf6b7ddSRafael Aquini 		 * swapon(8) releases.
3162dcf6b7ddSRafael Aquini 		 */
3163dcf6b7ddSRafael Aquini 		p->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
3164dcf6b7ddSRafael Aquini 			     SWP_PAGE_DISCARD);
3165dcf6b7ddSRafael Aquini 
3166dcf6b7ddSRafael Aquini 		/*
3167dcf6b7ddSRafael Aquini 		 * By flagging sys_swapon, a sysadmin can tell us to
3168dcf6b7ddSRafael Aquini 		 * either do single-time area discards only, or to just
3169dcf6b7ddSRafael Aquini 		 * perform discards for released swap page-clusters.
3170dcf6b7ddSRafael Aquini 		 * Now it's time to adjust the p->flags accordingly.
3171dcf6b7ddSRafael Aquini 		 */
3172dcf6b7ddSRafael Aquini 		if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
3173dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_PAGE_DISCARD;
3174dcf6b7ddSRafael Aquini 		else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
3175dcf6b7ddSRafael Aquini 			p->flags &= ~SWP_AREA_DISCARD;
3176dcf6b7ddSRafael Aquini 
3177dcf6b7ddSRafael Aquini 		/* issue a swapon-time discard if it's still required */
3178dcf6b7ddSRafael Aquini 		if (p->flags & SWP_AREA_DISCARD) {
3179dcf6b7ddSRafael Aquini 			int err = discard_swap(p);
3180dcf6b7ddSRafael Aquini 			if (unlikely(err))
3181465c47fdSAndrew Morton 				pr_err("swapon: discard_swap(%p): %d\n",
3182dcf6b7ddSRafael Aquini 					p, err);
3183dcf6b7ddSRafael Aquini 		}
3184dcf6b7ddSRafael Aquini 	}
31856a6ba831SHugh Dickins 
31864b3ef9daSHuang, Ying 	error = init_swap_address_space(p->type, maxpages);
31874b3ef9daSHuang, Ying 	if (error)
3188d795a90eSNaohiro Aota 		goto bad_swap_unlock_inode;
31894b3ef9daSHuang, Ying 
3190dc617f29SDarrick J. Wong 	/*
3191dc617f29SDarrick J. Wong 	 * Flush any pending IO and dirty mappings before we start using this
3192dc617f29SDarrick J. Wong 	 * swap device.
3193dc617f29SDarrick J. Wong 	 */
3194dc617f29SDarrick J. Wong 	inode->i_flags |= S_SWAPFILE;
3195dc617f29SDarrick J. Wong 	error = inode_drain_writes(inode);
3196dc617f29SDarrick J. Wong 	if (error) {
3197dc617f29SDarrick J. Wong 		inode->i_flags &= ~S_SWAPFILE;
3198822bca52SMiaohe Lin 		goto free_swap_address_space;
3199dc617f29SDarrick J. Wong 	}
3200dc617f29SDarrick J. Wong 
3201fc0abb14SIngo Molnar 	mutex_lock(&swapon_mutex);
320240531542SCesar Eduardo Barros 	prio = -1;
320378ecba08SHugh Dickins 	if (swap_flags & SWAP_FLAG_PREFER)
320440531542SCesar Eduardo Barros 		prio =
320578ecba08SHugh Dickins 		  (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
32062a8f9449SShaohua Li 	enable_swap_info(p, prio, swap_map, cluster_info, frontswap_map);
3207c69dbfb8SCesar Eduardo Barros 
3208756a025fSJoe Perches 	pr_info("Adding %uk swap on %s.  Priority:%d extents:%d across:%lluk %s%s%s%s%s\n",
320991a27b2aSJeff Layton 		p->pages<<(PAGE_SHIFT-10), name->name, p->prio,
3210c69dbfb8SCesar Eduardo Barros 		nr_extents, (unsigned long long)span<<(PAGE_SHIFT-10),
3211c69dbfb8SCesar Eduardo Barros 		(p->flags & SWP_SOLIDSTATE) ? "SS" : "",
321238b5faf4SDan Magenheimer 		(p->flags & SWP_DISCARDABLE) ? "D" : "",
3213dcf6b7ddSRafael Aquini 		(p->flags & SWP_AREA_DISCARD) ? "s" : "",
3214dcf6b7ddSRafael Aquini 		(p->flags & SWP_PAGE_DISCARD) ? "c" : "",
321538b5faf4SDan Magenheimer 		(frontswap_map) ? "FS" : "");
3216c69dbfb8SCesar Eduardo Barros 
3217fc0abb14SIngo Molnar 	mutex_unlock(&swapon_mutex);
321866d7dd51SKay Sievers 	atomic_inc(&proc_poll_event);
321966d7dd51SKay Sievers 	wake_up_interruptible(&proc_poll_wait);
322066d7dd51SKay Sievers 
32211da177e4SLinus Torvalds 	error = 0;
32221da177e4SLinus Torvalds 	goto out;
3223822bca52SMiaohe Lin free_swap_address_space:
3224822bca52SMiaohe Lin 	exit_swap_address_space(p->type);
3225d795a90eSNaohiro Aota bad_swap_unlock_inode:
3226d795a90eSNaohiro Aota 	inode_unlock(inode);
32271da177e4SLinus Torvalds bad_swap:
3228ebc2a1a6SShaohua Li 	free_percpu(p->percpu_cluster);
3229ebc2a1a6SShaohua Li 	p->percpu_cluster = NULL;
323049070588SHuang Ying 	free_percpu(p->cluster_next_cpu);
323149070588SHuang Ying 	p->cluster_next_cpu = NULL;
3232bd69010bSCesar Eduardo Barros 	if (inode && S_ISBLK(inode->i_mode) && p->bdev) {
3233f2090d2dSCesar Eduardo Barros 		set_blocksize(p->bdev, p->old_block_size);
3234f2090d2dSCesar Eduardo Barros 		blkdev_put(p->bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
32351da177e4SLinus Torvalds 	}
3236d795a90eSNaohiro Aota 	inode = NULL;
32374cd3bb10SHugh Dickins 	destroy_swap_extents(p);
3238e8e6c2ecSCesar Eduardo Barros 	swap_cgroup_swapoff(p->type);
32395d337b91SHugh Dickins 	spin_lock(&swap_lock);
32401da177e4SLinus Torvalds 	p->swap_file = NULL;
32411da177e4SLinus Torvalds 	p->flags = 0;
32425d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32431da177e4SLinus Torvalds 	vfree(swap_map);
32448606a1a9SDarrick J. Wong 	kvfree(cluster_info);
3245b6b1fd2aSDavid Rientjes 	kvfree(frontswap_map);
32467cbf3192SOmar Sandoval 	if (inced_nr_rotate_swap)
32477cbf3192SOmar Sandoval 		atomic_dec(&nr_rotate_swap);
3248d795a90eSNaohiro Aota 	if (swap_file)
32491da177e4SLinus Torvalds 		filp_close(swap_file, NULL);
32501da177e4SLinus Torvalds out:
32511da177e4SLinus Torvalds 	if (page && !IS_ERR(page)) {
32521da177e4SLinus Torvalds 		kunmap(page);
325309cbfeafSKirill A. Shutemov 		put_page(page);
32541da177e4SLinus Torvalds 	}
32551da177e4SLinus Torvalds 	if (name)
32561da177e4SLinus Torvalds 		putname(name);
32571638045cSDarrick J. Wong 	if (inode)
32585955102cSAl Viro 		inode_unlock(inode);
3259039939a6STim Chen 	if (!error)
3260039939a6STim Chen 		enable_swap_slots_cache();
32611da177e4SLinus Torvalds 	return error;
32621da177e4SLinus Torvalds }
32631da177e4SLinus Torvalds 
32641da177e4SLinus Torvalds void si_swapinfo(struct sysinfo *val)
32651da177e4SLinus Torvalds {
3266efa90a98SHugh Dickins 	unsigned int type;
32671da177e4SLinus Torvalds 	unsigned long nr_to_be_unused = 0;
32681da177e4SLinus Torvalds 
32695d337b91SHugh Dickins 	spin_lock(&swap_lock);
3270efa90a98SHugh Dickins 	for (type = 0; type < nr_swapfiles; type++) {
3271efa90a98SHugh Dickins 		struct swap_info_struct *si = swap_info[type];
3272efa90a98SHugh Dickins 
3273efa90a98SHugh Dickins 		if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
3274efa90a98SHugh Dickins 			nr_to_be_unused += si->inuse_pages;
32751da177e4SLinus Torvalds 	}
3276ec8acf20SShaohua Li 	val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
32771da177e4SLinus Torvalds 	val->totalswap = total_swap_pages + nr_to_be_unused;
32785d337b91SHugh Dickins 	spin_unlock(&swap_lock);
32791da177e4SLinus Torvalds }
32801da177e4SLinus Torvalds 
32811da177e4SLinus Torvalds /*
32821da177e4SLinus Torvalds  * Verify that a swap entry is valid and increment its swap map count.
32831da177e4SLinus Torvalds  *
3284355cfa73SKAMEZAWA Hiroyuki  * Returns error code in following case.
3285355cfa73SKAMEZAWA Hiroyuki  * - success -> 0
3286355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is invalid -> EINVAL
3287355cfa73SKAMEZAWA Hiroyuki  * - swp_entry is migration entry -> EINVAL
3288355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but there is already one. -> EEXIST
3289355cfa73SKAMEZAWA Hiroyuki  * - swap-cache reference is requested but the entry is not used. -> ENOENT
3290570a335bSHugh Dickins  * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
32911da177e4SLinus Torvalds  */
32928d69aaeeSHugh Dickins static int __swap_duplicate(swp_entry_t entry, unsigned char usage)
32931da177e4SLinus Torvalds {
32941da177e4SLinus Torvalds 	struct swap_info_struct *p;
3295235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3296c10d38ccSDaniel Jordan 	unsigned long offset;
32978d69aaeeSHugh Dickins 	unsigned char count;
32988d69aaeeSHugh Dickins 	unsigned char has_cache;
32999d9a0334SMiaohe Lin 	int err;
33001da177e4SLinus Torvalds 
3301eb085574SHuang Ying 	p = get_swap_device(entry);
3302c10d38ccSDaniel Jordan 	if (!p)
33039d9a0334SMiaohe Lin 		return -EINVAL;
3304c10d38ccSDaniel Jordan 
33051da177e4SLinus Torvalds 	offset = swp_offset(entry);
3306235b6217SHuang, Ying 	ci = lock_cluster_or_swap_info(p, offset);
3307355cfa73SKAMEZAWA Hiroyuki 
3308253d553bSHugh Dickins 	count = p->swap_map[offset];
3309edfe23daSShaohua Li 
3310edfe23daSShaohua Li 	/*
3311edfe23daSShaohua Li 	 * swapin_readahead() doesn't check if a swap entry is valid, so the
3312edfe23daSShaohua Li 	 * swap entry could be SWAP_MAP_BAD. Check here with lock held.
3313edfe23daSShaohua Li 	 */
3314edfe23daSShaohua Li 	if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
3315edfe23daSShaohua Li 		err = -ENOENT;
3316edfe23daSShaohua Li 		goto unlock_out;
3317edfe23daSShaohua Li 	}
3318edfe23daSShaohua Li 
3319253d553bSHugh Dickins 	has_cache = count & SWAP_HAS_CACHE;
3320253d553bSHugh Dickins 	count &= ~SWAP_HAS_CACHE;
3321253d553bSHugh Dickins 	err = 0;
3322355cfa73SKAMEZAWA Hiroyuki 
3323253d553bSHugh Dickins 	if (usage == SWAP_HAS_CACHE) {
3324355cfa73SKAMEZAWA Hiroyuki 
3325355cfa73SKAMEZAWA Hiroyuki 		/* set SWAP_HAS_CACHE if there is no cache and entry is used */
3326253d553bSHugh Dickins 		if (!has_cache && count)
3327253d553bSHugh Dickins 			has_cache = SWAP_HAS_CACHE;
3328253d553bSHugh Dickins 		else if (has_cache)		/* someone else added cache */
3329253d553bSHugh Dickins 			err = -EEXIST;
3330253d553bSHugh Dickins 		else				/* no users remaining */
3331253d553bSHugh Dickins 			err = -ENOENT;
3332355cfa73SKAMEZAWA Hiroyuki 
3333355cfa73SKAMEZAWA Hiroyuki 	} else if (count || has_cache) {
3334253d553bSHugh Dickins 
3335570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
3336570a335bSHugh Dickins 			count += usage;
3337570a335bSHugh Dickins 		else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX)
3338253d553bSHugh Dickins 			err = -EINVAL;
3339570a335bSHugh Dickins 		else if (swap_count_continued(p, offset, count))
3340570a335bSHugh Dickins 			count = COUNT_CONTINUED;
3341570a335bSHugh Dickins 		else
3342570a335bSHugh Dickins 			err = -ENOMEM;
3343253d553bSHugh Dickins 	} else
3344253d553bSHugh Dickins 		err = -ENOENT;			/* unused swap entry */
3345253d553bSHugh Dickins 
3346a449bf58SQian Cai 	WRITE_ONCE(p->swap_map[offset], count | has_cache);
3347253d553bSHugh Dickins 
3348355cfa73SKAMEZAWA Hiroyuki unlock_out:
3349235b6217SHuang, Ying 	unlock_cluster_or_swap_info(p, ci);
3350eb085574SHuang Ying 	put_swap_device(p);
3351253d553bSHugh Dickins 	return err;
33521da177e4SLinus Torvalds }
3353253d553bSHugh Dickins 
3354355cfa73SKAMEZAWA Hiroyuki /*
3355aaa46865SHugh Dickins  * Help swapoff by noting that swap entry belongs to shmem/tmpfs
3356aaa46865SHugh Dickins  * (in which case its reference count is never incremented).
3357aaa46865SHugh Dickins  */
3358aaa46865SHugh Dickins void swap_shmem_alloc(swp_entry_t entry)
3359aaa46865SHugh Dickins {
3360aaa46865SHugh Dickins 	__swap_duplicate(entry, SWAP_MAP_SHMEM);
3361aaa46865SHugh Dickins }
3362aaa46865SHugh Dickins 
3363aaa46865SHugh Dickins /*
336408259d58SHugh Dickins  * Increase reference count of swap entry by 1.
336508259d58SHugh Dickins  * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
336608259d58SHugh Dickins  * but could not be atomically allocated.  Returns 0, just as if it succeeded,
336708259d58SHugh Dickins  * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
336808259d58SHugh Dickins  * might occur if a page table entry has got corrupted.
3369355cfa73SKAMEZAWA Hiroyuki  */
3370570a335bSHugh Dickins int swap_duplicate(swp_entry_t entry)
3371355cfa73SKAMEZAWA Hiroyuki {
3372570a335bSHugh Dickins 	int err = 0;
3373570a335bSHugh Dickins 
3374570a335bSHugh Dickins 	while (!err && __swap_duplicate(entry, 1) == -ENOMEM)
3375570a335bSHugh Dickins 		err = add_swap_count_continuation(entry, GFP_ATOMIC);
3376570a335bSHugh Dickins 	return err;
3377355cfa73SKAMEZAWA Hiroyuki }
33781da177e4SLinus Torvalds 
3379cb4b86baSKAMEZAWA Hiroyuki /*
3380355cfa73SKAMEZAWA Hiroyuki  * @entry: swap entry for which we allocate swap cache.
3381355cfa73SKAMEZAWA Hiroyuki  *
338273c34b6aSHugh Dickins  * Called when allocating swap cache for existing swap entry,
3383355cfa73SKAMEZAWA Hiroyuki  * This can return error codes. Returns 0 at success.
33843eeba135SChen Wandun  * -EEXIST means there is a swap cache.
3385355cfa73SKAMEZAWA Hiroyuki  * Note: return code is different from swap_duplicate().
3386cb4b86baSKAMEZAWA Hiroyuki  */
3387cb4b86baSKAMEZAWA Hiroyuki int swapcache_prepare(swp_entry_t entry)
3388cb4b86baSKAMEZAWA Hiroyuki {
3389253d553bSHugh Dickins 	return __swap_duplicate(entry, SWAP_HAS_CACHE);
3390cb4b86baSKAMEZAWA Hiroyuki }
3391cb4b86baSKAMEZAWA Hiroyuki 
33920bcac06fSMinchan Kim struct swap_info_struct *swp_swap_info(swp_entry_t entry)
33930bcac06fSMinchan Kim {
3394c10d38ccSDaniel Jordan 	return swap_type_to_swap_info(swp_type(entry));
33950bcac06fSMinchan Kim }
33960bcac06fSMinchan Kim 
3397f981c595SMel Gorman struct swap_info_struct *page_swap_info(struct page *page)
3398f981c595SMel Gorman {
33990bcac06fSMinchan Kim 	swp_entry_t entry = { .val = page_private(page) };
34000bcac06fSMinchan Kim 	return swp_swap_info(entry);
3401f981c595SMel Gorman }
3402f981c595SMel Gorman 
3403f981c595SMel Gorman /*
34042f52578fSMatthew Wilcox (Oracle)  * out-of-line methods to avoid include hell.
3405f981c595SMel Gorman  */
34062f52578fSMatthew Wilcox (Oracle) struct address_space *swapcache_mapping(struct folio *folio)
3407f981c595SMel Gorman {
34082f52578fSMatthew Wilcox (Oracle) 	return page_swap_info(&folio->page)->swap_file->f_mapping;
3409f981c595SMel Gorman }
34102f52578fSMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(swapcache_mapping);
3411f981c595SMel Gorman 
3412f981c595SMel Gorman pgoff_t __page_file_index(struct page *page)
3413f981c595SMel Gorman {
3414f981c595SMel Gorman 	swp_entry_t swap = { .val = page_private(page) };
3415f981c595SMel Gorman 	return swp_offset(swap);
3416f981c595SMel Gorman }
3417f981c595SMel Gorman EXPORT_SYMBOL_GPL(__page_file_index);
3418f981c595SMel Gorman 
34191da177e4SLinus Torvalds /*
3420570a335bSHugh Dickins  * add_swap_count_continuation - called when a swap count is duplicated
3421570a335bSHugh Dickins  * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
3422570a335bSHugh Dickins  * page of the original vmalloc'ed swap_map, to hold the continuation count
3423570a335bSHugh Dickins  * (for that entry and for its neighbouring PAGE_SIZE swap entries).  Called
3424570a335bSHugh Dickins  * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
3425570a335bSHugh Dickins  *
3426570a335bSHugh Dickins  * These continuation pages are seldom referenced: the common paths all work
3427570a335bSHugh Dickins  * on the original swap_map, only referring to a continuation page when the
3428570a335bSHugh Dickins  * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
3429570a335bSHugh Dickins  *
3430570a335bSHugh Dickins  * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
3431570a335bSHugh Dickins  * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
3432570a335bSHugh Dickins  * can be called after dropping locks.
3433570a335bSHugh Dickins  */
3434570a335bSHugh Dickins int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
3435570a335bSHugh Dickins {
3436570a335bSHugh Dickins 	struct swap_info_struct *si;
3437235b6217SHuang, Ying 	struct swap_cluster_info *ci;
3438570a335bSHugh Dickins 	struct page *head;
3439570a335bSHugh Dickins 	struct page *page;
3440570a335bSHugh Dickins 	struct page *list_page;
3441570a335bSHugh Dickins 	pgoff_t offset;
3442570a335bSHugh Dickins 	unsigned char count;
3443eb085574SHuang Ying 	int ret = 0;
3444570a335bSHugh Dickins 
3445570a335bSHugh Dickins 	/*
3446570a335bSHugh Dickins 	 * When debugging, it's easier to use __GFP_ZERO here; but it's better
3447570a335bSHugh Dickins 	 * for latency not to zero a page while GFP_ATOMIC and holding locks.
3448570a335bSHugh Dickins 	 */
3449570a335bSHugh Dickins 	page = alloc_page(gfp_mask | __GFP_HIGHMEM);
3450570a335bSHugh Dickins 
3451eb085574SHuang Ying 	si = get_swap_device(entry);
3452570a335bSHugh Dickins 	if (!si) {
3453570a335bSHugh Dickins 		/*
3454570a335bSHugh Dickins 		 * An acceptable race has occurred since the failing
3455eb085574SHuang Ying 		 * __swap_duplicate(): the swap device may be swapoff
3456570a335bSHugh Dickins 		 */
3457570a335bSHugh Dickins 		goto outer;
3458570a335bSHugh Dickins 	}
3459eb085574SHuang Ying 	spin_lock(&si->lock);
3460570a335bSHugh Dickins 
3461570a335bSHugh Dickins 	offset = swp_offset(entry);
3462235b6217SHuang, Ying 
3463235b6217SHuang, Ying 	ci = lock_cluster(si, offset);
3464235b6217SHuang, Ying 
3465d8aa24e0SMiaohe Lin 	count = swap_count(si->swap_map[offset]);
3466570a335bSHugh Dickins 
3467570a335bSHugh Dickins 	if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
3468570a335bSHugh Dickins 		/*
3469570a335bSHugh Dickins 		 * The higher the swap count, the more likely it is that tasks
3470570a335bSHugh Dickins 		 * will race to add swap count continuation: we need to avoid
3471570a335bSHugh Dickins 		 * over-provisioning.
3472570a335bSHugh Dickins 		 */
3473570a335bSHugh Dickins 		goto out;
3474570a335bSHugh Dickins 	}
3475570a335bSHugh Dickins 
3476570a335bSHugh Dickins 	if (!page) {
3477eb085574SHuang Ying 		ret = -ENOMEM;
3478eb085574SHuang Ying 		goto out;
3479570a335bSHugh Dickins 	}
3480570a335bSHugh Dickins 
3481570a335bSHugh Dickins 	/*
3482570a335bSHugh Dickins 	 * We are fortunate that although vmalloc_to_page uses pte_offset_map,
3483570a335bSHugh Dickins 	 * no architecture is using highmem pages for kernel page tables: so it
3484570a335bSHugh Dickins 	 * will not corrupt the GFP_ATOMIC caller's atomic page table kmaps.
3485570a335bSHugh Dickins 	 */
3486570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3487570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3488570a335bSHugh Dickins 
34892628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3490570a335bSHugh Dickins 	/*
3491570a335bSHugh Dickins 	 * Page allocation does not initialize the page's lru field,
3492570a335bSHugh Dickins 	 * but it does always reset its private field.
3493570a335bSHugh Dickins 	 */
3494570a335bSHugh Dickins 	if (!page_private(head)) {
3495570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3496570a335bSHugh Dickins 		INIT_LIST_HEAD(&head->lru);
3497570a335bSHugh Dickins 		set_page_private(head, SWP_CONTINUED);
3498570a335bSHugh Dickins 		si->flags |= SWP_CONTINUED;
3499570a335bSHugh Dickins 	}
3500570a335bSHugh Dickins 
3501570a335bSHugh Dickins 	list_for_each_entry(list_page, &head->lru, lru) {
3502570a335bSHugh Dickins 		unsigned char *map;
3503570a335bSHugh Dickins 
3504570a335bSHugh Dickins 		/*
3505570a335bSHugh Dickins 		 * If the previous map said no continuation, but we've found
3506570a335bSHugh Dickins 		 * a continuation page, free our allocation and use this one.
3507570a335bSHugh Dickins 		 */
3508570a335bSHugh Dickins 		if (!(count & COUNT_CONTINUED))
35092628bd6fSHuang Ying 			goto out_unlock_cont;
3510570a335bSHugh Dickins 
35119b04c5feSCong Wang 		map = kmap_atomic(list_page) + offset;
3512570a335bSHugh Dickins 		count = *map;
35139b04c5feSCong Wang 		kunmap_atomic(map);
3514570a335bSHugh Dickins 
3515570a335bSHugh Dickins 		/*
3516570a335bSHugh Dickins 		 * If this continuation count now has some space in it,
3517570a335bSHugh Dickins 		 * free our allocation and use this one.
3518570a335bSHugh Dickins 		 */
3519570a335bSHugh Dickins 		if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
35202628bd6fSHuang Ying 			goto out_unlock_cont;
3521570a335bSHugh Dickins 	}
3522570a335bSHugh Dickins 
3523570a335bSHugh Dickins 	list_add_tail(&page->lru, &head->lru);
3524570a335bSHugh Dickins 	page = NULL;			/* now it's attached, don't free it */
35252628bd6fSHuang Ying out_unlock_cont:
35262628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
3527570a335bSHugh Dickins out:
3528235b6217SHuang, Ying 	unlock_cluster(ci);
3529ec8acf20SShaohua Li 	spin_unlock(&si->lock);
3530eb085574SHuang Ying 	put_swap_device(si);
3531570a335bSHugh Dickins outer:
3532570a335bSHugh Dickins 	if (page)
3533570a335bSHugh Dickins 		__free_page(page);
3534eb085574SHuang Ying 	return ret;
3535570a335bSHugh Dickins }
3536570a335bSHugh Dickins 
3537570a335bSHugh Dickins /*
3538570a335bSHugh Dickins  * swap_count_continued - when the original swap_map count is incremented
3539570a335bSHugh Dickins  * from SWAP_MAP_MAX, check if there is already a continuation page to carry
3540570a335bSHugh Dickins  * into, carry if so, or else fail until a new continuation page is allocated;
3541570a335bSHugh Dickins  * when the original swap_map count is decremented from 0 with continuation,
3542570a335bSHugh Dickins  * borrow from the continuation and report whether it still holds more.
3543235b6217SHuang, Ying  * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
3544235b6217SHuang, Ying  * lock.
3545570a335bSHugh Dickins  */
3546570a335bSHugh Dickins static bool swap_count_continued(struct swap_info_struct *si,
3547570a335bSHugh Dickins 				 pgoff_t offset, unsigned char count)
3548570a335bSHugh Dickins {
3549570a335bSHugh Dickins 	struct page *head;
3550570a335bSHugh Dickins 	struct page *page;
3551570a335bSHugh Dickins 	unsigned char *map;
35522628bd6fSHuang Ying 	bool ret;
3553570a335bSHugh Dickins 
3554570a335bSHugh Dickins 	head = vmalloc_to_page(si->swap_map + offset);
3555570a335bSHugh Dickins 	if (page_private(head) != SWP_CONTINUED) {
3556570a335bSHugh Dickins 		BUG_ON(count & COUNT_CONTINUED);
3557570a335bSHugh Dickins 		return false;		/* need to add count continuation */
3558570a335bSHugh Dickins 	}
3559570a335bSHugh Dickins 
35602628bd6fSHuang Ying 	spin_lock(&si->cont_lock);
3561570a335bSHugh Dickins 	offset &= ~PAGE_MASK;
3562213516acSchenqiwu 	page = list_next_entry(head, lru);
35639b04c5feSCong Wang 	map = kmap_atomic(page) + offset;
3564570a335bSHugh Dickins 
3565570a335bSHugh Dickins 	if (count == SWAP_MAP_MAX)	/* initial increment from swap_map */
3566570a335bSHugh Dickins 		goto init_map;		/* jump over SWAP_CONT_MAX checks */
3567570a335bSHugh Dickins 
3568570a335bSHugh Dickins 	if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
3569570a335bSHugh Dickins 		/*
3570570a335bSHugh Dickins 		 * Think of how you add 1 to 999
3571570a335bSHugh Dickins 		 */
3572570a335bSHugh Dickins 		while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
35739b04c5feSCong Wang 			kunmap_atomic(map);
3574213516acSchenqiwu 			page = list_next_entry(page, lru);
3575570a335bSHugh Dickins 			BUG_ON(page == head);
35769b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3577570a335bSHugh Dickins 		}
3578570a335bSHugh Dickins 		if (*map == SWAP_CONT_MAX) {
35799b04c5feSCong Wang 			kunmap_atomic(map);
3580213516acSchenqiwu 			page = list_next_entry(page, lru);
35812628bd6fSHuang Ying 			if (page == head) {
35822628bd6fSHuang Ying 				ret = false;	/* add count continuation */
35832628bd6fSHuang Ying 				goto out;
35842628bd6fSHuang Ying 			}
35859b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3586570a335bSHugh Dickins init_map:		*map = 0;		/* we didn't zero the page */
3587570a335bSHugh Dickins 		}
3588570a335bSHugh Dickins 		*map += 1;
35899b04c5feSCong Wang 		kunmap_atomic(map);
3590213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
35919b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3592570a335bSHugh Dickins 			*map = COUNT_CONTINUED;
35939b04c5feSCong Wang 			kunmap_atomic(map);
3594570a335bSHugh Dickins 		}
35952628bd6fSHuang Ying 		ret = true;			/* incremented */
3596570a335bSHugh Dickins 
3597570a335bSHugh Dickins 	} else {				/* decrementing */
3598570a335bSHugh Dickins 		/*
3599570a335bSHugh Dickins 		 * Think of how you subtract 1 from 1000
3600570a335bSHugh Dickins 		 */
3601570a335bSHugh Dickins 		BUG_ON(count != COUNT_CONTINUED);
3602570a335bSHugh Dickins 		while (*map == COUNT_CONTINUED) {
36039b04c5feSCong Wang 			kunmap_atomic(map);
3604213516acSchenqiwu 			page = list_next_entry(page, lru);
3605570a335bSHugh Dickins 			BUG_ON(page == head);
36069b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3607570a335bSHugh Dickins 		}
3608570a335bSHugh Dickins 		BUG_ON(*map == 0);
3609570a335bSHugh Dickins 		*map -= 1;
3610570a335bSHugh Dickins 		if (*map == 0)
3611570a335bSHugh Dickins 			count = 0;
36129b04c5feSCong Wang 		kunmap_atomic(map);
3613213516acSchenqiwu 		while ((page = list_prev_entry(page, lru)) != head) {
36149b04c5feSCong Wang 			map = kmap_atomic(page) + offset;
3615570a335bSHugh Dickins 			*map = SWAP_CONT_MAX | count;
3616570a335bSHugh Dickins 			count = COUNT_CONTINUED;
36179b04c5feSCong Wang 			kunmap_atomic(map);
3618570a335bSHugh Dickins 		}
36192628bd6fSHuang Ying 		ret = count == COUNT_CONTINUED;
3620570a335bSHugh Dickins 	}
36212628bd6fSHuang Ying out:
36222628bd6fSHuang Ying 	spin_unlock(&si->cont_lock);
36232628bd6fSHuang Ying 	return ret;
3624570a335bSHugh Dickins }
3625570a335bSHugh Dickins 
3626570a335bSHugh Dickins /*
3627570a335bSHugh Dickins  * free_swap_count_continuations - swapoff free all the continuation pages
3628570a335bSHugh Dickins  * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
3629570a335bSHugh Dickins  */
3630570a335bSHugh Dickins static void free_swap_count_continuations(struct swap_info_struct *si)
3631570a335bSHugh Dickins {
3632570a335bSHugh Dickins 	pgoff_t offset;
3633570a335bSHugh Dickins 
3634570a335bSHugh Dickins 	for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
3635570a335bSHugh Dickins 		struct page *head;
3636570a335bSHugh Dickins 		head = vmalloc_to_page(si->swap_map + offset);
3637570a335bSHugh Dickins 		if (page_private(head)) {
36380d576d20SGeliang Tang 			struct page *page, *next;
36390d576d20SGeliang Tang 
36400d576d20SGeliang Tang 			list_for_each_entry_safe(page, next, &head->lru, lru) {
36410d576d20SGeliang Tang 				list_del(&page->lru);
3642570a335bSHugh Dickins 				__free_page(page);
3643570a335bSHugh Dickins 			}
3644570a335bSHugh Dickins 		}
3645570a335bSHugh Dickins 	}
3646570a335bSHugh Dickins }
3647a2468cc9SAaron Lu 
36482cf85583STejun Heo #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
364901c4b28cSSuren Baghdasaryan void __cgroup_throttle_swaprate(struct page *page, gfp_t gfp_mask)
36502cf85583STejun Heo {
36512cf85583STejun Heo 	struct swap_info_struct *si, *next;
36526caa6a07SJohannes Weiner 	int nid = page_to_nid(page);
36536caa6a07SJohannes Weiner 
36546caa6a07SJohannes Weiner 	if (!(gfp_mask & __GFP_IO))
36552cf85583STejun Heo 		return;
36562cf85583STejun Heo 
36572cf85583STejun Heo 	if (!blk_cgroup_congested())
36582cf85583STejun Heo 		return;
36592cf85583STejun Heo 
36602cf85583STejun Heo 	/*
36612cf85583STejun Heo 	 * We've already scheduled a throttle, avoid taking the global swap
36622cf85583STejun Heo 	 * lock.
36632cf85583STejun Heo 	 */
36642cf85583STejun Heo 	if (current->throttle_queue)
36652cf85583STejun Heo 		return;
36662cf85583STejun Heo 
36672cf85583STejun Heo 	spin_lock(&swap_avail_lock);
36686caa6a07SJohannes Weiner 	plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
36696caa6a07SJohannes Weiner 				  avail_lists[nid]) {
36702cf85583STejun Heo 		if (si->bdev) {
36716caa6a07SJohannes Weiner 			blkcg_schedule_throttle(bdev_get_queue(si->bdev), true);
36722cf85583STejun Heo 			break;
36732cf85583STejun Heo 		}
36742cf85583STejun Heo 	}
36752cf85583STejun Heo 	spin_unlock(&swap_avail_lock);
36762cf85583STejun Heo }
36772cf85583STejun Heo #endif
36782cf85583STejun Heo 
3679a2468cc9SAaron Lu static int __init swapfile_init(void)
3680a2468cc9SAaron Lu {
3681a2468cc9SAaron Lu 	int nid;
3682a2468cc9SAaron Lu 
3683a2468cc9SAaron Lu 	swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
3684a2468cc9SAaron Lu 					 GFP_KERNEL);
3685a2468cc9SAaron Lu 	if (!swap_avail_heads) {
3686a2468cc9SAaron Lu 		pr_emerg("Not enough memory for swap heads, swap is disabled\n");
3687a2468cc9SAaron Lu 		return -ENOMEM;
3688a2468cc9SAaron Lu 	}
3689a2468cc9SAaron Lu 
3690a2468cc9SAaron Lu 	for_each_node(nid)
3691a2468cc9SAaron Lu 		plist_head_init(&swap_avail_heads[nid]);
3692a2468cc9SAaron Lu 
3693a2468cc9SAaron Lu 	return 0;
3694a2468cc9SAaron Lu }
3695a2468cc9SAaron Lu subsys_initcall(swapfile_init);
3696